1 | /* |
2 | * Copyright 2013 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 "include/core/SkCanvas.h" |
9 | #include "include/core/SkDocument.h" |
10 | #include "include/core/SkStream.h" |
11 | |
12 | SkDocument::SkDocument(SkWStream* stream) : fStream(stream), fState(kBetweenPages_State) {} |
13 | |
14 | SkDocument::~SkDocument() { |
15 | this->close(); |
16 | } |
17 | |
18 | static SkCanvas* trim(SkCanvas* canvas, SkScalar width, SkScalar height, |
19 | const SkRect* content) { |
20 | if (content && canvas) { |
21 | SkRect inner = *content; |
22 | if (!inner.intersect({0, 0, width, height})) { |
23 | return nullptr; |
24 | } |
25 | canvas->clipRect(inner); |
26 | canvas->translate(inner.x(), inner.y()); |
27 | } |
28 | return canvas; |
29 | } |
30 | |
31 | SkCanvas* SkDocument::beginPage(SkScalar width, SkScalar height, |
32 | const SkRect* content) { |
33 | if (width <= 0 || height <= 0 || kClosed_State == fState) { |
34 | return nullptr; |
35 | } |
36 | if (kInPage_State == fState) { |
37 | this->endPage(); |
38 | } |
39 | SkASSERT(kBetweenPages_State == fState); |
40 | fState = kInPage_State; |
41 | return trim(this->onBeginPage(width, height), width, height, content); |
42 | } |
43 | |
44 | void SkDocument::endPage() { |
45 | if (kInPage_State == fState) { |
46 | fState = kBetweenPages_State; |
47 | this->onEndPage(); |
48 | } |
49 | } |
50 | |
51 | void SkDocument::close() { |
52 | for (;;) { |
53 | switch (fState) { |
54 | case kBetweenPages_State: { |
55 | fState = kClosed_State; |
56 | this->onClose(fStream); |
57 | // we don't own the stream, but we mark it nullptr since we can |
58 | // no longer write to it. |
59 | fStream = nullptr; |
60 | return; |
61 | } |
62 | case kInPage_State: |
63 | this->endPage(); |
64 | break; |
65 | case kClosed_State: |
66 | return; |
67 | } |
68 | } |
69 | } |
70 | |
71 | void SkDocument::abort() { |
72 | this->onAbort(); |
73 | |
74 | fState = kClosed_State; |
75 | // we don't own the stream, but we mark it nullptr since we can |
76 | // no longer write to it. |
77 | fStream = nullptr; |
78 | } |
79 | |