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://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  std::ofstream outputfile;
166  FileOperations::openofstream(outputfile,
167  userFileContext("console").resolveCreate("history.txt"));
168  if (!outputfile) {
169  throw FileException(
170  "Error while saving the console history.");
171  }
172  for (auto& s : history) {
173  outputfile << s << '\n';
174  }
175  } catch (FileException& e) {
176  commandController.getCliComm().printWarning(e.getMessage());
177  }
178 }
179 
180 void CommandConsole::loadHistory()
181 {
182  try {
183  std::ifstream inputfile(
184  userFileContext("console").
185  resolveCreate("history.txt").c_str());
186  string line;
187  while (inputfile) {
188  getline(inputfile, line);
189  putCommandHistory(line);
190  }
191  } catch (FileException&) {
192  // Error while loading the console history, ignore
193  }
194 }
195 
196 void CommandConsole::getCursorPosition(unsigned& xPosition, unsigned& yPosition) const
197 {
198  xPosition = cursorPosition % getColumns();
199  unsigned num = lines[0].numChars() / getColumns();
200  yPosition = num - (cursorPosition / getColumns());
201 }
202 
204 {
205  unsigned count = 0;
206  for (auto buf : xrange(lines.size())) {
207  count += (lines[buf].numChars() / getColumns()) + 1;
208  if (count > line) {
209  return lines[buf].substr(
210  (count - line - 1) * getColumns(),
211  getColumns());
212  }
213  }
214  return ConsoleLine();
215 }
216 
217 int CommandConsole::signalEvent(const std::shared_ptr<const Event>& event)
218 {
219  auto& keyEvent = checked_cast<const KeyEvent&>(*event);
220  if (!consoleSetting.getBoolean()) return 0;
221 
222  // If the console is open then don't pass the event to the MSX
223  // (whetever the (keyboard) event is). If the event has a meaning for
224  // the console, then also don't pass the event to the hotkey system.
225  // For example PgUp, PgDown are keys that have both a meaning in the
226  // console and are used by standard key bindings.
227  if (event->getType() == OPENMSX_KEY_DOWN_EVENT) {
228  if (!executingCommand) {
229  if (handleEvent(keyEvent)) {
230  // event was used
231  display.repaintDelayed(40000); // 25fps
232  return EventDistributor::HOTKEY; // block HOTKEY and MSX
233  }
234  } else {
235  // For commands that take a long time to execute (e.g.
236  // a loadstate that needs to create a filepool index),
237  // we also send events during the execution (so that
238  // we can show progress on the OSD). In that case
239  // ignore extra input events.
240  }
241  } else {
242  assert(event->getType() == OPENMSX_KEY_UP_EVENT);
243  }
244  return EventDistributor::MSX; // block MSX
245 }
246 
247 bool CommandConsole::handleEvent(const KeyEvent& keyEvent)
248 {
249  auto keyCode = keyEvent.getKeyCode();
250  int key = keyCode & Keys::K_MASK;
251  int mod = keyCode & ~Keys::K_MASK;
252 
253  switch (mod) {
254  case Keys::KM_CTRL:
255  switch (key) {
256  case Keys::K_H:
257  backspace();
258  return true;
259  case Keys::K_A:
260  cursorPosition = unsigned(prompt.size());
261  return true;
262  case Keys::K_E:
263  cursorPosition = lines[0].numChars();
264  return true;
265  case Keys::K_C:
266  clearCommand();
267  return true;
268  }
269  break;
270  case Keys::KM_SHIFT:
271  switch (key) {
272  case Keys::K_PAGEUP:
273  scroll(max<int>(getRows() - 1, 1));
274  return true;
275  case Keys::K_PAGEDOWN:
276  scroll(-max<int>(getRows() - 1, 1));
277  return true;
278  }
279  break;
280  case 0: // no modifier
281  switch (key) {
282  case Keys::K_PAGEUP:
283  scroll(1);
284  return true;
285  case Keys::K_PAGEDOWN:
286  scroll(-1);
287  return true;
288  case Keys::K_UP:
289  prevCommand();
290  return true;
291  case Keys::K_DOWN:
292  nextCommand();
293  return true;
294  case Keys::K_BACKSPACE:
295  backspace();
296  return true;
297  case Keys::K_DELETE:
298  delete_key();
299  return true;
300  case Keys::K_TAB:
301  tabCompletion();
302  return true;
303  case Keys::K_RETURN:
304  case Keys::K_KP_ENTER:
305  commandExecute();
306  cursorPosition = unsigned(prompt.size());
307  return true;
308  case Keys::K_LEFT:
309  if (cursorPosition > prompt.size()) {
310  --cursorPosition;
311  }
312  return true;
313  case Keys::K_RIGHT:
314  if (cursorPosition < lines[0].numChars()) {
315  ++cursorPosition;
316  }
317  return true;
318  case Keys::K_HOME:
319  cursorPosition = unsigned(prompt.size());
320  return true;
321  case Keys::K_END:
322  cursorPosition = lines[0].numChars();
323  return true;
324  }
325  break;
326  }
327 
328  uint16_t unicode = keyEvent.getUnicode();
329  if (!unicode || (mod & Keys::KM_META)) {
330  // Disallow META modifer for 'normal' key presses because on
331  // MacOSX Cmd+L is used as a hotkey to toggle the console.
332  // Hopefully there are no systems that require META to type
333  // normal keys. However there _are_ systems that require the
334  // following modifiers, some examples:
335  // MODE: to type '1-9' on a N900
336  // ALT: to type | [ ] on a azerty keyboard layout
337  // CTRL+ALT: to type '#' on a spanish keyboard layout (windows)
338  //
339  // Event was not used by the console, allow the other
340  // subsystems to process it. E.g. F10, or Cmd+L to close the
341  // console.
342  return false;
343  }
344 
345  if (unicode >= 0x20) {
346  normalKey(unicode);
347  } else {
348  // Skip CTRL-<X> combinations, but still return true.
349  }
350  return true;
351 }
352 
353 void CommandConsole::output(string_ref text)
354 {
355  print(text);
356 }
357 
358 unsigned CommandConsole::getOutputColumns() const
359 {
360  return getColumns();
361 }
362 
363 void CommandConsole::print(string_ref text, unsigned rgb)
364 {
365  while (true) {
366  auto pos = text.find('\n');
367  newLineConsole(ConsoleLine(text.substr(0, pos), rgb));
368  if (pos == string_ref::npos) return;
369  text = text.substr(pos + 1); // skip newline
370  if (text.empty()) return;
371  }
372 }
373 
374 void CommandConsole::newLineConsole(string_ref line)
375 {
376  newLineConsole(ConsoleLine(line));
377 }
378 
379 void CommandConsole::newLineConsole(ConsoleLine line)
380 {
381  if (lines.isFull()) {
382  lines.removeBack();
383  }
384  ConsoleLine tmp = lines[0];
385  lines[0] = line;
386  lines.addFront(tmp);
387 }
388 
389 void CommandConsole::putCommandHistory(const string& command)
390 {
391  if (command.empty()) return;
392  if (removeDoublesSetting.getBoolean() && !history.empty() &&
393  (history.back() == command)) {
394  return;
395  }
396 
397  if (history.full()) history.pop_front();
398  history.push_back(command);
399 }
400 
401 void CommandConsole::commandExecute()
402 {
403  resetScrollBack();
404  string cmd0 = lines[0].str().substr(prompt.size());
405  putCommandHistory(cmd0);
406  saveHistory(); // save at this point already, so that we don't lose history in case of a crash
407 
408  commandBuffer += std::move(cmd0) + '\n';
409  newLineConsole(lines[0]);
410  if (commandController.isComplete(commandBuffer)) {
411  // Normally the busy promt is NOT shown (not even very briefly
412  // because the screen is not redrawn), though for some commands
413  // that potentially take a long time to execute, we explictly
414  // send events, see also comment in handleEvent().
415  prompt = PROMPT_BUSY;
416  putPrompt();
417 
418  try {
419  ScopedAssign<bool> sa(executingCommand, true);
420  auto resultObj = commandController.executeCommand(
421  commandBuffer);
422  auto result = resultObj.getString();
423  if (!result.empty()) {
424  print(result);
425  }
426  } catch (CommandException& e) {
427  print(e.getMessage(), 0xff0000);
428  }
429  commandBuffer.clear();
430  prompt = PROMPT_NEW;
431  } else {
432  prompt = PROMPT_CONT;
433  }
434  putPrompt();
435 }
436 
437 ConsoleLine CommandConsole::highLight(string_ref line)
438 {
439  ConsoleLine result;
440  result.addChunk(prompt, 0xffffff);
441 
442  TclParser parser = commandController.getInterpreter().parse(line);
443  string colors = parser.getColors();
444  assert(colors.size() == line.size());
445 
446  unsigned pos = 0;
447  while (pos != colors.size()) {
448  char col = colors[pos];
449  unsigned pos2 = pos++;
450  while ((pos != colors.size()) && (colors[pos] == col)) {
451  ++pos;
452  }
453  // TODO make these color configurable?
454  unsigned rgb;
455  switch (col) {
456  case 'E': rgb = 0xff0000; break; // error
457  case 'c': rgb = 0x5c5cff; break; // comment
458  case 'v': rgb = 0x00ffff; break; // variable
459  case 'l': rgb = 0xff00ff; break; // literal
460  case 'p': rgb = 0xcdcd00; break; // proc
461  case 'o': rgb = 0x00cdcd; break; // operator
462  default: rgb = 0xffffff; break; // other
463  }
464  result.addChunk(line.substr(pos2, pos - pos2), rgb);
465  }
466  return result;
467 }
468 
469 void CommandConsole::putPrompt()
470 {
471  commandScrollBack = unsigned(history.size());
472  currentLine.clear();
473  lines[0] = highLight(currentLine);
474  cursorPosition = unsigned(prompt.size());
475 }
476 
477 void CommandConsole::tabCompletion()
478 {
479  resetScrollBack();
480  unsigned pl = unsigned(prompt.size());
481  string_ref front = utf8::unchecked::substr(lines[0].str(), pl, cursorPosition - pl);
482  string_ref back = utf8::unchecked::substr(lines[0].str(), cursorPosition);
483  string newFront = commandController.tabCompletion(front);
484  cursorPosition = pl + unsigned(utf8::unchecked::size(newFront));
485  currentLine = newFront + back;
486  lines[0] = highLight(currentLine);
487 }
488 
489 void CommandConsole::scroll(int delta)
490 {
491  consoleScrollBack = min(max(consoleScrollBack + delta, 0),
492  int(lines.size()));
493 }
494 
495 void CommandConsole::prevCommand()
496 {
497  resetScrollBack();
498  if (history.empty()) {
499  return; // no elements
500  }
501  bool match = false;
502  unsigned tmp = commandScrollBack;
503  while ((tmp != 0) && !match) {
504  --tmp;
505  match = StringOp::startsWith(history[tmp], currentLine);
506  }
507  if (match) {
508  commandScrollBack = tmp;
509  lines[0] = highLight(history[commandScrollBack]);
510  cursorPosition = lines[0].numChars();
511  }
512 }
513 
514 void CommandConsole::nextCommand()
515 {
516  resetScrollBack();
517  if (commandScrollBack == history.size()) {
518  return; // don't loop !
519  }
520  bool match = false;
521  auto tmp = commandScrollBack;
522  while ((++tmp != history.size()) && !match) {
523  match = StringOp::startsWith(history[tmp], currentLine);
524  }
525  if (match) {
526  --tmp; // one time to many
527  commandScrollBack = tmp;
528  lines[0] = highLight(history[commandScrollBack]);
529  } else {
530  commandScrollBack = unsigned(history.size());
531  lines[0] = highLight(currentLine);
532  }
533  cursorPosition = lines[0].numChars();
534 }
535 
536 void CommandConsole::clearCommand()
537 {
538  resetScrollBack();
539  commandBuffer.clear();
540  prompt = PROMPT_NEW;
541  currentLine.clear();
542  lines[0] = highLight(currentLine);
543  cursorPosition = unsigned(prompt.size());
544 }
545 
546 void CommandConsole::backspace()
547 {
548  resetScrollBack();
549  if (cursorPosition > prompt.size()) {
550  currentLine = lines[0].str();
551  auto b = begin(currentLine);
552  utf8::unchecked::advance(b, cursorPosition - 1);
553  auto e = b;
555  currentLine.erase(b, e);
556  currentLine.erase(0, prompt.size());
557  lines[0] = highLight(currentLine);
558  --cursorPosition;
559  }
560 }
561 
562 void CommandConsole::delete_key()
563 {
564  resetScrollBack();
565  if (lines[0].numChars() > cursorPosition) {
566  currentLine = lines[0].str();
567  auto b = begin(currentLine);
568  utf8::unchecked::advance(b, cursorPosition);
569  auto e = b;
571  currentLine.erase(b, e);
572  currentLine.erase(0, prompt.size());
573  lines[0] = highLight(currentLine);
574  }
575 }
576 
577 void CommandConsole::normalKey(uint16_t chr)
578 {
579  assert(chr);
580  resetScrollBack();
581  currentLine = lines[0].str();
582  auto pos = begin(currentLine);
583  utf8::unchecked::advance(pos, cursorPosition);
584  utf8::unchecked::append(uint32_t(chr), inserter(currentLine, pos));
585  currentLine.erase(0, prompt.size());
586  lines[0] = highLight(currentLine);
587  ++cursorPosition;
588 }
589 
590 void CommandConsole::resetScrollBack()
591 {
592  consoleScrollBack = 0;
593 }
594 
595 } // namespace openmsx
ConsoleLine()
Construct empty line.
string_ref::const_iterator end(const string_ref &x)
Definition: string_ref.hh:167
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:139
vecN< N, T > min(const vecN< N, T > &x, const vecN< N, T > &y)
Definition: gl_vec.hh:257
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
size_t size() const
bool full() const
uint32_t next(octet_iterator &it)
STL namespace.
size_type find(string_ref s) const
Definition: string_ref.cc:38
This class implements a subset of the proposal for std::string_ref (proposed for the next c++ standar...
Definition: string_ref.hh:18
vecN< N, T > max(const vecN< N, T > &x, const vecN< N, T > &y)
Definition: gl_vec.hh:266
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
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:357
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.
FileContext userFileContext(string_ref savePath)
Definition: FileContext.cc:161
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.
bool empty() const
string_ref substr(size_type pos, size_type n=npos) const
Definition: string_ref.cc:32
ConsoleLine getLine(unsigned line) const
size_t size(string_ref utf8)
string_ref::const_iterator begin(const string_ref &x)
Definition: string_ref.hh:166
unsigned chunkColor(unsigned i) const
Get the color for the i-th chunk.
TclParser parse(string_ref command)
Definition: Interpreter.cc:422
void push_back(const T &t)
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