11 #include <libgnomecanvas/libgnomecanvas.h>
18 #include "xo-interface.h"
19 #include "xo-support.h"
20 #include "xo-callbacks.h"
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"};
33 // creates a new empty journal
35 void new_journal(void)
38 journal.pages = g_list_append(NULL, new_page(&ui.default_page));
39 journal.last_attach_no = 0;
42 ui.cur_page = (struct Page *) journal.pages->data;
43 ui.cur_layer = (struct Layer *) ui.cur_page->layers->data;
46 update_file_name(NULL);
49 // check attachment names
51 void chk_attach_names(void)
54 struct Background *bg;
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);
64 // saves the journal to a file: returns true on success, false on error
66 gboolean save_journal(const char *filename)
69 struct Page *pg, *tmppg;
78 GList *pagelist, *layerlist, *itemlist, *list;
81 f = gzopen(filename, "w");
82 if (f==NULL) return FALSE;
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]);
98 else if (pg->bg->type == BG_PIXMAP) {
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; }
108 gzprintf(f, "domain=\"clone\" filename=\"%d\" ", is_clone);
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);
121 gzprintf(f, "domain=\"%s\" filename=\"%s\" ",
122 file_domain_names[pg->bg->file_domain], pg->bg->filename->s);
125 else if (pg->bg->type == BG_PDF) {
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; }
132 if (pg->bg->file_domain == DOMAIN_ATTACH) {
133 tmpfn = g_strdup_printf("%s.%s", filename, pg->bg->filename->s);
135 if (bgpdf.status != STATUS_NOT_INIT &&
136 g_file_get_contents(bgpdf.tmpfile_copy, &pdfbuf, &pdflen, NULL))
138 tmpf = fopen(tmpfn, "w");
139 if (tmpf != NULL && fwrite(pdfbuf, 1, pdflen, tmpf) == pdflen)
144 dialog = gtk_message_dialog_new(GTK_WINDOW(winMain), GTK_DIALOG_MODAL,
145 GTK_MESSAGE_ERROR, GTK_BUTTONS_OK,
146 "Could not write background '%s'. Continuing anyway.", tmpfn);
147 gtk_dialog_run(GTK_DIALOG(dialog));
148 gtk_widget_destroy(dialog);
152 gzprintf(f, "domain=\"%s\" filename=\"%s\" ",
153 file_domain_names[pg->bg->file_domain], pg->bg->filename->s);
155 gzprintf(f, "pageno=\"%d\" ", pg->bg->file_page_seq);
158 for (layerlist = pg->layers; layerlist!=NULL; layerlist = layerlist->next) {
159 layer = (struct Layer *)layerlist->data;
160 gzprintf(f, "<layer>\n");
161 for (itemlist = layer->items; itemlist!=NULL; itemlist = itemlist->next) {
162 item = (struct Item *)itemlist->data;
163 if (item->type == ITEM_STROKE) {
164 gzprintf(f, "<stroke tool=\"%s\" color=\"",
165 tool_names[item->brush.tool_type]);
166 if (item->brush.color_no >= 0)
167 gzputs(f, color_names[item->brush.color_no]);
169 gzprintf(f, "#%08x", item->brush.color_rgba);
170 gzprintf(f, "\" width=\"%.2f\">\n", item->brush.thickness);
171 for (i=0;i<2*item->path->num_points;i++)
172 gzprintf(f, "%.2f ", item->path->coords[i]);
173 gzprintf(f, "\n</stroke>\n");
176 gzprintf(f, "</layer>\n");
178 gzprintf(f, "</page>\n");
184 // closes a journal: returns true on success, false on abort
186 gboolean close_journal(void)
188 if (!ok_to_close()) return FALSE;
190 // free everything...
196 delete_journal(&journal);
199 /* note: various members of ui and journal are now in invalid states,
200 use new_journal() to reinitialize them */
203 // the XML parser functions for open_journal()
205 struct Journal tmpJournal;
206 struct Page *tmpPage;
207 struct Layer *tmpLayer;
208 struct Item *tmpItem;
210 struct Background *tmpBg_pdf;
212 GError *xoj_invalid(void)
214 return g_error_new(G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT, "Invalid file contents");
217 void xoj_parser_start_element(GMarkupParseContext *context,
218 const gchar *element_name, const gchar **attribute_names,
219 const gchar **attribute_values, gpointer user_data, GError **error)
223 struct Background *tmpbg;
224 char *tmpbg_filename;
227 if (!strcmp(element_name, "title") || !strcmp(element_name, "xournal")) {
228 if (tmpPage != NULL) {
229 *error = xoj_invalid();
232 // nothing special to do
234 else if (!strcmp(element_name, "page")) { // start of a page
235 if (tmpPage != NULL) {
236 *error = xoj_invalid();
239 tmpPage = (struct Page *)g_malloc(sizeof(struct Page));
240 tmpPage->layers = NULL;
241 tmpPage->nlayers = 0;
242 tmpPage->group = NULL;
243 tmpPage->bg = g_new(struct Background, 1);
244 tmpPage->bg->type = -1;
245 tmpPage->bg->canvas_item = NULL;
246 tmpPage->bg->pixbuf = NULL;
247 tmpPage->bg->filename = NULL;
248 tmpJournal.pages = g_list_append(tmpJournal.pages, tmpPage);
250 // scan for height and width attributes
252 while (*attribute_names!=NULL) {
253 if (!strcmp(*attribute_names, "width")) {
254 if (has_attr & 1) *error = xoj_invalid();
255 tmpPage->width = strtod(*attribute_values, &ptr);
256 if (ptr == *attribute_values) *error = xoj_invalid();
259 else if (!strcmp(*attribute_names, "height")) {
260 if (has_attr & 2) *error = xoj_invalid();
261 tmpPage->height = strtod(*attribute_values, &ptr);
262 if (ptr == *attribute_values) *error = xoj_invalid();
265 else *error = xoj_invalid();
269 if (has_attr!=3) *error = xoj_invalid();
271 else if (!strcmp(element_name, "background")) {
272 if (tmpPage == NULL || tmpLayer !=NULL || tmpPage->bg->type >= 0) {
273 *error = xoj_invalid();
277 while (*attribute_names!=NULL) {
278 if (!strcmp(*attribute_names, "type")) {
279 if (has_attr) *error = xoj_invalid();
281 if (!strcmp(*attribute_values, bgtype_names[i]))
282 tmpPage->bg->type = i;
283 if (tmpPage->bg->type < 0) *error = xoj_invalid();
285 if (tmpPage->bg->type == BG_PDF) {
286 if (tmpBg_pdf == NULL) tmpBg_pdf = tmpPage->bg;
289 tmpPage->bg->filename = refstring_ref(tmpBg_pdf->filename);
290 tmpPage->bg->file_domain = tmpBg_pdf->file_domain;
294 else if (!strcmp(*attribute_names, "color")) {
295 if (tmpPage->bg->type != BG_SOLID) *error = xoj_invalid();
296 if (has_attr & 2) *error = xoj_invalid();
297 tmpPage->bg->color_no = COLOR_OTHER;
298 for (i=0; i<COLOR_MAX; i++)
299 if (!strcmp(*attribute_values, bgcolor_names[i])) {
300 tmpPage->bg->color_no = i;
301 tmpPage->bg->color_rgba = predef_bgcolors_rgba[i];
303 // there's also the case of hex (#rrggbbaa) colors
304 if (tmpPage->bg->color_no == COLOR_OTHER && **attribute_values == '#') {
305 tmpPage->bg->color_rgba = strtol(*attribute_values + 1, &ptr, 16);
306 if (*ptr!=0) *error = xoj_invalid();
310 else if (!strcmp(*attribute_names, "style")) {
311 if (tmpPage->bg->type != BG_SOLID) *error = xoj_invalid();
312 if (has_attr & 4) *error = xoj_invalid();
313 tmpPage->bg->ruling = -1;
315 if (!strcmp(*attribute_values, bgstyle_names[i]))
316 tmpPage->bg->ruling = i;
317 if (tmpPage->bg->ruling < 0) *error = xoj_invalid();
320 else if (!strcmp(*attribute_names, "domain")) {
321 if (tmpPage->bg->type <= BG_SOLID || (has_attr & 8))
322 { *error = xoj_invalid(); return; }
323 tmpPage->bg->file_domain = -1;
325 if (!strcmp(*attribute_values, file_domain_names[i]))
326 tmpPage->bg->file_domain = i;
327 if (tmpPage->bg->file_domain < 0)
328 { *error = xoj_invalid(); return; }
331 else if (!strcmp(*attribute_names, "filename")) {
332 if (tmpPage->bg->type <= BG_SOLID || (has_attr != 9))
333 { *error = xoj_invalid(); return; }
334 if (tmpPage->bg->file_domain == DOMAIN_CLONE) {
335 // filename is a page number
336 i = strtol(*attribute_values, &ptr, 10);
337 if (ptr == *attribute_values || i < 0 || i > tmpJournal.npages-2)
338 { *error = xoj_invalid(); return; }
339 tmpbg = ((struct Page *)g_list_nth_data(tmpJournal.pages, i))->bg;
340 if (tmpbg->type != tmpPage->bg->type)
341 { *error = xoj_invalid(); return; }
342 tmpPage->bg->filename = refstring_ref(tmpbg->filename);
343 tmpPage->bg->pixbuf = tmpbg->pixbuf;
344 if (tmpbg->pixbuf!=NULL) gdk_pixbuf_ref(tmpbg->pixbuf);
345 tmpPage->bg->file_domain = tmpbg->file_domain;
348 tmpPage->bg->filename = new_refstring(*attribute_values);
349 if (tmpPage->bg->type == BG_PIXMAP) {
350 if (tmpPage->bg->file_domain == DOMAIN_ATTACH) {
351 tmpbg_filename = g_strdup_printf("%s.%s", tmpFilename, *attribute_values);
352 if (sscanf(*attribute_values, "bg_%d.png", &i) == 1)
353 if (i > tmpJournal.last_attach_no)
354 tmpJournal.last_attach_no = i;
356 else tmpbg_filename = g_strdup(*attribute_values);
357 tmpPage->bg->pixbuf = gdk_pixbuf_new_from_file(tmpbg_filename, NULL);
358 if (tmpPage->bg->pixbuf == NULL) {
359 dialog = gtk_message_dialog_new(GTK_WINDOW(winMain), GTK_DIALOG_MODAL,
360 GTK_MESSAGE_WARNING, GTK_BUTTONS_OK,
361 "Could not open background '%s'. Setting background to white.",
363 gtk_dialog_run(GTK_DIALOG(dialog));
364 gtk_widget_destroy(dialog);
365 tmpPage->bg->pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8, 1, 1);
366 gdk_pixbuf_fill(tmpPage->bg->pixbuf, 0xffffffff); // solid white
368 g_free(tmpbg_filename);
373 else if (!strcmp(*attribute_names, "pageno")) {
374 if (tmpPage->bg->type != BG_PDF || (has_attr & 32))
375 { *error = xoj_invalid(); return; }
376 tmpPage->bg->file_page_seq = strtod(*attribute_values, &ptr);
377 if (ptr == *attribute_values) *error = xoj_invalid();
380 else *error = xoj_invalid();
384 if (tmpPage->bg->type < 0) *error = xoj_invalid();
385 if (tmpPage->bg->type == BG_SOLID && has_attr != 7) *error = xoj_invalid();
386 if (tmpPage->bg->type == BG_PIXMAP && has_attr != 25) *error = xoj_invalid();
387 if (tmpPage->bg->type == BG_PDF && has_attr != 57) *error = xoj_invalid();
389 else if (!strcmp(element_name, "layer")) { // start of a layer
390 if (tmpPage == NULL || tmpLayer != NULL) {
391 *error = xoj_invalid();
394 tmpLayer = (struct Layer *)g_malloc(sizeof(struct Layer));
395 tmpLayer->items = NULL;
396 tmpLayer->nitems = 0;
397 tmpLayer->group = NULL;
398 tmpPage->layers = g_list_append(tmpPage->layers, tmpLayer);
401 else if (!strcmp(element_name, "stroke")) { // start of a stroke
402 if (tmpLayer == NULL || tmpItem != NULL) {
403 *error = xoj_invalid();
406 tmpItem = (struct Item *)g_malloc(sizeof(struct Item));
407 tmpItem->type = ITEM_STROKE;
408 tmpItem->path = NULL;
409 tmpItem->canvas_item = NULL;
410 tmpLayer->items = g_list_append(tmpLayer->items, tmpItem);
412 // scan for tool, color, and width attributes
414 while (*attribute_names!=NULL) {
415 if (!strcmp(*attribute_names, "width")) {
416 if (has_attr & 1) *error = xoj_invalid();
417 tmpItem->brush.thickness = strtod(*attribute_values, &ptr);
418 if (ptr == *attribute_values) *error = xoj_invalid();
421 else if (!strcmp(*attribute_names, "color")) {
422 if (has_attr & 2) *error = xoj_invalid();
423 tmpItem->brush.color_no = COLOR_OTHER;
424 for (i=0; i<COLOR_MAX; i++)
425 if (!strcmp(*attribute_values, color_names[i])) {
426 tmpItem->brush.color_no = i;
427 tmpItem->brush.color_rgba = predef_colors_rgba[i];
429 // there's also the case of hex (#rrggbbaa) colors
430 if (tmpItem->brush.color_no == COLOR_OTHER && **attribute_values == '#') {
431 tmpItem->brush.color_rgba = strtol(*attribute_values + 1, &ptr, 16);
432 if (*ptr!=0) *error = xoj_invalid();
436 else if (!strcmp(*attribute_names, "tool")) {
437 if (has_attr & 4) *error = xoj_invalid();
438 tmpItem->brush.tool_type = -1;
439 for (i=0; i<NUM_STROKE_TOOLS; i++)
440 if (!strcmp(*attribute_values, tool_names[i])) {
441 tmpItem->brush.tool_type = i;
443 if (tmpItem->brush.tool_type == -1) *error = xoj_invalid();
446 else *error = xoj_invalid();
450 if (has_attr!=7) *error = xoj_invalid();
451 // finish filling the brush info
452 tmpItem->brush.thickness_no = 0; // who cares ?
453 tmpItem->brush.tool_options = 0; // who cares ?
454 if (tmpItem->brush.tool_type == TOOL_HIGHLIGHTER) {
455 if (tmpItem->brush.color_no >= 0)
456 tmpItem->brush.color_rgba &= HILITER_ALPHA_MASK;
461 void xoj_parser_end_element(GMarkupParseContext *context,
462 const gchar *element_name, gpointer user_data, GError **error)
464 if (!strcmp(element_name, "page")) {
465 if (tmpPage == NULL || tmpLayer != NULL) {
466 *error = xoj_invalid();
469 if (tmpPage->nlayers == 0 || tmpPage->bg->type < 0) *error = xoj_invalid();
472 if (!strcmp(element_name, "layer")) {
473 if (tmpLayer == NULL || tmpItem != NULL) {
474 *error = xoj_invalid();
479 if (!strcmp(element_name, "stroke")) {
480 if (tmpItem == NULL) {
481 *error = xoj_invalid();
484 update_item_bbox(tmpItem);
489 void xoj_parser_text(GMarkupParseContext *context,
490 const gchar *text, gsize text_len, gpointer user_data, GError **error)
492 const gchar *element_name, *ptr;
495 element_name = g_markup_parse_context_get_element(context);
496 if (element_name == NULL) return;
497 if (!strcmp(element_name, "stroke")) {
500 while (text_len > 0) {
501 realloc_cur_path(n/2 + 1);
502 ui.cur_path.coords[n] = strtod(text, (char **)(&ptr));
503 if (ptr == text) break;
504 text_len -= (ptr - text);
508 if (n<4 || n&1) { *error = xoj_invalid(); return; }
509 tmpItem->path = gnome_canvas_points_new(n/2);
510 g_memmove(tmpItem->path->coords, ui.cur_path.coords, n*sizeof(double));
514 gboolean user_wants_second_chance(char **filename)
517 GtkFileFilter *filt_all, *filt_pdf;
518 GtkResponseType response;
520 dialog = gtk_message_dialog_new(GTK_WINDOW(winMain), GTK_DIALOG_MODAL,
521 GTK_MESSAGE_ERROR, GTK_BUTTONS_YES_NO,
522 "Could not open background '%s'.\nSelect another file?",
524 response = gtk_dialog_run(GTK_DIALOG(dialog));
525 gtk_widget_destroy(dialog);
526 if (response != GTK_RESPONSE_YES) return FALSE;
527 dialog = gtk_file_chooser_dialog_new("Open PDF", GTK_WINDOW (winMain),
528 GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
529 GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, NULL);
531 filt_all = gtk_file_filter_new();
532 gtk_file_filter_set_name(filt_all, "All files");
533 gtk_file_filter_add_pattern(filt_all, "*");
534 filt_pdf = gtk_file_filter_new();
535 gtk_file_filter_set_name(filt_pdf, "PDF files");
536 gtk_file_filter_add_pattern(filt_pdf, "*.pdf");
537 gtk_file_chooser_add_filter(GTK_FILE_CHOOSER (dialog), filt_pdf);
538 gtk_file_chooser_add_filter(GTK_FILE_CHOOSER (dialog), filt_all);
540 if (gtk_dialog_run(GTK_DIALOG(dialog)) != GTK_RESPONSE_ACCEPT) {
541 gtk_widget_destroy(dialog);
545 *filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog));
546 gtk_widget_destroy(dialog);
550 gboolean open_journal(char *filename)
552 const GMarkupParser parser = { xoj_parser_start_element,
553 xoj_parser_end_element,
554 xoj_parser_text, NULL, NULL};
555 GMarkupParseContext *context;
565 f = gzopen(filename, "r");
566 if (f==NULL) return FALSE;
568 context = g_markup_parse_context_new(&parser, 0, NULL, NULL);
570 tmpJournal.npages = 0;
571 tmpJournal.pages = NULL;
572 tmpJournal.last_attach_no = 0;
576 tmpFilename = filename;
581 while (valid && !gzeof(f)) {
582 len = gzread(f, buffer, 1000);
583 if (len<0) valid = FALSE;
584 if (maybe_pdf && len>=4 && !strncmp(buffer, "%PDF", 4))
585 { valid = FALSE; break; } // most likely pdf
586 else maybe_pdf = FALSE;
588 valid = g_markup_parse_context_parse(context, buffer, len, &error);
591 if (valid) valid = g_markup_parse_context_end_parse(context, &error);
592 if (tmpJournal.npages == 0) valid = FALSE;
593 g_markup_parse_context_free(context);
596 delete_journal(&tmpJournal);
597 if (!maybe_pdf) return FALSE;
598 // essentially same as on_fileNewBackground from here on
601 while (bgpdf.status != STATUS_NOT_INIT) gtk_main_iteration();
603 ui.zoom = DEFAULT_ZOOM;
604 gnome_canvas_set_pixels_per_unit(canvas, ui.zoom);
606 return init_bgpdf(filename, TRUE, DOMAIN_ABSOLUTE);
609 ui.saved = TRUE; // force close_journal() to do its job
611 g_memmove(&journal, &tmpJournal, sizeof(struct Journal));
613 // if we need to initialize a fresh pdf loader
614 if (tmpBg_pdf!=NULL) {
615 while (bgpdf.status != STATUS_NOT_INIT) gtk_main_iteration();
616 if (tmpBg_pdf->file_domain == DOMAIN_ATTACH)
617 tmpfn = g_strdup_printf("%s.%s", filename, tmpBg_pdf->filename->s);
619 tmpfn = g_strdup(tmpBg_pdf->filename->s);
620 valid = init_bgpdf(tmpfn, FALSE, tmpBg_pdf->file_domain);
621 // in case the file name became invalid
622 if (!valid && tmpBg_pdf->file_domain != DOMAIN_ATTACH)
623 if (user_wants_second_chance(&tmpfn)) {
624 valid = init_bgpdf(tmpfn, FALSE, tmpBg_pdf->file_domain);
625 if (valid) { // change the file name...
626 g_free(tmpBg_pdf->filename->s);
627 tmpBg_pdf->filename->s = g_strdup(tmpfn);
631 refstring_unref(bgpdf.filename);
632 bgpdf.filename = refstring_ref(tmpBg_pdf->filename);
634 dialog = gtk_message_dialog_new(GTK_WINDOW(winMain), GTK_DIALOG_MODAL,
635 GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "Could not open background '%s'.",
637 gtk_dialog_run(GTK_DIALOG(dialog));
638 gtk_widget_destroy(dialog);
644 ui.cur_page = (struct Page *)journal.pages->data;
645 ui.layerno = ui.cur_page->nlayers-1;
646 ui.cur_layer = (struct Layer *)(g_list_last(ui.cur_page->layers)->data);
648 ui.zoom = DEFAULT_ZOOM;
649 update_file_name(g_strdup(filename));
650 gnome_canvas_set_pixels_per_unit(canvas, ui.zoom);
653 gtk_adjustment_set_value(gtk_layout_get_vadjustment(GTK_LAYOUT(canvas)), 0);
657 /************ file backgrounds *************/
659 struct Background *attempt_load_pix_bg(char *filename, gboolean attach)
661 struct Background *bg;
664 pix = gdk_pixbuf_new_from_file(filename, NULL);
665 if (pix == NULL) return NULL;
667 bg = g_new(struct Background, 1);
668 bg->type = BG_PIXMAP;
669 bg->canvas_item = NULL;
671 bg->pixbuf_scale = DEFAULT_ZOOM;
673 bg->filename = new_refstring(NULL);
674 bg->file_domain = DOMAIN_ATTACH;
676 bg->filename = new_refstring(filename);
677 bg->file_domain = DOMAIN_ABSOLUTE;
682 #define BUFSIZE 65536 // a reasonable buffer size for reads from gs pipe
684 GList *attempt_load_gv_bg(char *filename)
686 struct Background *bg;
689 GdkPixbufLoader *loader;
693 int buflen, remnlen, file_pageno;
695 buf = g_malloc(BUFSIZE); // a reasonable buffer size
696 f = fopen(filename, "r");
697 if (fread(buf, 1, 4, f) !=4 ||
698 (strncmp((char *)buf, "%!PS", 4) && strncmp((char *)buf, "%PDF", 4))) {
705 pipename = g_strdup_printf(GS_CMDLINE, (double)GS_BITMAP_DPI, filename);
706 gs_pipe = popen(pipename, "r");
714 while (!feof(gs_pipe)) {
715 if (!remnlen) { // new page: get a BMP header ?
716 buflen = fread(buf, 1, 54, gs_pipe);
717 if (buflen < 6) buflen += fread(buf, 1, 54-buflen, gs_pipe);
718 if (buflen < 6 || buf[0]!='B' || buf[1]!='M') break; // fatal: abort
719 remnlen = (int)(buf[5]<<24) + (buf[4]<<16) + (buf[3]<<8) + (buf[2]);
720 loader = gdk_pixbuf_loader_new();
722 else buflen = fread(buf, 1, (remnlen < BUFSIZE)?remnlen:BUFSIZE, gs_pipe);
724 if (buflen == 0) break;
725 if (!gdk_pixbuf_loader_write(loader, buf, buflen, NULL)) break;
726 if (remnlen == 0) { // make a new bg
727 pix = gdk_pixbuf_loader_get_pixbuf(loader);
728 if (pix == NULL) break;
730 gdk_pixbuf_loader_close(loader, NULL);
731 g_object_unref(loader);
733 bg = g_new(struct Background, 1);
734 bg->canvas_item = NULL;
736 bg->pixbuf_scale = (GS_BITMAP_DPI/72.0);
737 bg->type = BG_PIXMAP;
738 bg->filename = new_refstring(NULL);
739 bg->file_domain = DOMAIN_ATTACH;
741 bg_list = g_list_append(bg_list, bg);
744 if (loader != NULL) gdk_pixbuf_loader_close(loader, NULL);
750 struct Background *attempt_screenshot_bg(void)
752 struct Background *bg;
755 GError *error = NULL;
759 Window x_root, x_win;
761 x_root = gdk_x11_get_default_root_xwindow();
763 if (!XGrabButton(GDK_DISPLAY(), AnyButton, AnyModifier, x_root,
764 False, ButtonReleaseMask, GrabModeAsync, GrabModeSync, None, None))
767 XWindowEvent (GDK_DISPLAY(), x_root, ButtonReleaseMask, &x_event);
768 XUngrabButton(GDK_DISPLAY(), AnyButton, AnyModifier, x_root);
770 x_win = x_event.xbutton.subwindow;
771 if (x_win == None) x_win = x_root;
773 window = gdk_window_foreign_new_for_display(gdk_display_get_default(), x_win);
775 gdk_window_get_geometry(window, &x, &y, &w, &h, NULL);
777 pix = gdk_pixbuf_get_from_drawable(NULL, window,
778 gdk_colormap_get_system(), 0, 0, 0, 0, w, h);
780 if (pix == NULL) return NULL;
782 bg = g_new(struct Background, 1);
783 bg->type = BG_PIXMAP;
784 bg->canvas_item = NULL;
786 bg->pixbuf_scale = DEFAULT_ZOOM;
787 bg->filename = new_refstring(NULL);
788 bg->file_domain = DOMAIN_ATTACH;
792 /************** pdf annotation ***************/
794 /* free tmp directory */
796 void end_bgpdf_shutdown(void)
798 if (bgpdf.tmpdir!=NULL) {
799 if (bgpdf.tmpfile_copy!=NULL) {
800 g_unlink(bgpdf.tmpfile_copy);
801 g_free(bgpdf.tmpfile_copy);
802 bgpdf.tmpfile_copy = NULL;
804 g_rmdir(bgpdf.tmpdir);
805 g_free(bgpdf.tmpdir);
808 bgpdf.status = STATUS_NOT_INIT;
811 /* cancel a request */
813 void cancel_bgpdf_request(struct BgPdfRequest *req)
817 list_link = g_list_find(bgpdf.requests, req);
818 if (list_link == NULL) return;
819 if (list_link->prev == NULL && bgpdf.pid > 0) {
820 // this is being processed: kill the child but don't remove the request yet
821 if (bgpdf.status == STATUS_RUNNING) bgpdf.status = STATUS_ABORTED;
822 kill(bgpdf.pid, SIGHUP);
823 // printf("Cancelling a request - killing %d\n", bgpdf.pid);
826 // remove the request
827 bgpdf.requests = g_list_delete_link(bgpdf.requests, list_link);
829 // printf("Cancelling a request - no kill needed\n");
833 /* sigchld callback */
835 void bgpdf_child_handler(GPid pid, gint status, gpointer data)
837 struct BgPdfRequest *req;
838 struct BgPdfPage *bgpg;
842 if (bgpdf.requests == NULL) return;
843 req = (struct BgPdfRequest *)bgpdf.requests->data;
845 ppm_name = g_strdup_printf("%s/p-%06d.ppm", bgpdf.tmpdir, req->pageno);
846 // printf("Child %d finished, should look for %s... \n", pid, ppm_name);
848 if (bgpdf.status == STATUS_ABORTED || bgpdf.status == STATUS_SHUTDOWN)
851 pixbuf = gdk_pixbuf_new_from_file(ppm_name, NULL);
856 if (pixbuf != NULL) { // success
857 // printf("success\n");
858 while (req->pageno > bgpdf.npages) {
859 bgpg = g_new(struct BgPdfPage, 1);
861 bgpdf.pages = g_list_append(bgpdf.pages, bgpg);
864 bgpg = g_list_nth_data(bgpdf.pages, req->pageno-1);
865 if (bgpg->pixbuf!=NULL) gdk_pixbuf_unref(bgpg->pixbuf);
866 bgpg->pixbuf = pixbuf;
867 bgpg->dpi = req->dpi;
868 if (req->initial_request && bgpdf.create_pages) {
869 bgpdf_create_page_with_bg(req->pageno, bgpg);
870 // create page n, resize it, set its bg - all without any undo effect
872 if (!req->is_printing) bgpdf_update_bg(req->pageno, bgpg);
873 // look for all pages with this bg, and update their bg pixmaps
877 // printf("failed or aborted\n");
878 bgpdf.create_pages = FALSE;
879 req->initial_request = FALSE;
883 g_spawn_close_pid(pid);
885 if (req->initial_request)
886 req->pageno++; // try for next page
888 bgpdf.requests = g_list_delete_link(bgpdf.requests, bgpdf.requests);
890 if (bgpdf.status == STATUS_SHUTDOWN) {
891 end_bgpdf_shutdown();
895 bgpdf.status = STATUS_IDLE;
896 if (bgpdf.requests != NULL) bgpdf_spawn_child();
899 /* spawn a child to process the head request */
901 void bgpdf_spawn_child(void)
903 struct BgPdfRequest *req;
905 gchar pageno_str[10], dpi_str[10];
906 gchar *pdf_filename = bgpdf.tmpfile_copy;
907 gchar *ppm_root = g_strdup_printf("%s/p", bgpdf.tmpdir);
908 gchar *argv[]= PDFTOPPM_ARGV;
911 if (bgpdf.requests == NULL) return;
912 req = (struct BgPdfRequest *)bgpdf.requests->data;
913 if (req->pageno > bgpdf.npages+1 ||
914 (!req->initial_request && req->pageno <= bgpdf.npages &&
915 req->dpi == ((struct BgPdfPage *)g_list_nth_data(bgpdf.pages, req->pageno-1))->dpi))
916 { // ignore this request - it's redundant, or in outer space
918 bgpdf.status = STATUS_IDLE;
919 bgpdf.requests = g_list_delete_link(bgpdf.requests, bgpdf.requests);
921 if (bgpdf.requests != NULL) bgpdf_spawn_child();
924 g_snprintf(pageno_str, 10, "%d", req->pageno);
925 g_snprintf(dpi_str, 10, "%d", req->dpi);
926 /* printf("Processing request for page %d at %d dpi -- in %s\n",
927 req->pageno, req->dpi, ppm_root); */
928 if (!g_spawn_async(NULL, argv, NULL,
929 G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_SEARCH_PATH,
930 NULL, NULL, &pid, NULL))
932 // couldn't spawn... abort this request, try next one maybe ?
933 // printf("Couldn't spawn\n");
935 bgpdf.status = STATUS_IDLE;
936 bgpdf.requests = g_list_delete_link(bgpdf.requests, bgpdf.requests);
938 if (!bgpdf.has_failed) {
939 dialog = gtk_message_dialog_new(GTK_WINDOW(winMain), GTK_DIALOG_MODAL,
940 GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "Unable to start PDF loader %s.", argv[0]);
941 gtk_dialog_run(GTK_DIALOG(dialog));
942 gtk_widget_destroy(dialog);
944 bgpdf.has_failed = TRUE;
945 if (bgpdf.requests != NULL) bgpdf_spawn_child();
949 // printf("Spawned process %d\n", pid);
951 bgpdf.status = STATUS_RUNNING;
952 g_child_watch_add(pid, bgpdf_child_handler, NULL);
958 void add_bgpdf_request(int pageno, double zoom, gboolean printing)
960 struct BgPdfRequest *req, *cmp_req;
963 if (bgpdf.status == STATUS_NOT_INIT || bgpdf.status == STATUS_SHUTDOWN)
964 return; // don't accept requests in those modes...
965 req = g_new(struct BgPdfRequest, 1);
966 req->is_printing = printing;
967 if (printing) req->dpi = PDFTOPPM_PRINTING_DPI;
968 else req->dpi = (int)floor(72*zoom+0.5);
969 // printf("Enqueuing request for page %d at %d dpi\n", pageno, req->dpi);
971 // cancel any request this may supersede
972 for (list = bgpdf.requests; list != NULL; ) {
973 cmp_req = (struct BgPdfRequest *)list->data;
975 if (!cmp_req->initial_request && cmp_req->pageno == pageno &&
976 cmp_req->is_printing == printing)
977 cancel_bgpdf_request(cmp_req);
979 req->pageno = pageno;
980 req->initial_request = FALSE;
983 req->initial_request = TRUE;
985 bgpdf.requests = g_list_append(bgpdf.requests, req);
986 if (!bgpdf.pid) bgpdf_spawn_child();
989 /* shutdown the PDF reader */
991 void shutdown_bgpdf(void)
994 struct BgPdfPage *pdfpg;
995 struct BgPdfRequest *req;
997 if (bgpdf.status == STATUS_NOT_INIT || bgpdf.status == STATUS_SHUTDOWN) return;
998 refstring_unref(bgpdf.filename);
999 for (list = bgpdf.pages; list != NULL; list = list->next) {
1000 pdfpg = (struct BgPdfPage *)list->data;
1001 if (pdfpg->pixbuf!=NULL) gdk_pixbuf_unref(pdfpg->pixbuf);
1003 g_list_free(bgpdf.pages);
1004 bgpdf.status = STATUS_SHUTDOWN;
1005 for (list = g_list_last(bgpdf.requests); list != NULL; ) {
1006 req = (struct BgPdfRequest *)list->data;
1008 cancel_bgpdf_request(req);
1010 if (!bgpdf.pid) end_bgpdf_shutdown();
1011 /* The above will ultimately remove all requests and kill the child if needed.
1012 The child will set status to STATUS_NOT_INIT, clear the requests list,
1013 empty tmpdir, ... except if there's no child! */
1014 /* note: it could look like there's a race condition here - if a child
1015 terminates and a new request is enqueued while we are destroying the
1016 queue - but actually the child handler callback is NOT a signal
1017 callback, so execution of this function is atomic */
1020 gboolean init_bgpdf(char *pdfname, gboolean create_pages, int file_domain)
1026 if (bgpdf.status != STATUS_NOT_INIT) return FALSE;
1027 bgpdf.tmpfile_copy = NULL;
1028 bgpdf.tmpdir = mkdtemp(g_strdup(TMPDIR_TEMPLATE));
1029 if (!bgpdf.tmpdir) return FALSE;
1030 // make a local copy and check if it's a PDF
1031 if (!g_file_get_contents(pdfname, &filebuf, &filelen, NULL))
1032 { end_bgpdf_shutdown(); return FALSE; }
1033 if (filelen < 4 || strncmp(filebuf, "%PDF", 4))
1034 { g_free(filebuf); end_bgpdf_shutdown(); return FALSE; }
1035 bgpdf.tmpfile_copy = g_strdup_printf("%s/bg.pdf", bgpdf.tmpdir);
1036 f = fopen(bgpdf.tmpfile_copy, "w");
1037 if (f == NULL || fwrite(filebuf, 1, filelen, f) != filelen)
1038 { g_free(filebuf); end_bgpdf_shutdown(); return FALSE; }
1041 bgpdf.status = STATUS_IDLE;
1043 bgpdf.filename = new_refstring((file_domain == DOMAIN_ATTACH) ? "bg.pdf" : pdfname);
1044 bgpdf.file_domain = file_domain;
1047 bgpdf.requests = NULL;
1048 bgpdf.create_pages = create_pages;
1049 bgpdf.has_failed = FALSE;
1050 add_bgpdf_request(-1, DEFAULT_ZOOM, FALSE); // request all pages
1054 // create page n, resize it, set its bg
1055 void bgpdf_create_page_with_bg(int pageno, struct BgPdfPage *bgpg)
1058 struct Background *bg;
1060 if (journal.npages < pageno) {
1061 bg = g_new(struct Background, 1);
1062 bg->canvas_item = NULL;
1064 pg = (struct Page *)g_list_nth_data(journal.pages, pageno-1);
1066 if (bg->type != BG_SOLID) return;
1067 // don't mess with a page the user has modified significantly...
1071 bg->pixbuf = gdk_pixbuf_ref(bgpg->pixbuf);
1072 bg->filename = refstring_ref(bgpdf.filename);
1073 bg->file_domain = bgpdf.file_domain;
1074 bg->file_page_seq = pageno;
1075 bg->pixbuf_scale = DEFAULT_ZOOM;
1076 bg->pixbuf_dpi = bgpg->dpi;
1078 if (journal.npages < pageno) {
1079 pg = new_page_with_bg(bg,
1080 gdk_pixbuf_get_width(bg->pixbuf)*72.0/bg->pixbuf_dpi,
1081 gdk_pixbuf_get_height(bg->pixbuf)*72.0/bg->pixbuf_dpi);
1082 journal.pages = g_list_append(journal.pages, pg);
1085 pg->width = gdk_pixbuf_get_width(bgpg->pixbuf)*72.0/bg->pixbuf_dpi;
1086 pg->height = gdk_pixbuf_get_height(bgpg->pixbuf)*72.0/bg->pixbuf_dpi;
1087 make_page_clipbox(pg);
1088 update_canvas_bg(pg);
1090 update_page_stuff();
1093 // look for all journal pages with given pdf bg, and update their bg pixmaps
1094 void bgpdf_update_bg(int pageno, struct BgPdfPage *bgpg)
1099 for (list = journal.pages; list!= NULL; list = list->next) {
1100 pg = (struct Page *)list->data;
1101 if (pg->bg->type == BG_PDF && pg->bg->file_page_seq == pageno) {
1102 if (pg->bg->pixbuf!=NULL) gdk_pixbuf_unref(pg->bg->pixbuf);
1103 pg->bg->pixbuf = gdk_pixbuf_ref(bgpg->pixbuf);
1104 pg->bg->pixbuf_dpi = bgpg->dpi;
1105 update_canvas_bg(pg);