]> git.donarmstrong.com Git - xournal.git/blob - src/xo-file.c
Initial revision
[xournal.git] / src / xo-file.c
1 #ifdef HAVE_CONFIG_H
2 #  include <config.h>
3 #endif
4
5 #include <signal.h>
6 #include <memory.h>
7 #include <string.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <gtk/gtk.h>
11 #include <libgnomecanvas/libgnomecanvas.h>
12 #include <zlib.h>
13 #include <math.h>
14 #include <gdk/gdkx.h>
15 #include <X11/Xlib.h>
16
17 #include "xournal.h"
18 #include "xo-interface.h"
19 #include "xo-support.h"
20 #include "xo-callbacks.h"
21 #include "xo-misc.h"
22 #include "xo-file.h"
23
24 const char *tool_names[NUM_STROKE_TOOLS] = {"pen", "eraser", "highlighter"};
25 const char *color_names[COLOR_MAX] = {"black", "blue", "red", "green",
26    "gray", "lightblue", "lightgreen", "magenta", "orange", "yellow", "white"};
27 const char *bgtype_names[3] = {"solid", "pixmap", "pdf"};
28 const char *bgcolor_names[COLOR_MAX] = {"", "blue", "pink", "green",
29    "", "", "", "", "orange", "yellow", "white"};
30 const char *bgstyle_names[4] = {"plain", "lined", "ruled", "graph"};
31 const char *file_domain_names[3] = {"absolute", "attach", "clone"};
32
33 // creates a new empty journal
34
35 void new_journal(void)
36 {
37   journal.npages = 1;
38   journal.pages = g_list_append(NULL, new_page(&ui.default_page));
39   journal.last_attach_no = 0;
40   ui.pageno = 0;
41   ui.layerno = 0;
42   ui.cur_page = (struct Page *) journal.pages->data;
43   ui.cur_layer = (struct Layer *) ui.cur_page->layers->data;
44   ui.saved = TRUE;
45   ui.filename = NULL;
46   update_file_name(NULL);
47 }
48
49 // check attachment names
50
51 void chk_attach_names(void)
52 {
53   GList *list;
54   struct Background *bg;
55   
56   for (list = journal.pages; list!=NULL; list = list->next) {
57     bg = ((struct Page *)list->data)->bg;
58     if (bg->type == BG_SOLID || bg->file_domain != DOMAIN_ATTACH ||
59         bg->filename->s != NULL) continue;
60     bg->filename->s = g_strdup_printf("bg_%d.png", ++journal.last_attach_no);
61   }
62 }
63
64 // saves the journal to a file: returns true on success, false on error
65
66 gboolean save_journal(const char *filename)
67 {
68   gzFile f;
69   struct Page *pg, *tmppg;
70   struct Layer *layer;
71   struct Item *item;
72   int i, is_clone;
73   char *tmpfn;
74   gchar *pdfbuf;
75   gsize pdflen;
76   gboolean success;
77   FILE *tmpf;
78   GList *pagelist, *layerlist, *itemlist, *list;
79   GtkWidget *dialog;
80   
81   f = gzopen(filename, "w");
82   if (f==NULL) return FALSE;
83   chk_attach_names();
84   
85   gzprintf(f, "<?xml version=\"1.0\" standalone=\"no\"?>\n"
86      "<title>Xournal document - see http://math.mit.edu/~auroux/software/xournal/</title>\n"
87      "<xournal version=\"" VERSION "\"/>\n");
88   for (pagelist = journal.pages; pagelist!=NULL; pagelist = pagelist->next) {
89     pg = (struct Page *)pagelist->data;
90     gzprintf(f, "<page width=\"%.2f\" height=\"%.2f\">\n", pg->width, pg->height);
91     gzprintf(f, "<background type=\"%s\" ", bgtype_names[pg->bg->type]); 
92     if (pg->bg->type == BG_SOLID) {
93       gzputs(f, "color=\"");
94       if (pg->bg->color_no >= 0) gzputs(f, bgcolor_names[pg->bg->color_no]);
95       else gzprintf(f, "#%08x", pg->bg->color_rgba);
96       gzprintf(f, "\" style=\"%s\" ", bgstyle_names[pg->bg->ruling]);
97     }
98     else if (pg->bg->type == BG_PIXMAP) {
99       is_clone = -1;
100       for (list = journal.pages, i = 0; list!=pagelist; list = list->next, i++) {
101         tmppg = (struct Page *)list->data;
102         if (tmppg->bg->type == BG_PIXMAP && 
103             tmppg->bg->pixbuf == pg->bg->pixbuf &&
104             tmppg->bg->filename == pg->bg->filename)
105           { is_clone = i; break; }
106       }
107       if (is_clone >= 0)
108         gzprintf(f, "domain=\"clone\" filename=\"%d\" ", is_clone);
109       else {
110         if (pg->bg->file_domain == DOMAIN_ATTACH) {
111           tmpfn = g_strdup_printf("%s.%s", filename, pg->bg->filename->s);
112           if (!gdk_pixbuf_save(pg->bg->pixbuf, tmpfn, "png", NULL, NULL)) {
113             dialog = gtk_message_dialog_new(GTK_WINDOW(winMain), GTK_DIALOG_MODAL,
114               GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, 
115               "Could not write background '%s'. Continuing anyway.", tmpfn);
116             gtk_dialog_run(GTK_DIALOG(dialog));
117             gtk_widget_destroy(dialog);
118           }
119           g_free(tmpfn);
120         }
121         gzprintf(f, "domain=\"%s\" filename=\"%s\" ", 
122           file_domain_names[pg->bg->file_domain], pg->bg->filename->s);
123       }
124     }
125     else if (pg->bg->type == BG_PDF) {
126       is_clone = 0;
127       for (list = journal.pages; list!=pagelist; list = list->next) {
128         tmppg = (struct Page *)list->data;
129         if (tmppg->bg->type == BG_PDF) { is_clone = 1; break; }
130       }
131       if (!is_clone) {
132         if (pg->bg->file_domain == DOMAIN_ATTACH) {
133           tmpfn = g_strdup_printf("%s.%s", filename, pg->bg->filename->s);
134           success = FALSE;
135           if (bgpdf.status != STATUS_NOT_INIT &&
136               g_file_get_contents(bgpdf.tmpfile_copy, &pdfbuf, &pdflen, NULL))
137           {
138             tmpf = fopen(tmpfn, "w");
139             if (tmpf != NULL && fwrite(pdfbuf, 1, pdflen, tmpf) == pdflen)
140               success = TRUE;
141             fclose(tmpf);
142           }
143           if (!success) {
144             dialog = gtk_message_dialog_new(GTK_WINDOW(winMain), GTK_DIALOG_MODAL,
145               GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, 
146               "Could not write background '%s'. Continuing anyway.", tmpfn);
147             gtk_dialog_run(GTK_DIALOG(dialog));
148             gtk_widget_destroy(dialog);
149           }
150           g_free(tmpfn);
151         }
152         gzprintf(f, "domain=\"%s\" filename=\"%s\" ", 
153           file_domain_names[pg->bg->file_domain], pg->bg->filename->s);
154       }
155       gzprintf(f, "pageno=\"%d\" ", pg->bg->file_page_seq);
156     }
157     gzprintf(f, "/>\n");
158     for (layerlist = pg->layers; layerlist!=NULL; layerlist = layerlist->next) {
159       layer = (struct Layer *)layerlist->data;
160       gzprintf(f, "<layer>\n");
161       for (itemlist = layer->items; itemlist!=NULL; itemlist = itemlist->next) {
162         item = (struct Item *)itemlist->data;
163         if (item->type == ITEM_STROKE) {
164           gzprintf(f, "<stroke tool=\"%s\" color=\"", 
165                           tool_names[item->brush.tool_type]);
166           if (item->brush.color_no >= 0)
167             gzputs(f, color_names[item->brush.color_no]);
168           else
169             gzprintf(f, "#%08x", item->brush.color_rgba);
170           gzprintf(f, "\" width=\"%.2f\">\n", item->brush.thickness);
171           for (i=0;i<2*item->path->num_points;i++)
172             gzprintf(f, "%.2f ", item->path->coords[i]);
173           gzprintf(f, "\n</stroke>\n");
174         }
175       }
176       gzprintf(f, "</layer>\n");
177     }
178     gzprintf(f, "</page>\n");
179   }
180   gzclose(f);
181   return TRUE;
182 }
183
184 // closes a journal: returns true on success, false on abort
185
186 gboolean close_journal(void)
187 {
188   if (!ok_to_close()) return FALSE;
189   
190   // free everything...
191   reset_selection();
192   clear_redo_stack();
193   clear_undo_stack();
194
195   shutdown_bgpdf();
196   delete_journal(&journal);
197   
198   return TRUE;
199   /* note: various members of ui and journal are now in invalid states,
200      use new_journal() to reinitialize them */
201 }
202
203 // the XML parser functions for open_journal()
204
205 struct Journal tmpJournal;
206 struct Page *tmpPage;
207 struct Layer *tmpLayer;
208 struct Item *tmpItem;
209 char *tmpFilename;
210 struct Background *tmpBg_pdf;
211
212 GError *xoj_invalid(void)
213 {
214   return g_error_new(G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT, "Invalid file contents");
215 }
216
217 void xoj_parser_start_element(GMarkupParseContext *context,
218    const gchar *element_name, const gchar **attribute_names, 
219    const gchar **attribute_values, gpointer user_data, GError **error)
220 {
221   int has_attr, i;
222   char *ptr;
223   struct Background *tmpbg;
224   char *tmpbg_filename;
225   GtkWidget *dialog;
226   
227   if (!strcmp(element_name, "title") || !strcmp(element_name, "xournal")) {
228     if (tmpPage != NULL) {
229       *error = xoj_invalid();
230       return;
231     }
232     // nothing special to do
233   }
234   else if (!strcmp(element_name, "page")) { // start of a page
235     if (tmpPage != NULL) {
236       *error = xoj_invalid();
237       return;
238     }
239     tmpPage = (struct Page *)g_malloc(sizeof(struct Page));
240     tmpPage->layers = NULL;
241     tmpPage->nlayers = 0;
242     tmpPage->group = NULL;
243     tmpPage->bg = g_new(struct Background, 1);
244     tmpPage->bg->type = -1;
245     tmpPage->bg->canvas_item = NULL;
246     tmpPage->bg->pixbuf = NULL;
247     tmpPage->bg->filename = NULL;
248     tmpJournal.pages = g_list_append(tmpJournal.pages, tmpPage);
249     tmpJournal.npages++;
250     // scan for height and width attributes
251     has_attr = 0;
252     while (*attribute_names!=NULL) {
253       if (!strcmp(*attribute_names, "width")) {
254         if (has_attr & 1) *error = xoj_invalid();
255         tmpPage->width = strtod(*attribute_values, &ptr);
256         if (ptr == *attribute_values) *error = xoj_invalid();
257         has_attr |= 1;
258       }
259       else if (!strcmp(*attribute_names, "height")) {
260         if (has_attr & 2) *error = xoj_invalid();
261         tmpPage->height = strtod(*attribute_values, &ptr);
262         if (ptr == *attribute_values) *error = xoj_invalid();
263         has_attr |= 2;
264       }
265       else *error = xoj_invalid();
266       attribute_names++;
267       attribute_values++;
268     }
269     if (has_attr!=3) *error = xoj_invalid();
270   }
271   else if (!strcmp(element_name, "background")) {
272     if (tmpPage == NULL || tmpLayer !=NULL || tmpPage->bg->type >= 0) {
273       *error = xoj_invalid();
274       return;
275     }
276     has_attr = 0;
277     while (*attribute_names!=NULL) {
278       if (!strcmp(*attribute_names, "type")) {
279         if (has_attr) *error = xoj_invalid();
280         for (i=0; i<3; i++)
281           if (!strcmp(*attribute_values, bgtype_names[i]))
282             tmpPage->bg->type = i;
283         if (tmpPage->bg->type < 0) *error = xoj_invalid();
284         has_attr |= 1;
285         if (tmpPage->bg->type == BG_PDF) {
286           if (tmpBg_pdf == NULL) tmpBg_pdf = tmpPage->bg;
287           else {
288             has_attr |= 24;
289             tmpPage->bg->filename = refstring_ref(tmpBg_pdf->filename);
290             tmpPage->bg->file_domain = tmpBg_pdf->file_domain;
291           }
292         }
293       }
294       else if (!strcmp(*attribute_names, "color")) {
295         if (tmpPage->bg->type != BG_SOLID) *error = xoj_invalid();
296         if (has_attr & 2) *error = xoj_invalid();
297         tmpPage->bg->color_no = COLOR_OTHER;
298         for (i=0; i<COLOR_MAX; i++)
299           if (!strcmp(*attribute_values, bgcolor_names[i])) {
300             tmpPage->bg->color_no = i;
301             tmpPage->bg->color_rgba = predef_bgcolors_rgba[i];
302           }
303         // there's also the case of hex (#rrggbbaa) colors
304         if (tmpPage->bg->color_no == COLOR_OTHER && **attribute_values == '#') {
305           tmpPage->bg->color_rgba = strtol(*attribute_values + 1, &ptr, 16);
306           if (*ptr!=0) *error = xoj_invalid();
307         }
308         has_attr |= 2;
309       }
310       else if (!strcmp(*attribute_names, "style")) {
311         if (tmpPage->bg->type != BG_SOLID) *error = xoj_invalid();
312         if (has_attr & 4) *error = xoj_invalid();
313         tmpPage->bg->ruling = -1;
314         for (i=0; i<4; i++)
315           if (!strcmp(*attribute_values, bgstyle_names[i]))
316             tmpPage->bg->ruling = i;
317         if (tmpPage->bg->ruling < 0) *error = xoj_invalid();
318         has_attr |= 4;
319       }
320       else if (!strcmp(*attribute_names, "domain")) {
321         if (tmpPage->bg->type <= BG_SOLID || (has_attr & 8))
322           { *error = xoj_invalid(); return; }
323         tmpPage->bg->file_domain = -1;
324         for (i=0; i<3; i++)
325           if (!strcmp(*attribute_values, file_domain_names[i]))
326             tmpPage->bg->file_domain = i;
327         if (tmpPage->bg->file_domain < 0)
328           { *error = xoj_invalid(); return; }
329         has_attr |= 8;
330       }
331       else if (!strcmp(*attribute_names, "filename")) {
332         if (tmpPage->bg->type <= BG_SOLID || (has_attr != 9)) 
333           { *error = xoj_invalid(); return; }
334         if (tmpPage->bg->file_domain == DOMAIN_CLONE) {
335           // filename is a page number
336           i = strtol(*attribute_values, &ptr, 10);
337           if (ptr == *attribute_values || i < 0 || i > tmpJournal.npages-2)
338             { *error = xoj_invalid(); return; }
339           tmpbg = ((struct Page *)g_list_nth_data(tmpJournal.pages, i))->bg;
340           if (tmpbg->type != tmpPage->bg->type)
341             { *error = xoj_invalid(); return; }
342           tmpPage->bg->filename = refstring_ref(tmpbg->filename);
343           tmpPage->bg->pixbuf = tmpbg->pixbuf;
344           if (tmpbg->pixbuf!=NULL) gdk_pixbuf_ref(tmpbg->pixbuf);
345           tmpPage->bg->file_domain = tmpbg->file_domain;
346         }
347         else {
348           tmpPage->bg->filename = new_refstring(*attribute_values);
349           if (tmpPage->bg->type == BG_PIXMAP) {
350             if (tmpPage->bg->file_domain == DOMAIN_ATTACH) {
351               tmpbg_filename = g_strdup_printf("%s.%s", tmpFilename, *attribute_values);
352               if (sscanf(*attribute_values, "bg_%d.png", &i) == 1)
353                 if (i > tmpJournal.last_attach_no) 
354                   tmpJournal.last_attach_no = i;
355             }
356             else tmpbg_filename = g_strdup(*attribute_values);
357             tmpPage->bg->pixbuf = gdk_pixbuf_new_from_file(tmpbg_filename, NULL);
358             if (tmpPage->bg->pixbuf == NULL) {
359               dialog = gtk_message_dialog_new(GTK_WINDOW(winMain), GTK_DIALOG_MODAL,
360                 GTK_MESSAGE_WARNING, GTK_BUTTONS_OK, 
361                 "Could not open background '%s'. Setting background to white.",
362                 tmpbg_filename);
363               gtk_dialog_run(GTK_DIALOG(dialog));
364               gtk_widget_destroy(dialog);
365               tmpPage->bg->pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8, 1, 1);
366               gdk_pixbuf_fill(tmpPage->bg->pixbuf, 0xffffffff); // solid white
367             }
368             g_free(tmpbg_filename);
369           }
370         }
371         has_attr |= 16;
372       }
373       else if (!strcmp(*attribute_names, "pageno")) {
374         if (tmpPage->bg->type != BG_PDF || (has_attr & 32))
375           { *error = xoj_invalid(); return; }
376         tmpPage->bg->file_page_seq = strtod(*attribute_values, &ptr);
377         if (ptr == *attribute_values) *error = xoj_invalid();
378         has_attr |= 32;
379       }
380       else *error = xoj_invalid();
381       attribute_names++;
382       attribute_values++;
383     }
384     if (tmpPage->bg->type < 0) *error = xoj_invalid();
385     if (tmpPage->bg->type == BG_SOLID && has_attr != 7) *error = xoj_invalid();
386     if (tmpPage->bg->type == BG_PIXMAP && has_attr != 25) *error = xoj_invalid();
387     if (tmpPage->bg->type == BG_PDF && has_attr != 57) *error = xoj_invalid();
388   }
389   else if (!strcmp(element_name, "layer")) { // start of a layer
390     if (tmpPage == NULL || tmpLayer != NULL) {
391       *error = xoj_invalid();
392       return;
393     }
394     tmpLayer = (struct Layer *)g_malloc(sizeof(struct Layer));
395     tmpLayer->items = NULL;
396     tmpLayer->nitems = 0;
397     tmpLayer->group = NULL;
398     tmpPage->layers = g_list_append(tmpPage->layers, tmpLayer);
399     tmpPage->nlayers++;
400   }
401   else if (!strcmp(element_name, "stroke")) { // start of a stroke
402     if (tmpLayer == NULL || tmpItem != NULL) {
403       *error = xoj_invalid();
404       return;
405     }
406     tmpItem = (struct Item *)g_malloc(sizeof(struct Item));
407     tmpItem->type = ITEM_STROKE;
408     tmpItem->path = NULL;
409     tmpItem->canvas_item = NULL;
410     tmpLayer->items = g_list_append(tmpLayer->items, tmpItem);
411     tmpLayer->nitems++;
412     // scan for tool, color, and width attributes
413     has_attr = 0;
414     while (*attribute_names!=NULL) {
415       if (!strcmp(*attribute_names, "width")) {
416         if (has_attr & 1) *error = xoj_invalid();
417         tmpItem->brush.thickness = strtod(*attribute_values, &ptr);
418         if (ptr == *attribute_values) *error = xoj_invalid();
419         has_attr |= 1;
420       }
421       else if (!strcmp(*attribute_names, "color")) {
422         if (has_attr & 2) *error = xoj_invalid();
423         tmpItem->brush.color_no = COLOR_OTHER;
424         for (i=0; i<COLOR_MAX; i++)
425           if (!strcmp(*attribute_values, color_names[i])) {
426             tmpItem->brush.color_no = i;
427             tmpItem->brush.color_rgba = predef_colors_rgba[i];
428           }
429         // there's also the case of hex (#rrggbbaa) colors
430         if (tmpItem->brush.color_no == COLOR_OTHER && **attribute_values == '#') {
431           tmpItem->brush.color_rgba = strtol(*attribute_values + 1, &ptr, 16);
432           if (*ptr!=0) *error = xoj_invalid();
433         }
434         has_attr |= 2;
435       }
436       else if (!strcmp(*attribute_names, "tool")) {
437         if (has_attr & 4) *error = xoj_invalid();
438         tmpItem->brush.tool_type = -1;
439         for (i=0; i<NUM_STROKE_TOOLS; i++)
440           if (!strcmp(*attribute_values, tool_names[i])) {
441             tmpItem->brush.tool_type = i;
442           }
443         if (tmpItem->brush.tool_type == -1) *error = xoj_invalid();
444         has_attr |= 4;
445       }
446       else *error = xoj_invalid();
447       attribute_names++;
448       attribute_values++;
449     }
450     if (has_attr!=7) *error = xoj_invalid();
451     // finish filling the brush info
452     tmpItem->brush.thickness_no = 0;  // who cares ?
453     tmpItem->brush.tool_options = 0;  // who cares ?
454     if (tmpItem->brush.tool_type == TOOL_HIGHLIGHTER) {
455       if (tmpItem->brush.color_no >= 0)
456         tmpItem->brush.color_rgba &= HILITER_ALPHA_MASK;
457     }
458   }
459 }
460
461 void xoj_parser_end_element(GMarkupParseContext *context,
462    const gchar *element_name, gpointer user_data, GError **error)
463 {
464   if (!strcmp(element_name, "page")) {
465     if (tmpPage == NULL || tmpLayer != NULL) {
466       *error = xoj_invalid();
467       return;
468     }
469     if (tmpPage->nlayers == 0 || tmpPage->bg->type < 0) *error = xoj_invalid();
470     tmpPage = NULL;
471   }
472   if (!strcmp(element_name, "layer")) {
473     if (tmpLayer == NULL || tmpItem != NULL) {
474       *error = xoj_invalid();
475       return;
476     }
477     tmpLayer = NULL;
478   }
479   if (!strcmp(element_name, "stroke")) {
480     if (tmpItem == NULL) {
481       *error = xoj_invalid();
482       return;
483     }
484     update_item_bbox(tmpItem);
485     tmpItem = NULL;
486   }
487 }
488
489 void xoj_parser_text(GMarkupParseContext *context,
490    const gchar *text, gsize text_len, gpointer user_data, GError **error)
491 {
492   const gchar *element_name, *ptr;
493   int n;
494   
495   element_name = g_markup_parse_context_get_element(context);
496   if (element_name == NULL) return;
497   if (!strcmp(element_name, "stroke")) {
498     ptr = text;
499     n = 0;
500     while (text_len > 0) {
501       realloc_cur_path(n/2 + 1);
502       ui.cur_path.coords[n] = strtod(text, (char **)(&ptr));
503       if (ptr == text) break;
504       text_len -= (ptr - text);
505       text = ptr;
506       n++;
507     }
508     if (n<4 || n&1) { *error = xoj_invalid(); return; }
509     tmpItem->path = gnome_canvas_points_new(n/2);
510     g_memmove(tmpItem->path->coords, ui.cur_path.coords, n*sizeof(double));
511   }
512 }
513
514 gboolean user_wants_second_chance(char **filename)
515 {
516   GtkWidget *dialog;
517   GtkFileFilter *filt_all, *filt_pdf;
518   GtkResponseType response;
519
520   dialog = gtk_message_dialog_new(GTK_WINDOW(winMain), GTK_DIALOG_MODAL,
521     GTK_MESSAGE_ERROR, GTK_BUTTONS_YES_NO, 
522     "Could not open background '%s'.\nSelect another file?",
523     *filename);
524   response = gtk_dialog_run(GTK_DIALOG(dialog));
525   gtk_widget_destroy(dialog);
526   if (response != GTK_RESPONSE_YES) return FALSE;
527   dialog = gtk_file_chooser_dialog_new("Open PDF", GTK_WINDOW (winMain),
528      GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
529      GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, NULL);
530
531   filt_all = gtk_file_filter_new();
532   gtk_file_filter_set_name(filt_all, "All files");
533   gtk_file_filter_add_pattern(filt_all, "*");
534   filt_pdf = gtk_file_filter_new();
535   gtk_file_filter_set_name(filt_pdf, "PDF files");
536   gtk_file_filter_add_pattern(filt_pdf, "*.pdf");
537   gtk_file_chooser_add_filter(GTK_FILE_CHOOSER (dialog), filt_pdf);
538   gtk_file_chooser_add_filter(GTK_FILE_CHOOSER (dialog), filt_all);
539
540   if (gtk_dialog_run(GTK_DIALOG(dialog)) != GTK_RESPONSE_ACCEPT) {
541     gtk_widget_destroy(dialog);
542     return FALSE;
543   }
544   g_free(*filename);
545   *filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog));
546   gtk_widget_destroy(dialog);
547   return TRUE;    
548 }
549
550 gboolean open_journal(char *filename)
551 {
552   const GMarkupParser parser = { xoj_parser_start_element, 
553                                  xoj_parser_end_element, 
554                                  xoj_parser_text, NULL, NULL};
555   GMarkupParseContext *context;
556   GError *error;
557   GtkWidget *dialog;
558   gboolean valid;
559   gzFile f;
560   char buffer[1000];
561   int len;
562   gchar *tmpfn;
563   
564   f = gzopen(filename, "r");
565   if (f==NULL) return FALSE;
566   
567   context = g_markup_parse_context_new(&parser, 0, NULL, NULL);
568   valid = TRUE;
569   tmpJournal.npages = 0;
570   tmpJournal.pages = NULL;
571   tmpJournal.last_attach_no = 0;
572   tmpPage = NULL;
573   tmpLayer = NULL;
574   tmpItem = NULL;
575   tmpFilename = filename;
576   error = NULL;
577   tmpBg_pdf = NULL;
578
579   while (valid && !gzeof(f)) {
580     len = gzread(f, buffer, 1000);
581     if (len<0) valid = FALSE;
582     if (len<=0) break;
583     valid = g_markup_parse_context_parse(context, buffer, len, &error);
584   }
585   gzclose(f);
586   if (valid) valid = g_markup_parse_context_end_parse(context, &error);
587   if (tmpJournal.npages == 0) valid = FALSE;
588   g_markup_parse_context_free(context);
589   if (!valid) {
590     delete_journal(&tmpJournal);
591     return FALSE;
592   }
593   
594   ui.saved = TRUE; // force close_journal() to do its job
595   close_journal();
596   g_memmove(&journal, &tmpJournal, sizeof(struct Journal));
597   
598   // if we need to initialize a fresh pdf loader
599   if (tmpBg_pdf!=NULL) { 
600     while (bgpdf.status != STATUS_NOT_INIT) gtk_main_iteration();
601     if (tmpBg_pdf->file_domain == DOMAIN_ATTACH)
602       tmpfn = g_strdup_printf("%s.%s", filename, tmpBg_pdf->filename->s);
603     else
604       tmpfn = g_strdup(tmpBg_pdf->filename->s);
605     valid = init_bgpdf(tmpfn, FALSE, tmpBg_pdf->file_domain);
606     // in case the file name became invalid
607     if (!valid && tmpBg_pdf->file_domain != DOMAIN_ATTACH)
608       if (user_wants_second_chance(&tmpfn)) {
609         valid = init_bgpdf(tmpfn, FALSE, tmpBg_pdf->file_domain);
610         if (valid) { // change the file name...
611           g_free(tmpBg_pdf->filename->s);
612           tmpBg_pdf->filename->s = g_strdup(tmpfn);
613         }
614       }
615     if (valid) {
616       refstring_unref(bgpdf.filename);
617       bgpdf.filename = refstring_ref(tmpBg_pdf->filename);
618     } else {
619       dialog = gtk_message_dialog_new(GTK_WINDOW(winMain), GTK_DIALOG_MODAL,
620         GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "Could not open background '%s'.",
621         tmpfn);
622       gtk_dialog_run(GTK_DIALOG(dialog));
623       gtk_widget_destroy(dialog);
624     }
625     g_free(tmpfn);
626   }
627   
628   ui.pageno = 0;
629   ui.cur_page = (struct Page *)journal.pages->data;
630   ui.layerno = ui.cur_page->nlayers-1;
631   ui.cur_layer = (struct Layer *)(g_list_last(ui.cur_page->layers)->data);
632   ui.saved = TRUE;
633   ui.zoom = DEFAULT_ZOOM;
634   update_file_name(filename);
635   gnome_canvas_set_pixels_per_unit(canvas, ui.zoom);
636   make_canvas_items();
637   update_page_stuff();
638   gtk_adjustment_set_value(gtk_layout_get_vadjustment(GTK_LAYOUT(canvas)), 0);
639   return TRUE;
640 }
641
642 /************ file backgrounds *************/
643
644 struct Background *attempt_load_pix_bg(char *filename, gboolean attach)
645 {
646   struct Background *bg;
647   GdkPixbuf *pix;
648   
649   pix = gdk_pixbuf_new_from_file(filename, NULL);
650   if (pix == NULL) return NULL;
651   
652   bg = g_new(struct Background, 1);
653   bg->type = BG_PIXMAP;
654   bg->canvas_item = NULL;
655   bg->pixbuf = pix;
656   bg->pixbuf_scale = DEFAULT_ZOOM;
657   if (attach) {
658     bg->filename = new_refstring(NULL);
659     bg->file_domain = DOMAIN_ATTACH;
660   } else {
661     bg->filename = new_refstring(filename);
662     bg->file_domain = DOMAIN_ABSOLUTE;
663   }
664   return bg;
665 }
666
667 #define BUFSIZE 65536 // a reasonable buffer size for reads from gs pipe
668
669 GList *attempt_load_gv_bg(char *filename)
670 {
671   struct Background *bg;
672   GList *bg_list;
673   GdkPixbuf *pix;
674   GdkPixbufLoader *loader;
675   FILE *gs_pipe, *f;
676   unsigned char *buf;
677   char *pipename;
678   int buflen, remnlen, file_pageno;
679   
680   buf = g_malloc(BUFSIZE); // a reasonable buffer size
681   f = fopen(filename, "r");
682   if (fread(buf, 1, 4, f) !=4 ||
683         (strncmp((char *)buf, "%!PS", 4) && strncmp((char *)buf, "%PDF", 4))) {
684     fclose(f);
685     g_free(buf);
686     return NULL;
687   }
688   
689   fclose(f);
690   pipename = g_strdup_printf(GS_CMDLINE, (double)GS_BITMAP_DPI, filename);
691   gs_pipe = popen(pipename, "r");
692   g_free(pipename);
693   
694   bg_list = NULL;
695   remnlen = 0;
696   file_pageno = 0;
697   loader = NULL;
698   if (gs_pipe!=NULL)
699   while (!feof(gs_pipe)) {
700     if (!remnlen) { // new page: get a BMP header ?
701       buflen = fread(buf, 1, 54, gs_pipe);
702       if (buflen < 6) buflen += fread(buf, 1, 54-buflen, gs_pipe);
703       if (buflen < 6 || buf[0]!='B' || buf[1]!='M') break; // fatal: abort
704       remnlen = (int)(buf[5]<<24) + (buf[4]<<16) + (buf[3]<<8) + (buf[2]);
705       loader = gdk_pixbuf_loader_new();
706     }
707     else buflen = fread(buf, 1, (remnlen < BUFSIZE)?remnlen:BUFSIZE, gs_pipe);
708     remnlen -= buflen;
709     if (buflen == 0) break;
710     if (!gdk_pixbuf_loader_write(loader, buf, buflen, NULL)) break;
711     if (remnlen == 0) { // make a new bg
712       pix = gdk_pixbuf_loader_get_pixbuf(loader);
713       if (pix == NULL) break;
714       gdk_pixbuf_ref(pix);
715       gdk_pixbuf_loader_close(loader, NULL);
716       g_object_unref(loader);
717       loader = NULL;
718       bg = g_new(struct Background, 1);
719       bg->canvas_item = NULL;
720       bg->pixbuf = pix;
721       bg->pixbuf_scale = (GS_BITMAP_DPI/72.0);
722       bg->type = BG_PIXMAP;
723       bg->filename = new_refstring(NULL);
724       bg->file_domain = DOMAIN_ATTACH;
725       file_pageno++;
726       bg_list = g_list_append(bg_list, bg);
727     }
728   }
729   if (loader != NULL) gdk_pixbuf_loader_close(loader, NULL);
730   pclose(gs_pipe);
731   g_free(buf);
732   return bg_list;
733 }
734
735 struct Background *attempt_screenshot_bg(void)
736 {
737   struct Background *bg;
738   GdkPixbuf *pix;
739   XEvent x_event;
740   GError *error = NULL;
741   GdkWindow *window;
742   int x,y,w,h, status;
743   unsigned int tmp;
744   Window x_root, x_win;
745
746   x_root = gdk_x11_get_default_root_xwindow();
747   
748   if (!XGrabButton(GDK_DISPLAY(), AnyButton, AnyModifier, x_root, 
749       False, ButtonReleaseMask, GrabModeAsync, GrabModeSync, None, None))
750     return NULL;
751
752   XWindowEvent (GDK_DISPLAY(), x_root, ButtonReleaseMask, &x_event);
753   XUngrabButton(GDK_DISPLAY(), AnyButton, AnyModifier, x_root);
754
755   x_win = x_event.xbutton.subwindow;
756   if (x_win == None) x_win = x_root;
757
758   window = gdk_window_foreign_new_for_display(gdk_display_get_default(), x_win);
759     
760   gdk_window_get_geometry(window, &x, &y, &w, &h, NULL);
761   
762   pix = gdk_pixbuf_get_from_drawable(NULL, window,
763     gdk_colormap_get_system(), 0, 0, 0, 0, w, h);
764     
765   if (pix == NULL) return NULL;
766   
767   bg = g_new(struct Background, 1);
768   bg->type = BG_PIXMAP;
769   bg->canvas_item = NULL;
770   bg->pixbuf = pix;
771   bg->pixbuf_scale = DEFAULT_ZOOM;
772   bg->filename = new_refstring(NULL);
773   bg->file_domain = DOMAIN_ATTACH;
774   return bg;
775 }
776
777 /************** pdf annotation ***************/
778
779 /* free tmp directory */
780
781 void end_bgpdf_shutdown(void)
782 {
783   if (bgpdf.tmpdir!=NULL) {
784     g_unlink(bgpdf.tmpfile_copy);
785     g_free(bgpdf.tmpfile_copy);
786     g_rmdir(bgpdf.tmpdir);  
787     g_free(bgpdf.tmpdir);
788     bgpdf.tmpdir = NULL;
789   }
790   bgpdf.status = STATUS_NOT_INIT;
791 }
792
793 /* cancel a request */
794
795 void cancel_bgpdf_request(struct BgPdfRequest *req)
796 {
797   GList *list_link;
798   
799   list_link = g_list_find(bgpdf.requests, req);
800   if (list_link == NULL) return;
801   if (list_link->prev == NULL && bgpdf.pid > 0) {
802     // this is being processed: kill the child but don't remove the request yet
803     if (bgpdf.status == STATUS_RUNNING) bgpdf.status = STATUS_ABORTED;
804     kill(bgpdf.pid, SIGHUP);
805 //    printf("Cancelling a request - killing %d\n", bgpdf.pid);
806   }
807   else {
808     // remove the request
809     bgpdf.requests = g_list_delete_link(bgpdf.requests, list_link);
810     g_free(req);
811 //    printf("Cancelling a request - no kill needed\n");
812   }
813 }
814
815 /* sigchld callback */
816
817 void bgpdf_child_handler(GPid pid, gint status, gpointer data)
818 {
819   struct BgPdfRequest *req;
820   struct BgPdfPage *bgpg;
821   gchar *ppm_name;
822   GdkPixbuf *pixbuf;
823   
824   if (bgpdf.requests == NULL) return;
825   req = (struct BgPdfRequest *)bgpdf.requests->data;
826   
827   ppm_name = g_strdup_printf("%s/p-%06d.ppm", bgpdf.tmpdir, req->pageno);
828 //  printf("Child %d finished, should look for %s... \n", pid, ppm_name);
829   
830   if (bgpdf.status == STATUS_ABORTED || bgpdf.status == STATUS_SHUTDOWN)
831      pixbuf = NULL;
832   else
833      pixbuf = gdk_pixbuf_new_from_file(ppm_name, NULL);
834
835   unlink(ppm_name);
836   g_free(ppm_name);
837
838   if (pixbuf != NULL) { // success
839 //    printf("success\n");
840     while (req->pageno > bgpdf.npages) {
841       bgpg = g_new(struct BgPdfPage, 1);
842       bgpg->pixbuf = NULL;
843       bgpdf.pages = g_list_append(bgpdf.pages, bgpg);
844       bgpdf.npages++;
845     }
846     bgpg = g_list_nth_data(bgpdf.pages, req->pageno-1);
847     if (bgpg->pixbuf!=NULL) gdk_pixbuf_unref(bgpg->pixbuf);
848     bgpg->pixbuf = pixbuf;
849     bgpg->dpi = req->dpi;
850     if (req->initial_request && bgpdf.create_pages) {
851       bgpdf_create_page_with_bg(req->pageno, bgpg);
852       // create page n, resize it, set its bg - all without any undo effect
853     } else {
854       if (!req->is_printing) bgpdf_update_bg(req->pageno, bgpg);
855       // look for all pages with this bg, and update their bg pixmaps
856     }
857   }
858   else {
859 //    printf("failed or aborted\n");
860     bgpdf.create_pages = FALSE;
861     req->initial_request = FALSE;
862   }
863
864   bgpdf.pid = 0;
865   g_spawn_close_pid(pid);
866   
867   if (req->initial_request)
868     req->pageno++; // try for next page
869   else
870     bgpdf.requests = g_list_delete_link(bgpdf.requests, bgpdf.requests);
871   
872   if (bgpdf.status == STATUS_SHUTDOWN) {
873     end_bgpdf_shutdown();
874     return;
875   }
876   
877   bgpdf.status = STATUS_IDLE;
878   if (bgpdf.requests != NULL) bgpdf_spawn_child();
879 }
880
881 /* spawn a child to process the head request */
882
883 void bgpdf_spawn_child(void)
884 {
885   struct BgPdfRequest *req;
886   GPid pid;
887   gchar pageno_str[10], dpi_str[10];
888   gchar *pdf_filename = bgpdf.tmpfile_copy;
889   gchar *ppm_root = g_strdup_printf("%s/p", bgpdf.tmpdir);
890   gchar *argv[]= PDFTOPPM_ARGV;
891   GtkWidget *dialog;
892
893   if (bgpdf.requests == NULL) return;
894   req = (struct BgPdfRequest *)bgpdf.requests->data;
895   if (req->pageno > bgpdf.npages+1 || 
896       (!req->initial_request && req->pageno <= bgpdf.npages && 
897        req->dpi == ((struct BgPdfPage *)g_list_nth_data(bgpdf.pages, req->pageno-1))->dpi))
898   { // ignore this request - it's redundant, or in outer space
899     bgpdf.pid = 0;
900     bgpdf.status = STATUS_IDLE;
901     bgpdf.requests = g_list_delete_link(bgpdf.requests, bgpdf.requests);
902     g_free(ppm_root);
903     if (bgpdf.requests != NULL) bgpdf_spawn_child();
904     return;
905   }
906   g_snprintf(pageno_str, 10, "%d", req->pageno);
907   g_snprintf(dpi_str, 10, "%d", req->dpi);
908 /*  printf("Processing request for page %d at %d dpi -- in %s\n", 
909     req->pageno, req->dpi, ppm_root); */
910   if (!g_spawn_async(NULL, argv, NULL,
911                      G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_SEARCH_PATH, 
912                      NULL, NULL, &pid, NULL))
913   {
914     // couldn't spawn... abort this request, try next one maybe ?
915 //    printf("Couldn't spawn\n");
916     bgpdf.pid = 0;
917     bgpdf.status = STATUS_IDLE;
918     bgpdf.requests = g_list_delete_link(bgpdf.requests, bgpdf.requests);
919     g_free(ppm_root);
920     if (!bgpdf.has_failed) {
921       dialog = gtk_message_dialog_new(GTK_WINDOW(winMain), GTK_DIALOG_MODAL,
922         GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "Unable to start PDF loader %s.", argv[0]);
923       gtk_dialog_run(GTK_DIALOG(dialog));
924       gtk_widget_destroy(dialog);
925     }
926     bgpdf.has_failed = TRUE;
927     if (bgpdf.requests != NULL) bgpdf_spawn_child();
928     return;
929   }  
930
931 //  printf("Spawned process %d\n", pid);
932   bgpdf.pid = pid;
933   bgpdf.status = STATUS_RUNNING;
934   g_child_watch_add(pid, bgpdf_child_handler, NULL);
935   g_free(ppm_root);
936 }
937
938 /* make a request */
939
940 void add_bgpdf_request(int pageno, double zoom, gboolean printing)
941 {
942   struct BgPdfRequest *req, *cmp_req;
943   GList *list;
944   
945   if (bgpdf.status == STATUS_NOT_INIT || bgpdf.status == STATUS_SHUTDOWN)
946     return; // don't accept requests in those modes...
947   req = g_new(struct BgPdfRequest, 1);
948   req->is_printing = printing;
949   if (printing) req->dpi = PDFTOPPM_PRINTING_DPI;
950   else req->dpi = (int)floor(72*zoom+0.5);
951 //  printf("Enqueuing request for page %d at %d dpi\n", pageno, req->dpi);
952   if (pageno >= 1) {
953     // cancel any request this may supersede
954     for (list = bgpdf.requests; list != NULL; ) {
955       cmp_req = (struct BgPdfRequest *)list->data;
956       list = list->next;
957       if (!cmp_req->initial_request && cmp_req->pageno == pageno &&
958              cmp_req->is_printing == printing)
959         cancel_bgpdf_request(cmp_req);
960     }
961     req->pageno = pageno;
962     req->initial_request = FALSE;
963   } else {
964     req->pageno = 1;
965     req->initial_request = TRUE;
966   }
967   bgpdf.requests = g_list_append(bgpdf.requests, req);
968   if (!bgpdf.pid) bgpdf_spawn_child();
969 }
970
971 /* shutdown the PDF reader */
972
973 void shutdown_bgpdf(void)
974 {
975   GList *list;
976   struct BgPdfPage *pdfpg;
977   struct BgPdfRequest *req;
978   
979   if (bgpdf.status == STATUS_NOT_INIT || bgpdf.status == STATUS_SHUTDOWN) return;
980   refstring_unref(bgpdf.filename);
981   for (list = bgpdf.pages; list != NULL; list = list->next) {
982     pdfpg = (struct BgPdfPage *)list->data;
983     if (pdfpg->pixbuf!=NULL) gdk_pixbuf_unref(pdfpg->pixbuf);
984   }
985   g_list_free(bgpdf.pages);
986   bgpdf.status = STATUS_SHUTDOWN;
987   for (list = g_list_last(bgpdf.requests); list != NULL; ) {
988     req = (struct BgPdfRequest *)list->data;
989     list = list->prev;
990     cancel_bgpdf_request(req);
991   }
992   if (!bgpdf.pid) end_bgpdf_shutdown();
993   /* The above will ultimately remove all requests and kill the child if needed.
994      The child will set status to STATUS_NOT_INIT, clear the requests list,
995      empty tmpdir, ... except if there's no child! */
996   /* note: it could look like there's a race condition here - if a child
997      terminates and a new request is enqueued while we are destroying the
998      queue - but actually the child handler callback is NOT a signal
999      callback, so execution of this function is atomic */
1000 }
1001
1002 gboolean init_bgpdf(char *pdfname, gboolean create_pages, int file_domain)
1003 {
1004   FILE *f;
1005   gchar *filebuf;
1006   gsize filelen;
1007   
1008   if (bgpdf.status != STATUS_NOT_INIT) return FALSE;
1009   bgpdf.tmpdir = mkdtemp(g_strdup(TMPDIR_TEMPLATE));
1010   if (!bgpdf.tmpdir) return FALSE;
1011   // make a local copy and check if it's a PDF
1012   if (!g_file_get_contents(pdfname, &filebuf, &filelen, NULL)) return FALSE;
1013   if (filelen < 4 || strncmp(filebuf, "%PDF", 4))
1014     { g_free(filebuf); return FALSE; }
1015   bgpdf.tmpfile_copy = g_strdup_printf("%s/bg.pdf", bgpdf.tmpdir);
1016   f = fopen(bgpdf.tmpfile_copy, "w");
1017   if (f == NULL || fwrite(filebuf, 1, filelen, f) != filelen) 
1018     { g_free(filebuf); return FALSE; }
1019   fclose(f);
1020   g_free(filebuf);
1021   bgpdf.status = STATUS_IDLE;
1022   bgpdf.pid = 0;
1023   bgpdf.filename = new_refstring((file_domain == DOMAIN_ATTACH) ? "bg.pdf" : pdfname);
1024   bgpdf.file_domain = file_domain;
1025   bgpdf.npages = 0;
1026   bgpdf.pages = NULL;
1027   bgpdf.requests = NULL;
1028   bgpdf.create_pages = create_pages;
1029   bgpdf.has_failed = FALSE;
1030   add_bgpdf_request(-1, DEFAULT_ZOOM, FALSE); // request all pages
1031   return TRUE;
1032 }
1033
1034 // create page n, resize it, set its bg
1035 void bgpdf_create_page_with_bg(int pageno, struct BgPdfPage *bgpg)
1036 {
1037   struct Page *pg;
1038   struct Background *bg;
1039
1040   if (journal.npages < pageno) {
1041     bg = g_new(struct Background, 1);
1042     bg->canvas_item = NULL;
1043   } else {
1044     pg = (struct Page *)g_list_nth_data(journal.pages, pageno-1);
1045     bg = pg->bg;
1046     if (bg->type != BG_SOLID) return;
1047       // don't mess with a page the user has modified significantly...
1048   }
1049   
1050   bg->type = BG_PDF;
1051   bg->pixbuf = gdk_pixbuf_ref(bgpg->pixbuf);
1052   bg->filename = refstring_ref(bgpdf.filename);
1053   bg->file_domain = bgpdf.file_domain;
1054   bg->file_page_seq = pageno;
1055   bg->pixbuf_scale = DEFAULT_ZOOM;
1056   bg->pixbuf_dpi = bgpg->dpi;
1057
1058   if (journal.npages < pageno) {
1059     pg = new_page_with_bg(bg, 
1060             gdk_pixbuf_get_width(bg->pixbuf)*72.0/bg->pixbuf_dpi,
1061             gdk_pixbuf_get_height(bg->pixbuf)*72.0/bg->pixbuf_dpi);
1062     journal.pages = g_list_append(journal.pages, pg);
1063     journal.npages++;
1064   } else {
1065     pg->width = gdk_pixbuf_get_width(bgpg->pixbuf)*72.0/bg->pixbuf_dpi;
1066     pg->height = gdk_pixbuf_get_height(bgpg->pixbuf)*72.0/bg->pixbuf_dpi;
1067     make_page_clipbox(pg);
1068     update_canvas_bg(pg);
1069   }
1070   update_page_stuff();
1071 }
1072
1073 // look for all journal pages with given pdf bg, and update their bg pixmaps
1074 void bgpdf_update_bg(int pageno, struct BgPdfPage *bgpg)
1075 {
1076   GList *list;
1077   struct Page *pg;
1078   
1079   for (list = journal.pages; list!= NULL; list = list->next) {
1080     pg = (struct Page *)list->data;
1081     if (pg->bg->type == BG_PDF && pg->bg->file_page_seq == pageno) {
1082       if (pg->bg->pixbuf!=NULL) gdk_pixbuf_unref(pg->bg->pixbuf);
1083       pg->bg->pixbuf = gdk_pixbuf_ref(bgpg->pixbuf);
1084       pg->bg->pixbuf_dpi = bgpg->dpi;
1085       update_canvas_bg(pg);
1086     }
1087   }
1088 }
1089