summaryrefslogtreecommitdiff
path: root/RealtimeSync/tray_menu.cpp
blob: c8eccbf5a8f4d95503c0466d8d6ad7d58f818e61 (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
// **************************************************************************
// * This file is part of the FreeFileSync project. It is distributed under *
// * GNU General Public License: http://www.gnu.org/licenses/gpl.html       *
// * Copyright (C) ZenJu (zhnmju123 AT gmx DOT de) - All Rights Reserved    *
// **************************************************************************

#include "tray_menu.h"
#include <algorithm>
#include <iterator>
#include <limits>
#include <set>
#include <wx/msgdlg.h>
#include <wx/taskbar.h>
#include <wx/app.h>
#include <wx/utils.h>
#include <wx/menu.h>
#include "watcher.h"
#include <wx/utils.h>
#include <wx/log.h>
#include <wx/icon.h> //Linux needs this
#include <wx/timer.h>
#include "resources.h"
#include <wx+/string_conv.h>
#include <zen/assert_static.h>
#include <zen/build_info.h>
#include <wx+/shell_execute.h>

using namespace rts;
using namespace zen;

class TrayIconHolder : private wxEvtHandler
{
public:
    TrayIconHolder(const wxString& jobname);
    ~TrayIconHolder();

    void doUiRefreshNow();
    void showIconActive();
    void showIconWaiting();

    void requestAbort()
    {
        m_abortRequested = true;
    }

    void OnRequestResume(wxCommandEvent& event)
    {
        m_resumeRequested = true;
    }

    enum Selection
    {
        CONTEXT_ABORT,
        CONTEXT_RESTORE,
        CONTEXT_ABOUT
    };

    void OnContextMenuSelection(wxCommandEvent& event);

private:
    class RtsTrayIcon;
    RtsTrayIcon* trayMenu;

    bool m_abortRequested;
    bool m_resumeRequested;

    const wxString jobName_; //RTS job name, may be empty
};


//RtsTrayIcon shall be a dumb class whose sole purpose is to enable wxWidgets deferred deletion
class TrayIconHolder::RtsTrayIcon : public wxTaskBarIcon
{
public:
    RtsTrayIcon(TrayIconHolder* parent) : parent_(parent) {}

    void parentHasDied() //call before tray icon is marked for deferred deletion
    {
        parent_ = NULL;
    }

private:
    virtual wxMenu* CreatePopupMenu()
    {
        if (!parent_)
            return NULL;

        wxMenu* contextMenu = new wxMenu;
        contextMenu->Append(CONTEXT_RESTORE, _("&Restore"));
        contextMenu->Append(CONTEXT_ABOUT, _("&About..."));
        contextMenu->AppendSeparator();
        contextMenu->Append(CONTEXT_ABORT, _("&Exit"));
        //event handling
        contextMenu->Connect(wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(TrayIconHolder::OnContextMenuSelection), NULL, parent_);

        return contextMenu; //ownership transferred to caller
    }

    TrayIconHolder* parent_;
};
//##############################################################################################################


class AbortThisProcess //exception class
{
public:
    AbortThisProcess(MonitorResponse command) : command_(command) {}

    MonitorResponse getCommand() const
    {
        return command_;
    }

private:
    MonitorResponse command_;
};
//##############################################################################################################


TrayIconHolder::TrayIconHolder(const wxString& jobname) :
    m_abortRequested(false),
    m_resumeRequested(false),
    jobName_(jobname)
{
    trayMenu = new RtsTrayIcon(this); //not in initialization list: give it a valid parent object!

    showIconActive();

    //register double-click
    trayMenu->Connect(wxEVT_TASKBAR_LEFT_DCLICK, wxCommandEventHandler(TrayIconHolder::OnRequestResume), NULL, this);
}


TrayIconHolder::~TrayIconHolder()
{
    trayMenu->Disconnect(wxEVT_TASKBAR_LEFT_DCLICK, wxCommandEventHandler(TrayIconHolder::OnRequestResume), NULL, this);
    trayMenu->RemoveIcon(); //(try to) hide icon until final deletion takes place
    trayMenu->parentHasDied();

    //use wxWidgets delayed destruction: delete during next idle loop iteration (handle late window messages, e.g. when double-clicking)
    if (!wxPendingDelete.Member(trayMenu))
        wxPendingDelete.Append(trayMenu);
}


void TrayIconHolder::showIconActive()
{
    wxIcon realtimeIcon;
#ifdef FFS_WIN
    realtimeIcon.CopyFromBitmap(GlobalResources::getImage(wxT("RTS_tray_win.png"))); //use a 16x16 bitmap
#elif defined FFS_LINUX
    realtimeIcon.CopyFromBitmap(GlobalResources::getImage(wxT("RTS_tray_linux.png"))); //use a 22x22 bitmap for perfect fit
#endif
    const wxString postFix = jobName_.empty() ? wxString() : (wxT("\n\"") + jobName_ + wxT("\""));
    trayMenu->SetIcon(realtimeIcon, _("Monitoring active...") + postFix);
}


void TrayIconHolder::showIconWaiting()
{
    wxIcon realtimeIcon;
#ifdef FFS_WIN
    realtimeIcon.CopyFromBitmap(GlobalResources::getImage(wxT("RTS_tray_waiting_win.png"))); //use a 16x16 bitmap
#elif defined FFS_LINUX
    realtimeIcon.CopyFromBitmap(GlobalResources::getImage(wxT("RTS_tray_waiting_linux.png"))); //use a 22x22 bitmap for perfect fit
#endif
    const wxString postFix = jobName_.empty() ? wxString() : (wxT("\n\"") + jobName_ + wxT("\""));
    trayMenu->SetIcon(realtimeIcon, _("Waiting for missing directories...") + postFix);
}


void TrayIconHolder::OnContextMenuSelection(wxCommandEvent& event)
{
    const int eventId = event.GetId();
    switch (static_cast<Selection>(eventId))
    {
        case CONTEXT_ABORT:
            requestAbort();
            break;
        case CONTEXT_RESTORE:
            OnRequestResume(event); //just remember: never throw exceptions through a C-Layer (GUI) ;)
            break;
        case CONTEXT_ABOUT:
        {
            //build information
            wxString build = __TDATE__;
#if wxUSE_UNICODE
            build += wxT(" - Unicode");
#else
            build += wxT(" - ANSI");
#endif //wxUSE_UNICODE

            //compile time info about 32/64-bit build
            if (zen::is64BitBuild)
                build += wxT(" x64");
            else
                build += wxT(" x86");
            assert_static(zen::is32BitBuild || zen::is64BitBuild);

            wxString buildFormatted = _("(Build: %x)");
            buildFormatted.Replace(wxT("%x"), build);

            wxMessageDialog aboutDlg(NULL, wxString(wxT("RealtimeSync")) + wxT("\n\n") + buildFormatted, _("About"), wxOK);
            aboutDlg.ShowModal();
        }
        break;
    }
}


void TrayIconHolder::doUiRefreshNow()
{
    wxTheApp->Yield();

    if (m_abortRequested)
        throw ::AbortThisProcess(QUIT);

    if (m_resumeRequested)
        throw ::AbortThisProcess(RESUME);
}
//##############################################################################################################

namespace
{
std::vector<Zstring> convert(const std::vector<wxString>& dirList)
{
    std::set<Zstring, LessFilename> output;
    std::transform(dirList.begin(), dirList.end(),
    std::inserter(output, output.end()), [](const wxString & str) { return zen::toZ(str); });
    return std::vector<Zstring>(output.begin(), output.end());
}
}


class StartSyncNowException {};


class WaitCallbackImpl : public rts::WaitCallback
{
public:
    WaitCallbackImpl(const wxString& jobname) :
        trayIcon(jobname),
        nextSyncStart_(std::numeric_limits<long>::max()) {}

    void notifyAllDirectoriesExist()
    {
        trayIcon.showIconActive();
    }

    void notifyDirectoryMissing()
    {
        trayIcon.showIconWaiting();
    }

    virtual void requestUiRefresh() //throw StartSyncNowException()
    {
        if (nextSyncStart_ <= wxGetLocalTime())
            throw StartSyncNowException(); //abort wait and start sync

        if (updateUiIsAllowed())
            trayIcon.doUiRefreshNow();
    }

    void scheduleNextSync(long nextSyncStart)
    {
        nextSyncStart_ = nextSyncStart;
    }

private:
    TrayIconHolder trayIcon;
    long nextSyncStart_;
};

/*
Data Flow:
----------

TrayIconHolder (GUI output)
  /|\
   |
WaitCallbackImpl (higher level "interface")
  /|\
   |
startDirectoryMonitor() (wire dir-changes and execution of commandline)
  /|\
   |
watcher.h (low level wait for directory changes)
*/


rts::MonitorResponse rts::startDirectoryMonitor(const xmlAccess::XmlRealConfig& config, const wxString& jobname)
{
    Zstring lastFileChanged;

    const std::vector<Zstring> dirList = convert(config.directories);
    try
    {
        WaitCallbackImpl callback(jobname);

        if (config.commandline.empty())
        {
            std::wstring errorMsg = _("Invalid command line: %x");
            replace(errorMsg, L"%x", L"\"" + config.commandline + L"\"");
            throw FileError(errorMsg);
        }

        callback.notifyDirectoryMissing();
        waitForMissingDirs(dirList, &callback);
        callback.notifyAllDirectoriesExist();

        while (true)
        {
            ::wxSetEnv(L"changed_file", utf8CvrtTo<wxString>(lastFileChanged)); //some way to output what file changed to the user
            lastFileChanged.clear(); //make sure old name is not shown again after a directory reappears

            //execute command
            zen::shellExecute(config.commandline, zen::EXEC_TYPE_SYNC);

            wxLog::FlushActive(); //show wxWidgets error messages (if any)

            callback.scheduleNextSync(std::numeric_limits<long>::max()); //next sync not scheduled (yet)

            try
            {
                while (true)
                {
                    //wait for changes (and for all directories to become available)
                    WaitResult res = waitForChanges(dirList, &callback);
                    switch (res.type)
                    {
                        case CHANGE_DIR_MISSING: //don't execute the commandline before all directories are available!
                            callback.scheduleNextSync(std::numeric_limits<long>::max()); //next sync not scheduled (yet)
                            callback.notifyDirectoryMissing();
                            waitForMissingDirs(dirList, &callback);
                            callback.notifyAllDirectoriesExist();
                            break;
                        case CHANGE_DETECTED:
                            lastFileChanged = res.filename;
                            break;
                    }

                    callback.scheduleNextSync(wxGetLocalTime() + static_cast<long>(config.delay));
                }
            }
            catch (StartSyncNowException&) {}
        }
    }
    catch (const ::AbortThisProcess& ab)
    {
        return ab.getCommand();
    }
    catch (const zen::FileError& error)
    {
        wxMessageBox(error.toString(), _("Error"), wxOK | wxICON_ERROR);
        return RESUME;
    }

    return RESUME;
}
bgstack15