Repository navigation
Expand file tree
/
Copy pathD-LAN_GUI.cpp
More file actions
355 lines (310 loc) · 12.1 KB
/
Copy pathD-LAN_GUI.cpp
File metadata and controls
355 lines (310 loc) · 12.1 KB
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
/**
* D-LAN - A decentralized LAN file sharing software.
* Copyright (C) 2010-2012 Greg Burri <greg.burri@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Common/Global.h>
#include <D-LAN_GUI.h>
using namespace GUI;
#include <QMessageBox>
#include <QIcon>
#include <QPushButton>
#ifndef Q_OS_WIN
#include <QDir>
#include <QStandardPaths>
#endif
#include <Common/LogManager/Builder.h>
#include <Common/Constants.h>
#include <Common/Settings.h>
#include <Common/Languages.h>
#include <Common/RemoteCoreController/Builder.h>
#include <Log.h>
#ifdef Q_OS_WIN
const QString D_LAN_GUI::SHARED_MEMORY_KEYNAME("D-LAN GUI instance");
#endif
bool D_LAN_GUI::screenScalingIgnored = false;
/**
* @class GUI::D_LAN_GUI
* Creates the main window and, on platforms other than macOS, the tray icon.
* With a tray icon, closing the main window allows it to be reopened from the tray.
*/
/**
* @param autoStartLocalCore See 'RCC::ICoreConnection::setAutoStartLocalCore(..)'.
*/
D_LAN_GUI::D_LAN_GUI(int& argc, char* argv[], bool autoStartLocalCore) :
QApplication(argc, argv),
mainWindow(0),
#ifndef Q_OS_MACOS
trayIcon(QIcon(":/icons/resources/icon.svg")),
#endif
coreConnection(RCC::Builder::newCoreConnection(SETTINGS.get<quint32>("socket_timeout")))
{
// Qt has read them, the processes launched from the GUI (the Core, the opened files) must not inherit them.
if (D_LAN_GUI::screenScalingIgnored)
{
qunsetenv("QT_ENABLE_HIGHDPI_SCALING");
qunsetenv("QT_FONT_DPI");
}
// The style must be set before any widget is created. 'MainWindow::loadCustomStyle(..)' sets it again but
// switching the style once the widgets exist makes 'QWindows11Style::unpolish(..)' clear the
// 'autoFillBackground' flag of every scroll area viewport (Qt >= 6.11.2), the item views then lose their
// 'QPalette::Base' background. See 'MainWindow::loadCustomStyle(..)' about why Fusion is used.
this->setStyle("Fusion");
this->coreConnection->setAutoStartLocalCore(autoStartLocalCore);
this->setWindowIcon(QIcon(":/icons/resources/icon.svg"));
#ifdef Q_OS_LINUX
// Match the desktop entry installed by the Linux package.
this->setDesktopFileName("d-lan");
#endif
this->installTranslator(&this->translator);
QLocale current = QLocale::system();
if (SETTINGS.isSet("language"))
current = SETTINGS.get<QLocale>("language");
Common::Languages langs(Common::Global::getResourceFolder() + "/" + Common::Constants::LANGUAGE_DIRECTORY);
this->loadLanguage(langs.getBestMatchLanguage(Common::Languages::ExeType::GUI, current).filename);
// Keep the instance marker alive for the lifetime of the application.
// Windows frees a shared memory segment when its last process ends, even after a crash. On the other systems
// the segment would outlive a crashed GUI and make the next ones believe it's still running: a lock file is
// used instead.
if (!SETTINGS.get<bool>("multiple_instance_allowed"))
{
#ifndef Q_OS_WIN
const QString runtimeDirectory = QStandardPaths::writableLocation(QStandardPaths::RuntimeLocation);
bool alreadyRunning = false;
if (runtimeDirectory.isEmpty())
L_WARN("Unable to check for another GUI instance: no runtime directory available");
else
{
this->instanceLock.reset(new QLockFile(QDir(runtimeDirectory).filePath("d-lan-gui.lock")));
// A running GUI must never lose its lock due to its age. QLockFile still
// detects dead processes and removes their stale locks after a crash.
this->instanceLock->setStaleLockTime(0);
if (!this->instanceLock->tryLock())
{
alreadyRunning = this->instanceLock->error() == QLockFile::LockFailedError;
if (!alreadyRunning)
L_WARN(QString("Unable to check for another GUI instance: lock error %1").arg(this->instanceLock->error()));
}
}
#else
this->sharedMemory.setKey(SHARED_MEMORY_KEYNAME);
const bool alreadyRunning = !this->sharedMemory.create(1);
#endif
if (alreadyRunning)
{
QMessageBox message;
message.setWindowTitle(QObject::tr("D-LAN already launched"));
message.setText(QObject::tr("An instance of D-LAN is already launched"));
message.setIcon(QMessageBox::Information);
QAbstractButton* abortButton = message.addButton(QObject::tr("Quit"), QMessageBox::RejectRole);
message.addButton(QObject::tr("Launch anyway"), QMessageBox::ActionRole);
message.exec();
if (message.clickedButton() == abortButton)
{
QSharedPointer<LM::ILogger> mainLogger = LM::Builder::newLogger("D-LAN GUI");
mainLogger->log("User interface already launched, exiting . . .", LM::SV_END_USER);
throw AbortException();
}
}
}
this->setQuitOnLastWindowClosed(false);
// Native Quit (including the macOS menu) bypasses our tray Exit action.
connect(this, &QCoreApplication::aboutToQuit, this, [this] { this->shutdown(); });
this->showMainWindow();
#ifdef Q_OS_MACOS
// Cocoa also sends this signal when the Dock icon is clicked while the
// application is already active but has no windows.
connect(this, &QGuiApplication::applicationStateChanged, this, [this](Qt::ApplicationState state)
{
if (state == Qt::ApplicationActive && !this->mainWindow)
this->showMainWindow();
}, Qt::QueuedConnection);
#else
RCC::ICoreConnection* coreConnectionPointer = this->coreConnection.data();
connect(coreConnectionPointer, &RCC::ICoreConnection::localCoreStatusChanged, this, &D_LAN_GUI::updateTrayIconMenu);
connect(coreConnectionPointer, &RCC::ICoreConnection::connected, this, &D_LAN_GUI::updateTrayIconMenu);
connect(coreConnectionPointer, &RCC::ICoreConnection::disconnected, this, &D_LAN_GUI::updateTrayIconMenu);
connect(&this->trayIcon, &QSystemTrayIcon::activated, this, &D_LAN_GUI::trayIconActivated);
this->updateTrayIconMenu();
this->trayIcon.setContextMenu(&this->trayIconMenu);
this->trayIcon.setToolTip("D-LAN");
this->trayIcon.show();
#endif
}
D_LAN_GUI::~D_LAN_GUI()
{
// Also cover destruction when the event loop was never entered.
this->shutdown();
}
bool D_LAN_GUI::notify(QObject* receiver, QEvent* event)
{
try
{
return QApplication::notify(receiver, event);
}
catch (const std::exception& e)
{
qCritical()
<< "Exception in event handler:" << e.what()
<< "| receiver:" << receiver->objectName()
<< receiver->metaObject()->className()
<< "| event type:" << event->type();
}
catch (...)
{
qCritical()
<< "Unknown exception in event handler"
<< "| receiver:" << receiver->objectName()
<< receiver->metaObject()->className()
<< "| event type:" << event->type();
}
// Decide policy here: swallow, or terminate cleanly.
// std::abort();
return false;
}
#ifndef Q_OS_MACOS
bool D_LAN_GUI::event(QEvent* event)
{
if (event->type() == QEvent::LanguageChange)
this->updateTrayIconMenu();
return QApplication::event(event);
}
void D_LAN_GUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
if (reason == QSystemTrayIcon::Trigger)
this->showMainWindow();
}
void D_LAN_GUI::updateTrayIconMenu()
{
if (this->shuttingDown)
return;
this->trayIconMenu.clear();
this->trayIconMenu.addAction(tr("Show the user interface"), this, &D_LAN_GUI::showMainWindow);
// We cannot stop a parent process without killing his child (case with RCC::RUNNING_AS_SUB_PROCESS).
if (this->coreConnection->getLocalCoreStatus() == RCC::RUNNING_AS_SERVICE)
this->trayIconMenu.addAction(tr("Stop the user interface"), this, &D_LAN_GUI::exitGUI);
this->trayIconMenu.addSeparator();
this->trayIconMenu.addAction(tr("Exit"), this, [this]() { this->D_LAN_GUI::exit(true); });
}
#endif
/**
* Load a translation file. If 'filename' is empty the default language is loaded.
*/
void D_LAN_GUI::loadLanguage(const QString& filename)
{
const QString directory = Common::Global::getResourceFolder() + "/" + Common::Constants::LANGUAGE_DIRECTORY;
if (!this->translator.load(filename, directory) && !filename.isEmpty())
{
L_WARN(QString("Can't load translation file '%1' from directory '%2").arg(filename, directory));
}
// The interface is mirrored for the right-to-left languages. Without translation the texts are in English.
const Qt::LayoutDirection direction = this->translator.isEmpty() ? Qt::LeftToRight : QLocale(this->translator.language()).textDirection();
if (direction != this->layoutDirection())
{
this->setLayoutDirection(direction);
// The styles choose some images depending on the direction ('[layoutDirection="RightToLeft"]'), Qt only
// evaluates these selectors when the style sheet is set.
if (!this->styleSheet().isEmpty())
this->setStyleSheet(this->styleSheet());
}
}
/**
* The GUI is displayed as on a 96 DPI screen without scaling, for the styles drawn pixel for pixel
* (see 'MainWindow::ignoreScreenScaling'). Must be called before the application is created.
*/
void D_LAN_GUI::ignoreScreenScaling()
{
qputenv("QT_ENABLE_HIGHDPI_SCALING", "0");
qputenv("QT_FONT_DPI", "96");
D_LAN_GUI::screenScalingIgnored = true;
}
bool D_LAN_GUI::isScreenScalingIgnored()
{
return D_LAN_GUI::screenScalingIgnored;
}
void D_LAN_GUI::mainWindowClosed()
{
// This slot is called by the window's destroyed signal.
this->mainWindow = nullptr;
#ifndef Q_OS_MACOS
// Check on every close, since tray support can change during the session.
if (!QSystemTrayIcon::isSystemTrayAvailable())
{
this->exit(true);
return;
}
if (this->coreConnection->isConnected())
this->trayIcon.showMessage(
tr("D-LAN user interface closed"),
tr("D-LAN Core is still running in background. Select 'exit' from the contextual menu if you want to stop it.")
);
#endif
// Keep the application and core running. The Dock (macOS) or tray can
// recreate the window, whose constructor reconnects to the core.
this->coreConnection->disconnectFromCore();
}
void D_LAN_GUI::showMainWindow()
{
if (this->shuttingDown)
return;
if (this->mainWindow)
{
// Restore a minimized window without losing its maximized state.
this->mainWindow->setWindowState(this->mainWindow->windowState() & ~Qt::WindowMinimized);
this->mainWindow->raise();
this->mainWindow->activateWindow();
}
else
{
this->mainWindow = new MainWindow(this->coreConnection);
connect(this->mainWindow, &MainWindow::languageChanged, this, &D_LAN_GUI::loadLanguage);
connect(this->mainWindow, &MainWindow::destroyed, this, &D_LAN_GUI::mainWindowClosed);
this->mainWindow->show();
}
}
/**
* Stop only the GUI.
*/
void D_LAN_GUI::exitGUI()
{
this->exit(false);
}
void D_LAN_GUI::exit(bool stopTheCore)
{
this->shutdown(stopTheCore);
this->quit();
}
void D_LAN_GUI::shutdown(bool stopTheCore)
{
if (this->shuttingDown)
return;
this->shuttingDown = true;
#ifndef Q_OS_MACOS
this->trayIcon.hide();
#endif
this->coreConnection->disconnect(this);
if (this->mainWindow)
{
auto* window = this->mainWindow;
this->mainWindow = nullptr;
window->disconnect(this);
delete window;
}
// Tear down widgets before disconnecting/stopping the core can emit signals
// or process events. Repeated Quit must also preserve exitGUI's service mode.
this->coreConnection->disconnectFromCore();
if (stopTheCore)
this->coreConnection->stopLocalCore();
}