summaryrefslogtreecommitdiff
path: root/Application.cpp
blob: dcd887a2987ffa42b9404bc64aa9a66cdeb8974b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
/***************************************************************
 * Purpose:   Code for Application Class
 * Author:    ZenJu (zhnmju123@gmx.de)
 * Created:   2008-07-16
 **************************************************************/

#include "application.h"
#include "ui/mainDialog.h"
#include <wx/stdpaths.h>
#include <wx/filename.h>
#include <wx/ffile.h>
#include "library/globalFunctions.h"
#include <wx/msgdlg.h>
#include "library/processXml.h"
#include <wx/stopwatch.h>
#include "comparison.h"
#include "synchronization.h"
#include "algorithm.h"
#include <wx/taskbar.h>
#include "ui/smallDialogs.h"
#include <memory>


IMPLEMENT_APP(Application);


bool Application::OnInit()
{
    returnValue = 0;
    //do not call wxApp::OnInit() to avoid using default commandline parser

//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().
    Connect(wxEVT_IDLE, wxIdleEventHandler(Application::OnStartApplication), NULL, this);

    return true;
}


void Application::OnStartApplication(wxIdleEvent& event)
{
    Disconnect(wxEVT_IDLE, wxIdleEventHandler(Application::OnStartApplication), NULL, this);

    //test if FFS is to be started on UI with config file passed as commandline parameter
    //this needs to happen BEFORE the working directory is set!
    wxString cfgFilename;
    if (argc > 1)
    {
        //resolve relative names to avoid problems after working directory is changed
        wxFileName filename(argv[1]);
        if (!filename.Normalize())
        {
            wxMessageBox(wxString(_("Error retrieving full path:")) + wxT("\n\"") + argv[1] + wxT("\""));
            return;
        }
        const wxString fullFilename = filename.GetFullPath();

        if (wxFileExists(fullFilename))  //load file specified by %1 parameter:
            cfgFilename = fullFilename;
        else if (wxFileExists(fullFilename + wxT(".ffs_batch")))
            cfgFilename = fullFilename + wxT(".ffs_batch");
        else if (wxFileExists(fullFilename + wxT(".ffs_gui")))
            cfgFilename = fullFilename + wxT(".ffs_gui");
        else
        {
            wxMessageBox(wxString(_("File does not exist:")) + wxT(" \"") + fullFilename + wxT("\""), _("Error"), wxOK | wxICON_ERROR);
            return;
        }
    }


//set working directory to current executable directory
    const wxString workingDir = wxFileName(wxStandardPaths::Get().GetExecutablePath()).GetPath();
    if (!wxSetWorkingDirectory(workingDir))
    {   //show messagebox and quit program immediately
        wxMessageBox(wxString(_("Could not set working directory:")) + wxT(" ") + workingDir, _("An exception occured!"), wxOK | wxICON_ERROR);
        return;
    }

    try //load global settings from XML: must be called AFTER working dir was set
    {
        globalSettings = xmlAccess::readGlobalSettings();
    }
    catch (const FileError& error)
    {
        if (wxFileExists(FreeFileSync::GLOBAL_CONFIG_FILE))
        {   //show messagebox and quit program immediately
            wxMessageBox(error.show().c_str(), _("Error"), wxOK | wxICON_ERROR);
            return;
        }
        //else: globalSettings already has default values
    }

//set program language: needs to happen after working directory has been set!
    SetExitOnFrameDelete(false); //prevent error messagebox from becoming top-level window
    programLanguage.setLanguage(globalSettings.shared.programLanguage);
    SetExitOnFrameDelete(true);

//load image resources from file: must be called after working directory has been set
    globalResource.load();


    if (!cfgFilename.empty())
    {
        //load file specified by %1 parameter:
        xmlAccess::XmlType xmlConfigType = xmlAccess::getXmlType(cfgFilename);
        if (xmlConfigType == xmlAccess::XML_GUI_CONFIG) //start in GUI mode (configuration file specified)
        {
            MainDialog* frame = new MainDialog(NULL, cfgFilename, &programLanguage, globalSettings);
            frame->SetIcon(*globalResource.programIcon); //set application icon
            frame->Show();
        }
        else if (xmlConfigType == xmlAccess::XML_BATCH_CONFIG) //start in commandline mode
        {
            runBatchMode(cfgFilename, globalSettings);

            if (wxApp::GetTopWindow() == NULL) //if no windows are shown program won't exit automatically
                ExitMainLoop();
            return;
        }
        else
        {
            wxMessageBox(wxString(_("The file does not contain a valid configuration:")) + wxT(" \"") + cfgFilename + wxT("\""), _("Error"), wxOK | wxICON_ERROR);
            return;
        }
    }
    else //start in GUI mode (standard)
    {
        MainDialog* frame = new MainDialog(NULL, FreeFileSync::LAST_CONFIG_FILE, &programLanguage, globalSettings);
        frame->SetIcon(*globalResource.programIcon); //set application icon
        frame->Show();
    }
}


