11 #include <libgnomecanvas/libgnomecanvas.h>
19 #include "xo-interface.h"
20 #include "xo-support.h"
21 #include "xo-callbacks.h"
25 const char *tool_names[NUM_STROKE_TOOLS] = {"pen", "eraser", "highlighter"};
26 const char *color_names[COLOR_MAX] = {"black", "blue", "red", "green",
27 "gray", "lightblue", "lightgreen", "magenta", "orange", "yellow", "white"};
28 const char *bgtype_names[3] = {"solid", "pixmap", "pdf"};
29 const char *bgcolor_names[COLOR_MAX] = {"", "blue", "pink", "green",
30 "", "", "", "", "orange", "yellow", "white"};
31 const char *bgstyle_names[4] = {"plain", "lined", "ruled", "graph"};
32 const char *file_domain_names[3] = {"absolute", "attach", "clone"};
34 // creates a new empty journal
36 void new_journal(void)
39 journal.pages = g_list_append(NULL, new_page(&ui.default_page));
40 journal.last_attach_no = 0;
43 ui.cur_page = (struct Page *) journal.pages->data;
44 ui.cur_layer = (struct Layer *) ui.cur_page->layers->data;
47 update_file_name(NULL);
50 // check attachment names
52 void chk_attach_names(void)
55 struct Background *bg;
57 for (list = journal.pages; list!=NULL; list = list->next) {
58 bg = ((struct Page *)list->data)->bg;
59 if (bg->type == BG_SOLID || bg->file_domain != DOMAIN_ATTACH ||
60 bg->filename->s != NULL) continue;
61 bg->filename->s = g_strdup_printf("bg_%d.png", ++journal.last_attach_no);
65 // saves the journal to a file: returns true on success, false on error
67 gboolean save_journal(const char *filename)
70 struct Page *pg, *tmppg;
79 GList *pagelist, *layerlist, *itemlist, *list;
82 f = gzopen(filename, "w");
83 if (f==NULL) return FALSE;
86 setlocale(LC_NUMERIC, "C");
88 gzprintf(f, "<?xml version=\"1.0\" standalone=\"no\"?>\n"
89 "<title>Xournal document - see http://math.mit.edu/~auroux/software/xournal/</title>\n"
90 "<xournal version=\"" VERSION "\"/>\n");
91 for (pagelist = journal.pages; pagelist!=NULL; pagelist = pagelist->next) {
92 pg = (struct Page *)pagelist->data;
93 gzprintf(f, "<page width=\"%.2f\" height=\"%.2f\">\n", pg->width, pg->height);
94 gzprintf(f, "<background type=\"%s\" ", bgtype_names[pg->bg->type]);
95 if (pg->bg->type == BG_SOLID) {
96 gzputs(f, "color=\"");
97 if (pg->bg->color_no >= 0) gzputs(f, bgcolor_names[pg->bg->color_no]);
98 else gzprintf(f, "#%08x", pg->bg->color_rgba);
99 gzprintf(f, "\" style=\"%s\" ", bgstyle_names[pg->bg->ruling]);
101 else if (pg->bg->type == BG_PIXMAP) {
103 for (list = journal.pages, i = 0; list!=pagelist; list = list->next, i++) {
104 tmppg = (struct Page *)list->data;
105 if (tmppg->bg->type == BG_PIXMAP &&
106 tmppg->bg->pixbuf == pg->bg->pixbuf &&
107 tmppg->bg->filename == pg->bg->filename)
108 { is_clone = i; break; }
111 gzprintf(f, "domain=\"clone\" filename=\"%d\" ", is_clone);
113 if (pg->bg->file_domain == DOMAIN_ATTACH) {
114 tmpfn = g_strdup_printf("%s.%s", filename, pg->bg->filename->s);
115 if (!gdk_pixbuf_save(pg->bg->pixbuf, tmpfn, "png", NULL, NULL)) {
116 dialog = gtk_message_dialog_new(GTK_WINDOW(winMain), GTK_DIALOG_MODAL,
117 GTK_MESSAGE_ERROR, GTK_BUTTONS_OK,
118 "Could not write background '%s'. Continuing anyway.", tmpfn);
119 gtk_dialog_run(GTK_DIALOG(dialog));
120 gtk_widget_destroy(dialog);
124 gzprintf(f, "domain=\"%s\" filename=\"%s\" ",
125 file_domain_names[pg->bg->file_domain], pg->bg->filename->s);
128 else if (pg->bg->type == BG_PDF) {
130 for (list = journal.pages; list!=pagelist; list = list->next) {
131 tmppg = (struct Page *)list->data;
132 if (tmppg->bg->type == BG_PDF) { is_clone = 1; break; }
135 if (pg->bg->file_domain == DOMAIN_ATTACH) {
136 tmpfn = g_strdup_printf("%s.%s", filename, pg->bg->filename->s);
138 if (bgpdf.status != STATUS_NOT_INIT &&
139 g_file_get_contents(bgpdf.tmpfile_copy, &pdfbuf, &pdflen, NULL))
141 tmpf = fopen(tmpfn, "w");
142 if (tmpf != NULL && fwrite(pdfbuf, 1, pdflen, tmpf) == pdflen)
148 dialog = gtk_message_dialog_new(GTK_WINDOW(winMain), GTK_DIALOG_MODAL,
149 GTK_MESSAGE_ERROR, GTK_BUTTONS_OK,
150 "Could not write background '%s'. Continuing anyway.", tmpfn);
151 gtk_dialog_run(GTK_DIALOG(dialog));
152 gtk_widget_destroy(dialog);
156 gzprintf(f, "domain=\"%s\" filename=\"%s\" ",
157 file_domain_names[pg->bg->file_domain], pg->bg->filename->s);
159 gzprintf(f, "pageno=\"%d\" ", pg->bg->file_page_seq);
162 for (layerlist = pg->layers; layerlist!=NULL; layerlist = layerlist->next) {
163 layer = (struct Layer *)layerlist->data;
164 gzprintf(f, "<layer>\n");
165 for (itemlist = layer->items; itemlist!=NULL; itemlist = itemlist->next) {
166 item = (struct Item *)itemlist->data;
167 if (item->type == ITEM_STROKE) {
168 gzprintf(f, "<stroke tool=\"%s\" color=\"",
169 tool_names[item->brush.tool_type]);
170 if (item->brush.color_no >= 0)
171 gzputs(f, color_names[item->brush.color_no]);
173 gzprintf(f, "#%08x", item->brush.color_rgba);
174 gzprintf(f, "\" width=\"%.2f\">\n", item->brush.thickness);
175 for (i=0;i<2*item->path->num_points;i++)
176 gzprintf(f, "%.2f ", item->path->coords[i]);
177 gzprintf(f, "\n</stroke>\n");
180 gzprintf(f, "</layer>\n");
182 gzprintf(f, "</page>\n");
185 setlocale(LC_NUMERIC, "");
190 // closes a journal: returns true on success, false on abort
192 gboolean close_journal(void)
194 if (!ok_to_close()) return FALSE;
196 // free everything...
202 delete_journal(&journal);
205 /* note: various members of ui and journal are now in invalid states,
206 use new_journal() to reinitialize them */
209 // sanitize a string containing floats, in case it may have , instead of .
211 void cleanup_numeric(char *s)
213 while (*s!=0) { if (*s==',') *s='.'; s++; }
216 // the XML parser functions for open_journal()
218 struct Journal tmpJournal;
219 struct Page *tmpPage;
220 struct Layer *tmpLayer;
221 struct Item *tmpItem;
223 struct Background *tmpBg_pdf;
225 GError *xoj_invalid(void)
227 return g_error_new(G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT, "Invalid file contents");
230 void xoj_parser_start_element(GMarkupParseContext *context,
231 const gchar *element_name, const gchar **attribute_names,
232 const gchar **attribute_values, gpointer user_data, GError **error)
236 struct Background *tmpbg;
237 char *tmpbg_filename;
240 if (!strcmp(element_name, "title") || !strcmp(element_name, "xournal")) {
241 if (tmpPage != NULL) {
242 *error = xoj_invalid();
245 // nothing special to do
247 else if (!strcmp(element_name, "page")) { // start of a page
248 if (tmpPage != NULL) {
249 *error = xoj_invalid();
252 tmpPage = (struct Page *)g_malloc(sizeof(struct Page));
253 tmpPage->layers = NULL;
254 tmpPage->nlayers = 0;
255 tmpPage->group = NULL;
256 tmpPage->bg = g_new(struct Background, 1);
257 tmpPage->bg->type = -1;
258 tmpPage->bg->canvas_item = NULL;
259 tmpPage->bg->pixbuf = NULL;
260 tmpPage->bg->filename = NULL;
261 tmpJournal.pages = g_list_append(tmpJournal.pages, tmpPage);
263 // scan for height and width attributes
265 while (*attribute_names!=NULL) {
266 if (!strcmp(*attribute_names, "width")) {
267 if (has_attr & 1) *error = xoj_invalid();
268 cleanup_numeric((gchar *)*attribute_values);
269 tmpPage->width = g_ascii_strtod(*attribute_values, &ptr);
270 if (ptr == *attribute_values) *error = xoj_invalid();
273 else if (!strcmp(*attribute_names, "height")) {
274 if (has_attr & 2) *error = xoj_invalid();
275 cleanup_numeric((gchar *)*attribute_values);
276 tmpPage->height = g_ascii_strtod(*attribute_values, &ptr);
277 if (ptr == *attribute_values) *error = xoj_invalid();
280 else *error = xoj_invalid();
284 if (has_attr!=3) *error = xoj_invalid();
286 else if (!strcmp(element_name, "background")) {
287 if (tmpPage == NULL || tmpLayer !=NULL || tmpPage->bg->type >= 0) {
288 *error = xoj_invalid();
292 while (*attribute_names!=NULL) {
293 if (!strcmp(*attribute_names, "type")) {
294 if (has_attr) *error = xoj_invalid();
296 if (!strcmp(*attribute_values, bgtype_names[i]))
297 tmpPage->bg->type = i;
298 if (tmpPage->bg->type < 0) *error = xoj_invalid();
300 if (tmpPage->bg->type == BG_PDF) {
301 if (tmpBg_pdf == NULL) tmpBg_pdf = tmpPage->bg;
304 tmpPage->bg->filename = refstring_ref(tmpBg_pdf->filename);
305 tmpPage->bg->file_domain = tmpBg_pdf->file_domain;
309 else if (!strcmp(*attribute_names, "color")) {
310 if (tmpPage->bg->type != BG_SOLID) *error = xoj_invalid();
311 if (has_attr & 2) *error = xoj_invalid();
312 tmpPage->bg->color_no = COLOR_OTHER;
313 for (i=0; i<COLOR_MAX; i++)
314 if (!strcmp(*attribute_values, bgcolor_names[i])) {
315 tmpPage->bg->color_no = i;
316 tmpPage->bg->color_rgba = predef_bgcolors_rgba[i];
318 // there's also the case of hex (#rrggbbaa) colors
319 if (tmpPage->bg->color_no == COLOR_OTHER && **attribute_values == '#') {
320 tmpPage->bg->color_rgba = strtol(*attribute_values + 1, &ptr, 16);
321 if (*ptr!=0) *error = xoj_invalid();
325 else if (!strcmp(*attribute_names, "style")) {
326 if (tmpPage->bg->type != BG_SOLID) *error = xoj_invalid();
327 if (has_attr & 4) *error = xoj_invalid();
328 tmpPage->bg->ruling = -1;
330 if (!strcmp(*attribute_values, bgstyle_names[i]))
331 tmpPage->bg->ruling = i;
332 if (tmpPage->bg->ruling < 0) *error = xoj_invalid();
335 else if (!strcmp(*attribute_names, "domain")) {
336 if (tmpPage->bg->type <= BG_SOLID || (has_attr & 8))
337 { *error = xoj_invalid(); return; }
338 tmpPage->bg->file_domain = -1;
340 if (!strcmp(*attribute_values, file_domain_names[i]))
341 tmpPage->bg->file_domain = i;
342 if (tmpPage->bg->file_domain < 0)
343 { *error = xoj_invalid(); return; }
346 else if (!strcmp(*attribute_names, "filename")) {
347 if (tmpPage->bg->type <= BG_SOLID || (has_attr != 9))
348 { *error = xoj_invalid(); return; }
349 if (tmpPage->bg->file_domain == DOMAIN_CLONE) {
350 // filename is a page number
351 i = strtol(*attribute_values, &ptr, 10);
352 if (ptr == *attribute_values || i < 0 || i > tmpJournal.npages-2)
353 { *error = xoj_invalid(); return; }
354 tmpbg = ((struct Page *)g_list_nth_data(tmpJournal.pages, i))->bg;
355 if (tmpbg->type != tmpPage->bg->type)
356 { *error = xoj_invalid(); return; }
357 tmpPage->bg->filename = refstring_ref(tmpbg->filename);
358 tmpPage->bg->pixbuf = tmpbg->pixbuf;
359 if (tmpbg->pixbuf!=NULL) gdk_pixbuf_ref(tmpbg->pixbuf);
360 tmpPage->bg->file_domain = tmpbg->file_domain;
363 tmpPage->bg->filename = new_refstring(*attribute_values);
364 if (tmpPage->bg->type == BG_PIXMAP) {
365 if (tmpPage->bg->file_domain == DOMAIN_ATTACH) {
366 tmpbg_filename = g_strdup_printf("%s.%s", tmpFilename, *attribute_values);
367 if (sscanf(*attribute_values, "bg_%d.png", &i) == 1)
368 if (i > tmpJournal.last_attach_no)
369 tmpJournal.last_attach_no = i;
371 else tmpbg_filename = g_strdup(*attribute_values);
372 tmpPage->bg->pixbuf = gdk_pixbuf_new_from_file(tmpbg_filename, NULL);
373 if (tmpPage->bg->pixbuf == NULL) {
374 dialog = gtk_message_dialog_new(GTK_WINDOW(winMain), GTK_DIALOG_MODAL,
375 GTK_MESSAGE_WARNING, GTK_BUTTONS_OK,
376 "Could not open background '%s'. Setting background to white.",
378 gtk_dialog_run(GTK_DIALOG(dialog));
379 gtk_widget_destroy(dialog);
380 tmpPage->bg->pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8, 1, 1);
381 gdk_pixbuf_fill(tmpPage->bg->pixbuf, 0xffffffff); // solid white
383 g_free(tmpbg_filename);
388 else if (!strcmp(*attribute_names, "pageno")) {
389 if (tmpPage->bg->type != BG_PDF || (has_attr & 32))
390 { *error = xoj_invalid(); return; }
391 tmpPage->bg->file_page_seq = strtol(*attribute_values, &ptr, 10);
392 if (ptr == *attribute_values) *error = xoj_invalid();
395 else *error = xoj_invalid();
399 if (tmpPage->bg->type < 0) *error = xoj_invalid();
400 if (tmpPage->bg->type == BG_SOLID && has_attr != 7) *error = xoj_invalid();
401 if (tmpPage->bg->type == BG_PIXMAP && has_attr != 25) *error = xoj_invalid();
402 if (tmpPage->bg->type == BG_PDF && has_attr != 57) *error = xoj_invalid();
404 else if (!strcmp(element_name, "layer")) { // start of a layer
405 if (tmpPage == NULL || tmpLayer != NULL) {
406 *error = xoj_invalid();
409 tmpLayer = (struct Layer *)g_malloc(sizeof(struct Layer));
410 tmpLayer->items = NULL;
411 tmpLayer->nitems = 0;
412 tmpLayer->group = NULL;
413 tmpPage->layers = g_list_append(tmpPage->layers, tmpLayer);
416 else if (!strcmp(element_name, "stroke")) { // start of a stroke
417 if (tmpLayer == NULL || tmpItem != NULL) {
418 *error = xoj_invalid();
421 tmpItem = (struct Item *)g_malloc(sizeof(struct Item));
422 tmpItem->type = ITEM_STROKE;
423 tmpItem->path = NULL;
424 tmpItem->canvas_item = NULL;
425 tmpLayer->items = g_list_append(tmpLayer->items, tmpItem);
427 // scan for tool, color, and width attributes
429 while (*attribute_names!=NULL) {
430 if (!strcmp(*attribute_names, "width")) {
431 if (has_attr & 1) *error = xoj_invalid();
432 cleanup_numeric((gchar *)*attribute_values);
433 tmpItem->brush.thickness = g_ascii_strtod(*attribute_values, &ptr);
434 if (ptr == *attribute_values) *error = xoj_invalid();
437 else if (!strcmp(*attribute_names, "color")) {
438 if (has_attr & 2) *error = xoj_invalid();
439 tmpItem->brush.color_no = COLOR_OTHER;
440 for (i=0; i<COLOR_MAX; i++)
441 if (!strcmp(*attribute_values, color_names[i])) {
442 tmpItem->brush.color_no = i;
443 tmpItem->brush.color_rgba = predef_colors_rgba[i];
445 // there's also the case of hex (#rrggbbaa) colors
446 if (tmpItem->brush.color_no == COLOR_OTHER && **attribute_values == '#') {
447 tmpItem->brush.color_rgba = strtol(*attribute_values + 1, &ptr, 16);
448 if (*ptr!=0) *error = xoj_invalid();
452 else if (!strcmp(*attribute_names, "tool")) {
453 if (has_attr & 4) *error = xoj_invalid();
454 tmpItem->brush.tool_type = -1;
455 for (i=0; i<NUM_STROKE_TOOLS; i++)
456 if (!strcmp(*attribute_values, tool_names[i])) {
457 tmpItem->brush.tool_type = i;
459 if (tmpItem->brush.tool_type == -1) *error = xoj_invalid();
462 else *error = xoj_invalid();
466 if (has_attr!=7) *error = xoj_invalid();
467 // finish filling the brush info
468 tmpItem->brush.thickness_no = 0; // who cares ?
469 tmpItem->brush.tool_options = 0; // who cares ?
470 if (tmpItem->brush.tool_type == TOOL_HIGHLIGHTER) {
471 if (tmpItem->brush.color_no >= 0)
472 tmpItem->brush.color_rgba &= HILITER_ALPHA_MASK;
477 void xoj_parser_end_element(GMarkupParseContext *context,
478 const gchar *element_name, gpointer user_data, GError **error)
480 if (!strcmp(element_name, "page")) {
481 if (tmpPage == NULL || tmpLayer != NULL) {
482 *error = xoj_invalid();
485 if (tmpPage->nlayers == 0 || tmpPage->bg->type < 0) *error = xoj_invalid();
488 if (!strcmp(element_name, "layer")) {
489 if (tmpLayer == NULL || tmpItem != NULL) {
490 *error = xoj_invalid();
495 if (!strcmp(element_name, "stroke")) {
496 if (tmpItem == NULL) {
497 *error = xoj_invalid();
500 update_item_bbox(tmpItem);
505 void xoj_parser_text(GMarkupParseContext *context,
506 const gchar *text, gsize text_len, gpointer user_data, GError **error)
508 const gchar *element_name, *ptr;
511 element_name = g_markup_parse_context_get_element(context);
512 if (element_name == NULL) return;
513 if (!strcmp(element_name, "stroke")) {
514 cleanup_numeric((gchar *)text);
517 while (text_len > 0) {
518 realloc_cur_path(n/2 + 1);
519 ui.cur_path.coords[n] = g_ascii_strtod(text, (char **)(&ptr));
520 if (ptr == text) break;
521 text_len -= (ptr - text);
525 if (n<4 || n&1) { *error = xoj_invalid(); return; }
526 tmpItem->path = gnome_canvas_points_new(n/2);
527 g_memmove(tmpItem->path->coords, ui.cur_path.coords, n*sizeof(double));
531 gboolean user_wants_second_chance(char **filename)
534 GtkFileFilter *filt_all, *filt_pdf;
535 GtkResponseType response;
537 dialog = gtk_message_dialog_new(GTK_WINDOW(winMain), GTK_DIALOG_MODAL,
538 GTK_MESSAGE_ERROR, GTK_BUTTONS_YES_NO,
539 "Could not open background '%s'.\nSelect another file?",
541 response = gtk_dialog_run(GTK_DIALOG(dialog));
542 gtk_widget_destroy(dialog);
543 if (response != GTK_RESPONSE_YES) return FALSE;
544 dialog = gtk_file_chooser_dialog_new("Open PDF", GTK_WINDOW (winMain),
545 GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
546 GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, NULL);
548 filt_all = gtk_file_filter_new();
549 gtk_file_filter_set_name(filt_all, "All files");
550 gtk_file_filter_add_pattern(filt_all, "*");
551 filt_pdf = gtk_file_filter_new();
552 gtk_file_filter_set_name(filt_pdf, "PDF files");
553 gtk_file_filter_add_pattern(filt_pdf, "*.pdf");
554 gtk_file_chooser_add_filter(GTK_FILE_CHOOSER (dialog), filt_pdf);
555 gtk_file_chooser_add_filter(GTK_FILE_CHOOSER (dialog), filt_all);
557 if (gtk_dialog_run(GTK_DIALOG(dialog)) != GTK_RESPONSE_ACCEPT) {
558 gtk_widget_destroy(dialog);
562 *filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog));
563 gtk_widget_destroy(dialog);
567 gboolean open_journal(char *filename)
569 const GMarkupParser parser = { xoj_parser_start_element,
570 xoj_parser_end_element,
571 xoj_parser_text, NULL, NULL};
572 GMarkupParseContext *context;
582 f = gzopen(filename, "r");
583 if (f==NULL) return FALSE;
585 context = g_markup_parse_context_new(&parser, 0, NULL, NULL);
587 tmpJournal.npages = 0;
588 tmpJournal.pages = NULL;
589 tmpJournal.last_attach_no = 0;
593 tmpFilename = filename;
598 while (valid && !gzeof(f)) {
599 len = gzread(f, buffer, 1000);
600 if (len<0) valid = FALSE;
601 if (maybe_pdf && len>=4 && !strncmp(buffer, "%PDF", 4))
602 { valid = FALSE; break; } // most likely pdf
603 else maybe_pdf = FALSE;
605 valid = g_markup_parse_context_parse(context, buffer, len, &error);
608 if (valid) valid = g_markup_parse_context_end_parse(context, &error);
609 if (tmpJournal.npages == 0) valid = FALSE;
610 g_markup_parse_context_free(context);
613 delete_journal(&tmpJournal);
614 if (!maybe_pdf) return FALSE;
615 // essentially same as on_fileNewBackground from here on
618 while (bgpdf.status != STATUS_NOT_INIT) gtk_main_iteration();
620 ui.zoom = DEFAULT_ZOOM;
621 gnome_canvas_set_pixels_per_unit(canvas, ui.zoom);
623 return init_bgpdf(filename, TRUE, DOMAIN_ABSOLUTE);
626 ui.saved = TRUE; // force close_journal() to do its job
628 g_memmove(&journal, &tmpJournal, sizeof(struct Journal));
630 // if we need to initialize a fresh pdf loader
631 if (tmpBg_pdf!=NULL) {
632 while (bgpdf.status != STATUS_NOT_INIT) gtk_main_iteration();
633 if (tmpBg_pdf->file_domain == DOMAIN_ATTACH)
634 tmpfn = g_strdup_printf("%s.%s", filename, tmpBg_pdf->filename->s);
636 tmpfn = g_strdup(tmpBg_pdf->filename->s);
637 valid = init_bgpdf(tmpfn, FALSE, tmpBg_pdf->file_domain);
638 // in case the file name became invalid
639 if (!valid && tmpBg_pdf->file_domain != DOMAIN_ATTACH)
640 if (user_wants_second_chance(&tmpfn)) {
641 valid = init_bgpdf(tmpfn, FALSE, tmpBg_pdf->file_domain);
642 if (valid) { // change the file name...
643 g_free(tmpBg_pdf->filename->s);
644 tmpBg_pdf->filename->s = g_strdup(tmpfn);
648 refstring_unref(bgpdf.filename);
649 bgpdf.filename = refstring_ref(tmpBg_pdf->filename);
651 dialog = gtk_message_dialog_new(GTK_WINDOW(winMain), GTK_DIALOG_MODAL,
652 GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "Could not open background '%s'.",
654 gtk_dialog_run(GTK_DIALOG(dialog));
655 gtk_widget_destroy(dialog);
661 ui.cur_page = (struct Page *)journal.pages->data;
662 ui.layerno = ui.cur_page->nlayers-1;
663 ui.cur_layer = (struct Layer *)(g_list_last(ui.cur_page->layers)->data);
665 ui.zoom = DEFAULT_ZOOM;
666 update_file_name(g_strdup(filename));
667 gnome_canvas_set_pixels_per_unit(canvas, ui.zoom);
670 gtk_adjustment_set_value(gtk_layout_get_vadjustment(GTK_LAYOUT(canvas)), 0);
674 /************ file backgrounds *************/
676 struct Background *attempt_load_pix_bg(char *filename, gboolean attach)
678 struct Background *bg;
681 pix = gdk_pixbuf_new_from_file(filename, NULL);
682 if (pix == NULL) return NULL;
684 bg = g_new(struct Background, 1);
685 bg->type = BG_PIXMAP;
686 bg->canvas_item = NULL;
688 bg->pixbuf_scale = DEFAULT_ZOOM;
690 bg->filename = new_refstring(NULL);
691 bg->file_domain = DOMAIN_ATTACH;
693 bg->filename = new_refstring(filename);
694 bg->file_domain = DOMAIN_ABSOLUTE;
699 #define BUFSIZE 65536 // a reasonable buffer size for reads from gs pipe
701 GList *attempt_load_gv_bg(char *filename)
703 struct Background *bg;
706 GdkPixbufLoader *loader;
710 int buflen, remnlen, file_pageno;
712 buf = g_malloc(BUFSIZE); // a reasonable buffer size
713 f = fopen(filename, "r");
714 if (fread(buf, 1, 4, f) !=4 ||
715 (strncmp((char *)buf, "%!PS", 4) && strncmp((char *)buf, "%PDF", 4))) {
722 pipename = g_strdup_printf(GS_CMDLINE, (double)GS_BITMAP_DPI, filename);
723 gs_pipe = popen(pipename, "r");
731 while (!feof(gs_pipe)) {
732 if (!remnlen) { // new page: get a BMP header ?
733 buflen = fread(buf, 1, 54, gs_pipe);
734 if (buflen < 6) buflen += fread(buf, 1, 54-buflen, gs_pipe);
735 if (buflen < 6 || buf[0]!='B' || buf[1]!='M') break; // fatal: abort
736 remnlen = (int)(buf[5]<<24) + (buf[4]<<16) + (buf[3]<<8) + (buf[2]);
737 loader = gdk_pixbuf_loader_new();
739 else buflen = fread(buf, 1, (remnlen < BUFSIZE)?remnlen:BUFSIZE, gs_pipe);
741 if (buflen == 0) break;
742 if (!gdk_pixbuf_loader_write(loader, buf, buflen, NULL)) break;
743 if (remnlen == 0) { // make a new bg
744 pix = gdk_pixbuf_loader_get_pixbuf(loader);
745 if (pix == NULL) break;
747 gdk_pixbuf_loader_close(loader, NULL);
748 g_object_unref(loader);
750 bg = g_new(struct Background, 1);
751 bg->canvas_item = NULL;
753 bg->pixbuf_scale = (GS_BITMAP_DPI/72.0);
754 bg->type = BG_PIXMAP;
755 bg->filename = new_refstring(NULL);
756 bg->file_domain = DOMAIN_ATTACH;
758 bg_list = g_list_append(bg_list, bg);
761 if (loader != NULL) gdk_pixbuf_loader_close(loader, NULL);
767 struct Background *attempt_screenshot_bg(void)
769 struct Background *bg;
772 GError *error = NULL;
776 Window x_root, x_win;
778 x_root = gdk_x11_get_default_root_xwindow();
780 if (!XGrabButton(GDK_DISPLAY(), AnyButton, AnyModifier, x_root,
781 False, ButtonReleaseMask, GrabModeAsync, GrabModeSync, None, None))
784 XWindowEvent (GDK_DISPLAY(), x_root, ButtonReleaseMask, &x_event);
785 XUngrabButton(GDK_DISPLAY(), AnyButton, AnyModifier, x_root);
787 x_win = x_event.xbutton.subwindow;
788 if (x_win == None) x_win = x_root;
790 window = gdk_window_foreign_new_for_display(gdk_display_get_default(), x_win);
792 gdk_window_get_geometry(window, &x, &y, &w, &h, NULL);
794 pix = gdk_pixbuf_get_from_drawable(NULL, window,
795 gdk_colormap_get_system(), 0, 0, 0, 0, w, h);
797 if (pix == NULL) return NULL;
799 bg = g_new(struct Background, 1);
800 bg->type = BG_PIXMAP;
801 bg->canvas_item = NULL;
803 bg->pixbuf_scale = DEFAULT_ZOOM;
804 bg->filename = new_refstring(NULL);
805 bg->file_domain = DOMAIN_ATTACH;
809 /************** pdf annotation ***************/
811 /* free tmp directory */
813 void end_bgpdf_shutdown(void)
815 if (bgpdf.tmpdir!=NULL) {
816 if (bgpdf.tmpfile_copy!=NULL) {
817 g_unlink(bgpdf.tmpfile_copy);
818 g_free(bgpdf.tmpfile_copy);
819 bgpdf.tmpfile_copy = NULL;
821 g_rmdir(bgpdf.tmpdir);
822 g_free(bgpdf.tmpdir);
825 bgpdf.status = STATUS_NOT_INIT;
828 /* cancel a request */
830 void cancel_bgpdf_request(struct BgPdfRequest *req)
834 list_link = g_list_find(bgpdf.requests, req);
835 if (list_link == NULL) return;
836 if (list_link->prev == NULL && bgpdf.pid > 0) {
837 // this is being processed: kill the child but don't remove the request yet
838 if (bgpdf.status == STATUS_RUNNING) bgpdf.status = STATUS_ABORTED;
839 kill(bgpdf.pid, SIGHUP);
840 // printf("Cancelling a request - killing %d\n", bgpdf.pid);
843 // remove the request
844 bgpdf.requests = g_list_delete_link(bgpdf.requests, list_link);
846 // printf("Cancelling a request - no kill needed\n");
850 /* sigchld callback */
852 void bgpdf_child_handler(GPid pid, gint status, gpointer data)
854 struct BgPdfRequest *req;
855 struct BgPdfPage *bgpg;
859 if (bgpdf.requests == NULL) return;
860 req = (struct BgPdfRequest *)bgpdf.requests->data;
862 ppm_name = g_strdup_printf("%s/p-%06d.ppm", bgpdf.tmpdir, req->pageno);
863 // printf("Child %d finished, should look for %s... \n", pid, ppm_name);
865 if (bgpdf.status == STATUS_ABORTED || bgpdf.status == STATUS_SHUTDOWN)
868 pixbuf = gdk_pixbuf_new_from_file(ppm_name, NULL);
873 if (pixbuf != NULL) { // success
874 // printf("success\n");
875 while (req->pageno > bgpdf.npages) {
876 bgpg = g_new(struct BgPdfPage, 1);
878 bgpdf.pages = g_list_append(bgpdf.pages, bgpg);
881 bgpg = g_list_nth_data(bgpdf.pages, req->pageno-1);
882 if (bgpg->pixbuf!=NULL) gdk_pixbuf_unref(bgpg->pixbuf);
883 bgpg->pixbuf = pixbuf;
884 bgpg->dpi = req->dpi;
885 if (req->initial_request && bgpdf.create_pages) {
886 bgpdf_create_page_with_bg(req->pageno, bgpg);
887 // create page n, resize it, set its bg - all without any undo effect
889 if (!req->is_printing) bgpdf_update_bg(req->pageno, bgpg);
890 // look for all pages with this bg, and update their bg pixmaps
894 // printf("failed or aborted\n");
895 bgpdf.create_pages = FALSE;
896 req->initial_request = FALSE;
900 g_spawn_close_pid(pid);
902 if (req->initial_request)
903 req->pageno++; // try for next page
905 bgpdf.requests = g_list_delete_link(bgpdf.requests, bgpdf.requests);
907 if (bgpdf.status == STATUS_SHUTDOWN) {
908 end_bgpdf_shutdown();
912 bgpdf.status = STATUS_IDLE;
913 if (bgpdf.requests != NULL) bgpdf_spawn_child();
916 /* spawn a child to process the head request */
918 void bgpdf_spawn_child(void)
920 struct BgPdfRequest *req;
922 gchar pageno_str[10], dpi_str[10];
923 gchar *pdf_filename = bgpdf.tmpfile_copy;
924 gchar *ppm_root = g_strdup_printf("%s/p", bgpdf.tmpdir);
925 gchar *argv[]= PDFTOPPM_ARGV;
928 if (bgpdf.requests == NULL) return;
929 req = (struct BgPdfRequest *)bgpdf.requests->data;
930 if (req->pageno > bgpdf.npages+1 ||
931 (!req->initial_request && req->pageno <= bgpdf.npages &&
932 req->dpi == ((struct BgPdfPage *)g_list_nth_data(bgpdf.pages, req->pageno-1))->dpi))
933 { // ignore this request - it's redundant, or in outer space
935 bgpdf.status = STATUS_IDLE;
936 bgpdf.requests = g_list_delete_link(bgpdf.requests, bgpdf.requests);
938 if (bgpdf.requests != NULL) bgpdf_spawn_child();
941 g_snprintf(pageno_str, 10, "%d", req->pageno);
942 g_snprintf(dpi_str, 10, "%d", req->dpi);
943 /* printf("Processing request for page %d at %d dpi -- in %s\n",
944 req->pageno, req->dpi, ppm_root); */
945 if (!g_spawn_async(NULL, argv, NULL,
946 G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_SEARCH_PATH,
947 NULL, NULL, &pid, NULL))
949 // couldn't spawn... abort this request, try next one maybe ?
950 // printf("Couldn't spawn\n");
952 bgpdf.status = STATUS_IDLE;
953 bgpdf.requests = g_list_delete_link(bgpdf.requests, bgpdf.requests);
955 if (!bgpdf.has_failed) {
956 dialog = gtk_message_dialog_new(GTK_WINDOW(winMain), GTK_DIALOG_MODAL,
957 GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "Unable to start PDF loader %s.", argv[0]);
958 gtk_dialog_run(GTK_DIALOG(dialog));
959 gtk_widget_destroy(dialog);
961 bgpdf.has_failed = TRUE;
962 if (bgpdf.requests != NULL) bgpdf_spawn_child();
966 // printf("Spawned process %d\n", pid);
968 bgpdf.status = STATUS_RUNNING;
969 g_child_watch_add(pid, bgpdf_child_handler, NULL);
975 void add_bgpdf_request(int pageno, double zoom, gboolean printing)
977 struct BgPdfRequest *req, *cmp_req;
980 if (bgpdf.status == STATUS_NOT_INIT || bgpdf.status == STATUS_SHUTDOWN)
981 return; // don't accept requests in those modes...
982 req = g_new(struct BgPdfRequest, 1);
983 req->is_printing = printing;
984 if (printing) req->dpi = PDFTOPPM_PRINTING_DPI;
985 else req->dpi = (int)floor(72*zoom+0.5);
986 // printf("Enqueuing request for page %d at %d dpi\n", pageno, req->dpi);
988 // cancel any request this may supersede
989 for (list = bgpdf.requests; list != NULL; ) {
990 cmp_req = (struct BgPdfRequest *)list->data;
992 if (!cmp_req->initial_request && cmp_req->pageno == pageno &&
993 cmp_req->is_printing == printing)
994 cancel_bgpdf_request(cmp_req);
996 req->pageno = pageno;
997 req->initial_request = FALSE;
1000 req->initial_request = TRUE;
1002 bgpdf.requests = g_list_append(bgpdf.requests, req);
1003 if (!bgpdf.pid) bgpdf_spawn_child();
1006 /* shutdown the PDF reader */
1008 void shutdown_bgpdf(void)
1011 struct BgPdfPage *pdfpg;
1012 struct BgPdfRequest *req;
1014 if (bgpdf.status == STATUS_NOT_INIT || bgpdf.status == STATUS_SHUTDOWN) return;
1015 refstring_unref(bgpdf.filename);
1016 for (list = bgpdf.pages; list != NULL; list = list->next) {
1017 pdfpg = (struct BgPdfPage *)list->data;
1018 if (pdfpg->pixbuf!=NULL) gdk_pixbuf_unref(pdfpg->pixbuf);
1020 g_list_free(bgpdf.pages);
1021 bgpdf.status = STATUS_SHUTDOWN;
1022 for (list = g_list_last(bgpdf.requests); list != NULL; ) {
1023 req = (struct BgPdfRequest *)list->data;
1025 cancel_bgpdf_request(req);
1027 if (!bgpdf.pid) end_bgpdf_shutdown();
1028 /* The above will ultimately remove all requests and kill the child if needed.
1029 The child will set status to STATUS_NOT_INIT, clear the requests list,
1030 empty tmpdir, ... except if there's no child! */
1031 /* note: it could look like there's a race condition here - if a child
1032 terminates and a new request is enqueued while we are destroying the
1033 queue - but actually the child handler callback is NOT a signal
1034 callback, so execution of this function is atomic */
1037 gboolean init_bgpdf(char *pdfname, gboolean create_pages, int file_domain)
1043 if (bgpdf.status != STATUS_NOT_INIT) return FALSE;
1044 bgpdf.tmpfile_copy = NULL;
1045 bgpdf.tmpdir = mkdtemp(g_strdup(TMPDIR_TEMPLATE));
1046 if (!bgpdf.tmpdir) return FALSE;
1047 // make a local copy and check if it's a PDF
1048 if (!g_file_get_contents(pdfname, &filebuf, &filelen, NULL))
1049 { end_bgpdf_shutdown(); return FALSE; }
1050 if (filelen < 4 || strncmp(filebuf, "%PDF", 4))
1051 { g_free(filebuf); end_bgpdf_shutdown(); return FALSE; }
1052 bgpdf.tmpfile_copy = g_strdup_printf("%s/bg.pdf", bgpdf.tmpdir);
1053 f = fopen(bgpdf.tmpfile_copy, "w");
1054 if (f == NULL || fwrite(filebuf, 1, filelen, f) != filelen)
1055 { g_free(filebuf); end_bgpdf_shutdown(); return FALSE; }
1058 bgpdf.status = STATUS_IDLE;
1060 bgpdf.filename = new_refstring((file_domain == DOMAIN_ATTACH) ? "bg.pdf" : pdfname);
1061 bgpdf.file_domain = file_domain;
1064 bgpdf.requests = NULL;
1065 bgpdf.create_pages = create_pages;
1066 bgpdf.has_failed = FALSE;
1067 add_bgpdf_request(-1, DEFAULT_ZOOM, FALSE); // request all pages
1071 // create page n, resize it, set its bg
1072 void bgpdf_create_page_with_bg(int pageno, struct BgPdfPage *bgpg)
1075 struct Background *bg;
1077 if (journal.npages < pageno) {
1078 bg = g_new(struct Background, 1);
1079 bg->canvas_item = NULL;
1081 pg = (struct Page *)g_list_nth_data(journal.pages, pageno-1);
1083 if (bg->type != BG_SOLID) return;
1084 // don't mess with a page the user has modified significantly...
1088 bg->pixbuf = gdk_pixbuf_ref(bgpg->pixbuf);
1089 bg->filename = refstring_ref(bgpdf.filename);
1090 bg->file_domain = bgpdf.file_domain;
1091 bg->file_page_seq = pageno;
1092 bg->pixbuf_scale = DEFAULT_ZOOM;
1093 bg->pixbuf_dpi = bgpg->dpi;
1095 if (journal.npages < pageno) {
1096 pg = new_page_with_bg(bg,
1097 gdk_pixbuf_get_width(bg->pixbuf)*72.0/bg->pixbuf_dpi,
1098 gdk_pixbuf_get_height(bg->pixbuf)*72.0/bg->pixbuf_dpi);
1099 journal.pages = g_list_append(journal.pages, pg);
1102 pg->width = gdk_pixbuf_get_width(bgpg->pixbuf)*72.0/bg->pixbuf_dpi;
1103 pg->height = gdk_pixbuf_get_height(bgpg->pixbuf)*72.0/bg->pixbuf_dpi;
1104 make_page_clipbox(pg);
1105 update_canvas_bg(pg);
1107 update_page_stuff();
1110 // look for all journal pages with given pdf bg, and update their bg pixmaps
1111 void bgpdf_update_bg(int pageno, struct BgPdfPage *bgpg)
1116 for (list = journal.pages; list!= NULL; list = list->next) {
1117 pg = (struct Page *)list->data;
1118 if (pg->bg->type == BG_PDF && pg->bg->file_page_seq == pageno) {
1119 if (pg->bg->pixbuf!=NULL) gdk_pixbuf_unref(pg->bg->pixbuf);
1120 pg->bg->pixbuf = gdk_pixbuf_ref(bgpg->pixbuf);
1121 pg->bg->pixbuf_dpi = bgpg->dpi;
1122 update_canvas_bg(pg);
1127 // initialize the recent files list
1137 g_strlcpy(s, "mru0", 5);
1138 for (s[3]='0', i=0; i<MRU_SIZE; s[3]++, i++) {
1139 ui.mrumenu[i] = GET_COMPONENT(s);
1142 f = g_io_channel_new_file(ui.mrufile, "r", NULL);
1143 if (f) status = G_IO_STATUS_NORMAL;
1144 else status = G_IO_STATUS_ERROR;
1146 while (status == G_IO_STATUS_NORMAL && i<MRU_SIZE) {
1148 status = g_io_channel_read_line(f, &str, NULL, &lfptr, NULL);
1149 if (status == G_IO_STATUS_NORMAL && lfptr>0) {
1156 g_io_channel_shutdown(f, FALSE, NULL);
1157 g_io_channel_unref(f);
1162 void update_mru_menu(void)
1165 gboolean anyone = FALSE;
1167 for (i=0; i<MRU_SIZE; i++) {
1168 if (ui.mru[i]!=NULL) {
1169 gtk_label_set_text(GTK_LABEL(gtk_bin_get_child(GTK_BIN(ui.mrumenu[i]))),
1170 g_basename(ui.mru[i]));
1171 gtk_widget_show(ui.mrumenu[i]);
1174 else gtk_widget_hide(ui.mrumenu[i]);
1176 gtk_widget_set_sensitive(GET_COMPONENT("fileRecentFiles"), anyone);
1179 void new_mru_entry(char *name)
1183 for (i=0;i<MRU_SIZE;i++)
1184 if (ui.mru[i]!=NULL && !strcmp(ui.mru[i], name)) {
1186 for (j=i+1; j<MRU_SIZE; j++) ui.mru[j-1] = ui.mru[j];
1187 ui.mru[MRU_SIZE-1]=NULL;
1189 if (ui.mru[MRU_SIZE-1]!=NULL) g_free(ui.mru[MRU_SIZE-1]);
1190 for (j=MRU_SIZE-1; j>=1; j--) ui.mru[j] = ui.mru[j-1];
1191 ui.mru[0] = g_strdup(name);
1195 void delete_mru_entry(int which)
1199 if (ui.mru[which]!=NULL) g_free(ui.mru[which]);
1200 for (i=which+1;i<MRU_SIZE;i++)
1201 ui.mru[i-1] = ui.mru[i];
1202 ui.mru[MRU_SIZE-1] = NULL;
1206 void save_mru_list(void)
1211 f = fopen(ui.mrufile, "w");
1212 if (f==NULL) return;
1213 for (i=0; i<MRU_SIZE; i++)
1214 if (ui.mru[i]!=NULL) fprintf(f, "%s\n", ui.mru[i]);