bitcoingui.cpp 36 KB
Newer Older
1
// Copyright (c) 2011-2014 The Bitcoin developers
2
3
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4

Wladimir J. van der Laan's avatar
Wladimir J. van der Laan committed
5
#include "bitcoingui.h"
6

7
#include "bitcoinunits.h"
8
#include "clientmodel.h"
9
#include "guiconstants.h"
10
#include "guiutil.h"
11
#include "notificator.h"
12
#include "openuridialog.h"
13
14
#include "optionsdialog.h"
#include "optionsmodel.h"
15
#include "rpcconsole.h"
16
#include "utilitydialog.h"
17
#ifdef ENABLE_WALLET
18
19
#include "walletframe.h"
#include "walletmodel.h"
20
#endif
Wladimir J. van der Laan's avatar
Wladimir J. van der Laan committed
21

Philip Kaufmann's avatar
Philip Kaufmann committed
22
#ifdef Q_OS_MAC
23
24
25
#include "macdockiconhandler.h"
#endif

26
27
28
29
30
#include "init.h"
#include "ui_interface.h"

#include <iostream>

31
#include <QAction>
32
#include <QApplication>
33
34
35
#include <QDateTime>
#include <QDesktopWidget>
#include <QDragEnterEvent>
Wladimir J. van der Laan's avatar
Wladimir J. van der Laan committed
36
#include <QIcon>
37
38
#include <QListWidget>
#include <QMenuBar>
Wladimir J. van der Laan's avatar
Wladimir J. van der Laan committed
39
#include <QMessageBox>
40
#include <QMimeData>
41
#include <QProgressBar>
Cozz Lovan's avatar
Cozz Lovan committed
42
#include <QProgressDialog>
43
#include <QSettings>
44
#include <QStackedWidget>
45
46
#include <QStatusBar>
#include <QStyle>
47
#include <QTimer>
48
49
50
#include <QToolBar>
#include <QVBoxLayout>

Wladimir J. van der Laan's avatar
Wladimir J. van der Laan committed
51
#if QT_VERSION < 0x050000
52
#include <QUrl>
53
#include <QTextDocument>
54
55
#else
#include <QUrlQuery>
Wladimir J. van der Laan's avatar
Wladimir J. van der Laan committed
56
#endif
Wladimir J. van der Laan's avatar
Wladimir J. van der Laan committed
57

58
59
const QString BitcoinGUI::DEFAULT_WALLET = "~Default";

60
BitcoinGUI::BitcoinGUI(bool fIsTestnet, QWidget *parent) :
61
62
    QMainWindow(parent),
    clientModel(0),
63
    walletFrame(0),
64
65
    encryptWalletAction(0),
    changePassphraseAction(0),
66
    aboutQtAction(0),
67
    trayIcon(0),
68
    notificator(0),
69
    rpcConsole(0),
70
71
    prevBlocks(0),
    spinnerFrame(0)
Wladimir J. van der Laan's avatar
Wladimir J. van der Laan committed
72
{
73
    GUIUtil::restoreWindowGeometry("nWindow", QSize(850, 550), this);
74

75
76
77
78
79
80
81
82
83
84
85
86
87
88
    QString windowTitle = tr("Bitcoin Core") + " - ";
#ifdef ENABLE_WALLET
    /* if compiled with wallet support, -disablewallet can still disable the wallet */
    bool enableWallet = !GetBoolArg("-disablewallet", false);
#else
    bool enableWallet = false;
#endif
    if(enableWallet)
    {
        windowTitle += tr("Wallet");
    } else {
        windowTitle += tr("Node");
    }

89
90
    if (!fIsTestnet)
    {
91
#ifndef Q_OS_MAC
92
93
        QApplication::setWindowIcon(QIcon(":icons/bitcoin"));
        setWindowIcon(QIcon(":icons/bitcoin"));
94
95
96
#else
        MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin"));
#endif
97
98
99
    }
    else
    {
100
        windowTitle += " " + tr("[testnet]");
101
#ifndef Q_OS_MAC
102
103
        QApplication::setWindowIcon(QIcon(":icons/bitcoin_testnet"));
        setWindowIcon(QIcon(":icons/bitcoin_testnet"));
104
#else
105
        MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin_testnet"));
106
#endif
107
    }
108
    setWindowTitle(windowTitle);
109
110
111
112
113
114

#if defined(Q_OS_MAC) && QT_VERSION < 0x050000
    // This property is not implemented in Qt 5. Setting it has no effect.
    // A replacement API (QtMacUnifiedToolBar) is available in QtMacExtras.
    setUnifiedTitleAndToolBarOnMac(true);
#endif
115

116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
    rpcConsole = new RPCConsole(enableWallet ? this : 0);
#ifdef ENABLE_WALLET
    if(enableWallet)
    {
        /** Create wallet frame and make it the central widget */
        walletFrame = new WalletFrame(this);
        setCentralWidget(walletFrame);
    } else
#endif
    {
        /* When compiled without wallet or -disablewallet is provided,
         * the central widget is the rpc console.
         */
        setCentralWidget(rpcConsole);
    }
131

132
133
    // Accept D&D of URIs
    setAcceptDrops(true);
Wladimir J. van der Laan's avatar
Wladimir J. van der Laan committed
134

135
    // Create actions for the toolbar, menu bar and tray/dock icon
136
    // Needs walletFrame to be initialized
137
    createActions(fIsTestnet);
138

139
140
    // Create application menu bar
    createMenuBar();
141

142
143
    // Create the toolbars
    createToolBars();
Wladimir J. van der Laan's avatar
Wladimir J. van der Laan committed
144

145
    // Create system tray icon and notification
146
    createTrayIcon(fIsTestnet);
147

148
    // Create status bar
Wladimir J. van der Laan's avatar
Wladimir J. van der Laan committed
149
    statusBar();
150

151
    // Status bar notification icons
152
    QFrame *frameBlocks = new QFrame();
153
    frameBlocks->setContentsMargins(0,0,0,0);
154
    frameBlocks->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);