bool Application::OnExceptionInMainLoop()
{
    throw; //just re-throw exception and avoid display of additional exception messagebox: it will be caught in OnRun()
}


int Application::OnRun()
{
    try
    {
        wxApp::OnRun();
    }
    catch (const RuntimeException& theException) //catch runtime errors during main event loop; wxApp::OnUnhandledException could be used alternatively
    {
        wxMessageBox(theException.show(), _("An exception occured!"), wxOK | wxICON_ERROR);
        return -1;
    }
    catch (std::exception& e) //catch all STL exceptions
    {
        wxMessageBox(wxString::From8BitData(e.what()), _("An exception occured!"), wxOK | wxICON_ERROR);
        return -1;
    }

    return returnValue;
}


int Application::OnExit()
{
    //get program language
    globalSettings.shared.programLanguage = programLanguage.getLanguage();

    try //save global settings to XML
    {
        xmlAccess::writeGlobalSettings(globalSettings);
    }
    catch (const FileError& error)
    {
        wxMessageBox(error.show().c_str(), _("Error"), wxOK | wxICON_ERROR);
    }

    return 0;
}


class LogFile
{
public:
    LogFile(const wxString& logfileDirectory)
    {
        wxString timeNow = wxDateTime::Now().FormatISOTime();
        timeNow.Replace(wxT(":"), wxEmptyString);

        wxString logfileName;
        if (logfileDirectory.empty())
        {   //create subfolder "log" to hold logfiles
            if (!wxDirExists(wxT("Logs")))
                wxMkdir(wxT("Logs"));
            logfileName = wxString(wxT("Logs")) + GlobalResources::FILE_NAME_SEPARATOR + wxT("FFS_") + wxDateTime::Now().FormatISODate() + wxChar('_') + timeNow + wxT(".log");
        }
        else
        {   //use alternate logfile directory
            if (!wxDirExists(logfileDirectory))
                try
                {
                    FreeFileSync::createDirectory(logfileDirectory.c_str(), Zstring(), false);
                }
                catch (FileError&)
                {
                    readyToWrite = false;
                    return;
                }

            logfileName = logfileDirectory;
            if (!endsWithPathSeparator(logfileName.c_str()))
                logfileName += GlobalResources::FILE_NAME_SEPARATOR;

            logfileName += wxT("FFS_") + wxDateTime::Now().FormatISODate() + wxChar('_') + timeNow + wxT(".log");
        }


        logFile.Open(logfileName.c_str(), wxT("w"));
        readyToWrite = logFile.IsOpened();
        if (readyToWrite)
        {
            wxString headerLine = wxString(wxT("FreeFileSync - "))  +
                                  _("Batch execution") + wxT(" (") +
                                  _("Date") + wxT(": ") + wxDateTime::Now().FormatDate() + wxT(" ") + //"Date" is used at other places too
                                  _("Time") + wxT(":") + wxT(" ") +  wxDateTime::Now().FormatTime() + wxT(")");
            logFile.Write(headerLine + wxChar('\n'));
            logFile.Write(wxString().Pad(headerLine.Len(), wxChar('-')) + wxChar('\n') + wxChar('\n'));

            wxString caption = _("Log-messages:");
            logFile.Write(caption + wxChar('\n'));
            logFile.Write(wxString().Pad(caption.Len(), wxChar('-')) + wxChar('\n'));

            write(wxString(_("Start")) + wxChar('\n'));

            totalTime.Start(); //measure total time
        }
    }

    ~LogFile()
    {
        if (readyToWrite)
            close();
    }

    bool isOkay()
    {
        return readyToWrite;
    }

