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