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