blob: 4ca1903d21b2a23fce8268b994b513044a30c7ec [file] [log] [blame]
halcanary34422612015-10-12 10:11:18 -07001/*
2 * Copyright 2015 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
halcanaryffe54002016-03-29 09:09:29 -07008#include "SkMilestone.h"
halcanary34422612015-10-12 10:11:18 -07009#include "SkPDFMetadata.h"
10#include "SkPDFTypes.h"
bungeman221524d2016-01-05 14:59:40 -080011#include <utility>
halcanary34422612015-10-12 10:11:18 -070012
13#ifdef SK_PDF_GENERATE_PDFA
14#include "SkMD5.h"
15#endif
16
17static SkString pdf_date(const SkTime::DateTime& dt) {
18 int timeZoneMinutes = SkToInt(dt.fTimeZoneMinutes);
19 char timezoneSign = timeZoneMinutes >= 0 ? '+' : '-';
20 int timeZoneHours = SkTAbs(timeZoneMinutes) / 60;
21 timeZoneMinutes = SkTAbs(timeZoneMinutes) % 60;
22 return SkStringPrintf(
23 "D:%04u%02u%02u%02u%02u%02u%c%02d'%02d'",
24 static_cast<unsigned>(dt.fYear), static_cast<unsigned>(dt.fMonth),
25 static_cast<unsigned>(dt.fDay), static_cast<unsigned>(dt.fHour),
26 static_cast<unsigned>(dt.fMinute),
27 static_cast<unsigned>(dt.fSecond), timezoneSign, timeZoneHours,
28 timeZoneMinutes);
29}
30
halcanaryffe54002016-03-29 09:09:29 -070031#define SKPDF_STRING(X) SKPDF_STRING_IMPL(X)
32#define SKPDF_STRING_IMPL(X) #X
33
halcanary34422612015-10-12 10:11:18 -070034SkPDFObject* SkPDFMetadata::createDocumentInformationDict() const {
halcanaryece83922016-03-08 08:32:12 -080035 auto dict = sk_make_sp<SkPDFDict>();
halcanary34422612015-10-12 10:11:18 -070036 static const char* keys[] = {
37 "Title", "Author", "Subject", "Keywords", "Creator"};
38 for (const char* key : keys) {
39 for (const SkDocument::Attribute& keyValue : fInfo) {
40 if (keyValue.fKey.equals(key)) {
41 dict->insertString(key, keyValue.fValue);
42 }
43 }
44 }
halcanaryffe54002016-03-29 09:09:29 -070045 dict->insertString("Producer", "Skia/PDF m" SKPDF_STRING(SK_MILESTONE));
halcanary34422612015-10-12 10:11:18 -070046 if (fCreation) {
47 dict->insertString("CreationDate", pdf_date(*fCreation.get()));
48 }
49 if (fModified) {
50 dict->insertString("ModDate", pdf_date(*fModified.get()));
51 }
halcanaryfcad44b2016-03-06 14:47:10 -080052 return dict.release();
halcanary34422612015-10-12 10:11:18 -070053}
54
55#ifdef SK_PDF_GENERATE_PDFA
56SkPDFMetadata::UUID SkPDFMetadata::uuid() const {
57 // The main requirement is for the UUID to be unique; the exact
58 // format of the data that will be hashed is not important.
59 SkMD5 md5;
60 const char uuidNamespace[] = "org.skia.pdf\n";
61 md5.write(uuidNamespace, strlen(uuidNamespace));
benjaminwagnerec4d4d72016-03-25 12:59:53 -070062 double msec = SkTime::GetMSecs();
halcanary34422612015-10-12 10:11:18 -070063 md5.write(&msec, sizeof(msec));
64 SkTime::DateTime dateTime;
65 SkTime::GetDateTime(&dateTime);
66 md5.write(&dateTime, sizeof(dateTime));
67 if (fCreation) {
68 md5.write(fCreation.get(), sizeof(fCreation));
69 }
70 if (fModified) {
71 md5.write(fModified.get(), sizeof(fModified));
72 }
73 for (const auto& kv : fInfo) {
74 md5.write(kv.fKey.c_str(), kv.fKey.size());
75 md5.write("\037", 1);
76 md5.write(kv.fValue.c_str(), kv.fValue.size());
77 md5.write("\036", 1);
78 }
79 SkMD5::Digest digest;
80 md5.finish(digest);
81 // See RFC 4122, page 6-7.
82 digest.data[6] = (digest.data[6] & 0x0F) | 0x30;
83 digest.data[8] = (digest.data[6] & 0x3F) | 0x80;
84 static_assert(sizeof(digest) == sizeof(UUID), "uuid_size");
85 SkPDFMetadata::UUID uuid;
86 memcpy(&uuid, &digest, sizeof(digest));
87 return uuid;
88}
89
90SkPDFObject* SkPDFMetadata::CreatePdfId(const UUID& doc, const UUID& instance) {
91 // /ID [ <81b14aafa313db63dbd6f981e49f94f4>
92 // <81b14aafa313db63dbd6f981e49f94f4> ]
halcanaryece83922016-03-08 08:32:12 -080093 auto array = sk_make_sp<SkPDFArray>();
halcanary34422612015-10-12 10:11:18 -070094 static_assert(sizeof(UUID) == 16, "uuid_size");
95 array->appendString(
96 SkString(reinterpret_cast<const char*>(&doc), sizeof(UUID)));
97 array->appendString(
98 SkString(reinterpret_cast<const char*>(&instance), sizeof(UUID)));
halcanaryfcad44b2016-03-06 14:47:10 -080099 return array.release();
halcanary34422612015-10-12 10:11:18 -0700100}
101
102// Improvement on SkStringPrintf to allow for arbitrarily long output.
103// TODO: replace SkStringPrintf.
104static SkString sk_string_printf(const char* format, ...) {
105#ifdef SK_BUILD_FOR_WIN
106 va_list args;
107 va_start(args, format);
108 char buffer[1024];
109 int length = _vsnprintf_s(buffer, sizeof(buffer), _TRUNCATE, format, args);
110 va_end(args);
111 if (length >= 0 && length < (int)sizeof(buffer)) {
112 return SkString(buffer, length);
113 }
114 va_start(args, format);
115 length = _vscprintf(format, args);
116 va_end(args);
117
118 SkString string((size_t)length);
119 va_start(args, format);
120 SkDEBUGCODE(int check = ) _vsnprintf_s(string.writable_str(), length + 1,
121 _TRUNCATE, format, args);
122 va_end(args);
123 SkASSERT(check == length);
124 SkASSERT(string[length] == '\0');
bungeman221524d2016-01-05 14:59:40 -0800125 return std::move(string);
halcanary34422612015-10-12 10:11:18 -0700126#else // C99/C++11 standard vsnprintf
127 // TODO: When all compilers support this, remove windows-specific code.
128 va_list args;
129 va_start(args, format);
130 char buffer[1024];
131 int length = vsnprintf(buffer, sizeof(buffer), format, args);
132 va_end(args);
133 if (length < 0) {
134 return SkString();
135 }
136 if (length < (int)sizeof(buffer)) {
137 return SkString(buffer, length);
138 }
139 SkString string((size_t)length);
140 va_start(args, format);
141 SkDEBUGCODE(int check = )
142 vsnprintf(string.writable_str(), length + 1, format, args);
143 va_end(args);
144 SkASSERT(check == length);
145 SkASSERT(string[length] == '\0');
bungeman221524d2016-01-05 14:59:40 -0800146 return std::move(string);
halcanary34422612015-10-12 10:11:18 -0700147#endif
148}
149
150static const SkString get(const SkTArray<SkDocument::Attribute>& info,
151 const char* key) {
152 for (const auto& keyValue : info) {
153 if (keyValue.fKey.equals(key)) {
154 return keyValue.fValue;
155 }
156 }
157 return SkString();
158}
159
160#define HEXIFY(INPUT_PTR, OUTPUT_PTR, HEX_STRING, BYTE_COUNT) \
161 do { \
162 for (int i = 0; i < (BYTE_COUNT); ++i) { \
163 uint8_t value = *(INPUT_PTR)++; \
164 *(OUTPUT_PTR)++ = (HEX_STRING)[value >> 4]; \
165 *(OUTPUT_PTR)++ = (HEX_STRING)[value & 0xF]; \
166 } \
167 } while (false)
168static SkString uuid_to_string(const SkPDFMetadata::UUID& uuid) {
169 // 8-4-4-4-12
170 char buffer[36]; // [32 + 4]
171 static const char gHex[] = "0123456789abcdef";
172 SkASSERT(strlen(gHex) == 16);
173 char* ptr = buffer;
174 const uint8_t* data = uuid.fData;
175 HEXIFY(data, ptr, gHex, 4);
176 *ptr++ = '-';
177 HEXIFY(data, ptr, gHex, 2);
178 *ptr++ = '-';
179 HEXIFY(data, ptr, gHex, 2);
180 *ptr++ = '-';
181 HEXIFY(data, ptr, gHex, 2);
182 *ptr++ = '-';
183 HEXIFY(data, ptr, gHex, 6);
184 SkASSERT(ptr == buffer + 36);
185 SkASSERT(data == uuid.fData + 16);
186 return SkString(buffer, 36);
187}
188#undef HEXIFY
189
190namespace {
halcanary70d15542015-11-22 12:55:04 -0800191class PDFXMLObject final : public SkPDFObject {
halcanary34422612015-10-12 10:11:18 -0700192public:
bungeman221524d2016-01-05 14:59:40 -0800193 PDFXMLObject(SkString xml) : fXML(std::move(xml)) {}
halcanary34422612015-10-12 10:11:18 -0700194 void emitObject(SkWStream* stream,
195 const SkPDFObjNumMap& omap,
196 const SkPDFSubstituteMap& smap) const override {
197 SkPDFDict dict("Metadata");
198 dict.insertName("Subtype", "XML");
199 dict.insertInt("Length", fXML.size());
200 dict.emitObject(stream, omap, smap);
201 static const char streamBegin[] = " stream\n";
202 stream->write(streamBegin, strlen(streamBegin));
203 // Do not compress this. The standard requires that a
204 // program that does not understand PDF can grep for
205 // "<?xpacket" and extracť the entire XML.
206 stream->write(fXML.c_str(), fXML.size());
207 static const char streamEnd[] = "\nendstream";
208 stream->write(streamEnd, strlen(streamEnd));
209 }
210
211private:
212 const SkString fXML;
213};
214} // namespace
215
216static int count_xml_escape_size(const SkString& input) {
217 int extra = 0;
218 for (size_t i = 0; i < input.size(); ++i) {
219 if (input[i] == '&') {
220 extra += 4; // strlen("&amp;") - strlen("&")
221 } else if (input[i] == '<') {
222 extra += 3; // strlen("&lt;") - strlen("<")
223 }
224 }
225 return extra;
226}
227
228const SkString escape_xml(const SkString& input,
229 const char* before = nullptr,
230 const char* after = nullptr) {
231 if (input.size() == 0) {
232 return input;
233 }
234 // "&" --> "&amp;" and "<" --> "&lt;"
235 // text is assumed to be in UTF-8
236 // all strings are xml content, not attribute values.
237 size_t beforeLen = before ? strlen(before) : 0;
238 size_t afterLen = after ? strlen(after) : 0;
239 int extra = count_xml_escape_size(input);
240 SkString output(input.size() + extra + beforeLen + afterLen);
241 char* out = output.writable_str();
242 if (before) {
243 strncpy(out, before, beforeLen);
244 out += beforeLen;
245 }
246 static const char kAmp[] = "&amp;";
247 static const char kLt[] = "&lt;";
248 for (size_t i = 0; i < input.size(); ++i) {
249 if (input[i] == '&') {
250 strncpy(out, kAmp, strlen(kAmp));
251 out += strlen(kAmp);
252 } else if (input[i] == '<') {
253 strncpy(out, kLt, strlen(kLt));
254 out += strlen(kLt);
255 } else {
256 *out++ = input[i];
257 }
258 }
259 if (after) {
260 strncpy(out, after, afterLen);
261 out += afterLen;
262 }
263 // Validate that we haven't written outside of our string.
264 SkASSERT(out == &output.writable_str()[output.size()]);
265 *out = '\0';
halcanary78daeff2016-04-07 12:34:59 -0700266 return output;
halcanary34422612015-10-12 10:11:18 -0700267}
268
269SkPDFObject* SkPDFMetadata::createXMPObject(const UUID& doc,
270 const UUID& instance) const {
271 static const char templateString[] =
272 "<?xpacket begin=\"\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n"
273 "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"\n"
274 " x:xmptk=\"Adobe XMP Core 5.4-c005 78.147326, "
275 "2012/08/23-13:03:03\">\n"
276 "<rdf:RDF "
277 "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n"
278 "<rdf:Description rdf:about=\"\"\n"
279 " xmlns:xmp=\"http://ns.adobe.com/xap/1.0/\"\n"
280 " xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n"
281 " xmlns:xmpMM=\"http://ns.adobe.com/xap/1.0/mm/\"\n"
282 " xmlns:pdf=\"http://ns.adobe.com/pdf/1.3/\"\n"
283 " xmlns:pdfaid=\"http://www.aiim.org/pdfa/ns/id/\">\n"
284 "<pdfaid:part>2</pdfaid:part>\n"
285 "<pdfaid:conformance>B</pdfaid:conformance>\n"
286 "%s" // ModifyDate
287 "%s" // CreateDate
halcanary34422612015-10-12 10:11:18 -0700288 "%s" // xmp:CreatorTool
289 "<dc:format>application/pdf</dc:format>\n"
290 "%s" // dc:title
291 "%s" // dc:description
292 "%s" // author
293 "%s" // keywords
294 "<xmpMM:DocumentID>uuid:%s</xmpMM:DocumentID>\n"
295 "<xmpMM:InstanceID>uuid:%s</xmpMM:InstanceID>\n"
halcanary8cd4a242016-04-07 08:56:15 -0700296 "<pdf:Producer>Skia/PDF m" SKPDF_STRING(SK_MILESTONE) "</pdf:Producer>\n"
halcanary34422612015-10-12 10:11:18 -0700297 "%s" // pdf:Keywords
298 "</rdf:Description>\n"
299 "</rdf:RDF>\n"
300 "</x:xmpmeta>\n" // Note: the standard suggests 4k of padding.
301 "<?xpacket end=\"w\"?>\n";
302
303 SkString creationDate;
304 SkString modificationDate;
halcanary34422612015-10-12 10:11:18 -0700305 if (fCreation) {
306 SkString tmp;
307 fCreation->toISO8601(&tmp);
308 SkASSERT(0 == count_xml_escape_size(tmp));
309 // YYYY-mm-ddTHH:MM:SS[+|-]ZZ:ZZ; no need to escape
310 creationDate = sk_string_printf("<xmp:CreateDate>%s</xmp:CreateDate>\n",
311 tmp.c_str());
312 }
313 if (fModified) {
314 SkString tmp;
315 fModified->toISO8601(&tmp);
316 SkASSERT(0 == count_xml_escape_size(tmp));
317 modificationDate = sk_string_printf(
318 "<xmp:ModifyDate>%s</xmp:ModifyDate>\n", tmp.c_str());
halcanary34422612015-10-12 10:11:18 -0700319 }
halcanary78daeff2016-04-07 12:34:59 -0700320 SkString title = escape_xml(
321 get(fInfo, "Title"),
322 "<dc:title><rdf:Alt><rdf:li xml:lang=\"x-default\">",
323 "</rdf:li></rdf:Alt></dc:title>\n");
324 SkString author = escape_xml(
325 get(fInfo, "Author"), "<dc:creator><rdf:Bag><rdf:li>",
326 "</rdf:li></rdf:Bag></dc:creator>\n");
halcanary34422612015-10-12 10:11:18 -0700327 // TODO: in theory, XMP can support multiple authors. Split on a delimiter?
halcanary78daeff2016-04-07 12:34:59 -0700328 SkString subject = escape_xml(
329 get(fInfo, "Subject"),
330 "<dc:description><rdf:Alt><rdf:li xml:lang=\"x-default\">",
331 "</rdf:li></rdf:Alt></dc:description>\n");
332 SkString keywords1 = escape_xml(
333 get(fInfo, "Keywords"), "<dc:subject><rdf:Bag><rdf:li>",
334 "</rdf:li></rdf:Bag></dc:subject>\n");
335 SkString keywords2 = escape_xml(
336 get(fInfo, "Keywords"), "<pdf:Keywords>",
337 "</pdf:Keywords>\n");
halcanary34422612015-10-12 10:11:18 -0700338
339 // TODO: in theory, keywords can be a list too.
340 SkString creator = escape_xml(get(fInfo, "Creator"), "<xmp:CreatorTool>",
341 "</xmp:CreatorTool>\n");
342 SkString documentID = uuid_to_string(doc); // no need to escape
343 SkASSERT(0 == count_xml_escape_size(documentID));
344 SkString instanceID = uuid_to_string(instance);
345 SkASSERT(0 == count_xml_escape_size(instanceID));
346 return new PDFXMLObject(sk_string_printf(
347 templateString, modificationDate.c_str(), creationDate.c_str(),
halcanary78daeff2016-04-07 12:34:59 -0700348 creator.c_str(), title.c_str(),
halcanary34422612015-10-12 10:11:18 -0700349 subject.c_str(), author.c_str(), keywords1.c_str(),
350 documentID.c_str(), instanceID.c_str(), keywords2.c_str()));
351}
352
353#endif // SK_PDF_GENERATE_PDFA
halcanary8cd4a242016-04-07 08:56:15 -0700354
355#undef SKPDF_STRING
356#undef SKPDF_STRING_IMPL
357