Debian Codegraph @

src/Document.vala

raw
1 /* Document.vala
2 *
3 * Copyright 2023-2024 Diego Iván <[email protected]>
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 *
18 * SPDX-License-Identifier: GPL-3.0-or-later
19 */
20
21 public class PaperClip.Document : Object {
22 private ListStore keyword_list = new ListStore (typeof(StringObject));
23
24 private const string PDF_NS = "http://ns.adobe.com/pdf/1.3/";
25 private const string XMP_NS = "http://ns.adobe.com/xap/1.0/";
26
27 private Poppler.Document _document;
28 private Poppler.Document document {
29 get {
30 return _document;
31 }
32 set {
33 _document = value;
34 deserialize_keywords ();
35 }
36 }
37
38 public File original_file { get; construct; }
39 public File cached_file { get; private set; }
40
41 [CCode (notify = false)]
42 public bool has_xmp { get; private set; default = false; }
43
44 public string author {
45 owned get {
46 return document.author ?? "";
47 }
48 set {
49 document.author = value;
50 }
51 }
52
53 public string creator {
54 owned get {
55 return document.creator ?? "";
56 }
57 set {
58 document.creator = value;
59 }
60 }
61
62 public string subject {
63 owned get {
64 return document.subject ?? "";
65 }
66 set {
67 document.subject = value;
68 }
69 }
70
71 public string title {
72 owned get {
73 return document.title ?? "";
74 }
75 set {
76 document.title = value;
77 }
78 }
79
80 public string producer {
81 owned get {
82 return document.producer ?? "";
83 }
84 set {
85 document.producer = value;
86 }
87 }
88
89 public DateTime creation_date {
90 owned get {
91 return document.creation_datetime;
92 }
93 set {
94 document.creation_datetime = value;
95 }
96 }
97
98 public DateTime modification_date {
99 owned get {
100 return document.mod_datetime;
101 }
102 set {
103 document.mod_datetime = value;
104 }
105 }
106
107 [CCode (notify = false)]
108 public ListModel keywords {
109 get {
110 return keyword_list;
111 }
112 }
113
114 [CCode (notify = false)]
115 public string format {
116 owned get {
117 return document.format ?? _("Unknown");
118 }
119 }
120
121 [CCode (notify = false)]
122 public string layout {
123 owned get {
124 return layout_to_string ();
125 }
126 }
127
128 [CCode (notify = false)]
129 public string print_duplex {
130 owned get {
131 return print_duplex_to_string ();
132 }
133 }
134
135 [CCode (notify = false)]
136 public string subtype {
137 owned get {
138 return subtype_to_string ();
139 }
140 }
141
142 [CCode (notify = false)]
143 public string[] viewer_preferences {
144 owned get {
145 return viewer_preferences_to_string_array ();
146 }
147 }
148
149 [CCode (notify = false)]
150 public string[] permissions {
151 owned get {
152 return permissions_to_string_array ();
153 }
154 }
155
156 [CCode (notify = false)]
157 public bool contains_attachments {
158 get {
159 return document.has_attachments ();
160 }
161 }
162
163 [CCode (notify = false)]
164 public bool contains_javascript {
165 get {
166 return document.has_javascript ();
167 }
168 }
169
170 [CCode (notify = false)]
171 public int n_pages {
172 get {
173 return document.get_n_pages ();
174 }
175 }
176
177 public signal void keyword_changed ();
178
179 public async Document (File original_file, string? password = null) throws Error {
180 Object (original_file: original_file);
181 yield load_document (password);
182
183 try {
184 has_xmp = yield ThreadManager.run_in_thread<bool> (load_xmp);
185 } catch (Error e) {
186 critical (e.message);
187 }
188 }
189
190 // This function is intended to be run from a background thread
191 private bool load_xmp () throws Error {
192 bool success = false;
193 var xmp_file = new Xmp.File ();
194 bool opened_file = xmp_file.open_file (original_file.get_path (),
195 READ | INBACKGROUND | ONLYXMP);
196 if (!opened_file) {
197 debug ("Failed to open file with XMP");
198 return false;
199 }
200 var xmp_meta = new Xmp.Meta.empty ();
201 success = xmp_file.get_xmp (xmp_meta);
202 if (!success) {
203 debug ("File does not have XMP metadata");
204 }
205 xmp_file?.close (NOOPTION);
206 return success;
207 }
208
209 public async void save (string uri) {
210 try {
211 yield ThreadManager.run_in_thread<void> (() => save_thread (uri));
212 } catch (Error e) {
213 critical (e.message);
214 }
215 }
216
217 private void save_thread (string uri) throws Error {
218 lock (document) {
219 document.keywords = serialize_keywords ();
220 document.save (uri);
221 }
222 if (has_xmp) {
223 save_xmp (uri);
224 }
225 }
226
227 private void save_xmp (string uri) throws XmpError {
228 var xmp_file = new Xmp.File ();
229 Xmp.OpenFileOptions options = FORUPDATE | INBACKGROUND;
230 var file = File.new_for_uri (uri);
231 string path = file.get_path ();
232 bool success = xmp_file.open_file (path, options);
233
234 if (!success) {
235 int error = Xmp.get_error ();
236 throw new XmpError.FAILED_TO_OPEN (@"Failed to open $path XMP metadata. Error: $error");
237 }
238
239 var xmp_meta = new Xmp.Meta.empty ();
240 bool has_meta = xmp_file.get_xmp (xmp_meta);
241 if (!has_meta) {
242 throw new XmpError.NO_XMP (@"$path has no XMP Metadata");
243 }
244
245 xmp_meta.set_property (Xmp.Namespace.PDF, "Producer", producer, 0x0);
246 xmp_meta.set_property (Xmp.Namespace.XAP, "CreatorTool", creator, 0x0);
247 xmp_meta.set_property (Xmp.Namespace.PDF, "Keywords", document.keywords, 0x0);
248
249 xmp_meta.set_localized_text (Xmp.Namespace.DC, "title", "x", "x-default", title, 0x0);
250
251 if (creation_date == null) {
252 xmp_meta.delete_property (Xmp.Namespace.XAP, "CreateDate");
253 } else {
254 xmp_meta.set_property_date (Xmp.Namespace.XAP, "CreateDate", creation_date, 0x0);
255 }
256
257 if (modification_date == null) {
258 xmp_meta.delete_property (Xmp.Namespace.XAP, "ModifyDate");
259 } else {
260 xmp_meta.set_property_date (Xmp.Namespace.XAP, "ModifyDate", modification_date, 0x0);
261 }
262
263 var metadata_date = new DateTime.now_local ();
264 xmp_meta.set_property_date (Xmp.Namespace.XAP, "MetadataDate", metadata_date, 0x0);
265
266 if (xmp_file.can_put_xmp (xmp_meta)) {
267 debug ("Writing XMP Metadata");
268 xmp_file.put_xmp (xmp_meta);
269 }
270 xmp_file.close (SAFEUPDATE);
271 }
272
273 public void add_keyword (string keyword) {
274 var keyword_object = new StringObject (keyword);
275 keyword_object.notify["str"].connect (() => keyword_changed ());
276 keyword_list.append (keyword_object);
277 }
278
279 public bool remove_keyword (string keyword) {
280 for (int i = 0; i < keyword_list.get_n_items (); i++) {
281 var item = (StringObject) keyword_list.get_item (i);
282 if (keyword == item.str) {
283 keyword_list.remove (i);
284 return true;
285 }
286 }
287 return false;
288 }
289
290 public Poppler.Page get_page_for_index (int index) {
291 return document.get_page (index);
292 }
293
294 private void deserialize_keywords () {
295 if (document.keywords == null) {
296 return;
297 }
298
299 string[] keyword_array = document.keywords.split (",");
300 foreach (string keyword in keyword_array) {
301 add_keyword (keyword);
302 }
303 }
304
305 private string serialize_keywords () {
306 string format = "";
307 for (int i = 0; i < keyword_list.get_n_items (); i++) {
308 var item = (StringObject) keyword_list.get_item (i);
309 format += "%s".printf (item.str);
310 if (i == keywords.get_n_items () - 1) {
311 break;
312 }
313 format += ",";
314 }
315 return format;
316 }
317
318 private string layout_to_string () {
319 switch (document.page_layout) {
320 case ONE_COLUMN:
321 return _("Pages in one column");
322
323 case SINGLE_PAGE:
324 return _("One page at a time");
325
326 case TWO_COLUMN_LEFT:
327 return _("Odd numbered pages on the left");
328
329 case TWO_COLUMN_RIGHT:
330 return _("Odd numbered pages on the right");
331
332 case TWO_PAGE_LEFT:
333 return _("Two odd numbered pages on the left");
334
335 case TWO_PAGE_RIGHT:
336 return _("Two odd numbered pages on the right");
337
338 case UNSET:
339 default:
340 return _("No specific layout");
341 }
342 }
343
344 private string[] viewer_preferences_to_string_array () {
345 string[] preferences_array = {};
346 Poppler.ViewerPreferences preferences = document.viewer_preferences;
347
348 if (CENTER_WINDOW in preferences) {
349 preferences_array += _("Center document's window");
350 }
351
352 if (DIRECTION_RTL in preferences) {
353 preferences_array += _("Reading order is right to left");
354 }
355
356 if (DISPLAY_DOC_TITLE in preferences) {
357 preferences_array += _("Display document's title");
358 }
359
360 if (FIT_WINDOW in preferences) {
361 preferences_array += _("Fit document to window");
362 }
363
364 if (HIDE_MENUBAR in preferences) {
365 preferences_array += _("Hide window menubar");
366 }
367
368 if (HIDE_TOOLBAR in preferences) {
369 preferences_array += _("Hide window toolbars");
370 }
371
372 if (HIDE_WINDOWUI in preferences) {
373 preferences_array += _("Hide UI elements");
374 }
375
376 if (UNSET in preferences) {
377 preferences_array += _("No preferences");
378 }
379
380 return preferences_array;
381 }
382
383 private string[] permissions_to_string_array () {
384 string[] permission_array = {};
385 Poppler.Permissions permission_flags = document.permissions;
386
387 if (OK_TO_ADD_NOTES in permission_flags) {
388 permission_array += _("Adding notes");
389 }
390
391 if (OK_TO_ASSEMBLE in permission_flags) {
392 permission_array += _("Inserting elements");
393 }
394
395 if (OK_TO_COPY in permission_flags) {
396 permission_array += _("Copying");
397 }
398
399 if (OK_TO_EXTRACT_CONTENTS in permission_flags) {
400 permission_array += _("Extracting contents");
401 }
402
403 if (OK_TO_FILL_FORM in permission_flags) {
404 permission_array += _("Filling interactive forms");
405 }
406
407 if (OK_TO_MODIFY in permission_flags) {
408 permission_array += _("Modifying");
409 }
410
411 if (OK_TO_PRINT in permission_flags) {
412 permission_array += _("Printing");
413 }
414
415 if (OK_TO_PRINT_HIGH_RESOLUTION in permission_flags) {
416 permission_array += _("Printing in high resolution");
417 }
418
419 return permission_array;
420 }
421
422 private string print_duplex_to_string () {
423 switch (document.print_duplex) {
424 case DUPLEX_FLIP_LONG_EDGE:
425 return _("Flip on the long edge");
426
427 case DUPLEX_FLIP_SHORT_EDGE:
428 return _("Flip on the short edge");
429
430 case SIMPLEX:
431 return _("Only single sided");
432
433 case NONE:
434 default:
435 return _("No preference");
436 }
437 }
438
439 private string subtype_to_string () {
440 switch (document.subtype) {
441 case PDF_A:
442 return "ISO 19005";
443
444 case PDF_E:
445 return "ISO 24517";
446
447 case PDF_UA:
448 return "ISO 14289";
449
450 case PDF_VT:
451 return "ISO 16612";
452
453 case PDF_X:
454 return "ISO 15930";
455
456 case UNSET:
457 case NONE:
458 default:
459 return _("Not compliant");
460 }
461 }
462
463 private async void load_document (string? password) throws Error {
464 cached_file = yield create_copy_from_original ();
465 document = new Poppler.Document.from_gfile (cached_file, password);
466 }
467
468 private async File create_copy_from_original () throws Error {
469 var launcher = new SubprocessLauncher (NONE);
470 unowned string tmp_dir = Environment.get_tmp_dir ();
471 string destination_path = Path.build_path (Path.DIR_SEPARATOR_S,
472 tmp_dir,
473 "copies");
474 int res = DirUtils.create_with_parents (destination_path, 0777);
475 if (res < 0) {
476 throw new IOError.FAILED (@"Could not create $destination_path");
477 }
478
479 string destination_file = Path.build_filename (destination_path,
480 "%s".printf (original_file.get_basename ()));
481
482 Subprocess copy_process = launcher.spawn("cp", original_file.get_path(), destination_path);
483 bool success = yield copy_process.wait_async ();
484 if (!success) {
485 critical ("Processed failed");
486 }
487
488
489 var copy_file = File.new_for_path (destination_file);
490
491 return copy_file;
492 }
493 }
494
495 public class PaperClip.StringObject : Object {
496 public string str { get; set; default = ""; }
497
498 public StringObject (string str) {
499 Object (str: str);
500 }
501 }
502
503 public errordomain PaperClip.XmpError {
504 NO_XMP,
505 FAILED_TO_OPEN;
506 }