application.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  1. /*
  2. * Copyright (C) by Duncan Mac-Vicar P. <duncan@kde.org>
  3. * Copyright (C) by Klaas Freitag <freitag@owncloud.com>
  4. * Copyright (C) by Daniel Molkentin <danimo@owncloud.com>
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful, but
  12. * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  13. * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  14. * for more details.
  15. */
  16. #include "application.h"
  17. #include <iostream>
  18. #include <random>
  19. #include "config.h"
  20. #include "account.h"
  21. #include "accountstate.h"
  22. #include "connectionvalidator.h"
  23. #include "folder.h"
  24. #include "folderman.h"
  25. #include "logger.h"
  26. #include "configfile.h"
  27. #include "socketapi.h"
  28. #include "sslerrordialog.h"
  29. #include "theme.h"
  30. #include "clientproxy.h"
  31. #include "sharedialog.h"
  32. #include "accountmanager.h"
  33. #include "creds/abstractcredentials.h"
  34. #if defined(BUILD_UPDATER)
  35. #include "updater/ocupdater.h"
  36. #endif
  37. #include "owncloudsetupwizard.h"
  38. #include "version.h"
  39. #include "csync_exclude.h"
  40. #include "common/vfs.h"
  41. #include "config.h"
  42. #if defined(Q_OS_WIN)
  43. #include <windows.h>
  44. #endif
  45. #if defined(WITH_CRASHREPORTER)
  46. #include <libcrashreporter-handler/Handler.h>
  47. #endif
  48. #include <QTranslator>
  49. #include <QMenu>
  50. #include <QMessageBox>
  51. #include <QDesktopServices>
  52. #include <QGuiApplication>
  53. class QSocket;
  54. namespace OCC {
  55. Q_LOGGING_CATEGORY(lcApplication, "nextcloud.gui.application", QtInfoMsg)
  56. namespace {
  57. static const char optionsC[] =
  58. "Options:\n"
  59. " --help, -h : show this help screen.\n"
  60. " --version, -v : show version information.\n"
  61. " -q --quit : quit the running instance\n"
  62. " --logwindow, -l : open a window to show log output.\n"
  63. " --logfile <filename> : write log output to file <filename>.\n"
  64. " --logdir <name> : write each sync log output in a new file\n"
  65. " in folder <name>.\n"
  66. " --logexpire <hours> : removes logs older than <hours> hours.\n"
  67. " (to be used with --logdir)\n"
  68. " --logflush : flush the log file after every write.\n"
  69. " --logdebug : also output debug-level messages in the log.\n"
  70. " --confdir <dirname> : Use the given configuration folder.\n"
  71. " --background : launch the application in the background.\n";
  72. QString applicationTrPath()
  73. {
  74. QString devTrPath = qApp->applicationDirPath() + QString::fromLatin1("/../src/gui/");
  75. if (QDir(devTrPath).exists()) {
  76. // might miss Qt, QtKeyChain, etc.
  77. qCWarning(lcApplication) << "Running from build location! Translations may be incomplete!";
  78. return devTrPath;
  79. }
  80. #if defined(Q_OS_WIN)
  81. return QApplication::applicationDirPath() + QLatin1String("/i18n/");
  82. #elif defined(Q_OS_MAC)
  83. return QApplication::applicationDirPath() + QLatin1String("/../Resources/Translations"); // path defaults to app dir.
  84. #elif defined(Q_OS_UNIX)
  85. return QString::fromLatin1(SHAREDIR "/" APPLICATION_EXECUTABLE "/i18n/");
  86. #endif
  87. }
  88. }
  89. // ----------------------------------------------------------------------------------
  90. bool Application::configVersionMigration()
  91. {
  92. QStringList deleteKeys, ignoreKeys;
  93. AccountManager::backwardMigrationSettingsKeys(&deleteKeys, &ignoreKeys);
  94. FolderMan::backwardMigrationSettingsKeys(&deleteKeys, &ignoreKeys);
  95. ConfigFile configFile;
  96. // Did the client version change?
  97. // (The client version is adjusted further down)
  98. bool versionChanged = configFile.clientVersionString() != MIRALL_VERSION_STRING;
  99. // We want to message the user either for destructive changes,
  100. // or if we're ignoring something and the client version changed.
  101. bool warningMessage = !deleteKeys.isEmpty() || (!ignoreKeys.isEmpty() && versionChanged);
  102. if (!versionChanged && !warningMessage)
  103. return true;
  104. const auto backupFile = configFile.backup();
  105. if (warningMessage) {
  106. QString boldMessage;
  107. if (!deleteKeys.isEmpty()) {
  108. boldMessage = tr("Continuing will mean <b>deleting these settings</b>.");
  109. } else {
  110. boldMessage = tr("Continuing will mean <b>ignoring these settings</b>.");
  111. }
  112. QMessageBox box(
  113. QMessageBox::Warning,
  114. APPLICATION_SHORTNAME,
  115. tr("Some settings were configured in newer versions of this client and "
  116. "use features that are not available in this version.<br>"
  117. "<br>"
  118. "%1<br>"
  119. "<br>"
  120. "The current configuration file was already backed up to <i>%2</i>.")
  121. .arg(boldMessage, backupFile));
  122. box.addButton(tr("Quit"), QMessageBox::AcceptRole);
  123. auto continueBtn = box.addButton(tr("Continue"), QMessageBox::DestructiveRole);
  124. box.exec();
  125. if (box.clickedButton() != continueBtn) {
  126. QTimer::singleShot(0, qApp, SLOT(quit()));
  127. return false;
  128. }
  129. auto settings = ConfigFile::settingsWithGroup("foo");
  130. settings->endGroup();
  131. // Wipe confusing keys from the future, ignore the others
  132. for (const auto &badKey : deleteKeys)
  133. settings->remove(badKey);
  134. }
  135. configFile.setClientVersionString(MIRALL_VERSION_STRING);
  136. return true;
  137. }
  138. ownCloudGui *Application::gui() const
  139. {
  140. return _gui;
  141. }
  142. Application::Application(int &argc, char **argv)
  143. : SharedTools::QtSingleApplication(Theme::instance()->appName(), argc, argv)
  144. , _gui(nullptr)
  145. , _theme(Theme::instance())
  146. , _helpOnly(false)
  147. , _versionOnly(false)
  148. , _showLogWindow(false)
  149. , _logExpire(0)
  150. , _logFlush(false)
  151. , _logDebug(false)
  152. , _userTriggeredConnect(false)
  153. , _debugMode(false)
  154. , _backgroundMode(false)
  155. {
  156. _startedAt.start();
  157. qsrand(std::random_device()());
  158. #ifdef Q_OS_WIN
  159. // Ensure OpenSSL config file is only loaded from app directory
  160. QString opensslConf = QCoreApplication::applicationDirPath() + QString("/openssl.cnf");
  161. qputenv("OPENSSL_CONF", opensslConf.toLocal8Bit());
  162. #endif
  163. // TODO: Can't set this without breaking current config paths
  164. // setOrganizationName(QLatin1String(APPLICATION_VENDOR));
  165. setOrganizationDomain(QLatin1String(APPLICATION_REV_DOMAIN));
  166. // setDesktopFilename to provide wayland compatibility (in general: conformance with naming standards)
  167. // but only on Qt >= 5.7, where setDesktopFilename was introduced
  168. #if (QT_VERSION >= 0x050700)
  169. QString desktopFileName = QString(QLatin1String(LINUX_APPLICATION_ID)
  170. + QLatin1String(".desktop"));
  171. setDesktopFileName(desktopFileName);
  172. #endif
  173. setApplicationName(_theme->appName());
  174. setWindowIcon(_theme->applicationIcon());
  175. if (!ConfigFile().exists()) {
  176. // Migrate from version <= 2.4
  177. setApplicationName(_theme->appNameGUI());
  178. #ifndef QT_WARNING_DISABLE_DEPRECATED // Was added in Qt 5.9
  179. #define QT_WARNING_DISABLE_DEPRECATED QT_WARNING_DISABLE_GCC("-Wdeprecated-declarations")
  180. #endif
  181. QT_WARNING_PUSH
  182. QT_WARNING_DISABLE_DEPRECATED
  183. // We need to use the deprecated QDesktopServices::storageLocation because of its Qt4
  184. // behavior of adding "data" to the path
  185. QString oldDir = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
  186. if (oldDir.endsWith('/')) oldDir.chop(1); // macOS 10.11.x does not like trailing slash for rename/move.
  187. QT_WARNING_POP
  188. setApplicationName(_theme->appName());
  189. if (QFileInfo(oldDir).isDir()) {
  190. auto confDir = ConfigFile().configPath();
  191. if (confDir.endsWith('/')) confDir.chop(1); // macOS 10.11.x does not like trailing slash for rename/move.
  192. qCInfo(lcApplication) << "Migrating old config from" << oldDir << "to" << confDir;
  193. if (!QFile::rename(oldDir, confDir)) {
  194. qCWarning(lcApplication) << "Failed to move the old config directory to its new location (" << oldDir << "to" << confDir << ")";
  195. // Try to move the files one by one
  196. if (QFileInfo(confDir).isDir() || QDir().mkdir(confDir)) {
  197. const QStringList filesList = QDir(oldDir).entryList(QDir::Files);
  198. qCInfo(lcApplication) << "Will move the individual files" << filesList;
  199. for (const auto &name : filesList) {
  200. if (!QFile::rename(oldDir + "/" + name, confDir + "/" + name)) {
  201. qCWarning(lcApplication) << "Fallback move of " << name << "also failed";
  202. }
  203. }
  204. }
  205. } else {
  206. #ifndef Q_OS_WIN
  207. // Create a symbolic link so a downgrade of the client would still find the config.
  208. QFile::link(confDir, oldDir);
  209. #endif
  210. }
  211. }
  212. }
  213. parseOptions(arguments());
  214. //no need to waste time;
  215. if (_helpOnly || _versionOnly)
  216. return;
  217. if (_quitInstance) {
  218. QTimer::singleShot(0, qApp, &QApplication::quit);
  219. return;
  220. }
  221. if (isRunning())
  222. return;
  223. #if defined(WITH_CRASHREPORTER)
  224. if (ConfigFile().crashReporter()) {
  225. auto reporter = QStringLiteral(CRASHREPORTER_EXECUTABLE);
  226. #ifdef Q_OS_WIN
  227. if (!reporter.endsWith(QLatin1String(".exe"))) {
  228. reporter.append(QLatin1String(".exe"));
  229. }
  230. #endif
  231. _crashHandler.reset(new CrashReporter::Handler(QDir::tempPath(), true, reporter));
  232. }
  233. #endif
  234. setupLogging();
  235. setupTranslations();
  236. if (!configVersionMigration()) {
  237. return;
  238. }
  239. ConfigFile cfg;
  240. // The timeout is initialized with an environment variable, if not, override with the value from the config
  241. if (!AbstractNetworkJob::httpTimeout)
  242. AbstractNetworkJob::httpTimeout = cfg.timeout();
  243. // Check vfs plugins
  244. if (Theme::instance()->showVirtualFilesOption() && bestAvailableVfsMode() == Vfs::Off) {
  245. qCWarning(lcApplication) << "Theme wants to show vfs mode, but no vfs plugins are available";
  246. }
  247. if (isVfsPluginAvailable(Vfs::WindowsCfApi))
  248. qCInfo(lcApplication) << "VFS windows plugin is available";
  249. if (isVfsPluginAvailable(Vfs::WithSuffix))
  250. qCInfo(lcApplication) << "VFS suffix plugin is available";
  251. _folderManager.reset(new FolderMan);
  252. connect(this, &SharedTools::QtSingleApplication::messageReceived, this, &Application::slotParseMessage);
  253. if (!AccountManager::instance()->restore()) {
  254. // If there is an error reading the account settings, try again
  255. // after a couple of seconds, if that fails, give up.
  256. // (non-existence is not an error)
  257. Utility::sleep(5);
  258. if (!AccountManager::instance()->restore()) {
  259. qCCritical(lcApplication) << "Could not read the account settings, quitting";
  260. QMessageBox::critical(
  261. nullptr,
  262. tr("Error accessing the configuration file"),
  263. tr("There was an error while accessing the configuration "
  264. "file at %1. Please make sure the file can be accessed by your user.")
  265. .arg(ConfigFile().configFile()),
  266. tr("Quit %1").arg(Theme::instance()->appNameGUI()));
  267. QTimer::singleShot(0, qApp, SLOT(quit()));
  268. return;
  269. }
  270. }
  271. FolderMan::instance()->setSyncEnabled(true);
  272. setQuitOnLastWindowClosed(false);
  273. _theme->setSystrayUseMonoIcons(cfg.monoIcons());
  274. connect(_theme, &Theme::systrayUseMonoIconsChanged, this, &Application::slotUseMonoIconsChanged);
  275. // Setting up the gui class will allow tray notifications for the
  276. // setup that follows, like folder setup
  277. _gui = new ownCloudGui(this);
  278. if (_showLogWindow) {
  279. _gui->slotToggleLogBrowser(); // _showLogWindow is set in parseOptions.
  280. }
  281. #if WITH_LIBCLOUDPROVIDERS
  282. _gui->setupCloudProviders();
  283. #endif
  284. FolderMan::instance()->setupFolders();
  285. _proxy.setupQtProxyFromConfig(); // folders have to be defined first, than we set up the Qt proxy.
  286. connect(AccountManager::instance(), &AccountManager::accountAdded,
  287. this, &Application::slotAccountStateAdded);
  288. connect(AccountManager::instance(), &AccountManager::accountRemoved,
  289. this, &Application::slotAccountStateRemoved);
  290. for (const auto &ai : AccountManager::instance()->accounts()) {
  291. slotAccountStateAdded(ai.data());
  292. }
  293. connect(FolderMan::instance()->socketApi(), &SocketApi::shareCommandReceived,
  294. _gui.data(), &ownCloudGui::slotShowShareDialog);
  295. // startup procedure.
  296. connect(&_checkConnectionTimer, &QTimer::timeout, this, &Application::slotCheckConnection);
  297. _checkConnectionTimer.setInterval(ConnectionValidator::DefaultCallingIntervalMsec); // check for connection every 32 seconds.
  298. _checkConnectionTimer.start();
  299. // Also check immediately
  300. QTimer::singleShot(0, this, &Application::slotCheckConnection);
  301. // Can't use onlineStateChanged because it is always true on modern systems because of many interfaces
  302. connect(&_networkConfigurationManager, &QNetworkConfigurationManager::configurationChanged,
  303. this, &Application::slotSystemOnlineConfigurationChanged);
  304. #if defined(BUILD_UPDATER)
  305. // Update checks
  306. auto *updaterScheduler = new UpdaterScheduler(this);
  307. connect(updaterScheduler, &UpdaterScheduler::updaterAnnouncement,
  308. _gui.data(), &ownCloudGui::slotShowTrayMessage);
  309. connect(updaterScheduler, &UpdaterScheduler::requestRestart,
  310. _folderManager.data(), &FolderMan::slotScheduleAppRestart);
  311. #endif
  312. // Cleanup at Quit.
  313. connect(this, &QCoreApplication::aboutToQuit, this, &Application::slotCleanup);
  314. // Allow other classes to hook into isShowingSettingsDialog() signals (re-auth widgets, for example)
  315. connect(_gui.data(), &ownCloudGui::isShowingSettingsDialog, this, &Application::slotGuiIsShowingSettings);
  316. _gui->createTray();
  317. }
  318. Application::~Application()
  319. {
  320. // Make sure all folders are gone, otherwise removing the
  321. // accounts will remove the associated folders from the settings.
  322. if (_folderManager) {
  323. _folderManager->unloadAndDeleteAllFolders();
  324. }
  325. // Remove the account from the account manager so it can be deleted.
  326. disconnect(AccountManager::instance(), &AccountManager::accountRemoved,
  327. this, &Application::slotAccountStateRemoved);
  328. AccountManager::instance()->shutdown();
  329. }
  330. void Application::slotAccountStateRemoved(AccountState *accountState)
  331. {
  332. if (_gui) {
  333. disconnect(accountState, &AccountState::stateChanged,
  334. _gui.data(), &ownCloudGui::slotAccountStateChanged);
  335. disconnect(accountState->account().data(), &Account::serverVersionChanged,
  336. _gui.data(), &ownCloudGui::slotTrayMessageIfServerUnsupported);
  337. }
  338. if (_folderManager) {
  339. disconnect(accountState, &AccountState::stateChanged,
  340. _folderManager.data(), &FolderMan::slotAccountStateChanged);
  341. disconnect(accountState->account().data(), &Account::serverVersionChanged,
  342. _folderManager.data(), &FolderMan::slotServerVersionChanged);
  343. }
  344. // if there is no more account, show the wizard.
  345. if (_gui && AccountManager::instance()->accounts().isEmpty()) {
  346. // allow to add a new account if there is non any more. Always think
  347. // about single account theming!
  348. OwncloudSetupWizard::runWizard(this, SLOT(slotownCloudWizardDone(int)));
  349. }
  350. }
  351. void Application::slotAccountStateAdded(AccountState *accountState)
  352. {
  353. connect(accountState, &AccountState::stateChanged,
  354. _gui.data(), &ownCloudGui::slotAccountStateChanged);
  355. connect(accountState->account().data(), &Account::serverVersionChanged,
  356. _gui.data(), &ownCloudGui::slotTrayMessageIfServerUnsupported);
  357. connect(accountState, &AccountState::stateChanged,
  358. _folderManager.data(), &FolderMan::slotAccountStateChanged);
  359. connect(accountState->account().data(), &Account::serverVersionChanged,
  360. _folderManager.data(), &FolderMan::slotServerVersionChanged);
  361. _gui->slotTrayMessageIfServerUnsupported(accountState->account().data());
  362. }
  363. void Application::slotCleanup()
  364. {
  365. AccountManager::instance()->save();
  366. FolderMan::instance()->unloadAndDeleteAllFolders();
  367. _gui->slotShutdown();
  368. _gui->deleteLater();
  369. }
  370. // FIXME: This is not ideal yet since a ConnectionValidator might already be running and is in
  371. // progress of timing out in some seconds.
  372. // Maybe we need 2 validators, one triggered by timer, one by network configuration changes?
  373. void Application::slotSystemOnlineConfigurationChanged(QNetworkConfiguration cnf)
  374. {
  375. if (cnf.state() & QNetworkConfiguration::Active) {
  376. QMetaObject::invokeMethod(this, "slotCheckConnection", Qt::QueuedConnection);
  377. }
  378. }
  379. void Application::slotCheckConnection()
  380. {
  381. const auto list = AccountManager::instance()->accounts();
  382. for (const auto &accountState : list) {
  383. AccountState::State state = accountState->state();
  384. // Don't check if we're manually signed out or
  385. // when the error is permanent.
  386. if (state != AccountState::SignedOut
  387. && state != AccountState::ConfigurationError
  388. && state != AccountState::AskingCredentials) {
  389. accountState->checkConnectivity();
  390. }
  391. }
  392. if (list.isEmpty()) {
  393. // let gui open the setup wizard
  394. _gui->slotOpenSettingsDialog();
  395. _checkConnectionTimer.stop(); // don't popup the wizard on interval;
  396. }
  397. }
  398. void Application::slotCrash()
  399. {
  400. Utility::crash();
  401. }
  402. void Application::slotownCloudWizardDone(int res)
  403. {
  404. FolderMan *folderMan = FolderMan::instance();
  405. // During the wizard, scheduling of new syncs is disabled
  406. folderMan->setSyncEnabled(true);
  407. if (res == QDialog::Accepted) {
  408. // Check connectivity of the newly created account
  409. _checkConnectionTimer.start();
  410. slotCheckConnection();
  411. // If one account is configured: enable autostart
  412. #ifndef QT_DEBUG
  413. bool shouldSetAutoStart = AccountManager::instance()->accounts().size() == 1;
  414. #else
  415. bool shouldSetAutoStart = false;
  416. #endif
  417. #ifdef Q_OS_MAC
  418. // Don't auto start when not being 'installed'
  419. shouldSetAutoStart = shouldSetAutoStart
  420. && QCoreApplication::applicationDirPath().startsWith("/Applications/");
  421. #endif
  422. if (shouldSetAutoStart) {
  423. Utility::setLaunchOnStartup(_theme->appName(), _theme->appNameGUI(), true);
  424. }
  425. Systray::instance()->showWindow();
  426. }
  427. }
  428. void Application::setupLogging()
  429. {
  430. // might be called from second instance
  431. auto logger = Logger::instance();
  432. logger->setLogFile(_logFile);
  433. if (_logFile.isEmpty()) {
  434. logger->setLogDir(_logDir.isEmpty() ? ConfigFile().logDir() : _logDir);
  435. }
  436. logger->setLogExpire(_logExpire > 0 ? _logExpire : ConfigFile().logExpire());
  437. logger->setLogFlush(_logFlush || ConfigFile().logFlush());
  438. logger->setLogDebug(_logDebug || ConfigFile().logDebug());
  439. if (!logger->isLoggingToFile() && ConfigFile().automaticLogDir()) {
  440. logger->setupTemporaryFolderLogDir();
  441. }
  442. logger->enterNextLogFile();
  443. qCInfo(lcApplication) << QString::fromLatin1("################## %1 locale:[%2] ui_lang:[%3] version:[%4] os:[%5]").arg(_theme->appName()).arg(QLocale::system().name()).arg(property("ui_lang").toString()).arg(_theme->version()).arg(Utility::platformName());
  444. }
  445. void Application::slotUseMonoIconsChanged(bool)
  446. {
  447. _gui->slotComputeOverallSyncStatus();
  448. }
  449. void Application::slotParseMessage(const QString &msg, QObject *)
  450. {
  451. if (msg.startsWith(QLatin1String("MSG_PARSEOPTIONS:"))) {
  452. const int lengthOfMsgPrefix = 17;
  453. QStringList options = msg.mid(lengthOfMsgPrefix).split(QLatin1Char('|'));
  454. _showLogWindow = false;
  455. parseOptions(options);
  456. setupLogging();
  457. if (_showLogWindow) {
  458. _gui->slotToggleLogBrowser(); // _showLogWindow is set in parseOptions.
  459. }
  460. if (_quitInstance) {
  461. qApp->quit();
  462. }
  463. } else if (msg.startsWith(QLatin1String("MSG_SHOWMAINDIALOG"))) {
  464. qCInfo(lcApplication) << "Running for" << _startedAt.elapsed() / 1000.0 << "sec";
  465. if (_startedAt.elapsed() < 10 * 1000) {
  466. // This call is mirrored with the one in int main()
  467. qCWarning(lcApplication) << "Ignoring MSG_SHOWMAINDIALOG, possibly double-invocation of client via session restore and auto start";
  468. return;
  469. }
  470. // Show the main dialog only if there is at least one account configured
  471. if (!AccountManager::instance()->accounts().isEmpty()) {
  472. showMainDialog();
  473. } else {
  474. _gui->slotNewAccountWizard();
  475. }
  476. }
  477. }
  478. void Application::parseOptions(const QStringList &options)
  479. {
  480. QStringListIterator it(options);
  481. // skip file name;
  482. if (it.hasNext())
  483. it.next();
  484. //parse options; if help or bad option exit
  485. while (it.hasNext()) {
  486. QString option = it.next();
  487. if (option == QLatin1String("--help") || option == QLatin1String("-h")) {
  488. setHelp();
  489. break;
  490. } else if (option == QLatin1String("--quit") || option == QLatin1String("-q")) {
  491. _quitInstance = true;
  492. } else if (option == QLatin1String("--logwindow") || option == QLatin1String("-l")) {
  493. _showLogWindow = true;
  494. } else if (option == QLatin1String("--logfile")) {
  495. if (it.hasNext() && !it.peekNext().startsWith(QLatin1String("--"))) {
  496. _logFile = it.next();
  497. } else {
  498. showHint("Log file not specified");
  499. }
  500. } else if (option == QLatin1String("--logdir")) {
  501. if (it.hasNext() && !it.peekNext().startsWith(QLatin1String("--"))) {
  502. _logDir = it.next();
  503. } else {
  504. showHint("Log dir not specified");
  505. }
  506. } else if (option == QLatin1String("--logexpire")) {
  507. if (it.hasNext() && !it.peekNext().startsWith(QLatin1String("--"))) {
  508. _logExpire = it.next().toInt();
  509. } else {
  510. showHint("Log expiration not specified");
  511. }
  512. } else if (option == QLatin1String("--logflush")) {
  513. _logFlush = true;
  514. } else if (option == QLatin1String("--logdebug")) {
  515. _logDebug = true;
  516. } else if (option == QLatin1String("--confdir")) {
  517. if (it.hasNext() && !it.peekNext().startsWith(QLatin1String("--"))) {
  518. QString confDir = it.next();
  519. if (!ConfigFile::setConfDir(confDir)) {
  520. showHint("Invalid path passed to --confdir");
  521. }
  522. } else {
  523. showHint("Path for confdir not specified");
  524. }
  525. } else if (option == QLatin1String("--debug")) {
  526. _logDebug = true;
  527. _debugMode = true;
  528. } else if (option == QLatin1String("--background")) {
  529. _backgroundMode = true;
  530. } else if (option == QLatin1String("--version") || option == QLatin1String("-v")) {
  531. _versionOnly = true;
  532. } else if (option.endsWith(QStringLiteral(APPLICATION_DOTVIRTUALFILE_SUFFIX))) {
  533. // virtual file, open it after the Folder were created (if the app is not terminated)
  534. QTimer::singleShot(0, this, [this, option] { openVirtualFile(option); });
  535. } else {
  536. showHint("Unrecognized option '" + option.toStdString() + "'");
  537. }
  538. }
  539. }
  540. // Helpers for displaying messages. Note that there is no console on Windows.
  541. #ifdef Q_OS_WIN
  542. // Format as <pre> HTML
  543. static inline void toHtml(QString &t)
  544. {
  545. t.replace(QLatin1Char('&'), QLatin1String("&amp;"));
  546. t.replace(QLatin1Char('<'), QLatin1String("&lt;"));
  547. t.replace(QLatin1Char('>'), QLatin1String("&gt;"));
  548. t.insert(0, QLatin1String("<html><pre>"));
  549. t.append(QLatin1String("</pre></html>"));
  550. }
  551. static void displayHelpText(QString t) // No console on Windows.
  552. {
  553. toHtml(t);
  554. QMessageBox::information(0, Theme::instance()->appNameGUI(), t);
  555. }
  556. #else
  557. static void displayHelpText(const QString &t)
  558. {
  559. std::cout << qUtf8Printable(t);
  560. }
  561. #endif
  562. void Application::showHelp()
  563. {
  564. setHelp();
  565. QString helpText;
  566. QTextStream stream(&helpText);
  567. stream << _theme->appName()
  568. << QLatin1String(" version ")
  569. << _theme->version() << endl;
  570. stream << QLatin1String("File synchronisation desktop utility.") << endl
  571. << endl
  572. << QLatin1String(optionsC);
  573. if (_theme->appName() == QLatin1String("ownCloud"))
  574. stream << endl
  575. << "For more information, see http://www.owncloud.org" << endl
  576. << endl;
  577. displayHelpText(helpText);
  578. }
  579. void Application::showVersion()
  580. {
  581. displayHelpText(Theme::instance()->versionSwitchOutput());
  582. }
  583. void Application::showHint(std::string errorHint)
  584. {
  585. static QString binName = QFileInfo(QCoreApplication::applicationFilePath()).fileName();
  586. std::cerr << errorHint << std::endl;
  587. std::cerr << "Try '" << binName.toStdString() << " --help' for more information" << std::endl;
  588. std::exit(1);
  589. }
  590. bool Application::debugMode()
  591. {
  592. return _debugMode;
  593. }
  594. bool Application::backgroundMode() const
  595. {
  596. return _backgroundMode;
  597. }
  598. void Application::setHelp()
  599. {
  600. _helpOnly = true;
  601. }
  602. QString substLang(const QString &lang)
  603. {
  604. // Map the more appropriate script codes
  605. // to country codes as used by Qt and
  606. // transifex translation conventions.
  607. // Simplified Chinese
  608. if (lang == QLatin1String("zh_Hans"))
  609. return QLatin1String("zh_CN");
  610. // Traditional Chinese
  611. if (lang == QLatin1String("zh_Hant"))
  612. return QLatin1String("zh_TW");
  613. return lang;
  614. }
  615. void Application::setupTranslations()
  616. {
  617. QStringList uiLanguages;
  618. // uiLanguages crashes on Windows with 4.8.0 release builds
  619. #if (QT_VERSION >= 0x040801) || (QT_VERSION >= 0x040800 && !defined(Q_OS_WIN))
  620. uiLanguages = QLocale::system().uiLanguages();
  621. #else
  622. // older versions need to fall back to the systems locale
  623. uiLanguages << QLocale::system().name();
  624. #endif
  625. QString enforcedLocale = Theme::instance()->enforcedLocale();
  626. if (!enforcedLocale.isEmpty())
  627. uiLanguages.prepend(enforcedLocale);
  628. auto *translator = new QTranslator(this);
  629. auto *qtTranslator = new QTranslator(this);
  630. auto *qtkeychainTranslator = new QTranslator(this);
  631. for (QString lang : qAsConst(uiLanguages)) {
  632. lang.replace(QLatin1Char('-'), QLatin1Char('_')); // work around QTBUG-25973
  633. lang = substLang(lang);
  634. const QString trPath = applicationTrPath();
  635. const QString trFile = QLatin1String("client_") + lang;
  636. if (translator->load(trFile, trPath) || lang.startsWith(QLatin1String("en"))) {
  637. // Permissive approach: Qt and keychain translations
  638. // may be missing, but Qt translations must be there in order
  639. // for us to accept the language. Otherwise, we try with the next.
  640. // "en" is an exception as it is the default language and may not
  641. // have a translation file provided.
  642. qCInfo(lcApplication) << "Using" << lang << "translation";
  643. setProperty("ui_lang", lang);
  644. const QString qtTrPath = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
  645. const QString qtTrFile = QLatin1String("qt_") + lang;
  646. const QString qtBaseTrFile = QLatin1String("qtbase_") + lang;
  647. if (!qtTranslator->load(qtTrFile, qtTrPath)) {
  648. if (!qtTranslator->load(qtTrFile, trPath)) {
  649. if (!qtTranslator->load(qtBaseTrFile, qtTrPath)) {
  650. qtTranslator->load(qtBaseTrFile, trPath);
  651. }
  652. }
  653. }
  654. const QString qtkeychainTrFile = QLatin1String("qtkeychain_") + lang;
  655. if (!qtkeychainTranslator->load(qtkeychainTrFile, qtTrPath)) {
  656. qtkeychainTranslator->load(qtkeychainTrFile, trPath);
  657. }
  658. if (!translator->isEmpty())
  659. installTranslator(translator);
  660. if (!qtTranslator->isEmpty())
  661. installTranslator(qtTranslator);
  662. if (!qtkeychainTranslator->isEmpty())
  663. installTranslator(qtkeychainTranslator);
  664. break;
  665. }
  666. if (property("ui_lang").isNull())
  667. setProperty("ui_lang", "C");
  668. }
  669. }
  670. bool Application::giveHelp()
  671. {
  672. return _helpOnly;
  673. }
  674. bool Application::versionOnly()
  675. {
  676. return _versionOnly;
  677. }
  678. void Application::showMainDialog()
  679. {
  680. _gui->slotOpenMainDialog();
  681. }
  682. void Application::slotGuiIsShowingSettings()
  683. {
  684. emit isShowingSettingsDialog();
  685. }
  686. void Application::openVirtualFile(const QString &filename)
  687. {
  688. QString virtualFileExt = QStringLiteral(APPLICATION_DOTVIRTUALFILE_SUFFIX);
  689. if (!filename.endsWith(virtualFileExt)) {
  690. qWarning(lcApplication) << "Can only handle file ending in .owncloud. Unable to open" << filename;
  691. return;
  692. }
  693. auto folder = FolderMan::instance()->folderForPath(filename);
  694. if (!folder) {
  695. qWarning(lcApplication) << "Can't find sync folder for" << filename;
  696. // TODO: show a QMessageBox for errors
  697. return;
  698. }
  699. QString relativePath = QDir::cleanPath(filename).mid(folder->cleanPath().length() + 1);
  700. folder->implicitlyHydrateFile(relativePath);
  701. QString normalName = filename.left(filename.size() - virtualFileExt.size());
  702. auto con = QSharedPointer<QMetaObject::Connection>::create();
  703. *con = connect(folder, &Folder::syncFinished, folder, [folder, con, normalName] {
  704. folder->disconnect(*con);
  705. if (QFile::exists(normalName)) {
  706. QDesktopServices::openUrl(QUrl::fromLocalFile(normalName));
  707. }
  708. });
  709. }
  710. void Application::tryTrayAgain()
  711. {
  712. qCInfo(lcApplication) << "Trying tray icon, tray available:" << QSystemTrayIcon::isSystemTrayAvailable();
  713. _gui->hideAndShowTray();
  714. }
  715. bool Application::event(QEvent *event)
  716. {
  717. #ifdef Q_OS_MAC
  718. if (event->type() == QEvent::FileOpen) {
  719. QFileOpenEvent *openEvent = static_cast<QFileOpenEvent *>(event);
  720. qCDebug(lcApplication) << "QFileOpenEvent" << openEvent->file();
  721. // virtual file, open it after the Folder were created (if the app is not terminated)
  722. QString fn = openEvent->file();
  723. QTimer::singleShot(0, this, [this, fn] { openVirtualFile(fn); });
  724. }
  725. #endif
  726. return SharedTools::QtSingleApplication::event(event);
  727. }
  728. } // namespace OCC