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