1
0
mirror of https://github.com/veracrypt/VeraCrypt.git synced 2025-11-12 03:18:26 -06:00

Add TrueCrypt 7.1a MacOSX/Linux specific source files.

This commit is contained in:
Mounir IDRASSI
2014-05-31 18:44:53 +02:00
parent 97011f179c
commit 7ffce028d0
203 changed files with 52120 additions and 0 deletions

98
src/Main/Application.cpp Normal file
View File

@@ -0,0 +1,98 @@
/*
Copyright (c) 2008 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"
#include <wx/stdpaths.h>
#include "Main.h"
#include "Application.h"
#include "CommandLineInterface.h"
#ifndef TC_NO_GUI
#include "GraphicUserInterface.h"
#endif
#include "TextUserInterface.h"
namespace TrueCrypt
{
wxApp* Application::CreateConsoleApp ()
{
mUserInterface = new TextUserInterface;
mUserInterfaceType = UserInterfaceType::Text;
return mUserInterface;
}
#ifndef TC_NO_GUI
wxApp* Application::CreateGuiApp ()
{
mUserInterface = new GraphicUserInterface;
mUserInterfaceType = UserInterfaceType::Graphic;
return mUserInterface;
}
#endif
FilePath Application::GetConfigFilePath (const wxString &configFileName, bool createConfigDir)
{
wxStandardPaths stdPaths;
DirectoryPath configDir;
if (!Core->IsInPortableMode())
{
#ifdef TC_MACOSX
wxFileName configPath (L"~/Library/Application Support/TrueCrypt");
configPath.Normalize();
configDir = wstring (configPath.GetFullPath());
#else
configDir = wstring (stdPaths.GetUserDataDir());
#endif
}
else
configDir = GetExecutableDirectory();
if (createConfigDir && !configDir.IsDirectory())
Directory::Create (configDir);
FilePath filePath = wstring (wxFileName (wstring (configDir), configFileName).GetFullPath());
return filePath;
}
DirectoryPath Application::GetExecutableDirectory ()
{
return wstring (wxFileName (wxStandardPaths().GetExecutablePath()).GetPath());
}
FilePath Application::GetExecutablePath ()
{
return wstring (wxStandardPaths().GetExecutablePath());
}
void Application::Initialize (UserInterfaceType::Enum type)
{
switch (type)
{
case UserInterfaceType::Text:
{
wxAppInitializer wxTheAppInitializer((wxAppInitializerFunction) CreateConsoleApp);
break;
}
#ifndef TC_NO_GUI
case UserInterfaceType::Graphic:
{
wxAppInitializer wxTheAppInitializer((wxAppInitializerFunction) CreateGuiApp);
break;
}
#endif
default:
throw ParameterIncorrect (SRC_POS);
}
}
int Application::ExitCode = 0;
UserInterface *Application::mUserInterface = nullptr;
UserInterfaceType::Enum Application::mUserInterfaceType;
}

40
src/Main/Application.h Normal file
View File

@@ -0,0 +1,40 @@
/*
Copyright (c) 2008 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.
*/
#ifndef TC_HEADER_Main_AppMain
#define TC_HEADER_Main_AppMain
#include "Main.h"
#include "UserInterface.h"
#include "UserInterfaceType.h"
namespace TrueCrypt
{
class Application
{
public:
static wxApp* CreateConsoleApp ();
static wxApp* CreateGuiApp ();
static FilePath GetConfigFilePath (const wxString &configFileName, bool createConfigDir = false);
static DirectoryPath GetExecutableDirectory ();
static FilePath GetExecutablePath ();
static int GetExitCode () { return ExitCode; }
static wstring GetName () { return L"TrueCrypt"; }
static UserInterface *GetUserInterface () { return mUserInterface; }
static UserInterfaceType::Enum GetUserInterfaceType () { return mUserInterfaceType; }
static void Initialize (UserInterfaceType::Enum type);
static void SetExitCode (int code) { ExitCode = code; }
protected:
static int ExitCode;
static UserInterface *mUserInterface;
static UserInterfaceType::Enum mUserInterfaceType;
};
}
#endif // TC_HEADER_Main_AppMain

View File

@@ -0,0 +1,583 @@
/*
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"
#include <wx/cmdline.h>
#include <wx/tokenzr.h>
#include "Core/Core.h"
#include "Application.h"
#include "CommandLineInterface.h"
#include "LanguageStrings.h"
#include "UserInterfaceException.h"
namespace TrueCrypt
{
CommandLineInterface::CommandLineInterface (wxCmdLineParser &parser, UserInterfaceType::Enum interfaceType) :
ArgCommand (CommandId::None),
ArgFilesystem (VolumeCreationOptions::FilesystemType::Unknown),
ArgNoHiddenVolumeProtection (false),
ArgSize (0),
ArgVolumeType (VolumeType::Unknown),
StartBackgroundTask (false)
{
parser.SetSwitchChars (L"-");
parser.AddOption (L"", L"auto-mount", _("Auto mount device-hosted/favorite volumes"));
parser.AddSwitch (L"", L"backup-headers", _("Backup volume headers"));
parser.AddSwitch (L"", L"background-task", _("Start Background Task"));
#ifdef TC_WINDOWS
parser.AddSwitch (L"", L"cache", _("Cache passwords and keyfiles"));
#endif
parser.AddSwitch (L"C", L"change", _("Change password or keyfiles"));
parser.AddSwitch (L"c", L"create", _("Create new volume"));
parser.AddSwitch (L"", L"create-keyfile", _("Create new keyfile"));
parser.AddSwitch (L"", L"delete-token-keyfiles", _("Delete security token keyfiles"));
parser.AddSwitch (L"d", L"dismount", _("Dismount volume"));
parser.AddSwitch (L"", L"display-password", _("Display password while typing"));
parser.AddOption (L"", L"encryption", _("Encryption algorithm"));
parser.AddSwitch (L"", L"explore", _("Open explorer window for mounted volume"));
parser.AddSwitch (L"", L"export-token-keyfile",_("Export keyfile from security token"));
parser.AddOption (L"", L"filesystem", _("Filesystem type"));
parser.AddSwitch (L"f", L"force", _("Force mount/dismount/overwrite"));
#if !defined(TC_WINDOWS) && !defined(TC_MACOSX)
parser.AddOption (L"", L"fs-options", _("Filesystem mount options"));
#endif
parser.AddOption (L"", L"hash", _("Hash algorithm"));
parser.AddSwitch (L"h", L"help", _("Display detailed command line help"), wxCMD_LINE_OPTION_HELP);
parser.AddSwitch (L"", L"import-token-keyfiles", _("Import keyfiles to security token"));
parser.AddOption (L"k", L"keyfiles", _("Keyfiles"));
parser.AddSwitch (L"l", L"list", _("List mounted volumes"));
parser.AddSwitch (L"", L"list-token-keyfiles", _("List security token keyfiles"));
parser.AddSwitch (L"", L"load-preferences", _("Load user preferences"));
parser.AddSwitch (L"", L"mount", _("Mount volume interactively"));
parser.AddOption (L"m", L"mount-options", _("TrueCrypt volume mount options"));
parser.AddOption (L"", L"new-keyfiles", _("New keyfiles"));
parser.AddOption (L"", L"new-password", _("New password"));
parser.AddSwitch (L"", L"non-interactive", _("Do not interact with user"));
parser.AddOption (L"p", L"password", _("Password"));
parser.AddOption (L"", L"protect-hidden", _("Protect hidden volume"));
parser.AddOption (L"", L"protection-keyfiles", _("Keyfiles for protected hidden volume"));
parser.AddOption (L"", L"protection-password", _("Password for protected hidden volume"));
parser.AddOption (L"", L"random-source", _("Use file as source of random data"));
parser.AddSwitch (L"", L"restore-headers", _("Restore volume headers"));
parser.AddSwitch (L"", L"save-preferences", _("Save user preferences"));
parser.AddSwitch (L"", L"quick", _("Enable quick format"));
parser.AddOption (L"", L"size", _("Size in bytes"));
parser.AddOption (L"", L"slot", _("Volume slot number"));
parser.AddSwitch (L"", L"test", _("Test internal algorithms"));
parser.AddSwitch (L"t", L"text", _("Use text user interface"));
parser.AddOption (L"", L"token-lib", _("Security token library"));
parser.AddSwitch (L"v", L"verbose", _("Enable verbose output"));
parser.AddSwitch (L"", L"version", _("Display version information"));
parser.AddSwitch (L"", L"volume-properties", _("Display volume properties"));
parser.AddOption (L"", L"volume-type", _("Volume type"));
parser.AddParam ( _("Volume path"), wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL);
parser.AddParam ( _("Mount point"), wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL);
wxString str;
bool param1IsVolume = false;
bool param1IsMountedVolumeSpec = false;
bool param1IsMountPoint = false;
bool param1IsFile = false;
if (parser.Parse () > 0)
throw_err (_("Incorrect command line specified."));
if (parser.Found (L"help"))
{
ArgCommand = CommandId::Help;
return;
}
if (parser.Found (L"text") && interfaceType != UserInterfaceType::Text)
{
wstring msg = wstring (_("Option -t or --text must be specified as the first argument."));
wcerr << msg << endl;
throw_err (msg);
}
if (parser.Found (L"version"))
{
ArgCommand = CommandId::DisplayVersion;
return;
}
// Preferences
if (parser.Found (L"load-preferences"))
{
// Load preferences first to allow command line options to override them
Preferences.Load();
ArgMountOptions = Preferences.DefaultMountOptions;
}
// Commands
if (parser.Found (L"auto-mount", &str))
{
CheckCommandSingle();
wxStringTokenizer tokenizer (str, L",");
while (tokenizer.HasMoreTokens())
{
wxString token = tokenizer.GetNextToken();
if (token == L"devices")
{
if (ArgCommand == CommandId::AutoMountFavorites)
ArgCommand = CommandId::AutoMountDevicesFavorites;
else
ArgCommand = CommandId::AutoMountDevices;
param1IsMountPoint = true;
}
else if (token == L"favorites")
{
if (ArgCommand == CommandId::AutoMountDevices)
ArgCommand = CommandId::AutoMountDevicesFavorites;
else
ArgCommand = CommandId::AutoMountFavorites;
}
else
{
throw_err (LangString["UNKNOWN_OPTION"] + L": " + token);
}
}
}
if (parser.Found (L"backup-headers"))
{
CheckCommandSingle();
ArgCommand = CommandId::BackupHeaders;
param1IsVolume = true;
}
if (parser.Found (L"change"))
{
CheckCommandSingle();
ArgCommand = CommandId::ChangePassword;
param1IsVolume = true;
}
if (parser.Found (L"create"))
{
CheckCommandSingle();
ArgCommand = CommandId::CreateVolume;
param1IsVolume = true;
}
if (parser.Found (L"create-keyfile"))
{
CheckCommandSingle();
ArgCommand = CommandId::CreateKeyfile;
param1IsFile = true;
}
if (parser.Found (L"delete-token-keyfiles"))
{
CheckCommandSingle();
ArgCommand = CommandId::DeleteSecurityTokenKeyfiles;
}
if (parser.Found (L"dismount"))
{
CheckCommandSingle();
ArgCommand = CommandId::DismountVolumes;
param1IsMountedVolumeSpec = true;
}
if (parser.Found (L"export-token-keyfile"))
{
CheckCommandSingle();
ArgCommand = CommandId::ExportSecurityTokenKeyfile;
}
if (parser.Found (L"import-token-keyfiles"))
{
CheckCommandSingle();
ArgCommand = CommandId::ImportSecurityTokenKeyfiles;
}
if (parser.Found (L"list"))
{
CheckCommandSingle();
ArgCommand = CommandId::ListVolumes;
param1IsMountedVolumeSpec = true;
}
if (parser.Found (L"list-token-keyfiles"))
{
CheckCommandSingle();
ArgCommand = CommandId::ListSecurityTokenKeyfiles;
}
if (parser.Found (L"mount"))
{
CheckCommandSingle();
ArgCommand = CommandId::MountVolume;
param1IsVolume = true;
}
if (parser.Found (L"save-preferences"))
{
CheckCommandSingle();
ArgCommand = CommandId::SavePreferences;
}
if (parser.Found (L"test"))
{
CheckCommandSingle();
ArgCommand = CommandId::Test;
}
if (parser.Found (L"volume-properties"))
{
CheckCommandSingle();
ArgCommand = CommandId::DisplayVolumeProperties;
param1IsMountedVolumeSpec = true;
}
// Options
if (parser.Found (L"background-task"))
StartBackgroundTask = true;
#ifdef TC_WINDOWS
if (parser.Found (L"cache"))
ArgMountOptions.CachePassword = true;
#endif
ArgDisplayPassword = parser.Found (L"display-password");
if (parser.Found (L"encryption", &str))
{
ArgEncryptionAlgorithm.reset();
foreach (shared_ptr <EncryptionAlgorithm> ea, EncryptionAlgorithm::GetAvailableAlgorithms())
{
if (!ea->IsDeprecated() && wxString (ea->GetName()).IsSameAs (str, false))
ArgEncryptionAlgorithm = ea;
}
if (!ArgEncryptionAlgorithm)
throw_err (LangString["UNKNOWN_OPTION"] + L": " + str);
}
if (parser.Found (L"explore"))
Preferences.OpenExplorerWindowAfterMount = true;
if (parser.Found (L"filesystem", &str))
{
if (str.IsSameAs (L"none", false))
{
ArgMountOptions.NoFilesystem = true;
ArgFilesystem = VolumeCreationOptions::FilesystemType::None;
}
else
{
ArgMountOptions.FilesystemType = wstring (str);
if (str.IsSameAs (L"FAT", false))
ArgFilesystem = VolumeCreationOptions::FilesystemType::FAT;
else
ArgFilesystem = VolumeCreationOptions::FilesystemType::None;
}
}
ArgForce = parser.Found (L"force");
#if !defined(TC_WINDOWS) && !defined(TC_MACOSX)
if (parser.Found (L"fs-options", &str))
ArgMountOptions.FilesystemOptions = str;
#endif
if (parser.Found (L"hash", &str))
{
ArgHash.reset();
foreach (shared_ptr <Hash> hash, Hash::GetAvailableAlgorithms())
{
if (wxString (hash->GetName()).IsSameAs (str, false))
ArgHash = hash;
}
if (!ArgHash)
throw_err (LangString["UNKNOWN_OPTION"] + L": " + str);
}
if (parser.Found (L"keyfiles", &str))
ArgKeyfiles = ToKeyfileList (str);
if (parser.Found (L"mount-options", &str))
{
wxStringTokenizer tokenizer (str, L",");
while (tokenizer.HasMoreTokens())
{
wxString token = tokenizer.GetNextToken();
if (token == L"headerbak")
ArgMountOptions.UseBackupHeaders = true;
else if (token == L"nokernelcrypto")
ArgMountOptions.NoKernelCrypto = true;
else if (token == L"readonly" || token == L"ro")
ArgMountOptions.Protection = VolumeProtection::ReadOnly;
else if (token == L"system")
ArgMountOptions.PartitionInSystemEncryptionScope = true;
else if (token == L"timestamp" || token == L"ts")
ArgMountOptions.PreserveTimestamps = false;
#ifdef TC_WINDOWS
else if (token == L"removable" || token == L"rm")
ArgMountOptions.Removable = true;
#endif
else
throw_err (LangString["UNKNOWN_OPTION"] + L": " + token);
}
}
if (parser.Found (L"new-keyfiles", &str))
ArgNewKeyfiles = ToKeyfileList (str);
if (parser.Found (L"new-password", &str))
ArgNewPassword.reset (new VolumePassword (wstring (str)));
if (parser.Found (L"non-interactive"))
{
if (interfaceType != UserInterfaceType::Text)
throw_err (L"--non-interactive is supported only in text mode");
Preferences.NonInteractive = true;
}
if (parser.Found (L"password", &str))
ArgPassword.reset (new VolumePassword (wstring (str)));
if (parser.Found (L"protect-hidden", &str))
{
if (str == L"yes")
{
if (ArgMountOptions.Protection != VolumeProtection::ReadOnly)
ArgMountOptions.Protection = VolumeProtection::HiddenVolumeReadOnly;
}
else if (str == L"no")
ArgNoHiddenVolumeProtection = true;
else
throw_err (LangString["UNKNOWN_OPTION"] + L": " + str);
}
if (parser.Found (L"protection-keyfiles", &str))
{
ArgMountOptions.ProtectionKeyfiles = ToKeyfileList (str);
ArgMountOptions.Protection = VolumeProtection::HiddenVolumeReadOnly;
}
if (parser.Found (L"protection-password", &str))
{
ArgMountOptions.ProtectionPassword.reset (new VolumePassword (wstring (str)));
ArgMountOptions.Protection = VolumeProtection::HiddenVolumeReadOnly;
}
ArgQuick = parser.Found (L"quick");
if (parser.Found (L"random-source", &str))
ArgRandomSourcePath = FilesystemPath (str);
if (parser.Found (L"restore-headers"))
{
CheckCommandSingle();
ArgCommand = CommandId::RestoreHeaders;
param1IsVolume = true;
}
if (parser.Found (L"slot", &str))
{
unsigned long number;
if (!str.ToULong (&number) || number < Core->GetFirstSlotNumber() || number > Core->GetLastSlotNumber())
throw_err (LangString["PARAMETER_INCORRECT"] + L": " + str);
ArgMountOptions.SlotNumber = number;
if (param1IsMountedVolumeSpec)
{
shared_ptr <VolumeInfo> volume = Core->GetMountedVolume (number);
if (!volume)
throw_err (_("No such volume is mounted."));
ArgVolumes.push_back (volume);
param1IsMountedVolumeSpec = false;
}
}
if (parser.Found (L"size", &str))
{
try
{
ArgSize = StringConverter::ToUInt64 (wstring (str));
}
catch (...)
{
throw_err (LangString["PARAMETER_INCORRECT"] + L": " + str);
}
}
if (parser.Found (L"token-lib", &str))
Preferences.SecurityTokenModule = wstring (str);
if (parser.Found (L"verbose"))
Preferences.Verbose = true;
if (parser.Found (L"volume-type", &str))
{
if (str.IsSameAs (L"normal", false))
ArgVolumeType = VolumeType::Normal;
else if (str.IsSameAs (L"hidden", false))
ArgVolumeType = VolumeType::Hidden;
else
throw_err (LangString["UNKNOWN_OPTION"] + L": " + str);
}
// Parameters
if (parser.GetParamCount() > 0)
{
if (ArgCommand == CommandId::None)
{
ArgCommand = CommandId::MountVolume;
param1IsVolume = true;
}
if (param1IsVolume)
{
wxFileName volPath (parser.GetParam (0));
#ifdef TC_WINDOWS
if (!parser.GetParam (0).StartsWith (L"\\Device\\"))
#endif
volPath.Normalize (wxPATH_NORM_ABSOLUTE | wxPATH_NORM_DOTS);
ArgVolumePath.reset (new VolumePath (wstring (volPath.GetFullPath())));
}
if (param1IsMountPoint || parser.GetParamCount() >= 2)
{
wstring s (parser.GetParam (param1IsMountPoint ? 0 : 1));
if (s.empty())
ArgMountOptions.NoFilesystem = true;
wxFileName mountPoint (wstring (Directory::AppendSeparator (s)));
mountPoint.Normalize (wxPATH_NORM_ABSOLUTE | wxPATH_NORM_DOTS);
ArgMountPoint.reset (new DirectoryPath (wstring (mountPoint.GetPath())));
}
if (param1IsFile)
{
ArgFilePath.reset (new FilePath (parser.GetParam (0)));
}
}
if (param1IsMountedVolumeSpec)
ArgVolumes = GetMountedVolumes (parser.GetParamCount() > 0 ? parser.GetParam (0) : wxString());
if (ArgCommand == CommandId::None && Application::GetUserInterfaceType() == UserInterfaceType::Text)
parser.Usage();
}
CommandLineInterface::~CommandLineInterface ()
{
}
void CommandLineInterface::CheckCommandSingle () const
{
if (ArgCommand != CommandId::None)
throw_err (_("Only a single command can be specified at a time."));
}
shared_ptr <KeyfileList> CommandLineInterface::ToKeyfileList (const wxString &arg) const
{
wxStringTokenizer tokenizer (arg, L",", wxTOKEN_RET_EMPTY_ALL);
// Handle escaped separator
wxArrayString arr;
bool prevEmpty = false;
while (tokenizer.HasMoreTokens())
{
wxString token = tokenizer.GetNextToken();
if (prevEmpty && token.empty() && tokenizer.HasMoreTokens())
{
token = tokenizer.GetNextToken();
if (!token.empty())
{
arr.Add (token);
prevEmpty = true;
continue;
}
}
if (token.empty() && !tokenizer.HasMoreTokens())
break;
if (prevEmpty || token.empty())
{
if (arr.Count() < 1)
{
arr.Add (L"");
continue;
}
arr.Last() += token.empty() ? L',' : token;
}
else
arr.Add (token);
prevEmpty = token.empty();
}
make_shared_auto (KeyfileList, keyfileList);
for (size_t i = 0; i < arr.GetCount(); i++)
{
if (!arr[i].empty())
keyfileList->push_back (make_shared <Keyfile> (wstring (arr[i])));
}
return keyfileList;
}
VolumeInfoList CommandLineInterface::GetMountedVolumes (const wxString &mountedVolumeSpec) const
{
VolumeInfoList volumes = Core->GetMountedVolumes ();
VolumeInfoList filteredVolumes;
wxFileName pathFilter;
if (!mountedVolumeSpec.empty())
{
pathFilter = mountedVolumeSpec;
pathFilter.Normalize (wxPATH_NORM_ABSOLUTE | wxPATH_NORM_DOTS);
}
else
return volumes;
foreach (shared_ptr <VolumeInfo> volume, volumes)
{
if (mountedVolumeSpec.empty())
{
filteredVolumes.push_back (volume);
}
else if (wxString (volume->Path) == pathFilter.GetFullPath())
{
filteredVolumes.push_back (volume);
}
else if (wxString (volume->MountPoint) == pathFilter.GetFullPath()
|| (wxString (volume->MountPoint) + wxFileName::GetPathSeparator()) == pathFilter.GetFullPath())
{
filteredVolumes.push_back (volume);
}
}
if (!mountedVolumeSpec.IsEmpty() && filteredVolumes.size() < 1)
throw_err (_("No such volume is mounted."));
return filteredVolumes;
}
auto_ptr <CommandLineInterface> CmdLine;
}

View File

@@ -0,0 +1,94 @@
/*
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.
*/
#ifndef TC_HEADER_Main_CommandInterface
#define TC_HEADER_Main_CommandInterface
#include "System.h"
#include "Main.h"
#include "Volume/VolumeInfo.h"
#include "Core/MountOptions.h"
#include "Core/VolumeCreator.h"
#include "UserPreferences.h"
#include "UserInterfaceType.h"
namespace TrueCrypt
{
struct CommandId
{
enum Enum
{
None,
AutoMountDevices,
AutoMountDevicesFavorites,
AutoMountFavorites,
BackupHeaders,
ChangePassword,
CreateKeyfile,
CreateVolume,
DeleteSecurityTokenKeyfiles,
DismountVolumes,
DisplayVersion,
DisplayVolumeProperties,
ExportSecurityTokenKeyfile,
Help,
ImportSecurityTokenKeyfiles,
ListSecurityTokenKeyfiles,
ListVolumes,
MountVolume,
RestoreHeaders,
SavePreferences,
Test
};
};
struct CommandLineInterface
{
public:
CommandLineInterface (wxCmdLineParser &parser, UserInterfaceType::Enum interfaceType);
virtual ~CommandLineInterface ();
CommandId::Enum ArgCommand;
bool ArgDisplayPassword;
shared_ptr <EncryptionAlgorithm> ArgEncryptionAlgorithm;
shared_ptr <FilePath> ArgFilePath;
VolumeCreationOptions::FilesystemType::Enum ArgFilesystem;
bool ArgForce;
shared_ptr <Hash> ArgHash;
shared_ptr <KeyfileList> ArgKeyfiles;
MountOptions ArgMountOptions;
shared_ptr <DirectoryPath> ArgMountPoint;
shared_ptr <KeyfileList> ArgNewKeyfiles;
shared_ptr <VolumePassword> ArgNewPassword;
bool ArgNoHiddenVolumeProtection;
shared_ptr <VolumePassword> ArgPassword;
bool ArgQuick;
FilesystemPath ArgRandomSourcePath;
uint64 ArgSize;
shared_ptr <VolumePath> ArgVolumePath;
VolumeInfoList ArgVolumes;
VolumeType::Enum ArgVolumeType;
bool StartBackgroundTask;
UserPreferences Preferences;
protected:
void CheckCommandSingle () const;
shared_ptr <KeyfileList> ToKeyfileList (const wxString &arg) const;
VolumeInfoList GetMountedVolumes (const wxString &filter) const;
private:
CommandLineInterface (const CommandLineInterface &);
CommandLineInterface &operator= (const CommandLineInterface &);
};
extern auto_ptr <CommandLineInterface> CmdLine;
}
#endif // TC_HEADER_Main_CommandInterface

View File

@@ -0,0 +1,274 @@
/*
Copyright (c) 2008-2009 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"
#include <wx/stackwalk.h>
#include "Main.h"
#include "Application.h"
#include "UserInterface.h"
#include "GraphicUserInterface.h"
#include "Volume/Crc32.h"
#ifdef TC_UNIX
#include <signal.h>
#endif
#ifdef TC_MACOSX
# ifdef __ppc__
# include <ppc/ucontext.h>
# else
# include <i386/ucontext.h>
# endif
#elif defined (TC_BSD)
# include <ucontext.h>
#endif
#include "FatalErrorHandler.h"
namespace TrueCrypt
{
static terminate_handler DefaultTerminateHandler;
struct FatalErrorReport
{
bool UnhandledException;
};
#ifdef TC_UNIX
static void OnFatalProgramErrorSignal (int, siginfo_t *signalInfo, void *contextArg)
{
TC_UNUSED_VAR ucontext_t *context = (ucontext_t *) contextArg;
uint64 faultingInstructionAddress = 0;
#ifdef TC_LINUX
# ifdef REG_EIP
faultingInstructionAddress = context->uc_mcontext.gregs[REG_EIP];
# elif defined (REG_RIP)
faultingInstructionAddress = context->uc_mcontext.gregs[REG_RIP];
# endif
#elif defined (TC_MACOSX)
# ifdef __ppc__
faultingInstructionAddress = context->uc_mcontext->ss.srr0;
# elif defined (__x86_64__)
faultingInstructionAddress = context->uc_mcontext->ss.rip;
# else
faultingInstructionAddress = context->uc_mcontext->ss.eip;
# endif
#endif
wstringstream vars;
vars << L"cpus=" << wxThread::GetCPUCount();
vars << L"&cksum=" << hex << FatalErrorHandler::GetAppChecksum() << dec;
vars << L"&err=" << signalInfo->si_signo;
vars << L"&addr=" << hex << faultingInstructionAddress << dec;
vars << FatalErrorHandler::GetCallStack (16);
wxString url = Gui->GetHomepageLinkURL (L"err-report", true, vars.str());
url.Replace (L"=0x", L"=");
url.Replace (L"=0X0x", L"=0x");
url.Replace (L"=0X", L"=0x");
wxString msg = L"A critical error has occurred and TrueCrypt must be terminated. If this is caused by a bug in TrueCrypt, we would like to fix it. To help us, you can send us an automatically generated error report containing the following items:\n\n- Program version\n- Operating system version\n- Hardware architecture\n- Checksum of TrueCrypt executable\n- Error category\n- Error address\n";
#if wxUSE_STACKWALKER == 1
msg += L"- TrueCrypt call stack\n";
#endif
msg += L"\nIf you select 'Yes', the following URL (which contains the entire error report) will be opened in your default Internet browser.\n\n";
#ifdef __WXGTK__
wxString fUrl = url;
fUrl.Replace (L"&st", L" &st");
msg += fUrl;
#else
msg += url;
#endif
msg += L"\n\nDo you want to send us the error report?";
if (Gui->AskYesNo (msg, true))
wxLaunchDefaultBrowser (url, wxBROWSER_NEW_WINDOW);
_exit (1);
}
#endif // TC_UNIX
void FatalErrorHandler::Deregister()
{
#ifdef TC_UNIX
signal (SIGILL, SIG_DFL);
signal (SIGFPE, SIG_DFL);
signal (SIGSEGV, SIG_DFL);
signal (SIGBUS, SIG_DFL);
signal (SIGSYS, SIG_DFL);
#endif
#ifndef TC_WINDOWS
std::set_terminate (DefaultTerminateHandler);
#endif
}
uint32 FatalErrorHandler::GetAppChecksum ()
{
uint32 checkSum = 0;
try
{
File executable;
executable.Open (Application::GetExecutablePath());
Buffer executableData (executable.Length());
executable.ReadCompleteBuffer (executableData);
checkSum = Crc32::ProcessBuffer (executableData);
}
catch (...) { }
return checkSum;
}
wstring FatalErrorHandler::GetCallStack (int depth)
{
#if wxUSE_STACKWALKER == 1
class StackWalker : public wxStackWalker
{
public:
StackWalker () : FrameCount (0) { }
void OnStackFrame (const wxStackFrame &frame)
{
if (FrameCount >= 32)
return;
StackVars << L"&st" << FrameCount++ << L"=";
wxString functionName = frame.GetName();
if (!functionName.empty() && !frame.GetModule().empty())
{
int p = functionName.Find (L"(");
if (p != wxNOT_FOUND)
functionName = functionName.Mid (0, p);
for (size_t i = 0; i < functionName.size(); ++i)
{
if (!isalnum (functionName[i]))
functionName[i] = L'_';
}
while (functionName.Replace (L"__", L"_"));
StackVars << wstring (functionName);
}
else
StackVars << "0X" << hex << frame.GetAddress() << dec;
}
int FrameCount;
wstringstream StackVars;
};
StackWalker stackWalker;
stackWalker.Walk (2);
return stackWalker.StackVars.str();
#else // wxUSE_STACKWALKER
return wstring();
#endif // wxUSE_STACKWALKER
}
void FatalErrorHandler::OnTerminate ()
{
try
{
throw;
}
catch (UserAbort&)
{
}
catch (Exception &e)
{
wxString vars;
wxString exName = StringConverter::ToWide (StringConverter::GetTypeName (typeid (e)));
if (exName.find (L"TrueCrypt::") != string::npos)
exName = exName.Mid (11);
wxString exPos = StringConverter::ToWide (e.what());
if (exPos.find (L"TrueCrypt::") != string::npos)
exPos = exPos.Mid (11);
vars << L"cpus=" << wxThread::GetCPUCount();
vars << wxString::Format (L"&cksum=%x", GetAppChecksum());
vars << L"&exception=" << exName;
vars << L"&exlocation=" << exPos;
vars << FatalErrorHandler::GetCallStack (16);
vars.Replace (L"::", L".");
vars.Replace (L":", L".");
wxString url = Gui->GetHomepageLinkURL (L"err-report", true, vars);
url.Replace (L"=0x", L"=");
url.Replace (L"=0X0x", L"=0x");
url.Replace (L"=0X", L"=0x");
wxString msg = L"An unhandled exception has occurred and TrueCrypt must be terminated. If this is caused by a bug in TrueCrypt, we would like to fix it. To help us, you can send us an automatically generated error report containing the following items:\n\n- Program version\n- Operating system version\n- Hardware architecture\n- Checksum of TrueCrypt executable\n- Error description\n- Error location\n";
#if wxUSE_STACKWALKER == 1
msg += L"- TrueCrypt call stack\n";
#endif
msg += L"\nIf you select 'Yes', the following URL (which contains the entire error report) will be opened in your default Internet browser.\n\n";
#ifdef __WXGTK__
wxString fUrl = url;
fUrl.Replace (L"&st", L" &st");
msg += fUrl;
#else
msg += url;
#endif
msg += L"\n\nDo you want to send us the error report?";
if (Gui->AskYesNo (msg, true))
wxLaunchDefaultBrowser (url, wxBROWSER_NEW_WINDOW);
}
catch (exception &e)
{
Gui->ShowError (e);
}
catch (...)
{
Gui->ShowError (_("Unknown exception occurred."));
}
_exit (1);
}
void FatalErrorHandler::Register ()
{
#ifndef TC_WINDOWS
// OnUnhandledException() seems to be called only on Windows
DefaultTerminateHandler = std::set_terminate (OnTerminate);
#endif
#ifdef TC_UNIX
struct sigaction action;
Memory::Zero (&action, sizeof (action));
action.sa_flags = SA_SIGINFO;
action.sa_sigaction = OnFatalProgramErrorSignal;
throw_sys_if (sigaction (SIGILL, &action, nullptr) == -1);
throw_sys_if (sigaction (SIGFPE, &action, nullptr) == -1);
throw_sys_if (sigaction (SIGSEGV, &action, nullptr) == -1);
throw_sys_if (sigaction (SIGBUS, &action, nullptr) == -1);
throw_sys_if (sigaction (SIGSYS, &action, nullptr) == -1);
#endif
}
}

View File

@@ -0,0 +1,33 @@
/*
Copyright (c) 2008-2009 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.
*/
#ifndef TC_HEADER_Main_FatalErrorHandler
#define TC_HEADER_Main_FatalErrorHandler
#include "System.h"
namespace TrueCrypt
{
class FatalErrorHandler
{
public:
static void Deregister();
static uint32 GetAppChecksum ();
static wstring GetCallStack (int depth);
static void Register();
protected:
static void OnSignal (int signal);
static void OnTerminate ();
private:
FatalErrorHandler ();
};
}
#endif // TC_HEADER_Main_FatalErrorHandler

View File

@@ -0,0 +1,94 @@
/*
Copyright (c) 2008-2009 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"
#include "Application.h"
#include "FavoriteVolume.h"
#include "Xml.h"
namespace TrueCrypt
{
FavoriteVolumeList FavoriteVolume::LoadList ()
{
FavoriteVolumeList favorites;
FilePath path = Application::GetConfigFilePath (GetFileName());
if (path.IsFile())
{
foreach (XmlNode node, XmlParser (path).GetNodes (L"volume"))
{
VolumeSlotNumber slotNumber = 0;
wstring attr = wstring (node.Attributes[L"slotnumber"]);
if (!attr.empty())
slotNumber = StringConverter::ToUInt64 (attr);
bool readOnly = false;
attr = wstring (node.Attributes[L"readonly"]);
if (!attr.empty())
readOnly = (StringConverter::ToUInt32 (attr) != 0 ? true : false);
bool system = false;
attr = wstring (node.Attributes[L"system"]);
if (!attr.empty())
system = (StringConverter::ToUInt32 (attr) != 0 ? true : false);
favorites.push_back (shared_ptr <FavoriteVolume> (
new FavoriteVolume ((wstring) node.InnerText, wstring (node.Attributes[L"mountpoint"]), slotNumber, readOnly, system)));
}
}
return favorites;
}
void FavoriteVolume::SaveList (const FavoriteVolumeList &favorites)
{
FilePath favoritesCfgPath = Application::GetConfigFilePath (GetFileName(), true);
if (favorites.empty())
{
if (favoritesCfgPath.IsFile())
favoritesCfgPath.Delete();
}
else
{
XmlNode favoritesXml (L"favorites");
foreach_ref (const FavoriteVolume &favorite, favorites)
{
XmlNode node (L"volume", wstring (favorite.Path));
node.Attributes[L"mountpoint"] = wstring (favorite.MountPoint);
node.Attributes[L"slotnumber"] = StringConverter::FromNumber (favorite.SlotNumber);
node.Attributes[L"readonly"] = StringConverter::FromNumber (favorite.ReadOnly ? 1 : 0);
node.Attributes[L"system"] = StringConverter::FromNumber (favorite.System ? 1 : 0);
favoritesXml.InnerNodes.push_back (node);
}
XmlWriter favoritesWriter (favoritesCfgPath);
favoritesWriter.WriteNode (favoritesXml);
favoritesWriter.Close();
}
}
void FavoriteVolume::ToMountOptions (MountOptions &options) const
{
if (MountPoint.IsEmpty())
{
options.MountPoint.reset();
options.NoFilesystem = true;
}
else
options.MountPoint.reset (new DirectoryPath (MountPoint));
options.Path.reset (new VolumePath (Path));
options.PartitionInSystemEncryptionScope = System;
options.Protection = (ReadOnly ? VolumeProtection::ReadOnly : VolumeProtection::None);
options.SlotNumber = SlotNumber;
}
}

53
src/Main/FavoriteVolume.h Normal file
View File

@@ -0,0 +1,53 @@
/*
Copyright (c) 2008-2009 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.
*/
#ifndef TC_HEADER_Main_FavoriteVolume
#define TC_HEADER_Main_FavoriteVolume
#include "System.h"
#include "Main.h"
namespace TrueCrypt
{
struct FavoriteVolume;
typedef list < shared_ptr <FavoriteVolume> > FavoriteVolumeList;
struct FavoriteVolume
{
public:
FavoriteVolume ()
: ReadOnly (false),
System (false)
{
}
FavoriteVolume (const VolumePath &path, const DirectoryPath &mountPoint, VolumeSlotNumber slotNumber, bool readOnly, bool system)
: MountPoint (mountPoint),
Path (path),
ReadOnly (readOnly),
SlotNumber (slotNumber),
System (system)
{
}
static FavoriteVolumeList LoadList ();
static void SaveList (const FavoriteVolumeList &favorites);
void ToMountOptions (MountOptions &options) const;
DirectoryPath MountPoint;
VolumePath Path;
bool ReadOnly;
VolumeSlotNumber SlotNumber;
bool System;
protected:
static wxString GetFileName () { return L"Favorite Volumes.xml"; }
};
}
#endif // TC_HEADER_Main_FavoriteVolume

View File

@@ -0,0 +1,66 @@
/*
Copyright (c) 2008-2009 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"
#include "Volume/Version.h"
#include "Main/Application.h"
#include "Main/GraphicUserInterface.h"
#include "Main/Resources.h"
#include "AboutDialog.h"
namespace TrueCrypt
{
AboutDialog::AboutDialog (wxWindow* parent) : AboutDialogBase (parent)
{
LogoBitmap->SetBitmap (Resources::GetTextualLogoBitmap());
wxFont versionStaticTextFont = VersionStaticText->GetFont();
versionStaticTextFont.SetWeight (wxFONTWEIGHT_BOLD);
VersionStaticText->SetFont (versionStaticTextFont);
VersionStaticText->SetLabel (Application::GetName() + L" " + StringConverter::ToWide (Version::String()));
CopyrightStaticText->SetLabel (StringConverter::ToWide (TC_STR_RELEASED_BY));
WebsiteHyperlink->SetLabel (L"www.truecrypt.org");
CreditsTextCtrl->SetMinSize (wxSize (
Gui->GetCharWidth (CreditsTextCtrl) * 70,
Gui->GetCharHeight (CreditsTextCtrl) * 6
#ifdef TC_WINDOWS
- 5
#else
- 11
#endif
));
Layout();
Fit();
Center();
CreditsTextCtrl->ChangeValue (
L"Portions of this software are based in part on the works of the following people: "
L"Paul Le Roux, "
L"Bruce Schneier, John Kelsey, Doug Whiting, David Wagner, Chris Hall, Niels Ferguson, "
L"Lars Knudsen, Ross Anderson, Eli Biham, "
L"Joan Daemen, Vincent Rijmen, "
L"Phillip Rogaway, "
L"Hans Dobbertin, Antoon Bosselaers, Bart Preneel, "
L"Paulo Barreto, Brian Gladman, Wei Dai, Peter Gutmann, and many others.\n\n"
L"Portions of this software:\n"
L"Copyright \xA9 2003-2012 TrueCrypt Developers Association. All Rights Reserved.\n"
L"Copyright \xA9 1998-2000 Paul Le Roux. All Rights Reserved.\n"
L"Copyright \xA9 1998-2008 Brian Gladman. All Rights Reserved.\n"
L"\nThis software as a whole:\n"
L"Copyright \xA9 2012 TrueCrypt Developers Association. All rights reserved.\n\n"
L"This software uses wxWidgets library, which is copyright \xA9 1998-2011 Julian Smart, Robert Roebling et al.\n\n"
L"A TrueCrypt Foundation Release");
}
}

View File

@@ -0,0 +1,25 @@
/*
Copyright (c) 2008 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.
*/
#ifndef TC_HEADER_Main_Forms_AboutDialog
#define TC_HEADER_Main_Forms_AboutDialog
#include "Forms.h"
namespace TrueCrypt
{
class AboutDialog : public AboutDialogBase
{
public:
AboutDialog (wxWindow* parent);
void OnWebsiteHyperlinkClick (wxHyperlinkEvent& event) { Gui->OpenHomepageLink (this, L"main"); }
};
}
#endif // TC_HEADER_Main_Forms_AboutDialog

View File

@@ -0,0 +1,157 @@
/*
Copyright (c) 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"
#include "Volume/EncryptionModeXTS.h"
#include "Main/GraphicUserInterface.h"
#include "BenchmarkDialog.h"
namespace TrueCrypt
{
BenchmarkDialog::BenchmarkDialog (wxWindow *parent)
: BenchmarkDialogBase (parent)
{
BenchmarkNoteStaticText->SetLabel (LangString["IDT_BOX_BENCHMARK_INFO"]);
BenchmarkNoteStaticText->Wrap (RightSizer->GetSize().GetWidth());
list <size_t> bufferSizes;
bufferSizes.push_back (1 * BYTES_PER_MB);
bufferSizes.push_back (5 * BYTES_PER_MB);
bufferSizes.push_back (10 * BYTES_PER_MB);
bufferSizes.push_back (50 * BYTES_PER_MB);
bufferSizes.push_back (100 * BYTES_PER_MB);
bufferSizes.push_back (200 * BYTES_PER_MB);
bufferSizes.push_back (500 * BYTES_PER_MB);
bufferSizes.push_back (1 * BYTES_PER_GB);
foreach (size_t size, bufferSizes)
{
BufferSizeChoice->Append (Gui->SizeToString (size), (void *) size);
}
BufferSizeChoice->Select (1);
list <int> colPermilles;
BenchmarkListCtrl->InsertColumn (ColumnAlgorithm, LangString["ALGORITHM"], wxLIST_FORMAT_LEFT, 1);
colPermilles.push_back (322);
BenchmarkListCtrl->InsertColumn (ColumnEncryption, LangString["ENCRYPTION"], wxLIST_FORMAT_RIGHT, 1);
colPermilles.push_back (226);
BenchmarkListCtrl->InsertColumn (ColumnDecryption, LangString["DECRYPTION"], wxLIST_FORMAT_RIGHT, 1);
colPermilles.push_back (226);
BenchmarkListCtrl->InsertColumn (ColumnMean, LangString["MEAN"], wxLIST_FORMAT_RIGHT, 1);
colPermilles.push_back (226);
Gui->SetListCtrlWidth (BenchmarkListCtrl, 62, false);
Gui->SetListCtrlHeight (BenchmarkListCtrl, 14);
Gui->SetListCtrlColumnWidths (BenchmarkListCtrl, colPermilles);
Layout();
Fit();
Center();
}
void BenchmarkDialog::OnBenchmarkButtonClick (wxCommandEvent& event)
{
try
{
list <BenchmarkResult> results;
wxBusyCursor busy;
Buffer buffer ((size_t) Gui->GetSelectedData <size_t> (BufferSizeChoice));
EncryptionAlgorithmList encryptionAlgorithms = EncryptionAlgorithm::GetAvailableAlgorithms();
foreach (shared_ptr <EncryptionAlgorithm> ea, encryptionAlgorithms)
{
if (!ea->IsDeprecated())
{
BenchmarkResult result;
result.AlgorithmName = ea->GetName();
Buffer key (ea->GetKeySize());
ea->SetKey (key);
shared_ptr <EncryptionMode> xts (new EncryptionModeXTS);
xts->SetKey (key);
ea->SetMode (xts);
wxLongLong startTime = wxGetLocalTimeMillis();
// CPU "warm up" (an attempt to prevent skewed results on systems where CPU frequency gradually changes depending on CPU load).
do
{
ea->EncryptSectors (buffer, 0, buffer.Size() / ENCRYPTION_DATA_UNIT_SIZE, ENCRYPTION_DATA_UNIT_SIZE);
}
while (wxGetLocalTimeMillis().GetValue() - startTime.GetValue() < 20);
uint64 size = 0;
uint64 time;
startTime = wxGetLocalTimeMillis();
do
{
ea->EncryptSectors (buffer, 0, buffer.Size() / ENCRYPTION_DATA_UNIT_SIZE, ENCRYPTION_DATA_UNIT_SIZE);
size += buffer.Size();
time = (uint64) (wxGetLocalTimeMillis().GetValue() - startTime.GetValue());
}
while (time < 100);
result.EncryptionSpeed = size * 1000 / time;
startTime = wxGetLocalTimeMillis();
size = 0;
do
{
ea->DecryptSectors (buffer, 0, buffer.Size() / ENCRYPTION_DATA_UNIT_SIZE, ENCRYPTION_DATA_UNIT_SIZE);
size += buffer.Size();
time = (uint64) (wxGetLocalTimeMillis().GetValue() - startTime.GetValue());
}
while (time < 100);
result.DecryptionSpeed = size * 1000 / time;
result.MeanSpeed = (result.EncryptionSpeed + result.DecryptionSpeed) / 2;
bool inserted = false;
for (list <BenchmarkResult>::iterator i = results.begin(); i != results.end(); ++i)
{
if (i->MeanSpeed < result.MeanSpeed)
{
results.insert (i, result);
inserted = true;
break;
}
}
if (!inserted)
results.push_back (result);
}
}
BenchmarkListCtrl->DeleteAllItems();
foreach (const BenchmarkResult &result, results)
{
vector <wstring> fields (BenchmarkListCtrl->GetColumnCount());
fields[ColumnAlgorithm] = result.AlgorithmName;
fields[ColumnEncryption] = Gui->SpeedToString (result.EncryptionSpeed);
fields[ColumnDecryption] = Gui->SpeedToString (result.DecryptionSpeed);
fields[ColumnMean] = Gui->SpeedToString (result.MeanSpeed);
Gui->AppendToListCtrl (BenchmarkListCtrl, fields);
}
}
catch (exception &e)
{
Gui->ShowError (e);
}
}
}

View File

@@ -0,0 +1,43 @@
/*
Copyright (c) 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.
*/
#ifndef TC_HEADER_Main_Forms_BenchmarkDialog
#define TC_HEADER_Main_Forms_BenchmarkDialog
#include "Forms.h"
#include "Main/Main.h"
namespace TrueCrypt
{
class BenchmarkDialog : public BenchmarkDialogBase
{
public:
BenchmarkDialog (wxWindow *parent);
protected:
enum
{
ColumnAlgorithm = 0,
ColumnEncryption,
ColumnDecryption,
ColumnMean
};
struct BenchmarkResult
{
wstring AlgorithmName;
uint64 EncryptionSpeed;
uint64 DecryptionSpeed;
uint64 MeanSpeed;
};
void OnBenchmarkButtonClick (wxCommandEvent& event);
};
}
#endif // TC_HEADER_Main_Forms_BenchmarkDialog

View File

@@ -0,0 +1,195 @@
/*
Copyright (c) 2008-2009 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"
#include "Main/Main.h"
#include "Main/GraphicUserInterface.h"
#include "ChangePasswordDialog.h"
namespace TrueCrypt
{
ChangePasswordDialog::ChangePasswordDialog (wxWindow* parent, shared_ptr <VolumePath> volumePath, Mode::Enum mode, shared_ptr <VolumePassword> password, shared_ptr <KeyfileList> keyfiles, shared_ptr <VolumePassword> newPassword, shared_ptr <KeyfileList> newKeyfiles)
: ChangePasswordDialogBase (parent), DialogMode (mode), Path (volumePath)
{
bool enableNewPassword = false;
bool enableNewKeyfiles = false;
bool enablePkcs5Prf = false;
switch (mode)
{
case Mode::ChangePasswordAndKeyfiles:
enableNewPassword = true;
enableNewKeyfiles = true;
enablePkcs5Prf = true;
SetTitle (_("Change Volume Password and Keyfiles"));
break;
case Mode::ChangeKeyfiles:
enableNewKeyfiles = true;
SetTitle (_("Add/Remove Keyfiles to/from Volume"));
break;
case Mode::RemoveAllKeyfiles:
SetTitle (_("Remove All Keyfiles from Volume"));
break;
case Mode::ChangePkcs5Prf:
enablePkcs5Prf = true;
SetTitle (_("Change Header Key Derivation Algorithm"));
break;
default:
throw ParameterIncorrect (SRC_POS);
}
CurrentPasswordPanel = new VolumePasswordPanel (this, password, keyfiles);
CurrentPasswordPanel->UpdateEvent.Connect (EventConnector <ChangePasswordDialog> (this, &ChangePasswordDialog::OnPasswordPanelUpdate));
CurrentPasswordPanelSizer->Add (CurrentPasswordPanel, 1, wxALL | wxEXPAND);
NewPasswordPanel = new VolumePasswordPanel (this, newPassword, newKeyfiles, false, enableNewPassword, enableNewKeyfiles, enableNewPassword, enablePkcs5Prf);
NewPasswordPanel->UpdateEvent.Connect (EventConnector <ChangePasswordDialog> (this, &ChangePasswordDialog::OnPasswordPanelUpdate));
NewPasswordPanelSizer->Add (NewPasswordPanel, 1, wxALL | wxEXPAND);
if (mode == Mode::RemoveAllKeyfiles)
NewSizer->Show (false);
Layout();
Fit();
Center();
OnPasswordPanelUpdate();
CurrentPasswordPanel->SetFocusToPasswordTextCtrl();
}
ChangePasswordDialog::~ChangePasswordDialog ()
{
CurrentPasswordPanel->UpdateEvent.Disconnect (this);
NewPasswordPanel->UpdateEvent.Disconnect (this);
}
void ChangePasswordDialog::OnOKButtonClick (wxCommandEvent& event)
{
// Avoid a GTK bug
if (!OKButton->IsEnabled())
return;
try
{
shared_ptr <VolumePassword> newPassword;
if (DialogMode == Mode::ChangePasswordAndKeyfiles)
{
newPassword = NewPasswordPanel->GetPassword();
newPassword->CheckPortability();
if (newPassword->Size() > 0 && newPassword->Size() < VolumePassword::WarningSizeThreshold
&& !Gui->AskYesNo (LangString ["PASSWORD_LENGTH_WARNING"], false, true))
{
NewPasswordPanel->SetFocusToPasswordTextCtrl();
return;
}
}
else
newPassword = CurrentPasswordPanel->GetPassword();
shared_ptr <KeyfileList> newKeyfiles;
if (DialogMode == Mode::ChangePasswordAndKeyfiles || DialogMode == Mode::ChangeKeyfiles)
newKeyfiles = NewPasswordPanel->GetKeyfiles();
else if (DialogMode != Mode::RemoveAllKeyfiles)
newKeyfiles = CurrentPasswordPanel->GetKeyfiles();
Gui->UserEnrichRandomPool (this, NewPasswordPanel->GetPkcs5Kdf() ? NewPasswordPanel->GetPkcs5Kdf()->GetHash() : shared_ptr <Hash>());
{
#ifdef TC_UNIX
// Temporarily take ownership of a device if the user is not an administrator
UserId origDeviceOwner ((uid_t) -1);
if (!Core->HasAdminPrivileges() && Path->IsDevice())
{
origDeviceOwner = FilesystemPath (wstring (*Path)).GetOwner();
Core->SetFileOwner (*Path, UserId (getuid()));
}
finally_do_arg2 (FilesystemPath, *Path, UserId, origDeviceOwner,
{
if (finally_arg2.SystemId != (uid_t) -1)
Core->SetFileOwner (finally_arg, finally_arg2);
});
#endif
wxBusyCursor busy;
Core->ChangePassword (Path, Gui->GetPreferences().DefaultMountOptions.PreserveTimestamps,
CurrentPasswordPanel->GetPassword(), CurrentPasswordPanel->GetKeyfiles(),
newPassword, newKeyfiles, NewPasswordPanel->GetPkcs5Kdf());
}
switch (DialogMode)
{
case Mode::ChangePasswordAndKeyfiles:
Gui->ShowInfo ("PASSWORD_CHANGED");
break;
case Mode::ChangeKeyfiles:
case Mode::RemoveAllKeyfiles:
Gui->ShowInfo ("KEYFILE_CHANGED");
break;
case Mode::ChangePkcs5Prf:
Gui->ShowInfo ("PKCS5_PRF_CHANGED");
break;
default:
throw ParameterIncorrect (SRC_POS);
}
EndModal (wxID_OK);
}
catch (UnportablePassword &e)
{
Gui->ShowError (e);
NewPasswordPanel->SetFocusToPasswordTextCtrl();
}
catch (PasswordException &e)
{
Gui->ShowWarning (e);
CurrentPasswordPanel->SetFocusToPasswordTextCtrl();
}
catch (exception &e)
{
Gui->ShowError (e);
}
}
void ChangePasswordDialog::OnPasswordPanelUpdate ()
{
bool ok = true;
bool passwordEmpty = CurrentPasswordPanel->GetPassword()->IsEmpty();
bool keyfilesEmpty = !CurrentPasswordPanel->GetKeyfiles() || CurrentPasswordPanel->GetKeyfiles()->empty();
if (passwordEmpty && keyfilesEmpty)
ok = false;
if (DialogMode == Mode::RemoveAllKeyfiles && (passwordEmpty || keyfilesEmpty))
ok = false;
if (DialogMode == Mode::ChangePasswordAndKeyfiles || DialogMode == Mode::ChangeKeyfiles)
{
bool newKeyfilesEmpty = !NewPasswordPanel->GetKeyfiles() || NewPasswordPanel->GetKeyfiles()->empty();
if (DialogMode == Mode::ChangeKeyfiles
&& ((passwordEmpty && newKeyfilesEmpty) || (keyfilesEmpty && newKeyfilesEmpty)))
ok = false;
if (DialogMode == Mode::ChangePasswordAndKeyfiles
&& ((NewPasswordPanel->GetPassword()->IsEmpty() && newKeyfilesEmpty) || !NewPasswordPanel->PasswordsMatch()))
ok = false;
}
OKButton->Enable (ok);
}
}

View File

@@ -0,0 +1,48 @@
/*
Copyright (c) 2008 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.
*/
#ifndef TC_HEADER_Main_Forms_ChangePasswordDialog
#define TC_HEADER_Main_Forms_ChangePasswordDialog
#include "Forms.h"
#include "Main/Main.h"
#include "VolumePasswordPanel.h"
namespace TrueCrypt
{
class ChangePasswordDialog : public ChangePasswordDialogBase
{
public:
struct Mode
{
enum Enum
{
ChangePasswordAndKeyfiles,
ChangeKeyfiles,
RemoveAllKeyfiles,
ChangePkcs5Prf
};
};
ChangePasswordDialog (wxWindow* parent, shared_ptr <VolumePath> volumePath, Mode::Enum mode = Mode::ChangePasswordAndKeyfiles, shared_ptr <VolumePassword> password = shared_ptr <VolumePassword> (), shared_ptr <KeyfileList> keyfiles = shared_ptr <KeyfileList> (), shared_ptr <VolumePassword> newPassword = shared_ptr <VolumePassword> (), shared_ptr <KeyfileList> newKeyfiles = shared_ptr <KeyfileList> ());
virtual ~ChangePasswordDialog ();
protected:
void OnOKButtonClick (wxCommandEvent& event);
void OnPasswordPanelUpdate ();
void OnPasswordPanelUpdate (EventArgs &args) { OnPasswordPanelUpdate(); }
Mode::Enum DialogMode;
VolumePasswordPanel *CurrentPasswordPanel;
VolumePasswordPanel *NewPasswordPanel;
shared_ptr <VolumePath> Path;
};
}
#endif // TC_HEADER_Main_Forms_ChangePasswordDialog

View File

@@ -0,0 +1,120 @@
/*
Copyright (c) 2008 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"
#include "Main/GraphicUserInterface.h"
#include "Main/Resources.h"
#include "DeviceSelectionDialog.h"
namespace TrueCrypt
{
DeviceSelectionDialog::DeviceSelectionDialog (wxWindow* parent)
: DeviceSelectionDialogBase (parent)
{
wxBusyCursor busy;
list <int> colPermilles;
DeviceListCtrl->InsertColumn (ColumnDevice, LangString["DEVICE"], wxLIST_FORMAT_LEFT, 1);
colPermilles.push_back (447);
#ifdef TC_WINDOWS
DeviceListCtrl->InsertColumn (ColumnDrive, LangString["DRIVE"], wxLIST_FORMAT_LEFT, 1);
colPermilles.push_back (91);
#endif
DeviceListCtrl->InsertColumn (ColumnSize, LangString["SIZE"], wxLIST_FORMAT_RIGHT, 1);
colPermilles.push_back (153);
#ifdef TC_WINDOWS
DeviceListCtrl->InsertColumn (ColumnName, LangString["LABEL"], wxLIST_FORMAT_LEFT, 1);
colPermilles.push_back (307);
#else
DeviceListCtrl->InsertColumn (ColumnMountPoint, LangString["MOUNT_POINT"], wxLIST_FORMAT_LEFT, 1);
colPermilles.push_back (396);
#endif
wxImageList *imageList = new wxImageList (16, 12, true);
imageList->Add (Resources::GetDriveIconBitmap(), Resources::GetDriveIconMaskBitmap());
DeviceListCtrl->AssignImageList (imageList, wxIMAGE_LIST_SMALL);
DeviceList = Core->GetHostDevices();
foreach_ref (HostDevice &device, DeviceList)
{
if (device.Size == 0)
continue;
vector <wstring> fields (DeviceListCtrl->GetColumnCount());
if (DeviceListCtrl->GetItemCount() > 0)
Gui->AppendToListCtrl (DeviceListCtrl, fields);
#ifdef TC_WINDOWS
fields[ColumnDevice] = StringFormatter (L"{0} {1}:", _("Harddisk"), device.SystemNumber);
fields[ColumnDrive] = device.MountPoint;
fields[ColumnName] = device.Name;
#else
fields[ColumnDevice] = wstring (device.Path) + L":";
fields[ColumnMountPoint] = device.MountPoint;
#endif
fields[ColumnSize] = Gui->SizeToString (device.Size);
Gui->AppendToListCtrl (DeviceListCtrl, fields, 0, &device);
foreach_ref (HostDevice &partition, device.Partitions)
{
fields[ColumnDevice] =
#ifndef TC_WINDOWS
wstring (L" ") +
#endif
wstring (partition.Path);
#ifdef TC_WINDOWS
fields[ColumnDrive] = partition.MountPoint;
fields[ColumnName] = partition.Name;
#else
fields[ColumnMountPoint] = partition.MountPoint;
#endif
fields[ColumnSize] = Gui->SizeToString (partition.Size);
Gui->AppendToListCtrl (DeviceListCtrl, fields, -1, &partition);
}
}
Gui->SetListCtrlWidth (DeviceListCtrl, 73);
Gui->SetListCtrlHeight (DeviceListCtrl, 16);
Gui->SetListCtrlColumnWidths (DeviceListCtrl, colPermilles);
Fit();
Layout();
Center();
StdButtonsOK->Disable();
StdButtonsOK->SetDefault();
}
void DeviceSelectionDialog::OnListItemActivated (wxListEvent& event)
{
if (StdButtonsOK->IsEnabled())
EndModal (wxID_OK);
}
void DeviceSelectionDialog::OnListItemDeselected (wxListEvent& event)
{
if (DeviceListCtrl->GetSelectedItemCount() == 0)
StdButtonsOK->Disable();
}
void DeviceSelectionDialog::OnListItemSelected (wxListEvent& event)
{
HostDevice *device = (HostDevice *) (event.GetItem().GetData());
if (device)
{
SelectedDevice = *device;
StdButtonsOK->Enable();
}
else
StdButtonsOK->Disable();
}
}

View File

@@ -0,0 +1,46 @@
/*
Copyright (c) 2008 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.
*/
#ifndef TC_HEADER_Main_Forms_DeviceSelectionDialog
#define TC_HEADER_Main_Forms_DeviceSelectionDialog
#include "Forms.h"
#include "Main/Main.h"
namespace TrueCrypt
{
class DeviceSelectionDialog : public DeviceSelectionDialogBase
{
public:
DeviceSelectionDialog (wxWindow* parent);
HostDeviceList DeviceList;
HostDevice SelectedDevice;
protected:
enum
{
ColumnDevice = 0,
#ifdef TC_WINDOWS
ColumnDrive,
#endif
ColumnSize,
#ifdef TC_WINDOWS
ColumnName
#else
ColumnMountPoint
#endif
};
void OnListItemActivated (wxListEvent& event);
void OnListItemDeselected (wxListEvent& event);
void OnListItemSelected (wxListEvent& event);
};
}
#endif // TC_HEADER_Main_Forms_DeviceSelectionDialog

View File

@@ -0,0 +1,137 @@
/*
Copyright (c) 2008 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"
#include "Volume/EncryptionTest.h"
#include "Volume/Hash.h"
#include "Main/GraphicUserInterface.h"
#include "BenchmarkDialog.h"
#include "EncryptionOptionsWizardPage.h"
#include "EncryptionTestDialog.h"
namespace TrueCrypt
{
EncryptionOptionsWizardPage::EncryptionOptionsWizardPage (wxPanel* parent)
: EncryptionOptionsWizardPageBase (parent)
{
EncryptionAlgorithms = EncryptionAlgorithm::GetAvailableAlgorithms();
foreach (shared_ptr <EncryptionAlgorithm> ea, EncryptionAlgorithms)
{
if (!ea->IsDeprecated())
EncryptionAlgorithmChoice->Append (ea->GetName(), ea.get());
}
EncryptionAlgorithmChoice->Select (0);
Hashes = Hash::GetAvailableAlgorithms();
foreach (shared_ptr <Hash> hash, Hashes)
{
if (!hash->IsDeprecated())
HashChoice->Append (hash->GetName(), hash.get());
}
HashChoice->Select (0);
OnEncryptionAlgorithmSelected();
}
shared_ptr <EncryptionAlgorithm> EncryptionOptionsWizardPage::GetEncryptionAlgorithm () const
{
return Gui->GetSelectedData <EncryptionAlgorithm> (EncryptionAlgorithmChoice)->GetNew();
}
shared_ptr <Hash> EncryptionOptionsWizardPage::GetHash () const
{
return Gui->GetSelectedData <Hash> (HashChoice)->GetNew();
}
void EncryptionOptionsWizardPage::OnBenchmarkButtonClick (wxCommandEvent& event)
{
BenchmarkDialog dialog (this);
dialog.ShowModal();
}
void EncryptionOptionsWizardPage::OnEncryptionAlgorithmSelected ()
{
FreezeScope freeze (this);
shared_ptr <EncryptionAlgorithm> ea = GetEncryptionAlgorithm();
CipherList ciphers = ea->GetCiphers();
if (ciphers.size() == 1)
{
EncryptionAlgorithmHyperlink->SetLabel (StringFormatter (LangString["MORE_INFO_ABOUT"], ea->GetName()));
if (typeid (*ea) == typeid (AES))
EncryptionAlgorithmStaticText->SetLabel (LangString["AES_HELP"]);
else if (typeid (*ea) == typeid (Serpent))
EncryptionAlgorithmStaticText->SetLabel (LangString["SERPENT_HELP"]);
else if (typeid (*ea) == typeid (Twofish))
EncryptionAlgorithmStaticText->SetLabel (LangString["TWOFISH_HELP"]);
else
EncryptionAlgorithmStaticText->SetLabel (L"");
}
else
{
if (ciphers.size() == 2)
{
EncryptionAlgorithmStaticText->SetLabel (StringFormatter (LangString["TWO_LAYER_CASCADE_HELP"],
ciphers[0]->GetName(), (int) ciphers[0]->GetKeySize() * 8,
ciphers[1]->GetName(), (int) ciphers[1]->GetKeySize() * 8));
}
else if (ciphers.size() == 3)
{
EncryptionAlgorithmStaticText->SetLabel (StringFormatter (LangString["THREE_LAYER_CASCADE_HELP"],
ciphers[0]->GetName(), (int) ciphers[0]->GetKeySize() * 8,
ciphers[1]->GetName(), (int) ciphers[1]->GetKeySize() * 8,
ciphers[2]->GetName(), (int) ciphers[2]->GetKeySize() * 8));
}
else
EncryptionAlgorithmStaticText->SetLabel (L"");
EncryptionAlgorithmHyperlink->SetLabel (_("More information"));
}
Layout();
}
void EncryptionOptionsWizardPage::OnEncryptionAlgorithmHyperlinkClick (wxHyperlinkEvent& event)
{
if (GetEncryptionAlgorithm()->GetCiphers().size() == 1)
Gui->OpenHomepageLink (this, wxString (GetEncryptionAlgorithm()->GetName()).Lower());
else
Gui->OpenHomepageLink (this, L"cascades");
}
void EncryptionOptionsWizardPage::OnHashHyperlinkClick (wxHyperlinkEvent& event)
{
Gui->OpenHomepageLink (this, L"hashalgorithms");
}
void EncryptionOptionsWizardPage::OnTestButtonClick (wxCommandEvent& event)
{
EncryptionTestDialog dialog (this);
dialog.ShowModal();
}
void EncryptionOptionsWizardPage::SetEncryptionAlgorithm (shared_ptr <EncryptionAlgorithm> algorithm)
{
if (algorithm)
{
EncryptionAlgorithmChoice->SetStringSelection (algorithm->GetName());
OnEncryptionAlgorithmSelected ();
}
}
void EncryptionOptionsWizardPage::SetHash (shared_ptr <Hash> hash)
{
if (hash)
HashChoice->SetStringSelection (hash->GetName());
}
}

View File

@@ -0,0 +1,41 @@
/*
Copyright (c) 2008 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.
*/
#ifndef TC_HEADER_Main_Forms_EncryptionOptionsWizardPage
#define TC_HEADER_Main_Forms_EncryptionOptionsWizardPage
#include "Forms.h"
namespace TrueCrypt
{
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

View File

@@ -0,0 +1,227 @@
/*
Copyright (c) 2008 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"
#include "Volume/EncryptionModeXTS.h"
#include "Volume/EncryptionTest.h"
#include "Main/GraphicUserInterface.h"
#include "EncryptionTestDialog.h"
namespace TrueCrypt
{
EncryptionTestDialog::EncryptionTestDialog (wxWindow* parent)
: EncryptionTestDialogBase (parent)
{
EncryptionAlgorithms = EncryptionAlgorithm::GetAvailableAlgorithms();
foreach (shared_ptr <EncryptionAlgorithm> ea, EncryptionAlgorithms)
{
if (!ea->IsDeprecated())
EncryptionAlgorithmChoice->Append (ea->GetName(), ea.get());
}
EncryptionAlgorithmChoice->Select (0);
Reset();
Fit();
Layout();
Center();
}
void EncryptionTestDialog::EncryptOrDecrypt (bool encrypt)
{
try
{
bool xts = XtsModeCheckBox->IsChecked();
shared_ptr <EncryptionAlgorithm> ea = GetSelectedEncryptionAlgorithm();
Buffer key;
GetTextCtrlData (KeyTextCtrl, key);
if (key.Size() != ea->GetKeySize())
throw_err (LangString["TEST_KEY_SIZE"]);
ea->SetKey (key);
Buffer data;
GetTextCtrlData (encrypt ? PlainTextTextCtrl : CipherTextTextCtrl, data);
if (data.Size() != ea->GetMaxBlockSize())
throw_err (LangString[encrypt ? "TEST_PLAINTEXT_SIZE" : "TEST_CIPHERTEXT_SIZE"]);
if (xts)
{
Buffer secondaryKey;
GetTextCtrlData (SecondaryKeyTextCtrl, secondaryKey);
if (secondaryKey.Size() != ea->GetKeySize())
throw_err (LangString["TEST_INCORRECT_SECONDARY_KEY_SIZE"]);
uint64 dataUnitNumber;
size_t blockNumber;
try
{
dataUnitNumber = StringConverter::ToUInt64 (wstring (DataUnitNumberTextCtrl->GetValue()));
}
catch (...)
{
DataUnitNumberTextCtrl->SetFocus();
throw StringConversionFailed (SRC_POS);
}
try
{
blockNumber = StringConverter::ToUInt32 (wstring (BlockNumberTextCtrl->GetValue()));
if (blockNumber > 31)
{
blockNumber = 31;
BlockNumberTextCtrl->SetValue (L"31");
}
}
catch (...)
{
BlockNumberTextCtrl->SetFocus();
throw StringConversionFailed (SRC_POS);
}
shared_ptr <EncryptionMode> xts (new EncryptionModeXTS);
xts->SetKey (secondaryKey);
ea->SetMode (xts);
Buffer sector (ENCRYPTION_DATA_UNIT_SIZE);
BufferPtr block = sector.GetRange (blockNumber * ea->GetMaxBlockSize(), ea->GetMaxBlockSize());
block.CopyFrom (data);
if (encrypt)
ea->EncryptSectors (sector, dataUnitNumber, 1, sector.Size());
else
ea->DecryptSectors (sector, dataUnitNumber, 1, sector.Size());
data.CopyFrom (block);
}
else
{
if (encrypt)
ea->GetCiphers().front()->EncryptBlock (data);
else
ea->GetCiphers().front()->DecryptBlock (data);
}
SetTextCtrlData (encrypt ? CipherTextTextCtrl : PlainTextTextCtrl, data);
}
catch (exception &e)
{
Gui->ShowError (e);
}
}
shared_ptr <EncryptionAlgorithm> EncryptionTestDialog::GetSelectedEncryptionAlgorithm () const
{
return Gui->GetSelectedData <EncryptionAlgorithm> (EncryptionAlgorithmChoice)->GetNew();
}
void EncryptionTestDialog::GetTextCtrlData (wxTextCtrl *textCtrl, Buffer &buffer) const
{
vector <byte> data;
string dataStr = StringConverter::ToSingle (wstring (textCtrl->GetValue()));
for (size_t i = 0; i < dataStr.size() / 2; ++i)
{
unsigned int dataByte;
if (sscanf (dataStr.substr (i * 2, 2).c_str(), "%x", &dataByte) != 1)
{
textCtrl->SetFocus();
throw StringConversionFailed (SRC_POS);
}
data.push_back ((byte) dataByte);
}
if (data.empty())
return;
buffer.CopyFrom (ConstBufferPtr (&data.front(), data.size()));
}
void EncryptionTestDialog::OnAutoTestAllButtonClick (wxCommandEvent& event)
{
try
{
{
wxBusyCursor busy;
EncryptionTest::TestAll();
}
Gui->ShowInfo ("TESTS_PASSED");
}
catch (Exception &e)
{
Gui->ShowError (e);
Gui->ShowError ("TESTS_FAILED");
}
}
void EncryptionTestDialog::OnEncryptionAlgorithmSelected ()
{
shared_ptr <EncryptionAlgorithm> ea = GetSelectedEncryptionAlgorithm();
KeySizeStaticText->SetLabel (StringFormatter (L"{0} {1}", (uint32) ea->GetKeySize() * 8, LangString["BITS"]));
Buffer key (ea->GetKeySize());
key.Zero();
SetTextCtrlData (KeyTextCtrl, key);
SetTextCtrlData (SecondaryKeyTextCtrl, key);
Buffer block (ea->GetMaxBlockSize());
block.Zero();
SetTextCtrlData (PlainTextTextCtrl, block);
SetTextCtrlData (CipherTextTextCtrl, block);
if (ea->GetCiphers().size() > 1)
{
XtsModeCheckBox->Disable();
XtsModeCheckBox->SetValue (true);
SecondaryKeyTextCtrl->Enable (true);
DataUnitNumberTextCtrl->Enable (true);
BlockNumberTextCtrl->Enable (true);
}
else
XtsModeCheckBox->Enable();
}
void EncryptionTestDialog::OnXtsModeCheckBoxClick (wxCommandEvent& event)
{
bool enabled = event.IsChecked();
SecondaryKeyTextCtrl->Enable (enabled);
DataUnitNumberTextCtrl->Enable (enabled);
BlockNumberTextCtrl->Enable (enabled);
}
void EncryptionTestDialog::SetTextCtrlData (wxTextCtrl *textCtrl, const BufferPtr &data)
{
wstring str;
for (size_t i = 0; i < data.Size(); i++)
{
char strBuf[3];
sprintf (strBuf, "%02x", (int) data[i]);
str += StringConverter::ToWide (strBuf);
}
textCtrl->SetValue (str);
}
void EncryptionTestDialog::Reset ()
{
OnEncryptionAlgorithmSelected();
DataUnitNumberTextCtrl->SetValue (L"0");
BlockNumberTextCtrl->SetValue (L"0");
}
}

View File

@@ -0,0 +1,40 @@
/*
Copyright (c) 2008 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.
*/
#ifndef TC_HEADER_Main_Forms_EncryptionTestDialog
#define TC_HEADER_Main_Forms_EncryptionTestDialog
#include "Forms.h"
#include "Main/Main.h"
namespace TrueCrypt
{
class EncryptionTestDialog : public EncryptionTestDialogBase
{
public:
EncryptionTestDialog (wxWindow* parent);
protected:
void EncryptOrDecrypt (bool encrypt);
shared_ptr <EncryptionAlgorithm> GetSelectedEncryptionAlgorithm () const;
void GetTextCtrlData (wxTextCtrl *textCtrl, Buffer &buffer) const;
void OnAutoTestAllButtonClick (wxCommandEvent& event);
void OnDecryptButtonClick (wxCommandEvent& event) { EncryptOrDecrypt (false); }
void OnEncryptButtonClick (wxCommandEvent& event) { EncryptOrDecrypt (true); }
void OnEncryptionAlgorithmSelected ();
void OnEncryptionAlgorithmSelected (wxCommandEvent& event) { OnEncryptionAlgorithmSelected(); }
void OnResetButtonClick (wxCommandEvent& event) { Reset(); }
void OnXtsModeCheckBoxClick (wxCommandEvent& event);
void SetTextCtrlData (wxTextCtrl *textCtrl, const BufferPtr &data);
void Reset ();
EncryptionAlgorithmList EncryptionAlgorithms;
};
}
#endif // TC_HEADER_Main_Forms_EncryptionTestDialog

View File

@@ -0,0 +1,118 @@
/*
Copyright (c) 2008 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"
#include "Main/GraphicUserInterface.h"
#include "FavoriteVolumesDialog.h"
namespace TrueCrypt
{
FavoriteVolumesDialog::FavoriteVolumesDialog (wxWindow* parent, const FavoriteVolumeList &favorites, size_t newItemCount)
: FavoriteVolumesDialogBase (parent), Favorites (favorites)
{
list <int> colPermilles;
FavoritesListCtrl->InsertColumn (ColumnVolumePath, LangString["VOLUME"], wxLIST_FORMAT_LEFT, 1);
colPermilles.push_back (500);
FavoritesListCtrl->InsertColumn (ColumnMountPoint, LangString["MOUNT_POINT"], wxLIST_FORMAT_LEFT, 1);
colPermilles.push_back (500);
FavoritesListCtrl->SetMinSize (wxSize (400, -1));
Gui->SetListCtrlHeight (FavoritesListCtrl, 15);
Gui->SetListCtrlColumnWidths (FavoritesListCtrl, colPermilles);
Layout();
Fit();
Center();
#ifdef TC_MACOSX
// wxMac cannot insert items to wxListCtrl due to a bug
MoveUpButton->Show (false);
MoveDownButton->Show (false);
#endif
vector <wstring> fields (FavoritesListCtrl->GetColumnCount());
size_t itemCount = 0;
foreach (shared_ptr <FavoriteVolume> favorite, Favorites)
{
fields[ColumnVolumePath] = favorite->Path;
fields[ColumnMountPoint] = favorite->MountPoint;
Gui->AppendToListCtrl (FavoritesListCtrl, fields, -1, favorite.get());
if (++itemCount > Favorites.size() - newItemCount)
{
FavoritesListCtrl->SetItemState (itemCount - 1, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED);
FavoritesListCtrl->EnsureVisible (itemCount - 1);
}
}
UpdateButtons();
FavoritesListCtrl->SetFocus();
}
void FavoriteVolumesDialog::OnMoveDownButtonClick (wxCommandEvent& event)
{
FreezeScope freeze (this);
foreach_reverse (long itemIndex, Gui->GetListCtrlSelectedItems (FavoritesListCtrl))
{
if (itemIndex >= FavoritesListCtrl->GetItemCount() - 1)
break;
Gui->MoveListCtrlItem (FavoritesListCtrl, itemIndex, itemIndex + 1);
}
UpdateButtons();
}
void FavoriteVolumesDialog::OnMoveUpButtonClick (wxCommandEvent& event)
{
FreezeScope freeze (this);
foreach (long itemIndex, Gui->GetListCtrlSelectedItems (FavoritesListCtrl))
{
if (itemIndex == 0)
break;
Gui->MoveListCtrlItem (FavoritesListCtrl, itemIndex, itemIndex - 1);
}
UpdateButtons();
}
void FavoriteVolumesDialog::OnOKButtonClick (wxCommandEvent& event)
{
FavoriteVolumeList newFavorites;
for (long i = 0; i < FavoritesListCtrl->GetItemCount(); i++)
{
newFavorites.push_back (make_shared <FavoriteVolume> (
*reinterpret_cast <FavoriteVolume *> (FavoritesListCtrl->GetItemData (i))));
}
Favorites = newFavorites;
EndModal (wxID_OK);
}
void FavoriteVolumesDialog::OnRemoveAllButtonClick (wxCommandEvent& event)
{
FavoritesListCtrl->DeleteAllItems();
UpdateButtons();
}
void FavoriteVolumesDialog::OnRemoveButtonClick (wxCommandEvent& event)
{
long offset = 0;
foreach (long item, Gui->GetListCtrlSelectedItems (FavoritesListCtrl))
FavoritesListCtrl->DeleteItem (item - offset++);
}
void FavoriteVolumesDialog::UpdateButtons ()
{
bool selected = FavoritesListCtrl->GetSelectedItemCount() > 0;
MoveDownButton->Enable (selected);
MoveUpButton->Enable (selected);
RemoveAllButton->Enable (FavoritesListCtrl->GetItemCount() > 0);
RemoveButton->Enable (selected);
}
}

View File

@@ -0,0 +1,45 @@
/*
Copyright (c) 2008 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.
*/
#ifndef TC_HEADER_Main_Forms_FavoriteVolumesDialog
#define TC_HEADER_Main_Forms_FavoriteVolumesDialog
#include "Forms.h"
#include "Main/Main.h"
#include "Main/FavoriteVolume.h"
namespace TrueCrypt
{
class FavoriteVolumesDialog : public FavoriteVolumesDialogBase
{
public:
FavoriteVolumesDialog (wxWindow* parent, const FavoriteVolumeList &favorites, size_t newItemCount = 0);
FavoriteVolumeList GetFavorites () const { return Favorites; }
protected:
void OnListItemDeselected (wxListEvent& event) { UpdateButtons (); }
void OnListItemSelected (wxListEvent& event) { UpdateButtons (); }
void OnMoveUpButtonClick (wxCommandEvent& event);
void OnMoveDownButtonClick (wxCommandEvent& event);
void OnOKButtonClick (wxCommandEvent& event);
void OnRemoveAllButtonClick (wxCommandEvent& event);
void OnRemoveButtonClick (wxCommandEvent& event);
void UpdateButtons ();
enum
{
ColumnVolumePath = 0,
ColumnMountPoint
};
FavoriteVolumeList Favorites;
};
}
#endif // TC_HEADER_Main_Forms_FavoriteVolumesDialog

3062
src/Main/Forms/Forms.cpp Normal file

File diff suppressed because it is too large Load Diff

1023
src/Main/Forms/Forms.h Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,33 @@
/*
Copyright (c) 2008 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"
#include "InfoWizardPage.h"
namespace TrueCrypt
{
InfoWizardPage::InfoWizardPage (wxPanel *parent, const wxString &actionButtonText, shared_ptr <Functor> actionFunctor)
: InfoWizardPageBase (parent)
{
if (!actionButtonText.empty())
{
wxButton *actionButton = new wxButton (this, wxID_ANY, actionButtonText);
ActionFunctor = actionFunctor;
actionButton->Connect (wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler (InfoWizardPage::OnActionButtonClick), nullptr, this);
InfoPageSizer->Add (actionButton, 0, wxALL, 5);
}
InfoStaticText->SetFocus();
}
void InfoWizardPage::SetMaxStaticTextWidth (int width)
{
InfoStaticText->Wrap (width);
}
}

View File

@@ -0,0 +1,32 @@
/*
Copyright (c) 2008 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.
*/
#ifndef TC_HEADER_Main_Forms_InfoWizardPage
#define TC_HEADER_Main_Forms_InfoWizardPage
#include "Forms.h"
namespace TrueCrypt
{
class InfoWizardPage : public InfoWizardPageBase
{
public:
InfoWizardPage (wxPanel *parent, const wxString &actionButtonText = wxEmptyString, shared_ptr <Functor> actionFunctor = shared_ptr <Functor> ());
bool IsValid () { return true; }
void SetMaxStaticTextWidth (int width);
void SetPageText (const wxString &text) { InfoStaticText->SetLabel (text); }
protected:
virtual void OnActionButtonClick (wxCommandEvent& event) { (*ActionFunctor)(); }
shared_ptr <Functor> ActionFunctor;
};
}
#endif // TC_HEADER_Main_Forms_InfoWizardPage

View File

@@ -0,0 +1,118 @@
/*
Copyright (c) 2008-2009 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"
#include "Main/GraphicUserInterface.h"
#include "Volume/Hash.h"
#include "KeyfileGeneratorDialog.h"
namespace TrueCrypt
{
KeyfileGeneratorDialog::KeyfileGeneratorDialog (wxWindow* parent) : KeyfileGeneratorDialogBase (parent)
{
RandomNumberGenerator::Start();
Hashes = Hash::GetAvailableAlgorithms();
foreach (shared_ptr <Hash> hash, Hashes)
{
if (!hash->IsDeprecated())
HashChoice->Append (hash->GetName(), hash.get());
}
HashChoice->Select (0);
RandomNumberGenerator::SetHash (Gui->GetSelectedData <Hash> (HashChoice)->GetNew());
ShowBytes (RandomPoolStaticText, RandomNumberGenerator::PeekPool().GetRange (0, 24));
MouseStaticText->Wrap (Gui->GetCharWidth (MouseStaticText) * 70);
MainSizer->SetMinSize (wxSize (-1, Gui->GetCharHeight (this) * 24));
Layout();
Fit();
Center();
foreach (wxWindow *c, this->GetChildren())
c->Connect (wxEVT_MOTION, wxMouseEventHandler (KeyfileGeneratorDialog::OnMouseMotion), nullptr, this);
}
KeyfileGeneratorDialog::~KeyfileGeneratorDialog ()
{
}
void KeyfileGeneratorDialog::OnGenerateButtonClick (wxCommandEvent& event)
{
try
{
FilePathList files = Gui->SelectFiles (Gui->GetActiveWindow(), wxEmptyString, true);
if (files.empty())
return;
SecureBuffer keyfileBuffer (VolumePassword::MaxSize);
RandomNumberGenerator::GetData (keyfileBuffer);
{
File keyfile;
keyfile.Open (*files.front(), File::CreateWrite);
keyfile.Write (keyfileBuffer);
}
Gui->ShowInfo ("KEYFILE_CREATED");
}
catch (exception &e)
{
Gui->ShowError (e);
}
}
void KeyfileGeneratorDialog::OnHashSelected (wxCommandEvent& event)
{
RandomNumberGenerator::SetHash (Gui->GetSelectedData <Hash> (HashChoice)->GetNew());
}
void KeyfileGeneratorDialog::OnMouseMotion (wxMouseEvent& event)
{
event.Skip();
RandomNumberGenerator::AddToPool (ConstBufferPtr (reinterpret_cast <byte *> (&event), sizeof (event)));
long coord = event.GetX();
RandomNumberGenerator::AddToPool (ConstBufferPtr (reinterpret_cast <byte *> (&coord), sizeof (coord)));
coord = event.GetY();
RandomNumberGenerator::AddToPool (ConstBufferPtr (reinterpret_cast <byte *> (&coord), sizeof (coord)));
if (ShowRandomPoolCheckBox->IsChecked())
ShowBytes (RandomPoolStaticText, RandomNumberGenerator::PeekPool().GetRange (0, 24));
}
void KeyfileGeneratorDialog::OnShowRandomPoolCheckBoxClicked (wxCommandEvent& event)
{
if (!event.IsChecked())
RandomPoolStaticText->SetLabel (L"");
}
void KeyfileGeneratorDialog::ShowBytes (wxStaticText *textCtrl, const ConstBufferPtr &buffer, bool appendDots)
{
wxString str;
for (size_t i = 0; i < buffer.Size(); ++i)
{
str += wxString::Format (L"%02X", buffer[i]);
}
if (appendDots)
str += L"..";
textCtrl->SetLabel (str.c_str());
for (size_t i = 0; i < str.size(); ++i)
{
str[i] = L'X';
}
}
}

View File

@@ -0,0 +1,34 @@
/*
Copyright (c) 2008 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.
*/
#ifndef TC_HEADER_Main_Forms_KeyfileGeneratorDialog
#define TC_HEADER_Main_Forms_KeyfileGeneratorDialog
#include "Forms.h"
#include "Main/Main.h"
namespace TrueCrypt
{
class KeyfileGeneratorDialog : public KeyfileGeneratorDialogBase
{
public:
KeyfileGeneratorDialog (wxWindow* parent);
~KeyfileGeneratorDialog ();
protected:
void OnGenerateButtonClick (wxCommandEvent& event);
void OnHashSelected (wxCommandEvent& event);
void OnMouseMotion (wxMouseEvent& event);
void OnShowRandomPoolCheckBoxClicked (wxCommandEvent& event);
void ShowBytes (wxStaticText *textCtrl, const ConstBufferPtr &buffer, bool appendDots = true);
HashList Hashes;
};
}
#endif // TC_HEADER_Main_Forms_KeyfileGeneratorDialog

View File

@@ -0,0 +1,44 @@
/*
Copyright (c) 2008 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"
#include "Main/GraphicUserInterface.h"
#include "KeyfilesDialog.h"
namespace TrueCrypt
{
KeyfilesDialog::KeyfilesDialog (wxWindow* parent, shared_ptr <KeyfileList> keyfiles)
: KeyfilesDialogBase (parent), Keyfiles (keyfiles)
{
mKeyfilesPanel = new KeyfilesPanel (this, keyfiles);
PanelSizer->Add (mKeyfilesPanel, 1, wxALL | wxEXPAND);
WarningStaticText->SetLabel (LangString["IDT_KEYFILE_WARNING"]);
WarningStaticText->Wrap (Gui->GetCharWidth (this) * 15);
Layout();
Fit();
KeyfilesNoteStaticText->SetLabel (LangString["KEYFILES_NOTE"]);
KeyfilesNoteStaticText->Wrap (UpperSizer->GetSize().GetWidth() - Gui->GetCharWidth (this) * 2);
Layout();
Fit();
Center();
}
void KeyfilesDialog::OnCreateKeyfileButttonClick (wxCommandEvent& event)
{
Gui->CreateKeyfile();
}
void KeyfilesDialog::OnKeyfilesHyperlinkClick (wxHyperlinkEvent& event)
{
Gui->OpenHomepageLink (this, L"keyfiles");
}
}

View File

@@ -0,0 +1,33 @@
/*
Copyright (c) 2008 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.
*/
#ifndef TC_HEADER_Main_Forms_KeyfilesDialog
#define TC_HEADER_Main_Forms_KeyfilesDialog
#include "Forms.h"
#include "Main/Main.h"
#include "KeyfilesPanel.h"
namespace TrueCrypt
{
class KeyfilesDialog : public KeyfilesDialogBase
{
public:
KeyfilesDialog (wxWindow* parent, shared_ptr <KeyfileList> keyfiles);
shared_ptr <KeyfileList> GetKeyfiles () const { return mKeyfilesPanel->GetKeyfiles(); }
protected:
void OnCreateKeyfileButttonClick (wxCommandEvent& event);
void OnKeyfilesHyperlinkClick (wxHyperlinkEvent& event);
shared_ptr <KeyfileList> Keyfiles;
KeyfilesPanel *mKeyfilesPanel;
};
}
#endif // TC_HEADER_Main_Forms_KeyfilesDialog

View File

@@ -0,0 +1,160 @@
/*
Copyright (c) 2008 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"
#include "Main/GraphicUserInterface.h"
#include "KeyfilesPanel.h"
#include "SecurityTokenKeyfilesDialog.h"
namespace TrueCrypt
{
KeyfilesPanel::KeyfilesPanel (wxWindow* parent, shared_ptr <KeyfileList> keyfiles)
: KeyfilesPanelBase (parent)
{
KeyfilesListCtrl->InsertColumn (0, LangString["KEYFILE"], wxLIST_FORMAT_LEFT, 1);
Gui->SetListCtrlHeight (KeyfilesListCtrl, 10);
Layout();
Fit();
if (keyfiles)
{
foreach_ref (const Keyfile &k, *keyfiles)
{
vector <wstring> fields;
fields.push_back (FilesystemPath (k));
Gui->AppendToListCtrl (KeyfilesListCtrl, fields);
}
}
class FileDropTarget : public wxFileDropTarget
{
public:
FileDropTarget (KeyfilesPanel *panel) : Panel (panel) { }
wxDragResult OnDragOver (wxCoord x, wxCoord y, wxDragResult def)
{
return wxDragLink;
}
bool OnDropFiles (wxCoord x, wxCoord y, const wxArrayString &filenames)
{
foreach (const wxString &f, filenames)
Panel->AddKeyfile (make_shared <Keyfile> (wstring (f)));
return true;
}
protected:
KeyfilesPanel *Panel;
};
SetDropTarget (new FileDropTarget (this));
KeyfilesListCtrl->SetDropTarget (new FileDropTarget (this));
#ifdef TC_MACOSX
foreach (wxWindow *c, GetChildren())
c->SetDropTarget (new FileDropTarget (this));
#endif
UpdateButtons();
}
void KeyfilesPanel::AddKeyfile (shared_ptr <Keyfile> keyfile)
{
vector <wstring> fields;
fields.push_back (FilesystemPath (*keyfile));
Gui->AppendToListCtrl (KeyfilesListCtrl, fields);
UpdateButtons();
}
shared_ptr <KeyfileList> KeyfilesPanel::GetKeyfiles () const
{
make_shared_auto (KeyfileList, keyfiles);
for (long i = 0; i < KeyfilesListCtrl->GetItemCount(); i++)
keyfiles->push_back (make_shared <Keyfile> (wstring (KeyfilesListCtrl->GetItemText (i))));
return keyfiles;
}
void KeyfilesPanel::OnAddDirectoryButtonClick (wxCommandEvent& event)
{
DirectoryPath dir = Gui->SelectDirectory (this, LangString["SELECT_KEYFILE_PATH"]);
if (!dir.IsEmpty())
{
vector <wstring> fields;
fields.push_back (dir);
Gui->AppendToListCtrl (KeyfilesListCtrl, fields);
UpdateButtons();
}
}
void KeyfilesPanel::OnAddFilesButtonClick (wxCommandEvent& event)
{
FilePathList files = Gui->SelectFiles (this, LangString["SELECT_KEYFILES"], false, true);
foreach_ref (const FilePath &f, files)
{
vector <wstring> fields;
fields.push_back (f);
Gui->AppendToListCtrl (KeyfilesListCtrl, fields);
}
UpdateButtons();
}
void KeyfilesPanel::OnAddSecurityTokenSignatureButtonClick (wxCommandEvent& event)
{
try
{
SecurityTokenKeyfilesDialog dialog (this);
if (dialog.ShowModal() == wxID_OK)
{
foreach (const SecurityTokenKeyfilePath &path, dialog.GetSelectedSecurityTokenKeyfilePaths())
{
vector <wstring> fields;
fields.push_back (path);
Gui->AppendToListCtrl (KeyfilesListCtrl, fields);
}
UpdateButtons();
}
}
catch (exception &e)
{
Gui->ShowError (e);
}
}
void KeyfilesPanel::OnListSizeChanged (wxSizeEvent& event)
{
list <int> colPermilles;
colPermilles.push_back (1000);
Gui->SetListCtrlColumnWidths (KeyfilesListCtrl, colPermilles);
event.Skip();
}
void KeyfilesPanel::OnRemoveAllButtonClick (wxCommandEvent& event)
{
KeyfilesListCtrl->DeleteAllItems();
UpdateButtons();
}
void KeyfilesPanel::OnRemoveButtonClick (wxCommandEvent& event)
{
long offset = 0;
foreach (long item, Gui->GetListCtrlSelectedItems (KeyfilesListCtrl))
KeyfilesListCtrl->DeleteItem (item - offset++);
UpdateButtons();
}
void KeyfilesPanel::UpdateButtons ()
{
RemoveAllButton->Enable (KeyfilesListCtrl->GetItemCount() > 0);
RemoveButton->Enable (KeyfilesListCtrl->GetSelectedItemCount() > 0);
}
}

View File

@@ -0,0 +1,37 @@
/*
Copyright (c) 2008 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.
*/
#ifndef TC_HEADER_Main_Forms_KeyfilesPanel
#define TC_HEADER_Main_Forms_KeyfilesPanel
#include "Forms.h"
#include "Main/Main.h"
namespace TrueCrypt
{
class KeyfilesPanel : public KeyfilesPanelBase
{
public:
KeyfilesPanel (wxWindow* parent, shared_ptr <KeyfileList> keyfiles);
void AddKeyfile (shared_ptr <Keyfile> keyfile);
shared_ptr <KeyfileList> GetKeyfiles () const;
protected:
void OnAddFilesButtonClick (wxCommandEvent& event);
void OnAddDirectoryButtonClick (wxCommandEvent& event);
void OnAddSecurityTokenSignatureButtonClick (wxCommandEvent& event);
void OnListItemDeselected (wxListEvent& event) { UpdateButtons(); }
void OnListItemSelected (wxListEvent& event) { UpdateButtons(); }
void OnListSizeChanged (wxSizeEvent& event);
void OnRemoveButtonClick (wxCommandEvent& event);
void OnRemoveAllButtonClick (wxCommandEvent& event);
void UpdateButtons ();
};
}
#endif // TC_HEADER_Main_Forms_KeyfilesPanel

View File

@@ -0,0 +1,28 @@
/*
Copyright (c) 2008 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"
#include "LegalNoticesDialog.h"
#include "Main/GraphicUserInterface.h"
#include "Main/Resources.h"
namespace TrueCrypt
{
LegalNoticesDialog::LegalNoticesDialog (wxWindow* parent) : LegalNoticesDialogBase (parent)
{
LegalNoticesTextCtrl->SetMinSize (wxSize (
Gui->GetCharWidth (LegalNoticesTextCtrl) * 88,
Gui->GetCharHeight (LegalNoticesTextCtrl) * 28));
Layout();
Fit();
Center();
LegalNoticesTextCtrl->ChangeValue (StringConverter::ToWide (Resources::GetLegalNotices()));
}
}

View File

@@ -0,0 +1,23 @@
/*
Copyright (c) 2008 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.
*/
#ifndef TC_HEADER_Main_Forms_LegalNoticesDialog
#define TC_HEADER_Main_Forms_LegalNoticesDialog
#include "Forms.h"
namespace TrueCrypt
{
class LegalNoticesDialog : public LegalNoticesDialogBase
{
public:
LegalNoticesDialog (wxWindow* parent);
};
}
#endif // TC_HEADER_Main_Forms_LegalNoticesDialog

1585
src/Main/Forms/MainFrame.cpp Normal file

File diff suppressed because it is too large Load Diff

173
src/Main/Forms/MainFrame.h Normal file
View File

@@ -0,0 +1,173 @@
/*
Copyright (c) 2008-2009 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.
*/
#ifndef TC_HEADER_Main_Forms_MainFrame
#define TC_HEADER_Main_Forms_MainFrame
#include "Forms.h"
#include "ChangePasswordDialog.h"
namespace TrueCrypt
{
struct FavoriteVolume;
class MainFrame : public MainFrameBase
{
public:
MainFrame (wxWindow* parent);
virtual ~MainFrame ();
void OnDeviceChange (const DirectoryPath &mountPoint = DirectoryPath());
#ifdef TC_UNIX
static FilePath GetShowRequestFifoPath () { return Application::GetConfigFilePath (L".show-request-queue", true); }
#endif
protected:
enum
{
ColumnSlot = 0,
ColumnPath,
ColumnSize,
#ifdef TC_WINDOWS
ColumnEA,
#else
ColumnMountPoint,
#endif
ColumnType
};
void AddToFavorites (const VolumeInfoList &volumes);
bool CanExit () const;
void ChangePassword (ChangePasswordDialog::Mode::Enum mode = ChangePasswordDialog::Mode::ChangePasswordAndKeyfiles);
void CheckFilesystem (bool repair = false);
bool CheckVolumePathNotEmpty () const;
void DismountVolume (shared_ptr <VolumeInfo> volume = shared_ptr <VolumeInfo> ());
const UserPreferences &GetPreferences () const { return Gui->GetPreferences(); }
shared_ptr <VolumeInfo> GetSelectedVolume () const;
shared_ptr <VolumePath> GetSelectedVolumePath () const { return make_shared <VolumePath> (wstring (VolumePathComboBox->GetValue())); }
void InitControls ();
void InitEvents ();
void InitMessageFilter ();
void InitPreferences ();
void InitTaskBarIcon ();
bool IsFreeSlotSelected () const { return SlotListCtrl->GetSelectedItemCount() == 1 && Gui->GetListCtrlSubItemText (SlotListCtrl, SelectedItemIndex, ColumnPath).empty(); }
bool IsMountedSlotSelected () const { return SlotListCtrl->GetSelectedItemCount() == 1 && !Gui->GetListCtrlSubItemText (SlotListCtrl, SelectedItemIndex, ColumnPath).empty(); }
void LoadFavoriteVolumes ();
void LoadPreferences ();
void MountAllDevices ();
void MountAllFavorites ();
void MountVolume ();
void OnAboutMenuItemSelected (wxCommandEvent& event);
void OnActivate (wxActivateEvent& event);
void OnAddAllMountedToFavoritesMenuItemSelected (wxCommandEvent& event);
void OnAddToFavoritesMenuItemSelected (wxCommandEvent& event);
void OnBackupVolumeHeadersMenuItemSelected (wxCommandEvent& event);
void OnBeginnersTutorialMenuItemSelected (wxCommandEvent& event) { Gui->OpenHomepageLink (this, L"tutorial"); }
void OnBenchmarkMenuItemSelected (wxCommandEvent& event);
void OnChangeKeyfilesMenuItemSelected (wxCommandEvent& event) { ChangePassword (ChangePasswordDialog::Mode::ChangeKeyfiles); }
void OnChangePasswordMenuItemSelected (wxCommandEvent& event) { ChangePassword (); }
void OnChangePkcs5PrfMenuItemSelected (wxCommandEvent& event) { ChangePassword (ChangePasswordDialog::Mode::ChangePkcs5Prf); }
void OnCheckFilesystemMenuItemSelected( wxCommandEvent& event ) { CheckFilesystem (); }
void OnClearSlotSelectionMenuItemSelected (wxCommandEvent& event);
void OnClose (wxCloseEvent& event);
void OnCloseAllSecurityTokenSessionsMenuItemSelected (wxCommandEvent& event);
void OnContactMenuItemSelected (wxCommandEvent& event) { Gui->OpenHomepageLink (this, L"contact"); }
void OnCreateKeyfileMenuItemSelected (wxCommandEvent& event) { Gui->CreateKeyfile(); }
void OnCreateVolumeButtonClick (wxCommandEvent& event);
void OnDefaultKeyfilesMenuItemSelected (wxCommandEvent& event);
void OnDismountAllButtonClick (wxCommandEvent& event);
void OnDismountVolumeMenuItemSelected (wxCommandEvent& event) { DismountVolume(); }
void OnDownloadsMenuItemSelected (wxCommandEvent& event) { Gui->OpenHomepageLink (this, L"downloads"); }
void OnEncryptionTestMenuItemSelected (wxCommandEvent& event);
void OnExitButtonClick (wxCommandEvent& event);
void OnFavoriteVolumeMenuItemSelected (wxCommandEvent& event);
void OnFaqMenuItemSelected (wxCommandEvent& event) { Gui->OpenHomepageLink (this, L"faq"); }
void OnHiddenVolumeProtectionTriggered (shared_ptr <VolumeInfo> protectedVolume);
void OnHotkey (wxKeyEvent& event);
void OnHotkeysMenuItemSelected (wxCommandEvent& event);
void OnLegalNoticesMenuItemSelected (wxCommandEvent& event);
void OnListChanged ();
void OnListItemActivated (wxListEvent& event);
void OnListItemDeleted (long itemIndex);
void OnListItemDeselected (wxListEvent& event);
void OnListItemInserted (long itemIndex);
void OnListItemRightClick (wxListEvent& event);
void OnListItemSelected (wxListEvent& event);
void OnListItemSelectionChanged ();
void OnLogoBitmapClick (wxMouseEvent &event) { wxCommandEvent ev; OnAboutMenuItemSelected (ev); }
void OnManageSecurityTokenKeyfilesMenuItemSelected (wxCommandEvent& event);
void OnMountAllDevicesButtonClick (wxCommandEvent& event);
void OnMountAllFavoritesMenuItemSelected (wxCommandEvent& event);
void OnMountVolumeMenuItemSelected (wxCommandEvent& event) { MountVolume(); }
void OnNewsMenuItemSelected (wxCommandEvent& event) { Gui->OpenHomepageLink (this, L"news"); }
void OnNoHistoryCheckBoxClick (wxCommandEvent& event);
void OnOnlineHelpMenuItemSelected (wxCommandEvent& event) { Gui->OpenOnlineHelp (this); }
void OnOpenVolumeMenuItemSelected (wxCommandEvent& event) { OpenSelectedVolume(); }
void OnOpenVolumeSystemRequestEvent (EventArgs &args) { SetVolumePath (wstring (dynamic_cast <OpenVolumeSystemRequestEventArgs &> (args).mVolumePath)); }
void OnOrganizeFavoritesMenuItemSelected (wxCommandEvent& event);
void OnPreferencesMenuItemSelected (wxCommandEvent& event);
void OnPreferencesUpdated (EventArgs &args);
void OnRemoveKeyfilesMenuItemSelected (wxCommandEvent& event) { ChangePassword (ChangePasswordDialog::Mode::RemoveAllKeyfiles); }
void OnRepairFilesystemMenuItemSelected( wxCommandEvent& event ) { CheckFilesystem (true); }
void OnRestoreVolumeHeaderMenuItemSelected (wxCommandEvent& event);
void OnSecurityTokenPreferencesMenuItemSelected (wxCommandEvent& event);
void OnSelectDeviceAndMountMenuItemSelected (wxCommandEvent& event);
void OnSelectDeviceButtonClick (wxCommandEvent& event);
void OnSelectFileAndMountMenuItemSelected (wxCommandEvent& event);
void OnSelectFileButtonClick (wxCommandEvent& event);
void OnTimer ();
void OnVersionHistoryMenuItemSelected (wxCommandEvent& event) { Gui->OpenHomepageLink (this, L"history"); }
void OnVolumePropertiesButtonClick (wxCommandEvent& event);
void OnVolumeToolsButtonClick (wxCommandEvent& event);
void OnVolumeButtonClick (wxCommandEvent& event);
void OnVolumeDismounted (EventArgs &args) { UpdateVolumeList(); }
void OnVolumeMounted (EventArgs &args) { UpdateVolumeList(); }
void OnUserGuideMenuItemSelected (wxCommandEvent& event) { Gui->OpenUserGuide (this); }
void OnWebsiteMenuItemSelected (wxCommandEvent& event) { Gui->OpenHomepageLink (this, L"website"); }
void OnWipeCacheButtonClick (wxCommandEvent& event);
void OrganizeFavorites (const FavoriteVolumeList &favorites, size_t newItemCount = 0);
void OpenSelectedVolume () const;
void SavePreferences () const;
long SlotNumberToItemIndex (uint32 slotNumber) const;
void SetVolumePath (const VolumePath &path) { VolumePathComboBox->SetValue (wstring (path)); }
void ShowTaskBarIcon (bool show = true);
void UpdateControls ();
void UpdateVolumeList ();
void UpdateWipeCacheButton ();
void WipeCache ();
struct VolumeActivityMapEntry
{
VolumeActivityMapEntry () { }
VolumeActivityMapEntry (const VolumeInfo &volume, wxLongLong lastActivityTime)
: LastActivityTime (lastActivityTime),
SerialInstanceNumber (volume.SerialInstanceNumber),
TotalDataRead (volume.TotalDataRead),
TotalDataWritten (volume.TotalDataWritten)
{ }
wxLongLong LastActivityTime;
uint64 SerialInstanceNumber;
uint64 TotalDataRead;
uint64 TotalDataWritten;
};
map <int, FavoriteVolume> FavoriteVolumesMenuMap;
bool ListItemRightClickEventPending;
VolumeInfoList MountedVolumes;
auto_ptr <wxTaskBarIcon> mTaskBarIcon;
auto_ptr <wxTimer> mTimer;
long SelectedItemIndex;
VolumeSlotNumber SelectedSlotNumber;
int ShowRequestFifo;
map <wstring, VolumeActivityMapEntry> VolumeActivityMap;
};
}
#endif // TC_HEADER_Main_Forms_MainFrame

View File

@@ -0,0 +1,174 @@
/*
Copyright (c) 2008 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"
#include "Main/Main.h"
#include "Main/GraphicUserInterface.h"
#include "MountOptionsDialog.h"
namespace TrueCrypt
{
MountOptionsDialog::MountOptionsDialog (wxWindow *parent, MountOptions &options, const wxString &title, bool disableMountOptions)
: MountOptionsDialogBase (parent, wxID_ANY, wxString()
#ifdef __WXGTK__ // GTK apparently needs wxRESIZE_BORDER to support dynamic resizing
, wxDefaultPosition, wxSize (-1,-1), wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER
#endif
), Options (options)
{
if (!title.empty())
this->SetTitle (title);
else if (options.Path && !options.Path->IsEmpty())
this->SetTitle (StringFormatter (LangString["ENTER_PASSWORD_FOR"], wstring (*options.Path)));
else
this->SetTitle (LangString["ENTER_TC_VOL_PASSWORD"]);
if (disableMountOptions)
OptionsButton->Show (false);
PasswordPanel = new VolumePasswordPanel (this, options.Password, options.Keyfiles, !disableMountOptions);
PasswordPanel->SetCacheCheckBoxValidator (wxGenericValidator (&Options.CachePassword));
PasswordSizer->Add (PasswordPanel, 1, wxALL | wxEXPAND);
#ifdef __WXGTK__
FilesystemOptionsSizer->Remove (FilesystemSpacer);
OptionsPanel->Show (false);
Fit();
Layout();
SetMinSize (GetSize());
#endif
NoFilesystemCheckBox->SetValidator (wxGenericValidator (&Options.NoFilesystem));
RemovableCheckBox->SetValidator (wxGenericValidator (&Options.Removable));
PartitionInSystemEncryptionScopeCheckBox->SetValidator (wxGenericValidator (&Options.PartitionInSystemEncryptionScope));
TransferDataToWindow();
if (Options.MountPoint && !Options.MountPoint->IsEmpty())
MountPointTextCtrl->SetValue (wstring (*Options.MountPoint));
FilesystemOptionsTextCtrl->SetValue (Options.FilesystemOptions);
ReadOnlyCheckBox->SetValue (Options.Protection == VolumeProtection::ReadOnly);
ProtectionCheckBox->SetValue (Options.Protection == VolumeProtection::HiddenVolumeReadOnly);
OptionsButtonLabel = OptionsButton->GetLabel();
OptionsButton->SetLabel (OptionsButtonLabel + L" >");
OptionsPanel->Show (false);
ProtectionPasswordPanel = new VolumePasswordPanel (OptionsPanel, options.ProtectionPassword, options.ProtectionKeyfiles, false, true, true, false, false, _("P&assword to hidden volume:"));
ProtectionPasswordSizer->Add (ProtectionPasswordPanel, 1, wxALL | wxEXPAND);
UpdateDialog();
Center();
}
void MountOptionsDialog::OnInitDialog (wxInitDialogEvent& event)
{
PasswordPanel->SetFocusToPasswordTextCtrl();
}
void MountOptionsDialog::OnMountPointButtonClick (wxCommandEvent& event)
{
DirectoryPath dir = Gui->SelectDirectory (this, wxEmptyString, false);
if (!dir.IsEmpty())
MountPointTextCtrl->SetValue (wstring (dir));
}
void MountOptionsDialog::OnOKButtonClick (wxCommandEvent& event)
{
TransferDataFromWindow();
Options.Password = PasswordPanel->GetPassword();
Options.Keyfiles = PasswordPanel->GetKeyfiles();
if (ReadOnlyCheckBox->IsChecked())
{
Options.Protection = VolumeProtection::ReadOnly;
}
else if (ProtectionCheckBox->IsChecked())
{
Options.Protection = VolumeProtection::HiddenVolumeReadOnly;
Options.ProtectionPassword = ProtectionPasswordPanel->GetPassword();
Options.ProtectionKeyfiles = ProtectionPasswordPanel->GetKeyfiles();
}
else
{
Options.Protection = VolumeProtection::None;
}
wstring mountPoint (MountPointTextCtrl->GetValue());
if (!mountPoint.empty())
Options.MountPoint = make_shared <DirectoryPath> (mountPoint);
Options.FilesystemOptions = FilesystemOptionsTextCtrl->GetValue();
try
{
if (Options.Password)
Options.Password->CheckPortability();
}
catch (UnportablePassword &)
{
Gui->ShowWarning (LangString ["UNSUPPORTED_CHARS_IN_PWD_RECOM"]);
}
EndModal (wxID_OK);
}
void MountOptionsDialog::OnOptionsButtonClick (wxCommandEvent& event)
{
FreezeScope freeze (this);
OptionsPanel->Show (!OptionsPanel->IsShown());
UpdateDialog();
OptionsButton->SetLabel (OptionsButtonLabel + (OptionsPanel->IsShown() ? L" <" : L" >"));
}
void MountOptionsDialog::OnProtectionCheckBoxClick (wxCommandEvent& event)
{
FreezeScope freeze (this);
ProtectionPasswordPanel->Show (event.IsChecked());
Fit();
Layout();
ProtectionPasswordPanel->SetFocusToPasswordTextCtrl();
}
void MountOptionsDialog::OnProtectionHyperlinkClick (wxHyperlinkEvent& event)
{
Gui->OpenHomepageLink (this, L"hiddenvolprotection");
}
void MountOptionsDialog::UpdateDialog ()
{
FreezeScope freeze (this);
#ifdef TC_WINDOWS
FilesystemSizer->Show (false);
#else
FilesystemOptionsSizer->Show (!NoFilesystemCheckBox->IsChecked());
# ifdef TC_MACOSX
FilesystemOptionsStaticText->Show (false);
FilesystemOptionsTextCtrl->Show (false);
# endif
if (!Options.Path || Options.Path->IsEmpty())
{
MountPointTextCtrlStaticText->Show (false);
MountPointTextCtrl->Show (false);
MountPointButton->Show (false);
}
RemovableCheckBox->Show (false);
#endif
ProtectionSizer->Show (!ReadOnlyCheckBox->IsChecked());
ProtectionPasswordPanel->Show (!ReadOnlyCheckBox->IsChecked() && ProtectionCheckBox->IsChecked());
Fit();
Layout();
}
}

View File

@@ -0,0 +1,42 @@
/*
Copyright (c) 2008 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.
*/
#ifndef TC_HEADER_Main_Forms_MountOptionsDialog
#define TC_HEADER_Main_Forms_MountOptionsDialog
#include "Forms.h"
#include "Main/Main.h"
#include "VolumePasswordPanel.h"
namespace TrueCrypt
{
class MountOptionsDialog : public MountOptionsDialogBase
{
public:
MountOptionsDialog (wxWindow* parent, MountOptions &options, const wxString &title = wxEmptyString, bool disableMountOptions = false);
void OnShow ();
protected:
void OnInitDialog (wxInitDialogEvent& event);
void OnMountPointButtonClick (wxCommandEvent& event);
void OnNoFilesystemCheckBoxClick (wxCommandEvent& event) { UpdateDialog(); }
void OnOKButtonClick (wxCommandEvent& event);
void OnOptionsButtonClick (wxCommandEvent& event);
void OnProtectionCheckBoxClick (wxCommandEvent& event);
void OnProtectionHyperlinkClick (wxHyperlinkEvent& event);
void OnReadOnlyCheckBoxClick (wxCommandEvent& event) { UpdateDialog(); }
void UpdateDialog ();
MountOptions &Options;
wxString OptionsButtonLabel;
VolumePasswordPanel *PasswordPanel;
VolumePasswordPanel *ProtectionPasswordPanel;
};
}
#endif // TC_HEADER_Main_Forms_MountOptionsDialog

View File

@@ -0,0 +1,45 @@
/*
Copyright (c) 2008 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"
#include "Main/GraphicUserInterface.h"
#include "NewSecurityTokenKeyfileDialog.h"
namespace TrueCrypt
{
NewSecurityTokenKeyfileDialog::NewSecurityTokenKeyfileDialog (wxWindow* parent, const wstring &keyfileName) : NewSecurityTokenKeyfileDialogBase (parent)
{
list <SecurityTokenInfo> tokens = SecurityToken::GetAvailableTokens();
if (tokens.empty())
throw_err (LangString ["NO_TOKENS_FOUND"]);
foreach (const SecurityTokenInfo &token, tokens)
{
wstringstream tokenLabel;
tokenLabel << L"[" << token.SlotId << L"] " << token.Label;
SecurityTokenChoice->Append (tokenLabel.str(), (void *) token.SlotId);
}
SecurityTokenChoice->Select (0);
KeyfileNameTextCtrl->SetValue (keyfileName);
KeyfileNameTextCtrl->SetMinSize (wxSize (Gui->GetCharWidth (KeyfileNameTextCtrl) * 32, -1));
Fit();
Layout();
Center();
}
void NewSecurityTokenKeyfileDialog::OnKeyfileNameChanged (wxCommandEvent& event)
{
StdButtonsOK->Enable (!KeyfileNameTextCtrl->GetValue().empty());
event.Skip();
}
}

View File

@@ -0,0 +1,30 @@
/*
Copyright (c) 2008 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.
*/
#ifndef TC_HEADER_Main_Forms_NewSecurityTokenKeyfileDialog
#define TC_HEADER_Main_Forms_NewSecurityTokenKeyfileDialog
#include "Forms.h"
#include "Common/SecurityToken.h"
namespace TrueCrypt
{
class NewSecurityTokenKeyfileDialog : public NewSecurityTokenKeyfileDialogBase
{
public:
NewSecurityTokenKeyfileDialog (wxWindow* parent, const wstring &keyfileName);
wstring GetKeyfileName () const { return wstring (KeyfileNameTextCtrl->GetValue()); }
CK_SLOT_ID GetSelectedSlotId () const { return reinterpret_cast <CK_SLOT_ID> (SecurityTokenChoice->GetClientData (SecurityTokenChoice->GetSelection())); }
protected:
void OnKeyfileNameChanged (wxCommandEvent& event);
};
}
#endif // TC_HEADER_Main_Forms_NewSecurityTokenKeyfileDialog

View File

@@ -0,0 +1,488 @@
/*
Copyright (c) 2008-2009 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"
#include <wx/dynlib.h>
#ifdef TC_WINDOWS
#include <wx/msw/registry.h>
#endif
#include "Common/SecurityToken.h"
#include "Main/Main.h"
#include "Main/Application.h"
#include "Main/GraphicUserInterface.h"
#include "Volume/Cipher.h"
#include "PreferencesDialog.h"
namespace TrueCrypt
{
PreferencesDialog::PreferencesDialog (wxWindow* parent)
: PreferencesDialogBase (parent),
LastVirtualKeyPressed (0),
Preferences (Gui->GetPreferences()),
RestoreValidatorBell (false)
{
#define TC_CHECK_BOX_VALIDATOR(NAME) (TC_JOIN(NAME,CheckBox))->SetValidator (wxGenericValidator (&Preferences.NAME));
#ifdef TC_MACOSX
PreferencesNotebook->SetMinSize (wxSize (Gui->GetCharWidth (PreferencesNotebook) * 108, -1));
#endif
// Security
TC_CHECK_BOX_VALIDATOR (DismountOnLogOff);
TC_CHECK_BOX_VALIDATOR (DismountOnPowerSaving);
TC_CHECK_BOX_VALIDATOR (DismountOnScreenSaver);
TC_CHECK_BOX_VALIDATOR (DismountOnInactivity);
DismountOnInactivitySpinCtrl->SetValidator (wxGenericValidator (&Preferences.MaxVolumeIdleTime));
TC_CHECK_BOX_VALIDATOR (ForceAutoDismount);
PreserveTimestampsCheckBox->SetValidator (wxGenericValidator (&Preferences.DefaultMountOptions.PreserveTimestamps));
TC_CHECK_BOX_VALIDATOR (WipeCacheOnAutoDismount);
TC_CHECK_BOX_VALIDATOR (WipeCacheOnClose);
// Mount options
CachePasswordsCheckBox->SetValidator (wxGenericValidator (&Preferences.DefaultMountOptions.CachePassword));
MountReadOnlyCheckBox->SetValue (Preferences.DefaultMountOptions.Protection == VolumeProtection::ReadOnly);
MountRemovableCheckBox->SetValidator (wxGenericValidator (&Preferences.DefaultMountOptions.Removable));
FilesystemOptionsTextCtrl->SetValue (Preferences.DefaultMountOptions.FilesystemOptions);
// Keyfiles
TC_CHECK_BOX_VALIDATOR (UseKeyfiles);
DefaultKeyfilesPanel = new KeyfilesPanel (DefaultKeyfilesPage, make_shared <KeyfileList> (Preferences.DefaultKeyfiles));
DefaultKeyfilesSizer->Add (DefaultKeyfilesPanel, 1, wxALL | wxEXPAND);
DefaultKeyfilesSizer->Layout();
TC_CHECK_BOX_VALIDATOR (BackgroundTaskEnabled);
TC_CHECK_BOX_VALIDATOR (CloseBackgroundTaskOnNoVolumes);
CloseBackgroundTaskOnNoVolumesCheckBox->Show (!Core->IsInPortableMode());
TC_CHECK_BOX_VALIDATOR (BackgroundTaskMenuDismountItemsEnabled);
TC_CHECK_BOX_VALIDATOR (BackgroundTaskMenuMountItemsEnabled);
TC_CHECK_BOX_VALIDATOR (BackgroundTaskMenuOpenItemsEnabled);
// Encryption
AesHwCpuSupportedStaticText->SetLabel (
#ifdef TC_AES_HW_CPU
(is_aes_hw_cpu_supported() ? LangString["UISTR_YES"] : LangString["UISTR_NO"]));
#else
LangString["NOT_APPLICABLE_OR_NOT_AVAILABLE"]);
#endif
NoHardwareCryptoCheckBox->SetValidator (wxGenericValidator (&Preferences.DefaultMountOptions.NoHardwareCrypto));
// Security tokens
Pkcs11ModulePathTextCtrl->SetValue (wstring (Preferences.SecurityTokenModule));
TC_CHECK_BOX_VALIDATOR (CloseSecurityTokenSessionsAfterMount);
// System integration
TC_CHECK_BOX_VALIDATOR (StartOnLogon);
TC_CHECK_BOX_VALIDATOR (MountDevicesOnLogon);
TC_CHECK_BOX_VALIDATOR (MountFavoritesOnLogon);
TC_CHECK_BOX_VALIDATOR (CloseExplorerWindowsOnDismount);
TC_CHECK_BOX_VALIDATOR (OpenExplorerWindowAfterMount);
NoKernelCryptoCheckBox->SetValidator (wxGenericValidator (&Preferences.DefaultMountOptions.NoKernelCrypto));
#ifdef TC_WINDOWS
// Hotkeys
TC_CHECK_BOX_VALIDATOR (BeepAfterHotkeyMountDismount);
TC_CHECK_BOX_VALIDATOR (DisplayMessageAfterHotkeyDismount);
#endif
TransferDataToWindow(); // Code below relies on TransferDataToWindow() called at this point
#if defined (TC_WINDOWS) || defined (TC_MACOSX)
FilesystemSizer->Show (false);
#else
// Auto-dismount is not supported on Linux as dismount may require the user to enter admin password
AutoDismountSizer->Show (false);
WipeCacheOnAutoDismountCheckBox->Show (false);
#endif
#ifndef TC_WINDOWS
LogOnSizer->Show (false);
MountRemovableCheckBox->Show (false);
CloseExplorerWindowsOnDismountCheckBox->Show (false);
#endif
#ifndef wxHAS_POWER_EVENTS
DismountOnPowerSavingCheckBox->Show (false);
#endif
#ifdef TC_MACOSX
DismountOnScreenSaverCheckBox->Show (false);
DismountOnLogOffCheckBox->SetLabel (_("TrueCrypt quits"));
OpenExplorerWindowAfterMountCheckBox->SetLabel (_("Open Finder window for successfully mounted volume"));
MountRemovableCheckBox->Show (false);
FilesystemSizer->Show (false);
LogOnSizer->Show (false);
CloseExplorerWindowsOnDismountCheckBox->Show (false);
#endif
#ifndef TC_LINUX
KernelServicesSizer->Show (false);
#endif
#ifdef TC_WINDOWS
// Hotkeys
list <int> colPermilles;
HotkeyListCtrl->InsertColumn (ColumnHotkeyDescription, LangString["ACTION"], wxLIST_FORMAT_LEFT, 1);
colPermilles.push_back (642);
HotkeyListCtrl->InsertColumn (ColumnHotkey, LangString["SHORTCUT"], wxLIST_FORMAT_LEFT, 1);
colPermilles.push_back (358);
vector <wstring> fields (HotkeyListCtrl->GetColumnCount());
UnregisteredHotkeys = Preferences.Hotkeys;
Hotkey::UnregisterList (Gui->GetMainFrame(), UnregisteredHotkeys);
foreach (shared_ptr <Hotkey> hotkey, Preferences.Hotkeys)
{
fields[ColumnHotkeyDescription] = hotkey->Description;
fields[ColumnHotkey] = hotkey->GetShortcutString();
Gui->AppendToListCtrl (HotkeyListCtrl, fields, -1, hotkey.get());
}
Gui->SetListCtrlHeight (HotkeyListCtrl, 5);
Layout();
Fit();
Gui->SetListCtrlColumnWidths (HotkeyListCtrl, colPermilles);
RestoreValidatorBell = !wxTextValidator::IsSilent();
wxTextValidator::SetBellOnError (true);
HotkeyTextCtrl->SetValidator (wxTextValidator (wxFILTER_INCLUDE_CHAR_LIST));
UpdateHotkeyButtons();
#endif
// Page setup
for (size_t page = 0; page < PreferencesNotebook->GetPageCount(); page++)
{
wxNotebookPage *np = PreferencesNotebook->GetPage (page);
if (np == HotkeysPage)
{
#ifndef TC_WINDOWS
PreferencesNotebook->RemovePage (page--);
continue;
#endif
}
np->Layout();
}
Layout();
Fit();
Center();
StdButtonsOK->SetDefault();
#ifdef TC_WINDOWS
// Hotkey timer
class Timer : public wxTimer
{
public:
Timer (PreferencesDialog *dialog) : Dialog (dialog) { }
void Notify()
{
Dialog->OnTimer();
}
PreferencesDialog *Dialog;
};
mTimer.reset (dynamic_cast <wxTimer *> (new Timer (this)));
mTimer->Start (25);
#endif
}
PreferencesDialog::~PreferencesDialog ()
{
if (RestoreValidatorBell)
wxTextValidator::SetBellOnError (false);
}
void PreferencesDialog::SelectPage (wxPanel *page)
{
for (size_t pageIndex = 0; pageIndex < PreferencesNotebook->GetPageCount(); pageIndex++)
{
if (PreferencesNotebook->GetPage (pageIndex) == page)
PreferencesNotebook->ChangeSelection (pageIndex);
}
}
void PreferencesDialog::OnAssignHotkeyButtonClick (wxCommandEvent& event)
{
#ifdef TC_WINDOWS
foreach (long item, Gui->GetListCtrlSelectedItems (HotkeyListCtrl))
{
Hotkey *hotkey = reinterpret_cast <Hotkey *> (HotkeyListCtrl->GetItemData (item));
int mods = 0;
mods |= HotkeyShiftCheckBox->IsChecked() ? wxMOD_SHIFT : 0;
mods |= HotkeyControlCheckBox->IsChecked() ? wxMOD_CONTROL : 0;
mods |= HotkeyAltCheckBox->IsChecked() ? wxMOD_ALT : 0;
mods |= HotkeyWinCheckBox->IsChecked() ? wxMOD_WIN : 0;
// F1 is help and F12 is reserved for use by the debugger at all times
if (mods == 0 && (LastVirtualKeyPressed == VK_F1 || LastVirtualKeyPressed == VK_F12))
{
Gui->ShowError ("CANNOT_USE_RESERVED_KEY");
return;
}
// Test if the hotkey can be registered
if (!this->RegisterHotKey (hotkey->Id, mods, LastVirtualKeyPressed))
{
Gui->ShowError (SystemException (SRC_POS));
return;
}
UnregisterHotKey (hotkey->Id);
foreach_ref (const Hotkey &h, Preferences.Hotkeys)
{
if (h.Id != hotkey->Id && h.VirtualKeyCode == LastVirtualKeyPressed && h.VirtualKeyModifiers == mods)
{
Gui->ShowError ("SHORTCUT_ALREADY_IN_USE");
return;
}
}
hotkey->VirtualKeyCode = LastVirtualKeyPressed;
hotkey->VirtualKeyModifiers = mods;
vector <wstring> fields (HotkeyListCtrl->GetColumnCount());
fields[ColumnHotkeyDescription] = hotkey->Description;
fields[ColumnHotkey] = hotkey->GetShortcutString();
Gui->UpdateListCtrlItem (HotkeyListCtrl, item, fields);
UpdateHotkeyButtons();
}
#endif // TC_WINDOWS
}
void PreferencesDialog::OnBackgroundTaskEnabledCheckBoxClick (wxCommandEvent& event)
{
if (!event.IsChecked())
BackgroundTaskEnabledCheckBox->SetValue (!Gui->AskYesNo (LangString["CONFIRM_BACKGROUND_TASK_DISABLED"], false, true));
}
void PreferencesDialog::OnNoHardwareCryptoCheckBoxClick (wxCommandEvent& event)
{
if (event.IsChecked())
{
if (Gui->AskYesNo (LangString["CONFIRM_SETTING_DEGRADES_PERFORMANCE"], true, true))
{
#ifdef TC_LINUX
Gui->ShowWarning (_("Please note that this setting takes effect only if use of the kernel cryptographic services is disabled."));
#endif
}
else
NoHardwareCryptoCheckBox->SetValue (false);
}
Gui->ShowWarning (_("Please note that any currently mounted volumes need to be remounted before they can use this setting."));
}
void PreferencesDialog::OnNoKernelCryptoCheckBoxClick (wxCommandEvent& event)
{
if (event.IsChecked())
NoKernelCryptoCheckBox->SetValue (Gui->AskYesNo (_("Disabling the use of kernel cryptographic services can degrade performance.\n\nAre you sure?"), false, true));
}
void PreferencesDialog::OnClose (wxCloseEvent& event)
{
#ifdef TC_WINDOWS
Hotkey::RegisterList (Gui->GetMainFrame(), UnregisteredHotkeys);
#endif
event.Skip();
}
void PreferencesDialog::OnDismountOnPowerSavingCheckBoxClick (wxCommandEvent& event)
{
if (event.IsChecked() && !ForceAutoDismountCheckBox->IsChecked())
Gui->ShowWarning ("WARN_PREF_AUTO_DISMOUNT");
}
void PreferencesDialog::OnDismountOnScreenSaverCheckBoxClick (wxCommandEvent& event)
{
if (event.IsChecked() && !ForceAutoDismountCheckBox->IsChecked())
Gui->ShowWarning ("WARN_PREF_AUTO_DISMOUNT");
}
void PreferencesDialog::OnForceAutoDismountCheckBoxClick (wxCommandEvent& event)
{
if (!event.IsChecked())
ForceAutoDismountCheckBox->SetValue (!Gui->AskYesNo (LangString["CONFIRM_NO_FORCED_AUTODISMOUNT"], false, true));
}
void PreferencesDialog::OnHotkeyListItemDeselected (wxListEvent& event)
{
UpdateHotkeyButtons();
}
void PreferencesDialog::OnHotkeyListItemSelected (wxListEvent& event)
{
UpdateHotkeyButtons();
HotkeyTextCtrl->ChangeValue (LangString ["PRESS_A_KEY_TO_ASSIGN"]);
AssignHotkeyButton->Enable (false);
}
void PreferencesDialog::OnOKButtonClick (wxCommandEvent& event)
{
#ifdef TC_WINDOWS
HotkeyTextCtrl->SetValidator (wxTextValidator (wxFILTER_NONE));
#endif
if (!Validate())
return;
TransferDataFromWindow();
Preferences.DefaultMountOptions.Protection = MountReadOnlyCheckBox->IsChecked() ? VolumeProtection::ReadOnly : VolumeProtection::None;
Preferences.DefaultMountOptions.FilesystemOptions = FilesystemOptionsTextCtrl->GetValue();
Preferences.DefaultKeyfiles = *DefaultKeyfilesPanel->GetKeyfiles();
bool securityTokenModuleChanged = (Preferences.SecurityTokenModule != wstring (Pkcs11ModulePathTextCtrl->GetValue()));
Preferences.SecurityTokenModule = wstring (Pkcs11ModulePathTextCtrl->GetValue());
Gui->SetPreferences (Preferences);
try
{
if (securityTokenModuleChanged)
{
if (Preferences.SecurityTokenModule.IsEmpty())
{
if (SecurityToken::IsInitialized())
SecurityToken::CloseLibrary ();
}
else
{
Gui->InitSecurityTokenLibrary();
}
}
}
catch (exception &e)
{
Gui->ShowError (e);
}
#ifdef TC_WINDOWS
// Hotkeys
Hotkey::RegisterList (Gui->GetMainFrame(), Preferences.Hotkeys);
#endif
EndModal (wxID_OK);
}
void PreferencesDialog::OnPreserveTimestampsCheckBoxClick (wxCommandEvent& event)
{
#ifdef TC_LINUX
if (!event.IsChecked())
Gui->ShowInfo (_("Please note that disabling this option may have no effect on volumes mounted using kernel cryptographic services."));
#endif
}
void PreferencesDialog::OnRemoveHotkeyButtonClick (wxCommandEvent& event)
{
#ifdef TC_WINDOWS
foreach (long item, Gui->GetListCtrlSelectedItems (HotkeyListCtrl))
{
Hotkey *hotkey = reinterpret_cast <Hotkey *> (HotkeyListCtrl->GetItemData (item));
hotkey->VirtualKeyCode = 0;
hotkey->VirtualKeyModifiers = 0;
vector <wstring> fields (HotkeyListCtrl->GetColumnCount());
fields[ColumnHotkeyDescription] = hotkey->Description;
fields[ColumnHotkey] = hotkey->GetShortcutString();
Gui->UpdateListCtrlItem (HotkeyListCtrl, item, fields);
UpdateHotkeyButtons();
}
#endif
}
void PreferencesDialog::OnSelectPkcs11ModuleButtonClick (wxCommandEvent& event)
{
list < pair <wstring, wstring> > extensions;
wxString libExtension;
libExtension = wxDynamicLibrary::CanonicalizeName (L"x");
#ifdef TC_MACOSX
extensions.push_back (make_pair (L"dylib", LangString["DLL_FILES"]));
#endif
if (!libExtension.empty())
{
extensions.push_back (make_pair (libExtension.Mid (libExtension.find (L'.') + 1), LangString["DLL_FILES"]));
extensions.push_back (make_pair (L"*", L""));
}
string libDir;
#ifdef TC_WINDOWS
char sysDir[TC_MAX_PATH];
GetSystemDirectoryA (sysDir, sizeof (sysDir));
libDir = sysDir;
#elif defined (TC_MACOSX)
libDir = "/usr/local/lib";
#elif defined (TC_UNIX)
libDir = "/usr/lib";
#endif
Gui->ShowInfo ("SELECT_PKCS11_MODULE_HELP");
FilePathList files = Gui->SelectFiles (this, LangString["SELECT_PKCS11_MODULE"], false, false, extensions, libDir);
if (!files.empty())
Pkcs11ModulePathTextCtrl->SetValue (wstring (*files.front()));
}
void PreferencesDialog::OnTimer ()
{
#ifdef TC_WINDOWS
for (UINT vKey = 0; vKey <= 0xFF; vKey++)
{
if (GetAsyncKeyState (vKey) < 0)
{
bool shift = wxGetKeyState (WXK_SHIFT);
bool control = wxGetKeyState (WXK_CONTROL);
bool alt = wxGetKeyState (WXK_ALT);
bool win = wxGetKeyState (WXK_WINDOWS_LEFT) || wxGetKeyState (WXK_WINDOWS_RIGHT);
if (!Hotkey::GetVirtualKeyCodeString (vKey).empty()) // If the key is allowed and its name has been resolved
{
LastVirtualKeyPressed = vKey;
HotkeyShiftCheckBox->SetValue (shift);
HotkeyControlCheckBox->SetValue (control);
HotkeyAltCheckBox->SetValue (alt);
HotkeyWinCheckBox->SetValue (win);
HotkeyTextCtrl->ChangeValue (Hotkey::GetVirtualKeyCodeString (LastVirtualKeyPressed));
UpdateHotkeyButtons();
return;
}
}
}
#endif
}
void PreferencesDialog::UpdateHotkeyButtons()
{
AssignHotkeyButton->Enable (!HotkeyTextCtrl->IsEmpty() && HotkeyListCtrl->GetSelectedItemCount() > 0);
bool remove = false;
foreach (long item, Gui->GetListCtrlSelectedItems (HotkeyListCtrl))
{
if (reinterpret_cast <Hotkey *> (HotkeyListCtrl->GetItemData (item))->VirtualKeyCode != 0)
remove = true;
}
RemoveHotkeyButton->Enable (remove);
}
}

View File

@@ -0,0 +1,60 @@
/*
Copyright (c) 2008 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.
*/
#ifndef TC_HEADER_Main_Forms_PreferencesDialog
#define TC_HEADER_Main_Forms_PreferencesDialog
#include "Forms.h"
#include "Main/Main.h"
#include "KeyfilesPanel.h"
namespace TrueCrypt
{
class PreferencesDialog : public PreferencesDialogBase
{
public:
PreferencesDialog (wxWindow* parent);
~PreferencesDialog ();
void SelectPage (wxPanel *page);
protected:
void OnAssignHotkeyButtonClick (wxCommandEvent& event);
void OnBackgroundTaskEnabledCheckBoxClick (wxCommandEvent& event);
void OnCancelButtonClick (wxCommandEvent& event) { Close(); }
void OnClose (wxCloseEvent& event);
void OnDismountOnPowerSavingCheckBoxClick (wxCommandEvent& event);
void OnDismountOnScreenSaverCheckBoxClick (wxCommandEvent& event);
void OnForceAutoDismountCheckBoxClick (wxCommandEvent& event);
void OnHotkeyListItemDeselected (wxListEvent& event);
void OnHotkeyListItemSelected (wxListEvent& event);
void OnNoHardwareCryptoCheckBoxClick (wxCommandEvent& event);
void OnNoKernelCryptoCheckBoxClick (wxCommandEvent& event);
void OnOKButtonClick (wxCommandEvent& event);
void OnPreserveTimestampsCheckBoxClick (wxCommandEvent& event);
void OnRemoveHotkeyButtonClick (wxCommandEvent& event);
void OnSelectPkcs11ModuleButtonClick (wxCommandEvent& event);
void OnTimer ();
void UpdateHotkeyButtons();
enum
{
ColumnHotkeyDescription = 0,
ColumnHotkey
};
KeyfilesPanel *DefaultKeyfilesPanel;
int LastVirtualKeyPressed;
auto_ptr <wxTimer> mTimer;
UserPreferences Preferences;
bool RestoreValidatorBell;
HotkeyList UnregisteredHotkeys;
};
}
#endif // TC_HEADER_Main_Forms_PreferencesDialog

View File

@@ -0,0 +1,80 @@
/*
Copyright (c) 2008 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"
#include "Main/GraphicUserInterface.h"
#include "ProgressWizardPage.h"
namespace TrueCrypt
{
ProgressWizardPage::ProgressWizardPage (wxPanel* parent, bool enableAbort)
: ProgressWizardPageBase (parent),
PreviousGaugeValue (0),
ProgressBarRange (1),
RealProgressBarRange (1)
{
#ifdef TC_MACOSX
ProgressGauge->SetMinSize (wxSize (-1, 12)); // OS X apparently supports only up to 12px thick progress bars
#else
ProgressGauge->SetMinSize (wxSize (-1, Gui->GetCharHeight (this) * 2));
#endif
ProgressValue.Set (0);
ProgressGauge->SetValue (0);
AbortButton->Show (enableAbort);
class Timer : public wxTimer
{
public:
Timer (ProgressWizardPage *page) : Page (page) { }
void Notify()
{
Page->OnTimer();
}
ProgressWizardPage *Page;
};
mTimer.reset (dynamic_cast <wxTimer *> (new Timer (this)));
mTimer->Start (30);
}
void ProgressWizardPage::OnAbortButtonClick (wxCommandEvent& event)
{
AbortEvent.Raise();
}
void ProgressWizardPage::OnTimer ()
{
uint64 value = ProgressValue.Get();
int gaugeValue = static_cast <int> (value * RealProgressBarRange / ProgressBarRange);
if (value == ProgressBarRange)
gaugeValue = RealProgressBarRange; // Prevent round-off error
if (gaugeValue != PreviousGaugeValue)
{
ProgressGauge->SetValue (gaugeValue);
PreviousGaugeValue = gaugeValue;
}
}
void ProgressWizardPage::SetMaxStaticTextWidth (int width)
{
InfoStaticText->Wrap (width);
}
void ProgressWizardPage::SetProgressRange (uint64 progressBarRange)
{
ProgressBarRange = progressBarRange;
RealProgressBarRange = ProgressGauge->GetSize().GetWidth();
ProgressGauge->SetRange (RealProgressBarRange);
}
}

View File

@@ -0,0 +1,42 @@
/*
Copyright (c) 2008 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.
*/
#ifndef TC_HEADER_Main_Forms_ProgressWizardPage
#define TC_HEADER_Main_Forms_ProgressWizardPage
#include "Forms.h"
namespace TrueCrypt
{
class ProgressWizardPage : public ProgressWizardPageBase
{
public:
ProgressWizardPage (wxPanel* parent, bool enableAbort = false);
~ProgressWizardPage () { }
void EnableAbort (bool enable = true) { AbortButton->Enable (enable); }
bool IsValid () { return true; }
void SetMaxStaticTextWidth (int width);
void SetPageText (const wxString &text) { InfoStaticText->SetLabel (text); }
void SetProgressRange (uint64 progressBarRange);
Event AbortEvent;
SharedVal <uint64> ProgressValue;
protected:
void OnAbortButtonClick (wxCommandEvent& event);
void OnTimer ();
auto_ptr <wxTimer> mTimer;
int PreviousGaugeValue;
uint64 ProgressBarRange;
int RealProgressBarRange;
};
}
#endif // TC_HEADER_Main_Forms_ProgressWizardPage

View File

@@ -0,0 +1,93 @@
/*
Copyright (c) 2008-2009 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"
#include "Main/GraphicUserInterface.h"
#include "Volume/Hash.h"
#include "RandomPoolEnrichmentDialog.h"
namespace TrueCrypt
{
RandomPoolEnrichmentDialog::RandomPoolEnrichmentDialog (wxWindow* parent) : RandomPoolEnrichmentDialogBase (parent)
{
RandomNumberGenerator::Start();
Hashes = Hash::GetAvailableAlgorithms();
foreach (shared_ptr <Hash> hash, Hashes)
{
if (!hash->IsDeprecated())
{
HashChoice->Append (hash->GetName(), hash.get());
if (typeid (*hash) == typeid (*RandomNumberGenerator::GetHash()))
HashChoice->Select (HashChoice->GetCount() - 1);
}
}
ShowBytes (RandomPoolStaticText, RandomNumberGenerator::PeekPool().GetRange (0, 24));
MouseStaticText->Wrap (Gui->GetCharWidth (MouseStaticText) * 70);
MainSizer->SetMinSize (wxSize (-1, Gui->GetCharHeight (this) * 24));
Layout();
Fit();
Center();
foreach (wxWindow *c, this->GetChildren())
c->Connect (wxEVT_MOTION, wxMouseEventHandler (RandomPoolEnrichmentDialog::OnMouseMotion), nullptr, this);
}
RandomPoolEnrichmentDialog::~RandomPoolEnrichmentDialog ()
{
}
void RandomPoolEnrichmentDialog::OnHashSelected (wxCommandEvent& event)
{
RandomNumberGenerator::SetHash (Gui->GetSelectedData <Hash> (HashChoice)->GetNew());
}
void RandomPoolEnrichmentDialog::OnMouseMotion (wxMouseEvent& event)
{
event.Skip();
RandomNumberGenerator::AddToPool (ConstBufferPtr (reinterpret_cast <byte *> (&event), sizeof (event)));
long coord = event.GetX();
RandomNumberGenerator::AddToPool (ConstBufferPtr (reinterpret_cast <byte *> (&coord), sizeof (coord)));
coord = event.GetY();
RandomNumberGenerator::AddToPool (ConstBufferPtr (reinterpret_cast <byte *> (&coord), sizeof (coord)));
if (ShowRandomPoolCheckBox->IsChecked())
ShowBytes (RandomPoolStaticText, RandomNumberGenerator::PeekPool().GetRange (0, 24));
}
void RandomPoolEnrichmentDialog::OnShowRandomPoolCheckBoxClicked (wxCommandEvent& event)
{
if (!event.IsChecked())
RandomPoolStaticText->SetLabel (L"");
}
void RandomPoolEnrichmentDialog::ShowBytes (wxStaticText *textCtrl, const ConstBufferPtr &buffer)
{
wxString str;
for (size_t i = 0; i < buffer.Size(); ++i)
{
str += wxString::Format (L"%02X", buffer[i]);
}
str += L"..";
textCtrl->SetLabel (str.c_str());
for (size_t i = 0; i < str.size(); ++i)
{
str[i] = L'X';
}
}
}

View File

@@ -0,0 +1,33 @@
/*
Copyright (c) 2008-2009 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.
*/
#ifndef TC_HEADER_Main_Forms_RandomPoolEnrichmentDialog
#define TC_HEADER_Main_Forms_RandomPoolEnrichmentDialog
#include "Forms.h"
#include "Main/Main.h"
namespace TrueCrypt
{
class RandomPoolEnrichmentDialog : public RandomPoolEnrichmentDialogBase
{
public:
RandomPoolEnrichmentDialog (wxWindow* parent);
~RandomPoolEnrichmentDialog ();
protected:
void OnHashSelected (wxCommandEvent& event);
void OnMouseMotion (wxMouseEvent& event);
void OnShowRandomPoolCheckBoxClicked (wxCommandEvent& event);
void ShowBytes (wxStaticText *textCtrl, const ConstBufferPtr &buffer);
HashList Hashes;
};
}
#endif // TC_HEADER_Main_Forms_RandomPoolEnrichmentDialog

View File

@@ -0,0 +1,197 @@
/*
Copyright (c) 2008-2009 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"
#include "Main/GraphicUserInterface.h"
#include "Common/SecurityToken.h"
#include "NewSecurityTokenKeyfileDialog.h"
#include "SecurityTokenKeyfilesDialog.h"
namespace TrueCrypt
{
SecurityTokenKeyfilesDialog::SecurityTokenKeyfilesDialog (wxWindow* parent, bool selectionMode)
: SecurityTokenKeyfilesDialogBase (parent)
{
if (selectionMode)
SetTitle (LangString["SELECT_TOKEN_KEYFILES"]);
list <int> colPermilles;
SecurityTokenKeyfileListCtrl->InsertColumn (ColumnSecurityTokenSlotId, LangString["TOKEN_SLOT_ID"], wxLIST_FORMAT_CENTER, 1);
colPermilles.push_back (102);
SecurityTokenKeyfileListCtrl->InsertColumn (ColumnSecurityTokenLabel, LangString["TOKEN_NAME"], wxLIST_FORMAT_LEFT, 1);
colPermilles.push_back (368);
SecurityTokenKeyfileListCtrl->InsertColumn (ColumnSecurityTokenKeyfileLabel, LangString["TOKEN_DATA_OBJECT_LABEL"], wxLIST_FORMAT_LEFT, 1);
colPermilles.push_back (529);
FillSecurityTokenKeyfileListCtrl();
Gui->SetListCtrlWidth (SecurityTokenKeyfileListCtrl, 65);
Gui->SetListCtrlHeight (SecurityTokenKeyfileListCtrl, 16);
Gui->SetListCtrlColumnWidths (SecurityTokenKeyfileListCtrl, colPermilles);
Fit();
Layout();
Center();
DeleteButton->Disable();
ExportButton->Disable();
OKButton->Disable();
OKButton->SetDefault();
}
void SecurityTokenKeyfilesDialog::FillSecurityTokenKeyfileListCtrl ()
{
wxBusyCursor busy;
SecurityTokenKeyfileListCtrl->DeleteAllItems();
SecurityTokenKeyfileList = SecurityToken::GetAvailableKeyfiles();
size_t i = 0;
foreach (const SecurityTokenKeyfile &key, SecurityTokenKeyfileList)
{
vector <wstring> fields (SecurityTokenKeyfileListCtrl->GetColumnCount());
fields[ColumnSecurityTokenSlotId] = StringConverter::ToWide ((uint64) key.SlotId);
fields[ColumnSecurityTokenLabel] = key.Token.Label;
fields[ColumnSecurityTokenKeyfileLabel] = key.Id;
Gui->AppendToListCtrl (SecurityTokenKeyfileListCtrl, fields, 0, &SecurityTokenKeyfileList[i++]);
}
}
void SecurityTokenKeyfilesDialog::OnDeleteButtonClick (wxCommandEvent& event)
{
try
{
if (!Gui->AskYesNo (LangString["CONFIRM_SEL_FILES_DELETE"]))
return;
wxBusyCursor busy;
foreach (long item, Gui->GetListCtrlSelectedItems (SecurityTokenKeyfileListCtrl))
{
SecurityToken::DeleteKeyfile (*reinterpret_cast <SecurityTokenKeyfile *> (SecurityTokenKeyfileListCtrl->GetItemData (item)));
}
FillSecurityTokenKeyfileListCtrl();
}
catch (exception &e)
{
Gui->ShowError (e);
}
}
void SecurityTokenKeyfilesDialog::OnExportButtonClick (wxCommandEvent& event)
{
try
{
foreach (long item, Gui->GetListCtrlSelectedItems (SecurityTokenKeyfileListCtrl))
{
SecurityTokenKeyfile *keyfile = reinterpret_cast <SecurityTokenKeyfile *> (SecurityTokenKeyfileListCtrl->GetItemData (item));
FilePathList files = Gui->SelectFiles (this, wxEmptyString, true);
if (!files.empty())
{
wxBusyCursor busy;
vector <byte> keyfileData;
SecurityToken::GetKeyfileData (*keyfile, keyfileData);
BufferPtr keyfileDataBuf (&keyfileData.front(), keyfileData.size());
finally_do_arg (BufferPtr, keyfileDataBuf, { finally_arg.Erase(); });
File keyfile;
keyfile.Open (*files.front(), File::CreateWrite);
keyfile.Write (keyfileDataBuf);
}
else
break;
Gui->ShowInfo ("KEYFILE_EXPORTED");
}
}
catch (exception &e)
{
Gui->ShowError (e);
}
}
void SecurityTokenKeyfilesDialog::OnImportButtonClick (wxCommandEvent& event)
{
try
{
FilePathList keyfilePaths = Gui->SelectFiles (this, LangString["SELECT_KEYFILES"], false);
if (keyfilePaths.empty())
return;
FilePath keyfilePath = *keyfilePaths.front();
File keyfile;
keyfile.Open (keyfilePath, File::OpenRead, File::ShareReadWrite, File::PreserveTimestamps);
if (keyfile.Length() > 0)
{
vector <byte> keyfileData (keyfile.Length());
BufferPtr keyfileDataBuf (&keyfileData.front(), keyfileData.size());
keyfile.ReadCompleteBuffer (keyfileDataBuf);
finally_do_arg (BufferPtr, keyfileDataBuf, { finally_arg.Erase(); });
NewSecurityTokenKeyfileDialog newKeyfileDialog (this, keyfilePath.ToBaseName());
if (newKeyfileDialog.ShowModal() == wxID_OK)
{
wxBusyCursor busy;
SecurityToken::CreateKeyfile (newKeyfileDialog.GetSelectedSlotId(), keyfileData, StringConverter::ToSingle (newKeyfileDialog.GetKeyfileName()));
FillSecurityTokenKeyfileListCtrl();
}
}
else
throw InsufficientData (SRC_POS, keyfilePath);
}
catch (exception &e)
{
Gui->ShowError (e);
}
}
void SecurityTokenKeyfilesDialog::OnListItemDeselected (wxListEvent& event)
{
if (SecurityTokenKeyfileListCtrl->GetSelectedItemCount() == 0)
{
DeleteButton->Disable();
ExportButton->Disable();
OKButton->Disable();
}
}
void SecurityTokenKeyfilesDialog::OnListItemSelected (wxListEvent& event)
{
if (event.GetItem().GetData() != (wxUIntPtr) nullptr)
{
DeleteButton->Enable();
ExportButton->Enable();
OKButton->Enable();
}
}
void SecurityTokenKeyfilesDialog::OnOKButtonClick ()
{
foreach (long item, Gui->GetListCtrlSelectedItems (SecurityTokenKeyfileListCtrl))
{
SecurityTokenKeyfile *key = reinterpret_cast <SecurityTokenKeyfile *> (SecurityTokenKeyfileListCtrl->GetItemData (item));
SelectedSecurityTokenKeyfilePaths.push_back (*key);
}
EndModal (wxID_OK);
}
}

View File

@@ -0,0 +1,47 @@
/*
Copyright (c) 2008 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.
*/
#ifndef TC_HEADER_Main_Forms_SecurityTokenKeyfilesDialog
#define TC_HEADER_Main_Forms_SecurityTokenKeyfilesDialog
#include "Forms.h"
#include "Common/SecurityToken.h"
#include "Main/Main.h"
namespace TrueCrypt
{
class SecurityTokenKeyfilesDialog : public SecurityTokenKeyfilesDialogBase
{
public:
SecurityTokenKeyfilesDialog (wxWindow* parent, bool selectionMode = true);
list <SecurityTokenKeyfilePath> GetSelectedSecurityTokenKeyfilePaths() const { return SelectedSecurityTokenKeyfilePaths; }
protected:
enum
{
ColumnSecurityTokenSlotId = 0,
ColumnSecurityTokenLabel,
ColumnSecurityTokenKeyfileLabel,
};
void FillSecurityTokenKeyfileListCtrl ();
void OnDeleteButtonClick (wxCommandEvent& event);
void OnExportButtonClick (wxCommandEvent& event);
void OnImportButtonClick (wxCommandEvent& event);
void OnListItemActivated (wxListEvent& event) { OnOKButtonClick(); }
void OnListItemDeselected (wxListEvent& event);
void OnListItemSelected (wxListEvent& event);
void OnOKButtonClick ();
void OnOKButtonClick (wxCommandEvent& event) { OnOKButtonClick(); }
vector <SecurityTokenKeyfile> SecurityTokenKeyfileList;
list <SecurityTokenKeyfilePath> SelectedSecurityTokenKeyfilePaths;
};
}
#endif // TC_HEADER_Main_Forms_SecurityTokenKeyfilesDialog

View File

@@ -0,0 +1,32 @@
/*
Copyright (c) 2008 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"
#include "Main/GraphicUserInterface.h"
#include "SelectDirectoryWizardPage.h"
namespace TrueCrypt
{
bool SelectDirectoryWizardPage::IsValid ()
{
if (!DirectoryTextCtrl->IsEmpty())
{
return FilesystemPath (DirectoryTextCtrl->GetValue()).IsDirectory();
}
return false;
}
void SelectDirectoryWizardPage::OnBrowseButtonClick (wxCommandEvent& event)
{
DirectoryPath dir = Gui->SelectDirectory (this);
if (!dir.IsEmpty())
DirectoryTextCtrl->SetValue (wstring (dir));
}
}

View File

@@ -0,0 +1,33 @@
/*
Copyright (c) 2008 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.
*/
#ifndef TC_HEADER_Main_Forms_SelectDirectoryWizardPage
#define TC_HEADER_Main_Forms_SelectDirectoryWizardPage
#include "Forms.h"
namespace TrueCrypt
{
class SelectDirectoryWizardPage : public SelectDirectoryWizardPageBase
{
public:
SelectDirectoryWizardPage (wxPanel* parent) : SelectDirectoryWizardPageBase (parent) { }
DirectoryPath GetDirectory () const { return DirectoryPath (DirectoryTextCtrl->GetValue()); }
bool IsValid ();
void SetDirectory (const DirectoryPath &path) { DirectoryTextCtrl->SetValue (wstring (path)); }
void SetMaxStaticTextWidth (int width) { InfoStaticText->Wrap (width); }
void SetPageText (const wxString &text) { InfoStaticText->SetLabel (text); }
protected:
void OnBrowseButtonClick (wxCommandEvent& event);
void OnDirectoryTextChanged (wxCommandEvent& event) { PageUpdatedEvent.Raise(); }
};
}
#endif // TC_HEADER_Main_Forms_SelectDirectoryWizardPage

View File

@@ -0,0 +1,116 @@
/*
Copyright (c) 2008 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.
*/
#ifndef TC_HEADER_Main_Forms_SingleChoiceWizardPage
#define TC_HEADER_Main_Forms_SingleChoiceWizardPage
#include "Forms.h"
namespace TrueCrypt
{
template <class ChoiceType>
class SingleChoiceWizardPage : public SingleChoiceWizardPageBase
{
public:
SingleChoiceWizardPage (wxPanel* parent, const wxString &groupBoxText = wxEmptyString, bool choiceTextBold = false)
: SingleChoiceWizardPageBase (parent),
ChoiceTextBold (choiceTextBold)
{
if (!groupBoxText.empty())
{
OuterChoicesSizer->Remove (ChoicesSizer);
ChoicesSizer = new wxStaticBoxSizer (wxVERTICAL, this, groupBoxText);
OuterChoicesSizer->Add (ChoicesSizer, 0, wxEXPAND, 5);
}
}
void AddChoice (ChoiceType choice, const wxString &choiceText, const wxString &infoText = wxEmptyString, const wchar_t *infoLinkId = nullptr, const wxString &infoLinkText = wxEmptyString)
{
assert (RadioButtonMap.find (choice) == RadioButtonMap.end());
wxRadioButton *radioButton = new wxRadioButton (this, wxID_ANY, choiceText);
if (RadioButtonMap.empty())
radioButton->SetValue (true);
RadioButtonMap[choice] = radioButton;
if (ChoiceTextBold)
{
wxFont buttonFont = radioButton->GetFont();
buttonFont.SetWeight (wxFONTWEIGHT_BOLD);
radioButton->SetFont (buttonFont);
}
ChoicesSizer->Add (radioButton, 0, wxALL, 5);
wxBoxSizer *infoSizer = new wxBoxSizer (wxVERTICAL);
wxStaticText *infoStaticText = new wxStaticText (this, wxID_ANY, infoText, wxDefaultPosition, wxDefaultSize, 0);
ChoiceInfoTexts.push_back (infoStaticText);
infoSizer->Add (infoStaticText, 0, wxALL, 5);
ChoicesSizer->Add (infoSizer, 0, wxEXPAND | wxLEFT, Gui->GetCharWidth (this) * 3);
if (infoLinkId)
{
wxHyperlinkCtrl *hyperlink = Gui->CreateHyperlink (this, infoLinkId, infoLinkText);
infoSizer->Add (hyperlink, 0, wxALL, 5);
hyperlink->Connect (wxEVT_COMMAND_HYPERLINK, wxHyperlinkEventHandler (SingleChoiceWizardPage::OnChoiceHyperlinkClick), nullptr, this);
}
ChoicesSizer->Add (1, Gui->GetCharHeight (this) * 1, 0, wxEXPAND, 5);
}
ChoiceType GetSelection () const
{
typedef pair <ChoiceType, wxRadioButton*> MapPair;
foreach (MapPair p, RadioButtonMap)
{
if (p.second->GetValue())
return p.first;
}
throw NoItemSelected (SRC_POS);
}
bool IsValid ()
{
return true;
}
void SetMaxStaticTextWidth (int width)
{
InfoStaticText->Wrap (width);
foreach (wxStaticText *infoText, ChoiceInfoTexts)
infoText->Wrap (width - Gui->GetCharWidth (this) * 3);
}
void SetPageText (const wxString &text)
{
InfoStaticText->SetLabel (text);
}
void SetSelection (ChoiceType choice)
{
RadioButtonMap[choice]->SetValue (true);
}
protected:
void OnChoiceHyperlinkClick (wxHyperlinkEvent &event)
{
Gui->OpenHomepageLink (this, event.GetURL());
}
bool ChoiceTextBold;
list <wxStaticText*> ChoiceInfoTexts;
map <ChoiceType, wxRadioButton*> RadioButtonMap;
};
}
#endif // TC_HEADER_Main_Forms_SingleChoiceWizardPage

17436
src/Main/Forms/TrueCrypt.fbp Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,183 @@
/*
Copyright (c) 2008-2009 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"
#include "Main/GraphicUserInterface.h"
#include "VolumeCreationProgressWizardPage.h"
namespace TrueCrypt
{
VolumeCreationProgressWizardPage::VolumeCreationProgressWizardPage (wxPanel* parent, bool displayKeyInfo)
: VolumeCreationProgressWizardPageBase (parent),
PreviousGaugeValue (0),
ProgressBarRange (1),
RealProgressBarRange (1),
VolumeCreatorRunning (false)
{
DisplayKeysCheckBox->SetValue (displayKeyInfo);
#ifdef TC_WINDOWS
DisplayKeysCheckBox->SetLabel (L"");
#endif
#ifdef TC_MACOSX
ProgressGauge->SetMinSize (wxSize (-1, 12)); // OS X apparently supports only up to 12px thick progress bars
KeySamplesUpperSizer->Remove (KeySamplesUpperInnerSizer);
#else
ProgressGauge->SetMinSize (wxSize (-1, Gui->GetCharHeight (this) * 2));
#endif
if (DisplayKeysCheckBox->IsChecked())
ShowBytes (RandomPoolSampleStaticText, RandomNumberGenerator::PeekPool(), true);
else
ShowAsterisks (RandomPoolSampleStaticText);
class Timer : public wxTimer
{
public:
Timer (VolumeCreationProgressWizardPage *page) : Page (page) { }
void Notify()
{
Page->OnRandomPoolTimer();
}
VolumeCreationProgressWizardPage *Page;
};
RandomPoolTimer.reset (dynamic_cast <wxTimer *> (new Timer (this)));
RandomPoolTimer->Start (30);
AbortButton->Disable();
ProgressGauge->SetValue (0);
}
void VolumeCreationProgressWizardPage::OnAbortButtonClick (wxCommandEvent& event)
{
AbortEvent.Raise();
}
void VolumeCreationProgressWizardPage::OnDisplayKeysCheckBoxClick (wxCommandEvent& event)
{
if (!event.IsChecked())
{
ShowAsterisks (RandomPoolSampleStaticText);
ShowAsterisks (HeaderKeySampleStaticText);
ShowAsterisks (MasterKeySampleStaticText);
}
else
{
RandomPoolSampleStaticText->SetLabel (L"");
HeaderKeySampleStaticText->SetLabel (L"");
MasterKeySampleStaticText->SetLabel (L"");
}
}
void VolumeCreationProgressWizardPage::OnRandomPoolTimer ()
{
if (!VolumeCreatorRunning && DisplayKeysCheckBox->IsChecked())
ShowBytes (RandomPoolSampleStaticText, RandomNumberGenerator::PeekPool(), true);
}
void VolumeCreationProgressWizardPage::SetKeyInfo (const VolumeCreator::KeyInfo &keyInfo)
{
if (DisplayKeysCheckBox->IsChecked())
{
ShowBytes (RandomPoolSampleStaticText, RandomNumberGenerator::PeekPool(), true);
ShowBytes (HeaderKeySampleStaticText, keyInfo.HeaderKey);
ShowBytes (MasterKeySampleStaticText, keyInfo.MasterKey);
}
}
void VolumeCreationProgressWizardPage::ShowAsterisks (wxStaticText *textCtrl)
{
wxString str;
for (size_t i = 0; i < MaxDisplayedKeyBytes + 1; ++i)
{
str += L"**";
}
textCtrl->SetLabel (str.c_str());
}
void VolumeCreationProgressWizardPage::ShowBytes (wxStaticText *textCtrl, const ConstBufferPtr &buffer, bool appendDots)
{
wxString str;
for (size_t i = 0; i < MaxDisplayedKeyBytes && i < buffer.Size(); ++i)
{
str += wxString::Format (L"%02X", buffer[i]);
}
if (appendDots)
str += L"..";
textCtrl->SetLabel (str.c_str());
for (size_t i = 0; i < str.size(); ++i)
{
str[i] = L'X';
}
}
void VolumeCreationProgressWizardPage::SetProgressValue (uint64 value)
{
int gaugeValue = static_cast <int> (value * RealProgressBarRange / ProgressBarRange);
if (value == ProgressBarRange)
gaugeValue = RealProgressBarRange; // Prevent round-off error
if (gaugeValue != PreviousGaugeValue)
{
ProgressGauge->SetValue (gaugeValue);
PreviousGaugeValue = gaugeValue;
}
if (value != 0)
{
SizeDoneStaticText->SetLabel (wxString::Format (L"%7.3f%%", 100.0 - double (ProgressBarRange - value) / (double (ProgressBarRange) / 100.0)));
wxLongLong timeDiff = wxGetLocalTimeMillis() - StartTime;
if (timeDiff.GetValue() > 0)
{
uint64 speed = value * 1000 / timeDiff.GetValue();
if (ProgressBarRange != value)
SpeedStaticText->SetLabel (Gui->SpeedToString (speed));
TimeLeftStaticText->SetLabel (speed > 0 ? Gui->TimeSpanToString ((ProgressBarRange - value) / speed) : L"");
}
}
else
{
SizeDoneStaticText->SetLabel (L"");
SpeedStaticText->SetLabel (L"");
TimeLeftStaticText->SetLabel (L"");
}
}
void VolumeCreationProgressWizardPage::SetMaxStaticTextWidth (int width)
{
InfoStaticText->Wrap (width);
}
void VolumeCreationProgressWizardPage::SetProgressState (bool volumeCreatorRunning)
{
if (volumeCreatorRunning)
StartTime = wxGetLocalTimeMillis();
VolumeCreatorRunning = volumeCreatorRunning;
}
void VolumeCreationProgressWizardPage::SetProgressRange (uint64 progressBarRange)
{
ProgressBarRange = progressBarRange;
RealProgressBarRange = ProgressGauge->GetSize().GetWidth();
ProgressGauge->SetRange (RealProgressBarRange);
}
}

View File

@@ -0,0 +1,53 @@
/*
Copyright (c) 2008 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.
*/
#ifndef TC_HEADER_Main_Forms_VolumeCreationProgressWizardPage
#define TC_HEADER_Main_Forms_VolumeCreationProgressWizardPage
#include "Forms.h"
#include "Core/VolumeCreator.h"
namespace TrueCrypt
{
class VolumeCreationProgressWizardPage : public VolumeCreationProgressWizardPageBase
{
public:
VolumeCreationProgressWizardPage (wxPanel* parent, bool displayKeyInfo);
~VolumeCreationProgressWizardPage () { }
void EnableAbort (bool enable = true) { AbortButton->Enable (enable); }
bool IsKeyInfoDisplayed () const { return DisplayKeysCheckBox->GetValue(); }
bool IsValid () { return true; }
void OnRandomPoolTimer ();
void SetKeyInfo (const VolumeCreator::KeyInfo &keyInfo);
void SetMaxStaticTextWidth (int width);
void SetPageText (const wxString &text) { InfoStaticText->SetLabel (text); }
void SetProgressRange (uint64 progressBarRange);
void SetProgressValue (uint64 value);
void SetProgressState (bool volumeCreatorRunning);
Event AbortEvent;
protected:
void OnAbortButtonClick (wxCommandEvent& event);
void OnDisplayKeysCheckBoxClick (wxCommandEvent& event);
void ShowAsterisks (wxStaticText *textCtrl);
void ShowBytes (wxStaticText *textCtrl, const ConstBufferPtr &buffer, bool appendDots = true);
static const size_t MaxDisplayedKeyBytes = 13;
int PreviousGaugeValue;
uint64 ProgressBarRange;
auto_ptr <wxTimer> RandomPoolTimer;
int RealProgressBarRange;
wxLongLong StartTime;
bool VolumeCreatorRunning;
};
}
#endif // TC_HEADER_Main_Forms_VolumeCreationProgressWizardPage

View File

@@ -0,0 +1,984 @@
/*
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"
#include "Platform/SystemInfo.h"
#ifdef TC_UNIX
#include <unistd.h>
#include "Platform/Unix/Process.h"
#endif
#include "Core/RandomNumberGenerator.h"
#include "Core/VolumeCreator.h"
#include "Main/Application.h"
#include "Main/GraphicUserInterface.h"
#include "Main/Resources.h"
#include "VolumeCreationWizard.h"
#include "EncryptionOptionsWizardPage.h"
#include "InfoWizardPage.h"
#include "ProgressWizardPage.h"
#include "SingleChoiceWizardPage.h"
#include "VolumeCreationProgressWizardPage.h"
#include "VolumeFormatOptionsWizardPage.h"
#include "VolumeLocationWizardPage.h"
#include "VolumePasswordWizardPage.h"
#include "VolumeSizeWizardPage.h"
namespace TrueCrypt
{
VolumeCreationWizard::VolumeCreationWizard (wxWindow* parent)
: WizardFrame (parent),
CrossPlatformSupport (true),
DisplayKeyInfo (true),
LargeFilesSupport (false),
QuickFormatEnabled (false),
SelectedFilesystemClusterSize (0),
SelectedFilesystemType (VolumeCreationOptions::FilesystemType::FAT),
SelectedVolumeHostType (VolumeHostType::File),
SelectedVolumeType (VolumeType::Normal),
SectorSize (0),
VolumeSize (0)
{
RandomNumberGenerator::Start();
SetTitle (LangString["INTRO_TITLE"]);
SetImage (Resources::GetVolumeCreationWizardBitmap (Gui->GetCharHeight (this) * 21));
SetMaxStaticTextWidth (55);
SetStep (Step::VolumeHostType);
class Timer : public wxTimer
{
public:
Timer (VolumeCreationWizard *wizard) : Wizard (wizard) { }
void Notify()
{
Wizard->OnRandomPoolUpdateTimer();
}
VolumeCreationWizard *Wizard;
};
RandomPoolUpdateTimer.reset (dynamic_cast <wxTimer *> (new Timer (this)));
RandomPoolUpdateTimer->Start (200);
}
VolumeCreationWizard::~VolumeCreationWizard ()
{
}
WizardPage *VolumeCreationWizard::GetPage (WizardStep step)
{
switch (step)
{
case Step::VolumeHostType:
{
ClearHistory();
OuterVolume = false;
LargeFilesSupport = false;
QuickFormatEnabled = false;
SingleChoiceWizardPage <VolumeHostType::Enum> *page = new SingleChoiceWizardPage <VolumeHostType::Enum> (GetPageParent(), wxEmptyString, true);
page->SetMinSize (wxSize (Gui->GetCharWidth (this) * 58, Gui->GetCharHeight (this) * 18 + 5));
page->SetPageTitle (LangString["INTRO_TITLE"]);
page->AddChoice (VolumeHostType::File, LangString["IDC_FILE_CONTAINER"], LangString["IDT_FILE_CONTAINER"], L"introcontainer", LangString["IDC_MORE_INFO_ON_CONTAINERS"]);
page->AddChoice (VolumeHostType::Device, _("Create a volume within a partition/&drive"), _("Formats and encrypts a non-system partition, entire external or secondary drive, entire USB stick, etc."));
page->SetSelection (SelectedVolumeHostType);
return page;
}
case Step::VolumeType:
{
SingleChoiceWizardPage <VolumeType::Enum> *page = new SingleChoiceWizardPage <VolumeType::Enum> (GetPageParent(), wxEmptyString, true);
page->SetPageTitle (LangString["VOLUME_TYPE_TITLE"]);
page->AddChoice (VolumeType::Normal, LangString["IDC_STD_VOL"], LangString["NORMAL_VOLUME_TYPE_HELP"]);
page->AddChoice (VolumeType::Hidden, LangString["IDC_HIDDEN_VOL"], LangString["HIDDEN_VOLUME_TYPE_HELP"], L"hiddenvolume", LangString["IDC_HIDDEN_VOL_HELP"]);
page->SetSelection (SelectedVolumeType);
return page;
}
case Step::VolumeLocation:
{
VolumeLocationWizardPage *page = new VolumeLocationWizardPage (GetPageParent(), SelectedVolumeHostType);
page->SetPageTitle (LangString["VOLUME_LOCATION"]);
if (SelectedVolumeType == VolumeType::Hidden)
page->SetPageText (LangString[SelectedVolumeHostType == VolumeHostType::File ? "FILE_HELP_HIDDEN_HOST_VOL" : "DEVICE_HELP_HIDDEN_HOST_VOL"]);
else
page->SetPageText (LangString[SelectedVolumeHostType == VolumeHostType::File ? "FILE_HELP" : "DEVICE_HELP_NO_INPLACE"]);
page->SetVolumePath (SelectedVolumePath);
return page;
}
case Step::EncryptionOptions:
{
EncryptionOptionsWizardPage *page = new EncryptionOptionsWizardPage (GetPageParent());
if (OuterVolume)
page->SetPageTitle (LangString["CIPHER_HIDVOL_HOST_TITLE"]);
else if (SelectedVolumeType == VolumeType::Hidden)
page->SetPageTitle (LangString["CIPHER_HIDVOL_TITLE"]);
else
page->SetPageTitle (LangString["CIPHER_TITLE"]);
page->SetEncryptionAlgorithm (SelectedEncryptionAlgorithm);
page->SetHash (SelectedHash);
return page;
}
case Step::VolumeSize:
{
wxString freeSpaceText;
wxString pageTitle;
wxString pageText;
if (OuterVolume)
{
pageTitle = LangString["SIZE_HIDVOL_HOST_TITLE"];
pageText = LangString["SIZE_HELP_HIDDEN_HOST_VOL"];
}
else if (SelectedVolumeType == VolumeType::Hidden)
{
pageTitle = LangString["SIZE_HIDVOL_TITLE"];
pageText = LangString["SIZE_HELP_HIDDEN_VOL"] + L"\n\n" + _("Please note that if your operating system does not allocate files from the beginning of the free space, the maximum possible hidden volume size may be much smaller than the size of the free space on the outer volume. This not a bug in TrueCrypt but a limitation of the operating system.");
freeSpaceText = StringFormatter (_("Maximum possible hidden volume size for this volume is {0}."), Gui->SizeToString (MaxHiddenVolumeSize));
}
else
{
pageTitle = LangString["SIZE_TITLE"];
pageText = LangString["VOLUME_SIZE_HELP"];
}
VolumeSizeWizardPage *page = new VolumeSizeWizardPage (GetPageParent(), SelectedVolumePath, SectorSize, freeSpaceText);
page->SetPageTitle (pageTitle);
page->SetPageText (pageText);
if (!OuterVolume && SelectedVolumeType == VolumeType::Hidden)
page->SetMaxVolumeSize (MaxHiddenVolumeSize);
else
page->SetVolumeSize (VolumeSize);
if (OuterVolume)
page->SetMinVolumeSize (TC_MIN_HIDDEN_VOLUME_HOST_SIZE);
else if (SelectedVolumeType == VolumeType::Hidden)
page->SetMinVolumeSize (TC_MIN_HIDDEN_VOLUME_SIZE);
else
page->SetMinVolumeSize (TC_MIN_VOLUME_SIZE);
return page;
}
case Step::VolumePassword:
{
VolumePasswordWizardPage *page = new VolumePasswordWizardPage (GetPageParent(), Password, Keyfiles);
if (OuterVolume)
page->SetPageTitle (LangString["PASSWORD_HIDVOL_HOST_TITLE"]);
else if (SelectedVolumeType == VolumeType::Hidden)
page->SetPageTitle (LangString["PASSWORD_HIDVOL_TITLE"]);
else
page->SetPageTitle (LangString["PASSWORD_TITLE"]);
page->SetPageText (LangString[OuterVolume ? "PASSWORD_HIDDENVOL_HOST_HELP" : "PASSWORD_HELP"]);
return page;
}
case Step::LargeFilesSupport:
{
SingleChoiceWizardPage <bool> *page = new SingleChoiceWizardPage <bool> (GetPageParent(), wxEmptyString, true);
page->SetPageTitle (LangString["FILESYS_PAGE_TITLE"]);
page->AddChoice (false, _("I will not store files larger than 4 GB on the volume"),
_("Choose this option if you do not need to store files larger than 4 GB (4,294,967,296 bytes) on the volume."));
page->AddChoice (true, _("I will store files larger than 4 GB on the volume"),
_("Choose this option if you need to store files larger than 4 GB (4,294,967,296 bytes) on the volume."));
page->SetSelection (LargeFilesSupport);
return page;
}
case Step::FormatOptions:
{
VolumeFormatOptionsWizardPage *page = new VolumeFormatOptionsWizardPage (GetPageParent(), VolumeSize, SectorSize,
SelectedVolumePath.IsDevice() && (OuterVolume || SelectedVolumeType != VolumeType::Hidden), OuterVolume, LargeFilesSupport);
page->SetPageTitle (_("Format Options"));
page->SetFilesystemType (SelectedFilesystemType);
if (!OuterVolume && SelectedVolumeType == VolumeType::Hidden)
QuickFormatEnabled = true;
page->SetQuickFormat (QuickFormatEnabled);
return page;
}
case Step::CrossPlatformSupport:
{
SingleChoiceWizardPage <bool> *page = new SingleChoiceWizardPage <bool> (GetPageParent(), wxEmptyString, true);
page->SetPageTitle (_("Cross-Platform Support"));
page->AddChoice (true, _("I will mount the volume on other platforms"),
_("Choose this option if you need to use the volume on other platforms."));
page->AddChoice (false, StringFormatter (_("I will mount the volume only on {0}"), SystemInfo::GetPlatformName()),
_("Choose this option if you do not need to use the volume on other platforms."));
page->SetSelection (CrossPlatformSupport);
return page;
}
case Step::CreationProgress:
{
VolumeCreationProgressWizardPage *page = new VolumeCreationProgressWizardPage (GetPageParent(), DisplayKeyInfo);
if (OuterVolume)
page->SetPageTitle (LangString["FORMAT_HIDVOL_HOST_TITLE"]);
else if (SelectedVolumeType == VolumeType::Hidden)
page->SetPageTitle (LangString["FORMAT_HIDVOL_TITLE"]);
else
page->SetPageTitle (LangString["FORMAT_TITLE"]);
page->SetPageText (LangString["FORMAT_HELP"]);
page->AbortEvent.Connect (EventConnector <VolumeCreationWizard> (this, &VolumeCreationWizard::OnAbortButtonClick));
page->SetNextButtonText (LangString["FORMAT"]);
return page;
}
case Step::VolumeCreatedInfo:
{
InfoWizardPage *page = new InfoWizardPage (GetPageParent());
page->SetPageTitle (LangString["FORMAT_FINISHED_TITLE"]);
page->SetPageText (LangString["FORMAT_FINISHED_HELP"]);
SetCancelButtonText (_("Exit"));
return page;
}
case Step::OuterVolumeContents:
{
ClearHistory();
MountOptions mountOptions;
mountOptions.Keyfiles = Keyfiles;
mountOptions.Password = Password;
mountOptions.Path = make_shared <VolumePath> (SelectedVolumePath);
try
{
wxBusyCursor busy;
Gui->SetActiveFrame (this);
MountedOuterVolume = Core->MountVolume (mountOptions);
}
catch (exception &e)
{
Gui->SetActiveFrame (this);
Gui->ShowError (e);
Close();
return new InfoWizardPage (GetPageParent());
}
struct OpenOuterVolumeFunctor : public Functor
{
OpenOuterVolumeFunctor (const DirectoryPath &outerVolumeMountPoint) : OuterVolumeMountPoint (outerVolumeMountPoint) { }
virtual void operator() ()
{
Gui->OpenExplorerWindow (OuterVolumeMountPoint);
}
DirectoryPath OuterVolumeMountPoint;
};
InfoWizardPage *page = new InfoWizardPage (GetPageParent(), _("Open Outer Volume"),
shared_ptr <Functor> (new OpenOuterVolumeFunctor (MountedOuterVolume->MountPoint)));
page->SetPageTitle (LangString["HIDVOL_HOST_FILLING_TITLE"]);
page->SetPageText (StringFormatter (
_("Outer volume has been successfully created and mounted as '{0}'. To this volume you should now copy some sensitive-looking files that you actually do NOT want to hide. The files will be there for anyone forcing you to disclose your password. You will reveal only the password for this outer volume, not for the hidden one. The files that you really care about will be stored in the hidden volume, which will be created later on. When you finish copying, click Next. Do not dismount the volume.\n\nNote: After you click Next, the outer volume will be analyzed to determine the size of uninterrupted area of free space whose end is aligned with the end of the volume. This area will accommodate the hidden volume, so it will limit its maximum possible size. The procedure ensures no data on the outer volume are overwritten by the hidden volume."),
wstring (MountedOuterVolume->MountPoint)));
return page;
}
case Step::HiddenVolume:
{
ClearHistory();
OuterVolume = false;
LargeFilesSupport = false;
InfoWizardPage *page = new InfoWizardPage (GetPageParent());
page->SetPageTitle (LangString["HIDVOL_PRE_CIPHER_TITLE"]);
page->SetPageText (LangString["HIDVOL_PRE_CIPHER_HELP"]);
return page;
}
default:
throw ParameterIncorrect (SRC_POS);
}
}
void VolumeCreationWizard::OnAbortButtonClick (EventArgs &args)
{
AbortRequested = true;
}
void VolumeCreationWizard::OnMouseMotion (wxMouseEvent& event)
{
event.Skip();
if (!IsWorkInProgress() && RandomNumberGenerator::IsRunning())
{
RandomNumberGenerator::AddToPool (ConstBufferPtr (reinterpret_cast <byte *> (&event), sizeof (event)));
long coord = event.GetX();
RandomNumberGenerator::AddToPool (ConstBufferPtr (reinterpret_cast <byte *> (&coord), sizeof (coord)));
coord = event.GetY();
RandomNumberGenerator::AddToPool (ConstBufferPtr (reinterpret_cast <byte *> (&coord), sizeof (coord)));
}
}
void VolumeCreationWizard::OnProgressTimer ()
{
if (!IsWorkInProgress())
return;
if (AbortRequested && !AbortConfirmationPending)
{
AbortConfirmationPending = true;
if (Gui->AskYesNo (LangString ["FORMAT_ABORT"], true))
{
if (IsWorkInProgress() && Creator.get() != nullptr)
{
CreationAborted = true;
Creator->Abort();
}
}
AbortRequested = false;
AbortConfirmationPending = false;
}
VolumeCreator::ProgressInfo progress = Creator->GetProgressInfo();
VolumeCreationProgressWizardPage *page = dynamic_cast <VolumeCreationProgressWizardPage *> (GetCurrentPage());
page->SetProgressValue (progress.SizeDone);
if (!progress.CreationInProgress && !AbortConfirmationPending)
{
SetWorkInProgress (false);
OnVolumeCreatorFinished ();
}
}
void VolumeCreationWizard::OnRandomPoolUpdateTimer ()
{
if (!IsWorkInProgress())
{
wxLongLong time = wxGetLocalTimeMillis();
RandomNumberGenerator::AddToPool (ConstBufferPtr (reinterpret_cast <byte *> (&time), sizeof (time)));
}
}
void VolumeCreationWizard::OnVolumeCreatorFinished ()
{
VolumeCreationProgressWizardPage *page = dynamic_cast <VolumeCreationProgressWizardPage *> (GetCurrentPage());
ProgressTimer.reset();
page->SetProgressState (false);
Gui->EndInteractiveBusyState (this);
SetWorkInProgress (false);
UpdateControls();
try
{
if (!CreationAborted)
{
Creator->CheckResult();
#ifdef TC_UNIX
// Format non-FAT filesystem
const char *fsFormatter = nullptr;
switch (SelectedFilesystemType)
{
case VolumeCreationOptions::FilesystemType::Ext2: fsFormatter = "mkfs.ext2"; break;
case VolumeCreationOptions::FilesystemType::Ext3: fsFormatter = "mkfs.ext3"; break;
case VolumeCreationOptions::FilesystemType::Ext4: fsFormatter = "mkfs.ext4"; break;
case VolumeCreationOptions::FilesystemType::MacOsExt: fsFormatter = "newfs_hfs"; break;
case VolumeCreationOptions::FilesystemType::UFS: fsFormatter = "newfs" ; break;
default: break;
}
if (fsFormatter)
{
wxBusyCursor busy;
MountOptions mountOptions (Gui->GetPreferences().DefaultMountOptions);
mountOptions.Path = make_shared <VolumePath> (SelectedVolumePath);
mountOptions.NoFilesystem = true;
mountOptions.Protection = VolumeProtection::None;
mountOptions.Password = Password;
mountOptions.Keyfiles = Keyfiles;
shared_ptr <VolumeInfo> volume = Core->MountVolume (mountOptions);
finally_do_arg (shared_ptr <VolumeInfo>, volume, { Core->DismountVolume (finally_arg, true); });
Thread::Sleep (2000); // Try to prevent race conditions caused by OS
// Temporarily take ownership of the device if the user is not an administrator
UserId origDeviceOwner ((uid_t) -1);
DevicePath virtualDevice = volume->VirtualDevice;
#ifdef TC_MACOSX
string virtualDeviceStr = virtualDevice;
if (virtualDeviceStr.find ("/dev/rdisk") != 0)
virtualDevice = "/dev/r" + virtualDeviceStr.substr (5);
#endif
try
{
File file;
file.Open (virtualDevice, File::OpenReadWrite);
}
catch (...)
{
if (!Core->HasAdminPrivileges())
{
origDeviceOwner = virtualDevice.GetOwner();
Core->SetFileOwner (virtualDevice, UserId (getuid()));
}
}
finally_do_arg2 (FilesystemPath, virtualDevice, UserId, origDeviceOwner,
{
if (finally_arg2.SystemId != (uid_t) -1)
Core->SetFileOwner (finally_arg, finally_arg2);
});
// Create filesystem
list <string> args;
if (SelectedFilesystemType == VolumeCreationOptions::FilesystemType::MacOsExt && VolumeSize >= 10 * BYTES_PER_MB)
args.push_back ("-J");
args.push_back (string (virtualDevice));
Process::Execute (fsFormatter, args);
}
#endif // TC_UNIX
if (OuterVolume)
{
SetStep (Step::OuterVolumeContents);
}
else
{
Gui->ShowInfo (SelectedVolumeType == VolumeType::Hidden ? "HIDVOL_FORMAT_FINISHED_HELP" : "FORMAT_FINISHED_INFO");
SetStep (Step::VolumeCreatedInfo);
}
return;
}
}
catch (exception &e)
{
Gui->ShowError (e);
}
page->SetProgressValue (0);
if (SelectedVolumeType == VolumeType::Normal && !SelectedVolumePath.IsDevice())
{
try
{
FilePath (wstring (SelectedVolumePath)).Delete();
}
catch (...) { }
}
}
WizardFrame::WizardStep VolumeCreationWizard::ProcessPageChangeRequest (bool forward)
{
switch (GetCurrentStep())
{
case Step::VolumeHostType:
{
SingleChoiceWizardPage <VolumeHostType::Enum> *page = dynamic_cast <SingleChoiceWizardPage <VolumeHostType::Enum> *> (GetCurrentPage());
try
{
SelectedVolumeHostType = page->GetSelection();
}
catch (NoItemSelected &)
{
return GetCurrentStep();
}
return Step::VolumeType;
}
case Step::VolumeType:
{
SingleChoiceWizardPage <VolumeType::Enum> *page = dynamic_cast <SingleChoiceWizardPage <VolumeType::Enum> *> (GetCurrentPage());
try
{
SelectedVolumeType = page->GetSelection();
}
catch (NoItemSelected &)
{
return GetCurrentStep();
}
if (SelectedVolumeType == VolumeType::Hidden)
OuterVolume = true;
return Step::VolumeLocation;
}
case Step::VolumeLocation:
{
VolumeLocationWizardPage *page = dynamic_cast <VolumeLocationWizardPage *> (GetCurrentPage());
SelectedVolumePath = page->GetVolumePath();
VolumeSize = 0;
if (forward)
{
if (Core->IsVolumeMounted (SelectedVolumePath))
{
Gui->ShowInfo ("DISMOUNT_FIRST");
return GetCurrentStep();
}
if (SelectedVolumePath.IsDevice())
{
if (!DeviceWarningConfirmed && !Gui->AskYesNo (LangString["FORMAT_DEVICE_FOR_ADVANCED_ONLY"]))
return GetCurrentStep();
DeviceWarningConfirmed = true;
foreach_ref (const HostDevice &drive, Core->GetHostDevices())
{
if (drive.Path == SelectedVolumePath && !drive.Partitions.empty())
{
foreach_ref (const HostDevice &partition, drive.Partitions)
{
if (partition.MountPoint == "/")
{
Gui->ShowError (_("Error: You are trying to encrypt a system drive.\n\nTrueCrypt can encrypt a system drive only under Windows."));
return GetCurrentStep();
}
}
Gui->ShowError ("DEVICE_PARTITIONS_ERR");
return GetCurrentStep();
}
}
try
{
SectorSize = Core->GetDeviceSectorSize (SelectedVolumePath);
VolumeSize = Core->GetDeviceSize (SelectedVolumePath);
}
catch (UserAbort&)
{
return Step::VolumeLocation;
}
catch (exception &e)
{
Gui->ShowError (e);
Gui->ShowError ("CANNOT_CALC_SPACE");
return GetCurrentStep();
}
DirectoryPath mountPoint;
try
{
mountPoint = Core->GetDeviceMountPoint (SelectedVolumePath);
if (!mountPoint.IsEmpty())
{
if (mountPoint == "/")
{
Gui->ShowError (_("Error: You are trying to encrypt a system partition.\n\nTrueCrypt can encrypt system partitions only under Windows."));
return GetCurrentStep();
}
if (!Gui->AskYesNo (StringFormatter (_("WARNING: Formatting of the device will destroy all data on filesystem '{0}'.\n\nDo you want to continue?"), wstring (mountPoint)), false, true))
return GetCurrentStep();
try
{
Core->DismountFilesystem (mountPoint, true);
}
catch (exception &e)
{
Gui->ShowError (e);
Gui->ShowError (StringFormatter (_("The filesystem of the selected device is currently mounted. Please dismount '{0}' before proceeding."), wstring (mountPoint)));
return GetCurrentStep();
}
}
}
catch (...) { }
}
else
SectorSize = TC_SECTOR_SIZE_FILE_HOSTED_VOLUME;
}
return Step::EncryptionOptions;
}
case Step::EncryptionOptions:
{
EncryptionOptionsWizardPage *page = dynamic_cast <EncryptionOptionsWizardPage *> (GetCurrentPage());
SelectedEncryptionAlgorithm = page->GetEncryptionAlgorithm ();
SelectedHash = page->GetHash ();
if (forward)
RandomNumberGenerator::SetHash (SelectedHash);
if (SelectedVolumePath.IsDevice() && (OuterVolume || SelectedVolumeType != VolumeType::Hidden))
return Step::VolumePassword;
else
return Step::VolumeSize;
}
case Step::VolumeSize:
{
VolumeSizeWizardPage *page = dynamic_cast <VolumeSizeWizardPage *> (GetCurrentPage());
try
{
VolumeSize = page->GetVolumeSize();
}
catch (Exception &e)
{
if (forward)
{
Gui->ShowError (e);
return GetCurrentStep();
}
}
if (forward
&& !OuterVolume && SelectedVolumeType == VolumeType::Hidden
&& (double) VolumeSize / MaxHiddenVolumeSize > 0.85)
{
if (!Gui->AskYesNo (LangString["FREE_SPACE_FOR_WRITING_TO_OUTER_VOLUME"]))
return GetCurrentStep();
}
if (forward
&& SelectedVolumeHostType == VolumeHostType::File
&& VolumeSize > 4 * BYTES_PER_GB
&& (OuterVolume || SelectedVolumeType != VolumeType::Hidden)
&& !Core->FilesystemSupportsLargeFiles (SelectedVolumePath))
{
Gui->ShowWarning (LangString["VOLUME_TOO_LARGE_FOR_FAT32"]);
}
return Step::VolumePassword;
}
case Step::VolumePassword:
{
VolumePasswordWizardPage *page = dynamic_cast <VolumePasswordWizardPage *> (GetCurrentPage());
Password = page->GetPassword();
Keyfiles = page->GetKeyfiles();
if (forward && Password && !Password->IsEmpty())
{
try
{
Password->CheckPortability();
}
catch (UnportablePassword &e)
{
Gui->ShowError (e);
return GetCurrentStep();
}
if (Password->Size() < VolumePassword::WarningSizeThreshold
&& !Gui->AskYesNo (LangString["PASSWORD_LENGTH_WARNING"], false, true))
{
return GetCurrentStep();
}
}
if (forward && OuterVolume)
{
// Use FAT to prevent problems with free space
QuickFormatEnabled = false;
SelectedFilesystemType = VolumeCreationOptions::FilesystemType::FAT;
return Step::CreationProgress;
}
if (VolumeSize > 4 * BYTES_PER_GB)
{
if (VolumeSize <= TC_MAX_FAT_SECTOR_COUNT * SectorSize)
return Step::LargeFilesSupport;
else
SelectedFilesystemType = VolumeCreationOptions::FilesystemType::GetPlatformNative();
}
return Step::FormatOptions;
}
case Step::LargeFilesSupport:
{
SingleChoiceWizardPage <bool> *page = dynamic_cast <SingleChoiceWizardPage <bool> *> (GetCurrentPage());
try
{
LargeFilesSupport = page->GetSelection();
}
catch (NoItemSelected &)
{
return GetCurrentStep();
}
if (LargeFilesSupport)
SelectedFilesystemType = VolumeCreationOptions::FilesystemType::GetPlatformNative();
else
SelectedFilesystemType = VolumeCreationOptions::FilesystemType::FAT;
return Step::FormatOptions;
}
case Step::FormatOptions:
{
VolumeFormatOptionsWizardPage *page = dynamic_cast <VolumeFormatOptionsWizardPage *> (GetCurrentPage());
SelectedFilesystemType = page->GetFilesystemType();
QuickFormatEnabled = page->IsQuickFormatEnabled();
if (SelectedFilesystemType != VolumeCreationOptions::FilesystemType::None
&& SelectedFilesystemType != VolumeCreationOptions::FilesystemType::FAT)
return Step::CrossPlatformSupport;
return Step::CreationProgress;
}
case Step::CrossPlatformSupport:
{
SingleChoiceWizardPage <bool> *page = dynamic_cast <SingleChoiceWizardPage <bool> *> (GetCurrentPage());
try
{
CrossPlatformSupport = page->GetSelection();
}
catch (NoItemSelected &)
{
return GetCurrentStep();
}
if (forward && CrossPlatformSupport)
Gui->ShowWarning (StringFormatter (_("Please note that the volume will not be formatted with a FAT filesystem and, therefore, you may be required to install additional filesystem drivers on platforms other than {0}, which will enable you to mount the volume."), SystemInfo::GetPlatformName()));
return Step::CreationProgress;
}
case Step::CreationProgress:
{
VolumeCreationProgressWizardPage *page = dynamic_cast <VolumeCreationProgressWizardPage *> (GetCurrentPage());
DisplayKeyInfo = page->IsKeyInfoDisplayed();
if (forward)
{
if (SelectedVolumeType != VolumeType::Hidden || OuterVolume)
{
if (OuterVolume && VolumeSize > TC_MAX_FAT_SECTOR_COUNT * SectorSize)
{
uint64 limit = TC_MAX_FAT_SECTOR_COUNT * SectorSize / BYTES_PER_TB;
wstring err = StringFormatter (_("Error: The hidden volume to be created is larger than {0} TB ({1} GB).\n\nPossible solutions:\n- Create a container/partition smaller than {0} TB.\n"), limit, limit * 1024);
if (SectorSize < 4096)
{
err += _("- Use a drive with 4096-byte sectors to be able to create partition/device-hosted hidden volumes up to 16 TB in size");
#if defined (TC_LINUX)
err += _(".\n");
#else
err += _(" (not supported by components available on this platform).\n");
#endif
}
Gui->ShowError (err);
return GetCurrentStep();
}
if (SelectedVolumePath.IsDevice())
{
wxString confirmMsg = LangString["OVERWRITEPROMPT_DEVICE"];
confirmMsg.Replace (L"%hs", L"%s");
if (!Gui->AskYesNo (wxString::Format (confirmMsg, wxString (_("DEVICE")).c_str(), wstring (SelectedVolumePath).c_str(), L""), false, true))
return GetCurrentStep();
}
else if (FilesystemPath (wstring (SelectedVolumePath)).IsFile())
{
wxString confirmMsg = LangString["OVERWRITEPROMPT"];
confirmMsg.Replace (L"%hs", L"%s");
if (!Gui->AskYesNo (wxString::Format (confirmMsg, wstring (SelectedVolumePath).c_str(), false, true)))
return GetCurrentStep();
}
}
AbortRequested = false;
AbortConfirmationPending = false;
CreationAborted = false;
SetWorkInProgress (true);
UpdateControls();
Gui->BeginInteractiveBusyState (this);
try
{
make_shared_auto (VolumeCreationOptions, options);
options->Filesystem = SelectedFilesystemType;
options->FilesystemClusterSize = SelectedFilesystemClusterSize;
options->SectorSize = SectorSize;
options->EA = SelectedEncryptionAlgorithm;
options->Password = Password;
options->Keyfiles = Keyfiles;
options->Path = SelectedVolumePath;
options->Quick = QuickFormatEnabled;
options->Size = VolumeSize;
options->Type = OuterVolume ? VolumeType::Normal : SelectedVolumeType;
options->VolumeHeaderKdf = Pkcs5Kdf::GetAlgorithm (*SelectedHash);
Creator.reset (new VolumeCreator);
Creator->CreateVolume (options);
page->SetKeyInfo (Creator->GetKeyInfo());
class Timer : public wxTimer
{
public:
Timer (VolumeCreationWizard *wizard) : Wizard (wizard) { }
void Notify()
{
Wizard->OnProgressTimer();
}
VolumeCreationWizard *Wizard;
};
page->SetProgressRange (options->Size);
page->SetProgressState (true);
ProgressTimer.reset (dynamic_cast <wxTimer *> (new Timer (this)));
ProgressTimer->Start (50);
}
catch (Exception &e)
{
CreationAborted = true;
OnVolumeCreatorFinished();
Gui->ShowError (e);
}
}
return GetCurrentStep();
}
case Step::VolumeCreatedInfo:
Creator.reset();
SetCancelButtonText (L"");
return Step::VolumeHostType;
case Step::OuterVolumeContents:
try
{
// Determine maximum size of the hidden volume. Scan cluster table offline as a live filesystem test would
// require using FUSE and loop device which cannot be used for devices with sectors larger than 512.
wxBusyCursor busy;
MaxHiddenVolumeSize = 0;
Gui->SetActiveFrame (this);
if (MountedOuterVolume)
{
Core->DismountVolume (MountedOuterVolume);
MountedOuterVolume.reset();
}
#ifdef TC_UNIX
// Temporarily take ownership of a device if the user is not an administrator
UserId origDeviceOwner ((uid_t) -1);
if (!Core->HasAdminPrivileges() && SelectedVolumePath.IsDevice())
{
origDeviceOwner = FilesystemPath (wstring (SelectedVolumePath)).GetOwner();
Core->SetFileOwner (SelectedVolumePath, UserId (getuid()));
}
finally_do_arg2 (FilesystemPath, SelectedVolumePath, UserId, origDeviceOwner,
{
if (finally_arg2.SystemId != (uid_t) -1)
Core->SetFileOwner (finally_arg, finally_arg2);
});
#endif
shared_ptr <Volume> outerVolume = Core->OpenVolume (make_shared <VolumePath> (SelectedVolumePath), true, Password, Keyfiles, VolumeProtection::ReadOnly);
MaxHiddenVolumeSize = Core->GetMaxHiddenVolumeSize (outerVolume);
// Add a reserve (in case the user mounts the outer volume and creates new files
// on it by accident or OS writes some new data behind his or her back, such as
// System Restore etc.)
uint64 reservedSize = outerVolume->GetSize() / 200;
if (reservedSize > 10 * BYTES_PER_MB)
reservedSize = 10 * BYTES_PER_MB;
if (MaxHiddenVolumeSize < reservedSize)
MaxHiddenVolumeSize = 0;
else
MaxHiddenVolumeSize -= reservedSize;
MaxHiddenVolumeSize -= MaxHiddenVolumeSize % outerVolume->GetSectorSize(); // Must be a multiple of the sector size
}
catch (exception &e)
{
Gui->SetActiveFrame (this);
Gui->ShowError (e);
return GetCurrentStep();
}
return Step::HiddenVolume;
case Step::HiddenVolume:
return Step::EncryptionOptions;
default:
throw ParameterIncorrect (SRC_POS);
}
}
void VolumeCreationWizard::UpdateControls ()
{
VolumeCreationProgressWizardPage *page = dynamic_cast <VolumeCreationProgressWizardPage *> (GetCurrentPage());
if (page)
{
page->EnableAbort (IsWorkInProgress());
}
}
bool VolumeCreationWizard::DeviceWarningConfirmed;
}

View File

@@ -0,0 +1,85 @@
/*
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.
*/
#ifndef TC_HEADER_Main_Forms_VolumeCreationWizard
#define TC_HEADER_Main_Forms_VolumeCreationWizard
#include "WizardFrame.h"
#include "Core/VolumeCreator.h"
namespace TrueCrypt
{
class VolumeCreationWizard : public WizardFrame
{
public:
VolumeCreationWizard (wxWindow* parent);
~VolumeCreationWizard ();
protected:
struct Step
{
enum Enum
{
VolumeHostType,
VolumeType,
VolumeLocation,
EncryptionOptions,
VolumeSize,
VolumePassword,
LargeFilesSupport,
FormatOptions,
CrossPlatformSupport,
CreationProgress,
VolumeCreatedInfo,
OuterVolumeContents,
HiddenVolume
};
};
void CreateVolume ();
WizardPage *GetPage (WizardStep step);
void OnAbortButtonClick (EventArgs &args);
void OnMouseMotion (wxMouseEvent& event);
void OnProgressTimer ();
void OnRandomPoolUpdateTimer ();
void OnThreadExiting (wxCommandEvent& event);
void OnVolumeCreatorFinished ();
WizardStep ProcessPageChangeRequest (bool forward);
volatile bool AbortConfirmationPending;
volatile bool AbortRequested;
volatile bool CreationAborted;
auto_ptr <VolumeCreator> Creator;
bool CrossPlatformSupport;
static bool DeviceWarningConfirmed;
bool DisplayKeyInfo;
auto_ptr <wxTimer> ProgressTimer;
auto_ptr <wxTimer> RandomPoolUpdateTimer;
shared_ptr <KeyfileList> Keyfiles;
bool LargeFilesSupport;
uint64 MaxHiddenVolumeSize;
shared_ptr <VolumeInfo> MountedOuterVolume;
bool OuterVolume;
bool QuickFormatEnabled;
shared_ptr <EncryptionAlgorithm> SelectedEncryptionAlgorithm;
uint32 SelectedFilesystemClusterSize;
VolumeCreationOptions::FilesystemType::Enum SelectedFilesystemType;
VolumePath SelectedVolumePath;
VolumeHostType::Enum SelectedVolumeHostType;
VolumeType::Enum SelectedVolumeType;
shared_ptr <VolumePassword> Password;
uint32 SectorSize;
shared_ptr <Hash> SelectedHash;
uint64 VolumeSize;
private:
void UpdateControls ();
};
}
#endif // TC_HEADER_Main_Forms_VolumeCreationWizard

View File

@@ -0,0 +1,81 @@
/*
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"
#include "Main/GraphicUserInterface.h"
#include "VolumeFormatOptionsWizardPage.h"
namespace TrueCrypt
{
VolumeFormatOptionsWizardPage::VolumeFormatOptionsWizardPage (wxPanel* parent, uint64 volumeSize, uint32 sectorSize, bool enableQuickFormatButton, bool disableNoneFilesystem, bool disable32bitFilesystems)
: VolumeFormatOptionsWizardPageBase (parent)
{
InfoStaticText->SetLabel (_(
"In order to enable your operating system to mount your new volume, it has to be formatted with a filesystem. Please select a filesystem type.\n\nIf your volume is going to be hosted on a device or partition, you can use 'Quick format' to skip encryption of free space of the volume."));
if (!disableNoneFilesystem)
FilesystemTypeChoice->Append (LangString["NONE"], (void *) VolumeCreationOptions::FilesystemType::None);
if (!disable32bitFilesystems && volumeSize <= TC_MAX_FAT_SECTOR_COUNT * sectorSize)
FilesystemTypeChoice->Append (L"FAT", (void *) VolumeCreationOptions::FilesystemType::FAT);
#ifdef TC_WINDOWS
FilesystemTypeChoice->Append (L"NTFS", (void *) VolumeCreationOptions::FilesystemType::NTFS);
#elif defined (TC_LINUX)
FilesystemTypeChoice->Append (L"Linux Ext2", (void *) VolumeCreationOptions::FilesystemType::Ext2);
FilesystemTypeChoice->Append (L"Linux Ext3", (void *) VolumeCreationOptions::FilesystemType::Ext3);
FilesystemTypeChoice->Append (L"Linux Ext4", (void *) VolumeCreationOptions::FilesystemType::Ext4);
#elif defined (TC_MACOSX)
FilesystemTypeChoice->Append (L"Mac OS Extended", (void *) VolumeCreationOptions::FilesystemType::MacOsExt);
#elif defined (TC_FREEBSD) || defined (TC_SOLARIS)
FilesystemTypeChoice->Append (L"UFS", (void *) VolumeCreationOptions::FilesystemType::UFS);
#endif
if (!disable32bitFilesystems && volumeSize <= TC_MAX_FAT_SECTOR_COUNT * sectorSize)
SetFilesystemType (VolumeCreationOptions::FilesystemType::FAT);
else
SetFilesystemType (VolumeCreationOptions::FilesystemType::GetPlatformNative());
QuickFormatCheckBox->Enable (enableQuickFormatButton);
}
VolumeCreationOptions::FilesystemType::Enum VolumeFormatOptionsWizardPage::GetFilesystemType () const
{
return (VolumeCreationOptions::FilesystemType::Enum) reinterpret_cast <unsigned long long> (Gui->GetSelectedData <void> (FilesystemTypeChoice));
}
void VolumeFormatOptionsWizardPage::OnFilesystemTypeSelected (wxCommandEvent& event)
{
}
void VolumeFormatOptionsWizardPage::OnQuickFormatCheckBoxClick (wxCommandEvent& event)
{
if (event.IsChecked())
{
QuickFormatCheckBox->SetValue (Gui->AskYesNo (LangString["WARN_QUICK_FORMAT"], false, true));
}
}
void VolumeFormatOptionsWizardPage::SetFilesystemType (VolumeCreationOptions::FilesystemType::Enum type)
{
switch (type)
{
case VolumeCreationOptions::FilesystemType::None: FilesystemTypeChoice->SetStringSelection (LangString["NONE"]); break;
case VolumeCreationOptions::FilesystemType::FAT: FilesystemTypeChoice->SetStringSelection (L"FAT"); break;
case VolumeCreationOptions::FilesystemType::NTFS: FilesystemTypeChoice->SetStringSelection (L"NTFS"); break;
case VolumeCreationOptions::FilesystemType::Ext2: FilesystemTypeChoice->SetStringSelection (L"Linux Ext2"); break;
case VolumeCreationOptions::FilesystemType::Ext3: FilesystemTypeChoice->SetStringSelection (L"Linux Ext3"); break;
case VolumeCreationOptions::FilesystemType::Ext4: FilesystemTypeChoice->SetStringSelection (L"Linux Ext4"); break;
case VolumeCreationOptions::FilesystemType::MacOsExt: FilesystemTypeChoice->SetStringSelection (L"Mac OS Extended"); break;
case VolumeCreationOptions::FilesystemType::UFS: FilesystemTypeChoice->SetStringSelection (L"UFS"); break;
default:
throw ParameterIncorrect (SRC_POS);
}
}
}

View File

@@ -0,0 +1,36 @@
/*
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.
*/
#ifndef TC_HEADER_Main_Forms_VolumeFormatOptionsWizardPage
#define TC_HEADER_Main_Forms_VolumeFormatOptionsWizardPage
#include "Forms.h"
#include "Core/VolumeCreator.h"
namespace TrueCrypt
{
class VolumeFormatOptionsWizardPage : public VolumeFormatOptionsWizardPageBase
{
public:
VolumeFormatOptionsWizardPage (wxPanel* parent, uint64 volumeSize, uint32 sectorSize, bool enableQuickFormatButton = true, bool disableNoneFilesystem = false, bool disable32bitFilesystems = false);
VolumeCreationOptions::FilesystemType::Enum GetFilesystemType () const;
bool IsValid () { return true; }
bool IsQuickFormatEnabled () const { return QuickFormatCheckBox->IsChecked(); }
void SetMaxStaticTextWidth (int width) { InfoStaticText->Wrap (width); }
void SetFilesystemType (VolumeCreationOptions::FilesystemType::Enum type);
void SetPageText (const wxString &text) { InfoStaticText->SetLabel (text); }
void SetQuickFormat (bool enabled) { QuickFormatCheckBox->SetValue (enabled); }
protected:
void OnFilesystemTypeSelected (wxCommandEvent& event);
void OnQuickFormatCheckBoxClick (wxCommandEvent& event);
};
}
#endif // TC_HEADER_Main_Forms_VolumeFormatOptionsWizardPage

View File

@@ -0,0 +1,98 @@
/*
Copyright (c) 2008 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"
#include "Main/GraphicUserInterface.h"
#include "Main/VolumeHistory.h"
#include "VolumeLocationWizardPage.h"
namespace TrueCrypt
{
VolumeLocationWizardPage::VolumeLocationWizardPage (wxPanel* parent, VolumeHostType::Enum hostType, bool selectExisting)
: VolumeLocationWizardPageBase (parent),
SelectExisting (selectExisting)
{
switch (hostType)
{
case VolumeHostType::Device:
SelectFileButton->Show (false);
break;
case VolumeHostType::File:
SelectDeviceButton->Show (false);
break;
default:
break;
}
Gui->PreferencesUpdatedEvent.Connect (EventConnector <VolumeLocationWizardPage> (this, &VolumeLocationWizardPage::OnPreferencesUpdated));
VolumeHistory::ConnectComboBox (VolumePathComboBox);
NoHistoryCheckBox->SetValue (!Gui->GetPreferences().SaveHistory);
}
VolumeLocationWizardPage::~VolumeLocationWizardPage ()
{
Gui->PreferencesUpdatedEvent.Disconnect (this);
VolumeHistory::DisconnectComboBox (VolumePathComboBox);
}
void VolumeLocationWizardPage::OnNoHistoryCheckBoxClick (wxCommandEvent& event)
{
UserPreferences prefs = Gui->GetPreferences();
prefs.SaveHistory = !event.IsChecked();
Gui->SetPreferences (prefs);
if (event.IsChecked())
{
try
{
VolumeHistory::Clear();
}
catch (exception &e) { Gui->ShowError (e); }
}
}
void VolumeLocationWizardPage::OnPageChanging (bool forward)
{
if (forward)
{
VolumePath path = GetVolumePath();
if (!path.IsEmpty())
VolumeHistory::Add (path);
}
}
void VolumeLocationWizardPage::OnPreferencesUpdated (EventArgs &args)
{
NoHistoryCheckBox->SetValue (!Gui->GetPreferences().SaveHistory);
}
void VolumeLocationWizardPage::OnSelectFileButtonClick (wxCommandEvent& event)
{
FilePath path = Gui->SelectVolumeFile (this, !SelectExisting);
if (!path.IsEmpty())
SetVolumePath (path);
}
void VolumeLocationWizardPage::OnSelectDeviceButtonClick (wxCommandEvent& event)
{
DevicePath path = Gui->SelectDevice (this);
if (!path.IsEmpty())
SetVolumePath (path);
}
void VolumeLocationWizardPage::SetVolumePath (const VolumePath &path)
{
VolumePathComboBox->SetValue (wstring (path));
PageUpdatedEvent.Raise();
}
}

View File

@@ -0,0 +1,40 @@
/*
Copyright (c) 2008 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.
*/
#ifndef TC_HEADER_Main_Forms_VolumeLocationWizardPage
#define TC_HEADER_Main_Forms_VolumeLocationWizardPage
#include "Forms.h"
namespace TrueCrypt
{
class VolumeLocationWizardPage : public VolumeLocationWizardPageBase
{
public:
VolumeLocationWizardPage (wxPanel* parent, VolumeHostType::Enum hostType = VolumeHostType::Unknown, bool selectExisting = false);
~VolumeLocationWizardPage ();
VolumePath GetVolumePath () const { return VolumePath (wstring (VolumePathComboBox->GetValue())); }
bool IsValid () { return !VolumePathComboBox->GetValue().IsEmpty(); }
void OnPageChanging (bool forward);
void SetVolumePath (const VolumePath &path);
void SetMaxStaticTextWidth (int width) { InfoStaticText->Wrap (width); }
void SetPageText (const wxString &text) { InfoStaticText->SetLabel (text); }
protected:
void OnVolumePathTextChanged (wxCommandEvent& event) { PageUpdatedEvent.Raise(); }
void OnNoHistoryCheckBoxClick (wxCommandEvent& event);
void OnSelectDeviceButtonClick (wxCommandEvent& event);
void OnSelectFileButtonClick (wxCommandEvent& event);
void OnPreferencesUpdated (EventArgs &args);
bool SelectExisting;
};
}
#endif // TC_HEADER_Main_Forms_VolumeLocationWizardPage

View File

@@ -0,0 +1,310 @@
/*
Copyright (c) 2008 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"
#include "Main/GraphicUserInterface.h"
#include "KeyfilesDialog.h"
#include "VolumePasswordPanel.h"
#include "SecurityTokenKeyfilesDialog.h"
namespace TrueCrypt
{
VolumePasswordPanel::VolumePasswordPanel (wxWindow* parent, shared_ptr <VolumePassword> password, shared_ptr <KeyfileList> keyfiles, bool enableCache, bool enablePassword, bool enableKeyfiles, bool enableConfirmation, bool enablePkcs5Prf, const wxString &passwordLabel)
: VolumePasswordPanelBase (parent), Keyfiles (new KeyfileList)
{
if (keyfiles)
{
*Keyfiles = *keyfiles;
UseKeyfilesCheckBox->SetValue (!Keyfiles->empty());
}
else
{
*Keyfiles = Gui->GetPreferences().DefaultKeyfiles;
UseKeyfilesCheckBox->SetValue (Gui->GetPreferences().UseKeyfiles && !Keyfiles->empty());
}
PasswordTextCtrl->SetMaxLength (VolumePassword::MaxSize);
ConfirmPasswordTextCtrl->SetMaxLength (VolumePassword::MaxSize);
if (!passwordLabel.empty())
{
PasswordStaticText->SetLabel (passwordLabel);
GridBagSizer->Detach (PasswordStaticText);
GridBagSizer->Add (PasswordStaticText, wxGBPosition (0, 1), wxGBSpan (1, 1), wxALIGN_CENTER_VERTICAL | wxBOTTOM, Gui->GetDefaultBorderSize());
}
CacheCheckBox->Show (enableCache);
if (!enablePassword && enableKeyfiles)
{
Layout();
Fit();
PasswordPlaceholderSizer->SetMinSize (wxSize (PasswordTextCtrl->GetSize().GetWidth(), -1));
}
else if (!enablePkcs5Prf)
{
GridBagSizer->Remove (PasswordPlaceholderSizer);
}
PasswordStaticText->Show (enablePassword);
PasswordTextCtrl->Show (enablePassword);
DisplayPasswordCheckBox->Show (enablePassword);
ConfirmPasswordStaticText->Show (enableConfirmation);
ConfirmPasswordTextCtrl->Show (enableConfirmation);
UseKeyfilesCheckBox->Show (enableKeyfiles);
KeyfilesButton->Show (enableKeyfiles);
Pkcs5PrfStaticText->Show (enablePkcs5Prf);
Pkcs5PrfChoice->Show (enablePkcs5Prf);
if (enablePkcs5Prf)
{
foreach_ref (const Pkcs5Kdf &kdf, Pkcs5Kdf::GetAvailableAlgorithms())
{
if (!kdf.IsDeprecated())
Pkcs5PrfChoice->Append (kdf.GetName());
}
Pkcs5PrfChoice->Select (0);
}
if (!enablePkcs5Prf || (!enablePassword && !enableKeyfiles))
{
GridBagSizer->Remove (Pkcs5PrfSizer);
}
// Keyfiles drag & drop
class FileDropTarget : public wxFileDropTarget
{
public:
FileDropTarget (VolumePasswordPanel *panel) : Panel (panel) { }
wxDragResult OnDragOver (wxCoord x, wxCoord y, wxDragResult def)
{
return wxDragLink;
}
bool OnDropFiles (wxCoord x, wxCoord y, const wxArrayString &filenames)
{
foreach (const wxString &f, filenames)
Panel->AddKeyfile (make_shared <Keyfile> (wstring (f)));
return true;
}
protected:
VolumePasswordPanel *Panel;
};
if (enableKeyfiles)
{
SetDropTarget (new FileDropTarget (this));
#ifdef TC_MACOSX
foreach (wxWindow *c, GetChildren())
c->SetDropTarget (new FileDropTarget (this));
#endif
}
Layout();
Fit();
}
VolumePasswordPanel::~VolumePasswordPanel ()
{
WipeTextCtrl (PasswordTextCtrl);
WipeTextCtrl (ConfirmPasswordTextCtrl);
}
void VolumePasswordPanel::AddKeyfile (shared_ptr <Keyfile> keyfile)
{
if (!Keyfiles)
Keyfiles.reset (new KeyfileList);
Keyfiles->push_back (keyfile);
UseKeyfilesCheckBox->SetValue (true);
}
void VolumePasswordPanel::DisplayPassword (bool display, wxTextCtrl **textCtrl, int row)
{
FreezeScope freeze (this);
wxTextCtrl *newTextCtrl = new wxTextCtrl (this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, display ? 0 : wxTE_PASSWORD);
newTextCtrl->SetMaxLength (VolumePassword::MaxSize);
newTextCtrl->SetValue ((*textCtrl)->GetValue());
newTextCtrl->SetMinSize ((*textCtrl)->GetSize());
GridBagSizer->Detach ((*textCtrl));
GridBagSizer->Add (newTextCtrl, wxGBPosition (row, 1), wxGBSpan (1, 2), wxEXPAND|wxBOTTOM|wxALIGN_CENTER_VERTICAL, 5);
(*textCtrl)->Show (false);
WipeTextCtrl (*textCtrl);
Fit();
Layout();
newTextCtrl->SetMinSize ((*textCtrl)->GetMinSize());
newTextCtrl->Connect (wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler (VolumePasswordPanel::OnTextChanged), nullptr, this);
*textCtrl = newTextCtrl;
}
shared_ptr <VolumePassword> VolumePasswordPanel::GetPassword () const
{
return GetPassword (PasswordTextCtrl);
}
shared_ptr <VolumePassword> VolumePasswordPanel::GetPassword (wxTextCtrl *textCtrl) const
{
shared_ptr <VolumePassword> password;
wchar_t passwordBuf[VolumePassword::MaxSize + 1];
finally_do_arg (BufferPtr, BufferPtr (reinterpret_cast <byte *> (passwordBuf), sizeof (passwordBuf)), { finally_arg.Erase(); });
#ifdef TC_WINDOWS
int len = GetWindowText (static_cast <HWND> (textCtrl->GetHandle()), passwordBuf, VolumePassword::MaxSize + 1);
password.reset (new VolumePassword (passwordBuf, len));
#else
wxString passwordStr (textCtrl->GetValue()); // A copy of the password is created here by wxWidgets, which cannot be erased
for (size_t i = 0; i < passwordStr.size() && i < VolumePassword::MaxSize; ++i)
{
passwordBuf[i] = (wchar_t) passwordStr[i];
passwordStr[i] = L'X';
}
password.reset (new VolumePassword (passwordBuf, passwordStr.size() <= VolumePassword::MaxSize ? passwordStr.size() : VolumePassword::MaxSize));
#endif
return password;
}
shared_ptr <Pkcs5Kdf> VolumePasswordPanel::GetPkcs5Kdf () const
{
try
{
return Pkcs5Kdf::GetAlgorithm (wstring (Pkcs5PrfChoice->GetStringSelection()));
}
catch (ParameterIncorrect&)
{
return shared_ptr <Pkcs5Kdf> ();
}
}
void VolumePasswordPanel::OnAddKeyfileDirMenuItemSelected (wxCommandEvent& event)
{
try
{
DirectoryPath dir = Gui->SelectDirectory (this, LangString["SELECT_KEYFILE_PATH"]);
if (!dir.IsEmpty())
{
Keyfiles->push_back (make_shared <Keyfile> (dir));
UseKeyfilesCheckBox->SetValue (!Keyfiles->empty());
OnUpdate();
}
}
catch (exception &e)
{
Gui->ShowError (e);
}
}
void VolumePasswordPanel::OnAddKeyfilesMenuItemSelected (wxCommandEvent& event)
{
try
{
FilePathList files = Gui->SelectFiles (this, LangString["SELECT_KEYFILES"], false, true);
if (!files.empty())
{
foreach_ref (const FilePath &f, files)
Keyfiles->push_back (make_shared <Keyfile> (f));
UseKeyfilesCheckBox->SetValue (!Keyfiles->empty());
OnUpdate();
}
}
catch (exception &e)
{
Gui->ShowError (e);
}
}
void VolumePasswordPanel::OnAddSecurityTokenSignatureMenuItemSelected (wxCommandEvent& event)
{
try
{
SecurityTokenKeyfilesDialog dialog (this);
if (dialog.ShowModal() == wxID_OK)
{
foreach (const SecurityTokenKeyfilePath &path, dialog.GetSelectedSecurityTokenKeyfilePaths())
{
Keyfiles->push_back (make_shared <Keyfile> (wstring (path)));
}
if (!dialog.GetSelectedSecurityTokenKeyfilePaths().empty())
{
UseKeyfilesCheckBox->SetValue (!Keyfiles->empty());
OnUpdate();
}
}
}
catch (exception &e)
{
Gui->ShowError (e);
}
}
void VolumePasswordPanel::OnDisplayPasswordCheckBoxClick (wxCommandEvent& event)
{
DisplayPassword (event.IsChecked(), &PasswordTextCtrl, 1);
if (ConfirmPasswordTextCtrl->IsShown())
DisplayPassword (event.IsChecked(), &ConfirmPasswordTextCtrl, 2);
OnUpdate();
}
void VolumePasswordPanel::OnKeyfilesButtonClick (wxCommandEvent& event)
{
KeyfilesDialog dialog (GetParent(), Keyfiles);
if (dialog.ShowModal() == wxID_OK)
{
Keyfiles = dialog.GetKeyfiles();
UseKeyfilesCheckBox->SetValue (!Keyfiles->empty());
OnUpdate();
}
}
void VolumePasswordPanel::OnKeyfilesButtonRightClick (wxMouseEvent& event)
{
wxMenu popup;
Gui->AppendToMenu (popup, LangString["IDC_KEYADD"], this, wxCommandEventHandler (VolumePasswordPanel::OnAddKeyfilesMenuItemSelected));
Gui->AppendToMenu (popup, LangString["IDC_ADD_KEYFILE_PATH"], this, wxCommandEventHandler (VolumePasswordPanel::OnAddKeyfileDirMenuItemSelected));
Gui->AppendToMenu (popup, LangString["IDC_TOKEN_FILES_ADD"], this, wxCommandEventHandler (VolumePasswordPanel::OnAddSecurityTokenSignatureMenuItemSelected));
PopupMenu (&popup, KeyfilesButton->GetPosition().x + 2, KeyfilesButton->GetPosition().y + 2);
}
void VolumePasswordPanel::OnKeyfilesButtonRightDown (wxMouseEvent& event)
{
#ifndef TC_MACOSX
event.Skip();
#endif
}
bool VolumePasswordPanel::PasswordsMatch () const
{
assert (ConfirmPasswordStaticText->IsShown());
return *GetPassword (PasswordTextCtrl) == *GetPassword (ConfirmPasswordTextCtrl);
}
void VolumePasswordPanel::WipeTextCtrl (wxTextCtrl *textCtrl)
{
textCtrl->SetValue (wxString (L'X', textCtrl->GetLineLength(0)));
GetPassword (textCtrl);
}
}

View File

@@ -0,0 +1,54 @@
/*
Copyright (c) 2008 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.
*/
#ifndef TC_HEADER_Main_Forms_PasswordPanel
#define TC_HEADER_Main_Forms_PasswordPanel
#include "Forms.h"
#include "Platform/Functor.h"
#include "Main/Main.h"
namespace TrueCrypt
{
class VolumePasswordPanel : public VolumePasswordPanelBase
{
public:
VolumePasswordPanel (wxWindow* parent, shared_ptr <VolumePassword> password, shared_ptr <KeyfileList> keyfiles, bool enableCache = false, bool enablePassword = true, bool enableKeyfiles = true, bool enableConfirmation = false, bool enablePkcs5Prf = false, const wxString &passwordLabel = wxString());
virtual ~VolumePasswordPanel ();
void AddKeyfile (shared_ptr <Keyfile> keyfile);
shared_ptr <KeyfileList> GetKeyfiles () const { return UseKeyfilesCheckBox->IsChecked() ? Keyfiles : shared_ptr <KeyfileList> (); }
shared_ptr <VolumePassword> GetPassword () const;
shared_ptr <Pkcs5Kdf> GetPkcs5Kdf () const;
void SetCacheCheckBoxValidator (const wxGenericValidator &validator) { CacheCheckBox->SetValidator (validator); }
void SetFocusToPasswordTextCtrl () { PasswordTextCtrl->SetSelection (-1, -1); PasswordTextCtrl->SetFocus(); }
bool PasswordsMatch () const;
Event UpdateEvent;
protected:
void DisplayPassword (bool display, wxTextCtrl **textCtrl, int row);
shared_ptr <VolumePassword> GetPassword (wxTextCtrl *textCtrl) const;
void OnAddKeyfileDirMenuItemSelected (wxCommandEvent& event);
void OnAddKeyfilesMenuItemSelected (wxCommandEvent& event);
void OnAddSecurityTokenSignatureMenuItemSelected (wxCommandEvent& event);
void OnDisplayPasswordCheckBoxClick (wxCommandEvent& event);
void OnKeyfilesButtonClick (wxCommandEvent& event);
void OnKeyfilesButtonRightClick (wxMouseEvent& event);
void OnKeyfilesButtonRightDown (wxMouseEvent& event);
void OnTextChanged (wxCommandEvent& event) { OnUpdate(); }
void OnUpdate () { UpdateEvent.Raise(); }
void OnUseKeyfilesCheckBoxClick (wxCommandEvent& event) { OnUpdate(); }
void WipeTextCtrl (wxTextCtrl *textCtrl);
shared_ptr <KeyfileList> Keyfiles;
shared_ptr <Functor> UpdateCallback;
};
}
#endif // TC_HEADER_Main_Forms_PasswordPanel

View File

@@ -0,0 +1,39 @@
/*
Copyright (c) 2008 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"
#include "Main/GraphicUserInterface.h"
#include "VolumePasswordWizardPage.h"
namespace TrueCrypt
{
VolumePasswordWizardPage::VolumePasswordWizardPage (wxPanel* parent, shared_ptr <VolumePassword> password, shared_ptr <KeyfileList> keyfiles, bool enableConfirmation)
: VolumePasswordWizardPageBase (parent), ConfirmationMode (enableConfirmation)
{
PasswordPanel = new VolumePasswordPanel (this, password, keyfiles, false, true, true, enableConfirmation);
PasswordPanel->UpdateEvent.Connect (EventConnector <VolumePasswordWizardPage> (this, &VolumePasswordWizardPage::OnPasswordPanelUpdate));
PasswordPanelSizer->Add (PasswordPanel, 1, wxALL | wxEXPAND);
}
VolumePasswordWizardPage::~VolumePasswordWizardPage ()
{
PasswordPanel->UpdateEvent.Disconnect (this);
}
bool VolumePasswordWizardPage::IsValid ()
{
if (ConfirmationMode && !PasswordPanel->PasswordsMatch())
return false;
shared_ptr <KeyfileList> keyfiles (GetKeyfiles());
shared_ptr <VolumePassword> password (GetPassword());
return (password && !GetPassword()->IsEmpty()) || (keyfiles && !keyfiles->empty());
}
}

View File

@@ -0,0 +1,37 @@
/*
Copyright (c) 2008 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.
*/
#ifndef TC_HEADER_Main_Forms_VolumePasswordWizardPage
#define TC_HEADER_Main_Forms_VolumePasswordWizardPage
#include "Forms.h"
#include "VolumePasswordPanel.h"
namespace TrueCrypt
{
class VolumePasswordWizardPage : public VolumePasswordWizardPageBase
{
public:
VolumePasswordWizardPage (wxPanel* parent, shared_ptr <VolumePassword> password, shared_ptr <KeyfileList> keyfiles, bool enableConfirmation = true);
~VolumePasswordWizardPage ();
shared_ptr <KeyfileList> GetKeyfiles () const { return PasswordPanel->GetKeyfiles(); }
shared_ptr <VolumePassword> GetPassword () const { return PasswordPanel->GetPassword(); }
bool IsValid ();
void SetMaxStaticTextWidth (int width) { InfoStaticText->Wrap (width); }
void SetPageText (const wxString &text) { InfoStaticText->SetLabel (text); }
protected:
void OnPasswordPanelUpdate (EventArgs &args) { PageUpdatedEvent.Raise(); }
bool ConfirmationMode;
VolumePasswordPanel *PasswordPanel;
};
}
#endif // TC_HEADER_Main_Forms_VolumePasswordWizardPage

View File

@@ -0,0 +1,97 @@
/*
Copyright (c) 2008 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"
#include "Main/Main.h"
#include "Main/GraphicUserInterface.h"
#include "VolumePropertiesDialog.h"
namespace TrueCrypt
{
VolumePropertiesDialog::VolumePropertiesDialog (wxWindow* parent, const VolumeInfo &volumeInfo)
: VolumePropertiesDialogBase (parent)
{
list <int> colPermilles;
PropertiesListCtrl->InsertColumn (0, LangString["PROPERTY"], wxLIST_FORMAT_LEFT, 208);
colPermilles.push_back (500);
PropertiesListCtrl->InsertColumn (1, LangString["VALUE"], wxLIST_FORMAT_LEFT, 192);
colPermilles.push_back (500);
Gui->SetListCtrlWidth (PropertiesListCtrl, 70, false);
Gui->SetListCtrlHeight (PropertiesListCtrl, 17);
Gui->SetListCtrlColumnWidths (PropertiesListCtrl, colPermilles, false);
AppendToList ("LOCATION", wstring (volumeInfo.Path));
#ifndef TC_WINDOWS
AppendToList ("VIRTUAL_DEVICE", wstring (volumeInfo.VirtualDevice));
#endif
AppendToList ("SIZE", Gui->SizeToString (volumeInfo.Size));
AppendToList ("TYPE", Gui->VolumeTypeToString (volumeInfo.Type, volumeInfo.Protection));
AppendToList ("READ_ONLY", LangString [volumeInfo.Protection == VolumeProtection::ReadOnly ? "UISTR_YES" : "UISTR_NO"]);
wxString protection;
if (volumeInfo.Type == VolumeType::Hidden)
protection = LangString["NOT_APPLICABLE_OR_NOT_AVAILABLE"];
else if (volumeInfo.HiddenVolumeProtectionTriggered)
protection = LangString["HID_VOL_DAMAGE_PREVENTED"];
else
protection = LangString [volumeInfo.Protection == VolumeProtection::HiddenVolumeReadOnly ? "UISTR_YES" : "UISTR_NO"];
AppendToList ("HIDDEN_VOL_PROTECTION", protection);
AppendToList ("ENCRYPTION_ALGORITHM", volumeInfo.EncryptionAlgorithmName);
AppendToList ("KEY_SIZE", StringFormatter (L"{0} {1}", volumeInfo.EncryptionAlgorithmKeySize * 8, LangString ["BITS"]));
if (volumeInfo.EncryptionModeName == L"XTS")
AppendToList ("SECONDARY_KEY_SIZE_XTS", StringFormatter (L"{0} {1}", volumeInfo.EncryptionAlgorithmKeySize * 8, LangString ["BITS"]));
wstringstream blockSize;
blockSize << volumeInfo.EncryptionAlgorithmBlockSize * 8;
if (volumeInfo.EncryptionAlgorithmBlockSize != volumeInfo.EncryptionAlgorithmMinBlockSize)
blockSize << L"/" << volumeInfo.EncryptionAlgorithmMinBlockSize * 8;
AppendToList ("BLOCK_SIZE", blockSize.str() + L" " + LangString ["BITS"]);
AppendToList ("MODE_OF_OPERATION", volumeInfo.EncryptionModeName);
AppendToList ("PKCS5_PRF", volumeInfo.Pkcs5PrfName);
#if 0
AppendToList ("PKCS5_ITERATIONS", StringConverter::FromNumber (volumeInfo.Pkcs5IterationCount));
AppendToList ("VOLUME_CREATE_DATE", Gui->VolumeTimeToString (volumeInfo.VolumeCreationTime));
AppendToList ("VOLUME_HEADER_DATE", Gui->VolumeTimeToString (volumeInfo.HeaderCreationTime));
#endif
AppendToList ("VOLUME_FORMAT_VERSION", StringConverter::ToWide (volumeInfo.MinRequiredProgramVersion < 0x600 ? 1 : 2));
AppendToList ("BACKUP_HEADER", LangString[volumeInfo.MinRequiredProgramVersion >= 0x600 ? "UISTR_YES" : "UISTR_NO"]);
#ifdef TC_LINUX
if (string (volumeInfo.VirtualDevice).find ("/dev/mapper/truecrypt") != 0)
{
#endif
AppendToList ("TOTAL_DATA_READ", Gui->SizeToString (volumeInfo.TotalDataRead));
AppendToList ("TOTAL_DATA_WRITTEN", Gui->SizeToString (volumeInfo.TotalDataWritten));
#ifdef TC_LINUX
}
#endif
Layout();
Fit();
Center();
StdButtonsOK->SetDefault();
}
void VolumePropertiesDialog::AppendToList (const string &name, const wxString &value)
{
vector <wstring> fields (PropertiesListCtrl->GetColumnCount());
fields[0] = LangString[name];
fields[1] = value;
Gui->AppendToListCtrl (PropertiesListCtrl, fields);
}
}

View File

@@ -0,0 +1,26 @@
/*
Copyright (c) 2008 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.
*/
#ifndef TC_HEADER_Main_Forms_VolumePropertiesDialog
#define TC_HEADER_Main_Forms_VolumePropertiesDialog
#include "Forms.h"
#include "Main/Main.h"
namespace TrueCrypt
{
class VolumePropertiesDialog : public VolumePropertiesDialogBase
{
public:
VolumePropertiesDialog (wxWindow* parent, const VolumeInfo &volumeInfo);
void AppendToList (const string &name, const wxString &value);
};
}
#endif // TC_HEADER_Main_Forms_VolumePropertiesDialog

View File

@@ -0,0 +1,137 @@
/*
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"
#include "Main/GraphicUserInterface.h"
#include "VolumeSizeWizardPage.h"
namespace TrueCrypt
{
VolumeSizeWizardPage::VolumeSizeWizardPage (wxPanel* parent, const VolumePath &volumePath, uint32 sectorSize, const wxString &freeSpaceText)
: VolumeSizeWizardPageBase (parent),
MaxVolumeSize (0),
MaxVolumeSizeValid (false),
MinVolumeSize (1),
SectorSize (sectorSize)
{
VolumeSizePrefixChoice->Append (LangString["KB"], reinterpret_cast <void *> (1024));
VolumeSizePrefixChoice->Append (LangString["MB"], reinterpret_cast <void *> (1024 * 1024));
VolumeSizePrefixChoice->Append (LangString["GB"], reinterpret_cast <void *> (1024 * 1024 * 1024));
VolumeSizePrefixChoice->Select (Prefix::MB);
wxLongLong diskSpace = 0;
if (!wxGetDiskSpace (wxFileName (wstring (volumePath)).GetPath(), nullptr, &diskSpace))
{
VolumeSizeTextCtrl->Disable();
VolumeSizeTextCtrl->SetValue (L"");
}
FreeSpaceStaticText->SetFont (Gui->GetDefaultBoldFont (this));
if (!freeSpaceText.empty())
{
FreeSpaceStaticText->SetLabel (freeSpaceText);
}
else
{
#ifdef TC_WINDOWS
wxString drive = wxFileName (wstring (volumePath)).GetVolume();
if (!drive.empty())
{
FreeSpaceStaticText->SetLabel (StringFormatter (_("Free space on drive {0}: is {1}."),
drive, Gui->SizeToString (diskSpace.GetValue())));
}
else
#endif
{
FreeSpaceStaticText->SetLabel (StringFormatter (_("Free space available: {0}"),
Gui->SizeToString (diskSpace.GetValue())));
}
}
VolumeSizeTextCtrl->SetMinSize (wxSize (Gui->GetCharWidth (VolumeSizeTextCtrl) * 20, -1));
wxTextValidator validator (wxFILTER_INCLUDE_CHAR_LIST); // wxFILTER_NUMERIC does not exclude - . , etc.
const wxChar *valArr[] = { L"0", L"1", L"2", L"3", L"4", L"5", L"6", L"7", L"8", L"9" };
validator.SetIncludes (wxArrayString (array_capacity (valArr), (const wxChar **) &valArr));
VolumeSizeTextCtrl->SetValidator (validator);
}
uint64 VolumeSizeWizardPage::GetVolumeSize () const
{
uint64 prefixMult = 1;
int selection = VolumeSizePrefixChoice->GetSelection();
if (selection == wxNOT_FOUND)
return 0;
prefixMult = reinterpret_cast <uint64> (VolumeSizePrefixChoice->GetClientData (selection));
uint64 val = StringConverter::ToUInt64 (wstring (VolumeSizeTextCtrl->GetValue()));
if (val <= 0x7fffFFFFffffFFFFull / prefixMult)
{
val *= prefixMult;
uint32 sectorSizeRem = val % SectorSize;
if (sectorSizeRem != 0)
val += SectorSize - sectorSizeRem;
return val;
}
else
return 0;
}
bool VolumeSizeWizardPage::IsValid ()
{
if (!VolumeSizeTextCtrl->IsEmpty() && Validate())
{
try
{
if (GetVolumeSize() >= MinVolumeSize && (!MaxVolumeSizeValid || GetVolumeSize() <= MaxVolumeSize))
return true;
}
catch (...) { }
}
return false;
}
void VolumeSizeWizardPage::SetMaxStaticTextWidth (int width)
{
FreeSpaceStaticText->Wrap (width);
InfoStaticText->Wrap (width);
}
void VolumeSizeWizardPage::SetVolumeSize (uint64 size)
{
if (size == 0)
{
VolumeSizePrefixChoice->Select (Prefix::MB);
VolumeSizeTextCtrl->SetValue (L"");
return;
}
if (size % (1024 * 1024 * 1024) == 0)
{
size /= 1024 * 1024 * 1024;
VolumeSizePrefixChoice->Select (Prefix::GB);
}
else if (size % (1024 * 1024) == 0)
{
size /= 1024 * 1024;
VolumeSizePrefixChoice->Select (Prefix::MB);
}
else
{
size /= 1024;
VolumeSizePrefixChoice->Select (Prefix::KB);
}
VolumeSizeTextCtrl->SetValue (StringConverter::FromNumber (size));
}
}

View File

@@ -0,0 +1,51 @@
/*
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.
*/
#ifndef TC_HEADER_Main_Forms_VolumeSizeWizardPage
#define TC_HEADER_Main_Forms_VolumeSizeWizardPage
#include "Forms.h"
namespace TrueCrypt
{
class VolumeSizeWizardPage : public VolumeSizeWizardPageBase
{
public:
VolumeSizeWizardPage (wxPanel* parent, const VolumePath &volumePath, uint32 sectorSize, const wxString &freeSpaceText = wxEmptyString);
uint64 GetVolumeSize () const;
bool IsValid ();
void SetMaxStaticTextWidth (int width);
void SetMaxVolumeSize (uint64 size) { MaxVolumeSize = size; MaxVolumeSizeValid = true; }
void SetMinVolumeSize (uint64 size) { MinVolumeSize = size; }
void SetPageText (const wxString &text) { InfoStaticText->SetLabel (text); }
void SetVolumeSize (uint64 size);
protected:
struct Prefix
{
enum
{
KB = 0,
MB,
GB
};
};
void OnBrowseButtonClick (wxCommandEvent& event);
void OnVolumeSizePrefixSelected (wxCommandEvent& event) { PageUpdatedEvent.Raise(); }
void OnVolumeSizeTextChanged (wxCommandEvent& event) { PageUpdatedEvent.Raise(); }
uint64 MaxVolumeSize;
bool MaxVolumeSizeValid;
uint64 MinVolumeSize;
uint32 SectorSize;
};
}
#endif // TC_HEADER_Main_Forms_VolumeSizeWizardPage

View File

@@ -0,0 +1,189 @@
/*
Copyright (c) 2008 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"
#include "Main/GraphicUserInterface.h"
#include "Main/Resources.h"
#include "WizardFrame.h"
namespace TrueCrypt
{
WizardFrame::WizardFrame (wxWindow* parent)
: WizardFrameBase (parent),
CurrentPage (nullptr),
CurrentStep (-1),
MaxStaticTextWidth (-1),
WorkInProgress (false)
{
SetIcon (Resources::GetTrueCryptIcon());
PageTitleStaticText->SetFont (wxFont (
#ifdef TC_WINDOWS
16
#elif defined(TC_MACOSX)
18
#elif defined(__WXGTK__)
14
#endif
* Gui->GetCharHeight (this) / 13, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, L"Times New Roman"));
UpdateControls();
this->SetDefaultItem (NextButton);
NextButton->SetFocus();
foreach (wxWindow *c, MainPanel->GetChildren())
c->Connect (wxEVT_MOTION, wxMouseEventHandler (WizardFrame::OnMouseMotion), nullptr, this);
}
WizardFrame::~WizardFrame ()
{
if (CurrentPage)
CurrentPage->Destroy();
}
void WizardFrame::ClearHistory ()
{
StepHistory.clear();
UpdateControls();
}
void WizardFrame::OnActivate (wxActivateEvent& event)
{
Gui->SetActiveFrame (this);
event.Skip();
}
void WizardFrame::OnClose (wxCloseEvent& event)
{
if (WorkInProgress)
return;
Gui->SetActiveFrame (nullptr);
event.Skip();
}
void WizardFrame::OnHelpButtonClick (wxCommandEvent& event)
{
Gui->OpenUserGuide (this);
}
void WizardFrame::OnNextButtonClick (wxCommandEvent& event)
{
if (CurrentPage->IsValid())
{
WizardStep nextStep = ProcessPageChangeRequest (true);
if (nextStep != CurrentStep)
SetStep (nextStep);
}
}
void WizardFrame::OnPreviousButtonClick (wxCommandEvent& event)
{
ProcessPageChangeRequest (false);
if (!StepHistory.empty())
{
WizardStep prevStep = *StepHistory.rbegin();
StepHistory.pop_back();
SetStep (prevStep, false);
}
}
void WizardFrame::SetCancelButtonText (const wxString &text)
{
CancelButton->SetLabel (text.empty() ? wxString (_("Cancel")) : text);
}
void WizardFrame::SetImage (const wxBitmap &bitmap)
{
WizardBitmap->SetBitmap (bitmap);
}
void WizardFrame::SetMaxStaticTextWidth (size_t charCount)
{
MaxStaticTextWidth = Gui->GetCharWidth (this) * charCount;
}
void WizardFrame::SetStep (WizardStep newStep)
{
SetStep (newStep, true);
}
void WizardFrame::SetStep (WizardStep newStep, bool forward)
{
bool init = false;
FreezeScope freeze (this);
#ifdef TC_WINDOWS
HelpButton->Disable(); // Prevent Help button from getting default focus
NextButton->Enable();
#endif
if (CurrentPage)
{
if (forward)
StepHistory.push_back (CurrentStep);
CurrentPage->OnPageChanging (forward);
CurrentPage->Destroy();
CurrentPage = nullptr;
}
else
init = true;
CurrentStep = newStep;
CurrentPage = GetPage (newStep);
CurrentPage->PageUpdatedEvent.Connect (EventConnector <WizardFrame> (this, &WizardFrame::OnPageUpdated));
CurrentPage->Connect (wxEVT_MOTION, wxMouseEventHandler (WizardFrame::OnMouseMotion), nullptr, this);
foreach (wxWindow *c, CurrentPage->GetChildren())
c->Connect (wxEVT_MOTION, wxMouseEventHandler (WizardFrame::OnMouseMotion), nullptr, this);
if (MaxStaticTextWidth > 0)
CurrentPage->SetMaxStaticTextWidth (MaxStaticTextWidth);
PageTitleStaticText->SetLabel (CurrentPage->GetPageTitle());
PageSizer->Add (CurrentPage, 1, wxALL | wxEXPAND);
if (init)
{
Fit();
Layout();
Center();
}
else
MainPanel->Layout();
CurrentPage->SetFocus();
wxString nextButtonText = CurrentPage->GetNextButtonText();
if (nextButtonText.empty())
NextButton->SetLabel (_("&Next >"));
else
NextButton->SetLabel (nextButtonText);
#ifdef TC_WINDOWS
HelpButton->Enable();
#endif
UpdateControls();
}
void WizardFrame::SetWorkInProgress (bool state)
{
WorkInProgress = state;
UpdateControls();
}
void WizardFrame::UpdateControls ()
{
CancelButton->Enable (!WorkInProgress);
HelpButton->Enable (!WorkInProgress);
NextButton->Enable (!WorkInProgress && CurrentPage != nullptr && CurrentPage->IsValid());
PreviousButton->Enable (!WorkInProgress && !StepHistory.empty());
}
}

View File

@@ -0,0 +1,58 @@
/*
Copyright (c) 2008 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.
*/
#ifndef TC_HEADER_Main_Forms_WizardFrame
#define TC_HEADER_Main_Forms_WizardFrame
#include "Forms.h"
#include "Main/Main.h"
namespace TrueCrypt
{
class WizardFrame : public WizardFrameBase
{
public:
WizardFrame (wxWindow* parent);
virtual ~WizardFrame ();
protected:
typedef int WizardStep;
void ClearHistory ();
virtual WizardPage *GetPage (WizardStep step) = 0;
WizardPage *GetCurrentPage () const { return CurrentPage; }
WizardStep GetCurrentStep () const { return CurrentStep; }
wxPanel *GetPageParent () const { return MainPanel; }
bool IsWorkInProgress() const { return WorkInProgress; }
virtual void OnCancelButtonClick (wxCommandEvent& event) { Close(); }
virtual void OnClose (wxCloseEvent& event);
virtual void OnHelpButtonClick (wxCommandEvent& event);
virtual WizardStep ProcessPageChangeRequest (bool forward) = 0;
void SetCancelButtonText (const wxString &text);
void SetImage (const wxBitmap &bitmap);
void SetMaxStaticTextWidth (size_t charCount);
void SetStep (WizardStep newStep);
void SetWorkInProgress (bool state);
private:
void OnActivate (wxActivateEvent& event);
void OnNextButtonClick (wxCommandEvent& event);
void OnPageUpdated (EventArgs &args) { UpdateControls(); }
void OnPreviousButtonClick (wxCommandEvent& event);
void SetStep (WizardStep newStep, bool forward);
void UpdateControls ();
WizardPage *CurrentPage;
WizardStep CurrentStep;
int MaxStaticTextWidth;
list <WizardStep> StepHistory;
bool WorkInProgress;
};
}
#endif // TC_HEADER_Main_Forms_WizardFrame

View File

@@ -0,0 +1,41 @@
/*
Copyright (c) 2008 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.
*/
#ifndef TC_HEADER_Main_Forms_WizardPage
#define TC_HEADER_Main_Forms_WizardPage
#include "Main/Main.h"
namespace TrueCrypt
{
class WizardPage : public wxPanel
{
public:
WizardPage (wxWindow *parent, wxWindowID id, const wxPoint &pos, const wxSize &size, long style)
: wxPanel (parent, id, pos, size, style)
{ }
virtual ~WizardPage () { }
wxString GetPageTitle () const { return PageTitle; }
virtual bool IsValid () = 0;
virtual void OnPageChanging (bool forward) { }
wxString GetNextButtonText () const { return NextButtonText; }
void SetNextButtonText (const wxString &text) { NextButtonText = text; }
virtual void SetMaxStaticTextWidth (int width) { }
void SetPageTitle (const wxString &title) { PageTitle = title; }
virtual void SetPageText (const wxString &text) = 0;
Event PageUpdatedEvent;
protected:
wxString PageTitle;
wxString NextButtonText;
};
}
#endif // TC_HEADER_Main_Forms_WizardPage

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,160 @@
/*
Copyright (c) 2008-2009 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.
*/
#ifndef TC_HEADER_Main_GraphicUserInterface
#define TC_HEADER_Main_GraphicUserInterface
#include "System.h"
#include <utility>
#include "Main.h"
#include "UserInterface.h"
namespace TrueCrypt
{
class GraphicUserInterface : public UserInterface
{
public:
GraphicUserInterface ();
virtual ~GraphicUserInterface ();
virtual void AppendToListCtrl (wxListCtrl *listCtrl, const vector <wstring> &itemFields, int imageIndex = -1, void *itemDataPtr = nullptr) const;
virtual wxMenuItem *AppendToMenu (wxMenu &menu, const wxString &label, wxEvtHandler *handler = nullptr, wxObjectEventFunction handlerFunction = nullptr, int itemId = wxID_ANY) const;
virtual bool AskYesNo (const wxString &message, bool defaultYes = false, bool warning = false) const;
virtual void AutoDismountVolumes (VolumeInfoList mountedVolumes, bool alwaysForce = true);
virtual void BackupVolumeHeaders (shared_ptr <VolumePath> volumePath) const;
virtual void BeginBusyState () const { wxBeginBusyCursor(); }
virtual void BeginInteractiveBusyState (wxWindow *window);
virtual void ChangePassword (shared_ptr <VolumePath> volumePath = shared_ptr <VolumePath>(), shared_ptr <VolumePassword> password = shared_ptr <VolumePassword>(), shared_ptr <KeyfileList> keyfiles = shared_ptr <KeyfileList>(), shared_ptr <VolumePassword> newPassword = shared_ptr <VolumePassword>(), shared_ptr <KeyfileList> newKeyfiles = shared_ptr <KeyfileList>(), shared_ptr <Hash> newHash = shared_ptr <Hash>()) const { ThrowTextModeRequired(); }
wxHyperlinkCtrl *CreateHyperlink (wxWindow *parent, const wxString &linkUrl, const wxString &linkText) const;
virtual void CreateKeyfile (shared_ptr <FilePath> keyfilePath = shared_ptr <FilePath>()) const;
virtual void CreateVolume (shared_ptr <VolumeCreationOptions> options) const { ThrowTextModeRequired(); }
virtual void ClearListCtrlSelection (wxListCtrl *listCtrl) const;
virtual void DeleteSecurityTokenKeyfiles () const { ThrowTextModeRequired(); }
virtual void DoShowError (const wxString &message) const;
virtual void DoShowInfo (const wxString &message) const;
virtual void DoShowString (const wxString &str) const;
virtual void DoShowWarning (const wxString &message) const;
virtual void EndBusyState () const { wxEndBusyCursor(); }
virtual void EndInteractiveBusyState (wxWindow *window) const;
virtual void ExportSecurityTokenKeyfile () const { ThrowTextModeRequired(); }
virtual wxTopLevelWindow *GetActiveWindow () const;
virtual shared_ptr <GetStringFunctor> GetAdminPasswordRequestHandler ();
virtual int GetCharHeight (wxWindow *window) const;
virtual int GetCharWidth (wxWindow *window) const;
virtual int GetDefaultBorderSize () const { return 5; }
virtual wxFont GetDefaultBoldFont (wxWindow *window) const;
virtual wxString GetHomepageLinkURL (const wxString &linkId, bool secure = false, const wxString &extraVars = wxEmptyString) const;
virtual wxFrame *GetMainFrame () const { return mMainFrame; }
virtual int GetScrollbarWidth (wxWindow *window, bool noScrollBar = false) const;
virtual list <long> GetListCtrlSelectedItems (wxListCtrl *listCtrl) const;
virtual wxString GetListCtrlSubItemText (wxListCtrl *listCtrl, long itemIndex, int columnIndex) const;
virtual void ImportSecurityTokenKeyfiles () const { ThrowTextModeRequired(); }
virtual void InitSecurityTokenLibrary () const;
virtual void InsertToListCtrl (wxListCtrl *listCtrl, long itemIndex, const vector <wstring> &itemFields, int imageIndex = -1, void *itemDataPtr = nullptr) const;
virtual bool IsInBackgroundMode () const { return BackgroundMode; }
virtual bool IsTheOnlyTopLevelWindow (const wxWindow *window) const;
virtual void ListSecurityTokenKeyfiles () const;
virtual VolumeInfoList MountAllDeviceHostedVolumes (MountOptions &options) const;
virtual shared_ptr <VolumeInfo> MountVolume (MountOptions &options) const;
virtual void MoveListCtrlItem (wxListCtrl *listCtrl, long itemIndex, long newItemIndex) const;
virtual void OnAutoDismountAllEvent ();
virtual bool OnInit ();
virtual void OnLogOff ();
virtual void OpenDocument (wxWindow *parent, const wxFileName &document);
virtual void OpenHomepageLink (wxWindow *parent, const wxString &linkId, const wxString &extraVars = wxEmptyString);
virtual void OpenOnlineHelp (wxWindow *parent);
virtual void OpenUserGuide (wxWindow *parent);
virtual void RestoreVolumeHeaders (shared_ptr <VolumePath> volumePath) const;
virtual DevicePath SelectDevice (wxWindow *parent) const;
virtual DirectoryPath SelectDirectory (wxWindow *parent, const wxString &message = wxEmptyString, bool existingOnly = true) const;
virtual FilePathList SelectFiles (wxWindow *parent, const wxString &caption, bool saveMode = false, bool allowMultiple = false, const list < pair <wstring, wstring> > &fileExtensions = (list < pair <wstring, wstring> > ()), const DirectoryPath &directory = DirectoryPath()) const;
virtual FilePath SelectVolumeFile (wxWindow *parent, bool saveMode = false, const DirectoryPath &directory = DirectoryPath()) const;
virtual void SetActiveFrame (wxFrame *frame) { ActiveFrame = frame; }
virtual void SetBackgroundMode (bool state);
virtual void SetListCtrlColumnWidths (wxListCtrl *listCtrl, list <int> columnWidthPermilles, bool hasVerticalScrollbar = true) const;
virtual void SetListCtrlHeight (wxListCtrl *listCtrl, size_t rowCount) const;
virtual void SetListCtrlWidth (wxListCtrl *listCtrl, size_t charCount, bool hasVerticalScrollbar = true) const;
virtual void ShowErrorTopMost (char *langStringId) const { ShowErrorTopMost (LangString[langStringId]); }
virtual void ShowErrorTopMost (const wxString &message) const;
virtual void ShowInfoTopMost (char *langStringId) const { ShowInfoTopMost (LangString[langStringId]); }
virtual void ShowInfoTopMost (const wxString &message) const;
virtual void ShowWarningTopMost (char *langStringId) const { ShowWarningTopMost (LangString[langStringId]); }
virtual void ShowWarningTopMost (const wxString &message) const;
virtual bool UpdateListCtrlItem (wxListCtrl *listCtrl, long itemIndex, const vector <wstring> &itemFields) const;
virtual void UserEnrichRandomPool (wxWindow *parent, shared_ptr <Hash> hash = shared_ptr <Hash>()) const;
virtual void Yield () const;
#ifdef TC_MACOSX
virtual void MacOpenFile (const wxString &fileName);
#endif
template <class T>
T *GetSelectedData (wxControlWithItems *control) const
{
int sel = control->GetSelection();
if (sel == wxNOT_FOUND)
return nullptr;
return reinterpret_cast <T *> (control->GetClientData (sel));
}
Event OpenVolumeSystemRequestEvent;
protected:
virtual void OnEndSession (wxCloseEvent& event) { OnLogOff(); }
#ifdef wxHAS_POWER_EVENTS
virtual void OnPowerSuspending (wxPowerEvent& event);
#endif
static void OnSignal (int signal);
virtual void OnVolumesAutoDismounted ();
virtual int ShowMessage (const wxString &message, long style, bool topMost = false) const;
void ThrowTextModeRequired () const;
wxFrame *ActiveFrame;
bool BackgroundMode;
#ifdef TC_WINDOWS
auto_ptr <wxDDEServer> DDEServer;
#endif
wxFrame *mMainFrame;
auto_ptr <wxSingleInstanceChecker> SingleInstanceChecker;
private:
GraphicUserInterface (const GraphicUserInterface &);
GraphicUserInterface &operator= (const GraphicUserInterface &);
};
struct OpenVolumeSystemRequestEventArgs : public EventArgs
{
OpenVolumeSystemRequestEventArgs (const wxString &volumePath) : mVolumePath (volumePath) { }
wxString mVolumePath;
};
class FreezeScope
{
public:
FreezeScope (wxWindow *window) : Window (window)
{
Window->Freeze();
}
~FreezeScope ()
{
Window->Thaw();
}
wxWindow *Window;
};
DECLARE_EVENT_TYPE (TC_EVENT_THREAD_EXITING, -1);
extern GraphicUserInterface *Gui;
}
#endif // TC_HEADER_Main_GraphicUserInterface

241
src/Main/Hotkey.cpp Normal file
View File

@@ -0,0 +1,241 @@
/*
Copyright (c) 2008-2009 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"
#include "Application.h"
#include "LanguageStrings.h"
#include "GraphicUserInterface.h"
#include "Hotkey.h"
#include "Xml.h"
namespace TrueCrypt
{
HotkeyList Hotkey::GetAvailableHotkeys ()
{
HotkeyList hotkeys;
#ifdef TC_WINDOWS
#define TC_HOTKEY(ID,LANG) hotkeys.push_back (shared_ptr <Hotkey> (new Hotkey (Id::##ID, L###ID, LangString[LANG])))
TC_HOTKEY (CloseAllSecurityTokenSessions, "IDM_CLOSE_ALL_TOKEN_SESSIONS");
TC_HOTKEY (DismountAll, "HK_DISMOUNT_ALL");
TC_HOTKEY (DismountAllWipeCache, "HK_DISMOUNT_ALL_AND_WIPE");
TC_HOTKEY (ForceDismountAllWipeCache, "HK_FORCE_DISMOUNT_ALL_AND_WIPE");
TC_HOTKEY (ForceDismountAllWipeCacheExit, "HK_FORCE_DISMOUNT_ALL_AND_WIPE_AND_EXIT");
TC_HOTKEY (MountAllDevices, "HK_AUTOMOUNT_DEVICES");
TC_HOTKEY (MountAllFavorites, "HK_MOUNT_FAVORITE_VOLUMES");
TC_HOTKEY (ShowHideApplication, "HK_SHOW_HIDE_MAIN_WINDOW");
TC_HOTKEY (WipeCache, "HK_WIPE_CACHE");
#endif
return hotkeys;
}
wxString Hotkey::GetShortcutString () const
{
wxString keyStr = Hotkey::GetVirtualKeyCodeString (VirtualKeyCode);
if (keyStr.empty())
return L"";
wxString str;
if (VirtualKeyModifiers & wxMOD_SHIFT)
str += LangString["VK_SHIFT"] + L"+";
if (VirtualKeyModifiers & wxMOD_CONTROL)
str += LangString["VK_CONTROL"] + L"+";
if (VirtualKeyModifiers & wxMOD_ALT)
str += LangString["VK_ALT"] + L"+";
if (VirtualKeyModifiers & wxMOD_WIN )
str += LangString["VK_WIN"] + L"+";
return str + keyStr;
}
wxString Hotkey::GetVirtualKeyCodeString (int virtualKeyCode)
{
#ifdef TC_WINDOWS
// ASCII characters
if (virtualKeyCode >= 0x30 && virtualKeyCode <= 0x5a)
return StringFormatter (L"{0}", char (virtualKeyCode));
// OEM-specific
if (virtualKeyCode >= 0xE9 && virtualKeyCode <= 0xF5)
return StringFormatter (L"OEM-{0}", virtualKeyCode);
// F1-F24
if (virtualKeyCode >= VK_F1 && virtualKeyCode <= VK_F24)
return StringFormatter (L"F{0}", virtualKeyCode - VK_F1 + 1);
// Numpad numbers
if (virtualKeyCode >= VK_NUMPAD0 && virtualKeyCode <= VK_NUMPAD9)
return StringFormatter (L"{0} {1}", LangString["VK_NUMPAD"], virtualKeyCode - VK_NUMPAD0);
switch (virtualKeyCode)
{
case VK_MULTIPLY: return LangString["VK_NUMPAD"] + L" *";
case VK_ADD: return LangString["VK_NUMPAD"] + L" +";
case VK_SEPARATOR: return LangString["VK_NUMPAD"] + L" Separator";
case VK_SUBTRACT: return LangString["VK_NUMPAD"] + L" -";
case VK_DECIMAL: return LangString["VK_NUMPAD"] + L" .";
case VK_DIVIDE: return LangString["VK_NUMPAD"] + L" /";
case VK_OEM_1: return L"OEM 1 (';')";
case VK_OEM_PLUS: return L"+";
case VK_OEM_COMMA: return L",";
case VK_OEM_MINUS: return L"-";
case VK_OEM_PERIOD: return L".";
case VK_OEM_2: return L"OEM 2 ('/')";
case VK_OEM_3: return L"OEM 3 (`)";
case VK_OEM_4: return L"OEM 4 ('[')";
case VK_OEM_5: return L"OEM 5 ('\\')";
case VK_OEM_6: return L"OEM 6 (']')";
case VK_OEM_7: return L"OEM 7 (')";
case VK_OEM_8: return L"OEM 8";
case VK_OEM_AX: return L"OEM AX";
case VK_OEM_102: return L"OEM 102";
case VK_ICO_HELP: return L"ICO_HELP";
case VK_ICO_00: return L"ICO_00";
case VK_ICO_CLEAR: return L"ICO_CLEAR";
case VK_ATTN: return L"Attn";
case VK_CRSEL: return L"CrSel";
case VK_EXSEL: return L"ExSel";
case VK_EREOF: return L"Erase EOF";
case VK_PA1: return L"PA1";
case VK_OEM_CLEAR: return L"OEM Clear";
case 0:
case 1:
case 0xFF:
break;
default:
{
string langStrId = StringConverter::ToSingle (wstring (wxString::Format (L"VKEY_%02X", virtualKeyCode)));
if (LangString.Exists (langStrId))
return LangString[langStrId];
}
}
#endif // TC_WINDOWS
return L"";
}
HotkeyList Hotkey::LoadList ()
{
HotkeyList hotkeys = GetAvailableHotkeys();
FilePath path = Application::GetConfigFilePath (GetFileName());
if (path.IsFile())
{
foreach (XmlNode node, XmlParser (path).GetNodes (L"hotkey"))
{
wstring keyName (node.Attributes[L"name"]);
foreach (shared_ptr <Hotkey> hotkey, hotkeys)
{
if (hotkey->Name == keyName)
{
hotkey->VirtualKeyCode = StringConverter::ToUInt32 (wstring (node.Attributes[L"vkeycode"]));
hotkey->VirtualKeyModifiers = 0;
if (node.Attributes[L"modshift"] == L"1")
hotkey->VirtualKeyModifiers |= wxMOD_SHIFT;
if (node.Attributes[L"modcontrol"] == L"1")
hotkey->VirtualKeyModifiers |= wxMOD_CONTROL;
if (node.Attributes[L"modalt"] == L"1")
hotkey->VirtualKeyModifiers |= wxMOD_ALT;
if (node.Attributes[L"modwin"] == L"1")
hotkey->VirtualKeyModifiers |= wxMOD_WIN;
break;
}
}
}
}
return hotkeys;
}
void Hotkey::RegisterList (wxWindow *handler, const HotkeyList &hotkeys)
{
#ifdef TC_WINDOWS
bool res = true;
foreach (shared_ptr <Hotkey> hotkey, hotkeys)
{
if (hotkey->VirtualKeyCode != 0)
{
if (!handler->RegisterHotKey (hotkey->Id, hotkey->VirtualKeyModifiers, hotkey->VirtualKeyCode))
res = false;
}
}
if (!res)
Gui->ShowWarning ("HOTKEY_REGISTRATION_ERROR");
#endif
}
void Hotkey::SaveList (const HotkeyList &hotkeys)
{
FilePath hotkeysCfgPath = Application::GetConfigFilePath (GetFileName(), true);
bool noHotkey = true;
XmlNode hotkeysXml (L"hotkeys");
foreach_ref (const Hotkey &hotkey, hotkeys)
{
if (hotkey.VirtualKeyCode == 0)
continue;
noHotkey = false;
XmlNode node (L"hotkey");
node.Attributes[L"name"] = wstring (hotkey.Name);
node.Attributes[L"vkeycode"] = StringConverter::FromNumber (hotkey.VirtualKeyCode);
if (hotkey.VirtualKeyModifiers & wxMOD_SHIFT)
node.Attributes[L"modshift"] = L"1";
if (hotkey.VirtualKeyModifiers & wxMOD_CONTROL)
node.Attributes[L"modcontrol"] = L"1";
if (hotkey.VirtualKeyModifiers & wxMOD_ALT)
node.Attributes[L"modalt"] = L"1";
if (hotkey.VirtualKeyModifiers & wxMOD_WIN )
node.Attributes[L"modwin"] = L"1";
hotkeysXml.InnerNodes.push_back (node);
}
if (noHotkey)
{
if (hotkeysCfgPath.IsFile())
hotkeysCfgPath.Delete();
}
else
{
XmlWriter hotkeysWriter (hotkeysCfgPath);
hotkeysWriter.WriteNode (hotkeysXml);
hotkeysWriter.Close();
}
}
void Hotkey::UnregisterList (wxWindow *handler, const HotkeyList &hotkeys)
{
#ifdef TC_WINDOWS
foreach (shared_ptr <Hotkey> hotkey, hotkeys)
{
if (hotkey->VirtualKeyCode != 0)
handler->UnregisterHotKey (hotkey->Id);
}
#endif
}
}

63
src/Main/Hotkey.h Normal file
View File

@@ -0,0 +1,63 @@
/*
Copyright (c) 2008-2009 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.
*/
#ifndef TC_HEADER_Main_Hotkey
#define TC_HEADER_Main_Hotkey
#include "System.h"
#include "Main.h"
namespace TrueCrypt
{
struct Hotkey;
typedef list < shared_ptr <Hotkey> > HotkeyList;
struct Hotkey
{
public:
struct Id
{
enum
{
CloseAllSecurityTokenSessions = 0,
DismountAll,
DismountAllWipeCache,
ForceDismountAllWipeCache,
ForceDismountAllWipeCacheExit,
MountAllDevices,
MountAllFavorites,
ShowHideApplication,
WipeCache
};
};
Hotkey (int id, const wstring &name, const wxString &description, int virtualKeyCode = 0, int virtualKeyModifiers = 0)
: Description (description), Id (id), Name (name), VirtualKeyCode (virtualKeyCode), VirtualKeyModifiers (virtualKeyModifiers) { }
virtual ~Hotkey () { }
static HotkeyList GetAvailableHotkeys ();
wxString GetShortcutString () const;
static wxString GetVirtualKeyCodeString (int virtualKeyCode);
static HotkeyList LoadList ();
static void RegisterList (wxWindow *handler, const HotkeyList &hotkeys);
static void SaveList (const HotkeyList &hotkeys);
static void UnregisterList (wxWindow *handler, const HotkeyList &hotkeys);
wxString Description;
int Id;
wstring Name;
int VirtualKeyCode;
int VirtualKeyModifiers;
protected:
static wxString GetFileName () { return L"Hotkeys.xml"; }
};
}
#endif // TC_HEADER_Main_Hotkey

View File

@@ -0,0 +1,86 @@
/*
Copyright (c) 2008-2009 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"
#include "Resources.h"
#include "LanguageStrings.h"
#include "Xml.h"
namespace TrueCrypt
{
LanguageStrings::LanguageStrings ()
{
}
LanguageStrings::~LanguageStrings ()
{
}
wxString LanguageStrings::operator[] (const string &key) const
{
if (Map.count (key) > 0)
return wxString (Map.find (key)->second);
return wxString (L"?") + StringConverter::ToWide (key) + L"?";
}
wstring LanguageStrings::Get (const string &key) const
{
return wstring (LangString[key]);
}
void LanguageStrings::Init ()
{
foreach (XmlNode node, XmlParser (Resources::GetLanguageXml()).GetNodes (L"string"))
{
wxString text = node.InnerText;
text.Replace (L"\\n", L"\n");
Map[StringConverter::ToSingle (wstring (node.Attributes[L"key"]))] = text;
}
foreach (XmlNode node, XmlParser (Resources::GetLanguageXml()).GetNodes (L"control"))
{
wxString text = node.InnerText;
text.Replace (L"\\n", L"\n");
Map[StringConverter::ToSingle (wstring (node.Attributes[L"key"]))] = text;
}
Map["EXCEPTION_OCCURRED"] = _("Exception occurred");
Map["MOUNT"] = _("Mount");
Map["MOUNT_POINT"] = _("Mount Directory");
Map["NO"] = _("No");
Map["NO_VOLUMES_MOUNTED"] = _("No volumes mounted.");
Map["OPEN_NEW_VOLUME"] = _("Specify a New TrueCrypt Volume");
Map["PARAMETER_INCORRECT"] = _("Parameter incorrrect");
Map["SELECT_KEYFILES"] = _("Select Keyfiles");
Map["START_TC"] = _("Start TrueCrypt");
Map["VOLUME_ALREADY_MOUNTED"] = _("The volume \"{0}\" is already mounted.");
Map["UNKNOWN_OPTION"] = _("Unknown option");
Map["VOLUME_LOCATION"] = _("Volume Location");
Map["YES"] = _("Yes");
Map["VOLUME_HOST_IN_USE"] = _("WARNING: The host file/device \"{0}\" is already in use!\n\nIgnoring this can cause undesired results including system instability. All applications that might be using the host file/device should be closed before mounting the volume.\n\nContinue mounting?");
Map["VIRTUAL_DEVICE"] = _("Virtual Device");
Map["CONFIRM_BACKGROUND_TASK_DISABLED"] = _("WARNING: If the TrueCrypt Background Task is disabled, the following functions, depending on the platform, will be disabled whenever you exit TrueCrypt:\n\n1) Auto-dismount (e.g., upon logoff, time-out, etc.)\n2) Notifications (e.g., when damage to hidden volume is prevented)\n3) Tray icon\n\nNote: You may shut down the Background Task anytime by right-clicking the TrueCrypt tray icon and selecting 'Exit'.\n\nAre you sure you want to disable the TrueCrypt Background Task?");
Map["CONFIRM_EXIT"] = _("WARNING: If TrueCrypt exits now, the following functions, depending on the platform, will be disabled:\n\n1) Auto-dismount (e.g., upon logoff, time-out, etc.)\n2) Notifications (e.g., when damage to hidden volume is prevented)\n3) Tray icon\n\nNote: If you do not wish TrueCrypt to continue running in background after you close its window, disable the Background Task in the Preferences.\n\nAre you sure you want TrueCrypt to exit?");
Map["DAMAGE_TO_HIDDEN_VOLUME_PREVENTED"] = _("WARNING: Data were attempted to be saved to the hidden volume area of the volume \"{0}\"!\n\nTrueCrypt prevented these data from being saved in order to protect the hidden volume. This may have caused filesystem corruption on the outer volume and the operating system may have reported a write error (\"Delayed Write Failed\", \"The parameter is incorrect\", etc.). The entire volume (both the outer and the hidden part) will be write-protected until it is dismounted.\n\nWe strongly recommend that you restart the operating system now.");
Map["ENTER_PASSWORD"] = _("Enter password");
Map["ENTER_PASSWORD_FOR"] = _("Enter password for \"{0}\"");
Map["ENTER_TC_VOL_PASSWORD"] = _("Enter TrueCrypt Volume Password");
Map["SELECT_KEYFILE_PATH"] = _("Select Keyfile Search Path");
Map["MORE_INFO_ABOUT"] = _("More information on {0}");
Map["TWO_LAYER_CASCADE_HELP"] = _("Two ciphers in a cascade operating in XTS mode. Each block is first encrypted with {0} ({1}-bit key) and then with {2} ({3}-bit key). Each cipher uses its own key. All keys are mutually independent.");
Map["THREE_LAYER_CASCADE_HELP"] = _("Three ciphers in a cascade operating in XTS mode. Each block is first encrypted with {0} ({1}-bit key), then with {2} ({3}-bit key), and finally with {4} ({5}-bit key). Each cipher uses its own key. All keys are mutually independent.");
Map["CHECKING_FS"] = _("Checking the file system on the TrueCrypt volume mounted as {0}...");
Map["REPAIRING_FS"] = _("Attempting to repair the file system on the TrueCrypt volume mounted as {0}...");
Map["UNMOUNT_LOCK_FAILED"] = _("Volume \"{0}\" contains files or folders being used by applications or system.\n\nForce dismount?");
Map["VOLUME_SIZE_HELP"] = _("Please specify the size of the container to create. Note that the minimum possible size of a volume is 292 KB.");
Map["ENCRYPTION_MODE_NOT_SUPPORTED_BY_KERNEL"] = _("The volume you have mounted uses a mode of operation that is not supported by the Linux kernel. You may experience slow performance when using this volume. To achieve full performance, you should move the data from this volume to a new volume created by TrueCrypt 5.0 or later.");
}
LanguageStrings LangString;
}

View File

@@ -0,0 +1,40 @@
/*
Copyright (c) 2008 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.
*/
#ifndef TC_HEADER_Main_LanguageStrings
#define TC_HEADER_Main_LanguageStrings
#include "System.h"
#include "Main.h"
namespace TrueCrypt
{
class LanguageStrings
{
public:
LanguageStrings ();
virtual ~LanguageStrings ();
wxString operator[] (const string &key) const;
bool Exists (const string &key) const { return Map.find (key) != Map.end(); }
wstring Get (const string &key) const;
void Init ();
protected:
map <string, wstring> Map;
private:
LanguageStrings (const LanguageStrings &);
LanguageStrings &operator= (const LanguageStrings &);
};
extern LanguageStrings LangString;
}
#endif // TC_HEADER_Main_LanguageStrings

17
src/Main/Main.h Normal file
View File

@@ -0,0 +1,17 @@
/*
Copyright (c) 2008 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.
*/
#ifndef TC_HEADER_Main_Main
#define TC_HEADER_Main_Main
#include "System.h"
#include "Platform/Platform.h"
#include "Core/Core.h"
#include "Main/StringFormatter.h"
#endif // TC_HEADER_Main_Main

145
src/Main/Main.make Normal file
View File

@@ -0,0 +1,145 @@
#
# Copyright (c) 2008-2009 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.
#
OBJS :=
OBJS += Application.o
OBJS += CommandLineInterface.o
OBJS += FavoriteVolume.o
OBJS += LanguageStrings.o
OBJS += StringFormatter.o
OBJS += TextUserInterface.o
OBJS += UserInterface.o
OBJS += UserPreferences.o
OBJS += Xml.o
OBJS += Unix/Main.o
OBJS += Resources.o
ifndef TC_NO_GUI
OBJS += FatalErrorHandler.o
OBJS += GraphicUserInterface.o
OBJS += VolumeHistory.o
OBJS += Forms/AboutDialog.o
OBJS += Forms/BenchmarkDialog.o
OBJS += Forms/ChangePasswordDialog.o
OBJS += Forms/DeviceSelectionDialog.o
OBJS += Forms/EncryptionOptionsWizardPage.o
OBJS += Forms/EncryptionTestDialog.o
OBJS += Forms/FavoriteVolumesDialog.o
OBJS += Forms/Forms.o
OBJS += Forms/InfoWizardPage.o
OBJS += Forms/KeyfileGeneratorDialog.o
OBJS += Forms/KeyfilesDialog.o
OBJS += Forms/KeyfilesPanel.o
OBJS += Forms/LegalNoticesDialog.o
OBJS += Forms/MainFrame.o
OBJS += Forms/MountOptionsDialog.o
OBJS += Forms/NewSecurityTokenKeyfileDialog.o
OBJS += Forms/PreferencesDialog.o
OBJS += Forms/ProgressWizardPage.o
OBJS += Forms/RandomPoolEnrichmentDialog.o
OBJS += Forms/SecurityTokenKeyfilesDialog.o
OBJS += Forms/SelectDirectoryWizardPage.o
OBJS += Forms/VolumePasswordPanel.o
OBJS += Forms/VolumePropertiesDialog.o
OBJS += Forms/VolumeCreationProgressWizardPage.o
OBJS += Forms/VolumeCreationWizard.o
OBJS += Forms/VolumeFormatOptionsWizardPage.o
OBJS += Forms/VolumeLocationWizardPage.o
OBJS += Forms/VolumePasswordWizardPage.o
OBJS += Forms/VolumeSizeWizardPage.o
OBJS += Forms/WizardFrame.o
endif
ifndef DISABLE_PRECOMPILED_HEADERS
PCH := SystemPrecompiled.h.gch
endif
RESOURCES :=
RESOURCES += ../License.txt.h
RESOURCES += ../Common/Language.xml.h
ifndef TC_NO_GUI
RESOURCES += ../Common/Textual_logo_96dpi.bmp.h
RESOURCES += ../Format/TrueCrypt_Wizard.bmp.h
RESOURCES += ../Mount/Drive_icon_96dpi.bmp.h
RESOURCES += ../Mount/Drive_icon_mask_96dpi.bmp.h
RESOURCES += ../Mount/Logo_96dpi.bmp.h
endif
CXXFLAGS += -I$(BASE_DIR)/Main
#------ wxWidgets configuration ------
ifdef TC_NO_GUI
WX_CONFIG_LIBS := base
else
WX_CONFIG_LIBS := adv,core,base
endif
ifeq "$(TC_BUILD_CONFIG)" "Release"
CXXFLAGS += $(shell $(WX_CONFIG) $(WX_CONFIG_ARGS) --cxxflags)
WX_LIBS = $(shell $(WX_CONFIG) $(WX_CONFIG_ARGS) --libs $(WX_CONFIG_LIBS))
else
CXXFLAGS += $(shell $(WX_CONFIG) --debug $(WX_CONFIG_ARGS) --cxxflags)
WX_LIBS = $(shell $(WX_CONFIG) --debug $(WX_CONFIG_ARGS) --libs $(WX_CONFIG_LIBS))
endif
#------ FUSE configuration ------
FUSE_LIBS = $(shell pkg-config fuse --libs)
#------ Executable ------
TC_VERSION = $(shell grep VERSION_STRING ../Common/Tcdefs.h | head -n 1 | cut -d'"' -f 2)
$(APPNAME): $(LIBS) $(OBJS)
@echo Linking $@
$(CXX) -o $(APPNAME) $(LFLAGS) $(OBJS) $(LIBS) $(FUSE_LIBS) $(WX_LIBS)
ifeq "$(TC_BUILD_CONFIG)" "Release"
ifndef NOSTRIP
strip $(APPNAME)
endif
ifndef NOTEST
./$(APPNAME) --text --test >/dev/null || exit 1
endif
ifeq "$(PLATFORM_UNSUPPORTED)" "1"
@echo; echo "WARNING: This platform may be unsupported. To avoid possible serious problems, please read the chapter pertaining to $(PLATFORM) in Readme.txt."; echo
endif
endif
ifeq "$(PLATFORM)" "MacOSX"
mkdir -p $(APPNAME).app/Contents/MacOS $(APPNAME).app/Contents/Resources
-rm -f $(APPNAME).app/Contents/MacOS/$(APPNAME)
ifeq "$(TC_BUILD_CONFIG)" "Release"
cp $(PWD)/Main/$(APPNAME) $(APPNAME).app/Contents/MacOS/$(APPNAME)
else
-ln -sf $(PWD)/Main/$(APPNAME) $(APPNAME).app/Contents/MacOS/$(APPNAME)
endif
cp $(PWD)/Resources/Icons/TrueCrypt.icns $(APPNAME).app/Contents/Resources
echo -n APPLTRUE >$(APPNAME).app/Contents/PkgInfo
sed -e 's/_VERSION_/$(patsubst %a,%.1,$(patsubst %b,%.2,$(TC_VERSION)))/' ../Build/Resources/MacOSX/Info.plist.xml >$(APPNAME).app/Contents/Info.plist
endif
$(OBJS): $(PCH)
Resources.o: $(RESOURCES)
include $(BUILD_INC)/Makefile.inc

184
src/Main/Resources.cpp Normal file
View File

@@ -0,0 +1,184 @@
/*
Copyright (c) 2008 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"
#include "Platform/Platform.h"
#include "Resources.h"
#ifdef TC_WINDOWS
#include "Main/resource.h"
#endif
namespace TrueCrypt
{
#ifdef TC_WINDOWS
static ConstBufferPtr GetWindowsResource (const wchar_t *resourceType, const wchar_t *resourceName)
{
HGLOBAL hResL;
HRSRC hRes;
hRes = FindResource (NULL, resourceName, resourceType);
throw_sys_if (!hRes);
hResL = LoadResource (NULL, hRes);
throw_sys_if (!hResL);
const byte *resPtr = (const byte *) LockResource (hResL);
throw_sys_if (!resPtr);
return ConstBufferPtr (resPtr, SizeofResource (NULL, hRes));
}
#endif // TC_WINDOWS
string Resources::GetLanguageXml ()
{
#ifdef TC_WINDOWS
ConstBufferPtr res = GetWindowsResource (L"XML", L"IDR_LANGUAGE");
Buffer strBuf (res.Size() + 1);
strBuf.Zero();
strBuf.CopyFrom (res);
return string (reinterpret_cast <char *> (strBuf.Ptr()));
#else
static const char LanguageXml[] =
{
# include "Common/Language.xml.h"
, 0
};
return string (LanguageXml);
#endif
}
string Resources::GetLegalNotices ()
{
#ifdef TC_WINDOWS
ConstBufferPtr res = GetWindowsResource (L"TEXT", L"IDR_LICENSE");
Buffer strBuf (res.Size() + 1);
strBuf.Zero();
strBuf.CopyFrom (res);
return string (reinterpret_cast <char *> (strBuf.Ptr()));
#else
static const char License[] =
{
# include "License.txt.h"
, 0
};
return string (License);
#endif
}
#ifndef TC_NO_GUI
wxBitmap Resources::GetDriveIconBitmap ()
{
#ifdef TC_WINDOWS
return wxBitmap (L"IDB_DRIVE_ICON", wxBITMAP_TYPE_BMP_RESOURCE).ConvertToImage().Resize (wxSize (16, 12), wxPoint (0, 0));
#else
static const byte DriveIcon[] =
{
# include "Mount/Drive_icon_96dpi.bmp.h"
};
wxMemoryInputStream stream (DriveIcon, sizeof (DriveIcon));
return wxBitmap (wxImage (stream).Resize (wxSize (16, 12), wxPoint (0, 0)));
#endif
}
wxBitmap Resources::GetDriveIconMaskBitmap ()
{
#ifdef TC_WINDOWS
wxImage image = wxBitmap (L"IDB_DRIVE_ICON_MASK", wxBITMAP_TYPE_BMP_RESOURCE).ConvertToImage().Resize (wxSize (16, 12), wxPoint (0, 0));
return wxBitmap (image.ConvertToMono (0, 0, 0), 1);
#else
static const byte DriveIconMask[] =
{
# include "Mount/Drive_icon_mask_96dpi.bmp.h"
};
wxMemoryInputStream stream (DriveIconMask, sizeof (DriveIconMask));
wxImage image (stream);
image.Resize (wxSize (16, 12), wxPoint (0, 0));
# ifdef __WXGTK__
return wxBitmap (image.ConvertToMono (0, 0, 0), 1);
# else
return wxBitmap (image);
# endif
#endif
}
wxBitmap Resources::GetLogoBitmap ()
{
#ifdef TC_WINDOWS
return wxBitmap (L"IDB_LOGO", wxBITMAP_TYPE_BMP_RESOURCE);
#else
static const byte Logo[] =
{
# include "Mount/Logo_96dpi.bmp.h"
};
wxMemoryInputStream stream (Logo, sizeof (Logo));
return wxBitmap (wxImage (stream));
#endif
}
wxBitmap Resources::GetTextualLogoBitmap ()
{
#ifdef TC_WINDOWS
return wxBitmap (L"IDB_TEXTUAL_LOGO", wxBITMAP_TYPE_BMP_RESOURCE);
#else
static const byte Logo[] =
{
# include "Common/Textual_logo_96dpi.bmp.h"
};
wxMemoryInputStream stream (Logo, sizeof (Logo));
return wxBitmap (wxImage (stream));
#endif
}
wxIcon Resources::GetTrueCryptIcon ()
{
#ifdef TC_WINDOWS
return wxIcon (L"IDI_TRUECRYPT_ICON", wxBITMAP_TYPE_ICO_RESOURCE, 16, 16);
#else
# include "Resources/Icons/TrueCrypt-16x16.xpm"
return wxIcon (TrueCryptIcon16x16);
#endif
}
wxBitmap Resources::GetVolumeCreationWizardBitmap (int height)
{
#ifdef TC_WINDOWS
return wxBitmap (L"IDB_VOLUME_WIZARD_BITMAP", wxBITMAP_TYPE_BMP_RESOURCE);
#else
static const byte VolumeWizardIcon[] =
{
# include "Format/TrueCrypt_Wizard.bmp.h"
};
wxMemoryInputStream stream (VolumeWizardIcon, sizeof (VolumeWizardIcon));
wxImage image (stream);
if (height != -1)
{
double scaleFactor = double (height) / double (image.GetHeight());
image.Rescale (int (image.GetWidth() * scaleFactor), int (image.GetHeight() * scaleFactor), wxIMAGE_QUALITY_HIGH);
}
return wxBitmap (image);
#endif
}
#endif // !TC_NO_GUI
}

33
src/Main/Resources.h Normal file
View File

@@ -0,0 +1,33 @@
/*
Copyright (c) 2008 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.
*/
#ifndef TC_HEADER_Main_Resources
#define TC_HEADER_Main_Resources
#include "System.h"
#include "Platform/Platform.h"
namespace TrueCrypt
{
class Resources
{
public:
static string GetLanguageXml ();
static string GetLegalNotices ();
#ifndef TC_NO_GUI
static wxBitmap GetDriveIconBitmap ();
static wxBitmap GetDriveIconMaskBitmap ();
static wxBitmap GetLogoBitmap ();
static wxBitmap GetTextualLogoBitmap ();
static wxIcon GetTrueCryptIcon ();
static wxBitmap GetVolumeCreationWizardBitmap (int height = -1);
#endif
};
}
#endif // TC_HEADER_Main_Resources

View File

@@ -0,0 +1,88 @@
/*
Copyright (c) 2008 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"
#include "StringFormatter.h"
#include "UserInterfaceException.h"
namespace TrueCrypt
{
StringFormatter::StringFormatter (const wxString &format, StringFormatterArg arg0, StringFormatterArg arg1, StringFormatterArg arg2, StringFormatterArg arg3, StringFormatterArg arg4, StringFormatterArg arg5, StringFormatterArg arg6, StringFormatterArg arg7, StringFormatterArg arg8, StringFormatterArg arg9)
{
bool numberExpected = false;
bool endTagExpected = false;
foreach (wchar_t c, wstring (format))
{
if (numberExpected)
{
endTagExpected = true;
bool err = false;
switch (c)
{
case L'{': FormattedString += L'{'; endTagExpected = false; break; // Escaped {
case L'0': FormattedString += arg0; err = arg0.IsEmpty(); break;
case L'1': FormattedString += arg1; err = arg1.IsEmpty(); break;
case L'2': FormattedString += arg2; err = arg2.IsEmpty(); break;
case L'3': FormattedString += arg3; err = arg3.IsEmpty(); break;
case L'4': FormattedString += arg4; err = arg4.IsEmpty(); break;
case L'5': FormattedString += arg5; err = arg5.IsEmpty(); break;
case L'6': FormattedString += arg6; err = arg6.IsEmpty(); break;
case L'7': FormattedString += arg7; err = arg7.IsEmpty(); break;
case L'8': FormattedString += arg8; err = arg8.IsEmpty(); break;
case L'9': FormattedString += arg9; err = arg9.IsEmpty(); break;
default: err = true; break;
}
if (err)
throw StringFormatterException (SRC_POS, wstring (format));
numberExpected = false;
}
else if (endTagExpected)
{
if (c != L'}')
throw StringFormatterException (SRC_POS, wstring (format));
endTagExpected = false;
}
else if (c == L'{')
{
numberExpected = true;
}
else if (c == L'}')
{
FormattedString += c;
endTagExpected = true;
}
else
FormattedString += c;
}
if (numberExpected
|| endTagExpected
|| (!arg0.WasReferenced() && !arg0.IsEmpty())
|| (!arg1.WasReferenced() && !arg1.IsEmpty())
|| (!arg2.WasReferenced() && !arg2.IsEmpty())
|| (!arg3.WasReferenced() && !arg3.IsEmpty())
|| (!arg4.WasReferenced() && !arg4.IsEmpty())
|| (!arg5.WasReferenced() && !arg5.IsEmpty())
|| (!arg6.WasReferenced() && !arg6.IsEmpty())
|| (!arg7.WasReferenced() && !arg7.IsEmpty())
|| (!arg8.WasReferenced() && !arg8.IsEmpty())
|| (!arg9.WasReferenced() && !arg9.IsEmpty())
)
throw StringFormatterException (SRC_POS, wstring (format));
}
StringFormatter::~StringFormatter ()
{
}
}

View File

@@ -0,0 +1,64 @@
/*
Copyright (c) 2008 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.
*/
#ifndef TC_HEADER_Main_StringFormatter
#define TC_HEADER_Main_StringFormatter
#include "System.h"
#include "Main.h"
namespace TrueCrypt
{
class StringFormatterArg
{
public:
StringFormatterArg () : Empty (true) { }
StringFormatterArg (const char c) : Empty (false) { string s; s += c; StringArg = StringConverter::ToWide (s); }
StringFormatterArg (const wchar_t c) : Empty (false), Referenced (false), StringArg (c) { }
StringFormatterArg (const char *str) : Empty (false), Referenced (false), StringArg (StringConverter::ToWide (str)) { }
StringFormatterArg (const wchar_t *str) : Empty (false), Referenced (false), StringArg (str) { }
StringFormatterArg (const string &str) : Empty (false), Referenced (false), StringArg (StringConverter::ToWide (str)) { }
StringFormatterArg (const wstring &str) : Empty (false), Referenced (false), StringArg (str) { }
StringFormatterArg (const wxString &str) : Empty (false), Referenced (false), StringArg (str) { }
StringFormatterArg (int32 number) : Empty (false), Referenced (false), StringArg (StringConverter::FromNumber (number)) { }
StringFormatterArg (uint32 number) : Empty (false), Referenced (false), StringArg (StringConverter::FromNumber (number)) { }
StringFormatterArg (int64 number) : Empty (false), Referenced (false), StringArg (StringConverter::FromNumber (number)) { }
StringFormatterArg (uint64 number) : Empty (false), Referenced (false), StringArg (StringConverter::FromNumber (number)) { }
operator wxString () { Referenced = true; return StringArg; }
bool IsEmpty () const { return Empty; }
bool WasReferenced() const { return Referenced; }
protected:
bool Empty;
bool Referenced;
wxString StringArg;
};
class StringFormatter
{
public:
StringFormatter (const wxString &format, StringFormatterArg arg0 = StringFormatterArg(), StringFormatterArg arg1 = StringFormatterArg(), StringFormatterArg arg2 = StringFormatterArg(), StringFormatterArg arg3 = StringFormatterArg(), StringFormatterArg arg4 = StringFormatterArg(), StringFormatterArg arg5 = StringFormatterArg(), StringFormatterArg arg6 = StringFormatterArg(), StringFormatterArg arg7 = StringFormatterArg(), StringFormatterArg arg8 = StringFormatterArg(), StringFormatterArg arg9 = StringFormatterArg());
virtual ~StringFormatter ();
operator wstring () const { return wstring (FormattedString); }
operator wxString () const { return FormattedString; }
operator StringFormatterArg () const { return FormattedString; }
protected:
wxString FormattedString;
private:
StringFormatter (const StringFormatter &);
StringFormatter &operator= (const StringFormatter &);
};
}
#endif // TC_HEADER_Main_StringFormatter

10
src/Main/System.cpp Normal file
View File

@@ -0,0 +1,10 @@
/*
Copyright (c) 2008 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.
*/
// Precompiled header
#include "System.h"

69
src/Main/System.h Normal file
View File

@@ -0,0 +1,69 @@
/*
Copyright (c) 2008 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.
*/
#ifndef TC_HEADER_Main_System
#define TC_HEADER_Main_System
#ifndef TC_WINDOWS
#include "SystemPrecompiled.h"
#else
#ifndef WINVER
#define WINVER 0x0501
#endif
#ifndef TC_LOCAL_WIN32_WINNT_OVERRIDE
# ifndef _WIN32_WINNT
# define _WIN32_WINNT 0x0501
# endif
#endif
#ifndef _WIN32_WINDOWS
#define _WIN32_WINDOWS 0x0410
#endif
#ifndef _WIN32_IE
#define _WIN32_IE 0x0600
#endif
#define WIN32_LEAN_AND_MEAN
#ifndef UNICODE
#define UNICODE
#endif
#ifndef _UNICODE
#define _UNICODE
#endif _UNICODE
#include <wx/wxprec.h>
#include <wx/dde.h>
#include <wx/dnd.h>
#include <wx/filename.h>
#include <wx/hyperlink.h>
#include <wx/imaglist.h>
#include <wx/listctrl.h>
#include <wx/mstream.h>
#include <wx/power.h>
#include <wx/snglinst.h>
#include <wx/taskbar.h>
#include <wx/txtstrm.h>
#include <wx/valgen.h>
#include <wx/wfstream.h>
#include <shellapi.h>
#include <iostream>
#include <memory.h>
#include <stdio.h>
#include <stdlib.h>
#endif
#endif // TC_HEADER_Main_System

View File

@@ -0,0 +1,29 @@
/*
Copyright (c) 2008 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 <wx/wx.h>
#include <wx/filename.h>
#include <wx/mstream.h>
#include <wx/snglinst.h>
#include <wx/txtstrm.h>
#include <wx/wfstream.h>
#ifndef TC_NO_GUI
#include <wx/dnd.h>
#include <wx/hyperlink.h>
#include <wx/listctrl.h>
#include <wx/imaglist.h>
#include <wx/power.h>
#include <wx/taskbar.h>
#include <wx/valgen.h>
#endif
#include <iostream>
#include <memory.h>
#include <stdio.h>
#include <stdlib.h>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,78 @@
/*
Copyright (c) 2008-2009 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.
*/
#ifndef TC_HEADER_Main_TextUserInterface
#define TC_HEADER_Main_TextUserInterface
#include "System.h"
#include "Main.h"
#include "UserInterface.h"
namespace TrueCrypt
{
class TextUserInterface : public UserInterface
{
public:
TextUserInterface ();
virtual ~TextUserInterface ();
virtual FilePath AskFilePath (const wxString &message = wxEmptyString) const;
virtual shared_ptr <KeyfileList> AskKeyfiles (const wxString &message = L"") const;
virtual shared_ptr <VolumePassword> AskPassword (const wxString &message = L"", bool verify = false) const;
virtual ssize_t AskSelection (ssize_t optionCount, ssize_t defaultOption = -1) const;
virtual wstring AskString (const wxString &message = wxEmptyString) const;
virtual shared_ptr <VolumePath> AskVolumePath (const wxString &message = L"") const;
virtual bool AskYesNo (const wxString &message, bool defaultYes = false, bool warning = false) const;
virtual void BackupVolumeHeaders (shared_ptr <VolumePath> volumePath) const;
virtual void BeginBusyState () const { }
virtual void ChangePassword (shared_ptr <VolumePath> volumePath = shared_ptr <VolumePath>(), shared_ptr <VolumePassword> password = shared_ptr <VolumePassword>(), shared_ptr <KeyfileList> keyfiles = shared_ptr <KeyfileList>(), shared_ptr <VolumePassword> newPassword = shared_ptr <VolumePassword>(), shared_ptr <KeyfileList> newKeyfiles = shared_ptr <KeyfileList>(), shared_ptr <Hash> newHash = shared_ptr <Hash>()) const;
virtual void CreateKeyfile (shared_ptr <FilePath> keyfilePath = shared_ptr <FilePath>()) const;
virtual void CreateVolume (shared_ptr <VolumeCreationOptions> options) const;
virtual void DeleteSecurityTokenKeyfiles () const;
virtual void DoShowError (const wxString &message) const;
virtual void DoShowInfo (const wxString &message) const;
virtual void DoShowString (const wxString &str) const;
virtual void DoShowWarning (const wxString &message) const;
virtual void EndBusyState () const { }
virtual void ExportSecurityTokenKeyfile () const;
virtual shared_ptr <GetStringFunctor> GetAdminPasswordRequestHandler ();
virtual void ImportSecurityTokenKeyfiles () const;
#ifndef TC_NO_GUI
virtual bool Initialize (int &argc, wxChar **argv) { return wxAppBase::Initialize(argc, argv); }
#endif
virtual void InitSecurityTokenLibrary () const;
virtual void ListSecurityTokenKeyfiles () const;
virtual VolumeInfoList MountAllDeviceHostedVolumes (MountOptions &options) const;
virtual shared_ptr <VolumeInfo> MountVolume (MountOptions &options) const;
virtual bool OnInit ();
#ifndef TC_NO_GUI
virtual bool OnInitGui () { return true; }
#endif
virtual int OnRun();
virtual void RestoreVolumeHeaders (shared_ptr <VolumePath> volumePath) const;
static void SetTerminalEcho (bool enable);
virtual void UserEnrichRandomPool () const;
virtual void Yield () const { }
protected:
static void OnSignal (int signal);
virtual void ReadInputStreamLine (wxString &line) const;
virtual wxString ReadInputStreamLine () const;
auto_ptr <wxFFileInputStream> FInputStream;
auto_ptr <wxTextInputStream> TextInputStream;
private:
TextUserInterface (const TextUserInterface &);
TextUserInterface &operator= (const TextUserInterface &);
};
extern wxMessageOutput *DefaultMessageOutput;
}
#endif // TC_HEADER_Main_TextUserInterface

127
src/Main/Unix/Main.cpp Normal file
View File

@@ -0,0 +1,127 @@
/*
Copyright (c) 2008-2009 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"
#include <sys/mman.h>
#include "Platform/Platform.h"
#include "Platform/SystemLog.h"
#include "Volume/EncryptionThreadPool.h"
#include "Core/Unix/CoreService.h"
#include "Main/Application.h"
#include "Main/Main.h"
#include "Main/UserInterface.h"
#if defined (TC_MACOSX) && !defined (TC_NO_GUI)
#include <ApplicationServices/ApplicationServices.h>
#endif
using namespace TrueCrypt;
int main (int argc, char **argv)
{
try
{
// Make sure all required commands can be executed via default search path
string sysPathStr = "/usr/sbin:/sbin:/usr/bin:/bin";
char *sysPath = getenv ("PATH");
if (sysPath)
{
sysPathStr += ":";
sysPathStr += sysPath;
}
setenv ("PATH", sysPathStr.c_str(), 1);
if (argc > 1 && strcmp (argv[1], TC_CORE_SERVICE_CMDLINE_OPTION) == 0)
{
// Process elevated requests
try
{
CoreService::ProcessElevatedRequests();
return 0;
}
catch (exception &e)
{
#ifdef DEBUG
SystemLog::WriteException (e);
#endif
}
catch (...) { }
return 1;
}
// Start core service
CoreService::Start();
finally_do ({ CoreService::Stop(); });
// Start encryption thread pool
EncryptionThreadPool::Start();
finally_do ({ EncryptionThreadPool::Stop(); });
#ifdef TC_NO_GUI
bool forceTextUI = true;
#else
bool forceTextUI = false;
#endif
#ifdef __WXGTK__
if (!getenv ("DISPLAY"))
forceTextUI = true;
#endif
// Initialize application
if (forceTextUI || (argc > 1 && (strcmp (argv[1], "-t") == 0 || strcmp (argv[1], "--text") == 0)))
{
Application::Initialize (UserInterfaceType::Text);
}
else
{
#if defined (TC_MACOSX) && !defined (TC_NO_GUI)
if (argc > 1 && !(argc == 2 && strstr (argv[1], "-psn_") == argv[1]))
{
ProcessSerialNumber p;
if (GetCurrentProcess (&p) == noErr)
{
TransformProcessType (&p, kProcessTransformToForegroundApplication);
SetFrontProcess (&p);
}
}
#endif
Application::Initialize (UserInterfaceType::Graphic);
}
Application::SetExitCode (1);
// Start application
if (::wxEntry (argc, argv) == 0)
Application::SetExitCode (0);
}
catch (ErrorMessage &e)
{
wcerr << wstring (e) << endl;
}
catch (SystemException &e)
{
wstringstream s;
if (e.GetSubject().empty())
s << e.what() << endl << e.SystemText();
else
s << e.what() << endl << e.SystemText() << endl << e.GetSubject();
wcerr << s.str() << endl;
}
catch (exception &e)
{
stringstream s;
s << StringConverter::GetTypeName (typeid (e)) << endl << e.what();
cerr << s.str() << endl;
}
return Application::GetExitCode();
}

1494
src/Main/UserInterface.cpp Normal file

File diff suppressed because it is too large Load Diff

111
src/Main/UserInterface.h Normal file
View File

@@ -0,0 +1,111 @@
/*
Copyright (c) 2008-2009 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.
*/
#ifndef TC_HEADER_Main_UserInterface
#define TC_HEADER_Main_UserInterface
#include "System.h"
#include "Core/Core.h"
#include "Main.h"
#include "CommandLineInterface.h"
#include "FavoriteVolume.h"
#include "LanguageStrings.h"
#include "UserPreferences.h"
#include "UserInterfaceException.h"
#include "UserInterfaceType.h"
namespace TrueCrypt
{
class UserInterface : public wxApp
{
public:
virtual ~UserInterface ();
virtual bool AskYesNo (const wxString &message, bool defaultYes = false, bool warning = false) const = 0;
virtual void BackupVolumeHeaders (shared_ptr <VolumePath> volumePath) const = 0;
virtual void BeginBusyState () const = 0;
virtual void ChangePassword (shared_ptr <VolumePath> volumePath = shared_ptr <VolumePath>(), shared_ptr <VolumePassword> password = shared_ptr <VolumePassword>(), shared_ptr <KeyfileList> keyfiles = shared_ptr <KeyfileList>(), shared_ptr <VolumePassword> newPassword = shared_ptr <VolumePassword>(), shared_ptr <KeyfileList> newKeyfiles = shared_ptr <KeyfileList>(), shared_ptr <Hash> newHash = shared_ptr <Hash>()) const = 0;
virtual void CheckRequirementsForMountingVolume () const;
virtual void CloseExplorerWindows (shared_ptr <VolumeInfo> mountedVolume) const;
virtual void CreateKeyfile (shared_ptr <FilePath> keyfilePath = shared_ptr <FilePath>()) const = 0;
virtual void CreateVolume (shared_ptr <VolumeCreationOptions> options) const = 0;
virtual void DeleteSecurityTokenKeyfiles () const = 0;
virtual void DismountAllVolumes (bool ignoreOpenFiles = false, bool interactive = true) const;
virtual void DismountVolume (shared_ptr <VolumeInfo> volume, bool ignoreOpenFiles = false, bool interactive = true) const;
virtual void DismountVolumes (VolumeInfoList volumes, bool ignoreOpenFiles = false, bool interactive = true) const;
virtual void DisplayVolumeProperties (const VolumeInfoList &volumes) const;
virtual void DoShowError (const wxString &message) const = 0;
virtual void DoShowInfo (const wxString &message) const = 0;
virtual void DoShowString (const wxString &str) const = 0;
virtual void DoShowWarning (const wxString &message) const = 0;
virtual void EndBusyState () const = 0;
virtual wxString ExceptionToMessage (const exception &ex) const;
virtual void ExportSecurityTokenKeyfile () const = 0;
virtual shared_ptr <GetStringFunctor> GetAdminPasswordRequestHandler () = 0;
virtual const UserPreferences &GetPreferences () const { return Preferences; }
virtual void ImportSecurityTokenKeyfiles () const = 0;
virtual void Init ();
virtual void InitSecurityTokenLibrary () const = 0;
virtual void ListMountedVolumes (const VolumeInfoList &volumes) const;
virtual void ListSecurityTokenKeyfiles () const = 0;
virtual shared_ptr <VolumeInfo> MountVolume (MountOptions &options) const;
virtual VolumeInfoList MountAllDeviceHostedVolumes (MountOptions &options) const;
virtual VolumeInfoList MountAllFavoriteVolumes (MountOptions &options);
virtual void OpenExplorerWindow (const DirectoryPath &path);
virtual void RestoreVolumeHeaders (shared_ptr <VolumePath> volumePath) const = 0;
virtual void SetPreferences (const UserPreferences &preferences);
virtual void ShowError (const exception &ex) const;
virtual void ShowError (const char *langStringId) const { DoShowError (LangString[langStringId]); }
virtual void ShowError (const wxString &message) const { DoShowError (message); }
virtual void ShowInfo (const exception &ex) const { DoShowInfo (ExceptionToMessage (ex)); }
virtual void ShowInfo (const char *langStringId) const { DoShowInfo (LangString[langStringId]); }
virtual void ShowInfo (const wxString &message) const { DoShowInfo (message); }
virtual void ShowWarning (const exception &ex) const { DoShowWarning (ExceptionToMessage (ex)); }
virtual void ShowWarning (const char *langStringId) const { DoShowWarning (LangString[langStringId]); }
virtual void ShowString (const wxString &str) const { DoShowString (str); }
virtual void ShowWarning (const wxString &message) const { DoShowWarning (message); }
virtual wxString SizeToString (uint64 size) const;
virtual wxString SpeedToString (uint64 speed) const;
virtual void Test () const;
virtual wxString TimeSpanToString (uint64 seconds) const;
virtual bool VolumeHasUnrecommendedExtension (const VolumePath &path) const;
virtual void Yield () const = 0;
virtual wxDateTime VolumeTimeToDateTime (VolumeTime volumeTime) const { return wxDateTime ((time_t) (volumeTime / 1000ULL / 1000 / 10 - 134774ULL * 24 * 3600)); }
virtual wxString VolumeTimeToString (VolumeTime volumeTime) const;
virtual wxString VolumeTypeToString (VolumeType::Enum type, VolumeProtection::Enum protection) const;
Event PreferencesUpdatedEvent;
struct BusyScope
{
BusyScope (const UserInterface *userInterface) : UI (userInterface) { UI->BeginBusyState (); }
~BusyScope () { UI->EndBusyState (); }
const UserInterface *UI;
};
protected:
UserInterface ();
virtual bool OnExceptionInMainLoop () { throw; }
virtual void OnUnhandledException ();
virtual void OnVolumeMounted (EventArgs &args);
virtual void OnWarning (EventArgs &args);
virtual bool ProcessCommandLine ();
virtual wxString ExceptionToString (const Exception &ex) const;
virtual wxString ExceptionTypeToString (const std::type_info &ex) const;
UserPreferences Preferences;
UserInterfaceType::Enum InterfaceType;
private:
UserInterface (const UserInterface &);
UserInterface &operator= (const UserInterface &);
};
}
#endif // TC_HEADER_Main_UserInterface

View File

@@ -0,0 +1,36 @@
/*
Copyright (c) 2008 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.
*/
#ifndef TC_HEADER_Main_UserInterfaceException
#define TC_HEADER_Main_UserInterfaceException
#include "Platform/Platform.h"
namespace TrueCrypt
{
TC_EXCEPTION_DECL (UserInterfaceException, Exception);
TC_EXCEPTION_DECL (MissingArgument, UserInterfaceException);
TC_EXCEPTION_DECL (NoItemSelected, UserInterfaceException);
TC_EXCEPTION_DECL (StringFormatterException, UserInterfaceException);
struct ErrorMessage : public UserInterfaceException
{
ErrorMessage (const string &exceptionMessage, const wxString &errorMessage) : UserInterfaceException (exceptionMessage), Text (errorMessage) { }
virtual ~ErrorMessage () throw () { }
operator wstring () const { return wstring (Text); }
operator wxString () const { return Text; }
protected:
wxString Text;
};
#define throw_err(message) throw ErrorMessage (SRC_POS, (message))
}
#endif // TC_HEADER_Main_UserInterfaceException

View File

@@ -0,0 +1,25 @@
/*
Copyright (c) 2008 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.
*/
#ifndef TC_HEADER_Main_UserInterfaceType
#define TC_HEADER_Main_UserInterfaceType
namespace TrueCrypt
{
struct UserInterfaceType
{
enum Enum
{
Unknown,
Graphic,
Text
};
};
}
#endif // TC_HEADER_Main_UserInterfaceType

View File

@@ -0,0 +1,235 @@
/*
Copyright (c) 2008 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"
#include "Main/Application.h"
#include "UserPreferences.h"
#include "Xml.h"
namespace TrueCrypt
{
void UserPreferences::SetValue (const wxString &cfgText, bool &cfgVar)
{
if (cfgText == L"0")
cfgVar = false;
else if (cfgText == L"1")
cfgVar = true;
}
void UserPreferences::SetValue (const wxString &cfgText, int &cfgVar)
{
if (cfgText.empty())
cfgVar = 0;
else
cfgVar = StringConverter::ToUInt32 (wstring (cfgText));
}
void UserPreferences::SetValue (const wxString &cfgText, uint64 &cfgVar)
{
if (cfgText.empty())
cfgVar = 0;
else
cfgVar = StringConverter::ToUInt64 (wstring (cfgText));
}
void UserPreferences::SetValue (const wxString &cfgText, wstring &cfgVar)
{
cfgVar = cfgText;
}
void UserPreferences::SetValue (const wxString &cfgText, wxString &cfgVar)
{
cfgVar = cfgText;
}
void UserPreferences::SetValue (const wxString &cfgText, FilesystemPath &cfgVar)
{
cfgVar = wstring (cfgText);
}
void UserPreferences::Load()
{
// Preferences
FilePath cfgPath = Application::GetConfigFilePath (GetPreferencesFileName());
if (cfgPath.IsFile())
{
map <wxString, wxString> configMap;
foreach (XmlNode node, XmlParser (cfgPath).GetNodes (L"config"))
{
configMap[node.Attributes[L"key"]] = node.InnerText;
}
#define TC_CONFIG_SET(NAME) SetValue (configMap[L###NAME], NAME)
TC_CONFIG_SET (BackgroundTaskEnabled);
TC_CONFIG_SET (BackgroundTaskMenuDismountItemsEnabled);
TC_CONFIG_SET (BackgroundTaskMenuMountItemsEnabled);
TC_CONFIG_SET (BackgroundTaskMenuOpenItemsEnabled);
TC_CONFIG_SET (BeepAfterHotkeyMountDismount);
SetValue (configMap[L"CachePasswords"], DefaultMountOptions.CachePassword);
TC_CONFIG_SET (CloseBackgroundTaskOnNoVolumes);
TC_CONFIG_SET (CloseExplorerWindowsOnDismount);
TC_CONFIG_SET (CloseSecurityTokenSessionsAfterMount);
TC_CONFIG_SET (DisableKernelEncryptionModeWarning);
TC_CONFIG_SET (DismountOnInactivity);
TC_CONFIG_SET (DismountOnLogOff);
TC_CONFIG_SET (DismountOnPowerSaving);
TC_CONFIG_SET (DismountOnScreenSaver);
TC_CONFIG_SET (DisplayMessageAfterHotkeyDismount);
TC_CONFIG_SET (BackgroundTaskEnabled);
SetValue (configMap[L"FilesystemOptions"], DefaultMountOptions.FilesystemOptions);
TC_CONFIG_SET (ForceAutoDismount);
TC_CONFIG_SET (LastSelectedSlotNumber);
TC_CONFIG_SET (MaxVolumeIdleTime);
TC_CONFIG_SET (MountDevicesOnLogon);
TC_CONFIG_SET (MountFavoritesOnLogon);
bool readOnly;
SetValue (configMap[L"MountVolumesReadOnly"], readOnly);
DefaultMountOptions.Protection = readOnly ? VolumeProtection::ReadOnly : VolumeProtection::None;
SetValue (configMap[L"MountVolumesRemovable"], DefaultMountOptions.Removable);
SetValue (configMap[L"NoHardwareCrypto"], DefaultMountOptions.NoHardwareCrypto);
SetValue (configMap[L"NoKernelCrypto"], DefaultMountOptions.NoKernelCrypto);
TC_CONFIG_SET (OpenExplorerWindowAfterMount);
SetValue (configMap[L"PreserveTimestamps"], DefaultMountOptions.PreserveTimestamps);
TC_CONFIG_SET (SaveHistory);
SetValue (configMap[L"SecurityTokenLibrary"], SecurityTokenModule);
TC_CONFIG_SET (StartOnLogon);
TC_CONFIG_SET (UseKeyfiles);
TC_CONFIG_SET (WipeCacheOnAutoDismount);
TC_CONFIG_SET (WipeCacheOnClose);
}
// Default keyfiles
cfgPath = Application::GetConfigFilePath (GetDefaultKeyfilesFileName());
if (cfgPath.IsFile())
{
foreach (const XmlNode &node, XmlParser (cfgPath).GetNodes (L"keyfile"))
{
DefaultKeyfiles.push_back (make_shared <Keyfile> ((wstring) node.InnerText));
}
}
#ifdef TC_WINDOWS
// Hotkeys
Hotkeys = Hotkey::LoadList();
#endif
}
void UserPreferences::Save() const
{
// Preferences
class ConfigXmlFormatter
{
public:
void AddEntry (const wchar_t *key, const wxString &value)
{
if (!value.empty())
{
XmlNode config (L"config");
config.Attributes[L"key"] = key;
config.InnerText = value;
XmlConfig.InnerNodes.push_back (config);
}
}
void AddEntry (const wchar_t *key, bool value)
{
AddEntry (key, wxString (value ? L"1" : L"0"));
}
void AddEntry (const wchar_t *key, int value)
{
wstringstream s;
s << value;
AddEntry (key, s.str());
}
void AddEntry (const wchar_t *key, uint64 value)
{
wstringstream s;
s << value;
AddEntry (key, s.str());
}
XmlNode XmlConfig;
};
ConfigXmlFormatter formatter;
formatter.XmlConfig.Name = L"configuration";
#define TC_CONFIG_ADD(NAME) formatter.AddEntry (L###NAME, NAME)
TC_CONFIG_ADD (BackgroundTaskEnabled);
TC_CONFIG_ADD (BackgroundTaskMenuDismountItemsEnabled);
TC_CONFIG_ADD (BackgroundTaskMenuMountItemsEnabled);
TC_CONFIG_ADD (BackgroundTaskMenuOpenItemsEnabled);
TC_CONFIG_ADD (BeepAfterHotkeyMountDismount);
formatter.AddEntry (L"CachePasswords", DefaultMountOptions.CachePassword);
TC_CONFIG_ADD (CloseBackgroundTaskOnNoVolumes);
TC_CONFIG_ADD (CloseExplorerWindowsOnDismount);
TC_CONFIG_ADD (CloseSecurityTokenSessionsAfterMount);
TC_CONFIG_ADD (DisableKernelEncryptionModeWarning);
TC_CONFIG_ADD (DismountOnInactivity);
TC_CONFIG_ADD (DismountOnLogOff);
TC_CONFIG_ADD (DismountOnPowerSaving);
TC_CONFIG_ADD (DismountOnScreenSaver);
TC_CONFIG_ADD (DisplayMessageAfterHotkeyDismount);
TC_CONFIG_ADD (BackgroundTaskEnabled);
formatter.AddEntry (L"FilesystemOptions", DefaultMountOptions.FilesystemOptions);
TC_CONFIG_ADD (ForceAutoDismount);
TC_CONFIG_ADD (LastSelectedSlotNumber);
TC_CONFIG_ADD (MaxVolumeIdleTime);
TC_CONFIG_ADD (MountDevicesOnLogon);
TC_CONFIG_ADD (MountFavoritesOnLogon);
formatter.AddEntry (L"MountVolumesReadOnly", DefaultMountOptions.Protection == VolumeProtection::ReadOnly);
formatter.AddEntry (L"MountVolumesRemovable", DefaultMountOptions.Removable);
formatter.AddEntry (L"NoHardwareCrypto", DefaultMountOptions.NoHardwareCrypto);
formatter.AddEntry (L"NoKernelCrypto", DefaultMountOptions.NoKernelCrypto);
TC_CONFIG_ADD (OpenExplorerWindowAfterMount);
formatter.AddEntry (L"PreserveTimestamps", DefaultMountOptions.PreserveTimestamps);
TC_CONFIG_ADD (SaveHistory);
formatter.AddEntry (L"SecurityTokenLibrary", wstring (SecurityTokenModule));
TC_CONFIG_ADD (StartOnLogon);
TC_CONFIG_ADD (UseKeyfiles);
TC_CONFIG_ADD (WipeCacheOnAutoDismount);
TC_CONFIG_ADD (WipeCacheOnClose);
XmlWriter writer (Application::GetConfigFilePath (GetPreferencesFileName(), true));
writer.WriteNode (formatter.XmlConfig);
writer.Close();
// Default keyfiles
FilePath keyfilesCfgPath = Application::GetConfigFilePath (GetDefaultKeyfilesFileName(), true);
if (DefaultKeyfiles.empty())
{
if (keyfilesCfgPath.IsFile())
keyfilesCfgPath.Delete();
}
else
{
XmlNode keyfilesXml (L"defaultkeyfiles");
foreach_ref (const Keyfile &keyfile, DefaultKeyfiles)
{
keyfilesXml.InnerNodes.push_back (XmlNode (L"keyfile", wxString (FilesystemPath (keyfile))));
}
XmlWriter keyfileWriter (keyfilesCfgPath);
keyfileWriter.WriteNode (keyfilesXml);
keyfileWriter.Close();
}
#ifdef TC_WINDOWS
// Hotkeys
Hotkey::SaveList (Hotkeys);
#endif
}
}

107
src/Main/UserPreferences.h Normal file
View File

@@ -0,0 +1,107 @@
/*
Copyright (c) 2008-2009 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.
*/
#ifndef TC_HEADER_Main_UserPreferences
#define TC_HEADER_Main_UserPreferences
#include "System.h"
#include "Main.h"
#include "Hotkey.h"
namespace TrueCrypt
{
struct UserPreferences
{
UserPreferences ()
:
BackgroundTaskEnabled (true),
BackgroundTaskMenuDismountItemsEnabled (true),
BackgroundTaskMenuMountItemsEnabled (true),
BackgroundTaskMenuOpenItemsEnabled (true),
BeepAfterHotkeyMountDismount (false),
CloseBackgroundTaskOnNoVolumes (true),
CloseExplorerWindowsOnDismount (true),
CloseSecurityTokenSessionsAfterMount (false),
DisableKernelEncryptionModeWarning (false),
DismountOnInactivity (false),
DismountOnLogOff (true),
DismountOnPowerSaving (false),
DismountOnScreenSaver (false),
DisplayMessageAfterHotkeyDismount (false),
ForceAutoDismount (true),
LastSelectedSlotNumber (0),
MaxVolumeIdleTime (60),
MountDevicesOnLogon (false),
MountFavoritesOnLogon (false),
NonInteractive (false),
OpenExplorerWindowAfterMount (false),
SaveHistory (false),
StartOnLogon (false),
UseKeyfiles (false),
Verbose (false),
WipeCacheOnAutoDismount (true),
WipeCacheOnClose (false)
{
}
virtual ~UserPreferences ()
{
}
void Load();
void Save() const;
HotkeyList Hotkeys;
KeyfileList DefaultKeyfiles;
MountOptions DefaultMountOptions;
bool BackgroundTaskEnabled;
bool BackgroundTaskMenuDismountItemsEnabled;
bool BackgroundTaskMenuMountItemsEnabled;
bool BackgroundTaskMenuOpenItemsEnabled;
bool BeepAfterHotkeyMountDismount;
bool CloseBackgroundTaskOnNoVolumes;
bool CloseExplorerWindowsOnDismount;
bool CloseSecurityTokenSessionsAfterMount;
bool DisableKernelEncryptionModeWarning;
bool DismountOnInactivity;
bool DismountOnLogOff;
bool DismountOnPowerSaving;
bool DismountOnScreenSaver;
bool DisplayMessageAfterHotkeyDismount;
bool ForceAutoDismount;
uint64 LastSelectedSlotNumber;
int32 MaxVolumeIdleTime;
bool MountDevicesOnLogon;
bool MountFavoritesOnLogon;
bool NonInteractive;
bool OpenExplorerWindowAfterMount;
bool SaveHistory;
FilePath SecurityTokenModule;
bool StartOnLogon;
bool UseKeyfiles;
bool Verbose;
bool WipeCacheOnAutoDismount;
bool WipeCacheOnClose;
protected:
wxString GetDefaultKeyfilesFileName () const { return L"Default Keyfiles.xml"; }
#ifdef TC_PROTOTYPE
wxString GetPreferencesFileName () const { return L"Configuration_Debug.xml"; }
#else
wxString GetPreferencesFileName () const { return L"Configuration.xml"; }
#endif
void SetValue (const wxString &cfgText, bool &cfgVar);
void SetValue (const wxString &cfgText, int &cfgVar);
void SetValue (const wxString &cfgText, uint64 &cfgVar);
void SetValue (const wxString &cfgText, wstring &cfgVar);
void SetValue (const wxString &cfgText, wxString &cfgVar);
void SetValue (const wxString &cfgText, FilesystemPath &cfgVar);
};
}
#endif // TC_HEADER_Main_UserPreferences

152
src/Main/VolumeHistory.cpp Normal file
View File

@@ -0,0 +1,152 @@
/*
Copyright (c) 2008 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"
#include "Application.h"
#include "GraphicUserInterface.h"
#include "Xml.h"
#include "VolumeHistory.h"
namespace TrueCrypt
{
VolumeHistory::VolumeHistory ()
{
}
VolumeHistory::~VolumeHistory ()
{
}
void VolumeHistory::Add (const VolumePath &newPath)
{
if (Gui->GetPreferences().SaveHistory)
{
ScopeLock lock (AccessMutex);
VolumePathList::iterator iter = VolumePaths.begin();
foreach (const VolumePath &path, VolumePaths)
{
if (newPath == path)
{
VolumePaths.erase (iter);
break;
}
iter++;
}
VolumePaths.push_front (newPath);
if (VolumePaths.size() > MaxSize)
VolumePaths.pop_back();
foreach (wxComboBox *comboBox, ConnectedComboBoxes)
{
UpdateComboBox (comboBox);
}
}
}
void VolumeHistory::Clear ()
{
VolumePaths.clear();
foreach (wxComboBox *comboBox, ConnectedComboBoxes)
{
UpdateComboBox (comboBox);
}
Save();
}
void VolumeHistory::ConnectComboBox (wxComboBox *comboBox)
{
ScopeLock lock (AccessMutex);
ConnectedComboBoxes.push_back (comboBox);
UpdateComboBox (comboBox);
}
void VolumeHistory::DisconnectComboBox (wxComboBox *comboBox)
{
ScopeLock lock (AccessMutex);
for (list<wxComboBox *>::iterator iter = ConnectedComboBoxes.begin(); iter != ConnectedComboBoxes.end(); ++iter)
{
if (comboBox == *iter)
{
ConnectedComboBoxes.erase (iter);
break;
}
}
}
void VolumeHistory::Load ()
{
ScopeLock lock (AccessMutex);
FilePath historyCfgPath = Application::GetConfigFilePath (GetFileName());
if (historyCfgPath.IsFile())
{
if (!Gui->GetPreferences().SaveHistory)
{
historyCfgPath.Delete();
}
else
{
foreach_reverse (const XmlNode &node, XmlParser (historyCfgPath).GetNodes (L"volume"))
{
Add (wstring (node.InnerText));
}
}
}
}
void VolumeHistory::Save ()
{
ScopeLock lock (AccessMutex);
FilePath historyCfgPath = Application::GetConfigFilePath (GetFileName(), true);
if (!Gui->GetPreferences().SaveHistory || VolumePaths.empty())
{
if (historyCfgPath.IsFile())
historyCfgPath.Delete();
}
else
{
XmlNode historyXml (L"history");
foreach (const VolumePath &path, VolumePaths)
{
historyXml.InnerNodes.push_back (XmlNode (L"volume", wstring (path)));
}
XmlWriter historyWriter (historyCfgPath);
historyWriter.WriteNode (historyXml);
historyWriter.Close();
}
}
void VolumeHistory::UpdateComboBox (wxComboBox *comboBox)
{
wxString curValue = comboBox->GetValue();
comboBox->Freeze();
comboBox->Clear();
foreach (const VolumePath &path, VolumePaths)
{
comboBox->Append (wstring (path));
}
comboBox->SetValue (curValue);
comboBox->Thaw();
}
list <wxComboBox *> VolumeHistory::ConnectedComboBoxes;
VolumePathList VolumeHistory::VolumePaths;
Mutex VolumeHistory::AccessMutex;
}

46
src/Main/VolumeHistory.h Normal file
View File

@@ -0,0 +1,46 @@
/*
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.
*/
#ifndef TC_HEADER_Main_VolumeHistory
#define TC_HEADER_Main_VolumeHistory
#include "System.h"
#include "Main.h"
namespace TrueCrypt
{
class VolumeHistory
{
public:
VolumeHistory ();
virtual ~VolumeHistory ();
static void Add (const VolumePath &path);
static void Clear ();
static void ConnectComboBox (wxComboBox *comboBox);
static void DisconnectComboBox (wxComboBox *comboBox);
static VolumePathList Get () { return VolumePaths; }
static void Load ();
static void Save ();
protected:
static void UpdateComboBox (wxComboBox *comboBox);
static wxString GetFileName () { return L"History.xml"; }
static const unsigned int MaxSize = 10;
static list <wxComboBox *> ConnectedComboBoxes;
static VolumePathList VolumePaths;
static Mutex AccessMutex;
private:
VolumeHistory (const VolumeHistory &);
VolumeHistory &operator= (const VolumeHistory &);
};
}
#endif // TC_HEADER_Main_VolumeHistory

178
src/Main/Xml.cpp Normal file
View File

@@ -0,0 +1,178 @@
/*
Copyright (c) 2008 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"
#include <wx/tokenzr.h>
#include "Platform/FileStream.h"
#include "Xml.h"
namespace TrueCrypt
{
XmlParser::XmlParser (const FilePath &fileName)
{
make_shared_auto (File, file);
file->Open (fileName);
FileStream stream (file);
XmlText = wxString::FromUTF8 (stream.ReadToEnd().c_str());
}
wxString XmlParser::ConvertEscapedChars (wxString xmlString) const
{
xmlString.Replace (L"&lt;", L"<");
xmlString.Replace (L"&gt;", L">");
xmlString.Replace (L"&amp;", L"&");
xmlString.Replace (L"&quot;", L"\"");
return xmlString;
}
XmlNodeList XmlParser::GetNodes (const wxString &nodeName) const
{
XmlNodeList nodeList;
size_t nodePos = 0;
while ((nodePos = XmlText.find (L"<" + nodeName, nodePos)) != string::npos)
{
XmlNode xmlNode;
xmlNode.Name = nodeName;
size_t nodeEnd = XmlText.find (L">", nodePos);
if (nodeEnd == string::npos)
throw ParameterIncorrect (SRC_POS);
wxString nodeTagText = XmlText.substr (nodePos + 1, nodeEnd - nodePos - 1);
nodePos = nodeEnd;
if (nodeTagText.size() > nodeName.size() && nodeTagText[nodeName.size()] != L' ' && nodeTagText[nodeName.size()] != L'/')
continue;
nodeTagText = nodeTagText.substr (nodeName.size());
// Attributes
wxStringTokenizer tokenizer (nodeTagText, L"\"", wxTOKEN_RET_EMPTY);
while (tokenizer.HasMoreTokens())
{
wxString attributeName = tokenizer.GetNextToken();
attributeName.Replace (L" ", L"", true);
attributeName.Replace (L"=", L"");
if (!attributeName.empty() && tokenizer.HasMoreTokens())
{
wxString attributeText = tokenizer.GetNextToken();
xmlNode.Attributes[attributeName] = ConvertEscapedChars (attributeText);
}
}
// Inner text
if (!nodeTagText.EndsWith (L"/"))
{
size_t innerTextPos = nodeEnd + 1;
size_t innerTextEnd = XmlText.find (L"</" + nodeName + L">", innerTextPos);
if (innerTextEnd == string::npos)
throw ParameterIncorrect (SRC_POS);
xmlNode.InnerText = ConvertEscapedChars (XmlText.substr (innerTextPos, innerTextEnd - innerTextPos));
nodePos = innerTextEnd;
}
nodeList.push_back (xmlNode);
}
return nodeList;
}
XmlWriter::XmlWriter (const FilePath &fileName)
{
MemOutStream.reset (new wxMemoryOutputStream);
TextOutStream.reset (new wxTextOutputStream (*MemOutStream));
OutFile.Open (fileName, File::CreateWrite);
*TextOutStream << L"<?xml version=\"1.0\" encoding=\"utf-8\"?>" << endl << L"<TrueCrypt>" << endl;
CurrentIndentLevel = 0;
}
void XmlWriter::Close()
{
if (MemOutStream.get())
{
*TextOutStream << L"</TrueCrypt>" << endl;
wxStreamBuffer *buf = MemOutStream->GetOutputStreamBuffer();
OutFile.Write (ConstBufferPtr (reinterpret_cast <byte *> (buf->GetBufferStart()), buf->GetBufferSize()));
OutFile.Close();
TextOutStream.reset();
MemOutStream.reset();
}
}
wxString XmlWriter::EscapeChars (wxString rawString) const
{
rawString.Replace (L"<", L"&lt;");
rawString.Replace (L">", L"&gt;");
rawString.Replace (L"&", L"&amp;");
rawString.Replace (L"\"", L"&quot;");
return rawString;
}
void XmlWriter::WriteNode (const XmlNode &xmlNode)
{
XmlNodeList nodes;
nodes.push_back (xmlNode);
WriteNodes (nodes);
}
void XmlWriter::WriteNodes (const XmlNodeList &xmlNodes)
{
CurrentIndentLevel++;
wxString indent;
for (int i = 0; i < CurrentIndentLevel; ++i)
indent += L"\t";
foreach (const XmlNode &node, xmlNodes)
{
*TextOutStream << indent << L"<" << node.Name;
typedef pair <wxString, wxString> AttribPair;
foreach (AttribPair attrib, node.Attributes)
{
*TextOutStream << L" " << attrib.first << L"=\"" << EscapeChars (attrib.second) << L"\"";
}
if (!node.InnerNodes.empty())
{
*TextOutStream << L">" << endl;
WriteNodes (node.InnerNodes);
*TextOutStream << indent;
}
else if (!node.InnerText.empty())
{
*TextOutStream << L">" << EscapeChars (node.InnerText);
}
else
{
*TextOutStream << L"/>" << endl;
continue;
}
*TextOutStream << L"</" << node.Name << L">" << endl;
}
CurrentIndentLevel--;
}
XmlWriter::~XmlWriter ()
{
try
{
Close();
}
catch (...) { }
}
}

75
src/Main/Xml.h Normal file
View File

@@ -0,0 +1,75 @@
/*
Copyright (c) 2008 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.
*/
#ifndef TC_HEADER_Main_Xml
#define TC_HEADER_Main_Xml
#include "System.h"
#include "Main.h"
namespace TrueCrypt
{
struct XmlNode;
typedef list <XmlNode> XmlNodeList;
struct XmlNode
{
XmlNode () { }
XmlNode (const wxString &name) : Name (name) { }
XmlNode (const wxString &name, const wxString &innerText) : InnerText (innerText), Name (name) { }
XmlNode (const wxString &name, const XmlNodeList &innerNodes) : InnerNodes (innerNodes), Name (name) { }
map <wxString, wxString> Attributes;
XmlNodeList InnerNodes;
wxString InnerText;
wxString Name;
};
class XmlParser
{
public:
XmlParser (const FilePath &fileName);
XmlParser (const string &xmlTextUtf8) : XmlText (wxString::FromUTF8 (xmlTextUtf8.c_str())) { }
XmlParser (const wxString &xmlText) : XmlText (xmlText) { }
virtual ~XmlParser () { }
wxString ConvertEscapedChars (wxString xmlString) const;
XmlNodeList GetNodes (const wxString &nodeName) const;
protected:
wxString XmlText;
private:
XmlParser (const XmlParser &);
XmlParser &operator= (const XmlParser &);
};
class XmlWriter
{
public:
XmlWriter (const FilePath &fileName);
virtual ~XmlWriter ();
void Close();
wxString EscapeChars (wxString rawString) const;
void WriteNode (const XmlNode &xmlNode);
void WriteNodes (const XmlNodeList &xmlNodes);
protected:
int CurrentIndentLevel;
auto_ptr <wxMemoryOutputStream> MemOutStream;
auto_ptr <wxTextOutputStream> TextOutStream;
File OutFile;
private:
XmlWriter (const XmlWriter &);
XmlWriter &operator= (const XmlWriter &);
};
}
#endif // TC_HEADER_Main_Xml