VeraCrypt
aboutsummaryrefslogtreecommitdiff
path: root/src/Main/Forms/MainFrame.cpp
blob: 7c329292a182fbb6e03760dec5cd8d7bf28365a5 (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
/*
 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-2017 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.
*/

#ifndef TC_HEADER_Main_Forms_EncryptionOptionsWizardPage
#define TC_HEADER_Main_Forms_EncryptionOptionsWizardPage

#include "Forms.h"

namespace VeraCrypt
{
	class EncryptionOptionsWizardPage : public EncryptionOptionsWizardPageBase
	{
	public:
		EncryptionOptionsWizardPage (wxPanel* parent);

		shared_ptr <EncryptionAlgorithm> GetEncryptionAlgorithm () const;
		shared_ptr <Hash> GetHash () const;
		bool IsValid () { return true; }
		void SetPageText (const wxString &text) { }
		void SetEncryptionAlgorithm (shared_ptr <EncryptionAlgorithm> algorithm);
		void SetHash (shared_ptr <Hash> hash);

	protected:
		void OnBenchmarkButtonClick (wxCommandEvent& event);
		void OnEncryptionAlgorithmHyperlinkClick (wxHyperlinkEvent& event);
		void OnEncryptionAlgorithmSelected ();
		void OnEncryptionAlgorithmSelected (wxCommandEvent& event) { OnEncryptionAlgorithmSelected(); }
		void OnHashHyperlinkClick (wxHyperlinkEvent& event);
		void OnTestButtonClick (wxCommandEvent& event);

		EncryptionAlgorithmList EncryptionAlgorithms;
		HashList Hashes;
	};
}

#endif // TC_HEADER_Main_Forms_EncryptionOptionsWizardPage
href='#n345'>345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 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
/*
 Copyright (c) 2008-2010 TrueCrypt Developers Association. All rights reserved.

 Governed by the TrueCrypt License 3.0 the full text of which is contained in
 the file License.txt included in TrueCrypt binary and source code distribution
 packages.
*/

#include "System.h"

#ifdef TC_UNIX
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#endif

#include "Common/SecurityToken.h"
#include "Main/Main.h"
#include "Main/Resources.h"
#include "Main/Application.h"
#include "Main/GraphicUserInterface.h"
#include "Main/VolumeHistory.h"
#include "Main/Xml.h"
#include "MainFrame.h"
#include "AboutDialog.h"
#include "BenchmarkDialog.h"
#include "ChangePasswordDialog.h"
#include "EncryptionTestDialog.h"
#include "FavoriteVolumesDialog.h"
#include "LegalNoticesDialog.h"
#include "PreferencesDialog.h"
#include "SecurityTokenKeyfilesDialog.h"
#include "VolumeCreationWizard.h"
#include "VolumePropertiesDialog.h"

namespace VeraCrypt
{
	MainFrame::MainFrame (wxWindow* parent) : MainFrameBase (parent),
		ListItemRightClickEventPending (false),
		SelectedItemIndex (-1),
		SelectedSlotNumber (0),
		ShowRequestFifo (-1)
	{
		wxBusyCursor busy;

		SetName (Application::GetName());
		SetTitle (Application::GetName());
		SetIcon (Resources::GetVeraCryptIcon());

#if defined(TC_UNIX) && !defined(TC_MACOSX)
		try
		{
			string fifoPath = GetShowRequestFifoPath();

			remove (fifoPath.c_str());
			throw_sys_if (mkfifo (fifoPath.c_str(), S_IRUSR | S_IWUSR) == -1);

			ShowRequestFifo = open (fifoPath.c_str(), O_RDONLY | O_NONBLOCK);
			throw_sys_if (ShowRequestFifo == -1);
		}
		catch (...)
		{
#ifdef DEBUG
			throw;
#endif
		}
#endif

		InitControls();
		InitPreferences();
		InitTaskBarIcon();
		InitEvents();
		InitMessageFilter();

		if (!GetPreferences().SecurityTokenModule.IsEmpty() && !SecurityToken::IsInitialized())
		{
			try
			{
				Gui->InitSecurityTokenLibrary();
			}
			catch (exception &e)
			{
				Gui->ShowError (e);
			}
		}
	}

	MainFrame::~MainFrame ()
	{
#if defined(TC_UNIX) && !defined(TC_MACOSX)
		if (ShowRequestFifo != -1)
		{
			try
			{
				close (ShowRequestFifo);
				remove (string (GetShowRequestFifoPath()).c_str());
			}
			catch (...) { }
		}
#endif

		Core->VolumeMountedEvent.Disconnect (this);
		Core->VolumeDismountedEvent.Disconnect (this);
		Gui->OpenVolumeSystemRequestEvent.Disconnect (this);
		Gui->PreferencesUpdatedEvent.Disconnect (this);

		VolumeHistory::DisconnectComboBox (VolumePathComboBox);

#ifdef TC_WINDOWS
		Hotkey::UnregisterList (this, GetPreferences().Hotkeys);
#endif
	}

	void MainFrame::AddToFavorites (const VolumeInfoList &volumes)
	{
		try
		{
			FavoriteVolumeList newFavorites;

			// Delete duplicates
			foreach (shared_ptr <FavoriteVolume> favorite, FavoriteVolume::LoadList())
			{
				bool mounted = false;
				foreach_ref (const VolumeInfo &volume, volumes)
				{
					if (volume.Path == favorite->Path)
					{
						mounted = true;
						break;
					}
				}
				if (!mounted)
					newFavorites.push_back (favorite);
			}

			size_t newItemCount = 0;
			foreach_ref (const VolumeInfo &volume, volumes)
			{
				newFavorites.push_back (shared_ptr <FavoriteVolume> (new FavoriteVolume (volume.Path, volume.MountPoint, volume.SlotNumber, volume.Protection == VolumeProtection::ReadOnly, volume.SystemEncryption)));
				++newItemCount;
			}

			OrganizeFavorites (newFavorites, newItemCount);
		}
		catch (exception &e)
		{
			Gui->ShowError (e);
		}
	}

	bool MainFrame::CanExit () const
	{
		return Gui->IsTheOnlyTopLevelWindow (this);
	}

	void MainFrame::ChangePassword (ChangePasswordDialog::Mode::Enum mode)
	{
		if (!CheckVolumePathNotEmpty ())
			return;

		shared_ptr <VolumePath> volumePath = GetSelectedVolumePath();

#ifdef TC_WINDOWS
		if (Core->IsVolumeMounted (*volumePath))
		{
			Gui->ShowInfo (LangString [mode == ChangePasswordDialog::Mode::ChangePkcs5Prf ? "MOUNTED_NO_PKCS5_PRF_CHANGE" : "MOUNTED_NOPWCHANGE"]);
			return;
		}
#endif

		ChangePasswordDialog dialog (this, volumePath, mode);
		dialog.ShowModal();
	}

	void MainFrame::CheckFilesystem (bool repair)
	{
		shared_ptr <VolumeInfo> selectedVolume = GetSelectedVolume();
		if (selectedVolume)
		{
			try
			{
#ifdef TC_WINDOWS
				string mountPoint = selectedVolume->MountPoint;

				wstring args = StringFormatter (repair ? L"/C echo {0} & chkdsk {1} /F /X & pause" : L"/C echo {0} & chkdsk {1} & pause",
					StringFormatter (LangString[repair ? "REPAIRING_FS" : "CHECKING_FS"], mountPoint), mountPoint);

				ShellExecute (static_cast <HWND> (GetHandle()), 
					L"runas",
					L"cmd.exe", args.c_str(), nullptr, SW_SHOW);
#else
#	ifdef TC_MACOSX
				Gui->ShowInfo (_("Disk Utility will be launched after you press 'OK'.\n\nPlease select your volume in the Disk Utility window and press 'Verify Disk' or 'Repair Disk' button on the 'First Aid' page."));
#	endif
				Core->CheckFilesystem (selectedVolume, repair);
				UpdateVolumeList();
#endif
			}
			catch (exception &e)
			{
				Gui->ShowError (e);
			}
		}
	}

	bool MainFrame::CheckVolumePathNotEmpty () const
	{
		if (VolumePathComboBox->GetValue().empty())
		{
			Gui->ShowInfo ("NO_VOLUME_SELECTED");
			return false;
		}
		return true;
	}

	void MainFrame::DismountVolume (shared_ptr <VolumeInfo> volume)
	{
		try
		{
			if (!volume)
				volume = GetSelectedVolume();

			if (volume)
				Gui->DismountVolume (volume);
		}
		catch (exception &e)
		{
			Gui->ShowError (e);
		}
	}

	shared_ptr <VolumeInfo> MainFrame::GetSelectedVolume () const
	{
		return Core->GetMountedVolume (SelectedSlotNumber);
	}

	void MainFrame::InitControls ()
	{
		LogoBitmap->SetBitmap (Resources::GetLogoBitmap());
		
		list <int> colPermilles;

#ifndef TC_WINDOWS
		SettingsMenu->Remove (HotkeysMenuItem);
#endif

#ifdef TC_MACOSX
		SettingsMenu->Remove (PreferencesMenuItem);
		SettingsMenu->AppendSeparator();
		SettingsMenu->Append (PreferencesMenuItem);

		LowStaticBoxSizer->Detach (HigherButtonSizer);
		VolumeStaticBoxSizer->Detach (VolumeGridBagSizer);
		VolumeStaticBoxSizer->Add (VolumeGridBagSizer, 1, wxEXPAND, 0);

		ExitButton->SetLabel (_("Close"));
		MountAllDevicesButton->SetLabel (_("Mount All Devices"));
#endif

#ifdef TC_WINDOWS		 
		SlotListCtrl->InsertColumn (ColumnSlot, LangString["DRIVE"], wxLIST_FORMAT_LEFT, 1);
		colPermilles.push_back (75);
#else
		SlotListCtrl->InsertColumn (ColumnSlot, _("Slot"), wxLIST_FORMAT_LEFT, 1);
		colPermilles.push_back (82);
#endif

		SlotListCtrl->InsertColumn (ColumnPath, LangString["VOLUME"], wxLIST_FORMAT_LEFT, 1);
#ifdef TC_WINDOWS		 
		colPermilles.push_back (487);
#else
		colPermilles.push_back (429);
#endif

		SlotListCtrl->InsertColumn (ColumnSize, LangString["SIZE"], wxLIST_FORMAT_RIGHT, 1);
#ifdef TC_WINDOWS		 
		colPermilles.push_back (126);
#else
		colPermilles.push_back (130);
#endif

#ifdef TC_WINDOWS		 
		SlotListCtrl->InsertColumn (ColumnEA, LangString["ENCRYPTION_ALGORITHM_LV"], wxLIST_FORMAT_LEFT, 1);
		colPermilles.push_back (233);
#else
		SlotListCtrl->InsertColumn (ColumnMountPoint, LangString["MOUNT_POINT"], wxLIST_FORMAT_LEFT, 1);
		colPermilles.push_back (259);
#endif

		SlotListCtrl->InsertColumn (ColumnType, LangString["TYPE"], wxLIST_FORMAT_LEFT, 1);
		colPermilles.push_back (100);

		wxImageList *imageList = new wxImageList (16, 12, true);
		imageList->Add (Resources::GetDriveIconBitmap(), Resources::GetDriveIconMaskBitmap());
		SlotListCtrl->AssignImageList (imageList, wxIMAGE_LIST_SMALL);

		SetMinSize (wxSize (-1, -1));

		size_t slotListRowCount = 12;

#ifndef TC_WINDOWS
		int screenHeight = wxSystemSettings::GetMetric (wxSYS_SCREEN_Y);
		
		if (screenHeight < 480)
			slotListRowCount = 1;
		else if (screenHeight <= 600)
			slotListRowCount = slotListRowCount * screenHeight / 1000;
#endif

		Gui->SetListCtrlHeight (SlotListCtrl, slotListRowCount);

#ifdef __WXGTK__
		wxSize size (-1, (int) ((double) Gui->GetCharHeight (this) * 1.53));
		CreateVolumeButton->SetMinSize (size);
		VolumePropertiesButton->SetMinSize (size);
		WipeCacheButton->SetMinSize (size);
		VolumePathComboBox->SetMinSize (size);
		SelectFileButton->SetMinSize (size);
		SelectDeviceButton->SetMinSize (size);
		VolumeToolsButton->SetMinSize (size);
		size = wxSize (-1, 38);
		VolumeButton->SetMinSize (size);
#endif
		Fit();
		Layout();
		Center();

		VolumePathComboBox->SetMinSize (VolumePathComboBox->GetSize());
		VolumePathComboBox->SetMaxSize (VolumePathComboBox->GetSize());

		SetMinSize (GetSize());
		SetMaxSize (GetSize());

		Gui->SetListCtrlColumnWidths (SlotListCtrl, colPermilles);
		
		UpdateVolumeList();
		UpdateWipeCacheButton();
	}

	void MainFrame::InitEvents ()
	{
		Core->VolumeMountedEvent.Connect (EventConnector <MainFrame> (this, &MainFrame::OnVolumeMounted));
		Core->VolumeDismountedEvent.Connect (EventConnector <MainFrame> (this, &MainFrame::OnVolumeDismounted));
		Gui->OpenVolumeSystemRequestEvent.Connect (EventConnector <MainFrame> (this, &MainFrame::OnOpenVolumeSystemRequestEvent));
		Gui->PreferencesUpdatedEvent.Connect (EventConnector <MainFrame> (this, &MainFrame::OnPreferencesUpdated));

		// Drag & drop
		class FileDropTarget : public wxFileDropTarget
		{
		public:
			FileDropTarget (MainFrame *frame) : Frame (frame) { }

			wxDragResult OnDragOver (wxCoord x, wxCoord y, wxDragResult def)
			{
				wxPoint p;
				wxWindow *w = wxFindWindowAtPointer (p);
				if (w == Frame || wxGetTopLevelParent (w) == Frame)
					return wxDragLink;
				return wxDragNone;
			}

			bool OnDropFiles (wxCoord x, wxCoord y, const wxArrayString &filenames)
			{
				if (!filenames.empty())
					Frame->SetVolumePath (wstring (filenames.front()));
				return true;
			}

			MainFrame *Frame;
		};

		SetDropTarget (new FileDropTarget (this));
#ifdef TC_MACOSX
		foreach (wxWindow *c, MainPanel->GetChildren())
			c->SetDropTarget (new FileDropTarget (this));
#endif

		// Volume history
		VolumeHistory::ConnectComboBox (VolumePathComboBox);

#ifdef TC_WINDOWS
		// Hotkeys
		Hotkey::RegisterList (this, GetPreferences().Hotkeys);
		Connect (wxEVT_HOTKEY, wxKeyEventHandler (MainFrame::OnHotkey));
#endif

		// Timer
		class Timer : public wxTimer
		{
		public:
			Timer (MainFrame *frame) : Frame (frame) { }

			void Notify()
			{
				Frame->OnTimer();
			}

			MainFrame *Frame;
		};

		mTimer.reset (dynamic_cast <wxTimer *> (new Timer (this)));
		mTimer->Start (2000);
	}

#ifdef TC_WINDOWS
#include <dbt.h>
	static WNDPROC MainFrameWndProc;
	static LRESULT CALLBACK MainFrameWndProcFilter (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
	{
		if (message == WM_DEVICECHANGE && !Core->IsDeviceChangeInProgress())
		{
			MainFrame *frame = dynamic_cast <MainFrame *> (Gui->GetMainFrame());
			PDEV_BROADCAST_HDR hdr = (PDEV_BROADCAST_HDR) lParam;
			
			if (wParam == DBT_DEVICEREMOVECOMPLETE && hdr->dbch_devicetype == DBT_DEVTYP_VOLUME)
			{
				PDEV_BROADCAST_VOLUME vol = (PDEV_BROADCAST_VOLUME) lParam;
				for (wchar_t driveNo = 0; driveNo < 26; ++driveNo)
				{
					if (vol->dbcv_unitmask & (1 << driveNo))
						frame->OnDeviceChange (wstring (StringFormatter (L"{0}:\\", wchar_t (L'A' + driveNo))));
				}
			}
			else
			{
				frame->OnDeviceChange ();
			}
		}

		return CallWindowProc (MainFrameWndProc, hwnd, message, wParam, lParam);
	}
#endif

	void MainFrame::InitMessageFilter ()
	{
#ifdef TC_WINDOWS
		HWND mainFrameHwnd = static_cast <HWND> (GetHandle());
		MainFrameWndProc = (WNDPROC) GetWindowLongPtr (mainFrameHwnd, GWL_WNDPROC);
		SetWindowLongPtr (mainFrameHwnd, GWL_WNDPROC, (LONG_PTR) MainFrameWndProcFilter);
#endif
	}

	void MainFrame::InitPreferences ()
	{
		try
		{
			LoadPreferences();

			VolumeSlotNumber lastSelectedSlotNumber = GetPreferences().LastSelectedSlotNumber;
			if (Core->IsSlotNumberValid (lastSelectedSlotNumber))
			{
				long slotIndex = SlotNumberToItemIndex (lastSelectedSlotNumber);
				if (slotIndex >= 0)
				{
					SlotListCtrl->SetItemState (slotIndex, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED);
					SlotListCtrl->EnsureVisible (slotIndex);
				}
			}

			LoadFavoriteVolumes();
			VolumeHistory::Load();

			if (VolumePathComboBox->GetValue().empty() && !VolumeHistory::Get().empty())
				SetVolumePath (VolumeHistory::Get().front());
		}
		catch (exception &e)
		{
			Gui->ShowError (e);
			Gui->ShowError (_("Error while loading configuration files located in ") + wstring (Application::GetConfigFilePath (L"")));
		}
	}

	void MainFrame::InitTaskBarIcon ()
	{
		class TaskBarIcon : public wxTaskBarIcon
		{
		public:
			TaskBarIcon (MainFrame *frame) : Busy (false), Frame (frame)
			{
				Connect (wxEVT_TASKBAR_LEFT_DOWN, wxTaskBarIconEventHandler (TaskBarIcon::OnLeftButtonDown));
			}

			wxMenu *CreatePopupMenu ()
			{ 
				auto_ptr <wxMenu> popup (new wxMenu);

				Gui->AppendToMenu (*popup, LangString[Gui->IsInBackgroundMode() ? "SHOW_TC" : "HIDE_TC"], this, wxCommandEventHandler (TaskBarIcon::OnShowHideMenuItemSelected));
				
				popup->AppendSeparator();
				Gui->AppendToMenu (*popup, _("Mount All Favorite Volumes"), this, wxCommandEventHandler (TaskBarIcon::OnMountAllFavoritesMenuItemSelected))->Enable (!Busy);
				Gui->AppendToMenu (*popup, _("Dismount All Mounted Volumes"), this, wxCommandEventHandler (TaskBarIcon::OnDismountAllMenuItemSelected))->Enable (!Busy);
				
				// Favorite volumes
				if (Gui->GetPreferences().BackgroundTaskMenuMountItemsEnabled && !Frame->FavoriteVolumesMenuMap.empty())
				{
					popup->AppendSeparator();
					typedef pair <int, FavoriteVolume> FavMapPair;
					foreach (FavMapPair fp, Frame->FavoriteVolumesMenuMap)
					{
						Gui->AppendToMenu (*popup, LangString["MOUNT"] + L" " + wstring (fp.second.Path) + (fp.second.MountPoint.IsEmpty() ? L"" : L"  " + wstring (fp.second.MountPoint)),
							this, wxCommandEventHandler (TaskBarIcon::OnFavoriteVolumeMenuItemSelected), fp.first)->Enable (!Busy);
					}
				}

				// Mounted volumes
				VolumeInfoList mountedVolumes = Core->GetMountedVolumes();
				if (!mountedVolumes.empty())
				{
					if (Gui->GetPreferences().BackgroundTaskMenuOpenItemsEnabled)
					{
						popup->AppendSeparator();
						OpenMap.clear();
						foreach (shared_ptr <VolumeInfo> volume, mountedVolumes)
						{
							if (!volume->MountPoint.IsEmpty())
							{
								wxString label = LangString["OPEN"] + L" " + wstring (volume->MountPoint) + L" (" + wstring (volume->Path) + L")";
								wxMenuItem *item = Gui->AppendToMenu (*popup, label, this, wxCommandEventHandler (TaskBarIcon::OnOpenMenuItemSelected));
								OpenMap[item->GetId()] = volume;
							}
						}
					}

					if (Gui->GetPreferences().BackgroundTaskMenuDismountItemsEnabled)
					{
						popup->AppendSeparator();
						DismountMap.clear();
						foreach (shared_ptr <VolumeInfo> volume, mountedVolumes)
						{
							wxString label = LangString["DISMOUNT"] + L" ";

							if (!volume->MountPoint.IsEmpty())
								label += wstring (volume->MountPoint) + L" (" + wstring (volume->Path) + L")";
							else
								label += wstring (volume->Path);

							wxMenuItem *item = Gui->AppendToMenu (*popup, label, this, wxCommandEventHandler (TaskBarIcon::OnDismountMenuItemSelected));
							item->Enable (!Busy);
							DismountMap[item->GetId()] = volume;
						}
					}
				}

				popup->AppendSeparator();
				Gui->AppendToMenu (*popup, _("Preferences..."), this, wxCommandEventHandler (TaskBarIcon::OnPreferencesMenuItemSelected))->Enable (!Busy);
#ifndef TC_MACOSX
				popup->AppendSeparator();
				Gui->AppendToMenu (*popup, _("Exit"), this, wxCommandEventHandler (TaskBarIcon::OnExitMenuItemSelected))->Enable (!Busy && Frame->CanExit());
#endif
				return popup.release();
			}

			void OnDismountAllMenuItemSelected (wxCommandEvent& event) { Busy = true; Frame->OnDismountAllButtonClick (event); Busy = false; }
			void OnDismountMenuItemSelected (wxCommandEvent& event) { Busy = true; Frame->DismountVolume (DismountMap[event.GetId()]); Busy = false; }
			void OnFavoriteVolumeMenuItemSelected (wxCommandEvent& event) { Busy = true; Frame->OnFavoriteVolumeMenuItemSelected (event); Busy = false; }
			void OnMountAllFavoritesMenuItemSelected (wxCommandEvent& event) { Busy = true; Frame->MountAllFavorites (); Busy = false; }

			void OnExitMenuItemSelected (wxCommandEvent& event)
			{
				Busy = true;
				if (Core->GetMountedVolumes().empty() || Gui->AskYesNo (LangString ["CONFIRM_EXIT"], false, true))
					Frame->Close (true);
				Busy = false;
			}

			void OnLeftButtonDown (wxTaskBarIconEvent& event) { Gui->SetBackgroundMode (false); }
			void OnOpenMenuItemSelected (wxCommandEvent& event) { Gui->OpenExplorerWindow (OpenMap[event.GetId()]->MountPoint); }
			void OnPreferencesMenuItemSelected (wxCommandEvent& event) { Busy = true; Frame->OnPreferencesMenuItemSelected (event); Busy = false; }
			void OnShowHideMenuItemSelected (wxCommandEvent& event) { Gui->SetBackgroundMode (!Gui->IsInBackgroundMode()); }

			bool Busy;
			map < int, shared_ptr <VolumeInfo> > DismountMap;
			MainFrame *Frame;
			map < int, shared_ptr <VolumeInfo> > OpenMap;
		};

		mTaskBarIcon.reset (new TaskBarIcon (this));
		ShowTaskBarIcon (GetPreferences().BackgroundTaskEnabled);
	}

	void MainFrame::LoadFavoriteVolumes ()
	{
		typedef pair <int, FavoriteVolume> FavMapPair;
		foreach (FavMapPair p, FavoriteVolumesMenuMap)
		{
			FavoritesMenu->Delete (p.first);
		}
		FavoriteVolumesMenuMap.clear();

		foreach_ref (const FavoriteVolume &favorite, FavoriteVolume::LoadList())
		{
			wstring label = wstring (favorite.Path);
			if (!favorite.MountPoint.IsEmpty())
				label += wstring (L"   ") + wstring (favorite.MountPoint);

			wxMenuItem *item = Gui->AppendToMenu (*FavoritesMenu, label, this, wxCommandEventHandler (MainFrame::OnFavoriteVolumeMenuItemSelected));
			FavoriteVolumesMenuMap[item->GetId()] = favorite;
		}
	}

	void MainFrame::LoadPreferences ()
	{
		UserPreferences prefs;
		prefs.Load();
		Gui->SetPreferences (prefs);
		NoHistoryCheckBox->SetValue (!prefs.SaveHistory);
	}
	
	void MainFrame::MountAllDevices ()
	{
		try
		{
			MountOptions mountOptions (GetPreferences().DefaultMountOptions);

			if (SlotListCtrl->GetSelectedItemCount() == 1)
				mountOptions.SlotNumber = SelectedSlotNumber;

			Gui->MountAllDeviceHostedVolumes (mountOptions);
		}
		catch (exception &e)
		{
			Gui->ShowError (e);
		}
	}

	void MainFrame::MountAllFavorites ()
	{
		try
		{
			MountOptions mountOptions (GetPreferences().DefaultMountOptions);
			Gui->MountAllFavoriteVolumes (mountOptions);
		}
		catch (exception &e)
		{
			Gui->ShowError (e);
		}
	}

	void MainFrame::MountVolume ()
	{
		if (!IsFreeSlotSelected())
		{
			Gui->ShowWarning (_("Please select a free drive slot from the list."));
			return;
		}

		if (!CheckVolumePathNotEmpty())
			return;

		MountOptions mountOptions (GetPreferences().DefaultMountOptions);
		mountOptions.SlotNumber = SelectedSlotNumber;
		mountOptions.Path = GetSelectedVolumePath();

		try
		{
			if (Gui->MountVolume (mountOptions) && GetPreferences().SaveHistory)
				VolumeHistory::Add (*mountOptions.Path);
		}
		catch (exception &e)
		{
			Gui->ShowError (e);
		}
	}

	void MainFrame::OnAboutMenuItemSelected (wxCommandEvent& event)
	{
		AboutDialog dialog (this);
		dialog.ShowModal();
	}

	void MainFrame::OnActivate (wxActivateEvent& event)
	{
		Gui->SetActiveFrame (this);

#ifdef TC_MACOSX
		if (event.GetActive() && Gui->IsInBackgroundMode())
			Gui->SetBackgroundMode (false);
#endif
		event.Skip();
	}

	void MainFrame::OnAddAllMountedToFavoritesMenuItemSelected (wxCommandEvent& event)
	{
		AddToFavorites (MountedVolumes);
	}

	void MainFrame::OnAddToFavoritesMenuItemSelected (wxCommandEvent& event)
	{
		shared_ptr <VolumeInfo> selectedVolume = GetSelectedVolume();
		if (selectedVolume)
		{
			VolumeInfoList volumes;
			volumes.push_back (selectedVolume);
			AddToFavorites (volumes);
		}
	}

	void MainFrame::OnBackupVolumeHeadersMenuItemSelected (wxCommandEvent& event)
	{
		if (!CheckVolumePathNotEmpty ())
			return;

		try
		{
			Gui->BackupVolumeHeaders (GetSelectedVolumePath());
		}
		catch (exception &e)
		{
			Gui->ShowError (e);
		}
	}

	void MainFrame::OnBenchmarkMenuItemSelected (wxCommandEvent& event)
	{
		BenchmarkDialog dialog (this);
		dialog.ShowModal();
	}

	void MainFrame::OnClearSlotSelectionMenuItemSelected (wxCommandEvent& event)
	{
		Gui->ClearListCtrlSelection (SlotListCtrl);
		UpdateControls();
	}

	void MainFrame::OnClose (wxCloseEvent& event)
	{
		if (GetPreferences().WipeCacheOnClose)
			Core->WipePasswordCache();

#ifdef TC_MACOSX
		if (!event.CanVeto() && GetPreferences().DismountOnLogOff)
		{
			try
			{
				Gui->DismountVolumes (Core->GetMountedVolumes(), GetPreferences().ForceAutoDismount, false);
			}
			catch (...) { }
		}
#endif

		if (!Gui->IsTheOnlyTopLevelWindow (this))
		{
			// Bring first frame to foreground
			wxFrame *frame = nullptr;
			foreach (wxWindow *window, wxTopLevelWindows)
			{
				if (window != this
					&& dynamic_cast <wxFrame *> (window)
					&& StringConverter::GetTypeName (typeid (*window)).find ("wxTaskBarIcon") == string::npos)
				{
					frame = dynamic_cast <wxFrame *> (window);
					if (window->IsShown())
						break;
				}
			}

			if (frame)
			{
				frame->Show();
				if (frame->IsIconized())
					frame->Iconize(false);
				frame->Raise();
			}
		}
		else if (event.CanVeto() && GetPreferences().BackgroundTaskEnabled
			&& (!GetPreferences().CloseBackgroundTaskOnNoVolumes || !MountedVolumes.empty()))
		{
			// Enter background mode
			if (!Gui->IsInBackgroundMode())
				Gui->SetBackgroundMode (true);
		}
		else
		{
#ifdef __WXGTK__
			Show();
#endif
			SavePreferences();

			Destroy();
		}

		 // Cancel close - veto is not used to prevent aborting log off procedure on Windows
		return;
	}

	void MainFrame::OnCloseAllSecurityTokenSessionsMenuItemSelected (wxCommandEvent& event)
	{
		try
		{
			{
				wxBusyCursor busy;
				SecurityToken::CloseAllSessions();
			}
			Gui->ShowInfo ("ALL_TOKEN_SESSIONS_CLOSED");
		}
		catch (exception &e)
		{
			Gui->ShowError (e);
		}
	}

	void MainFrame::OnCreateVolumeButtonClick (wxCommandEvent& event)
	{
		try
		{
			(new VolumeCreationWizard (nullptr))->Show();
		}
		catch (exception &e)
		{
			Gui->ShowError (e);
		}
	}

	void MainFrame::OnDefaultKeyfilesMenuItemSelected (wxCommandEvent& event)
	{
		PreferencesDialog dialog (this);
		dialog.SelectPage (dialog.DefaultKeyfilesPage);
		dialog.ShowModal();
	}

	void MainFrame::OnDeviceChange (const DirectoryPath &mountPoint)
	{
		// Check if any host device has been removed and force dismount of volumes accordingly
		VolumeInfoList removedVolumes;
		foreach (shared_ptr <VolumeInfo> volume, Core->GetMountedVolumes())
		{
			// File-hosted volumes
			if (!volume->Path.IsDevice() && !mountPoint.IsEmpty())
			{
				if (wxString (wstring(volume->Path)).Upper().StartsWith (wstring (mountPoint).c_str()))
				{
					removedVolumes.push_back (volume);
					continue;
				}
			}

			// Device-hosted volumes
			if (volume->Path.IsDevice() && !Core->IsDevicePresent (volume->Path))
				removedVolumes.push_back (volume);
		}
		
		if (!removedVolumes.empty())
			Gui->AutoDismountVolumes (removedVolumes, true);
	}

	void MainFrame::OnDismountAllButtonClick (wxCommandEvent& event)
	{
		Gui->DismountAllVolumes();
	}

	void MainFrame::OnEncryptionTestMenuItemSelected (wxCommandEvent& event)
	{
		EncryptionTestDialog dialog (this);
		dialog.ShowModal();
	}

	void MainFrame::OnExitButtonClick (wxCommandEvent& event)
	{
		Close();
	}

	void MainFrame::OnFavoriteVolumeMenuItemSelected (wxCommandEvent& event)
	{
		FavoriteVolume favorite = FavoriteVolumesMenuMap[event.GetId()];
		if (!favorite.Path.IsEmpty())
		{
			SetVolumePath (favorite.Path);

			MountOptions mountOptions (GetPreferences().DefaultMountOptions);
			favorite.ToMountOptions (mountOptions);

			shared_ptr <VolumeInfo> volume = Gui->MountVolume (mountOptions);
			if (volume)
				SlotListCtrl->EnsureVisible (SlotNumberToItemIndex (volume->SlotNumber));
		}
	}

	void MainFrame::OnHiddenVolumeProtectionTriggered (shared_ptr <VolumeInfo> protectedVolume)
	{
		Gui->ShowWarningTopMost (StringFormatter (LangString["DAMAGE_TO_HIDDEN_VOLUME_PREVENTED"], wstring (protectedVolume->Path)));
	}

	void MainFrame::OnHotkey (wxKeyEvent& event)
	{
#ifdef TC_WINDOWS
		switch (event.GetId())
		{
		case Hotkey::Id::CloseAllSecurityTokenSessions:
			try
			{
				SecurityToken::CloseAllSessions();
				Gui->ShowInfo ("ALL_TOKEN_SESSIONS_CLOSED");
			}
			catch (exception &e) { Gui->ShowError (e); }
			break;

		case Hotkey::Id::DismountAll:
		case Hotkey::Id::DismountAllWipeCache:
			{
				if (event.GetId() == Hotkey::Id::DismountAllWipeCache)
					WipeCache();

				size_t mountedCount = Core->GetMountedVolumes().size();
				Gui->DismountAllVolumes();
				size_t newMountedCount = Core->GetMountedVolumes().size();

				if (newMountedCount < mountedCount)
				{
					if (newMountedCount == 0 && GetPreferences().DisplayMessageAfterHotkeyDismount)
						Gui->ShowInfo ("MOUNTED_VOLUMES_DISMOUNTED");
					else if (GetPreferences().BeepAfterHotkeyMountDismount)
						MessageBeep((UINT) -1);
				}
			}
			break;

		case Hotkey::Id::ForceDismountAllWipeCache:
		case Hotkey::Id::ForceDismountAllWipeCacheExit:
			{
				bool mounted = !Core->GetMountedVolumes().empty();

				WipeCache();
				Gui->DismountAllVolumes (true, true);

				if (mounted && GetPreferences().DisplayMessageAfterHotkeyDismount)
					Gui->ShowInfo ("VOLUMES_DISMOUNTED_CACHE_WIPED");
				else if (mounted && GetPreferences().BeepAfterHotkeyMountDismount)
					MessageBeep((UINT) -1);

				if (event.GetId() == Hotkey::Id::ForceDismountAllWipeCacheExit)
					Close (true);
			}
			break;

		case Hotkey::Id::MountAllDevices:
		case Hotkey::Id::MountAllFavorites:
			{
				size_t mountedCount = Core->GetMountedVolumes().size();
				
				if (event.GetId() == Hotkey::Id::MountAllDevices)
					MountAllDevices();
				else
					MountAllFavorites();

				if (Core->GetMountedVolumes().size() > mountedCount && GetPreferences().BeepAfterHotkeyMountDismount)
					MessageBeep((UINT) -1);
			}
			break;

		case Hotkey::Id::ShowHideApplication:
			Gui->SetBackgroundMode (!Gui->IsInBackgroundMode());
			break;

		case Hotkey::Id::WipeCache:
			WipeCache();
			Gui->ShowInfo ("PASSWORD_CACHE_WIPED");
			break;

		default:
			assert (false);
			break;
		}
#endif // TC_WINDOWS
	}

	void MainFrame::OnHotkeysMenuItemSelected (wxCommandEvent& event)
	{
		PreferencesDialog dialog (this);
		dialog.SelectPage (dialog.HotkeysPage);
		dialog.ShowModal();
	}

	void MainFrame::OnLegalNoticesMenuItemSelected (wxCommandEvent& event)
	{
		LegalNoticesDialog dialog (this);
		dialog.ShowModal();
	}

	void MainFrame::OnListChanged ()
	{
		OnListItemSelectionChanged();
		UpdateControls();
	}

	void MainFrame::OnListItemActivated (wxListEvent& event)
	{
		if (IsMountedSlotSelected())
			OpenSelectedVolume();
		else
			MountVolume();
	}

	void MainFrame::OnListItemDeleted (long itemIndex)
	{
		if (SelectedItemIndex > itemIndex)
			--SelectedItemIndex;
	}
	
	void MainFrame::OnListItemDeselected (wxListEvent& event)
	{
		OnListItemSelectionChanged();
	}

	void MainFrame::OnListItemInserted (long itemIndex)
	{
		if (SelectedItemIndex >= itemIndex)
			++SelectedItemIndex;
	}

	void MainFrame::OnListItemRightClick (wxListEvent& event)
	{
#ifdef TC_MACOSX
		if (SelectedItemIndex != event.GetIndex())
		{
			SelectedItemIndex = event.GetIndex();
			OnListItemSelectionChanged();
		}

		if (!ListItemRightClickEventPending)
		{
			ListItemRightClickEventPending = true;
			SlotListCtrl->AddPendingEvent (event);
			return;
		}

		ListItemRightClickEventPending = false;
#endif

		wxMenu popup;
		if (IsMountedSlotSelected())
		{
			Gui->AppendToMenu (popup, LangString["DISMOUNT"], this, wxCommandEventHandler (MainFrame::OnDismountVolumeMenuItemSelected));
			Gui->AppendToMenu (popup, LangString["OPEN"], this, wxCommandEventHandler (MainFrame::OnOpenVolumeMenuItemSelected));
			Gui->AppendToMenu (popup, _("Deselect"), this, wxCommandEventHandler (MainFrame::OnClearSlotSelectionMenuItemSelected));

			popup.AppendSeparator();
			Gui->AppendToMenu (popup, _("Add to Favorites..."), this, wxCommandEventHandler (MainFrame::OnAddToFavoritesMenuItemSelected));

			popup.AppendSeparator();
			Gui->AppendToMenu (popup, LangString["IDPM_CHECK_FILESYS"], this, wxCommandEventHandler (MainFrame::OnCheckFilesystemMenuItemSelected));
			Gui->AppendToMenu (popup, LangString["IDPM_REPAIR_FILESYS"], this, wxCommandEventHandler (MainFrame::OnRepairFilesystemMenuItemSelected));

			popup.AppendSeparator();
			Gui->AppendToMenu (popup, LangString["IDPM_PROPERTIES"], this, wxCommandEventHandler (MainFrame::OnVolumePropertiesButtonClick));

			PopupMenu (&popup);
		}
		else if (IsFreeSlotSelected())
		{
			Gui->AppendToMenu (popup, _("Mount Volume"), this, wxCommandEventHandler (MainFrame::OnMountVolumeMenuItemSelected));
			
			popup.AppendSeparator();

			Gui->AppendToMenu (popup, LangString["SELECT_FILE_AND_MOUNT"], this, wxCommandEventHandler (MainFrame::OnSelectFileAndMountMenuItemSelected));
			Gui->AppendToMenu (popup, LangString["SELECT_DEVICE_AND_MOUNT"], this, wxCommandEventHandler (MainFrame::OnSelectDeviceAndMountMenuItemSelected));

			popup.AppendSeparator();

			Gui->AppendToMenu (popup, _("Deselect"), this, wxCommandEventHandler (MainFrame::OnClearSlotSelectionMenuItemSelected));

			PopupMenu (&popup);
		}
	}

	void MainFrame::OnListItemSelected (wxListEvent& event)
	{
		SelectedItemIndex = event.GetIndex();
		OnListItemSelectionChanged();
	}
			
	void MainFrame::OnListItemSelectionChanged ()
	{
		if (SlotListCtrl->GetSelectedItemCount() < 1)
			SelectedItemIndex = -1;
		
		if (SelectedItemIndex >= 0)
			SelectedSlotNumber = (VolumeSlotNumber) SlotListCtrl->GetItemData (SelectedItemIndex);
		else
			SelectedSlotNumber = 0;

		UpdateControls();
	}
	
	void MainFrame::OnManageSecurityTokenKeyfilesMenuItemSelected (wxCommandEvent& event)
	{
		try
		{
			SecurityTokenKeyfilesDialog dialog (this, false);
			dialog.ShowModal();
		}
		catch (exception &e)
		{
			Gui->ShowError (e);
		}
	}

	void MainFrame::OnMountAllDevicesButtonClick (wxCommandEvent& event)
	{
		MountAllDevices();
	}

	void MainFrame::OnMountAllFavoritesMenuItemSelected (wxCommandEvent& event)
	{
		MountAllFavorites();
	}

	void MainFrame::OnNoHistoryCheckBoxClick (wxCommandEvent& event)
	{
		UserPreferences prefs = GetPreferences();
		prefs.SaveHistory = !event.IsChecked();
		Gui->SetPreferences (prefs);

		if (event.IsChecked())
		{
			try
			{
				VolumeHistory::Clear();
			}
			catch (exception &e) { Gui->ShowError (e); }
		}
	}

	void MainFrame::OnOrganizeFavoritesMenuItemSelected (wxCommandEvent& event)
	{
		try
		{
			OrganizeFavorites (FavoriteVolume::LoadList());
		}
		catch (exception &e)
		{
			Gui->ShowError (e);
		}
	}

	void MainFrame::OnPreferencesMenuItemSelected (wxCommandEvent& event)
	{
		PreferencesDialog dialog (this);
		dialog.ShowModal();
	}

	void MainFrame::OnPreferencesUpdated (EventArgs &args)
	{
		const UserPreferences &prefs = GetPreferences();

		NoHistoryCheckBox->SetValue (!prefs.SaveHistory);

		ShowTaskBarIcon (prefs.BackgroundTaskEnabled);
		if (Gui->IsInBackgroundMode() && !prefs.BackgroundTaskEnabled)
			Close (true);

		SavePreferences();
	}
	
	void MainFrame::OnRestoreVolumeHeaderMenuItemSelected (wxCommandEvent& event)
	{
		if (!CheckVolumePathNotEmpty ())
			return;

		try
		{
			Gui->RestoreVolumeHeaders (GetSelectedVolumePath());
		}
		catch (exception &e)
		{
			Gui->ShowError (e);
		}
	}

	void MainFrame::OnSecurityTokenPreferencesMenuItemSelected (wxCommandEvent& event)
	{
		PreferencesDialog dialog (this);
		dialog.SelectPage (dialog.SecurityTokensPage);
		dialog.ShowModal();
	}

	
	void MainFrame::OnSelectDeviceAndMountMenuItemSelected (wxCommandEvent& event)
	{
		DevicePath path = Gui->SelectDevice (this);

		if (!path.IsEmpty())
		{
			SetVolumePath (path);
			OnMountVolumeMenuItemSelected (event);
		}
	}

	void MainFrame::OnSelectDeviceButtonClick (wxCommandEvent& event)
	{
		DevicePath path = Gui->SelectDevice (this);

		if (!path.IsEmpty())
			SetVolumePath (path);
	}

	void MainFrame::OnSelectFileAndMountMenuItemSelected (wxCommandEvent& event)
	{
		FilePath path = Gui->SelectVolumeFile (this);

		if (!path.IsEmpty())
		{
			SetVolumePath (path);
			OnMountVolumeMenuItemSelected (event);
		}
	}

	void MainFrame::OnSelectFileButtonClick (wxCommandEvent& event)
	{
		FilePath path = Gui->SelectVolumeFile (this);
		if (!path.IsEmpty())
			SetVolumePath (path);
	}
	
	void MainFrame::OnTimer ()
	{
		try
		{
			UpdateVolumeList();
			UpdateWipeCacheButton();

			if (GetPreferences().BackgroundTaskEnabled)
			{
				// Inactivity auto-dismount
				if (GetPreferences().DismountOnInactivity)
				{
					VolumeInfoList inactiveVolumes;
					wxLongLong currentTime = wxGetLocalTimeMillis().GetValue();

					map <wstring, VolumeActivityMapEntry> newActivityTimeMap;

					foreach (shared_ptr <VolumeInfo> volume, MountedVolumes)
					{
						if (VolumeActivityMap.find (volume->Path) != VolumeActivityMap.end()
							&& VolumeActivityMap[volume->Path].SerialInstanceNumber == volume->SerialInstanceNumber)
						{
							VolumeActivityMapEntry ae = VolumeActivityMap[volume->Path];

							if (volume->TotalDataRead != ae.TotalDataRead || volume->TotalDataWritten != ae.TotalDataWritten)
							{
								ae.LastActivityTime = currentTime;
								ae.TotalDataRead = volume->TotalDataRead;
								ae.TotalDataWritten = volume->TotalDataWritten;
							}
							else if ((currentTime - ae.LastActivityTime) > GetPreferences().MaxVolumeIdleTime * 1000LL * 60)
							{
								inactiveVolumes.push_back (volume);
							}

							newActivityTimeMap[volume->Path] = ae;
						}
						else
						{
							newActivityTimeMap[volume->Path] = VolumeActivityMapEntry (*volume, currentTime);
						}
					}

					VolumeActivityMap = newActivityTimeMap;

					if (!inactiveVolumes.empty())
						Gui->AutoDismountVolumes (inactiveVolumes);
				}

				// Screen saver auto-dismount
				if (GetPreferences().DismountOnScreenSaver)
				{
#ifdef TC_WINDOWS
					bool running;
					if (SystemParametersInfo (SPI_GETSCREENSAVERRUNNING, 0, &running, 0) != 0)
					{
						static bool previousState = false;
						if (running && !previousState)
						{
							previousState = true;
							Gui->OnAutoDismountAllEvent();
						}
						else
						{
							previousState = running;
						}
					}
#endif
				}
			}

			if (Gui->IsInBackgroundMode())
			{
				if (!GetPreferences().BackgroundTaskEnabled)
				{
					Close (true);
				}
				else if (MountedVolumes.empty() && (GetPreferences().CloseBackgroundTaskOnNoVolumes || Core->IsInPortableMode()))
				{
					Close (true);
				}
			}

#if defined(TC_UNIX) && !defined(TC_MACOSX)
			try
			{
				byte buf[128];
				if (read (ShowRequestFifo, buf, sizeof (buf)) > 0 && Gui->IsInBackgroundMode())
					Gui->SetBackgroundMode (false);
			}
			catch (...)
			{
#ifdef DEBUG
				throw;
#endif
			}
#endif
		}
		catch (exception &e)
		{
			Gui->ShowError (e);
		}
	}

	void MainFrame::OnVolumeButtonClick (wxCommandEvent& event)
	{
		if (IsMountedSlotSelected())
			DismountVolume();
		else
			MountVolume();
	}

	void MainFrame::OnVolumePropertiesButtonClick (wxCommandEvent& event)
	{
		shared_ptr <VolumeInfo> selectedVolume = GetSelectedVolume();
		if (selectedVolume)
		{
			VolumePropertiesDialog dialog (this, *selectedVolume);
			dialog.ShowModal();
		}
	}

	void MainFrame::OnVolumeToolsButtonClick (wxCommandEvent& event)
	{
		if (!CheckVolumePathNotEmpty())
			return;

		wxMenu popup;

		Gui->AppendToMenu (popup, _("Change Volume Password..."), this, wxCommandEventHandler (MainFrame::OnChangePasswordMenuItemSelected));

		popup.AppendSeparator ();

		Gui->AppendToMenu (popup, _("Add/Remove Keyfiles to/from Volume..."), this, wxCommandEventHandler (MainFrame::OnChangeKeyfilesMenuItemSelected));
		Gui->AppendToMenu (popup, _("Remove All Keyfiles from Volume..."), this, wxCommandEventHandler (MainFrame::OnRemoveKeyfilesMenuItemSelected));

		popup.AppendSeparator ();

		Gui->AppendToMenu (popup, _("Change Header Key Derivation Algorithm..."), this, wxCommandEventHandler (MainFrame::OnChangePkcs5PrfMenuItemSelected));

		popup.AppendSeparator ();

		Gui->AppendToMenu (popup, _("Backup Volume Header..."), this, wxCommandEventHandler (MainFrame::OnBackupVolumeHeadersMenuItemSelected));
		Gui->AppendToMenu (popup, _("Restore Volume Header..."), this, wxCommandEventHandler (MainFrame::OnRestoreVolumeHeaderMenuItemSelected));

		PopupMenu (&popup, VolumeToolsButton->GetPosition().x + 2, VolumeToolsButton->GetPosition().y + 2);
	}

	void MainFrame::OnWipeCacheButtonClick (wxCommandEvent& event)
	{
		WipeCache();
		Gui->ShowInfo ("PASSWORD_CACHE_WIPED");
	}
	
	void MainFrame::OpenSelectedVolume () const
	{
		shared_ptr <VolumeInfo> selectedVolume = GetSelectedVolume();
		if (selectedVolume)
		{
			try
			{
				wxBusyCursor busy;
				Gui->OpenExplorerWindow (selectedVolume->MountPoint);
			}
			catch (exception &e)
			{
				Gui->ShowError (e);
			}
		}
	}

	void MainFrame::OrganizeFavorites (const FavoriteVolumeList &favorites, size_t newItemCount)
	{
		FavoriteVolumesDialog dialog (this, favorites, newItemCount);

		if (dialog.ShowModal() == wxID_OK)
		{
			FavoriteVolume::SaveList (dialog.GetFavorites());
			LoadFavoriteVolumes();
		}
	}

	void MainFrame::SavePreferences () const
	{
		try
		{
			UserPreferences prefs = GetPreferences();
			prefs.LastSelectedSlotNumber = SelectedSlotNumber;
			prefs.Save();

			VolumeHistory::Save();
		}
		catch (exception &e)
		{
			if (!Core->IsInPortableMode())
				Gui->ShowError (e);
		}
	}

	void MainFrame::ShowTaskBarIcon (bool show)
	{
		if (!show && mTaskBarIcon->IsIconInstalled())
		{
			mTaskBarIcon->RemoveIcon();
		}
		else if (show && !mTaskBarIcon->IsIconInstalled())
		{
#ifndef TC_MACOSX
			mTaskBarIcon->SetIcon (Resources::GetVeraCryptIcon(), L"VeraCrypt");
#endif
		}
	}

	long MainFrame::SlotNumberToItemIndex (uint32 slotNumber) const
	{
		for (long itemIndex = 0; itemIndex < SlotListCtrl->GetItemCount(); itemIndex++)
		{
			wxListItem item;
			item.SetId (itemIndex);
			if (slotNumber == (uint32) SlotListCtrl->GetItemData (item))
				return itemIndex;
		}
		return -1;
	}
	
	void MainFrame::UpdateControls ()
	{
		bool mounted = IsMountedSlotSelected();

		VolumeButton->SetLabel (mounted ? LangString["DISMOUNT"] : wxString (_("Mount")));
		VolumePropertiesButton->Enable (mounted);

		DismountVolumeMenuItem->Enable (mounted); 
		MountVolumeMenuItem->Enable (!mounted);
		VolumePropertiesMenuItem->Enable (mounted);
		AddToFavoritesMenuItem->Enable (mounted);
		AddAllMountedToFavoritesMenuItem->Enable (!MountedVolumes.empty());
		UpdateWipeCacheButton();
	}

	void MainFrame::UpdateVolumeList ()
	{
		static Mutex mutex;
		ScopeLock lock (mutex);

		bool listChanged = false;

		MountedVolumes = Core->GetMountedVolumes();
		
		map < VolumeSlotNumber, shared_ptr <VolumeInfo> > mountedVolumesMap;
		foreach (shared_ptr <VolumeInfo> volume, MountedVolumes)
		{
			mountedVolumesMap[volume->SlotNumber] = volume;
		}

		VolumeInfoList protectionTriggeredVolumes;

		// Update list
		long prevItemIndex = -1;
		for (VolumeSlotNumber slotNumber = Core->GetFirstSlotNumber(); slotNumber <= Core->GetLastSlotNumber(); ++slotNumber)
		{
			long itemIndex = SlotNumberToItemIndex (slotNumber);
			vector <wstring> fields (SlotListCtrl->GetColumnCount());

			if (mountedVolumesMap.find (slotNumber) != mountedVolumesMap.end())
			{
				shared_ptr <VolumeInfo> volume = mountedVolumesMap[slotNumber];

#ifdef TC_WINDOWS
				fields[ColumnSlot] = volume->MountPoint;
				fields[ColumnEA] = volume->EncryptionAlgorithmName;
#else
				fields[ColumnSlot] = StringConverter::FromNumber (slotNumber);
				fields[ColumnMountPoint] = volume->MountPoint;
#endif
				fields[ColumnPath] = volume->Path;
				fields[ColumnSize] = Gui->SizeToString (volume->Size);
				fields[ColumnType] = Gui->VolumeTypeToString (volume->Type, volume->Protection);
				
				if (volume->HiddenVolumeProtectionTriggered)
				{
					fields[ColumnType] += L"(!)";
				}

				bool slotUpdated = false;
				if (itemIndex == -1)
				{
					Gui->InsertToListCtrl (SlotListCtrl, ++prevItemIndex, fields, 0, (void *) volume->SlotNumber);
					OnListItemInserted (prevItemIndex);

					listChanged |= true;
					slotUpdated = true;
				}
				else
				{
					if (Gui->UpdateListCtrlItem (SlotListCtrl, itemIndex, fields))
					{
						listChanged = true;
						slotUpdated = true;
					}
					prevItemIndex = itemIndex;
				}

				if (slotUpdated && volume->HiddenVolumeProtectionTriggered)
					protectionTriggeredVolumes.push_back (volume);
			}
			else
			{
#ifdef TC_WINDOWS
				fields[ColumnSlot] = Core->SlotNumberToMountPoint (slotNumber);
#else
				fields[ColumnSlot] = StringConverter::FromNumber (slotNumber);
#endif
				
#ifdef TC_WINDOWS
				if (Core->IsMountPointAvailable (fields[ColumnSlot]))
#else
				if (true)
#endif
				{
					if (itemIndex == -1)
					{
						Gui->InsertToListCtrl (SlotListCtrl, ++prevItemIndex, fields, 0, (void *) slotNumber);
						OnListItemInserted (prevItemIndex);
						listChanged |= true;
					}
					else
					{
						listChanged |= Gui->UpdateListCtrlItem (SlotListCtrl, itemIndex, fields);
						prevItemIndex = itemIndex;
					}
				}
				else if (itemIndex != -1)
				{
					SlotListCtrl->DeleteItem (itemIndex);
					OnListItemDeleted (itemIndex);
					listChanged = true;
				}
			}
		}

		if (listChanged)
			OnListChanged();

		foreach (shared_ptr <VolumeInfo> volume, protectionTriggeredVolumes)
			OnHiddenVolumeProtectionTriggered (volume);
	}

	void MainFrame::UpdateWipeCacheButton ()
	{
		bool enabled = WipeCacheButton->IsEnabled();
		bool empty = Core->IsPasswordCacheEmpty();

		if (empty && enabled)
		{
			WipeCacheButton->Disable();
			WipeCachedPasswordsMenuItem->Enable (false);
		}
		else if (!empty && !enabled)
		{
			WipeCacheButton->Enable();
			WipeCachedPasswordsMenuItem->Enable();
		}
	}

	void MainFrame::WipeCache ()
	{
		Core->WipePasswordCache();
		UpdateWipeCacheButton();
	}
}