]> git.donarmstrong.com Git - xournal.git/blob - src/xo-file.c
Commit of current source code (post 0.2 release) - Denis.
[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   gboolean maybe_pdf;
564   
565   f = gzopen(filename, "r");
566   if (f==NULL) return FALSE;
567   
568   context = g_markup_parse_context_new(&parser, 0, NULL, NULL);
569   valid = TRUE;
570   tmpJournal.npages = 0;
571   tmpJournal.pages = NULL;
572   tmpJournal.last_attach_no = 0;
573   tmpPage = NULL;
574   tmpLayer = NULL;
575   tmpItem = NULL;
576   tmpFilename = filename;
577   error = NULL;
578   tmpBg_pdf = NULL;
579   maybe_pdf = TRUE;
580
581   while (valid && !gzeof(f)) {
582     len = gzread(f, buffer, 1000);
583     if (len<0) valid = FALSE;
584     if (maybe_pdf && len>=4 && !strncmp(buffer, "%PDF", 4))
585       { valid = FALSE; break; } // most likely pdf
586     else maybe_pdf = FALSE;
587     if (len<=0) break;
588     valid = g_markup_parse_context_parse(context, buffer, len, &error);
589   }
590   gzclose(f);
591   if (valid) valid = g_markup_parse_context_end_parse(context, &error);
592   if (tmpJournal.npages == 0) valid = FALSE;
593   g_markup_parse_context_free(context);
594   
595   if (!valid) {
596     delete_journal(&tmpJournal);
597     if (!maybe_pdf) return FALSE;
598     // essentially same as on_fileNewBackground from here on
599     ui.saved = TRUE;
600     close_journal();
601     while (bgpdf.status != STATUS_NOT_INIT) gtk_main_iteration();
602     new_journal();
603     ui.zoom = DEFAULT_ZOOM;
604     gnome_canvas_set_pixels_per_unit(canvas, ui.zoom);
605     update_page_stuff();
606     return init_bgpdf(filename, TRUE, DOMAIN_ABSOLUTE);
607   }
608   
609   ui.saved = TRUE; // force close_journal() to do its job
610   close_journal();
611   g_memmove(&journal, &tmpJournal, sizeof(struct Journal));
612   
613   // if we need to initialize a fresh pdf loader
614   if (tmpBg_pdf!=NULL) { 
615     while (bgpdf.status != STATUS_NOT_INIT) gtk_main_iteration();
616     if (tmpBg_pdf->file_domain == DOMAIN_ATTACH)
617       tmpfn = g_strdup_printf("%s.%s", filename, tmpBg_pdf->filename->s);
618     else
619       tmpfn = g_strdup(tmpBg_pdf->filename->s);
620     valid = init_bgpdf(tmpfn, FALSE, tmpBg_pdf->file_domain);
621     // in case the file name became invalid
622     if (!valid && tmpBg_pdf->file_domain != DOMAIN_ATTACH)
623       if (user_wants_second_chance(&tmpfn)) {
624         valid = init_bgpdf(tmpfn, FALSE, tmpBg_pdf->file_domain);
625         if (valid) { // change the file name...
626           g_free(tmpBg_pdf->filename->s);
627           tmpBg_pdf->filename->s = g_strdup(tmpfn);
628         }
629       }
630     if (valid) {
631       refstring_unref(bgpdf.filename);
632       bgpdf.filename = refstring_ref(tmpBg_pdf->filename);
633     } else {
634       dialog = gtk_message_dialog_new(GTK_WINDOW(winMain), GTK_DIALOG_MODAL,
635         GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "Could not open background '%s'.",
636         tmpfn);
637       gtk_dialog_run(GTK_DIALOG(dialog));
638       gtk_widget_destroy(dialog);
639     }
640     g_free(tmpfn);
641   }
642   
643   ui.pageno = 0;
644   ui.cur_page = (struct Page *)journal.pages->data;
645   ui.layerno = ui.cur_page->nlayers-1;
646   ui.cur_layer = (struct Layer *)(g_list_last(ui.cur_page->layers)->data);
647   ui.saved = TRUE;
648   ui.zoom = DEFAULT_ZOOM;
649   update_file_name(g_strdup(filename));
650   gnome_canvas_set_pixels_per_unit(canvas, ui.zoom);
651   make_canvas_items();
652   update_page_stuff();
653   gtk_adjustment_set_value(gtk_layout_get_vadjustment(GTK_LAYOUT(canvas)), 0);
654   return TRUE;
655 }
656
657 /************ file backgrounds *************/
658
659 struct Background *attempt_load_pix_bg(char *filename, gboolean attach)
660 {
661   struct Background *bg;
662   GdkPixbuf *pix;
663   
664   pix = gdk_pixbuf_new_from_file(filename, NULL);
665   if (pix == NULL) return NULL;
666   
667   bg = g_new(struct Background, 1);
668   bg->type = BG_PIXMAP;
669   bg->canvas_item = NULL;
670   bg->pixbuf = pix;
671   bg->pixbuf_scale = DEFAULT_ZOOM;
672   if (attach) {
673     bg->filename = new_refstring(NULL);
674     bg->file_domain = DOMAIN_ATTACH;
675   } else {
676     bg->filename = new_refstring(filename);
677     bg->file_domain = DOMAIN_ABSOLUTE;
678   }
679   return bg;
680 }
681
682 #define BUFSIZE 65536 // a reasonable buffer size for reads from gs pipe
683
684 GList *attempt_load_gv_bg(char *filename)
685 {
686   struct Background *bg;
687   GList *bg_list;
688   GdkPixbuf *pix;
689   GdkPixbufLoader *loader;
690   FILE *gs_pipe, *f;
691   unsigned char *buf;
692   char *pipename;
693   int buflen, remnlen, file_pageno;
694   
695   buf = g_malloc(BUFSIZE); // a reasonable buffer size
696   f = fopen(filename, "r");
697   if (fread(buf, 1, 4, f) !=4 ||
698         (strncmp((char *)buf, "%!PS", 4) && strncmp((char *)buf, "%PDF", 4))) {
699     fclose(f);
700     g_free(buf);
701     return NULL;
702   }
703   
704   fclose(f);
705   pipename = g_strdup_printf(GS_CMDLINE, (double)GS_BITMAP_DPI, filename);
706   gs_pipe = popen(pipename, "r");
707   g_free(pipename);
708   
709   bg_list = NULL;
710   remnlen = 0;
711   file_pageno = 0;
712   loader = NULL;
713   if (gs_pipe!=NULL)
714   while (!feof(gs_pipe)) {
715     if (!remnlen) { // new page: get a BMP header ?
716       buflen = fread(buf, 1, 54, gs_pipe);
717       if (buflen < 6) buflen += fread(buf, 1, 54-buflen, gs_pipe);
718       if (buflen < 6 || buf[0]!='B' || buf[1]!='M') break; // fatal: abort
719       remnlen = (int)(buf[5]<<24) + (buf[4]<<16) + (buf[3]<<8) + (buf[2]);
720       loader = gdk_pixbuf_loader_new();
721     }
722     else buflen = fread(buf, 1, (remnlen < BUFSIZE)?remnlen:BUFSIZE, gs_pipe);
723     remnlen -= buflen;
724     if (buflen == 0) break;
725     if (!gdk_pixbuf_loader_write(loader, buf, buflen, NULL)) break;
726     if (remnlen == 0) { // make a new bg
727       pix = gdk_pixbuf_loader_get_pixbuf(loader);
728       if (pix == NULL) break;
729       gdk_pixbuf_ref(pix);
730       gdk_pixbuf_loader_close(loader, NULL);
731       g_object_unref(loader);
732       loader = NULL;
733       bg = g_new(struct Background, 1);
734       bg->canvas_item = NULL;
735       bg->pixbuf = pix;
736       bg->pixbuf_scale = (GS_BITMAP_DPI/72.0);
737       bg->type = BG_PIXMAP;
738       bg->filename = new_refstring(NULL);
739       bg->file_domain = DOMAIN_ATTACH;
740       file_pageno++;
741       bg_list = g_list_append(bg_list, bg);
742     }
743   }
744   if (loader != NULL) gdk_pixbuf_loader_close(loader, NULL);
745   pclose(gs_pipe);
746   g_free(buf);
747   return bg_list;
748 }
749
750 struct Background *attempt_screenshot_bg(void)
751 {
752   struct Background *bg;
753   GdkPixbuf *pix;
754   XEvent x_event;
755   GError *error = NULL;
756   GdkWindow *window;
757   int x,y,w,h, status;
758   unsigned int tmp;
759   Window x_root, x_win;
760
761   x_root = gdk_x11_get_default_root_xwindow();
762   
763   if (!XGrabButton(GDK_DISPLAY(), AnyButton, AnyModifier, x_root, 
764       False, ButtonReleaseMask, GrabModeAsync, GrabModeSync, None, None))
765     return NULL;
766
767   XWindowEvent (GDK_DISPLAY(), x_root, ButtonReleaseMask, &x_event);
768   XUngrabButton(GDK_DISPLAY(), AnyButton, AnyModifier, x_root);
769
770   x_win = x_event.xbutton.subwindow;
771   if (x_win == None) x_win = x_root;
772
773   window = gdk_window_foreign_new_for_display(gdk_display_get_default(), x_win);
774     
775   gdk_window_get_geometry(window, &x, &y, &w, &h, NULL);
776   
777   pix = gdk_pixbuf_get_from_drawable(NULL, window,
778     gdk_colormap_get_system(), 0, 0, 0, 0, w, h);
779     
780   if (pix == NULL) return NULL;
781   
782   bg = g_new(struct Background, 1);
783   bg->type = BG_PIXMAP;
784   bg->canvas_item = NULL;
785   bg->pixbuf = pix;
786   bg->pixbuf_scale = DEFAULT_ZOOM;
787   bg->filename = new_refstring(NULL);
788   bg->file_domain = DOMAIN_ATTACH;
789   return bg;
790 }
791
792 /************** pdf annotation ***************/
793
794 /* free tmp directory */
795
796 void end_bgpdf_shutdown(void)
797 {
798   if (bgpdf.tmpdir!=NULL) {
799     if (bgpdf.tmpfile_copy!=NULL) {
800       g_unlink(bgpdf.tmpfile_copy);
801       g_free(bgpdf.tmpfile_copy);
802       bgpdf.tmpfile_copy = NULL;
803     }
804     g_rmdir(bgpdf.tmpdir);  
805     g_free(bgpdf.tmpdir);
806     bgpdf.tmpdir = NULL;
807   }
808   bgpdf.status = STATUS_NOT_INIT;
809 }
810
811 /* cancel a request */
812
813 void cancel_bgpdf_request(struct BgPdfRequest *req)
814 {
815   GList *list_link;
816   
817   list_link = g_list_find(bgpdf.requests, req);
818   if (list_link == NULL) return;
819   if (list_link->prev == NULL && bgpdf.pid > 0) {
820     // this is being processed: kill the child but don't remove the request yet
821     if (bgpdf.status == STATUS_RUNNING) bgpdf.status = STATUS_ABORTED;
822     kill(bgpdf.pid, SIGHUP);
823 //    printf("Cancelling a request - killing %d\n", bgpdf.pid);
824   }
825   else {
826     // remove the request
827     bgpdf.requests = g_list_delete_link(bgpdf.requests, list_link);
828     g_free(req);
829 //    printf("Cancelling a request - no kill needed\n");
830   }
831 }
832
833 /* sigchld callback */
834
835 void bgpdf_child_handler(GPid pid, gint status, gpointer data)
836 {
837   struct BgPdfRequest *req;
838   struct BgPdfPage *bgpg;
839   gchar *ppm_name;
840   GdkPixbuf *pixbuf;
841   
842   if (bgpdf.requests == NULL) return;
843   req = (struct BgPdfRequest *)bgpdf.requests->data;
844   
845   ppm_name = g_strdup_printf("%s/p-%06d.ppm", bgpdf.tmpdir, req->pageno);
846 //  printf("Child %d finished, should look for %s... \n", pid, ppm_name);
847   
848   if (bgpdf.status == STATUS_ABORTED || bgpdf.status == STATUS_SHUTDOWN)
849      pixbuf = NULL;
850   else
851      pixbuf = gdk_pixbuf_new_from_file(ppm_name, NULL);
852
853   unlink(ppm_name);
854   g_free(ppm_name);
855
856   if (pixbuf != NULL) { // success
857 //    printf("success\n");
858     while (req->pageno > bgpdf.npages) {
859       bgpg = g_new(struct BgPdfPage, 1);
860       bgpg->pixbuf = NULL;
861       bgpdf.pages = g_list_append(bgpdf.pages, bgpg);
862       bgpdf.npages++;
863     }
864     bgpg = g_list_nth_data(bgpdf.pages, req->pageno-1);
865     if (bgpg->pixbuf!=NULL) gdk_pixbuf_unref(bgpg->pixbuf);
866     bgpg->pixbuf = pixbuf;
867     bgpg->dpi = req->dpi;
868     if (req->initial_request && bgpdf.create_pages) {
869       bgpdf_create_page_with_bg(req->pageno, bgpg);
870       // create page n, resize it, set its bg - all without any undo effect
871     } else {
872       if (!req->is_printing) bgpdf_update_bg(req->pageno, bgpg);
873       // look for all pages with this bg, and update their bg pixmaps
874     }
875   }
876   else {
877 //    printf("failed or aborted\n");
878     bgpdf.create_pages = FALSE;
879     req->initial_request = FALSE;
880   }
881
882   bgpdf.pid = 0;
883   g_spawn_close_pid(pid);
884   
885   if (req->initial_request)
886     req->pageno++; // try for next page
887   else
888     bgpdf.requests = g_list_delete_link(bgpdf.requests, bgpdf.requests);
889   
890   if (bgpdf.status == STATUS_SHUTDOWN) {
891     end_bgpdf_shutdown();
892     return;
893   }
894   
895   bgpdf.status = STATUS_IDLE;
896   if (bgpdf.requests != NULL) bgpdf_spawn_child();
897 }
898
899 /* spawn a child to process the head request */
900
901 void bgpdf_spawn_child(void)
902 {
903   struct BgPdfRequest *req;
904   GPid pid;
905   gchar pageno_str[10], dpi_str[10];
906   gchar *pdf_filename = bgpdf.tmpfile_copy;
907   gchar *ppm_root = g_strdup_printf("%s/p", bgpdf.tmpdir);
908   gchar *argv[]= PDFTOPPM_ARGV;
909   GtkWidget *dialog;
910
911   if (bgpdf.requests == NULL) return;
912   req = (struct BgPdfRequest *)bgpdf.requests->data;
913   if (req->pageno > bgpdf.npages+1 || 
914       (!req->initial_request && req->pageno <= bgpdf.npages && 
915        req->dpi == ((struct BgPdfPage *)g_list_nth_data(bgpdf.pages, req->pageno-1))->dpi))
916   { // ignore this request - it's redundant, or in outer space
917     bgpdf.pid = 0;
918     bgpdf.status = STATUS_IDLE;
919     bgpdf.requests = g_list_delete_link(bgpdf.requests, bgpdf.requests);
920     g_free(ppm_root);
921     if (bgpdf.requests != NULL) bgpdf_spawn_child();
922     return;
923   }
924   g_snprintf(pageno_str, 10, "%d", req->pageno);
925   g_snprintf(dpi_str, 10, "%d", req->dpi);
926 /*  printf("Processing request for page %d at %d dpi -- in %s\n", 
927     req->pageno, req->dpi, ppm_root); */
928   if (!g_spawn_async(NULL, argv, NULL,
929                      G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_SEARCH_PATH, 
930                      NULL, NULL, &pid, NULL))
931   {
932     // couldn't spawn... abort this request, try next one maybe ?
933 //    printf("Couldn't spawn\n");
934     bgpdf.pid = 0;
935     bgpdf.status = STATUS_IDLE;
936     bgpdf.requests = g_list_delete_link(bgpdf.requests, bgpdf.requests);
937     g_free(ppm_root);
938     if (!bgpdf.has_failed) {
939       dialog = gtk_message_dialog_new(GTK_WINDOW(winMain), GTK_DIALOG_MODAL,
940         GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "Unable to start PDF loader %s.", argv[0]);
941       gtk_dialog_run(GTK_DIALOG(dialog));
942       gtk_widget_destroy(dialog);
943     }
944     bgpdf.has_failed = TRUE;
945     if (bgpdf.requests != NULL) bgpdf_spawn_child();
946     return;
947   }  
948
949 //  printf("Spawned process %d\n", pid);
950   bgpdf.pid = pid;
951   bgpdf.status = STATUS_RUNNING;
952   g_child_watch_add(pid, bgpdf_child_handler, NULL);
953   g_free(ppm_root);
954 }
955
956 /* make a request */
957
958 void add_bgpdf_request(int pageno, double zoom, gboolean printing)
959 {
960   struct BgPdfRequest *req, *cmp_req;
961   GList *list;
962   
963   if (bgpdf.status == STATUS_NOT_INIT || bgpdf.status == STATUS_SHUTDOWN)
964     return; // don't accept requests in those modes...
965   req = g_new(struct BgPdfRequest, 1);
966   req->is_printing = printing;
967   if (printing) req->dpi = PDFTOPPM_PRINTING_DPI;
968   else req->dpi = (int)floor(72*zoom+0.5);
969 //  printf("Enqueuing request for page %d at %d dpi\n", pageno, req->dpi);
970   if (pageno >= 1) {
971     // cancel any request this may supersede
972     for (list = bgpdf.requests; list != NULL; ) {
973       cmp_req = (struct BgPdfRequest *)list->data;
974       list = list->next;
975       if (!cmp_req->initial_request && cmp_req->pageno == pageno &&
976              cmp_req->is_printing == printing)
977         cancel_bgpdf_request(cmp_req);
978     }
979     req->pageno = pageno;
980     req->initial_request = FALSE;
981   } else {
982     req->pageno = 1;
983     req->initial_request = TRUE;
984   }
985   bgpdf.requests = g_list_append(bgpdf.requests, req);
986   if (!bgpdf.pid) bgpdf_spawn_child();
987 }
988
989 /* shutdown the PDF reader */
990
991 void shutdown_bgpdf(void)
992 {
993   GList *list;
994   struct BgPdfPage *pdfpg;
995   struct BgPdfRequest *req;
996   
997   if (bgpdf.status == STATUS_NOT_INIT || bgpdf.status == STATUS_SHUTDOWN) return;
998   refstring_unref(bgpdf.filename);
999   for (list = bgpdf.pages; list != NULL; list = list->next) {
1000     pdfpg = (struct BgPdfPage *)list->data;
1001     if (pdfpg->pixbuf!=NULL) gdk_pixbuf_unref(pdfpg->pixbuf);
1002   }
1003   g_list_free(bgpdf.pages);
1004   bgpdf.status = STATUS_SHUTDOWN;
1005   for (list = g_list_last(bgpdf.requests); list != NULL; ) {
1006     req = (struct BgPdfRequest *)list->data;
1007     list = list->prev;
1008     cancel_bgpdf_request(req);
1009   }
1010   if (!bgpdf.pid) end_bgpdf_shutdown();
1011   /* The above will ultimately remove all requests and kill the child if needed.
1012      The child will set status to STATUS_NOT_INIT, clear the requests list,
1013      empty tmpdir, ... except if there's no child! */
1014   /* note: it could look like there's a race condition here - if a child
1015      terminates and a new request is enqueued while we are destroying the
1016      queue - but actually the child handler callback is NOT a signal
1017      callback, so execution of this function is atomic */
1018 }
1019
1020 gboolean init_bgpdf(char *pdfname, gboolean create_pages, int file_domain)
1021 {
1022   FILE *f;
1023   gchar *filebuf;
1024   gsize filelen;
1025   
1026   if (bgpdf.status != STATUS_NOT_INIT) return FALSE;
1027   bgpdf.tmpfile_copy = NULL;
1028   bgpdf.tmpdir = mkdtemp(g_strdup(TMPDIR_TEMPLATE));
1029   if (!bgpdf.tmpdir) return FALSE;
1030   // make a local copy and check if it's a PDF
1031   if (!g_file_get_contents(pdfname, &filebuf, &filelen, NULL))
1032     { end_bgpdf_shutdown(); return FALSE; }
1033   if (filelen < 4 || strncmp(filebuf, "%PDF", 4))
1034     { g_free(filebuf); end_bgpdf_shutdown(); return FALSE; }
1035   bgpdf.tmpfile_copy = g_strdup_printf("%s/bg.pdf", bgpdf.tmpdir);
1036   f = fopen(bgpdf.tmpfile_copy, "w");
1037   if (f == NULL || fwrite(filebuf, 1, filelen, f) != filelen) 
1038     { g_free(filebuf); end_bgpdf_shutdown(); return FALSE; }
1039   fclose(f);
1040   g_free(filebuf);
1041   bgpdf.status = STATUS_IDLE;
1042   bgpdf.pid = 0;
1043   bgpdf.filename = new_refstring((file_domain == DOMAIN_ATTACH) ? "bg.pdf" : pdfname);
1044   bgpdf.file_domain = file_domain;
1045   bgpdf.npages = 0;
1046   bgpdf.pages = NULL;
1047   bgpdf.requests = NULL;
1048   bgpdf.create_pages = create_pages;
1049   bgpdf.has_failed = FALSE;
1050   add_bgpdf_request(-1, DEFAULT_ZOOM, FALSE); // request all pages
1051   return TRUE;
1052 }
1053
1054 // create page n, resize it, set its bg
1055 void bgpdf_create_page_with_bg(int pageno, struct BgPdfPage *bgpg)
1056 {
1057   struct Page *pg;
1058   struct Background *bg;
1059
1060   if (journal.npages < pageno) {
1061     bg = g_new(struct Background, 1);
1062     bg->canvas_item = NULL;
1063   } else {
1064     pg = (struct Page *)g_list_nth_data(journal.pages, pageno-1);
1065     bg = pg->bg;
1066     if (bg->type != BG_SOLID) return;
1067       // don't mess with a page the user has modified significantly...
1068   }
1069   
1070   bg->type = BG_PDF;
1071   bg->pixbuf = gdk_pixbuf_ref(bgpg->pixbuf);
1072   bg->filename = refstring_ref(bgpdf.filename);
1073   bg->file_domain = bgpdf.file_domain;
1074   bg->file_page_seq = pageno;
1075   bg->pixbuf_scale = DEFAULT_ZOOM;
1076   bg->pixbuf_dpi = bgpg->dpi;
1077
1078   if (journal.npages < pageno) {
1079     pg = new_page_with_bg(bg, 
1080             gdk_pixbuf_get_width(bg->pixbuf)*72.0/bg->pixbuf_dpi,
1081             gdk_pixbuf_get_height(bg->pixbuf)*72.0/bg->pixbuf_dpi);
1082     journal.pages = g_list_append(journal.pages, pg);
1083     journal.npages++;
1084   } else {
1085     pg->width = gdk_pixbuf_get_width(bgpg->pixbuf)*72.0/bg->pixbuf_dpi;
1086     pg->height = gdk_pixbuf_get_height(bgpg->pixbuf)*72.0/bg->pixbuf_dpi;
1087     make_page_clipbox(pg);
1088     update_canvas_bg(pg);
1089   }
1090   update_page_stuff();
1091 }
1092
1093 // look for all journal pages with given pdf bg, and update their bg pixmaps
1094 void bgpdf_update_bg(int pageno, struct BgPdfPage *bgpg)
1095 {
1096   GList *list;
1097   struct Page *pg;
1098   
1099   for (list = journal.pages; list!= NULL; list = list->next) {
1100     pg = (struct Page *)list->data;
1101     if (pg->bg->type == BG_PDF && pg->bg->file_page_seq == pageno) {
1102       if (pg->bg->pixbuf!=NULL) gdk_pixbuf_unref(pg->bg->pixbuf);
1103       pg->bg->pixbuf = gdk_pixbuf_ref(bgpg->pixbuf);
1104       pg->bg->pixbuf_dpi = bgpg->dpi;
1105       update_canvas_bg(pg);
1106     }
1107   }
1108 }
1109