openMSX
ImGuiUtils.hh
Go to the documentation of this file.
1#ifndef IMGUI_UTILS_HH
2#define IMGUI_UTILS_HH
3
4#include "ImGuiCpp.hh"
5
6#include "Reactor.hh"
7
8#include "function_ref.hh"
9#include "ranges.hh"
10#include "strCat.hh"
11#include "StringOp.hh"
12
13#include <imgui.h>
14#include <imgui_internal.h> // ImTextCharToUtf8
15
16#include <algorithm>
17#include <concepts>
18#include <span>
19#include <string>
20#include <string_view>
21#include <utility>
22
23namespace ImGui {
24
25inline void TextUnformatted(const std::string& str)
26{
27 const char* begin = str.data();
28 const char* end = begin + str.size();
30}
31inline void TextUnformatted(std::string_view str)
32{
33 const char* begin = str.data();
34 const char* end = begin + str.size();
36}
37
38inline auto CalcTextSize(std::string_view str)
39{
40 return ImGui::CalcTextSize(str.data(), str.data() + str.size());
41}
42
43template<typename... Ts>
44void StrCat(Ts&& ...ts)
45{
46 auto s = tmpStrCat(std::forward<Ts>(ts)...);
47 TextUnformatted(std::string_view(s));
48}
49
50inline void RightAlignText(std::string_view text, std::string_view maxWidthText)
51{
52 auto maxWidth = ImGui::CalcTextSize(maxWidthText).x;
53 auto actualWidth = ImGui::CalcTextSize(text).x;
54 if (auto spacing = maxWidth - actualWidth; spacing > 0.0f) {
55 auto pos = ImGui::GetCursorPosX();
56 ImGui::SetCursorPosX(pos + spacing);
57 }
59}
60
61} // namespace ImGui
62
63namespace openmsx {
64
65class BooleanSetting;
66class FloatSetting;
67class HotKey;
68class IntegerSetting;
69class Setting;
70class VideoSourceSetting;
71
73 std::string_view value;
74 std::string_view tip;
75};
76using EnumToolTips = std::span<const EnumToolTip>;
77
78inline void simpleToolTip(std::string_view desc)
79{
80 if (desc.empty()) return;
82 im::TextWrapPos(ImGui::GetFontSize() * 35.0f, [&]{
84 });
85 });
86}
87
88void simpleToolTip(std::invocable<> auto descFunc)
89{
90 if (!ImGui::IsItemHovered(ImGuiHoveredFlags_ForTooltip)) return;
91 auto desc = std::invoke(descFunc);
92 if (desc.empty()) return;
93 im::Tooltip([&]{
94 im::TextWrapPos(ImGui::GetFontSize() * 35.0f, [&]{
96 });
97 });
98}
99
100void HelpMarker(std::string_view desc);
101
103 const char* label, gl::vec2 size, bool pressed,
104 std::invocable<gl::vec2 /*center*/, ImDrawList*> auto render)
105{
106 bool result = false;
107 im::StyleColor(pressed, ImGuiCol_Button, ImGui::GetColorU32(ImGuiCol_ButtonActive), [&]{
108 gl::vec2 topLeft = ImGui::GetCursorScreenPos();
109 gl::vec2 center = topLeft + size * 0.5f;
110 result = ImGui::Button(label, size);
111 render(center, ImGui::GetWindowDrawList());
112 });
113 return result;
114}
115
117 const char* label, gl::vec2 size,
118 std::invocable<gl::vec2 /*center*/, ImDrawList*> auto render)
119{
120 return ButtonWithCustomRendering(label, size, false, render);
121}
122
123inline bool ButtonWithCenteredGlyph(ImWchar glyph, gl::vec2 maxGlyphSize)
124{
125 std::array<char, 2 + 5> label = {'#', '#'};
126 ImTextCharToUtf8(&label[2], glyph);
127
128 const auto& style = ImGui::GetStyle();
129 auto buttonSize = maxGlyphSize + 2.0f* gl::vec2(style.FramePadding);
130
131 return ButtonWithCustomRendering(label.data(), buttonSize, [&](gl::vec2 center, ImDrawList* drawList) {
132 const auto* font = ImGui::GetFont();
133 auto texId = font->ContainerAtlas->TexID;
134 const auto* g = font->FindGlyph(glyph);
135 auto halfSize = gl::vec2{g->X1 - g->X0, g->Y1 - g->Y0} * 0.5f;
136 drawList->AddImage(texId, center - halfSize, center + halfSize, {g->U0, g->V0}, {g->U1, g->V1});
137 });
138};
139
141{
142 static constexpr gl::vec2 center{0.5f, 0.5f};
143 gl::vec2 windowPos = ImGui::GetWindowPos();
144 gl::vec2 windowSize = ImGui::GetWindowSize();
145 auto windowCenter = windowPos + center * windowSize;
146 ImGui::SetNextWindowPos(windowCenter, ImGuiCond_Appearing, center);
147}
148
150 std::string operator()(const Setting& setting) const;
151};
152
153bool Checkbox(const HotKey& hotkey, BooleanSetting& setting);
154bool Checkbox(const HotKey& hotkey, const char* label, BooleanSetting& setting, function_ref<std::string(const Setting&)> getTooltip = GetSettingDescription{});
155bool SliderInt(IntegerSetting& setting, ImGuiSliderFlags flags = 0);
156bool SliderInt(const char* label, IntegerSetting& setting, ImGuiSliderFlags flags = 0);
157bool SliderFloat(FloatSetting& setting, const char* format = "%.3f", ImGuiSliderFlags flags = 0);
158bool SliderFloat(const char* label, FloatSetting& setting, const char* format = "%.3f", ImGuiSliderFlags flags = 0);
159bool InputText(Setting& setting);
160bool InputText(const char* label, Setting& setting);
161void ComboBox(Setting& setting, EnumToolTips toolTips = {}); // must be an EnumSetting
162void ComboBox(const char* label, Setting& setting, EnumToolTips toolTips = {}); // must be an EnumSetting
163void ComboBox(const char* label, Setting& setting, function_ref<std::string(const std::string&)> displayValue, EnumToolTips toolTips = {});
164void ComboBox(VideoSourceSetting& setting);
165void ComboBox(const char* label, VideoSourceSetting& setting);
166
167const char* getComboString(int item, const char* itemsSeparatedByZeros);
168
169std::string formatTime(std::optional<double> time);
170float calculateFade(float current, float target, float period);
171
172template<int HexDigits>
173void comboHexSequence(const char* label, int* value, int mult, int max, int offset) {
174 assert(offset < mult);
175 *value &= ~(mult - 1);
176 // only apply offset in display, not in the actual value
177 auto preview = tmpStrCat("0x", hex_string<HexDigits>(*value | offset));
178 im::Combo(label, preview.c_str(), [&]{
179 for (int addr = 0; addr < max; addr += mult) {
180 if (auto str = tmpStrCat("0x", hex_string<HexDigits>(addr | offset));
181 ImGui::Selectable(str.c_str(), *value == addr)) {
182 *value = addr;
183 }
184 if (*value == addr) {
185 ImGui::SetItemDefaultFocus();
186 }
187 }
188 });
189};
190
191template<typename Range, typename Projection>
192void sortUpDown_T(Range& range, const ImGuiTableSortSpecs* sortSpecs, Projection proj) {
193 if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Descending) {
194 ranges::stable_sort(range, std::greater<>{}, proj);
195 } else {
196 ranges::stable_sort(range, std::less<>{}, proj);
197 }
198};
199template<typename Range, typename Projection>
200void sortUpDown_String(Range& range, const ImGuiTableSortSpecs* sortSpecs, Projection proj) {
201 if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Descending) {
203 } else {
205 }
206};
207
208
209[[nodiscard]] inline const std::string* getOptionalDictValue(
210 const std::vector<std::pair<std::string, std::string>>& info,
211 std::string_view key)
212{
213 auto it = ranges::find_if(info, [&](const auto& p) { return p.first == key; });
214 if (it == info.end()) return {};
215 return &it->second;
216}
217
218template<typename T> // 'MachineInfo' or 'ExtensionInfo', both have a 'configInfo' member
219[[nodiscard]] std::vector<std::string> getAllValuesFor(std::string_view key, const std::vector<T>& items)
220{
221 std::vector<std::string> result;
222 for (const auto& item : items) {
223 if (const auto* value = getOptionalDictValue(item.configInfo, key)) {
224 if (!contains(result, *value)) { // O(N^2), but that's fine
225 result.emplace_back(*value);
226 }
227 }
228 }
230 return result;
231}
232
233template<typename T>
234void displayFilterCombo(std::string& selection, zstring_view key, const std::vector<T>& items)
235{
236 im::Combo(key.c_str(), selection.empty() ? "--all--" : selection.c_str(), [&]{
237 if (ImGui::Selectable("--all--")) {
238 selection.clear();
239 }
240 for (const auto& type : getAllValuesFor(key, items)) {
241 if (ImGui::Selectable(type.c_str())) {
242 selection = type;
243 }
244 }
245 });
246}
247
248template<typename T>
249void applyComboFilter(std::string_view key, std::string_view value, const std::vector<T>& items, std::vector<size_t>& indices)
250{
251 if (value.empty()) return;
252 std::erase_if(indices, [&](auto idx) {
253 const auto& info = items[idx].configInfo;
254 const auto* val = getOptionalDictValue(info, key);
255 if (!val) return true; // remove items that don't have the key
256 return *val != value;
257 });
258}
259
260template<std::invocable<size_t> GetName>
261void filterIndices(std::string_view filterString, GetName getName, std::vector<size_t>& indices)
262{
263 if (filterString.empty()) return;
264 std::erase_if(indices, [&](auto idx) {
265 const auto& name = getName(idx);
266 return !ranges::all_of(StringOp::split_view<StringOp::EmptyParts::REMOVE>(filterString, ' '),
267 [&](auto part) { return StringOp::containsCaseInsensitive(name, part); });
268 });
269}
270
271template<typename T>
272void applyDisplayNameFilter(std::string_view filterString, const std::vector<T>& items, std::vector<size_t>& indices)
273{
274 filterIndices(filterString, [&](size_t idx) { return items[idx].displayName; }, indices);
275}
276
277// Similar to c++23 chunk_by(). Main difference is internal vs external iteration.
278template<typename Range, typename BinaryPred, typename Action>
279static void chunk_by(Range&& range, BinaryPred pred, Action action)
280{
281 auto it = std::begin(range);
282 auto last = std::end(range);
283 while (it != last) {
284 auto start = it;
285 auto prev = it++;
286 while (it != last && pred(*prev, *it)) {
287 prev = it++;
288 }
289 action(start, it);
290 }
291}
292
293std::string getShortCutForCommand(const HotKey& hotkey, std::string_view command);
294
295std::string getKeyChordName(ImGuiKeyChord keyChord);
296std::optional<ImGuiKeyChord> parseKeyChord(std::string_view name);
297
298// Read from VRAM-table, including mirroring behavior
299// shared between ImGuiCharacter, ImGuiSpriteViewer
301public:
302 VramTable(std::span<const uint8_t> vram_, bool planar_ = false)
303 : vram(vram_), planar(planar_) {}
304
305 void setRegister(unsigned value, unsigned extraLsbBits) {
306 registerMask = (value << extraLsbBits) | ~(~0u << extraLsbBits);
307 }
308 void setIndexSize(unsigned bits) {
309 indexMask = ~0u << bits;
310 }
311
312 [[nodiscard]] auto getAddress(unsigned index) const {
313 return registerMask & (indexMask | index);
314 }
315 [[nodiscard]] uint8_t operator[](unsigned index) const {
316 auto addr = getAddress(index);
317 if (planar) {
318 addr = ((addr << 16) | (addr >> 1)) & 0x1'FFFF;
319 }
320 return vram[addr];
321 }
322private:
323 std::span<const uint8_t> vram;
324 unsigned registerMask = 0;
325 unsigned indexMask = 0;
326 bool planar = false;
327};
328
329enum class imColor : unsigned {
331 BLACK,
332 WHITE,
333 GRAY,
334 YELLOW,
335 RED_BG, // red background (transparent)
336 YELLOW_BG, // yellow background (transparent)
337
338 TEXT,
340
341 ERROR,
342 WARNING,
343
344 COMMENT, // syntax highlighting in the console
345 VARIABLE,
346 LITERAL,
347 PROC,
348 OPERATOR,
349
350 KEY_ACTIVE, // virtual keyboard
352
354};
355inline std::array<ImU32, size_t(imColor::NUM_COLORS)> imColors;
356
357void setColors(int style);
358
359inline ImU32 getColor(imColor col) {
360 assert(col < imColor::NUM_COLORS);
361 return imColors[size_t(col)];
362}
363
364} // namespace openmsx
365
366#endif
BaseSetting * setting
int g
void setRegister(unsigned value, unsigned extraLsbBits)
auto getAddress(unsigned index) const
VramTable(std::span< const uint8_t > vram_, bool planar_=false)
uint8_t operator[](unsigned index) const
void setIndexSize(unsigned bits)
Like std::string_view, but with the extra guarantee that it refers to a zero-terminated string.
constexpr const char * c_str() const
const char * ImTextCharToUtf8(char out_buf[5], unsigned int c)
Definition imgui.cc:2479
void StrCat(Ts &&...ts)
Definition ImGuiUtils.hh:44
auto CalcTextSize(std::string_view str)
Definition ImGuiUtils.hh:38
void TextUnformatted(const std::string &str)
Definition ImGuiUtils.hh:25
void RightAlignText(std::string_view text, std::string_view maxWidthText)
Definition ImGuiUtils.hh:50
bool containsCaseInsensitive(std::string_view haystack, std::string_view needle)
Definition StringOp.hh:181
vecN< 2, float > vec2
Definition gl_vec.hh:178
void Combo(const char *label, const char *preview_value, ImGuiComboFlags flags, std::invocable<> auto next)
Definition ImGuiCpp.hh:289
void StyleColor(bool active, Args &&...args)
Definition ImGuiCpp.hh:175
void TextWrapPos(float wrap_local_pos_x, std::invocable<> auto next)
Definition ImGuiCpp.hh:212
void Tooltip(std::invocable<> auto next)
Definition ImGuiCpp.hh:374
void ItemTooltip(std::invocable<> auto next)
Definition ImGuiCpp.hh:382
This file implemented 3 utility functions:
Definition Autofire.cc:11
bool Checkbox(const HotKey &hotKey, BooleanSetting &setting)
Definition ImGuiUtils.cc:58
std::span< const EnumToolTip > EnumToolTips
Definition ImGuiUtils.hh:76
void centerNextWindowOverCurrent()
void filterIndices(std::string_view filterString, GetName getName, std::vector< size_t > &indices)
void ComboBox(const char *label, Setting &setting, function_ref< std::string(const std::string &)> displayValue, EnumToolTips toolTips)
void applyComboFilter(std::string_view key, std::string_view value, const std::vector< T > &items, std::vector< size_t > &indices)
void sortUpDown_String(Range &range, const ImGuiTableSortSpecs *sortSpecs, Projection proj)
void simpleToolTip(std::string_view desc)
Definition ImGuiUtils.hh:78
std::vector< std::string > getAllValuesFor(std::string_view key, const std::vector< T > &items)
std::string getShortCutForCommand(const HotKey &hotkey, std::string_view command)
std::array< ImU32, size_t(imColor::NUM_COLORS)> imColors
void sortUpDown_T(Range &range, const ImGuiTableSortSpecs *sortSpecs, Projection proj)
void displayFilterCombo(std::string &selection, zstring_view key, const std::vector< T > &items)
void HelpMarker(std::string_view desc)
Definition ImGuiUtils.cc:23
const std::string * getOptionalDictValue(const std::vector< std::pair< std::string, std::string > > &info, std::string_view key)
ImU32 getColor(imColor col)
std::optional< ImGuiKeyChord > parseKeyChord(std::string_view name)
const char * getComboString(int item, const char *itemsSeparatedByZeros)
void setColors(int style)
std::string getKeyChordName(ImGuiKeyChord keyChord)
void comboHexSequence(const char *label, int *value, int mult, int max, int offset)
void applyDisplayNameFilter(std::string_view filterString, const std::vector< T > &items, std::vector< size_t > &indices)
bool ButtonWithCenteredGlyph(ImWchar glyph, gl::vec2 maxGlyphSize)
std::string formatTime(std::optional< double > time)
float calculateFade(float current, float target, float period)
bool ButtonWithCustomRendering(const char *label, gl::vec2 size, bool pressed, std::invocable< gl::vec2, ImDrawList * > auto render)
constexpr bool all_of(InputRange &&range, UnaryPredicate pred)
Definition ranges.hh:188
auto find_if(InputRange &&range, UnaryPredicate pred)
Definition ranges.hh:175
void stable_sort(RandomAccessRange &&range)
Definition ranges.hh:78
constexpr void sort(RandomAccessRange &&range)
Definition ranges.hh:51
constexpr bool contains(ITER first, ITER last, const VAL &val)
Check if a range contains a given value, using linear search.
Definition stl.hh:32
TemporaryString tmpStrCat(Ts &&... ts)
Definition strCat.hh:742
std::string_view value
Definition ImGuiUtils.hh:73
std::string_view tip
Definition ImGuiUtils.hh:74
constexpr auto begin(const zstring_view &x)
constexpr auto end(const zstring_view &x)