xref: /aosp_15_r20/external/skia/tools/viewer/ImGuiLayer.cpp (revision c8dee2aa9b3f27cf6c858bd81872bdeb2c07ed17)
1 /*
2 * Copyright 2017 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7 
8 #include "tools/viewer/ImGuiLayer.h"
9 
10 #include "include/core/SkBlendMode.h"
11 #include "include/core/SkCanvas.h"
12 #include "include/core/SkColor.h"
13 #include "include/core/SkImage.h"
14 #include "include/core/SkImageInfo.h"
15 #include "include/core/SkPixmap.h"
16 #include "include/core/SkRect.h"
17 #include "include/core/SkRefCnt.h"
18 #include "include/core/SkSamplingOptions.h"
19 #include "include/core/SkShader.h"
20 #include "include/core/SkSurface.h"
21 #include "include/core/SkSwizzle.h"
22 #include "include/core/SkVertices.h"
23 #include "include/private/base/SkTDArray.h"
24 #include "src/base/SkTime.h"
25 #include "tools/skui/InputState.h"
26 #include "tools/skui/Key.h"
27 
28 #include <cstdint>
29 
30 using namespace sk_app;
31 
build_ImFontAtlas(ImFontAtlas & atlas,SkPaint & fontPaint)32 static void build_ImFontAtlas(ImFontAtlas& atlas, SkPaint& fontPaint) {
33     int w, h;
34     unsigned char* pixels;
35     atlas.GetTexDataAsAlpha8(&pixels, &w, &h);
36     SkImageInfo info = SkImageInfo::MakeA8(w, h);
37     SkPixmap pmap(info, pixels, info.minRowBytes());
38     SkMatrix localMatrix = SkMatrix::Scale(1.0f / w, 1.0f / h);
39     auto fontImage = SkImages::RasterFromPixmap(pmap, nullptr, nullptr);
40     auto fontShader = fontImage->makeShader(SkSamplingOptions(SkFilterMode::kLinear), localMatrix);
41     fontPaint.setShader(fontShader);
42     fontPaint.setColor(SK_ColorWHITE);
43     atlas.TexID = &fontPaint;
44 }
45 
ImGuiLayer()46 ImGuiLayer::ImGuiLayer() {
47     // ImGui initialization:
48     ImGui::CreateContext();
49     ImGuiIO& io = ImGui::GetIO();
50 
51     // Keymap...
52     io.KeyMap[ImGuiKey_Tab]        = (int)skui::Key::kTab;
53     io.KeyMap[ImGuiKey_LeftArrow]  = (int)skui::Key::kLeft;
54     io.KeyMap[ImGuiKey_RightArrow] = (int)skui::Key::kRight;
55     io.KeyMap[ImGuiKey_UpArrow]    = (int)skui::Key::kUp;
56     io.KeyMap[ImGuiKey_DownArrow]  = (int)skui::Key::kDown;
57     io.KeyMap[ImGuiKey_PageUp]     = (int)skui::Key::kPageUp;
58     io.KeyMap[ImGuiKey_PageDown]   = (int)skui::Key::kPageDown;
59     io.KeyMap[ImGuiKey_Home]       = (int)skui::Key::kHome;
60     io.KeyMap[ImGuiKey_End]        = (int)skui::Key::kEnd;
61     io.KeyMap[ImGuiKey_Delete]     = (int)skui::Key::kDelete;
62     io.KeyMap[ImGuiKey_Backspace]  = (int)skui::Key::kBack;
63     io.KeyMap[ImGuiKey_Enter]      = (int)skui::Key::kOK;
64     io.KeyMap[ImGuiKey_Escape]     = (int)skui::Key::kEscape;
65     io.KeyMap[ImGuiKey_A]          = (int)skui::Key::kA;
66     io.KeyMap[ImGuiKey_C]          = (int)skui::Key::kC;
67     io.KeyMap[ImGuiKey_V]          = (int)skui::Key::kV;
68     io.KeyMap[ImGuiKey_X]          = (int)skui::Key::kX;
69     io.KeyMap[ImGuiKey_Y]          = (int)skui::Key::kY;
70     io.KeyMap[ImGuiKey_Z]          = (int)skui::Key::kZ;
71 
72     build_ImFontAtlas(*io.Fonts, fFontPaint);
73 }
74 
~ImGuiLayer()75 ImGuiLayer::~ImGuiLayer() {
76     ImGui::DestroyContext();
77 }
78 
setScaleFactor(float scaleFactor)79 void ImGuiLayer::setScaleFactor(float scaleFactor) {
80     ImGui::GetStyle() = ImGuiStyle{};
81     ImGui::GetStyle().ScaleAllSizes(scaleFactor);
82 
83     ImFontAtlas& atlas = *ImGui::GetIO().Fonts;
84     atlas.Clear();
85     ImFontConfig cfg;
86     cfg.SizePixels = 13 * scaleFactor;
87     atlas.AddFontDefault(&cfg);
88     build_ImFontAtlas(atlas, fFontPaint);
89 }
90 
91 #if defined(SK_BUILD_FOR_UNIX)
get_clipboard_text(void * user_data)92 static const char* get_clipboard_text(void* user_data) {
93     Window* w = (Window*)user_data;
94     return w->getClipboardText();
95 }
96 
set_clipboard_text(void * user_data,const char * text)97 static void set_clipboard_text(void* user_data, const char* text) {
98     Window* w = (Window*)user_data;
99     w->setClipboardText(text);
100 }
101 #endif
102 
onAttach(Window * window)103 void ImGuiLayer::onAttach(Window* window) {
104     fWindow = window;
105 
106 #if defined(SK_BUILD_FOR_UNIX)
107     ImGuiIO& io = ImGui::GetIO();
108     io.ClipboardUserData = fWindow;
109     io.GetClipboardTextFn = get_clipboard_text;
110     io.SetClipboardTextFn = set_clipboard_text;
111 #endif
112 }
113 
onMouse(int x,int y,skui::InputState state,skui::ModifierKey modifiers)114 bool ImGuiLayer::onMouse(int x, int y, skui::InputState state, skui::ModifierKey modifiers) {
115     ImGuiIO& io = ImGui::GetIO();
116     io.MousePos.x = static_cast<float>(x);
117     io.MousePos.y = static_cast<float>(y);
118     if (skui::InputState::kDown == state) {
119         io.MouseDown[0] = true;
120     } else if (skui::InputState::kUp == state) {
121         io.MouseDown[0] = false;
122     }
123     return io.WantCaptureMouse;
124 }
125 
onMouseWheel(float delta,int,int,skui::ModifierKey modifiers)126 bool ImGuiLayer::onMouseWheel(float delta, int, int, skui::ModifierKey modifiers) {
127     ImGuiIO& io = ImGui::GetIO();
128     io.MouseWheel += delta;
129     return io.WantCaptureMouse;
130 }
131 
skiaWidget(const ImVec2 & size,SkiaWidgetFunc func)132 void ImGuiLayer::skiaWidget(const ImVec2& size, SkiaWidgetFunc func) {
133     intptr_t funcIndex = fSkiaWidgetFuncs.size();
134     fSkiaWidgetFuncs.push_back(func);
135     ImGui::Image((ImTextureID)funcIndex, size);
136 }
137 
onPrePaint()138 void ImGuiLayer::onPrePaint() {
139     // Update ImGui input
140     ImGuiIO& io = ImGui::GetIO();
141 
142     static double previousTime = 0.0;
143     double currentTime = SkTime::GetSecs();
144     io.DeltaTime = static_cast<float>(currentTime - previousTime);
145     previousTime = currentTime;
146 
147     io.DisplaySize.x = static_cast<float>(fWindow->width());
148     io.DisplaySize.y = static_cast<float>(fWindow->height());
149 
150     io.KeyAlt   = io.KeysDown[static_cast<int>(skui::Key::kOption)];
151     io.KeyCtrl  = io.KeysDown[static_cast<int>(skui::Key::kCtrl)];
152     io.KeyShift = io.KeysDown[static_cast<int>(skui::Key::kShift)];
153     io.KeySuper = io.KeysDown[static_cast<int>(skui::Key::kSuper)];
154 
155     ImGui::NewFrame();
156 }
157 
onPaint(SkSurface * surface)158 void ImGuiLayer::onPaint(SkSurface* surface) {
159     // This causes ImGui to rebuild vertex/index data based on all immediate-mode commands
160     // (widgets, etc...) that have been issued
161     ImGui::Render();
162 
163     // Then we fetch the most recent data, and convert it so we can render with Skia
164     const ImDrawData* drawData = ImGui::GetDrawData();
165     SkTDArray<SkPoint> pos;
166     SkTDArray<SkPoint> uv;
167     SkTDArray<SkColor> color;
168 
169     auto canvas = surface->getCanvas();
170 
171     for (int i = 0; i < drawData->CmdListsCount; ++i) {
172         const ImDrawList* drawList = drawData->CmdLists[i];
173 
174         // De-interleave all vertex data (sigh), convert to Skia types
175         pos.clear(); uv.clear(); color.clear();
176         for (int j = 0; j < drawList->VtxBuffer.size(); ++j) {
177             const ImDrawVert& vert = drawList->VtxBuffer[j];
178             pos.push_back(SkPoint::Make(vert.pos.x, vert.pos.y));
179             uv.push_back(SkPoint::Make(vert.uv.x, vert.uv.y));
180             color.push_back(vert.col);
181         }
182         // ImGui colors are RGBA
183         SkSwapRB(color.begin(), color.begin(), color.size());
184 
185         int indexOffset = 0;
186 
187         // Draw everything with canvas.drawVertices...
188         for (int j = 0; j < drawList->CmdBuffer.size(); ++j) {
189             const ImDrawCmd* drawCmd = &drawList->CmdBuffer[j];
190 
191             SkAutoCanvasRestore acr(canvas, true);
192 
193             // TODO: Find min/max index for each draw, so we know how many vertices (sigh)
194             if (drawCmd->UserCallback) {
195                 drawCmd->UserCallback(drawList, drawCmd);
196             } else {
197                 intptr_t idIndex = (intptr_t)drawCmd->TextureId;
198                 if (idIndex < fSkiaWidgetFuncs.size()) {
199                     // Small image IDs are actually indices into a list of callbacks. We directly
200                     // examing the vertex data to deduce the image rectangle, then reconfigure the
201                     // canvas to be clipped and translated so that the callback code gets to use
202                     // Skia to render a widget in the middle of an ImGui panel.
203                     ImDrawIdx rectIndex = drawList->IdxBuffer[indexOffset];
204                     SkPoint tl = pos[rectIndex], br = pos[rectIndex + 2];
205                     canvas->clipRect(SkRect::MakeLTRB(tl.fX, tl.fY, br.fX, br.fY));
206                     canvas->translate(tl.fX, tl.fY);
207                     fSkiaWidgetFuncs[idIndex](canvas);
208                 } else {
209                     SkPaint* paint = static_cast<SkPaint*>(drawCmd->TextureId);
210                     SkASSERT(paint);
211 
212                     canvas->clipRect(SkRect::MakeLTRB(drawCmd->ClipRect.x, drawCmd->ClipRect.y,
213                                                       drawCmd->ClipRect.z, drawCmd->ClipRect.w));
214                     auto vertices = SkVertices::MakeCopy(SkVertices::kTriangles_VertexMode,
215                                                          drawList->VtxBuffer.size(),
216                                                          pos.begin(), uv.begin(), color.begin(),
217                                                          drawCmd->ElemCount,
218                                                          drawList->IdxBuffer.begin() + indexOffset);
219                     canvas->drawVertices(vertices, SkBlendMode::kModulate, *paint);
220                 }
221                 indexOffset += drawCmd->ElemCount;
222             }
223         }
224     }
225 
226     fSkiaWidgetFuncs.clear();
227 }
228 
onKey(skui::Key key,skui::InputState state,skui::ModifierKey modifiers)229 bool ImGuiLayer::onKey(skui::Key key, skui::InputState state, skui::ModifierKey modifiers) {
230     ImGuiIO& io = ImGui::GetIO();
231     io.KeysDown[static_cast<int>(key)] = (skui::InputState::kDown == state);
232     return io.WantCaptureKeyboard;
233 }
234 
onChar(SkUnichar c,skui::ModifierKey modifiers)235 bool ImGuiLayer::onChar(SkUnichar c, skui::ModifierKey modifiers) {
236     ImGuiIO& io = ImGui::GetIO();
237     if (io.WantTextInput) {
238         if (c > 0 && c < 0x10000) {
239             io.AddInputCharacter(c);
240         }
241         return true;
242     }
243     return false;
244 }
245