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