Qt 5 compatibility
[novacoin.git] / src / qt / bitcoingui.cpp
1 /*
2  * Qt4 bitcoin GUI.
3  *
4  * W.J. van der Laan 2011-2012
5  * The Bitcoin Developers 2011-2012
6  */
7 #include "bitcoingui.h"
8 #include "transactiontablemodel.h"
9 #include "addressbookpage.h"
10 #include "sendcoinsdialog.h"
11 #include "signverifymessagedialog.h"
12 #include "optionsdialog.h"
13 #include "aboutdialog.h"
14 #include "clientmodel.h"
15 #include "walletmodel.h"
16 #include "editaddressdialog.h"
17 #include "optionsmodel.h"
18 #include "transactiondescdialog.h"
19 #include "addresstablemodel.h"
20 #include "transactionview.h"
21 #include "overviewpage.h"
22 #include "bitcoinunits.h"
23 #include "guiconstants.h"
24 #include "askpassphrasedialog.h"
25 #include "notificator.h"
26 #include "guiutil.h"
27 #include "ui_interface.h"
28 #include "rpcconsole.h"
29
30 #ifdef Q_OS_MAC
31 #include "macdockiconhandler.h"
32 #endif
33
34 #include <QApplication>
35 #if QT_VERSION < 0x050000
36 #include <QMainWindow>
37 #endif
38 #include <QMenuBar>
39 #include <QMenu>
40 #include <QIcon>
41 #include <QTabWidget>
42 #include <QVBoxLayout>
43 #include <QToolBar>
44 #include <QStatusBar>
45 #include <QLabel>
46 #include <QLineEdit>
47 #include <QPushButton>
48 #include <QLocale>
49 #include <QMessageBox>
50 #include <QProgressBar>
51 #include <QStackedWidget>
52 #include <QDateTime>
53 #include <QMovie>
54 #include <QFileDialog>
55 #if QT_VERSION < 0x050000
56 #include <QDesktopServices>
57 #else
58 #include <QStandardPaths>
59 #endif
60 #include <QTimer>
61 #include <QDragEnterEvent>
62 #if QT_VERSION < 0x050000
63 #include <QUrl>
64 #endif
65 #include <QStyle>
66 #include <QMimeData>
67
68 #include <iostream>
69
70 extern bool fWalletUnlockMintOnly;
71
72 BitcoinGUI::BitcoinGUI(QWidget *parent):
73     QMainWindow(parent),
74     clientModel(0),
75     walletModel(0),
76     encryptWalletAction(0),
77     lockWalletAction(0),
78     unlockWalletAction(0),
79     unlockWalletMiningAction(0),
80     changePassphraseAction(0),
81     aboutQtAction(0),
82     trayIcon(0),
83     notificator(0),
84     rpcConsole(0)
85 {
86     resize(850, 550);
87     setWindowTitle(tr("NovaCoin") + " - " + tr("Wallet"));
88 #ifndef Q_OS_MAC
89     qApp->setWindowIcon(QIcon(":icons/bitcoin"));
90     setWindowIcon(QIcon(":icons/bitcoin"));
91 #else
92     setUnifiedTitleAndToolBarOnMac(true);
93     QApplication::setAttribute(Qt::AA_DontShowIconsInMenus);
94 #endif
95     // Accept D&D of URIs
96     setAcceptDrops(true);
97
98     // Create actions for the toolbar, menu bar and tray/dock icon
99     createActions();
100
101     // Create application menu bar
102     createMenuBar();
103
104     // Create the toolbars
105     createToolBars();
106
107     // Create the tray icon (or setup the dock icon)
108     createTrayIcon();
109
110     // Create tabs
111     overviewPage = new OverviewPage();
112
113     transactionsPage = new QWidget(this);
114     QVBoxLayout *vbox = new QVBoxLayout();
115     transactionView = new TransactionView(this);
116     vbox->addWidget(transactionView);
117     transactionsPage->setLayout(vbox);
118
119     addressBookPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab);
120
121     receiveCoinsPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab);
122
123     sendCoinsPage = new SendCoinsDialog(this);
124
125     signVerifyMessageDialog = new SignVerifyMessageDialog(this);
126
127     centralWidget = new QStackedWidget(this);
128     centralWidget->addWidget(overviewPage);
129     centralWidget->addWidget(transactionsPage);
130     centralWidget->addWidget(addressBookPage);
131     centralWidget->addWidget(receiveCoinsPage);
132     centralWidget->addWidget(sendCoinsPage);
133     setCentralWidget(centralWidget);
134
135     // Create status bar
136     statusBar();
137
138     // Status bar notification icons
139     QFrame *frameBlocks = new QFrame();
140     frameBlocks->setContentsMargins(0,0,0,0);
141     frameBlocks->setMinimumWidth(72);
142     frameBlocks->setMaximumWidth(72);
143     QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks);
144     frameBlocksLayout->setContentsMargins(3,0,3,0);
145     frameBlocksLayout->setSpacing(3);
146     labelEncryptionIcon = new QLabel();
147     labelMiningIcon = new QLabel();
148     labelConnectionsIcon = new QLabel();
149     labelBlocksIcon = new QLabel();
150     frameBlocksLayout->addStretch();
151     frameBlocksLayout->addWidget(labelEncryptionIcon);
152     frameBlocksLayout->addStretch();
153     frameBlocksLayout->addWidget(labelMiningIcon);
154     frameBlocksLayout->addStretch();
155     frameBlocksLayout->addWidget(labelConnectionsIcon);
156     frameBlocksLayout->addStretch();
157     frameBlocksLayout->addWidget(labelBlocksIcon);
158     frameBlocksLayout->addStretch();
159
160     // Progress bar and label for blocks download
161     progressBarLabel = new QLabel();
162     progressBarLabel->setVisible(false);
163     progressBar = new QProgressBar();
164     progressBar->setAlignment(Qt::AlignCenter);
165     progressBar->setVisible(false);
166
167     // Override style sheet for progress bar for styles that have a segmented progress bar,
168     // as they make the text unreadable (workaround for issue #1071)
169     // See https://qt-project.org/doc/qt-4.8/gallery.html
170     QString curStyle = qApp->style()->metaObject()->className();
171     if(curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle")
172     {
173         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; }");
174     }
175
176     statusBar()->addWidget(progressBarLabel);
177     statusBar()->addWidget(progressBar);
178     statusBar()->addPermanentWidget(frameBlocks);
179
180     syncIconMovie = new QMovie(":/movies/update_spinner", "mng", this);
181
182     // Clicking on a transaction on the overview page simply sends you to transaction history page
183     connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), this, SLOT(gotoHistoryPage()));
184     connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), transactionView, SLOT(focusTransaction(QModelIndex)));
185
186     // Double-clicking on a transaction on the transaction history page shows details
187     connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails()));
188
189     rpcConsole = new RPCConsole(this);
190     connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(show()));
191
192     // Clicking on "Verify Message" in the address book sends you to the verify message tab
193     connect(addressBookPage, SIGNAL(verifyMessage(QString)), this, SLOT(gotoVerifyMessageTab(QString)));
194     // Clicking on "Sign Message" in the receive coins page sends you to the sign message tab
195     connect(receiveCoinsPage, SIGNAL(signMessage(QString)), this, SLOT(gotoSignMessageTab(QString)));
196
197     gotoOverviewPage();
198 }
199
200 BitcoinGUI::~BitcoinGUI()
201 {
202     if(trayIcon) // Hide tray icon, as deleting will let it linger until quit (on Ubuntu)
203         trayIcon->hide();
204 #ifdef Q_OS_MAC
205     delete appMenuBar;
206 #endif
207 }
208
209 void BitcoinGUI::createActions()
210 {
211     QActionGroup *tabGroup = new QActionGroup(this);
212
213     overviewAction = new QAction(QIcon(":/icons/overview"), tr("&Overview"), this);
214     overviewAction->setToolTip(tr("Show general overview of wallet"));
215     overviewAction->setCheckable(true);
216     overviewAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1));
217     tabGroup->addAction(overviewAction);
218
219     sendCoinsAction = new QAction(QIcon(":/icons/send"), tr("&Send coins"), this);
220     sendCoinsAction->setToolTip(tr("Send coins to a NovaCoin address"));
221     sendCoinsAction->setCheckable(true);
222     sendCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2));
223     tabGroup->addAction(sendCoinsAction);
224
225     receiveCoinsAction = new QAction(QIcon(":/icons/receiving_addresses"), tr("&Receive coins"), this);
226     receiveCoinsAction->setToolTip(tr("Show the list of addresses for receiving payments"));
227     receiveCoinsAction->setCheckable(true);
228     receiveCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_3));
229     tabGroup->addAction(receiveCoinsAction);
230
231     historyAction = new QAction(QIcon(":/icons/history"), tr("&Transactions"), this);
232     historyAction->setToolTip(tr("Browse transaction history"));
233     historyAction->setCheckable(true);
234     historyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_4));
235     tabGroup->addAction(historyAction);
236
237     addressBookAction = new QAction(QIcon(":/icons/address-book"), tr("&Address Book"), this);
238     addressBookAction->setToolTip(tr("Edit the list of stored addresses and labels"));
239     addressBookAction->setCheckable(true);
240     addressBookAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_5));
241     tabGroup->addAction(addressBookAction);
242
243     connect(overviewAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
244     connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage()));
245     connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
246     connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage()));
247     connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
248     connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage()));
249     connect(historyAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
250     connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage()));
251     connect(addressBookAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
252     connect(addressBookAction, SIGNAL(triggered()), this, SLOT(gotoAddressBookPage()));
253
254     quitAction = new QAction(QIcon(":/icons/quit"), tr("E&xit"), this);
255     quitAction->setToolTip(tr("Quit application"));
256     quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q));
257     quitAction->setMenuRole(QAction::QuitRole);
258     aboutAction = new QAction(QIcon(":/icons/bitcoin"), tr("&About NovaCoin"), this);
259     aboutAction->setToolTip(tr("Show information about NovaCoin"));
260     aboutAction->setMenuRole(QAction::AboutRole);
261     aboutQtAction = new QAction(QIcon(":/trolltech/qmessagebox/images/qtlogo-64.png"), tr("About &Qt"), this);
262     aboutQtAction->setToolTip(tr("Show information about Qt"));
263     aboutQtAction->setMenuRole(QAction::AboutQtRole);
264     optionsAction = new QAction(QIcon(":/icons/options"), tr("&Options..."), this);
265     optionsAction->setToolTip(tr("Modify configuration options for NovaCoin"));
266     optionsAction->setMenuRole(QAction::PreferencesRole);
267     toggleHideAction = new QAction(QIcon(":/icons/bitcoin"), tr("&Show / Hide"), this);
268     encryptWalletAction = new QAction(QIcon(":/icons/lock_closed"), tr("&Encrypt Wallet..."), this);
269     encryptWalletAction->setToolTip(tr("Encrypt or decrypt wallet"));
270     encryptWalletAction->setCheckable(true);
271     backupWalletAction = new QAction(QIcon(":/icons/filesave"), tr("&Backup Wallet..."), this);
272     backupWalletAction->setToolTip(tr("Backup wallet to another location"));
273     dumpWalletAction = new QAction(QIcon(":/icons/dump"), tr("&Dump Wallet..."), this);
274     dumpWalletAction->setStatusTip(tr("Dump keys to a text file"));
275     importWalletAction = new QAction(QIcon(":/icons/import"), tr("&Import Wallet..."), this);
276     importWalletAction->setStatusTip(tr("Import keys into a wallet"));
277     changePassphraseAction = new QAction(QIcon(":/icons/key"), tr("&Change Passphrase..."), this);
278     changePassphraseAction->setToolTip(tr("Change the passphrase used for wallet encryption"));
279     signMessageAction = new QAction(QIcon(":/icons/edit"), tr("Sign &message..."), this);
280     verifyMessageAction = new QAction(QIcon(":/icons/transaction_0"), tr("&Verify message..."), this);
281
282     lockWalletAction = new QAction(QIcon(":/icons/lock_closed"), tr("&Lock wallet"), this);
283     lockWalletAction->setToolTip(tr("Lock wallet"));
284     lockWalletAction->setCheckable(true);
285
286     unlockWalletAction = new QAction(QIcon(":/icons/lock_open"), tr("Unlo&ck wallet"), this);
287     unlockWalletAction->setToolTip(tr("Unlock wallet"));
288     unlockWalletAction->setCheckable(true);
289
290     unlockWalletMiningAction = new QAction(QIcon(":/icons/mining_active"), tr("Unlo&ck wallet for mining"), this);
291     unlockWalletMiningAction->setToolTip(tr("Unlock wallet for mining"));
292     unlockWalletMiningAction->setCheckable(true);
293
294     exportAction = new QAction(QIcon(":/icons/export"), tr("&Export..."), this);
295     exportAction->setToolTip(tr("Export the data in the current tab to a file"));
296     openRPCConsoleAction = new QAction(QIcon(":/icons/debugwindow"), tr("&Debug window"), this);
297     openRPCConsoleAction->setToolTip(tr("Open debugging and diagnostic console"));
298
299     connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
300     connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClicked()));
301     connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
302     connect(optionsAction, SIGNAL(triggered()), this, SLOT(optionsClicked()));
303     connect(toggleHideAction, SIGNAL(triggered()), this, SLOT(toggleHidden()));
304     connect(encryptWalletAction, SIGNAL(triggered(bool)), this, SLOT(encryptWallet(bool)));
305     connect(lockWalletAction, SIGNAL(triggered(bool)), this, SLOT(lockWallet()));
306     connect(unlockWalletAction, SIGNAL(triggered(bool)), this, SLOT(unlockWallet()));
307     connect(unlockWalletMiningAction, SIGNAL(triggered(bool)), this, SLOT(unlockWalletMining(bool)));
308     connect(backupWalletAction, SIGNAL(triggered()), this, SLOT(backupWallet()));
309     connect(dumpWalletAction, SIGNAL(triggered()), this, SLOT(dumpWallet()));
310     connect(importWalletAction, SIGNAL(triggered()), this, SLOT(importWallet()));
311     connect(changePassphraseAction, SIGNAL(triggered()), this, SLOT(changePassphrase()));
312     connect(signMessageAction, SIGNAL(triggered()), this, SLOT(gotoSignMessageTab()));
313     connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(gotoVerifyMessageTab()));
314 }
315
316 void BitcoinGUI::createMenuBar()
317 {
318 #ifdef Q_OS_MAC
319     // Create a decoupled menu bar on Mac which stays even if the window is closed
320     appMenuBar = new QMenuBar();
321 #else
322     // Get the main window's menu bar on other platforms
323     appMenuBar = menuBar();
324 #endif
325
326     // Configure the menus
327     QMenu *file = appMenuBar->addMenu(tr("&File"));
328     file->addAction(backupWalletAction);
329     file->addSeparator();
330     file->addAction(dumpWalletAction);
331     file->addAction(importWalletAction);
332     file->addAction(exportAction);
333     file->addAction(signMessageAction);
334     file->addAction(verifyMessageAction);
335     file->addSeparator();
336     file->addAction(quitAction);
337
338     QMenu *settings = appMenuBar->addMenu(tr("&Settings"));
339     QMenu *securityMenu = settings->addMenu(QIcon(":/icons/key"), tr("&Wallet security"));
340     securityMenu->addAction(encryptWalletAction);
341     securityMenu->addAction(changePassphraseAction);
342     securityMenu->addAction(unlockWalletAction);
343     securityMenu->addAction(unlockWalletMiningAction);
344     securityMenu->addAction(lockWalletAction);
345     settings->addAction(optionsAction);
346
347     QMenu *help = appMenuBar->addMenu(tr("&Help"));
348     help->addAction(openRPCConsoleAction);
349     help->addSeparator();
350     help->addAction(aboutAction);
351     help->addAction(aboutQtAction);
352 }
353
354 void BitcoinGUI::createToolBars()
355 {
356     QToolBar *toolbar = addToolBar(tr("Tabs toolbar"));
357     toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
358     toolbar->addAction(overviewAction);
359     toolbar->addAction(sendCoinsAction);
360     toolbar->addAction(receiveCoinsAction);
361     toolbar->addAction(historyAction);
362     toolbar->addAction(addressBookAction);
363
364     QToolBar *toolbar2 = addToolBar(tr("Actions toolbar"));
365     toolbar2->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
366     toolbar2->addAction(exportAction);
367 }
368
369 void BitcoinGUI::setClientModel(ClientModel *clientModel)
370 {
371     this->clientModel = clientModel;
372     if(clientModel)
373     {
374         // Replace some strings and icons, when using the testnet
375         if(clientModel->isTestNet())
376         {
377             setWindowTitle(windowTitle() + QString(" ") + tr("[testnet]"));
378 #ifndef Q_OS_MAC
379             qApp->setWindowIcon(QIcon(":icons/bitcoin_testnet"));
380             setWindowIcon(QIcon(":icons/bitcoin_testnet"));
381 #else
382             MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin_testnet"));
383 #endif
384             if(trayIcon)
385             {
386                 trayIcon->setToolTip(tr("NovaCoin client") + QString(" ") + tr("[testnet]"));
387                 trayIcon->setIcon(QIcon(":/icons/toolbar_testnet"));
388                 toggleHideAction->setIcon(QIcon(":/icons/toolbar_testnet"));
389             }
390
391             aboutAction->setIcon(QIcon(":/icons/toolbar_testnet"));
392         }
393
394         // Keep up to date with client
395         setNumConnections(clientModel->getNumConnections());
396         connect(clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
397
398         setNumBlocks(clientModel->getNumBlocks(), clientModel->getNumBlocksOfPeers());
399         connect(clientModel, SIGNAL(numBlocksChanged(int,int)), this, SLOT(setNumBlocks(int,int)));
400         connect(clientModel, SIGNAL(numBlocksChanged(int,int)), this, SLOT(updateMining()));
401
402         // Report errors from network/worker thread
403         connect(clientModel, SIGNAL(error(QString,QString,bool)), this, SLOT(error(QString,QString,bool)));
404
405         rpcConsole->setClientModel(clientModel);
406         addressBookPage->setOptionsModel(clientModel->getOptionsModel());
407         receiveCoinsPage->setOptionsModel(clientModel->getOptionsModel());
408     }
409 }
410
411 void BitcoinGUI::setWalletModel(WalletModel *walletModel)
412 {
413     this->walletModel = walletModel;
414     if(walletModel)
415     {
416         // Report errors from wallet thread
417         connect(walletModel, SIGNAL(error(QString,QString,bool)), this, SLOT(error(QString,QString,bool)));
418
419         // Put transaction list in tabs
420         transactionView->setModel(walletModel);
421
422         overviewPage->setModel(walletModel);
423         addressBookPage->setModel(walletModel->getAddressTableModel());
424         receiveCoinsPage->setModel(walletModel->getAddressTableModel());
425         sendCoinsPage->setModel(walletModel);
426         signVerifyMessageDialog->setModel(walletModel);
427
428         setEncryptionStatus(walletModel->getEncryptionStatus());
429         connect(walletModel, SIGNAL(encryptionStatusChanged(int)), this, SLOT(setEncryptionStatus(int)));
430         connect(walletModel, SIGNAL(encryptionStatusChanged(int)), this, SLOT(updateMining()));
431
432         // Balloon pop-up for new transaction
433         connect(walletModel->getTransactionTableModel(), SIGNAL(rowsInserted(QModelIndex,int,int)),
434                 this, SLOT(incomingTransaction(QModelIndex,int,int)));
435
436         // Ask for passphrase if needed
437         connect(walletModel, SIGNAL(requireUnlock()), this, SLOT(unlockWallet()));
438     }
439 }
440
441 void BitcoinGUI::createTrayIcon()
442 {
443     QMenu *trayIconMenu;
444 #ifndef Q_OS_MAC
445     trayIcon = new QSystemTrayIcon(this);
446     trayIconMenu = new QMenu(this);
447     trayIcon->setContextMenu(trayIconMenu);
448     trayIcon->setToolTip(tr("NovaCoin client"));
449     trayIcon->setIcon(QIcon(":/icons/toolbar"));
450     connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
451             this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason)));
452     trayIcon->show();
453 #else
454     // Note: On Mac, the dock icon is used to provide the tray's functionality.
455     MacDockIconHandler *dockIconHandler = MacDockIconHandler::instance();
456     trayIconMenu = dockIconHandler->dockMenu();
457 #endif
458
459     // Configuration of the tray icon (or dock icon) icon menu
460     trayIconMenu->addAction(toggleHideAction);
461     trayIconMenu->addSeparator();
462     trayIconMenu->addAction(sendCoinsAction);
463     trayIconMenu->addAction(receiveCoinsAction);
464     trayIconMenu->addSeparator();
465     trayIconMenu->addAction(signMessageAction);
466     trayIconMenu->addAction(verifyMessageAction);
467     trayIconMenu->addSeparator();
468     trayIconMenu->addAction(optionsAction);
469     trayIconMenu->addAction(openRPCConsoleAction);
470 #ifndef Q_OS_MAC // This is built-in on Mac
471     trayIconMenu->addSeparator();
472     trayIconMenu->addAction(quitAction);
473 #endif
474
475     notificator = new Notificator(qApp->applicationName(), trayIcon);
476 }
477
478 #ifndef Q_OS_MAC
479 void BitcoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason)
480 {
481     if(reason == QSystemTrayIcon::Trigger)
482     {
483         // Click on system tray icon triggers show/hide of the main window
484         toggleHideAction->trigger();
485     }
486 }
487 #endif
488
489 void BitcoinGUI::optionsClicked()
490 {
491     if(!clientModel || !clientModel->getOptionsModel())
492         return;
493     OptionsDialog dlg;
494     dlg.setModel(clientModel->getOptionsModel());
495     dlg.exec();
496 }
497
498 void BitcoinGUI::aboutClicked()
499 {
500     AboutDialog dlg;
501     dlg.setModel(clientModel);
502     dlg.exec();
503 }
504
505 void BitcoinGUI::setNumConnections(int count)
506 {
507     QString icon;
508     switch(count)
509     {
510     case 0: icon = ":/icons/connect_0"; break;
511     case 1: case 2: case 3: icon = ":/icons/connect_1"; break;
512     case 4: case 5: case 6: icon = ":/icons/connect_2"; break;
513     case 7: case 8: case 9: icon = ":/icons/connect_3"; break;
514     default: icon = ":/icons/connect_4"; break;
515     }
516     labelConnectionsIcon->setPixmap(QIcon(icon).pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
517     labelConnectionsIcon->setToolTip(tr("%n active connection(s) to NovaCoin network", "", count));
518 }
519
520 void BitcoinGUI::setNumBlocks(int count, int nTotalBlocks)
521 {
522     // don't show / hide progress bar and its label if we have no connection to the network
523     if (!clientModel || clientModel->getNumConnections() == 0)
524     {
525         progressBarLabel->setVisible(false);
526         progressBar->setVisible(false);
527
528         return;
529     }
530
531     QString strStatusBarWarnings = clientModel->getStatusBarWarnings();
532     QString tooltip;
533
534     if(count < nTotalBlocks)
535     {
536         int nRemainingBlocks = nTotalBlocks - count;
537         float nPercentageDone = count / (nTotalBlocks * 0.01f);
538
539         if (strStatusBarWarnings.isEmpty())
540         {
541             progressBarLabel->setText(tr("Synchronizing with network..."));
542             progressBarLabel->setVisible(true);
543             progressBar->setFormat(tr("~%n block(s) remaining", "", nRemainingBlocks));
544             progressBar->setMaximum(nTotalBlocks);
545             progressBar->setValue(count);
546             progressBar->setVisible(true);
547         }
548
549         tooltip = tr("Downloaded %1 of %2 blocks of transaction history (%3% done).").arg(count).arg(nTotalBlocks).arg(nPercentageDone, 0, 'f', 2);
550     }
551     else
552     {
553         if (strStatusBarWarnings.isEmpty())
554             progressBarLabel->setVisible(false);
555
556         progressBar->setVisible(false);
557         tooltip = tr("Downloaded %1 blocks of transaction history.").arg(count);
558     }
559
560     // Override progressBarLabel text and hide progress bar, when we have warnings to display
561     if (!strStatusBarWarnings.isEmpty())
562     {
563         progressBarLabel->setText(strStatusBarWarnings);
564         progressBarLabel->setVisible(true);
565         progressBar->setVisible(false);
566     }
567
568     QDateTime lastBlockDate = clientModel->getLastBlockDate();
569     int secs = lastBlockDate.secsTo(QDateTime::currentDateTime());
570     QString text;
571
572     // Represent time from last generated block in human readable text
573     if(secs <= 0)
574     {
575         // Fully up to date. Leave text empty.
576     }
577     else if(secs < 60)
578     {
579         text = tr("%n second(s) ago","",secs);
580     }
581     else if(secs < 60*60)
582     {
583         text = tr("%n minute(s) ago","",secs/60);
584     }
585     else if(secs < 24*60*60)
586     {
587         text = tr("%n hour(s) ago","",secs/(60*60));
588     }
589     else
590     {
591         text = tr("%n day(s) ago","",secs/(60*60*24));
592     }
593
594     // Set icon state: spinning if catching up, tick otherwise
595     if(secs < 90*60 && count >= nTotalBlocks)
596     {
597         tooltip = tr("Up to date") + QString(".<br>") + tooltip;
598         labelBlocksIcon->setPixmap(QIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
599
600         overviewPage->showOutOfSyncWarning(false);
601     }
602     else
603     {
604         tooltip = tr("Catching up...") + QString("<br>") + tooltip;
605         labelBlocksIcon->setMovie(syncIconMovie);
606         syncIconMovie->start();
607
608         overviewPage->showOutOfSyncWarning(true);
609     }
610
611     if(!text.isEmpty())
612     {
613         tooltip += QString("<br>");
614         tooltip += tr("Last received block was generated %1.").arg(text);
615     }
616
617     // Don't word-wrap this (fixed-width) tooltip
618     tooltip = QString("<nobr>") + tooltip + QString("</nobr>");
619
620     labelBlocksIcon->setToolTip(tooltip);
621     progressBarLabel->setToolTip(tooltip);
622     progressBar->setToolTip(tooltip);
623 }
624
625 void BitcoinGUI::updateMining()
626 {
627    if(!walletModel)
628       return;
629
630     labelMiningIcon->setPixmap(QIcon(":/icons/mining_inactive").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
631
632     if (!clientModel->getNumConnections())
633     {
634         labelMiningIcon->setToolTip(tr("Wallet is offline"));
635         return;
636     }
637
638     if (walletModel->getEncryptionStatus() == WalletModel::Locked)
639     {
640         labelMiningIcon->setToolTip(tr("Wallet is locked"));
641         return;
642     }
643
644     if (clientModel->inInitialBlockDownload() || clientModel->getNumBlocksOfPeers() > clientModel->getNumBlocks())
645     {
646         labelMiningIcon->setToolTip(tr("Blockchain download is in progress"));
647         return;
648     }
649
650     uint64 nMinWeight = 0, nMaxWeight = 0, nTotalWeight = 0;
651     walletModel->getStakeWeight(nMinWeight, nMaxWeight, nTotalWeight);
652
653     if (nTotalWeight > 0)
654     {
655         labelMiningIcon->setPixmap(QIcon(":/icons/mining_active").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
656
657         uint64 nNetworkWeight = clientModel->getPoSKernelPS();
658 /*
659         double dDifficulty = clientModel->getDifficulty(true);
660         QString msg;
661
662         int nApproxTime = 4294967297 * dDifficulty / nTotalWeight;
663
664         if (nApproxTime < 60)
665             msg = tr("%n second(s)", "", nApproxTime);
666         else if (nApproxTime < 60*60)
667             msg = tr("%n minute(s)", "", nApproxTime / 60);
668         else if (nApproxTime < 24*60*60)
669             msg = tr("%n hour(s)", "", nApproxTime / 3600);
670         else
671             msg = tr("%n day(s)", "", nApproxTime / 86400);
672
673         labelMiningIcon->setToolTip(tr("Stake miner is active\nYour current stake weight is %1\nNetwork weight is %2\nAverage block generation time is %3").arg(nTotalWeight).arg(dNetworkWeight).arg(msg));
674 */
675
676         labelMiningIcon->setToolTip(tr("Stake miner is active\nYour current stake weight is %1\nNetwork weight is %2").arg(nTotalWeight).arg(nNetworkWeight));
677     }
678     else
679         labelMiningIcon->setToolTip(tr("No suitable inputs were found"));
680 }
681
682 void BitcoinGUI::error(const QString &title, const QString &message, bool modal)
683 {
684     // Report errors from network/worker thread
685     if(modal)
686     {
687         QMessageBox::critical(this, title, message, QMessageBox::Ok, QMessageBox::Ok);
688     } else {
689         notificator->notify(Notificator::Critical, title, message);
690     }
691 }
692
693 void BitcoinGUI::message(const QString &title, const QString &message, unsigned int style, const QString &detail)
694 {
695     QString strTitle = tr("NovaCoin") + " - ";
696     // Default to information icon
697     int nMBoxIcon = QMessageBox::Information;
698     int nNotifyIcon = Notificator::Information;
699
700
701     // Check for usage of predefined title
702     switch (style) {
703     case CClientUIInterface::MSG_ERROR:
704         strTitle += tr("Error");
705         break;
706     case CClientUIInterface::MSG_WARNING:
707         strTitle += tr("Warning");
708         break;
709     case CClientUIInterface::MSG_INFORMATION:
710         strTitle += tr("Information");
711         break;
712     default:
713         strTitle += title; // Use supplied title
714     }
715
716     // Check for error/warning icon
717     if (style & CClientUIInterface::ICON_ERROR) {
718         nMBoxIcon = QMessageBox::Critical;
719         nNotifyIcon = Notificator::Critical;
720     }
721     else if (style & CClientUIInterface::ICON_WARNING) {
722         nMBoxIcon = QMessageBox::Warning;
723         nNotifyIcon = Notificator::Warning;
724     }
725
726     // Display message
727     if (style & CClientUIInterface::MODAL) {
728         // Check for buttons, use OK as default, if none was supplied
729         QMessageBox::StandardButton buttons;
730         buttons = QMessageBox::Ok;
731
732         QMessageBox mBox((QMessageBox::Icon)nMBoxIcon, strTitle, message, buttons);
733
734         if(!detail.isEmpty()) { mBox.setDetailedText(detail); }
735
736         mBox.exec();
737     }
738     else
739         notificator->notify((Notificator::Class)nNotifyIcon, strTitle, message);
740 }
741
742
743 void BitcoinGUI::changeEvent(QEvent *e)
744 {
745     QMainWindow::changeEvent(e);
746 #ifndef Q_OS_MAC // Ignored on Mac
747     if(e->type() == QEvent::WindowStateChange)
748     {
749         if(clientModel && clientModel->getOptionsModel()->getMinimizeToTray())
750         {
751             QWindowStateChangeEvent *wsevt = static_cast<QWindowStateChangeEvent*>(e);
752             if(!(wsevt->oldState() & Qt::WindowMinimized) && isMinimized())
753             {
754                 QTimer::singleShot(0, this, SLOT(hide()));
755                 e->ignore();
756             }
757         }
758     }
759 #endif
760 }
761
762 void BitcoinGUI::closeEvent(QCloseEvent *event)
763 {
764     if(clientModel)
765     {
766 #ifndef Q_OS_MAC // Ignored on Mac
767         if(!clientModel->getOptionsModel()->getMinimizeToTray() &&
768            !clientModel->getOptionsModel()->getMinimizeOnClose())
769         {
770             qApp->quit();
771         }
772 #endif
773     }
774     QMainWindow::closeEvent(event);
775 }
776
777 void BitcoinGUI::askFee(qint64 nFeeRequired, bool *payFee)
778 {
779     QString strMessage =
780         tr("This transaction is over the size limit.  You can still send it for a fee of %1, "
781           "which goes to the nodes that process your transaction and helps to support the network.  "
782           "Do you want to pay the fee?").arg(
783                 BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, nFeeRequired));
784     QMessageBox::StandardButton retval = QMessageBox::question(
785           this, tr("Confirm transaction fee"), strMessage,
786           QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Yes);
787     *payFee = (retval == QMessageBox::Yes);
788 }
789
790 void BitcoinGUI::incomingTransaction(const QModelIndex & parent, int start, int end)
791 {
792     if(!walletModel || !clientModel)
793         return;
794     TransactionTableModel *ttm = walletModel->getTransactionTableModel();
795     qint64 amount = ttm->index(start, TransactionTableModel::Amount, parent)
796                     .data(Qt::EditRole).toULongLong();
797     if(!clientModel->inInitialBlockDownload())
798     {
799         // On new transaction, make an info balloon
800         // Unless the initial block download is in progress, to prevent balloon-spam
801         QString date = ttm->index(start, TransactionTableModel::Date, parent)
802                         .data().toString();
803         QString type = ttm->index(start, TransactionTableModel::Type, parent)
804                         .data().toString();
805         QString address = ttm->index(start, TransactionTableModel::ToAddress, parent)
806                         .data().toString();
807         QIcon icon = qvariant_cast<QIcon>(ttm->index(start,
808                             TransactionTableModel::ToAddress, parent)
809                         .data(Qt::DecorationRole));
810
811         notificator->notify(Notificator::Information,
812                             (amount)<0 ? tr("Sent transaction") :
813                                          tr("Incoming transaction"),
814                               tr("Date: %1\n"
815                                  "Amount: %2\n"
816                                  "Type: %3\n"
817                                  "Address: %4\n")
818                               .arg(date)
819                               .arg(BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), amount, true))
820                               .arg(type)
821                               .arg(address), icon);
822     }
823 }
824
825 void BitcoinGUI::gotoOverviewPage()
826 {
827     overviewAction->setChecked(true);
828     centralWidget->setCurrentWidget(overviewPage);
829
830     exportAction->setEnabled(false);
831     disconnect(exportAction, SIGNAL(triggered()), 0, 0);
832 }
833
834 void BitcoinGUI::gotoHistoryPage()
835 {
836     historyAction->setChecked(true);
837     centralWidget->setCurrentWidget(transactionsPage);
838
839     exportAction->setEnabled(true);
840     disconnect(exportAction, SIGNAL(triggered()), 0, 0);
841     connect(exportAction, SIGNAL(triggered()), transactionView, SLOT(exportClicked()));
842 }
843
844 void BitcoinGUI::gotoAddressBookPage()
845 {
846     addressBookAction->setChecked(true);
847     centralWidget->setCurrentWidget(addressBookPage);
848
849     exportAction->setEnabled(true);
850     disconnect(exportAction, SIGNAL(triggered()), 0, 0);
851     connect(exportAction, SIGNAL(triggered()), addressBookPage, SLOT(exportClicked()));
852 }
853
854 void BitcoinGUI::gotoReceiveCoinsPage()
855 {
856     receiveCoinsAction->setChecked(true);
857     centralWidget->setCurrentWidget(receiveCoinsPage);
858
859     exportAction->setEnabled(true);
860     disconnect(exportAction, SIGNAL(triggered()), 0, 0);
861     connect(exportAction, SIGNAL(triggered()), receiveCoinsPage, SLOT(exportClicked()));
862 }
863
864 void BitcoinGUI::gotoSendCoinsPage()
865 {
866     sendCoinsAction->setChecked(true);
867     centralWidget->setCurrentWidget(sendCoinsPage);
868
869     exportAction->setEnabled(false);
870     disconnect(exportAction, SIGNAL(triggered()), 0, 0);
871 }
872
873 void BitcoinGUI::gotoSignMessageTab(QString addr)
874 {
875     // call show() in showTab_SM()
876     signVerifyMessageDialog->showTab_SM(true);
877
878     if(!addr.isEmpty())
879         signVerifyMessageDialog->setAddress_SM(addr);
880 }
881
882 void BitcoinGUI::gotoVerifyMessageTab(QString addr)
883 {
884     // call show() in showTab_VM()
885     signVerifyMessageDialog->showTab_VM(true);
886
887     if(!addr.isEmpty())
888         signVerifyMessageDialog->setAddress_VM(addr);
889 }
890
891 void BitcoinGUI::dragEnterEvent(QDragEnterEvent *event)
892 {
893     // Accept only URIs
894     if(event->mimeData()->hasUrls())
895         event->acceptProposedAction();
896 }
897
898 void BitcoinGUI::dropEvent(QDropEvent *event)
899 {
900     if(event->mimeData()->hasUrls())
901     {
902         int nValidUrisFound = 0;
903         QList<QUrl> uris = event->mimeData()->urls();
904         foreach(const QUrl &uri, uris)
905         {
906             if (sendCoinsPage->handleURI(uri.toString()))
907                 nValidUrisFound++;
908         }
909
910         // if valid URIs were found
911         if (nValidUrisFound)
912             gotoSendCoinsPage();
913         else
914             notificator->notify(Notificator::Warning, tr("URI handling"), tr("URI can not be parsed! This can be caused by an invalid NovaCoin address or malformed URI parameters."));
915     }
916
917     event->acceptProposedAction();
918 }
919
920 void BitcoinGUI::handleURI(QString strURI)
921 {
922     // URI has to be valid
923     if (sendCoinsPage->handleURI(strURI))
924     {
925         showNormalIfMinimized();
926         gotoSendCoinsPage();
927     }
928     else
929         notificator->notify(Notificator::Warning, tr("URI handling"), tr("URI can not be parsed! This can be caused by an invalid NovaCoin address or malformed URI parameters."));
930 }
931
932 void BitcoinGUI::setEncryptionStatus(int status)
933 {
934     switch(status)
935     {
936     case WalletModel::Unencrypted:
937         labelEncryptionIcon->hide();
938         encryptWalletAction->setChecked(false);
939         changePassphraseAction->setEnabled(false);
940         lockWalletAction->setEnabled(false);
941         unlockWalletAction->setEnabled(false);
942         unlockWalletMiningAction->setEnabled(false);
943         encryptWalletAction->setEnabled(true);
944         break;
945     case WalletModel::Unlocked:
946         labelEncryptionIcon->show();
947         labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
948         labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b>"));
949         encryptWalletAction->setChecked(true);
950         changePassphraseAction->setEnabled(true);
951         encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
952
953         lockWalletAction->setEnabled(true);
954         lockWalletAction->setChecked(false);
955         unlockWalletAction->setEnabled(false);
956         unlockWalletMiningAction->setEnabled(false);
957
958         if (fWalletUnlockMintOnly)
959             unlockWalletMiningAction->setChecked(true);
960         else
961             unlockWalletAction->setChecked(true);
962
963         break;
964     case WalletModel::Locked:
965         labelEncryptionIcon->show();
966         labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_closed").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
967         labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>locked</b>"));
968         encryptWalletAction->setChecked(true);
969         changePassphraseAction->setEnabled(true);
970         encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
971
972         lockWalletAction->setChecked(true);
973         unlockWalletAction->setChecked(false);
974         unlockWalletMiningAction->setChecked(false);
975
976         lockWalletAction->setEnabled(false);
977         unlockWalletAction->setEnabled(true);
978         unlockWalletMiningAction->setEnabled(true);
979         break;
980     }
981 }
982
983 void BitcoinGUI::encryptWallet(bool status)
984 {
985     if(!walletModel)
986         return;
987     AskPassphraseDialog dlg(status ? AskPassphraseDialog::Encrypt:
988                                      AskPassphraseDialog::Decrypt, this);
989     dlg.setModel(walletModel);
990     dlg.exec();
991
992     setEncryptionStatus(walletModel->getEncryptionStatus());
993 }
994
995 void BitcoinGUI::unlockWalletMining(bool status)
996 {
997     if(!walletModel)
998         return;
999
1000     // Unlock wallet when requested by wallet model
1001     if(walletModel->getEncryptionStatus() == WalletModel::Locked)
1002     {
1003         AskPassphraseDialog dlg(AskPassphraseDialog::UnlockMining, this);
1004         dlg.setModel(walletModel);
1005         dlg.exec();
1006     }
1007 }
1008
1009 void BitcoinGUI::backupWallet()
1010 {
1011 #if QT_VERSION < 0x050000
1012     QString saveDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
1013 #else
1014     QString saveDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
1015 #endif
1016     QString filename = QFileDialog::getSaveFileName(this, tr("Backup Wallet"), saveDir, tr("Wallet Data (*.dat)"));
1017     if(!filename.isEmpty()) {
1018         if(!walletModel->backupWallet(filename)) {
1019             QMessageBox::warning(this, tr("Backup Failed"), tr("There was an error trying to save the wallet data to the new location."));
1020         }
1021     }
1022 }
1023
1024 void BitcoinGUI::dumpWallet()
1025 {
1026    if(!walletModel)
1027       return;
1028
1029    WalletModel::UnlockContext ctx(walletModel->requestUnlock());
1030    if(!ctx.isValid())
1031    {
1032        // Unlock wallet failed or was cancelled
1033        return;
1034    }
1035
1036 #if QT_VERSION < 0x050000
1037     QString saveDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
1038 #else
1039     QString saveDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
1040 #endif
1041     QString filename = QFileDialog::getSaveFileName(this, tr("Dump Wallet"), saveDir, tr("Wallet dump (*.txt)"));
1042     if(!filename.isEmpty()) {
1043         if(!walletModel->dumpWallet(filename)) {
1044             error(tr("Dump failed"),
1045                          tr("An error happened while trying to save the keys to your location.\n"
1046                             "Keys were not saved.")
1047                       ,CClientUIInterface::MSG_ERROR);
1048         }
1049         else
1050           message(tr("Dump successful"),
1051                        tr("Keys were saved to this file:\n%2")
1052                        .arg(filename)
1053                       ,CClientUIInterface::MSG_INFORMATION);
1054     }
1055 }
1056
1057 void BitcoinGUI::importWallet()
1058 {
1059    if(!walletModel)
1060       return;
1061
1062    WalletModel::UnlockContext ctx(walletModel->requestUnlock());
1063    if(!ctx.isValid())
1064    {
1065        // Unlock wallet failed or was cancelled
1066        return;
1067    }
1068
1069 #if QT_VERSION < 0x050000
1070     QString openDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
1071 #else
1072     QString openDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
1073 #endif
1074     QString filename = QFileDialog::getOpenFileName(this, tr("Import Wallet"), openDir, tr("Wallet dump (*.txt)"));
1075     if(!filename.isEmpty()) {
1076         if(!walletModel->importWallet(filename)) {
1077             error(tr("Import Failed"),
1078                          tr("An error happened while trying to import the keys.\n"
1079                             "Some or all keys from:\n %1,\n were not imported into your wallet.")
1080                          .arg(filename)
1081                       ,CClientUIInterface::MSG_ERROR);
1082         }
1083         else
1084           message(tr("Import Successful"),
1085                        tr("All keys from:\n %1,\n were imported into your wallet.")
1086                        .arg(filename)
1087                       ,CClientUIInterface::MSG_INFORMATION);
1088     }
1089 }
1090
1091
1092 void BitcoinGUI::changePassphrase()
1093 {
1094     AskPassphraseDialog dlg(AskPassphraseDialog::ChangePass, this);
1095     dlg.setModel(walletModel);
1096     dlg.exec();
1097 }
1098
1099 void BitcoinGUI::unlockWallet()
1100 {
1101     if(!walletModel)
1102         return;
1103     // Unlock wallet when requested by wallet model
1104     if(walletModel->getEncryptionStatus() == WalletModel::Locked)
1105     {
1106         AskPassphraseDialog dlg(AskPassphraseDialog::Unlock, this);
1107         dlg.setModel(walletModel);
1108         dlg.exec();
1109     }
1110 }
1111
1112 void BitcoinGUI::lockWallet()
1113 {
1114     if(!walletModel)
1115         return;
1116
1117     walletModel->setWalletLocked(true);
1118 }
1119
1120 void BitcoinGUI::showNormalIfMinimized(bool fToggleHidden)
1121 {
1122     // activateWindow() (sometimes) helps with keyboard focus on Windows
1123     if (isHidden())
1124     {
1125         show();
1126         activateWindow();
1127     }
1128     else if (isMinimized())
1129     {
1130         showNormal();
1131         activateWindow();
1132     }
1133     else if (GUIUtil::isObscured(this))
1134     {
1135         raise();
1136         activateWindow();
1137     }
1138     else if(fToggleHidden)
1139         hide();
1140 }
1141
1142 void BitcoinGUI::toggleHidden()
1143 {
1144     showNormalIfMinimized(true);
1145 }