155
156
157
    QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks);
    frameBlocksLayout->setContentsMargins(3,0,3,0);
    frameBlocksLayout->setSpacing(3);
158
    unitDisplayControl = new UnitDisplayStatusBarControl();
159
    labelEncryptionIcon = new QLabel();
160
    labelConnectionsIcon = new QLabel();
161
    labelBlocksIcon = new QLabel();
162
163
164
165
166
167
168
    if(enableWallet)
    {
        frameBlocksLayout->addStretch();
        frameBlocksLayout->addWidget(unitDisplayControl);
        frameBlocksLayout->addStretch();
        frameBlocksLayout->addWidget(labelEncryptionIcon);
    }
169
    frameBlocksLayout->addStretch();
170
171
    frameBlocksLayout->addWidget(labelConnectionsIcon);
    frameBlocksLayout->addStretch();
172
173
    frameBlocksLayout->addWidget(labelBlocksIcon);
    frameBlocksLayout->addStretch();
174

175
176
    // Progress bar and label for blocks download
    progressBarLabel = new QLabel();
177
178
    progressBarLabel->setVisible(false);
    progressBar = new QProgressBar();
179
    progressBar->setAlignment(Qt::AlignCenter);
180
181
    progressBar->setVisible(false);

182
183
184
    // Override style sheet for progress bar for styles that have a segmented progress bar,
    // as they make the text unreadable (workaround for issue #1071)
    // See https://qt-project.org/doc/qt-4.8/gallery.html
185
    QString curStyle = QApplication::style()->metaObject()->className();
186
187
188
189
190
    if(curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle")
    {
        progressBar->setStyleSheet("QProgressBar { background-color: #e8e8e8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #FF8000, stop: 1 orange); border-radius: 7px; margin: 0px; }");
    }

191
192
    statusBar()->addWidget(progressBarLabel);
    statusBar()->addWidget(progressBar);
193
    statusBar()->addPermanentWidget(frameBlocks);
194

195
    connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(show()));
196

Mathy Vanvoorden's avatar
Mathy Vanvoorden committed
197
    // prevents an open debug window from becoming stuck/unusable on client shutdown
198
    connect(quitAction, SIGNAL(triggered()), rpcConsole, SLOT(hide()));
199

200
201
    // Install event filter to be able to catch status tip events (QEvent::StatusTip)
    this->installEventFilter(this);
202
203
204

    // Initially wallet actions should be disabled
    setWalletActionsEnabled(false);
205
206
207

    // Subscribe to notifications from core
    subscribeToCoreSignals();
Wladimir J. van der Laan's avatar
Wladimir J. van der Laan committed
208
209
}

210
211
BitcoinGUI::~BitcoinGUI()
{
212
213
214
    // Unsubscribe from notifications from core
    unsubscribeFromCoreSignals();

215
    GUIUtil::saveWindowGeometry("nWindow", this);
216
217
    if(trayIcon) // Hide tray icon, as deleting will let it linger until quit (on Ubuntu)
        trayIcon->hide();
Philip Kaufmann's avatar
Philip Kaufmann committed
218
#ifdef Q_OS_MAC
219
    delete appMenuBar;
220
    MacDockIconHandler::instance()->setMainWindow(NULL);
221
222
223
#endif
}

224
void BitcoinGUI::createActions(bool fIsTestnet)
Wladimir J. van der Laan's avatar
Wladimir J. van der Laan committed
225
{
226
    QActionGroup *tabGroup = new QActionGroup(this);
227

228
    overviewAction = new QAction(QIcon(":/icons/overview"), tr("&Overview"), this);
229
230
    overviewAction->setStatusTip(tr("Show general overview of wallet"));
    overviewAction->setToolTip(overviewAction->statusTip());
231
    overviewAction->setCheckable(true);
232
    overviewAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1));
233
    tabGroup->addAction(overviewAction);
234

235
    sendCoinsAction = new QAction(QIcon(":/icons/send"), tr("&Send"), this);
236
237
    sendCoinsAction->setStatusTip(tr("Send coins to a Bitcoin address"));
    sendCoinsAction->setToolTip(sendCoinsAction->statusTip());
Philip Kaufmann's avatar
Philip Kaufmann committed
238
239
240
241
    sendCoinsAction->setCheckable(true);
    sendCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2));
    tabGroup->addAction(sendCoinsAction);

242
    receiveCoinsAction = new QAction(QIcon(":/icons/receiving_addresses"), tr("&Receive"), this);
243
    receiveCoinsAction->setStatusTip(tr("Request payments (generates QR codes and bitcoin: URIs)"));
244
    receiveCoinsAction->setToolTip(receiveCoinsAction->statusTip());
Philip Kaufmann's avatar
Philip Kaufmann committed
245
246
247
248
    receiveCoinsAction->setCheckable(true);
    receiveCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_3));
    tabGroup->addAction(receiveCoinsAction);

249
    historyAction = new QAction(QIcon(":/icons/history"), tr("&Transactions"), this);
250
251
    historyAction->setStatusTip(tr("Browse transaction history"));
    historyAction->setToolTip(historyAction->statusTip());
252
    historyAction->setCheckable(true);
253
    historyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_4));
254
255
    tabGroup->addAction(historyAction);

256
257
    // These showNormalIfMinimized are needed because Send Coins and Receive Coins
    // can be triggered from the tray menu, and need to show the GUI to be useful.
