]> Git Repo - VerusCoin.git/blob - src/qt/bitcoin.cpp
[Univalue] add univalue over subtree
[VerusCoin.git] / src / qt / bitcoin.cpp
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.
4
5 #if defined(HAVE_CONFIG_H)
6 #include "config/bitcoin-config.h"
7 #endif
8
9 #include "bitcoingui.h"
10
11 #include "clientmodel.h"
12 #include "guiconstants.h"
13 #include "guiutil.h"
14 #include "intro.h"
15 #include "networkstyle.h"
16 #include "optionsmodel.h"
17 #include "splashscreen.h"
18 #include "utilitydialog.h"
19 #include "winshutdownmonitor.h"
20
21 #ifdef ENABLE_WALLET
22 #include "paymentserver.h"
23 #include "walletmodel.h"
24 #endif
25
26 #include "init.h"
27 #include "main.h"
28 #include "rpcserver.h"
29 #include "scheduler.h"
30 #include "ui_interface.h"
31 #include "util.h"
32
33 #ifdef ENABLE_WALLET
34 #include "wallet/wallet.h"
35 #endif
36
37 #include <stdint.h>
38
39 #include <boost/filesystem/operations.hpp>
40 #include <boost/thread.hpp>
41
42 #include <QApplication>
43 #include <QDebug>
44 #include <QLibraryInfo>
45 #include <QLocale>
46 #include <QMessageBox>
47 #include <QSettings>
48 #include <QThread>
49 #include <QTimer>
50 #include <QTranslator>
51 #include <QSslConfiguration>
52
53 #if defined(QT_STATICPLUGIN)
54 #include <QtPlugin>
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)
61 #else
62 #if QT_VERSION < 0x050400
63 Q_IMPORT_PLUGIN(AccessibleFactory)
64 #endif
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);
71 #endif
72 #endif
73 #endif
74
75 #if QT_VERSION < 0x050000
76 #include <QTextCodec>
77 #endif
78
79 // Declare meta types used for QMetaObject::invokeMethod
80 Q_DECLARE_METATYPE(bool*)
81 Q_DECLARE_METATYPE(CAmount)
82
83 static void InitMessage(const std::string &message)
84 {
85     LogPrintf("init message: %s\n", message);
86 }
87
88 /*
89    Translate string to current locale using Qt.
90  */
91 static std::string Translate(const char* psz)
92 {
93     return QCoreApplication::translate("bitcoin-core", psz).toStdString();
94 }
95
96 static QString GetLangTerritory()
97 {
98     QSettings settings;
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;
109 }
110
111 /** Set up translations */
112 static void initTranslations(QTranslator &qtTranslatorBase, QTranslator &qtTranslator, QTranslator &translatorBase, QTranslator &translator)
113 {
114     // Remove old translators
115     QApplication::removeTranslator(&qtTranslatorBase);
116     QApplication::removeTranslator(&qtTranslator);
117     QApplication::removeTranslator(&translatorBase);
118     QApplication::removeTranslator(&translator);
119
120     // Get desired locale (e.g. "de_DE")
121     // 1) System default language
122     QString lang_territory = GetLangTerritory();
123
124     // Convert to "de" only by truncating "_DE"
125     QString lang = lang_territory;
126     lang.truncate(lang_territory.lastIndexOf('_'));
127
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
131
132     // Load e.g. qt_de.qm
133     if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
134         QApplication::installTranslator(&qtTranslatorBase);
135
136     // Load e.g. qt_de_DE.qm
137     if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
138         QApplication::installTranslator(&qtTranslator);
139
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);
143
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);
147 }
148
149 /* qDebug() message handler --> debug.log */
150 #if QT_VERSION < 0x050000
151 void DebugMessageHandler(QtMsgType type, const char *msg)
152 {
153     const char *category = (type == QtDebugMsg) ? "qt" : NULL;
154     LogPrint(category, "GUI: %s\n", msg);
155 }
156 #else
157 void DebugMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString &msg)
158 {
159     Q_UNUSED(context);
160     const char *category = (type == QtDebugMsg) ? "qt" : NULL;
161     LogPrint(category, "GUI: %s\n", msg.toStdString());
162 }
163 #endif
164
165 /** Class encapsulating Bitcoin Core startup and shutdown.
166  * Allows running startup and shutdown in a different thread from the UI thread.
167  */
168 class BitcoinCore: public QObject
169 {
170     Q_OBJECT
171 public:
172     explicit BitcoinCore();
173
174 public Q_SLOTS:
175     void initialize();
176     void shutdown();
177
178 Q_SIGNALS:
179     void initializeResult(int retval);
180     void shutdownResult(int retval);
181     void runawayException(const QString &message);
182
183 private:
184     boost::thread_group threadGroup;
185     CScheduler scheduler;
186
187     /// Pass fatal exception message to UI thread
188     void handleRunawayException(const std::exception *e);
189 };
190
191 /** Main Bitcoin application object */
192 class BitcoinApplication: public QApplication
193 {
194     Q_OBJECT
195 public:
196     explicit BitcoinApplication(int &argc, char **argv);
197     ~BitcoinApplication();
198
199 #ifdef ENABLE_WALLET
200     /// Create payment server
201     void createPaymentServer();
202 #endif
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);
209
210     /// Request core initialization
211     void requestInitialize();
212     /// Request core shutdown
213     void requestShutdown();
214
215     /// Get process return value
216     int getReturnValue() { return returnValue; }
217
218     /// Get window identifier of QMainWindow (BitcoinGUI)
219     WId getMainWinId() const;
220
221 public Q_SLOTS:
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);
226
227 Q_SIGNALS:
228     void requestedInitialize();
229     void requestedShutdown();
230     void stopThread();
231     void splashFinished(QWidget *window);
232
233 private:
234     QThread *coreThread;
235     OptionsModel *optionsModel;
236     ClientModel *clientModel;
237     BitcoinGUI *window;
238     QTimer *pollShutdownTimer;
239 #ifdef ENABLE_WALLET
240     PaymentServer* paymentServer;
241     WalletModel *walletModel;
242 #endif
243     int returnValue;
244
245     void startThread();
246 };
247
248 #include "bitcoin.moc"
249
250 BitcoinCore::BitcoinCore():
251     QObject()
252 {
253 }
254
255 void BitcoinCore::handleRunawayException(const std::exception *e)
256 {
257     PrintExceptionContinue(e, "Runaway exception");
258     Q_EMIT runawayException(QString::fromStdString(strMiscWarning));
259 }
260
261 void BitcoinCore::initialize()
262 {
263     try
264     {
265         qDebug() << __func__ << ": Running AppInit2 in thread";
266         int rv = AppInit2(threadGroup, scheduler);
267         if(rv)
268         {
269             /* Start a dummy RPC thread if no RPC thread is active yet
270              * to handle timeouts.
271              */
272             StartDummyRPCThread();
273         }
274         Q_EMIT initializeResult(rv);
275     } catch (const std::exception& e) {
276         handleRunawayException(&e);
277     } catch (...) {
278         handleRunawayException(NULL);
279     }
280 }
281
282 void BitcoinCore::shutdown()
283 {
284     try
285     {
286         qDebug() << __func__ << ": Running Shutdown in thread";
287         threadGroup.interrupt_all();
288         threadGroup.join_all();
289         Shutdown();
290         qDebug() << __func__ << ": Shutdown finished";
291         Q_EMIT shutdownResult(1);
292     } catch (const std::exception& e) {
293         handleRunawayException(&e);
294     } catch (...) {
295         handleRunawayException(NULL);
296     }
297 }
298
299 BitcoinApplication::BitcoinApplication(int &argc, char **argv):
300     QApplication(argc, argv),
301     coreThread(0),
302     optionsModel(0),
303     clientModel(0),
304     window(0),
305     pollShutdownTimer(0),
306 #ifdef ENABLE_WALLET
307     paymentServer(0),
308     walletModel(0),
309 #endif
310     returnValue(0)
311 {
312     setQuitOnLastWindowClosed(false);
313 }
314
315 BitcoinApplication::~BitcoinApplication()
316 {
317     if(coreThread)
318     {
319         qDebug() << __func__ << ": Stopping thread";
320         Q_EMIT stopThread();
321         coreThread->wait();
322         qDebug() << __func__ << ": Stopped thread";
323     }
324
325     delete window;
326     window = 0;
327 #ifdef ENABLE_WALLET
328     delete paymentServer;
329     paymentServer = 0;
330 #endif
331     delete optionsModel;
332     optionsModel = 0;
333 }
334
335 #ifdef ENABLE_WALLET
336 void BitcoinApplication::createPaymentServer()
337 {
338     paymentServer = new PaymentServer(this);
339 }
340 #endif
341
342 void BitcoinApplication::createOptionsModel()
343 {
344     optionsModel = new OptionsModel();
345 }
346
347 void BitcoinApplication::createWindow(const NetworkStyle *networkStyle)
348 {
349     window = new BitcoinGUI(networkStyle, 0);
350
351     pollShutdownTimer = new QTimer(window);
352     connect(pollShutdownTimer, SIGNAL(timeout()), window, SLOT(detectShutdown()));
353     pollShutdownTimer->start(200);
354 }
355
356 void BitcoinApplication::createSplashScreen(const NetworkStyle *networkStyle)
357 {
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);
362     splash->show();
363     connect(this, SIGNAL(splashFinished(QWidget*)), splash, SLOT(slotFinish(QWidget*)));
364 }
365
366 void BitcoinApplication::startThread()
367 {
368     if(coreThread)
369         return;
370     coreThread = new QThread(this);
371     BitcoinCore *executor = new BitcoinCore();
372     executor->moveToThread(coreThread);
373
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()));
383
384     coreThread->start();
385 }
386
387 void BitcoinApplication::requestInitialize()
388 {
389     qDebug() << __func__ << ": Requesting initialize";
390     startThread();
391     Q_EMIT requestedInitialize();
392 }
393
394 void BitcoinApplication::requestShutdown()
395 {
396     qDebug() << __func__ << ": Requesting shutdown";
397     startThread();
398     window->hide();
399     window->setClientModel(0);
400     pollShutdownTimer->stop();
401
402 #ifdef ENABLE_WALLET
403     window->removeAllWallets();
404     delete walletModel;
405     walletModel = 0;
406 #endif
407     delete clientModel;
408     clientModel = 0;
409
410     // Show a simple window indicating shutdown status
411     ShutdownWindow::showShutdownWindow(window);
412
413     // Request shutdown from core thread
414     Q_EMIT requestedShutdown();
415 }
416
417 void BitcoinApplication::initializeResult(int retval)
418 {
419     qDebug() << __func__ << ": Initialization result: " << retval;
420     // Set exit result: 0 if successful, 1 if failure
421     returnValue = retval ? 0 : 1;
422     if(retval)
423     {
424 #ifdef ENABLE_WALLET
425         PaymentServer::LoadRootCAs();
426         paymentServer->setOptionsModel(optionsModel);
427 #endif
428
429         clientModel = new ClientModel(optionsModel);
430         window->setClientModel(clientModel);
431
432 #ifdef ENABLE_WALLET
433         if(pwalletMain)
434         {
435             walletModel = new WalletModel(pwalletMain, optionsModel);
436
437             window->addWallet(BitcoinGUI::DEFAULT_WALLET, walletModel);
438             window->setCurrentWallet(BitcoinGUI::DEFAULT_WALLET);
439
440             connect(walletModel, SIGNAL(coinsSent(CWallet*,SendCoinsRecipient,QByteArray)),
441                              paymentServer, SLOT(fetchPaymentACK(CWallet*,const SendCoinsRecipient&,QByteArray)));
442         }
443 #endif
444
445         // If -min option passed, start window minimized.
446         if(GetBoolArg("-min", false))
447         {
448             window->showMinimized();
449         }
450         else
451         {
452             window->show();
453         }
454         Q_EMIT splashFinished(window);
455
456 #ifdef ENABLE_WALLET
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()));
466 #endif
467     } else {
468         quit(); // Exit main loop
469     }
470 }
471
472 void BitcoinApplication::shutdownResult(int retval)
473 {
474     qDebug() << __func__ << ": Shutdown result: " << retval;
475     quit(); // Exit main loop after shutdown finished
476 }
477
478 void BitcoinApplication::handleRunawayException(const QString &message)
479 {
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);
481     ::exit(1);
482 }
483
484 WId BitcoinApplication::getMainWinId() const
485 {
486     if (!window)
487         return 0;
488
489     return window->winId();
490 }
491
492 #ifndef BITCOIN_QT_TEST
493 int main(int argc, char *argv[])
494 {
495     SetupEnvironment();
496
497     /// 1. Parse command-line options. These take precedence over anything else.
498     // Command-line options take precedence:
499     ParseParameters(argc, argv);
500
501     // Do not refer to data directory yet, this can be overridden by Intro::pickDataDirectory
502
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());
508 #endif
509
510     Q_INIT_RESOURCE(bitcoin);
511     Q_INIT_RESOURCE(bitcoin_locale);
512
513     BitcoinApplication app(argc, argv);
514 #if QT_VERSION > 0x050100
515     // Generate high-dpi pixmaps
516     QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
517 #endif
518 #ifdef Q_OS_MAC
519     QApplication::setAttribute(Qt::AA_DontShowIconsInMenus);
520 #endif
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);
527 #endif
528
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");
534
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());
542
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);
548
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"))
552     {
553         HelpMessageDialog help(NULL, mapArgs.count("-version"));
554         help.showOrPrint();
555         return 1;
556     }
557
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();
561
562     /// 6. Determine availability of data directory and parse zcash.conf
563     /// - Do not call GetDataDir(true) before this step finishes
564     if (!boost::filesystem::is_directory(GetDataDir(false)))
565     {
566         QMessageBox::critical(0, QObject::tr("Bitcoin Core"),
567                               QObject::tr("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"])));
568         return 1;
569     }
570     try {
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()));
575         return false;
576     }
577
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
583
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."));
587         return 1;
588     }
589 #ifdef ENABLE_WALLET
590     // Parse URIs on command line -- this can affect Params()
591     PaymentServer::ipcParseCommandLine(argc, argv);
592 #endif
593
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);
600
601 #ifdef ENABLE_WALLET
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
605     // of the server.
606     // - Do this after creating app and setting up translations, so errors are
607     // translated properly.
608     if (PaymentServer::ipcSendCommandLine())
609         exit(0);
610
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();
614 #endif
615
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);
622 #else
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());
626 #endif
627     // Install qDebug() message handler to route to debug.log
628     qInstallMessageHandler(DebugMessageHandler);
629 #endif
630     // Load GUI settings from QSettings
631     app.createOptionsModel();
632
633     // Subscribe to global signals from core
634     uiInterface.InitMessage.connect(InitMessage);
635
636     if (GetBoolArg("-splash", true) && !GetBoolArg("-min", false))
637         app.createSplashScreen(networkStyle.data());
638
639     try
640     {
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());
645 #endif
646         app.exec();
647         app.requestShutdown();
648         app.exec();
649     } catch (const std::exception& e) {
650         PrintExceptionContinue(&e, "Runaway exception");
651         app.handleRunawayException(QString::fromStdString(strMiscWarning));
652     } catch (...) {
653         PrintExceptionContinue(NULL, "Runaway exception");
654         app.handleRunawayException(QString::fromStdString(strMiscWarning));
655     }
656     return app.getReturnValue();
657 }
658 #endif // BITCOIN_QT_TEST
This page took 0.060303 seconds and 4 git commands to generate.