    void write(const wxString& logText, const wxString& problemType = wxEmptyString)
    {
        logFile.Write(wxString(wxT("[")) + wxDateTime::Now().FormatTime() + wxT("] "));

        if (problemType != wxEmptyString)
            logFile.Write(problemType + wxT(": "));

        //remove linebreaks
        wxString formattedText = logText;
        for (wxString::iterator i = formattedText.begin(); i != formattedText.end(); ++i)
            if (*i == wxChar('\n'))
                *i = wxChar(' ');

        logFile.Write(formattedText + wxChar('\n'));
    }

private:

    void close()
    {
        logFile.Write(wxChar('\n'));

        long time = totalTime.Time(); //retrieve total time

        logFile.Write(wxString(wxT("[")) + wxDateTime::Now().FormatTime() + wxT("] "));
        logFile.Write(wxString(_("Stop")) + wxT(" (") + _("Total time:") + wxT(" ") + (wxTimeSpan::Milliseconds(time)).Format() + wxT(")"));

        //logFile.close(); <- not needed
    }

    bool readyToWrite;
    wxFFile logFile;
    wxStopWatch totalTime;
};


void Application::runBatchMode(const wxString& filename, xmlAccess::XmlGlobalSettings& globalSettings)
{
    //load XML settings
    xmlAccess::XmlBatchConfig batchCfg;  //structure to receive gui settings
    try
    {
        batchCfg = xmlAccess::readBatchConfig(filename);
    }
    catch (const FileError& error)
    {
        wxMessageBox(error.show().c_str(), _("Error"), wxOK | wxICON_ERROR);
        return;
    }
    //all settings have been read successfully...

    try //begin of synchronization process (all in one try-catch block)
    {
        //class handling status updates and error messages
        std::auto_ptr<BatchStatusHandler> statusHandler;  //delete object automatically
        if (batchCfg.silent)
            statusHandler = std::auto_ptr<BatchStatusHandler>(new BatchStatusHandlerSilent(batchCfg.handleError, batchCfg.logFileDirectory, returnValue));
        else
            statusHandler = std::auto_ptr<BatchStatusHandler>(new BatchStatusHandlerGui(batchCfg.handleError, returnValue));

        //COMPARE DIRECTORIES
        FileCompareResult currentGridData;
        FreeFileSync::CompareProcess comparison(globalSettings.shared.traverseDirectorySymlinks,
                                                globalSettings.shared.fileTimeTolerance,
                                                globalSettings.shared.warningDependentFolders,
                                                statusHandler.get());

        comparison.startCompareProcess(batchCfg.directoryPairs,
                                       batchCfg.mainCfg.compareVar,
                                       currentGridData);

        //APPLY FILTERS
        if (batchCfg.mainCfg.filterIsActive)
            FreeFileSync::filterGridData(currentGridData, batchCfg.mainCfg.includeFilter, batchCfg.mainCfg.excludeFilter);

        //check if there are files/folders to be sync'ed at all
        if (!synchronizationNeeded(currentGridData, batchCfg.mainCfg.syncConfiguration))
            statusHandler->exitAndSetStatus(_("Nothing to synchronize according to configuration!"), BatchStatusHandler::FINISHED); //inform about this special case

        //START SYNCHRONIZATION
        FreeFileSync::SyncProcess synchronization(
            batchCfg.mainCfg.useRecycleBin,
            globalSettings.shared.copyFileSymlinks,
            globalSettings.shared.traverseDirectorySymlinks,
            globalSettings.shared.warningSignificantDifference,
            statusHandler.get());

        synchronization.startSynchronizationProcess(currentGridData, batchCfg.mainCfg.syncConfiguration);
    }
    catch (AbortThisProcess&)  //exit used by statusHandler
    {   //don't set returnValue here! Program flow may arrive here in non-error situations also! E.g. "nothing to synchronize"
        return;
    }

    return; //exit program
}


//######################################################################################################

class FfsTrayIcon : public wxTaskBarIcon
{
public:
    FfsTrayIcon(StatusHandler* statusHandler) :
            m_statusHandler(statusHandler),
            processPaused(false)
    {
        running.reset(new wxIcon(*globalResource.programIcon));
        paused.reset(new wxIcon);
        paused->CopyFromBitmap(*globalResource.bitmapFFSPaused);

        wxTaskBarIcon::SetIcon(*running);
    }

