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