Add a menu entry in the transaction view allowing...
[novacoin.git] / src / qt / transactionview.cpp
1 #include "transactionview.h"
2
3 #include "transactionfilterproxy.h"
4 #include "transactionrecord.h"
5 #include "walletmodel.h"
6 #include "addresstablemodel.h"
7 #include "transactiontablemodel.h"
8 #include "bitcoinunits.h"
9 #include "csvmodelwriter.h"
10 #include "transactiondescdialog.h"
11 #include "editaddressdialog.h"
12 #include "optionsmodel.h"
13 #include "guiutil.h"
14 #include "wallet.h"
15
16 #include <QScrollBar>
17 #include <QComboBox>
18 #include <QDoubleValidator>
19 #include <QHBoxLayout>
20 #include <QVBoxLayout>
21 #include <QLineEdit>
22 #include <QTableView>
23 #include <QHeaderView>
24 #include <QPushButton>
25 #include <QMessageBox>
26 #include <QPoint>
27 #include <QMenu>
28 #include <QApplication>
29 #include <QClipboard>
30 #include <QLabel>
31 #include <QDateTimeEdit>
32 #include <QDesktopServices>
33 #include <QSignalMapper>
34 #include <QUrl>
35
36 TransactionView::TransactionView(QWidget *parent) :
37     QWidget(parent), model(0), transactionProxyModel(0),
38     transactionView(0)
39 {
40     // Build filter row
41     setContentsMargins(0,0,0,0);
42
43     QHBoxLayout *hlayout = new QHBoxLayout();
44     hlayout->setContentsMargins(0,0,0,0);
45 #ifdef Q_OS_MAC
46     hlayout->setSpacing(5);
47     hlayout->addSpacing(26);
48 #else
49     hlayout->setSpacing(0);
50     hlayout->addSpacing(23);
51 #endif
52
53     dateWidget = new QComboBox(this);
54 #ifdef Q_OS_MAC
55     dateWidget->setFixedWidth(121);
56 #else
57     dateWidget->setFixedWidth(120);
58 #endif
59     dateWidget->addItem(tr("All"), All);
60     dateWidget->addItem(tr("Today"), Today);
61     dateWidget->addItem(tr("This week"), ThisWeek);
62     dateWidget->addItem(tr("This month"), ThisMonth);
63     dateWidget->addItem(tr("Last month"), LastMonth);
64     dateWidget->addItem(tr("This year"), ThisYear);
65     dateWidget->addItem(tr("Range..."), Range);
66     hlayout->addWidget(dateWidget);
67
68     typeWidget = new QComboBox(this);
69 #ifdef Q_OS_MAC
70     typeWidget->setFixedWidth(121);
71 #else
72     typeWidget->setFixedWidth(120);
73 #endif
74
75     typeWidget->addItem(tr("All"), TransactionFilterProxy::ALL_TYPES);
76     typeWidget->addItem(tr("Received with"), TransactionFilterProxy::TYPE(TransactionRecord::RecvWithAddress) |
77                                         TransactionFilterProxy::TYPE(TransactionRecord::RecvFromOther));
78     typeWidget->addItem(tr("Sent to"), TransactionFilterProxy::TYPE(TransactionRecord::SendToAddress) |
79                                   TransactionFilterProxy::TYPE(TransactionRecord::SendToOther));
80     typeWidget->addItem(tr("To yourself"), TransactionFilterProxy::TYPE(TransactionRecord::SendToSelf));
81     typeWidget->addItem(tr("Mined"), TransactionFilterProxy::TYPE(TransactionRecord::Generated));
82     typeWidget->addItem(tr("Other"), TransactionFilterProxy::TYPE(TransactionRecord::Other));
83
84     hlayout->addWidget(typeWidget);
85
86     addressWidget = new QLineEdit(this);
87 #if QT_VERSION >= 0x040700
88     /* Do not move this to the XML file, Qt before 4.7 will choke on it */
89     addressWidget->setPlaceholderText(tr("Enter address or label to search"));
90 #endif
91     hlayout->addWidget(addressWidget);
92
93     amountWidget = new QLineEdit(this);
94 #if QT_VERSION >= 0x040700
95     /* Do not move this to the XML file, Qt before 4.7 will choke on it */
96     amountWidget->setPlaceholderText(tr("Min amount"));
97 #endif
98 #ifdef Q_OS_MAC
99     amountWidget->setFixedWidth(97);
100 #else
101     amountWidget->setFixedWidth(100);
102 #endif
103     amountWidget->setValidator(new QDoubleValidator(0, 1e20, 8, this));
104     hlayout->addWidget(amountWidget);
105
106     QVBoxLayout *vlayout = new QVBoxLayout(this);
107     vlayout->setContentsMargins(0,0,0,0);
108     vlayout->setSpacing(0);
109
110     QTableView *view = new QTableView(this);
111     vlayout->addLayout(hlayout);
112     vlayout->addWidget(createDateRangeWidget());
113     vlayout->addWidget(view);
114     vlayout->setSpacing(0);
115     int width = view->verticalScrollBar()->sizeHint().width();
116     // Cover scroll bar width with spacing
117 #ifdef Q_OS_MAC
118     hlayout->addSpacing(width+2);
119 #else
120     hlayout->addSpacing(width);
121 #endif
122     // Always show scroll bar
123     view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
124     view->setTabKeyNavigation(false);
125     view->setContextMenuPolicy(Qt::CustomContextMenu);
126
127     transactionView = view;
128
129     // Actions
130     QAction *copyAddressAction = new QAction(tr("Copy address"), this);
131     QAction *copyLabelAction = new QAction(tr("Copy label"), this);
132     QAction *copyAmountAction = new QAction(tr("Copy amount"), this);
133     QAction *copyTxIDAction = new QAction(tr("Copy transaction ID"), this);
134     QAction *editLabelAction = new QAction(tr("Edit label"), this);
135     QAction *showDetailsAction = new QAction(tr("Show transaction details"), this);
136     QAction *clearOrphansAction = new QAction(tr("Clear orphans"), this);
137
138     contextMenu = new QMenu();
139     contextMenu->addAction(copyAddressAction);
140     contextMenu->addAction(copyLabelAction);
141     contextMenu->addAction(copyAmountAction);
142     contextMenu->addAction(copyTxIDAction);
143     contextMenu->addAction(editLabelAction);
144     contextMenu->addAction(showDetailsAction);
145     contextMenu->addSeparator();
146     contextMenu->addAction(clearOrphansAction);
147
148     mapperThirdPartyTxUrls = new QSignalMapper(this);
149
150     // Connect actions
151     connect(mapperThirdPartyTxUrls, SIGNAL(mapped(QString)), this, SLOT(openThirdPartyTxUrl(QString)));
152
153     connect(dateWidget, SIGNAL(activated(int)), this, SLOT(chooseDate(int)));
154     connect(typeWidget, SIGNAL(activated(int)), this, SLOT(chooseType(int)));
155     connect(addressWidget, SIGNAL(textChanged(QString)), this, SLOT(changedPrefix(QString)));
156     connect(amountWidget, SIGNAL(textChanged(QString)), this, SLOT(changedAmount(QString)));
157
158     connect(view, SIGNAL(doubleClicked(QModelIndex)), this, SIGNAL(doubleClicked(QModelIndex)));
159     connect(view, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint)));
160
161     connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress()));
162     connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel()));
163     connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount()));
164     connect(copyTxIDAction, SIGNAL(triggered()), this, SLOT(copyTxID()));
165     connect(editLabelAction, SIGNAL(triggered()), this, SLOT(editLabel()));
166     connect(showDetailsAction, SIGNAL(triggered()), this, SLOT(showDetails()));
167     connect(clearOrphansAction, SIGNAL(triggered()), this, SLOT(clearOrphans()));
168 }
169
170 void TransactionView::setModel(WalletModel *model)
171 {
172     this->model = model;
173     if(model)
174     {
175         transactionProxyModel = new TransactionFilterProxy(this);
176         transactionProxyModel->setSourceModel(model->getTransactionTableModel());
177         transactionProxyModel->setDynamicSortFilter(true);
178         transactionProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
179         transactionProxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
180
181 //        transactionProxyModel->setSortRole(Qt::EditRole);
182         transactionProxyModel->setSortRole(TransactionTableModel::DateRole);
183
184         transactionView->setModel(transactionProxyModel);
185         transactionView->setAlternatingRowColors(true);
186         transactionView->setSelectionBehavior(QAbstractItemView::SelectRows);
187         transactionView->setSelectionMode(QAbstractItemView::ExtendedSelection);
188         transactionView->setSortingEnabled(true);
189         transactionView->sortByColumn(TransactionTableModel::Status, Qt::DescendingOrder);
190         transactionView->verticalHeader()->hide();
191
192         transactionView->horizontalHeader()->resizeSection(
193                 TransactionTableModel::Status, 23);
194         transactionView->horizontalHeader()->resizeSection(
195                 TransactionTableModel::Date, 120);
196         transactionView->horizontalHeader()->resizeSection(
197                 TransactionTableModel::Type, 120);
198 #if QT_VERSION < 0x050000
199         transactionView->horizontalHeader()->setResizeMode(
200                 TransactionTableModel::ToAddress, QHeaderView::Stretch);
201 #else
202         transactionView->horizontalHeader()->setSectionResizeMode(TransactionTableModel::ToAddress, QHeaderView::Stretch);
203 #endif
204         transactionView->horizontalHeader()->resizeSection(
205                 TransactionTableModel::Amount, 100);
206
207         if (model->getOptionsModel())
208         {
209             // Add third party transaction URLs to context menu
210             QStringList listUrls = model->getOptionsModel()->getThirdPartyTxUrls().split("|", QString::SkipEmptyParts);
211             for (int i = 0; i < listUrls.size(); ++i)
212             {
213                 QString host = QUrl(listUrls[i].trimmed(), QUrl::StrictMode).host();
214                 if (!host.isEmpty())
215                 {
216                     QAction *thirdPartyTxUrlAction = new QAction(host, this); // use host as menu item label
217                     if (i == 0)
218                         contextMenu->addSeparator();
219                     contextMenu->addAction(thirdPartyTxUrlAction);
220                     connect(thirdPartyTxUrlAction, SIGNAL(triggered()), mapperThirdPartyTxUrls, SLOT(map()));
221                     mapperThirdPartyTxUrls->setMapping(thirdPartyTxUrlAction, listUrls[i].trimmed());
222                  }
223              }
224         }
225     }
226 }
227
228 void TransactionView::chooseDate(int idx)
229 {
230     if(!transactionProxyModel)
231         return;
232     QDate current = QDate::currentDate();
233     dateRangeWidget->setVisible(false);
234     switch(dateWidget->itemData(idx).toInt())
235     {
236     case All:
237         transactionProxyModel->setDateRange(
238                 TransactionFilterProxy::MIN_DATE,
239                 TransactionFilterProxy::MAX_DATE);
240         break;
241     case Today:
242         transactionProxyModel->setDateRange(
243                 QDateTime(current),
244                 TransactionFilterProxy::MAX_DATE);
245         break;
246     case ThisWeek: {
247         // Find last Monday
248         QDate startOfWeek = current.addDays(-(current.dayOfWeek()-1));
249         transactionProxyModel->setDateRange(
250                 QDateTime(startOfWeek),
251                 TransactionFilterProxy::MAX_DATE);
252
253         } break;
254     case ThisMonth:
255         transactionProxyModel->setDateRange(
256                 QDateTime(QDate(current.year(), current.month(), 1)),
257                 TransactionFilterProxy::MAX_DATE);
258         break;
259     case LastMonth:
260         transactionProxyModel->setDateRange(
261                 QDateTime(QDate(current.year(), current.month()-1, 1)),
262                 QDateTime(QDate(current.year(), current.month(), 1)));
263         break;
264     case ThisYear:
265         transactionProxyModel->setDateRange(
266                 QDateTime(QDate(current.year(), 1, 1)),
267                 TransactionFilterProxy::MAX_DATE);
268         break;
269     case Range:
270         dateRangeWidget->setVisible(true);
271         dateRangeChanged();
272         break;
273     }
274 }
275
276 void TransactionView::chooseType(int idx)
277 {
278     if(!transactionProxyModel)
279         return;
280     transactionProxyModel->setTypeFilter(
281         typeWidget->itemData(idx).toInt());
282 }
283
284 void TransactionView::changedPrefix(const QString &prefix)
285 {
286     if(!transactionProxyModel)
287         return;
288     transactionProxyModel->setAddressPrefix(prefix);
289 }
290
291 void TransactionView::changedAmount(const QString &amount)
292 {
293     if(!transactionProxyModel)
294         return;
295     qint64 amount_parsed = 0;
296     if(BitcoinUnits::parse(model->getOptionsModel()->getDisplayUnit(), amount, &amount_parsed))
297     {
298         transactionProxyModel->setMinAmount(amount_parsed);
299     }
300     else
301     {
302         transactionProxyModel->setMinAmount(0);
303     }
304 }
305
306 void TransactionView::exportClicked()
307 {
308     // CSV is currently the only supported format
309     QString filename = GUIUtil::getSaveFileName(
310             this,
311             tr("Export Transaction Data"), QString(),
312             tr("Comma separated file (*.csv)"));
313
314     if (filename.isNull()) return;
315
316     CSVModelWriter writer(filename);
317
318     // name, column, role
319     writer.setModel(transactionProxyModel);
320     writer.addColumn(tr("Confirmed"), 0, TransactionTableModel::ConfirmedRole);
321     writer.addColumn(tr("Date"), 0, TransactionTableModel::DateRole);
322     writer.addColumn(tr("Type"), TransactionTableModel::Type, Qt::EditRole);
323     writer.addColumn(tr("Label"), 0, TransactionTableModel::LabelRole);
324     writer.addColumn(tr("Address"), 0, TransactionTableModel::AddressRole);
325     writer.addColumn(tr("Amount"), 0, TransactionTableModel::FormattedAmountRole);
326     writer.addColumn(tr("ID"), 0, TransactionTableModel::TxIDRole);
327
328     if(!writer.write())
329     {
330         QMessageBox::critical(this, tr("Error exporting"), tr("Could not write to file %1.").arg(filename),
331                               QMessageBox::Abort, QMessageBox::Abort);
332     }
333 }
334
335 void TransactionView::contextualMenu(const QPoint &point)
336 {
337     QModelIndex index = transactionView->indexAt(point);
338     if(index.isValid())
339     {
340         contextMenu->exec(QCursor::pos());
341     }
342 }
343
344 void TransactionView::copyAddress()
345 {
346     GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::AddressRole);
347 }
348
349 void TransactionView::copyLabel()
350 {
351     GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::LabelRole);
352 }
353
354 void TransactionView::copyAmount()
355 {
356     GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::FormattedAmountRole);
357 }
358
359 void TransactionView::copyTxID()
360 {
361     GUIUtil::copyEntryData(transactionView, 0, TransactionTableModel::TxIDRole);
362 }
363
364 void TransactionView::editLabel()
365 {
366     if(!transactionView->selectionModel() ||!model)
367         return;
368     QModelIndexList selection = transactionView->selectionModel()->selectedRows();
369     if(!selection.isEmpty())
370     {
371         AddressTableModel *addressBook = model->getAddressTableModel();
372         if(!addressBook)
373             return;
374         QString address = selection.at(0).data(TransactionTableModel::AddressRole).toString();
375         if(address.isEmpty())
376         {
377             // If this transaction has no associated address, exit
378             return;
379         }
380         // Is address in address book? Address book can miss address when a transaction is
381         // sent from outside the UI.
382         int idx = addressBook->lookupAddress(address);
383         if(idx != -1)
384         {
385             // Edit sending / receiving address
386             QModelIndex modelIdx = addressBook->index(idx, 0, QModelIndex());
387             // Determine type of address, launch appropriate editor dialog type
388             QString type = modelIdx.data(AddressTableModel::TypeRole).toString();
389
390             EditAddressDialog dlg(type==AddressTableModel::Receive
391                                          ? EditAddressDialog::EditReceivingAddress
392                                          : EditAddressDialog::EditSendingAddress,
393                                   this);
394             dlg.setModel(addressBook);
395             dlg.loadRow(idx);
396             dlg.exec();
397         }
398         else
399         {
400             // Add sending address
401             EditAddressDialog dlg(EditAddressDialog::NewSendingAddress,
402                                   this);
403             dlg.setModel(addressBook);
404             dlg.setAddress(address);
405             dlg.exec();
406         }
407     }
408 }
409
410 void TransactionView::showDetails()
411 {
412     if(!transactionView->selectionModel())
413         return;
414     QModelIndexList selection = transactionView->selectionModel()->selectedRows();
415     if(!selection.isEmpty())
416     {
417         TransactionDescDialog dlg(selection.at(0));
418         dlg.exec();
419     }
420 }
421
422 void TransactionView::clearOrphans()
423 {
424     if(!model)
425         return;
426
427     model->clearOrphans();
428 }
429
430 void TransactionView::openThirdPartyTxUrl(QString url)
431 {
432     if(!transactionView->selectionModel())
433        return;
434     QModelIndexList selection = transactionView->selectionModel()->selectedRows(0);
435     if(!selection.isEmpty())
436         QDesktopServices::openUrl(QUrl::fromUserInput(url.replace("%s", selection.at(0).data(TransactionTableModel::TxHashRole).toString())));
437 }
438
439 QWidget *TransactionView::createDateRangeWidget()
440 {
441     dateRangeWidget = new QFrame();
442     dateRangeWidget->setFrameStyle(QFrame::Panel | QFrame::Raised);
443     dateRangeWidget->setContentsMargins(1,1,1,1);
444     QHBoxLayout *layout = new QHBoxLayout(dateRangeWidget);
445     layout->setContentsMargins(0,0,0,0);
446     layout->addSpacing(23);
447     layout->addWidget(new QLabel(tr("Range:")));
448
449     dateFrom = new QDateTimeEdit(this);
450     dateFrom->setDisplayFormat("dd/MM/yy");
451     dateFrom->setCalendarPopup(true);
452     dateFrom->setMinimumWidth(100);
453     dateFrom->setDate(QDate::currentDate().addDays(-7));
454     layout->addWidget(dateFrom);
455     layout->addWidget(new QLabel(tr("to")));
456
457     dateTo = new QDateTimeEdit(this);
458     dateTo->setDisplayFormat("dd/MM/yy");
459     dateTo->setCalendarPopup(true);
460     dateTo->setMinimumWidth(100);
461     dateTo->setDate(QDate::currentDate());
462     layout->addWidget(dateTo);
463     layout->addStretch();
464
465     // Hide by default
466     dateRangeWidget->setVisible(false);
467
468     // Notify on change
469     connect(dateFrom, SIGNAL(dateChanged(QDate)), this, SLOT(dateRangeChanged()));
470     connect(dateTo, SIGNAL(dateChanged(QDate)), this, SLOT(dateRangeChanged()));
471
472     return dateRangeWidget;
473 }
474
475 void TransactionView::dateRangeChanged()
476 {
477     if(!transactionProxyModel)
478         return;
479     transactionProxyModel->setDateRange(
480             QDateTime(dateFrom->date()),
481             QDateTime(dateTo->date()).addDays(1));
482 }
483
484 void TransactionView::focusTransaction(const QModelIndex &idx)
485 {
486     if(!transactionProxyModel)
487         return;
488     QModelIndex targetIdx = transactionProxyModel->mapFromSource(idx);
489     transactionView->scrollTo(targetIdx);
490     transactionView->setCurrentIndex(targetIdx);
491     transactionView->setFocus();
492 }