Debian Codegraph @

src/librssguard/miscellaneous/application.cpp

raw symbols SCIP
1 // For license of this file, see <project-root-folder>/LICENSE.md.
2
3 #include "miscellaneous/application.h"
4
5 #include "3rd-party/boolinq/boolinq.h"
6
7 #if defined(SYSTEM_SQLITE3)
8 #include <sqlite3.h>
9 #else
10 #include "3rd-party/sqlite/sqlite3.h"
11 #endif
12
13 #include "core/feedsmodel.h"
14 #include "dynamic-shortcuts/dynamicshortcuts.h"
15 #include "exceptions/applicationexception.h"
16 #include "gui/dialogs/formabout.h"
17 #include "gui/dialogs/formlog.h"
18 #include "gui/dialogs/formmain.h"
19 #include "gui/feedmessageviewer.h"
20 #include "gui/messagebox.h"
21 #include "gui/messagesview.h"
22 #include "gui/notifications/toastnotificationsmanager.h"
23 #include "gui/toolbars/feedstoolbar.h"
24 #include "gui/toolbars/messagestoolbar.h"
25 #include "gui/toolbars/statusbar.h"
26 #include "gui/webviewers/qtextbrowser/textbrowserviewer.h"
27 #include "miscellaneous/feedreader.h"
28 #include "miscellaneous/iconfactory.h"
29 #include "miscellaneous/iofactory.h"
30 #include "miscellaneous/mutex.h"
31 #include "miscellaneous/notificationfactory.h"
32 #include "miscellaneous/settings.h"
33 #include "network-web/adblock/adblockicon.h"
34 #include "network-web/adblock/adblockmanager.h"
35 #include "network-web/webfactory.h"
36 #include "services/abstract/serviceroot.h"
37
38 #include <iostream>
39
40 #include <QLoggingCategory>
41 #include <QPainter>
42 #include <QPainterPath>
43 #include <QProcess>
44 #include <QSessionManager>
45 #include <QSslSocket>
46 #include <QThreadPool>
47 #include <QTimer>
48 #include <QVersionNumber>
49
50 #if defined(NO_LITE) && defined(MEDIAPLAYER_LIBMPV_OPENGL)
51 #include <QQuickWindow>
52 #endif
53
54 #if defined(Q_OS_UNIX) && !defined(Q_OS_MACOS)
55 #include <QDBusConnection>
56 #include <QDBusMessage>
57 #endif
58
59 #if defined(NO_LITE)
60 #include "gui/webviewers/webengine/webengineviewer.h" // WebEngine-based web browsing.
61 #include "network-web/webengine/networkurlinterceptor.h"
62
63 #if QT_VERSION_MAJOR == 6
64 #include <QWebEngineDownloadRequest>
65 #else
66 #include <QWebEngineDownloadItem>
67 #endif
68
69 #include <QWebEngineProfile>
70 #include <QWebEngineSettings>
71 #endif
72
73 #if defined(Q_OS_WIN)
74 #if QT_VERSION_MAJOR == 5
75 #include <QtPlatformHeaders/QWindowsWindowFunctions>
76 #else
77 #include <QWindow>
78 #include <QtGui/qpa/qplatformwindow_p.h>
79 #endif
80 #endif
81
82 #if defined(Q_OS_WIN)
83 #include <ShObjIdl.h>
84
85 #if QT_VERSION_MAJOR == 5
86 #include <QtWinExtras/QtWin>
87 #endif
88 #endif
89
90 Application::Application(const QString& id, int& argc, char** argv, const QStringList& raw_cli_args)
91 : SingleApplication(id, argc, argv), m_rawCliArgs(raw_cli_args), m_updateFeedsLock(new Mutex()) {
92
93 #if defined(NO_LITE) && defined(MEDIAPLAYER_LIBMPV_OPENGL)
94 // HACK: Force rendering system to use OpenGL backend.
95 #if QT_VERSION_MAJOR < 6
96 QQuickWindow::setSceneGraphBackend(QSGRendererInterface::GraphicsApi::OpenGL);
97 #else
98 QQuickWindow::setGraphicsApi(QSGRendererInterface::GraphicsApi::OpenGL);
99 #endif
100 #endif
101
102 QString custom_ua;
103
104 parseCmdArgumentsFromMyInstance(raw_cli_args, custom_ua);
105
106 qInstallMessageHandler(performLogging);
107
108 m_feedReader = nullptr;
109 m_quitLogicDone = false;
110 m_mainForm = nullptr;
111 m_logForm = nullptr;
112 m_trayIcon = nullptr;
113 m_settings = Settings::setupSettings(this);
114
115 #if defined(NO_LITE)
116 if (!m_forcedLite && qEnvironmentVariableIsEmpty("QTWEBENGINE_CHROMIUM_FLAGS")) {
117 QString flags = settings()->value(GROUP(Browser), SETTING(Browser::WebEngineChromiumFlags)).toString();
118
119 // NOTE: We do not want sandbox on Linux builds.
120 #if defined(Q_OS_LINUX) && !defined(IS_FLATPAK_BUILD)
121 if (!flags.contains(QSL("--no-sandbox"))) {
122 qDebugNN << LOGSEC_CORE << "Appending --no-sandbox to QTWEBENGINE_CHROMIUM_FLAGS.";
123 flags.append(QSL(" --no-sandbox"));
124 }
125 #endif
126
127 qputenv("QTWEBENGINE_CHROMIUM_FLAGS", flags.toLocal8Bit());
128 }
129 #endif
130
131 m_localization = new Localization(this);
132
133 m_localization->loadActiveLanguage();
134
135 m_nodejs = new NodeJs(m_settings, this);
136 m_workHorsePool = new QThreadPool(this);
137 m_webFactory = new WebFactory(this);
138 m_system = new SystemFactory(this);
139 m_skins = new SkinFactory(this);
140 m_icons = new IconFactory(this);
141 m_database = new DatabaseFactory(this);
142 m_downloadManager = nullptr;
143 m_notifications = new NotificationFactory(this);
144 m_toastNotifications =
145 (!isWayland() && m_notifications->useToastNotifications()) ? new ToastNotificationsManager(this) : nullptr;
146 m_shouldRestart = false;
147
148 #if defined(Q_OS_WIN)
149 m_windowsTaskBar = nullptr;
150
151 const GUID qIID_ITaskbarList4 = {0xc43dc798, 0x95d1, 0x4bea, {0x90, 0x30, 0xbb, 0x99, 0xe2, 0x98, 0x3a, 0x1a}};
152 HRESULT task_result = CoCreateInstance(CLSID_TaskbarList,
153 nullptr,
154 CLSCTX_INPROC_SERVER,
155 qIID_ITaskbarList4,
156 reinterpret_cast<void**>(&m_windowsTaskBar));
157
158 if (FAILED(task_result)) {
159 qCriticalNN << LOGSEC_CORE << "Taskbar integration for Windows failed to initialize with HRESULT:"
160 << QUOTE_W_SPACE_DOT(task_result);
161
162 m_windowsTaskBar = nullptr;
163 }
164 else if (FAILED(m_windowsTaskBar->HrInit())) {
165 qCriticalNN << LOGSEC_CORE << "Taskbar integration for Windows failed to initialize with inner HRESULT:"
166 << QUOTE_W_SPACE_DOT(m_windowsTaskBar->HrInit());
167
168 m_windowsTaskBar->Release();
169 m_windowsTaskBar = nullptr;
170 }
171 #endif
172
173 determineFirstRuns();
174
175 // Add an extra path for non-system icon themes and set current icon theme
176 // and skin.
177 m_icons->setupSearchPaths();
178 m_icons->loadCurrentIconTheme();
179
180 reloadCurrentSkin(false);
181 setupFontAntialiasing();
182
183 if (m_toastNotifications != nullptr) {
184 connect(m_toastNotifications,
185 &ToastNotificationsManager::openingArticleInArticleListRequested,
186 this,
187 &Application::loadMessageToFeedAndArticleList);
188 }
189
190 connect(this, &Application::aboutToQuit, this, &Application::onAboutToQuit);
191 connect(this, &Application::commitDataRequest, this, &Application::onCommitData);
192 connect(this, &Application::saveStateRequest, this, &Application::onSaveState);
193
194 connect(m_nodejs, &NodeJs::packageError, this, &Application::onNodeJsPackageUpdateError);
195 connect(m_nodejs, &NodeJs::packageInstalledUpdated, this, &Application::onNodeJsPackageInstalled);
196
197 #if defined(Q_OS_UNIX) && !defined(Q_OS_MACOS)
198 QString app_dir = QString::fromLocal8Bit(qgetenv("APPDIR"));
199
200 if (!app_dir.isEmpty()) {
201 bool success = qputenv("GST_PLUGIN_SYSTEM_PATH_1_0",
202 QSL("%1/usr/lib/gstreamer-1.0:%2")
203 .arg(app_dir, QString::fromLocal8Bit(qgetenv("GST_PLUGIN_SYSTEM_PATH_1_0")))
204 .toLocal8Bit());
205 success = qputenv("GST_PLUGIN_SCANNER_1_0",
206 QSL("%1/usr/lib/gstreamer1.0/gstreamer-1.0/gst-plugin-scanner").arg(app_dir).toLocal8Bit()) &&
207 success;
208 if (!success) {
209 qWarningNN << LOGSEC_CORE << "Unable to set up GStreamer environment.";
210 }
211 }
212 #endif
213
214 if (!custom_ua.isEmpty()) {
215 m_webFactory->setCustomUserAgent(custom_ua);
216 }
217 else {
218 custom_ua = qApp->settings()->value(GROUP(Network), SETTING(Network::CustomUserAgent)).toString();
219 m_webFactory->setCustomUserAgent(custom_ua);
220 }
221
222 #if defined(NO_LITE)
223 m_webFactory->urlIinterceptor()->load();
224
225 QString engine_cache_folder;
226 QString engine_storage_folder;
227
228 #if defined(NDEBUG)
229 engine_cache_folder = cacheFolder();
230 engine_storage_folder = userDataFolder();
231 #else
232 engine_cache_folder = QStandardPaths::writableLocation(QStandardPaths::StandardLocation::TempLocation) +
233 QDir::separator() + QSL(APP_NAME) + QDir::separator() + QSL("cache");
234 engine_storage_folder = QStandardPaths::writableLocation(QStandardPaths::StandardLocation::TempLocation) +
235 QDir::separator() + QSL(APP_NAME) + QDir::separator() + QSL("storage");
236 #endif
237
238 m_webFactory->engineProfile()->setCachePath(engine_cache_folder + QDir::separator() + QSL("web") + QDir::separator() +
239 QSL("cache"));
240 m_webFactory->engineProfile()->setPersistentStoragePath(engine_storage_folder + QDir::separator() + QSL("web") +
241 QDir::separator() + QSL("storage"));
242 m_webFactory->engineProfile()->setHttpCacheType(QWebEngineProfile::HttpCacheType::DiskHttpCache);
243
244 m_webFactory->loadCustomCss(userDataFolder() + QDir::separator() + QSL("web") + QDir::separator() +
245 QSL("user-styles.css"));
246
247 if (custom_ua.isEmpty()) {
248 m_webFactory->engineProfile()->setHttpUserAgent(QString(HTTP_COMPLETE_USERAGENT));
249 }
250 else {
251 m_webFactory->engineProfile()->setHttpUserAgent(custom_ua);
252 }
253
254 qDebugNN << LOGSEC_NETWORK << "Persistent web data storage path:"
255 << QUOTE_W_SPACE_DOT(m_webFactory->engineProfile()->persistentStoragePath());
256
257 connect(m_webFactory->engineProfile(), &QWebEngineProfile::downloadRequested, this, &Application::downloadRequested);
258 #endif
259
260 connect(m_webFactory->adBlock(), &AdBlockManager::processTerminated, this, &Application::onAdBlockFailure);
261
262 QTimer::singleShot(3000, this, [=]() {
263 try {
264 m_webFactory->adBlock()
265 ->setEnabled(qApp->settings()->value(GROUP(AdBlock), SETTING(AdBlock::AdBlockEnabled)).toBool());
266 }
267 catch (...) {
268 onAdBlockFailure();
269 }
270 });
271
272 m_webFactory->updateProxy();
273
274 if (isFirstRun()) {
275 m_notifications->save({Notification(Notification::Event::GeneralEvent, true),
276 Notification(Notification::Event::NewUnreadArticlesFetched,
277 true,
278 false,
279 true,
280 QSL("%1/notify.wav").arg(SOUNDS_BUILTIN_DIRECTORY)),
281 Notification(Notification::Event::NewAppVersionAvailable, true),
282 Notification(Notification::Event::LoginFailure, true),
283 Notification(Notification::Event::ArticlesFetchingError, true),
284 Notification(Notification::Event::NodePackageUpdated, true),
285 Notification(Notification::Event::NodePackageFailedToUpdate, true)},
286 settings());
287 }
288 else {
289 m_notifications->load(settings());
290 }
291
292 QTimer::singleShot(15000, system(), &SystemFactory::checkForUpdatesOnStartup);
293
294 setupWorkHorsePool();
295
296 #if QT_VERSION >= 0x060100 // Qt >= 6.1.0
297 QSslSocket::setActiveBackend(QSL("openssl"));
298 #endif
299
300 qDebugNN << LOGSEC_CORE << "Platform:" << QUOTE_W_SPACE_DOT(QGuiApplication::platformName());
301 qDebugNN << LOGSEC_CORE << "SQLite version:" << QUOTE_W_SPACE_DOT(SQLITE_VERSION);
302
303 #if QT_VERSION >= 0x060100 // Qt >= 6.1.0
304 qDebugNN << LOGSEC_CORE << "OpenSSL backends:" << QUOTE_W_SPACE_DOT(QSslSocket::availableBackends());
305 #endif
306
307 qDebugNN << LOGSEC_CORE << "OpenSSL version:" << QUOTE_W_SPACE_DOT(QSslSocket::sslLibraryVersionString());
308 qDebugNN << LOGSEC_CORE << "OpenSSL supported:" << QUOTE_W_SPACE_DOT(QSslSocket::supportsSsl());
309 qDebugNN << LOGSEC_CORE << "Global thread pool has"
310 << NONQUOTE_W_SPACE(QThreadPool::globalInstance()->maxThreadCount()) << "threads.";
311 }
312
313 Application::~Application() {
314 #if defined(Q_OS_WIN)
315 if (m_windowsTaskBar != nullptr) {
316 m_windowsTaskBar->Release();
317 }
318 #endif
319
320 // Disable logging into the form.
321 m_logForm = nullptr;
322
323 qDebugNN << LOGSEC_CORE << "Destroying Application instance.";
324 }
325
326 QString s_customLogFile = QString();
327 bool s_disableDebug = false;
328
329 void Application::performLogging(QtMsgType type, const QMessageLogContext& context, const QString& msg) {
330 #ifndef QT_NO_DEBUG_OUTPUT
331 QString console_message = qFormatLogMessage(type, context, msg);
332
333 if (!s_disableDebug) {
334 std::cerr << console_message.toStdString() << std::endl;
335 }
336
337 if (!s_customLogFile.isEmpty()) {
338 static QFile* log_file = new QFile(s_customLogFile);
339
340 if (log_file->isOpen() || log_file->open(QFile::OpenModeFlag::Append | QFile::OpenModeFlag::Unbuffered)) {
341 log_file->write(console_message.toUtf8());
342 log_file->write(QSL("\r\n").toUtf8());
343 }
344 }
345
346 if (qApp != nullptr) {
347 qApp->displayLogMessageInDialog(console_message);
348 }
349 if (type == QtMsgType::QtFatalMsg) {
350 qApp->exit(EXIT_FAILURE);
351 }
352 #else
353 Q_UNUSED(type)
354 Q_UNUSED(context)
355 Q_UNUSED(msg)
356 #endif
357 }
358
359 void Application::reactOnForeignNotifications() {
360 connect(this, &Application::messageReceived, this, &Application::parseCmdArgumentsFromOtherInstance);
361 }
362
363 void Application::hideOrShowMainForm() {
364 // Display main window.
365 if (qApp->settings()->value(GROUP(GUI), SETTING(GUI::MainWindowStartsHidden)).toBool()) {
366 qDebugNN << LOGSEC_CORE << "Hiding the main window when the application is starting.";
367 mainForm()->switchVisibility(true);
368 }
369 else {
370 qDebugNN << LOGSEC_CORE << "Showing the main window when the application is starting.";
371 mainForm()->show();
372 }
373 }
374
375 void Application::loadDynamicShortcuts() {
376 DynamicShortcuts::load(userAndExtraActions());
377 }
378
379 void Application::offerPolls() const {
380 /*
381 if (isFirstRunCurrentVersion()) {
382 qApp->web()->openUrlInExternalBrowser(QSL("https://forms.gle/3CZm95W6vrBLfi5K9"));
383 }
384 */
385 }
386
387 void Application::offerChanges() const {
388 if (isFirstRunCurrentVersion()) {
389 qApp->showGuiMessage(Notification::Event::GeneralEvent,
390 {tr("Welcome"),
391 tr("Welcome to %1.\n\nPlease, check NEW stuff included in this\n"
392 "version by clicking this popup notification.")
393 .arg(QSL(APP_LONG_NAME)),
394 QSystemTrayIcon::MessageIcon::Information},
395 {},
396 {tr("Go to changelog"), [] {
397 FormAbout(true, qApp->mainForm()).exec();
398 }});
399 }
400 }
401
402 bool Application::isAlreadyRunning() {
403 return m_allowMultipleInstances
404 ? false
405 : sendMessage((QStringList() << QSL("-%1").arg(QSL(CLI_IS_RUNNING)) << Application::arguments().mid(1))
406 .join(QSL(ARGUMENTS_LIST_SEPARATOR)));
407 }
408
409 QStringList Application::builtinSounds() const {
410 auto builtin_sounds = QDir(QSL(SOUNDS_BUILTIN_DIRECTORY)).entryInfoList(QDir::Filter::Files, QDir::SortFlag::Name);
411 auto iter = boolinq::from(builtin_sounds)
412 .select([](const QFileInfo& i) {
413 return i.absoluteFilePath();
414 })
415 .toStdList();
416 auto descs = FROM_STD_LIST(QStringList, iter);
417
418 return descs;
419 }
420
421 FeedReader* Application::feedReader() {
422 return m_feedReader;
423 }
424
425 QList<QAction*> Application::userActions() {
426 if (m_mainForm != nullptr && m_userActions.isEmpty()) {
427 m_userActions = m_mainForm->allActions();
428 m_userActions.append(m_webFactory->adBlock()->adBlockIcon());
429 }
430
431 return m_userActions;
432 }
433
434 QList<QAction*> Application::userAndExtraActions() {
435 auto user_actions = userActions();
436
437 user_actions << m_mainForm->tabWidget()->feedMessageViewer()->feedsToolBar()->extraActions();
438 user_actions << m_mainForm->tabWidget()->feedMessageViewer()->messagesToolBar()->extraActions();
439 user_actions << m_mainForm->statusBar()->extraActions();
440
441 return user_actions;
442 }
443
444 bool Application::isFirstRun() const {
445 return m_firstRunEver;
446 }
447
448 bool Application::isFirstRunCurrentVersion() const {
449 return m_firstRunCurrentVersion;
450 }
451
452 QCommandLineParser* Application::cmdParser() {
453 return &m_cmdParser;
454 }
455
456 WebFactory* Application::web() const {
457 return m_webFactory;
458 }
459
460 SystemFactory* Application::system() {
461 return m_system;
462 }
463
464 SkinFactory* Application::skins() {
465 return m_skins;
466 }
467
468 Localization* Application::localization() {
469 return m_localization;
470 }
471
472 DatabaseFactory* Application::database() {
473 return m_database;
474 }
475
476 void Application::eliminateFirstRuns() {
477 settings()->setValue(GROUP(General), General::FirstRun, false);
478 settings()->setValue(GROUP(General), QString(General::FirstRun) + QL1C('_') + APP_VERSION, false);
479 }
480
481 void Application::displayLogMessageInDialog(const QString& message) {
482 if (m_logForm != nullptr && m_logForm->isVisible()) {
483 emit sendLogToDialog(message);
484 }
485 }
486
487 ToastNotificationsManager* Application::toastNotifications() const {
488 return m_toastNotifications;
489 }
490
491 QThreadPool* Application::workHorsePool() const {
492 return m_workHorsePool;
493 }
494
495 int Application::customAdblockPort() const {
496 return m_customAdblockPort;
497 }
498
499 QStringList Application::rawCliArgs() const {
500 return m_rawCliArgs;
501 }
502
503 #if defined(NO_LITE)
504 bool Application::forcedLite() const {
505 return m_forcedLite;
506 }
507 #endif
508
509 NodeJs* Application::nodejs() const {
510 return m_nodejs;
511 }
512
513 NotificationFactory* Application::notifications() const {
514 return m_notifications;
515 }
516
517 void Application::setFeedReader(FeedReader* feed_reader) {
518 m_feedReader = feed_reader;
519
520 connect(m_feedReader, &FeedReader::feedUpdatesStarted, this, &Application::onFeedUpdatesStarted);
521 connect(m_feedReader, &FeedReader::feedUpdatesProgress, this, &Application::onFeedUpdatesProgress);
522 connect(m_feedReader, &FeedReader::feedUpdatesFinished, this, &Application::onFeedUpdatesFinished);
523 connect(m_feedReader->feedsModel(), &FeedsModel::messageCountsChanged, this, &Application::showMessagesNumber);
524 }
525
526 IconFactory* Application::icons() {
527 return m_icons;
528 }
529
530 DownloadManager* Application::downloadManager() {
531 if (m_downloadManager == nullptr) {
532 m_downloadManager = new DownloadManager();
533 connect(m_downloadManager,
534 &DownloadManager::downloadFinished,
535 mainForm()->statusBar(),
536 &StatusBar::clearProgressDownload);
537 connect(m_downloadManager,
538 &DownloadManager::downloadProgressed,
539 mainForm()->statusBar(),
540 &StatusBar::showProgressDownload);
541 }
542
543 return m_downloadManager;
544 }
545
546 Settings* Application::settings() const {
547 return m_settings;
548 }
549
550 Mutex* Application::feedUpdateLock() {
551 return m_updateFeedsLock.data();
552 }
553
554 FormMain* Application::mainForm() {
555 return m_mainForm;
556 }
557
558 QWidget* Application::mainFormWidget() {
559 return m_mainForm;
560 }
561
562 void Application::setMainForm(FormMain* main_form) {
563 m_mainForm = main_form;
564
565 if (m_toastNotifications != nullptr) {
566 connect(m_toastNotifications,
567 &ToastNotificationsManager::reloadMessageListRequested,
568 m_mainForm->tabWidget()->feedMessageViewer()->messagesView(),
569 &MessagesView::reloadSelections);
570 }
571 }
572
573 QString Application::configFolder() const {
574 return IOFactory::getSystemFolder(QStandardPaths::StandardLocation::GenericConfigLocation);
575 }
576
577 QString Application::userDataAppFolder() const {
578 static int major_version = QVersionNumber::fromString(QSL(APP_VERSION)).majorVersion();
579
580 // In "app" folder, we would like to separate all user data into own subfolder,
581 // therefore stick to "data" folder in this mode.
582 return QDir::toNativeSeparators(applicationDirPath() + QDir::separator() + QSL("data%1").arg(major_version));
583 }
584
585 QString Application::userDataFolder() {
586 if (settings()->type() == SettingsProperties::SettingsType::Custom) {
587 return customDataFolder();
588 }
589 else if (settings()->type() == SettingsProperties::SettingsType::Portable) {
590 return userDataAppFolder();
591 }
592 else {
593 return userDataHomeFolder();
594 }
595 }
596
597 QString Application::cacheFolder() {
598 #if defined(Q_OS_LINUX)
599 return QStandardPaths::writableLocation(QStandardPaths::StandardLocation::CacheLocation);
600 #else
601 return userDataFolder();
602 #endif
603 }
604
605 QString Application::replaceUserDataFolderPlaceholder(QString text) const {
606 auto user_data_folder = qApp->userDataFolder();
607
608 return text.replace(QSL(USER_DATA_PLACEHOLDER), user_data_folder);
609 }
610
611 QStringList Application::replaceUserDataFolderPlaceholder(QStringList texts) const {
612 auto user_data_folder = qApp->userDataFolder();
613
614 return texts.replaceInStrings(QSL(USER_DATA_PLACEHOLDER), user_data_folder);
615 }
616
617 QString Application::userDataHomeFolder() const {
618 QString pth;
619 static int major_version = QVersionNumber::fromString(QSL(APP_VERSION)).majorVersion();
620
621 #if defined(Q_OS_ANDROID)
622 return pth = IOFactory::getSystemFolder(QStandardPaths::GenericDataLocation) + QDir::separator() + QSL(APP_NAME) +
623 QSL(" %1").arg(major_version);
624 #else
625 return pth = configFolder() + QDir::separator() + QSL(APP_NAME) + QSL(" %1").arg(major_version);
626 #endif
627
628 return QDir::toNativeSeparators(pth);
629 }
630
631 QString Application::tempFolder() const {
632 return IOFactory::getSystemFolder(QStandardPaths::StandardLocation::TempLocation);
633 }
634
635 QString Application::documentsFolder() const {
636 return IOFactory::getSystemFolder(QStandardPaths::StandardLocation::DocumentsLocation);
637 }
638
639 QString Application::homeFolder() const {
640 #if defined(Q_OS_ANDROID)
641 return IOFactory::getSystemFolder(QStandardPaths::StandardLocation::GenericDataLocation);
642 #else
643 return IOFactory::getSystemFolder(QStandardPaths::StandardLocation::HomeLocation);
644 #endif
645 }
646
647 void Application::backupDatabaseSettings(bool backup_database,
648 bool backup_settings,
649 const QString& target_path,
650 const QString& backup_name) {
651 if (!QFileInfo(target_path).isWritable()) {
652 throw ApplicationException(tr("Output directory is not writable."));
653 }
654
655 if (backup_settings) {
656 settings()->sync();
657
658 if (!IOFactory::copyFile(settings()->fileName(),
659 target_path + QDir::separator() + backup_name + BACKUP_SUFFIX_SETTINGS)) {
660 throw ApplicationException(tr("Settings file not copied to output directory successfully."));
661 }
662 }
663
664 if (backup_database) {
665 database()->driver()->backupDatabase(target_path, backup_name);
666 }
667 }
668
669 void Application::restoreDatabaseSettings(bool restore_database,
670 bool restore_settings,
671 const QString& source_database_file_path,
672 const QString& source_settings_file_path) {
673 if (restore_database) {
674 if (!qApp->database()->driver()->initiateRestoration(source_database_file_path)) {
675 throw ApplicationException(tr("Database restoration was not initiated. Make sure that output directory is "
676 "writable."));
677 }
678 }
679
680 if (restore_settings) {
681 if (!qApp->settings()->initiateRestoration(source_settings_file_path)) {
682 throw ApplicationException(tr("Settings restoration was not initiated. Make sure that output directory is "
683 "writable."));
684 }
685 }
686 }
687
688 SystemTrayIcon* Application::trayIcon() {
689 if (m_trayIcon == nullptr) {
690 if (qApp->settings()->value(GROUP(GUI), SETTING(GUI::MonochromeTrayIcon)).toBool()) {
691 if (qApp->settings()->value(GROUP(GUI), SETTING(GUI::ColoredBusyTrayIcon)).toBool()) {
692 m_trayIcon = new SystemTrayIcon(APP_ICON_MONO_PATH, APP_ICON_PLAIN_PATH, m_mainForm);
693 }
694 else {
695 m_trayIcon = new SystemTrayIcon(APP_ICON_MONO_PATH, APP_ICON_MONO_PLAIN_PATH, m_mainForm);
696 }
697 }
698 else {
699 m_trayIcon = new SystemTrayIcon(APP_ICON_PATH, APP_ICON_PLAIN_PATH, m_mainForm);
700 }
701
702 connect(m_trayIcon, &SystemTrayIcon::shown, m_feedReader->feedsModel(), &FeedsModel::notifyWithCounts);
703 }
704
705 return m_trayIcon;
706 }
707
708 QIcon Application::desktopAwareIcon() const {
709 auto from_theme = m_icons->fromTheme(QSL(APP_LOW_NAME));
710
711 if (!from_theme.isNull()) {
712 return from_theme;
713 }
714 else {
715 return QIcon(APP_ICON_PATH);
716 }
717 }
718
719 void Application::showTrayIcon() {
720 // Display tray icon if it is enabled and available.
721 if (SystemTrayIcon::isSystemTrayDesired()) {
722 qDebugNN << LOGSEC_GUI << "User wants to have tray icon.";
723
724 // Delay avoids race conditions and tray icon is properly displayed.
725 qWarningNN << LOGSEC_GUI << "Showing tray icon with little delay.";
726
727 QTimer::singleShot(
728 #if defined(Q_OS_WIN)
729 500,
730 #else
731 3000,
732 #endif
733 this,
734 [=]() {
735 if (SystemTrayIcon::isSystemTrayAreaAvailable()) {
736 qWarningNN << LOGSEC_GUI << "Tray icon is available, showing now.";
737 trayIcon()->show();
738 }
739 else {
740 m_feedReader->feedsModel()->notifyWithCounts();
741 }
742
743 // NOTE: Below things have to be performed after tray icon is (if enabled)
744 // initialized.
745 offerChanges();
746 offerPolls();
747
748 #if defined(Q_OS_WIN)
749 #if QT_VERSION_MAJOR == 6
750 // NOTE: Fixes https://github.com/martinrotter/rssguard/issues/953 for Qt 6.
751 using QWindowsWindow = QNativeInterface::Private::QWindowsWindow;
752 if (auto w_w = qApp->mainForm()->windowHandle()->nativeInterface<QWindowsWindow>()) {
753 w_w->setHasBorderInFullScreen(true);
754 }
755 #endif
756 #endif
757 });
758 }
759 else {
760 m_feedReader->feedsModel()->notifyWithCounts();
761 }
762 }
763
764 void Application::deleteTrayIcon() {
765 if (m_trayIcon != nullptr) {
766 qDebugNN << LOGSEC_CORE << "Disabling tray icon, deleting it and raising main application window.";
767 m_mainForm->display();
768 delete m_trayIcon;
769 m_trayIcon = nullptr;
770
771 // Make sure that application quits when last window is closed.
772 setQuitOnLastWindowClosed(true);
773 }
774 }
775
776 void Application::showGuiMessageCore(Notification::Event event,
777 const GuiMessage& msg,
778 GuiMessageDestination dest,
779 const GuiAction& action,
780 QWidget* parent) {
781 bool show_dialog = true;
782
783 if (m_notifications->areNotificationsEnabled()) {
784 auto notification = m_notifications->notificationForEvent(event);
785
786 show_dialog = notification.dialogEnabled();
787
788 if (notification.soundEnabled()) {
789 notification.playSound(this);
790 }
791
792 if (notification.balloonEnabled() && dest.m_tray) {
793 if (notification.event() == Notification::Event::ArticlesFetchingStarted && m_mainForm != nullptr &&
794 m_mainForm->isActiveWindow() && m_mainForm->isVisible()) {
795 // We do not need to display the notification because
796 // user will see that fetching is running because
797 // he will see progress bar.
798 return;
799 }
800
801 if (m_toastNotifications != nullptr) {
802 // Toasts are enabled.
803 m_toastNotifications->showNotification(event, msg, action);
804 }
805 else if (SystemTrayIcon::isSystemTrayDesired() && SystemTrayIcon::isSystemTrayAreaAvailable()) {
806 // Use tray icon balloons (which are implemented as native notifications on most systems.
807 trayIcon()->showMessage(msg.m_title.simplified().isEmpty() ? Notification::nameForEvent(notification.event())
808 : msg.m_title,
809 msg.m_message,
810 msg.m_type,
811 TRAY_ICON_BUBBLE_TIMEOUT,
812 std::move(action.m_action));
813 }
814
815 return;
816 }
817 }
818
819 if (show_dialog && (dest.m_messageBox || msg.m_type == QSystemTrayIcon::MessageIcon::Critical)) {
820 // Tray icon or OSD is not available, display simple text box.
821 MsgBox::show(parent == nullptr ? mainFormWidget() : parent,
822 QMessageBox::Icon(msg.m_type),
823 msg.m_title,
824 msg.m_message,
825 {},
826 {},
827 QMessageBox::StandardButton::Ok,
828 QMessageBox::StandardButton::Ok,
829 {},
830 action.m_title,
831 action.m_action);
832 }
833 else if (dest.m_statusBar && mainForm()->statusBar() != nullptr && mainForm()->statusBar()->isVisible()) {
834 mainForm()->statusBar()->showMessage(msg.m_message, 3000);
835 }
836 else {
837 qDebugNN << LOGSEC_CORE << "Silencing GUI message:" << QUOTE_W_SPACE_DOT(msg.m_message);
838 }
839 }
840
841 void Application::loadMessageToFeedAndArticleList(Feed* feed, const Message& message) {
842 m_mainForm->display();
843 m_mainForm->tabWidget()->feedMessageViewer()->loadMessageToFeedAndArticleList(feed, message);
844 }
845
846 void Application::showGuiMessage(Notification::Event event,
847 const GuiMessage& msg,
848 GuiMessageDestination dest,
849 const GuiAction& action,
850 QWidget* parent) {
851 QMetaObject::invokeMethod(this,
852 "showGuiMessageCore",
853 Qt::ConnectionType::QueuedConnection,
854 Q_ARG(Notification::Event, event),
855 Q_ARG(const GuiMessage&, msg),
856 Q_ARG(GuiMessageDestination, dest),
857 Q_ARG(const GuiAction&, action),
858 Q_ARG(QWidget*, parent));
859 }
860
861 WebViewer* Application::createWebView() {
862 #if !defined(NO_LITE)
863 return new TextBrowserViewer();
864 #else
865 if (forcedLite()) {
866 return new TextBrowserViewer();
867 }
868 else {
869 return new WebEngineViewer();
870 }
871 #endif
872 }
873
874 bool Application::usingLite() const {
875 #if !defined(NO_LITE)
876 return true;
877 #else
878 return forcedLite();
879 #endif
880 }
881
882 bool Application::isWayland() const {
883 return QGuiApplication::platformName() == QSL("wayland");
884 }
885
886 void Application::onCommitData(QSessionManager& manager) {
887 qDebugNN << LOGSEC_CORE << "OS asked application to commit its data.";
888
889 onAboutToQuit();
890
891 manager.setRestartHint(QSessionManager::RestartHint::RestartNever);
892 manager.release();
893 }
894
895 void Application::onSaveState(QSessionManager& manager) {
896 qDebugNN << LOGSEC_CORE << "OS asked application to save its state.";
897
898 manager.setRestartHint(QSessionManager::RestartHint::RestartNever);
899 manager.release();
900 }
901
902 void Application::onAboutToQuit() {
903 if (m_quitLogicDone) {
904 qWarningNN << LOGSEC_CORE << "On-close logic is already done.";
905 return;
906 }
907
908 m_quitLogicDone = true;
909
910 // Make sure that we obtain close lock BEFORE even trying to quit the application.
911 const bool locked_safely = feedUpdateLock()->tryLock(4 * CLOSE_LOCK_TIMEOUT);
912
913 QCoreApplication::processEvents();
914 qDebugNN << LOGSEC_CORE << "Cleaning up resources and saving application state.";
915
916 if (locked_safely) {
917 // Application obtained permission to close in a safe way.
918 qDebugNN << LOGSEC_CORE << "Close lock was obtained safely.";
919
920 // We locked the lock to exit peacefully, unlock it to avoid warnings.
921 feedUpdateLock()->unlock();
922 }
923 else {
924 // Request for write lock timed-out. This means
925 // that some critical action can be processed right now.
926 qWarningNN << LOGSEC_CORE << "Close lock timed-out.";
927 }
928
929 qApp->feedReader()->quit();
930
931 try {
932 database()->driver()->saveDatabase();
933 }
934 catch (const ApplicationException& ex) {
935 qCriticalNN << LOGSEC_DB << "Error when saving DB:" << QUOTE_W_SPACE_DOT(ex.message());
936 }
937
938 if (mainForm() != nullptr) {
939 mainForm()->saveSize();
940 }
941
942 settings()->sync();
943
944 // Now, we can check if application should just quit or restart itself.
945 if (m_shouldRestart) {
946 finish();
947 qDebugNN << LOGSEC_CORE << "Killing local peer connection to allow another instance to start.";
948
949 if (QProcess::startDetached(QDir::toNativeSeparators(applicationFilePath()), arguments().mid(1))) {
950 qDebugNN << LOGSEC_CORE << "New application instance was started.";
951 }
952 else {
953 qCriticalNN << LOGSEC_CORE << "New application instance was not started successfully.";
954 }
955 }
956 }
957
958 void Application::showMessagesNumber(int unread_messages, bool any_feed_has_new_unread_messages) {
959 if (m_trayIcon != nullptr) {
960 m_trayIcon->setNumber(unread_messages, any_feed_has_new_unread_messages);
961 }
962
963 // Use Qt function to set "badge" number directly in some cases.
964 #if defined(Q_OS_MACOS) && QT_VERSION >= 0x060500 // Qt >= 6.5.0
965 qApp->setBadgeNumber(unread_messages);
966 #else
967 #if defined(Q_OS_UNIX) && !defined(Q_OS_MACOS)
968 // Use D-Bus "LauncherEntry" service on Linux.
969 bool task_bar_count_enabled = settings()->value(GROUP(GUI), SETTING(GUI::UnreadNumbersOnTaskBar)).toBool();
970 QDBusMessage signal = QDBusMessage::createSignal(QSL("/"), QSL("com.canonical.Unity.LauncherEntry"), QSL("Update"));
971
972 signal << QSL("application://%1.desktop").arg(APP_REVERSE_NAME);
973
974 QVariantMap setProperty;
975
976 setProperty.insert("count", qint64(unread_messages));
977 setProperty.insert("count-visible", task_bar_count_enabled && unread_messages > 0);
978
979 signal << setProperty;
980
981 QDBusConnection::sessionBus().send(signal);
982 #elif defined(Q_OS_WIN)
983 // Use SetOverlayIcon Windows API method on Windows.
984 bool task_bar_count_enabled = settings()->value(GROUP(GUI), SETTING(GUI::UnreadNumbersOnTaskBar)).toBool();
985
986 if (m_mainForm != nullptr) {
987 bool any_count = task_bar_count_enabled && unread_messages > 0;
988 HRESULT overlay_result;
989
990 if (any_count) {
991 QImage overlay_icon = generateOverlayIcon(unread_messages);
992
993 #if QT_VERSION_MAJOR == 5
994 HICON overlay_hicon = QtWin::toHICON(QPixmap::fromImage(overlay_icon));
995 #else
996 HICON overlay_hicon = overlay_icon.toHICON();
997 #endif
998
999 overlay_result =
1000 m_windowsTaskBar->SetOverlayIcon(reinterpret_cast<HWND>(m_mainForm->winId()), overlay_hicon, nullptr);
1001
1002 DestroyIcon(overlay_hicon);
1003 }
1004 else {
1005 overlay_result = m_windowsTaskBar->SetOverlayIcon(reinterpret_cast<HWND>(m_mainForm->winId()), nullptr, nullptr);
1006 }
1007
1008 if (FAILED(overlay_result)) {
1009 qCriticalNN << LOGSEC_GUI << "Failed to set overlay icon with HRESULT:" << QUOTE_W_SPACE_DOT(overlay_result);
1010 }
1011 }
1012 else {
1013 qCriticalNN << LOGSEC_GUI << "Main form not set for setting numbers.";
1014 }
1015 #endif
1016 #endif
1017
1018 if (m_mainForm != nullptr) {
1019 m_mainForm->setWindowTitle(unread_messages > 0
1020 ? QSL("[%2] %1").arg(QSL(APP_LONG_NAME), QString::number(unread_messages))
1021 : QSL(APP_LONG_NAME));
1022 }
1023 }
1024
1025 #if defined(Q_OS_WIN)
1026 QImage Application::generateOverlayIcon(int number) const {
1027 QImage img(128, 128, QImage::Format::Format_ARGB32);
1028 QPainter p;
1029 QString num_txt;
1030
1031 if (number < 1000) {
1032 num_txt = QString::number(number);
1033 }
1034 else if (number < 100000) {
1035 num_txt = QSL("%1k").arg(int(number / 1000));
1036 }
1037 else {
1038 num_txt = QChar(8734);
1039 }
1040
1041 QPainterPath rounded_rectangle;
1042 rounded_rectangle.addRoundedRect(QRectF(img.rect()), 15, 15);
1043 QFont fon = font();
1044
1045 if (num_txt.size() == 3) {
1046 fon.setPixelSize(img.width() * 0.52);
1047 }
1048 else if (num_txt.size() == 2) {
1049 fon.setPixelSize(img.width() * 0.68);
1050 }
1051 else {
1052 fon.setPixelSize(img.width() * 0.79);
1053 }
1054
1055 p.begin(&img);
1056 p.setFont(fon);
1057
1058 p.setRenderHint(QPainter::RenderHint::SmoothPixmapTransform, true);
1059 p.setRenderHint(QPainter::RenderHint::TextAntialiasing, true);
1060
1061 img.fill(Qt::GlobalColor::transparent);
1062
1063 p.fillPath(rounded_rectangle, Qt::GlobalColor::white);
1064
1065 p.setPen(Qt::GlobalColor::black);
1066 p.drawPath(rounded_rectangle);
1067
1068 p.drawText(img.rect().marginsRemoved(QMargins(0, 0, 0, img.height() * 0.05)),
1069 num_txt,
1070 QTextOption(Qt::AlignmentFlag::AlignCenter));
1071 p.end();
1072
1073 return img;
1074 }
1075 #endif
1076
1077 void Application::setupFontAntialiasing() {
1078 bool aa_enabled = qApp->settings()->value(GROUP(GUI), SETTING(GUI::FontAntialiasing)).toBool();
1079
1080 QFont fon = QApplication::font();
1081 fon.setStyleStrategy(aa_enabled ? QFont::StyleStrategy::PreferAntialias
1082 : QFont::StyleStrategy(QFont::StyleStrategy::NoAntialias |
1083 QFont::StyleStrategy::NoSubpixelAntialias));
1084 QApplication::setFont(fon);
1085 }
1086
1087 void Application::restart() {
1088 m_shouldRestart = true;
1089 quit();
1090 }
1091
1092 #if defined(NO_LITE)
1093
1094 #if QT_VERSION_MAJOR == 6
1095 void Application::downloadRequested(QWebEngineDownloadRequest* download_item) {
1096 #else
1097 void Application::downloadRequested(QWebEngineDownloadItem* download_item) {
1098 #endif
1099 downloadManager()->download(download_item->url());
1100 download_item->cancel();
1101 download_item->deleteLater();
1102 }
1103
1104 #endif
1105
1106 void Application::onFeedUpdatesStarted() {
1107 #if defined(Q_OS_WIN)
1108 // Use SetOverlayIcon Windows API method on Windows.
1109 bool task_bar_count_enabled = settings()->value(GROUP(GUI), SETTING(GUI::UnreadNumbersOnTaskBar)).toBool();
1110
1111 if (task_bar_count_enabled && m_mainForm != nullptr && m_windowsTaskBar != nullptr) {
1112 m_windowsTaskBar->SetProgressValue(reinterpret_cast<HWND>(m_mainForm->winId()), 1ul, 100ul);
1113 }
1114 #endif
1115 }
1116
1117 void Application::onFeedUpdatesProgress(const Feed* feed, int current, int total) {
1118 #if defined(Q_OS_WIN)
1119 // Use SetOverlayIcon Windows API method on Windows.
1120 bool task_bar_count_enabled = settings()->value(GROUP(GUI), SETTING(GUI::UnreadNumbersOnTaskBar)).toBool();
1121
1122 if (task_bar_count_enabled && m_mainForm != nullptr && m_windowsTaskBar != nullptr) {
1123 m_windowsTaskBar->SetProgressValue(reinterpret_cast<HWND>(m_mainForm->winId()), current, total);
1124 }
1125 #endif
1126 }
1127
1128 void Application::onFeedUpdatesFinished(const FeedDownloadResults& results) {
1129 auto fds = results.updatedFeeds().keys();
1130 bool some_unquiet_feed = boolinq::from(fds).any([](Feed* fd) {
1131 return !fd->isQuiet();
1132 });
1133
1134 if (some_unquiet_feed) {
1135 GuiMessage msg = {tr("Unread articles fetched"), QString(), QSystemTrayIcon::MessageIcon::NoIcon};
1136
1137 if (m_toastNotifications != nullptr) {
1138 // Show custom and richer overview of updated feeds and articles.
1139 msg.m_feedFetchResults = results;
1140 }
1141 else {
1142 // Show simpler overview of updated feeds.
1143 msg.m_message = results.overview(10);
1144 }
1145
1146 qApp->showGuiMessage(Notification::Event::NewUnreadArticlesFetched, msg);
1147 }
1148
1149 #if defined(Q_OS_WIN)
1150 // Use SetOverlayIcon Windows API method on Windows.
1151 bool task_bar_count_enabled = settings()->value(GROUP(GUI), SETTING(GUI::UnreadNumbersOnTaskBar)).toBool();
1152
1153 if (task_bar_count_enabled && m_mainForm != nullptr && m_windowsTaskBar != nullptr) {
1154 m_windowsTaskBar->SetProgressState(reinterpret_cast<HWND>(m_mainForm->winId()), TBPFLAG::TBPF_NOPROGRESS);
1155 }
1156 #endif
1157 }
1158
1159 void Application::setupCustomDataFolder(const QString& data_folder) {
1160 if (!QDir().mkpath(data_folder)) {
1161 qCriticalNN << LOGSEC_CORE << "Failed to create custom data path" << QUOTE_W_SPACE(data_folder)
1162 << "thus falling back to standard setup.";
1163 m_customDataFolder = QString();
1164 return;
1165 }
1166
1167 // Disable single instance mode.
1168 m_allowMultipleInstances = true;
1169
1170 // Save custom data folder.
1171 m_customDataFolder = data_folder;
1172 }
1173
1174 void Application::setupWorkHorsePool() {
1175 auto ideal_th_count = QThread::idealThreadCount();
1176 int custom_threads = m_cmdParser.value(QSL(CLI_THREADS)).toInt();
1177
1178 if (custom_threads > 0) {
1179 m_workHorsePool->setMaxThreadCount((std::min)(MAX_THREADPOOL_THREADS, custom_threads));
1180 }
1181 else if (ideal_th_count > 1) {
1182 m_workHorsePool->setMaxThreadCount((std::min)(MAX_THREADPOOL_THREADS, 2 * ideal_th_count));
1183 }
1184
1185 #if QT_VERSION >= 0x060200 // Qt >= 6.2.0
1186 // Avoid competing with interactive processes/threads by running the
1187 // worker pool at a very low priority
1188 m_workHorsePool->setThreadPriority(QThread::Priority::LowestPriority);
1189 #endif
1190
1191 // NOTE: Do not expire threads so that their IDs are not reused.
1192 // This fixes cross-thread QSqlDatabase access.
1193 m_workHorsePool->setExpiryTimeout(-1);
1194
1195 #if QT_VERSION_MAJOR == 5
1196 // NOTE: Qt 5 sadly does not allow to specify custom thread pool for
1197 // QtConcurrent::mapped() method, so we have to use global thread pool
1198 // there.
1199 QThreadPool::globalInstance()->setMaxThreadCount(m_workHorsePool->maxThreadCount());
1200 QThreadPool::globalInstance()->setExpiryTimeout(m_workHorsePool->expiryTimeout());
1201 #endif
1202 }
1203
1204 void Application::onAdBlockFailure() {
1205 qApp->showGuiMessage(Notification::Event::GeneralEvent,
1206 {tr("AdBlock needs to be configured"),
1207 tr("AdBlock is not configured properly or failed to start. Go to \"Settings\" -> \"Node.js\" "
1208 "and check "
1209 "if your Node.js is properly configured."),
1210 QSystemTrayIcon::MessageIcon::Critical},
1211 {true, true, false});
1212
1213 qApp->settings()->setValue(GROUP(AdBlock), AdBlock::AdBlockEnabled, false);
1214 }
1215
1216 void Application::reloadCurrentSkin(bool replace_existing_qss) {
1217 m_skins->loadCurrentSkin(usingLite(), replace_existing_qss);
1218 }
1219
1220 void Application::determineFirstRuns() {
1221 m_firstRunEver = settings()->value(GROUP(General), SETTING(General::FirstRun)).toBool();
1222 m_firstRunCurrentVersion =
1223 settings()->value(GROUP(General), QString(General::FirstRun) + QL1C('_') + APP_VERSION, true).toBool();
1224
1225 eliminateFirstRuns();
1226 }
1227
1228 void Application::parseCmdArgumentsFromOtherInstance(const QString& message) {
1229 if (message.isEmpty()) {
1230 qDebugNN << LOGSEC_CORE << "No execution message received from other app instances.";
1231 return;
1232 }
1233
1234 qDebugNN << LOGSEC_CORE << "Received" << QUOTE_W_SPACE(message) << "execution message.";
1235
1236 #if QT_VERSION >= 0x050F00 // Qt >= 5.15.0
1237 QStringList messages = message.split(QSL(ARGUMENTS_LIST_SEPARATOR), Qt::SplitBehaviorFlags::SkipEmptyParts);
1238 #else
1239 QStringList messages = message.split(QSL(ARGUMENTS_LIST_SEPARATOR), QString::SplitBehavior::SkipEmptyParts);
1240 #endif
1241
1242 QCommandLineParser cmd_parser;
1243
1244 messages.prepend(qApp->applicationFilePath());
1245
1246 cmd_parser.addOption(QCommandLineOption({QSL(CLI_QUIT_INSTANCE)}));
1247 cmd_parser.addOption(QCommandLineOption({QSL(CLI_IS_RUNNING)}));
1248
1249 fillCmdArgumentsParser(cmd_parser);
1250
1251 if (!cmd_parser.parse(messages)) {
1252 qCriticalNN << LOGSEC_CORE << cmd_parser.errorText();
1253 }
1254
1255 if (cmd_parser.isSet(QSL(CLI_QUIT_INSTANCE))) {
1256 quit();
1257 return;
1258 }
1259 else if (cmd_parser.isSet(QSL(CLI_IS_RUNNING))) {
1260 showGuiMessage(Notification::Event::GeneralEvent,
1261 {tr("Already running"),
1262 tr("Application is already running."),
1263 QSystemTrayIcon::MessageIcon::Information});
1264 mainForm()->display();
1265 }
1266
1267 messages = cmd_parser.positionalArguments();
1268
1269 for (const QString& msg : std::as_const(messages)) {
1270 // Application was running, and someone wants to add new feed.
1271 ServiceRoot* rt = boolinq::from(feedReader()->feedsModel()->serviceRoots()).firstOrDefault([](ServiceRoot* root) {
1272 return root->supportsFeedAdding();
1273 });
1274
1275 if (rt != nullptr) {
1276 rt->addNewFeed(nullptr, msg);
1277 }
1278 else {
1279 showGuiMessage(Notification::Event::GeneralEvent,
1280 {tr("Cannot add feed"),
1281 tr("Feed cannot be added because there is no active account which can add feeds."),
1282 QSystemTrayIcon::MessageIcon::Warning});
1283 }
1284 }
1285 }
1286
1287 void Application::parseCmdArgumentsFromMyInstance(const QStringList& raw_cli_args, QString& custom_ua) {
1288 fillCmdArgumentsParser(m_cmdParser);
1289
1290 m_cmdParser.setApplicationDescription(QSL(APP_NAME));
1291 m_cmdParser.setSingleDashWordOptionMode(QCommandLineParser::SingleDashWordOptionMode::ParseAsLongOptions);
1292
1293 if (!m_cmdParser.parse(raw_cli_args)) {
1294 qCriticalNN << LOGSEC_CORE << m_cmdParser.errorText();
1295 }
1296
1297 s_customLogFile = m_cmdParser.value(QSL(CLI_LOG_SHORT));
1298
1299 if (s_customLogFile.startsWith('\'')) {
1300 s_customLogFile = s_customLogFile.mid(1);
1301 }
1302
1303 if (s_customLogFile.endsWith('\'')) {
1304 s_customLogFile.chop(1);
1305 }
1306
1307 if (m_cmdParser.isSet(QSL(CLI_NDEBUG_SHORT))) {
1308 QLoggingCategory::setFilterRules(QSL("*.debug=false"));
1309 }
1310
1311 if (!m_cmdParser.value(QSL(CLI_DAT_SHORT)).isEmpty()) {
1312 auto data_folder = QDir::toNativeSeparators(m_cmdParser.value(QSL(CLI_DAT_SHORT)));
1313
1314 qDebugNN << LOGSEC_CORE << "User wants to use custom directory for user data (and disable single instance mode):"
1315 << QUOTE_W_SPACE_DOT(data_folder);
1316
1317 setupCustomDataFolder(data_folder);
1318 }
1319 else {
1320 m_allowMultipleInstances = false;
1321 }
1322
1323 if (m_cmdParser.isSet(QSL(CLI_HELP_SHORT))) {
1324 m_cmdParser.showHelp();
1325 }
1326 else if (m_cmdParser.isSet(QSL(CLI_VER_SHORT))) {
1327 m_cmdParser.showVersion();
1328 }
1329
1330 #if defined(NO_LITE)
1331 m_forcedLite = m_cmdParser.isSet(QSL(CLI_FORCE_LITE_SHORT));
1332
1333 if (m_forcedLite) {
1334 qDebugNN << LOGSEC_CORE << "Forcing no-web-engine.";
1335 }
1336 #endif
1337
1338 if (m_cmdParser.isSet(QSL(CLI_SIN_SHORT))) {
1339 m_allowMultipleInstances = true;
1340 qDebugNN << LOGSEC_CORE << "Explicitly allowing this instance to run.";
1341 }
1342
1343 if (m_cmdParser.isSet(QSL(CLI_NSTDOUTERR_SHORT))) {
1344 s_disableDebug = true;
1345 qDebugNN << LOGSEC_CORE << "Disabling any stdout/stderr outputs.";
1346 }
1347
1348 if (!m_cmdParser.value(QSL(CLI_ADBLOCKPORT_SHORT)).isEmpty()) {
1349 m_customAdblockPort = m_cmdParser.value(QSL(CLI_ADBLOCKPORT_SHORT)).toInt();
1350
1351 qDebugNN << LOGSEC_ADBLOCK << "Setting custom server port.";
1352 }
1353 else {
1354 m_customAdblockPort = 0;
1355 }
1356
1357 custom_ua = m_cmdParser.value(QSL(CLI_USERAGENT_SHORT));
1358 }
1359
1360 void Application::displayLog() {
1361 if (m_logForm == nullptr) {
1362 m_logForm = new FormLog(m_mainForm);
1363
1364 connect(this,
1365 &Application::sendLogToDialog,
1366 m_logForm,
1367 &FormLog::appendLogMessage,
1368 Qt::ConnectionType::QueuedConnection);
1369 }
1370
1371 m_logForm->close();
1372 m_logForm->show();
1373 }
1374
1375 void Application::fillCmdArgumentsParser(QCommandLineParser& parser) {
1376 QCommandLineOption help({QSL(CLI_HELP_SHORT), QSL(CLI_HELP_LONG)}, QSL("Displays overview of CLI."));
1377 QCommandLineOption version({QSL(CLI_VER_SHORT), QSL(CLI_VER_LONG)}, QSL("Displays version of the application."));
1378 QCommandLineOption
1379 log_file({QSL(CLI_LOG_SHORT), QSL(CLI_LOG_LONG)},
1380 QSL("Write application debug log to file. Note that logging to file may slow application down."),
1381 QSL("log-file"));
1382 QCommandLineOption
1383 custom_data_folder({QSL(CLI_DAT_SHORT), QSL(CLI_DAT_LONG)},
1384 QSL("Use custom folder for user data and disable single instance application mode."),
1385 QSL("user-data-folder"));
1386 QCommandLineOption disable_singleinstance({QSL(CLI_SIN_SHORT), QSL(CLI_SIN_LONG)},
1387 QSL("Allow running of multiple application instances."));
1388
1389 #if defined(NO_LITE)
1390 QCommandLineOption force_lite({QSL(CLI_FORCE_LITE_SHORT), QSL(CLI_FORCE_LITE_LONG)},
1391 QSL("Force lite variant of application."));
1392 #endif
1393
1394 QCommandLineOption disable_only_debug({QSL(CLI_NDEBUG_SHORT), QSL(CLI_NDEBUG_LONG)},
1395 QSL("Disable just \"debug\" output."));
1396 QCommandLineOption disable_debug({QSL(CLI_NSTDOUTERR_SHORT), QSL(CLI_NSTDOUTERR_LONG)},
1397 QSL("Completely disable stdout/stderr outputs."));
1398 QCommandLineOption forced_style({QSL(CLI_STYLE_SHORT), QSL(CLI_STYLE_LONG)},
1399 QSL("Force some application style."),
1400 QSL("style-name"));
1401
1402 QCommandLineOption custom_ua({QSL(CLI_USERAGENT_SHORT), QSL(CLI_USERAGENT_LONG)},
1403 QSL("User custom User-Agent HTTP header for all network requests. This option "
1404 "takes precedence over User-Agent set via application settings."),
1405 QSL("user-agent"));
1406 QCommandLineOption
1407 adblock_port({QSL(CLI_ADBLOCKPORT_SHORT), QSL(CLI_ADBLOCKPORT_LONG)},
1408 QSL("Use custom port for AdBlock server. It is highly recommended to use values higher than 1024."),
1409 QSL("port"));
1410
1411 QCommandLineOption custom_threads(QSL(CLI_THREADS),
1412 QSL("Specify number of threads. Note that number cannot be higher than %1.")
1413 .arg(MAX_THREADPOOL_THREADS),
1414 QSL("count"));
1415
1416 parser.addOptions({help,
1417 version,
1418 log_file,
1419 custom_data_folder,
1420 disable_singleinstance,
1421 disable_only_debug,
1422 disable_debug,
1423 #if defined(NO_LITE)
1424 force_lite,
1425 #endif
1426 forced_style,
1427 adblock_port,
1428 custom_ua,
1429 custom_threads});
1430 parser.addPositionalArgument(QSL("urls"),
1431 QSL("List of URL addresses pointing to individual online feeds which should be added."),
1432 QSL("[url-1 ... url-n]"));
1433 }
1434
1435 void Application::onNodeJsPackageUpdateError(const QObject* sndr,
1436 const QList<NodeJs::PackageMetadata>& pkgs,
1437 const QString& error) {
1438 Q_UNUSED(sndr)
1439 qApp->showGuiMessage(Notification::Event::NodePackageFailedToUpdate,
1440 {QSL("Node.js"),
1441 tr("Packages were NOT updated because of error: %2. Affected packages:\n%1")
1442 .arg(NodeJs::packagesToString(pkgs), error),
1443 QSystemTrayIcon::MessageIcon::Critical});
1444 }
1445
1446 void Application::onNodeJsPackageInstalled(const QObject* sndr,
1447 const QList<NodeJs::PackageMetadata>& pkgs,
1448 bool already_up_to_date) {
1449 Q_UNUSED(sndr)
1450 if (!already_up_to_date) {
1451 qApp->showGuiMessage(Notification::Event::NodePackageUpdated,
1452 {tr("Node.js"),
1453 tr("These packages were installed/updated:\n%1").arg(NodeJs::packagesToString(pkgs)),
1454 QSystemTrayIcon::MessageIcon::Information});
1455 }
1456 }
1457
1458 QString Application::customDataFolder() const {
1459 return m_customDataFolder;
1460 }