1 // Copyright (c) 2011-2020 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #if defined(HAVE_CONFIG_H)
6 #include <config/bitcoin-config.h>
7 #endif
8 
9 #include <qt/bitcoin.h>
10 #include <qt/bitcoingui.h>
11 
12 #include <chainparams.h>
13 #include <qt/clientmodel.h>
14 #include <qt/guiconstants.h>
15 #include <qt/guiutil.h>
16 #include <qt/intro.h>
17 #include <qt/networkstyle.h>
18 #include <qt/optionsmodel.h>
19 #include <qt/platformstyle.h>
20 #include <qt/splashscreen.h>
21 #include <qt/utilitydialog.h>
22 #include <qt/winshutdownmonitor.h>
23 
24 #ifdef ENABLE_WALLET
25 #include <qt/paymentserver.h>
26 #include <qt/walletcontroller.h>
27 #include <qt/walletmodel.h>
28 #endif // ENABLE_WALLET
29 
30 #include <init.h>
31 #include <interfaces/handler.h>
32 #include <interfaces/node.h>
33 #include <node/context.h>
34 #include <node/ui_interface.h>
35 #include <noui.h>
36 #include <uint256.h>
37 #include <util/system.h>
38 #include <util/threadnames.h>
39 #include <util/translation.h>
40 #include <validation.h>
41 
42 #include <boost/signals2/connection.hpp>
43 #include <memory>
44 
45 #include <QApplication>
46 #include <QDebug>
47 #include <QFontDatabase>
48 #include <QLatin1String>
49 #include <QLibraryInfo>
50 #include <QLocale>
51 #include <QMessageBox>
52 #include <QSettings>
53 #include <QThread>
54 #include <QTimer>
55 #include <QTranslator>
56 
57 #if defined(QT_STATICPLUGIN)
58 #include <QtPlugin>
59 #if defined(QT_QPA_PLATFORM_XCB)
60 Q_IMPORT_PLUGIN(QXcbIntegrationPlugin);
61 #elif defined(QT_QPA_PLATFORM_WINDOWS)
62 Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin);
63 Q_IMPORT_PLUGIN(QWindowsVistaStylePlugin);
64 #elif defined(QT_QPA_PLATFORM_COCOA)
65 Q_IMPORT_PLUGIN(QCocoaIntegrationPlugin);
66 Q_IMPORT_PLUGIN(QMacStylePlugin);
67 #endif
68 #endif
69 
70 // Declare meta types used for QMetaObject::invokeMethod
71 Q_DECLARE_METATYPE(bool*)
Q_DECLARE_METATYPE(CAmount)72 Q_DECLARE_METATYPE(CAmount)
73 Q_DECLARE_METATYPE(SynchronizationState)
74 Q_DECLARE_METATYPE(uint256)
75 
76 static void RegisterMetaTypes()
77 {
78     // Register meta types used for QMetaObject::invokeMethod and Qt::QueuedConnection
79     qRegisterMetaType<bool*>();
80     qRegisterMetaType<SynchronizationState>();
81   #ifdef ENABLE_WALLET
82     qRegisterMetaType<WalletModel*>();
83   #endif
84     // Register typedefs (see https://doc.qt.io/qt-5/qmetatype.html#qRegisterMetaType)
85     // IMPORTANT: if CAmount is no longer a typedef use the normal variant above (see https://doc.qt.io/qt-5/qmetatype.html#qRegisterMetaType-1)
86     qRegisterMetaType<CAmount>("CAmount");
87     qRegisterMetaType<size_t>("size_t");
88 
89     qRegisterMetaType<std::function<void()>>("std::function<void()>");
90     qRegisterMetaType<QMessageBox::Icon>("QMessageBox::Icon");
91     qRegisterMetaType<interfaces::BlockAndHeaderTipInfo>("interfaces::BlockAndHeaderTipInfo");
92 }
93 
GetLangTerritory()94 static QString GetLangTerritory()
95 {
96     QSettings settings;
97     // Get desired locale (e.g. "de_DE")
98     // 1) System default language
99     QString lang_territory = QLocale::system().name();
100     // 2) Language from QSettings
101     QString lang_territory_qsettings = settings.value("language", "").toString();
102     if(!lang_territory_qsettings.isEmpty())
103         lang_territory = lang_territory_qsettings;
104     // 3) -lang command line argument
105     lang_territory = QString::fromStdString(gArgs.GetArg("-lang", lang_territory.toStdString()));
106     return lang_territory;
107 }
108 
109 /** Set up translations */
initTranslations(QTranslator & qtTranslatorBase,QTranslator & qtTranslator,QTranslator & translatorBase,QTranslator & translator)110 static void initTranslations(QTranslator &qtTranslatorBase, QTranslator &qtTranslator, QTranslator &translatorBase, QTranslator &translator)
111 {
112     // Remove old translators
113     QApplication::removeTranslator(&qtTranslatorBase);
114     QApplication::removeTranslator(&qtTranslator);
115     QApplication::removeTranslator(&translatorBase);
116     QApplication::removeTranslator(&translator);
117 
118     // Get desired locale (e.g. "de_DE")
119     // 1) System default language
120     QString lang_territory = GetLangTerritory();
121 
122     // Convert to "de" only by truncating "_DE"
123     QString lang = lang_territory;
124     lang.truncate(lang_territory.lastIndexOf('_'));
125 
126     // Load language files for configured locale:
127     // - First load the translator for the base language, without territory
128     // - Then load the more specific locale translator
129 
130     // Load e.g. qt_de.qm
131     if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
132         QApplication::installTranslator(&qtTranslatorBase);
133 
134     // Load e.g. qt_de_DE.qm
135     if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
136         QApplication::installTranslator(&qtTranslator);
137 
138     // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc)
139     if (translatorBase.load(lang, ":/translations/"))
140         QApplication::installTranslator(&translatorBase);
141 
142     // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc)
143     if (translator.load(lang_territory, ":/translations/"))
144         QApplication::installTranslator(&translator);
145 }
146 
147 /* qDebug() message handler --> debug.log */
DebugMessageHandler(QtMsgType type,const QMessageLogContext & context,const QString & msg)148 void DebugMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString &msg)
149 {
150     Q_UNUSED(context);
151     if (type == QtDebugMsg) {
152         LogPrint(BCLog::QT, "GUI: %s\n", msg.toStdString());
153     } else {
154         LogPrintf("GUI: %s\n", msg.toStdString());
155     }
156 }
157 
BitcoinCore(interfaces::Node & node)158 BitcoinCore::BitcoinCore(interfaces::Node& node) :
159     QObject(), m_node(node)
160 {
161 }
162 
handleRunawayException(const std::exception * e)163 void BitcoinCore::handleRunawayException(const std::exception *e)
164 {
165     PrintExceptionContinue(e, "Runaway exception");
166     Q_EMIT runawayException(QString::fromStdString(m_node.getWarnings().translated));
167 }
168 
initialize()169 void BitcoinCore::initialize()
170 {
171     try
172     {
173         util::ThreadRename("qt-init");
174         qDebug() << __func__ << ": Running initialization in thread";
175         interfaces::BlockAndHeaderTipInfo tip_info;
176         bool rv = m_node.appInitMain(&tip_info);
177         Q_EMIT initializeResult(rv, tip_info);
178     } catch (const std::exception& e) {
179         handleRunawayException(&e);
180     } catch (...) {
181         handleRunawayException(nullptr);
182     }
183 }
184 
shutdown()185 void BitcoinCore::shutdown()
186 {
187     try
188     {
189         qDebug() << __func__ << ": Running Shutdown in thread";
190         m_node.appShutdown();
191         qDebug() << __func__ << ": Shutdown finished";
192         Q_EMIT shutdownResult();
193     } catch (const std::exception& e) {
194         handleRunawayException(&e);
195     } catch (...) {
196         handleRunawayException(nullptr);
197     }
198 }
199 
200 static int qt_argc = 1;
201 static const char* qt_argv = "bitcoin-qt";
202 
BitcoinApplication()203 BitcoinApplication::BitcoinApplication():
204     QApplication(qt_argc, const_cast<char **>(&qt_argv)),
205     coreThread(nullptr),
206     optionsModel(nullptr),
207     clientModel(nullptr),
208     window(nullptr),
209     pollShutdownTimer(nullptr),
210     returnValue(0),
211     platformStyle(nullptr)
212 {
213     // Qt runs setlocale(LC_ALL, "") on initialization.
214     RegisterMetaTypes();
215     setQuitOnLastWindowClosed(false);
216 }
217 
setupPlatformStyle()218 void BitcoinApplication::setupPlatformStyle()
219 {
220     // UI per-platform customization
221     // This must be done inside the BitcoinApplication constructor, or after it, because
222     // PlatformStyle::instantiate requires a QApplication
223     std::string platformName;
224     platformName = gArgs.GetArg("-uiplatform", BitcoinGUI::DEFAULT_UIPLATFORM);
225     platformStyle = PlatformStyle::instantiate(QString::fromStdString(platformName));
226     if (!platformStyle) // Fall back to "other" if specified name not found
227         platformStyle = PlatformStyle::instantiate("other");
228     assert(platformStyle);
229 }
230 
~BitcoinApplication()231 BitcoinApplication::~BitcoinApplication()
232 {
233     if(coreThread)
234     {
235         qDebug() << __func__ << ": Stopping thread";
236         coreThread->quit();
237         coreThread->wait();
238         qDebug() << __func__ << ": Stopped thread";
239     }
240 
241     delete window;
242     window = nullptr;
243     delete platformStyle;
244     platformStyle = nullptr;
245 }
246 
247 #ifdef ENABLE_WALLET
createPaymentServer()248 void BitcoinApplication::createPaymentServer()
249 {
250     paymentServer = new PaymentServer(this);
251 }
252 #endif
253 
createOptionsModel(bool resetSettings)254 void BitcoinApplication::createOptionsModel(bool resetSettings)
255 {
256     optionsModel = new OptionsModel(this, resetSettings);
257 }
258 
createWindow(const NetworkStyle * networkStyle)259 void BitcoinApplication::createWindow(const NetworkStyle *networkStyle)
260 {
261     window = new BitcoinGUI(node(), platformStyle, networkStyle, nullptr);
262 
263     pollShutdownTimer = new QTimer(window);
264     connect(pollShutdownTimer, &QTimer::timeout, window, &BitcoinGUI::detectShutdown);
265 }
266 
createSplashScreen(const NetworkStyle * networkStyle)267 void BitcoinApplication::createSplashScreen(const NetworkStyle *networkStyle)
268 {
269     assert(!m_splash);
270     m_splash = new SplashScreen(networkStyle);
271     // We don't hold a direct pointer to the splash screen after creation, but the splash
272     // screen will take care of deleting itself when finish() happens.
273     m_splash->show();
274     connect(this, &BitcoinApplication::requestedInitialize, m_splash, &SplashScreen::handleLoadWallet);
275     connect(this, &BitcoinApplication::splashFinished, m_splash, &SplashScreen::finish);
276     connect(this, &BitcoinApplication::requestedShutdown, m_splash, &QWidget::close);
277 }
278 
setNode(interfaces::Node & node)279 void BitcoinApplication::setNode(interfaces::Node& node)
280 {
281     assert(!m_node);
282     m_node = &node;
283     if (optionsModel) optionsModel->setNode(*m_node);
284     if (m_splash) m_splash->setNode(*m_node);
285 }
286 
baseInitialize()287 bool BitcoinApplication::baseInitialize()
288 {
289     return node().baseInitialize();
290 }
291 
startThread()292 void BitcoinApplication::startThread()
293 {
294     if(coreThread)
295         return;
296     coreThread = new QThread(this);
297     BitcoinCore *executor = new BitcoinCore(node());
298     executor->moveToThread(coreThread);
299 
300     /*  communication to and from thread */
301     connect(executor, &BitcoinCore::initializeResult, this, &BitcoinApplication::initializeResult);
302     connect(executor, &BitcoinCore::shutdownResult, this, &BitcoinApplication::shutdownResult);
303     connect(executor, &BitcoinCore::runawayException, this, &BitcoinApplication::handleRunawayException);
304     connect(this, &BitcoinApplication::requestedInitialize, executor, &BitcoinCore::initialize);
305     connect(this, &BitcoinApplication::requestedShutdown, executor, &BitcoinCore::shutdown);
306     /*  make sure executor object is deleted in its own thread */
307     connect(coreThread, &QThread::finished, executor, &QObject::deleteLater);
308 
309     coreThread->start();
310 }
311 
parameterSetup()312 void BitcoinApplication::parameterSetup()
313 {
314     // Default printtoconsole to false for the GUI. GUI programs should not
315     // print to the console unnecessarily.
316     gArgs.SoftSetBoolArg("-printtoconsole", false);
317 
318     InitLogging(gArgs);
319     InitParameterInteraction(gArgs);
320 }
321 
InitPruneSetting(int64_t prune_MiB)322 void BitcoinApplication::InitPruneSetting(int64_t prune_MiB)
323 {
324     optionsModel->SetPruneTargetGB(PruneMiBtoGB(prune_MiB), true);
325 }
326 
requestInitialize()327 void BitcoinApplication::requestInitialize()
328 {
329     qDebug() << __func__ << ": Requesting initialize";
330     startThread();
331     Q_EMIT requestedInitialize();
332 }
333 
requestShutdown()334 void BitcoinApplication::requestShutdown()
335 {
336     // Show a simple window indicating shutdown status
337     // Do this first as some of the steps may take some time below,
338     // for example the RPC console may still be executing a command.
339     shutdownWindow.reset(ShutdownWindow::showShutdownWindow(window));
340 
341     qDebug() << __func__ << ": Requesting shutdown";
342     startThread();
343     window->hide();
344     // Must disconnect node signals otherwise current thread can deadlock since
345     // no event loop is running.
346     window->unsubscribeFromCoreSignals();
347     // Request node shutdown, which can interrupt long operations, like
348     // rescanning a wallet.
349     node().startShutdown();
350     // Unsetting the client model can cause the current thread to wait for node
351     // to complete an operation, like wait for a RPC execution to complete.
352     window->setClientModel(nullptr);
353     pollShutdownTimer->stop();
354 
355     delete clientModel;
356     clientModel = nullptr;
357 
358     // Request shutdown from core thread
359     Q_EMIT requestedShutdown();
360 }
361 
initializeResult(bool success,interfaces::BlockAndHeaderTipInfo tip_info)362 void BitcoinApplication::initializeResult(bool success, interfaces::BlockAndHeaderTipInfo tip_info)
363 {
364     qDebug() << __func__ << ": Initialization result: " << success;
365     // Set exit result.
366     returnValue = success ? EXIT_SUCCESS : EXIT_FAILURE;
367     if(success)
368     {
369         // Log this only after AppInitMain finishes, as then logging setup is guaranteed complete
370         qInfo() << "Platform customization:" << platformStyle->getName();
371         clientModel = new ClientModel(node(), optionsModel);
372         window->setClientModel(clientModel, &tip_info);
373 #ifdef ENABLE_WALLET
374         if (WalletModel::isWalletEnabled()) {
375             m_wallet_controller = new WalletController(*clientModel, platformStyle, this);
376             window->setWalletController(m_wallet_controller);
377             if (paymentServer) {
378                 paymentServer->setOptionsModel(optionsModel);
379             }
380         }
381 #endif // ENABLE_WALLET
382 
383         // If -min option passed, start window minimized (iconified) or minimized to tray
384         if (!gArgs.GetBoolArg("-min", false)) {
385             window->show();
386         } else if (clientModel->getOptionsModel()->getMinimizeToTray() && window->hasTrayIcon()) {
387             // do nothing as the window is managed by the tray icon
388         } else {
389             window->showMinimized();
390         }
391         Q_EMIT splashFinished();
392         Q_EMIT windowShown(window);
393 
394 #ifdef ENABLE_WALLET
395         // Now that initialization/startup is done, process any command-line
396         // bitcoin: URIs or payment requests:
397         if (paymentServer) {
398             connect(paymentServer, &PaymentServer::receivedPaymentRequest, window, &BitcoinGUI::handlePaymentRequest);
399             connect(window, &BitcoinGUI::receivedURI, paymentServer, &PaymentServer::handleURIOrFile);
400             connect(paymentServer, &PaymentServer::message, [this](const QString& title, const QString& message, unsigned int style) {
401                 window->message(title, message, style);
402             });
403             QTimer::singleShot(100, paymentServer, &PaymentServer::uiReady);
404         }
405 #endif
406         pollShutdownTimer->start(200);
407     } else {
408         Q_EMIT splashFinished(); // Make sure splash screen doesn't stick around during shutdown
409         quit(); // Exit first main loop invocation
410     }
411 }
412 
shutdownResult()413 void BitcoinApplication::shutdownResult()
414 {
415     quit(); // Exit second main loop invocation after shutdown finished
416 }
417 
handleRunawayException(const QString & message)418 void BitcoinApplication::handleRunawayException(const QString &message)
419 {
420     QMessageBox::critical(
421         nullptr, tr("Runaway exception"),
422         tr("A fatal error occurred. %1 can no longer continue safely and will quit.").arg(PACKAGE_NAME) +
423         QLatin1String("<br><br>") + GUIUtil::MakeHtmlLink(message, PACKAGE_BUGREPORT));
424     ::exit(EXIT_FAILURE);
425 }
426 
handleNonFatalException(const QString & message)427 void BitcoinApplication::handleNonFatalException(const QString& message)
428 {
429     assert(QThread::currentThread() == thread());
430     QMessageBox::warning(
431         nullptr, tr("Internal error"),
432         tr("An internal error occurred. %1 will attempt to continue safely. This is "
433            "an unexpected bug which can be reported as described below.").arg(PACKAGE_NAME) +
434         QLatin1String("<br><br>") + GUIUtil::MakeHtmlLink(message, PACKAGE_BUGREPORT));
435 }
436 
getMainWinId() const437 WId BitcoinApplication::getMainWinId() const
438 {
439     if (!window)
440         return 0;
441 
442     return window->winId();
443 }
444 
SetupUIArgs(ArgsManager & argsman)445 static void SetupUIArgs(ArgsManager& argsman)
446 {
447     argsman.AddArg("-choosedatadir", strprintf("Choose data directory on startup (default: %u)", DEFAULT_CHOOSE_DATADIR), ArgsManager::ALLOW_ANY, OptionsCategory::GUI);
448     argsman.AddArg("-lang=<lang>", "Set language, for example \"de_DE\" (default: system locale)", ArgsManager::ALLOW_ANY, OptionsCategory::GUI);
449     argsman.AddArg("-min", "Start minimized", ArgsManager::ALLOW_ANY, OptionsCategory::GUI);
450     argsman.AddArg("-resetguisettings", "Reset all settings changed in the GUI", ArgsManager::ALLOW_ANY, OptionsCategory::GUI);
451     argsman.AddArg("-splash", strprintf("Show splash screen on startup (default: %u)", DEFAULT_SPLASHSCREEN), ArgsManager::ALLOW_ANY, OptionsCategory::GUI);
452     argsman.AddArg("-uiplatform", strprintf("Select platform to customize UI for (one of windows, macosx, other; default: %s)", BitcoinGUI::DEFAULT_UIPLATFORM), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::GUI);
453 }
454 
GuiMain(int argc,char * argv[])455 int GuiMain(int argc, char* argv[])
456 {
457 #ifdef WIN32
458     util::WinCmdLineArgs winArgs;
459     std::tie(argc, argv) = winArgs.get();
460 #endif
461     SetupEnvironment();
462     util::ThreadSetInternalName("main");
463 
464     NodeContext node_context;
465     std::unique_ptr<interfaces::Node> node = interfaces::MakeNode(&node_context);
466 
467     // Subscribe to global signals from core
468     boost::signals2::scoped_connection handler_message_box = ::uiInterface.ThreadSafeMessageBox_connect(noui_ThreadSafeMessageBox);
469     boost::signals2::scoped_connection handler_question = ::uiInterface.ThreadSafeQuestion_connect(noui_ThreadSafeQuestion);
470     boost::signals2::scoped_connection handler_init_message = ::uiInterface.InitMessage_connect(noui_InitMessage);
471 
472     // Do not refer to data directory yet, this can be overridden by Intro::pickDataDirectory
473 
474     /// 1. Basic Qt initialization (not dependent on parameters or configuration)
475     Q_INIT_RESOURCE(bitcoin);
476     Q_INIT_RESOURCE(bitcoin_locale);
477 
478     // Generate high-dpi pixmaps
479     QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
480     QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
481 
482 #if defined(QT_QPA_PLATFORM_ANDROID)
483     QApplication::setAttribute(Qt::AA_DontUseNativeMenuBar);
484     QApplication::setAttribute(Qt::AA_DontCreateNativeWidgetSiblings);
485     QApplication::setAttribute(Qt::AA_DontUseNativeDialogs);
486 #endif
487 
488     BitcoinApplication app;
489     QFontDatabase::addApplicationFont(":/fonts/monospace");
490 
491     /// 2. Parse command-line options. We do this after qt in order to show an error if there are problems parsing these
492     // Command-line options take precedence:
493     node_context.args = &gArgs;
494     SetupServerArgs(gArgs);
495     SetupUIArgs(gArgs);
496     std::string error;
497     if (!gArgs.ParseParameters(argc, argv, error)) {
498         InitError(strprintf(Untranslated("Error parsing command line arguments: %s\n"), error));
499         // Create a message box, because the gui has neither been created nor has subscribed to core signals
500         QMessageBox::critical(nullptr, PACKAGE_NAME,
501             // message can not be translated because translations have not been initialized
502             QString::fromStdString("Error parsing command line arguments: %1.").arg(QString::fromStdString(error)));
503         return EXIT_FAILURE;
504     }
505 
506     // Now that the QApplication is setup and we have parsed our parameters, we can set the platform style
507     app.setupPlatformStyle();
508 
509     /// 3. Application identification
510     // must be set before OptionsModel is initialized or translations are loaded,
511     // as it is used to locate QSettings
512     QApplication::setOrganizationName(QAPP_ORG_NAME);
513     QApplication::setOrganizationDomain(QAPP_ORG_DOMAIN);
514     QApplication::setApplicationName(QAPP_APP_NAME_DEFAULT);
515 
516     /// 4. Initialization of translations, so that intro dialog is in user's language
517     // Now that QSettings are accessible, initialize translations
518     QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
519     initTranslations(qtTranslatorBase, qtTranslator, translatorBase, translator);
520 
521     // Show help message immediately after parsing command-line options (for "-lang") and setting locale,
522     // but before showing splash screen.
523     if (HelpRequested(gArgs) || gArgs.IsArgSet("-version")) {
524         HelpMessageDialog help(nullptr, gArgs.IsArgSet("-version"));
525         help.showOrPrint();
526         return EXIT_SUCCESS;
527     }
528 
529     // Install global event filter that makes sure that long tooltips can be word-wrapped
530     app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));
531 
532     /// 5. Now that settings and translations are available, ask user for data directory
533     // User language is set up: pick a data directory
534     bool did_show_intro = false;
535     int64_t prune_MiB = 0;  // Intro dialog prune configuration
536     // Gracefully exit if the user cancels
537     if (!Intro::showIfNeeded(did_show_intro, prune_MiB)) return EXIT_SUCCESS;
538 
539     /// 6. Determine availability of data directory and parse bitcoin.conf
540     /// - Do not call gArgs.GetDataDirNet() before this step finishes
541     if (!CheckDataDirOption()) {
542         InitError(strprintf(Untranslated("Specified data directory \"%s\" does not exist.\n"), gArgs.GetArg("-datadir", "")));
543         QMessageBox::critical(nullptr, PACKAGE_NAME,
544             QObject::tr("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(gArgs.GetArg("-datadir", ""))));
545         return EXIT_FAILURE;
546     }
547     if (!gArgs.ReadConfigFiles(error, true)) {
548         InitError(strprintf(Untranslated("Error reading configuration file: %s\n"), error));
549         QMessageBox::critical(nullptr, PACKAGE_NAME,
550             QObject::tr("Error: Cannot parse configuration file: %1.").arg(QString::fromStdString(error)));
551         return EXIT_FAILURE;
552     }
553 
554     /// 7. Determine network (and switch to network specific options)
555     // - Do not call Params() before this step
556     // - Do this after parsing the configuration file, as the network can be switched there
557     // - QSettings() will use the new application name after this, resulting in network-specific settings
558     // - Needs to be done before createOptionsModel
559 
560     // Check for chain settings (Params() calls are only valid after this clause)
561     try {
562         SelectParams(gArgs.GetChainName());
563     } catch(std::exception &e) {
564         InitError(Untranslated(strprintf("%s\n", e.what())));
565         QMessageBox::critical(nullptr, PACKAGE_NAME, QObject::tr("Error: %1").arg(e.what()));
566         return EXIT_FAILURE;
567     }
568 #ifdef ENABLE_WALLET
569     // Parse URIs on command line -- this can affect Params()
570     PaymentServer::ipcParseCommandLine(argc, argv);
571 #endif
572     if (!gArgs.InitSettings(error)) {
573         InitError(Untranslated(error));
574         QMessageBox::critical(nullptr, PACKAGE_NAME, QObject::tr("Error initializing settings: %1").arg(QString::fromStdString(error)));
575         return EXIT_FAILURE;
576     }
577 
578     QScopedPointer<const NetworkStyle> networkStyle(NetworkStyle::instantiate(Params().NetworkIDString()));
579     assert(!networkStyle.isNull());
580     // Allow for separate UI settings for testnets
581     QApplication::setApplicationName(networkStyle->getAppName());
582     // Re-initialize translations after changing application name (language in network-specific settings can be different)
583     initTranslations(qtTranslatorBase, qtTranslator, translatorBase, translator);
584 
585 #ifdef ENABLE_WALLET
586     /// 8. URI IPC sending
587     // - Do this early as we don't want to bother initializing if we are just calling IPC
588     // - Do this *after* setting up the data directory, as the data directory hash is used in the name
589     // of the server.
590     // - Do this after creating app and setting up translations, so errors are
591     // translated properly.
592     if (PaymentServer::ipcSendCommandLine())
593         exit(EXIT_SUCCESS);
594 
595     // Start up the payment server early, too, so impatient users that click on
596     // bitcoin: links repeatedly have their payment requests routed to this process:
597     if (WalletModel::isWalletEnabled()) {
598         app.createPaymentServer();
599     }
600 #endif // ENABLE_WALLET
601 
602     /// 9. Main GUI initialization
603     // Install global event filter that makes sure that out-of-focus labels do not contain text cursor.
604     app.installEventFilter(new GUIUtil::LabelOutOfFocusEventFilter(&app));
605 #if defined(Q_OS_WIN)
606     // Install global event filter for processing Windows session related Windows messages (WM_QUERYENDSESSION and WM_ENDSESSION)
607     qApp->installNativeEventFilter(new WinShutdownMonitor());
608 #endif
609     // Install qDebug() message handler to route to debug.log
610     qInstallMessageHandler(DebugMessageHandler);
611     // Allow parameter interaction before we create the options model
612     app.parameterSetup();
613     GUIUtil::LogQtInfo();
614     // Load GUI settings from QSettings
615     app.createOptionsModel(gArgs.GetBoolArg("-resetguisettings", false));
616 
617     if (did_show_intro) {
618         // Store intro dialog settings other than datadir (network specific)
619         app.InitPruneSetting(prune_MiB);
620     }
621 
622     if (gArgs.GetBoolArg("-splash", DEFAULT_SPLASHSCREEN) && !gArgs.GetBoolArg("-min", false))
623         app.createSplashScreen(networkStyle.data());
624 
625     app.setNode(*node);
626 
627     int rv = EXIT_SUCCESS;
628     try
629     {
630         app.createWindow(networkStyle.data());
631         // Perform base initialization before spinning up initialization/shutdown thread
632         // This is acceptable because this function only contains steps that are quick to execute,
633         // so the GUI thread won't be held up.
634         if (app.baseInitialize()) {
635             app.requestInitialize();
636 #if defined(Q_OS_WIN)
637             WinShutdownMonitor::registerShutdownBlockReason(QObject::tr("%1 didn't yet exit safely…").arg(PACKAGE_NAME), (HWND)app.getMainWinId());
638 #endif
639             app.exec();
640             app.requestShutdown();
641             app.exec();
642             rv = app.getReturnValue();
643         } else {
644             // A dialog with detailed error will have been shown by InitError()
645             rv = EXIT_FAILURE;
646         }
647     } catch (const std::exception& e) {
648         PrintExceptionContinue(&e, "Runaway exception");
649         app.handleRunawayException(QString::fromStdString(app.node().getWarnings().translated));
650     } catch (...) {
651         PrintExceptionContinue(nullptr, "Runaway exception");
652         app.handleRunawayException(QString::fromStdString(app.node().getWarnings().translated));
653     }
654     return rv;
655 }
656