]> git.donarmstrong.com Git - xournal.git/blob - src/xo-file.c
1afcd18436545f71ba535a797986d55569625dd6
[xournal.git] / src / xo-file.c
1 #ifdef HAVE_CONFIG_H
2 #  include <config.h>
3 #endif
4
5 #include <signal.h>
6 #include <memory.h>
7 #include <string.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <gtk/gtk.h>
11 #include <libgnomecanvas/libgnomecanvas.h>
12 #include <zlib.h>
13 #include <math.h>
14 #include <gdk/gdkx.h>
15 #include <X11/Xlib.h>
16
17 #include "xournal.h"
18 #include "xo-interface.h"
19 #include "xo-support.h"
20 #include "xo-callbacks.h"
21 #include "xo-misc.h"
22 #include "xo-file.h"
23
24 const char *tool_names[NUM_STROKE_TOOLS] = {"pen", "eraser", "highlighter"};
25 const char *color_names[COLOR_MAX] = {"black", "blue", "red", "green",
26    "gray", "lightblue", "lightgreen", "magenta", "orange", "yellow", "white"};
27 const char *bgtype_names[3] = {"solid", "pixmap", "pdf"};
28 const char *bgcolor_names[COLOR_MAX] = {"", "blue", "pink", "green",
29    "", "", "", "", "orange", "yellow", "white"};
30 const char *bgstyle_names[4] = {"plain", "lined", "ruled", "graph"};
31 const char *file_domain_names[3] = {"absolute", "attach", "clone"};
32
33 // creates a new empty journal
34
35 void new_journal(void)
36 {
37   journal.npages = 1;
38   journal.pages = g_list_append(NULL, new_page(&ui.default_page));
39   journal.last_attach_no = 0;
40   ui.pageno = 0;
41   ui.layerno = 0;
42   ui.cur_page = (struct Page *) journal.pages->data;
43   ui.cur_layer = (struct Layer *) ui.cur_page->layers->data;
44   ui.saved = TRUE;
45   ui.filename = NULL;
46   update_file_name(NULL);
47 }
48
49 // check attachment names
50
51 void chk_attach_names(void)
52 {
53   GList *list;
54   struct Background *bg;
55   
56   for (list = journal.pages; list!=NULL; list = list->next) {
57     bg = ((struct Page *)list->data)->bg;
58     if (bg->type == BG_SOLID || bg->file_domain != DOMAIN_ATTACH ||
59         bg->filename->s != NULL) continue;
60     bg->filename->s = g_strdup_printf("bg_%d.png", ++journal.last_attach_no);
61   }
62 }
63
64 // saves the journal to a file: returns true on success, false on error
65
66 gboolean save_journal(const char *filename)
67 {
68   gzFile f;
69   struct Page *pg, *tmppg;
70   struct Layer *layer;
71   struct Item *item;
72   int i, is_clone;
73   char *tmpfn;
74   gchar *pdfbuf;
75   gsize pdflen;
76   gboolean success;
77   FILE *tmpf;
78   GList *pagelist, *layerlist, *itemlist, *list;
79   GtkWidget *dialog;
80   
81   f = gzopen(filename, "w");
82   if (f==NULL) return FALSE;
83   chk_attach_names();
84   
85   gzprintf(f, "<?xml version=\"1.0\" standalone=\"no\"?>\n"
86      "<title>Xournal document - see http://math.mit.edu/~auroux/software/xournal/</title>\n"
87      "<xournal version=\"" VERSION "\"/>\n");
88   for (pagelist = journal.pages; pagelist!=NULL; pagelist = pagelist->next) {
89     pg = (struct Page *)pagelist->data;
90     gzprintf(f, "<page width=\"%.2f\" height=\"%.2f\">\n", pg->width, pg->height);
91     gzprintf(f, "<background type=\"%s\" ", bgtype_names[pg->bg->type]); 
92     if (pg->bg->type == BG_SOLID) {
93       gzputs(f, "color=\"");
94       if (pg->bg->color_no >= 0) gzputs(f, bgcolor_names[pg->bg->color_no]);
95       else gzprintf(f, "#%08x", pg->bg->color_rgba);
96       gzprintf(f, "\" style=\"%s\" ", bgstyle_names[pg->bg->ruling]);
97     }
98     else if (pg->bg->type == BG_PIXMAP) {
99       is_clone = -1;
100       for (list = journal.pages, i = 0; list!=pagelist; list = list->next, i++) {
101         tmppg = (struct Page *)list->data;
102         if (tmppg->bg->type == BG_PIXMAP && 
103             tmppg->bg->pixbuf == pg->bg->pixbuf &&
104             tmppg->bg->filename == pg->bg->filename)
105           { is_clone = i; break; }
106       }
107       if (is_clone >= 0)
108         gzprintf(f, "domain=\"clone\" filename=\"%d\" ", is_clone);
109       else {
110         if (pg->bg->file_domain == DOMAIN_ATTACH) {
111           tmpfn = g_strdup_printf("%s.%s", filename, pg->bg->filename->s);
112           if (!gdk_pixbuf_save(pg->bg->pixbuf, tmpfn, "png", NULL, NULL)) {
113             dialog = gtk_message_dialog_new(GTK_WINDOW(winMain), GTK_DIALOG_MODAL,
114               GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, 
115               "Could not write background '%s'. Continuing anyway.", tmpfn);
116             gtk_dialog_run(GTK_DIALOG(dialog));
117             gtk_widget_destroy(dialog);
118           }
119           g_free(tmpfn);
120         }
121         gzprintf(f, "domain=\"%s\" filename=\"%s\" ", 
122           file_domain_names[pg->bg->file_domain], pg->bg->filename->s);
123       }
124     }
125     else if (pg->bg->type == BG_PDF) {
126       is_clone = 0;
127       for (list = journal.pages; list!=pagelist; list = list->next) {
128         tmppg = (struct Page *)list->data;
129         if (tmppg->bg->type == BG_PDF) { is_clone = 1; break; }
130       }
131       if (!is_clone) {
132         if (pg->bg->file_domain == DOMAIN_ATTACH) {
133           tmpfn = g_strdup_printf("%s.%s", filename, pg->bg->filename->s);
134           success = FALSE;
135           if (bgpdf.status != STATUS_NOT_INIT &&
136               g_file_get_contents(bgpdf.tmpfile_copy, &pdfbuf, &pdflen, NULL))
137           {
138             tmpf = fopen(tmpfn, "w");
139             if (tmpf != NULL && fwrite(pdfbuf, 1, pdflen, tmpf) == pdflen)
140               success = TRUE;
141             g_free(pdfbuf);
142             fclose(tmpf);
143           }
144           if (!success) {
145             dialog = gtk_message_dialog_new(GTK_WINDOW(winMain), GTK_DIALOG_MODAL,
146               GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, 
147               "Could not write background '%s'. Continuing anyway.", tmpfn);
148             gtk_dialog_run(GTK_DIALOG(dialog));
149             gtk_widget_destroy(dialog);
150           }
151           g_free(tmpfn);
152         }
153         gzprintf(f, "domain=\"%s\" filename=\"%s\" ", 
154           file_domain_names[pg->bg->file_domain], pg->bg->filename->s);
155       }
156       gzprintf(f, "pageno=\"%d\" ", pg->bg->file_page_seq);
157     }
158     gzprintf(f, "/>\n");
159     for (layerlist = pg->layers; layerlist!=NULL; layerlist = layerlist->next) {
160       layer = (struct Layer *)layerlist->data;
161       gzprintf(f, "<layer>\n");
162       for (itemlist = layer->items; itemlist!=NULL; itemlist = itemlist->next) {
163         item = (struct Item *)itemlist->data;
164         if (item->type == ITEM_STROKE) {
165           gzprintf(f, "<stroke tool=\"%s\" color=\"", 
166                           tool_names[item->brush.tool_type]);
167           if (item->brush.color_no >= 0)
168             gzputs(f, color_names[item->brush.color_no]);
169           else
170             gzprintf(f, "#%08x", item->brush.color_rgba);
171           gzprintf(f, "\" width=\"%.2f\">\n", item->brush.thickness);
172           for (i=0;i<2*item->path->num_points;i++)
173             gzprintf(f, "%.2f ", item->path->coords[i]);
174           gzprintf(f, "\n</stroke>\n");
175         }
176       }
177       gzprintf(f, "</layer>\n");
178     }
179     gzprintf(f, "</page>\n");
180   }
181   gzclose(f);
182   return TRUE;
183 }
184
185 // closes a journal: returns true on success, false on abort
186
187 gboolean close_journal(void)
188 {
189   if (!ok_to_close()) return FALSE;
190   
191   // free everything...
192   reset_selection();
193   clear_redo_stack();
194   clear_undo_stack();
195
196   shutdown_bgpdf();
197   delete_journal(&journal);
198   
199   return TRUE;
200   /* note: various members of ui and journal are now in invalid states,
201      use new_journal() to reinitialize them */
202 }
203
204 // the XML parser functions for open_journal()
205
206 struct Journal tmpJournal;
207 struct Page *tmpPage;
208 struct Layer *tmpLayer;
209 struct Item *tmpItem;
210 char *tmpFilename;
211 struct Background *tmpBg_pdf;
212
213 GError *xoj_invalid(void)
214 {
215   return g_error_new(G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT, "Invalid file contents");
216 }
217
218 void xoj_parser_start_element(GMarkupParseContext *context,
219    const gchar *element_name, const gchar **attribute_names, 
220    const gchar **attribute_values, gpointer user_data, GError **error)
221 {
222   int has_attr, i;
223   char *ptr;
224   struct Background *tmpbg;
225   char *tmpbg_filename;
226   GtkWidget *dialog;
227   
228   if (!strcmp(element_name, "title") || !strcmp(element_name, "xournal")) {
229     if (tmpPage != NULL) {
230       *error = xoj_invalid();
231       return;
232     }
233     // nothing special to do
234   }
235   else if (!strcmp(element_name, "page")) { // start of a page
236     if (tmpPage != NULL) {
237       *error = xoj_invalid();
238       return;
239     }
240     tmpPage = (struct Page *)g_malloc(sizeof(struct Page));
241     tmpPage->layers = NULL;
242     tmpPage->nlayers = 0;
243     tmpPage->group = NULL;
244     tmpPage->bg = g_new(struct Background, 1);
245     tmpPage->bg->type = -1;
246     tmpPage->bg->canvas_item = NULL;
247     tmpPage->bg->pixbuf = NULL;
248     tmpPage->bg->filename = NULL;
249     tmpJournal.pages = g_list_append(tmpJournal.pages, tmpPage);
250     tmpJournal.npages++;
251     // scan for height and width attributes
252     has_attr = 0;
253     while (*attribute_names!=NULL) {
254       if (!strcmp(*attribute_names, "width")) {
255         if (has_attr & 1) *error = xoj_invalid();
256         tmpPage->width = strtod(*attribute_values, &ptr);
257         if (ptr == *attribute_values) *error = xoj_invalid();
258         has_attr |= 1;
259       }
260       else if (!strcmp(*attribute_names, "height")) {
261         if (has_attr & 2) *error = xoj_invalid();
262         tmpPage->height = strtod(*attribute_values, &ptr);
263         if (ptr == *attribute_values) *error = xoj_invalid();
264         has_attr |= 2;
265       }
266       else *error = xoj_invalid();
267       attribute_names++;
268       attribute_values++;
269     }
270     if (has_attr!=3) *error = xoj_invalid();
271   }
272   else if (!strcmp(element_name, "background")) {
273     if (tmpPage == NULL || tmpLayer !=NULL || tmpPage->bg->type >= 0) {
274       *error = xoj_invalid();
275       return;
276     }
277     has_attr = 0;
278     while (*attribute_names!=NULL) {
279       if (!strcmp(*attribute_names, "type")) {
280         if (has_attr) *error = xoj_invalid();
281         for (i=0; i<3; i++)
282           if (!strcmp(*attribute_values, bgtype_names[i]))
283             tmpPage->bg->type = i;
284         if (tmpPage->bg->type < 0) *error = xoj_invalid();
285         has_attr |= 1;
286         if (tmpPage->bg->type == BG_PDF) {
287           if (tmpBg_pdf == NULL) tmpBg_pdf = tmpPage->bg;
288           else {
289             has_attr |= 24;
290             tmpPage->bg->filename = refstring_ref(tmpBg_pdf->filename);
291             tmpPage->bg->file_domain = tmpBg_pdf->file_domain;
292           }
293         }
294       }
295       else if (!strcmp(*attribute_names, "color")) {
296         if (tmpPage->bg->type != BG_SOLID) *error = xoj_invalid();
297         if (has_attr & 2) *error = xoj_invalid();
298         tmpPage->bg->color_no = COLOR_OTHER;
299         for (i=0; i<COLOR_MAX; i++)
300           if (!strcmp(*attribute_values, bgcolor_names[i])) {
301             tmpPage->bg->color_no = i;
302             tmpPage->bg->color_rgba = predef_bgcolors_rgba[i];
303           }
304         // there's also the case of hex (#rrggbbaa) colors
305         if (tmpPage->bg->color_no == COLOR_OTHER && **attribute_values == '#') {
306           tmpPage->bg->color_rgba = strtol(*attribute_values + 1, &ptr, 16);
307           if (*ptr!=0) *error = xoj_invalid();
308         }
309         has_attr |= 2;
310       }
311       else if (!strcmp(*attribute_names, "style")) {
312         if (tmpPage->bg->type != BG_SOLID) *error = xoj_invalid();
313         if (has_attr & 4) *error = xoj_invalid();
314         tmpPage->bg->ruling = -1;
315         for (i=0; i<4; i++)
316           if (!strcmp(*attribute_values, bgstyle_names[i]))
317             tmpPage->bg->ruling = i;
318         if (tmpPage->bg->ruling < 0) *error = xoj_invalid();
319         has_attr |= 4;
320       }
321       else if (!strcmp(*attribute_names, "domain")) {
322         if (tmpPage->bg->type <= BG_SOLID || (has_attr & 8))
323           { *error = xoj_invalid(); return; }
324         tmpPage->bg->file_domain = -1;
325         for (i=0; i<3; i++)
326           if (!strcmp(*attribute_values, file_domain_names[i]))
327             tmpPage->bg->file_domain = i;
328         if (tmpPage->bg->file_domain < 0)
329           { *error = xoj_invalid(); return; }
330         has_attr |= 8;
331       }
332       else if (!strcmp(*attribute_names, "filename")) {
333         if (tmpPage->bg->type <= BG_SOLID || (has_attr != 9)) 
334           { *error = xoj_invalid(); return; }
335         if (tmpPage->bg->file_domain == DOMAIN_CLONE) {
336           // filename is a page number
337           i = strtol(*attribute_values, &ptr, 10);
338           if (ptr == *attribute_values || i < 0 || i > tmpJournal.npages-2)
339             { *error = xoj_invalid(); return; }
340           tmpbg = ((struct Page *)g_list_nth_data(tmpJournal.pages, i))->bg;
341           if (tmpbg->type != tmpPage->bg->type)
342             { *error = xoj_invalid(); return; }
343           tmpPage->bg->filename = refstring_ref(tmpbg->filename);
344           tmpPage->bg->pixbuf = tmpbg->pixbuf;
345           if (tmpbg->pixbuf!=NULL) gdk_pixbuf_ref(tmpbg->pixbuf);
346           tmpPage->bg->file_domain = tmpbg->file_domain;
347         }
348         else {
349           tmpPage->bg->filename = new_refstring(*attribute_values);
350           if (tmpPage->bg->type == BG_PIXMAP) {
351             if (tmpPage->bg->file_domain == DOMAIN_ATTACH) {
352               tmpbg_filename = g_strdup_printf("%s.%s", tmpFilename, *attribute_values);
353               if (sscanf(*attribute_values, "bg_%d.png", &i) == 1)
354                 if (i > tmpJournal.last_attach_no) 
355                   tmpJournal.last_attach_no = i;
356             }
357             else tmpbg_filename = g_strdup(*attribute_values);
358             tmpPage->bg->pixbuf = gdk_pixbuf_new_from_file(tmpbg_filename, NULL);
359             if (tmpPage->bg->pixbuf == NULL) {
360               dialog = gtk_message_dialog_new(GTK_WINDOW(winMain), GTK_DIALOG_MODAL,
361                 GTK_MESSAGE_WARNING, GTK_BUTTONS_OK, 
362                 "Could not open background '%s'. Setting background to white.",
363                 tmpbg_filename);
364               gtk_dialog_run(GTK_DIALOG(dialog));
365               gtk_widget_destroy(dialog);
366               tmpPage->bg->pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8, 1, 1);
367               gdk_pixbuf_fill(tmpPage->bg->pixbuf, 0xffffffff); // solid white
368             }
369             g_free(tmpbg_filename);
370           }
371         }
372         has_attr |= 16;
373       }
374       else if (!strcmp(*attribute_names, "pageno")) {
375         if (tmpPage->bg->type != BG_PDF || (has_attr & 32))
376           { *error = xoj_invalid(); return; }
377         tmpPage->bg->file_page_seq = strtod(*attribute_values, &ptr);
378         if (ptr == *attribute_values) *error = xoj_invalid();
379         has_attr |= 32;
380       }
381       else *error = xoj_invalid();
382       attribute_names++;
383       attribute_values++;
384     }
385     if (tmpPage->bg->type < 0) *error = xoj_invalid();
386     if (tmpPage->bg->type == BG_SOLID && has_attr != 7) *error = xoj_invalid();
387     if (tmpPage->bg->type == BG_PIXMAP && has_attr != 25) *error = xoj_invalid();
388     if (tmpPage->bg->type == BG_PDF && has_attr != 57) *error = xoj_invalid();
389   }
390   else if (!strcmp(element_name, "layer")) { // start of a layer
391     if (tmpPage == NULL || tmpLayer != NULL) {
392       *error = xoj_invalid();
393       return;
394     }
395     tmpLayer = (struct Layer *)g_malloc(sizeof(struct Layer));
396     tmpLayer->items = NULL;
397     tmpLayer->nitems = 0;
398     tmpLayer->group = NULL;
399     tmpPage->layers = g_list_append(tmpPage->layers, tmpLayer);
400     tmpPage->nlayers++;
401   }
402   else if (!strcmp(element_name, "stroke")) { // start of a stroke
403     if (tmpLayer == NULL || tmpItem != NULL) {
404       *error = xoj_invalid();
405       return;
406     }
407     tmpItem = (struct Item *)g_malloc(sizeof(struct Item));
408     tmpItem->type = ITEM_STROKE;
409     tmpItem->path = NULL;
410     tmpItem->canvas_item = NULL;
411     tmpLayer->items = g_list_append(tmpLayer->items, tmpItem);
412     tmpLayer->nitems++;
413     // scan for tool, color, and width attributes
414     has_attr = 0;
415     while (*attribute_names!=NULL) {
416       if (!strcmp(*attribute_names, "width")) {
417         if (has_attr & 1) *error = xoj_invalid();
418         tmpItem->brush.thickness = strtod(*attribute_values, &ptr);
419         if (ptr == *attribute_values) *error = xoj_invalid();
420         has_attr |= 1;
421       }
422       else if (!strcmp(*attribute_names, "color")) {
423         if (has_attr & 2) *error = xoj_invalid();
424         tmpItem->brush.color_no = COLOR_OTHER;
425         for (i=0; i<COLOR_MAX; i++)
426           if (!strcmp(*attribute_values, color_names[i])) {
427             tmpItem->brush.color_no = i;
428             tmpItem->brush.color_rgba = predef_colors_rgba[i];
429           }
430         // there's also the case of hex (#rrggbbaa) colors
431         if (tmpItem->brush.color_no == COLOR_OTHER && **attribute_values == '#') {
432           tmpItem->brush.color_rgba = strtol(*attribute_values + 1, &ptr, 16);
433           if (*ptr!=0) *error = xoj_invalid();
434         }
435         has_attr |= 2;
436       }
437       else if (!strcmp(*attribute_names, "tool")) {
438         if (has_attr & 4) *error = xoj_invalid();
439         tmpItem->brush.tool_type = -1;
440         for (i=0; i<NUM_STROKE_TOOLS; i++)
441           if (!strcmp(*attribute_values, tool_names[i])) {
442             tmpItem->brush.tool_type = i;
443           }
444         if (tmpItem->brush.tool_type == -1) *error = xoj_invalid();
445         has_attr |= 4;
446       }
447       else *error = xoj_invalid();
448       attribute_names++;
449       attribute_values++;
450     }
451     if (has_attr!=7) *error = xoj_invalid();
452     // finish filling the brush info
453     tmpItem->brush.thickness_no = 0;  // who cares ?
454     tmpItem->brush.tool_options = 0;  // who cares ?
455     if (tmpItem->brush.tool_type == TOOL_HIGHLIGHTER) {
456       if (tmpItem->brush.color_no >= 0)
457         tmpItem->brush.color_rgba &= HILITER_ALPHA_MASK;
458     }
459   }
460 }
461
462 void xoj_parser_end_element(GMarkupParseContext *context,
463    const gchar *element_name, gpointer user_data, GError **error)
464 {
465   if (!strcmp(element_name, "page")) {
466     if (tmpPage == NULL || tmpLayer != NULL) {
467       *error = xoj_invalid();
468       return;
469     }
470     if (tmpPage->nlayers == 0 || tmpPage->bg->type < 0) *error = xoj_invalid();
471     tmpPage = NULL;
472   }
473   if (!strcmp(element_name, "layer")) {
474     if (tmpLayer == NULL || tmpItem != NULL) {
475       *error = xoj_invalid();
476       return;
477     }
478     tmpLayer = NULL;
479   }
480   if (!strcmp(element_name, "stroke")) {
481     if (tmpItem == NULL) {
482       *error = xoj_invalid();
483       return;
484     }
485     update_item_bbox(tmpItem);
486     tmpItem = NULL;
487   }
488 }
489
490 void xoj_parser_text(GMarkupParseContext *context,
491    const gchar *text, gsize text_len, gpointer user_data, GError **error)
492 {
493   const gchar *element_name, *ptr;
494   int n;
495   
496   element_name = g_markup_parse_context_get_element(context);
497   if (element_name == NULL) return;
498   if (!strcmp(element_name, "stroke")) {
499     ptr = text;
500     n = 0;
501     while (text_len > 0) {
502       realloc_cur_path(n/2 + 1);
503       ui.cur_path.coords[n] = strtod(text, (char **)(&ptr));
504       if (ptr == text) break;
505       text_len -= (ptr - text);
506       text = ptr;
507       n++;
508     }
509     if (n<4 || n&1) { *error = xoj_invalid(); return; }
510     tmpItem->path = gnome_canvas_points_new(n/2);
511     g_memmove(tmpItem->path->coords, ui.cur_path.coords, n*sizeof(double));
512   }
513 }
514
515 gboolean user_wants_second_chance(char **filename)
516 {
517   GtkWidget *dialog;
518   GtkFileFilter *filt_all, *filt_pdf;
519   GtkResponseType response;
520
521   dialog = gtk_message_dialog_new(GTK_WINDOW(winMain), GTK_DIALOG_MODAL,
522     GTK_MESSAGE_ERROR, GTK_BUTTONS_YES_NO, 
523     "Could not open background '%s'.\nSelect another file?",
524     *filename);
525   response = gtk_dialog_run(GTK_DIALOG(dialog));
526   gtk_widget_destroy(dialog);
527   if (response != GTK_RESPONSE_YES) return FALSE;
528   dialog = gtk_file_chooser_dialog_new("Open PDF", GTK_WINDOW (winMain),
529      GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
530      GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, NULL);
531
532   filt_all = gtk_file_filter_new();
533   gtk_file_filter_set_name(filt_all, "All files");
534   gtk_file_filter_add_pattern(filt_all, "*");
535   filt_pdf = gtk_file_filter_new();
536   gtk_file_filter_set_name(filt_pdf, "PDF files");
537   gtk_file_filter_add_pattern(filt_pdf, "*.pdf");
538   gtk_file_chooser_add_filter(GTK_FILE_CHOOSER (dialog), filt_pdf);
539   gtk_file_chooser_add_filter(GTK_FILE_CHOOSER (dialog), filt_all);
540
541   if (gtk_dialog_run(GTK_DIALOG(dialog)) != GTK_RESPONSE_ACCEPT) {
542     gtk_widget_destroy(dialog);
543     return FALSE;
544   }
545   g_free(*filename);
546   *filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog));
547   gtk_widget_destroy(dialog);
548   return TRUE;    
549 }
550
551 gboolean open_journal(char *filename)
552 {
553   const GMarkupParser parser = { xoj_parser_start_element, 
554                                  xoj_parser_end_element, 
555                                  xoj_parser_text, NULL, NULL};
556   GMarkupParseContext *context;
557   GError *error;
558   GtkWidget *dialog;
559   gboolean valid;
560   gzFile f;
561   char buffer[1000];
562   int len;
563   gchar *tmpfn;
564   gboolean maybe_pdf;
565   
566   f = gzopen(filename, "r");
567   if (f==NULL) return FALSE;
568   
569   context = g_markup_parse_context_new(&parser, 0, NULL, NULL);
570   valid = TRUE;
571   tmpJournal.npages = 0;
572   tmpJournal.pages = NULL;
573   tmpJournal.last_attach_no = 0;
574   tmpPage = NULL;
575   tmpLayer = NULL;
576   tmpItem = NULL;
577   tmpFilename = filename;
578   error = NULL;
579   tmpBg_pdf = NULL;
580   maybe_pdf = TRUE;
581
582   while (valid && !gzeof(f)) {
583     len = gzread(f, buffer, 1000);
584     if (len<0) valid = FALSE;
585     if (maybe_pdf && len>=4 && !strncmp(buffer, "%PDF", 4))
586       { valid = FALSE; break; } // most likely pdf
587     else maybe_pdf = FALSE;
588     if (len<=0) break;
589     valid = g_markup_parse_context_parse(context, buffer, len, &error);
590   }
591   gzclose(f);
592   if (valid) valid = g_markup_parse_context_end_parse(context, &error);
593   if (tmpJournal.npages == 0) valid = FALSE;
594   g_markup_parse_context_free(context);
595   
596   if (!valid) {
597     delete_journal(&tmpJournal);
598     if (!maybe_pdf) return FALSE;
599     // essentially same as on_fileNewBackground from here on
600     ui.saved = TRUE;
601     close_journal();
602     while (bgpdf.status != STATUS_NOT_INIT) gtk_main_iteration();
603     new_journal();
604     ui.zoom = DEFAULT_ZOOM;
605     gnome_canvas_set_pixels_per_unit(canvas, ui.zoom);
606     update_page_stuff();
607     return init_bgpdf(filename, TRUE, DOMAIN_ABSOLUTE);
608   }
609   
610   ui.saved = TRUE; // force close_journal() to do its job
611   close_journal();
612   g_memmove(&journal, &tmpJournal, sizeof(struct Journal));
613   
614   // if we need to initialize a fresh pdf loader
615   if (tmpBg_pdf!=NULL) { 
616     while (bgpdf.status != STATUS_NOT_INIT) gtk_main_iteration();
617     if (tmpBg_pdf->file_domain == DOMAIN_ATTACH)
618       tmpfn = g_strdup_printf("%s.%s", filename, tmpBg_pdf->filename->s);
619     else
620       tmpfn = g_strdup(tmpBg_pdf->filename->s);
621     valid = init_bgpdf(tmpfn, FALSE, tmpBg_pdf->file_domain);
622     // in case the file name became invalid
623     if (!valid && tmpBg_pdf->file_domain != DOMAIN_ATTACH)
624       if (user_wants_second_chance(&tmpfn)) {
625         valid = init_bgpdf(tmpfn, FALSE, tmpBg_pdf->file_domain);
626         if (valid) { // change the file name...
627           g_free(tmpBg_pdf->filename->s);
628           tmpBg_pdf->filename->s = g_strdup(tmpfn);
629         }
630       }
631     if (valid) {
632       refstring_unref(bgpdf.filename);
633       bgpdf.filename = refstring_ref(tmpBg_pdf->filename);
634     } else {
635       dialog = gtk_message_dialog_new(GTK_WINDOW(winMain), GTK_DIALOG_MODAL,
636         GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "Could not open background '%s'.",
637         tmpfn);
638       gtk_dialog_run(GTK_DIALOG(dialog));
639       gtk_widget_destroy(dialog);
640     }
641     g_free(tmpfn);
642   }
643   
644   ui.pageno = 0;
645   ui.cur_page = (struct Page *)journal.pages->data;
646   ui.layerno = ui.cur_page->nlayers-1;
647   ui.cur_layer = (struct Layer *)(g_list_last(ui.cur_page->layers)->data);
648   ui.saved = TRUE;
649   ui.zoom = DEFAULT_ZOOM;
650   update_file_name(g_strdup(filename));
651   gnome_canvas_set_pixels_per_unit(canvas, ui.zoom);
652   make_canvas_items();
653   update_page_stuff();
654   gtk_adjustment_set_value(gtk_layout_get_vadjustment(GTK_LAYOUT(canvas)), 0);
655   return TRUE;
656 }
657
658 /************ file backgrounds *************/
659
660 struct Background *attempt_load_pix_bg(char *filename, gboolean attach)
661 {
662   struct Background *bg;
663   GdkPixbuf *pix;
664   
665   pix = gdk_pixbuf_new_from_file(filename, NULL);
666   if (pix == NULL) return NULL;
667   
668   bg = g_new(struct Background, 1);
669   bg->type = BG_PIXMAP;
670   bg->canvas_item = NULL;
671   bg->pixbuf = pix;
672   bg->pixbuf_scale = DEFAULT_ZOOM;
673   if (attach) {
674     bg->filename = new_refstring(NULL);
675     bg->file_domain = DOMAIN_ATTACH;
676   } else {
677     bg->filename = new_refstring(filename);
678     bg->file_domain = DOMAIN_ABSOLUTE;
679   }
680   return bg;
681 }
682
683 #define BUFSIZE 65536 // a reasonable buffer size for reads from gs pipe
684
685 GList *attempt_load_gv_bg(char *filename)
686 {
687   struct Background *bg;
688   GList *bg_list;
689   GdkPixbuf *pix;
690   GdkPixbufLoader *loader;
691   FILE *gs_pipe, *f;
692   unsigned char *buf;
693   char *pipename;
694   int buflen, remnlen, file_pageno;
695   
696   buf = g_malloc(BUFSIZE); // a reasonable buffer size
697   f = fopen(filename, "r");
698   if (fread(buf, 1, 4, f) !=4 ||
699         (strncmp((char *)buf, "%!PS", 4) && strncmp((char *)buf, "%PDF", 4))) {
700     fclose(f);
701     g_free(buf);
702     return NULL;
703   }
704   
705   fclose(f);
706   pipename = g_strdup_printf(GS_CMDLINE, (double)GS_BITMAP_DPI, filename);
707   gs_pipe = popen(pipename, "r");
708   g_free(pipename);
709   
710   bg_list = NULL;
711   remnlen = 0;
712   file_pageno = 0;
713   loader = NULL;
714   if (gs_pipe!=NULL)
715   while (!feof(gs_pipe)) {
716     if (!remnlen) { // new page: get a BMP header ?
717       buflen = fread(buf, 1, 54, gs_pipe);
718       if (buflen < 6) buflen += fread(buf, 1, 54-buflen, gs_pipe);
719       if (buflen < 6 || buf[0]!='B' || buf[1]!='M') break; // fatal: abort
720       remnlen = (int)(buf[5]<<24) + (buf[4]<<16) + (buf[3]<<8) + (buf[2]);
721       loader = gdk_pixbuf_loader_new();
722     }
723     else buflen = fread(buf, 1, (remnlen < BUFSIZE)?remnlen:BUFSIZE, gs_pipe);
724     remnlen -= buflen;
725     if (buflen == 0) break;
726     if (!gdk_pixbuf_loader_write(loader, buf, buflen, NULL)) break;
727     if (remnlen == 0) { // make a new bg
728       pix = gdk_pixbuf_loader_get_pixbuf(loader);
729       if (pix == NULL) break;
730       gdk_pixbuf_ref(pix);
731       gdk_pixbuf_loader_close(loader, NULL);
732       g_object_unref(loader);
733       loader = NULL;
734       bg = g_new(struct Background, 1);
735       bg->canvas_item = NULL;
736       bg->pixbuf = pix;
737       bg->pixbuf_scale = (GS_BITMAP_DPI/72.0);
738       bg->type = BG_PIXMAP;
739       bg->filename = new_refstring(NULL);
740       bg->file_domain = DOMAIN_ATTACH;
741       file_pageno++;
742       bg_list = g_list_append(bg_list, bg);
743     }
744   }
745   if (loader != NULL) gdk_pixbuf_loader_close(loader, NULL);
746   pclose(gs_pipe);
747   g_free(buf);
748   return bg_list;
749 }
750
751 struct Background *attempt_screenshot_bg(void)
752 {
753   struct Background *bg;
754   GdkPixbuf *pix;
755   XEvent x_event;
756   GError *error = NULL;
757   GdkWindow *window;
758   int x,y,w,h, status;
759   unsigned int tmp;
760   Window x_root, x_win;
761
762   x_root = gdk_x11_get_default_root_xwindow();
763   
764   if (!XGrabButton(GDK_DISPLAY(), AnyButton, AnyModifier, x_root, 
765       False, ButtonReleaseMask, GrabModeAsync, GrabModeSync, None, None))
766     return NULL;
767
768   XWindowEvent (GDK_DISPLAY(), x_root, ButtonReleaseMask, &x_event);
769   XUngrabButton(GDK_DISPLAY(), AnyButton, AnyModifier, x_root);
770
771   x_win = x_event.xbutton.subwindow;
772   if (x_win == None) x_win = x_root;
773
774   window = gdk_window_foreign_new_for_display(gdk_display_get_default(), x_win);
775     
776   gdk_window_get_geometry(window, &x, &y, &w, &h, NULL);
777   
778   pix = gdk_pixbuf_get_from_drawable(NULL, window,
779     gdk_colormap_get_system(), 0, 0, 0, 0, w, h);
780     
781   if (pix == NULL) return NULL;
782   
783   bg = g_new(struct Background, 1);
784   bg->type = BG_PIXMAP;
785   bg->canvas_item = NULL;
786   bg->pixbuf = pix;
787   bg->pixbuf_scale = DEFAULT_ZOOM;
788   bg->filename = new_refstring(NULL);
789   bg->file_domain = DOMAIN_ATTACH;
790   return bg;
791 }
792
793 /************** pdf annotation ***************/
794
795 /* free tmp directory */
796
797 void end_bgpdf_shutdown(void)
798 {
799   if (bgpdf.tmpdir!=NULL) {
800     if (bgpdf.tmpfile_copy!=NULL) {
801       g_unlink(bgpdf.tmpfile_copy);
802       g_free(bgpdf.tmpfile_copy);
803       bgpdf.tmpfile_copy = NULL;
804     }
805     g_rmdir(bgpdf.tmpdir);  
806     g_free(bgpdf.tmpdir);
807     bgpdf.tmpdir = NULL;
808   }
809   bgpdf.status = STATUS_NOT_INIT;
810 }
811
812 /* cancel a request */
813
814 void cancel_bgpdf_request(struct BgPdfRequest *req)
815 {
816   GList *list_link;
817   
818   list_link = g_list_find(bgpdf.requests, req);
819   if (list_link == NULL) return;
820   if (list_link->prev == NULL && bgpdf.pid > 0) {
821     // this is being processed: kill the child but don't remove the request yet
822     if (bgpdf.status == STATUS_RUNNING) bgpdf.status = STATUS_ABORTED;
823     kill(bgpdf.pid, SIGHUP);
824 //    printf("Cancelling a request - killing %d\n", bgpdf.pid);
825   }
826   else {
827     // remove the request
828     bgpdf.requests = g_list_delete_link(bgpdf.requests, list_link);
829     g_free(req);
830 //    printf("Cancelling a request - no kill needed\n");
831   }
832 }
833
834 /* sigchld callback */
835
836 void bgpdf_child_handler(GPid pid, gint status, gpointer data)
837 {
838   struct BgPdfRequest *req;
839   struct BgPdfPage *bgpg;
840   gchar *ppm_name;
841   GdkPixbuf *pixbuf;
842   
843   if (bgpdf.requests == NULL) return;
844   req = (struct BgPdfRequest *)bgpdf.requests->data;
845   
846   ppm_name = g_strdup_printf("%s/p-%06d.ppm", bgpdf.tmpdir, req->pageno);
847 //  printf("Child %d finished, should look for %s... \n", pid, ppm_name);
848   
849   if (bgpdf.status == STATUS_ABORTED || bgpdf.status == STATUS_SHUTDOWN)
850      pixbuf = NULL;
851   else
852      pixbuf = gdk_pixbuf_new_from_file(ppm_name, NULL);
853
854   unlink(ppm_name);
855   g_free(ppm_name);
856
857   if (pixbuf != NULL) { // success
858 //    printf("success\n");
859     while (req->pageno > bgpdf.npages) {
860       bgpg = g_new(struct BgPdfPage, 1);
861       bgpg->pixbuf = NULL;
862       bgpdf.pages = g_list_append(bgpdf.pages, bgpg);
863       bgpdf.npages++;
864     }
865     bgpg = g_list_nth_data(bgpdf.pages, req->pageno-1);
866     if (bgpg->pixbuf!=NULL) gdk_pixbuf_unref(bgpg->pixbuf);
867     bgpg->pixbuf = pixbuf;
868     bgpg->dpi = req->dpi;
869     if (req->initial_request && bgpdf.create_pages) {
870       bgpdf_create_page_with_bg(req->pageno, bgpg);
871       // create page n, resize it, set its bg - all without any undo effect
872     } else {
873       if (!req->is_printing) bgpdf_update_bg(req->pageno, bgpg);
874       // look for all pages with this bg, and update their bg pixmaps
875     }
876   }
877   else {
878 //    printf("failed or aborted\n");
879     bgpdf.create_pages = FALSE;
880     req->initial_request = FALSE;
881   }
882
883   bgpdf.pid = 0;
884   g_spawn_close_pid(pid);
885   
886   if (req->initial_request)
887     req->pageno++; // try for next page
888   else
889     bgpdf.requests = g_list_delete_link(bgpdf.requests, bgpdf.requests);
890   
891   if (bgpdf.status == STATUS_SHUTDOWN) {
892     end_bgpdf_shutdown();
893     return;
894   }
895   
896   bgpdf.status = STATUS_IDLE;
897   if (bgpdf.requests != NULL) bgpdf_spawn_child();
898 }
899
900 /* spawn a child to process the head request */
901
902 void bgpdf_spawn_child(void)
903 {
904   struct BgPdfRequest *req;
905   GPid pid;
906   gchar pageno_str[10], dpi_str[10];
907   gchar *pdf_filename = bgpdf.tmpfile_copy;
908   gchar *ppm_root = g_strdup_printf("%s/p", bgpdf.tmpdir);
909   gchar *argv[]= PDFTOPPM_ARGV;
910   GtkWidget *dialog;
911
912   if (bgpdf.requests == NULL) return;
913   req = (struct BgPdfRequest *)bgpdf.requests->data;
914   if (req->pageno > bgpdf.npages+1 || 
915       (!req->initial_request && req->pageno <= bgpdf.npages && 
916        req->dpi == ((struct BgPdfPage *)g_list_nth_data(bgpdf.pages, req->pageno-1))->dpi))
917   { // ignore this request - it's redundant, or in outer space
918     bgpdf.pid = 0;
919     bgpdf.status = STATUS_IDLE;
920     bgpdf.requests = g_list_delete_link(bgpdf.requests, bgpdf.requests);
921     g_free(ppm_root);
922     if (bgpdf.requests != NULL) bgpdf_spawn_child();
923     return;
924   }
925   g_snprintf(pageno_str, 10, "%d", req->pageno);
926   g_snprintf(dpi_str, 10, "%d", req->dpi);
927 /*  printf("Processing request for page %d at %d dpi -- in %s\n", 
928     req->pageno, req->dpi, ppm_root); */
929   if (!g_spawn_async(NULL, argv, NULL,
930                      G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_SEARCH_PATH, 
931                      NULL, NULL, &pid, NULL))
932   {
933     // couldn't spawn... abort this request, try next one maybe ?
934 //    printf("Couldn't spawn\n");
935     bgpdf.pid = 0;
936     bgpdf.status = STATUS_IDLE;
937     bgpdf.requests = g_list_delete_link(bgpdf.requests, bgpdf.requests);
938     g_free(ppm_root);
939     if (!bgpdf.has_failed) {
940       dialog = gtk_message_dialog_new(GTK_WINDOW(winMain), GTK_DIALOG_MODAL,
941         GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "Unable to start PDF loader %s.", argv[0]);
942       gtk_dialog_run(GTK_DIALOG(dialog));
943       gtk_widget_destroy(dialog);
944     }
945     bgpdf.has_failed = TRUE;
946     if (bgpdf.requests != NULL) bgpdf_spawn_child();
947     return;
948   }  
949
950 //  printf("Spawned process %d\n", pid);
951   bgpdf.pid = pid;
952   bgpdf.status = STATUS_RUNNING;
953   g_child_watch_add(pid, bgpdf_child_handler, NULL);
954   g_free(ppm_root);
955 }
956
957 /* make a request */
958
959 void add_bgpdf_request(int pageno, double zoom, gboolean printing)
960 {
961   struct BgPdfRequest *req, *cmp_req;
962   GList *list;
963   
964   if (bgpdf.status == STATUS_NOT_INIT || bgpdf.status == STATUS_SHUTDOWN)
965     return; // don't accept requests in those modes...
966   req = g_new(struct BgPdfRequest, 1);
967   req->is_printing = printing;
968   if (printing) req->dpi = PDFTOPPM_PRINTING_DPI;
969   else req->dpi = (int)floor(72*zoom+0.5);
970 //  printf("Enqueuing request for page %d at %d dpi\n", pageno, req->dpi);
971   if (pageno >= 1) {
972     // cancel any request this may supersede
973     for (list = bgpdf.requests; list != NULL; ) {
974       cmp_req = (struct BgPdfRequest *)list->data;
975       list = list->next;
976       if (!cmp_req->initial_request && cmp_req->pageno == pageno &&
977              cmp_req->is_printing == printing)
978         cancel_bgpdf_request(cmp_req);
979     }
980     req->pageno = pageno;
981     req->initial_request = FALSE;
982   } else {
983     req->pageno = 1;
984     req->initial_request = TRUE;
985   }
986   bgpdf.requests = g_list_append(bgpdf.requests, req);
987   if (!bgpdf.pid) bgpdf_spawn_child();
988 }
989
990 /* shutdown the PDF reader */
991
992 void shutdown_bgpdf(void)
993 {
994   GList *list;
995   struct BgPdfPage *pdfpg;
996   struct BgPdfRequest *req;
997   
998   if (bgpdf.status == STATUS_NOT_INIT || bgpdf.status == STATUS_SHUTDOWN) return;
999   refstring_unref(bgpdf.filename);
1000   for (list = bgpdf.pages; list != NULL; list = list->next) {
1001     pdfpg = (struct BgPdfPage *)list->data;
1002     if (pdfpg->pixbuf!=NULL) gdk_pixbuf_unref(pdfpg->pixbuf);
1003   }
1004   g_list_free(bgpdf.pages);
1005   bgpdf.status = STATUS_SHUTDOWN;
1006   for (list = g_list_last(bgpdf.requests); list != NULL; ) {
1007     req = (struct BgPdfRequest *)list->data;
1008     list = list->prev;
1009     cancel_bgpdf_request(req);
1010   }
1011   if (!bgpdf.pid) end_bgpdf_shutdown();
1012   /* The above will ultimately remove all requests and kill the child if needed.
1013      The child will set status to STATUS_NOT_INIT, clear the requests list,
1014      empty tmpdir, ... except if there's no child! */
1015   /* note: it could look like there's a race condition here - if a child
1016      terminates and a new request is enqueued while we are destroying the
1017      queue - but actually the child handler callback is NOT a signal
1018      callback, so execution of this function is atomic */
1019 }
1020
1021 gboolean init_bgpdf(char *pdfname, gboolean create_pages, int file_domain)
1022 {
1023   FILE *f;
1024   gchar *filebuf;
1025   gsize filelen;
1026   
1027   if (bgpdf.status != STATUS_NOT_INIT) return FALSE;
1028   bgpdf.tmpfile_copy = NULL;
1029   bgpdf.tmpdir = mkdtemp(g_strdup(TMPDIR_TEMPLATE));
1030   if (!bgpdf.tmpdir) return FALSE;
1031   // make a local copy and check if it's a PDF
1032   if (!g_file_get_contents(pdfname, &filebuf, &filelen, NULL))
1033     { end_bgpdf_shutdown(); return FALSE; }
1034   if (filelen < 4 || strncmp(filebuf, "%PDF", 4))
1035     { g_free(filebuf); end_bgpdf_shutdown(); return FALSE; }
1036   bgpdf.tmpfile_copy = g_strdup_printf("%s/bg.pdf", bgpdf.tmpdir);
1037   f = fopen(bgpdf.tmpfile_copy, "w");
1038   if (f == NULL || fwrite(filebuf, 1, filelen, f) != filelen) 
1039     { g_free(filebuf); end_bgpdf_shutdown(); return FALSE; }
1040   fclose(f);
1041   g_free(filebuf);
1042   bgpdf.status = STATUS_IDLE;
1043   bgpdf.pid = 0;
1044   bgpdf.filename = new_refstring((file_domain == DOMAIN_ATTACH) ? "bg.pdf" : pdfname);
1045   bgpdf.file_domain = file_domain;
1046   bgpdf.npages = 0;
1047   bgpdf.pages = NULL;
1048   bgpdf.requests = NULL;
1049   bgpdf.create_pages = create_pages;
1050   bgpdf.has_failed = FALSE;
1051   add_bgpdf_request(-1, DEFAULT_ZOOM, FALSE); // request all pages
1052   return TRUE;
1053 }
1054
1055 // create page n, resize it, set its bg
1056 void bgpdf_create_page_with_bg(int pageno, struct BgPdfPage *bgpg)
1057 {
1058   struct Page *pg;
1059   struct Background *bg;
1060
1061   if (journal.npages < pageno) {
1062     bg = g_new(struct Background, 1);
1063     bg->canvas_item = NULL;
1064   } else {
1065     pg = (struct Page *)g_list_nth_data(journal.pages, pageno-1);
1066     bg = pg->bg;
1067     if (bg->type != BG_SOLID) return;
1068       // don't mess with a page the user has modified significantly...
1069   }
1070   
1071   bg->type = BG_PDF;
1072   bg->pixbuf = gdk_pixbuf_ref(bgpg->pixbuf);
1073   bg->filename = refstring_ref(bgpdf.filename);
1074   bg->file_domain = bgpdf.file_domain;
1075   bg->file_page_seq = pageno;
1076   bg->pixbuf_scale = DEFAULT_ZOOM;
1077   bg->pixbuf_dpi = bgpg->dpi;
1078
1079   if (journal.npages < pageno) {
1080     pg = new_page_with_bg(bg, 
1081             gdk_pixbuf_get_width(bg->pixbuf)*72.0/bg->pixbuf_dpi,
1082             gdk_pixbuf_get_height(bg->pixbuf)*72.0/bg->pixbuf_dpi);
1083     journal.pages = g_list_append(journal.pages, pg);
1084     journal.npages++;
1085   } else {
1086     pg->width = gdk_pixbuf_get_width(bgpg->pixbuf)*72.0/bg->pixbuf_dpi;
1087     pg->height = gdk_pixbuf_get_height(bgpg->pixbuf)*72.0/bg->pixbuf_dpi;
1088     make_page_clipbox(pg);
1089     update_canvas_bg(pg);
1090   }
1091   update_page_stuff();
1092 }
1093
1094 // look for all journal pages with given pdf bg, and update their bg pixmaps
1095 void bgpdf_update_bg(int pageno, struct BgPdfPage *bgpg)
1096 {
1097   GList *list;
1098   struct Page *pg;
1099   
1100   for (list = journal.pages; list!= NULL; list = list->next) {
1101     pg = (struct Page *)list->data;
1102     if (pg->bg->type == BG_PDF && pg->bg->file_page_seq == pageno) {
1103       if (pg->bg->pixbuf!=NULL) gdk_pixbuf_unref(pg->bg->pixbuf);
1104       pg->bg->pixbuf = gdk_pixbuf_ref(bgpg->pixbuf);
1105       pg->bg->pixbuf_dpi = bgpg->dpi;
1106       update_canvas_bg(pg);
1107     }
1108   }
1109 }
1110
1111 // initialize the recent files list
1112 void init_mru(void)
1113 {
1114   int i;
1115   gsize lfptr;
1116   char s[5];
1117   GIOChannel *f;
1118   gchar *str;
1119   GIOStatus status;
1120   
1121   g_strlcpy(s, "mru0", 5);
1122   for (s[3]='0', i=0; i<MRU_SIZE; s[3]++, i++) {
1123     ui.mrumenu[i] = GET_COMPONENT(s);
1124     ui.mru[i] = NULL;
1125   }
1126   f = g_io_channel_new_file(ui.mrufile, "r", NULL);
1127   if (f) status = G_IO_STATUS_NORMAL;
1128   else status = G_IO_STATUS_ERROR;
1129   i = 0;
1130   while (status == G_IO_STATUS_NORMAL && i<MRU_SIZE) {
1131     lfptr = 0;
1132     status = g_io_channel_read_line(f, &str, NULL, &lfptr, NULL);
1133     if (status == G_IO_STATUS_NORMAL && lfptr>0) {
1134       str[lfptr] = 0;
1135       ui.mru[i] = str;
1136       i++;
1137     }
1138   }
1139   if (f) {
1140     g_io_channel_shutdown(f, FALSE, NULL);
1141     g_io_channel_unref(f);
1142   }
1143   update_mru_menu();
1144 }
1145
1146 void update_mru_menu(void)
1147 {
1148   int i;
1149   gboolean anyone = FALSE;
1150   
1151   for (i=0; i<MRU_SIZE; i++) {
1152     if (ui.mru[i]!=NULL) {
1153       gtk_label_set_text(GTK_LABEL(gtk_bin_get_child(GTK_BIN(ui.mrumenu[i]))),
1154           g_basename(ui.mru[i]));
1155       gtk_widget_show(ui.mrumenu[i]);
1156       anyone = TRUE;
1157     }
1158     else gtk_widget_hide(ui.mrumenu[i]);
1159   }
1160   gtk_widget_set_sensitive(GET_COMPONENT("fileRecentFiles"), anyone);
1161 }
1162
1163 void new_mru_entry(char *name)
1164 {
1165   int i, j;
1166   
1167   for (i=0;i<MRU_SIZE;i++) 
1168     if (ui.mru[i]!=NULL && !strcmp(ui.mru[i], name)) {
1169       g_free(ui.mru[i]);
1170       for (j=i+1; j<MRU_SIZE; j++) ui.mru[j-1] = ui.mru[j];
1171       ui.mru[MRU_SIZE-1]=NULL;
1172     }
1173   if (ui.mru[MRU_SIZE-1]!=NULL) g_free(ui.mru[MRU_SIZE-1]);
1174   for (j=MRU_SIZE-1; j>=1; j--) ui.mru[j] = ui.mru[j-1];
1175   ui.mru[0] = g_strdup(name);
1176   update_mru_menu();
1177 }
1178
1179 void delete_mru_entry(int which)
1180 {
1181   int i;
1182   
1183   if (ui.mru[which]!=NULL) g_free(ui.mru[which]);
1184   for (i=which+1;i<MRU_SIZE;i++) 
1185     ui.mru[i-1] = ui.mru[i];
1186   ui.mru[MRU_SIZE-1] = NULL;
1187   update_mru_menu();
1188 }
1189
1190 void save_mru_list(void)
1191 {
1192   FILE *f;
1193   int i;
1194   
1195   f = fopen(ui.mrufile, "w");
1196   if (f==NULL) return;
1197   for (i=0; i<MRU_SIZE; i++)
1198     if (ui.mru[i]!=NULL) fprintf(f, "%s\n", ui.mru[i]);
1199   fclose(f);
1200 }