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