    ~FfsTrayIcon() {}

    enum
    {
        CONTEXT_PAUSE,
        CONTEXT_ABORT,
        CONTEXT_ABOUT
    };

    virtual wxMenu* CreatePopupMenu()
    {
        wxMenu* contextMenu = new wxMenu;
        contextMenu->Append(CONTEXT_PAUSE, _("&Pause"), wxEmptyString, wxITEM_CHECK);
        contextMenu->Check(CONTEXT_PAUSE, processPaused);
        contextMenu->Append(CONTEXT_ABORT, _("&Abort"));
        contextMenu->AppendSeparator();
        contextMenu->Append(CONTEXT_ABOUT, _("&About..."));
        //event handling
        contextMenu->Connect(wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(FfsTrayIcon::onContextMenuSelection), NULL, this);

        return contextMenu; //ownership transferred to library
    }

    void onContextMenuSelection(wxCommandEvent& event)
    {
        int eventId = event.GetId();
        if (eventId == CONTEXT_PAUSE)
        {
            processPaused = !processPaused;
            if (processPaused)
                wxTaskBarIcon::SetIcon(*paused);
            else
                wxTaskBarIcon::SetIcon(*running);
        }
        else if (eventId == CONTEXT_ABORT)
        {
            processPaused = false;
            wxTaskBarIcon::SetIcon(*running);
            m_statusHandler->requestAbortion();
        }
        else if (eventId == CONTEXT_ABOUT)
        {
            AboutDlg* aboutDlg = new AboutDlg(NULL);
            aboutDlg->ShowModal();
            aboutDlg->Destroy();
        }
    }

    void updateSysTray()
    {
        updateUiNow();

        //support for pause button
        while (processPaused)
        {
            wxMilliSleep(UI_UPDATE_INTERVAL);
            updateUiNow();
        }
    }

private:
    StatusHandler* m_statusHandler;
    bool processPaused;
    std::auto_ptr<wxIcon> running;
    std::auto_ptr<wxIcon> paused;
};


BatchStatusHandlerSilent::BatchStatusHandlerSilent(const xmlAccess::OnError handleError, const wxString& logfileDirectory, int& returnVal) :
        m_handleError(handleError),
        currentProcess(StatusHandler::PROCESS_NONE),
        returnValue(returnVal),
        trayIcon(new FfsTrayIcon(this)),
        m_log(new LogFile(logfileDirectory))
{
    //test if log was instantiated successfully
    if (!m_log->isOkay())
    {  //handle error: file load
        wxMessageBox(_("Unable to create logfile!"), _("Error"), wxOK | wxICON_ERROR);
        throw AbortThisProcess();
    }
}


BatchStatusHandlerSilent::~BatchStatusHandlerSilent()
{
    unsigned int failedItems = unhandledErrors.GetCount();

    //write result
    if (abortRequested)
    {
        returnValue = -4;
        m_log->write(_("Synchronization aborted!"), _("Error"));
    }
    else if (failedItems)
    {
        returnValue = -5;
        m_log->write(_("Synchronization completed with errors!"), _("Info"));
    }
    else
        m_log->write(_("Synchronization completed successfully!"), _("Info"));
}


inline
void BatchStatusHandlerSilent::updateStatusText(const Zstring& text)
{
    if (currentProcess == StatusHandler::PROCESS_SYNCHRONIZING)
        m_log->write(text.c_str(), _("Info"));
}


inline
void BatchStatusHandlerSilent::initNewProcess(int objectsTotal, double dataTotal, StatusHandler::Process processID)
{
    currentProcess = processID;
}


