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