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