1 // Copyright (c) 2011-2014 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.
5 #if defined(HAVE_CONFIG_H)
6 #include "config/bitcoin-config.h"
9 #include "bitcoingui.h"
11 #include "clientmodel.h"
12 #include "guiconstants.h"
15 #include "networkstyle.h"
16 #include "optionsmodel.h"
17 #include "splashscreen.h"
18 #include "utilitydialog.h"
19 #include "winshutdownmonitor.h"
22 #include "paymentserver.h"
23 #include "walletmodel.h"
28 #include "rpcserver.h"
29 #include "ui_interface.h"
38 #include <boost/filesystem/operations.hpp>
39 #include <boost/thread.hpp>
41 #include <QApplication>
43 #include <QLibraryInfo>
45 #include <QMessageBox>
49 #include <QTranslator>
51 #if defined(QT_STATICPLUGIN)
53 #if QT_VERSION < 0x050000
54 Q_IMPORT_PLUGIN(qcncodecs)
55 Q_IMPORT_PLUGIN(qjpcodecs)
56 Q_IMPORT_PLUGIN(qtwcodecs)
57 Q_IMPORT_PLUGIN(qkrcodecs)
58 Q_IMPORT_PLUGIN(qtaccessiblewidgets)
60 Q_IMPORT_PLUGIN(AccessibleFactory)
61 #if defined(QT_QPA_PLATFORM_XCB)
62 Q_IMPORT_PLUGIN(QXcbIntegrationPlugin);
63 #elif defined(QT_QPA_PLATFORM_WINDOWS)
64 Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin);
65 #elif defined(QT_QPA_PLATFORM_COCOA)
66 Q_IMPORT_PLUGIN(QCocoaIntegrationPlugin);
71 #if QT_VERSION < 0x050000
75 // Declare meta types used for QMetaObject::invokeMethod
76 Q_DECLARE_METATYPE(bool*)
77 Q_DECLARE_METATYPE(CAmount)
79 static void InitMessage(const std::string &message)
81 LogPrintf("init message: %s\n", message);
85 Translate string to current locale using Qt.
87 static std::string Translate(const char* psz)
89 return QCoreApplication::translate("bitcoin-core", psz).toStdString();
92 static QString GetLangTerritory()
95 // Get desired locale (e.g. "de_DE")
96 // 1) System default language
97 QString lang_territory = QLocale::system().name();
98 // 2) Language from QSettings
99 QString lang_territory_qsettings = settings.value("language", "").toString();
100 if(!lang_territory_qsettings.isEmpty())
101 lang_territory = lang_territory_qsettings;
102 // 3) -lang command line argument
103 lang_territory = QString::fromStdString(GetArg("-lang", lang_territory.toStdString()));
104 return lang_territory;
107 /** Set up translations */
108 static void initTranslations(QTranslator &qtTranslatorBase, QTranslator &qtTranslator, QTranslator &translatorBase, QTranslator &translator)
111 // Remove old translators
112 QApplication::removeTranslator(&qtTranslatorBase);
113 QApplication::removeTranslator(&qtTranslator);
114 QApplication::removeTranslator(&translatorBase);
115 QApplication::removeTranslator(&translator);
117 // Get desired locale (e.g. "de_DE")
118 // 1) System default language
119 QString lang_territory = GetLangTerritory();
121 // Convert to "de" only by truncating "_DE"
122 QString lang = lang_territory;
123 lang.truncate(lang_territory.lastIndexOf('_'));
125 // Load language files for configured locale:
126 // - First load the translator for the base language, without territory
127 // - Then load the more specific locale translator
129 // Load e.g. qt_de.qm
130 if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
131 QApplication::installTranslator(&qtTranslatorBase);
133 // Load e.g. qt_de_DE.qm
134 if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
135 QApplication::installTranslator(&qtTranslator);
137 // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc)
138 if (translatorBase.load(lang, ":/translations/"))
139 QApplication::installTranslator(&translatorBase);
141 // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc)
142 if (translator.load(lang_territory, ":/translations/"))
143 QApplication::installTranslator(&translator);
146 /* qDebug() message handler --> debug.log */
147 #if QT_VERSION < 0x050000
148 void DebugMessageHandler(QtMsgType type, const char *msg)
150 const char *category = (type == QtDebugMsg) ? "qt" : NULL;
151 LogPrint(category, "GUI: %s\n", msg);
154 void DebugMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString &msg)
157 const char *category = (type == QtDebugMsg) ? "qt" : NULL;
158 LogPrint(category, "GUI: %s\n", msg.toStdString());
162 /** Class encapsulating Bitcoin Core startup and shutdown.
163 * Allows running startup and shutdown in a different thread from the UI thread.
165 class BitcoinCore: public QObject
169 explicit BitcoinCore();
176 void initializeResult(int retval);
177 void shutdownResult(int retval);
178 void runawayException(const QString &message);
181 boost::thread_group threadGroup;
183 /// Pass fatal exception message to UI thread
184 void handleRunawayException(const std::exception *e);
187 /** Main Bitcoin application object */
188 class BitcoinApplication: public QApplication
192 explicit BitcoinApplication(int &argc, char **argv);
193 ~BitcoinApplication();
196 /// Create payment server
197 void createPaymentServer();
199 /// Create options model
200 void createOptionsModel();
201 /// Create main window
202 void createWindow(const NetworkStyle *networkStyle);
203 /// Create splash screen
204 void createSplashScreen(const NetworkStyle *networkStyle);
206 /// Request core initialization
207 void requestInitialize();
208 /// Request core shutdown
209 void requestShutdown();
211 /// Get process return value
212 int getReturnValue() { return returnValue; }
214 /// Get window identifier of QMainWindow (BitcoinGUI)
215 WId getMainWinId() const;
218 void initializeResult(int retval);
219 void shutdownResult(int retval);
220 /// Handle runaway exceptions. Shows a message box with the problem and quits the program.
221 void handleRunawayException(const QString &message);
224 void requestedInitialize();
225 void requestedShutdown();
227 void splashFinished(QWidget *window);
231 OptionsModel *optionsModel;
232 ClientModel *clientModel;
234 QTimer *pollShutdownTimer;
236 PaymentServer* paymentServer;
237 WalletModel *walletModel;
244 #include "bitcoin.moc"
246 BitcoinCore::BitcoinCore():
251 void BitcoinCore::handleRunawayException(const std::exception *e)
253 PrintExceptionContinue(e, "Runaway exception");
254 emit runawayException(QString::fromStdString(strMiscWarning));
257 void BitcoinCore::initialize()
261 qDebug() << __func__ << ": Running AppInit2 in thread";
262 int rv = AppInit2(threadGroup);
265 /* Start a dummy RPC thread if no RPC thread is active yet
266 * to handle timeouts.
268 StartDummyRPCThread();
270 emit initializeResult(rv);
271 } catch (const std::exception& e) {
272 handleRunawayException(&e);
274 handleRunawayException(NULL);
278 void BitcoinCore::shutdown()
282 qDebug() << __func__ << ": Running Shutdown in thread";
283 threadGroup.interrupt_all();
284 threadGroup.join_all();
286 qDebug() << __func__ << ": Shutdown finished";
287 emit shutdownResult(1);
288 } catch (const std::exception& e) {
289 handleRunawayException(&e);
291 handleRunawayException(NULL);
295 BitcoinApplication::BitcoinApplication(int &argc, char **argv):
296 QApplication(argc, argv),
301 pollShutdownTimer(0),
308 setQuitOnLastWindowClosed(false);
311 BitcoinApplication::~BitcoinApplication()
315 qDebug() << __func__ << ": Stopping thread";
318 qDebug() << __func__ << ": Stopped thread";
324 delete paymentServer;
332 void BitcoinApplication::createPaymentServer()
334 paymentServer = new PaymentServer(this);
338 void BitcoinApplication::createOptionsModel()
340 optionsModel = new OptionsModel();
343 void BitcoinApplication::createWindow(const NetworkStyle *networkStyle)
345 window = new BitcoinGUI(networkStyle, 0);
347 pollShutdownTimer = new QTimer(window);
348 connect(pollShutdownTimer, SIGNAL(timeout()), window, SLOT(detectShutdown()));
349 pollShutdownTimer->start(200);
352 void BitcoinApplication::createSplashScreen(const NetworkStyle *networkStyle)
354 SplashScreen *splash = new SplashScreen(0, networkStyle);
355 // We don't hold a direct pointer to the splash screen after creation, so use
356 // Qt::WA_DeleteOnClose to make sure that the window will be deleted eventually.
357 splash->setAttribute(Qt::WA_DeleteOnClose);
359 connect(this, SIGNAL(splashFinished(QWidget*)), splash, SLOT(slotFinish(QWidget*)));
362 void BitcoinApplication::startThread()
366 coreThread = new QThread(this);
367 BitcoinCore *executor = new BitcoinCore();
368 executor->moveToThread(coreThread);
370 /* communication to and from thread */
371 connect(executor, SIGNAL(initializeResult(int)), this, SLOT(initializeResult(int)));
372 connect(executor, SIGNAL(shutdownResult(int)), this, SLOT(shutdownResult(int)));
373 connect(executor, SIGNAL(runawayException(QString)), this, SLOT(handleRunawayException(QString)));
374 connect(this, SIGNAL(requestedInitialize()), executor, SLOT(initialize()));
375 connect(this, SIGNAL(requestedShutdown()), executor, SLOT(shutdown()));
376 /* make sure executor object is deleted in its own thread */
377 connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater()));
378 connect(this, SIGNAL(stopThread()), coreThread, SLOT(quit()));
383 void BitcoinApplication::requestInitialize()
385 qDebug() << __func__ << ": Requesting initialize";
387 emit requestedInitialize();
390 void BitcoinApplication::requestShutdown()
392 qDebug() << __func__ << ": Requesting shutdown";
395 window->setClientModel(0);
396 pollShutdownTimer->stop();
399 window->removeAllWallets();
406 // Show a simple window indicating shutdown status
407 ShutdownWindow::showShutdownWindow(window);
409 // Request shutdown from core thread
410 emit requestedShutdown();
413 void BitcoinApplication::initializeResult(int retval)
415 qDebug() << __func__ << ": Initialization result: " << retval;
416 // Set exit result: 0 if successful, 1 if failure
417 returnValue = retval ? 0 : 1;
421 PaymentServer::LoadRootCAs();
422 paymentServer->setOptionsModel(optionsModel);
425 clientModel = new ClientModel(optionsModel);
426 window->setClientModel(clientModel);
431 walletModel = new WalletModel(pwalletMain, optionsModel);
433 window->addWallet(BitcoinGUI::DEFAULT_WALLET, walletModel);
434 window->setCurrentWallet(BitcoinGUI::DEFAULT_WALLET);
436 connect(walletModel, SIGNAL(coinsSent(CWallet*,SendCoinsRecipient,QByteArray)),
437 paymentServer, SLOT(fetchPaymentACK(CWallet*,const SendCoinsRecipient&,QByteArray)));
441 // If -min option passed, start window minimized.
442 if(GetBoolArg("-min", false))
444 window->showMinimized();
450 emit splashFinished(window);
453 // Now that initialization/startup is done, process any command-line
454 // bitcoin: URIs or payment requests:
455 connect(paymentServer, SIGNAL(receivedPaymentRequest(SendCoinsRecipient)),
456 window, SLOT(handlePaymentRequest(SendCoinsRecipient)));
457 connect(window, SIGNAL(receivedURI(QString)),
458 paymentServer, SLOT(handleURIOrFile(QString)));
459 connect(paymentServer, SIGNAL(message(QString,QString,unsigned int)),
460 window, SLOT(message(QString,QString,unsigned int)));
461 QTimer::singleShot(100, paymentServer, SLOT(uiReady()));
464 quit(); // Exit main loop
468 void BitcoinApplication::shutdownResult(int retval)
470 qDebug() << __func__ << ": Shutdown result: " << retval;
471 quit(); // Exit main loop after shutdown finished
474 void BitcoinApplication::handleRunawayException(const QString &message)
476 QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. Bitcoin can no longer continue safely and will quit.") + QString("\n\n") + message);
480 WId BitcoinApplication::getMainWinId() const
485 return window->winId();
488 #ifndef BITCOIN_QT_TEST
489 int main(int argc, char *argv[])
493 /// 1. Parse command-line options. These take precedence over anything else.
494 // Command-line options take precedence:
495 ParseParameters(argc, argv);
497 // Do not refer to data directory yet, this can be overridden by Intro::pickDataDirectory
499 /// 2. Basic Qt initialization (not dependent on parameters or configuration)
500 #if QT_VERSION < 0x050000
501 // Internal string conversion is all UTF-8
502 QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
503 QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());
506 Q_INIT_RESOURCE(bitcoin);
507 Q_INIT_RESOURCE(bitcoin_locale);
509 BitcoinApplication app(argc, argv);
510 #if QT_VERSION > 0x050100
511 // Generate high-dpi pixmaps
512 QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
515 QApplication::setAttribute(Qt::AA_DontShowIconsInMenus);
518 // Register meta types used for QMetaObject::invokeMethod
519 qRegisterMetaType< bool* >();
520 // Need to pass name here as CAmount is a typedef (see http://qt-project.org/doc/qt-5/qmetatype.html#qRegisterMetaType)
521 // IMPORTANT if it is no longer a typedef use the normal variant above
522 qRegisterMetaType< CAmount >("CAmount");
524 /// 3. Application identification
525 // must be set before OptionsModel is initialized or translations are loaded,
526 // as it is used to locate QSettings
527 QApplication::setOrganizationName(QAPP_ORG_NAME);
528 QApplication::setOrganizationDomain(QAPP_ORG_DOMAIN);
529 QApplication::setApplicationName(QAPP_APP_NAME_DEFAULT);
530 GUIUtil::SubstituteFonts(GetLangTerritory());
532 /// 4. Initialization of translations, so that intro dialog is in user's language
533 // Now that QSettings are accessible, initialize translations
534 QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
535 initTranslations(qtTranslatorBase, qtTranslator, translatorBase, translator);
536 uiInterface.Translate.connect(Translate);
538 // Show help message immediately after parsing command-line options (for "-lang") and setting locale,
539 // but before showing splash screen.
540 if (mapArgs.count("-?") || mapArgs.count("-help") || mapArgs.count("-version"))
542 HelpMessageDialog help(NULL, mapArgs.count("-version"));
547 /// 5. Now that settings and translations are available, ask user for data directory
548 // User language is set up: pick a data directory
549 Intro::pickDataDirectory();
551 /// 6. Determine availability of data directory and parse bitcoin.conf
552 /// - Do not call GetDataDir(true) before this step finishes
553 if (!boost::filesystem::is_directory(GetDataDir(false)))
555 QMessageBox::critical(0, QObject::tr("Bitcoin Core"),
556 QObject::tr("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"])));
560 ReadConfigFile(mapArgs, mapMultiArgs);
561 } catch (const std::exception& e) {
562 QMessageBox::critical(0, QObject::tr("Bitcoin Core"),
563 QObject::tr("Error: Cannot parse configuration file: %1. Only use key=value syntax.").arg(e.what()));
567 /// 7. Determine network (and switch to network specific options)
568 // - Do not call Params() before this step
569 // - Do this after parsing the configuration file, as the network can be switched there
570 // - QSettings() will use the new application name after this, resulting in network-specific settings
571 // - Needs to be done before createOptionsModel
573 // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
574 if (!SelectParamsFromCommandLine()) {
575 QMessageBox::critical(0, QObject::tr("Bitcoin Core"), QObject::tr("Error: Invalid combination of -regtest and -testnet."));
579 // Parse URIs on command line -- this can affect Params()
580 PaymentServer::ipcParseCommandLine(argc, argv);
583 QScopedPointer<const NetworkStyle> networkStyle(NetworkStyle::instantiate(QString::fromStdString(Params().NetworkIDString())));
584 assert(!networkStyle.isNull());
585 // Allow for separate UI settings for testnets
586 QApplication::setApplicationName(networkStyle->getAppName());
587 // Re-initialize translations after changing application name (language in network-specific settings can be different)
588 initTranslations(qtTranslatorBase, qtTranslator, translatorBase, translator);
591 /// 8. URI IPC sending
592 // - Do this early as we don't want to bother initializing if we are just calling IPC
593 // - Do this *after* setting up the data directory, as the data directory hash is used in the name
595 // - Do this after creating app and setting up translations, so errors are
596 // translated properly.
597 if (PaymentServer::ipcSendCommandLine())
600 // Start up the payment server early, too, so impatient users that click on
601 // bitcoin: links repeatedly have their payment requests routed to this process:
602 app.createPaymentServer();
605 /// 9. Main GUI initialization
606 // Install global event filter that makes sure that long tooltips can be word-wrapped
607 app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));
608 #if QT_VERSION < 0x050000
609 // Install qDebug() message handler to route to debug.log
610 qInstallMsgHandler(DebugMessageHandler);
612 #if defined(Q_OS_WIN)
613 // Install global event filter for processing Windows session related Windows messages (WM_QUERYENDSESSION and WM_ENDSESSION)
614 qApp->installNativeEventFilter(new WinShutdownMonitor());
616 // Install qDebug() message handler to route to debug.log
617 qInstallMessageHandler(DebugMessageHandler);
619 // Load GUI settings from QSettings
620 app.createOptionsModel();
622 // Subscribe to global signals from core
623 uiInterface.InitMessage.connect(InitMessage);
625 if (GetBoolArg("-splash", true) && !GetBoolArg("-min", false))
626 app.createSplashScreen(networkStyle.data());
630 app.createWindow(networkStyle.data());
631 app.requestInitialize();
632 #if defined(Q_OS_WIN) && QT_VERSION >= 0x050000
633 WinShutdownMonitor::registerShutdownBlockReason(QObject::tr("Bitcoin Core didn't yet exit safely..."), (HWND)app.getMainWinId());
636 app.requestShutdown();
638 } catch (const std::exception& e) {
639 PrintExceptionContinue(&e, "Runaway exception");
640 app.handleRunawayException(QString::fromStdString(strMiscWarning));
642 PrintExceptionContinue(NULL, "Runaway exception");
643 app.handleRunawayException(QString::fromStdString(strMiscWarning));
645 return app.getReturnValue();
647 #endif // BITCOIN_QT_TEST