openMSX
ImGuiConsole.cc
Go to the documentation of this file.
1#include "ImGuiConsole.hh"
2
3#include "ImGuiCpp.hh"
4#include "ImGuiManager.hh"
5#include "ImGuiUtils.hh"
6
7#include "BooleanSetting.hh"
8#include "CliComm.hh"
9#include "Completer.hh"
10#include "FileContext.hh"
11#include "FileException.hh"
12#include "FileOperations.hh"
14#include "Interpreter.hh"
15#include "Reactor.hh"
16#include "TclParser.hh"
17#include "Version.hh"
18
19#include "narrow.hh"
20#include "strCat.hh"
21#include "utf8_unchecked.hh"
22#include "xrange.hh"
23
24#include <imgui.h>
25#include <imgui_internal.h> // Hack: see below
26#include <imgui_stdlib.h>
27
28#include <fstream>
29
30namespace openmsx {
31
32using namespace std::literals;
33
34static constexpr std::string_view PROMPT_NEW = "> ";
35static constexpr std::string_view PROMPT_CONT = "| ";
36static constexpr std::string_view PROMPT_BUSY = "*busy*";
37
39 : ImGuiPart(manager_)
40 , consoleSetting(
41 manager.getReactor().getCommandController(), "console",
42 "turns console display on/off", false, Setting::DONT_SAVE)
43 , history(1000)
44 , lines(1000)
45 , prompt(PROMPT_NEW)
46{
47 loadHistory();
48
51 consoleSetting.attach(*this);
52
53 const auto& fullVersion = Version::full();
54 print(fullVersion);
55 print(std::string(fullVersion.size(), '-'));
56 print("\n"
57 "General information about openMSX is available at http://openmsx.org.\n"
58 "\n"
59 "Type 'help' to see a list of available commands.\n"
60 "Or read the Console Command Reference in the manual.\n"
61 "\n");
62}
63
65{
66 consoleSetting.detach(*this);
67}
68
69void ImGuiConsole::save(ImGuiTextBuffer& buf)
70{
71 savePersistent(buf, *this, persistentElements);
72}
73
74void ImGuiConsole::loadLine(std::string_view name, zstring_view value)
75{
76 loadOnePersistent(name, value, *this, persistentElements);
77}
78
79void ImGuiConsole::print(std::string_view text, imColor color)
80{
81 do {
82 auto pos = text.find('\n');
83 newLineConsole(ConsoleLine(std::string(text.substr(0, pos)), color));
84 if (pos == std::string_view::npos) break;
85 text.remove_prefix(pos + 1); // skip newline
86 } while (!text.empty());
87}
88
89void ImGuiConsole::newLineConsole(ConsoleLine line)
90{
91 auto addLine = [&](ConsoleLine&& l) {
92 if (lines.full()) lines.pop_front();
93 lines.push_back(std::move(l));
94 };
95
96 if (wrap) {
97 do {
98 auto rest = line.splitAtColumn(columns);
99 addLine(std::move(line));
100 line = std::move(rest);
101 } while (!line.str().empty());
102 } else {
103 addLine(std::move(line));
104 }
105
106 scrollToBottom = true;
107}
108
109static void drawLine(const ConsoleLine& line)
110{
111 auto n = line.numChunks();
112 for (auto i : xrange(n)) {
113 im::StyleColor(ImGuiCol_Text, getColor(line.chunkColor(i)), [&]{
114 ImGui::TextUnformatted(line.chunkText(i));
115 if (i != (n - 1)) ImGui::SameLine(0.0f, 0.0f);
116 });
117 }
118}
119
121{
122 bool reclaimFocus = show && !wasShown; // window appears
123 wasShown = show;
124 if (!show) return;
125
126 ImGui::SetNextWindowSize(ImVec2(520, 600), ImGuiCond_FirstUseEver);
127 im::Window("Console", &show, [&]{
129
130 // Reserve enough left-over height for 1 separator + 1 input text
131 auto& style = ImGui::GetStyle();
132 const float footerHeightToReserve = style.ItemSpacing.y +
133 ImGui::GetFrameHeightWithSpacing();
134 im::Child("ScrollingRegion", ImVec2(0, -footerHeightToReserve), 0,
135 ImGuiWindowFlags_HorizontalScrollbar, [&]{
137 if (ImGui::Selectable("Clear")) {
138 lines.clear();
139 }
140 ImGui::Checkbox("Wrap (new) output", &wrap);
141 });
142
143 im::StyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4, 1), [&]{ // Tighten spacing
144 im::ListClipper(lines.size(), [&](int i) {
145 drawLine(lines[i]);
146 });
147 });
148
149 // Keep up at the bottom of the scroll region if we were already
150 // at the bottom at the beginning of the frame.
151 if (scrollToBottom || (ImGui::GetScrollY() >= ImGui::GetScrollMaxY())) {
152 scrollToBottom = false;
153 ImGui::SetScrollHereY(1.0f);
154 }
155
156 // recalculate the number of columns
157 auto width = ImGui::GetContentRegionMax().x;
158 auto charWidth = ImGui::CalcTextSize("M"sv).x;
159 columns = narrow_cast<unsigned>(width / charWidth);
160 });
161 ImGui::Separator();
162
163 // Command-line
164 ImGui::AlignTextToFramePadding();
166 ImGui::SameLine(0.0f, 0.0f);
167
168 ImGui::SetNextItemWidth(-FLT_MIN); // full window width
169 // Hack: see below
170 auto cursorScrnPos = ImGui::GetCursorScreenPos();
171 auto itemWidth = ImGui::CalcItemWidth();
172
173 ImGuiInputTextFlags flags = ImGuiInputTextFlags_EnterReturnsTrue |
174 ImGuiInputTextFlags_EscapeClearsAll |
175 ImGuiInputTextFlags_CallbackEdit |
176 ImGuiInputTextFlags_CallbackCompletion |
177 ImGuiInputTextFlags_CallbackHistory;
178 if (ImGui::InputTextWithHint("##Input", "enter command", &inputBuf, flags, &textEditCallbackStub, this) &&
179 (prompt != PROMPT_BUSY)) {
180 // print command in output buffer, with prompt prepended
181 ConsoleLine cmdLine(prompt);
182 cmdLine.addLine(coloredInputBuf);
183 newLineConsole(std::move(cmdLine));
184
185 // append (partial) command to a possibly multi-line command
186 strAppend(commandBuffer, inputBuf, '\n');
187
188 putHistory(std::move(inputBuf));
189 saveHistory(); // save at this point already, so that we don't lose history in case of a crash
190 inputBuf.clear();
191 coloredInputBuf.clear();
192 historyPos = -1;
193 historyBackupLine.clear();
194
195 auto& commandController = manager.getReactor().getGlobalCommandController();
196 if (commandController.isComplete(commandBuffer)) {
197 // Normally the busy prompt is NOT shown (not even briefly
198 // because the screen is not redrawn), though for some commands
199 // that potentially take a long time to execute, we explicitly
200 // do redraw.
201 prompt = PROMPT_BUSY;
202
203 manager.executeDelayed(TclObject(commandBuffer),
204 [this](const TclObject& result) {
205 if (const auto& s = result.getString(); !s.empty()) {
206 this->print(s);
207 }
208 prompt = PROMPT_NEW;
209 },
210 [this](const std::string& error) {
211 this->print(error, imColor::ERROR);
212 prompt = PROMPT_NEW;
213 });
214 commandBuffer.clear();
215 } else {
216 prompt = PROMPT_CONT;
217 }
218 reclaimFocus = true;
219 }
220 ImGui::SetItemDefaultFocus();
221
222 if (reclaimFocus ||
223 (ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows) &&
224 !ImGui::IsPopupOpen(nullptr, ImGuiPopupFlags_AnyPopupId) &&
225 !ImGui::IsAnyItemActive() && !ImGui::IsMouseClicked(0) && !ImGui::IsMouseClicked(1))) {
226 ImGui::SetKeyboardFocusHere(-1); // focus the InputText widget
227 }
228
229 // Hack: currently ImGui::InputText() does not support colored text.
230 // Though there are plans to extend this. See:
231 // https://github.com/ocornut/imgui/pull/3130
232 // https://github.com/ocornut/imgui/issues/902
233 // To work around this limitation, we use ImGui::InputText() as-is,
234 // but then overdraw the text using the correct colors. This works,
235 // but it's fragile because it depends on some internal implementation
236 // details. More specifically: the scroll-position. And obtaining this
237 // information required stuff from <imgui_internal.h>.
238 auto* font = ImGui::GetFont();
239 auto fontSize = ImGui::GetFontSize();
240 gl::vec2 frameSize(itemWidth, fontSize + style.FramePadding.y * 2.0f);
241 gl::vec2 topLeft = cursorScrnPos;
242 gl::vec2 bottomRight = topLeft + frameSize;
243 gl::vec2 drawPos = topLeft + gl::vec2(style.FramePadding);
244 if (ImGui::IsItemActive()) {
245 auto id = ImGui::GetID("##Input");
246 if (auto* state = ImGui::GetInputTextState(id)) { // Internal API !!!
247 drawPos[0] -= state->ScrollX;
248 }
249 }
250 auto charWidth = ImGui::GetFont()->GetCharAdvance('A'); // assumes fixed-width font
251 ImVec4 clipRect = gl::vec4(topLeft, bottomRight);
252 auto* drawList = ImGui::GetWindowDrawList();
253 for (auto i : xrange(coloredInputBuf.numChunks())) {
254 auto text = coloredInputBuf.chunkText(i);
255 auto rgba = getColor(coloredInputBuf.chunkColor(i));
256 const char* begin = text.data();
257 const char* end = begin + text.size();
258 drawList->AddText(font, fontSize, drawPos, rgba, begin, end, 0.0f, &clipRect);
259 // avoid ImGui::CalcTextSize(): it's off-by-one for sizes >= 256 pixels
260 drawPos[0] += charWidth * float(utf8::unchecked::distance(begin, end));
261 }
262 });
263}
264
265int ImGuiConsole::textEditCallbackStub(ImGuiInputTextCallbackData* data)
266{
267 auto* console = static_cast<ImGuiConsole*>(data->UserData);
268 return console->textEditCallback(data);
269}
270
271int ImGuiConsole::textEditCallback(ImGuiInputTextCallbackData* data)
272{
273 switch (data->EventFlag) {
274 case ImGuiInputTextFlags_CallbackCompletion: {
275 std::string_view oldLine{data->Buf, narrow<size_t>(data->BufTextLen)};
276 std::string_view front = utf8::unchecked::substr(oldLine, 0, data->CursorPos);
277 std::string_view back = utf8::unchecked::substr(oldLine, data->CursorPos);
278
279 auto& commandController = manager.getReactor().getGlobalCommandController();
280 std::string newFront = commandController.tabCompletion(front);
281 historyBackupLine = strCat(std::move(newFront), back);
282 historyPos = -1;
283
284 data->DeleteChars(0, data->BufTextLen);
285 data->InsertChars(0, historyBackupLine.c_str());
286
287 colorize(historyBackupLine);
288 break;
289 }
290 case ImGuiInputTextFlags_CallbackHistory: {
291 bool match = false;
292 if (data->EventKey == ImGuiKey_UpArrow) {
293 while (!match && (historyPos < narrow<int>(history.size() - 1))) {
294 ++historyPos;
295 match = history[historyPos].starts_with(historyBackupLine);
296 }
297 } else if ((data->EventKey == ImGuiKey_DownArrow) && (historyPos != -1)) {
298 while (!match) {
299 if (--historyPos == -1) break;
300 match = history[historyPos].starts_with(historyBackupLine);
301 }
302 }
303 if (match || (historyPos == -1)) {
304 const auto& historyStr = (historyPos >= 0) ? history[historyPos] : historyBackupLine;
305 data->DeleteChars(0, data->BufTextLen);
306 data->InsertChars(0, historyStr.c_str());
307 colorize(std::string_view{data->Buf, narrow<size_t>(data->BufTextLen)});
308 }
309 break;
310 }
311 case ImGuiInputTextFlags_CallbackEdit: {
312 historyBackupLine.assign(data->Buf, narrow<size_t>(data->BufTextLen));
313 historyPos = -1;
314 colorize(historyBackupLine);
315 break;
316 }
317 }
318 return 0;
319}
320
321void ImGuiConsole::colorize(std::string_view line)
322{
323 TclParser parser = manager.getInterpreter().parse(line);
324 const auto& colors = parser.getColors();
325 assert(colors.size() == line.size());
326
327 coloredInputBuf.clear();
328 size_t pos = 0;
329 while (pos != colors.size()) {
330 char col = colors[pos];
331 size_t pos2 = pos++;
332 while ((pos != colors.size()) && (colors[pos] == col)) {
333 ++pos;
334 }
335 imColor color = [&] {
336 switch (col) {
337 case 'E': return imColor::ERROR;
338 case 'c': return imColor::COMMENT;
339 case 'v': return imColor::VARIABLE;
340 case 'l': return imColor::LITERAL;
341 case 'p': return imColor::PROC;
342 case 'o': return imColor::OPERATOR;
343 default: return imColor::TEXT; // other
344 }
345 }();
346 coloredInputBuf.addChunk(line.substr(pos2, pos - pos2), color);
347 }
348}
349
350void ImGuiConsole::putHistory(std::string command)
351{
352 if (command.empty()) return;
353 if (!history.empty() && (history.front() == command)) {
354 return;
355 }
356 if (history.full()) history.pop_back();
357 history.push_front(std::move(command));
358}
359
360void ImGuiConsole::saveHistory()
361{
362 try {
363 std::ofstream outputFile;
365 userFileContext("console").resolveCreate("history.txt"));
366 if (!outputFile) {
367 throw FileException("Error while saving the console history.");
368 }
369 for (auto& s : view::reverse(history)) {
370 outputFile << s << '\n';
371 }
372 } catch (FileException& e) {
373 manager.getCliComm().printWarning(e.getMessage());
374 }
375}
376
377void ImGuiConsole::loadHistory()
378{
379 try {
380 std::ifstream inputFile(
381 userFileContext("console").resolveCreate("history.txt"));
382 std::string line;
383 while (inputFile) {
384 getline(inputFile, line);
385 putHistory(line);
386 }
387 } catch (FileException&) {
388 // Error while loading the console history, ignore
389 }
390}
391
392void ImGuiConsole::output(std::string_view text)
393{
394 print(text);
395}
396
397unsigned ImGuiConsole::getOutputColumns() const
398{
399 return columns;
400}
401
402void ImGuiConsole::update(const Setting& /*setting*/) noexcept
403{
404 show = consoleSetting.getBoolean();
405 if (!show) {
406 // Close the console via the 'console' setting. Typically this
407 // means via the F10 hotkey (or possibly by typing 'set console
408 // off' in the console).
409 //
410 // Give focus to the main openMSX window.
411 //
412 // This makes the following scenario work:
413 // * You were controlling the MSX, e.g. playing a game.
414 // * You press F10 to open the console.
415 // * You type a command (e.g. swap a game disk, for some people
416 // the console is still more convenient and/or faster than the
417 // new media menu).
418 // * You press F10 again to close the console
419 // * At this point the focus should go back to the main openMSX
420 // window (so that MSX input works).
421 SDL_SetWindowInputFocus(SDL_GetWindowFromID(WindowEvent::getMainWindowId()));
422 ImGui::SetWindowFocus(nullptr);
423 }
424}
425
426} // namespace openmsx
const 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:29
void push_front(T2 &&t)
size_t size() const
void printWarning(std::string_view message)
Definition CliComm.cc:10
static void setOutput(InterpreterOutput *output_)
Definition Completer.hh:68
This class represents a single text line in the console.
void addLine(const ConsoleLine &ln)
Append another line (possibly containing multiple chunks).
std::string_view chunkText(size_t i) const
Get the text for the i-th chunk.
imColor chunkColor(size_t i) const
Get the color for the i-th chunk.
void addChunk(std::string_view text, imColor color=imColor::TEXT)
Append a chunk with a (different) color.
void clear()
Reinitialize to an empty line.
size_t numChunks() const
Get the number of different chunks.
std::string tabCompletion(std::string_view command)
Complete the given command.
void paint(MSXMotherBoard *motherBoard) override
void save(ImGuiTextBuffer &buf) override
ImGuiConsole(ImGuiManager &manager)
void loadLine(std::string_view name, zstring_view value) override
Interpreter & getInterpreter()
void executeDelayed(std::function< void()> action)
ImGuiManager & manager
Definition ImGuiPart.hh:30
void setOutput(InterpreterOutput *output_)
TclParser parse(std::string_view command)
GlobalCommandController & getGlobalCommandController()
Definition Reactor.hh:88
void detach(Observer< T > &observer)
Definition Subject.hh:56
void attach(Observer< T > &observer)
Definition Subject.hh:50
zstring_view getString() const
Definition TclObject.cc:142
static std::string full()
Definition Version.cc:8
static uint32_t getMainWindowId()
Definition Event.hh:227
Like std::string_view, but with the extra guarantee that it refers to a zero-terminated string.
auto CalcTextSize(std::string_view str)
Definition ImGuiUtils.hh:37
void TextUnformatted(const std::string &str)
Definition ImGuiUtils.hh:24
constexpr double e
Definition Math.hh:21
vecN< 2, float > vec2
Definition gl_vec.hh:150
vecN< 4, float > vec4
Definition gl_vec.hh:152
void Window(const char *name, bool *p_open, ImGuiWindowFlags flags, std::invocable<> auto next)
Definition ImGuiCpp.hh:63
void StyleVar(ImGuiStyleVar idx, float val, std::invocable<> auto next)
Definition ImGuiCpp.hh:204
void PopupContextWindow(const char *str_id, ImGuiPopupFlags popup_flags, std::invocable<> auto next)
Definition ImGuiCpp.hh:456
void Child(const char *str_id, const ImVec2 &size, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags, std::invocable<> auto next)
Definition ImGuiCpp.hh:104
void StyleColor(ImGuiCol idx1, ImVec4 col1, ImGuiCol idx2, ImVec4 col2, std::invocable<> auto next)
Definition ImGuiCpp.hh:156
void ListClipper(size_t count, std::invocable< int > auto next)
Definition ImGuiCpp.hh:556
void openOfStream(std::ofstream &stream, zstring_view filename)
Open an ofstream in a platform-independent manner.
This file implemented 3 utility functions:
Definition Autofire.cc:9
bool loadOnePersistent(std::string_view name, zstring_view value, C &c, const std::tuple< Elements... > &tup)
void savePersistent(ImGuiTextBuffer &buf, C &c, const std::tuple< Elements... > &tup)
std::optional< bool > match(const BooleanInput &binding, const Event &event, std::function< int(JoystickId)> getJoyDeadZone)
ImU32 getColor(imColor col)
const FileContext & userFileContext()
std::string_view substr(std::string_view utf8, std::string_view::size_type first=0, std::string_view::size_type len=std::string_view::npos)
auto distance(octet_iterator first, octet_iterator last)
Definition view.hh:15
constexpr auto reverse(Range &&range)
Definition view.hh:514
std::string strCat()
Definition strCat.hh:703
void strAppend(std::string &result, Ts &&...ts)
Definition strCat.hh:752
constexpr auto xrange(T e)
Definition xrange.hh:132
constexpr auto begin(const zstring_view &x)
constexpr auto end(const zstring_view &x)