openMSX
CommandConsole.cc
Go to the documentation of this file.
1 #include "CommandConsole.hh"
2 #include "CommandException.hh"
4 #include "Completer.hh"
5 #include "Interpreter.hh"
6 #include "Keys.hh"
7 #include "FileContext.hh"
8 #include "FileException.hh"
9 #include "FileOperations.hh"
10 #include "CliComm.hh"
11 #include "InputEvents.hh"
12 #include "Display.hh"
13 #include "EventDistributor.hh"
14 #include "Version.hh"
15 #include "checked_cast.hh"
16 #include "utf8_unchecked.hh"
17 #include "StringOp.hh"
18 #include "ScopedAssign.hh"
19 #include "xrange.hh"
20 #include <algorithm>
21 #include <fstream>
22 #include <cassert>
23 
24 using std::min;
25 using std::max;
26 using std::string;
27 
28 namespace openmsx {
29 
30 // class ConsoleLine
31 
33 {
34 }
35 
37  : line(line_.str())
38  , chunks(1, {rgb, 0})
39 {
40 }
41 
42 void ConsoleLine::addChunk(string_ref text, unsigned rgb)
43 {
44  chunks.emplace_back(rgb, line.size());
45  line.append(text.data(), text.size());
46 }
47 
48 unsigned ConsoleLine::numChars() const
49 {
50  return unsigned(utf8::unchecked::size(line));
51 }
52 
53 unsigned ConsoleLine::chunkColor(unsigned i) const
54 {
55  assert(i < chunks.size());
56  return chunks[i].first;
57 }
58 
60 {
61  assert(i < chunks.size());
62  auto pos = chunks[i].second;
63  auto len = ((i + 1) == chunks.size())
65  : chunks[i + 1].second - pos;
66  return string_ref(line).substr(pos, len);
67 }
68 
69 ConsoleLine ConsoleLine::substr(unsigned pos, unsigned len) const
70 {
71  ConsoleLine result;
72  if (chunks.empty()) {
73  assert(line.empty());
74  assert(pos == 0);
75  return result;
76  }
77 
78  auto b = begin(line);
80  auto e = b;
81  while (len-- && (e != end(line))) {
83  }
84  result.line.assign(b, e);
85 
86  unsigned bpos = b - begin(line);
87  unsigned bend = e - begin(line);
88  unsigned i = 1;
89  while ((i < chunks.size()) && (chunks[i].second <= bpos)) {
90  ++i;
91  }
92  result.chunks.emplace_back(chunks[i - 1].first, 0);
93  while ((i < chunks.size()) && (chunks[i].second < bend)) {
94  result.chunks.emplace_back(chunks[i].first,
95  chunks[i].second - bpos);
96  ++i;
97  }
98  return result;
99 }
100 
101 // class CommandConsole
102 
103 static const char* const PROMPT_NEW = "> ";
104 static const char* const PROMPT_CONT = "| ";
105 static const char* const PROMPT_BUSY = "*busy*";
106 
108  GlobalCommandController& commandController_,
109  EventDistributor& eventDistributor_,
110  Display& display_)
111  : commandController(commandController_)
112  , eventDistributor(eventDistributor_)
113  , display(display_)
114  , consoleSetting(
115  commandController, "console",
116  "turns console display on/off", false, Setting::DONT_SAVE)
117  , historySizeSetting(
118  commandController, "console_history_size",
119  "amount of commands kept in console history", 100, 0, 10000)
120  , removeDoublesSetting(
121  commandController, "console_remove_doubles",
122  "don't add the command to history if it's the same as the previous one",
123  true)
124  , history(std::max(1, historySizeSetting.getInt()))
125  , executingCommand(false)
126 {
127  resetScrollBack();
128  prompt = PROMPT_NEW;
129  newLineConsole(prompt);
130  loadHistory();
131  putPrompt();
132  Completer::setOutput(this);
133 
134  const auto& fullVersion = Version::full();
135  print(fullVersion);
136  print(string(fullVersion.size(), '-'));
137  print("\n"
138  "General information about openMSX is available at "
139  "http://www.openmsx.org.\n"
140  "\n"
141  "Type 'help' to see a list of available commands "
142  "(use <PgUp>/<PgDn> to scroll).\n"
143  "Or read the Console Command Reference in the manual.\n"
144  "\n");
145 
146  commandController.getInterpreter().setOutput(this);
147  eventDistributor.registerEventListener(
149  // also listen to KEY_UP events, so that we can consume them
150  eventDistributor.registerEventListener(
152 }
153 
155 {
156  eventDistributor.unregisterEventListener(OPENMSX_KEY_DOWN_EVENT, *this);
157  eventDistributor.unregisterEventListener(OPENMSX_KEY_UP_EVENT, *this);
158  commandController.getInterpreter().setOutput(nullptr);
159  Completer::setOutput(nullptr);
160 }
161 
162 void CommandConsole::saveHistory()
163 {
164  try {
165  UserFileContext context("console");
166  std::ofstream outputfile;
167  FileOperations::openofstream(outputfile,
168  context.resolveCreate("history.txt"));
169  if (!outputfile) {
170  throw FileException(
171  "Error while saving the console history.");
172  }
173  for (auto& s : history) {
174  outputfile << string_ref(s).substr(prompt.size()) << '\n';
175  }
176  } catch (FileException& e) {
177  commandController.getCliComm().printWarning(e.getMessage());
178  }
179 }
180 
181 void CommandConsole::loadHistory()
182 {
183  try {
184  UserFileContext context("console");
185  std::ifstream inputfile(
186  context.resolveCreate("history.txt").c_str());
187  string line;
188  while (inputfile) {
189  getline(inputfile, line);
190  if (!line.empty()) {
191  putCommandHistory(prompt + line);
192  }
193  }
194  } catch (FileException&) {
195  // Error while loading the console history, ignore
196  }
197 }
198 
199 void CommandConsole::getCursorPosition(unsigned& xPosition, unsigned& yPosition) const
200 {
201  xPosition = cursorPosition % getColumns();
202  unsigned num = lines[0].numChars() / getColumns();
203  yPosition = num - (cursorPosition / getColumns());
204 }
205 
207 {
208  unsigned count = 0;
209  for (auto buf : xrange(lines.size())) {
210  count += (lines[buf].numChars() / getColumns()) + 1;
211  if (count > line) {
212  return lines[buf].substr(
213  (count - line - 1) * getColumns(),
214  getColumns());
215  }
216  }
217  return ConsoleLine();
218 }
219 
220 int CommandConsole::signalEvent(const std::shared_ptr<const Event>& event)
221 {
222  auto& keyEvent = checked_cast<const KeyEvent&>(*event);
223  if (!consoleSetting.getBoolean()) return 0;
224 
225  // If the console is open then don't pass the event to the MSX
226  // (whetever the (keyboard) event is). If the event has a meaning for
227  // the console, then also don't pass the event to the hotkey system.
228  // For example PgUp, PgDown are keys that have both a meaning in the
229  // console and are used by standard key bindings.
230  if (event->getType() == OPENMSX_KEY_DOWN_EVENT) {
231  if (!executingCommand) {
232  if (handleEvent(keyEvent)) {
233  // event was used
234  display.repaintDelayed(40000); // 25fps
235  return EventDistributor::HOTKEY; // block HOTKEY and MSX
236  }
237  } else {
238  // For commands that take a long time to execute (e.g.
239  // a loadstate that needs to create a filepool index),
240  // we also send events during the execution (so that
241  // we can show progress on the OSD). In that case
242  // ignore extra input events.
243  }
244  } else {
245  assert(event->getType() == OPENMSX_KEY_UP_EVENT);
246  }
247  return EventDistributor::MSX; // block MSX
248 }
249 
250 bool CommandConsole::handleEvent(const KeyEvent& keyEvent)
251 {
252  auto keyCode = keyEvent.getKeyCode();
253  int key = keyCode & Keys::K_MASK;
254  int mod = keyCode & ~Keys::K_MASK;
255 
256  switch (mod) {
257  case Keys::KM_CTRL:
258  switch (key) {
259  case Keys::K_H:
260  backspace();
261  return true;
262  case Keys::K_A:
263  cursorPosition = unsigned(prompt.size());
264  return true;
265  case Keys::K_E:
266  cursorPosition = lines[0].numChars();
267  return true;
268  case Keys::K_C:
269  clearCommand();
270  return true;
271  }
272  break;
273  case Keys::KM_SHIFT:
274  switch (key) {
275  case Keys::K_PAGEUP:
276  scroll(max<int>(getRows() - 1, 1));
277  return true;
278  case Keys::K_PAGEDOWN:
279  scroll(-max<int>(getRows() - 1, 1));
280  return true;
281  }
282  break;
283  case 0: // no modifier
284  switch (key) {
285  case Keys::K_PAGEUP:
286  scroll(1);
287  return true;
288  case Keys::K_PAGEDOWN:
289  scroll(-1);
290  return true;
291  case Keys::K_UP:
292  prevCommand();
293  return true;
294  case Keys::K_DOWN:
295  nextCommand();
296  return true;
297  case Keys::K_BACKSPACE:
298  backspace();
299  return true;
300  case Keys::K_DELETE:
301  delete_key();
302  return true;
303  case Keys::K_TAB:
304  tabCompletion();
305  return true;
306  case Keys::K_RETURN:
307  case Keys::K_KP_ENTER:
308  commandExecute();
309  cursorPosition = unsigned(prompt.size());
310  return true;
311  case Keys::K_LEFT:
312  if (cursorPosition > prompt.size()) {
313  --cursorPosition;
314  }
315  return true;
316  case Keys::K_RIGHT:
317  if (cursorPosition < lines[0].numChars()) {
318  ++cursorPosition;
319  }
320  return true;
321  case Keys::K_HOME:
322  cursorPosition = unsigned(prompt.size());
323  return true;
324  case Keys::K_END:
325  cursorPosition = lines[0].numChars();
326  return true;
327  }
328  break;
329  }
330 
331  uint16_t unicode = keyEvent.getUnicode();
332  if (!unicode || (mod & Keys::KM_META)) {
333  // Disallow META modifer for 'normal' key presses because on
334  // MacOSX Cmd+L is used as a hotkey to toggle the console.
335  // Hopefully there are no systems that require META to type
336  // normal keys. However there _are_ systems that require the
337  // following modifiers, some examples:
338  // MODE: to type '1-9' on a N900
339  // ALT: to type | [ ] on a azerty keyboard layout
340  // CTRL+ALT: to type '#' on a spanish keyboard layout (windows)
341  //
342  // Event was not used by the console, allow the other
343  // subsystems to process it. E.g. F10, or Cmd+L to close the
344  // console.
345  return false;
346  }
347 
348  if (unicode >= 0x20) {
349  normalKey(unicode);
350  } else {
351  // Skip CTRL-<X> combinations, but still return true.
352  }
353  return true;
354 }
355 
356 void CommandConsole::output(string_ref text)
357 {
358  print(text);
359 }
360 
361 unsigned CommandConsole::getOutputColumns() const
362 {
363  return getColumns();
364 }
365 
366 void CommandConsole::print(string_ref text, unsigned rgb)
367 {
368  while (true) {
369  auto pos = text.find('\n');
370  newLineConsole(ConsoleLine(text.substr(0, pos), rgb));
371  if (pos == string_ref::npos) return;
372  text = text.substr(pos + 1); // skip newline
373  if (text.empty()) return;
374  }
375 }
376 
377 void CommandConsole::newLineConsole(string_ref line)
378 {
379  newLineConsole(ConsoleLine(line));
380 }
381 
382 void CommandConsole::newLineConsole(ConsoleLine line)
383 {
384  if (lines.isFull()) {
385  lines.removeBack();
386  }
387  ConsoleLine tmp = lines[0];
388  lines[0] = line;
389  lines.addFront(tmp);
390 }
391 
392 void CommandConsole::putCommandHistory(const string& command)
393 {
394  // TODO don't store PROMPT as part of history
395  if (command == prompt) {
396  return;
397  }
398  if (removeDoublesSetting.getBoolean() && !history.empty()
399  && (history.back() == command)) {
400  return;
401  }
402 
403  if (history.full()) history.pop_front();
404  history.push_back(command);
405 
406 }
407 
408 void CommandConsole::commandExecute()
409 {
410  resetScrollBack();
411  putCommandHistory(lines[0].str());
412  saveHistory(); // save at this point already, so that we don't lose history in case of a crash
413 
414  commandBuffer += lines[0].str().substr(prompt.size()) + '\n';
415  newLineConsole(lines[0]);
416  if (commandController.isComplete(commandBuffer)) {
417  // Normally the busy promt is NOT shown (not even very briefly
418  // because the screen is not redrawn), though for some commands
419  // that potentially take a long time to execute, we explictly
420  // send events, see also comment in handleEvent().
421  prompt = PROMPT_BUSY;
422  putPrompt();
423 
424  try {
425  ScopedAssign<bool> sa(executingCommand, true);
426  auto resultObj = commandController.executeCommand(
427  commandBuffer);
428  auto result = resultObj.getString();
429  if (!result.empty()) {
430  print(result);
431  }
432  } catch (CommandException& e) {
433  print(e.getMessage(), 0xff0000);
434  }
435  commandBuffer.clear();
436  prompt = PROMPT_NEW;
437  } else {
438  prompt = PROMPT_CONT;
439  }
440  putPrompt();
441 }
442 
443 ConsoleLine CommandConsole::highLight(string_ref line)
444 {
445  assert(line.starts_with(prompt));
446  string_ref command = line.substr(prompt.size());
447  ConsoleLine result;
448  result.addChunk(prompt, 0xffffff);
449 
450  TclParser parser = commandController.getInterpreter().parse(command);
451  string colors = parser.getColors();
452  assert(colors.size() == command.size());
453 
454  unsigned pos = 0;
455  while (pos != colors.size()) {
456  char col = colors[pos];
457  unsigned pos2 = pos++;
458  while ((pos != colors.size()) && (colors[pos] == col)) {
459  ++pos;
460  }
461  // TODO make these color configurable?
462  unsigned rgb;
463  switch (col) {
464  case 'E': rgb = 0xff0000; break; // error
465  case 'c': rgb = 0x5c5cff; break; // comment
466  case 'v': rgb = 0x00ffff; break; // variable
467  case 'l': rgb = 0xff00ff; break; // literal
468  case 'p': rgb = 0xcdcd00; break; // proc
469  case 'o': rgb = 0x00cdcd; break; // operator
470  default: rgb = 0xffffff; break; // other
471  }
472  result.addChunk(command.substr(pos2, pos - pos2), rgb);
473  }
474  return result;
475 }
476 
477 void CommandConsole::putPrompt()
478 {
479  commandScrollBack = history.size();
480  currentLine = prompt;
481  lines[0] = highLight(currentLine);
482  cursorPosition = unsigned(prompt.size());
483 }
484 
485 void CommandConsole::tabCompletion()
486 {
487  resetScrollBack();
488  unsigned pl = unsigned(prompt.size());
489  string_ref front = utf8::unchecked::substr(lines[0].str(), pl, cursorPosition - pl);
490  string_ref back = utf8::unchecked::substr(lines[0].str(), cursorPosition);
491  string newFront = commandController.tabCompletion(front);
492  cursorPosition = pl + unsigned(utf8::unchecked::size(newFront));
493  currentLine = prompt + newFront + back;
494  lines[0] = highLight(currentLine);
495 }
496 
497 void CommandConsole::scroll(int delta)
498 {
499  consoleScrollBack = min(max(consoleScrollBack + delta, 0),
500  int(lines.size()));
501 }
502 
503 void CommandConsole::prevCommand()
504 {
505  resetScrollBack();
506  if (history.empty()) {
507  return; // no elements
508  }
509  bool match = false;
510  unsigned tmp = commandScrollBack;
511  while ((tmp != 0) && !match) {
512  --tmp;
513  match = StringOp::startsWith(history[tmp], currentLine);
514  }
515  if (match) {
516  commandScrollBack = tmp;
517  lines[0] = highLight(history[commandScrollBack]);
518  cursorPosition = lines[0].numChars();
519  }
520 }
521 
522 void CommandConsole::nextCommand()
523 {
524  resetScrollBack();
525  if (commandScrollBack == history.size()) {
526  return; // don't loop !
527  }
528  bool match = false;
529  auto tmp = commandScrollBack;
530  while ((++tmp != history.size()) && !match) {
531  match = StringOp::startsWith(history[tmp], currentLine);
532  }
533  if (match) {
534  --tmp; // one time to many
535  commandScrollBack = tmp;
536  lines[0] = highLight(history[commandScrollBack]);
537  } else {
538  commandScrollBack = history.size();
539  lines[0] = highLight(currentLine);
540  }
541  cursorPosition = lines[0].numChars();
542 }
543 
544 void CommandConsole::clearCommand()
545 {
546  resetScrollBack();
547  commandBuffer.clear();
548  prompt = PROMPT_NEW;
549  currentLine = prompt;
550  lines[0] = highLight(currentLine);
551  cursorPosition = unsigned(prompt.size());
552 }
553 
554 void CommandConsole::backspace()
555 {
556  resetScrollBack();
557  if (cursorPosition > prompt.size()) {
558  currentLine = lines[0].str();
559  auto b = begin(currentLine);
560  utf8::unchecked::advance(b, cursorPosition - 1);
561  auto e = b;
563  currentLine.erase(b, e);
564  lines[0] = highLight(currentLine);
565  --cursorPosition;
566  }
567 }
568 
569 void CommandConsole::delete_key()
570 {
571  resetScrollBack();
572  if (lines[0].numChars() > cursorPosition) {
573  currentLine = lines[0].str();
574  auto b = begin(currentLine);
575  utf8::unchecked::advance(b, cursorPosition);
576  auto e = b;
578  currentLine.erase(b, e);
579  lines[0] = highLight(currentLine);
580  }
581 }
582 
583 void CommandConsole::normalKey(uint16_t chr)
584 {
585  assert(chr);
586  resetScrollBack();
587  currentLine = lines[0].str();
588  auto pos = begin(currentLine);
589  utf8::unchecked::advance(pos, cursorPosition);
590  utf8::unchecked::append(uint32_t(chr), inserter(currentLine, pos));
591  lines[0] = highLight(currentLine);
592  ++cursorPosition;
593 }
594 
595 void CommandConsole::resetScrollBack()
596 {
597  consoleScrollBack = 0;
598 }
599 
600 } // namespace openmsx
ConsoleLine()
Construct empty line.
string_ref::const_iterator end(const string_ref &x)
Definition: string_ref.hh:150
octet_iterator append(uint32_t cp, octet_iterator result)
Represents the output window/screen of openMSX.
Definition: Display.hh:31
void registerEventListener(EventType type, EventListener &listener, Priority priority=OTHER)
Registers a given object to receive certain events.
string_ref getString() const
Definition: TclObject.cc:190
void getCursorPosition(unsigned &xPosition, unsigned &yPosition) const
void unregisterEventListener(EventType type, EventListener &listener)
Unregisters a previously registered event listener.
void openofstream(std::ofstream &stream, const std::string &filename)
Open an ofstream in a platform-independent manner.
unsigned getRows() const
void printWarning(string_ref message)
Definition: CliComm.cc:28
uint32_t next(octet_iterator &it)
bool starts_with(string_ref x) const
Definition: string_ref.cc:138
STL namespace.
size_type find(string_ref s) const
Definition: string_ref.cc:60
This class implements a subset of the proposal for std::string_ref (proposed for the next c++ standar...
Definition: string_ref.hh:18
size_type size() const
Definition: string_ref.hh:55
This class represents a single text line in the console.
ConsoleLine substr(unsigned pos, unsigned len) const
Get a part of total line.
string_ref substr(string_ref utf8, string_ref::size_type first=0, string_ref::size_type len=string_ref::npos)
const char * data() const
Definition: string_ref.hh:68
bool startsWith(string_ref total, string_ref part)
Definition: StringOp.cc:242
std::unique_ptr< Context > context
Definition: GLContext.cc:9
CommandConsole(GlobalCommandController &commandController, EventDistributor &eventDistributor, Display &display)
bool isComplete(const std::string &command)
Returns true iff the command is complete (all braces, quotes etc.
unsigned numChars() const
Get the number of UTF8 characters in this line.
static void setOutput(InterpreterOutput *output_)
Definition: Completer.hh:46
void repaintDelayed(uint64_t delta)
Definition: Display.cc:356
Thanks to enen for testing this on a real cartridge:
Definition: Autofire.cc:5
static const size_type npos
Definition: string_ref.hh:26
std::string tabCompletion(string_ref command)
Complete the given command.
void addChunk(string_ref text, unsigned rgb)
Append a chunk with a (different) color.
unsigned getColumns() const
void advance(octet_iterator &it, distance_type n)
static std::string full()
Definition: Version.cc:7
void setOutput(InterpreterOutput *output_)
Definition: Interpreter.hh:25
string_ref chunkText(unsigned i) const
Get the text for the i-th chunk.
string_ref substr(size_type pos, size_type n=npos) const
Definition: string_ref.cc:54
ConsoleLine getLine(unsigned line) const
size_t size(string_ref utf8)
string_ref::const_iterator begin(const string_ref &x)
Definition: string_ref.hh:149
unsigned chunkColor(unsigned i) const
Get the color for the i-th chunk.
TclParser parse(string_ref command)
Definition: Interpreter.cc:425
bool empty() const
Definition: string_ref.hh:56
TclObject executeCommand(const std::string &command, CliConnection *connection=nullptr) override
Execute the given command.
std::string getColors() const
Ouput: a string of equal length of the input command where each character indicates the type of the c...
Definition: TclParser.hh:27
XRange< T > xrange(T e)
Definition: xrange.hh:98
Assign new value to some variable and restore the original value when this object goes out of scope...
Definition: ScopedAssign.hh:7