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