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