SampleSVGFile.cpp revision d3b65972aad96453ff4510caa3e25a2b847c6d1e
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 "SampleCode.h"
9#include "SkCanvas.h"
10#include "SkDOM.h"
11#include "SkOSFile.h"
12#include "SkOSPath.h"
13#include "SkStream.h"
14#include "SkSVGDOM.h"
15#include "SkView.h"
16
17namespace {
18
19class SVGFileView : public SampleView {
20public:
21    SVGFileView(const SkString& path)
22        : fPath(path), fLabel(SkStringPrintf("[%s]", SkOSPath::Basename(path.c_str()).c_str())) {}
23    ~SVGFileView() override = default;
24
25protected:
26    void onOnceBeforeDraw() override {
27        SkFILEStream svgStream(fPath.c_str());
28        if (!svgStream.isValid()) {
29            SkDebugf("file not found: \"path\"\n", fPath.c_str());
30            return;
31        }
32
33        SkDOM xmlDom;
34        if (!xmlDom.build(svgStream)) {
35            SkDebugf("XML parsing failed: \"path\"\n", fPath.c_str());
36            return;
37        }
38
39        fDom = SkSVGDOM::MakeFromDOM(xmlDom);
40        if (fDom) {
41            fDom->setContainerSize(SkSize::Make(this->width(), this->height()));
42        }
43    }
44
45    void onDrawContent(SkCanvas* canvas) override {
46        if (fDom) {
47            fDom->render(canvas);
48        }
49    }
50
51    void onSizeChange() override {
52        if (fDom) {
53            fDom->setContainerSize(SkSize::Make(this->width(), this->height()));
54        }
55
56        this->INHERITED::onSizeChange();
57    }
58
59    bool onQuery(SkEvent* evt) override {
60        if (SampleCode::TitleQ(*evt)) {
61            SampleCode::TitleR(evt, fLabel.c_str());
62            return true;
63        }
64
65        return this->INHERITED::onQuery(evt);
66    }
67private:
68    sk_sp<SkSVGDOM> fDom;
69    SkString        fPath;
70    SkString        fLabel;
71
72    typedef SampleView INHERITED;
73};
74
75} // anonymous namespace
76
77SampleView* CreateSampleSVGFileView(const SkString& filename);
78SampleView* CreateSampleSVGFileView(const SkString& filename) {
79    return new SVGFileView(filename);
80}
81