OXYGENHUB
◆ main openmsx / src / imgui / ImGuiMessages.cc
15.8 KiB · C++ · last changed chore(): initial commit 1 month ago source blame history raw
1
#include "ImGuiMessages.hh"
2
3
#include "CustomFont.h"
4
#include "ImGuiCpp.hh"
5
#include "ImGuiManager.hh"
6
#include "ImGuiUtils.hh"
7
8
#include "GlobalCliComm.hh"
9
#include "PixelOperations.hh"
10
#include "Reactor.hh"
11
12
#include "Timer.hh"
13
#include "stl.hh"
14
15
#include <imgui.h>
16
#include <imgui_stdlib.h>
17
18
#include <algorithm>
19
#include <cassert>
20
#include <concepts>
21
#include <utility>
22
23
namespace openmsx {
24
25
using namespace std::literals;
26
using enum CliComm::LogLevel;
27
28
ImGuiMessages::ImGuiMessages(ImGuiManager& manager_)
29
	: ImGuiPart(manager_)
30
	, modalMessages(10)
31
	, popupMessages(10)
32
	, allMessages(10)
33
{
34
	popupAction[INFO] = NO_POPUP;
35
	popupAction[WARNING] = POPUP;
36
	popupAction[LOGLEVEL_ERROR] = MODAL_POPUP;
37
	popupAction[PROGRESS] = NO_POPUP;
38
	openLogAction[INFO] = NO_OPEN_LOG;
39
	openLogAction[WARNING] = NO_OPEN_LOG;
40
	openLogAction[LOGLEVEL_ERROR] = NO_OPEN_LOG;
41
	openLogAction[PROGRESS] = NO_OPEN_LOG;
42
	osdAction[INFO] = SHOW_OSD;
43
	osdAction[WARNING] = NO_OSD;
44
	osdAction[LOGLEVEL_ERROR] = NO_OSD;
45
	osdAction[PROGRESS] = NO_OSD;
46
47
	auto& reactor = manager.getReactor();
48
	auto& cliComm = reactor.getGlobalCliComm();
49
	listenerHandle = cliComm.addListener(std::make_unique<Listener>(*this));
50
}
51
52
ImGuiMessages::~ImGuiMessages()
53
{
54
	auto& reactor = manager.getReactor();
55
	auto& cliComm = reactor.getGlobalCliComm();
56
	cliComm.removeListener(*listenerHandle);
57
}
58
59
void ImGuiMessages::save(ImGuiTextBuffer& buf)
60
{
61
	savePersistent(buf, *this, persistentElements);
62
	buf.appendf("popupActions=[%d %d %d]\n",
63
		popupAction[LOGLEVEL_ERROR],
64
		popupAction[WARNING],
65
		popupAction[INFO]);
66
	buf.appendf("openLogActions=[%d %d %d]\n",
67
		openLogAction[LOGLEVEL_ERROR],
68
		openLogAction[WARNING],
69
		openLogAction[INFO]);
70
	buf.appendf("osdActions=[%d %d %d]\n",
71
		osdAction[LOGLEVEL_ERROR],
72
		osdAction[WARNING],
73
		osdAction[INFO]);
74
	buf.appendf("fadeOutDuration=[%f %f %f]\n",
75
		double(colorSequence[LOGLEVEL_ERROR][2].start), // note: cast to double only to silence warnings
76
		double(colorSequence[WARNING][2].start),
77
		double(colorSequence[INFO][2].start));
78
}
79
80
void ImGuiMessages::loadLine(std::string_view name, zstring_view value)
81
{
82
	if (loadOnePersistent(name, value, *this, persistentElements)) {
83
		// already handled
84
	} else if (name == "popupActions"sv) {
85
		std::array<int, 3> a = {};
86
		if (sscanf(value.c_str(), "[%d %d %d]", &a[0], &a[1], &a[2]) == 3) {
87
			popupAction[LOGLEVEL_ERROR] = PopupAction(a[0]);
88
			popupAction[WARNING]        = PopupAction(a[1]);
89
			popupAction[INFO]           = PopupAction(a[2]);
90
		}
91
	} else if (name == "openLogActions"sv) {
92
		std::array<int, 3> a = {};
93
		if (sscanf(value.c_str(), "[%d %d %d]", &a[0], &a[1], &a[2]) == 3) {
94
			openLogAction[LOGLEVEL_ERROR] = OpenLogAction(a[0]);
95
			openLogAction[WARNING]        = OpenLogAction(a[1]);
96
			openLogAction[INFO]           = OpenLogAction(a[2]);
97
		}
98
	} else if (name == "osdActions"sv) {
99
		std::array<int, 3> a = {};
100
		if (sscanf(value.c_str(), "[%d %d %d]", &a[0], &a[1], &a[2]) == 3) {
101
			osdAction[LOGLEVEL_ERROR] = OsdAction(a[0]);
102
			osdAction[WARNING]        = OsdAction(a[1]);
103
			osdAction[INFO]           = OsdAction(a[2]);
104
		}
105
	} else if (name == "fadeOutDuration"sv) {
106
		std::array<float, 3> a = {};
107
		if (sscanf(value.c_str(), "[%f %f %f]", &a[0], &a[1], &a[2]) == 3) {
108
			colorSequence[LOGLEVEL_ERROR][2].start = a[0];
109
			colorSequence[WARNING][2].start        = a[1];
110
			colorSequence[INFO][2].start           = a[2];
111
		}
112
	}
113
}
114
115
void ImGuiMessages::paint(MSXMotherBoard* /*motherBoard*/)
116
{
117
	paintModal();
118
	paintPopup();
119
	paintProgress();
120
	paintOSD();
121
	if (logWindow.open) paintLog();
122
	if (configureWindow.open) paintConfigure();
123
}
124
125
template<std::predicate<std::string_view, std::string_view> Filter = always_true>
126
static void printMessages(const circular_buffer<ImGuiMessages::Message>& messages, Filter filter = {})
127
{
128
	im::TextWrapPos(ImGui::GetFontSize() * 50.0f, [&]{
129
		for (const auto& message : messages) {
130
			auto [color, prefix] = [&] -> std::pair<ImU32, std::string_view> {
131
				switch (message.level) {
132
					case LOGLEVEL_ERROR: return {getColor(imColor::ERROR),   "Error:"};
133
					case WARNING:        return {getColor(imColor::WARNING), "Warning:"};
134
					case INFO:           return {getColor(imColor::TEXT),    "Info:"};
135
					default: assert(false);       return {getColor(imColor::TEXT),    "Unknown:"};
136
				}
137
			}();
138
			if (std::invoke(filter, prefix, message.text)) {
139
				im::StyleColor(ImGuiCol_Text, color, [&]{
140
					ImGui::TextUnformatted(prefix);
141
					ImGui::SameLine();
142
					ImGui::TextUnformatted(message.text);
143
				});
144
			}
145
		}
146
	});
147
}
148
149
bool ImGuiMessages::paintButtons()
150
{
151
	ImGui::SetCursorPosX(40.0f);
152
	bool close = ImGui::Button("Ok");
153
	ImGui::SameLine(0.0f, 30.0f);
154
	if (ImGui::SmallButton("Configure")) {
155
		close = true;
156
		configureWindow.raise();
157
	}
158
	return close;
159
}
160
161
void ImGuiMessages::paintModal()
162
{
163
	if (doOpenModal) {
164
		doOpenModal = false;
165
		ImGui::OpenPopup("Message");
166
	}
167
168
	bool open = true;
169
	ImGui::SetNextWindowPos(ImGui::GetMainViewport()->GetCenter(), ImGuiCond_Appearing, {0.5f, 0.5f});
170
	im::PopupModal("Message", &open, ImGuiWindowFlags_AlwaysAutoResize, [&]{
171
		printMessages(modalMessages);
172
		bool close = paintButtons();
173
		if (!open || close) {
174
			modalMessages.clear();
175
			ImGui::CloseCurrentPopup();
176
		}
177
	});
178
}
179
180
void ImGuiMessages::paintPopup()
181
{
182
	// TODO automatically fade-out and close
183
	if (doOpenPopup) {
184
		// on first open, clear old messages
185
		if (!ImGui::IsPopupOpen("popup-message")) {
186
			while (popupMessages.size() > doOpenPopup) {
187
				popupMessages.pop_back();
188
			}
189
		}
190
		doOpenPopup = 0;
191
		ImGui::OpenPopup("popup-message");
192
	}
193
194
	im::Popup("popup-message", [&]{
195
		printMessages(popupMessages);
196
		bool close = paintButtons();
197
		if (close) ImGui::CloseCurrentPopup();
198
	});
199
}
200
201
void ImGuiMessages::paintProgress()
202
{
203
	if (doOpenProgress) {
204
		doOpenProgress = false;
205
		ImGui::OpenPopup("popup-progress");
206
	}
207
208
	im::Popup("popup-progress", [&]{
209
		if (progressFraction >= 1.0f) {
210
			ImGui::CloseCurrentPopup();
211
		} else {
212
			ImGui::TextUnformatted(progressMessage);
213
			if (progressFraction >= 0.0f) {
214
				ImGui::ProgressBar(progressFraction);
215
			} else {
216
				// unknown fraction, animate progress bar, no label
217
				progressTime = fmodf(progressTime + ImGui::GetIO().DeltaTime, 2.0f);
218
				float fraction = (progressTime < 1.0f) ? progressTime : (2.0f - progressTime);
219
				ImGui::ProgressBar(fraction, {}, "");
220
			}
221
		}
222
	});
223
}
224
225
void ImGuiMessages::paintOSD()
226
{
227
	auto getColors = [&](const ColorSequence& seq, float t) -> std::optional<Colors> {
228
		for (auto i : xrange(seq.size() - 1)) { // TODO c++23 std::views::pairwise
229
			const auto& step0 = seq[i + 0];
230
			const auto& step1 = seq[i + 1];
231
			if (t < step1.start) {
232
				PixelOperations p;
233
				auto x = int(256.0f * (t / step1.start));
234
				auto tCol = p.lerp(step0.colors.text,       step1.colors.text,       x);
235
				auto bCol = p.lerp(step0.colors.background, step1.colors.background, x);
236
				return Colors{.text = tCol, .background = bCol};
237
			}
238
			t -= step1.start;
239
		}
240
		return {};
241
	};
242
243
	const auto& style = ImGui::GetStyle();
244
	gl::vec2 offset = style.FramePadding;
245
	const auto* mainViewPort = ImGui::GetMainViewport();
246
247
	struct DrawInfo {
248
		std::string message;
249
		gl::vec2 boxSize;
250
		float yPos;
251
		uint32_t textCol, bgCol;
252
	};
253
	std::vector<DrawInfo> drawInfo;
254
	float y = 0.0f;
255
	float width = 0.0f;
256
	//float wrapWidth = mainViewPort->WorkSize.x - 2.0f * offset[0]; // TODO wrap ?
257
	float delta = ImGui::GetIO().DeltaTime;
258
	std::erase_if(osdMessages, [&](OsdMessage& message) {
259
		message.time += delta;
260
		auto colors = getColors(colorSequence[message.level], message.time);
261
		if (!colors) return true; // remove message
262
263
		auto& text = message.text;
264
		gl::vec2 textSize = ImGui::CalcTextSize(text.data(), text.data() + text.size());
265
		gl::vec2 boxSize = textSize + 2.0f * offset;
266
		drawInfo.emplace_back(text, boxSize, y, colors->text, colors->background);
267
		y += boxSize.y + style.ItemSpacing.y;
268
		width = std::max(width, boxSize.x);
269
		return false; // keep message
270
	});
271
	if (drawInfo.empty()) return;
272
273
	int flags = ImGuiWindowFlags_NoMove
274
	          | ImGuiWindowFlags_NoBackground
275
	          | ImGuiWindowFlags_NoSavedSettings
276
	          | ImGuiWindowFlags_NoDocking
277
	          | ImGuiWindowFlags_NoNav
278
	          | ImGuiWindowFlags_NoDecoration
279
	          | ImGuiWindowFlags_NoInputs
280
	          | ImGuiWindowFlags_NoFocusOnAppearing;
281
	ImGui::SetNextWindowViewport(mainViewPort->ID);
282
	ImGui::SetNextWindowPos(gl::vec2(mainViewPort->WorkPos) + gl::vec2(style.ItemSpacing));
283
	ImGui::SetNextWindowSize({width, y});
284
	im::Window("OSD messages", nullptr, flags, [&]{
285
		auto* drawList = ImGui::GetWindowDrawList();
286
		gl::vec2 windowPos = ImGui::GetWindowPos();
287
		for (const auto& [message, boxSize, yPos, textCol, bgCol] : drawInfo) {
288
			gl::vec2 pos = windowPos + gl::vec2{0.0f, yPos};
289
			drawList->AddRectFilled(pos, pos + boxSize, bgCol);
290
			drawList->AddText(pos + offset, textCol, message.data(), message.data() + message.size());
291
		}
292
	});
293
}
294
295
void ImGuiMessages::paintLog()
296
{
297
	if (logWindow.do_raise) {
298
		assert(logWindow.open);
299
		ImGui::SetNextWindowFocus();
300
	}
301
	ImGui::SetNextWindowSize(gl::vec2{40, 14} * ImGui::GetFontSize(), ImGuiCond_FirstUseEver);
302
	im::Window("Message Log", logWindow, ImGuiWindowFlags_NoFocusOnAppearing, [&]{
303
		const auto& style = ImGui::GetStyle();
304
		auto buttonHeight = ImGui::GetFontSize() + 2.0f * style.FramePadding.y + style.ItemSpacing.y;
305
		im::Child("messages", {0.0f, -buttonHeight}, ImGuiChildFlags_Borders, ImGuiWindowFlags_HorizontalScrollbar, [&]{
306
			printMessages(allMessages, [&](std::string_view prefix, std::string_view message) {
307
				if (filterLog.empty()) return true;
308
				auto full = tmpStrCat(prefix, message);
309
				return std::ranges::all_of(StringOp::split_view<StringOp::EmptyParts::REMOVE>(filterLog, ' '),
310
					[&](auto part) { return StringOp::containsCaseInsensitive(full, part); });
311
			});
312
		});
313
		if (ImGui::Button("Clear")) {
314
			allMessages.clear();
315
		}
316
		simpleToolTip("Remove all log messages");
317
		ImGui::SameLine(0.0f, 30.0f);
318
		ImGui::TextUnformatted(ICON_IGFD_FILTER);
319
		ImGui::SameLine();
320
		auto size = ImGui::CalcTextSize("Configure"sv).x + 30.0f + style.WindowPadding.x;
321
		ImGui::SetNextItemWidth(-size);
322
		ImGui::InputTextWithHint("##filter", "enter filter terms", &filterLog);
323
		ImGui::SameLine(0.0f, 30.0f);
324
		if (ImGui::SmallButton("Configure")) {
325
			configureWindow.raise();
326
		}
327
	});
328
}
329
330
void ImGuiMessages::paintConfigure()
331
{
332
	ImGui::SetNextWindowSize(gl::vec2{24, 26} * ImGui::GetFontSize(), ImGuiCond_FirstUseEver);
333
	im::Window("Configure messages", configureWindow, [&]{
334
		ImGui::TextUnformatted("When a message is emitted"sv);
335
336
		auto size = ImGui::CalcTextSize("Warning"sv).x;
337
		im::Table("table", 4, ImGuiTableFlags_SizingFixedFit, [&]{
338
			ImGui::TableSetupColumn("", ImGuiTableColumnFlags_None, 0);
339
			ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, size);
340
			ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, size);
341
			ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, size);
342
343
			if (ImGui::TableNextColumn()) { /* nothing */ }
344
			if (ImGui::TableNextColumn()) ImGui::TextUnformatted("Error"sv);
345
			if (ImGui::TableNextColumn()) ImGui::TextUnformatted("Warning"sv);
346
			if (ImGui::TableNextColumn()) ImGui::TextUnformatted("Info"sv);
347
348
			if (ImGui::TableNextColumn()) {
349
				ImGui::TextUnformatted("Show popup"sv);
350
			}
351
			ImGui::TableNextRow();
352
			if (ImGui::TableNextColumn()) {
353
				im::Indent([]{ ImGui::TextUnformatted("modal"sv); });
354
			}
355
			for (auto level : {LOGLEVEL_ERROR, WARNING, INFO}) {
356
				if (ImGui::TableNextColumn()) {
357
					ImGui::RadioButton(tmpStrCat("##modal", std::to_underlying(level)).c_str(), &popupAction[level], MODAL_POPUP);
358
				}
359
			}
360
			if (ImGui::TableNextColumn()) {
361
				im::Indent([]{ ImGui::TextUnformatted("non-modal"sv); });
362
			}
363
			for (auto level : {LOGLEVEL_ERROR, WARNING, INFO}) {
364
				if (ImGui::TableNextColumn()) {
365
					ImGui::RadioButton(tmpStrCat("##popup", std::to_underlying(level)).c_str(), &popupAction[level], POPUP);
366
				}
367
			}
368
			if (ImGui::TableNextColumn()) {
369
				im::Indent([]{ ImGui::TextUnformatted("don't show"sv); });
370
			}
371
			for (auto level : {LOGLEVEL_ERROR, WARNING, INFO}) {
372
				if (ImGui::TableNextColumn()) {
373
					ImGui::RadioButton(tmpStrCat("##noPopup", std::to_underlying(level)).c_str(), &popupAction[level], NO_POPUP);
374
				}
375
			}
376
377
			if (ImGui::TableNextColumn()) {
378
				ImGui::TextUnformatted("Log window"sv);
379
			}
380
			ImGui::TableNextRow();
381
			if (ImGui::TableNextColumn()) {
382
				im::Indent([]{ ImGui::TextUnformatted("open and focus"sv); });
383
			}
384
			for (auto level : {LOGLEVEL_ERROR, WARNING, INFO}) {
385
				if (ImGui::TableNextColumn()) {
386
					ImGui::RadioButton(tmpStrCat("##focus", std::to_underlying(level)).c_str(), &openLogAction[level], OPEN_LOG_FOCUS);
387
				}
388
			}
389
			if (ImGui::TableNextColumn()) {
390
				im::Indent([]{ ImGui::TextUnformatted("open without focus"sv); });
391
			}
392
			for (auto level : {LOGLEVEL_ERROR, WARNING, INFO}) {
393
				if (ImGui::TableNextColumn()) {
394
					ImGui::RadioButton(tmpStrCat("##log", std::to_underlying(level)).c_str(), &openLogAction[level], OPEN_LOG);
395
				}
396
			}
397
			if (ImGui::TableNextColumn()) {
398
				im::Indent([]{ ImGui::TextUnformatted("don't open"sv); });
399
			}
400
			for (auto level : {LOGLEVEL_ERROR, WARNING, INFO}) {
401
				if (ImGui::TableNextColumn()) {
402
					ImGui::RadioButton(tmpStrCat("##nolog", std::to_underlying(level)).c_str(), &openLogAction[level], NO_OPEN_LOG);
403
				}
404
			}
405
406
			if (ImGui::TableNextColumn()) {
407
				ImGui::TextUnformatted("On-screen message"sv);
408
			}
409
			ImGui::TableNextRow();
410
			if (ImGui::TableNextColumn()) {
411
				im::Indent([]{ ImGui::TextUnformatted("show"sv); });
412
			}
413
			for (auto level : {LOGLEVEL_ERROR, WARNING, INFO}) {
414
				if (ImGui::TableNextColumn()) {
415
					ImGui::RadioButton(tmpStrCat("##osd", std::to_underlying(level)).c_str(), &osdAction[level], SHOW_OSD);
416
				}
417
			}
418
			if (ImGui::TableNextColumn()) {
419
				im::Indent([]{ ImGui::TextUnformatted("don't show"sv); });
420
			}
421
			for (auto level : {LOGLEVEL_ERROR, WARNING, INFO}) {
422
				if (ImGui::TableNextColumn()) {
423
					ImGui::RadioButton(tmpStrCat("##no-osd", std::to_underlying(level)).c_str(), &osdAction[level], NO_OSD);
424
				}
425
			}
426
			if (ImGui::TableNextColumn()) {
427
				im::Indent([]{ ImGui::TextUnformatted("fade-out (seconds)"sv); });
428
			}
429
			for (auto level : {LOGLEVEL_ERROR, WARNING, INFO}) {
430
				if (ImGui::TableNextColumn()) {
431
					float& d = colorSequence[level][2].start;
432
					if (ImGui::InputFloat(tmpStrCat("##dur", std::to_underlying(level)).c_str(), &d, 0.0f, 0.0f, "%.0f", ImGuiInputTextFlags_CharsDecimal)) {
433
						d = std::clamp(d, 1.0f, 99.0f);
434
					}
435
				}
436
			}
437
		});
438
	});
