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
49} // namespace ImGui
50
51namespace openmsx {
52
53class BooleanSetting;
54class FloatSetting;
55class HotKey;
56class IntegerSetting;
57class Setting;
58class VideoSourceSetting;
59
61 std::string_view value;
62 std::string_view tip;
63};
64using EnumToolTips = std::span<const EnumToolTip>;
65
66inline void simpleToolTip(std::string_view desc)
67{
68 if (desc.empty()) return;
70 im::TextWrapPos(ImGui::GetFontSize() * 35.0f, [&]{
72 });
73 });
74}
75
76void simpleToolTip(std::invocable<> auto descFunc)
77{
78 if (!ImGui::IsItemHovered(ImGuiHoveredFlags_ForTooltip)) return;
79 auto desc = std::invoke(descFunc);
80 if (desc.empty()) return;
81 im::Tooltip([&]{
82 im::TextWrapPos(ImGui::GetFontSize() * 35.0f, [&]{
84 });
85 });
86}
87
88void HelpMarker(std::string_view desc);
89
91{
92 static constexpr gl::vec2 center{0.5f, 0.5f};
93 gl::vec2 windowPos = ImGui::GetWindowPos();
94 gl::vec2 windowSize = ImGui::GetWindowSize();
95 auto windowCenter = windowPos + center * windowSize;
96 ImGui::SetNextWindowPos(windowCenter, ImGuiCond_Appearing, center);
97}
98
99void drawURL(std::string_view text, zstring_view url);
100
102 std::string operator()(const Setting& setting) const;
103};
104
105bool Checkbox(const HotKey& hotkey, BooleanSetting& setting);
106bool Checkbox(const HotKey& hotkey, const char* label, BooleanSetting& setting, function_ref<std::string(const Setting&)> getTooltip = GetSettingDescription{});
107bool SliderInt(IntegerSetting& setting, ImGuiSliderFlags flags = 0);
108bool SliderInt(const char* label, IntegerSetting& setting, ImGuiSliderFlags flags = 0);
109bool SliderFloat(FloatSetting& setting, const char* format = "%.3f", ImGuiSliderFlags flags = 0);
110bool SliderFloat(const char* label, FloatSetting& setting, const char* format = "%.3f", ImGuiSliderFlags flags = 0);
111bool InputText(Setting& setting);
112bool InputText(const char* label, Setting& setting);
113void ComboBox(Setting& setting, EnumToolTips toolTips = {}); // must be an EnumSetting
114void ComboBox(const char* label, Setting& setting, EnumToolTips toolTips = {}); // must be an EnumSetting
115void ComboBox(const char* label, Setting& setting, function_ref<std::string(const std::string&)> displayValue, EnumToolTips toolTips = {});
116void ComboBox(VideoSourceSetting& setting);
117void ComboBox(const char* label, VideoSourceSetting& setting);
118
119const char* getComboString(int item, const char* itemsSeparatedByZeros);
120
121std::string formatTime(double time);
122float calculateFade(float current, float target, float period);
123
124template<int HexDigits>
125void comboHexSequence(const char* label, int* value, int mult, int offset = 0) {
126 assert(offset < mult);
127 *value &= ~(mult - 1);
128 // only apply offset in display, not in the actual value
129 auto preview = tmpStrCat("0x", hex_string<HexDigits>(*value | offset));
130 im::Combo(label, preview.c_str(), [&]{
131 for (int addr = 0; addr < 0x1ffff; addr += mult) {
132 if (auto str = tmpStrCat("0x", hex_string<HexDigits>(addr | offset));
133 ImGui::Selectable(str.c_str(), *value == addr)) {
134 *value = addr;
135 }
136 if (*value == addr) {
137 ImGui::SetItemDefaultFocus();
138 }
139 }
140 });
141};
142
143template<typename Range, typename Projection>
144void sortUpDown_T(Range& range, const ImGuiTableSortSpecs* sortSpecs, Projection proj) {
145 if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Descending) {
146 ranges::stable_sort(range, std::greater<>{}, proj);
147 } else {
148 ranges::stable_sort(range, std::less<>{}, proj);
149 }
150};
151template<typename Range, typename Projection>
152void sortUpDown_String(Range& range, const ImGuiTableSortSpecs* sortSpecs, Projection proj) {
153 if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Descending) {
155 } else {
157 }
158};
159
160
161[[nodiscard]] inline const std::string* getOptionalDictValue(
162 const std::vector<std::pair<std::string, std::string>>& info,
163 std::string_view key)
164{
165 auto it = ranges::find_if(info, [&](const auto& p) { return p.first == key; });
166 if (it == info.end()) return {};
167 return &it->second;
168}
169
170template<typename T> // 'MachineInfo' or 'ExtensionInfo', both have a 'configInfo' member
171[[nodiscard]] std::vector<std::string> getAllValuesFor(std::string_view key, const std::vector<T>& items)
172{
173 std::vector<std::string> result;
174 for (const auto& item : items) {
175 if (const auto* value = getOptionalDictValue(item.configInfo, key)) {
176 if (!contains(result, *value)) { // O(N^2), but that's fine
177 result.emplace_back(*value);
178 }
179 }
180 }
182 return result;
183}
184
185template<typename T>
186void displayFilterCombo(std::string& selection, zstring_view key, const std::vector<T>& items)
187{
188 im::Combo(key.c_str(), selection.empty() ? "--all--" : selection.c_str(), [&]{
189 if (ImGui::Selectable("--all--")) {
190 selection.clear();
191 }
192 for (const auto& type : getAllValuesFor(key, items)) {
193 if (ImGui::Selectable(type.c_str())) {
194 selection = type;
195 }
196 }
197 });
198}
199
200template<typename T>
201void applyComboFilter(std::string_view key, const std::string& value, const std::vector<T>& items, std::vector<size_t>& indices)
202{
203 if (value.empty()) return;
204 std::erase_if(indices, [&](auto idx) {
205 const auto& info = items[idx].configInfo;
206 const auto* val = getOptionalDictValue(info, key);
207 if (!val) return true; // remove items that don't have the key
208 return *val != value;
209 });
210}
211
212template<std::invocable<size_t> GetName>
213void filterIndices(std::string_view filterString, GetName getName, std::vector<size_t>& indices)
214{
215 if (filterString.empty()) return;
216 std::erase_if(indices, [&](auto idx) {
217 const auto& name = getName(idx);
218 return !ranges::all_of(StringOp::split_view<StringOp::REMOVE_EMPTY_PARTS>(filterString, ' '),
219 [&](auto part) { return StringOp::containsCaseInsensitive(name, part); });
220 });
221}
222
223template<typename T>
224void applyDisplayNameFilter(std::string_view filterString, const std::vector<T>& items, std::vector<size_t>& indices)
225{
226 filterIndices(filterString, [&](size_t idx) { return items[idx].displayName; }, indices);
227}
228
229// Similar to c++23 chunk_by(). Main difference is internal vs external iteration.
230template<typename Range, typename BinaryPred, typename Action>
231static void chunk_by(Range&& range, BinaryPred pred, Action action)
232{
233 auto it = std::begin(range);
234 auto last = std::end(range);
235 while (it != last) {
236 auto start = it;
237 auto prev = it++;
238 while (it != last && pred(*prev, *it)) {
239 prev = it++;
240 }
241 action(start, it);
242 }
243}
244
245std::string getShortCutForCommand(const HotKey& hotkey, std::string_view command);
246
247std::string getKeyChordName(ImGuiKeyChord keyChord);
248std::optional<ImGuiKeyChord> parseKeyChord(std::string_view name);
249
250enum class imColor : unsigned {
252 BLACK,
253 WHITE,
254 GRAY,
255 YELLOW,
256 RED_BG, // red background (transparent)
257 YELLOW_BG, // yellow background (transparent)
258
259 TEXT,
261
262 ERROR,
263 WARNING,
264
265 COMMENT, // syntax highlighting in the console
266 VARIABLE,
267 LITERAL,
268 PROC,
269 OPERATOR,
270
271 KEY_ACTIVE, // virtual keyboard
273
275};
276inline std::array<ImU32, size_t(imColor::NUM_COLORS)> imColors;
277
278void setColors(int style);
279
280inline ImU32 getColor(imColor col) {
281 assert(col < imColor::NUM_COLORS);
282 return imColors[size_t(col)];
283}
284
285} // namespace openmsx
286
287#endif
BaseSetting * setting
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
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:313
void TextWrapPos(float wrap_local_pos_x, std::invocable<> auto next)
Definition ImGuiCpp.hh:232
void Tooltip(std::invocable<> auto next)
Definition ImGuiCpp.hh:398
void ItemTooltip(std::invocable<> auto next)
Definition ImGuiCpp.hh:406
This file implemented 3 utility functions:
Definition Autofire.cc:11
bool Checkbox(const HotKey &hotKey, BooleanSetting &setting)
Definition ImGuiUtils.cc:81
bool SliderFloat(FloatSetting &setting, const char *format, ImGuiSliderFlags flags)
std::string formatTime(double time)
std::span< const EnumToolTip > EnumToolTips
Definition ImGuiUtils.hh:64
void centerNextWindowOverCurrent()
Definition ImGuiUtils.hh:90
bool SliderInt(IntegerSetting &setting, ImGuiSliderFlags flags)
void drawURL(std::string_view text, zstring_view url)
Definition ImGuiUtils.cc:30
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 sortUpDown_String(Range &range, const ImGuiTableSortSpecs *sortSpecs, Projection proj)
void simpleToolTip(std::string_view desc)
Definition ImGuiUtils.hh:66
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)
void comboHexSequence(const char *label, int *value, int mult, int offset=0)
std::string getKeyChordName(ImGuiKeyChord keyChord)
void applyComboFilter(std::string_view key, const std::string &value, const std::vector< T > &items, std::vector< size_t > &indices)
void applyDisplayNameFilter(std::string_view filterString, const std::vector< T > &items, std::vector< size_t > &indices)
float calculateFade(float current, float target, float period)
bool all_of(InputRange &&range, UnaryPredicate pred)
Definition ranges.hh:186
auto find_if(InputRange &&range, UnaryPredicate pred)
Definition ranges.hh:173
void stable_sort(RandomAccessRange &&range)
Definition ranges.hh:76
constexpr void sort(RandomAccessRange &&range)
Definition ranges.hh:49
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:61
std::string_view tip
Definition ImGuiUtils.hh:62
std::string operator()(const Setting &setting) const
Definition ImGuiUtils.cc:53
constexpr auto begin(const zstring_view &x)
constexpr auto end(const zstring_view &x)