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
|
// *****************************************************************************
// * This file is part of the FreeFileSync project. It is distributed under *
// * GNU General Public License: https://www.gnu.org/licenses/gpl-3.0 *
// * Copyright (C) Zenju (zenju AT freefilesync DOT org) - All Rights Reserved *
// *****************************************************************************
#include "tray_menu.h"
#include <chrono>
//#include <zen/thread.h>
#include <zen/resolve_path.h>
#include <wx/taskbar.h>
#include <wx/icon.h> //Linux needs this
#include <wx/app.h>
#include <wx/menu.h>
#include <wx/timer.h>
#include <wx+/dc.h>
#include <wx+/image_tools.h>
#include <zen/process_exec.h>
#include <wx+/popup_dlg.h>
#include <wx+/image_resources.h>
#include "monitor.h"
using namespace zen;
using namespace rts;
namespace
{
constexpr std::chrono::seconds RETRY_AFTER_ERROR_INTERVAL(15);
constexpr std::chrono::milliseconds UI_UPDATE_INTERVAL(100); //perform ui updates not more often than necessary, 100 seems to be a good value with only a minimal performance loss
std::chrono::steady_clock::time_point lastExec;
bool uiUpdateDue()
{
const auto now = std::chrono::steady_clock::now();
if (now > lastExec + UI_UPDATE_INTERVAL)
{
lastExec = now;
return true;
}
return false;
}
enum TrayMode
{
active,
waiting,
error,
};
class TrayIconObject : public wxTaskBarIcon
{
public:
TrayIconObject(const wxString& jobname) :
jobName_(jobname)
{
Bind(wxEVT_TASKBAR_LEFT_DCLICK, [this](wxTaskBarIconEvent& event) { onDoubleClick(event); });
assert(mode_ != TrayMode::active); //setMode() supports polling!
setMode(TrayMode::active, Zstring());
timer_.Bind(wxEVT_TIMER, [this](wxTimerEvent& event) { onErrorFlashIcon(event); });
}
//require polling:
bool resumeIsRequested() const { return resumeRequested_; }
bool abortIsRequested () const { return cancelRequested_; }
//during TrayMode::error those two functions are available:
void clearShowErrorRequested() { assert(mode_ == TrayMode::error); showErrorMsgRequested_ = false; }
bool getShowErrorRequested() const { assert(mode_ == TrayMode::error); return showErrorMsgRequested_; }
void setMode(TrayMode m, const Zstring& missingFolderPath)
{
if (mode_ == m && missingFolderPath_ == missingFolderPath)
return; //support polling
mode_ = m;
missingFolderPath_ = missingFolderPath;
timer_.Stop();
switch (m)
{
case TrayMode::active:
setTrayIcon(trayImg_, _("Directory monitoring active"));
break;
case TrayMode::waiting:
assert(!missingFolderPath.empty());
setTrayIcon(greyScale(trayImg_), _("Waiting until directory is available:") + L' ' + fmtPath(missingFolderPath));
break;
case TrayMode::error:
timer_.Start(500); //timer interval in [ms]
break;
}
}
private:
void onErrorFlashIcon(wxEvent& event)
{
iconFlashStatusLast_ = !iconFlashStatusLast_;
setTrayIcon(greyScaleIfDisabled(trayImg_, iconFlashStatusLast_), _("Error"));
}
void setTrayIcon(const wxImage& img, const wxString& statusTxt)
{
wxIcon realtimeIcon;
realtimeIcon.CopyFromBitmap(img);
wxString tooltip = L"RealTimeSync";
if (!jobName_.empty())
tooltip += SPACED_DASH + jobName_;
tooltip += L"\n" + statusTxt;
SetIcon(realtimeIcon, tooltip);
}
wxMenu* CreatePopupMenu() override
{
wxMenu* contextMenu = new wxMenu;
wxMenuItem* defaultItem = nullptr;
switch (mode_)
{
case TrayMode::active:
case TrayMode::waiting:
defaultItem = new wxMenuItem(contextMenu, wxID_ANY, _("&Configure")); //better than "Restore"? https://freefilesync.org/forum/viewtopic.php?t=2044&p=20391#p20391
contextMenu->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent& event) { resumeRequested_ = true; }, defaultItem->GetId());
break;
case TrayMode::error:
defaultItem = new wxMenuItem(contextMenu, wxID_ANY, _("&Show error message"));
contextMenu->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent& event) { showErrorMsgRequested_ = true; }, defaultItem->GetId());
break;
}
contextMenu->Append(defaultItem);
contextMenu->AppendSeparator();
wxMenuItem* itemAbort = contextMenu->Append(wxID_ANY, _("&Quit"));
contextMenu->Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent& event) { cancelRequested_ = true; }, itemAbort->GetId());
return contextMenu; //ownership transferred to caller
}
void onDoubleClick(wxEvent& event)
{
switch (mode_)
{
case TrayMode::active:
case TrayMode::waiting:
resumeRequested_ = true; //never throw exceptions through a C-Layer call stack (GUI)!
break;
case TrayMode::error:
showErrorMsgRequested_ = true;
break;
}
}
bool resumeRequested_ = false;
bool cancelRequested_ = false;
bool showErrorMsgRequested_ = false;
TrayMode mode_ = TrayMode::waiting;
Zstring missingFolderPath_;
bool iconFlashStatusLast_ = false; //flash try icon for TrayMode::error
wxTimer timer_; //
const wxString jobName_; //RTS job name, may be empty
const wxImage trayImg_ = loadImage("start_rts", dipToScreen(24)); //use 24x24 bitmap for perfect fit
};
struct AbortMonitoring //exception class
{
AbortMonitoring(CancelReason reasonCode) : reasonCode_(reasonCode) {}
CancelReason reasonCode_;
};
//=> don't derive from wxEvtHandler or any other wxWidgets object unless instance is safely deleted (deferred) during idle event!!tray_icon.h
class TrayIconHolder
{
public:
TrayIconHolder(const wxString& jobname) :
trayObj_(new TrayIconObject(jobname)) {}
~TrayIconHolder()
{
//harmonize with tray_icon.cpp!!!
trayObj_->RemoveIcon();
//use wxWidgets delayed destruction: delete during next idle loop iteration (handle late window messages, e.g. when double-clicking)
wxPendingDelete.Append(trayObj_);
}
void doUiRefreshNow() //throw AbortMonitoring
{
wxTheApp->Yield(); //yield is UI-layer which is represented by this tray icon
//advantage of polling vs callbacks: we can throw exceptions!
if (trayObj_->resumeIsRequested())
throw AbortMonitoring(CancelReason::requestGui);
if (trayObj_->abortIsRequested())
throw AbortMonitoring(CancelReason::requestExit);
}
void setMode(TrayMode m, const Zstring& missingFolderPath) { trayObj_->setMode(m, missingFolderPath); }
bool getShowErrorRequested() const { return trayObj_->getShowErrorRequested(); }
void clearShowErrorRequested() { trayObj_->clearShowErrorRequested(); }
private:
TrayIconObject* const trayObj_;
};
//##############################################################################################################
}
rts::CancelReason rts::runFolderMonitor(const XmlRealConfig& config, const wxString& jobname)
{
std::vector<Zstring> dirNamesNonFmt = config.directories;
std::erase_if(dirNamesNonFmt, [](const Zstring& str) { return trimCpy(str).empty(); }); //remove empty entries WITHOUT formatting paths yet!
if (dirNamesNonFmt.empty())
{
showNotificationDialog(nullptr, DialogInfoType::error, PopupDialogCfg().setMainInstructions(_("A folder input field is empty.")));
return CancelReason::requestGui;
}
const Zstring cmdLine = trimCpy(config.commandline);
if (cmdLine.empty())
{
showNotificationDialog(nullptr, DialogInfoType::error, PopupDialogCfg().setMainInstructions(replaceCpy(_("Command %x failed."), L"%x", fmtPath(cmdLine))));
return CancelReason::requestGui;
}
TrayIconHolder trayIcon(jobname);
auto executeExternalCommand = [&](const Zstring& changedItemPath, const std::wstring& actionName) //throw FileError
{
::wxSetEnv(L"change_path", utfTo<wxString>(changedItemPath)); //crude way to report changed file
::wxSetEnv(L"change_action", actionName); //
auto cmdLineExp = expandMacros(cmdLine);
try
{
if (const auto& [exitCode, output] = consoleExecute(cmdLineExp, std::nullopt /*timeoutMs*/); //throw SysError, (SysErrorTimeOut)
exitCode != 0)
throw SysError(formatSystemError("", replaceCpy(_("Exit code %x"), L"%x", numberTo<std::wstring>(exitCode)), utfTo<std::wstring>(output)));
}
catch (const SysError& e) { throw FileError(replaceCpy(_("Command %x failed."), L"%x", fmtPath(cmdLineExp)), e.toString()); }
};
auto requestUiUpdate = [&](const Zstring* missingFolderPath)
{
if (missingFolderPath)
trayIcon.setMode(TrayMode::waiting, *missingFolderPath);
else
trayIcon.setMode(TrayMode::active, Zstring());
if (uiUpdateDue())
trayIcon.doUiRefreshNow(); //throw AbortMonitoring
};
auto reportError = [&](const std::wstring& msg)
{
trayIcon.setMode(TrayMode::error, Zstring());
trayIcon.clearShowErrorRequested();
//wait for some time, then return to retry
const auto delayUntil = std::chrono::steady_clock::now() + RETRY_AFTER_ERROR_INTERVAL;
for (auto now = std::chrono::steady_clock::now(); now < delayUntil; now = std::chrono::steady_clock::now())
{
trayIcon.doUiRefreshNow(); //throw AbortMonitoring
if (trayIcon.getShowErrorRequested())
switch (showConfirmationDialog(nullptr, DialogInfoType::error, PopupDialogCfg().
setDetailInstructions(msg), _("&Retry")))
{
case ConfirmationButton::accept: //retry
return;
case ConfirmationButton::cancel:
throw AbortMonitoring(CancelReason::requestGui);
}
std::this_thread::sleep_for(UI_UPDATE_INTERVAL);
}
};
try
{
monitorDirectories(dirNamesNonFmt, std::chrono::seconds(config.delay),
executeExternalCommand /*throw FileError*/,
requestUiUpdate, //throw AbortMonitoring
reportError, //
UI_UPDATE_INTERVAL / 2);
assert(false);
return CancelReason::requestGui;
}
catch (const AbortMonitoring& ab)
{
return ab.reasonCode_;
}
}
|