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