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