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