forked from f3d-app/f3d
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvtkF3DImguiConsole.cxx
421 lines (368 loc) · 14.1 KB
/
vtkF3DImguiConsole.cxx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
#include "vtkF3DImguiConsole.h"
#include <vtkCallbackCommand.h>
#include <vtkCommand.h>
#include <vtkNew.h>
#include <vtkObjectFactory.h>
#include <imgui.h>
#include <algorithm>
#include <array>
struct vtkF3DImguiConsole::Internals
{
enum class LogType
{
Log,
Warning,
Error,
Typed,
Completion
};
std::vector<std::pair<LogType, std::string>> Logs;
std::array<char, 256> CurrentInput = {};
bool NewError = false;
bool NewWarning = false;
std::pair<size_t, size_t> Completions{ 0,
0 }; // Index for start and length of completions in Logs
std::function<std::vector<std::string>(const std::string& pattern)>
GetCommandsMatchCallback; // Callback to get the list of commands matching pattern
std::vector<std::string> CommandHistory;
std::pair<std::string, int> LastInput; // Last input before navigating history
int CommandHistoryIndexInv = -1; // Current inverted index in command history navigation
/**
* Clear completions from the logs
*/
void ClearCompletions()
{
if (this->Completions.second > 0)
{
this->Logs.erase(this->Logs.begin() + this->Completions.first,
this->Logs.begin() + this->Completions.second);
this->Completions.second = 0;
}
}
/**
* Callback to process text editing events in console
*/
int TextEditCallback(ImGuiInputTextCallbackData* data)
{
this->ClearCompletions();
switch (data->EventFlag)
{
case ImGuiInputTextFlags_CallbackCompletion:
{
assert(this->GetCommandsMatchCallback);
std::string pattern{ data->Buf };
std::vector<std::string> candidates =
this->GetCommandsMatchCallback(pattern); // List of supported commands
if (candidates.size() == 1)
{
// Single match. Delete the beginning of the word and replace it entirely so we've got
// nice casing.
data->DeleteChars(0, static_cast<int>(pattern.size()));
data->InsertChars(data->CursorPos, candidates[0].c_str());
data->InsertChars(data->CursorPos, " ");
}
else if (candidates.size() > 1)
{
// Multiple matches. Complete as much as we can.
// So inputting "C"+Tab will complete to "CL" then display "CLEAR" and "CLASSIFY" as
// matches.
size_t matchLen = pattern.size();
bool allCandidatesMatches = true;
// Find the common prefix to all candidates
while (allCandidatesMatches)
{
const std::string& first = candidates[0];
if (first.size() <= matchLen)
{
// The first candidate is shorter than the current match length
allCandidatesMatches = false;
}
else
{
// Check if all candidates match the current character
const char target = first[matchLen];
allCandidatesMatches = std::all_of(candidates.begin(), candidates.end(),
[matchLen, target](const std::string& s)
{ return s.size() > matchLen && s[matchLen] == target; });
}
if (allCandidatesMatches)
{
matchLen++;
}
}
if (matchLen > 0)
{
// Fill the best we can by now - use the longest common prefix from available candidates
// (possibly just pattern itself in the worst case)
data->DeleteChars(0, static_cast<int>(pattern.size()));
data->InsertChars(
data->CursorPos, candidates[0].c_str(), candidates[0].c_str() + matchLen);
}
this->Completions.first = this->Logs.size();
this->Completions.second = this->Logs.size() + candidates.size() + 1;
// Add all candidates to the logs
this->Logs.emplace_back(
std::make_pair(Internals::LogType::Completion, "Possible matches:"));
std::transform(candidates.begin(), candidates.end(), std::back_inserter(this->Logs),
[](const std::string& candidate)
{ return std::make_pair(Internals::LogType::Completion, candidate); });
}
break;
}
case ImGuiInputTextFlags_CallbackHistory:
{
/* CommandHistoryIndexInv is a reversed index for command history:
- `-1` represents the current user input (not yet stored in history).
- `0` corresponds to the most recent command (CommandHistory.size() - 1).
- `CommandHistory.size() - 1` maps to the oldest command (0 in CommandHistory). */
const int prevHistoryPos = this->CommandHistoryIndexInv;
if (prevHistoryPos == -1)
{
/* Saving the last input before history navigation */
this->LastInput = { this->CurrentInput.data(), data->CursorPos };
}
const int histSize = static_cast<int>(this->CommandHistory.size());
if (data->EventKey == ImGuiKey_UpArrow && this->CommandHistoryIndexInv < (histSize - 1))
{
this->CommandHistoryIndexInv++;
}
else if (data->EventKey == ImGuiKey_DownArrow && this->CommandHistoryIndexInv >= 0)
{
this->CommandHistoryIndexInv--;
}
if (prevHistoryPos != this->CommandHistoryIndexInv)
{
if (this->CommandHistoryIndexInv == -1)
{
/* Restoring the last input when navigated back to it */
data->DeleteChars(0, data->BufTextLen);
data->InsertChars(0, this->LastInput.first.c_str());
data->CursorPos = this->LastInput.second;
}
else
{
/* We should not be able to have negative index here */
/* Retrieve the command from history */
std::string historyStr =
this->CommandHistory[histSize - this->CommandHistoryIndexInv - 1];
data->DeleteChars(0, data->BufTextLen);
data->InsertChars(0, historyStr.c_str());
data->CursorPos = static_cast<int>(historyStr.size());
}
}
}
}
return 0;
}
};
vtkStandardNewMacro(vtkF3DImguiConsole);
//----------------------------------------------------------------------------
vtkF3DImguiConsole::vtkF3DImguiConsole()
: Pimpl(new Internals())
{
}
//----------------------------------------------------------------------------
vtkF3DImguiConsole::~vtkF3DImguiConsole() = default;
//----------------------------------------------------------------------------
void vtkF3DImguiConsole::DisplayText(const char* text)
{
switch (this->GetCurrentMessageType())
{
case vtkOutputWindow::MESSAGE_TYPE_ERROR:
this->Pimpl->Logs.emplace_back(std::make_pair(Internals::LogType::Error, text));
this->Pimpl->NewError = true;
break;
case vtkOutputWindow::MESSAGE_TYPE_WARNING:
case vtkOutputWindow::MESSAGE_TYPE_GENERIC_WARNING:
this->Pimpl->Logs.emplace_back(std::make_pair(Internals::LogType::Warning, text));
this->Pimpl->NewWarning = true;
break;
default:
this->Pimpl->Logs.emplace_back(std::make_pair(Internals::LogType::Log, text));
}
// also print text to std::cout
this->Superclass::DisplayText(text);
}
//----------------------------------------------------------------------------
void vtkF3DImguiConsole::ShowConsole(bool minimal)
{
ImGuiViewport* viewport = ImGui::GetMainViewport();
constexpr float margin = 30.f;
constexpr float marginTopRight = 5.f;
const float padding = ImGui::GetStyle().WindowPadding.x + ImGui::GetStyle().FramePadding.x;
// explicitly calculate size of minimal console to avoid extra flashing frame
if (minimal)
{
if (this->Pimpl->NewError || this->Pimpl->NewWarning)
{
// prevent overlap with console badge in minimal console
ImGui::SetNextWindowSize(ImVec2(viewport->WorkSize.x - 2.f * margin -
(ImGui::CalcTextSize("!").y + 2.f * padding) - marginTopRight,
ImGui::CalcTextSize(">").y + 2.f * padding));
}
else
{
ImGui::SetNextWindowSize(
ImVec2(viewport->WorkSize.x - 2.f * margin, ImGui::CalcTextSize(">").y + 2.f * padding));
}
}
else
{
// minimal console shouldn't clear console badge
this->Pimpl->NewError = false;
this->Pimpl->NewWarning = false;
ImGui::SetNextWindowSize(
ImVec2(viewport->WorkSize.x - 2.f * margin, viewport->WorkSize.y - 2.f * margin));
}
ImGui::SetNextWindowPos(ImVec2(margin, margin));
ImGui::SetNextWindowBgAlpha(0.9f);
ImGuiWindowFlags winFlags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoSavedSettings |
ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav | ImGuiWindowFlags_NoMove;
// Since imgui has focus, it won't propagate the "Escape" key event to VTK
// So let's handle the console visibility here
if (ImGui::IsKeyPressed(ImGuiKey_Escape, false) && this->Pimpl->CurrentInput[0] == '\0')
{
this->Pimpl->CommandHistoryIndexInv = -1; // Reset history navigation on hiding
this->Pimpl->ClearCompletions(); // Clear completion on hiding
this->InvokeEvent(vtkF3DImguiConsole::HideEvent);
}
ImGui::Begin("Console", nullptr, winFlags);
// Log window, will only show if not in minimal mode
if (!minimal)
{
const float reservedHeight =
ImGui::GetStyle().ItemSpacing.y + ImGui::GetFrameHeightWithSpacing();
if (ImGui::BeginChild(
"LogRegion", ImVec2(0, -reservedHeight), 0, ImGuiWindowFlags_HorizontalScrollbar))
{
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4, 1)); // Tighten spacing
for (const auto& [severity, msg] : this->Pimpl->Logs)
{
bool hasColor = true;
if (this->GetUseColoring())
{
switch (severity)
{
case Internals::LogType::Error:
ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.0f, 0.0f, 1.0f));
break;
case Internals::LogType::Warning:
ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 1.0f, 0.0f, 1.0f));
break;
case Internals::LogType::Typed:
ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.0f, 1.0f, 1.0f, 1.0f));
break;
case Internals::LogType::Completion:
ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.6f, 1.0f, 0.6f, 1.0f));
break;
default:
hasColor = false;
}
}
else
{
hasColor = false;
}
ImGui::TextUnformatted(msg.c_str());
if (hasColor)
{
ImGui::PopStyleColor();
}
}
if (ImGui::GetScrollY() >= ImGui::GetScrollMaxY())
{
ImGui::SetScrollHereY(1.0f);
}
ImGui::PopStyleVar();
}
ImGui::EndChild();
ImGui::Separator();
}
// input
ImGuiInputTextFlags inputFlags = ImGuiInputTextFlags_EnterReturnsTrue |
ImGuiInputTextFlags_EscapeClearsAll | ImGuiInputTextFlags_CallbackCompletion |
ImGuiInputTextFlags_CallbackHistory;
ImGui::Text("> ");
ImGui::SameLine();
ImGui::PushItemWidth(-1);
auto TextEditCallbackStub = [](ImGuiInputTextCallbackData* data) -> int
{
vtkF3DImguiConsole::Internals* internals = (vtkF3DImguiConsole::Internals*)data->UserData;
return internals->TextEditCallback(data);
};
bool runCommand = ImGui::InputText("##ConsoleInput", this->Pimpl->CurrentInput.data(),
sizeof(this->Pimpl->CurrentInput), inputFlags, TextEditCallbackStub, this->Pimpl.get());
ImGui::PopItemWidth();
ImGui::SetItemDefaultFocus();
// if always forcing the focus, it prevents grabbing the scrollbar
if (!ImGui::IsAnyItemActive())
{
ImGui::SetKeyboardFocusHere(-1);
}
// do not run the command if nothing is in the input text
if (runCommand && this->Pimpl->CurrentInput[0] != 0)
{
this->Pimpl->Logs.emplace_back(std::make_pair(
Internals::LogType::Typed, std::string("> ") + this->Pimpl->CurrentInput.data()));
this->InvokeEvent(vtkF3DImguiConsole::TriggerEvent, this->Pimpl->CurrentInput.data());
this->Pimpl->CommandHistory.emplace_back(this->Pimpl->CurrentInput.data());
this->Pimpl->CommandHistoryIndexInv = -1; // Reset history navigation, looks natural
this->Pimpl->CurrentInput = {};
}
if (runCommand)
{
// No need to show completions after command is run
this->Pimpl->ClearCompletions();
// exit console immediately after running command if in minimal mode
if (minimal)
{
this->InvokeEvent(vtkF3DImguiConsole::HideEvent);
}
}
ImGui::End();
}
//----------------------------------------------------------------------------
void vtkF3DImguiConsole::ShowBadge()
{
ImGuiViewport* viewport = ImGui::GetMainViewport();
if (this->Pimpl->NewError || this->Pimpl->NewWarning)
{
constexpr float marginTopRight = 5.f;
const float padding = ImGui::GetStyle().WindowPadding.x + ImGui::GetStyle().FramePadding.x;
ImVec2 winSize = ImGui::CalcTextSize("!");
winSize.x += 2.f * padding;
winSize.y += 2.f * padding;
ImGui::SetNextWindowPos(
ImVec2(viewport->WorkSize.x - winSize.x - marginTopRight, marginTopRight));
ImGui::SetNextWindowSize(winSize);
ImGuiWindowFlags winFlags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoSavedSettings |
ImGuiWindowFlags_NoNav | ImGuiWindowFlags_NoMove;
ImGui::Begin("ConsoleAlert", nullptr, winFlags);
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));
const bool useColoring = this->GetUseColoring();
if (useColoring)
{
ImGui::PushStyleColor(ImGuiCol_Text,
this->Pimpl->NewError ? ImVec4(1.0f, 0.0f, 0.0f, 1.0f) : ImVec4(1.0f, 1.0f, 0.0f, 1.0f));
}
if (ImGui::Button("!"))
{
this->InvokeEvent(vtkF3DImguiConsole::ShowEvent);
}
ImGui::PopStyleColor(useColoring ? 2 : 1);
ImGui::End();
}
}
//----------------------------------------------------------------------------
void vtkF3DImguiConsole::Clear()
{
this->Pimpl->Logs.clear();
this->Pimpl->NewError = false;
this->Pimpl->NewWarning = false;
}
//----------------------------------------------------------------------------
void vtkF3DImguiConsole::SetCommandsMatchCallback(
std::function<std::vector<std::string>(const std::string& pattern)> callback)
{
this->Pimpl->GetCommandsMatchCallback = std::move(callback);
}