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