VeraCrypt
aboutsummaryrefslogtreecommitdiff
path: root/src/Main/GraphicUserInterface.cpp
blob: a9ea6cfd0375541fa94b604d757e7765d1186648 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>VeraCrypt - Free Open source disk encryption with strong security for the Paranoid</title>
<meta name="description" content="VeraCrypt is free open-source disk encryption software for Windows, Mac OS X and Linux. In case an attacker forces you to reveal the password, VeraCrypt provides plausible deniability. In contrast to file encryption, data encryption performed by VeraCrypt is real-time (on-the-fly), automatic, transparent, needs very little memory, and does not involve temporary unencrypted files."/>
<meta name="keywords" content="encryption, security"/>
<link href="styles.css" rel="stylesheet" type="text/css" />
</head>
<body>

<div>                      
<a href="https://www.veracrypt.fr/en/Home.html"><img src="VeraCrypt128x128.png" alt="VeraCrypt"/></a>
</div>

<div id="menu">
	<ul>
	  <li><a href="Home.html">Home</a></li>
	  <li><a href="/code/">Source Code</a></li>
	  <li><a href="Downloads.html">Downloads</a></li>
	  <li><a class="active" href="Documentation.html">Documentation</a></li>
	  <li><a href="Donation.html">Donate</a></li>
	  <li><a href="https://sourceforge.net/p/veracrypt/discussion/" target="_blank">Forums</a></li>
	</ul>
</div>

<div>
<p>
<a href="Documentation.html">Documentation</a>           
<img src="arrow_right.gif" alt=">>" style="margin-top: 5px">
<a href="Technical%20Details.html">Technical Details</a>
<img src="arrow_right.gif" alt=">>" style="margin-top: 5px">
<a href="Keyfiles.html">Keyfiles</a>
</p></div>

<div class="wikidoc">
<h1>Keyfiles</h1>
<div style="text-align:left; margin-top:19px; margin-bottom:19px; padding-top:0px; padding-bottom:0px">
<p>VeraCrypt keyfile is a file whose content is combined with a password. The user can use any kind of file as a VeraCrypt keyfile. The user can also generate a keyfile using the built-in keyfile generator, which utilizes the VeraCrypt RNG to generate a file
 with random content (for more information, see the section <a href="Random%20Number%20Generator.html">
<em>Random Number Generator</em></a>).</p>
<p>The maximum size of a keyfile is not limited; however, only its first 1,048,576 bytes (1 MB) are processed (all remaining bytes are ignored due to performance issues connected with processing extremely large files). The user can supply one or more keyfiles
 (the number of keyfiles is not limited).</p>
<p>Keyfiles can be stored on PKCS-11-compliant [23] security tokens and smart cards protected by multiple PIN codes (which can be entered either using a hardware PIN pad or via the VeraCrypt GUI).</p>
<p>Keyfiles are processed and applied to a password using the following method:</p>
<ol>
<li>Let <em>P</em> be a VeraCrypt volume password supplied by user (may be empty)
</li><li>Let <em>KP</em> be the keyfile pool </li><li>Let <em>kpl</em> be the size of the keyfile pool <em>KP</em>, in bytes (64, i.e., 512 bits);
<p>kpl must be a multiple of the output size of a hash function H</p>
</li><li>Let <em>pl</em> be the length of the password <em>P</em>, in bytes (in the current version: 0 &le;
<em>pl</em> &le; 64) </li><li>if <em>kpl &gt; pl</em>, append (<em>kpl &ndash; pl</em>) zero bytes to the password
<em>P</em> (thus <em>pl = kpl</em>) </li><li>Fill the keyfile pool <em>KP</em> with <em>kpl</em> zero bytes. </li><li>For each keyfile perform the following steps:
<ol type="a">
<li>Set the position of the keyfile pool cursor to the beginning of the pool </li><li>Initialize the hash function <em>H</em> </li><li>Load all bytes of the keyfile one by one, and for each loaded byte perform the following steps:
<ol type="i">
<li>Hash the loaded byte using the hash function <em>H</em> without initializing the hash, to obtain an intermediate hash (state)
<em>M.</em> Do not finalize the hash (the state is retained for next round). </li><li>Divide the state <em>M</em> into individual bytes.<br>
For example, if the hash output size is 4 bytes, (<em>T</em><sub>0</sub> || <em>T</em><sub>1</sub> ||
<em>T</em><sub>2</sub> || <em>T</em><sub>3</sub>) = <em>M</em> </li><li>Write these bytes (obtained in step 7.c.ii) individually to the keyfile pool with the modulo 2<sup>8</sup> addition operation (not by replacing the old values in the pool) at the position of the pool cursor. After a byte is written, the pool cursor position
 is advanced by one byte. When the cursor reaches the end of the pool, its position is set to the beginning of the pool.
