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