Update stake miner GUI
[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(72);
128     frameBlocks->setMaximumWidth(72);
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         connect(walletModel, SIGNAL(encryptionStatusChanged(int)), this, SLOT(updateMining()));
399
400         // Balloon pop-up for new transaction
401         connect(walletModel->getTransactionTableModel(), SIGNAL(rowsInserted(QModelIndex,int,int)),
402                 this, SLOT(incomingTransaction(QModelIndex,int,int)));
403
404         // Ask for passphrase if needed
405         connect(walletModel, SIGNAL(requireUnlock()), this, SLOT(unlockWallet()));
406     }
407 }
408
409 void BitcoinGUI::createTrayIcon()
410 {
411     QMenu *trayIconMenu;
412 #ifndef Q_OS_MAC
413     trayIcon = new QSystemTrayIcon(this);
414     trayIconMenu = new QMenu(this);
415     trayIcon->setContextMenu(trayIconMenu);
416     trayIcon->setToolTip(tr("NovaCoin client"));
417     trayIcon->setIcon(QIcon(":/icons/toolbar"));
418     connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
419             this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason)));
420     trayIcon->show();
421 #else
422     // Note: On Mac, the dock icon is used to provide the tray's functionality.
423     MacDockIconHandler *dockIconHandler = MacDockIconHandler::instance();
424     trayIconMenu = dockIconHandler->dockMenu();
425 #endif
426
427     // Configuration of the tray icon (or dock icon) icon menu
428     trayIconMenu->addAction(toggleHideAction);
429     trayIconMenu->addSeparator();
430     trayIconMenu->addAction(sendCoinsAction);
431     trayIconMenu->addAction(receiveCoinsAction);
432     trayIconMenu->addSeparator();
433     trayIconMenu->addAction(signMessageAction);
434     trayIconMenu->addAction(verifyMessageAction);
435     trayIconMenu->addSeparator();
436     trayIconMenu->addAction(optionsAction);
437     trayIconMenu->addAction(openRPCConsoleAction);
438 #ifndef Q_OS_MAC // This is built-in on Mac
439     trayIconMenu->addSeparator();
440     trayIconMenu->addAction(quitAction);
441 #endif
442
443     notificator = new Notificator(qApp->applicationName(), trayIcon);
444 }
445
446 #ifndef Q_OS_MAC
447 void BitcoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason)
448 {
449     if(reason == QSystemTrayIcon::Trigger)
450     {
451         // Click on system tray icon triggers show/hide of the main window
452         toggleHideAction->trigger();
453     }
454 }
455 #endif
456
457 void BitcoinGUI::optionsClicked()
458 {
459     if(!clientModel || !clientModel->getOptionsModel())
460         return;
461     OptionsDialog dlg;
462     dlg.setModel(clientModel->getOptionsModel());
463     dlg.exec();
464 }
465
466 void BitcoinGUI::aboutClicked()
467 {
468     AboutDialog dlg;
469     dlg.setModel(clientModel);
470     dlg.exec();
471 }
472
473 void BitcoinGUI::setNumConnections(int count)
474 {
475     QString icon;
476     switch(count)
477     {
478     case 0: icon = ":/icons/connect_0"; break;
479     case 1: case 2: case 3: icon = ":/icons/connect_1"; break;
480     case 4: case 5: case 6: icon = ":/icons/connect_2"; break;
481     case 7: case 8: case 9: icon = ":/icons/connect_3"; break;
482     default: icon = ":/icons/connect_4"; break;
483     }
484     labelConnectionsIcon->setPixmap(QIcon(icon).pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
485     labelConnectionsIcon->setToolTip(tr("%n active connection(s) to NovaCoin network", "", count));
486 }
487
488 void BitcoinGUI::setNumBlocks(int count, int nTotalBlocks)
489 {
490     // don't show / hide progress bar and its label if we have no connection to the network
491     if (!clientModel || clientModel->getNumConnections() == 0)
492     {
493         progressBarLabel->setVisible(false);
494         progressBar->setVisible(false);
495
496         return;
497     }
498
499     QString strStatusBarWarnings = clientModel->getStatusBarWarnings();
500     QString tooltip;
501
502     if(count < nTotalBlocks)
503     {
504         int nRemainingBlocks = nTotalBlocks - count;
505         float nPercentageDone = count / (nTotalBlocks * 0.01f);
506
507         if (strStatusBarWarnings.isEmpty())
508         {
509             progressBarLabel->setText(tr("Synchronizing with network..."));
510             progressBarLabel->setVisible(true);
511             progressBar->setFormat(tr("~%n block(s) remaining", "", nRemainingBlocks));
512             progressBar->setMaximum(nTotalBlocks);
513             progressBar->setValue(count);
514             progressBar->setVisible(true);
515         }
516
517         tooltip = tr("Downloaded %1 of %2 blocks of transaction history (%3% done).").arg(count).arg(nTotalBlocks).arg(nPercentageDone, 0, 'f', 2);
518     }
519     else
520     {
521         if (strStatusBarWarnings.isEmpty())
522             progressBarLabel->setVisible(false);
523
524         progressBar->setVisible(false);
525         tooltip = tr("Downloaded %1 blocks of transaction history.").arg(count);
526     }
527
528     // Override progressBarLabel text and hide progress bar, when we have warnings to display
529     if (!strStatusBarWarnings.isEmpty())
530     {
531         progressBarLabel->setText(strStatusBarWarnings);
532         progressBarLabel->setVisible(true);
533         progressBar->setVisible(false);
534     }
535
536     QDateTime lastBlockDate = clientModel->getLastBlockDate();
537     int secs = lastBlockDate.secsTo(QDateTime::currentDateTime());
538     QString text;
539
540     // Represent time from last generated block in human readable text
541     if(secs <= 0)
542     {
543         // Fully up to date. Leave text empty.
544     }
545     else if(secs < 60)
546     {
547         text = tr("%n second(s) ago","",secs);
548     }
549     else if(secs < 60*60)
550     {
551         text = tr("%n minute(s) ago","",secs/60);
552     }
553     else if(secs < 24*60*60)
554     {
555         text = tr("%n hour(s) ago","",secs/(60*60));
556     }
557     else
558     {
559         text = tr("%n day(s) ago","",secs/(60*60*24));
560     }
561
562     // Set icon state: spinning if catching up, tick otherwise
563     if(secs < 90*60 && count >= nTotalBlocks)
564     {
565         tooltip = tr("Up to date") + QString(".<br>") + tooltip;
566         labelBlocksIcon->setPixmap(QIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
567
568         overviewPage->showOutOfSyncWarning(false);
569     }
570     else
571     {
572         tooltip = tr("Catching up...") + QString("<br>") + tooltip;
573         labelBlocksIcon->setMovie(syncIconMovie);
574         syncIconMovie->start();
575
576         overviewPage->showOutOfSyncWarning(true);
577     }
578
579     if(!text.isEmpty())
580     {
581         tooltip += QString("<br>");
582         tooltip += tr("Last received block was generated %1.").arg(text);
583     }
584
585     // Don't word-wrap this (fixed-width) tooltip
586     tooltip = QString("<nobr>") + tooltip + QString("</nobr>");
587
588     labelBlocksIcon->setToolTip(tooltip);
589     progressBarLabel->setToolTip(tooltip);
590     progressBar->setToolTip(tooltip);
591 }
592
593 void BitcoinGUI::updateMining()
594 {
595    if(!walletModel)
596       return;
597
598     labelMiningIcon->setPixmap(QIcon(":/icons/mining_inactive").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
599
600     if (!clientModel->getNumConnections())
601     {
602         labelMiningIcon->setToolTip(tr("Wallet is offline"));
603         return;
604     }
605
606     if (walletModel->getEncryptionStatus() == WalletModel::Locked)
607     {
608         labelMiningIcon->setToolTip(tr("Wallet is locked"));
609         return;
610     }
611
612     if (clientModel->inInitialBlockDownload() || clientModel->getNumBlocksOfPeers() > clientModel->getNumBlocks())
613     {
614         labelMiningIcon->setToolTip(tr("Blockchain download is in progress"));
615         return;
616     }
617
618     uint64 nMinWeight = 0, nMaxWeight = 0, nTotalWeight = 0;
619     walletModel->getStakeWeight(nMinWeight, nMaxWeight, nTotalWeight);
620
621     if (nTotalWeight > 0)
622     {
623         labelMiningIcon->setPixmap(QIcon(":/icons/mining_active").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
624
625         double dNetworkWeight = clientModel->getPoSKernelPS();
626 /*
627         double dDifficulty = clientModel->getDifficulty(true);
628         QString msg;
629
630         int nApproxTime = 4294967297 * dDifficulty / nTotalWeight;
631
632         if (nApproxTime < 60)
633             msg = tr("%n second(s)", "", nApproxTime);
634         else if (nApproxTime < 60*60)
635             msg = tr("%n minute(s)", "", nApproxTime / 60);
636         else if (nApproxTime < 24*60*60)
637             msg = tr("%n hour(s)", "", nApproxTime / 3600);
638         else
639             msg = tr("%n day(s)", "", nApproxTime / 86400);
640
641         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));
642 */
643
644         labelMiningIcon->setToolTip(tr("Stake miner is active\nYour current stake weight is %1\nNetwork weight is %2").arg(nTotalWeight).arg(dNetworkWeight));
645     }
646     else
647         labelMiningIcon->setToolTip(tr("No suitable inputs were found"));
648 }
649
650 void BitcoinGUI::error(const QString &title, const QString &message, bool modal)
651 {
652     // Report errors from network/worker thread
653     if(modal)
654     {
655         QMessageBox::critical(this, title, message, QMessageBox::Ok, QMessageBox::Ok);
656     } else {
657         notificator->notify(Notificator::Critical, title, message);
658     }
659 }
660
661 void BitcoinGUI::message(const QString &title, const QString &message, unsigned int style, const QString &detail)
662 {
663     QString strTitle = tr("NovaCoin") + " - ";
664     // Default to information icon
665     int nMBoxIcon = QMessageBox::Information;
666     int nNotifyIcon = Notificator::Information;
667
668
669     // Check for usage of predefined title
670     switch (style) {
671     case CClientUIInterface::MSG_ERROR:
672         strTitle += tr("Error");
673         break;
674     case CClientUIInterface::MSG_WARNING:
675         strTitle += tr("Warning");
676         break;
677     case CClientUIInterface::MSG_INFORMATION:
678         strTitle += tr("Information");
679         break;
680     default:
681         strTitle += title; // Use supplied title
682     }
683
684     // Check for error/warning icon
685     if (style & CClientUIInterface::ICON_ERROR) {
686         nMBoxIcon = QMessageBox::Critical;
687         nNotifyIcon = Notificator::Critical;
688     }
689     else if (style & CClientUIInterface::ICON_WARNING) {
690         nMBoxIcon = QMessageBox::Warning;
691         nNotifyIcon = Notificator::Warning;
692     }
693
694     // Display message
695     if (style & CClientUIInterface::MODAL) {
696         // Check for buttons, use OK as default, if none was supplied
697         QMessageBox::StandardButton buttons;
698         buttons = QMessageBox::Ok;
699
700         QMessageBox mBox((QMessageBox::Icon)nMBoxIcon, strTitle, message, buttons);
701
702         if(!detail.isEmpty()) { mBox.setDetailedText(detail); }
703
704         mBox.exec();
705     }
706     else
707         notificator->notify((Notificator::Class)nNotifyIcon, strTitle, message);
708 }
709
710
711 void BitcoinGUI::changeEvent(QEvent *e)
712 {
713     QMainWindow::changeEvent(e);
714 #ifndef Q_OS_MAC // Ignored on Mac
715     if(e->type() == QEvent::WindowStateChange)
716     {
717         if(clientModel && clientModel->getOptionsModel()->getMinimizeToTray())
718         {
719             QWindowStateChangeEvent *wsevt = static_cast<QWindowStateChangeEvent*>(e);
720             if(!(wsevt->oldState() & Qt::WindowMinimized) && isMinimized())
721             {
722                 QTimer::singleShot(0, this, SLOT(hide()));
723                 e->ignore();
724             }
725         }
726     }
727 #endif
728 }
729
730 void BitcoinGUI::closeEvent(QCloseEvent *event)
731 {
732     if(clientModel)
733     {
734 #ifndef Q_OS_MAC // Ignored on Mac
735         if(!clientModel->getOptionsModel()->getMinimizeToTray() &&
736            !clientModel->getOptionsModel()->getMinimizeOnClose())
737         {
738             qApp->quit();
739         }
740 #endif
741     }
742     QMainWindow::closeEvent(event);
743 }
744
745 void BitcoinGUI::askFee(qint64 nFeeRequired, bool *payFee)
746 {
747     QString strMessage =
748         tr("This transaction is over the size limit.  You can still send it for a fee of %1, "
749           "which goes to the nodes that process your transaction and helps to support the network.  "
750           "Do you want to pay the fee?").arg(
751                 BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, nFeeRequired));
752     QMessageBox::StandardButton retval = QMessageBox::question(
753           this, tr("Confirm transaction fee"), strMessage,
754           QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Yes);
755     *payFee = (retval == QMessageBox::Yes);
756 }
757
758 void BitcoinGUI::incomingTransaction(const QModelIndex & parent, int start, int end)
759 {
760     if(!walletModel || !clientModel)
761         return;
762     TransactionTableModel *ttm = walletModel->getTransactionTableModel();
763     qint64 amount = ttm->index(start, TransactionTableModel::Amount, parent)
764                     .data(Qt::EditRole).toULongLong();
765     if(!clientModel->inInitialBlockDownload())
766     {
767         // On new transaction, make an info balloon
768         // Unless the initial block download is in progress, to prevent balloon-spam
769         QString date = ttm->index(start, TransactionTableModel::Date, parent)
770                         .data().toString();
771         QString type = ttm->index(start, TransactionTableModel::Type, parent)
772                         .data().toString();
773         QString address = ttm->index(start, TransactionTableModel::ToAddress, parent)
774                         .data().toString();
775         QIcon icon = qvariant_cast<QIcon>(ttm->index(start,
776                             TransactionTableModel::ToAddress, parent)
777                         .data(Qt::DecorationRole));
778
779         notificator->notify(Notificator::Information,
780                             (amount)<0 ? tr("Sent transaction") :
781                                          tr("Incoming transaction"),
782                               tr("Date: %1\n"
783                                  "Amount: %2\n"
784                                  "Type: %3\n"
785                                  "Address: %4\n")
786                               .arg(date)
787                               .arg(BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), amount, true))
788                               .arg(type)
789                               .arg(address), icon);
790     }
791 }
792
793 void BitcoinGUI::gotoOverviewPage()
794 {
795     overviewAction->setChecked(true);
796     centralWidget->setCurrentWidget(overviewPage);
797
798     exportAction->setEnabled(false);
799     disconnect(exportAction, SIGNAL(triggered()), 0, 0);
800 }
801
802 void BitcoinGUI::gotoHistoryPage()
803 {
804     historyAction->setChecked(true);
805     centralWidget->setCurrentWidget(transactionsPage);
806
807     exportAction->setEnabled(true);
808     disconnect(exportAction, SIGNAL(triggered()), 0, 0);
809     connect(exportAction, SIGNAL(triggered()), transactionView, SLOT(exportClicked()));
810 }
811
812 void BitcoinGUI::gotoAddressBookPage()
813 {
814     addressBookAction->setChecked(true);
815     centralWidget->setCurrentWidget(addressBookPage);
816
817     exportAction->setEnabled(true);
818     disconnect(exportAction, SIGNAL(triggered()), 0, 0);
819     connect(exportAction, SIGNAL(triggered()), addressBookPage, SLOT(exportClicked()));
820 }
821
822 void BitcoinGUI::gotoReceiveCoinsPage()
823 {
824     receiveCoinsAction->setChecked(true);
825     centralWidget->setCurrentWidget(receiveCoinsPage);
826
827     exportAction->setEnabled(true);
828     disconnect(exportAction, SIGNAL(triggered()), 0, 0);
829     connect(exportAction, SIGNAL(triggered()), receiveCoinsPage, SLOT(exportClicked()));
830 }
831
832 void BitcoinGUI::gotoSendCoinsPage()
833 {
834     sendCoinsAction->setChecked(true);
835     centralWidget->setCurrentWidget(sendCoinsPage);
836
837     exportAction->setEnabled(false);
838     disconnect(exportAction, SIGNAL(triggered()), 0, 0);
839 }
840
841 void BitcoinGUI::gotoSignMessageTab(QString addr)
842 {
843     // call show() in showTab_SM()
844     signVerifyMessageDialog->showTab_SM(true);
845
846     if(!addr.isEmpty())
847         signVerifyMessageDialog->setAddress_SM(addr);
848 }
849
850 void BitcoinGUI::gotoVerifyMessageTab(QString addr)
851 {
852     // call show() in showTab_VM()
853     signVerifyMessageDialog->showTab_VM(true);
854
855     if(!addr.isEmpty())
856         signVerifyMessageDialog->setAddress_VM(addr);
857 }
858
859 void BitcoinGUI::dragEnterEvent(QDragEnterEvent *event)
860 {
861     // Accept only URIs
862     if(event->mimeData()->hasUrls())
863         event->acceptProposedAction();
864 }
865
866 void BitcoinGUI::dropEvent(QDropEvent *event)
867 {
868     if(event->mimeData()->hasUrls())
869     {
870         int nValidUrisFound = 0;
871         QList<QUrl> uris = event->mimeData()->urls();
872         foreach(const QUrl &uri, uris)
873         {
874             if (sendCoinsPage->handleURI(uri.toString()))
875                 nValidUrisFound++;
876         }
877
878         // if valid URIs were found
879         if (nValidUrisFound)
880             gotoSendCoinsPage();
881         else
882             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."));
883     }
884
885     event->acceptProposedAction();
886 }
887
888 void BitcoinGUI::handleURI(QString strURI)
889 {
890     // URI has to be valid
891     if (sendCoinsPage->handleURI(strURI))
892     {
893         showNormalIfMinimized();
894         gotoSendCoinsPage();
895     }
896     else
897         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."));
898 }
899
900 void BitcoinGUI::setEncryptionStatus(int status)
901 {
902     switch(status)
903     {
904     case WalletModel::Unencrypted:
905         labelEncryptionIcon->hide();
906         encryptWalletAction->setChecked(false);
907         changePassphraseAction->setEnabled(false);
908         encryptWalletAction->setEnabled(true);
909         break;
910     case WalletModel::Unlocked:
911         labelEncryptionIcon->show();
912         labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
913         labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b>"));
914         encryptWalletAction->setChecked(true);
915         changePassphraseAction->setEnabled(true);
916         encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
917         break;
918     case WalletModel::Locked:
919         labelEncryptionIcon->show();
920         labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_closed").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
921         labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>locked</b>"));
922         encryptWalletAction->setChecked(true);
923         changePassphraseAction->setEnabled(true);
924         encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
925         break;
926     }
927 }
928
929 void BitcoinGUI::encryptWallet(bool status)
930 {
931     if(!walletModel)
932         return;
933     AskPassphraseDialog dlg(status ? AskPassphraseDialog::Encrypt:
934                                      AskPassphraseDialog::Decrypt, this);
935     dlg.setModel(walletModel);
936     dlg.exec();
937
938     setEncryptionStatus(walletModel->getEncryptionStatus());
939 }
940
941 void BitcoinGUI::backupWallet()
942 {
943     QString saveDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
944     QString filename = QFileDialog::getSaveFileName(this, tr("Backup Wallet"), saveDir, tr("Wallet Data (*.dat)"));
945     if(!filename.isEmpty()) {
946         if(!walletModel->backupWallet(filename)) {
947             QMessageBox::warning(this, tr("Backup Failed"), tr("There was an error trying to save the wallet data to the new location."));
948         }
949     }
950 }
951
952 void BitcoinGUI::dumpWallet()
953 {
954    if(!walletModel)
955       return;
956
957    WalletModel::UnlockContext ctx(walletModel->requestUnlock());
958    if(!ctx.isValid())
959    {
960        // Unlock wallet failed or was cancelled
961        return;
962    }
963
964 #if QT_VERSION < 0x050000
965     QString saveDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
966 #else
967     QString saveDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
968 #endif
969     QString filename = QFileDialog::getSaveFileName(this, tr("Dump Wallet"), saveDir, tr("Wallet dump (*.txt)"));
970     if(!filename.isEmpty()) {
971         if(!walletModel->dumpWallet(filename)) {
972             error(tr("Dump failed"),
973                          tr("An error happened while trying to save the keys to your location.\n"
974                             "Keys were not saved.")
975                       ,CClientUIInterface::MSG_ERROR);
976         }
977         else
978           message(tr("Dump successful"),
979                        tr("Keys were saved to this file:\n%2")
980                        .arg(filename)
981                       ,CClientUIInterface::MSG_INFORMATION);
982     }
983 }
984
985 void BitcoinGUI::importWallet()
986 {
987    if(!walletModel)
988       return;
989
990    WalletModel::UnlockContext ctx(walletModel->requestUnlock());
991    if(!ctx.isValid())
992    {
993        // Unlock wallet failed or was cancelled
994        return;
995    }
996
997 #if QT_VERSION < 0x050000
998     QString openDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
999 #else
1000     QString openDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
1001 #endif
1002     QString filename = QFileDialog::getOpenFileName(this, tr("Import Wallet"), openDir, tr("Wallet dump (*.txt)"));
1003     if(!filename.isEmpty()) {
1004         if(!walletModel->importWallet(filename)) {
1005             error(tr("Import Failed"),
1006                          tr("An error happened while trying to import the keys.\n"
1007                             "Some or all keys from:\n %1,\n were not imported into your wallet.")
1008                          .arg(filename)
1009                       ,CClientUIInterface::MSG_ERROR);
1010         }
1011         else
1012           message(tr("Import Successful"),
1013                        tr("All keys from:\n %1,\n were imported into your wallet.")
1014                        .arg(filename)
1015                       ,CClientUIInterface::MSG_INFORMATION);
1016     }
1017 }
1018
1019
1020 void BitcoinGUI::changePassphrase()
1021 {
1022     AskPassphraseDialog dlg(AskPassphraseDialog::ChangePass, this);
1023     dlg.setModel(walletModel);
1024     dlg.exec();
1025 }
1026
1027 void BitcoinGUI::unlockWallet()
1028 {
1029     if(!walletModel)
1030         return;
1031     // Unlock wallet when requested by wallet model
1032     if(walletModel->getEncryptionStatus() == WalletModel::Locked)
1033     {
1034         AskPassphraseDialog dlg(AskPassphraseDialog::Unlock, this);
1035         dlg.setModel(walletModel);
1036         dlg.exec();
1037     }
1038 }
1039
1040 void BitcoinGUI::showNormalIfMinimized(bool fToggleHidden)
1041 {
1042     // activateWindow() (sometimes) helps with keyboard focus on Windows
1043     if (isHidden())
1044     {
1045         show();
1046         activateWindow();
1047     }
1048     else if (isMinimized())
1049     {
1050         showNormal();
1051         activateWindow();
1052     }
1053     else if (GUIUtil::isObscured(this))
1054     {
1055         raise();
1056         activateWindow();
1057     }
1058     else if(fToggleHidden)
1059         hide();
1060 }
1061
1062 void BitcoinGUI::toggleHidden()
1063 {
1064     showNormalIfMinimized(true);
1065 }