258
    connect(overviewAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
259
    connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage()));
Philip Kaufmann's avatar
Philip Kaufmann committed
260
261
262
263
    connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
    connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage()));
    connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
    connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage()));
264
    connect(historyAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
265
    connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage()));
266

267
    quitAction = new QAction(QIcon(":/icons/quit"), tr("E&xit"), this);
268
    quitAction->setStatusTip(tr("Quit application"));
269
    quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q));
270
    quitAction->setMenuRole(QAction::QuitRole);
271
    if (!fIsTestnet)
272
        aboutAction = new QAction(QIcon(":/icons/bitcoin"), tr("&About Bitcoin Core"), this);
273
    else
274
        aboutAction = new QAction(QIcon(":/icons/bitcoin_testnet"), tr("&About Bitcoin Core"), this);
275
    aboutAction->setStatusTip(tr("Show information about Bitcoin"));
276
    aboutAction->setMenuRole(QAction::AboutRole);
277
#if QT_VERSION < 0x050000
278
    aboutQtAction = new QAction(QIcon(":/trolltech/qmessagebox/images/qtlogo-64.png"), tr("About &Qt"), this);
279
280
#else
    aboutQtAction = new QAction(QIcon(":/qt-project.org/qmessagebox/images/qtlogo-64.png"), tr("About &Qt"), this);
281
#endif
282
    aboutQtAction->setStatusTip(tr("Show information about Qt"));
283
    aboutQtAction->setMenuRole(QAction::AboutQtRole);
284
    optionsAction = new QAction(QIcon(":/icons/options"), tr("&Options..."), this);
285
    optionsAction->setStatusTip(tr("Modify configuration options for Bitcoin"));
286
    optionsAction->setMenuRole(QAction::PreferencesRole);
287
288
289
290
    if (!fIsTestnet)
        toggleHideAction = new QAction(QIcon(":/icons/bitcoin"), tr("&Show / Hide"), this);
    else
        toggleHideAction = new QAction(QIcon(":/icons/bitcoin_testnet"), tr("&Show / Hide"), this);
291
    toggleHideAction->setStatusTip(tr("Show or hide the main Window"));
292

293
    encryptWalletAction = new QAction(QIcon(":/icons/lock_closed"), tr("&Encrypt Wallet..."), this);
294
    encryptWalletAction->setStatusTip(tr("Encrypt the private keys that belong to your wallet"));
295
    encryptWalletAction->setCheckable(true);
296
    backupWalletAction = new QAction(QIcon(":/icons/filesave"), tr("&Backup Wallet..."), this);
297
    backupWalletAction->setStatusTip(tr("Backup wallet to another location"));
298
    changePassphraseAction = new QAction(QIcon(":/icons/key"), tr("&Change Passphrase..."), this);
299
    changePassphraseAction->setStatusTip(tr("Change the passphrase used for wallet encryption"));
Philip Kaufmann's avatar
Philip Kaufmann committed
300
    signMessageAction = new QAction(QIcon(":/icons/edit"), tr("Sign &message..."), this);
301
    signMessageAction->setStatusTip(tr("Sign messages with your Bitcoin addresses to prove you own them"));
Philip Kaufmann's avatar
Philip Kaufmann committed
302
    verifyMessageAction = new QAction(QIcon(":/icons/transaction_0"), tr("&Verify message..."), this);
303
    verifyMessageAction->setStatusTip(tr("Verify messages to ensure they were signed with specified Bitcoin addresses"));
Philip Kaufmann's avatar
Philip Kaufmann committed
304

305
    openRPCConsoleAction = new QAction(QIcon(":/icons/debugwindow"), tr("&Debug window"), this);
306
    openRPCConsoleAction->setStatusTip(tr("Open debugging and diagnostic console"));
Wladimir J. van der Laan's avatar
Wladimir J. van der Laan committed
307

308
    usedSendingAddressesAction = new QAction(QIcon(":/icons/address-book"), tr("&Sending addresses..."), this);
309
    usedSendingAddressesAction->setStatusTip(tr("Show the list of used sending addresses and labels"));
310
    usedReceivingAddressesAction = new QAction(QIcon(":/icons/address-book"), tr("&Receiving addresses..."), this);
311
    usedReceivingAddressesAction->setStatusTip(tr("Show the list of used receiving addresses and labels"));
312

313
    openAction = new QAction(QApplication::style()->standardIcon(QStyle::SP_FileIcon), tr("Open &URI..."), this);
314
315
    openAction->setStatusTip(tr("Open a bitcoin: URI or payment request"));

316
317
318
    showHelpMessageAction = new QAction(QApplication::style()->standardIcon(QStyle::SP_MessageBoxInformation), tr("&Command-line options"), this);
    showHelpMessageAction->setStatusTip(tr("Show the Bitcoin Core help message to get a list with possible Bitcoin command-line options"));

319
320
    connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
    connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClicked()));
321
    connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
Philip Kaufmann's avatar
Philip Kaufmann committed
322
    connect(optionsAction, SIGNAL(triggered()), this, SLOT(optionsClicked()));
323
    connect(toggleHideAction, SIGNAL(triggered()), this, SLOT(toggleHidden()));
324
    connect(showHelpMessageAction, SIGNAL(triggered()), this, SLOT(showHelpMessageClicked()));
