]> git.donarmstrong.com Git - xournal.git/blob - src/xo-file.c
option to force pdf background rendering via cairo (slower, nicer)
[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 <locale.h>
15 #include <glib.h>
16 #include <glib/gstdio.h>
17 #include <poppler/glib/poppler.h>
18
19 #ifndef WIN32
20  #include <gdk/gdkx.h>
21  #include <X11/Xlib.h>
22 #endif
23
24 #include "xournal.h"
25 #include "xo-interface.h"
26 #include "xo-support.h"
27 #include "xo-callbacks.h"
28 #include "xo-misc.h"
29 #include "xo-file.h"
30 #include "xo-paint.h"
31
32 const char *tool_names[NUM_TOOLS] = {"pen", "eraser", "highlighter", "text", "", "selectrect", "vertspace", "hand"};
33 const char *color_names[COLOR_MAX] = {"black", "blue", "red", "green",
34    "gray", "lightblue", "lightgreen", "magenta", "orange", "yellow", "white"};
35 const char *bgtype_names[3] = {"solid", "pixmap", "pdf"};
36 const char *bgcolor_names[COLOR_MAX] = {"", "blue", "pink", "green",
37    "", "", "", "", "orange", "yellow", "white"};
38 const char *bgstyle_names[4] = {"plain", "lined", "ruled", "graph"};
39 const char *file_domain_names[3] = {"absolute", "attach", "clone"};
40 const char *unit_names[4] = {"cm", "in", "px", "pt"};
41 int PDFTOPPM_PRINTING_DPI, GS_BITMAP_DPI;
42
43 // creates a new empty journal
44
45 void new_journal(void)
46 {
47   journal.npages = 1;
48   journal.pages = g_list_append(NULL, new_page(&ui.default_page));
49   journal.last_attach_no = 0;
50   ui.pageno = 0;
51   ui.layerno = 0;
52   ui.cur_page = (struct Page *) journal.pages->data;
53   ui.cur_layer = (struct Layer *) ui.cur_page->layers->data;
54   ui.saved = TRUE;
55   ui.filename = NULL;
56   update_file_name(NULL);
57 }
58
59 // check attachment names
60
61 void chk_attach_names(void)
62 {
63   GList *list;
64   struct Background *bg;
65   
66   for (list = journal.pages; list!=NULL; list = list->next) {
67     bg = ((struct Page *)list->data)->bg;
68     if (bg->type == BG_SOLID || bg->file_domain != DOMAIN_ATTACH ||
69         bg->filename->s != NULL) continue;
70     bg->filename->s = g_strdup_printf("bg_%d.png", ++journal.last_attach_no);
71   }
72 }
73
74 // saves the journal to a file: returns true on success, false on error
75
76 gboolean save_journal(const char *filename)
77 {
78   gzFile f;
79   struct Page *pg, *tmppg;
80   struct Layer *layer;
81   struct Item *item;
82   int i, is_clone;
83   char *tmpfn, *tmpstr;
84   gboolean success;
85   FILE *tmpf;
86   GList *pagelist, *layerlist, *itemlist, *list;
87   GtkWidget *dialog;
88   
89   f = gzopen(filename, "wb");
90   if (f==NULL) return FALSE;
91   chk_attach_names();
92
93   setlocale(LC_NUMERIC, "C");
94   
95   gzprintf(f, "<?xml version=\"1.0\" standalone=\"no\"?>\n"
96      "<xournal version=\"" VERSION "\">\n"
97      "<title>Xournal document - see http://math.mit.edu/~auroux/software/xournal/</title>\n");
98   for (pagelist = journal.pages; pagelist!=NULL; pagelist = pagelist->next) {
99     pg = (struct Page *)pagelist->data;
100     gzprintf(f, "<page width=\"%.2f\" height=\"%.2f\">\n", pg->width, pg->height);
101     gzprintf(f, "<background type=\"%s\" ", bgtype_names[pg->bg->type]); 
102     if (pg->bg->type == BG_SOLID) {
103       gzputs(f, "color=\"");
104       if (pg->bg->color_no >= 0) gzputs(f, bgcolor_names[pg->bg->color_no]);
105       else gzprintf(f, "#%08x", pg->bg->color_rgba);
106       gzprintf(f, "\" style=\"%s\" ", bgstyle_names[pg->bg->ruling]);
107     }
108     else if (pg->bg->type == BG_PIXMAP) {
109       is_clone = -1;
110       for (list = journal.pages, i = 0; list!=pagelist; list = list->next, i++) {
111         tmppg = (struct Page *)list->data;
112         if (tmppg->bg->type == BG_PIXMAP && 
113             tmppg->bg->pixbuf == pg->bg->pixbuf &&
114             tmppg->bg->filename == pg->bg->filename)
115           { is_clone = i; break; }
116       }
117       if (is_clone >= 0)
118         gzprintf(f, "domain=\"clone\" filename=\"%d\" ", is_clone);
119       else {
120         if (pg->bg->file_domain == DOMAIN_ATTACH) {
121           tmpfn = g_strdup_printf("%s.%s", filename, pg->bg->filename->s);
122           if (!gdk_pixbuf_save(pg->bg->pixbuf, tmpfn, "png", NULL, NULL)) {
123             dialog = gtk_message_dialog_new(GTK_WINDOW(winMain), GTK_DIALOG_MODAL,
124               GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, 
125               _("Could not write background '%s'. Continuing anyway."), tmpfn);
126             gtk_dialog_run(GTK_DIALOG(dialog));
127             gtk_widget_destroy(dialog);
128           }
129           g_free(tmpfn);
130         }
131         tmpstr = g_markup_escape_text(pg->bg->filename->s, -1);
132         gzprintf(f, "domain=\"%s\" filename=\"%s\" ", 
133           file_domain_names[pg->bg->file_domain], tmpstr);
134         g_free(tmpstr);
135       }
136     }
137     else if (pg->bg->type == BG_PDF) {
138       is_clone = 0;
139       for (list = journal.pages; list!=pagelist; list = list->next) {
140         tmppg = (struct Page *)list->data;
141         if (tmppg->bg->type == BG_PDF) { is_clone = 1; break; }
142       }
143       if (!is_clone) {
144         if (pg->bg->file_domain == DOMAIN_ATTACH) {
145           tmpfn = g_strdup_printf("%s.%s", filename, pg->bg->filename->s);
146           success = FALSE;
147           if (bgpdf.status != STATUS_NOT_INIT && bgpdf.file_contents != NULL)
148           {
149             tmpf = fopen(tmpfn, "wb");
150             if (tmpf != NULL && fwrite(bgpdf.file_contents, 1, bgpdf.file_length, tmpf) == bgpdf.file_length)
151               success = TRUE;
152             fclose(tmpf);
153           }
154           if (!success) {
155             dialog = gtk_message_dialog_new(GTK_WINDOW(winMain), GTK_DIALOG_MODAL,
156               GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, 
157               _("Could not write background '%s'. Continuing anyway."), tmpfn);
158             gtk_dialog_run(GTK_DIALOG(dialog));
159             gtk_widget_destroy(dialog);
160           }
161           g_free(tmpfn);
162         }
163         tmpstr = g_markup_escape_text(pg->bg->filename->s, -1);
164         gzprintf(f, "domain=\"%s\" filename=\"%s\" ", 
165           file_domain_names[pg->bg->file_domain], tmpstr);
166         g_free(tmpstr);
167       }
168       gzprintf(f, "pageno=\"%d\" ", pg->bg->file_page_seq);
169     }
170     gzprintf(f, "/>\n");
171     for (layerlist = pg->layers; layerlist!=NULL; layerlist = layerlist->next) {
172       layer = (struct Layer *)layerlist->data;
173       gzprintf(f, "<layer>\n");
174       for (itemlist = layer->items; itemlist!=NULL; itemlist = itemlist->next) {
175         item = (struct Item *)itemlist->data;
176         if (item->type == ITEM_STROKE) {
177           gzprintf(f, "<stroke tool=\"%s\" color=\"", 
178                           tool_names[item->brush.tool_type]);
179           if (item->brush.color_no >= 0)
180             gzputs(f, color_names[item->brush.color_no]);
181           else
182             gzprintf(f, "#%08x", item->brush.color_rgba);
183           gzprintf(f, "\" width=\"%.2f", item->brush.thickness);
184           if (item->brush.variable_width)
185             for (i=0;i<item->path->num_points-1;i++)
186               gzprintf(f, " %.2f", item->widths[i]);
187           gzprintf(f, "\">\n");
188           for (i=0;i<2*item->path->num_points;i++)
189             gzprintf(f, "%.2f ", item->path->coords[i]);
190           gzprintf(f, "\n</stroke>\n");
191         }
192         if (item->type == ITEM_TEXT) {
193           tmpstr = g_markup_escape_text(item->font_name, -1);
194           gzprintf(f, "<text font=\"%s\" size=\"%.2f\" x=\"%.2f\" y=\"%.2f\" color=\"",
195             tmpstr, item->font_size, item->bbox.left, item->bbox.top);
196           g_free(tmpstr);
197           if (item->brush.color_no >= 0)
198             gzputs(f, color_names[item->brush.color_no]);
199           else
200             gzprintf(f, "#%08x", item->brush.color_rgba);
201           tmpstr = g_markup_escape_text(item->text, -1);
202           gzputs(f, "\">");
203           gzputs(f, tmpstr); // gzprintf() can't handle > 4095 bytes
204           gzputs(f, "</text>\n");
205           g_free(tmpstr);
206         }
207       }
208       gzprintf(f, "</layer>\n");
209     }
210     gzprintf(f, "</page>\n");
211   }
212   gzprintf(f, "</xournal>\n");
213   gzclose(f);
214   setlocale(LC_NUMERIC, "");
215
216   return TRUE;
217 }
218
219 // closes a journal: returns true on success, false on abort
220
221 gboolean close_journal(void)
222 {
223   if (!ok_to_close()) return FALSE;
224   
225   // free everything...
226   reset_selection();
227   reset_recognizer();
228   clear_redo_stack();
229   clear_undo_stack();
230
231   shutdown_bgpdf();
232   delete_journal(&journal);
233   
234   return TRUE;
235   /* note: various members of ui and journal are now in invalid states,
236      use new_journal() to reinitialize them */
237 }
238
239 // sanitize a string containing floats, in case it may have , instead of .
240
241 void cleanup_numeric(char *s)
242 {
243   while (*s!=0) { if (*s==',') *s='.'; s++; }
244 }
245
246 // the XML parser functions for open_journal()
247
248 struct Journal tmpJournal;
249 struct Page *tmpPage;
250 struct Layer *tmpLayer;
251 struct Item *tmpItem;
252 char *tmpFilename;
253 struct Background *tmpBg_pdf;
254
255 GError *xoj_invalid(void)
256 {
257   return g_error_new(G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT, _("Invalid file contents"));
258 }
259
260 void xoj_parser_start_element(GMarkupParseContext *context,
261    const gchar *element_name, const gchar **attribute_names, 
262    const gchar **attribute_values, gpointer user_data, GError **error)
263 {
264   int has_attr, i;
265   char *ptr, *tmpptr;
266   struct Background *tmpbg;
267   char *tmpbg_filename;
268   gdouble val;
269   GtkWidget *dialog;
270   
271   if (!strcmp(element_name, "title") || !strcmp(element_name, "xournal")) {
272     if (tmpPage != NULL) {
273       *error = xoj_invalid();
274       return;
275     }
276     // nothing special to do
277   }
278   else if (!strcmp(element_name, "page")) { // start of a page
279     if (tmpPage != NULL) {
280       *error = xoj_invalid();
281       return;
282     }
283     tmpPage = (struct Page *)g_malloc(sizeof(struct Page));
284     tmpPage->layers = NULL;
285     tmpPage->nlayers = 0;
286     tmpPage->group = NULL;
287     tmpPage->bg = g_new(struct Background, 1);
288     tmpPage->bg->type = -1;
289     tmpPage->bg->canvas_item = NULL;
290     tmpPage->bg->pixbuf = NULL;
291     tmpPage->bg->filename = NULL;
292     tmpJournal.pages = g_list_append(tmpJournal.pages, tmpPage);
293     tmpJournal.npages++;
294     // scan for height and width attributes
295     has_attr = 0;
296     while (*attribute_names!=NULL) {
297       if (!strcmp(*attribute_names, "width")) {
298         if (has_attr & 1) *error = xoj_invalid();
299         cleanup_numeric((gchar *)*attribute_values);
300         tmpPage->width = g_ascii_strtod(*attribute_values, &ptr);
301         if (ptr == *attribute_values) *error = xoj_invalid();
302         has_attr |= 1;
303       }
304       else if (!strcmp(*attribute_names, "height")) {
305         if (has_attr & 2) *error = xoj_invalid();
306         cleanup_numeric((gchar *)*attribute_values);
307         tmpPage->height = g_ascii_strtod(*attribute_values, &ptr);
308         if (ptr == *attribute_values) *error = xoj_invalid();
309         has_attr |= 2;
310       }
311       else *error = xoj_invalid();
312       attribute_names++;
313       attribute_values++;
314     }
315     if (has_attr!=3) *error = xoj_invalid();
316   }
317   else if (!strcmp(element_name, "background")) {
318     if (tmpPage == NULL || tmpLayer !=NULL || tmpPage->bg->type >= 0) {
319       *error = xoj_invalid();
320       return;
321     }
322     has_attr = 0;
323     while (*attribute_names!=NULL) {
324       if (!strcmp(*attribute_names, "type")) {
325         if (has_attr) *error = xoj_invalid();
326         for (i=0; i<3; i++)
327           if (!strcmp(*attribute_values, bgtype_names[i]))
328             tmpPage->bg->type = i;
329         if (tmpPage->bg->type < 0) *error = xoj_invalid();
330         has_attr |= 1;
331         if (tmpPage->bg->type == BG_PDF) {
332           if (tmpBg_pdf == NULL) tmpBg_pdf = tmpPage->bg;
333           else {
334             has_attr |= 24;
335             tmpPage->bg->filename = refstring_ref(tmpBg_pdf->filename);
336             tmpPage->bg->file_domain = tmpBg_pdf->file_domain;
337           }
338         }
339       }
340       else if (!strcmp(*attribute_names, "color")) {
341         if (tmpPage->bg->type != BG_SOLID) *error = xoj_invalid();
342         if (has_attr & 2) *error = xoj_invalid();
343         tmpPage->bg->color_no = COLOR_OTHER;
344         for (i=0; i<COLOR_MAX; i++)
345           if (!strcmp(*attribute_values, bgcolor_names[i])) {
346             tmpPage->bg->color_no = i;
347             tmpPage->bg->color_rgba = predef_bgcolors_rgba[i];
348           }
349         // there's also the case of hex (#rrggbbaa) colors
350         if (tmpPage->bg->color_no == COLOR_OTHER && **attribute_values == '#') {
351           tmpPage->bg->color_rgba = strtoul(*attribute_values + 1, &ptr, 16);
352           if (*ptr!=0) *error = xoj_invalid();
353         }
354         has_attr |= 2;
355       }
356       else if (!strcmp(*attribute_names, "style")) {
357         if (tmpPage->bg->type != BG_SOLID) *error = xoj_invalid();
358         if (has_attr & 4) *error = xoj_invalid();
359         tmpPage->bg->ruling = -1;
360         for (i=0; i<4; i++)
361           if (!strcmp(*attribute_values, bgstyle_names[i]))
362             tmpPage->bg->ruling = i;
363         if (tmpPage->bg->ruling < 0) *error = xoj_invalid();
364         has_attr |= 4;
365       }
366       else if (!strcmp(*attribute_names, "domain")) {
367         if (tmpPage->bg->type <= BG_SOLID || (has_attr & 8))
368           { *error = xoj_invalid(); return; }
369         tmpPage->bg->file_domain = -1;
370         for (i=0; i<3; i++)
371           if (!strcmp(*attribute_values, file_domain_names[i]))
372             tmpPage->bg->file_domain = i;
373         if (tmpPage->bg->file_domain < 0)
374           { *error = xoj_invalid(); return; }
375         has_attr |= 8;
376       }
377       else if (!strcmp(*attribute_names, "filename")) {
378         if (tmpPage->bg->type <= BG_SOLID || (has_attr != 9)) 
379           { *error = xoj_invalid(); return; }
380         if (tmpPage->bg->file_domain == DOMAIN_CLONE) {
381           // filename is a page number
382           i = strtol(*attribute_values, &ptr, 10);
383           if (ptr == *attribute_values || i < 0 || i > tmpJournal.npages-2)
384             { *error = xoj_invalid(); return; }
385           tmpbg = ((struct Page *)g_list_nth_data(tmpJournal.pages, i))->bg;
386           if (tmpbg->type != tmpPage->bg->type)
387             { *error = xoj_invalid(); return; }
388           tmpPage->bg->filename = refstring_ref(tmpbg->filename);
389           tmpPage->bg->pixbuf = tmpbg->pixbuf;
390           if (tmpbg->pixbuf!=NULL) gdk_pixbuf_ref(tmpbg->pixbuf);
391           tmpPage->bg->file_domain = tmpbg->file_domain;
392         }
393         else {
394           tmpPage->bg->filename = new_refstring(*attribute_values);
395           if (tmpPage->bg->type == BG_PIXMAP) {
396             if (tmpPage->bg->file_domain == DOMAIN_ATTACH) {
397               tmpbg_filename = g_strdup_printf("%s.%s", tmpFilename, *attribute_values);
398               if (sscanf(*attribute_values, "bg_%d.png", &i) == 1)
399                 if (i > tmpJournal.last_attach_no) 
400                   tmpJournal.last_attach_no = i;
401             }
402             else tmpbg_filename = g_strdup(*attribute_values);
403             tmpPage->bg->pixbuf = gdk_pixbuf_new_from_file(tmpbg_filename, NULL);
404             if (tmpPage->bg->pixbuf == NULL) {
405               dialog = gtk_message_dialog_new(GTK_WINDOW(winMain), GTK_DIALOG_MODAL,
406                 GTK_MESSAGE_WARNING, GTK_BUTTONS_OK, 
407                 _("Could not open background '%s'. Setting background to white."),
408                 tmpbg_filename);
409               gtk_dialog_run(GTK_DIALOG(dialog));
410               gtk_widget_destroy(dialog);
411               tmpPage->bg->pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8, 1, 1);
412               gdk_pixbuf_fill(tmpPage->bg->pixbuf, 0xffffffff); // solid white
413             }
414             g_free(tmpbg_filename);
415           }
416         }
417         has_attr |= 16;
418       }
419       else if (!strcmp(*attribute_names, "pageno")) {
420         if (tmpPage->bg->type != BG_PDF || (has_attr & 32))
421           { *error = xoj_invalid(); return; }
422         tmpPage->bg->file_page_seq = strtol(*attribute_values, &ptr, 10);
423         if (ptr == *attribute_values) *error = xoj_invalid();
424         has_attr |= 32;
425       }
426       else *error = xoj_invalid();
427       attribute_names++;
428       attribute_values++;
429     }
430     if (tmpPage->bg->type < 0) *error = xoj_invalid();
431     if (tmpPage->bg->type == BG_SOLID && has_attr != 7) *error = xoj_invalid();
432     if (tmpPage->bg->type == BG_PIXMAP && has_attr != 25) *error = xoj_invalid();
433     if (tmpPage->bg->type == BG_PDF && has_attr != 57) *error = xoj_invalid();
434   }
435   else if (!strcmp(element_name, "layer")) { // start of a layer
436     if (tmpPage == NULL || tmpLayer != NULL) {
437       *error = xoj_invalid();
438       return;
439     }
440     tmpLayer = (struct Layer *)g_malloc(sizeof(struct Layer));
441     tmpLayer->items = NULL;
442     tmpLayer->nitems = 0;
443     tmpLayer->group = NULL;
444     tmpPage->layers = g_list_append(tmpPage->layers, tmpLayer);
445     tmpPage->nlayers++;
446   }
447   else if (!strcmp(element_name, "stroke")) { // start of a stroke
448     if (tmpLayer == NULL || tmpItem != NULL) {
449       *error = xoj_invalid();
450       return;
451     }
452     tmpItem = (struct Item *)g_malloc(sizeof(struct Item));
453     tmpItem->type = ITEM_STROKE;
454     tmpItem->path = NULL;
455     tmpItem->canvas_item = NULL;
456     tmpItem->widths = NULL;
457     tmpLayer->items = g_list_append(tmpLayer->items, tmpItem);
458     tmpLayer->nitems++;
459     // scan for tool, color, and width attributes
460     has_attr = 0;
461     while (*attribute_names!=NULL) {
462       if (!strcmp(*attribute_names, "width")) {
463         if (has_attr & 1) *error = xoj_invalid();
464         cleanup_numeric((gchar *)*attribute_values);
465         tmpItem->brush.thickness = g_ascii_strtod(*attribute_values, &ptr);
466         if (ptr == *attribute_values) *error = xoj_invalid();
467         i = 0;
468         while (*ptr!=0) {
469           realloc_cur_widths(i+1);
470           ui.cur_widths[i] = g_ascii_strtod(ptr, &tmpptr);
471           if (tmpptr == ptr) break;
472           ptr = tmpptr;
473           i++;
474         }
475         tmpItem->brush.variable_width = (i>0);
476         if (i>0) {
477           tmpItem->brush.variable_width = TRUE;
478           tmpItem->widths = (gdouble *) g_memdup(ui.cur_widths, i*sizeof(gdouble));
479           ui.cur_path.num_points =  i+1;
480         }
481         has_attr |= 1;
482       }
483       else if (!strcmp(*attribute_names, "color")) {
484         if (has_attr & 2) *error = xoj_invalid();
485         tmpItem->brush.color_no = COLOR_OTHER;
486         for (i=0; i<COLOR_MAX; i++)
487           if (!strcmp(*attribute_values, color_names[i])) {
488             tmpItem->brush.color_no = i;
489             tmpItem->brush.color_rgba = predef_colors_rgba[i];
490           }
491         // there's also the case of hex (#rrggbbaa) colors
492         if (tmpItem->brush.color_no == COLOR_OTHER && **attribute_values == '#') {
493           tmpItem->brush.color_rgba = strtoul(*attribute_values + 1, &ptr, 16);
494           if (*ptr!=0) *error = xoj_invalid();
495         }
496         has_attr |= 2;
497       }
498       else if (!strcmp(*attribute_names, "tool")) {
499         if (has_attr & 4) *error = xoj_invalid();
500         tmpItem->brush.tool_type = -1;
501         for (i=0; i<NUM_STROKE_TOOLS; i++)
502           if (!strcmp(*attribute_values, tool_names[i])) {
503             tmpItem->brush.tool_type = i;
504           }
505         if (tmpItem->brush.tool_type == -1) *error = xoj_invalid();
506         has_attr |= 4;
507       }
508       else *error = xoj_invalid();
509       attribute_names++;
510       attribute_values++;
511     }
512     if (has_attr!=7) *error = xoj_invalid();
513     // finish filling the brush info
514     tmpItem->brush.thickness_no = 0;  // who cares ?
515     tmpItem->brush.tool_options = 0;  // who cares ?
516     tmpItem->brush.ruler = FALSE;
517     tmpItem->brush.recognizer = FALSE;
518     if (tmpItem->brush.tool_type == TOOL_HIGHLIGHTER) {
519       if (tmpItem->brush.color_no >= 0)
520         tmpItem->brush.color_rgba &= ui.hiliter_alpha_mask;
521     }
522   }
523   else if (!strcmp(element_name, "text")) { // start of a text item
524     if (tmpLayer == NULL || tmpItem != NULL) {
525       *error = xoj_invalid();
526       return;
527     }
528     tmpItem = (struct Item *)g_malloc0(sizeof(struct Item));
529     tmpItem->type = ITEM_TEXT;
530     tmpItem->canvas_item = NULL;
531     tmpLayer->items = g_list_append(tmpLayer->items, tmpItem);
532     tmpLayer->nitems++;
533     // scan for font, size, x, y, and color attributes
534     has_attr = 0;
535     while (*attribute_names!=NULL) {
536       if (!strcmp(*attribute_names, "font")) {
537         if (has_attr & 1) *error = xoj_invalid();
538         tmpItem->font_name = g_strdup(*attribute_values);
539         has_attr |= 1;
540       }
541       else if (!strcmp(*attribute_names, "size")) {
542         if (has_attr & 2) *error = xoj_invalid();
543         cleanup_numeric((gchar *)*attribute_values);
544         tmpItem->font_size = g_ascii_strtod(*attribute_values, &ptr);
545         if (ptr == *attribute_values) *error = xoj_invalid();
546         has_attr |= 2;
547       }
548       else if (!strcmp(*attribute_names, "x")) {
549         if (has_attr & 4) *error = xoj_invalid();
550         cleanup_numeric((gchar *)*attribute_values);
551         tmpItem->bbox.left = g_ascii_strtod(*attribute_values, &ptr);
552         if (ptr == *attribute_values) *error = xoj_invalid();
553         has_attr |= 4;
554       }
555       else if (!strcmp(*attribute_names, "y")) {
556         if (has_attr & 8) *error = xoj_invalid();
557         cleanup_numeric((gchar *)*attribute_values);
558         tmpItem->bbox.top = g_ascii_strtod(*attribute_values, &ptr);
559         if (ptr == *attribute_values) *error = xoj_invalid();
560         has_attr |= 8;
561       }
562       else if (!strcmp(*attribute_names, "color")) {
563         if (has_attr & 16) *error = xoj_invalid();
564         tmpItem->brush.color_no = COLOR_OTHER;
565         for (i=0; i<COLOR_MAX; i++)
566           if (!strcmp(*attribute_values, color_names[i])) {
567             tmpItem->brush.color_no = i;
568             tmpItem->brush.color_rgba = predef_colors_rgba[i];
569           }
570         // there's also the case of hex (#rrggbbaa) colors
571         if (tmpItem->brush.color_no == COLOR_OTHER && **attribute_values == '#') {
572           tmpItem->brush.color_rgba = strtoul(*attribute_values + 1, &ptr, 16);
573           if (*ptr!=0) *error = xoj_invalid();
574         }
575         has_attr |= 16;
576       }
577       else *error = xoj_invalid();
578       attribute_names++;
579       attribute_values++;
580     }
581     if (has_attr!=31) *error = xoj_invalid();
582   }
583 }
584
585 void xoj_parser_end_element(GMarkupParseContext *context,
586    const gchar *element_name, gpointer user_data, GError **error)
587 {
588   if (!strcmp(element_name, "page")) {
589     if (tmpPage == NULL || tmpLayer != NULL) {
590       *error = xoj_invalid();
591       return;
592     }
593     if (tmpPage->nlayers == 0 || tmpPage->bg->type < 0) *error = xoj_invalid();
594     tmpPage = NULL;
595   }
596   if (!strcmp(element_name, "layer")) {
597     if (tmpLayer == NULL || tmpItem != NULL) {
598       *error = xoj_invalid();
599       return;
600     }
601     tmpLayer = NULL;
602   }
603   if (!strcmp(element_name, "stroke")) {
604     if (tmpItem == NULL) {
605       *error = xoj_invalid();
606       return;
607     }
608     update_item_bbox(tmpItem);
609     tmpItem = NULL;
610   }
611   if (!strcmp(element_name, "text")) {
612     if (tmpItem == NULL) {
613       *error = xoj_invalid();
614       return;
615     }
616     tmpItem = NULL;
617   }
618 }
619
620 void xoj_parser_text(GMarkupParseContext *context,
621    const gchar *text, gsize text_len, gpointer user_data, GError **error)
622 {
623   const gchar *element_name, *ptr;
624   int n;
625   
626   element_name = g_markup_parse_context_get_element(context);
627   if (element_name == NULL) return;
628   if (!strcmp(element_name, "stroke")) {
629     cleanup_numeric((gchar *)text);
630     ptr = text;
631     n = 0;
632     while (text_len > 0) {
633       realloc_cur_path(n/2 + 1);
634       ui.cur_path.coords[n] = g_ascii_strtod(text, (char **)(&ptr));
635       if (ptr == text) break;
636       text_len -= (ptr - text);
637       text = ptr;
638       if (!finite(ui.cur_path.coords[n])) {
639         if (n>=2) ui.cur_path.coords[n] = ui.cur_path.coords[n-2];
640         else ui.cur_path.coords[n] = 0;
641       }
642       n++;
643     }
644     if (n<4 || n&1 || 
645         (tmpItem->brush.variable_width && (n!=2*ui.cur_path.num_points))) 
646       { *error = xoj_invalid(); return; } // wrong number of points
647     tmpItem->path = gnome_canvas_points_new(n/2);
648     g_memmove(tmpItem->path->coords, ui.cur_path.coords, n*sizeof(double));
649   }
650   if (!strcmp(element_name, "text")) {
651     tmpItem->text = g_malloc(text_len+1);
652     g_memmove(tmpItem->text, text, text_len);
653     tmpItem->text[text_len]=0;
654   }
655 }
656
657 gboolean user_wants_second_chance(char **filename)
658 {
659   GtkWidget *dialog;
660   GtkFileFilter *filt_all, *filt_pdf;
661   GtkResponseType response;
662
663   dialog = gtk_message_dialog_new(GTK_WINDOW(winMain), GTK_DIALOG_MODAL,
664     GTK_MESSAGE_ERROR, GTK_BUTTONS_YES_NO, 
665     _("Could not open background '%s'.\nSelect another file?"),
666     *filename);
667   response = gtk_dialog_run(GTK_DIALOG(dialog));
668   gtk_widget_destroy(dialog);
669   if (response != GTK_RESPONSE_YES) return FALSE;
670   dialog = gtk_file_chooser_dialog_new(_("Open PDF"), GTK_WINDOW (winMain),
671      GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
672      GTK_STOCK_OPEN, GTK_RESPONSE_OK, NULL);
673 #ifdef FILE_DIALOG_SIZE_BUGFIX
674   gtk_window_set_default_size(GTK_WINDOW(dialog), 500, 400);
675 #endif
676   
677   filt_all = gtk_file_filter_new();
678   gtk_file_filter_set_name(filt_all, _("All files"));
679   gtk_file_filter_add_pattern(filt_all, "*");
680   filt_pdf = gtk_file_filter_new();
681   gtk_file_filter_set_name(filt_pdf, _("PDF files"));
682   gtk_file_filter_add_pattern(filt_pdf, "*.pdf");
683   gtk_file_chooser_add_filter(GTK_FILE_CHOOSER (dialog), filt_pdf);
684   gtk_file_chooser_add_filter(GTK_FILE_CHOOSER (dialog), filt_all);
685
686   if (ui.default_path!=NULL) gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER (dialog), ui.default_path);
687
688   if (gtk_dialog_run(GTK_DIALOG(dialog)) != GTK_RESPONSE_OK) {
689     gtk_widget_destroy(dialog);
690     return FALSE;
691   }
692   g_free(*filename);
693   *filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog));
694   gtk_widget_destroy(dialog);
695   return TRUE;    
696 }
697
698 gboolean open_journal(char *filename)
699 {
700   const GMarkupParser parser = { xoj_parser_start_element, 
701                                  xoj_parser_end_element, 
702                                  xoj_parser_text, NULL, NULL};
703   GMarkupParseContext *context;
704   GError *error;
705   GtkWidget *dialog;
706   gboolean valid;
707   gzFile f;
708   char buffer[1000];
709   int len;
710   gchar *tmpfn, *tmpfn2, *p, *q;
711   gboolean maybe_pdf;
712   
713   tmpfn = g_strdup_printf("%s.xoj", filename);
714   if (ui.autoload_pdf_xoj && g_file_test(tmpfn, G_FILE_TEST_EXISTS) &&
715       (g_str_has_suffix(filename, ".pdf") || g_str_has_suffix(filename, ".PDF")))
716   {
717     valid = open_journal(tmpfn);
718     g_free(tmpfn);
719     return valid;
720   }
721   g_free(tmpfn);
722
723   f = gzopen(filename, "rb");
724   if (f==NULL) return FALSE;
725   if (filename[0]=='/') {
726     if (ui.default_path != NULL) g_free(ui.default_path);
727     ui.default_path = g_path_get_dirname(filename);
728   }
729   
730   context = g_markup_parse_context_new(&parser, 0, NULL, NULL);
731   valid = TRUE;
732   tmpJournal.npages = 0;
733   tmpJournal.pages = NULL;
734   tmpJournal.last_attach_no = 0;
735   tmpPage = NULL;
736   tmpLayer = NULL;
737   tmpItem = NULL;
738   tmpFilename = filename;
739   error = NULL;
740   tmpBg_pdf = NULL;
741   maybe_pdf = TRUE;
742
743   while (valid && !gzeof(f)) {
744     len = gzread(f, buffer, 1000);
745     if (len<0) valid = FALSE;
746     if (maybe_pdf && len>=4 && !strncmp(buffer, "%PDF", 4))
747       { valid = FALSE; break; } // most likely pdf
748     else maybe_pdf = FALSE;
749     if (len<=0) break;
750     valid = g_markup_parse_context_parse(context, buffer, len, &error);
751   }
752   gzclose(f);
753   if (valid) valid = g_markup_parse_context_end_parse(context, &error);
754   if (tmpJournal.npages == 0) valid = FALSE;
755   g_markup_parse_context_free(context);
756   
757   if (!valid) {
758     delete_journal(&tmpJournal);
759     if (!maybe_pdf) return FALSE;
760     // essentially same as on_fileNewBackground from here on
761     ui.saved = TRUE;
762     close_journal();
763     while (bgpdf.status != STATUS_NOT_INIT) gtk_main_iteration();
764     new_journal();
765     ui.zoom = ui.startup_zoom;
766     gnome_canvas_set_pixels_per_unit(canvas, ui.zoom);
767     update_page_stuff();
768     return init_bgpdf(filename, TRUE, DOMAIN_ABSOLUTE);
769   }
770   
771   ui.saved = TRUE; // force close_journal() to do its job
772   close_journal();
773   g_memmove(&journal, &tmpJournal, sizeof(struct Journal));
774   
775   // if we need to initialize a fresh pdf loader
776   if (tmpBg_pdf!=NULL) { 
777     while (bgpdf.status != STATUS_NOT_INIT) gtk_main_iteration();
778     if (tmpBg_pdf->file_domain == DOMAIN_ATTACH)
779       tmpfn = g_strdup_printf("%s.%s", filename, tmpBg_pdf->filename->s);
780     else
781       tmpfn = g_strdup(tmpBg_pdf->filename->s);
782     valid = init_bgpdf(tmpfn, FALSE, tmpBg_pdf->file_domain);
783     // if file name is invalid: first try in xoj file's directory
784     if (!valid && tmpBg_pdf->file_domain != DOMAIN_ATTACH) {
785       p = g_path_get_dirname(filename);
786       q = g_path_get_basename(tmpfn);
787       tmpfn2 = g_strdup_printf("%s/%s", p, q);
788       g_free(p); g_free(q);
789       valid = init_bgpdf(tmpfn2, FALSE, tmpBg_pdf->file_domain);
790       if (valid) {  // change the file name...
791         printf("substituting %s -> %s\n", tmpfn, tmpfn2);
792         g_free(tmpBg_pdf->filename->s);
793         tmpBg_pdf->filename->s = tmpfn2;
794       }
795       else g_free(tmpfn2);
796     }
797     // if file name is invalid: next prompt user
798     if (!valid && tmpBg_pdf->file_domain != DOMAIN_ATTACH)
799       if (user_wants_second_chance(&tmpfn)) {
800         valid = init_bgpdf(tmpfn, FALSE, tmpBg_pdf->file_domain);
801         if (valid) { // change the file name...
802           g_free(tmpBg_pdf->filename->s);
803           tmpBg_pdf->filename->s = g_strdup(tmpfn);
804         }
805       }
806     if (valid) {
807       refstring_unref(bgpdf.filename);
808       bgpdf.filename = refstring_ref(tmpBg_pdf->filename);
809     } else {
810       dialog = gtk_message_dialog_new(GTK_WINDOW(winMain), GTK_DIALOG_MODAL,
811         GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, _("Could not open background '%s'."),
812         tmpfn);
813       gtk_dialog_run(GTK_DIALOG(dialog));
814       gtk_widget_destroy(dialog);
815     }
816     g_free(tmpfn);
817   }
818   
819   ui.pageno = 0;
820   ui.cur_page = (struct Page *)journal.pages->data;
821   ui.layerno = ui.cur_page->nlayers-1;
822   ui.cur_layer = (struct Layer *)(g_list_last(ui.cur_page->layers)->data);
823   ui.saved = TRUE;
824   ui.zoom = ui.startup_zoom;
825   update_file_name(g_strdup(filename));
826   gnome_canvas_set_pixels_per_unit(canvas, ui.zoom);
827   make_canvas_items();
828   update_page_stuff();
829   rescale_bg_pixmaps(); // this requests the PDF pages if need be
830   gtk_adjustment_set_value(gtk_layout_get_vadjustment(GTK_LAYOUT(canvas)), 0);
831   return TRUE;
832 }
833
834 /************ file backgrounds *************/
835
836 struct Background *attempt_load_pix_bg(char *filename, gboolean attach)
837 {
838   struct Background *bg;
839   GdkPixbuf *pix;
840   
841   pix = gdk_pixbuf_new_from_file(filename, NULL);
842   if (pix == NULL) return NULL;
843   
844   bg = g_new(struct Background, 1);
845   bg->type = BG_PIXMAP;
846   bg->canvas_item = NULL;
847   bg->pixbuf = pix;
848   bg->pixbuf_scale = DEFAULT_ZOOM;
849   if (attach) {
850     bg->filename = new_refstring(NULL);
851     bg->file_domain = DOMAIN_ATTACH;
852   } else {
853     bg->filename = new_refstring(filename);
854     bg->file_domain = DOMAIN_ABSOLUTE;
855   }
856   return bg;
857 }
858
859 #define BUFSIZE 65536 // a reasonable buffer size for reads from gs pipe
860
861 GList *attempt_load_gv_bg(char *filename)
862 {
863   struct Background *bg;
864   GList *bg_list;
865   GdkPixbuf *pix;
866   GdkPixbufLoader *loader;
867   FILE *gs_pipe, *f;
868   unsigned char *buf;
869   char *pipename;
870   int buflen, remnlen, file_pageno;
871   
872   f = fopen(filename, "rb");
873   if (f == NULL) return NULL;
874   buf = g_malloc(BUFSIZE); // a reasonable buffer size
875   if (fread(buf, 1, 4, f) !=4 ||
876         (strncmp((char *)buf, "%!PS", 4) && strncmp((char *)buf, "%PDF", 4))) {
877     fclose(f);
878     g_free(buf);
879     return NULL;
880   }
881   
882   fclose(f);
883   pipename = g_strdup_printf(GS_CMDLINE, (double)GS_BITMAP_DPI, filename);
884   gs_pipe = popen(pipename, "rb");
885   g_free(pipename);
886   
887   bg_list = NULL;
888   remnlen = 0;
889   file_pageno = 0;
890   loader = NULL;
891   if (gs_pipe!=NULL)
892   while (!feof(gs_pipe)) {
893     if (!remnlen) { // new page: get a BMP header ?
894       buflen = fread(buf, 1, 54, gs_pipe);
895       if (buflen < 6) buflen += fread(buf, 1, 54-buflen, gs_pipe);
896       if (buflen < 6 || buf[0]!='B' || buf[1]!='M') break; // fatal: abort
897       remnlen = (int)(buf[5]<<24) + (buf[4]<<16) + (buf[3]<<8) + (buf[2]);
898       loader = gdk_pixbuf_loader_new();
899     }
900     else buflen = fread(buf, 1, (remnlen < BUFSIZE)?remnlen:BUFSIZE, gs_pipe);
901     remnlen -= buflen;
902     if (buflen == 0) break;
903     if (!gdk_pixbuf_loader_write(loader, buf, buflen, NULL)) break;
904     if (remnlen == 0) { // make a new bg
905       pix = gdk_pixbuf_loader_get_pixbuf(loader);
906       if (pix == NULL) break;
907       gdk_pixbuf_ref(pix);
908       gdk_pixbuf_loader_close(loader, NULL);
909       g_object_unref(loader);
910       loader = NULL;
911       bg = g_new(struct Background, 1);
912       bg->canvas_item = NULL;
913       bg->pixbuf = pix;
914       bg->pixbuf_scale = (GS_BITMAP_DPI/72.0);
915       bg->type = BG_PIXMAP;
916       bg->filename = new_refstring(NULL);
917       bg->file_domain = DOMAIN_ATTACH;
918       file_pageno++;
919       bg_list = g_list_append(bg_list, bg);
920     }
921   }
922   if (loader != NULL) gdk_pixbuf_loader_close(loader, NULL);
923   pclose(gs_pipe);
924   g_free(buf);
925   return bg_list;
926 }
927
928 struct Background *attempt_screenshot_bg(void)
929 {
930 #ifndef WIN32
931   struct Background *bg;
932   GdkPixbuf *pix;
933   XEvent x_event;
934   GdkWindow *window;
935   int x,y,w,h;
936   Window x_root, x_win;
937
938   x_root = gdk_x11_get_default_root_xwindow();
939   
940   if (!XGrabButton(GDK_DISPLAY(), AnyButton, AnyModifier, x_root, 
941       False, ButtonReleaseMask, GrabModeAsync, GrabModeSync, None, None))
942     return NULL;
943
944   XWindowEvent (GDK_DISPLAY(), x_root, ButtonReleaseMask, &x_event);
945   XUngrabButton(GDK_DISPLAY(), AnyButton, AnyModifier, x_root);
946
947   x_win = x_event.xbutton.subwindow;
948   if (x_win == None) x_win = x_root;
949
950   window = gdk_window_foreign_new_for_display(gdk_display_get_default(), x_win);
951     
952   gdk_window_get_geometry(window, &x, &y, &w, &h, NULL);
953   
954   pix = gdk_pixbuf_get_from_drawable(NULL, window,
955     gdk_colormap_get_system(), 0, 0, 0, 0, w, h);
956     
957   if (pix == NULL) return NULL;
958   
959   bg = g_new(struct Background, 1);
960   bg->type = BG_PIXMAP;
961   bg->canvas_item = NULL;
962   bg->pixbuf = pix;
963   bg->pixbuf_scale = DEFAULT_ZOOM;
964   bg->filename = new_refstring(NULL);
965   bg->file_domain = DOMAIN_ATTACH;
966   return bg;
967 #else
968   // not implemented under WIN32
969   return FALSE;
970 #endif
971 }
972
973 /************** pdf annotation ***************/
974
975 /* cancel a request */
976
977 void cancel_bgpdf_request(struct BgPdfRequest *req)
978 {
979   GList *list_link;
980   
981   list_link = g_list_find(bgpdf.requests, req);
982   if (list_link == NULL) return;
983   // remove the request
984   bgpdf.requests = g_list_delete_link(bgpdf.requests, list_link);
985   g_free(req);
986 }
987
988 /* process a bg PDF request from the queue, and recurse */
989
990 gboolean bgpdf_scheduler_callback(gpointer data)
991 {
992   struct BgPdfRequest *req;
993   struct BgPdfPage *bgpg;
994   GdkPixbuf *pixbuf;
995   GtkWidget *dialog;
996   PopplerPage *pdfpage;
997   gdouble height, width;
998   int scaled_height, scaled_width;
999   GdkPixmap *pixmap;
1000   cairo_t *cr;
1001
1002   // if all requests have been cancelled, remove ourselves from main loop
1003   if (bgpdf.requests == NULL) { bgpdf.pid = 0; return FALSE; }
1004   if (bgpdf.status == STATUS_NOT_INIT)
1005     { printf("DEBUG: BGPDF not initialized??\n"); bgpdf.pid = 0; return FALSE; }
1006
1007   req = (struct BgPdfRequest *)bgpdf.requests->data;
1008
1009   // use poppler to generate the page
1010   pixbuf = NULL;
1011   pdfpage = poppler_document_get_page(bgpdf.document, req->pageno-1);
1012   if (pdfpage) {
1013 //    printf("DEBUG: Processing request for page %d at %f dpi\n", req->pageno, req->dpi);
1014     set_cursor_busy(TRUE);
1015     poppler_page_get_size(pdfpage, &width, &height);
1016     scaled_width = (int) (req->dpi * width/72);
1017     scaled_height = (int) (req->dpi * height/72);
1018
1019     if (ui.poppler_force_cairo) { // poppler -> cairo -> pixmap -> pixbuf
1020       pixmap = gdk_pixmap_new(GTK_WIDGET(canvas)->window, scaled_width, scaled_height, -1);
1021       cr = gdk_cairo_create(pixmap);
1022       cairo_set_source_rgb(cr, 1., 1., 1.);
1023       cairo_paint(cr);
1024       cairo_scale(cr, scaled_width/width, scaled_height/height);
1025       poppler_page_render(pdfpage, cr);
1026       cairo_destroy(cr);
1027       pixbuf = gdk_pixbuf_get_from_drawable(NULL, GDK_DRAWABLE(pixmap),
1028         NULL, 0, 0, 0, 0, scaled_width, scaled_height);
1029       g_object_unref(pixmap);
1030     }
1031     else { // directly poppler -> pixbuf: faster, but bitmap font bug
1032       pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB,
1033                  FALSE, 8, scaled_width, scaled_height);
1034       poppler_page_render_to_pixbuf(
1035                 pdfpage, 0, 0, scaled_width, scaled_height,
1036                 req->dpi/72, 0, pixbuf);
1037     }
1038     g_object_unref(pdfpage);
1039     set_cursor_busy(FALSE);
1040   }
1041
1042   // process the generated pixbuf...
1043   if (pixbuf != NULL) { // success
1044     while (req->pageno > bgpdf.npages) {
1045       bgpg = g_new(struct BgPdfPage, 1);
1046       bgpg->pixbuf = NULL;
1047       bgpdf.pages = g_list_append(bgpdf.pages, bgpg);
1048       bgpdf.npages++;
1049     }
1050     bgpg = g_list_nth_data(bgpdf.pages, req->pageno-1);
1051     if (bgpg->pixbuf!=NULL) gdk_pixbuf_unref(bgpg->pixbuf);
1052     bgpg->pixbuf = pixbuf;
1053     bgpg->dpi = req->dpi;
1054     bgpg->pixel_height = scaled_height;
1055     bgpg->pixel_width = scaled_width;
1056     bgpdf_update_bg(req->pageno, bgpg); // update all pages that have this bg
1057   } else { // failure
1058     if (!bgpdf.has_failed) {
1059       dialog = gtk_message_dialog_new(GTK_WINDOW(winMain), GTK_DIALOG_MODAL,
1060         GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, _("Unable to render one or more PDF pages."));
1061       gtk_dialog_run(GTK_DIALOG(dialog));
1062       gtk_widget_destroy(dialog);
1063     }
1064     bgpdf.has_failed = TRUE;
1065   }
1066
1067   bgpdf.requests = g_list_delete_link(bgpdf.requests, bgpdf.requests);
1068   if (bgpdf.requests != NULL) return TRUE; // remain in the idle loop
1069   bgpdf.pid = 0;
1070   return FALSE; // we're done
1071 }
1072
1073 /* make a request */
1074
1075 gboolean add_bgpdf_request(int pageno, double zoom)
1076 {
1077   struct BgPdfRequest *req, *cmp_req;
1078   GList *list;
1079
1080   if (bgpdf.status == STATUS_NOT_INIT)
1081     return FALSE; // don't accept requests
1082   req = g_new(struct BgPdfRequest, 1);
1083   req->pageno = pageno;
1084   req->dpi = 72*zoom;
1085 //  printf("DEBUG: Enqueuing request for page %d at %f dpi\n", pageno, req->dpi);
1086
1087   // cancel any request this may supersede
1088   for (list = bgpdf.requests; list != NULL; ) {
1089     cmp_req = (struct BgPdfRequest *)list->data;
1090     list = list->next;
1091     if (cmp_req->pageno == pageno) cancel_bgpdf_request(cmp_req);
1092   }
1093
1094   // make the request
1095   bgpdf.requests = g_list_append(bgpdf.requests, req);
1096   if (!bgpdf.pid) bgpdf.pid = g_idle_add(bgpdf_scheduler_callback, NULL);
1097   return TRUE;
1098 }
1099
1100 /* shutdown the PDF reader */
1101
1102 void shutdown_bgpdf(void)
1103 {
1104   GList *list;
1105   struct BgPdfPage *pdfpg;
1106   struct BgPdfRequest *req;
1107
1108   if (bgpdf.status == STATUS_NOT_INIT) return;
1109   
1110   // cancel all requests and free data structures
1111   refstring_unref(bgpdf.filename);
1112   for (list = bgpdf.pages; list != NULL; list = list->next) {
1113     pdfpg = (struct BgPdfPage *)list->data;
1114     if (pdfpg->pixbuf!=NULL) gdk_pixbuf_unref(pdfpg->pixbuf);
1115     g_free(pdfpg);
1116   }
1117   g_list_free(bgpdf.pages);
1118   for (list = bgpdf.requests; list != NULL; list = list->next) {
1119     req = (struct BgPdfRequest *)list->data;
1120     g_free(req);
1121   }
1122   g_list_free(bgpdf.requests);
1123
1124   if (bgpdf.file_contents!=NULL) {
1125     g_free(bgpdf.file_contents); 
1126     bgpdf.file_contents = NULL;
1127   }
1128   if (bgpdf.document!=NULL) {
1129     g_object_unref(bgpdf.document);
1130     bgpdf.document = NULL;
1131   }
1132
1133   bgpdf.status = STATUS_NOT_INIT;
1134 }
1135
1136
1137 // initialize PDF background rendering 
1138
1139 gboolean init_bgpdf(char *pdfname, gboolean create_pages, int file_domain)
1140 {
1141   int i, n_pages;
1142   struct Background *bg;
1143   struct Page *pg;
1144   PopplerPage *pdfpage;
1145   gdouble width, height;
1146   gchar *uri;
1147   
1148   if (bgpdf.status != STATUS_NOT_INIT) return FALSE;
1149   
1150   // make a copy of the file in memory and check it's a PDF
1151   if (!g_file_get_contents(pdfname, &(bgpdf.file_contents), &(bgpdf.file_length), NULL))
1152     return FALSE;
1153   if (bgpdf.file_length < 4 || strncmp(bgpdf.file_contents, "%PDF", 4))
1154     { g_free(bgpdf.file_contents); bgpdf.file_contents = NULL; return FALSE; }
1155
1156   // init bgpdf data structures and open poppler document
1157   bgpdf.status = STATUS_READY;
1158   bgpdf.filename = new_refstring((file_domain == DOMAIN_ATTACH) ? "bg.pdf" : pdfname);
1159   bgpdf.file_domain = file_domain;
1160   bgpdf.npages = 0;
1161   bgpdf.pages = NULL;
1162   bgpdf.requests = NULL;
1163   bgpdf.pid = 0;
1164   bgpdf.has_failed = FALSE;
1165
1166 /* poppler_document_new_from_data() starts at 0.6.1, but we want to
1167    be compatible with poppler 0.5.4 = latest in CentOS as of sept 2009 */
1168   uri = g_filename_to_uri(pdfname, NULL, NULL);
1169   if (!uri) uri = g_strdup_printf("file://%s", pdfname);
1170   bgpdf.document = poppler_document_new_from_file(uri, NULL, NULL);
1171   g_free(uri);
1172 /*    with poppler 0.6.1 or later, can replace the above 4 lines by:
1173   bgpdf.document = poppler_document_new_from_data(bgpdf.file_contents, 
1174                           bgpdf.file_length, NULL, NULL);
1175 */
1176   if (bgpdf.document == NULL) { shutdown_bgpdf(); return FALSE; }
1177   
1178   if (pdfname[0]=='/' && ui.filename == NULL) {
1179     if (ui.default_path!=NULL) g_free(ui.default_path);
1180     ui.default_path = g_path_get_dirname(pdfname);
1181   }
1182
1183   if (!create_pages) return TRUE; // we're done
1184   
1185   // create pages with correct sizes if requested
1186   n_pages = poppler_document_get_n_pages(bgpdf.document);
1187   for (i=1; i<=n_pages; i++) {
1188     pdfpage = poppler_document_get_page(bgpdf.document, i-1);
1189     if (!pdfpage) continue;
1190     if (journal.npages < i) {
1191       bg = g_new(struct Background, 1);
1192       bg->canvas_item = NULL;
1193       pg = NULL;
1194     } else {
1195       pg = (struct Page *)g_list_nth_data(journal.pages, i-1);
1196       bg = pg->bg;
1197     }
1198     bg->type = BG_PDF;
1199     bg->filename = refstring_ref(bgpdf.filename);
1200     bg->file_domain = bgpdf.file_domain;
1201     bg->file_page_seq = i;
1202     bg->pixbuf = NULL;
1203     bg->pixbuf_scale = 0;
1204     poppler_page_get_size(pdfpage, &width, &height);
1205     g_object_unref(pdfpage);
1206     if (pg == NULL) {
1207       pg = new_page_with_bg(bg, width, height);
1208       journal.pages = g_list_append(journal.pages, pg);
1209       journal.npages++;
1210     } else {
1211       pg->width = width; 
1212       pg->height = height;
1213       make_page_clipbox(pg);
1214       update_canvas_bg(pg);
1215     }
1216   }
1217   update_page_stuff();
1218   rescale_bg_pixmaps(); // this actually requests the pages !!
1219   return TRUE;
1220 }
1221
1222
1223 // look for all journal pages with given pdf bg, and update their bg pixmaps
1224 void bgpdf_update_bg(int pageno, struct BgPdfPage *bgpg)
1225 {
1226   GList *list;
1227   struct Page *pg;
1228   
1229   for (list = journal.pages; list!= NULL; list = list->next) {
1230     pg = (struct Page *)list->data;
1231     if (pg->bg->type == BG_PDF && pg->bg->file_page_seq == pageno) {
1232       if (pg->bg->pixbuf!=NULL) gdk_pixbuf_unref(pg->bg->pixbuf);
1233       pg->bg->pixbuf = gdk_pixbuf_ref(bgpg->pixbuf);
1234       pg->bg->pixel_width = bgpg->pixel_width;
1235       pg->bg->pixel_height = bgpg->pixel_height;
1236       update_canvas_bg(pg);
1237     }
1238   }
1239 }
1240
1241 // initialize the recent files list
1242 void init_mru(void)
1243 {
1244   int i;
1245   gsize lfptr;
1246   char s[5];
1247   GIOChannel *f;
1248   gchar *str;
1249   GIOStatus status;
1250   
1251   g_strlcpy(s, "mru0", 5);
1252   for (s[3]='0', i=0; i<MRU_SIZE; s[3]++, i++) {
1253     ui.mrumenu[i] = GET_COMPONENT(s);
1254     ui.mru[i] = NULL;
1255   }
1256   f = g_io_channel_new_file(ui.mrufile, "r", NULL);
1257   if (f) status = G_IO_STATUS_NORMAL;
1258   else status = G_IO_STATUS_ERROR;
1259   i = 0;
1260   while (status == G_IO_STATUS_NORMAL && i<MRU_SIZE) {
1261     lfptr = 0;
1262     status = g_io_channel_read_line(f, &str, NULL, &lfptr, NULL);
1263     if (status == G_IO_STATUS_NORMAL && lfptr>0) {
1264       str[lfptr] = 0;
1265       ui.mru[i] = str;
1266       i++;
1267     }
1268   }
1269   if (f) {
1270     g_io_channel_shutdown(f, FALSE, NULL);
1271     g_io_channel_unref(f);
1272   }
1273   update_mru_menu();
1274 }
1275
1276 void update_mru_menu(void)
1277 {
1278   int i;
1279   gboolean anyone = FALSE;
1280   gchar *tmp;
1281   
1282   for (i=0; i<MRU_SIZE; i++) {
1283     if (ui.mru[i]!=NULL) {
1284       tmp = g_strdup_printf("_%d %s", i+1,
1285                g_strjoinv("__", g_strsplit_set(g_basename(ui.mru[i]),"_",-1)));
1286       gtk_label_set_text_with_mnemonic(GTK_LABEL(gtk_bin_get_child(GTK_BIN(ui.mrumenu[i]))),
1287           tmp);
1288       g_free(tmp);
1289       gtk_widget_show(ui.mrumenu[i]);
1290       anyone = TRUE;
1291     }
1292     else gtk_widget_hide(ui.mrumenu[i]);
1293   }
1294   gtk_widget_set_sensitive(GET_COMPONENT("fileRecentFiles"), anyone);
1295 }
1296
1297 void new_mru_entry(char *name)
1298 {
1299   int i, j;
1300   
1301   for (i=0;i<MRU_SIZE;i++) 
1302     if (ui.mru[i]!=NULL && !strcmp(ui.mru[i], name)) {
1303       g_free(ui.mru[i]);
1304       for (j=i+1; j<MRU_SIZE; j++) ui.mru[j-1] = ui.mru[j];
1305       ui.mru[MRU_SIZE-1]=NULL;
1306     }
1307   if (ui.mru[MRU_SIZE-1]!=NULL) g_free(ui.mru[MRU_SIZE-1]);
1308   for (j=MRU_SIZE-1; j>=1; j--) ui.mru[j] = ui.mru[j-1];
1309   ui.mru[0] = g_strdup(name);
1310   update_mru_menu();
1311 }
1312
1313 void delete_mru_entry(int which)
1314 {
1315   int i;
1316   
1317   if (ui.mru[which]!=NULL) g_free(ui.mru[which]);
1318   for (i=which+1;i<MRU_SIZE;i++) 
1319     ui.mru[i-1] = ui.mru[i];
1320   ui.mru[MRU_SIZE-1] = NULL;
1321   update_mru_menu();
1322 }
1323
1324 void save_mru_list(void)
1325 {
1326   FILE *f;
1327   int i;
1328   
1329   f = fopen(ui.mrufile, "w");
1330   if (f==NULL) return;
1331   for (i=0; i<MRU_SIZE; i++)
1332     if (ui.mru[i]!=NULL) fprintf(f, "%s\n", ui.mru[i]);
1333   fclose(f);
1334 }
1335
1336 void init_config_default(void)
1337 {
1338   int i, j;
1339
1340   DEFAULT_ZOOM = DISPLAY_DPI_DEFAULT/72.0;
1341   ui.zoom = ui.startup_zoom = 1.0*DEFAULT_ZOOM;
1342   ui.default_page.height = 792.0;
1343   ui.default_page.width = 612.0;
1344   ui.default_page.bg->type = BG_SOLID;
1345   ui.default_page.bg->color_no = COLOR_WHITE;
1346   ui.default_page.bg->color_rgba = predef_bgcolors_rgba[COLOR_WHITE];
1347   ui.default_page.bg->ruling = RULING_LINED;
1348   ui.view_continuous = TRUE;
1349   ui.allow_xinput = TRUE;
1350   ui.discard_corepointer = FALSE;
1351   ui.left_handed = FALSE;
1352   ui.shorten_menus = FALSE;
1353   ui.shorten_menu_items = g_strdup(DEFAULT_SHORTEN_MENUS);
1354   ui.auto_save_prefs = FALSE;
1355   ui.bg_apply_all_pages = FALSE;
1356   ui.use_erasertip = FALSE;
1357   ui.window_default_width = 720;
1358   ui.window_default_height = 480;
1359   ui.maximize_at_start = FALSE;
1360   ui.fullscreen = FALSE;
1361   ui.scrollbar_step_increment = 30;
1362   ui.zoom_step_increment = 1;
1363   ui.zoom_step_factor = 1.5;
1364   ui.progressive_bg = TRUE;
1365   ui.print_ruling = TRUE;
1366   ui.default_unit = UNIT_CM;
1367   ui.default_path = NULL;
1368   ui.default_font_name = g_strdup(DEFAULT_FONT);
1369   ui.default_font_size = DEFAULT_FONT_SIZE;
1370   ui.pressure_sensitivity = FALSE;
1371   ui.width_minimum_multiplier = 0.0;
1372   ui.width_maximum_multiplier = 1.25;
1373   ui.button_switch_mapping = FALSE;
1374   ui.autoload_pdf_xoj = FALSE;
1375   ui.poppler_force_cairo = FALSE;
1376   
1377   // the default UI vertical order
1378   ui.vertical_order[0][0] = 1; 
1379   ui.vertical_order[0][1] = 2; 
1380   ui.vertical_order[0][2] = 3; 
1381   ui.vertical_order[0][3] = 0; 
1382   ui.vertical_order[0][4] = 4;
1383   ui.vertical_order[1][0] = 2;
1384   ui.vertical_order[1][1] = 3;
1385   ui.vertical_order[1][2] = 0;
1386   ui.vertical_order[1][3] = ui.vertical_order[1][4] = -1;
1387
1388   ui.toolno[0] = ui.startuptool = TOOL_PEN;
1389   for (i=1; i<=NUM_BUTTONS; i++) {
1390     ui.toolno[i] = TOOL_ERASER;
1391   }
1392   for (i=0; i<=NUM_BUTTONS; i++)
1393     ui.linked_brush[i] = BRUSH_LINKED;
1394   ui.brushes[0][TOOL_PEN].color_no = COLOR_BLACK;
1395   ui.brushes[0][TOOL_ERASER].color_no = COLOR_WHITE;
1396   ui.brushes[0][TOOL_HIGHLIGHTER].color_no = COLOR_YELLOW;
1397   for (i=0; i < NUM_STROKE_TOOLS; i++) {
1398     ui.brushes[0][i].thickness_no = THICKNESS_MEDIUM;
1399     ui.brushes[0][i].tool_options = 0;
1400     ui.brushes[0][i].ruler = FALSE;
1401     ui.brushes[0][i].recognizer = FALSE;
1402     ui.brushes[0][i].variable_width = FALSE;
1403   }
1404   for (i=0; i< NUM_STROKE_TOOLS; i++)
1405     for (j=1; j<=NUM_BUTTONS; j++)
1406       g_memmove(&(ui.brushes[j][i]), &(ui.brushes[0][i]), sizeof(struct Brush));
1407
1408   // predef_thickness is already initialized as a global variable
1409   GS_BITMAP_DPI = 144;
1410   PDFTOPPM_PRINTING_DPI = 150;
1411   
1412   ui.hiliter_opacity = 0.5;
1413   
1414 #if GTK_CHECK_VERSION(2,10,0)
1415   ui.print_settings = NULL;
1416 #endif
1417   
1418 }
1419
1420 #if GLIB_CHECK_VERSION(2,6,0)
1421
1422 void update_keyval(const gchar *group_name, const gchar *key,
1423                 const gchar *comment, gchar *value)
1424 {
1425   gboolean has_it = g_key_file_has_key(ui.config_data, group_name, key, NULL);
1426   cleanup_numeric(value);
1427   g_key_file_set_value(ui.config_data, group_name, key, value);
1428   g_free(value);
1429   if (!has_it) g_key_file_set_comment(ui.config_data, group_name, key, comment, NULL);
1430 }
1431
1432 #endif
1433
1434 const char *vorder_usernames[VBOX_MAIN_NITEMS+1] = 
1435   {"drawarea", "menu", "main_toolbar", "pen_toolbar", "statusbar", NULL};
1436   
1437 gchar *verbose_vertical_order(int *order)
1438 {
1439   gchar buf[80], *p; // longer than needed
1440   int i;
1441
1442   p = buf;  
1443   for (i=0; i<VBOX_MAIN_NITEMS; i++) {
1444     if (order[i]<0 || order[i]>=VBOX_MAIN_NITEMS) continue;
1445     if (p!=buf) *(p++) = ' ';
1446     p = g_stpcpy(p, vorder_usernames[order[i]]);
1447   }
1448   return g_strdup(buf);
1449 }
1450
1451 void save_config_to_file(void)
1452 {
1453   gchar *buf;
1454   FILE *f;
1455
1456 #if GLIB_CHECK_VERSION(2,6,0)
1457   // no support for keyval files before Glib 2.6.0
1458   if (glib_minor_version<6) return; 
1459
1460   // save some data...
1461   ui.maximize_at_start = (gdk_window_get_state(winMain->window) & GDK_WINDOW_STATE_MAXIMIZED);
1462   if (!ui.maximize_at_start && !ui.fullscreen)
1463     gdk_drawable_get_size(winMain->window, 
1464       &ui.window_default_width, &ui.window_default_height);
1465
1466   update_keyval("general", "display_dpi",
1467     _(" the display resolution, in pixels per inch"),
1468     g_strdup_printf("%.2f", DEFAULT_ZOOM*72));
1469   update_keyval("general", "initial_zoom",
1470     _(" the initial zoom level, in percent"),
1471     g_strdup_printf("%.2f", 100*ui.zoom/DEFAULT_ZOOM));
1472   update_keyval("general", "window_maximize",
1473     _(" maximize the window at startup (true/false)"),
1474     g_strdup(ui.maximize_at_start?"true":"false"));
1475   update_keyval("general", "window_fullscreen",
1476     _(" start in full screen mode (true/false)"),
1477     g_strdup(ui.fullscreen?"true":"false"));
1478   update_keyval("general", "window_width",
1479     _(" the window width in pixels (when not maximized)"),
1480     g_strdup_printf("%d", ui.window_default_width));
1481   update_keyval("general", "window_height",
1482     _(" the window height in pixels"),
1483     g_strdup_printf("%d", ui.window_default_height));
1484   update_keyval("general", "scrollbar_speed",
1485     _(" scrollbar step increment (in pixels)"),
1486     g_strdup_printf("%d", ui.scrollbar_step_increment));
1487   update_keyval("general", "zoom_dialog_increment",
1488     _(" the step increment in the zoom dialog box"),
1489     g_strdup_printf("%d", ui.zoom_step_increment));
1490   update_keyval("general", "zoom_step_factor",
1491     _(" the multiplicative factor for zoom in/out"),
1492     g_strdup_printf("%.3f", ui.zoom_step_factor));
1493   update_keyval("general", "view_continuous",
1494     _(" document view (true = continuous, false = single page)"),
1495     g_strdup(ui.view_continuous?"true":"false"));
1496   update_keyval("general", "use_xinput",
1497     _(" use XInput extensions (true/false)"),
1498     g_strdup(ui.allow_xinput?"true":"false"));
1499   update_keyval("general", "discard_corepointer",
1500     _(" discard Core Pointer events in XInput mode (true/false)"),
1501     g_strdup(ui.discard_corepointer?"true":"false"));
1502   update_keyval("general", "use_erasertip",
1503     _(" always map eraser tip to eraser (true/false)"),
1504     g_strdup(ui.use_erasertip?"true":"false"));
1505   update_keyval("general", "buttons_switch_mappings",
1506     _(" buttons 2 and 3 switch mappings instead of drawing (useful for some tablets) (true/false)"),
1507     g_strdup(ui.button_switch_mapping?"true":"false"));
1508   update_keyval("general", "autoload_pdf_xoj",
1509     _(" automatically load filename.pdf.xoj instead of filename.pdf (true/false)"),
1510     g_strdup(ui.autoload_pdf_xoj?"true":"false"));
1511   update_keyval("general", "default_path",
1512     _(" default path for open/save (leave blank for current directory)"),
1513     g_strdup((ui.default_path!=NULL)?ui.default_path:""));
1514   update_keyval("general", "pressure_sensitivity",
1515      _(" use pressure sensitivity to control pen stroke width (true/false)"),
1516      g_strdup(ui.pressure_sensitivity?"true":"false"));
1517   update_keyval("general", "width_minimum_multiplier",
1518      _(" minimum width multiplier"),
1519      g_strdup_printf("%.2f", ui.width_minimum_multiplier));
1520   update_keyval("general", "width_maximum_multiplier",
1521      _(" maximum width multiplier"),
1522      g_strdup_printf("%.2f", ui.width_maximum_multiplier));
1523   update_keyval("general", "interface_order",
1524     _(" interface components from top to bottom\n valid values: drawarea menu main_toolbar pen_toolbar statusbar"),
1525     verbose_vertical_order(ui.vertical_order[0]));
1526   update_keyval("general", "interface_fullscreen",
1527     _(" interface components in fullscreen mode, from top to bottom"),
1528     verbose_vertical_order(ui.vertical_order[1]));
1529   update_keyval("general", "interface_lefthanded",
1530     _(" interface has left-handed scrollbar (true/false)"),
1531     g_strdup(ui.left_handed?"true":"false"));
1532   update_keyval("general", "shorten_menus",
1533     _(" hide some unwanted menu or toolbar items (true/false)"),
1534     g_strdup(ui.shorten_menus?"true":"false"));
1535   update_keyval("general", "shorten_menu_items",
1536     _(" interface items to hide (customize at your own risk!)\n see source file xo-interface.c for a list of item names"),
1537     g_strdup(ui.shorten_menu_items));
1538   update_keyval("general", "highlighter_opacity",
1539     _(" highlighter opacity (0 to 1, default 0.5)\n warning: opacity level is not saved in xoj files!"),
1540     g_strdup_printf("%.2f", ui.hiliter_opacity));
1541   update_keyval("general", "autosave_prefs",
1542     _(" auto-save preferences on exit (true/false)"),
1543     g_strdup(ui.auto_save_prefs?"true":"false"));
1544   update_keyval("general", "poppler_force_cairo",
1545     _(" force PDF rendering through cairo (slower but nicer) (true/false)"),
1546     g_strdup(ui.poppler_force_cairo?"true":"false"));
1547
1548   update_keyval("paper", "width",
1549     _(" the default page width, in points (1/72 in)"),
1550     g_strdup_printf("%.2f", ui.default_page.width));
1551   update_keyval("paper", "height",
1552     _(" the default page height, in points (1/72 in)"),
1553     g_strdup_printf("%.2f", ui.default_page.height));
1554   update_keyval("paper", "color",
1555     _(" the default paper color"),
1556     (ui.default_page.bg->color_no>=0)?
1557     g_strdup(bgcolor_names[ui.default_page.bg->color_no]):
1558     g_strdup_printf("#%08x", ui.default_page.bg->color_rgba));
1559   update_keyval("paper", "style",
1560     _(" the default paper style (plain, lined, ruled, or graph)"),
1561     g_strdup(bgstyle_names[ui.default_page.bg->ruling]));
1562   update_keyval("paper", "apply_all",
1563     _(" apply paper style changes to all pages (true/false)"),
1564     g_strdup(ui.bg_apply_all_pages?"true":"false"));
1565   update_keyval("paper", "default_unit",
1566     _(" preferred unit (cm, in, px, pt)"),
1567     g_strdup(unit_names[ui.default_unit]));
1568   update_keyval("paper", "print_ruling",
1569     _(" include paper ruling when printing or exporting to PDF (true/false)"),
1570     g_strdup(ui.print_ruling?"true":"false"));
1571   update_keyval("paper", "progressive_bg",
1572     _(" just-in-time update of page backgrounds (true/false)"),
1573     g_strdup(ui.progressive_bg?"true":"false"));
1574   update_keyval("paper", "gs_bitmap_dpi",
1575     _(" bitmap resolution of PS/PDF backgrounds rendered using ghostscript (dpi)"),
1576     g_strdup_printf("%d", GS_BITMAP_DPI));
1577   update_keyval("paper", "pdftoppm_printing_dpi",
1578     _(" bitmap resolution of PDF backgrounds when printing with libgnomeprint (dpi)"),
1579     g_strdup_printf("%d", PDFTOPPM_PRINTING_DPI));
1580
1581   update_keyval("tools", "startup_tool",
1582     _(" selected tool at startup (pen, eraser, highlighter, selectrect, vertspace, hand)"),
1583     g_strdup(tool_names[ui.startuptool]));
1584   update_keyval("tools", "pen_color",
1585     _(" default pen color"),
1586     (ui.default_brushes[TOOL_PEN].color_no>=0)?
1587     g_strdup(color_names[ui.default_brushes[TOOL_PEN].color_no]):
1588     g_strdup_printf("#%08x", ui.default_brushes[TOOL_PEN].color_rgba));
1589   update_keyval("tools", "pen_thickness",
1590     _(" default pen thickness (fine = 1, medium = 2, thick = 3)"),
1591     g_strdup_printf("%d", ui.default_brushes[TOOL_PEN].thickness_no));
1592   update_keyval("tools", "pen_ruler",
1593     _(" default pen is in ruler mode (true/false)"),
1594     g_strdup(ui.default_brushes[TOOL_PEN].ruler?"true":"false"));
1595   update_keyval("tools", "pen_recognizer",
1596     _(" default pen is in shape recognizer mode (true/false)"),
1597     g_strdup(ui.default_brushes[TOOL_PEN].recognizer?"true":"false"));
1598   update_keyval("tools", "eraser_thickness",
1599     _(" default eraser thickness (fine = 1, medium = 2, thick = 3)"),
1600     g_strdup_printf("%d", ui.default_brushes[TOOL_ERASER].thickness_no));
1601   update_keyval("tools", "eraser_mode",
1602     _(" default eraser mode (standard = 0, whiteout = 1, strokes = 2)"),
1603     g_strdup_printf("%d", ui.default_brushes[TOOL_ERASER].tool_options));
1604   update_keyval("tools", "highlighter_color",
1605     _(" default highlighter color"),
1606     (ui.default_brushes[TOOL_HIGHLIGHTER].color_no>=0)?
1607     g_strdup(color_names[ui.default_brushes[TOOL_HIGHLIGHTER].color_no]):
1608     g_strdup_printf("#%08x", ui.default_brushes[TOOL_HIGHLIGHTER].color_rgba));
1609   update_keyval("tools", "highlighter_thickness",
1610     _(" default highlighter thickness (fine = 1, medium = 2, thick = 3)"),
1611     g_strdup_printf("%d", ui.default_brushes[TOOL_HIGHLIGHTER].thickness_no));
1612   update_keyval("tools", "highlighter_ruler",
1613     _(" default highlighter is in ruler mode (true/false)"),
1614     g_strdup(ui.default_brushes[TOOL_HIGHLIGHTER].ruler?"true":"false"));
1615   update_keyval("tools", "highlighter_recognizer",
1616     _(" default highlighter is in shape recognizer mode (true/false)"),
1617     g_strdup(ui.default_brushes[TOOL_HIGHLIGHTER].recognizer?"true":"false"));
1618   update_keyval("tools", "btn2_tool",
1619     _(" button 2 tool (pen, eraser, highlighter, text, selectrect, vertspace, hand)"),
1620     g_strdup(tool_names[ui.toolno[1]]));
1621   update_keyval("tools", "btn2_linked",
1622     _(" button 2 brush linked to primary brush (true/false) (overrides all other settings)"),
1623     g_strdup((ui.linked_brush[1]==BRUSH_LINKED)?"true":"false"));
1624   update_keyval("tools", "btn2_color",
1625     _(" button 2 brush color (for pen or highlighter only)"),
1626     (ui.toolno[1]<NUM_STROKE_TOOLS)?
1627       ((ui.brushes[1][ui.toolno[1]].color_no>=0)?
1628        g_strdup(color_names[ui.brushes[1][ui.toolno[1]].color_no]):
1629        g_strdup_printf("#%08x", ui.brushes[1][ui.toolno[1]].color_rgba)):
1630       g_strdup("white"));
1631   update_keyval("tools", "btn2_thickness",
1632     _(" button 2 brush thickness (pen, eraser, or highlighter only)"),
1633     g_strdup_printf("%d", (ui.toolno[1]<NUM_STROKE_TOOLS)?
1634                             ui.brushes[1][ui.toolno[1]].thickness_no:0));
1635   update_keyval("tools", "btn2_ruler",
1636     _(" button 2 ruler mode (true/false) (for pen or highlighter only)"),
1637     g_strdup(((ui.toolno[1]<NUM_STROKE_TOOLS)?
1638               ui.brushes[1][ui.toolno[1]].ruler:FALSE)?"true":"false"));
1639   update_keyval("tools", "btn2_recognizer",
1640     _(" button 2 shape recognizer mode (true/false) (pen or highlighter only)"),
1641     g_strdup(((ui.toolno[1]<NUM_STROKE_TOOLS)?
1642               ui.brushes[1][ui.toolno[1]].recognizer:FALSE)?"true":"false"));
1643   update_keyval("tools", "btn2_erasermode",
1644     _(" button 2 eraser mode (eraser only)"),
1645     g_strdup_printf("%d", ui.brushes[1][TOOL_ERASER].tool_options));
1646   update_keyval("tools", "btn3_tool",
1647     _(" button 3 tool (pen, eraser, highlighter, text, selectrect, vertspace, hand)"),
1648     g_strdup(tool_names[ui.toolno[2]]));
1649   update_keyval("tools", "btn3_linked",
1650     _(" button 3 brush linked to primary brush (true/false) (overrides all other settings)"),
1651     g_strdup((ui.linked_brush[2]==BRUSH_LINKED)?"true":"false"));
1652   update_keyval("tools", "btn3_color",
1653     _(" button 3 brush color (for pen or highlighter only)"),
1654     (ui.toolno[2]<NUM_STROKE_TOOLS)?
1655       ((ui.brushes[2][ui.toolno[2]].color_no>=0)?
1656        g_strdup(color_names[ui.brushes[2][ui.toolno[2]].color_no]):
1657        g_strdup_printf("#%08x", ui.brushes[2][ui.toolno[2]].color_rgba)):
1658       g_strdup("white"));
1659   update_keyval("tools", "btn3_thickness",
1660     _(" button 3 brush thickness (pen, eraser, or highlighter only)"),
1661     g_strdup_printf("%d", (ui.toolno[2]<NUM_STROKE_TOOLS)?
1662                             ui.brushes[2][ui.toolno[2]].thickness_no:0));
1663   update_keyval("tools", "btn3_ruler",
1664     _(" button 3 ruler mode (true/false) (for pen or highlighter only)"),
1665     g_strdup(((ui.toolno[2]<NUM_STROKE_TOOLS)?
1666               ui.brushes[2][ui.toolno[2]].ruler:FALSE)?"true":"false"));
1667   update_keyval("tools", "btn3_recognizer",
1668     _(" button 3 shape recognizer mode (true/false) (pen or highlighter only)"),
1669     g_strdup(((ui.toolno[2]<NUM_STROKE_TOOLS)?
1670               ui.brushes[2][ui.toolno[2]].recognizer:FALSE)?"true":"false"));
1671   update_keyval("tools", "btn3_erasermode",
1672     _(" button 3 eraser mode (eraser only)"),
1673     g_strdup_printf("%d", ui.brushes[2][TOOL_ERASER].tool_options));
1674
1675   update_keyval("tools", "pen_thicknesses",
1676     _(" thickness of the various pens (in points, 1 pt = 1/72 in)"),
1677     g_strdup_printf("%.2f;%.2f;%.2f;%.2f;%.2f", 
1678       predef_thickness[TOOL_PEN][0], predef_thickness[TOOL_PEN][1],
1679       predef_thickness[TOOL_PEN][2], predef_thickness[TOOL_PEN][3],
1680       predef_thickness[TOOL_PEN][4]));
1681   update_keyval("tools", "eraser_thicknesses",
1682     _(" thickness of the various erasers (in points, 1 pt = 1/72 in)"),
1683     g_strdup_printf("%.2f;%.2f;%.2f", 
1684       predef_thickness[TOOL_ERASER][1], predef_thickness[TOOL_ERASER][2],
1685       predef_thickness[TOOL_ERASER][3]));
1686   update_keyval("tools", "highlighter_thicknesses",
1687     _(" thickness of the various highlighters (in points, 1 pt = 1/72 in)"),
1688     g_strdup_printf("%.2f;%.2f;%.2f", 
1689       predef_thickness[TOOL_HIGHLIGHTER][1], predef_thickness[TOOL_HIGHLIGHTER][2],
1690       predef_thickness[TOOL_HIGHLIGHTER][3]));
1691   update_keyval("tools", "default_font",
1692     _(" name of the default font"),
1693     g_strdup(ui.default_font_name));
1694   update_keyval("tools", "default_font_size",
1695     _(" default font size"),
1696     g_strdup_printf("%.1f", ui.default_font_size));
1697
1698   buf = g_key_file_to_data(ui.config_data, NULL, NULL);
1699   if (buf == NULL) return;
1700   f = fopen(ui.configfile, "w");
1701   if (f==NULL) { g_free(buf); return; }
1702   fputs(buf, f);
1703   fclose(f);
1704   g_free(buf);
1705 #endif
1706 }
1707
1708 #if GLIB_CHECK_VERSION(2,6,0)
1709 gboolean parse_keyval_float(const gchar *group, const gchar *key, double *val, double inf, double sup)
1710 {
1711   gchar *ret, *end;
1712   double conv;
1713   
1714   ret = g_key_file_get_value(ui.config_data, group, key, NULL);
1715   if (ret==NULL) return FALSE;
1716   conv = g_ascii_strtod(ret, &end);
1717   if (*end!=0) { g_free(ret); return FALSE; }
1718   g_free(ret);
1719   if (conv < inf || conv > sup) return FALSE;
1720   *val = conv;
1721   return TRUE;
1722 }
1723
1724 gboolean parse_keyval_floatlist(const gchar *group, const gchar *key, double *val, int n, double inf, double sup)
1725 {
1726   gchar *ret, *end;
1727   double conv[5];
1728   int i;
1729
1730   if (n>5) return FALSE;
1731   ret = g_key_file_get_value(ui.config_data, group, key, NULL);
1732   if (ret==NULL) return FALSE;
1733   end = ret;
1734   for (i=0; i<n; i++) {
1735     conv[i] = g_ascii_strtod(end, &end);
1736     if ((i==n-1 && *end!=0) || (i<n-1 && *end!=';') ||
1737         (conv[i] < inf) || (conv[i] > sup)) { g_free(ret); return FALSE; }
1738     end++;
1739   }
1740   g_free(ret);
1741   for (i=0; i<n; i++) val[i] = conv[i];
1742   return TRUE;
1743 }
1744
1745 gboolean parse_keyval_int(const gchar *group, const gchar *key, int *val, int inf, int sup)
1746 {
1747   gchar *ret, *end;
1748   int conv;
1749   
1750   ret = g_key_file_get_value(ui.config_data, group, key, NULL);
1751   if (ret==NULL) return FALSE;
1752   conv = strtol(ret, &end, 10);
1753   if (*end!=0) { g_free(ret); return FALSE; }
1754   g_free(ret);
1755   if (conv < inf || conv > sup) return FALSE;
1756   *val = conv;
1757   return TRUE;
1758 }
1759
1760 gboolean parse_keyval_enum(const gchar *group, const gchar *key, int *val, const char **names, int n)
1761 {
1762   gchar *ret;
1763   int i;
1764   
1765   ret = g_key_file_get_value(ui.config_data, group, key, NULL);
1766   if (ret==NULL) return FALSE;
1767   for (i=0; i<n; i++) {
1768     if (!names[i][0]) continue; // "" is for invalid values
1769     if (!g_ascii_strcasecmp(ret, names[i]))
1770       { *val = i; g_free(ret); return TRUE; }
1771   }
1772   return FALSE;
1773 }
1774
1775 gboolean parse_keyval_enum_color(const gchar *group, const gchar *key, int *val, guint *val_rgba, 
1776                                  const char **names, const guint *predef_rgba, int n)
1777 {
1778   gchar *ret;
1779   int i;
1780   
1781   ret = g_key_file_get_value(ui.config_data, group, key, NULL);
1782   if (ret==NULL) return FALSE;
1783   for (i=0; i<n; i++) {
1784     if (!names[i][0]) continue; // "" is for invalid values
1785     if (!g_ascii_strcasecmp(ret, names[i]))
1786       { *val = i; *val_rgba = predef_rgba[i]; g_free(ret); return TRUE; }
1787   }
1788   if (ret[0]=='#') {
1789     *val = COLOR_OTHER;
1790     *val_rgba = strtoul(ret+1, NULL, 16);
1791     g_free(ret);
1792     return TRUE;
1793   }
1794   return FALSE;
1795 }
1796
1797 gboolean parse_keyval_boolean(const gchar *group, const gchar *key, gboolean *val)
1798 {
1799   gchar *ret;
1800   
1801   ret = g_key_file_get_value(ui.config_data, group, key, NULL);
1802   if (ret==NULL) return FALSE;
1803   if (!g_ascii_strcasecmp(ret, "true")) 
1804     { *val = TRUE; g_free(ret); return TRUE; }
1805   if (!g_ascii_strcasecmp(ret, "false")) 
1806     { *val = FALSE; g_free(ret); return TRUE; }
1807   g_free(ret);
1808   return FALSE;
1809 }
1810
1811 gboolean parse_keyval_string(const gchar *group, const gchar *key, gchar **val)
1812 {
1813   gchar *ret;
1814   
1815   ret = g_key_file_get_value(ui.config_data, group, key, NULL);
1816   if (ret==NULL) return FALSE;
1817   if (strlen(ret) == 0) {
1818     *val = NULL;
1819     g_free(ret);
1820   } 
1821   else *val = ret;
1822   return TRUE;
1823 }
1824
1825 gboolean parse_keyval_vorderlist(const gchar *group, const gchar *key, int *order)
1826 {
1827   gchar *ret, *p;
1828   int tmp[VBOX_MAIN_NITEMS];
1829   int i, n, l;
1830
1831   ret = g_key_file_get_value(ui.config_data, group, key, NULL);
1832   if (ret==NULL) return FALSE;
1833   
1834   for (i=0; i<VBOX_MAIN_NITEMS; i++) tmp[i] = -1;
1835   n = 0; p = ret;
1836   while (*p==' ') p++;
1837   while (*p!=0) {
1838     if (n>VBOX_MAIN_NITEMS) return FALSE; // too many items
1839     for (i=0; i<VBOX_MAIN_NITEMS; i++) {
1840       if (!g_str_has_prefix(p, vorder_usernames[i])) continue;
1841       l = strlen(vorder_usernames[i]);
1842       if (p[l]==' '||p[l]==0) { p+=l; break; }
1843     }
1844     if (i>=VBOX_MAIN_NITEMS) { g_free(ret); return FALSE; } // parse error
1845     // we found item #i
1846     tmp[n++] = i;
1847     while (*p==' ') p++;
1848   }
1849   
1850   for (n=0; n<VBOX_MAIN_NITEMS; n++) order[n] = tmp[n];
1851   g_free(ret);
1852   return TRUE;
1853 }
1854
1855 #endif
1856
1857 void load_config_from_file(void)
1858 {
1859   double f;
1860   gboolean b;
1861   int i, j;
1862   gchar *str;
1863   
1864 #if GLIB_CHECK_VERSION(2,6,0)
1865   // no support for keyval files before Glib 2.6.0
1866   if (glib_minor_version<6) return; 
1867   ui.config_data = g_key_file_new();
1868   if (!g_key_file_load_from_file(ui.config_data, ui.configfile, 
1869          G_KEY_FILE_KEEP_COMMENTS, NULL)) {
1870     g_key_file_free(ui.config_data);
1871     ui.config_data = g_key_file_new();
1872     g_key_file_set_comment(ui.config_data, NULL, NULL, 
1873          _(" Xournal configuration file.\n"
1874            " This file is generated automatically upon saving preferences.\n"
1875            " Use caution when editing this file manually.\n"), NULL);
1876     return;
1877   }
1878
1879   // parse keys from the keyfile to set defaults
1880   if (parse_keyval_float("general", "display_dpi", &f, 10., 500.))
1881     DEFAULT_ZOOM = f/72.0;
1882   if (parse_keyval_float("general", "initial_zoom", &f, 
1883               MIN_ZOOM*100/DEFAULT_ZOOM, MAX_ZOOM*100/DEFAULT_ZOOM))
1884     ui.zoom = ui.startup_zoom = DEFAULT_ZOOM*f/100.0;
1885   parse_keyval_boolean("general", "window_maximize", &ui.maximize_at_start);
1886   parse_keyval_boolean("general", "window_fullscreen", &ui.fullscreen);
1887   parse_keyval_int("general", "window_width", &ui.window_default_width, 10, 5000);
1888   parse_keyval_int("general", "window_height", &ui.window_default_height, 10, 5000);
1889   parse_keyval_int("general", "scrollbar_speed", &ui.scrollbar_step_increment, 1, 5000);
1890   parse_keyval_int("general", "zoom_dialog_increment", &ui.zoom_step_increment, 1, 500);
1891   parse_keyval_float("general", "zoom_step_factor", &ui.zoom_step_factor, 1., 5.);
1892   parse_keyval_boolean("general", "view_continuous", &ui.view_continuous);
1893   parse_keyval_boolean("general", "use_xinput", &ui.allow_xinput);
1894   parse_keyval_boolean("general", "discard_corepointer", &ui.discard_corepointer);
1895   parse_keyval_boolean("general", "use_erasertip", &ui.use_erasertip);
1896   parse_keyval_boolean("general", "buttons_switch_mappings", &ui.button_switch_mapping);
1897   parse_keyval_boolean("general", "autoload_pdf_xoj", &ui.autoload_pdf_xoj);
1898   parse_keyval_string("general", "default_path", &ui.default_path);
1899   parse_keyval_boolean("general", "pressure_sensitivity", &ui.pressure_sensitivity);
1900   parse_keyval_float("general", "width_minimum_multiplier", &ui.width_minimum_multiplier, 0., 10.);
1901   parse_keyval_float("general", "width_maximum_multiplier", &ui.width_maximum_multiplier, 0., 10.);
1902
1903   parse_keyval_vorderlist("general", "interface_order", ui.vertical_order[0]);
1904   parse_keyval_vorderlist("general", "interface_fullscreen", ui.vertical_order[1]);
1905   parse_keyval_boolean("general", "interface_lefthanded", &ui.left_handed);
1906   parse_keyval_boolean("general", "shorten_menus", &ui.shorten_menus);
1907   if (parse_keyval_string("general", "shorten_menu_items", &str))
1908     if (str!=NULL) { g_free(ui.shorten_menu_items); ui.shorten_menu_items = str; }
1909   parse_keyval_float("general", "highlighter_opacity", &ui.hiliter_opacity, 0., 1.);
1910   parse_keyval_boolean("general", "autosave_prefs", &ui.auto_save_prefs);
1911   parse_keyval_boolean("general", "poppler_force_cairo", &ui.poppler_force_cairo);
1912   
1913   parse_keyval_float("paper", "width", &ui.default_page.width, 1., 5000.);
1914   parse_keyval_float("paper", "height", &ui.default_page.height, 1., 5000.);
1915   parse_keyval_enum_color("paper", "color", 
1916      &(ui.default_page.bg->color_no), &(ui.default_page.bg->color_rgba), 
1917      bgcolor_names, predef_bgcolors_rgba, COLOR_MAX);
1918   parse_keyval_enum("paper", "style", &(ui.default_page.bg->ruling), bgstyle_names, 4);
1919   parse_keyval_boolean("paper", "apply_all", &ui.bg_apply_all_pages);
1920   parse_keyval_enum("paper", "default_unit", &ui.default_unit, unit_names, 4);
1921   parse_keyval_boolean("paper", "progressive_bg", &ui.progressive_bg);
1922   parse_keyval_boolean("paper", "print_ruling", &ui.print_ruling);
1923   parse_keyval_int("paper", "gs_bitmap_dpi", &GS_BITMAP_DPI, 1, 1200);
1924   parse_keyval_int("paper", "pdftoppm_printing_dpi", &PDFTOPPM_PRINTING_DPI, 1, 1200);
1925
1926   parse_keyval_enum("tools", "startup_tool", &ui.startuptool, tool_names, NUM_TOOLS);
1927   ui.toolno[0] = ui.startuptool;
1928   parse_keyval_enum_color("tools", "pen_color", 
1929      &(ui.brushes[0][TOOL_PEN].color_no), &(ui.brushes[0][TOOL_PEN].color_rgba),
1930      color_names, predef_colors_rgba, COLOR_MAX);
1931   parse_keyval_int("tools", "pen_thickness", &(ui.brushes[0][TOOL_PEN].thickness_no), 0, 4);
1932   parse_keyval_boolean("tools", "pen_ruler", &(ui.brushes[0][TOOL_PEN].ruler));
1933   parse_keyval_boolean("tools", "pen_recognizer", &(ui.brushes[0][TOOL_PEN].recognizer));
1934   parse_keyval_int("tools", "eraser_thickness", &(ui.brushes[0][TOOL_ERASER].thickness_no), 1, 3);
1935   parse_keyval_int("tools", "eraser_mode", &(ui.brushes[0][TOOL_ERASER].tool_options), 0, 2);
1936   parse_keyval_enum_color("tools", "highlighter_color", 
1937      &(ui.brushes[0][TOOL_HIGHLIGHTER].color_no), &(ui.brushes[0][TOOL_HIGHLIGHTER].color_rgba),
1938      color_names, predef_colors_rgba, COLOR_MAX);
1939   parse_keyval_int("tools", "highlighter_thickness", &(ui.brushes[0][TOOL_HIGHLIGHTER].thickness_no), 0, 4);
1940   parse_keyval_boolean("tools", "highlighter_ruler", &(ui.brushes[0][TOOL_HIGHLIGHTER].ruler));
1941   parse_keyval_boolean("tools", "highlighter_recognizer", &(ui.brushes[0][TOOL_HIGHLIGHTER].recognizer));
1942   ui.brushes[0][TOOL_PEN].variable_width = ui.pressure_sensitivity;
1943   for (i=0; i< NUM_STROKE_TOOLS; i++)
1944     for (j=1; j<=NUM_BUTTONS; j++)
1945       g_memmove(&(ui.brushes[j][i]), &(ui.brushes[0][i]), sizeof(struct Brush));
1946
1947   parse_keyval_enum("tools", "btn2_tool", &(ui.toolno[1]), tool_names, NUM_TOOLS);
1948   if (parse_keyval_boolean("tools", "btn2_linked", &b))
1949     ui.linked_brush[1] = b?BRUSH_LINKED:BRUSH_STATIC;
1950   parse_keyval_enum("tools", "btn3_tool", &(ui.toolno[2]), tool_names, NUM_TOOLS);
1951   if (parse_keyval_boolean("tools", "btn3_linked", &b))
1952     ui.linked_brush[2] = b?BRUSH_LINKED:BRUSH_STATIC;
1953   if (ui.linked_brush[1]!=BRUSH_LINKED) {
1954     if (ui.toolno[1]==TOOL_PEN || ui.toolno[1]==TOOL_HIGHLIGHTER) {
1955       parse_keyval_boolean("tools", "btn2_ruler", &(ui.brushes[1][ui.toolno[1]].ruler));
1956       parse_keyval_boolean("tools", "btn2_recognizer", &(ui.brushes[1][ui.toolno[1]].recognizer));
1957       parse_keyval_enum_color("tools", "btn2_color", 
1958          &(ui.brushes[1][ui.toolno[1]].color_no), &(ui.brushes[1][ui.toolno[1]].color_rgba), 
1959          color_names, predef_colors_rgba, COLOR_MAX);
1960     }
1961     if (ui.toolno[1]<NUM_STROKE_TOOLS)
1962       parse_keyval_int("tools", "btn2_thickness", &(ui.brushes[1][ui.toolno[1]].thickness_no), 0, 4);
1963     if (ui.toolno[1]==TOOL_ERASER)
1964       parse_keyval_int("tools", "btn2_erasermode", &(ui.brushes[1][TOOL_ERASER].tool_options), 0, 2);
1965   }
1966   if (ui.linked_brush[2]!=BRUSH_LINKED) {
1967     if (ui.toolno[2]==TOOL_PEN || ui.toolno[2]==TOOL_HIGHLIGHTER) {
1968       parse_keyval_boolean("tools", "btn3_ruler", &(ui.brushes[2][ui.toolno[2]].ruler));
1969       parse_keyval_boolean("tools", "btn3_recognizer", &(ui.brushes[2][ui.toolno[2]].recognizer));
1970       parse_keyval_enum_color("tools", "btn3_color", 
1971          &(ui.brushes[2][ui.toolno[2]].color_no), &(ui.brushes[2][ui.toolno[2]].color_rgba), 
1972          color_names, predef_colors_rgba, COLOR_MAX);
1973     }
1974     if (ui.toolno[2]<NUM_STROKE_TOOLS)
1975       parse_keyval_int("tools", "btn3_thickness", &(ui.brushes[2][ui.toolno[2]].thickness_no), 0, 4);
1976     if (ui.toolno[2]==TOOL_ERASER)
1977       parse_keyval_int("tools", "btn3_erasermode", &(ui.brushes[2][TOOL_ERASER].tool_options), 0, 2);
1978   }
1979   parse_keyval_floatlist("tools", "pen_thicknesses", predef_thickness[TOOL_PEN], 5, 0.01, 1000.0);
1980   parse_keyval_floatlist("tools", "eraser_thicknesses", predef_thickness[TOOL_ERASER]+1, 3, 0.01, 1000.0);
1981   parse_keyval_floatlist("tools", "highlighter_thicknesses", predef_thickness[TOOL_HIGHLIGHTER]+1, 3, 0.01, 1000.0);
1982   if (parse_keyval_string("tools", "default_font", &str))
1983     if (str!=NULL) { g_free(ui.default_font_name); ui.default_font_name = str; }
1984   parse_keyval_float("tools", "default_font_size", &ui.default_font_size, 1., 200.);
1985 #endif
1986 }