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