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