]> Git Repo - VerusCoin.git/blob - src/qt/bitcoin.cpp
Merge pull request #5286
[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 "ui_interface.h"
30 #include "util.h"
31
32 #ifdef ENABLE_WALLET
33 #include "wallet.h"
34 #endif
35
36 #include <stdint.h>
37
38 #include <boost/filesystem/operations.hpp>
39 #include <boost/thread.hpp>
40
41 #include <QApplication>
42 #include <QDebug>
43 #include <QLibraryInfo>
44 #include <QLocale>
45 #include <QMessageBox>
46 #include <QSettings>
47 #include <QThread>
48 #include <QTimer>
49 #include <QTranslator>
50
51 #if defined(QT_STATICPLUGIN)
52 #include <QtPlugin>
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)
59 #else
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);
67 #endif
68 #endif
69 #endif
70
71 #if QT_VERSION < 0x050000
72 #include <QTextCodec>
73 #endif
74
75 // Declare meta types used for QMetaObject::invokeMethod
76 Q_DECLARE_METATYPE(bool*)
77 Q_DECLARE_METATYPE(CAmount)
78
79 static void InitMessage(const std::string &message)
80 {
81     LogPrintf("init message: %s\n", message);
82 }
83
84 /*
85    Translate string to current locale using Qt.
86  */
87 static std::string Translate(const char* psz)
88 {
89     return QCoreApplication::translate("bitcoin-core", psz).toStdString();
90 }
91
92 static QString GetLangTerritory()
93 {
94     QSettings settings;
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;
105 }
106
107 /** Set up translations */
108 static void initTranslations(QTranslator &qtTranslatorBase, QTranslator &qtTranslator, QTranslator &translatorBase, QTranslator &translator)
109 {
110
111     // Remove old translators
112     QApplication::removeTranslator(&qtTranslatorBase);
113     QApplication::removeTranslator(&qtTranslator);
114     QApplication::removeTranslator(&translatorBase);
115     QApplication::removeTranslator(&translator);
116
117     // Get desired locale (e.g. "de_DE")
118     // 1) System default language
119     QString lang_territory = GetLangTerritory();
120
121     // Convert to "de" only by truncating "_DE"
122     QString lang = lang_territory;
123     lang.truncate(lang_territory.lastIndexOf('_'));
124
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
128
129     // Load e.g. qt_de.qm
130     if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
131         QApplication::installTranslator(&qtTranslatorBase);
132
133     // Load e.g. qt_de_DE.qm
134     if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
135         QApplication::installTranslator(&qtTranslator);
136
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);
140
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);
144 }
145
146 /* qDebug() message handler --> debug.log */
147 #if QT_VERSION < 0x050000
148 void DebugMessageHandler(QtMsgType type, const char *msg)
149 {
150     const char *category = (type == QtDebugMsg) ? "qt" : NULL;
151     LogPrint(category, "GUI: %s\n", msg);
152 }
153 #else
154 void DebugMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString &msg)
155 {
156     Q_UNUSED(context);
157     const char *category = (type == QtDebugMsg) ? "qt" : NULL;
158     LogPrint(category, "GUI: %s\n", msg.toStdString());
159 }
160 #endif
161
162 /** Class encapsulating Bitcoin Core startup and shutdown.
163  * Allows running startup and shutdown in a different thread from the UI thread.
164  */
165 class BitcoinCore: public QObject
166 {
167     Q_OBJECT
168 public:
169     explicit BitcoinCore();
170
171 public slots:
172     void initialize();
173     void shutdown();
174
175 signals:
176     void initializeResult(int retval);
177     void shutdownResult(int retval);
178     void runawayException(const QString &message);
179
180 private:
181     boost::thread_group threadGroup;
182
183     /// Pass fatal exception message to UI thread
184     void handleRunawayException(const std::exception *e);
185 };
186
187 /** Main Bitcoin application object */
188 class BitcoinApplication: public QApplication
189 {
190     Q_OBJECT
191 public:
192     explicit BitcoinApplication(int &argc, char **argv);
193     ~BitcoinApplication();
194
195 #ifdef ENABLE_WALLET
196     /// Create payment server
197     void createPaymentServer();
198 #endif
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);
205
206     /// Request core initialization
207     void requestInitialize();
208     /// Request core shutdown
209     void requestShutdown();
210
211     /// Get process return value
212     int getReturnValue() { return returnValue; }
213
214     /// Get window identifier of QMainWindow (BitcoinGUI)
215     WId getMainWinId() const;
216
217 public slots:
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);
222
223 signals:
224     void requestedInitialize();
225     void requestedShutdown();
226     void stopThread();
227     void splashFinished(QWidget *window);
228
229 private:
230     QThread *coreThread;
231     OptionsModel *optionsModel;
232     ClientModel *clientModel;
233     BitcoinGUI *window;
234     QTimer *pollShutdownTimer;
235 #ifdef ENABLE_WALLET
236     PaymentServer* paymentServer;
237     WalletModel *walletModel;
238 #endif
239     int returnValue;
240
241     void startThread();
242 };
243
244 #include "bitcoin.moc"
245
246 BitcoinCore::BitcoinCore():
247     QObject()
248 {
249 }
250
251 void BitcoinCore::handleRunawayException(const std::exception *e)
252 {
253     PrintExceptionContinue(e, "Runaway exception");
254     emit runawayException(QString::fromStdString(strMiscWarning));
255 }
256
257 void BitcoinCore::initialize()
258 {
259     try
260     {
261         qDebug() << __func__ << ": Running AppInit2 in thread";
262         int rv = AppInit2(threadGroup);
263         if(rv)
264         {
265             /* Start a dummy RPC thread if no RPC thread is active yet
266              * to handle timeouts.
267              */
268             StartDummyRPCThread();
269         }
270         emit initializeResult(rv);
271     } catch (const std::exception& e) {
272         handleRunawayException(&e);
273     } catch (...) {
274         handleRunawayException(NULL);
275     }
276 }
277
278 void BitcoinCore::shutdown()
279 {
280     try
281     {
282         qDebug() << __func__ << ": Running Shutdown in thread";
283         threadGroup.interrupt_all();
284         threadGroup.join_all();
285         Shutdown();
286         qDebug() << __func__ << ": Shutdown finished";
287         emit shutdownResult(1);
288     } catch (const std::exception& e) {
289         handleRunawayException(&e);
290     } catch (...) {
291         handleRunawayException(NULL);
292     }
293 }
294
295 BitcoinApplication::BitcoinApplication(int &argc, char **argv):
296     QApplication(argc, argv),
297     coreThread(0),
298     optionsModel(0),
299     clientModel(0),
300     window(0),
301     pollShutdownTimer(0),
302 #ifdef ENABLE_WALLET
303     paymentServer(0),
304     walletModel(0),
305 #endif
306     returnValue(0)
307 {
308     setQuitOnLastWindowClosed(false);
309 }
310
311 BitcoinApplication::~BitcoinApplication()
312 {
313     if(coreThread)
314     {
315         qDebug() << __func__ << ": Stopping thread";
316         emit stopThread();
317         coreThread->wait();
318         qDebug() << __func__ << ": Stopped thread";
319     }
320
321     delete window;
322     window = 0;
323 #ifdef ENABLE_WALLET
324     delete paymentServer;
325     paymentServer = 0;
326 #endif
327     delete optionsModel;
328     optionsModel = 0;
329 }
330
331 #ifdef ENABLE_WALLET
332 void BitcoinApplication::createPaymentServer()
333 {
334     paymentServer = new PaymentServer(this);
335 }
336 #endif
337
338 void BitcoinApplication::createOptionsModel()
339 {
340     optionsModel = new OptionsModel();
341 }
342
343 void BitcoinApplication::createWindow(const NetworkStyle *networkStyle)
344 {
345     window = new BitcoinGUI(networkStyle, 0);
346
347     pollShutdownTimer = new QTimer(window);
348     connect(pollShutdownTimer, SIGNAL(timeout()), window, SLOT(detectShutdown()));
349     pollShutdownTimer->start(200);
350 }
351
352 void BitcoinApplication::createSplashScreen(const NetworkStyle *networkStyle)
353 {
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);
358     splash->show();
359     connect(this, SIGNAL(splashFinished(QWidget*)), splash, SLOT(slotFinish(QWidget*)));
360 }
361
362 void BitcoinApplication::startThread()
363 {
364     if(coreThread)
365         return;
366     coreThread = new QThread(this);
367     BitcoinCore *executor = new BitcoinCore();
368     executor->moveToThread(coreThread);
369
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()));
379
380     coreThread->start();
381 }
382
383 void BitcoinApplication::requestInitialize()
384 {
385     qDebug() << __func__ << ": Requesting initialize";
386     startThread();
387     emit requestedInitialize();
388 }
389
390 void BitcoinApplication::requestShutdown()
391 {
392     qDebug() << __func__ << ": Requesting shutdown";
393     startThread();
394     window->hide();
395     window->setClientModel(0);
396     pollShutdownTimer->stop();
397
398 #ifdef ENABLE_WALLET
399     window->removeAllWallets();
400     delete walletModel;
401     walletModel = 0;
402 #endif
403     delete clientModel;
404     clientModel = 0;
405
406     // Show a simple window indicating shutdown status
407     ShutdownWindow::showShutdownWindow(window);
408
409     // Request shutdown from core thread
410     emit requestedShutdown();
411 }
412
413 void BitcoinApplication::initializeResult(int retval)
414 {
415     qDebug() << __func__ << ": Initialization result: " << retval;
416     // Set exit result: 0 if successful, 1 if failure
417     returnValue = retval ? 0 : 1;
418     if(retval)
419     {
420 #ifdef ENABLE_WALLET
421         PaymentServer::LoadRootCAs();
422         paymentServer->setOptionsModel(optionsModel);
423 #endif
424
425         clientModel = new ClientModel(optionsModel);
426         window->setClientModel(clientModel);
427
428 #ifdef ENABLE_WALLET
429         if(pwalletMain)
430         {
431             walletModel = new WalletModel(pwalletMain, optionsModel);
432
433             window->addWallet(BitcoinGUI::DEFAULT_WALLET, walletModel);
434             window->setCurrentWallet(BitcoinGUI::DEFAULT_WALLET);
435
436             connect(walletModel, SIGNAL(coinsSent(CWallet*,SendCoinsRecipient,QByteArray)),
437                              paymentServer, SLOT(fetchPaymentACK(CWallet*,const SendCoinsRecipient&,QByteArray)));
438         }
439 #endif
440
441         // If -min option passed, start window minimized.
442         if(GetBoolArg("-min", false))
443         {
444             window->showMinimized();
445         }
446         else
447         {
448             window->show();
449         }
450         emit splashFinished(window);
451
452 #ifdef ENABLE_WALLET
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()));
462 #endif
463     } else {
464         quit(); // Exit main loop
465     }
466 }
467
468 void BitcoinApplication::shutdownResult(int retval)
469 {
470     qDebug() << __func__ << ": Shutdown result: " << retval;
471     quit(); // Exit main loop after shutdown finished
472 }
473
474 void BitcoinApplication::handleRunawayException(const QString &message)
475 {
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);
477     ::exit(1);
478 }
479
480 WId BitcoinApplication::getMainWinId() const
481 {
482     if (!window)
483         return 0;
484
485     return window->winId();
486 }
487
488 #ifndef BITCOIN_QT_TEST
489 int main(int argc, char *argv[])
490 {
491     SetupEnvironment();
492
493     /// 1. Parse command-line options. These take precedence over anything else.
494     // Command-line options take precedence:
495     ParseParameters(argc, argv);
496
497     // Do not refer to data directory yet, this can be overridden by Intro::pickDataDirectory
498
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());
504 #endif
505
506     Q_INIT_RESOURCE(bitcoin);
507     Q_INIT_RESOURCE(bitcoin_locale);
508
509     BitcoinApplication app(argc, argv);
510 #if QT_VERSION > 0x050100
511     // Generate high-dpi pixmaps
512     QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
513 #endif
514 #ifdef Q_OS_MAC
515     QApplication::setAttribute(Qt::AA_DontShowIconsInMenus);
516 #endif
517
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");
523
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());
531
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);
537
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"))
541     {
542         HelpMessageDialog help(NULL, mapArgs.count("-version"));
543         help.showOrPrint();
544         return 1;
545     }
546
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();
550
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)))
554     {
555         QMessageBox::critical(0, QObject::tr("Bitcoin Core"),
556                               QObject::tr("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"])));
557         return 1;
558     }
559     try {
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()));
564         return false;
565     }
566
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
572
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."));
576         return 1;
577     }
578 #ifdef ENABLE_WALLET
579     // Parse URIs on command line -- this can affect Params()
580     PaymentServer::ipcParseCommandLine(argc, argv);
581 #endif
582
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);
589
590 #ifdef ENABLE_WALLET
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
594     // of the server.
595     // - Do this after creating app and setting up translations, so errors are
596     // translated properly.
597     if (PaymentServer::ipcSendCommandLine())
598         exit(0);
599
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();
603 #endif
604
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);
611 #else
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());
615 #endif
616     // Install qDebug() message handler to route to debug.log
617     qInstallMessageHandler(DebugMessageHandler);
618 #endif
619     // Load GUI settings from QSettings
620     app.createOptionsModel();
621
622     // Subscribe to global signals from core
623     uiInterface.InitMessage.connect(InitMessage);
624
625     if (GetBoolArg("-splash", true) && !GetBoolArg("-min", false))
626         app.createSplashScreen(networkStyle.data());
627
628     try
629     {
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());
634 #endif
635         app.exec();
636         app.requestShutdown();
637         app.exec();
638     } catch (const std::exception& e) {
639         PrintExceptionContinue(&e, "Runaway exception");
640         app.handleRunawayException(QString::fromStdString(strMiscWarning));
641     } catch (...) {
642         PrintExceptionContinue(NULL, "Runaway exception");
643         app.handleRunawayException(QString::fromStdString(strMiscWarning));
644     }
645     return app.getReturnValue();
646 }
647 #endif // BITCOIN_QT_TEST
This page took 0.058623 seconds and 4 git commands to generate.