439
}
440
441
static bool needThrottle(const circular_buffer<ImGuiMessages::Message>& buffer, uint64_t now)
442
{
443
	return ((buffer.size() >=  5) && ((now - buffer[4].timestamp) <  1'000'000)) || // 5 in the last second
444
	       ((buffer.size() >= 10) && ((now - buffer[9].timestamp) < 60'000'000));   // 10 in the last minute
445
}
446
447
void ImGuiMessages::log(CliComm::LogLevel level, std::string_view text, float fraction)
448
{
449
	if (level == PROGRESS) {
450
		progressMessage = text;
451
		progressFraction = fraction;
452
		if (progressFraction < 1.0f) doOpenProgress = true;
453
		return;
454
	}
455
456
	auto now = Timer::getTime();
457
	Message message{.level = level, .text = std::string(text), .timestamp = now};
458
459
	if (popupAction[level] == MODAL_POPUP) {
460
		if (modalMessages.full()) modalMessages.pop_back();
461
		modalMessages.push_front(message);
462
		if (!needThrottle(modalMessages, now)) {
463
			doOpenModal = true;
464
		}
465
	} else if (popupAction[level] == POPUP) {
466
		if (popupMessages.full()) popupMessages.pop_back();
467
		popupMessages.push_front(message);
468
		if (!needThrottle(popupMessages, now)) {
469
			doOpenPopup = popupMessages.size();
470
		}
471
	}
472
473
	if (openLogAction[level] == OPEN_LOG) {
474
		logWindow.open = true;
475
	} else if (openLogAction[level] == OPEN_LOG_FOCUS) {
476
		if (!needThrottle(allMessages, now)) {
477
			logWindow.raise();
478
		}
479
	}
480
481
	if (osdAction[level] == SHOW_OSD) {
482
		if (osdMessages.size() >= 10) {
483
			osdMessages.erase(osdMessages.begin());
484
		}
485
		osdMessages.emplace_back(std::string(text), 0.0f, level);
486
	}
487
488
	if (allMessages.full()) allMessages.pop_back();
489
	allMessages.push_front(std::move(message));
490
}
491
492
} // namespace openmsx