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