/*************************************************************** * Name: FreeFileSyncApp.cpp * Purpose: Code for Application Class * Author: ZenJu (zhnmju123@gmx.de) * Created: 2008-07-16 * Copyright: ZenJu () * License: **************************************************************/ #include "application.h" #include "ui/mainDialog.h" #include #include #include "library/globalFunctions.h" IMPLEMENT_APP(Application); bool Application::ProcessIdle() { static bool firstExecution = true; if (firstExecution) { firstExecution = false; initialize(); //here the program initialization takes place } return wxApp::ProcessIdle(); } //Note: initialization is done in the FIRST idle event instead of OnInit. Reason: Commandline mode requires the wxApp eventhandler to be established //for UI update events. This is not the case at the time of OnInit. bool Application::OnInit() { returnValue = 0; //do not call wxApp::OnInit() to avoid parsing commandline now, instead use own parser later return true; } void Application::initialize() { //set working directory to current executable directory if (!wxSetWorkingDirectory(wxFileName(wxStandardPaths::Get().GetExecutablePath()).GetPath())) throw runtime_error(_("Could not set working directory to directory containing executable file!")); //set program language programLanguage.loadLanguageFromCfg(); //activate support for .png files wxImage::AddHandler(new wxPNGHandler); //load icon and animation resources (also needed for commandline: status dialog, error dialog GlobalResources::loadResourceFiles(); //test if ffs is to be started on UI with config file passed as commandline parameter wxString configFileForUI = FreeFileSync::FFS_LastConfigFile; if (argc > 1 && wxFileExists(argv[1]) && FreeFileSync::isFFS_ConfigFile(argv[1])) configFileForUI = argv[1]; //should it start in commandline mode? else if (argc > 1) { parseCommandline(); if (applicationRunsOnCommandLineWithoutWindows) { ExitMainLoop(); //exit programm on next main loop iteration return; } else return; //wait for the user to close the status window } else //no parameters passed: continue with UI { //show UI dialog MainDialog* frame = new MainDialog(0L, configFileForUI, &programLanguage); frame->SetIcon(*GlobalResources::programIcon); //set application icon frame->Show(); } } int Application::OnRun() { try { wxApp::OnRun(); } catch (std::runtime_error& theException) //catch runtime errors during main event loop { wxMessageBox(_(theException.what()), _("An exception occured!"), wxOK | wxICON_ERROR); return -1; } return returnValue; } int Application::OnExit() { GlobalResources::unloadResourceFiles(); return 0; } SyncDirection convertCmdlineCfg(const wxString& cfg, const int i) { assert (cfg.Len() == 5); assert (0 <= i <= 4); switch (cfg[i]) { case 'L': return syncDirLeft; case 'R': return syncDirRight; case 'N': return syncDirNone; default: assert(false); return syncDirNone; } } void Application::logInit() { wxString tmp = wxDateTime::Now().FormatISOTime(); tmp.Replace(":", ""); wxString logfileName = wxString("FFS_") + wxDateTime::Now().FormatISODate() + '_' + tmp + ".log"; logFile.open(logfileName.c_str()); if (!logFile) throw std::runtime_error(_("Unable to create logfile!")); logFile<<_("FreeFileSync (Date: ") + wxDateTime::Now().FormatDate() + _(" Time: ") + wxDateTime::Now().FormatTime() + ")"<"), wxCMD_LINE_VAL_STRING }, { wxCMD_LINE_PARAM, NULL, NULL, _(""), wxCMD_LINE_VAL_STRING }, { wxCMD_LINE_OPTION, GlobalResources::paramInclude, NULL, _("Specify names to be included separated by ';'. Wildcards '*' and '?' are supported. Default: \"*\"\n"), wxCMD_LINE_VAL_STRING, }, { wxCMD_LINE_OPTION, GlobalResources::paramExclude, NULL, _("Specify names to be excluded separated by ';'. Wildcards '*' and '?' are supported. Default: \"\"\n"), wxCMD_LINE_VAL_STRING, }, { wxCMD_LINE_SWITCH, GlobalResources::paramContinueError, NULL, _("If errors occur during folder comparison or synchronization they are ignored and the process continues\n") }, { wxCMD_LINE_SWITCH, GlobalResources::paramRecycler, NULL, _("Move files to Recycle Bin instead of deleting or overwriting them directly.\n") }, { wxCMD_LINE_SWITCH, GlobalResources::paramSilent, NULL, wxString(_("Do not show graphical status and error messages but write to a logfile instead")) + _(".\n\nExamples:\n\n1.) FreeFileSync -cmp SIZEDATE -cfg RRRRR C:\\Source C:\\Target\n2.) FreeFileSync -cmp sizedate -cfg rlrln c:\\dir1 c:\\dir2 -incl *.doc\n\n1: Creates a mirror backup of the left directory\n2: Synchronizes all *.doc files from both directories simultaneously\n\n") }, { wxCMD_LINE_NONE } }; //now set the parser with all MANDATORY options and parameters wxCmdLineParser parser(cmdLineDesc, argc, argv); parser.SetSwitchChars(wxT("-")); if (parser.Parse() != 0) //if commandline is used incorrectly display help dialog and exit program return; //commandline parameters wxString cmp; wxString cfg; wxString leftDir; wxString rightDir; wxString included; wxString excluded; bool continueOnError = parser.Found(GlobalResources::paramContinueError); bool useRecycler = parser.Found(GlobalResources::paramRecycler); bool silent = parser.Found(GlobalResources::paramSilent); applicationRunsOnCommandLineWithoutWindows = silent; //this value is needed for the application to decide whether to wait for windows to close or not //check existence of all commandline parameters if (!parser.Found(GlobalResources::paramCompare, &cmp) || !parser.Found(GlobalResources::paramCfg, &cfg) || parser.GetParamCount() != 2) { parser.Usage(); return; } cmp.UpperCase(); cfg.UpperCase(); leftDir = parser.GetParam(0); rightDir = parser.GetParam(1); //evaluate filter settings bool filteringEnabled = false; if (parser.Found(GlobalResources::paramInclude, &included)) filteringEnabled = true; else included = "*"; if (parser.Found(GlobalResources::paramExclude, &excluded)) filteringEnabled = true; else excluded = ""; //until here all options and parameters have been set //-------------------------------------------------------------------- //check consistency of all commandline parameters if ((cmp != GlobalResources::valueSizeDate && cmp != GlobalResources::valueContent) || cfg.Len() != 5 || (cfg[0] != 'L' && cfg[0] != 'R' && cfg[0] != 'N') || (cfg[1] != 'L' && cfg[1] != 'R' && cfg[1] != 'N') || (cfg[2] != 'L' && cfg[2] != 'R' && cfg[2] != 'N') || (cfg[3] != 'L' && cfg[3] != 'R' && cfg[3] != 'N') || (cfg[4] != 'L' && cfg[4] != 'R' && cfg[4] != 'N')) { parser.Usage(); return; } //init logfile if (silent) logInit(); wxString logText; //check if directories exist if (!wxDirExists(leftDir)) { wxString errorMessage = wxString(_("Directory ")) + leftDir + _(" does not exist."); wxString statusMessage = wxString(_("Synchronization aborted!")); if (silent) { logWrite(errorMessage, _("Warning")); logClose(statusMessage); } else wxMessageBox(errorMessage + "\n\n" + statusMessage, _("Warning"), wxICON_WARNING); returnValue = -2; return; } else if (!wxDirExists(rightDir)) { wxString errorMessage = wxString(_("Directory ")) + rightDir + _(" does not exist."); wxString statusMessage = wxString(_("Synchronization aborted!")); if (silent) { logWrite(errorMessage, _("Warning")); logClose(statusMessage); } else wxMessageBox(errorMessage + "\n\n" + statusMessage, _("Warning"), wxICON_WARNING); returnValue = -2; return; } //test existence of Recycle Bin if (useRecycler) { if (!FreeFileSync::recycleBinExists()) { wxString errorMessage = wxString(_("Unable to initialize Recycle Bin!")); wxString statusMessage = wxString(_("Synchronization aborted!")); if (silent) { logWrite(errorMessage, _("Error")); logClose(statusMessage); } else wxMessageBox(errorMessage + "\n\n" + statusMessage, _("Error"), wxICON_WARNING); returnValue = -2; return; } } //until here all options and parameters are consistent //-------------------------------------------------------------------- CompareVariant cmpVar = compareByContent; //dummy value to suppress compiler warning SyncConfiguration syncConfiguration; FileCompareResult currentGridData; if (cmp == GlobalResources::valueSizeDate) cmpVar = compareByTimeAndSize; else if (cmp == GlobalResources::valueContent) cmpVar = compareByContent; else assert (false); syncConfiguration.exLeftSideOnly = convertCmdlineCfg(cfg, 0); syncConfiguration.exRightSideOnly = convertCmdlineCfg(cfg, 1); syncConfiguration.leftNewer = convertCmdlineCfg(cfg, 2); syncConfiguration.rightNewer = convertCmdlineCfg(cfg, 3); syncConfiguration.different = convertCmdlineCfg(cfg, 4); //class handling status updates and error messages CommandLineStatusUpdater statusUpdater(this, continueOnError, silent); //begin of synchronization process (all in one try-catch block) try { //COMPARE DIRECTORIES //unsigned int startTime = GetTickCount(); FreeFileSync::startCompareProcess(currentGridData, FreeFileSync::getFormattedDirectoryName(leftDir), FreeFileSync::getFormattedDirectoryName(rightDir), cmpVar, &statusUpdater); //wxMessageBox(wxString::Format(wxT("%i"), unsigned(GetTickCount()) - startTime)); //check if folders are already in sync bool nothingToSync = true; for (FileCompareResult::const_iterator i = currentGridData.begin(); i != currentGridData.end(); ++i) if (i->cmpResult != filesEqual) { nothingToSync = false; break; } if (nothingToSync) { wxString errorMessage = _("Nothing to synchronize. Both directories seem to contain the same data!"); if (silent) logClose(errorMessage); else statusUpdater.updateFinalStatus(errorMessage); returnValue = -3; return; } //APPLY FILTERS if (filteringEnabled) FreeFileSync::filterCurrentGridData(currentGridData, included, excluded); //START SYNCHRONIZATION //unsigned int startTime = GetTickCount(); FreeFileSync::startSynchronizationProcess(currentGridData, syncConfiguration, &statusUpdater, useRecycler); //default: do not use recycle bin since it's not sure if its possible //wxMessageBox(wxString::Format(wxT("%i"), unsigned(GetTickCount()) - startTime)); //show success message wxString successMessage = _("Synchronization completed."); if (silent) logClose(successMessage); else statusUpdater.updateFinalStatus(successMessage); } catch (AbortThisProcess& theException) //exit used by statusUpdater { if (silent) logClose(_("Synchronization aborted!")); returnValue = -4; return; } return; //exit program and skip UI dialogs } //###################################################################################################### CommandLineStatusUpdater::CommandLineStatusUpdater(Application* application, bool continueOnError, bool silent) : app(application), continueErrors(continueOnError), silentMode(silent), currentProcess(-1) { if (!silentMode) { syncStatusFrame = new SyncStatus(this, 0); syncStatusFrame->Show(); } } CommandLineStatusUpdater::~CommandLineStatusUpdater() { if (!silentMode) { //print the results list unsigned int failedItems = unhandledErrors.GetCount(); wxString errorMessages; if (failedItems) { errorMessages = wxString(_("Warning: Synchronization failed for ")) + globalFunctions::numberToWxString(failedItems) + _(" item(s):\n\n"); for (unsigned int j = 0; j < failedItems; ++j) errorMessages+= unhandledErrors[j] + "\n"; syncStatusFrame->setStatusText_NoUpdate(errorMessages); } //notify to syncStatusFrame that current process has ended if (abortionRequested) syncStatusFrame->processHasFinished(SyncStatus::statusAborted); //enable okay and close events else if (failedItems) syncStatusFrame->processHasFinished(SyncStatus::statusCompletedWithErrors); else syncStatusFrame->processHasFinished(SyncStatus::statusCompletedWithSuccess); } } inline void CommandLineStatusUpdater::updateStatusText(const wxString& text) { if (!silentMode) syncStatusFrame->setStatusText_NoUpdate(text); } void CommandLineStatusUpdater::initNewProcess(int objectsTotal, double dataTotal, int processID) { currentProcess = processID; if (!silentMode) { if (currentProcess == FreeFileSync::scanningFilesProcess) syncStatusFrame->setCurrentStatus(SyncStatus::statusScanning); else if (currentProcess == FreeFileSync::compareFileContentProcess) { syncStatusFrame->resetGauge(objectsTotal, dataTotal); syncStatusFrame->setCurrentStatus(SyncStatus::statusComparing); } else if (currentProcess == FreeFileSync::synchronizeFilesProcess) { syncStatusFrame->resetGauge(objectsTotal, dataTotal); syncStatusFrame->setCurrentStatus(SyncStatus::statusSynchronizing); } else assert(false); } } inline void CommandLineStatusUpdater::updateProcessedData(int objectsProcessed, double dataProcessed) { if (!silentMode) { if (currentProcess == FreeFileSync::scanningFilesProcess) syncStatusFrame->m_gauge1->Pulse(); else if (currentProcess == FreeFileSync::compareFileContentProcess) syncStatusFrame->incProgressIndicator_NoUpdate(objectsProcessed, dataProcessed); else if (currentProcess == FreeFileSync::synchronizeFilesProcess) syncStatusFrame->incProgressIndicator_NoUpdate(objectsProcessed, dataProcessed); else assert(false); } } int CommandLineStatusUpdater::reportError(const wxString& text) { if (silentMode) //write error message log and abort the complete session if necessary { app->logWrite(text, _("Error")); if (continueErrors) // <- /|\ before return, the logfile is written!!! return StatusUpdater::continueNext; else { abortionRequested = true; throw AbortThisProcess(); } } else //show dialog to user who can decide how to continue { if (continueErrors) //this option can be set from commandline or by the user in the error dialog on UI { unhandledErrors.Add(text); return StatusUpdater::continueNext; } syncStatusFrame->updateStatusDialogNow(); wxString errorMessage = text + _("\n\nContinue with next object, retry or abort synchronization?"); ErrorDlg* errorDlg = new ErrorDlg(errorMessage, continueErrors); int rv = errorDlg->ShowModal(); errorDlg->Destroy(); switch (rv) { case ErrorDlg::continueButtonPressed: unhandledErrors.Add(text); return StatusUpdater::continueNext; case ErrorDlg::retryButtonPressed: return StatusUpdater::retry; case ErrorDlg::abortButtonPressed: { unhandledErrors.Add(text); abortionRequested = true; throw AbortThisProcess(); } default: assert (false); } } return StatusUpdater::continueNext; //dummy return value } inline void CommandLineStatusUpdater::triggerUI_Refresh() { if (abortionRequested) throw AbortThisProcess(); if (!silentMode) if (updateUI_IsAllowed()) //test if specific time span between ui updates is over syncStatusFrame->updateStatusDialogNow(); } inline void CommandLineStatusUpdater::updateFinalStatus(const wxString& text) //set by parsedCommandline() to communicate e.g. the final "success message" { if (!silentMode) syncStatusFrame->setStatusText_NoUpdate(text); }