ErrorHandler::Response BatchStatusHandlerSilent::reportError(const Zstring& errorMessage)
{
    switch (m_handleError)
    {
    case xmlAccess::ON_ERROR_POPUP:
    {
        bool ignoreNextErrors = false;
        ErrorDlg* errorDlg = new ErrorDlg(NULL,
                                          ErrorDlg::BUTTON_IGNORE |  ErrorDlg::BUTTON_RETRY | ErrorDlg::BUTTON_ABORT,
                                          wxString(errorMessage) + wxT("\n\n") + _("Ignore this error, retry or abort?"),
                                          ignoreNextErrors);
        const int rv = errorDlg->ShowModal();
        errorDlg->Destroy();
        switch (rv)
        {
        case ErrorDlg::BUTTON_IGNORE:
            if (ignoreNextErrors) //falsify only
                m_handleError = xmlAccess::ON_ERROR_IGNORE;
            unhandledErrors.Add(errorMessage.c_str());
            m_log->write(errorMessage.c_str(), _("Error"));
            return ErrorHandler::IGNORE_ERROR;

        case ErrorDlg::BUTTON_RETRY:
            return ErrorHandler::RETRY;

        case ErrorDlg::BUTTON_ABORT:
            unhandledErrors.Add(errorMessage.c_str());
            m_log->write(errorMessage.c_str(), _("Error"));
            abortThisProcess();
        }
    }
    break; //used if last switch didn't find a match

    case xmlAccess::ON_ERROR_EXIT: //abort
        unhandledErrors.Add(errorMessage.c_str());
        m_log->write(errorMessage.c_str(), _("Error"));
        abortThisProcess();

    case xmlAccess::ON_ERROR_IGNORE:
        unhandledErrors.Add(errorMessage.c_str());
        m_log->write(errorMessage.c_str(), _("Error"));
        return ErrorHandler::IGNORE_ERROR;
    }

    assert(false);
    return ErrorHandler::IGNORE_ERROR; //dummy value
}


void BatchStatusHandlerSilent::reportFatalError(const Zstring& errorMessage)
{
    switch (m_handleError)
    {
    case xmlAccess::ON_ERROR_POPUP:
    {
        bool dummy = false;
        ErrorDlg* errorDlg = new ErrorDlg(NULL,
                                          ErrorDlg::BUTTON_ABORT,
                                          errorMessage.c_str(), dummy);
        errorDlg->ShowModal();
        errorDlg->Destroy();
    }
    break;

    case xmlAccess::ON_ERROR_EXIT:
        break;

    case xmlAccess::ON_ERROR_IGNORE:
        break;
    }

    unhandledErrors.Add(errorMessage.c_str());
    m_log->write(errorMessage.c_str(), _("Error"));
    abortThisProcess();
}


void BatchStatusHandlerSilent::reportWarning(const Zstring& warningMessage, bool& dontShowAgain)
{
    switch (m_handleError)
    {
    case xmlAccess::ON_ERROR_POPUP:
    {
        //show popup and ask user how to handle warning
        bool dontWarnAgain = false;
        WarningDlg* warningDlg = new WarningDlg(NULL,
                                                WarningDlg::BUTTON_IGNORE | WarningDlg::BUTTON_ABORT,
                                                warningMessage.c_str(),
                                                dontWarnAgain);
        const int rv = warningDlg->ShowModal();
        warningDlg->Destroy();
        switch (rv)
        {
        case WarningDlg::BUTTON_ABORT:
            unhandledErrors.Add(warningMessage.c_str());
            m_log->write(warningMessage.c_str(), _("Warning"));
            abortThisProcess();
        case WarningDlg::BUTTON_IGNORE: //no unhandled error situation!
            dontShowAgain = dontWarnAgain;
            m_log->write(warningMessage.c_str(), _("Warning"));
            return;
        }
    }
    break; //keep it! last switch might not find match

    case xmlAccess::ON_ERROR_EXIT: //abort
        unhandledErrors.Add(warningMessage.c_str());
        m_log->write(warningMessage.c_str(), _("Warning"));
        abortThisProcess();

    case xmlAccess::ON_ERROR_IGNORE: //no unhandled error situation!
        m_log->write(warningMessage.c_str(), _("Warning"));
        return;
    }

    assert(false);
}


void BatchStatusHandlerSilent::forceUiRefresh()
{
    trayIcon->updateSysTray(); //needed by sys-tray icon only
}


void BatchStatusHandlerSilent::abortThisProcess() //used by sys-tray menu
{
    abortRequested = true;
    throw AbortThisProcess();
}


void BatchStatusHandlerSilent::exitAndSetStatus(const wxString& message, ExitCode code) //abort externally
{
    switch (code)
    {
    case BatchStatusHandler::ABORTED:
        unhandledErrors.Add(message);
        m_log->write(message, _("Error"));
        abortRequested = true;
        throw AbortThisProcess();

    case BatchStatusHandler::FINISHED:
        m_log->write(message, _("Info"));
        throw AbortThisProcess();
    default:
        assert(false);
    }
}


