blob: 1694e962e0e438a3a86617fd5295ac0b9c2e3baf [file] [log] [blame]
halcanary00d44e02016-05-03 15:09:52 -07001/*
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
halcanary85e38bc2016-05-04 09:34:25 -07008// This sample progam demonstrates how to use Skia and HarfBuzz to
9// produce a PDF file from UTF-8 text in stdin.
halcanary00d44e02016-05-03 15:09:52 -070010
11#include <cassert>
halcanarydd05e2a2016-05-12 10:09:58 -070012#include <cstdlib>
halcanary00d44e02016-05-03 15:09:52 -070013#include <iostream>
14#include <map>
15#include <string>
halcanarydd05e2a2016-05-12 10:09:58 -070016#include <sstream>
halcanary00d44e02016-05-03 15:09:52 -070017
halcanary85e38bc2016-05-04 09:34:25 -070018#include <hb-ot.h>
19
20#include "SkCanvas.h"
21#include "SkDocument.h"
22#include "SkStream.h"
23#include "SkTextBlob.h"
24#include "SkTypeface.h"
halcanary00d44e02016-05-03 15:09:52 -070025
26struct BaseOption {
27 std::string selector;
28 std::string description;
29 virtual void set(std::string _value) = 0;
30 virtual std::string valueToString() = 0;
31
32 BaseOption(std::string _selector, std::string _description) :
33 selector(_selector),
34 description(_description) {}
35
36 virtual ~BaseOption() {}
37};
38
39template <class T> struct Option : BaseOption {
40 T value;
41 Option(std::string selector, std::string description, T defaultValue) :
42 BaseOption(selector, description),
43 value(defaultValue) {}
44};
45
46struct DoubleOption : Option<double> {
47 virtual void set(std::string _value) {
48 value = atof(_value.c_str());
49 }
50 virtual std::string valueToString() {
halcanarydd05e2a2016-05-12 10:09:58 -070051 std::ostringstream stm;
52 stm << value;
53 return stm.str();
halcanary00d44e02016-05-03 15:09:52 -070054 }
55 DoubleOption(std::string selector, std::string description, double defaultValue) :
56 Option<double>(selector, description, defaultValue) {}
57};
58
59struct SkStringOption : Option<SkString> {
60 virtual void set(std::string _value) {
61 value = _value.c_str();
62 }
63 virtual std::string valueToString() {
64 return value.c_str();
65 }
66 SkStringOption(std::string selector, std::string description, SkString defaultValue) :
67 Option<SkString>(selector, description, defaultValue) {}
68};
69
70struct StdStringOption : Option<std::string> {
71 virtual void set(std::string _value) {
72 value = _value;
73 }
74 virtual std::string valueToString() {
75 return value;
76 }
77 StdStringOption(std::string selector, std::string description, std::string defaultValue) :
78 Option<std::string>(selector, description, defaultValue) {}
79};
80
81struct Config {
82 DoubleOption *page_width = new DoubleOption("-w", "Page width", 600.0f);
83 DoubleOption *page_height = new DoubleOption("-h", "Page height", 800.0f);
84 SkStringOption *title = new SkStringOption("-t", "PDF title", SkString("---"));
85 SkStringOption *author = new SkStringOption("-a", "PDF author", SkString("---"));
86 SkStringOption *subject = new SkStringOption("-k", "PDF subject", SkString("---"));
87 SkStringOption *keywords = new SkStringOption("-c", "PDF keywords", SkString("---"));
88 SkStringOption *creator = new SkStringOption("-t", "PDF creator", SkString("---"));
89 StdStringOption *font_file = new StdStringOption("-f", ".ttf font file", "fonts/DejaVuSans.ttf");
90 DoubleOption *font_size = new DoubleOption("-z", "Font size", 8.0f);
91 DoubleOption *left_margin = new DoubleOption("-m", "Left margin", 20.0f);
92 DoubleOption *line_spacing_ratio = new DoubleOption("-h", "Line spacing ratio", 1.5f);
93 StdStringOption *output_file_name = new StdStringOption("-o", ".pdf output file name", "out-skiahf.pdf");
94
95 std::map<std::string, BaseOption*> options = {
96 { page_width->selector, page_width },
97 { page_height->selector, page_height },
98 { title->selector, title },
99 { author->selector, author },
100 { subject->selector, subject },
101 { keywords->selector, keywords },
102 { creator->selector, creator },
103 { font_file->selector, font_file },
104 { font_size->selector, font_size },
105 { left_margin->selector, left_margin },
106 { line_spacing_ratio->selector, line_spacing_ratio },
107 { output_file_name->selector, output_file_name },
108 };
109
110 Config(int argc, char **argv) {
111 for (int i = 1; i < argc; i++) {
112 std::string option_selector(argv[i]);
113 auto it = options.find(option_selector);
114 if (it != options.end()) {
115 if (i >= argc) {
116 break;
117 }
118 const char *option_value = argv[i + 1];
119 it->second->set(option_value);
120 i++;
121 } else {
122 printf("Ignoring unrecognized option: %s.\n", argv[i]);
123 printf("Usage: %s {option value}\n", argv[0]);
124 printf("\tTakes text from stdin and produces pdf file.\n");
125 printf("Supported options:\n");
126 for (auto it = options.begin(); it != options.end(); ++it) {
127 printf("\t%s\t%s (%s)\n", it->first.c_str(),
128 it->second->description.c_str(),
129 it->second->valueToString().c_str());
130 }
131 exit(-1);
132 }
133 }
134 } // end of Config::Config
135};
136
137const double FONT_SIZE_SCALE = 64.0f;
138
139struct Face {
140 struct HBFDel { void operator()(hb_face_t* f) { hb_face_destroy(f); } };
141 std::unique_ptr<hb_face_t, HBFDel> fHarfBuzzFace;
142 sk_sp<SkTypeface> fSkiaTypeface;
143
144 Face(const char* path, int index) {
145 // fairly portable mmap impl
146 auto data = SkData::MakeFromFileName(path);
147 assert(data);
148 if (!data) { return; }
bungeman13b9c952016-05-12 10:09:30 -0700149 fSkiaTypeface = SkTypeface::MakeFromStream(new SkMemoryStream(data), index);
halcanary00d44e02016-05-03 15:09:52 -0700150 assert(fSkiaTypeface);
151 if (!fSkiaTypeface) { return; }
152 auto destroy = [](void *d) { static_cast<SkData*>(d)->unref(); };
153 const char* bytes = (const char*)data->data();
154 unsigned int size = (unsigned int)data->size();
155 hb_blob_t* blob = hb_blob_create(bytes,
156 size,
157 HB_MEMORY_MODE_READONLY,
158 data.release(),
159 destroy);
160 assert(blob);
161 hb_blob_make_immutable(blob);
162 hb_face_t* face = hb_face_create(blob, (unsigned)index);
163 hb_blob_destroy(blob);
164 assert(face);
165 if (!face) {
166 fSkiaTypeface.reset();
167 return;
168 }
169 hb_face_set_index(face, (unsigned)index);
170 hb_face_set_upem(face, fSkiaTypeface->getUnitsPerEm());
171 fHarfBuzzFace.reset(face);
172 }
173};
174
175class Placement {
176 public:
177 Placement(Config &_config, SkWStream* outputStream) : config(_config) {
178 face = new Face(config.font_file->value.c_str(), 0 /* index */);
179 hb_font = hb_font_create(face->fHarfBuzzFace.get());
180
181 hb_font_set_scale(hb_font,
182 FONT_SIZE_SCALE * config.font_size->value,
183 FONT_SIZE_SCALE * config.font_size->value);
184 hb_ot_font_set_funcs(hb_font);
185
186 SkDocument::PDFMetadata pdf_info;
187 pdf_info.fTitle = config.title->value;
188 pdf_info.fAuthor = config.author->value;
189 pdf_info.fSubject = config.subject->value;
190 pdf_info.fKeywords = config.keywords->value;
191 pdf_info.fCreator = config.creator->value;
192 SkTime::DateTime now;
193 SkTime::GetDateTime(&now);
194 pdf_info.fCreation.fEnabled = true;
195 pdf_info.fCreation.fDateTime = now;
196 pdf_info.fModified.fEnabled = true;
197 pdf_info.fModified.fDateTime = now;
198 pdfDocument = SkDocument::MakePDF(outputStream, SK_ScalarDefaultRasterDPI,
199 pdf_info, nullptr, true);
200 assert(pdfDocument);
201
202 white_paint.setColor(SK_ColorWHITE);
203
204 glyph_paint.setFlags(
205 SkPaint::kAntiAlias_Flag |
206 SkPaint::kSubpixelText_Flag); // ... avoid waggly text when rotating.
207 glyph_paint.setColor(SK_ColorBLACK);
208 glyph_paint.setTextSize(config.font_size->value);
halcanary00d44e02016-05-03 15:09:52 -0700209 glyph_paint.setTypeface(face->fSkiaTypeface);
210 glyph_paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
211
212 NewPage();
213 } // end of Placement
214
215 ~Placement() {
216 delete face;
217 hb_font_destroy (hb_font);
218 }
219
220 void WriteLine(const char *text) {
221 /* Create hb-buffer and populate. */
222 hb_buffer_t *hb_buffer = hb_buffer_create ();
223 hb_buffer_add_utf8 (hb_buffer, text, -1, 0, -1);
224 hb_buffer_guess_segment_properties (hb_buffer);
225
226 /* Shape it! */
227 hb_shape (hb_font, hb_buffer, NULL, 0);
228
229 DrawGlyphs(hb_buffer);
230
231 hb_buffer_destroy (hb_buffer);
232
233 // Advance to the next line.
234 current_y += config.line_spacing_ratio->value * config.font_size->value;
235 if (current_y > config.page_height->value) {
236 pdfDocument->endPage();
237 NewPage();
238 }
239 }
240
241 bool Close() {
242 return pdfDocument->close();
243 }
244
245private:
246 Config config;
247
248 Face *face;
249
250 hb_font_t *hb_font;
251
252 sk_sp<SkDocument> pdfDocument;
253
254 SkCanvas* pageCanvas;
255
256 SkPaint white_paint;
257 SkPaint glyph_paint;
258
259 double current_x;
260 double current_y;
261
262 void NewPage() {
263 pageCanvas = pdfDocument->beginPage(config.page_width->value, config.page_height->value);
264
265 pageCanvas->drawPaint(white_paint);
266
267 current_x = config.left_margin->value;
268 current_y = config.line_spacing_ratio->value * config.font_size->value;
269 }
270
271 bool DrawGlyphs(hb_buffer_t *hb_buffer) {
272 SkTextBlobBuilder textBlobBuilder;
273 unsigned len = hb_buffer_get_length (hb_buffer);
274 if (len == 0) {
275 return true;
276 }
277 hb_glyph_info_t *info = hb_buffer_get_glyph_infos (hb_buffer, NULL);
278 hb_glyph_position_t *pos = hb_buffer_get_glyph_positions (hb_buffer, NULL);
279 auto runBuffer = textBlobBuilder.allocRunPos(glyph_paint, len);
280
281 double x = 0;
282 double y = 0;
283 for (unsigned int i = 0; i < len; i++)
284 {
285 runBuffer.glyphs[i] = info[i].codepoint;
286 reinterpret_cast<SkPoint*>(runBuffer.pos)[i] = SkPoint::Make(
287 x + pos[i].x_offset / FONT_SIZE_SCALE,
288 y - pos[i].y_offset / FONT_SIZE_SCALE);
289 x += pos[i].x_advance / FONT_SIZE_SCALE;
290 y += pos[i].y_advance / FONT_SIZE_SCALE;
291 }
292
293 pageCanvas->drawTextBlob(textBlobBuilder.build(), current_x, current_y, glyph_paint);
294 return true;
295 } // end of DrawGlyphs
296}; // end of Placement class
297
298int main(int argc, char** argv) {
299 Config config(argc, argv);
300
301 Placement placement(config, new SkFILEWStream(config.output_file_name->value.c_str()));
302 for (std::string line; std::getline(std::cin, line);) {
303 placement.WriteLine(line.c_str());
304 }
305 placement.Close();
306
307 return 0;
308}