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