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 "SkTypes.h"
9
10 #ifdef SAMPLE_PDF_FILE_VIEWER
11
12 #include "Sample.h"
13 #include "SkCanvas.h"
14 #include "SkGradientShader.h"
15 #include "SkGraphics.h"
16 #include "SkOSFile.h"
17 #include "SkPath.h"
18 #include "SkPicture.h"
19 #include "SkRandom.h"
20 #include "SkRegion.h"
21 #include "SkShader.h"
22 #include "SkUTF.h"
23 #include "SkColorPriv.h"
24 #include "SkColorFilter.h"
25 #include "SkTime.h"
26 #include "SkTypeface.h"
27 #include "SkPdfRenderer.h"
28
29 class PdfFileViewer : public Sample {
30 private:
31 SkString fFilename;
32 SkPicture* fPicture; // TODO(edisonn): multiple pages, one page / picture, make it an array
33
LoadPdf(const char path[])34 static SkPicture* LoadPdf(const char path[]) {
35 std::unique_ptr<SkPdfRenderer> renderer(SkPdfRenderer::CreateFromFile(path));
36 if (nullptr == renderer.get()) {
37 return nullptr;
38 }
39
40 SkPicture* pic = new SkPicture;
41 SkCanvas* canvas = pic->beginRecording((int) renderer->MediaBox(0).width(),
42 (int) renderer->MediaBox(0).height());
43 renderer->renderPage(0, canvas, renderer->MediaBox(0));
44 pic->endRecording();
45 return pic;
46 }
47
48 public:
PdfFileViewer(const char name[]=nullptr)49 PdfFileViewer(const char name[] = nullptr) : fFilename(name) {
50 fPicture = nullptr;
51 }
52
~PdfFileViewer()53 virtual ~PdfFileViewer() {
54 SkSafeUnref(fPicture);
55 }
56
57 protected:
onQuery(Sample::Event * evt)58 virtual bool onQuery(Sample::Event* evt) {
59 if (Sample::TitleQ(*evt)) {
60 SkString name("P:");
61 const char* basename = strrchr(fFilename.c_str(), SkPATH_SEPARATOR);
62 name.append(basename ? basename+1: fFilename.c_str());
63 Sample::TitleR(evt, name.c_str());
64 return true;
65 }
66 return this->INHERITED::onQuery(evt);
67 }
68
onEvent(const SkEvent & evt)69 virtual bool onEvent(const SkEvent& evt) {
70 // TODO(edisonn): add here event handlers to disable clipping, or to show helpful info
71 // like pdf object from click, ...
72 // TODO(edisonn): first, next, prev, last page navigation + slideshow
73 return this->INHERITED::onEvent(evt);
74 }
75
onDrawContent(SkCanvas * canvas)76 virtual void onDrawContent(SkCanvas* canvas) {
77 if (!fPicture) {
78 fPicture = LoadPdf(fFilename.c_str());
79 }
80 if (fPicture) {
81 canvas->drawPicture(*fPicture);
82 }
83 }
84
85 private:
86 typedef Sample INHERITED;
87 };
88
89 Sample* CreateSamplePdfFileViewer(const char filename[]);
CreateSamplePdfFileViewer(const char filename[])90 Sample* CreateSamplePdfFileViewer(const char filename[]) {
91 return new PdfFileViewer(filename);
92 }
93
94 //////////////////////////////////////////////////////////////////////////////
95
96 #if 0
97 static Sample* MyFactory() { return new PdfFileViewer; }
98 static SampleRegister reg(MyFactory);
99 #endif
100
101 #endif // SAMPLE_PDF_FILE_VIEWER
102