1 /*
2 * Copyright 2016 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 "include/core/SkCanvas.h"
9 #include "include/core/SkData.h"
10 #include "include/core/SkGraphics.h"
11 #include "include/core/SkPictureRecorder.h"
12 #include "include/core/SkStream.h"
13 #include "include/core/SkSurface.h"
14 #include "include/gpu/GrDirectContext.h"
15 #include "include/private/SkTPin.h"
16 #include "include/private/SkTo.h"
17 #include "include/utils/SkPaintFilterCanvas.h"
18 #include "src/core/SkColorSpacePriv.h"
19 #include "src/core/SkImagePriv.h"
20 #include "src/core/SkMD5.h"
21 #include "src/core/SkOSFile.h"
22 #include "src/core/SkScan.h"
23 #include "src/core/SkTSort.h"
24 #include "src/core/SkTaskGroup.h"
25 #include "src/core/SkTextBlobPriv.h"
26 #include "src/gpu/GrDirectContextPriv.h"
27 #include "src/gpu/GrGpu.h"
28 #include "src/gpu/GrPersistentCacheUtils.h"
29 #include "src/gpu/GrShaderUtils.h"
30 #include "src/gpu/ccpr/GrCoverageCountingPathRenderer.h"
31 #include "src/image/SkImage_Base.h"
32 #include "src/utils/SkJSONWriter.h"
33 #include "src/utils/SkOSPath.h"
34 #include "tools/Resources.h"
35 #include "tools/ToolUtils.h"
36 #include "tools/flags/CommandLineFlags.h"
37 #include "tools/flags/CommonFlags.h"
38 #include "tools/trace/EventTracingPriv.h"
39 #include "tools/viewer/BisectSlide.h"
40 #include "tools/viewer/GMSlide.h"
41 #include "tools/viewer/ImageSlide.h"
42 #include "tools/viewer/ParticlesSlide.h"
43 #include "tools/viewer/SKPSlide.h"
44 #include "tools/viewer/SampleSlide.h"
45 #include "tools/viewer/SkSLSlide.h"
46 #include "tools/viewer/SlideDir.h"
47 #include "tools/viewer/SvgSlide.h"
48 #include "tools/viewer/Viewer.h"
49 
50 #include <cstdlib>
51 #include <map>
52 
53 #include "imgui.h"
54 #include "misc/cpp/imgui_stdlib.h"  // For ImGui support of std::string
55 
56 #ifdef SK_VULKAN
57 #include "spirv-tools/libspirv.hpp"
58 #endif
59 
60 #if defined(SK_ENABLE_SKOTTIE)
61     #include "tools/viewer/SkottieSlide.h"
62 #endif
63 #if defined(SK_ENABLE_SKRIVE)
64     #include "tools/viewer/SkRiveSlide.h"
65 #endif
66 
67 class CapturingShaderErrorHandler : public GrContextOptions::ShaderErrorHandler {
68 public:
compileError(const char * shader,const char * errors)69     void compileError(const char* shader, const char* errors) override {
70         fShaders.push_back(SkString(shader));
71         fErrors.push_back(SkString(errors));
72     }
73 
reset()74     void reset() {
75         fShaders.reset();
76         fErrors.reset();
77     }
78 
79     SkTArray<SkString> fShaders;
80     SkTArray<SkString> fErrors;
81 };
82 
83 static CapturingShaderErrorHandler gShaderErrorHandler;
84 
ShaderErrorHandler()85 GrContextOptions::ShaderErrorHandler* Viewer::ShaderErrorHandler() { return &gShaderErrorHandler; }
86 
87 using namespace sk_app;
88 
89 static std::map<GpuPathRenderers, std::string> gPathRendererNames;
90 
Create(int argc,char ** argv,void * platformData)91 Application* Application::Create(int argc, char** argv, void* platformData) {
92     return new Viewer(argc, argv, platformData);
93 }
94 
95 static DEFINE_string(slide, "", "Start on this sample.");
96 static DEFINE_bool(list, false, "List samples?");
97 
98 #ifdef SK_GL
99 #define GL_BACKEND_STR ", \"gl\""
100 #else
101 #define GL_BACKEND_STR
102 #endif
103 #ifdef SK_VULKAN
104 #define VK_BACKEND_STR ", \"vk\""
105 #else
106 #define VK_BACKEND_STR
107 #endif
108 #ifdef SK_METAL
109 #define MTL_BACKEND_STR ", \"mtl\""
110 #else
111 #define MTL_BACKEND_STR
112 #endif
113 #ifdef SK_DIRECT3D
114 #define D3D_BACKEND_STR ", \"d3d\""
115 #else
116 #define D3D_BACKEND_STR
117 #endif
118 #ifdef SK_DAWN
119 #define DAWN_BACKEND_STR ", \"dawn\""
120 #else
121 #define DAWN_BACKEND_STR
122 #endif
123 #define BACKENDS_STR_EVALUATOR(sw, gl, vk, mtl, d3d, dawn) sw gl vk mtl d3d dawn
124 #define BACKENDS_STR BACKENDS_STR_EVALUATOR( \
125     "\"sw\"", GL_BACKEND_STR, VK_BACKEND_STR, MTL_BACKEND_STR, D3D_BACKEND_STR, DAWN_BACKEND_STR)
126 
127 static DEFINE_string2(backend, b, "sw", "Backend to use. Allowed values are " BACKENDS_STR ".");
128 
129 static DEFINE_int(msaa, 1, "Number of subpixel samples. 0 for no HW antialiasing.");
130 
131 static DEFINE_string(bisect, "", "Path to a .skp or .svg file to bisect.");
132 
133 static DEFINE_string2(file, f, "", "Open a single file for viewing.");
134 
135 static DEFINE_string2(match, m, nullptr,
136                "[~][^]substring[$] [...] of name to run.\n"
137                "Multiple matches may be separated by spaces.\n"
138                "~ causes a matching name to always be skipped\n"
139                "^ requires the start of the name to match\n"
140                "$ requires the end of the name to match\n"
141                "^ and $ requires an exact match\n"
142                "If a name does not match any list entry,\n"
143                "it is skipped unless some list entry starts with ~");
144 
145 #if defined(SK_BUILD_FOR_ANDROID)
146     static DEFINE_string(jpgs, "/data/local/tmp/resources", "Directory to read jpgs from.");
147     static DEFINE_string(skps, "/data/local/tmp/skps", "Directory to read skps from.");
148     static DEFINE_string(lotties, "/data/local/tmp/lotties",
149                          "Directory to read (Bodymovin) jsons from.");
150     static DEFINE_string(rives, "/data/local/tmp/rives",
151                          "Directory to read Rive (Flare) files from.");
152 #else
153     static DEFINE_string(jpgs, "jpgs", "Directory to read jpgs from.");
154     static DEFINE_string(skps, "skps", "Directory to read skps from.");
155     static DEFINE_string(lotties, "lotties", "Directory to read (Bodymovin) jsons from.");
156     static DEFINE_string(rives, "rives", "Directory to read Rive (Flare) files from.");
157 #endif
158 
159 static DEFINE_string(svgs, "", "Directory to read SVGs from, or a single SVG file.");
160 
161 static DEFINE_int_2(threads, j, -1,
162                "Run threadsafe tests on a threadpool with this many extra threads, "
163                "defaulting to one extra thread per core.");
164 
165 static DEFINE_bool(redraw, false, "Toggle continuous redraw.");
166 
167 static DEFINE_bool(offscreen, false, "Force rendering to an offscreen surface.");
168 static DEFINE_bool(skvm, false, "Force skvm blitters for raster.");
169 static DEFINE_bool(jit, true, "JIT SkVM?");
170 static DEFINE_bool(dylib, false, "JIT via dylib (much slower compile but easier to debug/profile)");
171 static DEFINE_bool(stats, false, "Display stats overlay on startup.");
172 
173 #ifndef SK_GL
174 static_assert(false, "viewer requires GL backend for raster.")
175 #endif
176 
177 const char* kBackendTypeStrings[sk_app::Window::kBackendTypeCount] = {
178     "OpenGL",
179 #if SK_ANGLE && defined(SK_BUILD_FOR_WIN)
180     "ANGLE",
181 #endif
182 #ifdef SK_DAWN
183     "Dawn",
184 #endif
185 #ifdef SK_VULKAN
186     "Vulkan",
187 #endif
188 #ifdef SK_METAL
189     "Metal",
190 #endif
191 #ifdef SK_DIRECT3D
192     "Direct3D",
193 #endif
194     "Raster"
195 };
196 
get_backend_type(const char * str)197 static sk_app::Window::BackendType get_backend_type(const char* str) {
198 #ifdef SK_DAWN
199     if (0 == strcmp(str, "dawn")) {
200         return sk_app::Window::kDawn_BackendType;
201     } else
202 #endif
203 #ifdef SK_VULKAN
204     if (0 == strcmp(str, "vk")) {
205         return sk_app::Window::kVulkan_BackendType;
206     } else
207 #endif
208 #if SK_ANGLE && defined(SK_BUILD_FOR_WIN)
209     if (0 == strcmp(str, "angle")) {
210         return sk_app::Window::kANGLE_BackendType;
211     } else
212 #endif
213 #ifdef SK_METAL
214     if (0 == strcmp(str, "mtl")) {
215         return sk_app::Window::kMetal_BackendType;
216     } else
217 #endif
218 #ifdef SK_DIRECT3D
219     if (0 == strcmp(str, "d3d")) {
220         return sk_app::Window::kDirect3D_BackendType;
221     } else
222 #endif
223 
224     if (0 == strcmp(str, "gl")) {
225         return sk_app::Window::kNativeGL_BackendType;
226     } else if (0 == strcmp(str, "sw")) {
227         return sk_app::Window::kRaster_BackendType;
228     } else {
229         SkDebugf("Unknown backend type, %s, defaulting to sw.", str);
230         return sk_app::Window::kRaster_BackendType;
231     }
232 }
233 
234 static SkColorSpacePrimaries gSrgbPrimaries = {
235     0.64f, 0.33f,
236     0.30f, 0.60f,
237     0.15f, 0.06f,
238     0.3127f, 0.3290f };
239 
240 static SkColorSpacePrimaries gAdobePrimaries = {
241     0.64f, 0.33f,
242     0.21f, 0.71f,
243     0.15f, 0.06f,
244     0.3127f, 0.3290f };
245 
246 static SkColorSpacePrimaries gP3Primaries = {
247     0.680f, 0.320f,
248     0.265f, 0.690f,
249     0.150f, 0.060f,
250     0.3127f, 0.3290f };
251 
252 static SkColorSpacePrimaries gRec2020Primaries = {
253     0.708f, 0.292f,
254     0.170f, 0.797f,
255     0.131f, 0.046f,
256     0.3127f, 0.3290f };
257 
258 struct NamedPrimaries {
259     const char* fName;
260     SkColorSpacePrimaries* fPrimaries;
261 } gNamedPrimaries[] = {
262     { "sRGB", &gSrgbPrimaries },
263     { "AdobeRGB", &gAdobePrimaries },
264     { "P3", &gP3Primaries },
265     { "Rec. 2020", &gRec2020Primaries },
266 };
267 
primaries_equal(const SkColorSpacePrimaries & a,const SkColorSpacePrimaries & b)268 static bool primaries_equal(const SkColorSpacePrimaries& a, const SkColorSpacePrimaries& b) {
269     return memcmp(&a, &b, sizeof(SkColorSpacePrimaries)) == 0;
270 }
271 
backend_type_for_window(Window::BackendType backendType)272 static Window::BackendType backend_type_for_window(Window::BackendType backendType) {
273     // In raster mode, we still use GL for the window.
274     // This lets us render the GUI faster (and correct).
275     return Window::kRaster_BackendType == backendType ? Window::kNativeGL_BackendType : backendType;
276 }
277 
278 class NullSlide : public Slide {
getDimensions() const279     SkISize getDimensions() const override {
280         return SkISize::Make(640, 480);
281     }
282 
draw(SkCanvas * canvas)283     void draw(SkCanvas* canvas) override {
284         canvas->clear(0xffff11ff);
285     }
286 };
287 
288 static const char kName[] = "name";
289 static const char kValue[] = "value";
290 static const char kOptions[] = "options";
291 static const char kSlideStateName[] = "Slide";
292 static const char kBackendStateName[] = "Backend";
293 static const char kMSAAStateName[] = "MSAA";
294 static const char kPathRendererStateName[] = "Path renderer";
295 static const char kSoftkeyStateName[] = "Softkey";
296 static const char kSoftkeyHint[] = "Please select a softkey";
297 static const char kON[] = "ON";
298 static const char kRefreshStateName[] = "Refresh";
299 
300 extern bool gUseSkVMBlitter;
301 extern bool gSkVMAllowJIT;
302 extern bool gSkVMJITViaDylib;
303 
Viewer(int argc,char ** argv,void * platformData)304 Viewer::Viewer(int argc, char** argv, void* platformData)
305     : fCurrentSlide(-1)
306     , fRefresh(false)
307     , fSaveToSKP(false)
308     , fShowSlideDimensions(false)
309     , fShowImGuiDebugWindow(false)
310     , fShowSlidePicker(false)
311     , fShowImGuiTestWindow(false)
312     , fShowZoomWindow(false)
313     , fZoomWindowFixed(false)
314     , fZoomWindowLocation{0.0f, 0.0f}
315     , fLastImage(nullptr)
316     , fZoomUI(false)
317     , fBackendType(sk_app::Window::kNativeGL_BackendType)
318     , fColorMode(ColorMode::kLegacy)
319     , fColorSpacePrimaries(gSrgbPrimaries)
320     // Our UI can only tweak gamma (currently), so start out gamma-only
321     , fColorSpaceTransferFn(SkNamedTransferFn::k2Dot2)
322     , fZoomLevel(0.0f)
323     , fRotation(0.0f)
324     , fOffset{0.5f, 0.5f}
325     , fGestureDevice(GestureDevice::kNone)
326     , fTiled(false)
327     , fDrawTileBoundaries(false)
328     , fTileScale{0.25f, 0.25f}
329     , fPerspectiveMode(kPerspective_Off)
330 {
331     SkGraphics::Init();
332 
333     gPathRendererNames[GpuPathRenderers::kDefault] = "Default Path Renderers";
334     gPathRendererNames[GpuPathRenderers::kTessellation] = "Tessellation";
335     gPathRendererNames[GpuPathRenderers::kStencilAndCover] = "NV_path_rendering";
336     gPathRendererNames[GpuPathRenderers::kSmall] = "Small paths (cached sdf or alpha masks)";
337     gPathRendererNames[GpuPathRenderers::kCoverageCounting] = "CCPR";
338     gPathRendererNames[GpuPathRenderers::kTriangulating] = "Triangulating";
339     gPathRendererNames[GpuPathRenderers::kNone] = "Software masks";
340 
341     SkDebugf("Command line arguments: ");
342     for (int i = 1; i < argc; ++i) {
343         SkDebugf("%s ", argv[i]);
344     }
345     SkDebugf("\n");
346 
347     CommandLineFlags::Parse(argc, argv);
348 #ifdef SK_BUILD_FOR_ANDROID
349     SetResourcePath("/data/local/tmp/resources");
350 #endif
351 
352     gUseSkVMBlitter = FLAGS_skvm;
353     gSkVMAllowJIT = FLAGS_jit;
354     gSkVMJITViaDylib = FLAGS_dylib;
355 
356     ToolUtils::SetDefaultFontMgr();
357 
358     initializeEventTracingForTools();
359     static SkTaskGroup::Enabler kTaskGroupEnabler(FLAGS_threads);
360 
361     fBackendType = get_backend_type(FLAGS_backend[0]);
362     fWindow = Window::CreateNativeWindow(platformData);
363 
364     DisplayParams displayParams;
365     displayParams.fMSAASampleCount = FLAGS_msaa;
366     SetCtxOptionsFromCommonFlags(&displayParams.fGrContextOptions);
367     displayParams.fGrContextOptions.fPersistentCache = &fPersistentCache;
368     displayParams.fGrContextOptions.fShaderCacheStrategy =
369             GrContextOptions::ShaderCacheStrategy::kBackendSource;
370     displayParams.fGrContextOptions.fShaderErrorHandler = &gShaderErrorHandler;
371     displayParams.fGrContextOptions.fSuppressPrints = true;
372     fWindow->setRequestedDisplayParams(displayParams);
373     fDisplay = fWindow->getRequestedDisplayParams();
374     fRefresh = FLAGS_redraw;
375 
376     // Configure timers
377     fStatsLayer.setActive(FLAGS_stats);
378     fAnimateTimer = fStatsLayer.addTimer("Animate", SK_ColorMAGENTA, 0xffff66ff);
379     fPaintTimer = fStatsLayer.addTimer("Paint", SK_ColorGREEN);
380     fFlushTimer = fStatsLayer.addTimer("Flush", SK_ColorRED, 0xffff6666);
381 
382     // register callbacks
383     fCommands.attach(fWindow);
384     fWindow->pushLayer(this);
385     fWindow->pushLayer(&fStatsLayer);
386     fWindow->pushLayer(&fImGuiLayer);
387 
388     // add key-bindings
__anon564140590102() 389     fCommands.addCommand(' ', "GUI", "Toggle Debug GUI", [this]() {
390         this->fShowImGuiDebugWindow = !this->fShowImGuiDebugWindow;
391         fWindow->inval();
392     });
393     // Command to jump directly to the slide picker and give it focus
__anon564140590202() 394     fCommands.addCommand('/', "GUI", "Jump to slide picker", [this]() {
395         this->fShowImGuiDebugWindow = true;
396         this->fShowSlidePicker = true;
397         fWindow->inval();
398     });
399     // Alias that to Backspace, to match SampleApp
__anon564140590302() 400     fCommands.addCommand(skui::Key::kBack, "Backspace", "GUI", "Jump to slide picker", [this]() {
401         this->fShowImGuiDebugWindow = true;
402         this->fShowSlidePicker = true;
403         fWindow->inval();
404     });
__anon564140590402() 405     fCommands.addCommand('g', "GUI", "Toggle GUI Demo", [this]() {
406         this->fShowImGuiTestWindow = !this->fShowImGuiTestWindow;
407         fWindow->inval();
408     });
__anon564140590502() 409     fCommands.addCommand('z', "GUI", "Toggle zoom window", [this]() {
410         this->fShowZoomWindow = !this->fShowZoomWindow;
411         fWindow->inval();
412     });
__anon564140590602() 413     fCommands.addCommand('Z', "GUI", "Toggle zoom window state", [this]() {
414         this->fZoomWindowFixed = !this->fZoomWindowFixed;
415         fWindow->inval();
416     });
__anon564140590702() 417     fCommands.addCommand('v', "Swapchain", "Toggle vsync on/off", [this]() {
418         DisplayParams params = fWindow->getRequestedDisplayParams();
419         params.fDisableVsync = !params.fDisableVsync;
420         fWindow->setRequestedDisplayParams(params);
421         this->updateTitle();
422         fWindow->inval();
423     });
__anon564140590802() 424     fCommands.addCommand('V', "Swapchain", "Toggle delayed acquire on/off (Metal only)", [this]() {
425         DisplayParams params = fWindow->getRequestedDisplayParams();
426         params.fDelayDrawableAcquisition = !params.fDelayDrawableAcquisition;
427         fWindow->setRequestedDisplayParams(params);
428         this->updateTitle();
429         fWindow->inval();
430     });
__anon564140590902() 431     fCommands.addCommand('r', "Redraw", "Toggle redraw", [this]() {
432         fRefresh = !fRefresh;
433         fWindow->inval();
434     });
__anon564140590a02() 435     fCommands.addCommand('s', "Overlays", "Toggle stats display", [this]() {
436         fStatsLayer.setActive(!fStatsLayer.getActive());
437         fWindow->inval();
438     });
__anon564140590b02() 439     fCommands.addCommand('0', "Overlays", "Reset stats", [this]() {
440         fStatsLayer.resetMeasurements();
441         this->updateTitle();
442         fWindow->inval();
443     });
__anon564140590c02() 444     fCommands.addCommand('c', "Modes", "Cycle color mode", [this]() {
445         switch (fColorMode) {
446             case ColorMode::kLegacy:
447                 this->setColorMode(ColorMode::kColorManaged8888);
448                 break;
449             case ColorMode::kColorManaged8888:
450                 this->setColorMode(ColorMode::kColorManagedF16);
451                 break;
452             case ColorMode::kColorManagedF16:
453                 this->setColorMode(ColorMode::kColorManagedF16Norm);
454                 break;
455             case ColorMode::kColorManagedF16Norm:
456                 this->setColorMode(ColorMode::kLegacy);
457                 break;
458         }
459     });
__anon564140590d02() 460     fCommands.addCommand('w', "Modes", "Toggle wireframe", [this]() {
461         DisplayParams params = fWindow->getRequestedDisplayParams();
462         params.fGrContextOptions.fWireframeMode = !params.fGrContextOptions.fWireframeMode;
463         fWindow->setRequestedDisplayParams(params);
464         fWindow->inval();
465     });
__anon564140590e02() 466     fCommands.addCommand(skui::Key::kRight, "Right", "Navigation", "Next slide", [this]() {
467         this->setCurrentSlide(fCurrentSlide < fSlides.count() - 1 ? fCurrentSlide + 1 : 0);
468     });
__anon564140590f02() 469     fCommands.addCommand(skui::Key::kLeft, "Left", "Navigation", "Previous slide", [this]() {
470         this->setCurrentSlide(fCurrentSlide > 0 ? fCurrentSlide - 1 : fSlides.count() - 1);
471     });
__anon564140591002() 472     fCommands.addCommand(skui::Key::kUp, "Up", "Transform", "Zoom in", [this]() {
473         this->changeZoomLevel(1.f / 32.f);
474         fWindow->inval();
475     });
__anon564140591102() 476     fCommands.addCommand(skui::Key::kDown, "Down", "Transform", "Zoom out", [this]() {
477         this->changeZoomLevel(-1.f / 32.f);
478         fWindow->inval();
479     });
__anon564140591202() 480     fCommands.addCommand('d', "Modes", "Change rendering backend", [this]() {
481         sk_app::Window::BackendType newBackend = (sk_app::Window::BackendType)(
482                 (fBackendType + 1) % sk_app::Window::kBackendTypeCount);
483         // Switching to and from Vulkan is problematic on Linux so disabled for now
484 #if defined(SK_BUILD_FOR_UNIX) && defined(SK_VULKAN)
485         if (newBackend == sk_app::Window::kVulkan_BackendType) {
486             newBackend = (sk_app::Window::BackendType)((newBackend + 1) %
487                                                        sk_app::Window::kBackendTypeCount);
488         } else if (fBackendType == sk_app::Window::kVulkan_BackendType) {
489             newBackend = sk_app::Window::kVulkan_BackendType;
490         }
491 #endif
492         this->setBackend(newBackend);
493     });
__anon564140591302() 494     fCommands.addCommand('K', "IO", "Save slide to SKP", [this]() {
495         fSaveToSKP = true;
496         fWindow->inval();
497     });
__anon564140591402() 498     fCommands.addCommand('&', "Overlays", "Show slide dimensios", [this]() {
499         fShowSlideDimensions = !fShowSlideDimensions;
500         fWindow->inval();
501     });
__anon564140591502() 502     fCommands.addCommand('G', "Modes", "Geometry", [this]() {
503         DisplayParams params = fWindow->getRequestedDisplayParams();
504         uint32_t flags = params.fSurfaceProps.flags();
505         SkPixelGeometry defaultPixelGeometry = fDisplay.fSurfaceProps.pixelGeometry();
506         if (!fDisplayOverrides.fSurfaceProps.fPixelGeometry) {
507             fDisplayOverrides.fSurfaceProps.fPixelGeometry = true;
508             params.fSurfaceProps = SkSurfaceProps(flags, kUnknown_SkPixelGeometry);
509         } else {
510             switch (params.fSurfaceProps.pixelGeometry()) {
511                 case kUnknown_SkPixelGeometry:
512                     params.fSurfaceProps = SkSurfaceProps(flags, kRGB_H_SkPixelGeometry);
513                     break;
514                 case kRGB_H_SkPixelGeometry:
515                     params.fSurfaceProps = SkSurfaceProps(flags, kBGR_H_SkPixelGeometry);
516                     break;
517                 case kBGR_H_SkPixelGeometry:
518                     params.fSurfaceProps = SkSurfaceProps(flags, kRGB_V_SkPixelGeometry);
519                     break;
520                 case kRGB_V_SkPixelGeometry:
521                     params.fSurfaceProps = SkSurfaceProps(flags, kBGR_V_SkPixelGeometry);
522                     break;
523                 case kBGR_V_SkPixelGeometry:
524                     params.fSurfaceProps = SkSurfaceProps(flags, defaultPixelGeometry);
525                     fDisplayOverrides.fSurfaceProps.fPixelGeometry = false;
526                     break;
527             }
528         }
529         fWindow->setRequestedDisplayParams(params);
530         this->updateTitle();
531         fWindow->inval();
532     });
__anon564140591602() 533     fCommands.addCommand('H', "Font", "Hinting mode", [this]() {
534         if (!fFontOverrides.fHinting) {
535             fFontOverrides.fHinting = true;
536             fFont.setHinting(SkFontHinting::kNone);
537         } else {
538             switch (fFont.getHinting()) {
539                 case SkFontHinting::kNone:
540                     fFont.setHinting(SkFontHinting::kSlight);
541                     break;
542                 case SkFontHinting::kSlight:
543                     fFont.setHinting(SkFontHinting::kNormal);
544                     break;
545                 case SkFontHinting::kNormal:
546                     fFont.setHinting(SkFontHinting::kFull);
547                     break;
548                 case SkFontHinting::kFull:
549                     fFont.setHinting(SkFontHinting::kNone);
550                     fFontOverrides.fHinting = false;
551                     break;
552             }
553         }
554         this->updateTitle();
555         fWindow->inval();
556     });
__anon564140591702() 557     fCommands.addCommand('A', "Paint", "Antialias Mode", [this]() {
558         if (!fPaintOverrides.fAntiAlias) {
559             fPaintOverrides.fAntiAliasState = SkPaintFields::AntiAliasState::Alias;
560             fPaintOverrides.fAntiAlias = true;
561             fPaint.setAntiAlias(false);
562             gSkUseAnalyticAA = gSkForceAnalyticAA = false;
563         } else {
564             fPaint.setAntiAlias(true);
565             switch (fPaintOverrides.fAntiAliasState) {
566                 case SkPaintFields::AntiAliasState::Alias:
567                     fPaintOverrides.fAntiAliasState = SkPaintFields::AntiAliasState::Normal;
568                     gSkUseAnalyticAA = gSkForceAnalyticAA = false;
569                     break;
570                 case SkPaintFields::AntiAliasState::Normal:
571                     fPaintOverrides.fAntiAliasState = SkPaintFields::AntiAliasState::AnalyticAAEnabled;
572                     gSkUseAnalyticAA = true;
573                     gSkForceAnalyticAA = false;
574                     break;
575                 case SkPaintFields::AntiAliasState::AnalyticAAEnabled:
576                     fPaintOverrides.fAntiAliasState = SkPaintFields::AntiAliasState::AnalyticAAForced;
577                     gSkUseAnalyticAA = gSkForceAnalyticAA = true;
578                     break;
579                 case SkPaintFields::AntiAliasState::AnalyticAAForced:
580                     fPaintOverrides.fAntiAliasState = SkPaintFields::AntiAliasState::Alias;
581                     fPaintOverrides.fAntiAlias = false;
582                     gSkUseAnalyticAA = fPaintOverrides.fOriginalSkUseAnalyticAA;
583                     gSkForceAnalyticAA = fPaintOverrides.fOriginalSkForceAnalyticAA;
584                     break;
585             }
586         }
587         this->updateTitle();
588         fWindow->inval();
589     });
__anon564140591802() 590     fCommands.addCommand('D', "Modes", "DFT", [this]() {
591         DisplayParams params = fWindow->getRequestedDisplayParams();
592         uint32_t flags = params.fSurfaceProps.flags();
593         flags ^= SkSurfaceProps::kUseDeviceIndependentFonts_Flag;
594         params.fSurfaceProps = SkSurfaceProps(flags, params.fSurfaceProps.pixelGeometry());
595         fWindow->setRequestedDisplayParams(params);
596         this->updateTitle();
597         fWindow->inval();
598     });
__anon564140591902() 599     fCommands.addCommand('L', "Font", "Subpixel Antialias Mode", [this]() {
600         if (!fFontOverrides.fEdging) {
601             fFontOverrides.fEdging = true;
602             fFont.setEdging(SkFont::Edging::kAlias);
603         } else {
604             switch (fFont.getEdging()) {
605                 case SkFont::Edging::kAlias:
606                     fFont.setEdging(SkFont::Edging::kAntiAlias);
607                     break;
608                 case SkFont::Edging::kAntiAlias:
609                     fFont.setEdging(SkFont::Edging::kSubpixelAntiAlias);
610                     break;
611                 case SkFont::Edging::kSubpixelAntiAlias:
612                     fFont.setEdging(SkFont::Edging::kAlias);
613                     fFontOverrides.fEdging = false;
614                     break;
615             }
616         }
617         this->updateTitle();
618         fWindow->inval();
619     });
__anon564140591a02() 620     fCommands.addCommand('S', "Font", "Subpixel Position Mode", [this]() {
621         if (!fFontOverrides.fSubpixel) {
622             fFontOverrides.fSubpixel = true;
623             fFont.setSubpixel(false);
624         } else {
625             if (!fFont.isSubpixel()) {
626                 fFont.setSubpixel(true);
627             } else {
628                 fFontOverrides.fSubpixel = false;
629             }
630         }
631         this->updateTitle();
632         fWindow->inval();
633     });
__anon564140591b02() 634     fCommands.addCommand('B', "Font", "Baseline Snapping", [this]() {
635         if (!fFontOverrides.fBaselineSnap) {
636             fFontOverrides.fBaselineSnap = true;
637             fFont.setBaselineSnap(false);
638         } else {
639             if (!fFont.isBaselineSnap()) {
640                 fFont.setBaselineSnap(true);
641             } else {
642                 fFontOverrides.fBaselineSnap = false;
643             }
644         }
645         this->updateTitle();
646         fWindow->inval();
647     });
__anon564140591c02() 648     fCommands.addCommand('p', "Transform", "Toggle Perspective Mode", [this]() {
649         fPerspectiveMode = (kPerspective_Real == fPerspectiveMode) ? kPerspective_Fake
650                                                                    : kPerspective_Real;
651         this->updateTitle();
652         fWindow->inval();
653     });
__anon564140591d02() 654     fCommands.addCommand('P', "Transform", "Toggle Perspective", [this]() {
655         fPerspectiveMode = (kPerspective_Off == fPerspectiveMode) ? kPerspective_Real
656                                                                   : kPerspective_Off;
657         this->updateTitle();
658         fWindow->inval();
659     });
__anon564140591e02() 660     fCommands.addCommand('a', "Transform", "Toggle Animation", [this]() {
661         fAnimTimer.togglePauseResume();
662     });
__anon564140591f02() 663     fCommands.addCommand('u', "GUI", "Zoom UI", [this]() {
664         fZoomUI = !fZoomUI;
665         fStatsLayer.setDisplayScale(fZoomUI ? 2.0f : 1.0f);
666         fWindow->inval();
667     });
__anon564140592002() 668     fCommands.addCommand('$', "ViaSerialize", "Toggle ViaSerialize", [this]() {
669         fDrawViaSerialize = !fDrawViaSerialize;
670         this->updateTitle();
671         fWindow->inval();
672     });
__anon564140592102() 673     fCommands.addCommand('!', "SkVM", "Toggle SkVM blitter", [this]() {
674         gUseSkVMBlitter = !gUseSkVMBlitter;
675         this->updateTitle();
676         fWindow->inval();
677     });
__anon564140592202() 678     fCommands.addCommand('@', "SkVM", "Toggle SkVM JIT", [this]() {
679         gSkVMAllowJIT = !gSkVMAllowJIT;
680         this->updateTitle();
681         fWindow->inval();
682     });
683 
684     // set up slides
685     this->initSlides();
686     if (FLAGS_list) {
687         this->listNames();
688     }
689 
690     fPerspectivePoints[0].set(0, 0);
691     fPerspectivePoints[1].set(1, 0);
692     fPerspectivePoints[2].set(0, 1);
693     fPerspectivePoints[3].set(1, 1);
694     fAnimTimer.run();
695 
696     auto gamutImage = GetResourceAsImage("images/gamut.png");
697     if (gamutImage) {
698         fImGuiGamutPaint.setShader(gamutImage->makeShader());
699     }
700     fImGuiGamutPaint.setColor(SK_ColorWHITE);
701     fImGuiGamutPaint.setFilterQuality(kLow_SkFilterQuality);
702 
703     fWindow->attach(backend_type_for_window(fBackendType));
704     this->setCurrentSlide(this->startupSlide());
705 }
706 
initSlides()707 void Viewer::initSlides() {
708     using SlideFactory = sk_sp<Slide>(*)(const SkString& name, const SkString& path);
709     static const struct {
710         const char*                            fExtension;
711         const char*                            fDirName;
712         const CommandLineFlags::StringArray&   fFlags;
713         const SlideFactory                     fFactory;
714     } gExternalSlidesInfo[] = {
715         { ".skp", "skp-dir", FLAGS_skps,
716             [](const SkString& name, const SkString& path) -> sk_sp<Slide> {
717                 return sk_make_sp<SKPSlide>(name, path);}
718         },
719         { ".jpg", "jpg-dir", FLAGS_jpgs,
720             [](const SkString& name, const SkString& path) -> sk_sp<Slide> {
721                 return sk_make_sp<ImageSlide>(name, path);}
722         },
723 #if defined(SK_ENABLE_SKOTTIE)
724         { ".json", "skottie-dir", FLAGS_lotties,
725             [](const SkString& name, const SkString& path) -> sk_sp<Slide> {
726                 return sk_make_sp<SkottieSlide>(name, path);}
727         },
728 #endif
729     #if defined(SK_ENABLE_SKRIVE)
730             { ".flr", "skrive-dir", FLAGS_rives,
731                 [](const SkString& name, const SkString& path) -> sk_sp<Slide> {
732                     return sk_make_sp<SkRiveSlide>(name, path);}
733             },
734     #endif
735 #if defined(SK_XML)
736         { ".svg", "svg-dir", FLAGS_svgs,
737             [](const SkString& name, const SkString& path) -> sk_sp<Slide> {
738                 return sk_make_sp<SvgSlide>(name, path);}
739         },
740 #endif
741     };
742 
743     SkTArray<sk_sp<Slide>> dirSlides;
744 
745     const auto addSlide =
746             [&](const SkString& name, const SkString& path, const SlideFactory& fact) {
747                 if (CommandLineFlags::ShouldSkip(FLAGS_match, name.c_str())) {
748                     return;
749                 }
750 
751                 if (auto slide = fact(name, path)) {
752                     dirSlides.push_back(slide);
753                     fSlides.push_back(std::move(slide));
754                 }
755             };
756 
757     if (!FLAGS_file.isEmpty()) {
758         // single file mode
759         const SkString file(FLAGS_file[0]);
760 
761         if (sk_exists(file.c_str(), kRead_SkFILE_Flag)) {
762             for (const auto& sinfo : gExternalSlidesInfo) {
763                 if (file.endsWith(sinfo.fExtension)) {
764                     addSlide(SkOSPath::Basename(file.c_str()), file, sinfo.fFactory);
765                     return;
766                 }
767             }
768 
769             fprintf(stderr, "Unsupported file type \"%s\"\n", file.c_str());
770         } else {
771             fprintf(stderr, "Cannot read \"%s\"\n", file.c_str());
772         }
773 
774         return;
775     }
776 
777     // Bisect slide.
778     if (!FLAGS_bisect.isEmpty()) {
779         sk_sp<BisectSlide> bisect = BisectSlide::Create(FLAGS_bisect[0]);
780         if (bisect && !CommandLineFlags::ShouldSkip(FLAGS_match, bisect->getName().c_str())) {
781             if (FLAGS_bisect.count() >= 2) {
782                 for (const char* ch = FLAGS_bisect[1]; *ch; ++ch) {
783                     bisect->onChar(*ch);
784                 }
785             }
786             fSlides.push_back(std::move(bisect));
787         }
788     }
789 
790     // GMs
791     int firstGM = fSlides.count();
792     for (skiagm::GMFactory gmFactory : skiagm::GMRegistry::Range()) {
793         std::unique_ptr<skiagm::GM> gm = gmFactory();
794         if (!CommandLineFlags::ShouldSkip(FLAGS_match, gm->getName())) {
795             sk_sp<Slide> slide(new GMSlide(std::move(gm)));
796             fSlides.push_back(std::move(slide));
797         }
798     }
799     // reverse gms
800     int numGMs = fSlides.count() - firstGM;
801     for (int i = 0; i < numGMs/2; ++i) {
802         std::swap(fSlides[firstGM + i], fSlides[fSlides.count() - i - 1]);
803     }
804 
805     // samples
806     for (const SampleFactory factory : SampleRegistry::Range()) {
807         sk_sp<Slide> slide(new SampleSlide(factory));
808         if (!CommandLineFlags::ShouldSkip(FLAGS_match, slide->getName().c_str())) {
809             fSlides.push_back(slide);
810         }
811     }
812 
813     // Particle demo
814     {
815         // TODO: Convert this to a sample
816         sk_sp<Slide> slide(new ParticlesSlide());
817         if (!CommandLineFlags::ShouldSkip(FLAGS_match, slide->getName().c_str())) {
818             fSlides.push_back(std::move(slide));
819         }
820     }
821 
822     // Runtime shader editor
823     {
824         sk_sp<Slide> slide(new SkSLSlide());
825         if (!CommandLineFlags::ShouldSkip(FLAGS_match, slide->getName().c_str())) {
826             fSlides.push_back(std::move(slide));
827         }
828     }
829 
830     for (const auto& info : gExternalSlidesInfo) {
831         for (const auto& flag : info.fFlags) {
832             if (SkStrEndsWith(flag.c_str(), info.fExtension)) {
833                 // single file
834                 addSlide(SkOSPath::Basename(flag.c_str()), flag, info.fFactory);
835             } else {
836                 // directory
837                 SkString name;
838                 SkTArray<SkString> sortedFilenames;
839                 SkOSFile::Iter it(flag.c_str(), info.fExtension);
840                 while (it.next(&name)) {
841                     sortedFilenames.push_back(name);
842                 }
843                 if (sortedFilenames.count()) {
844                     SkTQSort(sortedFilenames.begin(), sortedFilenames.end(),
845                              [](const SkString& a, const SkString& b) {
846                                  return strcmp(a.c_str(), b.c_str()) < 0;
847                              });
848                 }
849                 for (const SkString& filename : sortedFilenames) {
850                     addSlide(filename, SkOSPath::Join(flag.c_str(), filename.c_str()),
851                              info.fFactory);
852                 }
853             }
854             if (!dirSlides.empty()) {
855                 fSlides.push_back(
856                     sk_make_sp<SlideDir>(SkStringPrintf("%s[%s]", info.fDirName, flag.c_str()),
857                                          std::move(dirSlides)));
858                 dirSlides.reset();  // NOLINT(bugprone-use-after-move)
859             }
860         }
861     }
862 
863     if (!fSlides.count()) {
864         sk_sp<Slide> slide(new NullSlide());
865         fSlides.push_back(std::move(slide));
866     }
867 }
868 
869 
~Viewer()870 Viewer::~Viewer() {
871     for(auto& slide : fSlides) {
872         slide->gpuTeardown();
873     }
874 
875     fWindow->detach();
876     delete fWindow;
877 }
878 
879 struct SkPaintTitleUpdater {
SkPaintTitleUpdaterSkPaintTitleUpdater880     SkPaintTitleUpdater(SkString* title) : fTitle(title), fCount(0) {}
appendSkPaintTitleUpdater881     void append(const char* s) {
882         if (fCount == 0) {
883             fTitle->append(" {");
884         } else {
885             fTitle->append(", ");
886         }
887         fTitle->append(s);
888         ++fCount;
889     }
doneSkPaintTitleUpdater890     void done() {
891         if (fCount > 0) {
892             fTitle->append("}");
893         }
894     }
895     SkString* fTitle;
896     int fCount;
897 };
898 
updateTitle()899 void Viewer::updateTitle() {
900     if (!fWindow) {
901         return;
902     }
903     if (fWindow->sampleCount() < 1) {
904         return; // Surface hasn't been created yet.
905     }
906 
907     SkString title("Viewer: ");
908     title.append(fSlides[fCurrentSlide]->getName());
909 
910     if (gSkUseAnalyticAA) {
911         if (gSkForceAnalyticAA) {
912             title.append(" <FAAA>");
913         } else {
914             title.append(" <AAA>");
915         }
916     }
917     if (fDrawViaSerialize) {
918         title.append(" <serialize>");
919     }
920     if (gUseSkVMBlitter) {
921         title.append(" <SkVMBlitter>");
922     }
923     if (!gSkVMAllowJIT) {
924         title.append(" <SkVM interpreter>");
925     }
926 
927     SkPaintTitleUpdater paintTitle(&title);
928     auto paintFlag = [this, &paintTitle](bool SkPaintFields::* flag,
929                                          bool (SkPaint::* isFlag)() const,
930                                          const char* on, const char* off)
931     {
932         if (fPaintOverrides.*flag) {
933             paintTitle.append((fPaint.*isFlag)() ? on : off);
934         }
935     };
936 
937     auto fontFlag = [this, &paintTitle](bool SkFontFields::* flag, bool (SkFont::* isFlag)() const,
938                                         const char* on, const char* off)
939     {
940         if (fFontOverrides.*flag) {
941             paintTitle.append((fFont.*isFlag)() ? on : off);
942         }
943     };
944 
945     paintFlag(&SkPaintFields::fAntiAlias, &SkPaint::isAntiAlias, "Antialias", "Alias");
946     paintFlag(&SkPaintFields::fDither, &SkPaint::isDither, "DITHER", "No Dither");
947     if (fPaintOverrides.fFilterQuality) {
948         switch (fPaint.getFilterQuality()) {
949             case kNone_SkFilterQuality:
950                 paintTitle.append("NoFilter");
951                 break;
952             case kLow_SkFilterQuality:
953                 paintTitle.append("LowFilter");
954                 break;
955             case kMedium_SkFilterQuality:
956                 paintTitle.append("MediumFilter");
957                 break;
958             case kHigh_SkFilterQuality:
959                 paintTitle.append("HighFilter");
960                 break;
961         }
962     }
963 
964     fontFlag(&SkFontFields::fForceAutoHinting, &SkFont::isForceAutoHinting,
965              "Force Autohint", "No Force Autohint");
966     fontFlag(&SkFontFields::fEmbolden, &SkFont::isEmbolden, "Fake Bold", "No Fake Bold");
967     fontFlag(&SkFontFields::fBaselineSnap, &SkFont::isBaselineSnap, "BaseSnap", "No BaseSnap");
968     fontFlag(&SkFontFields::fLinearMetrics, &SkFont::isLinearMetrics,
969              "Linear Metrics", "Non-Linear Metrics");
970     fontFlag(&SkFontFields::fEmbeddedBitmaps, &SkFont::isEmbeddedBitmaps,
971              "Bitmap Text", "No Bitmap Text");
972     fontFlag(&SkFontFields::fSubpixel, &SkFont::isSubpixel, "Subpixel Text", "Pixel Text");
973 
974     if (fFontOverrides.fEdging) {
975         switch (fFont.getEdging()) {
976             case SkFont::Edging::kAlias:
977                 paintTitle.append("Alias Text");
978                 break;
979             case SkFont::Edging::kAntiAlias:
980                 paintTitle.append("Antialias Text");
981                 break;
982             case SkFont::Edging::kSubpixelAntiAlias:
983                 paintTitle.append("Subpixel Antialias Text");
984                 break;
985         }
986     }
987 
988     if (fFontOverrides.fHinting) {
989         switch (fFont.getHinting()) {
990             case SkFontHinting::kNone:
991                 paintTitle.append("No Hinting");
992                 break;
993             case SkFontHinting::kSlight:
994                 paintTitle.append("Slight Hinting");
995                 break;
996             case SkFontHinting::kNormal:
997                 paintTitle.append("Normal Hinting");
998                 break;
999             case SkFontHinting::kFull:
1000                 paintTitle.append("Full Hinting");
1001                 break;
1002         }
1003     }
1004     paintTitle.done();
1005 
1006     switch (fColorMode) {
1007         case ColorMode::kLegacy:
1008             title.append(" Legacy 8888");
1009             break;
1010         case ColorMode::kColorManaged8888:
1011             title.append(" ColorManaged 8888");
1012             break;
1013         case ColorMode::kColorManagedF16:
1014             title.append(" ColorManaged F16");
1015             break;
1016         case ColorMode::kColorManagedF16Norm:
1017             title.append(" ColorManaged F16 Norm");
1018             break;
1019     }
1020 
1021     if (ColorMode::kLegacy != fColorMode) {
1022         int curPrimaries = -1;
1023         for (size_t i = 0; i < SK_ARRAY_COUNT(gNamedPrimaries); ++i) {
1024             if (primaries_equal(*gNamedPrimaries[i].fPrimaries, fColorSpacePrimaries)) {
1025                 curPrimaries = i;
1026                 break;
1027             }
1028         }
1029         title.appendf(" %s Gamma %f",
1030                       curPrimaries >= 0 ? gNamedPrimaries[curPrimaries].fName : "Custom",
1031                       fColorSpaceTransferFn.g);
1032     }
1033 
1034     const DisplayParams& params = fWindow->getRequestedDisplayParams();
1035     if (fDisplayOverrides.fSurfaceProps.fPixelGeometry) {
1036         switch (params.fSurfaceProps.pixelGeometry()) {
1037             case kUnknown_SkPixelGeometry:
1038                 title.append( " Flat");
1039                 break;
1040             case kRGB_H_SkPixelGeometry:
1041                 title.append( " RGB");
1042                 break;
1043             case kBGR_H_SkPixelGeometry:
1044                 title.append( " BGR");
1045                 break;
1046             case kRGB_V_SkPixelGeometry:
1047                 title.append( " RGBV");
1048                 break;
1049             case kBGR_V_SkPixelGeometry:
1050                 title.append( " BGRV");
1051                 break;
1052         }
1053     }
1054 
1055     if (params.fSurfaceProps.isUseDeviceIndependentFonts()) {
1056         title.append(" DFT");
1057     }
1058 
1059     title.append(" [");
1060     title.append(kBackendTypeStrings[fBackendType]);
1061     int msaa = fWindow->sampleCount();
1062     if (msaa > 1) {
1063         title.appendf(" MSAA: %i", msaa);
1064     }
1065     title.append("]");
1066 
1067     GpuPathRenderers pr = fWindow->getRequestedDisplayParams().fGrContextOptions.fGpuPathRenderers;
1068     if (GpuPathRenderers::kDefault != pr) {
1069         title.appendf(" [Path renderer: %s]", gPathRendererNames[pr].c_str());
1070     }
1071 
1072     if (kPerspective_Real == fPerspectiveMode) {
1073         title.append(" Perpsective (Real)");
1074     } else if (kPerspective_Fake == fPerspectiveMode) {
1075         title.append(" Perspective (Fake)");
1076     }
1077 
1078     fWindow->setTitle(title.c_str());
1079 }
1080 
startupSlide() const1081 int Viewer::startupSlide() const {
1082 
1083     if (!FLAGS_slide.isEmpty()) {
1084         int count = fSlides.count();
1085         for (int i = 0; i < count; i++) {
1086             if (fSlides[i]->getName().equals(FLAGS_slide[0])) {
1087                 return i;
1088             }
1089         }
1090 
1091         fprintf(stderr, "Unknown slide \"%s\"\n", FLAGS_slide[0]);
1092         this->listNames();
1093     }
1094 
1095     return 0;
1096 }
1097 
listNames() const1098 void Viewer::listNames() const {
1099     SkDebugf("All Slides:\n");
1100     for (const auto& slide : fSlides) {
1101         SkDebugf("    %s\n", slide->getName().c_str());
1102     }
1103 }
1104 
setCurrentSlide(int slide)1105 void Viewer::setCurrentSlide(int slide) {
1106     SkASSERT(slide >= 0 && slide < fSlides.count());
1107 
1108     if (slide == fCurrentSlide) {
1109         return;
1110     }
1111 
1112     if (fCurrentSlide >= 0) {
1113         fSlides[fCurrentSlide]->unload();
1114     }
1115 
1116     fSlides[slide]->load(SkIntToScalar(fWindow->width()),
1117                          SkIntToScalar(fWindow->height()));
1118     fCurrentSlide = slide;
1119     this->setupCurrentSlide();
1120 }
1121 
setupCurrentSlide()1122 void Viewer::setupCurrentSlide() {
1123     if (fCurrentSlide >= 0) {
1124         // prepare dimensions for image slides
1125         fGesture.resetTouchState();
1126         fDefaultMatrix.reset();
1127 
1128         const SkISize slideSize = fSlides[fCurrentSlide]->getDimensions();
1129         const SkRect slideBounds = SkRect::MakeIWH(slideSize.width(), slideSize.height());
1130         const SkRect windowRect = SkRect::MakeIWH(fWindow->width(), fWindow->height());
1131 
1132         // Start with a matrix that scales the slide to the available screen space
1133         if (fWindow->scaleContentToFit()) {
1134             if (windowRect.width() > 0 && windowRect.height() > 0) {
1135                 fDefaultMatrix.setRectToRect(slideBounds, windowRect, SkMatrix::kStart_ScaleToFit);
1136             }
1137         }
1138 
1139         // Prevent the user from dragging content so far outside the window they can't find it again
1140         fGesture.setTransLimit(slideBounds, windowRect, this->computePreTouchMatrix());
1141 
1142         this->updateTitle();
1143         this->updateUIState();
1144 
1145         fStatsLayer.resetMeasurements();
1146 
1147         fWindow->inval();
1148     }
1149 }
1150 
1151 #define MAX_ZOOM_LEVEL  8.0f
1152 #define MIN_ZOOM_LEVEL  -8.0f
1153 
changeZoomLevel(float delta)1154 void Viewer::changeZoomLevel(float delta) {
1155     fZoomLevel += delta;
1156     fZoomLevel = SkTPin(fZoomLevel, MIN_ZOOM_LEVEL, MAX_ZOOM_LEVEL);
1157     this->preTouchMatrixChanged();
1158 }
1159 
preTouchMatrixChanged()1160 void Viewer::preTouchMatrixChanged() {
1161     // Update the trans limit as the transform changes.
1162     const SkISize slideSize = fSlides[fCurrentSlide]->getDimensions();
1163     const SkRect slideBounds = SkRect::MakeIWH(slideSize.width(), slideSize.height());
1164     const SkRect windowRect = SkRect::MakeIWH(fWindow->width(), fWindow->height());
1165     fGesture.setTransLimit(slideBounds, windowRect, this->computePreTouchMatrix());
1166 }
1167 
computePerspectiveMatrix()1168 SkMatrix Viewer::computePerspectiveMatrix() {
1169     SkScalar w = fWindow->width(), h = fWindow->height();
1170     SkPoint orthoPts[4] = { { 0, 0 }, { w, 0 }, { 0, h }, { w, h } };
1171     SkPoint perspPts[4] = {
1172         { fPerspectivePoints[0].fX * w, fPerspectivePoints[0].fY * h },
1173         { fPerspectivePoints[1].fX * w, fPerspectivePoints[1].fY * h },
1174         { fPerspectivePoints[2].fX * w, fPerspectivePoints[2].fY * h },
1175         { fPerspectivePoints[3].fX * w, fPerspectivePoints[3].fY * h }
1176     };
1177     SkMatrix m;
1178     m.setPolyToPoly(orthoPts, perspPts, 4);
1179     return m;
1180 }
1181 
computePreTouchMatrix()1182 SkMatrix Viewer::computePreTouchMatrix() {
1183     SkMatrix m = fDefaultMatrix;
1184 
1185     SkScalar zoomScale = exp(fZoomLevel);
1186     m.preTranslate((fOffset.x() - 0.5f) * 2.0f, (fOffset.y() - 0.5f) * 2.0f);
1187     m.preScale(zoomScale, zoomScale);
1188 
1189     const SkISize slideSize = fSlides[fCurrentSlide]->getDimensions();
1190     m.preRotate(fRotation, slideSize.width() * 0.5f, slideSize.height() * 0.5f);
1191 
1192     if (kPerspective_Real == fPerspectiveMode) {
1193         SkMatrix persp = this->computePerspectiveMatrix();
1194         m.postConcat(persp);
1195     }
1196 
1197     return m;
1198 }
1199 
computeMatrix()1200 SkMatrix Viewer::computeMatrix() {
1201     SkMatrix m = fGesture.localM();
1202     m.preConcat(fGesture.globalM());
1203     m.preConcat(this->computePreTouchMatrix());
1204     return m;
1205 }
1206 
setBackend(sk_app::Window::BackendType backendType)1207 void Viewer::setBackend(sk_app::Window::BackendType backendType) {
1208     fPersistentCache.reset();
1209     fCachedShaders.reset();
1210     fBackendType = backendType;
1211 
1212     // The active context is going away in 'detach'
1213     for(auto& slide : fSlides) {
1214         slide->gpuTeardown();
1215     }
1216 
1217     fWindow->detach();
1218 
1219 #if defined(SK_BUILD_FOR_WIN)
1220     // Switching between OpenGL, Vulkan, and ANGLE in the same window is problematic at this point
1221     // on Windows, so we just delete the window and recreate it.
1222     DisplayParams params = fWindow->getRequestedDisplayParams();
1223     delete fWindow;
1224     fWindow = Window::CreateNativeWindow(nullptr);
1225 
1226     // re-register callbacks
1227     fCommands.attach(fWindow);
1228     fWindow->pushLayer(this);
1229     fWindow->pushLayer(&fStatsLayer);
1230     fWindow->pushLayer(&fImGuiLayer);
1231 
1232     // Don't allow the window to re-attach. If we're in MSAA mode, the params we grabbed above
1233     // will still include our correct sample count. But the re-created fWindow will lose that
1234     // information. On Windows, we need to re-create the window when changing sample count,
1235     // so we'll incorrectly detect that situation, then re-initialize the window in GL mode,
1236     // rendering this tear-down step pointless (and causing the Vulkan window context to fail
1237     // as if we had never changed windows at all).
1238     fWindow->setRequestedDisplayParams(params, false);
1239 #endif
1240 
1241     fWindow->attach(backend_type_for_window(fBackendType));
1242 }
1243 
setColorMode(ColorMode colorMode)1244 void Viewer::setColorMode(ColorMode colorMode) {
1245     fColorMode = colorMode;
1246     this->updateTitle();
1247     fWindow->inval();
1248 }
1249 
1250 class OveridePaintFilterCanvas : public SkPaintFilterCanvas {
1251 public:
OveridePaintFilterCanvas(SkCanvas * canvas,SkPaint * paint,Viewer::SkPaintFields * pfields,SkFont * font,Viewer::SkFontFields * ffields)1252     OveridePaintFilterCanvas(SkCanvas* canvas, SkPaint* paint, Viewer::SkPaintFields* pfields,
1253             SkFont* font, Viewer::SkFontFields* ffields)
1254         : SkPaintFilterCanvas(canvas), fPaint(paint), fPaintOverrides(pfields), fFont(font), fFontOverrides(ffields)
1255     { }
filterTextBlob(const SkPaint & paint,const SkTextBlob * blob,sk_sp<SkTextBlob> * cache)1256     const SkTextBlob* filterTextBlob(const SkPaint& paint, const SkTextBlob* blob,
1257                                      sk_sp<SkTextBlob>* cache) {
1258         bool blobWillChange = false;
1259         for (SkTextBlobRunIterator it(blob); !it.done(); it.next()) {
1260             SkTCopyOnFirstWrite<SkFont> filteredFont(it.font());
1261             bool shouldDraw = this->filterFont(&filteredFont);
1262             if (it.font() != *filteredFont || !shouldDraw) {
1263                 blobWillChange = true;
1264                 break;
1265             }
1266         }
1267         if (!blobWillChange) {
1268             return blob;
1269         }
1270 
1271         SkTextBlobBuilder builder;
1272         for (SkTextBlobRunIterator it(blob); !it.done(); it.next()) {
1273             SkTCopyOnFirstWrite<SkFont> filteredFont(it.font());
1274             bool shouldDraw = this->filterFont(&filteredFont);
1275             if (!shouldDraw) {
1276                 continue;
1277             }
1278 
1279             SkFont font = *filteredFont;
1280 
1281             const SkTextBlobBuilder::RunBuffer& runBuffer
1282                 = it.positioning() == SkTextBlobRunIterator::kDefault_Positioning
1283                     ? SkTextBlobBuilderPriv::AllocRunText(&builder, font,
1284                         it.glyphCount(), it.offset().x(),it.offset().y(), it.textSize(), SkString())
1285                 : it.positioning() == SkTextBlobRunIterator::kHorizontal_Positioning
1286                     ? SkTextBlobBuilderPriv::AllocRunTextPosH(&builder, font,
1287                         it.glyphCount(), it.offset().y(), it.textSize(), SkString())
1288                 : it.positioning() == SkTextBlobRunIterator::kFull_Positioning
1289                     ? SkTextBlobBuilderPriv::AllocRunTextPos(&builder, font,
1290                         it.glyphCount(), it.textSize(), SkString())
1291                 : (SkASSERT_RELEASE(false), SkTextBlobBuilder::RunBuffer());
1292             uint32_t glyphCount = it.glyphCount();
1293             if (it.glyphs()) {
1294                 size_t glyphSize = sizeof(decltype(*it.glyphs()));
1295                 memcpy(runBuffer.glyphs, it.glyphs(), glyphCount * glyphSize);
1296             }
1297             if (it.pos()) {
1298                 size_t posSize = sizeof(decltype(*it.pos()));
1299                 uint8_t positioning = it.positioning();
1300                 memcpy(runBuffer.pos, it.pos(), glyphCount * positioning * posSize);
1301             }
1302             if (it.text()) {
1303                 size_t textSize = sizeof(decltype(*it.text()));
1304                 uint32_t textCount = it.textSize();
1305                 memcpy(runBuffer.utf8text, it.text(), textCount * textSize);
1306             }
1307             if (it.clusters()) {
1308                 size_t clusterSize = sizeof(decltype(*it.clusters()));
1309                 memcpy(runBuffer.clusters, it.clusters(), glyphCount * clusterSize);
1310             }
1311         }
1312         *cache = builder.make();
1313         return cache->get();
1314     }
onDrawTextBlob(const SkTextBlob * blob,SkScalar x,SkScalar y,const SkPaint & paint)1315     void onDrawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y,
1316                         const SkPaint& paint) override {
1317         sk_sp<SkTextBlob> cache;
1318         this->SkPaintFilterCanvas::onDrawTextBlob(
1319             this->filterTextBlob(paint, blob, &cache), x, y, paint);
1320     }
filterFont(SkTCopyOnFirstWrite<SkFont> * font) const1321     bool filterFont(SkTCopyOnFirstWrite<SkFont>* font) const {
1322         if (fFontOverrides->fSize) {
1323             font->writable()->setSize(fFont->getSize());
1324         }
1325         if (fFontOverrides->fScaleX) {
1326             font->writable()->setScaleX(fFont->getScaleX());
1327         }
1328         if (fFontOverrides->fSkewX) {
1329             font->writable()->setSkewX(fFont->getSkewX());
1330         }
1331         if (fFontOverrides->fHinting) {
1332             font->writable()->setHinting(fFont->getHinting());
1333         }
1334         if (fFontOverrides->fEdging) {
1335             font->writable()->setEdging(fFont->getEdging());
1336         }
1337         if (fFontOverrides->fEmbolden) {
1338             font->writable()->setEmbolden(fFont->isEmbolden());
1339         }
1340         if (fFontOverrides->fBaselineSnap) {
1341             font->writable()->setBaselineSnap(fFont->isBaselineSnap());
1342         }
1343         if (fFontOverrides->fLinearMetrics) {
1344             font->writable()->setLinearMetrics(fFont->isLinearMetrics());
1345         }
1346         if (fFontOverrides->fSubpixel) {
1347             font->writable()->setSubpixel(fFont->isSubpixel());
1348         }
1349         if (fFontOverrides->fEmbeddedBitmaps) {
1350             font->writable()->setEmbeddedBitmaps(fFont->isEmbeddedBitmaps());
1351         }
1352         if (fFontOverrides->fForceAutoHinting) {
1353             font->writable()->setForceAutoHinting(fFont->isForceAutoHinting());
1354         }
1355 
1356         return true;
1357     }
onFilter(SkPaint & paint) const1358     bool onFilter(SkPaint& paint) const override {
1359         if (fPaintOverrides->fAntiAlias) {
1360             paint.setAntiAlias(fPaint->isAntiAlias());
1361         }
1362         if (fPaintOverrides->fDither) {
1363             paint.setDither(fPaint->isDither());
1364         }
1365         if (fPaintOverrides->fFilterQuality) {
1366             paint.setFilterQuality(fPaint->getFilterQuality());
1367         }
1368         return true;
1369     }
1370     SkPaint* fPaint;
1371     Viewer::SkPaintFields* fPaintOverrides;
1372     SkFont* fFont;
1373     Viewer::SkFontFields* fFontOverrides;
1374 };
1375 
drawSlide(SkSurface * surface)1376 void Viewer::drawSlide(SkSurface* surface) {
1377     if (fCurrentSlide < 0) {
1378         return;
1379     }
1380 
1381     SkAutoCanvasRestore autorestore(surface->getCanvas(), false);
1382 
1383     // By default, we render directly into the window's surface/canvas
1384     SkSurface* slideSurface = surface;
1385     SkCanvas* slideCanvas = surface->getCanvas();
1386     fLastImage.reset();
1387 
1388     // If we're in any of the color managed modes, construct the color space we're going to use
1389     sk_sp<SkColorSpace> colorSpace = nullptr;
1390     if (ColorMode::kLegacy != fColorMode) {
1391         skcms_Matrix3x3 toXYZ;
1392         SkAssertResult(fColorSpacePrimaries.toXYZD50(&toXYZ));
1393         colorSpace = SkColorSpace::MakeRGB(fColorSpaceTransferFn, toXYZ);
1394     }
1395 
1396     if (fSaveToSKP) {
1397         SkPictureRecorder recorder;
1398         SkCanvas* recorderCanvas = recorder.beginRecording(
1399                 SkRect::Make(fSlides[fCurrentSlide]->getDimensions()));
1400         fSlides[fCurrentSlide]->draw(recorderCanvas);
1401         sk_sp<SkPicture> picture(recorder.finishRecordingAsPicture());
1402         SkFILEWStream stream("sample_app.skp");
1403         picture->serialize(&stream);
1404         fSaveToSKP = false;
1405     }
1406 
1407     // Grab some things we'll need to make surfaces (for tiling or general offscreen rendering)
1408     SkColorType colorType;
1409     switch (fColorMode) {
1410         case ColorMode::kLegacy:
1411         case ColorMode::kColorManaged8888:
1412             colorType = kN32_SkColorType;
1413             break;
1414         case ColorMode::kColorManagedF16:
1415             colorType = kRGBA_F16_SkColorType;
1416             break;
1417         case ColorMode::kColorManagedF16Norm:
1418             colorType = kRGBA_F16Norm_SkColorType;
1419             break;
1420     }
1421 
1422     auto make_surface = [=](int w, int h) {
1423         SkSurfaceProps props(fWindow->getRequestedDisplayParams().fSurfaceProps);
1424         slideCanvas->getProps(&props);
1425 
1426         SkImageInfo info = SkImageInfo::Make(w, h, colorType, kPremul_SkAlphaType, colorSpace);
1427         return Window::kRaster_BackendType == this->fBackendType
1428                 ? SkSurface::MakeRaster(info, &props)
1429                 : slideCanvas->makeSurface(info, &props);
1430     };
1431 
1432     // We need to render offscreen if we're...
1433     // ... in fake perspective or zooming (so we have a snapped copy of the results)
1434     // ... in any raster mode, because the window surface is actually GL
1435     // ... in any color managed mode, because we always make the window surface with no color space
1436     // ... or if the user explicitly requested offscreen rendering
1437     sk_sp<SkSurface> offscreenSurface = nullptr;
1438     if (kPerspective_Fake == fPerspectiveMode ||
1439         fShowZoomWindow ||
1440         Window::kRaster_BackendType == fBackendType ||
1441         colorSpace != nullptr ||
1442         FLAGS_offscreen) {
1443 
1444         offscreenSurface = make_surface(fWindow->width(), fWindow->height());
1445         slideSurface = offscreenSurface.get();
1446         slideCanvas = offscreenSurface->getCanvas();
1447     }
1448 
1449     SkPictureRecorder recorder;
1450     SkCanvas* recorderRestoreCanvas = nullptr;
1451     if (fDrawViaSerialize) {
1452         recorderRestoreCanvas = slideCanvas;
1453         slideCanvas = recorder.beginRecording(
1454                 SkRect::Make(fSlides[fCurrentSlide]->getDimensions()));
1455     }
1456 
1457     int count = slideCanvas->save();
1458     slideCanvas->clear(SK_ColorWHITE);
1459     // Time the painting logic of the slide
1460     fStatsLayer.beginTiming(fPaintTimer);
1461     if (fTiled) {
1462         int tileW = SkScalarCeilToInt(fWindow->width() * fTileScale.width());
1463         int tileH = SkScalarCeilToInt(fWindow->height() * fTileScale.height());
1464         for (int y = 0; y < fWindow->height(); y += tileH) {
1465             for (int x = 0; x < fWindow->width(); x += tileW) {
1466                 SkAutoCanvasRestore acr(slideCanvas, true);
1467                 slideCanvas->clipRect(SkRect::MakeXYWH(x, y, tileW, tileH));
1468                 fSlides[fCurrentSlide]->draw(slideCanvas);
1469             }
1470         }
1471 
1472         // Draw borders between tiles
1473         if (fDrawTileBoundaries) {
1474             SkPaint border;
1475             border.setColor(0x60FF00FF);
1476             border.setStyle(SkPaint::kStroke_Style);
1477             for (int y = 0; y < fWindow->height(); y += tileH) {
1478                 for (int x = 0; x < fWindow->width(); x += tileW) {
1479                     slideCanvas->drawRect(SkRect::MakeXYWH(x, y, tileW, tileH), border);
1480                 }
1481             }
1482         }
1483     } else {
1484         slideCanvas->concat(this->computeMatrix());
1485         if (kPerspective_Real == fPerspectiveMode) {
1486             slideCanvas->clipRect(SkRect::MakeWH(fWindow->width(), fWindow->height()));
1487         }
1488         OveridePaintFilterCanvas filterCanvas(slideCanvas, &fPaint, &fPaintOverrides, &fFont, &fFontOverrides);
1489         fSlides[fCurrentSlide]->draw(&filterCanvas);
1490     }
1491     fStatsLayer.endTiming(fPaintTimer);
1492     slideCanvas->restoreToCount(count);
1493 
1494     if (recorderRestoreCanvas) {
1495         sk_sp<SkPicture> picture(recorder.finishRecordingAsPicture());
1496         auto data = picture->serialize();
1497         slideCanvas = recorderRestoreCanvas;
1498         slideCanvas->drawPicture(SkPicture::MakeFromData(data.get()));
1499     }
1500 
1501     // Force a flush so we can time that, too
1502     fStatsLayer.beginTiming(fFlushTimer);
1503     slideSurface->flushAndSubmit();
1504     fStatsLayer.endTiming(fFlushTimer);
1505 
1506     // If we rendered offscreen, snap an image and push the results to the window's canvas
1507     if (offscreenSurface) {
1508         fLastImage = offscreenSurface->makeImageSnapshot();
1509 
1510         SkCanvas* canvas = surface->getCanvas();
1511         SkPaint paint;
1512         paint.setBlendMode(SkBlendMode::kSrc);
1513         int prePerspectiveCount = canvas->save();
1514         if (kPerspective_Fake == fPerspectiveMode) {
1515             paint.setFilterQuality(kHigh_SkFilterQuality);
1516             canvas->clear(SK_ColorWHITE);
1517             canvas->concat(this->computePerspectiveMatrix());
1518         }
1519         canvas->drawImage(fLastImage, 0, 0, &paint);
1520         canvas->restoreToCount(prePerspectiveCount);
1521     }
1522 
1523     if (fShowSlideDimensions) {
1524         SkRect r = SkRect::Make(fSlides[fCurrentSlide]->getDimensions());
1525         SkPaint paint;
1526         paint.setColor(0x40FFFF00);
1527         surface->getCanvas()->drawRect(r, paint);
1528     }
1529 }
1530 
onBackendCreated()1531 void Viewer::onBackendCreated() {
1532     this->setupCurrentSlide();
1533     fWindow->show();
1534 }
1535 
onPaint(SkSurface * surface)1536 void Viewer::onPaint(SkSurface* surface) {
1537     this->drawSlide(surface);
1538 
1539     fCommands.drawHelp(surface->getCanvas());
1540 
1541     this->drawImGui();
1542 
1543     fLastImage.reset();
1544 
1545     if (auto direct = fWindow->directContext()) {
1546         // Clean out cache items that haven't been used in more than 10 seconds.
1547         direct->performDeferredCleanup(std::chrono::seconds(10));
1548     }
1549 }
1550 
onResize(int width,int height)1551 void Viewer::onResize(int width, int height) {
1552     if (fCurrentSlide >= 0) {
1553         fSlides[fCurrentSlide]->resize(width, height);
1554     }
1555 }
1556 
mapEvent(float x,float y)1557 SkPoint Viewer::mapEvent(float x, float y) {
1558     const auto m = this->computeMatrix();
1559     SkMatrix inv;
1560 
1561     SkAssertResult(m.invert(&inv));
1562 
1563     return inv.mapXY(x, y);
1564 }
1565 
onTouch(intptr_t owner,skui::InputState state,float x,float y)1566 bool Viewer::onTouch(intptr_t owner, skui::InputState state, float x, float y) {
1567     if (GestureDevice::kMouse == fGestureDevice) {
1568         return false;
1569     }
1570 
1571     const auto slidePt = this->mapEvent(x, y);
1572     if (fSlides[fCurrentSlide]->onMouse(slidePt.x(), slidePt.y(), state, skui::ModifierKey::kNone)) {
1573         fWindow->inval();
1574         return true;
1575     }
1576 
1577     void* castedOwner = reinterpret_cast<void*>(owner);
1578     switch (state) {
1579         case skui::InputState::kUp: {
1580             fGesture.touchEnd(castedOwner);
1581 #if defined(SK_BUILD_FOR_IOS)
1582             // TODO: move IOS swipe detection higher up into the platform code
1583             SkPoint dir;
1584             if (fGesture.isFling(&dir)) {
1585                 // swiping left or right
1586                 if (SkTAbs(dir.fX) > SkTAbs(dir.fY)) {
1587                     if (dir.fX < 0) {
1588                         this->setCurrentSlide(fCurrentSlide < fSlides.count() - 1 ?
1589                                               fCurrentSlide + 1 : 0);
1590                     } else {
1591                         this->setCurrentSlide(fCurrentSlide > 0 ?
1592                                               fCurrentSlide - 1 : fSlides.count() - 1);
1593                     }
1594                 }
1595                 fGesture.reset();
1596             }
1597 #endif
1598             break;
1599         }
1600         case skui::InputState::kDown: {
1601             fGesture.touchBegin(castedOwner, x, y);
1602             break;
1603         }
1604         case skui::InputState::kMove: {
1605             fGesture.touchMoved(castedOwner, x, y);
1606             break;
1607         }
1608         default: {
1609             // kLeft and kRight are only for swipes
1610             SkASSERT(false);
1611             break;
1612         }
1613     }
1614     fGestureDevice = fGesture.isBeingTouched() ? GestureDevice::kTouch : GestureDevice::kNone;
1615     fWindow->inval();
1616     return true;
1617 }
1618 
onMouse(int x,int y,skui::InputState state,skui::ModifierKey modifiers)1619 bool Viewer::onMouse(int x, int y, skui::InputState state, skui::ModifierKey modifiers) {
1620     if (GestureDevice::kTouch == fGestureDevice) {
1621         return false;
1622     }
1623 
1624     const auto slidePt = this->mapEvent(x, y);
1625     if (fSlides[fCurrentSlide]->onMouse(slidePt.x(), slidePt.y(), state, modifiers)) {
1626         fWindow->inval();
1627         return true;
1628     }
1629 
1630     switch (state) {
1631         case skui::InputState::kUp: {
1632             fGesture.touchEnd(nullptr);
1633             break;
1634         }
1635         case skui::InputState::kDown: {
1636             fGesture.touchBegin(nullptr, x, y);
1637             break;
1638         }
1639         case skui::InputState::kMove: {
1640             fGesture.touchMoved(nullptr, x, y);
1641             break;
1642         }
1643         default: {
1644             SkASSERT(false); // shouldn't see kRight or kLeft here
1645             break;
1646         }
1647     }
1648     fGestureDevice = fGesture.isBeingTouched() ? GestureDevice::kMouse : GestureDevice::kNone;
1649 
1650     if (state != skui::InputState::kMove || fGesture.isBeingTouched()) {
1651         fWindow->inval();
1652     }
1653     return true;
1654 }
1655 
onFling(skui::InputState state)1656 bool Viewer::onFling(skui::InputState state) {
1657     if (skui::InputState::kRight == state) {
1658         this->setCurrentSlide(fCurrentSlide > 0 ? fCurrentSlide - 1 : fSlides.count() - 1);
1659         return true;
1660     } else if (skui::InputState::kLeft == state) {
1661         this->setCurrentSlide(fCurrentSlide < fSlides.count() - 1 ? fCurrentSlide + 1 : 0);
1662         return true;
1663     }
1664     return false;
1665 }
1666 
onPinch(skui::InputState state,float scale,float x,float y)1667 bool Viewer::onPinch(skui::InputState state, float scale, float x, float y) {
1668     switch (state) {
1669         case skui::InputState::kDown:
1670             fGesture.startZoom();
1671             return true;
1672             break;
1673         case skui::InputState::kMove:
1674             fGesture.updateZoom(scale, x, y, x, y);
1675             return true;
1676             break;
1677         case skui::InputState::kUp:
1678             fGesture.endZoom();
1679             return true;
1680             break;
1681         default:
1682             SkASSERT(false);
1683             break;
1684     }
1685 
1686     return false;
1687 }
1688 
ImGui_Primaries(SkColorSpacePrimaries * primaries,SkPaint * gamutPaint)1689 static void ImGui_Primaries(SkColorSpacePrimaries* primaries, SkPaint* gamutPaint) {
1690     // The gamut image covers a (0.8 x 0.9) shaped region
1691     ImGui::DragCanvas dc(primaries, { 0.0f, 0.9f }, { 0.8f, 0.0f });
1692 
1693     // Background image. Only draw a subset of the image, to avoid the regions less than zero.
1694     // Simplifes re-mapping math, clipping behavior, and increases resolution in the useful area.
1695     // Magic numbers are pixel locations of the origin and upper-right corner.
1696     dc.fDrawList->AddImage(gamutPaint, dc.fPos,
1697                            ImVec2(dc.fPos.x + dc.fSize.x, dc.fPos.y + dc.fSize.y),
1698                            ImVec2(242, 61), ImVec2(1897, 1922));
1699 
1700     dc.dragPoint((SkPoint*)(&primaries->fRX), true, 0xFF000040);
1701     dc.dragPoint((SkPoint*)(&primaries->fGX), true, 0xFF004000);
1702     dc.dragPoint((SkPoint*)(&primaries->fBX), true, 0xFF400000);
1703     dc.dragPoint((SkPoint*)(&primaries->fWX), true);
1704     dc.fDrawList->AddPolyline(dc.fScreenPoints.begin(), 3, 0xFFFFFFFF, true, 1.5f);
1705 }
1706 
ImGui_DragLocation(SkPoint * pt)1707 static bool ImGui_DragLocation(SkPoint* pt) {
1708     ImGui::DragCanvas dc(pt);
1709     dc.fillColor(IM_COL32(0, 0, 0, 128));
1710     dc.dragPoint(pt);
1711     return dc.fDragging;
1712 }
1713 
ImGui_DragQuad(SkPoint * pts)1714 static bool ImGui_DragQuad(SkPoint* pts) {
1715     ImGui::DragCanvas dc(pts);
1716     dc.fillColor(IM_COL32(0, 0, 0, 128));
1717 
1718     for (int i = 0; i < 4; ++i) {
1719         dc.dragPoint(pts + i);
1720     }
1721 
1722     dc.fDrawList->AddLine(dc.fScreenPoints[0], dc.fScreenPoints[1], 0xFFFFFFFF);
1723     dc.fDrawList->AddLine(dc.fScreenPoints[1], dc.fScreenPoints[3], 0xFFFFFFFF);
1724     dc.fDrawList->AddLine(dc.fScreenPoints[3], dc.fScreenPoints[2], 0xFFFFFFFF);
1725     dc.fDrawList->AddLine(dc.fScreenPoints[2], dc.fScreenPoints[0], 0xFFFFFFFF);
1726 
1727     return dc.fDragging;
1728 }
1729 
build_sksl_highlight_shader()1730 static SkSL::String build_sksl_highlight_shader() {
1731     return SkSL::String("out half4 sk_FragColor;\n"
1732                         "void main() { sk_FragColor = half4(1, 0, 1, 0.5); }");
1733 }
1734 
build_metal_highlight_shader(const SkSL::String & inShader)1735 static SkSL::String build_metal_highlight_shader(const SkSL::String& inShader) {
1736     // Metal fragment shaders need a lot of non-trivial boilerplate that we don't want to recompute
1737     // here. So keep all shader code, but right before `return *_out;`, swap out the sk_FragColor.
1738     size_t pos = inShader.rfind("return *_out;\n");
1739     if (pos == std::string::npos) {
1740         return inShader;
1741     }
1742 
1743     SkSL::String replacementShader = inShader;
1744     replacementShader.insert(pos, "_out->sk_FragColor = float4(1.0, 0.0, 1.0, 0.5); ");
1745     return replacementShader;
1746 }
1747 
build_glsl_highlight_shader(const GrShaderCaps & shaderCaps)1748 static SkSL::String build_glsl_highlight_shader(const GrShaderCaps& shaderCaps) {
1749     const char* versionDecl = shaderCaps.versionDeclString();
1750     SkSL::String highlight = versionDecl ? versionDecl : "";
1751     if (shaderCaps.usesPrecisionModifiers()) {
1752         highlight.append("precision mediump float;\n");
1753     }
1754     highlight.appendf("out vec4 sk_FragColor;\n"
1755                       "void main() { sk_FragColor = vec4(1, 0, 1, 0.5); }");
1756     return highlight;
1757 }
1758 
drawImGui()1759 void Viewer::drawImGui() {
1760     // Support drawing the ImGui demo window. Superfluous, but gives a good idea of what's possible
1761     if (fShowImGuiTestWindow) {
1762         ImGui::ShowDemoWindow(&fShowImGuiTestWindow);
1763     }
1764 
1765     if (fShowImGuiDebugWindow) {
1766         // We have some dynamic content that sizes to fill available size. If the scroll bar isn't
1767         // always visible, we can end up in a layout feedback loop.
1768         ImGui::SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
1769         DisplayParams params = fWindow->getRequestedDisplayParams();
1770         bool paramsChanged = false;
1771         auto ctx = fWindow->directContext();
1772 
1773         if (ImGui::Begin("Tools", &fShowImGuiDebugWindow,
1774                          ImGuiWindowFlags_AlwaysVerticalScrollbar)) {
1775             if (ImGui::CollapsingHeader("Backend")) {
1776                 int newBackend = static_cast<int>(fBackendType);
1777                 ImGui::RadioButton("Raster", &newBackend, sk_app::Window::kRaster_BackendType);
1778                 ImGui::SameLine();
1779                 ImGui::RadioButton("OpenGL", &newBackend, sk_app::Window::kNativeGL_BackendType);
1780 #if SK_ANGLE && defined(SK_BUILD_FOR_WIN)
1781                 ImGui::SameLine();
1782                 ImGui::RadioButton("ANGLE", &newBackend, sk_app::Window::kANGLE_BackendType);
1783 #endif
1784 #if defined(SK_DAWN)
1785                 ImGui::SameLine();
1786                 ImGui::RadioButton("Dawn", &newBackend, sk_app::Window::kDawn_BackendType);
1787 #endif
1788 #if defined(SK_VULKAN)
1789                 ImGui::SameLine();
1790                 ImGui::RadioButton("Vulkan", &newBackend, sk_app::Window::kVulkan_BackendType);
1791 #endif
1792 #if defined(SK_METAL)
1793                 ImGui::SameLine();
1794                 ImGui::RadioButton("Metal", &newBackend, sk_app::Window::kMetal_BackendType);
1795 #endif
1796 #if defined(SK_DIRECT3D)
1797                 ImGui::SameLine();
1798                 ImGui::RadioButton("Direct3D", &newBackend, sk_app::Window::kDirect3D_BackendType);
1799 #endif
1800                 if (newBackend != fBackendType) {
1801                     fDeferredActions.push_back([=]() {
1802                         this->setBackend(static_cast<sk_app::Window::BackendType>(newBackend));
1803                     });
1804                 }
1805 
1806                 bool* wire = &params.fGrContextOptions.fWireframeMode;
1807                 if (ctx && ImGui::Checkbox("Wireframe Mode", wire)) {
1808                     paramsChanged = true;
1809                 }
1810 
1811                 if (ctx) {
1812                     // Determine the context's max sample count for MSAA radio buttons.
1813                     int sampleCount = fWindow->sampleCount();
1814                     int maxMSAA = (fBackendType != sk_app::Window::kRaster_BackendType) ?
1815                             ctx->maxSurfaceSampleCountForColorType(kRGBA_8888_SkColorType) :
1816                             1;
1817 
1818                     // Only display the MSAA radio buttons when there are options above 1x MSAA.
1819                     if (maxMSAA >= 4) {
1820                         ImGui::Text("MSAA: ");
1821 
1822                         for (int curMSAA = 1; curMSAA <= maxMSAA; curMSAA *= 2) {
1823                             // 2x MSAA works, but doesn't offer much of a visual improvement, so we
1824                             // don't show it in the list.
1825                             if (curMSAA == 2) {
1826                                 continue;
1827                             }
1828                             ImGui::SameLine();
1829                             ImGui::RadioButton(SkStringPrintf("%d", curMSAA).c_str(),
1830                                                &sampleCount, curMSAA);
1831                         }
1832                     }
1833 
1834                     if (sampleCount != params.fMSAASampleCount) {
1835                         params.fMSAASampleCount = sampleCount;
1836                         paramsChanged = true;
1837                     }
1838                 }
1839 
1840                 int pixelGeometryIdx = 0;
1841                 if (fDisplayOverrides.fSurfaceProps.fPixelGeometry) {
1842                     pixelGeometryIdx = params.fSurfaceProps.pixelGeometry() + 1;
1843                 }
1844                 if (ImGui::Combo("Pixel Geometry", &pixelGeometryIdx,
1845                                  "Default\0Flat\0RGB\0BGR\0RGBV\0BGRV\0\0"))
1846                 {
1847                     uint32_t flags = params.fSurfaceProps.flags();
1848                     if (pixelGeometryIdx == 0) {
1849                         fDisplayOverrides.fSurfaceProps.fPixelGeometry = false;
1850                         SkPixelGeometry pixelGeometry = fDisplay.fSurfaceProps.pixelGeometry();
1851                         params.fSurfaceProps = SkSurfaceProps(flags, pixelGeometry);
1852                     } else {
1853                         fDisplayOverrides.fSurfaceProps.fPixelGeometry = true;
1854                         SkPixelGeometry pixelGeometry = SkTo<SkPixelGeometry>(pixelGeometryIdx - 1);
1855                         params.fSurfaceProps = SkSurfaceProps(flags, pixelGeometry);
1856                     }
1857                     paramsChanged = true;
1858                 }
1859 
1860                 bool useDFT = params.fSurfaceProps.isUseDeviceIndependentFonts();
1861                 if (ImGui::Checkbox("DFT", &useDFT)) {
1862                     uint32_t flags = params.fSurfaceProps.flags();
1863                     if (useDFT) {
1864                         flags |= SkSurfaceProps::kUseDeviceIndependentFonts_Flag;
1865                     } else {
1866                         flags &= ~SkSurfaceProps::kUseDeviceIndependentFonts_Flag;
1867                     }
1868                     SkPixelGeometry pixelGeometry = params.fSurfaceProps.pixelGeometry();
1869                     params.fSurfaceProps = SkSurfaceProps(flags, pixelGeometry);
1870                     paramsChanged = true;
1871                 }
1872 
1873                 if (ImGui::TreeNode("Path Renderers")) {
1874                     GpuPathRenderers prevPr = params.fGrContextOptions.fGpuPathRenderers;
1875                     auto prButton = [&](GpuPathRenderers x) {
1876                         if (ImGui::RadioButton(gPathRendererNames[x].c_str(), prevPr == x)) {
1877                             if (x != params.fGrContextOptions.fGpuPathRenderers) {
1878                                 params.fGrContextOptions.fGpuPathRenderers = x;
1879                                 paramsChanged = true;
1880                             }
1881                         }
1882                     };
1883 
1884                     if (!ctx) {
1885                         ImGui::RadioButton("Software", true);
1886                     } else {
1887                         const auto* caps = ctx->priv().caps();
1888                         prButton(GpuPathRenderers::kDefault);
1889                         if (fWindow->sampleCount() > 1 || caps->mixedSamplesSupport()) {
1890                             if (caps->shaderCaps()->tessellationSupport()) {
1891                                 prButton(GpuPathRenderers::kTessellation);
1892                             }
1893                             if (caps->shaderCaps()->pathRenderingSupport()) {
1894                                 prButton(GpuPathRenderers::kStencilAndCover);
1895                             }
1896                         }
1897                         if (1 == fWindow->sampleCount()) {
1898                             if (GrCoverageCountingPathRenderer::IsSupported(*caps)) {
1899                                 prButton(GpuPathRenderers::kCoverageCounting);
1900                             }
1901                             prButton(GpuPathRenderers::kSmall);
1902                         }
1903                         prButton(GpuPathRenderers::kTriangulating);
1904                         prButton(GpuPathRenderers::kNone);
1905                     }
1906                     ImGui::TreePop();
1907                 }
1908             }
1909 
1910             if (ImGui::CollapsingHeader("Tiling")) {
1911                 ImGui::Checkbox("Enable", &fTiled);
1912                 ImGui::Checkbox("Draw Boundaries", &fDrawTileBoundaries);
1913                 ImGui::SliderFloat("Horizontal", &fTileScale.fWidth, 0.1f, 1.0f);
1914                 ImGui::SliderFloat("Vertical", &fTileScale.fHeight, 0.1f, 1.0f);
1915             }
1916 
1917             if (ImGui::CollapsingHeader("Transform")) {
1918                 float zoom = fZoomLevel;
1919                 if (ImGui::SliderFloat("Zoom", &zoom, MIN_ZOOM_LEVEL, MAX_ZOOM_LEVEL)) {
1920                     fZoomLevel = zoom;
1921                     this->preTouchMatrixChanged();
1922                     paramsChanged = true;
1923                 }
1924                 float deg = fRotation;
1925                 if (ImGui::SliderFloat("Rotate", &deg, -30, 360, "%.3f deg")) {
1926                     fRotation = deg;
1927                     this->preTouchMatrixChanged();
1928                     paramsChanged = true;
1929                 }
1930                 if (ImGui::CollapsingHeader("Subpixel offset", ImGuiTreeNodeFlags_NoTreePushOnOpen)) {
1931                     if (ImGui_DragLocation(&fOffset)) {
1932                         this->preTouchMatrixChanged();
1933                         paramsChanged = true;
1934                     }
1935                 } else if (fOffset != SkVector{0.5f, 0.5f}) {
1936                     this->preTouchMatrixChanged();
1937                     paramsChanged = true;
1938                     fOffset = {0.5f, 0.5f};
1939                 }
1940                 int perspectiveMode = static_cast<int>(fPerspectiveMode);
1941                 if (ImGui::Combo("Perspective", &perspectiveMode, "Off\0Real\0Fake\0\0")) {
1942                     fPerspectiveMode = static_cast<PerspectiveMode>(perspectiveMode);
1943                     this->preTouchMatrixChanged();
1944                     paramsChanged = true;
1945                 }
1946                 if (perspectiveMode != kPerspective_Off && ImGui_DragQuad(fPerspectivePoints)) {
1947                     this->preTouchMatrixChanged();
1948                     paramsChanged = true;
1949                 }
1950             }
1951 
1952             if (ImGui::CollapsingHeader("Paint")) {
1953                 int aliasIdx = 0;
1954                 if (fPaintOverrides.fAntiAlias) {
1955                     aliasIdx = SkTo<int>(fPaintOverrides.fAntiAliasState) + 1;
1956                 }
1957                 if (ImGui::Combo("Anti-Alias", &aliasIdx,
1958                                  "Default\0Alias\0Normal\0AnalyticAAEnabled\0AnalyticAAForced\0\0"))
1959                 {
1960                     gSkUseAnalyticAA = fPaintOverrides.fOriginalSkUseAnalyticAA;
1961                     gSkForceAnalyticAA = fPaintOverrides.fOriginalSkForceAnalyticAA;
1962                     if (aliasIdx == 0) {
1963                         fPaintOverrides.fAntiAliasState = SkPaintFields::AntiAliasState::Alias;
1964                         fPaintOverrides.fAntiAlias = false;
1965                     } else {
1966                         fPaintOverrides.fAntiAlias = true;
1967                         fPaintOverrides.fAntiAliasState = SkTo<SkPaintFields::AntiAliasState>(aliasIdx-1);
1968                         fPaint.setAntiAlias(aliasIdx > 1);
1969                         switch (fPaintOverrides.fAntiAliasState) {
1970                             case SkPaintFields::AntiAliasState::Alias:
1971                                 break;
1972                             case SkPaintFields::AntiAliasState::Normal:
1973                                 break;
1974                             case SkPaintFields::AntiAliasState::AnalyticAAEnabled:
1975                                 gSkUseAnalyticAA = true;
1976                                 gSkForceAnalyticAA = false;
1977                                 break;
1978                             case SkPaintFields::AntiAliasState::AnalyticAAForced:
1979                                 gSkUseAnalyticAA = gSkForceAnalyticAA = true;
1980                                 break;
1981                         }
1982                     }
1983                     paramsChanged = true;
1984                 }
1985 
1986                 auto paintFlag = [this, &paramsChanged](const char* label, const char* items,
1987                                                         bool SkPaintFields::* flag,
1988                                                         bool (SkPaint::* isFlag)() const,
1989                                                         void (SkPaint::* setFlag)(bool) )
1990                 {
1991                     int itemIndex = 0;
1992                     if (fPaintOverrides.*flag) {
1993                         itemIndex = (fPaint.*isFlag)() ? 2 : 1;
1994                     }
1995                     if (ImGui::Combo(label, &itemIndex, items)) {
1996                         if (itemIndex == 0) {
1997                             fPaintOverrides.*flag = false;
1998                         } else {
1999                             fPaintOverrides.*flag = true;
2000                             (fPaint.*setFlag)(itemIndex == 2);
2001                         }
2002                         paramsChanged = true;
2003                     }
2004                 };
2005 
2006                 paintFlag("Dither",
2007                           "Default\0No Dither\0Dither\0\0",
2008                           &SkPaintFields::fDither,
2009                           &SkPaint::isDither, &SkPaint::setDither);
2010 
2011                 int filterQualityIdx = 0;
2012                 if (fPaintOverrides.fFilterQuality) {
2013                     filterQualityIdx = SkTo<int>(fPaint.getFilterQuality()) + 1;
2014                 }
2015                 if (ImGui::Combo("Filter Quality", &filterQualityIdx,
2016                                  "Default\0None\0Low\0Medium\0High\0\0"))
2017                 {
2018                     if (filterQualityIdx == 0) {
2019                         fPaintOverrides.fFilterQuality = false;
2020                         fPaint.setFilterQuality(kNone_SkFilterQuality);
2021                     } else {
2022                         fPaint.setFilterQuality(SkTo<SkFilterQuality>(filterQualityIdx - 1));
2023                         fPaintOverrides.fFilterQuality = true;
2024                     }
2025                     paramsChanged = true;
2026                 }
2027             }
2028 
2029             if (ImGui::CollapsingHeader("Font")) {
2030                 int hintingIdx = 0;
2031                 if (fFontOverrides.fHinting) {
2032                     hintingIdx = SkTo<int>(fFont.getHinting()) + 1;
2033                 }
2034                 if (ImGui::Combo("Hinting", &hintingIdx,
2035                                  "Default\0None\0Slight\0Normal\0Full\0\0"))
2036                 {
2037                     if (hintingIdx == 0) {
2038                         fFontOverrides.fHinting = false;
2039                         fFont.setHinting(SkFontHinting::kNone);
2040                     } else {
2041                         fFont.setHinting(SkTo<SkFontHinting>(hintingIdx - 1));
2042                         fFontOverrides.fHinting = true;
2043                     }
2044                     paramsChanged = true;
2045                 }
2046 
2047                 auto fontFlag = [this, &paramsChanged](const char* label, const char* items,
2048                                                        bool SkFontFields::* flag,
2049                                                        bool (SkFont::* isFlag)() const,
2050                                                        void (SkFont::* setFlag)(bool) )
2051                 {
2052                     int itemIndex = 0;
2053                     if (fFontOverrides.*flag) {
2054                         itemIndex = (fFont.*isFlag)() ? 2 : 1;
2055                     }
2056                     if (ImGui::Combo(label, &itemIndex, items)) {
2057                         if (itemIndex == 0) {
2058                             fFontOverrides.*flag = false;
2059                         } else {
2060                             fFontOverrides.*flag = true;
2061                             (fFont.*setFlag)(itemIndex == 2);
2062                         }
2063                         paramsChanged = true;
2064                     }
2065                 };
2066 
2067                 fontFlag("Fake Bold Glyphs",
2068                          "Default\0No Fake Bold\0Fake Bold\0\0",
2069                          &SkFontFields::fEmbolden,
2070                          &SkFont::isEmbolden, &SkFont::setEmbolden);
2071 
2072                 fontFlag("Baseline Snapping",
2073                          "Default\0No Baseline Snapping\0Baseline Snapping\0\0",
2074                          &SkFontFields::fBaselineSnap,
2075                          &SkFont::isBaselineSnap, &SkFont::setBaselineSnap);
2076 
2077                 fontFlag("Linear Text",
2078                          "Default\0No Linear Text\0Linear Text\0\0",
2079                          &SkFontFields::fLinearMetrics,
2080                          &SkFont::isLinearMetrics, &SkFont::setLinearMetrics);
2081 
2082                 fontFlag("Subpixel Position Glyphs",
2083                          "Default\0Pixel Text\0Subpixel Text\0\0",
2084                          &SkFontFields::fSubpixel,
2085                          &SkFont::isSubpixel, &SkFont::setSubpixel);
2086 
2087                 fontFlag("Embedded Bitmap Text",
2088                          "Default\0No Embedded Bitmaps\0Embedded Bitmaps\0\0",
2089                          &SkFontFields::fEmbeddedBitmaps,
2090                          &SkFont::isEmbeddedBitmaps, &SkFont::setEmbeddedBitmaps);
2091 
2092                 fontFlag("Force Auto-Hinting",
2093                          "Default\0No Force Auto-Hinting\0Force Auto-Hinting\0\0",
2094                          &SkFontFields::fForceAutoHinting,
2095                          &SkFont::isForceAutoHinting, &SkFont::setForceAutoHinting);
2096 
2097                 int edgingIdx = 0;
2098                 if (fFontOverrides.fEdging) {
2099                     edgingIdx = SkTo<int>(fFont.getEdging()) + 1;
2100                 }
2101                 if (ImGui::Combo("Edging", &edgingIdx,
2102                                  "Default\0Alias\0Antialias\0Subpixel Antialias\0\0"))
2103                 {
2104                     if (edgingIdx == 0) {
2105                         fFontOverrides.fEdging = false;
2106                         fFont.setEdging(SkFont::Edging::kAlias);
2107                     } else {
2108                         fFont.setEdging(SkTo<SkFont::Edging>(edgingIdx-1));
2109                         fFontOverrides.fEdging = true;
2110                     }
2111                     paramsChanged = true;
2112                 }
2113 
2114                 ImGui::Checkbox("Override Size", &fFontOverrides.fSize);
2115                 if (fFontOverrides.fSize) {
2116                     ImGui::DragFloat2("TextRange", fFontOverrides.fSizeRange,
2117                                       0.001f, -10.0f, 300.0f, "%.6f", 2.0f);
2118                     float textSize = fFont.getSize();
2119                     if (ImGui::DragFloat("TextSize", &textSize, 0.001f,
2120                                          fFontOverrides.fSizeRange[0],
2121                                          fFontOverrides.fSizeRange[1],
2122                                          "%.6f", 2.0f))
2123                     {
2124                         fFont.setSize(textSize);
2125                         paramsChanged = true;
2126                     }
2127                 }
2128 
2129                 ImGui::Checkbox("Override ScaleX", &fFontOverrides.fScaleX);
2130                 if (fFontOverrides.fScaleX) {
2131                     float scaleX = fFont.getScaleX();
2132                     if (ImGui::SliderFloat("ScaleX", &scaleX, MIN_ZOOM_LEVEL, MAX_ZOOM_LEVEL)) {
2133                         fFont.setScaleX(scaleX);
2134                         paramsChanged = true;
2135                     }
2136                 }
2137 
2138                 ImGui::Checkbox("Override SkewX", &fFontOverrides.fSkewX);
2139                 if (fFontOverrides.fSkewX) {
2140                     float skewX = fFont.getSkewX();
2141                     if (ImGui::SliderFloat("SkewX", &skewX, MIN_ZOOM_LEVEL, MAX_ZOOM_LEVEL)) {
2142                         fFont.setSkewX(skewX);
2143                         paramsChanged = true;
2144                     }
2145                 }
2146             }
2147 
2148             {
2149                 SkMetaData controls;
2150                 if (fSlides[fCurrentSlide]->onGetControls(&controls)) {
2151                     if (ImGui::CollapsingHeader("Current Slide")) {
2152                         SkMetaData::Iter iter(controls);
2153                         const char* name;
2154                         SkMetaData::Type type;
2155                         int count;
2156                         while ((name = iter.next(&type, &count)) != nullptr) {
2157                             if (type == SkMetaData::kScalar_Type) {
2158                                 float val[3];
2159                                 SkASSERT(count == 3);
2160                                 controls.findScalars(name, &count, val);
2161                                 if (ImGui::SliderFloat(name, &val[0], val[1], val[2])) {
2162                                     controls.setScalars(name, 3, val);
2163                                 }
2164                             } else if (type == SkMetaData::kBool_Type) {
2165                                 bool val;
2166                                 SkASSERT(count == 1);
2167                                 controls.findBool(name, &val);
2168                                 if (ImGui::Checkbox(name, &val)) {
2169                                     controls.setBool(name, val);
2170                                 }
2171                             }
2172                         }
2173                         fSlides[fCurrentSlide]->onSetControls(controls);
2174                     }
2175                 }
2176             }
2177 
2178             if (fShowSlidePicker) {
2179                 ImGui::SetNextTreeNodeOpen(true);
2180             }
2181             if (ImGui::CollapsingHeader("Slide")) {
2182                 static ImGuiTextFilter filter;
2183                 static ImVector<const char*> filteredSlideNames;
2184                 static ImVector<int> filteredSlideIndices;
2185 
2186                 if (fShowSlidePicker) {
2187                     ImGui::SetKeyboardFocusHere();
2188                     fShowSlidePicker = false;
2189                 }
2190 
2191                 filter.Draw();
2192                 filteredSlideNames.clear();
2193                 filteredSlideIndices.clear();
2194                 int filteredIndex = 0;
2195                 for (int i = 0; i < fSlides.count(); ++i) {
2196                     const char* slideName = fSlides[i]->getName().c_str();
2197                     if (filter.PassFilter(slideName) || i == fCurrentSlide) {
2198                         if (i == fCurrentSlide) {
2199                             filteredIndex = filteredSlideIndices.size();
2200                         }
2201                         filteredSlideNames.push_back(slideName);
2202                         filteredSlideIndices.push_back(i);
2203                     }
2204                 }
2205 
2206                 if (ImGui::ListBox("", &filteredIndex, filteredSlideNames.begin(),
2207                                    filteredSlideNames.size(), 20)) {
2208                     this->setCurrentSlide(filteredSlideIndices[filteredIndex]);
2209                 }
2210             }
2211 
2212             if (ImGui::CollapsingHeader("Color Mode")) {
2213                 ColorMode newMode = fColorMode;
2214                 auto cmButton = [&](ColorMode mode, const char* label) {
2215                     if (ImGui::RadioButton(label, mode == fColorMode)) {
2216                         newMode = mode;
2217                     }
2218                 };
2219 
2220                 cmButton(ColorMode::kLegacy, "Legacy 8888");
2221                 cmButton(ColorMode::kColorManaged8888, "Color Managed 8888");
2222                 cmButton(ColorMode::kColorManagedF16, "Color Managed F16");
2223                 cmButton(ColorMode::kColorManagedF16Norm, "Color Managed F16 Norm");
2224 
2225                 if (newMode != fColorMode) {
2226                     this->setColorMode(newMode);
2227                 }
2228 
2229                 // Pick from common gamuts:
2230                 int primariesIdx = 4; // Default: Custom
2231                 for (size_t i = 0; i < SK_ARRAY_COUNT(gNamedPrimaries); ++i) {
2232                     if (primaries_equal(*gNamedPrimaries[i].fPrimaries, fColorSpacePrimaries)) {
2233                         primariesIdx = i;
2234                         break;
2235                     }
2236                 }
2237 
2238                 // Let user adjust the gamma
2239                 ImGui::SliderFloat("Gamma", &fColorSpaceTransferFn.g, 0.5f, 3.5f);
2240 
2241                 if (ImGui::Combo("Primaries", &primariesIdx,
2242                                  "sRGB\0AdobeRGB\0P3\0Rec. 2020\0Custom\0\0")) {
2243                     if (primariesIdx >= 0 && primariesIdx <= 3) {
2244                         fColorSpacePrimaries = *gNamedPrimaries[primariesIdx].fPrimaries;
2245                     }
2246                 }
2247 
2248                 // Allow direct editing of gamut
2249                 ImGui_Primaries(&fColorSpacePrimaries, &fImGuiGamutPaint);
2250             }
2251 
2252             if (ImGui::CollapsingHeader("Animation")) {
2253                 bool isPaused = AnimTimer::kPaused_State == fAnimTimer.state();
2254                 if (ImGui::Checkbox("Pause", &isPaused)) {
2255                     fAnimTimer.togglePauseResume();
2256                 }
2257 
2258                 float speed = fAnimTimer.getSpeed();
2259                 if (ImGui::DragFloat("Speed", &speed, 0.1f)) {
2260                     fAnimTimer.setSpeed(speed);
2261                 }
2262             }
2263 
2264             if (ImGui::CollapsingHeader("Shaders")) {
2265                 bool sksl = params.fGrContextOptions.fShaderCacheStrategy ==
2266                             GrContextOptions::ShaderCacheStrategy::kSkSL;
2267 #if defined(SK_VULKAN)
2268                 const bool isVulkan = fBackendType == sk_app::Window::kVulkan_BackendType;
2269 #else
2270                 const bool isVulkan = false;
2271 #endif
2272 
2273                 // To re-load shaders from the currently active programs, we flush all
2274                 // caches on one frame, then set a flag to poll the cache on the next frame.
2275                 static bool gLoadPending = false;
2276                 if (gLoadPending) {
2277                     auto collectShaders = [this](sk_sp<const SkData> key, sk_sp<SkData> data,
2278                                                  int hitCount) {
2279                         CachedShader& entry(fCachedShaders.push_back());
2280                         entry.fKey = key;
2281                         SkMD5 hash;
2282                         hash.write(key->bytes(), key->size());
2283                         SkMD5::Digest digest = hash.finish();
2284                         for (int i = 0; i < 16; ++i) {
2285                             entry.fKeyString.appendf("%02x", digest.data[i]);
2286                         }
2287 
2288                         SkReadBuffer reader(data->data(), data->size());
2289                         entry.fShaderType = GrPersistentCacheUtils::GetType(&reader);
2290                         GrPersistentCacheUtils::UnpackCachedShaders(&reader, entry.fShader,
2291                                                                     entry.fInputs,
2292                                                                     kGrShaderTypeCount);
2293                     };
2294                     fCachedShaders.reset();
2295                     fPersistentCache.foreach(collectShaders);
2296                     gLoadPending = false;
2297 
2298 #if defined(SK_VULKAN)
2299                     if (isVulkan && !sksl) {
2300                         spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
2301                         for (auto& entry : fCachedShaders) {
2302                             for (int i = 0; i < kGrShaderTypeCount; ++i) {
2303                                 const SkSL::String& spirv(entry.fShader[i]);
2304                                 std::string disasm;
2305                                 tools.Disassemble((const uint32_t*)spirv.c_str(), spirv.size() / 4,
2306                                                   &disasm);
2307                                 entry.fShader[i].assign(disasm);
2308                             }
2309                         }
2310                     }
2311 #endif
2312                 }
2313 
2314                 // Defer actually doing the load/save logic so that we can trigger a save when we
2315                 // start or finish hovering on a tree node in the list below:
2316                 bool doLoad = ImGui::Button("Load"); ImGui::SameLine();
2317                 bool doSave = ImGui::Button("Save"); ImGui::SameLine();
2318                 if (ImGui::Checkbox("SkSL", &sksl)) {
2319                     params.fGrContextOptions.fShaderCacheStrategy =
2320                             sksl ? GrContextOptions::ShaderCacheStrategy::kSkSL
2321                                  : GrContextOptions::ShaderCacheStrategy::kBackendSource;
2322                     paramsChanged = true;
2323                     doLoad = true;
2324                     fDeferredActions.push_back([=]() { fPersistentCache.reset(); });
2325                 }
2326 
2327                 ImGui::BeginChild("##ScrollingRegion");
2328                 for (auto& entry : fCachedShaders) {
2329                     bool inTreeNode = ImGui::TreeNode(entry.fKeyString.c_str());
2330                     bool hovered = ImGui::IsItemHovered();
2331                     if (hovered != entry.fHovered) {
2332                         // Force a save to patch the highlight shader in/out
2333                         entry.fHovered = hovered;
2334                         doSave = true;
2335                     }
2336                     if (inTreeNode) {
2337                         auto stringBox = [](const char* label, std::string* str) {
2338                             // Full width, and not too much space for each shader
2339                             int lines = std::count(str->begin(), str->end(), '\n') + 2;
2340                             ImVec2 boxSize(-1.0f, ImGui::GetTextLineHeight() * std::min(lines, 30));
2341                             ImGui::InputTextMultiline(label, str, boxSize);
2342                         };
2343                         stringBox("##VP", &entry.fShader[kVertex_GrShaderType]);
2344                         stringBox("##FP", &entry.fShader[kFragment_GrShaderType]);
2345                         ImGui::TreePop();
2346                     }
2347                 }
2348                 ImGui::EndChild();
2349 
2350                 if (doLoad) {
2351                     fPersistentCache.reset();
2352                     ctx->priv().getGpu()->resetShaderCacheForTesting();
2353                     gLoadPending = true;
2354                 }
2355                 // We don't support updating SPIRV shaders. We could re-assemble them (with edits),
2356                 // but I'm not sure anyone wants to do that.
2357                 if (isVulkan && !sksl) {
2358                     doSave = false;
2359                 }
2360                 if (doSave) {
2361                     fPersistentCache.reset();
2362                     ctx->priv().getGpu()->resetShaderCacheForTesting();
2363                     for (auto& entry : fCachedShaders) {
2364                         SkSL::String backup = entry.fShader[kFragment_GrShaderType];
2365                         if (entry.fHovered) {
2366                             // The hovered item (if any) gets a special shader to make it
2367                             // identifiable.
2368                             SkSL::String& fragShader = entry.fShader[kFragment_GrShaderType];
2369                             switch (entry.fShaderType) {
2370                                 case SkSetFourByteTag('S', 'K', 'S', 'L'): {
2371                                     fragShader = build_sksl_highlight_shader();
2372                                     break;
2373                                 }
2374                                 case SkSetFourByteTag('G', 'L', 'S', 'L'): {
2375                                     fragShader = build_glsl_highlight_shader(
2376                                         *ctx->priv().caps()->shaderCaps());
2377                                     break;
2378                                 }
2379                                 case SkSetFourByteTag('M', 'S', 'L', ' '): {
2380                                     fragShader = build_metal_highlight_shader(fragShader);
2381                                     break;
2382                                 }
2383                             }
2384                         }
2385 
2386                         auto data = GrPersistentCacheUtils::PackCachedShaders(entry.fShaderType,
2387                                                                               entry.fShader,
2388                                                                               entry.fInputs,
2389                                                                               kGrShaderTypeCount);
2390                         fPersistentCache.store(*entry.fKey, *data);
2391 
2392                         entry.fShader[kFragment_GrShaderType] = backup;
2393                     }
2394                 }
2395             }
2396         }
2397         if (paramsChanged) {
2398             fDeferredActions.push_back([=]() {
2399                 fWindow->setRequestedDisplayParams(params);
2400                 fWindow->inval();
2401                 this->updateTitle();
2402             });
2403         }
2404         ImGui::End();
2405     }
2406 
2407     if (gShaderErrorHandler.fErrors.count()) {
2408         ImGui::SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
2409         ImGui::Begin("Shader Errors", nullptr, ImGuiWindowFlags_NoFocusOnAppearing);
2410         for (int i = 0; i < gShaderErrorHandler.fErrors.count(); ++i) {
2411             ImGui::TextWrapped("%s", gShaderErrorHandler.fErrors[i].c_str());
2412             SkSL::String sksl(gShaderErrorHandler.fShaders[i].c_str());
2413             GrShaderUtils::VisitLineByLine(sksl, [](int lineNumber, const char* lineText) {
2414                 ImGui::TextWrapped("%4i\t%s\n", lineNumber, lineText);
2415             });
2416         }
2417         ImGui::End();
2418         gShaderErrorHandler.reset();
2419     }
2420 
2421     if (fShowZoomWindow && fLastImage) {
2422         ImGui::SetNextWindowSize(ImVec2(200, 200), ImGuiCond_FirstUseEver);
2423         if (ImGui::Begin("Zoom", &fShowZoomWindow)) {
2424             static int zoomFactor = 8;
2425             if (ImGui::Button("<<")) {
2426                 zoomFactor = std::max(zoomFactor / 2, 4);
2427             }
2428             ImGui::SameLine(); ImGui::Text("%2d", zoomFactor); ImGui::SameLine();
2429             if (ImGui::Button(">>")) {
2430                 zoomFactor = std::min(zoomFactor * 2, 32);
2431             }
2432 
2433             if (!fZoomWindowFixed) {
2434                 ImVec2 mousePos = ImGui::GetMousePos();
2435                 fZoomWindowLocation = SkPoint::Make(mousePos.x, mousePos.y);
2436             }
2437             SkScalar x = fZoomWindowLocation.x();
2438             SkScalar y = fZoomWindowLocation.y();
2439             int xInt = SkScalarRoundToInt(x);
2440             int yInt = SkScalarRoundToInt(y);
2441             ImVec2 avail = ImGui::GetContentRegionAvail();
2442 
2443             uint32_t pixel = 0;
2444             SkImageInfo info = SkImageInfo::MakeN32Premul(1, 1);
2445             auto dContext = fWindow->directContext();
2446             if (fLastImage->readPixels(dContext, info, &pixel, info.minRowBytes(), xInt, yInt)) {
2447                 ImGui::SameLine();
2448                 ImGui::Text("(X, Y): %d, %d RGBA: %X %X %X %X",
2449                             xInt, yInt,
2450                             SkGetPackedR32(pixel), SkGetPackedG32(pixel),
2451                             SkGetPackedB32(pixel), SkGetPackedA32(pixel));
2452             }
2453 
2454             fImGuiLayer.skiaWidget(avail, [=, lastImage = fLastImage](SkCanvas* c) {
2455                 // Translate so the region of the image that's under the mouse cursor is centered
2456                 // in the zoom canvas:
2457                 c->scale(zoomFactor, zoomFactor);
2458                 c->translate(avail.x * 0.5f / zoomFactor - x - 0.5f,
2459                              avail.y * 0.5f / zoomFactor - y - 0.5f);
2460                 c->drawImage(lastImage, 0, 0);
2461 
2462                 SkPaint outline;
2463                 outline.setStyle(SkPaint::kStroke_Style);
2464                 c->drawRect(SkRect::MakeXYWH(x, y, 1, 1), outline);
2465             });
2466         }
2467 
2468         ImGui::End();
2469     }
2470 }
2471 
onIdle()2472 void Viewer::onIdle() {
2473     for (int i = 0; i < fDeferredActions.count(); ++i) {
2474         fDeferredActions[i]();
2475     }
2476     fDeferredActions.reset();
2477 
2478     fStatsLayer.beginTiming(fAnimateTimer);
2479     fAnimTimer.updateTime();
2480     bool animateWantsInval = fSlides[fCurrentSlide]->animate(fAnimTimer.nanos());
2481     fStatsLayer.endTiming(fAnimateTimer);
2482 
2483     ImGuiIO& io = ImGui::GetIO();
2484     // ImGui always has at least one "active" window, which is the default "Debug" window. It may
2485     // not be visible, though. So we need to redraw if there is at least one visible window, or
2486     // more than one active window. Newly created windows are active but not visible for one frame
2487     // while they determine their layout and sizing.
2488     if (animateWantsInval || fStatsLayer.getActive() || fRefresh ||
2489         io.MetricsActiveWindows > 1 || io.MetricsRenderWindows > 0) {
2490         fWindow->inval();
2491     }
2492 }
2493 
2494 template <typename OptionsFunc>
WriteStateObject(SkJSONWriter & writer,const char * name,const char * value,OptionsFunc && optionsFunc)2495 static void WriteStateObject(SkJSONWriter& writer, const char* name, const char* value,
2496                              OptionsFunc&& optionsFunc) {
2497     writer.beginObject();
2498     {
2499         writer.appendString(kName , name);
2500         writer.appendString(kValue, value);
2501 
2502         writer.beginArray(kOptions);
2503         {
2504             optionsFunc(writer);
2505         }
2506         writer.endArray();
2507     }
2508     writer.endObject();
2509 }
2510 
2511 
updateUIState()2512 void Viewer::updateUIState() {
2513     if (!fWindow) {
2514         return;
2515     }
2516     if (fWindow->sampleCount() < 1) {
2517         return; // Surface hasn't been created yet.
2518     }
2519 
2520     SkDynamicMemoryWStream memStream;
2521     SkJSONWriter writer(&memStream);
2522     writer.beginArray();
2523 
2524     // Slide state
2525     WriteStateObject(writer, kSlideStateName, fSlides[fCurrentSlide]->getName().c_str(),
2526         [this](SkJSONWriter& writer) {
2527             for(const auto& slide : fSlides) {
2528                 writer.appendString(slide->getName().c_str());
2529             }
2530         });
2531 
2532     // Backend state
2533     WriteStateObject(writer, kBackendStateName, kBackendTypeStrings[fBackendType],
2534         [](SkJSONWriter& writer) {
2535             for (const auto& str : kBackendTypeStrings) {
2536                 writer.appendString(str);
2537             }
2538         });
2539 
2540     // MSAA state
2541     const auto countString = SkStringPrintf("%d", fWindow->sampleCount());
2542     WriteStateObject(writer, kMSAAStateName, countString.c_str(),
2543         [this](SkJSONWriter& writer) {
2544             writer.appendS32(0);
2545 
2546             if (sk_app::Window::kRaster_BackendType == fBackendType) {
2547                 return;
2548             }
2549 
2550             for (int msaa : {4, 8, 16}) {
2551                 writer.appendS32(msaa);
2552             }
2553         });
2554 
2555     // Path renderer state
2556     GpuPathRenderers pr = fWindow->getRequestedDisplayParams().fGrContextOptions.fGpuPathRenderers;
2557     WriteStateObject(writer, kPathRendererStateName, gPathRendererNames[pr].c_str(),
2558         [this](SkJSONWriter& writer) {
2559             auto ctx = fWindow->directContext();
2560             if (!ctx) {
2561                 writer.appendString("Software");
2562             } else {
2563                 const auto* caps = ctx->priv().caps();
2564                 writer.appendString(gPathRendererNames[GpuPathRenderers::kDefault].c_str());
2565                 if (fWindow->sampleCount() > 1 || caps->mixedSamplesSupport()) {
2566                     if (caps->shaderCaps()->tessellationSupport()) {
2567                         writer.appendString(
2568                                 gPathRendererNames[GpuPathRenderers::kTessellation].c_str());
2569                     }
2570                     if (caps->shaderCaps()->pathRenderingSupport()) {
2571                         writer.appendString(
2572                                 gPathRendererNames[GpuPathRenderers::kStencilAndCover].c_str());
2573                     }
2574                 }
2575                 if (1 == fWindow->sampleCount()) {
2576                     if(GrCoverageCountingPathRenderer::IsSupported(*caps)) {
2577                         writer.appendString(
2578                             gPathRendererNames[GpuPathRenderers::kCoverageCounting].c_str());
2579                     }
2580                     writer.appendString(gPathRendererNames[GpuPathRenderers::kSmall].c_str());
2581                 }
2582                 writer.appendString(gPathRendererNames[GpuPathRenderers::kTriangulating].c_str());
2583                 writer.appendString(gPathRendererNames[GpuPathRenderers::kNone].c_str());
2584             }
2585         });
2586 
2587     // Softkey state
2588     WriteStateObject(writer, kSoftkeyStateName, kSoftkeyHint,
2589         [this](SkJSONWriter& writer) {
2590             writer.appendString(kSoftkeyHint);
2591             for (const auto& softkey : fCommands.getCommandsAsSoftkeys()) {
2592                 writer.appendString(softkey.c_str());
2593             }
2594         });
2595 
2596     writer.endArray();
2597     writer.flush();
2598 
2599     auto data = memStream.detachAsData();
2600 
2601     // TODO: would be cool to avoid this copy
2602     const SkString cstring(static_cast<const char*>(data->data()), data->size());
2603 
2604     fWindow->setUIState(cstring.c_str());
2605 }
2606 
onUIStateChanged(const SkString & stateName,const SkString & stateValue)2607 void Viewer::onUIStateChanged(const SkString& stateName, const SkString& stateValue) {
2608     // For those who will add more features to handle the state change in this function:
2609     // After the change, please call updateUIState no notify the frontend (e.g., Android app).
2610     // For example, after slide change, updateUIState is called inside setupCurrentSlide;
2611     // after backend change, updateUIState is called in this function.
2612     if (stateName.equals(kSlideStateName)) {
2613         for (int i = 0; i < fSlides.count(); ++i) {
2614             if (fSlides[i]->getName().equals(stateValue)) {
2615                 this->setCurrentSlide(i);
2616                 return;
2617             }
2618         }
2619 
2620         SkDebugf("Slide not found: %s", stateValue.c_str());
2621     } else if (stateName.equals(kBackendStateName)) {
2622         for (int i = 0; i < sk_app::Window::kBackendTypeCount; i++) {
2623             if (stateValue.equals(kBackendTypeStrings[i])) {
2624                 if (fBackendType != i) {
2625                     fBackendType = (sk_app::Window::BackendType)i;
2626                     for(auto& slide : fSlides) {
2627                         slide->gpuTeardown();
2628                     }
2629                     fWindow->detach();
2630                     fWindow->attach(backend_type_for_window(fBackendType));
2631                 }
2632                 break;
2633             }
2634         }
2635     } else if (stateName.equals(kMSAAStateName)) {
2636         DisplayParams params = fWindow->getRequestedDisplayParams();
2637         int sampleCount = atoi(stateValue.c_str());
2638         if (sampleCount != params.fMSAASampleCount) {
2639             params.fMSAASampleCount = sampleCount;
2640             fWindow->setRequestedDisplayParams(params);
2641             fWindow->inval();
2642             this->updateTitle();
2643             this->updateUIState();
2644         }
2645     } else if (stateName.equals(kPathRendererStateName)) {
2646         DisplayParams params = fWindow->getRequestedDisplayParams();
2647         for (const auto& pair : gPathRendererNames) {
2648             if (pair.second == stateValue.c_str()) {
2649                 if (params.fGrContextOptions.fGpuPathRenderers != pair.first) {
2650                     params.fGrContextOptions.fGpuPathRenderers = pair.first;
2651                     fWindow->setRequestedDisplayParams(params);
2652                     fWindow->inval();
2653                     this->updateTitle();
2654                     this->updateUIState();
2655                 }
2656                 break;
2657             }
2658         }
2659     } else if (stateName.equals(kSoftkeyStateName)) {
2660         if (!stateValue.equals(kSoftkeyHint)) {
2661             fCommands.onSoftkey(stateValue);
2662             this->updateUIState(); // This is still needed to reset the value to kSoftkeyHint
2663         }
2664     } else if (stateName.equals(kRefreshStateName)) {
2665         // This state is actually NOT in the UI state.
2666         // We use this to allow Android to quickly set bool fRefresh.
2667         fRefresh = stateValue.equals(kON);
2668     } else {
2669         SkDebugf("Unknown stateName: %s", stateName.c_str());
2670     }
2671 }
2672 
onKey(skui::Key key,skui::InputState state,skui::ModifierKey modifiers)2673 bool Viewer::onKey(skui::Key key, skui::InputState state, skui::ModifierKey modifiers) {
2674     return fCommands.onKey(key, state, modifiers);
2675 }
2676 
onChar(SkUnichar c,skui::ModifierKey modifiers)2677 bool Viewer::onChar(SkUnichar c, skui::ModifierKey modifiers) {
2678     if (fSlides[fCurrentSlide]->onChar(c)) {
2679         fWindow->inval();
2680         return true;
2681     } else {
2682         return fCommands.onChar(c, modifiers);
2683     }
2684 }
2685