//######################################################################################################
BatchStatusHandlerGui::BatchStatusHandlerGui(const xmlAccess::OnError handleError, int& returnVal) :
        m_handleError(handleError),
        currentProcess(StatusHandler::PROCESS_NONE),
        returnValue(returnVal)
{
    syncStatusFrame = new SyncStatus(this, NULL);
    syncStatusFrame->Show();
}


BatchStatusHandlerGui::~BatchStatusHandlerGui()
{
    //display result
    wxString finalMessage;

    unsigned int failedItems = unhandledErrors.GetCount();
    if (failedItems)
    {
        finalMessage = wxString(_("Warning: Synchronization failed for %x item(s):")) + wxT("\n\n");
        finalMessage.Replace(wxT("%x"), globalFunctions::numberToWxString(failedItems), false);

        for (unsigned int j = 0; j < failedItems; ++j)
        {   //remove linebreaks
            wxString errorMessage = unhandledErrors[j];
            for (wxString::iterator i = errorMessage.begin(); i != errorMessage.end(); ++i)
                if (*i == wxChar('\n'))
                    *i = wxChar(' ');

            finalMessage += errorMessage + wxT("\n");
        }
        finalMessage += wxT("\n");
    }

    if (!additionalStatusInfo.IsEmpty())
        finalMessage += additionalStatusInfo + wxT("\n\n");

    //notify to syncStatusFrame that current process has ended
    if (abortRequested)
    {
        returnValue = -4;
        finalMessage += _("Synchronization aborted!");
        syncStatusFrame->setStatusText_NoUpdate(finalMessage.c_str());
        syncStatusFrame->processHasFinished(SyncStatus::ABORTED);  //enable okay and close events
    }
    else if (failedItems)
    {
        returnValue = -5;
        finalMessage += _("Synchronization completed with errors!");
        syncStatusFrame->setStatusText_NoUpdate(finalMessage.c_str());
        syncStatusFrame->processHasFinished(SyncStatus::FINISHED_WITH_ERROR);
    }
    else
    {
        finalMessage += _("Synchronization completed successfully!");
        syncStatusFrame->setStatusText_NoUpdate(finalMessage.c_str());
        syncStatusFrame->processHasFinished(SyncStatus::FINISHED_WITH_SUCCESS);
    }
}


inline
void BatchStatusHandlerGui::updateStatusText(const Zstring& text)
{
    syncStatusFrame->setStatusText_NoUpdate(text);
}


void BatchStatusHandlerGui::initNewProcess(int objectsTotal, double dataTotal, StatusHandler::Process processID)
{
    currentProcess = processID;

    if (currentProcess == StatusHandler::PROCESS_SCANNING)
        syncStatusFrame->setCurrentStatus(SyncStatus::SCANNING);

    else if (currentProcess == StatusHandler::PROCESS_COMPARING_CONTENT)
    {
        syncStatusFrame->resetGauge(objectsTotal, dataTotal);
        syncStatusFrame->setCurrentStatus(SyncStatus::COMPARING);
    }

    else if (currentProcess == StatusHandler::PROCESS_SYNCHRONIZING)
    {
        syncStatusFrame->resetGauge(objectsTotal, dataTotal);
        syncStatusFrame->setCurrentStatus(SyncStatus::SYNCHRONIZING);
    }
    else assert(false);
}


inline
void BatchStatusHandlerGui::updateProcessedData(int objectsProcessed, double dataProcessed)
{
    if (currentProcess == StatusHandler::PROCESS_SCANNING)
        ;
    else if (currentProcess == StatusHandler::PROCESS_COMPARING_CONTENT)
        syncStatusFrame->incProgressIndicator_NoUpdate(objectsProcessed, dataProcessed);
    else if (currentProcess == StatusHandler::PROCESS_SYNCHRONIZING)
        syncStatusFrame->incProgressIndicator_NoUpdate(objectsProcessed, dataProcessed);
    else assert(false);
}


