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