yaze 0.3.2
Link to the Past ROM Editor
 
Loading...
Searching...
No Matches
font_picker.cc
Go to the documentation of this file.
2
3#include <array>
4#include <cstdio>
5#include <string_view>
6
7#include "imgui/imgui.h"
8#include "imgui/imgui_internal.h"
9
10namespace yaze {
11namespace gui {
12namespace font_picker_internal {
13
14const char* FontNameAt(int index) {
15 static thread_local std::array<char, 64> fallback_name;
16 ImGuiIO& io = ImGui::GetIO();
17 if (io.Fonts == nullptr || index < 0 || index >= io.Fonts->Fonts.Size) {
18 std::snprintf(fallback_name.data(), fallback_name.size(), "Font #%d",
19 index);
20 return fallback_name.data();
21 }
22 const ImFont* font = io.Fonts->Fonts[index];
23 if (font == nullptr) {
24 std::snprintf(fallback_name.data(), fallback_name.size(), "Font #%d",
25 index);
26 return fallback_name.data();
27 }
28 const char* name = font->GetDebugName();
29 if (name != nullptr && name[0] != '\0' &&
30 // GetDebugName() returns "<unknown>" when no ImFontConfig::Name was set.
31 std::string_view(name) != "<unknown>") {
32 return name;
33 }
34 std::snprintf(fallback_name.data(), fallback_name.size(), "Font #%d", index);
35 return fallback_name.data();
36}
37
39 ImGuiContext* ctx = ImGui::GetCurrentContext();
40 if (ctx == nullptr)
41 return 0;
42 ImGuiIO& io = ImGui::GetIO();
43 if (io.Fonts == nullptr)
44 return 0;
45 return io.Fonts->Fonts.Size;
46}
47
48} // namespace font_picker_internal
49
50bool FontPicker(const char* label, int* index) {
51 if (index == nullptr)
52 return false;
53
55 if (count <= 0) {
56 ImGui::BeginDisabled();
57 int dummy = 0;
58 ImGui::Combo(label, &dummy, "(no fonts loaded)\0\0");
59 ImGui::EndDisabled();
60 return false;
61 }
62
63 const int current = (*index < 0 || *index >= count) ? 0 : *index;
64 const char* preview_name = font_picker_internal::FontNameAt(current);
65
66 bool changed = false;
67 if (ImGui::BeginCombo(label, preview_name)) {
68 ImGuiIO& io = ImGui::GetIO();
69 for (int i = 0; i < count; ++i) {
70 const bool is_selected = (i == current);
71 const char* name = font_picker_internal::FontNameAt(i);
72
73 ImFont* font = io.Fonts->Fonts[i];
74 if (font != nullptr) {
75 ImGui::PushFont(font);
76 }
77 const bool picked = ImGui::Selectable(name, is_selected);
78 if (font != nullptr) {
79 ImGui::PopFont();
80 }
81 if (picked && i != current) {
82 *index = i;
83 changed = true;
84 }
85 if (is_selected) {
86 ImGui::SetItemDefaultFocus();
87 }
88 }
89 ImGui::EndCombo();
90 }
91 return changed;
92}
93
94} // namespace gui
95} // namespace yaze
const char * FontNameAt(int index)
bool FontPicker(const char *label, int *index)