325
326
327
328
329
330
331
332
333
334
335
336
337
#ifdef ENABLE_WALLET
    if(walletFrame)
    {
        connect(encryptWalletAction, SIGNAL(triggered(bool)), walletFrame, SLOT(encryptWallet(bool)));
        connect(backupWalletAction, SIGNAL(triggered()), walletFrame, SLOT(backupWallet()));
        connect(changePassphraseAction, SIGNAL(triggered()), walletFrame, SLOT(changePassphrase()));
        connect(signMessageAction, SIGNAL(triggered()), this, SLOT(gotoSignMessageTab()));
        connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(gotoVerifyMessageTab()));
        connect(usedSendingAddressesAction, SIGNAL(triggered()), walletFrame, SLOT(usedSendingAddresses()));
        connect(usedReceivingAddressesAction, SIGNAL(triggered()), walletFrame, SLOT(usedReceivingAddresses()));
        connect(openAction, SIGNAL(triggered()), this, SLOT(openClicked()));
    }
#endif
Wladimir J. van der Laan's avatar
Wladimir J. van der Laan committed
338
339
}

340
341
void BitcoinGUI::createMenuBar()
{
Philip Kaufmann's avatar
Philip Kaufmann committed
342
#ifdef Q_OS_MAC
343
344
345
346
347
348
349
350
351
    // Create a decoupled menu bar on Mac which stays even if the window is closed
    appMenuBar = new QMenuBar();
#else
    // Get the main window's menu bar on other platforms
    appMenuBar = menuBar();
#endif

    // Configure the menus
    QMenu *file = appMenuBar->addMenu(tr("&File"));
352
353
354
355
356
357
358
359
360
361
362
    if(walletFrame)
    {
        file->addAction(openAction);
        file->addAction(backupWalletAction);
        file->addAction(signMessageAction);
        file->addAction(verifyMessageAction);
        file->addSeparator();
        file->addAction(usedSendingAddressesAction);
        file->addAction(usedReceivingAddressesAction);
        file->addSeparator();
    }
363
364
365
    file->addAction(quitAction);

    QMenu *settings = appMenuBar->addMenu(tr("&Settings"));
366
367
368
369
370
371
    if(walletFrame)
    {
        settings->addAction(encryptWalletAction);
        settings->addAction(changePassphraseAction);
        settings->addSeparator();
    }
372
373
374
    settings->addAction(optionsAction);

    QMenu *help = appMenuBar->addMenu(tr("&Help"));
375
376
377
378
    if(walletFrame)
    {
        help->addAction(openRPCConsoleAction);
    }
379
380
    help->addAction(showHelpMessageAction);
    help->addSeparator();
381
    help->addAction(aboutAction);
382
    help->addAction(aboutQtAction);
383
384
385
386
}

void BitcoinGUI::createToolBars()
{
387
388
389
390
391
392
393
394
395
396
    if(walletFrame)
    {
        QToolBar *toolbar = addToolBar(tr("Tabs toolbar"));
        toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
        toolbar->addAction(overviewAction);
        toolbar->addAction(sendCoinsAction);
        toolbar->addAction(receiveCoinsAction);
        toolbar->addAction(historyAction);
        overviewAction->setChecked(true);
    }
397
398
}

399
void BitcoinGUI::setClientModel(ClientModel *clientModel)
400
{
401
    this->clientModel = clientModel;
402
    if(clientModel)
403
    {
404
405
        // Create system tray menu (or setup the dock menu) that late to prevent users from calling actions,
        // while the client has not yet fully loaded
406
        createTrayIconMenu();
407

408
409
410
        // Keep up to date with client
        setNumConnections(clientModel->getNumConnections());
        connect(clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
411

412
413
        setNumBlocks(clientModel->getNumBlocks());
        connect(clientModel, SIGNAL(numBlocksChanged(int)), this, SLOT(setNumBlocks(int)));
414

415
        // Receive and report messages from client model
416
        connect(clientModel, SIGNAL(message(QString,QString,unsigned int)), this, SLOT(message(QString,QString,unsigned int)));
417

Cozz Lovan's avatar
Cozz Lovan committed
418
419
420
        // Show progress dialog
        connect(clientModel, SIGNAL(showProgress(QString,int)), this, SLOT(showProgress(QString,int)));

Philip Kaufmann's avatar
Philip Kaufmann committed
421
        rpcConsole->setClientModel(clientModel);
422
423
424
425
426
427
#ifdef ENABLE_WALLET
        if(walletFrame)
        {
            walletFrame->setClientModel(clientModel);
        }
#endif
428
429

        this->unitDisplayControl->setOptionsModel(clientModel->getOptionsModel());
430
    }
431
432
}

433
#ifdef ENABLE_WALLET
434
bool BitcoinGUI::addWallet(const QString& name, WalletModel *walletModel)
435
{
436
437
    if(!walletFrame)
        return false;
438
    setWalletActionsEnabled(true);
439
440
441
442
443
    return walletFrame->addWallet(name, walletModel);
}

bool BitcoinGUI::setCurrentWallet(const QString& name)
{
444
445
    if(!walletFrame)
        return false;
446
447
448
449
450
    return walletFrame->setCurrentWallet(name);
}

void BitcoinGUI::removeAllWallets()
{
451
452
    if(!walletFrame)
        return;
453
    setWalletActionsEnabled(false);
454
    walletFrame->removeAllWallets();
455
}
456
#endif
457

458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
void BitcoinGUI::setWalletActionsEnabled(bool enabled)
{
    overviewAction->setEnabled(enabled);
    sendCoinsAction->setEnabled(enabled);
    receiveCoinsAction->setEnabled(enabled);
    historyAction->setEnabled(enabled);
    encryptWalletAction->setEnabled(enabled);
    backupWalletAction->setEnabled(enabled);
    changePassphraseAction->setEnabled(enabled);
    signMessageAction->setEnabled(enabled);
    verifyMessageAction->setEnabled(enabled);
    usedSendingAddressesAction->setEnabled(enabled);
    usedReceivingAddressesAction->setEnabled(enabled);
    openAction->setEnabled(enabled);
}

474
void BitcoinGUI::createTrayIcon(bool fIsTestnet)
Wladimir J. van der Laan's avatar
Wladimir J. van der Laan committed
475
{
Philip Kaufmann's avatar
Philip Kaufmann committed
476
#ifndef Q_OS_MAC
Wladimir J. van der Laan's avatar
Wladimir J. van der Laan committed
477
    trayIcon = new QSystemTrayIcon(this);
478

479
480
481
482
483
484
485
486
487
488
489
    if (!fIsTestnet)
    {
        trayIcon->setToolTip(tr("Bitcoin client"));
        trayIcon->setIcon(QIcon(":/icons/toolbar"));
    }
    else
    {
        trayIcon->setToolTip(tr("Bitcoin client") + " " + tr("[testnet]"));
        trayIcon->setIcon(QIcon(":/icons/toolbar_testnet"));
    }

490
491
492
    trayIcon->show();
#endif

493
    notificator = new Notificator(QApplication::applicationName(), trayIcon, this);
494
495
496
497
498
499
}

void BitcoinGUI::createTrayIconMenu()
{
    QMenu *trayIconMenu;
#ifndef Q_OS_MAC
500
501
502
503
    // return if trayIcon is unset (only on non-Mac OSes)
    if (!trayIcon)
        return;

504
505
506
    trayIconMenu = new QMenu(this);
    trayIcon->setContextMenu(trayIconMenu);

507
508
    connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
            this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason)));
