See https://github.com/bitcoin/bitcoin/pull/1767
[novacoin.git] / src / qt / rpcconsole.cpp
1 #include "rpcconsole.h"
2 #include "ui_rpcconsole.h"
3
4 #include "clientmodel.h"
5 #include "bitcoinrpc.h"
6 #include "guiutil.h"
7 #include "dialogwindowflags.h"
8
9 #include <QTime>
10 #include <QTimer>
11 #include <QThread>
12 #include <QTextEdit>
13 #include <QKeyEvent>
14 #include <QUrl>
15 #include <QScrollBar>
16
17 #include <openssl/crypto.h>
18 #include <db_cxx.h>
19
20 // TODO: make it possible to filter out categories (esp debug messages when implemented)
21 // TODO: receive errors and debug messages through ClientModel
22
23 const int CONSOLE_HISTORY = 50;
24
25 const QSize ICON_SIZE(24, 24);
26
27 const int INITIAL_TRAFFIC_GRAPH_MINS = 30;
28
29 const struct {
30     const char *url;
31     const char *source;
32 } ICON_MAPPING[] = {
33     {"cmd-request", ":/icons/tx_input"},
34     {"cmd-reply", ":/icons/tx_output"},
35     {"cmd-error", ":/icons/tx_output"},
36     {"misc", ":/icons/tx_inout"},
37     {NULL, NULL}
38 };
39
40 /* Object for executing console RPC commands in a separate thread.
41 */
42 class RPCExecutor: public QObject
43 {
44     Q_OBJECT
45 public slots:
46     void start();
47     void request(const QString &command);
48 signals:
49     void reply(int category, const QString &command);
50 };
51
52 #include "rpcconsole.moc"
53
54 void RPCExecutor::start()
55 {
56    // Nothing to do
57 }
58
59 /**
60  * Split shell command line into a list of arguments. Aims to emulate \c bash and friends.
61  *
62  * - Arguments are delimited with whitespace
63  * - Extra whitespace at the beginning and end and between arguments will be ignored
64  * - Text can be "double" or 'single' quoted
65  * - The backslash \c \ is used as escape character
66  *   - Outside quotes, any character can be escaped
67  *   - Within double quotes, only escape \c " and backslashes before a \c " or another backslash
68  *   - Within single quotes, no escaping is possible and no special interpretation takes place
69  *
70  * @param[out]   args        Parsed arguments will be appended to this list
71  * @param[in]    strCommand  Command line to split
72  */
73 bool parseCommandLine(std::vector<std::string> &args, const std::string &strCommand)
74 {
75     enum CmdParseState
76     {
77         STATE_EATING_SPACES,
78         STATE_ARGUMENT,
79         STATE_SINGLEQUOTED,
80         STATE_DOUBLEQUOTED,
81         STATE_ESCAPE_OUTER,
82         STATE_ESCAPE_DOUBLEQUOTED
83     } state = STATE_EATING_SPACES;
84     std::string curarg;
85     foreach(char ch, strCommand)
86     {
87         switch(state)
88         {
89         case STATE_ARGUMENT: // In or after argument
90         case STATE_EATING_SPACES: // Handle runs of whitespace
91             switch(ch)
92             {
93             case '"': state = STATE_DOUBLEQUOTED; break;
94             case '\'': state = STATE_SINGLEQUOTED; break;
95             case '\\': state = STATE_ESCAPE_OUTER; break;
96             case ' ': case '\n': case '\t':
97                 if(state == STATE_ARGUMENT) // Space ends argument
98                 {
99                     args.push_back(curarg);
100                     curarg.clear();
101                 }
102                 state = STATE_EATING_SPACES;
103                 break;
104             default: curarg += ch; state = STATE_ARGUMENT;
105             }
106             break;
107         case STATE_SINGLEQUOTED: // Single-quoted string
108             switch(ch)
109             {
110             case '\'': state = STATE_ARGUMENT; break;
111             default: curarg += ch;
112             }
113             break;
114         case STATE_DOUBLEQUOTED: // Double-quoted string
115             switch(ch)
116             {
117             case '"': state = STATE_ARGUMENT; break;
118             case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break;
119             default: curarg += ch;
120             }
121             break;
122         case STATE_ESCAPE_OUTER: // '\' outside quotes
123             curarg += ch; state = STATE_ARGUMENT;
124             break;
125         case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text
126             if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself
127             curarg += ch; state = STATE_DOUBLEQUOTED;
128             break;
129         }
130     }
131     switch(state) // final state
132     {
133     case STATE_EATING_SPACES:
134         return true;
135     case STATE_ARGUMENT:
136         args.push_back(curarg);
137         return true;
138     default: // ERROR to end in one of the other states
139         return false;
140     }
141 }
142
143 void RPCExecutor::request(const QString &command)
144 {
145     std::vector<std::string> args;
146     if(!parseCommandLine(args, command.toStdString()))
147     {
148         emit reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \""));
149         return;
150     }
151     if(args.empty())
152         return; // Nothing to do
153     try
154     {
155         std::string strPrint;
156         // Convert argument list to JSON objects in method-dependent way,
157         // and pass it along with the method name to the dispatcher.
158         json_spirit::Value result = tableRPC.execute(
159             args[0],
160             RPCConvertValues(args[0], std::vector<std::string>(args.begin() + 1, args.end())));
161
162         // Format result reply
163         if (result.type() == json_spirit::null_type)
164             strPrint = "";
165         else if (result.type() == json_spirit::str_type)
166             strPrint = result.get_str();
167         else
168             strPrint = write_string(result, true);
169
170         emit reply(RPCConsole::CMD_REPLY, QString::fromStdString(strPrint));
171     }
172     catch (json_spirit::Object& objError)
173     {
174         try // Nice formatting for standard-format error
175         {
176             int code = find_value(objError, "code").get_int();
177             std::string message = find_value(objError, "message").get_str();
178             emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")");
179         }
180         catch(std::runtime_error &) // raised when converting to invalid type, i.e. missing code or message
181         {   // Show raw JSON object
182             emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(write_string(json_spirit::Value(objError), false)));
183         }
184     }
185     catch (std::exception& e)
186     {
187         emit reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what()));
188     }
189 }
190
191 RPCConsole::RPCConsole(QWidget *parent) :
192     QWidget(parent),
193     ui(new Ui::RPCConsole),
194     historyPtr(0)
195 {
196     ui->setupUi(this);
197
198 #ifndef Q_OS_MAC
199     ui->openDebugLogfileButton->setIcon(QIcon(":/icons/export"));
200     ui->openConfigurationfileButton->setIcon(QIcon(":/icons/export"));
201     ui->showCLOptionsButton->setIcon(QIcon(":/icons/options"));
202 #endif
203
204     // Install event filter for up and down arrow
205     ui->lineEdit->installEventFilter(this);
206     ui->messagesWidget->installEventFilter(this);
207
208     connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
209     connect(ui->btnClearTrafficGraph, SIGNAL(clicked()), ui->trafficGraph, SLOT(clear()));
210
211     // set library version labels
212     ui->openSSLVersion->setText(SSLeay_version(SSLEAY_VERSION));
213     ui->berkeleyDBVersion->setText(DbEnv::version(0, 0, 0));
214
215     startExecutor();
216     setTrafficGraphRange(INITIAL_TRAFFIC_GRAPH_MINS);
217
218     clear();
219 }
220
221 RPCConsole::~RPCConsole()
222 {
223     emit stopExecutor();
224     delete ui;
225 }
226
227 bool RPCConsole::eventFilter(QObject* obj, QEvent *event)
228 {
229     if(event->type() == QEvent::KeyPress) // Special key handling
230     {
231         QKeyEvent *keyevt = static_cast<QKeyEvent*>(event);
232         int key = keyevt->key();
233         Qt::KeyboardModifiers mod = keyevt->modifiers();
234         switch(key)
235         {
236         case Qt::Key_Up: if(obj == ui->lineEdit) { browseHistory(-1); return true; } break;
237         case Qt::Key_Down: if(obj == ui->lineEdit) { browseHistory(1); return true; } break;
238         case Qt::Key_PageUp: /* pass paging keys to messages widget */
239         case Qt::Key_PageDown:
240             if(obj == ui->lineEdit)
241             {
242                 QApplication::postEvent(ui->messagesWidget, new QKeyEvent(*keyevt));
243                 return true;
244             }
245             break;
246         default:
247             // Typing in messages widget brings focus to line edit, and redirects key there
248             // Exclude most combinations and keys that emit no text, except paste shortcuts
249             if(obj == ui->messagesWidget && (
250                   (!mod && !keyevt->text().isEmpty() && key != Qt::Key_Tab) ||
251                   ((mod & Qt::ControlModifier) && key == Qt::Key_V) ||
252                   ((mod & Qt::ShiftModifier) && key == Qt::Key_Insert)))
253             {
254                 ui->lineEdit->setFocus();
255                 QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt));
256                 return true;
257             }
258         }
259     }
260     return QWidget::eventFilter(obj, event);
261 }
262
263 void RPCConsole::setClientModel(ClientModel *model)
264 {
265     this->clientModel = model;
266     ui->trafficGraph->setClientModel(model);
267     if(model)
268     {
269         // Subscribe to information, replies, messages, errors
270         connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
271         connect(model, SIGNAL(numBlocksChanged(int,int)), this, SLOT(setNumBlocks(int,int)));
272
273         updateTrafficStats(model->getTotalBytesRecv(), model->getTotalBytesSent());
274         connect(model, SIGNAL(bytesChanged(quint64,quint64)), this, SLOT(updateTrafficStats(quint64, quint64)));
275         // Provide initial values
276         ui->clientVersion->setText(model->formatFullVersion());
277         ui->clientName->setText(model->clientName());
278         ui->buildDate->setText(model->formatBuildDate());
279         ui->startupTime->setText(model->formatClientStartupTime());
280
281         setNumConnections(model->getNumConnections());
282         ui->isTestNet->setChecked(model->isTestNet());
283
284         setNumBlocks(model->getNumBlocks(), model->getNumBlocksOfPeers());
285     }
286 }
287
288 static QString categoryClass(int category)
289 {
290     switch(category)
291     {
292     case RPCConsole::CMD_REQUEST:  return "cmd-request"; break;
293     case RPCConsole::CMD_REPLY:    return "cmd-reply"; break;
294     case RPCConsole::CMD_ERROR:    return "cmd-error"; break;
295     default:                       return "misc";
296     }
297 }
298
299 void RPCConsole::clear()
300 {
301     ui->messagesWidget->clear();
302     history.clear();
303     historyPtr = 0;
304     ui->lineEdit->clear();
305     ui->lineEdit->setFocus();
306
307     // Add smoothly scaled icon images.
308     // (when using width/height on an img, Qt uses nearest instead of linear interpolation)
309     for(int i=0; ICON_MAPPING[i].url; ++i)
310     {
311         ui->messagesWidget->document()->addResource(
312                     QTextDocument::ImageResource,
313                     QUrl(ICON_MAPPING[i].url),
314                     QImage(ICON_MAPPING[i].source).scaled(ICON_SIZE, Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
315     }
316
317     // Set default style sheet
318     ui->messagesWidget->document()->setDefaultStyleSheet(
319                 "table { }"
320                 "td.time { color: #808080; padding-top: 3px; } "
321                 "td.message { font-family: Monospace; } "
322                 "td.cmd-request { color: #006060; } "
323                 "td.cmd-error { color: red; } "
324                 "b { color: #006060; } "
325                 );
326
327     message(CMD_REPLY, (tr("Welcome to the NovaCoin RPC console.") + "<br>" +
328                         tr("Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.") + "<br>" +
329                         tr("Type <b>help</b> for an overview of available commands.")), true);
330 }
331
332 void RPCConsole::message(int category, const QString &message, bool html)
333 {
334     QTime time = QTime::currentTime();
335     QString timeString = time.toString();
336     QString out;
337     out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>";
338     out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>";
339     out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">";
340     if(html)
341         out += message;
342     else
343         out += GUIUtil::HtmlEscape(message, true);
344     out += "</td></tr></table>";
345     ui->messagesWidget->append(out);
346 }
347
348 void RPCConsole::setNumConnections(int count)
349 {
350     if (!clientModel)
351         return;
352
353     QString connections = QString::number(count) + " (";
354     connections += tr("Inbound:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_IN)) + " / ";
355     connections += tr("Outbound:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_OUT)) + ")";
356
357     ui->numberOfConnections->setText(connections);
358 }
359
360 void RPCConsole::setNumBlocks(int count, int countOfPeers)
361 {
362     ui->numberOfBlocks->setText(QString::number(count));
363     ui->totalBlocks->setText(QString::number(countOfPeers));
364     if(clientModel)
365     {
366         // If there is no current number available display N/A instead of 0, which can't ever be true
367         ui->totalBlocks->setText(clientModel->getNumBlocksOfPeers() == 0 ? tr("N/A") : QString::number(clientModel->getNumBlocksOfPeers()));
368         ui->lastBlockTime->setText(clientModel->getLastBlockDate().toString());
369     }
370 }
371
372 void RPCConsole::on_lineEdit_returnPressed()
373 {
374     QString cmd = ui->lineEdit->text();
375     ui->lineEdit->clear();
376
377     if(!cmd.isEmpty())
378     {
379         message(CMD_REQUEST, cmd);
380         emit cmdRequest(cmd);
381         // Remove command, if already in history
382         history.removeOne(cmd);
383         // Append command to history
384         history.append(cmd);
385         // Enforce maximum history size
386         while(history.size() > CONSOLE_HISTORY)
387             history.removeFirst();
388         // Set pointer to end of history
389         historyPtr = history.size();
390         // Scroll console view to end
391         scrollToEnd();
392     }
393 }
394
395 void RPCConsole::browseHistory(int offset)
396 {
397     historyPtr += offset;
398     if(historyPtr < 0)
399         historyPtr = 0;
400     if(historyPtr > history.size())
401         historyPtr = history.size();
402     QString cmd;
403     if(historyPtr < history.size())
404         cmd = history.at(historyPtr);
405     ui->lineEdit->setText(cmd);
406 }
407
408 void RPCConsole::startExecutor()
409 {
410     QThread* thread = new QThread;
411     RPCExecutor *executor = new RPCExecutor();
412     executor->moveToThread(thread);
413
414     // Notify executor when thread started (in executor thread)
415     connect(thread, SIGNAL(started()), executor, SLOT(start()));
416     // Replies from executor object must go to this object
417     connect(executor, SIGNAL(reply(int,QString)), this, SLOT(message(int,QString)));
418     // Requests from this object must go to executor
419     connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString)));
420     // On stopExecutor signal
421     // - queue executor for deletion (in execution thread)
422     // - quit the Qt event loop in the execution thread
423     connect(this, SIGNAL(stopExecutor()), executor, SLOT(deleteLater()));
424     connect(this, SIGNAL(stopExecutor()), thread, SLOT(quit()));
425     // Queue the thread for deletion (in this thread) when it is finished
426     connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
427
428     // Default implementation of QThread::run() simply spins up an event loop in the thread,
429     // which is what we want.
430     thread->start();
431 }
432
433 void RPCConsole::on_tabWidget_currentChanged(int index)
434 {
435     if(ui->tabWidget->widget(index) == ui->tab_console)
436     {
437         ui->lineEdit->setFocus();
438     }
439 }
440
441 void RPCConsole::on_openDebugLogfileButton_clicked()
442 {
443     GUIUtil::openDebugLogfile();
444 }
445
446 void RPCConsole::on_openConfigurationfileButton_clicked()
447 {
448     GUIUtil::openConfigfile();
449 }
450
451 void RPCConsole::scrollToEnd()
452 {
453     QScrollBar *scrollbar = ui->messagesWidget->verticalScrollBar();
454     scrollbar->setValue(scrollbar->maximum());
455 }
456
457 void RPCConsole::on_showCLOptionsButton_clicked()
458 {
459     GUIUtil::HelpMessageBox help;
460     help.exec();
461 }
462 void RPCConsole::on_sldGraphRange_valueChanged(int value)
463 {
464     const int multiplier = 5; // each position on the slider represents 5 min
465     int mins = value * multiplier;
466     setTrafficGraphRange(mins);
467 }
468
469 QString RPCConsole::FormatBytes(quint64 bytes)
470 {
471     if(bytes < 1024)
472         return QString(tr("%1 B")).arg(bytes);
473     if(bytes < 1024 * 1024)
474         return QString(tr("%1 KB")).arg(bytes / 1024);
475     if(bytes < 1024 * 1024 * 1024)
476         return QString(tr("%1 MB")).arg(bytes / 1024 / 1024);
477
478     return QString(tr("%1 GB")).arg(bytes / 1024 / 1024 / 1024);
479 }
480
481 void RPCConsole::setTrafficGraphRange(int mins)
482 {
483     ui->trafficGraph->setGraphRangeMins(mins);
484     ui->lblGraphRange->setText(GUIUtil::formatDurationStr(mins * 60));
485 }
486
487 void RPCConsole::updateTrafficStats(quint64 totalBytesIn, quint64 totalBytesOut)
488 {
489     ui->lblBytesIn->setText(FormatBytes(totalBytesIn));
490     ui->lblBytesOut->setText(FormatBytes(totalBytesOut));
491 }
492
493 void RPCConsole::resizeEvent(QResizeEvent *event)
494 {
495     QWidget::resizeEvent(event);
496 }
497
498 void RPCConsole::showEvent(QShowEvent *event)
499 {
500     QWidget::showEvent(event);
501
502     if (!clientModel)
503         return;
504 }
505
506 void RPCConsole::hideEvent(QHideEvent *event)
507 {
508     QWidget::hideEvent(event);
509
510     if (!clientModel)
511         return;
512 }
513
514 void RPCConsole::keyPressEvent(QKeyEvent *event)
515 {
516 #ifdef ANDROID
517     if(windowType() != Qt::Widget && event->key() == Qt::Key_Back)
518     {
519         close();
520     }
521 #else
522     if(windowType() != Qt::Widget && event->key() == Qt::Key_Escape)
523     {
524         close();
525     }
526 #endif
527 }