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
15#include <algorithm>
16#include <concepts>
17#include <span>
18#include <string>
19#include <string_view>
20#include <utility>
21
22namespace ImGui {
23
24inline void TextUnformatted(const std::string& str)
25{
26 const char* begin = str.data();
27 const char* end = begin + str.size();
29}
30inline void TextUnformatted(std::string_view str)
31{
32 const char* begin = str.data();
33 const char* end = begin + str.size();
35}
36
37inline auto CalcTextSize(std::string_view str)
38{
39 return ImGui::CalcTextSize(str.data(), str.data() + str.size());
40}
41
42template<typename... Ts>
43void StrCat(Ts&& ...ts)
44{
45 auto s = tmpStrCat(std::forward<Ts>(ts)...);
46 TextUnformatted(std::string_view(s));
47}
48
49inline void RightAlignText(std::string_view text, std::string_view maxWidthText)
50{
51 auto maxWidth = ImGui::CalcTextSize(maxWidthText).x;
52 auto actualWidth = ImGui::CalcTextSize(text).x;
53 if (auto spacing = maxWidth - actualWidth; spacing > 0.0f) {
54 auto pos = ImGui::GetCursorPosX();
55 ImGui::SetCursorPosX(pos + spacing);
56 }
58}
59
60} // namespace ImGui
61
62namespace openmsx {
63
64class BooleanSetting;
65class FloatSetting;
66class HotKey;
67class IntegerSetting;
68class Setting;
69class VideoSourceSetting;
70
72 std::string_view value;
73 std::string_view tip;
74};
75using EnumToolTips = std::span<const EnumToolTip>;
76
77inline void simpleToolTip(std::string_view desc)
78{
79 if (desc.empty()) return;
81 im::TextWrapPos(ImGui::GetFontSize() * 35.0f, [&]{
83 });
84 });
85}
86
87void simpleToolTip(std::invocable<> auto descFunc)
88{
89 if (!ImGui::IsItemHovered(ImGuiHoveredFlags_ForTooltip)) return;
90 auto desc = std::invoke(descFunc);
91 if (desc.empty()) return;
92 im::Tooltip([&]{
93 im::TextWrapPos(ImGui::GetFontSize() * 35.0f, [&]{
95 });
96 });
97}
98
99void HelpMarker(std::string_view desc);
100
102{
103 static constexpr gl::vec2 center{0.5f, 0.5f};
104 gl::vec2 windowPos = ImGui::GetWindowPos();
105 gl::vec2 windowSize = ImGui::GetWindowSize();
106 auto windowCenter = windowPos + center * windowSize;
107 ImGui::SetNextWindowPos(windowCenter, ImGuiCond_Appearing, center);
108}
109
111 std::string operator()(const Setting& setting) const;
112};
113
114bool Checkbox(const HotKey& hotkey, BooleanSetting& setting);
115bool Checkbox(const HotKey& hotkey, const char* label, BooleanSetting& setting, function_ref<std::string(const Setting&)> getTooltip = GetSettingDescription{});
116bool SliderInt(IntegerSetting& setting, ImGuiSliderFlags flags = 0);
117bool SliderInt(const char* label, IntegerSetting& setting, ImGuiSliderFlags flags = 0);
118bool SliderFloat(FloatSetting& setting, const char* format = "%.3f", ImGuiSliderFlags flags = 0);
119bool SliderFloat(const char* label, FloatSetting& setting, const char* format = "%.3f", ImGuiSliderFlags flags = 0);
120bool InputText(Setting& setting);
121bool InputText(const char* label, Setting& setting);
122void ComboBox(Setting& setting, EnumToolTips toolTips = {}); // must be an EnumSetting
123void ComboBox(const char* label, Setting& setting, EnumToolTips toolTips = {}); // must be an EnumSetting
124void ComboBox(const char* label, Setting& setting, function_ref<std::string(const std::string&)> displayValue, EnumToolTips toolTips = {});
125void ComboBox(VideoSourceSetting& setting);
126void ComboBox(const char* label, VideoSourceSetting& setting);
127
128const char* getComboString(int item, const char* itemsSeparatedByZeros);
129
130std::string formatTime(std::optional<double> time);
131float calculateFade(float current, float target, float period);
132
133template<int HexDigits>
134void comboHexSequence(const char* label, int* value, int mult, int max, int offset) {
135 assert(offset < mult);
136 *value &= ~(mult - 1);
137 // only apply offset in display, not in the actual value
138 auto preview = tmpStrCat("0x", hex_string<HexDigits>(*value | offset));
139 im::Combo(label, preview.c_str(), [&]{
140 for (int addr = 0; addr < max; addr += mult) {
141 if (auto str = tmpStrCat("0x", hex_string<HexDigits>(addr | offset));
142 ImGui::Selectable(str.c_str(), *value == addr)) {
143 *value = addr;
144 }
145 if (*value == addr) {
146 ImGui::SetItemDefaultFocus();
147 }
148 }
149 });
150};
151
152template<typename Range, typename Projection>
153void sortUpDown_T(Range& range, const ImGuiTableSortSpecs* sortSpecs, Projection proj) {
154 if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Descending) {
155 ranges::stable_sort(range, std::greater<>{}, proj);
156 } else {
157 ranges::stable_sort(range, std::less<>{}, proj);
158 }
159};
160template<typename Range, typename Projection>
161void sortUpDown_String(Range& range, const ImGuiTableSortSpecs* sortSpecs, Projection proj) {
162 if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Descending) {
164 } else {
166 }
167};
168
169
170[[nodiscard]] inline const std::string* getOptionalDictValue(
171 const std::vector<std::pair<std::string, std::string>>& info,
172 std::string_view key)
173{
174 auto it = ranges::find_if(info, [&](const auto& p) { return p.first == key; });
175 if (it == info.end()) return {};
176 return &it->second;
177}
178
179template<typename T> // 'MachineInfo' or 'ExtensionInfo', both have a 'configInfo' member
180[[nodiscard]] std::vector<std::string> getAllValuesFor(std::string_view key, const std::vector<T>& items)
181{
182 std::vector<std::string> result;
183 for (const auto& item : items) {
184 if (const auto* value = getOptionalDictValue(item.configInfo, key)) {
185 if (!contains(result, *value)) { // O(N^2), but that's fine
186 result.emplace_back(*value);
187 }
188 }
189 }
191 return result;
192}
193
194template<typename T>
195void displayFilterCombo(std::string& selection, zstring_view key, const std::vector<T>& items)
196{
197 im::Combo(key.c_str(), selection.empty() ? "--all--" : selection.c_str(), [&]{
198 if (ImGui::Selectable("--all--")) {
199 selection.clear();
200 }
201 for (const auto& type : getAllValuesFor(key, items)) {
202 if (ImGui::Selectable(type.c_str())) {
203 selection = type;
204 }
205 }
206 });
207}
208
209template<typename T>
210void applyComboFilter(std::string_view key, std::string_view value, const std::vector<T>& items, std::vector<size_t>& indices)
211{
212 if (value.empty()) return;
213 std::erase_if(indices, [&](auto idx) {
214 const auto& info = items[idx].configInfo;
215 const auto* val = getOptionalDictValue(info, key);
216 if (!val) return true; // remove items that don't have the key
217 return *val != value;
218 });
219}
220
221template<std::invocable<size_t> GetName>
222void filterIndices(std::string_view filterString, GetName getName, std::vector<size_t>& indices)
223{
224 if (filterString.empty()) return;
225 std::erase_if(indices, [&](auto idx) {
226 const auto& name = getName(idx);
227 return !ranges::all_of(StringOp::split_view<StringOp::EmptyParts::REMOVE>(filterString, ' '),
228 [&](auto part) { return StringOp::containsCaseInsensitive(name, part); });
229 });
230}
231
232template<typename T>
233void applyDisplayNameFilter(std::string_view filterString, const std::vector<T>& items, std::vector<size_t>& indices)
234{
235 filterIndices(filterString, [&](size_t idx) { return items[idx].displayName; }, indices);
236}
237
238// Similar to c++23 chunk_by(). Main difference is internal vs external iteration.
239template<typename Range, typename BinaryPred, typename Action>
240static void chunk_by(Range&& range, BinaryPred pred, Action action)
241{
242 auto it = std::begin(range);
243 auto last = std::end(range);
244 while (it != last) {
245 auto start = it;
246 auto prev = it++;
247 while (it != last && pred(*prev, *it)) {
248 prev = it++;
249 }
250 action(start, it);
251 }
252}
253
254std::string getShortCutForCommand(const HotKey& hotkey, std::string_view command);
255
256std::string getKeyChordName(ImGuiKeyChord keyChord);
257std::optional<ImGuiKeyChord> parseKeyChord(std::string_view name);
258
259// Read from VRAM-table, including mirroring behavior
260// shared between ImGuiCharacter, ImGuiSpriteViewer
262public:
263 VramTable(std::span<const uint8_t> vram_, bool planar_ = false)
264 : vram(vram_), planar(planar_) {}
265
266 void setRegister(unsigned value, unsigned extraLsbBits) {
267 registerMask = (value << extraLsbBits) | ~(~0u << extraLsbBits);
268 }
269 void setIndexSize(unsigned bits) {
270 indexMask = ~0u << bits;
271 }
272
273 [[nodiscard]] uint8_t operator[](unsigned index) const {
274 auto addr = registerMask & (indexMask | index);
275 if (planar) {
276 addr = ((addr << 16) | (addr >> 1)) & 0x1'FFFF;
277 }
278 return vram[addr];
279 }
280private:
281 std::span<const uint8_t> vram;
282 unsigned registerMask = 0;
283 unsigned indexMask = 0;
284 bool planar = false;
285};
286
287enum class imColor : unsigned {
289 BLACK,
290 WHITE,
291 GRAY,
292 YELLOW,
293 RED_BG, // red background (transparent)
294 YELLOW_BG, // yellow background (transparent)
295
296 TEXT,
298
299 ERROR,
300 WARNING,
301
302 COMMENT, // syntax highlighting in the console
303 VARIABLE,
304 LITERAL,
305 PROC,
306 OPERATOR,
307
308 KEY_ACTIVE, // virtual keyboard
310
312};
313inline std::array<ImU32, size_t(imColor::NUM_COLORS)> imColors;
314
315void setColors(int style);
316
317inline ImU32 getColor(imColor col) {
318 assert(col < imColor::NUM_COLORS);
319 return imColors[size_t(col)];
320}
321
322} // namespace openmsx
323
324#endif
BaseSetting * setting
void setRegister(unsigned value, unsigned extraLsbBits)
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
void StrCat(Ts &&...ts)
Definition ImGuiUtils.hh:43
auto CalcTextSize(std::string_view str)
Definition ImGuiUtils.hh:37
void TextUnformatted(const std::string &str)
Definition ImGuiUtils.hh:24
void RightAlignText(std::string_view text, std::string_view maxWidthText)
Definition ImGuiUtils.hh:49
bool containsCaseInsensitive(std::string_view haystack, std::string_view needle)
Definition StringOp.hh:181
void Combo(const char *label, const char *preview_value, ImGuiComboFlags flags, std::invocable<> auto next)
Definition ImGuiCpp.hh:289
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
bool SliderFloat(FloatSetting &setting, const char *format, ImGuiSliderFlags flags)
std::span< const EnumToolTip > EnumToolTips
Definition ImGuiUtils.hh:75
void centerNextWindowOverCurrent()
bool SliderInt(IntegerSetting &setting, ImGuiSliderFlags flags)
Definition ImGuiUtils.cc:83
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:77
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)
bool InputText(Setting &setting)
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)
std::string formatTime(std::optional< double > time)
float calculateFade(float current, float target, float period)
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:72
std::string_view tip
Definition ImGuiUtils.hh:73
std::string operator()(const Setting &setting) const
Definition ImGuiUtils.cc:30
constexpr auto begin(const zstring_view &x)
constexpr auto end(const zstring_view &x)