509
510
511
#else
    // Note: On Mac, the dock icon is used to provide the tray's functionality.
    MacDockIconHandler *dockIconHandler = MacDockIconHandler::instance();
512
    dockIconHandler->setMainWindow((QMainWindow *)this);
513
514
515
516
    trayIconMenu = dockIconHandler->dockMenu();
#endif

    // Configuration of the tray icon (or dock icon) icon menu
517
    trayIconMenu->addAction(toggleHideAction);
518
    trayIconMenu->addSeparator();
519
520
    trayIconMenu->addAction(sendCoinsAction);
    trayIconMenu->addAction(receiveCoinsAction);
521
    trayIconMenu->addSeparator();
522
    trayIconMenu->addAction(signMessageAction);
523
    trayIconMenu->addAction(verifyMessageAction);
524
525
    trayIconMenu->addSeparator();
    trayIconMenu->addAction(optionsAction);
526
    trayIconMenu->addAction(openRPCConsoleAction);
Philip Kaufmann's avatar
Philip Kaufmann committed
527
#ifndef Q_OS_MAC // This is built-in on Mac
528
529
530
    trayIconMenu->addSeparator();
    trayIconMenu->addAction(quitAction);
#endif
Wladimir J. van der Laan's avatar
Wladimir J. van der Laan committed
531
532
}

Philip Kaufmann's avatar
Philip Kaufmann committed
533
#ifndef Q_OS_MAC
534
535
void BitcoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
536
    if(reason == QSystemTrayIcon::Trigger)
537
    {
538
        // Click on system tray icon triggers show/hide of the main window
539
        toggleHideAction->trigger();
540
541
    }
}
542
#endif
543

544
545
void BitcoinGUI::optionsClicked()
{
546
547
    if(!clientModel || !clientModel->getOptionsModel())
        return;
548
549

    OptionsDialog dlg(this);
550
    dlg.setModel(clientModel->getOptionsModel());
551
    dlg.exec();
552
553
}

554
void BitcoinGUI::aboutClicked()
555
{
556
557
558
    if(!clientModel)
        return;

559
    HelpMessageDialog dlg(this, true);
560
    dlg.exec();
561
562
}

563
564
void BitcoinGUI::showHelpMessageClicked()
{
565
    HelpMessageDialog *help = new HelpMessageDialog(this, false);
566
567
568
569
    help->setAttribute(Qt::WA_DeleteOnClose);
    help->show();
}

570
#ifdef ENABLE_WALLET
571
572
void BitcoinGUI::openClicked()
{
573
    OpenURIDialog dlg(this);
574
575
576
577
578
579
    if(dlg.exec())
    {
        emit receivedURI(dlg.getURI());
    }
}

580
581
void BitcoinGUI::gotoOverviewPage()
{
582
    overviewAction->setChecked(true);
583
584
585
586
587
    if (walletFrame) walletFrame->gotoOverviewPage();
}

void BitcoinGUI::gotoHistoryPage()
{
588
    historyAction->setChecked(true);
589
590
591
592
593
    if (walletFrame) walletFrame->gotoHistoryPage();
}

void BitcoinGUI::gotoReceiveCoinsPage()
{
594
    receiveCoinsAction->setChecked(true);
595
596
597
    if (walletFrame) walletFrame->gotoReceiveCoinsPage();
}

598
void BitcoinGUI::gotoSendCoinsPage(QString addr)
599
{
600
    sendCoinsAction->setChecked(true);
601
    if (walletFrame) walletFrame->gotoSendCoinsPage(addr);
602
603
604
605
606
607
608
609
610
}

void BitcoinGUI::gotoSignMessageTab(QString addr)
{
    if (walletFrame) walletFrame->gotoSignMessageTab(addr);
}

void BitcoinGUI::gotoVerifyMessageTab(QString addr)
{
611
    if (walletFrame) walletFrame->gotoVerifyMessageTab(addr);
612
}
613
#endif
614