</li></ol>
</li></ol>
</li><li>Apply the content of the keyfile pool to the password <em>P</em> using the following method:
<ol type="a">
<li>Divide the password <em>P</em> into individual bytes <em>B</em><sub>0</sub>...<em>B</em><sub>pl-1</sub>.<br>
Note that if the password was shorter than the keyfile pool, then the password was padded with zero bytes to the length of the pool in Step 5 (hence, at this point the length of the password is always greater than or equal to the length of the keyfile pool).
</li><li>Divide the keyfile pool <em>KP</em> into individual bytes <em>G</em><sub>0</sub>...<em>G</em><sub>kpl-1</sub>
</li><li>For 0 &le; i &lt; kpl perform: Bi = Bi &oplus; Gi </li><li><em>P</em> = <em>B</em><sub>0</sub> || <em>B</em><sub>1</sub> || ... || <em>B</em><sub>pl-2</sub> ||
<em>B</em><sub>pl-1</sub> </li></ol>
</li><li>The password <em>P</em> (after the keyfile pool content has been applied to it) is now passed to the header key derivation function PBKDF2 (PKCS #5 v2), which processes it (along with salt and other data) using a cryptographically secure hash algorithm
 selected by the user (e.g., SHA-512). See the section <a href="Header%20Key%20Derivation.html">
<em>Header Key Derivation, Salt, and Iteration Count</em></a> for more information.
</li></ol>
<p>The role of the hash function <em>H</em> is merely to perform diffusion [2]. CRC-32 is used as the hash function
<em>H</em>. Note that the output of CRC-32 is subsequently processed using a cryptographically secure hash algorithm: The keyfile pool content (in addition to being hashed using CRC-32) is applied to the password, which is then passed to the header key derivation
 function PBKDF2 (PKCS #5 v2), which processes it (along with salt and other data) using a cryptographically secure hash algorithm selected by the user (e.g., SHA-512). The resultant values are used to form the header key and the secondary header key (XTS mode).</p>
<p>&nbsp;</p>
<p><a href="Personal%20Iterations%20Multiplier%20%28PIM%29.html" style="text-align:left; color:#0080c0; text-decoration:none; font-weight:bold.html">Next Section &gt;&gt;</a></p>
</div>
</div><div class="ClearBoth"></div></body></html>
039'>1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888
/*
 Derived from source code of TrueCrypt 7.1a, which is
 Copyright (c) 2008-2012 TrueCrypt Developers Association and which is governed
 by the TrueCrypt License 3.0.

 Modifications and additions to the original source code (contained in this file)
 and all other portions of this file are Copyright (c) 2013-2016 IDRIX
 and are governed by the Apache License 2.0 the full text of which is
 contained in the file License.txt included in VeraCrypt binary and source
 code distribution packages.
*/

#include "System.h"

#ifdef TC_UNIX
#include <wx/mimetype.h>
#include <wx/sckipc.h>
#include <fcntl.h>
#include <signal.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/utsname.h>
#include "Platform/Unix/Process.h"
#endif

#include "Common/SecurityToken.h"
#include "Application.h"
#include "GraphicUserInterface.h"
#include "FatalErrorHandler.h"
#include "Forms/DeviceSelectionDialog.h"
#include "Forms/KeyfileGeneratorDialog.h"
#include "Forms/MainFrame.h"
#include "Forms/MountOptionsDialog.h"
#include "Forms/RandomPoolEnrichmentDialog.h"
#include "Forms/SecurityTokenKeyfilesDialog.h"

namespace VeraCrypt
{
	GraphicUserInterface::GraphicUserInterface () :
		ActiveFrame (nullptr),
		BackgroundMode (false),
		mMainFrame (nullptr),
		mWaitDialog (nullptr)
	{
#ifdef TC_UNIX
		signal (SIGHUP, OnSignal);
		signal (SIGINT, OnSignal);
		signal (SIGQUIT, OnSignal);
		signal (SIGTERM, OnSignal);
#endif

#ifdef TC_MACOSX
		wxApp::s_macHelpMenuTitleName = _("&Help");
#endif
	}

	GraphicUserInterface::~GraphicUserInterface ()
	{
		try
		{
			if (RandomNumberGenerator::IsRunning())
				RandomNumberGenerator::Stop();
		}
		catch (...) { }

		FatalErrorHandler::Deregister();

#ifdef TC_UNIX
		signal (SIGHUP, SIG_DFL);
		signal (SIGINT, SIG_DFL);
		signal (SIGQUIT, SIG_DFL);
		signal (SIGTERM, SIG_DFL);
#endif
	}

	void GraphicUserInterface::AppendToListCtrl (wxListCtrl *listCtrl, const vector <wstring> &itemFields, int imageIndex, void *itemDataPtr) const
	{
		InsertToListCtrl (listCtrl, listCtrl->GetItemCount(), itemFields, imageIndex, itemDataPtr);
	}

	wxMenuItem *GraphicUserInterface::AppendToMenu (wxMenu &menu, const wxString &label, wxEvtHandler *handler, wxObjectEventFunction handlerFunction, int itemId) const
	{
		wxMenuItem *item = new wxMenuItem (&menu, itemId, label);
		menu.Append (item);

		if (handler)
			handler->Connect (item->GetId(), wxEVT_COMMAND_MENU_SELECTED, handlerFunction);

		return item;
	}

	bool GraphicUserInterface::AskYesNo (const wxString &message, bool defaultYes, bool warning) const
	{
		return ShowMessage (message,
			wxYES_NO | (warning ? wxICON_EXCLAMATION : wxICON_QUESTION) | (defaultYes ? wxYES_DEFAULT : wxNO_DEFAULT)
			) == wxYES;
	}

	void GraphicUserInterface::AutoDismountVolumes (VolumeInfoList mountedVolumes, bool alwaysForce)
	{
		size_t mountedVolumeCount = Core->GetMountedVolumes().size();
		try
		{
			wxBusyCursor busy;
			DismountVolumes (mountedVolumes, alwaysForce ? true : GetPreferences().ForceAutoDismount, false);
		}
		catch (...) { }

		if (Core->GetMountedVolumes().size() < mountedVolumeCount)
			OnVolumesAutoDismounted();
	}

	void GraphicUserInterface::BackupVolumeHeaders (shared_ptr <VolumePath> volumePath) const
	{
		wxWindow *parent = GetActiveWindow();

		if (!volumePath || volumePath->IsEmpty())
			volumePath = make_shared <VolumePath> (SelectVolumeFile (GetActiveWindow()));

		if (volumePath->IsEmpty())
			throw UserAbort (SRC_POS);

#ifdef TC_WINDOWS
		if (Core->IsVolumeMounted (*volumePath))
		{
			ShowInfo ("DISMOUNT_FIRST");
			return;
		}
#endif

#ifdef TC_UNIX
		// Temporarily take ownership of a device if the user is not an administrator
		UserId origDeviceOwner ((uid_t) -1);

		if (!Core->HasAdminPrivileges() && volumePath->IsDevice())
		{
			origDeviceOwner = FilesystemPath (wstring (*volumePath)).GetOwner();
			Core->SetFileOwner (*volumePath, UserId (getuid()));
		}

		finally_do_arg2 (FilesystemPath, *volumePath, UserId, origDeviceOwner,
		{
			if (finally_arg2.SystemId != (uid_t) -1)
				Core->SetFileOwner (finally_arg, finally_arg2);
		});
#endif

		ShowInfo ("EXTERNAL_VOL_HEADER_BAK_FIRST_INFO");

		shared_ptr <Volume> normalVolume;
		shared_ptr <Volume> hiddenVolume;

		MountOptions normalVolumeMountOptions;
		MountOptions hiddenVolumeMountOptions;

		normalVolumeMountOptions.Path = volumePath;
		hiddenVolumeMountOptions.Path = volumePath;

		VolumeType::Enum volumeType = VolumeType::Normal;

		// Open both types of volumes
		while (true)
		{
			shared_ptr <Volume> volume;
			MountOptions *options = (volumeType == VolumeType::Hidden ? &hiddenVolumeMountOptions : &normalVolumeMountOptions);

			MountOptionsDialog dialog (parent, *options,
				LangString[volumeType == VolumeType::Hidden ? "ENTER_HIDDEN_VOL_PASSWORD" : "ENTER_NORMAL_VOL_PASSWORD"],
				true);

			while (!volume)
			{
				dialog.Hide();
				if (dialog.ShowModal() != wxID_OK)
					return;

				try
				{
					wxBusyCursor busy;
					OpenVolumeThreadRoutine routine(
						options->Path,
						options->PreserveTimestamps,
						options->Password,
						options->Pim,
						options->Kdf,
						false,
						options->Keyfiles,
						options->Protection,
						options->ProtectionPassword,
						options->ProtectionPim,
						options->ProtectionKdf,
						options->ProtectionKeyfiles,
						true,
						volumeType,
						options->UseBackupHeaders
						);

						ExecuteWaitThreadRoutine (parent, &routine);
						volume = routine.m_pVolume;
				}
				catch (PasswordException &e)
				{
					ShowWarning (e);
				}
			}

			if (volumeType == VolumeType::Hidden)
				hiddenVolume = volume;
			else
				normalVolume = volume;

			// Ask whether a hidden volume is present
			if (volumeType == VolumeType::Normal)
			{
				wxArrayString choices;
				choices.Add (LangString["VOLUME_CONTAINS_HIDDEN"]);
				choices.Add (LangString["VOLUME_DOES_NOT_CONTAIN_HIDDEN"]);

				wxSingleChoiceDialog choiceDialog (parent, LangString["DOES_VOLUME_CONTAIN_HIDDEN"], Application::GetName(), choices);
				choiceDialog.SetSize (wxSize (Gui->GetCharWidth (&choiceDialog) * 60, -1));
				choiceDialog.SetSelection (-1);

				if (choiceDialog.ShowModal() != wxID_OK)
					return;

				switch (choiceDialog.GetSelection())
				{
				case 0:
					volumeType = VolumeType::Hidden;
					continue;

				case 1:
					break;

				default:
					return;
				}
			}

			break;
		}

		if (hiddenVolume)
		{
			if (typeid (*normalVolume->GetLayout()) == typeid (VolumeLayoutV1Normal))
				throw ParameterIncorrect (SRC_POS);

			if (typeid (*normalVolume->GetLayout()) == typeid (VolumeLayoutV2Normal) && typeid (*hiddenVolume->GetLayout()) != typeid (VolumeLayoutV2Hidden))
				throw ParameterIncorrect (SRC_POS);
		}

		// Ask user to select backup file path
		wxString confirmMsg = LangString["CONFIRM_VOL_HEADER_BAK"];

		if (!AskYesNo (wxString::Format (confirmMsg, wstring (*volumePath).c_str()), true))
			return;

		FilePathList files = SelectFiles (parent, wxEmptyString, true, false);
		if (files.empty())
			return;

		File backupFile;
		backupFile.Open (*files.front(), File::CreateWrite);

		RandomNumberGenerator::Start();
		/* force the display of the random enriching interface */
		RandomNumberGenerator::SetEnrichedByUserStatus (false);
		UserEnrichRandomPool (nullptr);

		{
			wxBusyCursor busy;

			// Re-encrypt volume header
			SecureBuffer newHeaderBuffer (normalVolume->GetLayout()->GetHeaderSize());
			ReEncryptHeaderThreadRoutine routine(newHeaderBuffer, normalVolume->GetHeader(), normalVolumeMountOptions.Password, normalVolumeMountOptions.Pim, normalVolumeMountOptions.Keyfiles);

			ExecuteWaitThreadRoutine (parent, &routine);

			backupFile.Write (newHeaderBuffer);

			if (hiddenVolume)
			{
				// Re-encrypt hidden volume header
				ReEncryptHeaderThreadRoutine hiddenRoutine(newHeaderBuffer, hiddenVolume->GetHeader(), hiddenVolumeMountOptions.Password, hiddenVolumeMountOptions.Pim, hiddenVolumeMountOptions.Keyfiles);

				ExecuteWaitThreadRoutine (parent, &hiddenRoutine);
			}
			else
			{
				// Store random data in place of hidden volume header
				shared_ptr <EncryptionAlgorithm> ea = normalVolume->GetEncryptionAlgorithm();
				Core->RandomizeEncryptionAlgorithmKey (ea);
				ea->Encrypt (newHeaderBuffer);
			}

			backupFile.Write (newHeaderBuffer);
		}

		ShowWarning ("VOL_HEADER_BACKED_UP");
	}

	void GraphicUserInterface::BeginInteractiveBusyState (wxWindow *window)
	{
		static auto_ptr <wxCursor> arrowWaitCursor;

		if (arrowWaitCursor.get() == nullptr)
			arrowWaitCursor.reset (new wxCursor (wxCURSOR_ARROWWAIT));

		window->SetCursor (*arrowWaitCursor);
	}

	void GraphicUserInterface::CreateKeyfile (shared_ptr <FilePath> keyfilePath) const
	{
		try
		{
			KeyfileGeneratorDialog dialog (GetActiveWindow());
			dialog.ShowModal();
		}
		catch (exception &e)
		{
			ShowError (e);
		}
	}

	void GraphicUserInterface::ClearListCtrlSelection (wxListCtrl *listCtrl) const
	{
		foreach (long item, GetListCtrlSelectedItems (listCtrl))
			listCtrl->SetItemState (item, 0, wxLIST_STATE_SELECTED);
	}

	wxHyperlinkCtrl *GraphicUserInterface::CreateHyperlink (wxWindow *parent, const wxString &linkUrl, const wxString &linkText) const
	{
		wxHyperlinkCtrl *hyperlink = new wxHyperlinkCtrl (parent, wxID_ANY, linkText, linkUrl, wxDefaultPosition, wxDefaultSize, wxHL_DEFAULT_STYLE);

		wxColour color = wxSystemSettings::GetColour (wxSYS_COLOUR_WINDOWTEXT);
		hyperlink->SetHoverColour (color);
		hyperlink->SetNormalColour (color);
		hyperlink->SetVisitedColour (color);

		return hyperlink;
	}

	void GraphicUserInterface::DoShowError (const wxString &message) const
	{
		ShowMessage (message, wxOK | wxICON_ERROR);
	}

	void GraphicUserInterface::DoShowInfo (const wxString &message) const
	{
		ShowMessage (message, wxOK | wxICON_INFORMATION);
	}

	void GraphicUserInterface::DoShowString (const wxString &str) const
	{
		ShowMessage (str, wxOK);
	}

	void GraphicUserInterface::DoShowWarning (const wxString &message) const
	{
		ShowMessage (message, wxOK
#ifndef TC_MACOSX
			| wxICON_EXCLAMATION
#endif
			);
	}

	void GraphicUserInterface::EndInteractiveBusyState (wxWindow *window) const
	{
		static auto_ptr <wxCursor> arrowCursor;

		if (arrowCursor.get() == nullptr)
			arrowCursor.reset (new wxCursor (wxCURSOR_ARROW));

		window->SetCursor (*arrowCursor);
	}

	wxTopLevelWindow *GraphicUserInterface::GetActiveWindow () const
	{
#ifdef TC_WINDOWS
		return dynamic_cast <wxTopLevelWindow *> (wxGetActiveWindow());
#endif

#ifdef __WXGTK__
		// GTK for some reason unhides a hidden window if it is a parent of a new window
		if (IsInBackgroundMode())
			return nullptr;
#endif
		if (wxTopLevelWindows.size() == 1)
			return dynamic_cast <wxTopLevelWindow *> (wxTopLevelWindows.front());

#ifdef __WXGTK__
		wxLongLong startTime = wxGetLocalTimeMillis();
		do
		{
#endif
			foreach (wxWindow *window, wxTopLevelWindows)
			{
				wxTopLevelWindow *topLevelWin = dynamic_cast <wxTopLevelWindow *> (window);
				if (topLevelWin && topLevelWin->IsActive() && topLevelWin->IsShown())
					return topLevelWin;
			}
#ifdef __WXGTK__
			Yield(); // GTK does a lot of operations asynchronously, which makes it prone to many race conditions
		} while	(wxGetLocalTimeMillis() - startTime < 500);
#endif

		return dynamic_cast <wxTopLevelWindow *> (ActiveFrame ? ActiveFrame : GetTopWindow());
	}

	shared_ptr <GetStringFunctor> GraphicUserInterface::GetAdminPasswordRequestHandler ()
	{
		struct AdminPasswordRequestHandler : public GetStringFunctor
		{
			virtual void operator() (string &passwordStr)
			{

				wxString sValue;
				if (Gui->GetWaitDialog())
				{
					Gui->GetWaitDialog()->RequestAdminPassword(sValue);
					if (sValue.IsEmpty())
						throw UserAbort (SRC_POS);
				}
				else
				{
					wxPasswordEntryDialog dialog (Gui->GetActiveWindow(), _("Enter your user password or administrator password:"), _("Administrator privileges required"));
					if (dialog.ShowModal() != wxID_OK)
						throw UserAbort (SRC_POS);
					sValue = dialog.GetValue();
				}
				wstring wPassword (sValue);	// A copy of the password is created here by wxWidgets, which cannot be erased
				finally_do_arg (wstring *, &wPassword, { StringConverter::Erase (*finally_arg); });

				StringConverter::ToSingle (wPassword, passwordStr);
			}
		};

		return shared_ptr <GetStringFunctor> (new AdminPasswordRequestHandler);
	}

	int GraphicUserInterface::GetCharHeight (wxWindow *window) const
	{
		int width;
		int height;
		window->GetTextExtent (L"a", &width, &height);

		if (height < 1)
			return 14;

		return height;
	}

	int GraphicUserInterface::GetCharWidth (wxWindow *window) const
	{
		int width;
		int height;
		window->GetTextExtent (L"a", &width, &height);

		if (width < 1)
			return 7;

		return width;
	}

	wxFont GraphicUserInterface::GetDefaultBoldFont (wxWindow *window) const
	{
		return wxFont (
#ifdef __WXGTK__
			9
#elif defined(TC_MACOSX)
			13
#else
			10
#endif
			* GetCharHeight (window) / 13, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL,
#ifdef __WXGTK__
			wxFONTWEIGHT_BOLD, false);
#elif defined(TC_MACOSX)
			wxFONTWEIGHT_NORMAL, false);
#else
			wxFONTWEIGHT_BOLD, false, L"Arial");
#endif
	}

	list <long> GraphicUserInterface::GetListCtrlSelectedItems (wxListCtrl *listCtrl) const
	{
		list <long> selectedItems;

		long item = -1;
		while ((item = listCtrl->GetNextItem (item, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED)) != -1)
			selectedItems.push_back (item);

		return selectedItems;
	}

	wxString GraphicUserInterface::GetListCtrlSubItemText (wxListCtrl *listCtrl, long itemIndex, int columnIndex) const
	{
		wxListItem item;
		item.SetId (itemIndex);
		item.SetColumn (columnIndex);
		item.SetText (L"");

		if (!listCtrl->GetItem (item))
			throw ParameterIncorrect (SRC_POS);

		return item.GetText();
	}

	int GraphicUserInterface::GetScrollbarWidth (wxWindow *window, bool noScrollBar) const
	{
		int offset = 0;
#ifdef TC_WINDOWS
		offset = 4;
#elif defined (__WXGTK__)
		offset = 7;
#elif defined (TC_MACOSX)
		offset = 9;
#endif
		if (noScrollBar)
			return offset;

		int width = wxSystemSettings::GetMetric (wxSYS_VSCROLL_X, window);

		if (width == -1)
			return 24;

		return width + offset;
	}

	void GraphicUserInterface::InitSecurityTokenLibrary () const
	{
		if (Preferences.SecurityTokenModule.IsEmpty())
			throw_err (LangString ["NO_PKCS11_MODULE_SPECIFIED"]);

		struct PinRequestHandler : public GetPinFunctor
		{
			virtual void operator() (string &passwordStr)
			{
                if (CmdLine->ArgTokenPin && CmdLine->ArgTokenPin->IsAllocated ())
                {
        			passwordStr.clear();
        			passwordStr.insert (0, (char*) CmdLine->ArgTokenPin->Ptr (), CmdLine->ArgTokenPin->Size());
                    return;
                }

				if (Gui->GetPreferences().NonInteractive)
					throw MissingArgument (SRC_POS);

				wxString sValue;
				if (Gui->GetWaitDialog())
				{
					sValue = StringConverter::ToWide (passwordStr).c_str();
					Gui->GetWaitDialog()->RequestPin (sValue);
					if (sValue.IsEmpty ())
						throw UserAbort (SRC_POS);
				}
				else
				{
					wxPasswordEntryDialog dialog (Gui->GetActiveWindow(), wxString::Format (LangString["ENTER_TOKEN_PASSWORD"], StringConverter::ToWide (passwordStr).c_str()), LangString["IDD_TOKEN_PASSWORD"]);
					dialog.SetSize (wxSize (Gui->GetCharWidth (&dialog) * 50, -1));

					if (dialog.ShowModal() != wxID_OK)
						throw UserAbort (SRC_POS);
					sValue = dialog.GetValue();
				}

				wstring wPassword (sValue);	// A copy of the password is created here by wxWidgets, which cannot be erased
				finally_do_arg (wstring *, &wPassword, { StringConverter::Erase (*finally_arg); });

				StringConverter::ToSingle (wPassword, passwordStr);
			}

			virtual void notifyIncorrectPin ()
			{
				if (CmdLine->ArgTokenPin && CmdLine->ArgTokenPin->IsAllocated ())
				{
					CmdLine->ArgTokenPin->Free ();
				}
			}
		};

		struct WarningHandler : public SendExceptionFunctor
		{
			virtual void operator() (const Exception &e)
			{
				Gui->ShowError (e);
			}
		};

		try
		{
			SecurityToken::InitLibrary (Preferences.SecurityTokenModule, auto_ptr <GetPinFunctor> (new PinRequestHandler), auto_ptr <SendExceptionFunctor> (new WarningHandler));
		}
		catch (Exception &e)
		{
			ShowError (e);
			throw_err (LangString ["PKCS11_MODULE_INIT_FAILED"]);
		}
	}

	void GraphicUserInterface::InsertToListCtrl (wxListCtrl *listCtrl, long itemIndex, const vector <wstring> &itemFields, int imageIndex, void *itemDataPtr) const
	{
		wxListItem item;
		item.SetData (itemDataPtr);
		item.SetId (itemIndex);
		item.SetImage (imageIndex);
		int col = 0;
		foreach (wxString field, itemFields)
		{
			item.SetColumn (col++);
			item.SetText (field);
			if (col == 1)
			{
				throw_sys_if (listCtrl->InsertItem (item) == -1);
				item.SetImage (-1);
				continue;
			}

			listCtrl->SetItem (item);
		}
	}

	bool GraphicUserInterface::IsTheOnlyTopLevelWindow (const wxWindow *window) const
	{
		foreach (wxWindow *w, wxTopLevelWindows)
		{
			if (w != window
				&& (dynamic_cast <const wxFrame *> (w) || dynamic_cast <const wxDialog *> (w))
				&& StringConverter::GetTypeName (typeid (*w)).find ("wxTaskBarIcon") == string::npos)
			{
				return false;
			}
		}
		return true;
	}

	void GraphicUserInterface::ListSecurityTokenKeyfiles () const
	{
		SecurityTokenKeyfilesDialog dialog (nullptr);
		dialog.ShowModal();
	}

#ifdef TC_MACOSX
	void GraphicUserInterface::MacOpenFiles (const wxArrayString &fileNames)
	{
		if (fileNames.GetCount() > 0)
		{
			// we can only put one volume path at a time on the text field
			// so we take the first on the list
			OpenVolumeSystemRequestEventArgs eventArgs (fileNames[0]);
			OpenVolumeSystemRequestEvent.Raise (eventArgs);
		}
	}

	void GraphicUserInterface::MacReopenApp ()
	{
		SetBackgroundMode (false);
	}
#endif

	void GraphicUserInterface::MoveListCtrlItem (wxListCtrl *listCtrl, long itemIndex, long newItemIndex) const
	{
		if (itemIndex == newItemIndex || newItemIndex < 0
			|| (newItemIndex > itemIndex && newItemIndex == listCtrl->GetItemCount()))
			return;

		wxListItem item;
		item.SetId (itemIndex);
		item.SetData ((void *) nullptr);
		item.SetImage (-1);

		if (!listCtrl->GetItem (item))
			throw ParameterIncorrect (SRC_POS);

		int itemState = listCtrl->GetItemState (itemIndex, wxLIST_STATE_SELECTED);

		vector <wstring> itemFields (listCtrl->GetColumnCount());
		for (size_t col = 0; col < itemFields.size(); ++col)
		{
			itemFields[col] = GetListCtrlSubItemText (listCtrl, itemIndex, col);
		}

		listCtrl->DeleteItem (itemIndex);

		if (newItemIndex > listCtrl->GetItemCount() - 1)
			AppendToListCtrl (listCtrl, itemFields, item.GetImage(), (void *) item.GetData());
		else
			InsertToListCtrl (listCtrl, newItemIndex, itemFields, item.GetImage(), (void *) item.GetData());

		item.SetId (newItemIndex);
		listCtrl->SetItemState (item, itemState, wxLIST_STATE_SELECTED);
	}

	VolumeInfoList GraphicUserInterface::MountAllDeviceHostedVolumes (MountOptions &options) const
	{
		MountOptionsDialog dialog (GetTopWindow(), options);
		while (true)
		{
			options.Path.reset();

			if (dialog.ShowModal() != wxID_OK)
				return VolumeInfoList();

			VolumeInfoList mountedVolumes = UserInterface::MountAllDeviceHostedVolumes (options);

			if (!mountedVolumes.empty())
				return mountedVolumes;
		}
	}

	shared_ptr <VolumeInfo> GraphicUserInterface::MountVolume (MountOptions &options) const
	{
		CheckRequirementsForMountingVolume();

		shared_ptr <VolumeInfo> volume;

		if (!options.Path || options.Path->IsEmpty())
			options.Path = make_shared <VolumePath> (SelectVolumeFile (GetActiveWindow()));

		if (options.Path->IsEmpty())
			throw UserAbort (SRC_POS);

		if (Core->IsVolumeMounted (*options.Path))
		{
			ShowInfo (StringFormatter (LangString["VOLUME_ALREADY_MOUNTED"], wstring (*options.Path)));
			return volume;
		}

		try
		{
			if ((!options.Password || options.Password->IsEmpty())
				&& (!options.Keyfiles || options.Keyfiles->empty())
				&& !Core->IsPasswordCacheEmpty())
			{
				// Cached password
				try
				{
					wxBusyCursor busy;
					return UserInterface::MountVolume (options);
				}
				catch (PasswordException&) { }
			}

			if (!options.Keyfiles && GetPreferences().UseKeyfiles && !GetPreferences().DefaultKeyfiles.empty())
				options.Keyfiles = make_shared <KeyfileList> (GetPreferences().DefaultKeyfiles);

			if ((options.Password && !options.Password->IsEmpty())
				|| (options.Keyfiles && !options.Keyfiles->empty() && (options.TrueCryptMode || options.Password)))
			{
				try
				{
					wxBusyCursor busy;
					return UserInterface::MountVolume (options);
				}
				catch (PasswordException&) { }
			}

			VolumePassword password;
			KeyfileList keyfiles;

			MountOptionsDialog dialog (GetTopWindow(), options);
			int incorrectPasswordCount = 0;

			while (!volume)
			{
				dialog.Hide();
				if (dialog.ShowModal() != wxID_OK)
					return volume;

				try
				{
					wxBusyCursor busy;
					volume = UserInterface::MountVolume (options);
				}
				catch (PasswordIncorrect &e)
				{
					if (++incorrectPasswordCount > 2 && !options.UseBackupHeaders)
					{
						// Try to mount the volume using the backup header
						options.UseBackupHeaders = true;

						try
						{
							volume = UserInterface::MountVolume (options);
							ShowWarning ("HEADER_DAMAGED_AUTO_USED_HEADER_BAK");
						}
						catch (...)
						{
							options.UseBackupHeaders = false;
							ShowWarning (e);
						}
					}
					else
						ShowWarning (e);
				}
				catch (PasswordException &e)
				{
					ShowWarning (e);
				}
			}
		}
		catch (exception &e)
		{
			ShowError (e);
		}

#ifdef TC_LINUX
		if (volume && !Preferences.NonInteractive && !Preferences.DisableKernelEncryptionModeWarning
			&& volume->EncryptionModeName != L"XTS"
			&& !AskYesNo (LangString["ENCRYPTION_MODE_NOT_SUPPORTED_BY_KERNEL"] + _("\n\nDo you want to show this message next time you mount such a volume?"), true, true))
		{
			UserPreferences prefs = GetPreferences();
			prefs.DisableKernelEncryptionModeWarning = true;
			Gui->SetPreferences (prefs);
		}
#endif
		return volume;
	}

	void GraphicUserInterface::OnAutoDismountAllEvent ()
	{
		VolumeInfoList mountedVolumes = Core->GetMountedVolumes();

		if (!mountedVolumes.empty())
		{
			wxBusyCursor busy;
			AutoDismountVolumes (mountedVolumes);
		}
	}

	bool GraphicUserInterface::OnInit ()
	{
		Gui = this;
		InterfaceType = UserInterfaceType::Graphic;
		try
		{
			FatalErrorHandler::Register();
			Init();

			if (ProcessCommandLine() && !CmdLine->StartBackgroundTask)
			{
				Yield();
				Application::SetExitCode (0);
				return false;
			}

			// Check if another instance is already running and bring its windows to foreground
#ifndef TC_MACOSX
#ifdef TC_WINDOWS
			const wxString serverName = Application::GetName() + L"-" + wxGetUserId();
			class Connection : public wxDDEConnection
			{
			public:
				Connection () { }

				bool OnExecute (const wxString& topic, wxChar *data, int size, wxIPCFormat format)
				{
					if (topic == L"raise")
					{
						if (Gui->IsInBackgroundMode())
							Gui->SetBackgroundMode (false);

						Gui->mMainFrame->Show (true);
						Gui->mMainFrame->Raise ();
						return true;
					}
					return false;
				}
			};
#endif

			wxLogLevel logLevel = wxLog::GetLogLevel();
			wxLog::SetLogLevel (wxLOG_Error);

			const wxString instanceCheckerName = wxString (L".") + Application::GetName() + L"-lock-" + wxGetUserId();
			SingleInstanceChecker.reset (new wxSingleInstanceChecker (instanceCheckerName));

			wxLog::SetLogLevel (logLevel);

			if (SingleInstanceChecker->IsAnotherRunning())
			{
#ifdef TC_WINDOWS
				class Client: public wxDDEClient
				{
				public:
					Client() {};
					wxConnectionBase *OnMakeConnection () { return new Connection; }
				};

				auto_ptr <wxDDEClient> client (new Client);
				auto_ptr <wxConnectionBase> connection (client->MakeConnection (L"localhost", serverName, L"raise"));

				if (connection.get() && connection->Execute (nullptr))
				{
					connection->Disconnect();
					Application::SetExitCode (0);
					return false;
				}
#endif

#if defined(TC_UNIX) && !defined(TC_MACOSX)
				try
				{
					int showFifo = open (string (MainFrame::GetShowRequestFifoPath()).c_str(), O_WRONLY | O_NONBLOCK);
					throw_sys_if (showFifo == -1);

					byte buf[1] = { 1 };
					if (write (showFifo, buf, 1) == 1)
					{
						close (showFifo);
						Gui->ShowInfo (_("VeraCrypt is already running."));
						Application::SetExitCode (0);
						return false;
					}

					close (showFifo);
				}
				catch (...)
				{
#ifdef DEBUG
					throw;
#endif
				}

				// This is a false positive as VeraCrypt is not running (pipe not available)
				// we continue running after cleaning the lock file
				// and creating a new instance of the checker
				wxString lockFileName = wxGetHomeDir();
				if ( lockFileName.Last() != wxT('/') )
				{
					lockFileName += wxT('/');
				}
				lockFileName << instanceCheckerName;

				if (wxRemoveFile (lockFileName))
				{
					SingleInstanceChecker.reset (new wxSingleInstanceChecker (instanceCheckerName));
				}
#else

				wxLog::FlushActive();
				Application::SetExitCode (1);
				Gui->ShowInfo (_("VeraCrypt is already running."));
				return false;
#endif
			}

#ifdef TC_WINDOWS
			class Server : public wxDDEServer
			{
			public:
				wxConnectionBase *OnAcceptConnection (const wxString &topic)
				{
					if (topic == L"raise")
						return new Connection;
					return nullptr;
				}
			};

			DDEServer.reset (new Server);
			if (!DDEServer->Create (serverName))
				wxLog::FlushActive();
#endif
#endif // !TC_MACOSX

			Connect (wxEVT_END_SESSION, wxCloseEventHandler (GraphicUserInterface::OnEndSession));
#ifdef wxHAS_POWER_EVENTS
			Gui->Connect (wxEVT_POWER_SUSPENDING, wxPowerEventHandler (GraphicUserInterface::OnPowerSuspending));
#endif

			mMainFrame = new MainFrame (nullptr);

			if (CmdLine->StartBackgroundTask)
			{
				UserPreferences prefs = GetPreferences ();
				prefs.BackgroundTaskEnabled = true;
				SetPreferences (prefs);
				mMainFrame->Close();
			}
			else
			{
				mMainFrame->Show (true);
			}

			SetTopWindow (mMainFrame);
		}
		catch (exception &e)
		{
			ShowError (e);
			return false;
		}

		return true;
	}

	void GraphicUserInterface::OnLogOff ()
	{
		VolumeInfoList mountedVolumes = Core->GetMountedVolumes();
		if (GetPreferences().BackgroundTaskEnabled && GetPreferences().DismountOnLogOff
			&& !mountedVolumes.empty())
		{
			wxLongLong startTime = wxGetLocalTimeMillis();
			bool timeOver = false;

			wxBusyCursor busy;
			while (!timeOver && !mountedVolumes.empty())
			{
				try
				{
					timeOver = (wxGetLocalTimeMillis() - startTime >= 4000);

					DismountVolumes (mountedVolumes, !timeOver ? false : GetPreferences().ForceAutoDismount, timeOver);
					OnVolumesAutoDismounted();

					break;
				}
				catch (UserAbort&)
				{
					return;
				}
				catch (...)
				{
					Thread::Sleep (500);
				}

				VolumeInfoList mountedVolumes = Core->GetMountedVolumes();
			}

		}
	}

#ifdef wxHAS_POWER_EVENTS
	void GraphicUserInterface::OnPowerSuspending (wxPowerEvent& event)
	{
		size_t volumeCount = Core->GetMountedVolumes().size();
		if (GetPreferences().BackgroundTaskEnabled && GetPreferences().DismountOnPowerSaving && volumeCount > 0)
		{
			OnAutoDismountAllEvent();

			if (Core->GetMountedVolumes().size() < volumeCount)
				ShowInfoTopMost (LangString["MOUNTED_VOLUMES_AUTO_DISMOUNTED"]);
		}
	}
#endif

	void GraphicUserInterface::OnSignal (int signal)
	{
#ifdef TC_UNIX
		Gui->SingleInstanceChecker.reset();
		_exit (1);
#endif
	}

	void GraphicUserInterface::OnVolumesAutoDismounted ()
	{
		if (GetPreferences().WipeCacheOnAutoDismount)
		{
			Core->WipePasswordCache();
			SecurityToken::CloseAllSessions();
		}
	}

	void GraphicUserInterface::OpenDocument (wxWindow *parent, const wxFileName &document)
	{
		if (!document.FileExists())
			throw ParameterIncorrect (SRC_POS);

#ifdef TC_WINDOWS

		if (int (ShellExecute (GetTopWindow() ? static_cast <HWND> (GetTopWindow()->GetHandle()) : nullptr, L"open",
		document.GetFullPath().c_str(), nullptr, nullptr, SW_SHOWNORMAL)) >= 32)
		return;

#else
		wxMimeTypesManager mimeMgr;
		wxFileType *fileType = mimeMgr.GetFileTypeFromExtension (document.GetExt());
		if (fileType)
		{
			try
			{
				if (wxExecute (fileType->GetOpenCommand (document.GetFullPath())) != 0)
					return;
			}
			catch (TimeOut&) { }
		}
#endif
	}

	wxString GraphicUserInterface::GetHomepageLinkURL (const wxString &linkId, bool secure, const wxString &extraVars) const
	{
		wxString url = wxString (StringConverter::ToWide (secure ? TC_APPLINK_SECURE : TC_APPLINK));

		if (linkId == L"donate")
		{
			url = L"https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=5BCXVMTTNJDCY";
		}
		else if (linkId == L"main")
		{
			url = wxString (StringConverter::ToWide (TC_HOMEPAGE));
		}
		else if (linkId == L"localizations")
		{
			url = L"https://veracrypt.codeplex.com/wikipage?title=Language%20Packs";
		}
		else if (linkId == L"beginnerstutorial" || linkId == L"tutorial")
		{
			url = L"https://veracrypt.codeplex.com/wikipage?title=Beginner%27s%20Tutorial";
		}
		else if (linkId == L"releasenotes" || linkId == L"history")
		{
			url = L"https://veracrypt.codeplex.com/wikipage?title=Release%20Notes";
		}
		else if (linkId == L"hwacceleration")
		{
			url = L"https://veracrypt.codeplex.com/wikipage?title=Hardware%20Acceleration";
		}
		else if (linkId == L"parallelization")
		{
			url = L"https://veracrypt.codeplex.com/wikipage?title=Parallelization";
		}
		else if (linkId == L"help")
		{
			url = L"https://veracrypt.codeplex.com/documentation";
		}
		else if (linkId == L"keyfiles")
		{
			url = L"https://veracrypt.codeplex.com/wikipage?title=Keyfiles";
		}
		else if (linkId == L"introcontainer")
		{
			url = L"https://veracrypt.codeplex.com/wikipage?title=Creating%20New%20Volumes";
		}
		else if (linkId == L"introsysenc")
		{
			url = L"https://veracrypt.codeplex.com/wikipage?title=System%20Encryption";
		}
		else if (linkId == L"hiddensysenc")
		{
			url = L"https://veracrypt.codeplex.com/wikipage?title=VeraCrypt%20Hidden%20Operating%20System";
		}
		else if (linkId == L"sysencprogressinfo")
		{
			url = L"https://veracrypt.codeplex.com/wikipage?title=System%20Encryption";
		}
		else if (linkId == L"hiddenvolume")
		{
			url = L"https://veracrypt.codeplex.com/wikipage?title=Hidden%20Volume";
		}
		else if (linkId == L"aes")
		{
			url = L"https://veracrypt.codeplex.com/wikipage?title=AES";
		}
		else if (linkId == L"serpent")
		{
			url = L"https://veracrypt.codeplex.com/wikipage?title=Serpent";
		}
		else if (linkId == L"twofish")
		{
			url = L"https://veracrypt.codeplex.com/wikipage?title=Twofish";
		}
		else if (linkId == L"camellia")
		{
			url = L"https://veracrypt.codeplex.com/wikipage?title=Camellia";
		}
		else if (linkId == L"cascades")
		{
			url = L"https://veracrypt.codeplex.com/wikipage?title=Cascades";
		}
		else if (linkId == L"hashalgorithms")
		{
			url = L"https://veracrypt.codeplex.com/wikipage?title=Hash%20Algorithms";
		}
		else if (linkId == L"isoburning")
		{
			url = L"https://cdburnerxp.se/en/home";
		}
		else if (linkId == L"sysfavorites")
		{
			url = L"https://veracrypt.codeplex.com/wikipage?title=System%20Favorite%20Volumes";
		}
		else if (linkId == L"favorites")
		{
			url = L"https://veracrypt.codeplex.com/wikipage?title=Favorite%20Volumes";
		}
		else if (linkId == L"hiddenvolprotection")
		{
			url = L"https://veracrypt.codeplex.com/wikipage?title=Protection%20of%20Hidden%20Volumes";
		}
		else if (linkId == L"faq")
		{
			url = L"https://veracrypt.codeplex.com/wikipage?title=FAQ";
		}
		else if (linkId == L"downloads")
		{
			url = L"https://veracrypt.codeplex.com/wikipage?title=Downloads";
		}
		else if (linkId == L"news")
		{
			url = L"https://veracrypt.codeplex.com/wikipage?title=News";
		}
		else if (linkId == L"contact")
		{
			url = L"https://veracrypt.codeplex.com/wikipage?title=Contact";
		}

		return url;
	}

	void GraphicUserInterface::OpenHomepageLink (wxWindow *parent, const wxString &linkId, const wxString &extraVars)
	{
		wxString url;

		BeginInteractiveBusyState (parent);
		wxLaunchDefaultBrowser (GetHomepageLinkURL (linkId, false, extraVars), wxBROWSER_NEW_WINDOW);
		Thread::Sleep (200);
		EndInteractiveBusyState (parent);
	}

	void GraphicUserInterface::OpenOnlineHelp (wxWindow *parent)
	{
		OpenHomepageLink (parent, L"help");
	}

	void GraphicUserInterface::OpenUserGuide (wxWindow *parent)
	{
		try
		{
			wxString docPath = wstring (Application::GetExecutableDirectory());

#ifdef TC_RESOURCE_DIR
			docPath = StringConverter::ToWide (string (TC_TO_STRING (TC_RESOURCE_DIR)) + "/doc/VeraCrypt User Guide.pdf");
#elif defined (TC_WINDOWS)
			docPath += L"\\VeraCrypt User Guide.pdf";
#elif defined (TC_MACOSX)
			docPath += L"/../Resources/VeraCrypt User Guide.pdf";
#elif defined (TC_UNIX)
			docPath = L"/usr/share/veracrypt/doc/VeraCrypt User Guide.pdf";
#else
#	error TC_RESOURCE_DIR undefined
#endif

			wxFileName docFile = docPath;
			docFile.Normalize();

			try
			{
				Gui->OpenDocument (parent, docFile);
			}
			catch (...)
			{
				if (Gui->AskYesNo (LangString ["HELP_READER_ERROR"], true))
					OpenOnlineHelp (parent);
			}
		}
		catch (Exception &e)
		{
			Gui->ShowError (e);
		}
	}

	void GraphicUserInterface::RestoreVolumeHeaders (shared_ptr <VolumePath> volumePath) const
	{
		wxWindow *parent = GetActiveWindow();

		if (!volumePath || volumePath->IsEmpty())
			volumePath = make_shared <VolumePath> (SelectVolumeFile (GetActiveWindow()));

		if (volumePath->IsEmpty())
			throw UserAbort (SRC_POS);

#ifdef TC_WINDOWS
		if (Core->IsVolumeMounted (*volumePath))
		{
			ShowInfo ("DISMOUNT_FIRST");
			return;
		}
#endif

#ifdef TC_UNIX
		// Temporarily take ownership of a device if the user is not an administrator
		UserId origDeviceOwner ((uid_t) -1);

		if (!Core->HasAdminPrivileges() && volumePath->IsDevice())
		{
			origDeviceOwner = FilesystemPath (wstring (*volumePath)).GetOwner();
			Core->SetFileOwner (*volumePath, UserId (getuid()));
		}

		finally_do_arg2 (FilesystemPath, *volumePath, UserId, origDeviceOwner,
		{
			if (finally_arg2.SystemId != (uid_t) -1)
				Core->SetFileOwner (finally_arg, finally_arg2);
		});
#endif

		// Ask whether to restore internal or external backup
		bool restoreInternalBackup;
		wxArrayString choices;
		choices.Add (LangString["HEADER_RESTORE_INTERNAL"]);
		choices.Add (LangString["HEADER_RESTORE_EXTERNAL"]);

		wxSingleChoiceDialog choiceDialog (parent, LangString["HEADER_RESTORE_EXTERNAL_INTERNAL"], Application::GetName(), choices);
		choiceDialog.SetSize (wxSize (Gui->GetCharWidth (&choiceDialog) * 80, -1));
		choiceDialog.SetSelection (-1);

		if (choiceDialog.ShowModal() != wxID_OK)
			return;

		switch (choiceDialog.GetSelection())
		{
		case 0:
			restoreInternalBackup = true;
			break;

		case 1:
			restoreInternalBackup = false;
			break;

		default:
			return;
		}

		/* force the display of the random enriching interface */
		RandomNumberGenerator::SetEnrichedByUserStatus (false);

		if (restoreInternalBackup)
		{
			// Restore header from the internal backup
			shared_ptr <Volume> volume;
			MountOptions options;
			options.Path = volumePath;

			MountOptionsDialog dialog (parent, options, wxEmptyString, true);

			while (!volume)
			{
				dialog.Hide();
				if (dialog.ShowModal() != wxID_OK)
					return;

				try
				{
					wxBusyCursor busy;
					OpenVolumeThreadRoutine routine(
						options.Path,
						options.PreserveTimestamps,
						options.Password,
						options.Pim,
						options.Kdf,
						options.TrueCryptMode,
						options.Keyfiles,
						options.Protection,
						options.ProtectionPassword,
						options.ProtectionPim,
						options.ProtectionKdf,
						options.ProtectionKeyfiles,
						options.SharedAccessAllowed,
						VolumeType::Unknown,
						true
						);

						ExecuteWaitThreadRoutine (parent, &routine);
						volume = routine.m_pVolume;
				}
				catch (PasswordException &e)
				{
					ShowWarning (e);
				}
			}

			shared_ptr <VolumeLayout> layout = volume->GetLayout();
			if (typeid (*layout) == typeid (VolumeLayoutV1Normal))
			{
				ShowError ("VOLUME_HAS_NO_BACKUP_HEADER");
				return;
			}

			RandomNumberGenerator::Start();
			UserEnrichRandomPool (nullptr);

			// Re-encrypt volume header
			wxBusyCursor busy;
			SecureBuffer newHeaderBuffer (volume->GetLayout()->GetHeaderSize());
			ReEncryptHeaderThreadRoutine routine(newHeaderBuffer, volume->GetHeader(), options.Password, options.Pim, options.Keyfiles);

			ExecuteWaitThreadRoutine (parent, &routine);

			// Write volume header
			int headerOffset = volume->GetLayout()->GetHeaderOffset();
			shared_ptr <File> volumeFile = volume->GetFile();

			if (headerOffset >= 0)
				volumeFile->SeekAt (headerOffset);
			else
				volumeFile->SeekEnd (headerOffset);

			volumeFile->Write (newHeaderBuffer);
		}
		else
		{
			// Restore header from an external backup

			wxString confirmMsg = LangString["CONFIRM_VOL_HEADER_RESTORE"];

			if (!AskYesNo (wxString::Format (confirmMsg, wstring (*volumePath).c_str()), true, true))
				return;

			FilePathList files = SelectFiles (parent, wxEmptyString, false, false);
			if (files.empty())
				return;

			File backupFile;
			backupFile.Open (*files.front(), File::OpenRead);

			bool legacyBackup;

			// Determine the format of the backup file
			switch (backupFile.Length())
			{
			case TC_VOLUME_HEADER_GROUP_SIZE:
				legacyBackup = false;
				break;

			case TC_VOLUME_HEADER_SIZE_LEGACY * 2:
				legacyBackup = true;
				break;

			default:
				ShowError ("HEADER_BACKUP_SIZE_INCORRECT");
				return;
			}

			// Open the volume header stored in the backup file
			MountOptions options;

			MountOptionsDialog dialog (parent, options, LangString["ENTER_HEADER_BACKUP_PASSWORD"], true);
			shared_ptr <VolumeLayout> decryptedLayout;

			while (!decryptedLayout)
			{
				dialog.Hide();
				if (dialog.ShowModal() != wxID_OK)
					return;

				try
				{
					wxBusyCursor busy;

					// Test volume layouts
					foreach (shared_ptr <VolumeLayout> layout, VolumeLayout::GetAvailableLayouts ())
					{
						if (layout->HasDriveHeader())
							continue;

						if (!legacyBackup && (typeid (*layout) == typeid (VolumeLayoutV1Normal)))
							continue;

						if (legacyBackup && (typeid (*layout) == typeid (VolumeLayoutV2Normal) || typeid (*layout) == typeid (VolumeLayoutV2Hidden)))
							continue;

						SecureBuffer headerBuffer (layout->GetHeaderSize());
						backupFile.ReadAt (headerBuffer, layout->GetType() == VolumeType::Hidden ? layout->GetHeaderSize() : 0);

						// Decrypt header
						shared_ptr <VolumePassword> passwordKey = Keyfile::ApplyListToPassword (options.Keyfiles, options.Password);
						Pkcs5KdfList keyDerivationFunctions = layout->GetSupportedKeyDerivationFunctions(options.TrueCryptMode);
						EncryptionAlgorithmList encryptionAlgorithms = layout->GetSupportedEncryptionAlgorithms();
						EncryptionModeList encryptionModes = layout->GetSupportedEncryptionModes();

						DecryptThreadRoutine decryptRoutine(layout->GetHeader(), headerBuffer, *passwordKey, options.Pim, options.Kdf, options.TrueCryptMode, keyDerivationFunctions, encryptionAlgorithms, encryptionModes);

						ExecuteWaitThreadRoutine (parent, &decryptRoutine);

						if (decryptRoutine.m_bResult)
						{
							decryptedLayout = layout;
							break;
						}
					}

					if (!decryptedLayout)
						throw PasswordIncorrect (SRC_POS);
				}
				catch (PasswordException &e)
				{
					ShowWarning (e);
				}
			}

			File volumeFile;
			volumeFile.Open (*volumePath, File::OpenReadWrite, File::ShareNone, File::PreserveTimestamps);

			RandomNumberGenerator::Start();
			UserEnrichRandomPool (nullptr);

			// Re-encrypt volume header
			wxBusyCursor busy;
			SecureBuffer newHeaderBuffer (decryptedLayout->GetHeaderSize());
			ReEncryptHeaderThreadRoutine routine(newHeaderBuffer, decryptedLayout->GetHeader(), options.Password, options.Pim, options.Keyfiles);

			ExecuteWaitThreadRoutine (parent, &routine);

			// Write volume header
			int headerOffset = decryptedLayout->GetHeaderOffset();
			if (headerOffset >= 0)
				volumeFile.SeekAt (headerOffset);
			else
				volumeFile.SeekEnd (headerOffset);

			volumeFile.Write (newHeaderBuffer);

			if (decryptedLayout->HasBackupHeader())
			{
				// Re-encrypt backup volume header
				ReEncryptHeaderThreadRoutine backupRoutine(newHeaderBuffer, decryptedLayout->GetHeader(), options.Password, options.Pim, options.Keyfiles);

				ExecuteWaitThreadRoutine (parent, &backupRoutine);

				// Write backup volume header
				headerOffset = decryptedLayout->GetBackupHeaderOffset();
				if (headerOffset >= 0)
					volumeFile.SeekAt (headerOffset);
				else
					volumeFile.SeekEnd (headerOffset);

				volumeFile.Write (newHeaderBuffer);
			}
		}

		ShowInfo ("VOL_HEADER_RESTORED");
	}

	DevicePath GraphicUserInterface::SelectDevice (wxWindow *parent) const
	{
		try
		{
			DeviceSelectionDialog dialog (parent);
			if (dialog.ShowModal() == wxID_OK)
			{
				return dialog.SelectedDevice.Path;
			}
		}
		catch (exception &e)
		{
			Gui->ShowError (e);
		}

		return DevicePath();
	}

	DirectoryPath GraphicUserInterface::SelectDirectory (wxWindow *parent, const wxString &message, bool existingOnly) const
	{
		return DirectoryPath (::wxDirSelector (!message.empty() ? message :
#ifdef __WXGTK__
			wxDirSelectorPromptStr,
#else
			L"",
#endif
			L"", wxDD_DEFAULT_STYLE | (existingOnly ? wxDD_DIR_MUST_EXIST : 0), wxDefaultPosition, parent).wc_str());
	}

	FilePathList GraphicUserInterface::SelectFiles (wxWindow *parent, const wxString &caption, bool saveMode, bool allowMultiple, const list < pair <wstring, wstring> > &fileExtensions, const DirectoryPath &directory) const
	{
		FilePathList files;

		long style;
		if (saveMode)
			style = wxFD_SAVE | wxFD_OVERWRITE_PROMPT;
		else
			style = wxFD_OPEN | wxFD_FILE_MUST_EXIST | (allowMultiple ? wxFD_MULTIPLE : 0);

		wxString wildcards = L"*.*";

#ifndef __WXGTK__
		if (!fileExtensions.empty())
#endif
		{
			wildcards = LangString["ALL_FILES"] +
#ifdef TC_WINDOWS
				L" (*.*)|*.*";
#else
				L"|*";
#endif
			typedef pair <wstring, wstring> StringPair;
			foreach (StringPair p, fileExtensions)
			{
				if (p.first == L"*" || p.first == L"*.*")
				{
					wildcards += L"|" + wildcards.substr (0, wildcards.find (L"*|") + 1);
					wildcards = wildcards.substr (wildcards.find (L"*|") + 2);
					continue;
				}

				wildcards += wxString (L"|") + p.second + L" (*." + p.first + L")|*." + p.first;
			}
		}

		wxFileDialog dialog (parent, !caption.empty() ? caption : LangString ["OPEN_TITLE"], wstring (directory), wxString(), wildcards, style);

		if (dialog.ShowModal() == wxID_OK)
		{
			if (!allowMultiple)
				files.push_back (make_shared <FilePath> (dialog.GetPath().wc_str()));
			else
			{
				wxArrayString paths;
				dialog.GetPaths (paths);

				foreach (const wxString &path, paths)
					files.push_back (make_shared <FilePath> (path.wc_str()));
			}
		}

		return files;
	}

	FilePath GraphicUserInterface::SelectVolumeFile (wxWindow *parent, bool saveMode, const DirectoryPath &directory) const
	{
		list < pair <wstring, wstring> > extensions;
		extensions.push_back (make_pair (L"tc", LangString["TC_VOLUMES"].ToStdWstring()));

		FilePathList selFiles = Gui->SelectFiles (parent, LangString[saveMode ? "OPEN_NEW_VOLUME" : "OPEN_VOL_TITLE"], saveMode, false, extensions, directory);

		if (!selFiles.empty())
			return *selFiles.front();
		else
			return FilePath();
	}

	void GraphicUserInterface::SetBackgroundMode (bool state)
	{
#ifdef TC_MACOSX
		// Hiding an iconized window on OS X apparently cannot be reversed
		if (state && mMainFrame->IsIconized())
			mMainFrame->Iconize (false);
#endif
		mMainFrame->Show (!state);
		if (!state)
		{
			if (mMainFrame->IsIconized())
				mMainFrame->Iconize (false);

			mMainFrame->Raise();
		}

		BackgroundMode = state;
	}

	void GraphicUserInterface::SetListCtrlColumnWidths (wxListCtrl *listCtrl, list <int> columnWidthPermilles, bool hasVerticalScrollbar) const
	{
#ifdef TC_MACOSX
		hasVerticalScrollbar = true;
#endif
		int listWidth = listCtrl->GetSize().GetWidth();
		int minListWidth = listCtrl->GetMinSize().GetWidth();
		if (minListWidth > listWidth)
			listWidth = minListWidth;

		listWidth -= GetScrollbarWidth (listCtrl, !hasVerticalScrollbar);

		int col = 0;
		int totalColWidth = 0;
		foreach (int colWidth, columnWidthPermilles)
		{
			int width = listWidth * colWidth / 1000;
			totalColWidth += width;

			if (col == listCtrl->GetColumnCount() - 1)
				width += listWidth - totalColWidth;

			listCtrl->SetColumnWidth (col++, width);
		}
	}

	void GraphicUserInterface::SetListCtrlHeight (wxListCtrl *listCtrl, size_t rowCount) const
	{
		wxRect itemRect;
		if (listCtrl->GetItemCount() == 0)
		{
			bool addedCols = false;
			if (listCtrl->GetColumnCount() == 0)
			{
				listCtrl->InsertColumn (0, L".", wxLIST_FORMAT_LEFT, 1);
				addedCols = true;
			}
			vector <wstring> f;
			f.push_back (L".");
			AppendToListCtrl (listCtrl, f);
			listCtrl->GetItemRect (0, itemRect);

			if (addedCols)
				listCtrl->ClearAll();
			else
				listCtrl->DeleteAllItems();
		}
		else
			listCtrl->GetItemRect (0, itemRect);

		int headerHeight = itemRect.y;
#ifdef TC_WINDOWS
		headerHeight += 4;
#elif defined (TC_MACOSX)
		headerHeight += 7;
#elif defined (__WXGTK__)
		headerHeight += 5;
#endif
		int rowHeight = itemRect.height;
#ifdef TC_MACOSX
		rowHeight += 1;
#endif
		listCtrl->SetMinSize (wxSize (listCtrl->GetMinSize().GetWidth(), rowHeight * rowCount + headerHeight));
	}

	void GraphicUserInterface::SetListCtrlWidth (wxListCtrl *listCtrl, size_t charCount, bool hasVerticalScrollbar) const
	{
		int width = GetCharWidth (listCtrl) * charCount;
#ifdef TC_MACOSX
		if (!hasVerticalScrollbar)
			width += GetScrollbarWidth (listCtrl);
#endif
		listCtrl->SetMinSize (wxSize (width, listCtrl->GetMinSize().GetHeight()));
	}

	void GraphicUserInterface::ShowErrorTopMost (const wxString &message) const
	{
		ShowMessage (message, wxOK | wxICON_ERROR, true);
	}

	void GraphicUserInterface::ShowInfoTopMost (const wxString &message) const
	{
		ShowMessage (message, wxOK | wxICON_INFORMATION, true);
	}

	int GraphicUserInterface::ShowMessage (const wxString &message, long style, bool topMost) const
	{
		wxString caption = Application::GetName();
		wxString subMessage = message;

#ifdef TC_MACOSX
		size_t p = message.find (L"\n");
		if (p != string::npos)
		{
			// Divide message to caption and info message
			caption = message.substr (0, p);

			p = message.find_first_not_of (L'\n', p);
			if (p != string::npos)
				subMessage = message.substr (p);
			else
				subMessage.clear();

			if (subMessage.EndsWith (L"?"))
			{
				// Move question to caption
				caption += wstring (L" ");
				p = subMessage.find_last_of (L".\n");
				if (p != string::npos)
				{
					if (caption.EndsWith (L": "))
						caption[caption.size() - 2] = L'.';

					caption += subMessage.substr (subMessage.find_first_not_of (L"\n ", p + 1));
					subMessage = subMessage.substr (0, p + 1);
				}
				else
				{
					caption += subMessage.substr (subMessage.find_first_not_of (L"\n"));
					subMessage.clear();
				}
			}
		}
		else if (message.size() < 160)
		{
			caption = message;
			subMessage.clear();
		}
		else
		{
			if (style & wxICON_EXCLAMATION)
				caption = wxString (_("Warning")) + L':';
			else if (style & wxICON_ERROR || style & wxICON_HAND)
				caption = wxString (_("Error")) + L':';
			else
				caption.clear();
		}
#endif
		if (mWaitDialog)
		{
			return mWaitDialog->RequestShowMessage(subMessage, caption, style, topMost);
		}
		else
		{
			if (topMost)
			{
				if (!IsActive())
					mMainFrame->RequestUserAttention (wxUSER_ATTENTION_ERROR);

				style |= wxSTAY_ON_TOP;
			}

			return wxMessageBox (subMessage, caption, style, GetActiveWindow());
		}
	}

	void GraphicUserInterface::ShowWarningTopMost (const wxString &message) const
	{
		ShowMessage (message, wxOK
#ifndef TC_MACOSX
			| wxICON_EXCLAMATION
#endif
			, true);
	}

	void GraphicUserInterface::ThrowTextModeRequired () const
	{
		Gui->ShowError (_("This feature is currently supported only in text mode."));
		throw UserAbort (SRC_POS);
	}

	bool GraphicUserInterface::UpdateListCtrlItem (wxListCtrl *listCtrl, long itemIndex, const vector <wstring> &itemFields) const
	{
		bool changed = false;
		wxListItem item;
		item.SetId (itemIndex);
		item.SetText (L"");

		int col = 0;
		foreach (wxString field, itemFields)
		{
			item.SetColumn (col++);

			if (!listCtrl->GetItem (item))
				throw ParameterIncorrect (SRC_POS);

			if (item.GetText() != field)
			{
				item.SetText (field);
				listCtrl->SetItem (item);
				if (item.GetColumn() == 3 || item.GetColumn() == 4)
					listCtrl->SetColumnWidth(item.GetColumn(), wxLIST_AUTOSIZE);
				changed = true;
			}
		}
		return changed;
	}

	void GraphicUserInterface::UserEnrichRandomPool (wxWindow *parent, shared_ptr <Hash> hash) const
	{
		RandomNumberGenerator::Start();

		if (hash)
			RandomNumberGenerator::SetHash (hash);

		if (!RandomNumberGenerator::IsEnrichedByUser())
		{
			RandomPoolEnrichmentDialog dialog (parent);
			RandomNumberGenerator::SetEnrichedByUserStatus (dialog.ShowModal() == wxID_OK);
		}
	}

	void GraphicUserInterface::Yield () const
	{
#ifndef TC_WINDOWS
		wxSafeYield (nullptr, true);
#endif
	}

	shared_ptr <VolumeInfo> GraphicUserInterface::MountVolumeThread (MountOptions &options) const
	{
		MountThreadRoutine routine(options);

		ExecuteWaitThreadRoutine(GetTopWindow(), &routine);
		return routine.m_pVolume;
	}

	void GraphicUserInterface::ExecuteWaitThreadRoutine (wxWindow *parent, WaitThreadRoutine *pRoutine) const
	{
		WaitDialog dlg(parent, LangString["IDT_STATIC_MODAL_WAIT_DLG_INFO"], pRoutine);
		mWaitDialog = &dlg;
		finally_do_arg (WaitDialog**, &mWaitDialog, { *finally_arg = nullptr; });
		dlg.Run();
	}

	DEFINE_EVENT_TYPE (TC_EVENT_THREAD_EXITING);

	GraphicUserInterface *Gui = nullptr;
}