1 #include "rpcconsole.h"
2 #include "ui_rpcconsole.h"
4 #include "clientmodel.h"
5 #include "bitcoinrpc.h"
7 #include "dialogwindowflags.h"
17 #include <openssl/crypto.h>
19 // TODO: make it possible to filter out categories (esp debug messages when implemented)
20 // TODO: receive errors and debug messages through ClientModel
22 const int CONSOLE_SCROLLBACK = 50;
23 const int CONSOLE_HISTORY = 50;
25 const QSize ICON_SIZE(24, 24);
31 {"cmd-request", ":/icons/tx_input"},
32 {"cmd-reply", ":/icons/tx_output"},
33 {"cmd-error", ":/icons/tx_output"},
34 {"misc", ":/icons/tx_inout"},
38 /* Object for executing console RPC commands in a separate thread.
40 class RPCExecutor: public QObject
45 void request(const QString &command);
47 void reply(int category, const QString &command);
50 #include "rpcconsole.moc"
52 void RPCExecutor::start()
58 * Split shell command line into a list of arguments. Aims to emulate \c bash and friends.
60 * - Arguments are delimited with whitespace
61 * - Extra whitespace at the beginning and end and between arguments will be ignored
62 * - Text can be "double" or 'single' quoted
63 * - The backslash \c \ is used as escape character
64 * - Outside quotes, any character can be escaped
65 * - Within double quotes, only escape \c " and backslashes before a \c " or another backslash
66 * - Within single quotes, no escaping is possible and no special interpretation takes place
68 * @param[out] args Parsed arguments will be appended to this list
69 * @param[in] strCommand Command line to split
71 bool parseCommandLine(std::vector<std::string> &args, const std::string &strCommand)
80 STATE_ESCAPE_DOUBLEQUOTED
81 } state = STATE_EATING_SPACES;
83 foreach(char ch, strCommand)
87 case STATE_ARGUMENT: // In or after argument
88 case STATE_EATING_SPACES: // Handle runs of whitespace
91 case '"': state = STATE_DOUBLEQUOTED; break;
92 case '\'': state = STATE_SINGLEQUOTED; break;
93 case '\\': state = STATE_ESCAPE_OUTER; break;
94 case ' ': case '\n': case '\t':
95 if(state == STATE_ARGUMENT) // Space ends argument
97 args.push_back(curarg);
100 state = STATE_EATING_SPACES;
102 default: curarg += ch; state = STATE_ARGUMENT;
105 case STATE_SINGLEQUOTED: // Single-quoted string
108 case '\'': state = STATE_ARGUMENT; break;
109 default: curarg += ch;
112 case STATE_DOUBLEQUOTED: // Double-quoted string
115 case '"': state = STATE_ARGUMENT; break;
116 case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break;
117 default: curarg += ch;
120 case STATE_ESCAPE_OUTER: // '\' outside quotes
121 curarg += ch; state = STATE_ARGUMENT;
123 case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text
124 if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself
125 curarg += ch; state = STATE_DOUBLEQUOTED;
129 switch(state) // final state
131 case STATE_EATING_SPACES:
134 args.push_back(curarg);
136 default: // ERROR to end in one of the other states
141 void RPCExecutor::request(const QString &command)
143 std::vector<std::string> args;
144 if(!parseCommandLine(args, command.toStdString()))
146 emit reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \""));
150 return; // Nothing to do
153 std::string strPrint;
154 // Convert argument list to JSON objects in method-dependent way,
155 // and pass it along with the method name to the dispatcher.
156 json_spirit::Value result = tableRPC.execute(
158 RPCConvertValues(args[0], std::vector<std::string>(args.begin() + 1, args.end())));
160 // Format result reply
161 if (result.type() == json_spirit::null_type)
163 else if (result.type() == json_spirit::str_type)
164 strPrint = result.get_str();
166 strPrint = write_string(result, true);
168 emit reply(RPCConsole::CMD_REPLY, QString::fromStdString(strPrint));
170 catch (json_spirit::Object& objError)
172 try // Nice formatting for standard-format error
174 int code = find_value(objError, "code").get_int();
175 std::string message = find_value(objError, "message").get_str();
176 emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")");
178 catch(std::runtime_error &) // raised when converting to invalid type, i.e. missing code or message
179 { // Show raw JSON object
180 emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(write_string(json_spirit::Value(objError), false)));
183 catch (std::exception& e)
185 emit reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what()));
189 RPCConsole::RPCConsole(QWidget *parent) :
190 QDialog(parent, DIALOGWINDOWHINTS),
191 ui(new Ui::RPCConsole),
197 ui->openDebugLogfileButton->setIcon(QIcon(":/icons/export"));
198 ui->showCLOptionsButton->setIcon(QIcon(":/icons/options"));
201 // Install event filter for up and down arrow
202 ui->lineEdit->installEventFilter(this);
203 ui->messagesWidget->installEventFilter(this);
205 connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
207 // set OpenSSL version label
208 ui->openSSLVersion->setText(SSLeay_version(SSLEAY_VERSION));
215 RPCConsole::~RPCConsole()
221 bool RPCConsole::eventFilter(QObject* obj, QEvent *event)
223 if(event->type() == QEvent::KeyPress) // Special key handling
225 QKeyEvent *keyevt = static_cast<QKeyEvent*>(event);
226 int key = keyevt->key();
227 Qt::KeyboardModifiers mod = keyevt->modifiers();
230 case Qt::Key_Up: if(obj == ui->lineEdit) { browseHistory(-1); return true; } break;
231 case Qt::Key_Down: if(obj == ui->lineEdit) { browseHistory(1); return true; } break;
232 case Qt::Key_PageUp: /* pass paging keys to messages widget */
233 case Qt::Key_PageDown:
234 if(obj == ui->lineEdit)
236 QApplication::postEvent(ui->messagesWidget, new QKeyEvent(*keyevt));
241 // Typing in messages widget brings focus to line edit, and redirects key there
242 // Exclude most combinations and keys that emit no text, except paste shortcuts
243 if(obj == ui->messagesWidget && (
244 (!mod && !keyevt->text().isEmpty() && key != Qt::Key_Tab) ||
245 ((mod & Qt::ControlModifier) && key == Qt::Key_V) ||
246 ((mod & Qt::ShiftModifier) && key == Qt::Key_Insert)))
248 ui->lineEdit->setFocus();
249 QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt));
254 return QDialog::eventFilter(obj, event);
257 void RPCConsole::setClientModel(ClientModel *model)
259 this->clientModel = model;
262 // Subscribe to information, replies, messages, errors
263 connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
264 connect(model, SIGNAL(numBlocksChanged(int,int)), this, SLOT(setNumBlocks(int,int)));
266 // Provide initial values
267 ui->clientVersion->setText(model->formatFullVersion());
268 ui->clientName->setText(model->clientName());
269 ui->buildDate->setText(model->formatBuildDate());
270 ui->startupTime->setText(model->formatClientStartupTime());
272 setNumConnections(model->getNumConnections());
273 ui->isTestNet->setChecked(model->isTestNet());
275 setNumBlocks(model->getNumBlocks(), model->getNumBlocksOfPeers());
279 static QString categoryClass(int category)
283 case RPCConsole::CMD_REQUEST: return "cmd-request"; break;
284 case RPCConsole::CMD_REPLY: return "cmd-reply"; break;
285 case RPCConsole::CMD_ERROR: return "cmd-error"; break;
286 default: return "misc";
290 void RPCConsole::clear()
292 ui->messagesWidget->clear();
293 ui->lineEdit->clear();
294 ui->lineEdit->setFocus();
296 // Add smoothly scaled icon images.
297 // (when using width/height on an img, Qt uses nearest instead of linear interpolation)
298 for(int i=0; ICON_MAPPING[i].url; ++i)
300 ui->messagesWidget->document()->addResource(
301 QTextDocument::ImageResource,
302 QUrl(ICON_MAPPING[i].url),
303 QImage(ICON_MAPPING[i].source).scaled(ICON_SIZE, Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
306 // Set default style sheet
307 ui->messagesWidget->document()->setDefaultStyleSheet(
309 "td.time { color: #808080; padding-top: 3px; } "
310 "td.message { font-family: Monospace; font-size: 12px; } "
311 "td.cmd-request { color: #006060; } "
312 "td.cmd-error { color: red; } "
313 "b { color: #006060; } "
316 message(CMD_REPLY, (tr("Welcome to the NovaCoin RPC console.") + "<br>" +
317 tr("Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.") + "<br>" +
318 tr("Type <b>help</b> for an overview of available commands.")), true);
321 void RPCConsole::message(int category, const QString &message, bool html)
323 QTime time = QTime::currentTime();
324 QString timeString = time.toString();
326 out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>";
327 out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>";
328 out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">";
332 out += GUIUtil::HtmlEscape(message, true);
333 out += "</td></tr></table>";
334 ui->messagesWidget->append(out);
337 void RPCConsole::setNumConnections(int count)
339 ui->numberOfConnections->setText(QString::number(count));
342 void RPCConsole::setNumBlocks(int count, int countOfPeers)
344 ui->numberOfBlocks->setText(QString::number(count));
345 ui->totalBlocks->setText(QString::number(countOfPeers));
348 // If there is no current number available display N/A instead of 0, which can't ever be true
349 ui->totalBlocks->setText(clientModel->getNumBlocksOfPeers() == 0 ? tr("N/A") : QString::number(clientModel->getNumBlocksOfPeers()));
350 ui->lastBlockTime->setText(clientModel->getLastBlockDate().toString());
354 void RPCConsole::on_lineEdit_returnPressed()
356 QString cmd = ui->lineEdit->text();
357 ui->lineEdit->clear();
361 message(CMD_REQUEST, cmd);
362 emit cmdRequest(cmd);
363 // Truncate history from current position
364 history.erase(history.begin() + historyPtr, history.end());
365 // Append command to history
367 // Enforce maximum history size
368 while(history.size() > CONSOLE_HISTORY)
369 history.removeFirst();
370 // Set pointer to end of history
371 historyPtr = history.size();
372 // Scroll console view to end
377 void RPCConsole::browseHistory(int offset)
379 historyPtr += offset;
382 if(historyPtr > history.size())
383 historyPtr = history.size();
385 if(historyPtr < history.size())
386 cmd = history.at(historyPtr);
387 ui->lineEdit->setText(cmd);
390 void RPCConsole::startExecutor()
392 QThread* thread = new QThread;
393 RPCExecutor *executor = new RPCExecutor();
394 executor->moveToThread(thread);
396 // Notify executor when thread started (in executor thread)
397 connect(thread, SIGNAL(started()), executor, SLOT(start()));
398 // Replies from executor object must go to this object
399 connect(executor, SIGNAL(reply(int,QString)), this, SLOT(message(int,QString)));
400 // Requests from this object must go to executor
401 connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString)));
402 // On stopExecutor signal
403 // - queue executor for deletion (in execution thread)
404 // - quit the Qt event loop in the execution thread
405 connect(this, SIGNAL(stopExecutor()), executor, SLOT(deleteLater()));
406 connect(this, SIGNAL(stopExecutor()), thread, SLOT(quit()));
407 // Queue the thread for deletion (in this thread) when it is finished
408 connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
410 // Default implementation of QThread::run() simply spins up an event loop in the thread,
411 // which is what we want.
415 void RPCConsole::on_tabWidget_currentChanged(int index)
417 if(ui->tabWidget->widget(index) == ui->tab_console)
419 ui->lineEdit->setFocus();
423 void RPCConsole::on_openDebugLogfileButton_clicked()
425 GUIUtil::openDebugLogfile();
428 void RPCConsole::scrollToEnd()
430 QScrollBar *scrollbar = ui->messagesWidget->verticalScrollBar();
431 scrollbar->setValue(scrollbar->maximum());
434 void RPCConsole::on_showCLOptionsButton_clicked()
436 GUIUtil::HelpMessageBox help;