render_pdfs_main.cpp revision 58190644c30e1c4aa8e527f3503c58f841e0fcf3
1/*
2 * Copyright 2012 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 "SkCanvas.h"
9#include "SkDevice.h"
10#include "SkForceLinking.h"
11#include "SkGraphics.h"
12#include "SkImageEncoder.h"
13#include "SkOSFile.h"
14#include "SkPicture.h"
15#include "SkStream.h"
16#include "SkTArray.h"
17#include "PdfRenderer.h"
18#include "picture_utils.h"
19
20__SK_FORCE_IMAGE_DECODER_LINKING;
21
22#ifdef SK_USE_CDB
23#include "win_dbghelp.h"
24#endif
25
26/**
27 * render_pdfs
28 *
29 * Given list of directories and files to use as input, expects to find .skp
30 * files and it will convert them to .pdf files writing them in the output
31 * directory.
32 *
33 * Returns zero exit code if all .skp files were converted successfully,
34 * otherwise returns error code 1.
35 */
36
37static const char PDF_FILE_EXTENSION[] = "pdf";
38static const char SKP_FILE_EXTENSION[] = "skp";
39
40static void usage(const char* argv0) {
41    SkDebugf("SKP to PDF rendering tool\n");
42    SkDebugf("\n"
43"Usage: \n"
44"     %s <input>... [-w <outputDir>] [--jpegQuality N] \n"
45, argv0);
46    SkDebugf("\n\n");
47    SkDebugf(
48"     input:     A list of directories and files to use as input. Files are\n"
49"                expected to have the .skp extension.\n\n");
50    SkDebugf(
51"     outputDir: directory to write the rendered pdfs.\n\n");
52    SkDebugf("\n");
53        SkDebugf(
54"     jpegQuality N: encodes images in JPEG at quality level N, which can\n"
55"                    be in range 0-100).\n"
56"                    N = -1 will disable JPEG compression.\n"
57"                    Default is N = 100, maximum quality.\n\n");
58    SkDebugf("\n");
59}
60
61/** Replaces the extension of a file.
62 * @param path File name whose extension will be changed.
63 * @param old_extension The old extension.
64 * @param new_extension The new extension.
65 * @returns false if the file did not has the expected extension.
66 *  if false is returned, contents of path are undefined.
67 */
68static bool replace_filename_extension(SkString* path,
69                                       const char old_extension[],
70                                       const char new_extension[]) {
71    if (path->endsWith(old_extension)) {
72        path->remove(path->size() - strlen(old_extension),
73                     strlen(old_extension));
74        if (!path->endsWith(".")) {
75            return false;
76        }
77        path->append(new_extension);
78        return true;
79    }
80    return false;
81}
82
83int gJpegQuality = 100;
84static bool encode_to_dct_stream(SkWStream* stream, const SkBitmap& bitmap, const SkIRect& rect) {
85    if (gJpegQuality == -1) return false;
86
87        SkIRect bitmapBounds;
88        SkBitmap subset;
89        const SkBitmap* bitmapToUse = &bitmap;
90        bitmap.getBounds(&bitmapBounds);
91        if (rect != bitmapBounds) {
92            SkAssertResult(bitmap.extractSubset(&subset, rect));
93            bitmapToUse = &subset;
94        }
95
96#if defined(SK_BUILD_FOR_MAC)
97        // Workaround bug #1043 where bitmaps with referenced pixels cause
98        // CGImageDestinationFinalize to crash
99        SkBitmap copy;
100        bitmapToUse->deepCopyTo(&copy, bitmapToUse->config());
101        bitmapToUse = &copy;
102#endif
103
104    return SkImageEncoder::EncodeStream(stream,
105                                        *bitmapToUse,
106                                        SkImageEncoder::kJPEG_Type,
107                                        gJpegQuality);
108}
109
110/** Builds the output filename. path = dir/name, and it replaces expected
111 * .skp extension with .pdf extention.
112 * @param path Output filename.
113 * @param name The name of the file.
114 * @returns false if the file did not has the expected extension.
115 *  if false is returned, contents of path are undefined.
116 */
117static bool make_output_filepath(SkString* path, const SkString& dir,
118                                 const SkString& name) {
119    sk_tools::make_filepath(path, dir, name);
120    return replace_filename_extension(path,
121                                      SKP_FILE_EXTENSION,
122                                      PDF_FILE_EXTENSION);
123}
124
125/** Write the output of pdf renderer to a file.
126 * @param outputDir Output dir.
127 * @param inputFilename The skp file that was read.
128 * @param renderer The object responsible to write the pdf file.
129 */
130static bool write_output(const SkString& outputDir,
131                         const SkString& inputFilename,
132                         const sk_tools::PdfRenderer& renderer) {
133    if (outputDir.isEmpty()) {
134        SkDynamicMemoryWStream stream;
135        renderer.write(&stream);
136        return true;
137    }
138
139    SkString outputPath;
140    if (!make_output_filepath(&outputPath, outputDir, inputFilename)) {
141        return false;
142    }
143
144    SkFILEWStream stream(outputPath.c_str());
145    if (!stream.isValid()) {
146        SkDebugf("Could not write to file %s\n", outputPath.c_str());
147        return false;
148    }
149    renderer.write(&stream);
150
151    return true;
152}
153
154/** Reads an skp file, renders it to pdf and writes the output to a pdf file
155 * @param inputPath The skp file to be read.
156 * @param outputDir Output dir.
157 * @param renderer The object responsible to render the skp object into pdf.
158 */
159static bool render_pdf(const SkString& inputPath, const SkString& outputDir,
160                       sk_tools::PdfRenderer& renderer) {
161    SkString inputFilename;
162    sk_tools::get_basename(&inputFilename, inputPath);
163
164    SkFILEStream inputStream;
165    inputStream.setPath(inputPath.c_str());
166    if (!inputStream.isValid()) {
167        SkDebugf("Could not open file %s\n", inputPath.c_str());
168        return false;
169    }
170
171    SkAutoTUnref<SkPicture> picture(SkPicture::CreateFromStream(&inputStream));
172
173    if (NULL == picture.get()) {
174        SkDebugf("Could not read an SkPicture from %s\n", inputPath.c_str());
175        return false;
176    }
177
178    SkDebugf("exporting... [%i %i] %s\n", picture->width(), picture->height(),
179             inputPath.c_str());
180
181    renderer.init(picture);
182
183    renderer.render();
184
185    bool success = write_output(outputDir, inputFilename, renderer);
186
187    renderer.end();
188    return success;
189}
190
191/** For each file in the directory or for the file passed in input, call
192 * render_pdf.
193 * @param input A directory or an skp file.
194 * @param outputDir Output dir.
195 * @param renderer The object responsible to render the skp object into pdf.
196 */
197static int process_input(const SkString& input, const SkString& outputDir,
198                         sk_tools::PdfRenderer& renderer) {
199    int failures = 0;
200    if (sk_isdir(input.c_str())) {
201        SkOSFile::Iter iter(input.c_str(), SKP_FILE_EXTENSION);
202        SkString inputFilename;
203        while (iter.next(&inputFilename)) {
204            SkString inputPath;
205            sk_tools::make_filepath(&inputPath, input, inputFilename);
206            if (!render_pdf(inputPath, outputDir, renderer)) {
207                ++failures;
208            }
209        }
210    } else {
211        SkString inputPath(input);
212        if (!render_pdf(inputPath, outputDir, renderer)) {
213            ++failures;
214        }
215    }
216    return failures;
217}
218
219static void parse_commandline(int argc, char* const argv[],
220                              SkTArray<SkString>* inputs,
221                              SkString* outputDir) {
222    const char* argv0 = argv[0];
223    char* const* stop = argv + argc;
224
225    for (++argv; argv < stop; ++argv) {
226        if ((0 == strcmp(*argv, "-h")) || (0 == strcmp(*argv, "--help"))) {
227            usage(argv0);
228            exit(-1);
229        } else if (0 == strcmp(*argv, "-w")) {
230            ++argv;
231            if (argv >= stop) {
232                SkDebugf("Missing outputDir for -w\n");
233                usage(argv0);
234                exit(-1);
235            }
236            *outputDir = SkString(*argv);
237        } else if (0 == strcmp(*argv, "--jpegQuality")) {
238            ++argv;
239            if (argv >= stop) {
240                SkDebugf("Missing argument for --jpegQuality\n");
241                usage(argv0);
242                exit(-1);
243            }
244            gJpegQuality = atoi(*argv);
245            if (gJpegQuality < -1 || gJpegQuality > 100) {
246                SkDebugf("Invalid argument for --jpegQuality\n");
247                usage(argv0);
248                exit(-1);
249            }
250        } else {
251            inputs->push_back(SkString(*argv));
252        }
253    }
254
255    if (inputs->count() < 1) {
256        usage(argv0);
257        exit(-1);
258    }
259}
260
261int tool_main_core(int argc, char** argv);
262int tool_main_core(int argc, char** argv) {
263    SkAutoGraphics ag;
264    SkTArray<SkString> inputs;
265
266    SkAutoTUnref<sk_tools::PdfRenderer>
267        renderer(SkNEW_ARGS(sk_tools::SimplePdfRenderer, (encode_to_dct_stream)));
268    SkASSERT(renderer.get());
269
270    SkString outputDir;
271    parse_commandline(argc, argv, &inputs, &outputDir);
272
273    int failures = 0;
274    for (int i = 0; i < inputs.count(); i ++) {
275        failures += process_input(inputs[i], outputDir, *renderer);
276    }
277
278    if (failures != 0) {
279        SkDebugf("Failed to render %i PDFs.\n", failures);
280        return 1;
281    }
282
283    return 0;
284}
285
286int tool_main(int argc, char** argv);
287int tool_main(int argc, char** argv) {
288#ifdef SK_USE_CDB
289    setUpDebuggingFromArgs(argv[0]);
290    __try {
291#endif
292      return tool_main_core(argc, argv);
293#ifdef SK_USE_CDB
294    }
295    __except(GenerateDumpAndPrintCallstack(GetExceptionInformation()))
296    {
297        return -1;
298    }
299#endif
300    return 0;
301}
302
303#if !defined SK_BUILD_FOR_IOS
304int main(int argc, char * const argv[]) {
305    return tool_main(argc, (char**) argv);
306}
307#endif
308