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  auto& keyEvent = checked_cast<const KeyEvent&>(*event);
216  if (!consoleSetting.getBoolean()) return 0;
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  uint16_t 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  if (unicode >= 0x20) {
342  normalKey(unicode);
343  } else {
344  // Skip CTRL-<X> combinations, but still return true.
345  }
346  return true;
347 }
348 
349 void CommandConsole::output(string_view text)
350 {
351  print(text);
352 }
353 
354 unsigned CommandConsole::getOutputColumns() const
355 {
356  return getColumns();
357 }
358 
359 void CommandConsole::print(string_view text, unsigned rgb)
360 {
361  while (true) {
362  auto pos = text.find('\n');
363  newLineConsole(ConsoleLine(text.substr(0, pos), rgb));
364  if (pos == string_view::npos) return;
365  text = text.substr(pos + 1); // skip newline
366  if (text.empty()) return;
367  }
368 }
369 
370 void CommandConsole::newLineConsole(string_view line)
371 {
372  newLineConsole(ConsoleLine(line));
373 }
374 
375 void CommandConsole::newLineConsole(ConsoleLine line)
376 {
377  if (lines.isFull()) {
378  lines.removeBack();
379  }
380  ConsoleLine tmp = lines[0];
381  lines[0] = std::move(line);
382  lines.addFront(tmp);
383 }
384 
385 void CommandConsole::putCommandHistory(const string& command)
386 {
387  if (command.empty()) return;
388  if (removeDoublesSetting.getBoolean() && !history.empty() &&
389  (history.back() == command)) {
390  return;
391  }
392 
393  if (history.full()) history.pop_front();
394  history.push_back(command);
395 }
396 
397 void CommandConsole::commandExecute()
398 {
399  resetScrollBack();
400  string cmd0 = lines[0].str().substr(prompt.size());
401  putCommandHistory(cmd0);
402  saveHistory(); // save at this point already, so that we don't lose history in case of a crash
403 
404  strAppend(commandBuffer, cmd0, '\n');
405  newLineConsole(lines[0]);
406  if (commandController.isComplete(commandBuffer)) {
407  // Normally the busy promt is NOT shown (not even very briefly
408  // because the screen is not redrawn), though for some commands
409  // that potentially take a long time to execute, we explictly
410  // send events, see also comment in handleEvent().
411  prompt = PROMPT_BUSY;
412  putPrompt();
413 
414  try {
415  ScopedAssign<bool> sa(executingCommand, true);
416  auto resultObj = commandController.executeCommand(
417  commandBuffer);
418  auto result = resultObj.getString();
419  if (!result.empty()) {
420  print(result);
421  }
422  } catch (CommandException& e) {
423  print(e.getMessage(), 0xff0000);
424  }
425  commandBuffer.clear();
426  prompt = PROMPT_NEW;
427  } else {
428  prompt = PROMPT_CONT;
429  }
430  putPrompt();
431 }
432 
433 ConsoleLine CommandConsole::highLight(string_view line)
434 {
435  ConsoleLine result;
436  result.addChunk(prompt, 0xffffff);
437 
438  TclParser parser = commandController.getInterpreter().parse(line);
439  string colors = parser.getColors();
440  assert(colors.size() == line.size());
441 
442  unsigned pos = 0;
443  while (pos != colors.size()) {
444  char col = colors[pos];
445  unsigned pos2 = pos++;
446  while ((pos != colors.size()) && (colors[pos] == col)) {
447  ++pos;
448  }
449  // TODO make these color configurable?
450  unsigned rgb;
451  switch (col) {
452  case 'E': rgb = 0xff0000; break; // error
453  case 'c': rgb = 0x5c5cff; break; // comment
454  case 'v': rgb = 0x00ffff; break; // variable
455  case 'l': rgb = 0xff00ff; break; // literal
456  case 'p': rgb = 0xcdcd00; break; // proc
457  case 'o': rgb = 0x00cdcd; break; // operator
458  default: rgb = 0xffffff; break; // other
459  }
460  result.addChunk(line.substr(pos2, pos - pos2), rgb);
461  }
462  return result;
463 }
464 
465 void CommandConsole::putPrompt()
466 {
467  commandScrollBack = unsigned(history.size());
468  currentLine.clear();
469  lines[0] = highLight(currentLine);
470  cursorPosition = unsigned(prompt.size());
471 }
472 
473 void CommandConsole::tabCompletion()
474 {
475  resetScrollBack();
476  unsigned pl = unsigned(prompt.size());
477  string front = utf8::unchecked::substr(lines[0].str(), pl, cursorPosition - pl).str();
478  string back = utf8::unchecked::substr(lines[0].str(), cursorPosition).str();
479  string newFront = commandController.tabCompletion(front);
480  cursorPosition = pl + unsigned(utf8::unchecked::size(newFront));
481  currentLine = newFront + back;
482  lines[0] = highLight(currentLine);
483 }
484 
485 void CommandConsole::scroll(int delta)
486 {
487  consoleScrollBack = min(max(consoleScrollBack + delta, 0),
488  int(lines.size()));
489 }
490 
491 void CommandConsole::prevCommand()
492 {
493  resetScrollBack();
494  if (history.empty()) {
495  return; // no elements
496  }
497  bool match = false;
498  unsigned tmp = commandScrollBack;
499  while ((tmp != 0) && !match) {
500  --tmp;
501  match = StringOp::startsWith(history[tmp], currentLine);
502  }
503  if (match) {
504  commandScrollBack = tmp;
505  lines[0] = highLight(history[commandScrollBack]);
506  cursorPosition = unsigned(lines[0].numChars());
507  }
508 }
509 
510 void CommandConsole::nextCommand()
511 {
512  resetScrollBack();
513  if (commandScrollBack == history.size()) {
514  return; // don't loop !
515  }
516  bool match = false;
517  auto tmp = commandScrollBack;
518  while ((++tmp != history.size()) && !match) {
519  match = StringOp::startsWith(history[tmp], currentLine);
520  }
521  if (match) {
522  --tmp; // one time to many
523  commandScrollBack = tmp;
524  lines[0] = highLight(history[commandScrollBack]);
525  } else {
526  commandScrollBack = unsigned(history.size());
527  lines[0] = highLight(currentLine);
528  }
529  cursorPosition = unsigned(lines[0].numChars());
530 }
531 
532 void CommandConsole::clearCommand()
533 {
534  resetScrollBack();
535  commandBuffer.clear();
536  prompt = PROMPT_NEW;
537  currentLine.clear();
538  lines[0] = highLight(currentLine);
539  cursorPosition = unsigned(prompt.size());
540 }
541 
542 void CommandConsole::backspace()
543 {
544  resetScrollBack();
545  if (cursorPosition > prompt.size()) {
546  currentLine = lines[0].str();
547  auto b = begin(currentLine);
548  utf8::unchecked::advance(b, cursorPosition - 1);
549  auto e = b;
551  currentLine.erase(b, e);
552  currentLine.erase(0, prompt.size());
553  lines[0] = highLight(currentLine);
554  --cursorPosition;
555  }
556 }
557 
558 void CommandConsole::delete_key()
559 {
560  resetScrollBack();
561  if (lines[0].numChars() > cursorPosition) {
562  currentLine = lines[0].str();
563  auto b = begin(currentLine);
564  utf8::unchecked::advance(b, cursorPosition);
565  auto e = b;
567  currentLine.erase(b, e);
568  currentLine.erase(0, prompt.size());
569  lines[0] = highLight(currentLine);
570  }
571 }
572 
573 void CommandConsole::normalKey(uint16_t chr)
574 {
575  assert(chr);
576  resetScrollBack();
577  currentLine = lines[0].str();
578  auto pos = begin(currentLine);
579  utf8::unchecked::advance(pos, cursorPosition);
580  utf8::unchecked::append(uint32_t(chr), inserter(currentLine, pos));
581  currentLine.erase(0, prompt.size());
582  lines[0] = highLight(currentLine);
583  ++cursorPosition;
584 }
585 
586 void CommandConsole::resetScrollBack()
587 {
588  consoleScrollBack = 0;
589 }
590 
591 } // 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)
Represents the output window/screen of openMSX.
Definition: Display.hh:32
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:268
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
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:277
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
const std::string & getMessage() const
Definition: MSXException.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)
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:361
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:26
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)
uint16_t getUnicode() const
Definition: InputEvents.hh:27
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