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 "rpc/server.h"
29 #include "scheduler.h"
30 #include "ui_interface.h"
34 #include "wallet/wallet.h"
39 #include <boost/filesystem/operations.hpp>
40 #include <boost/thread.hpp>
42 #include <QApplication>
44 #include <QLibraryInfo>
46 #include <QMessageBox>
50 #include <QTranslator>
51 #include <QSslConfiguration>
53 #if defined(QT_STATICPLUGIN)
55 #if QT_VERSION < 0x050000
56 Q_IMPORT_PLUGIN(qcncodecs)
57 Q_IMPORT_PLUGIN(qjpcodecs)
58 Q_IMPORT_PLUGIN(qtwcodecs)
59 Q_IMPORT_PLUGIN(qkrcodecs)
60 Q_IMPORT_PLUGIN(qtaccessiblewidgets)
62 #if QT_VERSION < 0x050400
63 Q_IMPORT_PLUGIN(AccessibleFactory)
65 #if defined(QT_QPA_PLATFORM_XCB)
66 Q_IMPORT_PLUGIN(QXcbIntegrationPlugin);
67 #elif defined(QT_QPA_PLATFORM_WINDOWS)
68 Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin);
69 #elif defined(QT_QPA_PLATFORM_COCOA)
70 Q_IMPORT_PLUGIN(QCocoaIntegrationPlugin);
75 #if QT_VERSION < 0x050000
79 // Declare meta types used for QMetaObject::invokeMethod
80 Q_DECLARE_METATYPE(bool*)
81 Q_DECLARE_METATYPE(CAmount)
83 static void InitMessage(const std::string &message)
85 LogPrintf("init message: %s\n", message);
89 Translate string to current locale using Qt.
91 static std::string Translate(const char* psz)
93 return QCoreApplication::translate("bitcoin-core", psz).toStdString();
96 static QString GetLangTerritory()
99 // Get desired locale (e.g. "de_DE")
100 // 1) System default language
101 QString lang_territory = QLocale::system().name();
102 // 2) Language from QSettings
103 QString lang_territory_qsettings = settings.value("language", "").toString();
104 if(!lang_territory_qsettings.isEmpty())
105 lang_territory = lang_territory_qsettings;
106 // 3) -lang command line argument
107 lang_territory = QString::fromStdString(GetArg("-lang", lang_territory.toStdString()));
108 return lang_territory;
111 /** Set up translations */
112 static void initTranslations(QTranslator &qtTranslatorBase, QTranslator &qtTranslator, QTranslator &translatorBase, QTranslator &translator)
114 // Remove old translators
115 QApplication::removeTranslator(&qtTranslatorBase);
116 QApplication::removeTranslator(&qtTranslator);
117 QApplication::removeTranslator(&translatorBase);
118 QApplication::removeTranslator(&translator);
120 // Get desired locale (e.g. "de_DE")
121 // 1) System default language
122 QString lang_territory = GetLangTerritory();
124 // Convert to "de" only by truncating "_DE"
125 QString lang = lang_territory;
126 lang.truncate(lang_territory.lastIndexOf('_'));
128 // Load language files for configured locale:
129 // - First load the translator for the base language, without territory
130 // - Then load the more specific locale translator
132 // Load e.g. qt_de.qm
133 if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
134 QApplication::installTranslator(&qtTranslatorBase);
136 // Load e.g. qt_de_DE.qm
137 if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
138 QApplication::installTranslator(&qtTranslator);
140 // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc)
141 if (translatorBase.load(lang, ":/translations/"))
142 QApplication::installTranslator(&translatorBase);
144 // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc)
145 if (translator.load(lang_territory, ":/translations/"))
146 QApplication::installTranslator(&translator);
149 /* qDebug() message handler --> debug.log */
150 #if QT_VERSION < 0x050000
151 void DebugMessageHandler(QtMsgType type, const char *msg)
153 const char *category = (type == QtDebugMsg) ? "qt" : NULL;
154 LogPrint(category, "GUI: %s\n", msg);
157 void DebugMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString &msg)
160 const char *category = (type == QtDebugMsg) ? "qt" : NULL;
161 LogPrint(category, "GUI: %s\n", msg.toStdString());
165 /** Class encapsulating Bitcoin Core startup and shutdown.
166 * Allows running startup and shutdown in a different thread from the UI thread.
168 class BitcoinCore: public QObject
172 explicit BitcoinCore();
179 void initializeResult(int retval);
180 void shutdownResult(int retval);
181 void runawayException(const QString &message);
184 boost::thread_group threadGroup;
185 CScheduler scheduler;
187 /// Pass fatal exception message to UI thread
188 void handleRunawayException(const std::exception *e);
191 /** Main Bitcoin application object */
192 class BitcoinApplication: public QApplication
196 explicit BitcoinApplication(int &argc, char **argv);
197 ~BitcoinApplication();
200 /// Create payment server
201 void createPaymentServer();
203 /// Create options model
204 void createOptionsModel();
205 /// Create main window
206 void createWindow(const NetworkStyle *networkStyle);
207 /// Create splash screen
208 void createSplashScreen(const NetworkStyle *networkStyle);
210 /// Request core initialization
211 void requestInitialize();
212 /// Request core shutdown
213 void requestShutdown();
215 /// Get process return value
216 int getReturnValue() { return returnValue; }
218 /// Get window identifier of QMainWindow (BitcoinGUI)
219 WId getMainWinId() const;
222 void initializeResult(int retval);
223 void shutdownResult(int retval);
224 /// Handle runaway exceptions. Shows a message box with the problem and quits the program.
225 void handleRunawayException(const QString &message);
228 void requestedInitialize();
229 void requestedShutdown();
231 void splashFinished(QWidget *window);
235 OptionsModel *optionsModel;
236 ClientModel *clientModel;
238 QTimer *pollShutdownTimer;
240 PaymentServer* paymentServer;
241 WalletModel *walletModel;
248 #include "bitcoin.moc"
250 BitcoinCore::BitcoinCore():
255 void BitcoinCore::handleRunawayException(const std::exception *e)
257 PrintExceptionContinue(e, "Runaway exception");
258 Q_EMIT runawayException(QString::fromStdString(strMiscWarning));
261 void BitcoinCore::initialize()
265 qDebug() << __func__ << ": Running AppInit2 in thread";
266 int rv = AppInit2(threadGroup, scheduler);
269 /* Start a dummy RPC thread if no RPC thread is active yet
270 * to handle timeouts.
272 StartDummyRPCThread();
274 Q_EMIT initializeResult(rv);
275 } catch (const std::exception& e) {
276 handleRunawayException(&e);
278 handleRunawayException(NULL);
282 void BitcoinCore::shutdown()
286 qDebug() << __func__ << ": Running Shutdown in thread";
287 threadGroup.interrupt_all();
288 threadGroup.join_all();
290 qDebug() << __func__ << ": Shutdown finished";
291 Q_EMIT shutdownResult(1);
292 } catch (const std::exception& e) {
293 handleRunawayException(&e);
295 handleRunawayException(NULL);
299 BitcoinApplication::BitcoinApplication(int &argc, char **argv):
300 QApplication(argc, argv),
305 pollShutdownTimer(0),
312 setQuitOnLastWindowClosed(false);
315 BitcoinApplication::~BitcoinApplication()
319 qDebug() << __func__ << ": Stopping thread";
322 qDebug() << __func__ << ": Stopped thread";
328 delete paymentServer;
336 void BitcoinApplication::createPaymentServer()
338 paymentServer = new PaymentServer(this);
342 void BitcoinApplication::createOptionsModel()
344 optionsModel = new OptionsModel();
347 void BitcoinApplication::createWindow(const NetworkStyle *networkStyle)
349 window = new BitcoinGUI(networkStyle, 0);
351 pollShutdownTimer = new QTimer(window);
352 connect(pollShutdownTimer, SIGNAL(timeout()), window, SLOT(detectShutdown()));
353 pollShutdownTimer->start(200);
356 void BitcoinApplication::createSplashScreen(const NetworkStyle *networkStyle)
358 SplashScreen *splash = new SplashScreen(0, networkStyle);
359 // We don't hold a direct pointer to the splash screen after creation, so use
360 // Qt::WA_DeleteOnClose to make sure that the window will be deleted eventually.
361 splash->setAttribute(Qt::WA_DeleteOnClose);
363 connect(this, SIGNAL(splashFinished(QWidget*)), splash, SLOT(slotFinish(QWidget*)));
366 void BitcoinApplication::startThread()
370 coreThread = new QThread(this);
371 BitcoinCore *executor = new BitcoinCore();
372 executor->moveToThread(coreThread);
374 /* communication to and from thread */
375 connect(executor, SIGNAL(initializeResult(int)), this, SLOT(initializeResult(int)));
376 connect(executor, SIGNAL(shutdownResult(int)), this, SLOT(shutdownResult(int)));
377 connect(executor, SIGNAL(runawayException(QString)), this, SLOT(handleRunawayException(QString)));
378 connect(this, SIGNAL(requestedInitialize()), executor, SLOT(initialize()));
379 connect(this, SIGNAL(requestedShutdown()), executor, SLOT(shutdown()));
380 /* make sure executor object is deleted in its own thread */
381 connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater()));
382 connect(this, SIGNAL(stopThread()), coreThread, SLOT(quit()));
387 void BitcoinApplication::requestInitialize()
389 qDebug() << __func__ << ": Requesting initialize";
391 Q_EMIT requestedInitialize();
394 void BitcoinApplication::requestShutdown()
396 qDebug() << __func__ << ": Requesting shutdown";
399 window->setClientModel(0);
400 pollShutdownTimer->stop();
403 window->removeAllWallets();
410 // Show a simple window indicating shutdown status
411 ShutdownWindow::showShutdownWindow(window);
413 // Request shutdown from core thread
414 Q_EMIT requestedShutdown();
417 void BitcoinApplication::initializeResult(int retval)
419 qDebug() << __func__ << ": Initialization result: " << retval;
420 // Set exit result: 0 if successful, 1 if failure
421 returnValue = retval ? 0 : 1;
425 PaymentServer::LoadRootCAs();
426 paymentServer->setOptionsModel(optionsModel);
429 clientModel = new ClientModel(optionsModel);
430 window->setClientModel(clientModel);
435 walletModel = new WalletModel(pwalletMain, optionsModel);
437 window->addWallet(BitcoinGUI::DEFAULT_WALLET, walletModel);
438 window->setCurrentWallet(BitcoinGUI::DEFAULT_WALLET);
440 connect(walletModel, SIGNAL(coinsSent(CWallet*,SendCoinsRecipient,QByteArray)),
441 paymentServer, SLOT(fetchPaymentACK(CWallet*,const SendCoinsRecipient&,QByteArray)));
445 // If -min option passed, start window minimized.
446 if(GetBoolArg("-min", false))
448 window->showMinimized();
454 Q_EMIT splashFinished(window);
457 // Now that initialization/startup is done, process any command-line
458 // bitcoin: URIs or payment requests:
459 connect(paymentServer, SIGNAL(receivedPaymentRequest(SendCoinsRecipient)),
460 window, SLOT(handlePaymentRequest(SendCoinsRecipient)));
461 connect(window, SIGNAL(receivedURI(QString)),
462 paymentServer, SLOT(handleURIOrFile(QString)));
463 connect(paymentServer, SIGNAL(message(QString,QString,unsigned int)),
464 window, SLOT(message(QString,QString,unsigned int)));
465 QTimer::singleShot(100, paymentServer, SLOT(uiReady()));
468 quit(); // Exit main loop
472 void BitcoinApplication::shutdownResult(int retval)
474 qDebug() << __func__ << ": Shutdown result: " << retval;
475 quit(); // Exit main loop after shutdown finished
478 void BitcoinApplication::handleRunawayException(const QString &message)
480 QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. Bitcoin can no longer continue safely and will quit.") + QString("\n\n") + message);
484 WId BitcoinApplication::getMainWinId() const
489 return window->winId();
492 #ifndef BITCOIN_QT_TEST
493 int main(int argc, char *argv[])
497 /// 1. Parse command-line options. These take precedence over anything else.
498 // Command-line options take precedence:
499 ParseParameters(argc, argv);
501 // Do not refer to data directory yet, this can be overridden by Intro::pickDataDirectory
503 /// 2. Basic Qt initialization (not dependent on parameters or configuration)
504 #if QT_VERSION < 0x050000
505 // Internal string conversion is all UTF-8
506 QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
507 QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());
510 Q_INIT_RESOURCE(bitcoin);
511 Q_INIT_RESOURCE(bitcoin_locale);
513 BitcoinApplication app(argc, argv);
514 #if QT_VERSION > 0x050100
515 // Generate high-dpi pixmaps
516 QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
519 QApplication::setAttribute(Qt::AA_DontShowIconsInMenus);
521 #if QT_VERSION >= 0x050500
522 // Because of the POODLE attack it is recommended to disable SSLv3 (https://disablessl3.com/),
523 // so set SSL protocols to TLS1.0+.
524 QSslConfiguration sslconf = QSslConfiguration::defaultConfiguration();
525 sslconf.setProtocol(QSsl::TlsV1_0OrLater);
526 QSslConfiguration::setDefaultConfiguration(sslconf);
529 // Register meta types used for QMetaObject::invokeMethod
530 qRegisterMetaType< bool* >();
531 // Need to pass name here as CAmount is a typedef (see http://qt-project.org/doc/qt-5/qmetatype.html#qRegisterMetaType)
532 // IMPORTANT if it is no longer a typedef use the normal variant above
533 qRegisterMetaType< CAmount >("CAmount");
535 /// 3. Application identification
536 // must be set before OptionsModel is initialized or translations are loaded,
537 // as it is used to locate QSettings
538 QApplication::setOrganizationName(QAPP_ORG_NAME);
539 QApplication::setOrganizationDomain(QAPP_ORG_DOMAIN);
540 QApplication::setApplicationName(QAPP_APP_NAME_DEFAULT);
541 GUIUtil::SubstituteFonts(GetLangTerritory());
543 /// 4. Initialization of translations, so that intro dialog is in user's language
544 // Now that QSettings are accessible, initialize translations
545 QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
546 initTranslations(qtTranslatorBase, qtTranslator, translatorBase, translator);
547 translationInterface.Translate.connect(Translate);
549 // Show help message immediately after parsing command-line options (for "-lang") and setting locale,
550 // but before showing splash screen.
551 if (mapArgs.count("-?") || mapArgs.count("-h") || mapArgs.count("-help") || mapArgs.count("-version"))
553 HelpMessageDialog help(NULL, mapArgs.count("-version"));
558 /// 5. Now that settings and translations are available, ask user for data directory
559 // User language is set up: pick a data directory
560 Intro::pickDataDirectory();
562 /// 6. Determine availability of data directory and parse komodo.conf
563 /// - Do not call GetDataDir(true) before this step finishes
564 if (!boost::filesystem::is_directory(GetDataDir(false)))
566 QMessageBox::critical(0, QObject::tr("Bitcoin Core"),
567 QObject::tr("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"])));
571 ReadConfigFile(mapArgs, mapMultiArgs);
572 } catch (const std::exception& e) {
573 QMessageBox::critical(0, QObject::tr("Bitcoin Core"),
574 QObject::tr("Error: Cannot parse configuration file: %1. Only use key=value syntax.").arg(e.what()));
578 /// 7. Determine network (and switch to network specific options)
579 // - Do not call Params() before this step
580 // - Do this after parsing the configuration file, as the network can be switched there
581 // - QSettings() will use the new application name after this, resulting in network-specific settings
582 // - Needs to be done before createOptionsModel
584 // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
585 if (!SelectParamsFromCommandLine()) {
586 QMessageBox::critical(0, QObject::tr("Bitcoin Core"), QObject::tr("Error: Invalid combination of -regtest and -testnet."));
590 // Parse URIs on command line -- this can affect Params()
591 PaymentServer::ipcParseCommandLine(argc, argv);
594 QScopedPointer<const NetworkStyle> networkStyle(NetworkStyle::instantiate(QString::fromStdString(Params().NetworkIDString())));
595 assert(!networkStyle.isNull());
596 // Allow for separate UI settings for testnets
597 QApplication::setApplicationName(networkStyle->getAppName());
598 // Re-initialize translations after changing application name (language in network-specific settings can be different)
599 initTranslations(qtTranslatorBase, qtTranslator, translatorBase, translator);
602 /// 8. URI IPC sending
603 // - Do this early as we don't want to bother initializing if we are just calling IPC
604 // - Do this *after* setting up the data directory, as the data directory hash is used in the name
606 // - Do this after creating app and setting up translations, so errors are
607 // translated properly.
608 if (PaymentServer::ipcSendCommandLine())
611 // Start up the payment server early, too, so impatient users that click on
612 // bitcoin: links repeatedly have their payment requests routed to this process:
613 app.createPaymentServer();
616 /// 9. Main GUI initialization
617 // Install global event filter that makes sure that long tooltips can be word-wrapped
618 app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));
619 #if QT_VERSION < 0x050000
620 // Install qDebug() message handler to route to debug.log
621 qInstallMsgHandler(DebugMessageHandler);
623 #if defined(Q_OS_WIN)
624 // Install global event filter for processing Windows session related Windows messages (WM_QUERYENDSESSION and WM_ENDSESSION)
625 qApp->installNativeEventFilter(new WinShutdownMonitor());
627 // Install qDebug() message handler to route to debug.log
628 qInstallMessageHandler(DebugMessageHandler);
630 // Load GUI settings from QSettings
631 app.createOptionsModel();
633 // Subscribe to global signals from core
634 uiInterface.InitMessage.connect(InitMessage);
636 if (GetBoolArg("-splash", true) && !GetBoolArg("-min", false))
637 app.createSplashScreen(networkStyle.data());
641 app.createWindow(networkStyle.data());
642 app.requestInitialize();
643 #if defined(Q_OS_WIN) && QT_VERSION >= 0x050000
644 WinShutdownMonitor::registerShutdownBlockReason(QObject::tr("Bitcoin Core didn't yet exit safely..."), (HWND)app.getMainWinId());
647 app.requestShutdown();
649 } catch (const std::exception& e) {
650 PrintExceptionContinue(&e, "Runaway exception");
651 app.handleRunawayException(QString::fromStdString(strMiscWarning));
653 PrintExceptionContinue(NULL, "Runaway exception");
654 app.handleRunawayException(QString::fromStdString(strMiscWarning));
656 return app.getReturnValue();
658 #endif // BITCOIN_QT_TEST