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