ErrorHandler::Response BatchStatusHandlerGui::reportError(const Zstring& errorMessage)
{
    //add current time before error message
    wxString errorWithTime = wxString(wxT("[")) + wxDateTime::Now().FormatTime() + wxT("] ") + errorMessage.c_str();

    switch (m_handleError)
    {
    case xmlAccess::ON_ERROR_POPUP:
    {
        syncStatusFrame->updateStatusDialogNow();

        bool ignoreNextErrors = false;
        ErrorDlg* errorDlg = new ErrorDlg(syncStatusFrame,
                                          ErrorDlg::BUTTON_IGNORE |  ErrorDlg::BUTTON_RETRY | ErrorDlg::BUTTON_ABORT,
                                          wxString(errorMessage) + wxT("\n\n") + _("Ignore this error, retry or abort?"),
                                          ignoreNextErrors);
        switch (errorDlg->ShowModal())
        {
        case ErrorDlg::BUTTON_IGNORE:
            if (ignoreNextErrors) //falsify only
                m_handleError = xmlAccess::ON_ERROR_IGNORE;
            unhandledErrors.Add(errorWithTime);
            return ErrorHandler::IGNORE_ERROR;
        case ErrorDlg::BUTTON_RETRY:
            return ErrorHandler::RETRY;
        case ErrorDlg::BUTTON_ABORT:
            unhandledErrors.Add(errorWithTime);
            abortThisProcess();
        }
    }
    break; //used IF last switch didn't find a match

    case xmlAccess::ON_ERROR_EXIT: //abort
        unhandledErrors.Add(errorWithTime);
        abortThisProcess();

    case xmlAccess::ON_ERROR_IGNORE:
        unhandledErrors.Add(errorWithTime);
        return ErrorHandler::IGNORE_ERROR;
    }

    assert(false);
    return ErrorHandler::IGNORE_ERROR; //dummy value
}


void BatchStatusHandlerGui::reportFatalError(const Zstring& errorMessage)
{   //add current time before error message
    wxString errorWithTime = wxString(wxT("[")) + wxDateTime::Now().FormatTime() + wxT("] ") + errorMessage.c_str();

    unhandledErrors.Add(errorWithTime);
    abortThisProcess();
}


void BatchStatusHandlerGui::reportWarning(const Zstring& warningMessage, bool& dontShowAgain)
{   //add current time before warning message
    wxString warningWithTime = wxString(wxT("[")) + wxDateTime::Now().FormatTime() + wxT("] ") + warningMessage.c_str();

    switch (m_handleError)
    {
    case xmlAccess::ON_ERROR_POPUP:
    case xmlAccess::ON_ERROR_EXIT: //show popup in this case also
    {
        //show popup and ask user how to handle warning
        bool dontWarnAgain = false;
        WarningDlg* warningDlg = new WarningDlg(NULL,
                                                WarningDlg::BUTTON_IGNORE | WarningDlg::BUTTON_ABORT,
                                                warningMessage.c_str(),
                                                dontWarnAgain);
        const int rv = warningDlg->ShowModal();
        warningDlg->Destroy();
        switch (rv)
        {
        case WarningDlg::BUTTON_IGNORE: //no unhandled error situation!
            dontShowAgain = dontWarnAgain;
            return;
        case WarningDlg::BUTTON_ABORT:
            unhandledErrors.Add(warningWithTime);
            abortThisProcess();
        }
    }
    break; //keep it! last switch might not find match

    case xmlAccess::ON_ERROR_IGNORE: //no unhandled error situation!
        return;
    }

    assert(false);
}


inline
void BatchStatusHandlerGui::forceUiRefresh()
{
    if (currentProcess == StatusHandler::PROCESS_SCANNING)
        syncStatusFrame->m_gauge1->Pulse(); //expensive! So put it here!

    syncStatusFrame->updateStatusDialogNow();
}


void BatchStatusHandlerGui::abortThisProcess()
{
    abortRequested = true;
    throw AbortThisProcess();  //abort can be triggered by syncStatusFrame
}


void BatchStatusHandlerGui::exitAndSetStatus(const wxString& message, ExitCode code) //abort externally
{
    switch (code)
    {
    case BatchStatusHandler::ABORTED:
        unhandledErrors.Add(message);
        abortRequested = true;
        throw AbortThisProcess();
        break;

    case BatchStatusHandler::FINISHED:
        additionalStatusInfo = message;
        throw AbortThisProcess();
        break;
    default:
        assert(false);
    }
}
bgstack15