xref: /aosp_15_r20/external/skia/tools/SvgPathExtractor.cpp (revision c8dee2aa9b3f27cf6c858bd81872bdeb2c07ed17)
1 /*
2  * Copyright 2023 Google LLC
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/SvgPathExtractor.h"
9 
10 #include "include/core/SkCanvas.h"
11 #include "include/core/SkPicture.h"
12 #include "include/core/SkRefCnt.h"
13 #include "include/core/SkStream.h"
14 #include "include/private/base/SkDebug.h"
15 #include "modules/svg/include/SkSVGDOM.h"
16 #include "modules/svg/include/SkSVGNode.h"
17 #include "src/xml/SkDOM.h"
18 
19 #include <cstring>
20 
21 class SkPaint;
22 class SkPath;
23 
24 namespace ToolUtils {
25 
ExtractPaths(const char filepath[],std::function<PathSniffCallback> callback)26 void ExtractPaths(const char filepath[], std::function<PathSniffCallback> callback) {
27     SkFILEStream stream(filepath);
28     if (!stream.isValid()) {
29         SkDebugf("ExtractPaths: invalid input file at \"%s\"\n", filepath);
30         return;
31     }
32 
33     class PathSniffer : public SkCanvas {
34     public:
35         PathSniffer(std::function<PathSniffCallback> callback)
36                 : SkCanvas(4096, 4096, nullptr)
37                 , fPathSniffCallback(callback) {}
38     private:
39         void onDrawPath(const SkPath& path, const SkPaint& paint) override {
40             fPathSniffCallback(this->getTotalMatrix(), path, paint);
41         }
42         std::function<PathSniffCallback> fPathSniffCallback;
43     };
44 
45     sk_sp<SkSVGDOM> svg = SkSVGDOM::MakeFromStream(stream);
46     if (!svg) {
47         SkDebugf("ExtractPaths: couldn't load svg at \"%s\"\n", filepath);
48         return;
49     }
50     PathSniffer pathSniffer(callback);
51     svg->setContainerSize(SkSize::Make(pathSniffer.getBaseLayerSize()));
52     svg->render(&pathSniffer);
53 }
54 
55 }  // namespace ToolUtils
56