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