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