615
616
void BitcoinGUI::setNumConnections(int count)
{
617
618
619
    QString icon;
    switch(count)
    {
620
621
622
623
624
    case 0: icon = ":/icons/connect_0"; break;
    case 1: case 2: case 3: icon = ":/icons/connect_1"; break;
    case 4: case 5: case 6: icon = ":/icons/connect_2"; break;
    case 7: case 8: case 9: icon = ":/icons/connect_3"; break;
    default: icon = ":/icons/connect_4"; break;
625
    }
626
    labelConnectionsIcon->setPixmap(QIcon(icon).pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
Wladimir J. van der Laan's avatar
Wladimir J. van der Laan committed
627
    labelConnectionsIcon->setToolTip(tr("%n active connection(s) to Bitcoin network", "", count));
628
629
}

630
void BitcoinGUI::setNumBlocks(int count)
631
{
632
633
634
    // Prevent orphan statusbar messages (e.g. hover Quit in main menu, wait until chain-sync starts -> garbelled text)
    statusBar()->clearMessage();

635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
    // Acquire current block source
    enum BlockSource blockSource = clientModel->getBlockSource();
    switch (blockSource) {
        case BLOCK_SOURCE_NETWORK:
            progressBarLabel->setText(tr("Synchronizing with network..."));
            break;
        case BLOCK_SOURCE_DISK:
            progressBarLabel->setText(tr("Importing blocks from disk..."));
            break;
        case BLOCK_SOURCE_REINDEX:
            progressBarLabel->setText(tr("Reindexing blocks on disk..."));
            break;
        case BLOCK_SOURCE_NONE:
            // Case: not Importing, not Reindexing and no network connection
            progressBarLabel->setText(tr("No block source available..."));
            break;
651
652
    }

653
654
    QString tooltip;

655
    QDateTime lastBlockDate = clientModel->getLastBlockDate();
656
657
    QDateTime currentDate = QDateTime::currentDateTime();
    int secs = lastBlockDate.secsTo(currentDate);
658

659
    tooltip = tr("Processed %1 blocks of transaction history.").arg(count);
660

661
    // Set icon state: spinning if catching up, tick otherwise
662
    if(secs < 90*60)
663
    {
664
        tooltip = tr("Up to date") + QString(".<br>") + tooltip;
665
        labelBlocksIcon->setPixmap(QIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
666

667
668
669
670
#ifdef ENABLE_WALLET
        if(walletFrame)
            walletFrame->showOutOfSyncWarning(false);
#endif
671
672
673

        progressBarLabel->setVisible(false);
        progressBar->setVisible(false);
674
    }
675
676
    else
    {
677
678
        // Represent time from last generated block in human readable text
        QString timeBehindText;
679
680
681
682
683
        const int HOUR_IN_SECONDS = 60*60;
        const int DAY_IN_SECONDS = 24*60*60;
        const int WEEK_IN_SECONDS = 7*24*60*60;
        const int YEAR_IN_SECONDS = 31556952; // Average length of year in Gregorian calendar
        if(secs < 2*DAY_IN_SECONDS)
684
        {
685
            timeBehindText = tr("%n hour(s)","",secs/HOUR_IN_SECONDS);
686
        }
687
        else if(secs < 2*WEEK_IN_SECONDS)
688
        {
689
690
691
692
693
            timeBehindText = tr("%n day(s)","",secs/DAY_IN_SECONDS);
        }
        else if(secs < YEAR_IN_SECONDS)
        {
            timeBehindText = tr("%n week(s)","",secs/WEEK_IN_SECONDS);
694
695
696
        }
        else
        {
697
698
699
            int years = secs / YEAR_IN_SECONDS;
            int remainder = secs % YEAR_IN_SECONDS;
            timeBehindText = tr("%1 and %2").arg(tr("%n year(s)", "", years)).arg(tr("%n week(s)","", remainder/WEEK_IN_SECONDS));
700
701
702
703
        }

        progressBarLabel->setVisible(true);
        progressBar->setFormat(tr("%1 behind").arg(timeBehindText));
704
705
        progressBar->setMaximum(1000000000);
        progressBar->setValue(clientModel->getVerificationProgress() * 1000000000.0 + 0.5);
706
707
        progressBar->setVisible(true);

708
        tooltip = tr("Catching up...") + QString("<br>") + tooltip;
709
        if(count != prevBlocks)
710
711
712
713
714
715
        {
            labelBlocksIcon->setPixmap(QIcon(QString(
                ":/movies/spinner-%1").arg(spinnerFrame, 3, 10, QChar('0')))
                .pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
            spinnerFrame = (spinnerFrame + 1) % SPINNER_FRAMES;
        }
716
        prevBlocks = count;
717

718
719
720
721
#ifdef ENABLE_WALLET
        if(walletFrame)
            walletFrame->showOutOfSyncWarning(true);
#endif
722

723
        tooltip += QString("<br>");
724
725
726
        tooltip += tr("Last received block was generated %1 ago.").arg(timeBehindText);
        tooltip += QString("<br>");
        tooltip += tr("Transactions after this will not yet be visible.");
727
    }
728

729
730
731
    // Don't word-wrap this (fixed-width) tooltip
    tooltip = QString("<nobr>") + tooltip + QString("</nobr>");

732
    labelBlocksIcon->setToolTip(tooltip);
733
734
    progressBarLabel->setToolTip(tooltip);
    progressBar->setToolTip(tooltip);
735
736
}

737
void BitcoinGUI::message(const QString &title, const QString &message, unsigned int style, bool *ret)
Wladimir J. van der Laan's avatar
Wladimir J. van der Laan committed
738
{
739
    QString strTitle = tr("Bitcoin"); // default title
740
741
742
743
    // Default to information icon
    int nMBoxIcon = QMessageBox::Information;
    int nNotifyIcon = Notificator::Information;

744
    QString msgType;
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763

    // Prefer supplied title over style based title
    if (!title.isEmpty()) {
        msgType = title;
    }
    else {
        switch (style) {
        case CClientUIInterface::MSG_ERROR:
            msgType = tr("Error");
            break;
        case CClientUIInterface::MSG_WARNING:
            msgType = tr("Warning");
            break;
        case CClientUIInterface::MSG_INFORMATION:
            msgType = tr("Information");
            break;
        default:
            break;
        }
764
    }
765
    // Append title to "Bitcoin - "
766
767
    if (!msgType.isEmpty())
        strTitle += " - " + msgType;
768
769
770
771
772

    // Check for error/warning icon
    if (style & CClientUIInterface::ICON_ERROR) {
        nMBoxIcon = QMessageBox::Critical;
        nNotifyIcon = Notificator::Critical;
773
    }
774
775
776
777
778
779
    else if (style & CClientUIInterface::ICON_WARNING) {
        nMBoxIcon = QMessageBox::Warning;
        nNotifyIcon = Notificator::Warning;
    }

    // Display message
780
    if (style & CClientUIInterface::MODAL) {
781
782
783
784
785
        // Check for buttons, use OK as default, if none was supplied
        QMessageBox::StandardButton buttons;
        if (!(buttons = (QMessageBox::StandardButton)(style & CClientUIInterface::BTN_MASK)))
            buttons = QMessageBox::Ok;

786
        showNormalIfMinimized();
787
        QMessageBox mBox((QMessageBox::Icon)nMBoxIcon, strTitle, message, buttons, this);
788
789
790
        int r = mBox.exec();
        if (ret != NULL)
            *ret = r == QMessageBox::Ok;
791
792
793
    }
    else
        notificator->notify((Notificator::Class)nNotifyIcon, strTitle, message);
Wladimir J. van der Laan's avatar
Wladimir J. van der Laan committed
794
}
795
796
797

void BitcoinGUI::changeEvent(QEvent *e)
{
798
    QMainWindow::changeEvent(e);
Philip Kaufmann's avatar
Philip Kaufmann committed
799
#ifndef Q_OS_MAC // Ignored on Mac
800
    if(e->type() == QEvent::WindowStateChange)
801
    {
802
        if(clientModel && clientModel->getOptionsModel()->getMinimizeToTray())
803
        {
804
            QWindowStateChangeEvent *wsevt = static_cast<QWindowStateChangeEvent*>(e);
805
            if(!(wsevt->oldState() & Qt::WindowMinimized) && isMinimized())
806
            {
807
808
                QTimer::singleShot(0, this, SLOT(hide()));
                e->ignore();
809
810
811
            }
        }
    }
812
#endif
813
814
815
816
}

void BitcoinGUI::closeEvent(QCloseEvent *event)
{
817
    if(clientModel)
818
    {
Philip Kaufmann's avatar
Philip Kaufmann committed
819
#ifndef Q_OS_MAC // Ignored on Mac
820
821
822
        if(!clientModel->getOptionsModel()->getMinimizeToTray() &&
           !clientModel->getOptionsModel()->getMinimizeOnClose())
        {
823
            QApplication::quit();
824
        }
825
#endif
826
    }
827
828
    QMainWindow::closeEvent(event);
}
Wladimir J. van der Laan's avatar
ask fee    
Wladimir J. van der Laan committed
829

830
#ifdef ENABLE_WALLET
831
void BitcoinGUI::incomingTransaction(const QString& date, int unit, qint64 amount, const QString& type, const QString& address)
832
{
833
    // On new transaction, make an info balloon
834
835
836
837
838
839
    message((amount)<0 ? tr("Sent transaction") : tr("Incoming transaction"),
             tr("Date: %1\n"
                "Amount: %2\n"
                "Type: %3\n"
                "Address: %4\n")
                  .arg(date)
840
                  .arg(BitcoinUnits::formatWithUnit(unit, amount, true))
841
842
                  .arg(type)
                  .arg(address), CClientUIInterface::MSG_INFORMATION);
843
}
844
#endif
845

846
847
void BitcoinGUI::dragEnterEvent(QDragEnterEvent *event)
{
848
    // Accept only URIs
849
850
851
852
853
854
855
856
    if(event->mimeData()->hasUrls())
        event->acceptProposedAction();
}

void BitcoinGUI::dropEvent(QDropEvent *event)
{
    if(event->mimeData()->hasUrls())
    {
857
        foreach(const QUrl &uri, event->mimeData()->urls())
858
        {
859
            emit receivedURI(uri.toString());
860
861
862
863
864
        }
    }
    event->acceptProposedAction();
}

865
866
867
868
869
870
bool BitcoinGUI::eventFilter(QObject *object, QEvent *event)
{
    // Catch status tip events
    if (event->type() == QEvent::StatusTip)
    {
        // Prevent adding text from setStatusTip(), if we currently use the status bar for displaying other stuff
871
        if (progressBarLabel->isVisible() || progressBar->isVisible())
872
873
874
875
876
            return true;
    }
    return QMainWindow::eventFilter(object, event);
}

877
#ifdef ENABLE_WALLET
878
bool BitcoinGUI::handlePaymentRequest(const SendCoinsRecipient& recipient)
879
{
880
    // URI has to be valid
881
    if (walletFrame && walletFrame->handlePaymentRequest(recipient))
882
883
884
885
886
887
888
    {
        showNormalIfMinimized();
        gotoSendCoinsPage();
        return true;
    }
    else
        return false;
889
890
}

891
892
893
894
895
896
void BitcoinGUI::setEncryptionStatus(int status)
{
    switch(status)
    {
    case WalletModel::Unencrypted:
        labelEncryptionIcon->hide();
897
898
899
        encryptWalletAction->setChecked(false);
        changePassphraseAction->setEnabled(false);
        encryptWalletAction->setEnabled(true);
900
901
902
903
904
        break;
    case WalletModel::Unlocked:
        labelEncryptionIcon->show();
        labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
        labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b>"));
905
906
907
        encryptWalletAction->setChecked(true);
        changePassphraseAction->setEnabled(true);
        encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
908
909
910
911
912
        break;
    case WalletModel::Locked:
        labelEncryptionIcon->show();
        labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_closed").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
        labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>locked</b>"));
913
914
915
        encryptWalletAction->setChecked(true);
        changePassphraseAction->setEnabled(true);
        encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
916
917
918
        break;
    }
}
919
#endif
920

921
void BitcoinGUI::showNormalIfMinimized(bool fToggleHidden)
922
{
923
924
    if(!clientModel)
        return;
925
926
927
    // activateWindow() (sometimes) helps with keyboard focus on Windows
    if (isHidden())
    {
928
        show();
929
930
931
932
        activateWindow();
    }
    else if (isMinimized())
    {
933
        showNormal();
934
935
936
937
938
939
940
941
942
943
944
945
946
947
        activateWindow();
    }
    else if (GUIUtil::isObscured(this))
    {
        raise();
        activateWindow();
    }
    else if(fToggleHidden)
        hide();
}

void BitcoinGUI::toggleHidden()
{
    showNormalIfMinimized(true);
948
}
949
950
951
952

void BitcoinGUI::detectShutdown()
{
    if (ShutdownRequested())
953
954
955
956
957
    {
        if(rpcConsole)
            rpcConsole->hide();
        qApp->quit();
    }
958
}
959

Cozz Lovan's avatar
Cozz Lovan committed
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
void BitcoinGUI::showProgress(const QString &title, int nProgress)
{
    if (nProgress == 0)
    {
        progressDialog = new QProgressDialog(title, "", 0, 100);
        progressDialog->setWindowModality(Qt::ApplicationModal);
        progressDialog->setMinimumDuration(0);
        progressDialog->setCancelButton(0);
        progressDialog->setAutoClose(false);
        progressDialog->setValue(0);
    }
    else if (nProgress == 100)
    {
        if (progressDialog)
        {
            progressDialog->close();
            progressDialog->deleteLater();
        }
    }
    else if (progressDialog)
        progressDialog->setValue(nProgress);
}

983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
static bool ThreadSafeMessageBox(BitcoinGUI *gui, const std::string& message, const std::string& caption, unsigned int style)
{
    bool modal = (style & CClientUIInterface::MODAL);
    bool ret = false;
    // In case of modal message, use blocking connection to wait for user to click a button
    QMetaObject::invokeMethod(gui, "message",
                               modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
                               Q_ARG(QString, QString::fromStdString(caption)),
                               Q_ARG(QString, QString::fromStdString(message)),
                               Q_ARG(unsigned int, style),
                               Q_ARG(bool*, &ret));
    return ret;
}

void BitcoinGUI::subscribeToCoreSignals()
{
    // Connect signals to client
    uiInterface.ThreadSafeMessageBox.connect(boost::bind(ThreadSafeMessageBox, this, _1, _2, _3));
}

void BitcoinGUI::unsubscribeFromCoreSignals()
{
    // Disconnect signals from client
    uiInterface.ThreadSafeMessageBox.disconnect(boost::bind(ThreadSafeMessageBox, this, _1, _2, _3));
}
1008
1009
1010
1011
1012
1013
1014
1015

UnitDisplayStatusBarControl::UnitDisplayStatusBarControl():QLabel()
{
    optionsModel = 0;
    createContextMenu();
    setToolTip(tr("Unit to show amounts in. Click to select another unit."));
}

1016
/** So that it responds to button clicks */
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
void UnitDisplayStatusBarControl::mousePressEvent(QMouseEvent *event)
{
    onDisplayUnitsClicked(event->pos());
}

/** Creates context menu, its actions, and wires up all the relevant signals for mouse events. */
void UnitDisplayStatusBarControl::createContextMenu()
{
    menu = new QMenu();
    foreach(BitcoinUnits::Unit u, BitcoinUnits::availableUnits())
    {
        QAction *menuAction = new QAction(QString(BitcoinUnits::name(u)), this);
        menuAction->setData(QVariant(u));
        menu->addAction(menuAction);
    }
    connect(menu,SIGNAL(triggered(QAction*)),this,SLOT(onMenuSelection(QAction*)));
}

/** Lets the control know about the Options Model (and its signals) */
void UnitDisplayStatusBarControl::setOptionsModel(OptionsModel *optionsModel)
{
    if (optionsModel)
    {
        this->optionsModel = optionsModel;

        // be aware of a display unit change reported by the OptionsModel object.
        connect(optionsModel,SIGNAL(displayUnitChanged(int)),this,SLOT(updateDisplayUnit(int)));

        // initialize the display units label with the current value in the model.
        updateDisplayUnit(optionsModel->getDisplayUnit());
    }
}

/** When Display Units are changed on OptionsModel it will refresh the display text of the control on the status bar */
void UnitDisplayStatusBarControl::updateDisplayUnit(int newUnits)
{
1053
    setPixmap(QIcon(":/icons/unit_" + BitcoinUnits::id(newUnits)).pixmap(31,STATUSBAR_ICONSIZE));
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
}

/** Shows context menu with Display Unit options by the mouse coordinates */
void UnitDisplayStatusBarControl::onDisplayUnitsClicked(const QPoint& point)
{
    QPoint globalPos = mapToGlobal(point);
    menu->exec(globalPos);
}

/** Tells underlying optionsModel to update its current display unit. */
void UnitDisplayStatusBarControl::onMenuSelection(QAction* action)
{
    if (action)
    {
        optionsModel->setDisplayUnit(action->data());
    }
}