From fb1055dd92e9aa1173de92add6f4a6f5e4a62d2d Mon Sep 17 00:00:00 2001 From: Marco Pesenti Gritti Date: Wed, 22 Dec 2004 10:53:40 +0000 Subject: Import ggv backend. Not hooked up yet. 2004-12-22 Marco Pesenti Gritti * Makefile.am: * configure.ac: * ps/Makefile.am: * ps/ggvutils.c: * ps/ggvutils.h: * ps/gsdefaults.c: * ps/gsdefaults.h: * ps/gsio.c: * ps/gsio.h: * ps/gtkgs.c: * ps/gtkgs.h: * ps/ps.c: * ps/ps.h: Import ggv backend. Not hooked up yet. --- diff --git a/ChangeLog b/ChangeLog index df84885..3c66429 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,21 @@ +2004-12-22 Marco Pesenti Gritti + + * Makefile.am: + * configure.ac: + * ps/Makefile.am: + * ps/ggvutils.c: + * ps/ggvutils.h: + * ps/gsdefaults.c: + * ps/gsdefaults.h: + * ps/gsio.c: + * ps/gsio.h: + * ps/gtkgs.c: + * ps/gtkgs.h: + * ps/ps.c: + * ps/ps.h: + + Import ggv backend. Not hooked up yet. + 2004-12-22 Mark McLoughlin * shell/main.c: (load_files), (main): load files diff --git a/configure.ac b/configure.ac index d268d3f..ab87408 100644 --- a/configure.ac +++ b/configure.ac @@ -33,6 +33,7 @@ PKG_CHECK_MODULES(LIBEVPRIVATE, gtk+-2.0 >= 2.4.0) PKG_CHECK_MODULES(RECENT_FILES, gtk+-2.0 >= 2.4.0 libgnomeui-2.0 >= 2.4.0) PKG_CHECK_MODULES(SHELL, gtk+-2.0 >= 2.5.0 libgnomeui-2.0 gnome-vfs-2.0 libgnomeprint-2.2 libgnomeprintui-2.2 libglade-2.0) PKG_CHECK_MODULES(GTK, gtk+-2.0 >= 2.6.0) +PKG_CHECK_MODULES(PS, gtk+-2.0 >= 2.6.0 gnome-vfs-2.0 libgnomeui-2.0) GLIB_GENMARSHAL=`$PKG_CONFIG --variable=glib_genmarshal glib-2.0` AC_SUBST(GLIB_GENMARSHAL) @@ -272,6 +273,38 @@ AC_SUBST(FREETYPE_LIBS) dnl ================== End of xpdf checks =========================================== +dnl ================== ggv checks =================================================== +AC_ARG_WITH(gs-pkg, + [ --with-gs=dir Directory Where GhostScript package is installed.]) + +if test "x$with_gs" = "x"; then + AC_PATH_PROG(GS_PROG, gs) + if test -z "$GS_PROG"; then + AC_MSG_ERROR(Unable to find GhostScript in the PATH. Provide the full path for GhostScript(--with-gs=PATH). You need to have Ghostscript installed in order to run GGV) + fi +else + GS_PROG=$with_gs +fi + +AC_DEFINE_UNQUOTED(GS_PATH, "$GS_PROG", [Path to the 'gs' executable.]) + + +dnl check for GS version and define appropriate alpha parameters +AC_MSG_CHECKING(for Ghostscript version...) +GS_VERSION=`$GS_PROG --version | head -n 1` +AC_MSG_RESULT(found $GS_VERSION) +dnl GS tends to get a lot of BadMatch errors with the *AlphaBits parameters +dnl so I've commented their use out +dnl if test "$GS_VERSION" -gt "5"; then +dnl AA_PARMS="-sDEVICE=x11 -dTextAlphaBits=4 -dGraphicsAlphaBits=4" +dnl else +dnl AA_PARMS="-sDEVICE=x11alpha" +dnl fi +AA_PARMS="-sDEVICE=x11alpha -dNOPLATFONTS" +AC_DEFINE_UNQUOTED(ALPHA_PARAMS, "$AA_PARMS", [Anti-aliasing parameters for Ghostscript.]) +AC_MSG_RESULT(Antialiasing parameters for Ghostscript: $AA_PARMS) + + dnl Turn on the additional warnings last, so -Werror doesn't affect other tests. dnl stolen from nautilus and gnome-common @@ -324,7 +357,7 @@ else AC_MSG_RESULT(no) fi -dnl ========================================================================== +dnl ======================== End of ggv checks ================================= AC_OUTPUT([ Makefile @@ -336,6 +369,7 @@ pdf/goo/Makefile pdf/fofi/Makefile pdf/splash/Makefile pdf/xpdf/Makefile +ps/Makefile po/Makefile.in backend/Makefile shell/Makefile diff --git a/ps/Makefile.am b/ps/Makefile.am new file mode 100644 index 0000000..3c6fcf3 --- /dev/null +++ b/ps/Makefile.am @@ -0,0 +1,18 @@ +INCLUDES = \ + -I$(top_srcdir) \ + -DGNOMEICONDIR=\""${prefix}/${DATADIRNAME}/pixmaps"\" \ + $(PS_CFLAGS) + +noinst_LTLIBRARIES = libgtkgs.la + +libgtkgs_la_SOURCES = \ + gsio.c \ + gsio.h \ + gsdefaults.c \ + gsdefaults.h \ + ps.c \ + ps.h \ + ggvutils.c \ + ggvutils.h \ + gtkgs.c \ + gtkgs.h diff --git a/ps/ggvutils.c b/ps/ggvutils.c new file mode 100644 index 0000000..c79ec04 --- /dev/null +++ b/ps/ggvutils.c @@ -0,0 +1,348 @@ +/* + * ggv-utils.c: misc utility functions + * + * Copyright 2002 - 2005 The Free Software Foundation + * + * Author: Jaka Mocnik + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include "config.h" +#include +#include +#include + +#include +#include +#include + +#include + +#include "ggvutils.h" + +typedef struct { + char *stock_id; + char *name; +} GgvStockIcon; + +GtkGSPaperSize ggv_paper_sizes[] = { + {N_("BBox"), 0, 0}, + {N_("Letter"), 612, 792,}, + {N_("Tabloid"), 792, 1224,}, + {N_("Ledger"), 1224, 792,}, + {N_("Legal"), 612, 1008,}, + {N_("Statement"), 396, 612,}, + {N_("Executive"), 540, 720,}, + {N_("A0"), 2380, 3368,}, + {N_("A1"), 1684, 2380,}, + {N_("A2"), 1190, 1684,}, + {N_("A3"), 842, 1190,}, + {N_("A4"), 595, 842,}, + {N_("A5"), 420, 595,}, + {N_("B4"), 729, 1032,}, + {N_("B5"), 516, 729,}, + {N_("Folio"), 612, 936,}, + {N_("Quarto"), 610, 780,}, + {N_("10x14"), 720, 1008,}, + {NULL, 0, 0} +}; + +const gfloat ggv_unit_factors[] = { + 1.0, + 25.4, + 2.54, + 72.0 +}; + +const gchar *ggv_orientation_labels[] = { + N_("Portrait"), + N_("Landscape"), + N_("Upside Down"), + N_("Seascape"), + NULL, +}; + +const gint ggv_max_orientation_labels = + (sizeof(ggv_orientation_labels) / sizeof(gchar *)) - 2; + +const gchar *ggv_unit_labels[] = { + N_("inch"), + N_("mm"), + N_("cm"), + N_("point"), + NULL +}; + +const gint ggv_max_unit_labels = + (sizeof(ggv_unit_labels) / sizeof(gchar *)) - 2; + +gfloat ggv_zoom_levels[] = { + 1.0 / 6.0, 1.0 / 5.0, 1.0 / 4.0, 1.0 / 3.0, 1.0 / 2.0, 3.0 / 4.0, 1.0, + 3.0 / 2.0, 2.0, 3.0, 4.0, 5.0, 6.0 +}; + +const gchar *ggv_zoom_level_names[] = { + "1:6", "1:5", "1:4", "1:3", + "1:2", "3:4", "1:1", "3:2", + "2:1", "3:1", "4:1", "5:1", + "6:1", +}; + +const gint ggv_max_zoom_levels = (sizeof(ggv_zoom_levels) / sizeof(gfloat)) - 1; + +const gchar *ggv_auto_fit_modes[] = { + N_("None"), N_("Fit to page width"), N_("Fit to page size") +}; + +const gint ggv_max_auto_fit_modes = + (sizeof(ggv_auto_fit_modes) / sizeof(gchar *)) - 1; + +gint +ggv_zoom_index_from_float(gfloat zoom_level) +{ + int i; + + for(i = 0; i <= ggv_max_zoom_levels; i++) { + float this, epsilon; + + /* if we're close to a zoom level */ + this = ggv_zoom_levels[i]; + epsilon = this * 0.01; + + if(zoom_level < this + epsilon) + return i; + } + + return ggv_max_zoom_levels; +} + +gfloat +ggv_zoom_level_from_index(gint index) +{ + if(index > ggv_max_zoom_levels) + index = ggv_max_zoom_levels; + + return ggv_zoom_levels[index]; +} + +GSList * +ggv_split_string(const gchar * string, const gchar * delimiter) +{ + const gchar *ptr = string; + int pos = 0, escape = 0; + char buffer[BUFSIZ]; + GSList *list = NULL; + + g_return_val_if_fail(string != NULL, NULL); + g_return_val_if_fail(delimiter != NULL, NULL); + + while(*ptr) { + char c = *ptr++; + const gchar *d; + int found = 0; + + if(pos >= BUFSIZ) { + g_warning("string too long, aborting"); + return list; + } + + if(escape) { + buffer[pos++] = c; + escape = 0; + continue; + } + + if(c == '\\') { + escape = 1; + continue; + } + + for(d = delimiter; *d; d++) { + if(c == *d) { + buffer[pos++] = 0; + list = g_slist_prepend(list, g_strdup(buffer)); + pos = 0; + found = 1; + break; + } + } + + if(!found) + buffer[pos++] = c; + } + + buffer[pos++] = 0; + list = g_slist_prepend(list, g_strdup(buffer)); + + return list; +} + +gint +ggv_get_index_of_string(gchar * string, gchar ** strings) +{ + guint idx = 0; + + while(strings[idx] != NULL) { + if(strcmp(strings[idx], string) == 0) + return idx; + idx++; + } + + return -1; +} + +/* Quote filename for system call */ +gchar * +ggv_quote_filename(const gchar * str) +{ + return g_shell_quote(str); +} + +/* escapes filename to form a proper URI: works conservatively - anything + except [a-zA-Z0-9_] will be escaped with a %XX escape sequence where + XX is the hex value of the char. */ +gchar * +ggv_filename_to_uri(const gchar * fname) +{ + gchar *full_path, *ret_val; + + if(*fname != '/') { + gchar *cwd; + /* relative file name - we will have to absolutize it */ + cwd = g_get_current_dir(); + full_path = g_strconcat(cwd, "/", fname, NULL); + } + else + full_path = NULL; + ret_val = gnome_vfs_get_uri_from_local_path(full_path ? full_path : fname); + if(full_path) + g_free(full_path); + return ret_val; +} + +/* If file exists and is a regular file then return its length, else -1 */ +gint +ggv_file_length(const gchar * filename) +{ + struct stat stat_rec; + + if(filename && (stat(filename, &stat_rec) == 0) + && S_ISREG(stat_rec.st_mode)) + return stat_rec.st_size; + else + return -1; +} + +/* Test if file exists, is a regular file and its length is > 0 */ +gboolean +ggv_file_readable(const char *filename) +{ + return (ggv_file_length(filename) > 0); +} + +/* Set a tooltip for a widget */ +void +ggv_set_tooltip(GtkWidget * w, const gchar * tip) +{ + GtkTooltips *t = gtk_tooltips_new(); + + gtk_tooltips_set_tip(t, w, tip, NULL); +} + +gfloat +ggv_compute_zoom(gint zoom_spec) +{ + return pow(1.2, zoom_spec); /* The Knuth magstep formula rules */ +} + +gint +ggv_compute_spec(gfloat zoom) +{ + zoom = MAX(0.02, zoom); + zoom = MIN(10.0, zoom); + + zoom = log(zoom) / log(1.2); + return (gint) rint(zoom); +} + +void +ggv_raise_and_focus_widget(GtkWidget * widget) +{ + g_assert(GTK_WIDGET_REALIZED(widget)); + gdk_window_raise(widget->window); + gtk_widget_grab_focus(widget); +} + +void +ggv_get_window_size(GtkWidget * widget, gint * width, gint * height) +{ + *width = widget->allocation.width; + *height = widget->allocation.height; +} + +static GgvStockIcon items[] = { + {GGV_CLEAR_ALL, GNOMEICONDIR "/ggv/clearall.xpm"}, + {GGV_TOGGLE_ALL, GNOMEICONDIR "/ggv/toggleall.xpm"}, + {GGV_TOGGLE_EVEN, GNOMEICONDIR "/ggv/toggleeven.xpm"}, + {GGV_TOGGLE_ODD, GNOMEICONDIR "/ggv/toggleodd.xpm"}, + {GGV_FIT_WIDTH, GNOMEICONDIR "/ggv/fitwidth.png"}, + {GGV_ZOOM, GNOMEICONDIR "/ggv/zoom.xpm"} +}; + +static void +ggv_register_stock_icons(GtkIconFactory * factory) +{ + gint i; + GtkIconSource *source; + + source = gtk_icon_source_new(); + + for(i = 0; i < G_N_ELEMENTS(items); ++i) { + GtkIconSet *icon_set; + + if(!g_file_test(items[i].name, G_FILE_TEST_EXISTS)) { + g_warning(_("Unable to load ggv stock icon '%s'\n"), items[i].name); + icon_set = gtk_icon_factory_lookup_default(GTK_STOCK_MISSING_IMAGE); + gtk_icon_factory_add(factory, items[i].stock_id, icon_set); + continue; + } + + gtk_icon_source_set_filename(source, items[i].name); + + icon_set = gtk_icon_set_new(); + gtk_icon_set_add_source(icon_set, source); + gtk_icon_factory_add(factory, items[i].stock_id, icon_set); + gtk_icon_set_unref(icon_set); + } + gtk_icon_source_free(source); +} + +void +ggv_init_stock_icons(void) +{ + GtkIconFactory *factory; + static gboolean initialized = FALSE; + + if(initialized) + return; + initialized = TRUE; + + factory = gtk_icon_factory_new(); + gtk_icon_factory_add_default(factory); + ggv_register_stock_icons(factory); + + g_object_unref(factory); +} diff --git a/ps/ggvutils.h b/ps/ggvutils.h new file mode 100644 index 0000000..92aecf8 --- /dev/null +++ b/ps/ggvutils.h @@ -0,0 +1,85 @@ +/* + * ggvutils.h: misc utility functions + * + * Copyright 2002 - 2005 the Free Software Foundation + * + * Author: Jaka Mocnik + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef __GGV_UTILS_H__ +#define __GGV_UTILS_H__ + +#include + +#include + +/*Define StockIds*/ +#define GGV_CLEAR_ALL "ggv-clear-all" +#define GGV_TOGGLE_ALL "ggv-toggle-all" +#define GGV_TOGGLE_EVEN "ggv-toggle-even" +#define GGV_TOGGLE_ODD "ggv-toggle-odd" +#define GGV_FIT_WIDTH "ggv-fit-width" +#define GGV_ZOOM "ggv-zoom" + +extern GtkGSPaperSize ggv_paper_sizes[]; +extern const gchar *ggv_orientation_labels[]; +extern const gint ggv_max_orientation_labels; +extern const gfloat ggv_unit_factors[]; +extern const gchar *ggv_unit_labels[]; +extern const gint ggv_max_unit_labels; +extern gfloat ggv_zoom_levels[]; +extern const gchar *ggv_zoom_level_names[]; +extern const gint ggv_max_zoom_levels; +extern const gchar *ggv_auto_fit_modes[]; +extern const gint ggv_max_auto_fit_modes; + +/* zoom level index <-> zoom factor */ +gint ggv_zoom_index_from_float(gfloat zoom_level); +gfloat ggv_zoom_level_from_index(gint index); + +/* Split delimited string into a list of strings. */ +GSList *ggv_split_string(const gchar * string, const gchar * delimiter); + +/* Get index of a string from a list of them. */ +gint ggv_get_index_of_string(gchar * string, gchar ** strings); + +/* Quote filename for system call */ +gchar *ggv_quote_filename(const gchar * str); + +/* escape filename to conform to URI specification */ +gchar *ggv_filename_to_uri(const gchar * fname); + +/* If file exists and is a regular file then return its length, else -1 */ +gint ggv_file_length(const gchar * filename); + +/* Test if file exists, is a regular file and its length is > 0 */ +gboolean ggv_file_readable(const char *filename); + +/* Set a tooltip for a widget */ +void ggv_set_tooltip(GtkWidget * w, const gchar * tip); + +/* zoom <-> magstep (currently not used...) */ +gfloat ggv_compute_zoom(gint zoom_spec); +gint ggv_compute_spec(gfloat zoom); + +void ggv_raise_and_focus_widget(GtkWidget * widget); + +void ggv_get_window_size(GtkWidget * widget, gint * width, gint * height); + +void ggv_init_stock_icons(void); + +#endif /* __GGV_UTILS_H__ */ diff --git a/ps/gsdefaults.c b/ps/gsdefaults.c new file mode 100644 index 0000000..d5d2fbb --- /dev/null +++ b/ps/gsdefaults.c @@ -0,0 +1,505 @@ +/* + * gsdefaults.c: default settings for the GtkGS widget + * + * Copyright 2002 - 2005 the Free Software Foundation + * + * Author: Jaka Mocnik + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include + +#include +#include + +#include "gtkgs.h" +#include "gsdefaults.h" +#include "ggvutils.h" + +#include + +/** + * defaults for GtkGS widgets + **/ + +static GConfClient *gconf_client; + +/* Default values to pass to gtk_gs_init */ +typedef struct _GtkGSDefaults { + gboolean antialiased; + gboolean override_size; + gint default_size; + gboolean override_orientation; + gboolean respect_eof; + gboolean show_scroll_rect; + gint fallback_orientation; + gfloat zoom_factor; + gfloat scroll_step; + gchar *interpreter_cmd; + gchar *alpha_params; + gchar *dsc_cmd; + gchar *convert_pdf_cmd; + gchar *ungzip_cmd; + gchar *unbzip2_cmd; + GtkGSZoomMode zoom_mode; +} GtkGSDefaults; + +static GtkGSDefaults gtk_gs_defaults = { + TRUE, FALSE, 8, FALSE, TRUE, TRUE, + 0, 1.0, 0.25, NULL, NULL, NULL, NULL, NULL, NULL, + GTK_GS_ZOOM_ABSOLUTE +}; + +void +gtk_gs_defaults_set_scroll_step(gfloat step) +{ + if(fabs(gtk_gs_defaults.scroll_step - step) > 0.001) { + gtk_gs_defaults.scroll_step = step; + gconf_client_set_float(gconf_client, + "/apps/ggv/gtkgs/scrollstep", + gtk_gs_defaults_get_scroll_step(), NULL); + } +} + +gfloat +gtk_gs_defaults_get_scroll_step() +{ + return gtk_gs_defaults.scroll_step; +} + +void +gtk_gs_defaults_set_size(gint iNewPageSize) +{ + if(gtk_gs_defaults.default_size != iNewPageSize) { + gtk_gs_defaults.default_size = iNewPageSize; + gconf_client_set_int(gconf_client, "/apps/ggv/gtkgs/size", + gtk_gs_defaults_get_size(), NULL); + } +} + +gint +gtk_gs_defaults_get_size() +{ + return gtk_gs_defaults.default_size; +} + +void +gtk_gs_defaults_set_override_size(gboolean bOverrSize) +{ + if(gtk_gs_defaults.override_size != bOverrSize) { + gtk_gs_defaults.override_size = bOverrSize; + gconf_client_set_bool(gconf_client, + "/apps/ggv/gtkgs/override_size", + gtk_gs_defaults_get_override_size(), NULL); + } +} + +gboolean +gtk_gs_defaults_get_override_size() +{ + return gtk_gs_defaults.override_size; +} + +void +gtk_gs_defaults_set_override_orientation(gboolean bOverOrien) +{ + if(gtk_gs_defaults.override_orientation != bOverOrien) { + gtk_gs_defaults.override_orientation = bOverOrien; + gconf_client_set_bool(gconf_client, + "/apps/ggv/gtkgs/override_orientation", + gtk_gs_defaults_get_override_orientation(), NULL); + } +} + +gboolean +gtk_gs_defaults_get_override_orientation() +{ + return gtk_gs_defaults.override_orientation; +} + +void +gtk_gs_defaults_set_antialiased(gint iNewAntialiased) +{ + if(gtk_gs_defaults.antialiased != iNewAntialiased) { + gtk_gs_defaults.antialiased = iNewAntialiased; + gconf_client_set_bool(gconf_client, + "/apps/ggv/gtkgs/antialiasing", + gtk_gs_defaults_get_antialiased(), NULL); + } +} + +gboolean +gtk_gs_defaults_get_antialiased() +{ + return gtk_gs_defaults.antialiased; +} + +void +gtk_gs_defaults_set_zoom_factor(gfloat fZoom) +{ + fZoom = MIN(fZoom, 30.0); + fZoom = MAX(0.05, fZoom); + if(fabs(gtk_gs_defaults.zoom_factor - fZoom) > 0.001) { + gtk_gs_defaults.zoom_factor = fZoom; + gconf_client_set_float(gconf_client, "/apps/ggv/gtkgs/zoom", + gtk_gs_defaults_get_zoom_factor(), NULL); + } +} + +gfloat +gtk_gs_defaults_get_zoom_factor() +{ + return gtk_gs_defaults.zoom_factor; +} + +void +gtk_gs_defaults_set_orientation(gint iNewOrientation) +{ + g_assert((iNewOrientation == GTK_GS_ORIENTATION_PORTRAIT) || + (iNewOrientation == GTK_GS_ORIENTATION_LANDSCAPE) || + (iNewOrientation == GTK_GS_ORIENTATION_UPSIDEDOWN) || + (iNewOrientation == GTK_GS_ORIENTATION_SEASCAPE)); + if(gtk_gs_defaults.fallback_orientation != iNewOrientation) { + gtk_gs_defaults.fallback_orientation = iNewOrientation; + gconf_client_set_int(gconf_client, + "/apps/ggv/gtkgs/orientation", + gtk_gs_defaults_get_orientation(), NULL); + } +} + +gint +gtk_gs_defaults_get_orientation() +{ + return gtk_gs_defaults.fallback_orientation; +} + +void +gtk_gs_defaults_set_respect_eof(gboolean resp) +{ + if(gtk_gs_defaults.respect_eof != resp) { + gtk_gs_defaults.respect_eof = resp; + gconf_client_set_bool(gconf_client, + "/apps/ggv/gtkgs/respect_eof", + gtk_gs_defaults_get_respect_eof(), NULL); + } +} + +gboolean +gtk_gs_defaults_get_respect_eof() +{ + return gtk_gs_defaults.respect_eof; +} + +GtkGSPaperSize * +gtk_gs_defaults_get_paper_sizes() +{ + return ggv_paper_sizes; +} + +gint +gtk_gs_defaults_get_paper_count() +{ + gint n = 0; + + while(ggv_paper_sizes[n].name != NULL) + n++; + + return n; +} + +gboolean +gtk_gs_defaults_get_show_scroll_rect() +{ + return gtk_gs_defaults.show_scroll_rect; +} + +void +gtk_gs_defaults_set_show_scroll_rect(gboolean f) +{ + if(gtk_gs_defaults.show_scroll_rect != f) { + gtk_gs_defaults.show_scroll_rect = f; + gconf_client_set_bool(gconf_client, + "/apps/ggv/gtkgs/show_scroll_rect", + gtk_gs_defaults_get_show_scroll_rect(), NULL); + } +} + +const gchar * +gtk_gs_defaults_get_interpreter_cmd() +{ + if(!gtk_gs_defaults.interpreter_cmd) + return GS_PATH; + return gtk_gs_defaults.interpreter_cmd; +} + +const gchar * +gtk_gs_defaults_get_alpha_parameters() +{ + if(!gtk_gs_defaults.alpha_params) + return ALPHA_PARAMS; + return gtk_gs_defaults.alpha_params; +} + +const gchar * +gtk_gs_defaults_get_convert_pdf_cmd() +{ + if(!gtk_gs_defaults.convert_pdf_cmd) + return GS_PATH + " -q -dNOPAUSE -dBATCH -dSAFER" + " -dQUIET -sDEVICE=pswrite" " -sOutputFile=%s -c save pop -f %s"; + return gtk_gs_defaults.convert_pdf_cmd; +} + +const gchar * +gtk_gs_defaults_get_dsc_cmd() +{ + if(!gtk_gs_defaults.dsc_cmd) + return GS_PATH + " -q -dNODISPLAY -dSAFER -dDELAYSAFER" + " -sDSCname=%s -sPDFname=%s pdf2dsc.ps" " -c quit"; + return gtk_gs_defaults.dsc_cmd; +} + +const gchar * +gtk_gs_defaults_get_ungzip_cmd() +{ + if(!gtk_gs_defaults.ungzip_cmd) + return "gzip -cd"; + return gtk_gs_defaults.ungzip_cmd; +} + +const gchar * +gtk_gs_defaults_get_unbzip2_cmd() +{ + if(!gtk_gs_defaults.unbzip2_cmd) + return "bzip2 -cd"; + return gtk_gs_defaults.unbzip2_cmd; +} + +void +gtk_gs_defaults_set_interpreter_cmd(gchar * cmd) +{ + if((NULL == gtk_gs_defaults.interpreter_cmd) || + strcmp(gtk_gs_defaults.interpreter_cmd, cmd)) { + if(gtk_gs_defaults.interpreter_cmd) + g_free(gtk_gs_defaults.interpreter_cmd); + gtk_gs_defaults.interpreter_cmd = cmd; + gconf_client_set_string(gconf_client, + "/apps/ggv/gtkgs/interpreter", + gtk_gs_defaults_get_interpreter_cmd(), NULL); + } +} + +void +gtk_gs_defaults_set_alpha_parameters(gchar * par) +{ + if((NULL == gtk_gs_defaults.alpha_params) || + strcmp(gtk_gs_defaults.alpha_params, par)) { + if(gtk_gs_defaults.alpha_params) + g_free(gtk_gs_defaults.alpha_params); + gtk_gs_defaults.alpha_params = par; + gconf_client_set_string(gconf_client, + "/apps/ggv/gtkgs/alphaparams", + gtk_gs_defaults_get_alpha_parameters(), NULL); + } +} + +void +gtk_gs_defaults_set_convert_pdf_cmd(gchar * cmd) +{ + if((NULL == gtk_gs_defaults.convert_pdf_cmd) || + strcmp(gtk_gs_defaults.convert_pdf_cmd, cmd)) { + if(gtk_gs_defaults.convert_pdf_cmd) + g_free(gtk_gs_defaults.convert_pdf_cmd); + gtk_gs_defaults.convert_pdf_cmd = cmd; + gconf_client_set_string(gconf_client, + "/apps/ggv/gtkgs/convertpdf", + gtk_gs_defaults_get_convert_pdf_cmd(), NULL); + } +} + +void +gtk_gs_defaults_set_dsc_cmd(gchar * cmd) +{ + if((NULL == gtk_gs_defaults.dsc_cmd) || strcmp(gtk_gs_defaults.dsc_cmd, cmd)) { + if(gtk_gs_defaults.dsc_cmd) + g_free(gtk_gs_defaults.dsc_cmd); + gtk_gs_defaults.dsc_cmd = cmd; + gconf_client_set_string(gconf_client, + "/apps/ggv/gtkgs/pdf2dsc", + gtk_gs_defaults_get_dsc_cmd(), NULL); + } +} + +void +gtk_gs_defaults_set_ungzip_cmd(gchar * cmd) +{ + if((NULL == gtk_gs_defaults.ungzip_cmd) || + strcmp(gtk_gs_defaults.ungzip_cmd, cmd)) { + if(gtk_gs_defaults.ungzip_cmd) + g_free(gtk_gs_defaults.ungzip_cmd); + gtk_gs_defaults.ungzip_cmd = cmd; + gconf_client_set_string(gconf_client, + "/apps/ggv/gtkgs/ungzip", + gtk_gs_defaults_get_ungzip_cmd(), NULL); + } +} + +void +gtk_gs_defaults_set_unbzip2_cmd(gchar * cmd) +{ + if((NULL == gtk_gs_defaults.unbzip2_cmd) || + strcmp(gtk_gs_defaults.unbzip2_cmd, cmd)) { + if(gtk_gs_defaults.unbzip2_cmd) + g_free(gtk_gs_defaults.unbzip2_cmd); + gtk_gs_defaults.unbzip2_cmd = cmd; + gconf_client_set_string(gconf_client, + "/apps/ggv/gtkgs/unbzip2", + gtk_gs_defaults_get_unbzip2_cmd(), NULL); + } +} + +GtkGSZoomMode +gtk_gs_defaults_get_zoom_mode() +{ + return gtk_gs_defaults.zoom_mode; +} + +void +gtk_gs_defaults_set_zoom_mode(GtkGSZoomMode zoom_mode) +{ + if(gtk_gs_defaults.zoom_mode != zoom_mode) { + gtk_gs_defaults.zoom_mode = zoom_mode; + gconf_client_set_int(gconf_client, "/apps/ggv/gtkgs/zoommode", + gtk_gs_defaults_get_zoom_mode(), NULL); + } +} + +void +gtk_gs_defaults_load() +{ + gtk_gs_defaults_gconf_client(); + + gtk_gs_defaults.respect_eof = + (gconf_client_get_bool(gconf_client, "/apps/ggv/gtkgs/respect_eof", NULL)); + gtk_gs_defaults.override_size = + (gconf_client_get_bool(gconf_client, "/apps/ggv/gtkgs/override_size", + NULL)); + gtk_gs_defaults.override_orientation = + (gconf_client_get_bool + (gconf_client, "/apps/ggv/gtkgs/override_orientation", NULL)); + gtk_gs_defaults.antialiased = + (gconf_client_get_bool(gconf_client, "/apps/ggv/gtkgs/antialiasing", NULL)); + gtk_gs_defaults.default_size = + (gconf_client_get_int(gconf_client, "/apps/ggv/gtkgs/size", NULL)); + gtk_gs_defaults.zoom_factor = + (gconf_client_get_float(gconf_client, "/apps/ggv/gtkgs/zoom", NULL)); + gtk_gs_defaults.fallback_orientation = + (gconf_client_get_int(gconf_client, "/apps/ggv/gtkgs/orientation", NULL)); + gtk_gs_defaults.interpreter_cmd = + (gconf_client_get_string + (gconf_client, "/apps/ggv/gtkgs/interpreter", NULL)); + gtk_gs_defaults.alpha_params = + (gconf_client_get_string + (gconf_client, "/apps/ggv/gtkgs/alphaparams", NULL)); + gtk_gs_defaults.convert_pdf_cmd = + (gconf_client_get_string(gconf_client, "/apps/ggv/gtkgs/convertpdf", NULL)); + gtk_gs_defaults.dsc_cmd = + (gconf_client_get_string(gconf_client, "/apps/ggv/gtkgs/pdf2dsc", NULL)); + gtk_gs_defaults.ungzip_cmd = + (gconf_client_get_string(gconf_client, "/apps/ggv/gtkgs/ungzip", NULL)); + gtk_gs_defaults.unbzip2_cmd = + (gconf_client_get_string(gconf_client, "/apps/ggv/gtkgs/unbzip2", NULL)); + gtk_gs_defaults.show_scroll_rect = + (gconf_client_get_bool + (gconf_client, "/apps/ggv/gtkgs/show_scroll_rect", NULL)); + gtk_gs_defaults.scroll_step = + (gconf_client_get_float(gconf_client, "/apps/ggv/gtkgs/scrollstep", NULL)); + gtk_gs_defaults.zoom_mode = + (gconf_client_get_int(gconf_client, "/apps/ggv/gtkgs/zoommode", NULL)); +} + +static void +gtk_gs_defaults_changed(GConfClient * client, guint cnxn_id, + GConfEntry * entry, gpointer user_data) +{ + if(!strcmp(entry->key, "/apps/ggv/gtkgs/respect_eof")) + gtk_gs_defaults_set_respect_eof + (gconf_client_get_bool(client, "/apps/ggv/gtkgs/respect_eof", NULL)); + else if(!strcmp(entry->key, "/apps/ggv/gtkgs/override_orientation")) + gtk_gs_defaults_set_override_orientation + (gconf_client_get_bool(client, "/apps/ggv/gtkgs/override_orientation", + NULL)); + else if(!strcmp(entry->key, "/apps/ggv/gtkgs/orientation")) + gtk_gs_defaults_set_orientation + (gconf_client_get_int(client, "/apps/ggv/gtkgs/orientation", NULL)); + else if(!strcmp(entry->key, "/apps/ggv/gtkgs/zoom")) + gtk_gs_defaults_set_zoom_factor + (gconf_client_get_float(client, "/apps/ggv/gtkgs/zoom", NULL)); + else if(!strcmp(entry->key, "/apps/ggv/gtkgs/size")) + gtk_gs_defaults_set_size + (gconf_client_get_int(client, "/apps/ggv/gtkgs/size", NULL)); + else if(!strcmp(entry->key, "/apps/ggv/gtkgs/antialiasing")) + gtk_gs_defaults_set_antialiased + (gconf_client_get_bool(client, "/apps/ggv/gtkgs/antialiasing", NULL)); + else if(!strcmp(entry->key, "/apps/ggv/gtkgs/override_size")) + gtk_gs_defaults_set_override_size + (gconf_client_get_bool(client, "/apps/ggv/gtkgs/override_size", NULL)); + else if(!strcmp(entry->key, "/apps/ggv/gtkgs/show_scroll_rect")) + gtk_gs_defaults_set_show_scroll_rect + (gconf_client_get_bool(client, "/apps/ggv/gtkgs/show_scroll_rect", NULL)); + else if(!strcmp(entry->key, "/apps/ggv/gtkgs/interpreter")) + gtk_gs_defaults_set_interpreter_cmd + (gconf_client_get_string(client, "/apps/ggv/gtkgs/interpreter", NULL)); + else if(!strcmp(entry->key, "/apps/ggv/gtkgs/alphaparams")) + gtk_gs_defaults_set_alpha_parameters + (gconf_client_get_string(client, "/apps/ggv/gtkgs/alphaparams", NULL)); + else if(!strcmp(entry->key, "/apps/ggv/gtkgs/convertpdf")) + gtk_gs_defaults_set_convert_pdf_cmd + (gconf_client_get_string(client, "/apps/ggv/gtkgs/convertpdf", NULL)); + else if(!strcmp(entry->key, "/apps/ggv/gtkgs/pdf2dsc")) + gtk_gs_defaults_set_dsc_cmd + (gconf_client_get_string(client, "/apps/ggv/gtkgs/pdf2dsc", NULL)); + else if(!strcmp(entry->key, "/apps/ggv/gtkgs/ungzip")) + gtk_gs_defaults_set_ungzip_cmd + (gconf_client_get_string(client, "/apps/ggv/gtkgs/ungzip", NULL)); + else if(!strcmp(entry->key, "/apps/ggv/gtkgs/unbzip2")) + gtk_gs_defaults_set_unbzip2_cmd + (gconf_client_get_string(client, "/apps/ggv/gtkgs/unbzip2", NULL)); + else if(!strcmp(entry->key, "/apps/ggv/gtkgs/zoommode")) + gtk_gs_defaults_set_zoom_mode + (gconf_client_get_int(client, "/apps/ggv/gtkgs/zoommode", NULL)); + else if(!strcmp(entry->key, "/apps/ggv/gtkgs/scrollstep")) + gtk_gs_defaults_set_scroll_step + (gconf_client_get_float(client, "/apps/ggv/gtkgs/scrollstep", NULL)); +} + +GConfClient * +gtk_gs_defaults_gconf_client() +{ + if(!gconf_client) { + g_assert(gconf_is_initialized()); + gconf_client = gconf_client_get_default(); + g_assert(gconf_client != NULL); + gconf_client_add_dir(gconf_client, "/apps/ggv/gtkgs", + GCONF_CLIENT_PRELOAD_RECURSIVE, NULL); + gconf_client_notify_add(gconf_client, + "/apps/ggv/gtkgs", (GConfClientNotifyFunc) + gtk_gs_defaults_changed, NULL, NULL, NULL); + } + + return gconf_client; +} diff --git a/ps/gsdefaults.h b/ps/gsdefaults.h new file mode 100644 index 0000000..bec907f --- /dev/null +++ b/ps/gsdefaults.h @@ -0,0 +1,72 @@ +/* + * gsdefaults.h: default settings of a GtkGS widget. + * + * Copyright 2002 - 2005 the Free Software Foundation + * + * Author: Jaka Mocnik + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. + */ +#ifndef __GS_DEFAULTS_H__ +#define __GS_DEFAULTS_H__ + +#include + +G_BEGIN_DECLS + +/* defaults accessors */ +void gtk_gs_defaults_set_size(gint iNewPageSize); +void gtk_gs_defaults_set_override_size(gboolean bOverrSize); +void gtk_gs_defaults_set_antialiased(gint iNewAntialiased); +void gtk_gs_defaults_set_orientation(gint); +void gtk_gs_defaults_set_override_orientation(gboolean bOverOrien); +void gtk_gs_defaults_set_zoom_factor(gfloat fZoom); +void gtk_gs_defaults_set_respect_eof(gboolean resp); +void gtk_gs_defaults_set_scroll_step(gfloat step); +void gtk_gs_defaults_set_show_scroll_rect(gboolean f); +gint gtk_gs_defaults_get_size(void); +gboolean gtk_gs_defaults_get_override_size(void); +gboolean gtk_gs_defaults_get_antialiased(void); +gint gtk_gs_defaults_get_orientation(void); +gboolean gtk_gs_defaults_get_override_orientation(void); +gfloat gtk_gs_defaults_get_zoom_factor(void); +gboolean gtk_gs_defaults_get_respect_eof(void); +gint gtk_gs_defaults_get_paper_count(void); +gfloat gtk_gs_defaults_get_scroll_step(void); +gboolean gtk_gs_defaults_get_show_scroll_rect(void); +GtkGSPaperSize *gtk_gs_defaults_get_paper_sizes(void); +const gchar *gtk_gs_defaults_get_interpreter_cmd(void); +const gchar *gtk_gs_defaults_get_convert_pdf_cmd(void); +const gchar *gtk_gs_defaults_get_dsc_cmd(void); +const gchar *gtk_gs_defaults_get_ungzip_cmd(void); +const gchar *gtk_gs_defaults_get_unbzip2_cmd(void); +const gchar *gtk_gs_defaults_get_alpha_parameters(void); +void gtk_gs_defaults_set_interpreter_cmd(gchar *); +void gtk_gs_defaults_set_convert_pdf_cmd(gchar *); +void gtk_gs_defaults_set_dsc_cmd(gchar *); +void gtk_gs_defaults_set_ungzip_cmd(gchar *); +void gtk_gs_defaults_set_unbzip2_cmd(gchar *); +void gtk_gs_defaults_set_alpha_parameters(gchar *); +GtkGSZoomMode gtk_gs_defaults_get_zoom_mode(void); +void gtk_gs_defaults_set_zoom_mode(GtkGSZoomMode zoom_mode); + +/* prefs IO */ +void gtk_gs_defaults_load(void); + +GConfClient *gtk_gs_defaults_gconf_client(void); + +G_END_DECLS + +#endif /* __GS_DEFAULTS_H__ */ diff --git a/ps/gsio.c b/ps/gsio.c new file mode 100644 index 0000000..15c7f38 --- /dev/null +++ b/ps/gsio.c @@ -0,0 +1,172 @@ +/* + * gsio.c: an IO abstraction + * + * Copyright 2002 - 2005 the Free Software Foundation + * + * Author: Jaka Mocnik + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include + +#include + +#define CHUNK_SIZE 32768 + +typedef struct _GtkGSDocChunk GtkGSDocChunk; +struct _GtkGSDocChunk { + gchar *buf, *ptr; + guint len, max_len; +}; + +struct _GtkGSDocSink { + GSList *chunks; + GtkGSDocChunk *tail; +}; + +static GtkGSDocChunk * +gtk_gs_doc_chunk_new(guint size) +{ + GtkGSDocChunk *c; + + c = g_new0(GtkGSDocChunk, 1); + if((c->buf = g_malloc(sizeof(gchar) * size)) == NULL) { + g_free(c); + return NULL; + } + c->ptr = c->buf; + *c->ptr = '\0'; + c->max_len = size; + c->len = 0; + return c; +} + +static void +gtk_gs_doc_chunk_free(GtkGSDocChunk * c) +{ + if(c->buf) + g_free(c->buf); + g_free(c); +} + +GtkGSDocSink * +gtk_gs_doc_sink_new() +{ + GtkGSDocSink *sink; + + sink = g_new0(GtkGSDocSink, 1); + return sink; +} + +void +gtk_gs_doc_sink_free(GtkGSDocSink * sink) +{ + GSList *node; + + node = sink->chunks; + while(node) { + gtk_gs_doc_chunk_free((GtkGSDocChunk *) node->data); + node = node->next; + } + g_slist_free(sink->chunks); +} + +void +gtk_gs_doc_sink_write(GtkGSDocSink * sink, const gchar * buf, int len) +{ + gint real_len; + + if(sink->tail == NULL) { + sink->tail = gtk_gs_doc_chunk_new(CHUNK_SIZE); + sink->chunks = g_slist_append(sink->chunks, sink->tail); + } + + real_len = MIN(sink->tail->max_len - sink->tail->len, len); + if(real_len > 0) { + strncpy(sink->tail->ptr, buf, real_len); + sink->tail->ptr += real_len; + sink->tail->len += real_len; + } + len -= real_len; + if(len > 0) { + sink->tail = NULL; + gtk_gs_doc_sink_write(sink, buf + real_len, len); + } +} + +void +gtk_gs_doc_sink_printf_v(GtkGSDocSink * sink, const gchar * fmt, va_list ap) +{ + gint max_len, len; + + if(sink->tail == NULL) { + sink->tail = gtk_gs_doc_chunk_new(CHUNK_SIZE); + sink->chunks = g_slist_append(sink->chunks, sink->tail); + } + + max_len = sink->tail->max_len - sink->tail->len; + if(max_len > 0) { + len = g_vsnprintf(sink->tail->ptr, max_len, fmt, ap); + if(len >= max_len - 1) { + /* force printf in the next chunk later on */ + max_len = 0; + sink->tail = NULL; + } + else { + sink->tail->ptr += len; + sink->tail->len += len; + } + } + if(max_len <= 0) { + gtk_gs_doc_sink_printf(sink, fmt, ap); + } +} + +void +gtk_gs_doc_sink_printf(GtkGSDocSink * sink, const gchar * fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + gtk_gs_doc_sink_printf_v(sink, fmt, ap); + va_end(ap); +} + +gchar * +gtk_gs_doc_sink_get_buffer(GtkGSDocSink * sink) +{ + guint total; + GSList *node; + + for(total = 0, node = sink->chunks; node; node = node->next) { + total += ((GtkGSDocChunk *) node->data)->len; + } + if(total) { + gchar *buf = g_malloc(sizeof(gchar) * (total + 1)), *ptr; + if(!buf) + return NULL; + for(ptr = buf, node = sink->chunks; node; node = node->next) { + memcpy(ptr, + ((GtkGSDocChunk *) node->data)->buf, + ((GtkGSDocChunk *) node->data)->len); + ptr += ((GtkGSDocChunk *) node->data)->len; + } + buf[total] = '\0'; + return buf; + } + else + return NULL; +} diff --git a/ps/gsio.h b/ps/gsio.h new file mode 100644 index 0000000..31a7823 --- /dev/null +++ b/ps/gsio.h @@ -0,0 +1,45 @@ +/* + * gsio.h: an IO abstraction + * + * Copyright 2002 - 2005 The Free Software Foundation + * + * Author: jaKa Mocnik + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifndef __GS_IO_H__ +#define __GS_IO_H__ + +#include + +G_BEGIN_DECLS + +typedef struct _GtkGSDocSink GtkGSDocSink; + +gchar *gtk_gs_get_pages(GtkGS * gs, gint * pages); +gchar *gtk_gs_get_document(GtkGS * gs); + +GtkGSDocSink *gtk_gs_doc_sink_new(void); +void gtk_gs_doc_sink_free(GtkGSDocSink * sink); +void gtk_gs_doc_sink_write(GtkGSDocSink * sink, const gchar * buf, int len); +void gtk_gs_doc_sink_printf_v(GtkGSDocSink * sink, const gchar * fmt, + va_list ap); +void gtk_gs_doc_sink_printf(GtkGSDocSink * sink, const gchar * fmt, ...); +gchar *gtk_gs_doc_sink_get_buffer(GtkGSDocSink * sink); + +G_END_DECLS + +#endif /* __GS_IO_H__ */ diff --git a/ps/gtkgs.c b/ps/gtkgs.c new file mode 100644 index 0000000..3890c68 --- /dev/null +++ b/ps/gtkgs.c @@ -0,0 +1,2740 @@ +/* Ghostscript widget for GTK/GNOME + * + * Copyright (C) 1998 - 2005 the Free Software Foundation + * + * Authors: Jonathan Blandford, Jaka Mocnik + * + * Based on code by: Federico Mena (Quartic), Szekeres Istvan (Pista) + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + */ + +/* +Ghostview interface to ghostscript + +When the GHOSTVIEW environment variable is set, ghostscript draws on +an existing drawable rather than creating its own window. Ghostscript +can be directed to draw on either a window or a pixmap. + +Drawing on a Window + +The GHOSTVIEW environment variable contains the window id of the target +window. The window id is an integer. Ghostscript will use the attributes +of the window to obtain the width, height, colormap, screen, and visual of +the window. The remainder of the information is gotten from the GHOSTVIEW +property on that window. + + +Drawing on a Pixmap + +The GHOSTVIEW environment variable contains a window id and a pixmap id. +They are integers separated by white space. Ghostscript will use the +attributes of the window to obtain the colormap, screen, and visual to use. +The width and height will be obtained from the pixmap. The remainder of the +information, is gotten from the GHOSTVIEW property on the window. In this +case, the property is deleted when read. + +The GHOSTVIEW environment variable + +parameters: window-id [pixmap-id] + +scanf format: "%d %d" + +explanation of parameters: + + window-id: tells ghostscript where to + - read the GHOSTVIEW property + - send events + If pixmap-id is not present, + ghostscript will draw on this window. + + pixmap-id: If present, tells ghostscript that a pixmap will be used + as the final destination for drawing. The window will + not be touched for drawing purposes. + +The GHOSTVIEW property + +type: STRING + +parameters: + + bpixmap orient llx lly urx ury xdpi ydpi [left bottom top right] + +scanf format: "%d %d %d %d %d %d %f %f %d %d %d %d" + +explanation of parameters: + + bpixmap: pixmap id of the backing pixmap for the window. If no + pixmap is to be used, this parameter should be zero. This + parameter must be zero when drawing on a pixmap. + + orient: orientation of the page. The number represents clockwise + rotation of the paper in degrees. Permitted values are + 0, 90, 180, 270. + + llx, lly, urx, ury: Bounding box of the drawable. The bounding box + is specified in PostScript points in default user coordinates. + + xdpi, ydpi: Resolution of window. (This can be derived from the + other parameters, but not without roundoff error. These + values are included to avoid this error.) + + left, bottom, top, right: (optional) + Margins around the window. The margins extend the imageable + area beyond the boundaries of the window. This is primarily + used for popup zoom windows. I have encountered several + instances of PostScript programs that position themselves + with respect to the imageable area. The margins are specified + in PostScript points. If omitted, the margins are assumed to + be 0. + +Events from ghostscript + +If the final destination is a pixmap, the client will get a property notify +event when ghostscript reads the GHOSTVIEW property causing it to be deleted. + +Ghostscript sends events to the window where it read the GHOSTVIEW property. +These events are of type ClientMessage. The message_type is set to +either PAGE or DONE. The first long data value gives the window to be used +to send replies to ghostscript. The second long data value gives the primary +drawable. If rendering to a pixmap, it is the primary drawable. If rendering +to a window, the backing pixmap is the primary drawable. If no backing pixmap +is employed, then the window is the primary drawable. This field is necessary +to distinguish multiple ghostscripts rendering to separate pixmaps where the +GHOSTVIEW property was placed on the same window. + +The PAGE message indicates that a "page" has completed. Ghostscript will +wait until it receives a ClientMessage whose message_type is NEXT before +continuing. + +The DONE message indicates that ghostscript has finished processing. + +*/ + +#include "config.h" +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef HAVE_XINERAMA +# include +# include +#endif /* HAVE_XINERAMA */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "gtkgs.h" +#include "ggvutils.h" +#include "ps.h" +#include "gsdefaults.h" + +#ifdef HAVE_LOCALE_H +# include +#endif + +/* if POSIX O_NONBLOCK is not available, use O_NDELAY */ +#if !defined(O_NONBLOCK) && defined(O_NDELAY) +# define O_NONBLOCK O_NDELAY +#endif + +#define GTK_GS_WATCH_INTERVAL 1000 +#define GTK_GS_WATCH_TIMEOUT 2 + +#define MAX_BUFSIZE 1024 + +enum { INTERPRETER_MESSAGE, INTERPRETER_ERROR, LAST_SIGNAL }; + +static gboolean broken_pipe = FALSE; + +static void +catchPipe(int i) +{ + broken_pipe = True; +} + +/* Forward declarations */ +static void gtk_gs_init(GtkGS * gs); +static void gtk_gs_class_init(GtkGSClass * klass); +static void gtk_gs_destroy(GtkObject * object); +static void gtk_gs_realize(GtkWidget * widget); +static void gtk_gs_size_request(GtkWidget * widget, + GtkRequisition * requisition); +static void gtk_gs_size_allocate(GtkWidget * widget, + GtkAllocation * allocation); +static gint gtk_gs_widget_event(GtkWidget * widget, GdkEvent * event, + gpointer data); +static void gtk_gs_value_adjustment_changed(GtkAdjustment * adjustment, + gpointer data); +static void gtk_gs_interpreter_message(GtkGS * gs, gchar * msg, + gpointer user_data); +static void gtk_gs_emit_error_msg(GtkGS * gs, const gchar * msg); +static void gtk_gs_set_adjustments(GtkGS * gs, GtkAdjustment * hadj, + GtkAdjustment * vadj); +static void send_ps(GtkGS * gs, long begin, unsigned int len, gboolean close); +static void set_up_page(GtkGS * gs); +static void close_pipe(int p[2]); +static void interpreter_failed(GtkGS * gs); +static float compute_xdpi(void); +static float compute_ydpi(void); +static gboolean compute_size(GtkGS * gs); +static void output(gpointer data, gint source, GdkInputCondition condition); +static void input(gpointer data, gint source, GdkInputCondition condition); +static void stop_interpreter(GtkGS * gs); +static gint start_interpreter(GtkGS * gs); +gboolean computeSize(void); + +static GtkWidgetClass *parent_class = NULL; + +static GtkGSClass *gs_class = NULL; + +static gint gtk_gs_signals[LAST_SIGNAL] = { 0 }; + +/* Static, private functions */ + +static void +ggv_marshaller_VOID__POINTER(GClosure * closure, + GValue * return_value, + guint n_param_values, + const GValue * param_values, + gpointer invocation_hint, gpointer marshal_data) +{ + typedef void (*GMarshalFunc_VOID__POINTER) (gpointer data1, + gpointer arg_1, gpointer data2); + register GMarshalFunc_VOID__POINTER callback; + register GCClosure *cc = (GCClosure *) closure; + register gpointer data1, data2; + + g_return_if_fail(n_param_values == 2); + + if(G_CCLOSURE_SWAP_DATA(closure)) { + data1 = closure->data; + data2 = g_value_peek_pointer(param_values + 0); + } + else { + data1 = g_value_peek_pointer(param_values + 0); + data2 = closure->data; + } + callback = + (GMarshalFunc_VOID__POINTER) (marshal_data ? marshal_data : cc->callback); + + callback(data1, g_value_get_pointer(param_values + 1), data2); +} + +static void +ggv_marshaller_VOID__INT(GClosure * closure, + GValue * return_value, + guint n_param_values, + const GValue * param_values, + gpointer invocation_hint, gpointer marshal_data) +{ + typedef void (*GMarshalFunc_VOID__INT) (gpointer data1, + gint arg_1, gpointer data2); + register GMarshalFunc_VOID__INT callback; + register GCClosure *cc = (GCClosure *) closure; + register gpointer data1, data2; + + g_return_if_fail(n_param_values == 2); + + if(G_CCLOSURE_SWAP_DATA(closure)) { + data1 = closure->data; + data2 = g_value_peek_pointer(param_values + 0); + } + else { + data1 = g_value_peek_pointer(param_values + 0); + data2 = closure->data; + } + callback = + (GMarshalFunc_VOID__INT) (marshal_data ? marshal_data : cc->callback); + + callback(data1, g_value_get_int(param_values + 1), data2); +} + +static void +ggv_marshaller_VOID__POINTER_POINTER(GClosure * closure, + GValue * return_value, + guint n_param_values, + const GValue * param_values, + gpointer invocation_hint, + gpointer marshal_data) +{ + typedef void (*GMarshalFunc_VOID__POINTER_POINTER) (gpointer data1, + gpointer arg_1, + gpointer arg_2, + gpointer data2); + register GMarshalFunc_VOID__POINTER_POINTER callback; + register GCClosure *cc = (GCClosure *) closure; + register gpointer data1, data2; + + g_return_if_fail(n_param_values == 3); + + if(G_CCLOSURE_SWAP_DATA(closure)) { + data1 = closure->data; + data2 = g_value_peek_pointer(param_values + 0); + } + else { + data1 = g_value_peek_pointer(param_values + 0); + data2 = closure->data; + } + callback = + (GMarshalFunc_VOID__POINTER_POINTER) (marshal_data ? marshal_data : cc-> + callback); + + callback(data1, + g_value_get_pointer(param_values + 1), + g_value_get_pointer(param_values + 2), data2); +} + +static void +gtk_gs_init(GtkGS * gs) +{ + gs->bpixmap = NULL; + gs->use_bpixmap = TRUE; + + gs->current_page = -2; + gs->disable_start = FALSE; + gs->interpreter_pid = -1; + + gs->width = -1; + gs->height = -1; + gs->busy = FALSE; + gs->changed = FALSE; + gs->gs_scanstyle = 0; + gs->gs_filename = 0; + gs->gs_filename_dsc = 0; + gs->gs_filename_unc = 0; + + broken_pipe = FALSE; + + gs->structured_doc = FALSE; + gs->reading_from_pipe = FALSE; + gs->send_filename_to_gs = FALSE; + + gs->doc = NULL; + gs->loaded = FALSE; + + gs->interpreter_input = -1; + gs->interpreter_output = -1; + gs->interpreter_err = -1; + gs->interpreter_input_id = 0; + gs->interpreter_output_id = 0; + gs->interpreter_error_id = 0; + + gs->ps_input = NULL; + gs->input_buffer = NULL; + gs->input_buffer_ptr = NULL; + gs->bytes_left = 0; + gs->buffer_bytes_left = 0; + + gs->llx = 0; + gs->lly = 0; + gs->urx = 0; + gs->ury = 0; + gs->xdpi = compute_xdpi(); + gs->ydpi = compute_ydpi(); + + gs->left_margin = 0; + gs->top_margin = 0; + gs->right_margin = 0; + gs->bottom_margin = 0; + + /* Set user defined defaults */ + gs->override_orientation = gtk_gs_defaults_get_override_orientation(); + gs->fallback_orientation = gtk_gs_defaults_get_orientation(); + gs->zoom_factor = gtk_gs_defaults_get_zoom_factor(); + gs->default_size = gtk_gs_defaults_get_size(); + gs->antialiased = gtk_gs_defaults_get_antialiased(); + gs->override_size = gtk_gs_defaults_get_override_size(); + gs->respect_eof = gtk_gs_defaults_get_respect_eof(); + gs->show_scroll_rect = gtk_gs_defaults_get_show_scroll_rect(); + gs->scroll_step = gtk_gs_defaults_get_scroll_step(); + gs->zoom_mode = gtk_gs_defaults_get_zoom_mode(); + + gs->scroll_start_x = gs->scroll_start_y = -1; + + gs->gs_status = _("No document loaded."); +} + +static void +gtk_gs_class_init(GtkGSClass * klass) +{ + GtkObjectClass *object_class; + GObjectClass *gobject_class; + GtkWidgetClass *widget_class; + + object_class = (GtkObjectClass *) klass; + gobject_class = (GObjectClass *) klass; + widget_class = (GtkWidgetClass *) klass; + parent_class = gtk_type_class(gtk_widget_get_type()); + gs_class = klass; + + gtk_gs_signals[INTERPRETER_MESSAGE] = g_signal_new("interpreter_message", + G_TYPE_FROM_CLASS + (object_class), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET + (GtkGSClass, + interpreter_message), + NULL, NULL, + ggv_marshaller_VOID__POINTER, + G_TYPE_NONE, 1, + G_TYPE_POINTER); + gtk_gs_signals[INTERPRETER_ERROR] = + g_signal_new("interpreter_error", G_TYPE_FROM_CLASS(object_class), + G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET(GtkGSClass, + interpreter_error), + NULL, NULL, ggv_marshaller_VOID__INT, G_TYPE_NONE, 1, + G_TYPE_INT); + + object_class->destroy = gtk_gs_destroy; + + widget_class->realize = gtk_gs_realize; + widget_class->size_request = gtk_gs_size_request; + widget_class->size_allocate = gtk_gs_size_allocate; + widget_class->set_scroll_adjustments_signal = + g_signal_new("set_scroll_adjustments", + G_TYPE_FROM_CLASS(object_class), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET(GtkGSClass, set_scroll_adjustments), + NULL, + NULL, + ggv_marshaller_VOID__POINTER_POINTER, + G_TYPE_NONE, 2, G_TYPE_POINTER, G_TYPE_POINTER); + + /* Create atoms */ + klass->gs_atom = gdk_atom_intern("GHOSTVIEW", FALSE); + klass->gs_colors_atom = gdk_atom_intern("GHOSTVIEW_COLORS", FALSE); + klass->next_atom = gdk_atom_intern("NEXT", FALSE); + klass->page_atom = gdk_atom_intern("PAGE", FALSE); + klass->done_atom = gdk_atom_intern("DONE", FALSE); + klass->string_atom = gdk_atom_intern("STRING", FALSE); + + /* a default handler for "interpreter_message" signal */ + klass->interpreter_message = gtk_gs_interpreter_message; + /* supply a scrollable interface */ + klass->set_scroll_adjustments = gtk_gs_set_adjustments; + + gtk_gs_defaults_load(); +} + +/* Clean all memory and temporal files */ +static void +gtk_gs_cleanup(GtkGS * gs) +{ + g_return_if_fail(gs != NULL); + g_return_if_fail(GTK_IS_GS(gs)); + + stop_interpreter(gs); + + if(gs->gs_psfile) { + fclose(gs->gs_psfile); + gs->gs_psfile = NULL; + } + if(gs->gs_filename) { + g_free(gs->gs_filename); + gs->gs_filename = NULL; + } + if(gs->doc) { + psfree(gs->doc); + gs->doc = NULL; + } + if(gs->gs_filename_dsc) { + unlink(gs->gs_filename_dsc); + g_free(gs->gs_filename_dsc); + gs->gs_filename_dsc = NULL; + } + if(gs->gs_filename_unc) { + unlink(gs->gs_filename_unc); + g_free(gs->gs_filename_unc); + gs->gs_filename_unc = NULL; + } + if(gs->pstarget && gdk_window_is_visible(gs->pstarget)) + gdk_window_hide(gs->pstarget); + gs->current_page = -1; + gs->loaded = FALSE; + gs->llx = 0; + gs->lly = 0; + gs->urx = 0; + gs->ury = 0; + set_up_page(gs); +} + +/* free message as it was allocated in output() */ +static void +gtk_gs_interpreter_message(GtkGS * gs, gchar * msg, gpointer user_data) +{ + gdk_pointer_ungrab(GDK_CURRENT_TIME); + if(strstr(msg, "Error:")) { + gs->gs_status = _("File is not a valid PostScript document."); + gtk_gs_cleanup(gs); + g_signal_emit_by_name(G_OBJECT(gs), "interpreter_error", 1, NULL); + } + g_free(msg); +} + +static void +gtk_gs_destroy(GtkObject * object) +{ + GtkGS *gs; + + g_return_if_fail(object != NULL); + g_return_if_fail(GTK_IS_GS(object)); + + gs = GTK_GS(object); + + gtk_gs_cleanup(gs); + + if(gs->input_buffer) { + g_free(gs->input_buffer); + gs->input_buffer = NULL; + } + if(gs->hadj) { + g_signal_handlers_disconnect_matched(G_OBJECT(gs->hadj), + G_SIGNAL_MATCH_DATA, + 0, 0, NULL, NULL, gs); + gtk_object_unref(GTK_OBJECT(gs->hadj)); + gs->hadj = NULL; + } + if(gs->vadj) { + g_signal_handlers_disconnect_matched(G_OBJECT(gs->vadj), + G_SIGNAL_MATCH_DATA, + 0, 0, NULL, NULL, gs); + gtk_object_unref(GTK_OBJECT(gs->vadj)); + gs->vadj = NULL; + } + + if(GTK_OBJECT_CLASS(parent_class)->destroy) + (*GTK_OBJECT_CLASS(parent_class)->destroy) (object); +} + +/* FIXME: I'm not sure if all this is supposed to be here + * this is just a quick hack so that this can be called whenever + * something changes. + */ +static void +gtk_gs_munge_adjustments(GtkGS * gs) +{ + gint x, y; + + gdk_window_get_position(gs->pstarget, &x, &y); + + /* + * This is a bit messy: + * we want to make sure that we do the right thing if dragged. + */ + if(gs->widget.allocation.width >= gs->width || + gs->zoom_mode != GTK_GS_ZOOM_ABSOLUTE) { + x = (gs->widget.allocation.width - gs->width) / 2; + gs->hadj->value = 0.0; + gs->hadj->page_size = 1.0; + gs->hadj->step_increment = 1.0; + } + else { + if(x > 0) + x = 0; + else if(gs->widget.allocation.width > x + gs->width) + x = gs->widget.allocation.width - gs->width; + gs->hadj->page_size = ((gfloat) gs->widget.allocation.width) / gs->width; + gs->hadj->page_increment = gs->hadj->page_size * 0.9; + gs->hadj->step_increment = gs->scroll_step * gs->hadj->page_size; + gs->hadj->value = -((gfloat) x) / gs->width; + } + if(gs->widget.allocation.height >= gs->height || + gs->zoom_mode == GTK_GS_ZOOM_FIT_PAGE) { + y = (gs->widget.allocation.height - gs->height) / 2; + gs->vadj->value = 0.0; + gs->vadj->page_size = 1.0; + gs->vadj->step_increment = 1.0; + } + else { + if(y > 0) + y = 0; + else if(gs->widget.allocation.height > y + gs->height) + y = gs->widget.allocation.height - gs->height; + gs->vadj->page_size = ((gfloat) gs->widget.allocation.height) / gs->height; + gs->vadj->page_increment = gs->vadj->page_size * 0.9; + gs->vadj->step_increment = gs->scroll_step * gs->vadj->page_size; + gs->vadj->value = -((gfloat) y) / gs->height; + } + + gdk_window_move(gs->pstarget, x, y); + + gtk_adjustment_changed(gs->hadj); + gtk_adjustment_changed(gs->vadj); +} + +static void +gtk_gs_realize(GtkWidget * widget) +{ + GtkGS *gs; + GdkWindowAttr attributes; + gint attributes_mask; + + g_return_if_fail(widget != NULL); + g_return_if_fail(GTK_IS_GS(widget)); + + gs = GTK_GS(widget); + + /* we set up the main widget! */ + GTK_WIDGET_SET_FLAGS(widget, GTK_REALIZED); + attributes.window_type = GDK_WINDOW_CHILD; + attributes.x = widget->allocation.x; + attributes.y = widget->allocation.y; + attributes.width = widget->allocation.width; + attributes.height = widget->allocation.height; + attributes.wclass = GDK_INPUT_OUTPUT; + attributes.visual = gtk_widget_get_visual(widget); + attributes.colormap = gtk_widget_get_colormap(widget); + attributes.event_mask = gtk_widget_get_events(widget) | GDK_EXPOSURE_MASK; + attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_COLORMAP; + + widget->window = + gdk_window_new(widget->parent->window, &attributes, attributes_mask); + gdk_window_set_user_data(widget->window, gs); + widget->style = gtk_style_attach(widget->style, widget->window); + gtk_style_set_background(widget->style, widget->window, GTK_STATE_NORMAL); + + /* now we set up the child window. This is the one that ps actually draws too. */ + attributes.x = 0; + attributes.y = 0; + + gs->pstarget = gdk_window_new(widget->window, &attributes, attributes_mask); + gdk_window_set_user_data(gs->pstarget, widget); + gdk_window_clear(gs->pstarget); + gtk_style_set_background(widget->style, gs->pstarget, GTK_STATE_ACTIVE); + gs->psgc = gdk_gc_new(gs->pstarget); + gdk_gc_set_function(gs->psgc, GDK_INVERT); + + gs->width = 0; + gs->height = 0; + + gtk_gs_set_page_size(gs, -1, 0); + + if((gs->width > 0) && (gs->height > 0) && GTK_WIDGET_REALIZED(gs)) { + gtk_gs_munge_adjustments(gs); + } + + g_signal_connect(G_OBJECT(widget), "event", + G_CALLBACK(gtk_gs_widget_event), gs); + + gtk_gs_goto_page(gs, gs->current_page); +} + +static void +gtk_gs_size_request(GtkWidget * widget, GtkRequisition * requisition) +{ + GtkGS *gs = GTK_GS(widget); + + compute_size(gs); + requisition->width = gs->width; + requisition->height = gs->height; +} + +static void +gtk_gs_size_allocate(GtkWidget * widget, GtkAllocation * allocation) +{ + GtkGS *gs = GTK_GS(widget); + GdkEventConfigure event; + + g_return_if_fail(widget != NULL); + g_return_if_fail(GTK_IS_GS(widget)); + g_return_if_fail(allocation != NULL); + + widget->allocation = *allocation; + if(GTK_WIDGET_REALIZED(widget)) { + gdk_window_move_resize(widget->window, + allocation->x, allocation->y, + allocation->width, allocation->height); + + event.type = GDK_CONFIGURE; + event.window = widget->window; + event.x = allocation->x; + event.y = allocation->y; + event.width = allocation->width; + event.height = allocation->height; + gtk_widget_event(widget, (GdkEvent *) & event); + } + + /* + * update the adjustment if necessary (ie. a resize); + */ +#if 0 + if(gs->zoom_mode != GTK_GS_ZOOM_ABSOLUTE) { + gtk_gs_set_zoom(gs, 0.0); + } +#endif + + if(GTK_WIDGET_REALIZED(gs)) { + gtk_gs_munge_adjustments(gs); + } + + gtk_gs_goto_page(gs, gs->current_page); +} + +static gboolean +gtk_gs_widget_event(GtkWidget * widget, GdkEvent * event, gpointer data) +{ + GtkGS *gs = (GtkGS *) data; + if(event->type != GDK_CLIENT_EVENT) + return FALSE; + + /* the first long is the window to communicate with gs, + only if event if client_event */ + gs->message_window = event->client.data.l[0]; + + if(event->client.message_type == gs_class->page_atom) { + gs->busy = FALSE; + } + return TRUE; +} + + +static void +gtk_gs_value_adjustment_changed(GtkAdjustment * adjustment, gpointer data) +{ + GtkGS *gs; + gint x, y, width, height, depth; + gint newx, newy; + + g_return_if_fail(adjustment != NULL); + g_return_if_fail(data != NULL); + gs = GTK_GS(data); + if(gs->bpixmap == NULL) + return; + +#if 0 + g_print("Adjustment %c: val = %f, page = %f, upper = %f, lower = %f\n", + (adjustment == gs->hadj) ? 'H' : 'V', + adjustment->value, adjustment->page_size, + adjustment->upper, adjustment->lower); +#endif + + gdk_window_get_geometry(gs->pstarget, &x, &y, &width, &height, &depth); + if(gs->width <= gs->widget.allocation.width) + newx = (gs->widget.allocation.width - gs->width) / 2; + else + newx = -gs->hadj->value * gs->width; + if(gs->height <= gs->widget.allocation.height) + newy = (gs->widget.allocation.height - gs->height) / 2; + else + newy = -gs->vadj->value * gs->height; + + gdk_window_move(gs->pstarget, newx, newy); +} + +void +gtk_gs_set_center(GtkGS * gs, gfloat hval, gfloat vval) +{ + if(hval <= gs->hadj->upper - gs->hadj->page_size / 2 && + hval >= gs->hadj->lower + gs->hadj->page_size / 2) + gtk_adjustment_set_value(gs->hadj, hval); + if(vval <= gs->vadj->upper - gs->vadj->page_size / 2 && + vval >= gs->vadj->lower + gs->vadj->page_size / 2) + gtk_adjustment_set_value(gs->vadj, vval); +} + +static void +send_ps(GtkGS * gs, long begin, unsigned int len, gboolean close) +{ + struct record_list *ps_new; + + if(gs->interpreter_input < 0) { + g_critical("No pipe to gs: error in send_ps()."); + return; + } + + ps_new = (struct record_list *) g_malloc(sizeof(struct record_list)); + ps_new->fp = gs->gs_psfile; + ps_new->begin = begin; + ps_new->len = len; + ps_new->seek_needed = TRUE; + ps_new->close = close; + ps_new->next = NULL; + + if(gs->input_buffer == NULL) { + gs->input_buffer = g_malloc(MAX_BUFSIZE); + } + + if(gs->ps_input == NULL) { + gs->input_buffer_ptr = gs->input_buffer; + gs->bytes_left = len; + gs->buffer_bytes_left = 0; + gs->ps_input = ps_new; + gs->interpreter_input_id = + gdk_input_add(gs->interpreter_input, GDK_INPUT_WRITE, input, gs); + } + else { + struct record_list *p = gs->ps_input; + while(p->next != NULL) { + p = p->next; + } + p->next = ps_new; + } +} + +static void +set_up_page(GtkGS * gs) + /* + * This is used to prepare the widget internally for + * a new document. It sets gs->pstarget to the + * correct size and position, and updates the + * adjustments appropriately. + * + * It is not meant to be used every time a specific page + * is selected. + * + * NOTE: It expects the widget is realized. + */ +{ + guint orientation; + char buf[1024]; + GdkPixmap *pprivate; + GdkColormap *colormap; + GdkGC *fill; + GdkColor white = { 0, 0xFFFF, 0xFFFF, 0xFFFF }; /* pixel, r, g, b */ + +#ifdef HAVE_LOCALE_H + char *savelocale; +#endif + + if(!GTK_WIDGET_REALIZED(gs)) + return; + + /* Do we have to check if the actual geometry changed? */ + + stop_interpreter(gs); + + orientation = gtk_gs_get_orientation(gs); + + if(compute_size(gs)) { + gdk_flush(); + + /* clear new pixmap (set to white) */ + fill = gdk_gc_new(gs->pstarget); + if(fill) { + colormap = gtk_widget_get_colormap(GTK_WIDGET(gs)); + gdk_color_alloc(colormap, &white); + gdk_gc_set_foreground(fill, &white); + + if(gs->use_bpixmap && gs->width > 0 && gs->height > 0) { + if(gs->bpixmap) { + gdk_drawable_unref(gs->bpixmap); + gs->bpixmap = NULL; + } + + gs->bpixmap = gdk_pixmap_new(gs->pstarget, gs->width, gs->height, -1); + + gdk_draw_rectangle(gs->bpixmap, fill, TRUE, + 0, 0, gs->width, gs->height); + + gdk_window_set_back_pixmap(gs->pstarget, gs->bpixmap, FALSE); + } + else { + gdk_draw_rectangle(gs->pstarget, fill, TRUE, + 0, 0, gs->width, gs->height); + } + gdk_gc_unref(fill); + + gdk_window_resize(gs->pstarget, gs->width, gs->height); + + gdk_flush(); + } + } + +#ifdef HAVE_LOCALE_H + /* gs needs floating point parameters with '.' as decimal point + * while some (european) locales use ',' instead, so we set the + * locale for this snprintf to "C". + */ + savelocale = setlocale(LC_NUMERIC, "C"); +#endif + pprivate = (GdkPixmap *) gs->bpixmap; + + g_snprintf(buf, 1024, "%ld %d %d %d %d %d %f %f %d %d %d %d", + pprivate ? gdk_x11_drawable_get_xid(pprivate) : 0L, + orientation * 90, + gs->llx, + gs->lly, + gs->urx, + gs->ury, + gs->xdpi * gs->zoom_factor, + gs->ydpi * gs->zoom_factor, + gs->left_margin, + gs->bottom_margin, gs->right_margin, gs->top_margin); + +#ifdef HAVE_LOCALE_H + setlocale(LC_NUMERIC, savelocale); +#endif + gdk_property_change(gs->pstarget, + gs_class->gs_atom, + gs_class->string_atom, + 8, GDK_PROP_MODE_REPLACE, buf, strlen(buf)); + gdk_flush(); +} + +static void +close_pipe(int p[2]) +{ + if(p[0] != -1) + close(p[0]); + if(p[1] != -1) + close(p[1]); +} + +static gboolean +is_interpreter_ready(GtkGS * gs) +{ + return (gs->interpreter_pid != -1 && !gs->busy && gs->ps_input == NULL); +} + +static void +interpreter_failed(GtkGS * gs) +{ + stop_interpreter(gs); +} + +static void +output(gpointer data, gint source, GdkInputCondition condition) +{ + char buf[MAX_BUFSIZE + 1], *msg; + guint bytes = 0; + GtkGS *gs = GTK_GS(data); + + if(source == gs->interpreter_output) { + bytes = read(gs->interpreter_output, buf, MAX_BUFSIZE); + if(bytes == 0) { /* EOF occurred */ + close(gs->interpreter_output); + gs->interpreter_output = -1; + gdk_input_remove(gs->interpreter_output_id); + return; + } + else if(bytes == -1) { + /* trouble... */ + interpreter_failed(gs); + return; + } + if(gs->interpreter_err == -1) { + stop_interpreter(gs); + } + } + else if(source == gs->interpreter_err) { + bytes = read(gs->interpreter_err, buf, MAX_BUFSIZE); + if(bytes == 0) { /* EOF occurred */ + close(gs->interpreter_err); + gs->interpreter_err = -1; + gdk_input_remove(gs->interpreter_error_id); + return; + } + else if(bytes == -1) { + /* trouble... */ + interpreter_failed(gs); + return; + } + if(gs->interpreter_output == -1) { + stop_interpreter(gs); + } + } + if(bytes > 0) { + buf[bytes] = '\0'; + msg = g_strdup(buf); + gtk_signal_emit(GTK_OBJECT(gs), gtk_gs_signals[INTERPRETER_MESSAGE], msg); + } +} + +static void +input(gpointer data, gint source, GdkInputCondition condition) +{ + GtkGS *gs = GTK_GS(data); + int bytes_written; + void (*oldsig) (int); + oldsig = signal(SIGPIPE, catchPipe); + + do { + if(gs->buffer_bytes_left == 0) { + /* Get a new section if required */ + if(gs->ps_input && gs->bytes_left == 0) { + struct record_list *ps_old = gs->ps_input; + gs->ps_input = ps_old->next; + if(ps_old->close && NULL != ps_old->fp) + fclose(ps_old->fp); + g_free((char *) ps_old); + } + /* Have to seek at the beginning of each section */ + if(gs->ps_input && gs->ps_input->seek_needed) { + fseek(gs->ps_input->fp, gs->ps_input->begin, SEEK_SET); + gs->ps_input->seek_needed = FALSE; + gs->bytes_left = gs->ps_input->len; + } + + if(gs->bytes_left > MAX_BUFSIZE) { + gs->buffer_bytes_left = + fread(gs->input_buffer, sizeof(char), MAX_BUFSIZE, gs->ps_input->fp); + } + else if(gs->bytes_left > 0) { + gs->buffer_bytes_left = + fread(gs->input_buffer, + sizeof(char), gs->bytes_left, gs->ps_input->fp); + } + else { + gs->buffer_bytes_left = 0; + } + if(gs->bytes_left > 0 && gs->buffer_bytes_left == 0) { + interpreter_failed(gs); /* Error occurred */ + } + gs->input_buffer_ptr = gs->input_buffer; + gs->bytes_left -= gs->buffer_bytes_left; + } + + if(gs->buffer_bytes_left > 0) { + /* g_print (" writing: %s\n",gs->input_buffer_ptr); */ + + bytes_written = write(gs->interpreter_input, + gs->input_buffer_ptr, gs->buffer_bytes_left); + + if(broken_pipe) { + gtk_gs_emit_error_msg(gs, g_strdup(_("Broken pipe."))); + broken_pipe = FALSE; + interpreter_failed(gs); + } + else if(bytes_written == -1) { + if((errno != EWOULDBLOCK) && (errno != EAGAIN)) { + interpreter_failed(gs); /* Something bad happened */ + } + } + else { + gs->buffer_bytes_left -= bytes_written; + gs->input_buffer_ptr += bytes_written; + } + } + } + while(gs->ps_input && gs->buffer_bytes_left == 0); + + signal(SIGPIPE, oldsig); + + if(gs->ps_input == NULL && gs->buffer_bytes_left == 0) { + if(gs->interpreter_input_id != 0) { + gdk_input_remove(gs->interpreter_input_id); + gs->interpreter_input_id = 0; + } + } +} + +static int +start_interpreter(GtkGS * gs) +{ + int std_in[2] = { -1, -1 }; /* pipe to interp stdin */ + int std_out[2]; /* pipe from interp stdout */ + int std_err[2]; /* pipe from interp stderr */ + +#define NUM_ARGS 100 +#define NUM_GS_ARGS (NUM_ARGS - 20) +#define NUM_ALPHA_ARGS 10 + + char *argv[NUM_ARGS], *dir, *gv_env; + char **gs_args, **alpha_args = NULL; + int argc = 0, i; + + if(!gs->gs_filename) + return 0; + + stop_interpreter(gs); + + if(gs->disable_start == TRUE) + return 0; + + /* set up the args... */ + gs_args = g_strsplit(gtk_gs_defaults_get_interpreter_cmd(), " ", NUM_GS_ARGS); + for(i = 0; i < NUM_GS_ARGS && gs_args[i]; i++, argc++) + argv[argc] = gs_args[i]; + + if(gs->antialiased) { + if(strlen(gtk_gs_defaults_get_alpha_parameters()) == 0) + alpha_args = g_strsplit(ALPHA_PARAMS, " ", NUM_ALPHA_ARGS); + else + alpha_args = g_strsplit(gtk_gs_defaults_get_alpha_parameters(), + " ", NUM_ALPHA_ARGS); + for(i = 0; i < NUM_ALPHA_ARGS && alpha_args[i]; i++, argc++) + argv[argc] = alpha_args[i]; + } + else + argv[argc++] = "-sDEVICE=x11"; + argv[argc++] = "-dNOPAUSE"; + argv[argc++] = "-dQUIET"; + /* I assume we do _not_ want to change this... (: */ + argv[argc++] = "-dSAFER"; + + /* set up the pipes */ + if(gs->send_filename_to_gs) { + argv[argc++] = GTK_GS_GET_PS_FILE(gs); + argv[argc++] = "-c"; + argv[argc++] = "quit"; + } + else + argv[argc++] = "-"; + + argv[argc++] = NULL; + + if(!gs->reading_from_pipe && !gs->send_filename_to_gs) { + if(pipe(std_in) == -1) { + g_critical("Unable to open pipe to Ghostscript."); + return -1; + } + } + if(pipe(std_out) == -1) { + close_pipe(std_in); + return -1; + } + if(pipe(std_err) == -1) { + close_pipe(std_in); + close_pipe(std_out); + return -1; + } + + gs->busy = TRUE; + gs->interpreter_pid = fork(); + switch (gs->interpreter_pid) { + case -1: /* error */ + close_pipe(std_in); + close_pipe(std_out); + close_pipe(std_err); + return -2; + break; + case 0: /* child */ + close(std_out[0]); + dup2(std_out[1], 1); + close(std_out[1]); + + close(std_err[0]); + dup2(std_err[1], 2); + close(std_err[1]); + + if(!gs->reading_from_pipe) { + if(gs->send_filename_to_gs) { + int stdinfd; + /* just in case gs tries to read from stdin */ + stdinfd = open("/dev/null", O_RDONLY); + if(stdinfd != 0) { + dup2(stdinfd, 0); + close(stdinfd); + } + } + else { + close(std_in[1]); + dup2(std_in[0], 0); + close(std_in[0]); + } + } + + gv_env = g_strdup_printf("GHOSTVIEW=%ld", + gdk_x11_drawable_get_xid(gs->pstarget)); + putenv(gv_env); + + /* change to directory where the input file is. This helps + * with postscript-files which include other files using + * a relative path */ + dir = g_path_get_dirname(gs->gs_filename); + chdir(dir); + g_free(dir); + + execvp(argv[0], argv); + + /* Notify error */ + g_print("Unable to execute [%s]\n", argv[0]); + g_strfreev(gs_args); + g_free(gv_env); + if(alpha_args) + g_strfreev(alpha_args); + _exit(1); + break; + default: /* parent */ + if(!gs->send_filename_to_gs && !gs->reading_from_pipe) { + int result; + close(std_in[0]); + /* use non-blocking IO for pipe to ghostscript */ + result = fcntl(std_in[1], F_GETFL, 0); + fcntl(std_in[1], F_SETFL, result | O_NONBLOCK); + gs->interpreter_input = std_in[1]; + } + else { + gs->interpreter_input = -1; + } + close(std_out[1]); + gs->interpreter_output = std_out[0]; + close(std_err[1]); + gs->interpreter_err = std_err[0]; + gs->interpreter_output_id = + gdk_input_add(std_out[0], GDK_INPUT_READ, output, gs); + gs->interpreter_error_id = + gdk_input_add(std_err[0], GDK_INPUT_READ, output, gs); + break; + } + return TRUE; +} + +static void +stop_interpreter(GtkGS * gs) +{ + if(gs->interpreter_pid > 0) { + int status = 0; + kill(gs->interpreter_pid, SIGTERM); + while((wait(&status) == -1) && (errno == EINTR)) ; + gs->interpreter_pid = -1; + if(status == 1) { + gtk_gs_cleanup(gs); + gs->gs_status = _("Interpreter failed."); + g_signal_emit_by_name(G_OBJECT(gs), "interpreter_error", status); + } + } + + if(gs->interpreter_input >= 0) { + close(gs->interpreter_input); + gs->interpreter_input = -1; + if(gs->interpreter_input_id != 0) { + gdk_input_remove(gs->interpreter_input_id); + gs->interpreter_input_id = 0; + } + while(gs->ps_input) { + struct record_list *ps_old = gs->ps_input; + gs->ps_input = gs->ps_input->next; + if(ps_old->close && NULL != ps_old->fp) + fclose(ps_old->fp); + g_free((char *) ps_old); + } + } + + if(gs->interpreter_output >= 0) { + close(gs->interpreter_output); + gs->interpreter_output = -1; + if(gs->interpreter_output_id) { + gdk_input_remove(gs->interpreter_output_id); + gs->interpreter_output_id = 0; + } + } + + if(gs->interpreter_err >= 0) { + close(gs->interpreter_err); + gs->interpreter_err = -1; + if(gs->interpreter_error_id) { + gdk_input_remove(gs->interpreter_error_id); + gs->interpreter_error_id = 0; + } + } + + gs->busy = FALSE; +} + + +/* + * Decompress gs->gs_filename if necessary + * Set gs->filename_unc to the name of the uncompressed file or NULL. + * Error reporting via signal 'interpreter_message' + * Return name of input file to use or NULL on error.. + */ +static gchar * +check_filecompressed(GtkGS * gs) +{ + FILE *file; + gchar buf[1024]; + gchar *filename, *filename_unc, *filename_err, *cmdline; + const gchar *cmd; + int fd; + + cmd = NULL; + + if((file = fopen(gs->gs_filename, "r")) + && (fread(buf, sizeof(gchar), 3, file) == 3)) { + if((buf[0] == '\037') && ((buf[1] == '\235') || (buf[1] == '\213'))) { + /* file is gzipped or compressed */ + cmd = gtk_gs_defaults_get_ungzip_cmd(); + } + else if(strncmp(buf, "BZh", 3) == 0) { + /* file is compressed with bzip2 */ + cmd = gtk_gs_defaults_get_unbzip2_cmd(); + } + } + if(NULL != file) + fclose(file); + + if(!cmd) + return gs->gs_filename; + + /* do the decompression */ + filename = ggv_quote_filename(gs->gs_filename); + filename_unc = g_strconcat(g_get_tmp_dir(), "/ggvXXXXXX", NULL); + if((fd = mkstemp(filename_unc)) < 0) { + g_free(filename_unc); + g_free(filename); + return NULL; + } + close(fd); + filename_err = g_strconcat(g_get_tmp_dir(), "/ggvXXXXXX", NULL); + if((fd = mkstemp(filename_err)) < 0) { + g_free(filename_err); + g_free(filename_unc); + g_free(filename); + return NULL; + } + close(fd); + cmdline = g_strdup_printf("%s %s >%s 2>%s", cmd, + filename, filename_unc, filename_err); + if((system(cmdline) == 0) + && ggv_file_readable(filename_unc) + && (ggv_file_length(filename_err) == 0)) { + /* sucessfully uncompressed file */ + gs->gs_filename_unc = filename_unc; + } + else { + /* report error */ + g_snprintf(buf, 1024, _("Error while decompressing file %s:\n"), + gs->gs_filename); + gtk_gs_emit_error_msg(gs, buf); + if(ggv_file_length(filename_err) > 0) { + FILE *err; + if((err = fopen(filename_err, "r"))) { + /* print file to message window */ + while(fgets(buf, 1024, err)) + gtk_gs_emit_error_msg(gs, buf); + fclose(err); + } + } + unlink(filename_unc); + g_free(filename_unc); + filename_unc = NULL; + } + unlink(filename_err); + g_free(filename_err); + g_free(cmdline); + g_free(filename); + return filename_unc; +} + +/* + * Check if gs->gs_filename or gs->gs_filename_unc is a pdf file and scan + * pdf file if necessary. + * Set gs->filename_dsc to the name of the dsc file or NULL. + * Error reporting via signal 'interpreter_message'. + */ +static gchar * +check_pdf(GtkGS * gs) +{ + FILE *file; + gchar buf[1024], *filename; + int fd; + + /* use uncompressed file as input if necessary */ + filename = (gs->gs_filename_unc ? gs->gs_filename_unc : gs->gs_filename); + + if((file = fopen(filename, "r")) + && (fread(buf, sizeof(char), 5, file) == 5) + && (strncmp(buf, "%PDF-", 5) == 0)) { + /* we found a PDF file */ + gchar *fname, *filename_dsc, *filename_err, *cmd, *cmdline; + filename_dsc = g_strconcat(g_get_tmp_dir(), "/ggvXXXXXX", NULL); + if((fd = mkstemp(filename_dsc)) < 0) { + return NULL; + } + close(fd); + filename_err = g_strconcat(g_get_tmp_dir(), "/ggvXXXXXX", NULL); + if((fd = mkstemp(filename_err)) < 0) { + g_free(filename_dsc); + return NULL; + } + close(fd); + fname = ggv_quote_filename(filename); + cmd = g_strdup_printf(gtk_gs_defaults_get_dsc_cmd(), filename_dsc, fname); + g_free(fname); + /* this command (sometimes?) prints error messages to stdout! */ + cmdline = g_strdup_printf("%s >%s 2>&1", cmd, filename_err); + g_free(cmd); + + if((system(cmdline) == 0) && ggv_file_readable(filename_dsc)) { + + /* success */ + filename = gs->gs_filename_dsc = filename_dsc; + + if(ggv_file_length(filename_err) > 0) { + gchar *err_msg = " "; + GtkWidget *dialog; + FILE *err; + GdkColor color; + + if((err = fopen(filename_err, "r"))) { + + /* print the content of the file to a message box */ + while(fgets(buf, 1024, err)) + err_msg = g_strconcat(err_msg, buf, NULL); + + /* FIXME The dialog is not yet set to modal, difficult to + * get the parent of the dialog box here + */ + + dialog = gtk_message_dialog_new(NULL, + GTK_DIALOG_MODAL, + GTK_MESSAGE_WARNING, + GTK_BUTTONS_OK, + ("There was an error while scaning the file: %s \n%s"), + gs->gs_filename, err_msg); + + gdk_color_parse("white", &color); + gtk_widget_modify_bg(GTK_WIDGET(dialog), GTK_STATE_NORMAL, &color); + + g_signal_connect(G_OBJECT(dialog), "response", + G_CALLBACK(gtk_widget_destroy), NULL); + + gtk_window_set_resizable(GTK_WINDOW(dialog), FALSE); + gtk_widget_show(dialog); + g_free(err_msg); + } + } + + } + else { + /* report error */ + g_snprintf(buf, 1024, + _("Error while converting pdf file %s:\n"), filename); + gtk_gs_emit_error_msg(gs, buf); + + if(ggv_file_length(filename_err) > 0) { + FILE *err; + if((err = fopen(filename_err, "r"))) { + /* print file to message window */ + while(fgets(buf, 1024, err)) + gtk_gs_emit_error_msg(gs, buf); + } + } + unlink(filename_dsc); + g_free(filename_dsc); + filename = NULL; + } + unlink(filename_err); + g_free(filename_err); + g_free(cmdline); + } + if(NULL != file) + fclose(file); + return filename; +} + +#ifdef BROKEN_XINERAMA_PATCH_THAT_SHOULD_NOT_BE_USED +/* never mind this patch: a properly working X server should take care of + calculating the proper values. */ +static float +compute_xdpi(void) +{ +# ifndef HAVE_XINERAMA + return 25.4 * gdk_screen_width() / gdk_screen_width_mm(); +# else + Display *dpy; + dpy = (Display *) GDK_DISPLAY(); + if(XineramaIsActive(dpy)) { + int num_heads; + XineramaScreenInfo *head_info; + head_info = (XineramaScreenInfo *) XineramaQueryScreens(dpy, &num_heads); + /* fake it with dimensions of the first head for now */ + return 25.4 * head_info[0].width / gdk_screen_width_mm(); + } + else { + return 25.4 * gdk_screen_width() / gdk_screen_width_mm(); + } +# endif + /* HAVE_XINERAMA */ +} + +static float +compute_ydpi(void) +{ +# ifndef HAVE_XINERAMA + return 25.4 * gdk_screen_height() / gdk_screen_height_mm(); +# else + Display *dpy; + dpy = (Display *) GDK_DISPLAY(); + if(XineramaIsActive(dpy)) { + int num_heads; + XineramaScreenInfo *head_info; + head_info = (XineramaScreenInfo *) XineramaQueryScreens(dpy, &num_heads); + /* fake it with dimensions of the first head for now */ + return 25.4 * head_info[0].height / gdk_screen_height_mm(); + } + else { + return 25.4 * gdk_screen_height() / gdk_screen_height_mm(); + } +# endif + /* HAVE_XINERAMA */ +} +#else +static float +compute_xdpi(void) +{ + return 25.4 * gdk_screen_width() / gdk_screen_width_mm(); +} + +static float +compute_ydpi(void) +{ + return 25.4 * gdk_screen_height() / gdk_screen_height_mm(); +} +#endif /* BROKEN_XINERAMA_PATCH_THAT_SHOULD_NOT_BE_USED */ + +/* Compute new size of window, sets xdpi and ydpi if necessary. + * returns True if new window size is different */ +static gboolean +compute_size(GtkGS * gs) +{ + guint new_width = 1; + guint new_height = 1; + gboolean change = FALSE; + gint orientation; + + /* width and height can be changed, calculate window size according */ + /* to xpdi and ydpi */ + orientation = gtk_gs_get_orientation(gs); + + switch (orientation) { + case GTK_GS_ORIENTATION_PORTRAIT: + case GTK_GS_ORIENTATION_UPSIDEDOWN: + new_width = (gs->urx - gs->llx) / 72.0 * gs->xdpi + 0.5; + new_height = (gs->ury - gs->lly) / 72.0 * gs->ydpi + 0.5; + break; + case GTK_GS_ORIENTATION_LANDSCAPE: + case GTK_GS_ORIENTATION_SEASCAPE: + new_width = (gs->ury - gs->lly) / 72.0 * gs->xdpi + 0.5; + new_height = (gs->urx - gs->llx) / 72.0 * gs->ydpi + 0.5; + break; + } + + change = (new_width != gs->width * gs->zoom_factor) + || (new_height != gs->height * gs->zoom_factor); + gs->width = (gint) (new_width * gs->zoom_factor); + gs->height = (gint) (new_height * gs->zoom_factor); + if(GTK_WIDGET_REALIZED(gs)) { + if(!gs->loaded) { + if(gdk_window_is_visible(gs->pstarget)) + gdk_window_hide(gs->pstarget); + } + else { + if(!gdk_window_is_visible(gs->pstarget) && gs->width > 0 + && gs->height > 0) + gdk_window_show(gs->pstarget); + } + gtk_gs_munge_adjustments(gs); + } + + return (change); +} + +gint +gtk_gs_enable_interpreter(GtkGS * gs) +{ + g_return_val_if_fail(gs != NULL, FALSE); + g_return_val_if_fail(GTK_IS_GS(gs), FALSE); + + if(!gs->gs_filename) + return 0; + + gs->disable_start = FALSE; + if(GTK_WIDGET_REALIZED(gs)) { + return start_interpreter(gs); + } + else { + return 0; + } +} + +/* publicly accessible functions */ + +GType +gtk_gs_get_type(void) +{ + static GType gs_type = 0; + if(!gs_type) { + GTypeInfo gs_info = { + sizeof(GtkGSClass), + (GBaseInitFunc) NULL, + (GBaseFinalizeFunc) NULL, + (GClassInitFunc) gtk_gs_class_init, + (GClassFinalizeFunc) NULL, + NULL, /* class_data */ + sizeof(GtkGS), + 0, /* n_preallocs */ + (GInstanceInitFunc) gtk_gs_init + }; + + gs_type = g_type_register_static(gtk_widget_get_type(), + "GtkGS", &gs_info, 0); + } + return gs_type; + + +} + +GtkWidget * +gtk_gs_new(GtkAdjustment * hadj, GtkAdjustment * vadj) +{ + GtkGS *gs; + + if(NULL == hadj) + hadj = GTK_ADJUSTMENT(gtk_adjustment_new(0.0, 0.0, 1.0, 0.01, 0.1, 0.09)); + if(NULL == vadj) + vadj = GTK_ADJUSTMENT(gtk_adjustment_new(0.0, 0.0, 1.0, 0.01, 0.1, 0.09)); + + gs = (GtkGS *) gtk_type_new(gtk_gs_get_type()); + + gtk_gs_set_adjustments(gs, hadj, vadj); + + return GTK_WIDGET(gs); +} + + +GtkWidget * +gtk_gs_new_from_file(GtkAdjustment * hadj, GtkAdjustment * vadj, char *fname) +{ + GtkWidget *gs = gtk_gs_new(hadj, vadj); + gtk_gs_load(GTK_GS(gs), fname); + return gs; +} + +void +gtk_gs_reload(GtkGS * gs) +{ + gchar *fname; + gfloat hval = gs->hadj->value; + gfloat vval = gs->vadj->value; + gint page; + + if(!gs->gs_filename) + return; + + page = gtk_gs_get_current_page(gs); + fname = g_strdup(gs->gs_filename); + gtk_gs_load(gs, fname); + gtk_gs_goto_page(gs, page); + gtk_adjustment_set_value(gs->hadj, hval); + gtk_adjustment_set_value(gs->vadj, vval); + g_free(fname); +} + + +/* + * Show error message -> send signal "interpreter_message" + */ +static void +gtk_gs_emit_error_msg(GtkGS * gs, const gchar * msg) +{ + gtk_signal_emit(GTK_OBJECT(gs), + gtk_gs_signals[INTERPRETER_MESSAGE], g_strdup(msg)); +} + + +void +gtk_gs_center_page(GtkGS * gs) +{ + g_return_if_fail(gs != NULL); + g_return_if_fail(GTK_IS_GS(gs)); + + gdk_window_move(gs->pstarget, + (gs->widget.allocation.width - gs->width) / 2, + (gs->widget.allocation.height - gs->height) / 2); + gs->hadj->page_size = ((gfloat) gs->widget.allocation.width) / gs->width; + gs->hadj->page_size = MIN(gs->hadj->page_size, 1.0); + gs->vadj->page_size = ((gfloat) gs->widget.allocation.height) / gs->height; + gs->vadj->page_size = MIN(gs->vadj->page_size, 1.0); + gs->hadj->value = 0.5 - gs->hadj->page_size / 2; + gs->vadj->value = 0.5 - gs->vadj->page_size / 2; + gtk_adjustment_changed(gs->hadj); + gtk_adjustment_changed(gs->vadj); +} + +void +gtk_gs_scroll(GtkGS * gs, gint x_delta, gint y_delta) +{ + gfloat hval, vval; + + g_return_if_fail(gs != NULL); + g_return_if_fail(GTK_IS_GS(gs)); + + hval = gs->hadj->value + ((gfloat) x_delta) / gs->width; + vval = gs->vadj->value + ((gfloat) y_delta) / gs->height; + if(hval <= gs->hadj->upper - gs->hadj->page_size && hval >= gs->hadj->lower) + gtk_adjustment_set_value(gs->hadj, hval); + if(vval <= gs->vadj->upper - gs->vadj->page_size && vval >= gs->vadj->lower) + gtk_adjustment_set_value(gs->vadj, vval); +} + +void +gtk_gs_disable_interpreter(GtkGS * gs) +{ + g_return_if_fail(gs != NULL); + g_return_if_fail(GTK_IS_GS(gs)); + + gs->disable_start = TRUE; + if(GTK_WIDGET_REALIZED(GTK_WIDGET(gs))) + stop_interpreter(gs); +} + +gboolean +gtk_gs_load(GtkGS * gs, const gchar * fname) +{ + g_return_val_if_fail(gs != NULL, FALSE); + g_return_val_if_fail(GTK_IS_GS(gs), FALSE); + + /* clean up previous document */ + gtk_gs_cleanup(gs); + + if(fname == NULL) { + if(gs->pstarget != NULL && gdk_window_is_visible(gs->pstarget)) + gdk_window_hide(gs->pstarget); + gs->gs_status = ""; + return FALSE; + } + + /* prepare this document */ + + /* default values: no dsc information available */ + gs->structured_doc = FALSE; + gs->send_filename_to_gs = TRUE; + gs->current_page = -2; + gs->loaded = FALSE; + if(*fname == '/') { + /* an absolute path */ + gs->gs_filename = g_strdup(fname); + } + else { + /* path relative to our cwd: make it absolute */ + gchar *cwd = g_get_current_dir(); + gs->gs_filename = g_strconcat(cwd, "/", fname, NULL); + g_free(cwd); + } + + if((gs->reading_from_pipe = (strcmp(fname, "-") == 0))) { + gs->send_filename_to_gs = FALSE; + } + else { + /* + * We need to make sure that the file is loadable/exists! + * otherwise we want to exit without loading new stuff... + */ + gchar *filename = NULL; + + if(!ggv_file_readable(fname)) { + gchar buf[1024]; + g_snprintf(buf, 1024, _("Cannot open file %s.\n"), fname); + gtk_gs_emit_error_msg(gs, buf); + gs->gs_status = _("File is not readable."); + } + else { + filename = check_filecompressed(gs); + if(filename) + filename = check_pdf(gs); + } + + if(!filename || (gs->gs_psfile = fopen(filename, "r")) == NULL) { + gtk_gs_cleanup(gs); + return FALSE; + } + + /* we grab the vital statistics!!! */ + gs->doc = psscan(gs->gs_psfile, gs->respect_eof, filename); + + if(gs->doc == NULL) { + /* File does not seem to be a Postscript one */ + gchar buf[1024]; + g_snprintf(buf, 1024, _("Error while scanning file %s\n"), fname); + gtk_gs_emit_error_msg(gs, buf); + gtk_gs_cleanup(gs); + gs->gs_status = _("The file is not a PostScript document."); + return FALSE; + } + + if((!gs->doc->epsf && gs->doc->numpages > 0) || + (gs->doc->epsf && gs->doc->numpages > 1)) { + gs->structured_doc = TRUE; + gs->send_filename_to_gs = FALSE; + } + + /* We have to set up the orientation of the document */ + + + /* orientation can only be portrait, and landscape or none. + This is the document default. A document can have + pages in landscape and some in portrait */ + if(gs->override_orientation) { + /* If the orientation should be override... + then gs->orientation has already the correct + value (it was set when the widget was created */ + /* So do nothing */ + + } + else { + /* Otherwise, set the proper orientation for the doc */ + gs->real_orientation = gs->doc->orientation; + } + } + gtk_gs_set_page_size(gs, -1, gs->current_page); + gtk_widget_queue_resize(&(gs->widget)); + gs->loaded = TRUE; + + gs->gs_status = _("Document loaded."); + + return gs->loaded; +} + + +gboolean +gtk_gs_next_page(GtkGS * gs) +{ + XEvent event; + + g_return_val_if_fail(gs != NULL, FALSE); + g_return_val_if_fail(GTK_IS_GS(gs), FALSE); + + if(gs->interpreter_pid == 0) { /* no interpreter active */ + return FALSE; + } + + if(gs->busy) { /* interpreter is busy */ + return FALSE; + } + + gs->busy = TRUE; + + event.xclient.type = ClientMessage; + event.xclient.display = gdk_display; + event.xclient.window = gs->message_window; + event.xclient.message_type = gdk_x11_atom_to_xatom(gs_class->next_atom); + event.xclient.format = 32; + + gdk_error_trap_push(); + XSendEvent(gdk_display, gs->message_window, FALSE, 0, &event); + gdk_flush(); + gdk_error_trap_pop(); + + return TRUE; +} + +gint +gtk_gs_get_current_page(GtkGS * gs) +{ + g_return_val_if_fail(gs != NULL, -1); + g_return_val_if_fail(GTK_IS_GS(gs), -1); + + return gs->current_page; +} + +gint +gtk_gs_get_page_count(GtkGS * gs) +{ + if(!gs->gs_filename) + return 0; + + if(gs->doc) { + if(gs->structured_doc) + return gs->doc->numpages; + else + return G_MAXINT; + } + else + return 0; +} + +gboolean +gtk_gs_goto_page(GtkGS * gs, gint page) +{ + g_return_val_if_fail(gs != NULL, FALSE); + g_return_val_if_fail(GTK_IS_GS(gs), FALSE); + + if(!gs->gs_filename) { + return FALSE; + } + + /* range checking... */ + if(page < 0) + page = 0; + + if(gs->structured_doc && gs->doc) { + if(page >= gs->doc->numpages) + page = gs->doc->numpages - 1; + + if(page == gs->current_page && !gs->changed) + return TRUE; + + gs->current_page = page; + + if(!GTK_WIDGET_REALIZED(gs)) + return FALSE; + + if(gs->doc->pages[page].orientation != NONE && + !gs->override_orientation && + gs->doc->pages[page].orientation != gs->real_orientation) { + gs->real_orientation = gs->doc->pages[page].orientation; + gs->changed = TRUE; + } + + gtk_gs_set_page_size(gs, -1, page); + + gs->changed = FALSE; + + if(is_interpreter_ready(gs)) { + gtk_gs_next_page(gs); + } + else { + gtk_gs_enable_interpreter(gs); + send_ps(gs, gs->doc->beginprolog, gs->doc->lenprolog, FALSE); + send_ps(gs, gs->doc->beginsetup, gs->doc->lensetup, FALSE); + } + + send_ps(gs, gs->doc->pages[gs->current_page].begin, + gs->doc->pages[gs->current_page].len, FALSE); + } + else { + /* Unstructured document */ + /* In the case of non structured documents, + GS read the PS from the actual file (via command + line. Hence, ggv only send a signal next page. + If ghostview is not running it is usually because + the last page of the file was displayed. In that + case, ggv restarts GS again and the first page is displayed. + */ + if(page == gs->current_page && !gs->changed) + return TRUE; + + if(!GTK_WIDGET_REALIZED(gs)) + return FALSE; + + if(!is_interpreter_ready(gs)) + gtk_gs_enable_interpreter(gs); + + gs->current_page = page; + + gtk_gs_next_page(gs); + } + return TRUE; +} + +/* + * set pagesize sets the size from + * if new_pagesize is -1, then it is set to either + * a) the default settings of pageid, if they exist, or if pageid != -1. + * b) the default setting of the document, if it exists. + * c) the default setting of the widget. + * otherwise, the new_pagesize is used as the pagesize + */ +gboolean +gtk_gs_set_page_size(GtkGS * gs, gint new_pagesize, gint pageid) +{ + gint new_llx = 0; + gint new_lly = 0; + gint new_urx = 0; + gint new_ury = 0; + GtkGSPaperSize *papersizes = gtk_gs_defaults_get_paper_sizes(); + + g_return_val_if_fail(gs != NULL, FALSE); + g_return_val_if_fail(GTK_IS_GS(gs), FALSE); + + if(new_pagesize == -1) { + if(gs->default_size > 0) + new_pagesize = gs->default_size; + if(!gs->override_size && gs->doc) { + /* If we have a document: + We use -- the page size (if specified) + or the doc. size (if specified) + or the page bbox (if specified) + or the bounding box + */ + if((pageid >= 0) && (gs->doc->numpages > pageid) && + (gs->doc->pages) && (gs->doc->pages[pageid].size)) { + new_pagesize = gs->doc->pages[pageid].size - gs->doc->size; + } + else if(gs->doc->default_page_size != NULL) { + new_pagesize = gs->doc->default_page_size - gs->doc->size; + } + else if((pageid >= 0) && + (gs->doc->numpages > pageid) && + (gs->doc->pages) && + (gs->doc->pages[pageid].boundingbox[URX] > + gs->doc->pages[pageid].boundingbox[LLX]) && + (gs->doc->pages[pageid].boundingbox[URY] > + gs->doc->pages[pageid].boundingbox[LLY])) { + new_pagesize = -1; + } + else if((gs->doc->boundingbox[URX] > gs->doc->boundingbox[LLX]) && + (gs->doc->boundingbox[URY] > gs->doc->boundingbox[LLY])) { + new_pagesize = -1; + } + } + } + + /* Compute bounding box */ + if(gs->doc && ((gs->doc->epsf && !gs->override_size) || new_pagesize == -1)) { /* epsf or bbox */ + if((pageid >= 0) && + (gs->doc->pages) && + (gs->doc->pages[pageid].boundingbox[URX] > + gs->doc->pages[pageid].boundingbox[LLX]) + && (gs->doc->pages[pageid].boundingbox[URY] > + gs->doc->pages[pageid].boundingbox[LLY])) { + /* use page bbox */ + new_llx = gs->doc->pages[pageid].boundingbox[LLX]; + new_lly = gs->doc->pages[pageid].boundingbox[LLY]; + new_urx = gs->doc->pages[pageid].boundingbox[URX]; + new_ury = gs->doc->pages[pageid].boundingbox[URY]; + } + else if((gs->doc->boundingbox[URX] > gs->doc->boundingbox[LLX]) && + (gs->doc->boundingbox[URY] > gs->doc->boundingbox[LLY])) { + /* use doc bbox */ + new_llx = gs->doc->boundingbox[LLX]; + new_lly = gs->doc->boundingbox[LLY]; + new_urx = gs->doc->boundingbox[URX]; + new_ury = gs->doc->boundingbox[URY]; + } + } + else { + if(new_pagesize < 0) + new_pagesize = gs->default_size; + new_llx = new_lly = 0; + if(gs->doc && !gs->override_size && gs->doc->size && + (new_pagesize < gs->doc->numsizes)) { + new_urx = gs->doc->size[new_pagesize].width; + new_ury = gs->doc->size[new_pagesize].height; + } + else { + new_urx = papersizes[new_pagesize].width; + new_ury = papersizes[new_pagesize].height; + } + } + + if(new_urx <= new_llx) + new_urx = papersizes[12].width; + if(new_ury <= new_lly) + new_ury = papersizes[12].height; + + /* If bounding box changed, setup for new size. */ + /* gtk_gs_disable_interpreter (gs); */ + if((new_llx != gs->llx) || (new_lly != gs->lly) || + (new_urx != gs->urx) || (new_ury != gs->ury)) { + gs->llx = new_llx; + gs->lly = new_lly; + gs->urx = new_urx; + gs->ury = new_ury; + gs->changed = TRUE; + } + + if(gs->changed) { + if(GTK_WIDGET_REALIZED(gs)) { + set_up_page(gs); + gtk_widget_queue_resize(&(gs->widget)); + } + return TRUE; + } + + return FALSE; +} + +void +gtk_gs_set_override_orientation(GtkGS * gs, gboolean bNewOverride) +{ + gint iOldOrientation; + + g_return_if_fail(gs != NULL); + g_return_if_fail(GTK_IS_GS(gs)); + + iOldOrientation = gtk_gs_get_orientation(gs); + + gs->override_orientation = bNewOverride; + + /* If the current orientation is different from the + new orientation then redisplay */ + if(iOldOrientation != gtk_gs_get_orientation(gs)) { + gs->changed = TRUE; + if(GTK_WIDGET_REALIZED(gs)) + set_up_page(gs); + } + gtk_widget_queue_resize(&(gs->widget)); +} + +gboolean +gtk_gs_get_override_orientation(GtkGS * gs) +{ + g_return_val_if_fail(gs != NULL, FALSE); + g_return_val_if_fail(GTK_IS_GS(gs), FALSE); + + return gs->override_orientation; +} + +void +gtk_gs_set_override_size(GtkGS * gs, gboolean f) +{ + g_return_if_fail(gs != NULL); + g_return_if_fail(GTK_IS_GS(gs)); + + if(f != gs->override_size) { + gs->override_size = f; + gs->changed = TRUE; + gtk_gs_set_page_size(gs, -1, gs->current_page); + if(GTK_WIDGET_REALIZED(gs)) + set_up_page(gs); + } + gtk_widget_queue_resize(&(gs->widget)); +} + +gboolean +gtk_gs_get_override_size(GtkGS * gs) +{ + g_return_val_if_fail(gs != NULL, FALSE); + g_return_val_if_fail(GTK_IS_GS(gs), FALSE); + + return gs->override_size; +} + +void +gtk_gs_set_zoom(GtkGS * gs, gfloat zoom) +{ + g_return_if_fail(gs != NULL); + g_return_if_fail(GTK_IS_GS(gs)); + + switch (gs->zoom_mode) { + case GTK_GS_ZOOM_FIT_WIDTH: + zoom = gtk_gs_zoom_to_fit(gs, TRUE); + break; + case GTK_GS_ZOOM_FIT_PAGE: + zoom = gtk_gs_zoom_to_fit(gs, FALSE); + break; + case GTK_GS_ZOOM_ABSOLUTE: + default: + break; + } + if(zoom < ggv_zoom_levels[0]) + zoom = ggv_zoom_levels[0]; + else if(zoom > ggv_zoom_levels[ggv_max_zoom_levels]) + zoom = ggv_zoom_levels[ggv_max_zoom_levels]; + if(fabs(gs->zoom_factor - zoom) > 0.001) { + gs->zoom_factor = zoom; + if(GTK_WIDGET_REALIZED(gs)) + set_up_page(gs); + gs->changed = TRUE; + gtk_widget_queue_resize(&(gs->widget)); + } +} + +gfloat +gtk_gs_get_zoom(GtkGS * gs) +{ + g_return_val_if_fail(gs != NULL, 0.0); + g_return_val_if_fail(GTK_IS_GS(gs), 0.0); + + return gs->zoom_factor; +} + +gfloat +gtk_gs_zoom_to_fit(GtkGS * gs, gboolean fit_width) +{ + gint new_y; + gfloat new_zoom; + guint avail_w, avail_h; + + g_return_val_if_fail(gs != NULL, 0.0); + g_return_val_if_fail(GTK_IS_GS(gs), 0.0); + + avail_w = (gs->avail_w > 0) ? gs->avail_w : gs->width; + avail_h = (gs->avail_h > 0) ? gs->avail_h : gs->height; + + new_zoom = ((gfloat) avail_w) / ((gfloat) gs->width) * gs->zoom_factor; + if(!fit_width) { + new_y = new_zoom * ((gfloat) gs->height) / gs->zoom_factor; + if(new_y > avail_h) + new_zoom = ((gfloat) avail_h) / ((gfloat) gs->height) * gs->zoom_factor; + } + + return new_zoom; +} + +gboolean +gtk_gs_set_default_orientation(GtkGS * gs, gint orientation) +{ + gint iOldOrientation; + + g_return_val_if_fail(gs != NULL, FALSE); + g_return_val_if_fail(GTK_IS_GS(gs), FALSE); + g_return_val_if_fail((orientation == GTK_GS_ORIENTATION_PORTRAIT) || + (orientation == GTK_GS_ORIENTATION_LANDSCAPE) || + (orientation == GTK_GS_ORIENTATION_UPSIDEDOWN) || + (orientation == GTK_GS_ORIENTATION_SEASCAPE), FALSE); + + iOldOrientation = gtk_gs_get_orientation(gs); + gs->fallback_orientation = orientation; + + /* We are setting the fallback orientation */ + if(iOldOrientation != gtk_gs_get_orientation(gs)) { + gs->changed = TRUE; + if(GTK_WIDGET_REALIZED(gs)) + set_up_page(gs); + gtk_widget_queue_resize(&(gs->widget)); + return TRUE; + } + + return FALSE; +} + +gint +gtk_gs_get_default_orientation(GtkGS * gs) +{ + g_return_val_if_fail(gs != NULL, -1); + g_return_val_if_fail(GTK_IS_GS(gs), -1); + + return gs->fallback_orientation; +} + +gint +gtk_gs_get_orientation(GtkGS * gs) +{ + g_return_val_if_fail(gs != NULL, -1); + g_return_val_if_fail(GTK_IS_GS(gs), -1); + + if(gs->doc) { + if(gs->structured_doc) { + if(gs->doc->pages[MAX(gs->current_page, 0)].orientation != + GTK_GS_ORIENTATION_NONE) + gs->real_orientation = + gs->doc->pages[MAX(gs->current_page, 0)].orientation; + else + gs->real_orientation = gs->doc->default_page_orientation; + } + + if(gs->real_orientation == GTK_GS_ORIENTATION_NONE) + gs->real_orientation = gs->doc->orientation; + } + + if(gs->override_orientation || + gs->real_orientation == GTK_GS_ORIENTATION_NONE) + return gs->fallback_orientation; + else + return gs->real_orientation; +} + +void +gtk_gs_set_default_size(GtkGS * gs, gint size) +{ + g_return_if_fail(gs != NULL); + g_return_if_fail(GTK_IS_GS(gs)); + + gs->default_size = size; + gtk_gs_set_page_size(gs, -1, gs->current_page); +} + +gint +gtk_gs_get_default_size(GtkGS * gs) +{ + g_return_val_if_fail(gs != NULL, -1); + g_return_val_if_fail(GTK_IS_GS(gs), -1); + + return gs->default_size; +} + +void +gtk_gs_set_respect_eof(GtkGS * gs, gboolean f) +{ + g_return_if_fail(gs != NULL); + g_return_if_fail(GTK_IS_GS(gs)); + + if(gs->respect_eof == f) + return; + + gs->respect_eof = f; + gtk_gs_set_page_size(gs, -1, gs->current_page); +} + +gint +gtk_gs_get_respect_eof(GtkGS * gs) +{ + g_return_val_if_fail(gs != NULL, -1); + g_return_val_if_fail(GTK_IS_GS(gs), -1); + + return gs->respect_eof; +} + +void +gtk_gs_set_antialiasing(GtkGS * gs, gboolean f) +{ + g_return_if_fail(gs != NULL); + g_return_if_fail(GTK_IS_GS(gs)); + + if(gs->antialiased == f) + return; + + gs->antialiased = f; + gs->changed = TRUE; + if(GTK_WIDGET_REALIZED(gs)) + start_interpreter(gs); + gtk_gs_goto_page(gs, gs->current_page); +} + +gint +gtk_gs_get_antialiasing(GtkGS * gs) +{ + g_return_val_if_fail(gs != NULL, -1); + g_return_val_if_fail(GTK_IS_GS(gs), -1); + + return gs->antialiased; +} + +const gchar * +gtk_gs_get_document_title(GtkGS * gs) +{ + g_return_val_if_fail(gs != NULL, NULL); + g_return_val_if_fail(GTK_IS_GS(gs), NULL); + + if(gs->doc && gs->doc->title) + return gs->doc->title; + + return NULL; +} + +guint +gtk_gs_get_document_numpages(GtkGS * widget) +{ + g_return_val_if_fail(widget != NULL, 0); + g_return_val_if_fail(GTK_IS_GS(widget), 0); + + if(widget->doc) + return widget->doc->numpages; + + return 0; +} + +const gchar * +gtk_gs_get_document_page_label(GtkGS * widget, int page) +{ + g_return_val_if_fail(widget != NULL, NULL); + g_return_val_if_fail(GTK_IS_GS(widget), NULL); + + if(widget->doc && widget->doc->pages && (widget->doc->numpages >= page)) + return widget->doc->pages[page - 1].label; + + return NULL; +} + +gint +gtk_gs_get_size_index(const gchar * string, GtkGSPaperSize * size) +{ + guint idx = 0; + + while(size[idx].name != NULL) { + if(strcmp(size[idx].name, string) == 0) + return idx; + idx++; + } + + return -1; +} + +void +gtk_gs_start_scroll(GtkGS * gs) +{ + gint x, y, w, h; + + if(!GTK_WIDGET_REALIZED(gs) || !gs->show_scroll_rect) + return; + + gdk_window_get_geometry(gs->pstarget, &x, &y, &w, &h, NULL); + gs->scroll_start_x = MAX(-x, 0); + gs->scroll_start_y = MAX(-y, 0); + gs->scroll_width = MIN(gs->widget.allocation.width - 1, w - 1); + gs->scroll_height = MIN(gs->widget.allocation.height - 1, h - 1); + + if(gs->bpixmap) { + GdkRectangle rect; + rect.x = gs->scroll_start_x; + rect.y = gs->scroll_start_y; + rect.width = gs->scroll_width + 1; + rect.height = gs->scroll_height + 1; + gdk_draw_rectangle(gs->bpixmap, gs->psgc, FALSE, + gs->scroll_start_x, gs->scroll_start_y, + gs->scroll_width, gs->scroll_height); + rect.width = 1; + gdk_window_invalidate_rect(gs->pstarget, &rect, TRUE); + rect.x = gs->scroll_start_x + gs->scroll_width; + gdk_window_invalidate_rect(gs->pstarget, &rect, TRUE); + rect.x = gs->scroll_start_x + 1; + rect.width = gs->scroll_start_x + gs->scroll_width - 1; + rect.height = 1; + gdk_window_invalidate_rect(gs->pstarget, &rect, TRUE); + rect.y = gs->scroll_start_y + gs->scroll_height; + gdk_window_invalidate_rect(gs->pstarget, &rect, TRUE); + } +} + +void +gtk_gs_end_scroll(GtkGS * gs) +{ + if(!GTK_WIDGET_REALIZED(gs) || !gs->show_scroll_rect) + return; + + if(gs->scroll_start_x == -1 || gs->scroll_start_y == -1) + return; + + if(gs->bpixmap) { + GdkRectangle rect; + rect.x = gs->scroll_start_x; + rect.y = gs->scroll_start_y; + rect.width = gs->scroll_width + 1; + rect.height = gs->scroll_height + 1; + gdk_draw_rectangle(gs->bpixmap, gs->psgc, FALSE, + gs->scroll_start_x, gs->scroll_start_y, + gs->scroll_width, gs->scroll_height); + rect.width = 1; + gdk_window_invalidate_rect(gs->pstarget, &rect, TRUE); + rect.x = gs->scroll_start_x + gs->scroll_width; + gdk_window_invalidate_rect(gs->pstarget, &rect, TRUE); + rect.x = gs->scroll_start_x + 1; + rect.width = gs->scroll_start_x + gs->scroll_width - 1; + rect.height = 1; + gdk_window_invalidate_rect(gs->pstarget, &rect, TRUE); + rect.y = gs->scroll_start_y + gs->scroll_height; + gdk_window_invalidate_rect(gs->pstarget, &rect, TRUE); + } + gs->scroll_start_x = -1; + gs->scroll_start_y = -1; +} + +void +gtk_gs_set_show_scroll_rect(GtkGS * gs, gboolean f) +{ + gs->show_scroll_rect = f; +} + +gboolean +gtk_gs_get_show_scroll_rect(GtkGS * gs) +{ + return gs->show_scroll_rect; +} + +gboolean +gtk_gs_scroll_to_edge(GtkGS * gs, GtkPositionType vertical, + GtkPositionType horizontal) +{ + g_return_val_if_fail(gs != NULL, FALSE); + g_return_val_if_fail(GTK_IS_GS(gs), FALSE); + + switch (vertical) { + case GTK_POS_TOP: + gs->vadj->value = gs->vadj->lower; + gtk_adjustment_value_changed(gs->vadj); + break; + case GTK_POS_BOTTOM: + gs->vadj->value = gs->vadj->upper - gs->vadj->page_size; + gtk_adjustment_value_changed(gs->vadj); + break; + default: + g_assert(0); /* Illegal parameter error */ + } + + + switch (horizontal) { + case GTK_POS_TOP: + gs->hadj->value = gs->hadj->lower; + gtk_adjustment_value_changed(gs->hadj); + break; + case GTK_POS_BOTTOM: + gs->hadj->value = gs->hadj->upper - gs->hadj->page_size; + gtk_adjustment_value_changed(gs->hadj); + break; + default: + g_assert(0); /* Illegal parameter error */ + } + + return TRUE; +} + +gboolean +gtk_gs_scroll_step(GtkGS * gs, GtkScrollType direction, gboolean dowrap) +{ + GtkAdjustment *MainAdj; /* We will move this adjustment */ + GtkAdjustment *SecoAdj; /* And this _only_ if we can't move MainAdj (ie. we're edge) + and there is wrapping */ + + gboolean MoveHorizontal = TRUE; /* Positive if we move horizontal */ + gboolean DirectionFlag = TRUE; /* Positive if we move towards upper */ + g_return_val_if_fail(gs != NULL, FALSE); + g_return_val_if_fail(GTK_IS_GS(gs), FALSE); + +#define EPSILON 0.00005 + +#define CHECK_THERE_IS_NO_LOWER_SPACE(adj) \ + ((adj)->value - (EPSILON) <= (adj)->lower) +#define CHECK_THERE_IS_NO_UPPER_SPACE(adj) \ + ((adj)->value + (EPSILON) >= (adj)->upper - (adj)->page_size) + +#define CHECK_THERE_IS_NO_SPACE_FOR_STEP(adj,dir) \ + (dir?CHECK_THERE_IS_NO_UPPER_SPACE(adj):CHECK_THERE_IS_NO_LOWER_SPACE(adj)) + + /* To make code more readable, we make a macro */ +#define ADVANCE_TOWARDS_LOWER(adj) \ + (adj->value -= gs->scroll_step * (adj->page_size)) +#define ADVANCE_TOWARDS_UPPER(adj) \ + (adj->value += gs->scroll_step * (adj->page_size)) + +#define ADVANCE_STEP(adj,dir) \ + (dir?ADVANCE_TOWARDS_UPPER(adj):ADVANCE_TOWARDS_LOWER(adj)) + +#define MOVE_TO_LOWER_EDGE(adj) \ + (adj->value = adj->lower) +#define MOVE_TO_UPPER_EDGE(adj) \ + (adj->value = adj->upper - adj->page_size) + + /* if upper is 1 goto upper, otherwise to lower */ +#define MOVE_TO_EDGE(adj,upper) (upper?MOVE_TO_UPPER_EDGE(adj):MOVE_TO_LOWER_EDGE(adj)) + + /* These variables make our life easier */ + switch (direction) { + case GTK_SCROLL_STEP_RIGHT: + MoveHorizontal = TRUE; + DirectionFlag = TRUE; + break; + case GTK_SCROLL_STEP_LEFT: + MoveHorizontal = TRUE; + DirectionFlag = FALSE; + break; + case GTK_SCROLL_STEP_DOWN: + MoveHorizontal = FALSE; + DirectionFlag = TRUE; + break; + case GTK_SCROLL_STEP_UP: + MoveHorizontal = FALSE; + DirectionFlag = FALSE; + break; + default: + g_warning("Illegal scroll step direction."); + } + + if(MoveHorizontal) { + MainAdj = gs->hadj; + SecoAdj = gs->vadj; + } + else { + MainAdj = gs->vadj; + SecoAdj = gs->hadj; + } + + if(CHECK_THERE_IS_NO_SPACE_FOR_STEP(MainAdj, DirectionFlag)) { + if(!dowrap) + return FALSE; + /* Move in the oposite axis */ + if(CHECK_THERE_IS_NO_SPACE_FOR_STEP(SecoAdj, DirectionFlag)) { + /* there is no place to move, we need a new page */ + return FALSE; + } + ADVANCE_STEP(SecoAdj, DirectionFlag); + + if(CHECK_THERE_IS_NO_SPACE_FOR_STEP(SecoAdj, DirectionFlag)) { + /* We move it too far, lets move it to the edge */ + MOVE_TO_EDGE(SecoAdj, DirectionFlag); + } + /* now move to edge (other axis) in oposite direction */ + MOVE_TO_EDGE(MainAdj, !DirectionFlag); + gtk_adjustment_value_changed(SecoAdj); + return TRUE; + } + + /* Now we know we can move in the direction sought */ + ADVANCE_STEP(MainAdj, DirectionFlag); + + if(CHECK_THERE_IS_NO_SPACE_FOR_STEP(MainAdj, DirectionFlag)) { + /* We move it too far, lets move it to the edge */ + MOVE_TO_EDGE(MainAdj, DirectionFlag); + } + gtk_adjustment_value_changed(MainAdj); + + return TRUE; +} + +gchar * +gtk_gs_get_postscript(GtkGS * gs, gint * pages) +{ + GtkGSDocSink *sink; + gchar *doc; + gboolean free_pages = FALSE; + + if(pages == NULL) { + if(!gs->structured_doc) { + FILE *f; + struct stat sb; + + if(stat(GTK_GS_GET_PS_FILE(gs), &sb)) + return NULL; + doc = g_new(gchar, sb.st_size); + if(!doc) + return NULL; + f = fopen(GTK_GS_GET_PS_FILE(gs), "r"); + if(NULL != f && fread(doc, sb.st_size, 1, f) != 1) { + g_free(doc); + doc = NULL; + } + if(NULL != f) + fclose(f); + return doc; + } + else { + int i, n = gtk_gs_get_page_count(gs); + pages = g_new0(gint, n); + for(i = 0; i < n; i++) + pages[i] = TRUE; + free_pages = TRUE; + } + } + + sink = gtk_gs_doc_sink_new(); + + if(GTK_GS_IS_PDF(gs)) { + gchar *tmpn = g_strconcat(g_get_tmp_dir(), "/ggvXXXXXX", NULL); + gchar *cmd, *fname; + int tmpfd; + + if((tmpfd = mkstemp(tmpn)) < 0) { + g_free(tmpn); + return NULL; + } + close(tmpfd); + fname = ggv_quote_filename(gs->gs_filename_unc ? + gs->gs_filename_unc : gs->gs_filename); + cmd = g_strdup_printf(gtk_gs_defaults_get_convert_pdf_cmd(), tmpn, fname); + g_free(fname); + if((system(cmd) == 0) && ggv_file_readable(tmpn)) { + GtkWidget *tmp_gs; + tmp_gs = gtk_gs_new_from_file(NULL, NULL, tmpn); + if(NULL != tmp_gs) { + if(GTK_GS(tmp_gs)->loaded) + pscopydoc(sink, tmpn, GTK_GS(tmp_gs)->doc, pages); + gtk_widget_destroy(tmp_gs); + } + } + g_free(cmd); + g_free(tmpn); + } + else { + /* Use uncompressed file if necessary */ + pscopydoc(sink, GTK_GS_GET_PS_FILE(gs), gs->doc, pages); + } + if(free_pages) + g_free(pages); + doc = gtk_gs_doc_sink_get_buffer(sink); + gtk_gs_doc_sink_free(sink); + return doc; +} + +void +gtk_gs_set_adjustments(GtkGS * gs, GtkAdjustment * hadj, GtkAdjustment * vadj) +{ + g_return_if_fail(gs != NULL); + g_return_if_fail(GTK_IS_GS(gs)); + if(hadj) + g_return_if_fail(GTK_IS_ADJUSTMENT(hadj)); + else + hadj = GTK_ADJUSTMENT(gtk_adjustment_new(0.0, 0.0, 1.0, 0.0, 0.0, 1.0)); + if(vadj) + g_return_if_fail(GTK_IS_ADJUSTMENT(vadj)); + else + vadj = GTK_ADJUSTMENT(gtk_adjustment_new(0.0, 0.0, 1.0, 0.0, 0.0, 1.0)); + + if(gs->hadj && (gs->hadj != hadj)) { + g_signal_handlers_disconnect_matched(G_OBJECT(gs->hadj), + G_SIGNAL_MATCH_DATA, + 0, 0, NULL, NULL, gs); + gtk_object_unref(GTK_OBJECT(gs->hadj)); + } + if(gs->vadj && (gs->vadj != vadj)) { + g_signal_handlers_disconnect_matched(G_OBJECT(gs->vadj), + G_SIGNAL_MATCH_DATA, + 0, 0, NULL, NULL, gs); + gtk_object_unref(GTK_OBJECT(gs->vadj)); + } + if(gs->hadj != hadj) { + hadj->lower = 0.0; + hadj->upper = 1.0; + hadj->value = 0.0; + hadj->page_size = 1.0; + hadj->page_increment = 1.0; + gs->hadj = hadj; + gtk_object_ref(GTK_OBJECT(gs->hadj)); + gtk_object_sink(GTK_OBJECT(gs->hadj)); + + g_signal_connect(G_OBJECT(hadj), "value_changed", + G_CALLBACK(gtk_gs_value_adjustment_changed), + (gpointer) gs); + } + if(gs->vadj != vadj) { + vadj->lower = 0.0; + vadj->upper = 1.0; + vadj->value = 0.0; + vadj->page_size = 1.0; + vadj->page_increment = 1.0; + gs->vadj = vadj; + gtk_object_ref(GTK_OBJECT(gs->vadj)); + gtk_object_sink(GTK_OBJECT(gs->vadj)); + + g_signal_connect(G_OBJECT(vadj), "value_changed", + G_CALLBACK(gtk_gs_value_adjustment_changed), + (gpointer) gs); + } + if(GTK_WIDGET_REALIZED(gs)) + gtk_gs_munge_adjustments(gs); +} + + +void +gtk_gs_set_scroll_step(GtkGS * gs, gfloat scroll_step) +{ + gs->scroll_step = scroll_step; +} + +gfloat +gtk_gs_get_scroll_step(GtkGS * gs) +{ + return gs->scroll_step; +} + +void +gtk_gs_set_zoom_mode(GtkGS * gs, GtkGSZoomMode zoom_mode) +{ + if(zoom_mode != gs->zoom_mode) { + gs->zoom_mode = zoom_mode; + gtk_gs_set_zoom(gs, 1.0); + } +} + +GtkGSZoomMode +gtk_gs_get_zoom_mode(GtkGS * gs) +{ + return gs->zoom_mode; +} + +void +gtk_gs_set_available_size(GtkGS * gs, guint avail_w, guint avail_h) +{ + gs->avail_w = avail_w; + gs->avail_h = avail_h; + if(gs->zoom_mode != GTK_GS_ZOOM_ABSOLUTE) { + gtk_gs_set_zoom(gs, 0.0); + } +} diff --git a/ps/gtkgs.h b/ps/gtkgs.h new file mode 100644 index 0000000..35f9bfd --- /dev/null +++ b/ps/gtkgs.h @@ -0,0 +1,241 @@ +/* + * Ghostscript widget for GTK/GNOME + * + * Copyright 1998 - 2005 The Free Software Foundation + * + * Authors: Jaka Mocnik, Federico Mena (Quartic), Szekeres Istvan (Pista) + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + */ + +#ifndef __GTK_GS_H__ +#define __GTK_GS_H__ + +#include +#include + +#include + +#include +#include +#include +#include +#include + +G_BEGIN_DECLS + +#define GTK_GS(obj) GTK_CHECK_CAST (obj, gtk_gs_get_type (), GtkGS) +#define GTK_GS_CLASS(klass) GTK_CHECK_CLASS_CAST (klass, gtk_gs_get_type (), GtkGSClass) +#define GTK_IS_GS(obj) GTK_CHECK_TYPE (obj, gtk_gs_get_type()) + +typedef struct _GtkGS GtkGS; +typedef struct _GtkGSClass GtkGSClass; +typedef struct _GtkGSPaperSize GtkGSPaperSize; + +typedef enum { + GTK_GS_ORIENTATION_NONE = -1, + GTK_GS_ORIENTATION_PORTRAIT = 0, + GTK_GS_ORIENTATION_SEASCAPE = 3, + GTK_GS_ORIENTATION_UPSIDEDOWN = 2, + GTK_GS_ORIENTATION_LANDSCAPE = 1 +} GtkGSOrientation; + +typedef enum { + GTK_GS_ZOOM_ABSOLUTE = 0, + GTK_GS_ZOOM_FIT_WIDTH = 1, + GTK_GS_ZOOM_FIT_PAGE = 2 +} GtkGSZoomMode; + +struct _GtkGS { + GtkWidget widget; /* the main widget */ + GdkWindow *pstarget; /* the window passed to gv + * it is a child of widget... + */ + GtkAdjustment *hadj, *vadj; + + GdkGC *psgc; + gint scroll_start_x, scroll_start_y; + gint scroll_width, scroll_height; + gboolean show_scroll_rect; + + GtkGSZoomMode zoom_mode; + + GdkPixmap *bpixmap; /* Backing pixmap */ + int use_bpixmap; + + long message_window; /* Used by ghostview to receive messages from app */ + + int disable_start; /* Can the interpreter be started? */ + pid_t interpreter_pid; /* PID of interpreter, -1 if none */ + int interpreter_input; /* stdin of interpreter */ + int interpreter_output; /* stdout of interpreter */ + int interpreter_err; /* stderr of interpreter */ + guint interpreter_input_id; + guint interpreter_output_id; + guint interpreter_error_id; + + gint llx; + gint lly; + gint urx; + gint ury; + gint left_margin; + gint right_margin; + gint top_margin; + gint bottom_margin; + gint width; /* Size of window at last setup() */ + gint height; + gboolean busy; /* Is gs busy drawing? */ + gboolean changed; /* Anything changed since setup */ + gfloat zoom_factor; + gfloat scroll_step; + gint current_page; + gboolean structured_doc; + gboolean loaded; + + struct record_list *ps_input; + gchar *input_buffer_ptr; + guint bytes_left; + guint buffer_bytes_left; + + FILE *gs_psfile; /* the currently loaded FILE */ + gchar *gs_filename; /* the currently loaded filename */ + gchar *gs_filename_dsc; /* Used to browse PDF to PS */ + gchar *gs_filename_unc; /* Uncompressed file */ + gchar *input_buffer; + gint gs_scanstyle; + gboolean send_filename_to_gs; /* True if gs should read from file directly */ + gboolean reading_from_pipe; /* True if ggv is reading input from pipe */ + struct document *doc; + + /* User selected options... */ + gboolean antialiased; /* Using antialiased display */ + gboolean respect_eof; /* respect EOF comments? */ + gint default_size; + gboolean override_size; + gfloat xdpi, ydpi; + gboolean override_orientation; + gint fallback_orientation; /* Orientation to use if override */ + gint real_orientation; /* Real orientation from the document */ + + const gchar *gs_status; /* GtkGS status */ + + guint avail_w, avail_h; +}; + +struct _GtkGSClass { + GtkWidgetClass parent_class; + GdkAtom gs_atom; + GdkAtom gs_colors_atom; + GdkAtom next_atom; + GdkAtom page_atom; + GdkAtom done_atom; + GdkAtom string_atom; + + GConfClient *gconf_client; + + void (*interpreter_message) (GtkGS *, gchar *, gpointer); + void (*interpreter_error) (GtkGS *, gint, gpointer); + void (*set_scroll_adjustments) (GtkGS *, GtkAdjustment *, GtkAdjustment *); +}; + + +/* structure to describe section of file to send to ghostscript */ +struct record_list { + FILE *fp; + long begin; + guint len; + gboolean seek_needed; + gboolean close; + struct record_list *next; +}; + +struct _GtkGSPaperSize { + gchar *name; + gint width, height; +}; + +GType gtk_gs_get_type(void); + +GtkWidget *gtk_gs_new_from_file(GtkAdjustment * hadj, GtkAdjustment * vadj, + gchar * fname); +GtkWidget *gtk_gs_new(GtkAdjustment * hadj, GtkAdjustment * vadj); +gboolean gtk_gs_load(GtkGS * gs, const gchar * fname); +void gtk_gs_reload(GtkGS * gs); + +/* control functions */ +void gtk_gs_center_page(GtkGS * gs); +void gtk_gs_scroll(GtkGS * gs, gint, gint); +gboolean gtk_gs_scroll_step(GtkGS * gs, GtkScrollType direction, + gboolean dowrap); +gboolean gtk_gs_scroll_to_edge(GtkGS * gs, GtkPositionType vertical, + GtkPositionType horizontal); +gboolean gtk_gs_next_page(GtkGS * gs); +gboolean gtk_gs_prev_page(GtkGS * gs); +gboolean gtk_gs_goto_page(GtkGS * gs, gint); +gint gtk_gs_enable_interpreter(GtkGS * gs); +void gtk_gs_disable_interpreter(GtkGS * gs); + +gint gtk_gs_get_current_page(GtkGS * gs); +gint gtk_gs_get_page_count(GtkGS * gs); +gboolean gtk_gs_set_page_size(GtkGS * gs, gint new_pagesize, gint pageid); +gboolean gtk_gs_set_default_orientation(GtkGS * gs, gint orientation); +gint gtk_gs_get_default_orientation(GtkGS * gs); +void gtk_gs_set_default_size(GtkGS * gs, gint size); +gint gtk_gs_get_default_size(GtkGS * gs); +void gtk_gs_set_zoom(GtkGS * gs, gfloat zoom); +gfloat gtk_gs_get_zoom(GtkGS * gs); +void gtk_gs_set_scroll_step(GtkGS * gs, gfloat scroll_step); +gfloat gtk_gs_get_scroll_step(GtkGS * gs); +gfloat gtk_gs_zoom_to_fit(GtkGS * gs, gboolean fit_width); +void gtk_gs_set_center(GtkGS * gs, gfloat hval, gfloat vval); +gint gtk_gs_get_orientation(GtkGS * gs); +void gtk_gs_set_override_orientation(GtkGS * gs, gboolean f); +gboolean gtk_gs_get_override_orientation(GtkGS * gs); +void gtk_gs_set_respect_eof(GtkGS * gs, gboolean f); +gboolean gtk_gs_get_respect_eof(GtkGS * gs); +void gtk_gs_set_antialiasing(GtkGS * gs, gboolean f); +gboolean gtk_gs_get_antialiasing(GtkGS * gs); +void gtk_gs_set_override_size(GtkGS * gs, gboolean f); +gboolean gtk_gs_get_override_size(GtkGS * gs); +const gchar *gtk_gs_get_document_title(GtkGS * widget); +guint gtk_gs_get_document_numpages(GtkGS * widget); +const gchar *gtk_gs_get_document_page_label(GtkGS * widget, int page); +void gtk_gs_set_show_scroll_rect(GtkGS * gs, gboolean f); +gboolean gtk_gs_get_show_scroll_rect(GtkGS * gs); + +void gtk_gs_start_scroll(GtkGS * gs); +void gtk_gs_end_scroll(GtkGS * gs); + +void gtk_gs_set_zoom_mode(GtkGS * gs, GtkGSZoomMode zoom_mode); +GtkGSZoomMode gtk_gs_get_zoom_mode(GtkGS * gs); + +void gtk_gs_set_available_size(GtkGS * gs, guint avail_w, guint avail_h); + +/* utility functions */ +gint gtk_gs_get_size_index(const gchar * string, GtkGSPaperSize * size); + +gchar *gtk_gs_get_postscript(GtkGS * gs, gint * pages); + +#define GTK_GS_IS_COMPRESSED(gs) (GTK_GS(gs)->gs_filename_unc != NULL) +#define GTK_GS_GET_PS_FILE(gs) (GTK_GS_IS_COMPRESSED(gs) ? \ + GTK_GS(gs)->gs_filename_unc : \ + GTK_GS(gs)->gs_filename) +#define GTK_GS_IS_PDF(gs) (GTK_GS(gs)->gs_filename_dsc != NULL) +#define GTK_GS_IS_STRUCTURED_DOC(gs) (GTK_GS(gs)->structured_doc) + +G_END_DECLS + +#endif /* __GTK_GS_H__ */ diff --git a/ps/ps.c b/ps/ps.c new file mode 100644 index 0000000..5726915 --- /dev/null +++ b/ps/ps.c @@ -0,0 +1,1814 @@ +/* + * ps.c -- Postscript scanning and copying routines. + * Copyright (C) 1992, 1998 Timothy O. Theisen + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + * + * Author: Tim Theisen Systems Programmer + * Internet: tim@cs.wisc.edu Department of Computer Sciences + * UUCP: uwvax!tim University of Wisconsin-Madison + * Phone: (608)262-0438 1210 West Dayton Street + * FAX: (608)262-9777 Madison, WI 53706 + */ + +/* 18/3/98 Jake Hamby patch */ + +/* + * 98/03/17: Jake Hamby (jehamby@lightside.com): + * Added support for compressed/gzipped Postscript and PDF files. + * Compressed files are gunzipped to a temporary file, and PDF files are + * scanned by calling Ghostscript to generate a fake DSC file. + * This is based on code from GV 3.5.8, which is available at: + * http://wwwthep.physik.uni-mainz.de/~plass/gv/ + */ + +/* GV by Johannes Plass + * Department of Physics + * Johannes Gutenberg University + * Mainz, Germany + * + * + */ + +/* end of patch */ + +#include +#include +#ifndef SEEK_SET +# define SEEK_SET 0 +#endif +#ifndef BUFSIZ +# define BUFSIZ 1024 +#endif +#include +#include /* #includes the appropriate */ +#include "gtkgs.h" +#include "gsdefaults.h" +#include "ps.h" +#include "gsio.h" + +#include + +/* length calculates string length at compile time */ +/* can only be used with character constants */ +#define length(a) (sizeof(a)-1) +#define iscomment(a, b) (strncmp(a, b, length(b)) == 0) +#define DSCcomment(a) (a[0] == '%' && a[1] == '%') + + /* list of standard paper sizes from Adobe's PPD. */ + +#if 1 //NeedFunctionPrototypes +static char *readline(char *line, int size, FILE * fp, + long *position, unsigned int *line_len); +static char *gettextline(char *line); +static char *get_next_text(char *line, char **next_char); +static int blank(char *line); +#else +static char *readline(); +static char *gettextline(); +static char *get_next_text(); +static int blank(); +#endif + + +static struct page * +pages_new(struct page *pages, int current, int maxpages) +{ + struct page *oldpages = pages; + if(!oldpages) + pages = g_new0(struct page, maxpages); + else + pages = g_renew(struct page, oldpages, maxpages); + for(; current < maxpages; current++) { + memset(&(pages[current]), 0x00, sizeof(struct page)); + pages[current].orientation = GTK_GS_ORIENTATION_NONE; + } + return pages; +} + +/* + * psscan -- scan the PostScript file for document structuring comments. + * + * This scanner is designed to retrieve the information necessary for + * the ghostview previewer. It will scan files that conform to any + * version (1.0, 2.0, 2.1, or 3.0) of the document structuring conventions. + * It does not really care which version of comments the file contains. + * (The comments are largely upward compatible.) It will scan a number + * of non-conforming documents. (You could have part of the document + * conform to V2.0 and the rest conform to V3.0. It would be similar + * to the DC-2 1/2+, it would look funny but it can still fly.) + * + * This routine returns a pointer to the document structure. + * The structure contains the information relevant to previewing. + * These include EPSF flag (to tell if the file is a encapsulated figure), + * Page Size (for the Page Size), Bounding Box (to minimize backing + * pixmap size or determine window size for encapsulated PostScript), + * Orientation of Paper (for default transformation matrix), and + * Page Order. The title and CreationDate are also retrieved to + * help identify the document. + * + * The following comments are examined: + * + * Header section: + * Must start with %!PS-Adobe-. Version numbers ignored. + * Also allowed to be just %!PS, many files seem to have that. + * + * %!PS-Adobe-* [EPSF-*] + * %%BoundingBox: |(atend) + * %%CreationDate: + * %%Orientation: Portrait|Landscape|(atend) + * %%Pages: []|(atend) + * %%PageOrder: Ascend|Descend|Special|(atend) + * %%Title: + * %%DocumentMedia: + * %%DocumentPaperSizes: + * %%EndComments + * + * Note: Either the 3.0 or 2.0 syntax for %%Pages is accepted. + * Also either the 2.0 %%DocumentPaperSizes or the 3.0 + * %%DocumentMedia comments are accepted as well. + * + * The header section ends either explicitly with %%EndComments or + * implicitly with any line that does not begin with %X where X is + * a not whitespace character. + * + * If the file is encapsulated PostScript the optional Preview section + * is next: + * + * %%BeginPreview + * %%EndPreview + * + * This section explicitly begins and ends with the above comments. + * + * Next the Defaults section for version 3 page defaults: + * + * %%BeginDefaults + * %%PageBoundingBox: + * %%PageOrientation: Portrait|Landscape + * %%PageMedia: + * %%EndDefaults + * + * This section explicitly begins and ends with the above comments. + * + * The prolog section either explicitly starts with %%BeginProlog or + * implicitly with any nonblank line. + * + * %%BeginProlog + * %%EndProlog + * + * The Prolog should end with %%EndProlog, however the proglog implicitly + * ends when %%BeginSetup, %%Page, %%Trailer or %%EOF are encountered. + * + * The Setup section is where the version 2 page defaults are found. + * This section either explicitly begins with %%BeginSetup or implicitly + * with any nonblank line after the Prolog. + * + * %%BeginSetup + * %%PageBoundingBox: + * %%PageOrientation: Portrait|Landscape + * %%PaperSize: + * %%EndSetup + * + * The Setup should end with %%EndSetup, however the setup implicitly + * ends when %%Page, %%Trailer or %%EOF are encountered. + * + * Next each page starts explicitly with %%Page and ends implicitly with + * %%Page or %%Trailer or %%EOF. The following comments are recognized: + * + * %%Page: + * %%PageBoundingBox: |(atend) + * %%PageOrientation: Portrait|Landscape + * %%PageMedia: + * %%PaperSize: + * + * The tralier section start explicitly with %%Trailer and end with %%EOF. + * The following comment are examined with the proper (atend) notation + * was used in the header: + * + * %%Trailer + * %%BoundingBox: |(atend) + * %%Orientation: Portrait|Landscape|(atend) + * %%Pages: []|(atend) + * %%PageOrder: Ascend|Descend|Special|(atend) + * %%EOF + * + * + * + A DC-3 received severe damage to one of its wings. The wing was a total + * loss. There was no replacement readily available, so the mechanic + * installed a wing from a DC-2. + */ + +#include + +#include + +struct document * +psscan(FILE * file, int respect_eof, const gchar * fname) +{ + struct document *doc; + int bb_set = NONE; + int pages_set = NONE; + int page_order_set = NONE; + int orientation_set = NONE; + int page_bb_set = NONE; + int page_size_set = NONE; + int preread; /* flag which tells the readline isn't needed */ + int i; + unsigned int maxpages = 0; + unsigned int nextpage = 1; /* Next expected page */ + unsigned int thispage; + int ignore = 0; /* whether to ignore page ordinals */ + char *label; + char line[PSLINELENGTH]; /* 255 characters + 1 newline + 1 NULL */ + char text[PSLINELENGTH]; /* Temporary storage for text */ + long position; /* Position of the current line */ + long beginsection; /* Position of the beginning of the section */ + unsigned int line_len; /* Length of the current line */ + unsigned int section_len; /* Place to accumulate the section length */ + char *next_char; /* 1st char after text returned by get_next_text() */ + char *cp; + GtkGSPaperSize *dmp; + GtkGSPaperSize *papersizes = gtk_gs_defaults_get_paper_sizes(); + + if(!file) + return NULL; + + rewind(file); + + if(!readline(line, sizeof line, file, &position, &line_len)) { + g_print("psscan: empty input file.\n"); + return (NULL); + } + + /* HP printer job language data follows. Some printer drivers add pjl + * commands to switch a pjl printer to postscript mode. If no PS header + * follows, this seems to be a real pjl file. */ + if(iscomment(line, "\033%-12345X@PJL")) { + /* read until first DSC comment */ + while(readline(line, sizeof line, file, &position, &line_len) + && (line[0] != '%')) ; + if(line[0] != '%') { + g_print("psscan error: input files seems to be a PJL file.\n"); + return (NULL); + } + } + + /* Header comments */ + + /* Header should start with "%!PS-Adobe-", but some programms omit + * parts of this or add a ^D at the beginning. */ + if(iscomment(line, "%!PS") || iscomment(line, "\004%!PS")) { + doc = g_new0(struct document, 1); + doc->default_page_orientation = GTK_GS_ORIENTATION_NONE; + doc->orientation = GTK_GS_ORIENTATION_NONE; + + /* ignore possible leading ^D */ + if(*line == '\004') { + position++; + line_len--; + } + +/* Jake Hamby patch 18/3/98 */ + + text[0] = '\0'; + sscanf(line, "%*s %256s", text); + /*doc->epsf = iscomment(text, "EPSF-"); */ + doc->epsf = iscomment(text, "EPSF"); /* Hamby - This line changed */ + doc->beginheader = position; + section_len = line_len; + } + else { + /* There are postscript documents that do not have + %PS at the beginning, usually unstructured. We should GS decide + For instance, the tech reports at this university: + + http://svrc.it.uq.edu.au/Bibliography/svrc-tr.html?94-45 + + add ugly PostScript before the actual document. + + GS and gv is + able to display them correctly as unstructured PS. + + In a way, this makes sense, a program PostScript does not need + the !PS at the beginning. + */ + /* use a test command to determine if ghostscript can + understand this document! */ + gchar *test_cmd; + + test_cmd = g_strdup_printf + ("%s -dNOPAUSE -dBATCH -sDEVICE=nullpage %s " + "1>/dev/null 2>/dev/null", gtk_gs_defaults_get_interpreter_cmd(), fname); + if(system(test_cmd) != 0) { + g_free(test_cmd); + return NULL; + } + g_free(test_cmd); + doc = g_new0(struct document, 1); + doc->default_page_orientation = GTK_GS_ORIENTATION_NONE; + doc->orientation = GTK_GS_ORIENTATION_NONE; + return (doc); + } + + preread = 0; + while(preread || readline(line, sizeof line, file, &position, &line_len)) { + if(!preread) + section_len += line_len; + preread = 0; + if(line[0] != '%' || + iscomment(line + 1, "%EndComments") || + line[1] == ' ' || line[1] == '\t' || line[1] == '\n' || + !isprint(line[1])) { + break; + } + else if(line[1] != '%') { + /* Do nothing */ + } + else if(doc->title == NULL && iscomment(line + 2, "Title:")) { + doc->title = gettextline(line + length("%%Title:")); + } + else if(doc->date == NULL && iscomment(line + 2, "CreationDate:")) { + doc->date = gettextline(line + length("%%CreationDate:")); + } + else if(bb_set == NONE && iscomment(line + 2, "BoundingBox:")) { + sscanf(line + length("%%BoundingBox:"), "%256s", text); + if(strcmp(text, "(atend)") == 0) { + bb_set = ATEND; + } + else { + if(sscanf(line + length("%%BoundingBox:"), "%d %d %d %d", + &(doc->boundingbox[LLX]), + &(doc->boundingbox[LLY]), + &(doc->boundingbox[URX]), &(doc->boundingbox[URY])) == 4) + bb_set = 1; + else { + float fllx, flly, furx, fury; + if(sscanf(line + length("%%BoundingBox:"), "%f %f %f %f", + &fllx, &flly, &furx, &fury) == 4) { + bb_set = 1; + doc->boundingbox[LLX] = fllx; + doc->boundingbox[LLY] = flly; + doc->boundingbox[URX] = furx; + doc->boundingbox[URY] = fury; + if(fllx < doc->boundingbox[LLX]) + doc->boundingbox[LLX]--; + if(flly < doc->boundingbox[LLY]) + doc->boundingbox[LLY]--; + if(furx > doc->boundingbox[URX]) + doc->boundingbox[URX]++; + if(fury > doc->boundingbox[URY]) + doc->boundingbox[URY]++; + } + } + } + } + else if(orientation_set == NONE && iscomment(line + 2, "Orientation:")) { + sscanf(line + length("%%Orientation:"), "%256s", text); + if(strcmp(text, "(atend)") == 0) { + orientation_set = ATEND; + } + else if(strcmp(text, "Portrait") == 0) { + doc->orientation = GTK_GS_ORIENTATION_PORTRAIT; + orientation_set = 1; + } + else if(strcmp(text, "Landscape") == 0) { + doc->orientation = GTK_GS_ORIENTATION_LANDSCAPE; + orientation_set = 1; + } + else if(strcmp(text, "Seascape") == 0) { + doc->orientation = GTK_GS_ORIENTATION_SEASCAPE; + orientation_set = 1; + } + } + else if(page_order_set == NONE && iscomment(line + 2, "PageOrder:")) { + sscanf(line + length("%%PageOrder:"), "%256s", text); + if(strcmp(text, "(atend)") == 0) { + page_order_set = ATEND; + } + else if(strcmp(text, "Ascend") == 0) { + doc->pageorder = ASCEND; + page_order_set = 1; + } + else if(strcmp(text, "Descend") == 0) { + doc->pageorder = DESCEND; + page_order_set = 1; + } + else if(strcmp(text, "Special") == 0) { + doc->pageorder = SPECIAL; + page_order_set = 1; + } + } + else if(pages_set == NONE && iscomment(line + 2, "Pages:")) { + sscanf(line + length("%%Pages:"), "%256s", text); + if(strcmp(text, "(atend)") == 0) { + pages_set = ATEND; + } + else { + switch (sscanf(line + length("%%Pages:"), "%d %d", &maxpages, &i)) { + case 2: + if(page_order_set == NONE) { + if(i == -1) { + doc->pageorder = DESCEND; + page_order_set = 1; + } + else if(i == 0) { + doc->pageorder = SPECIAL; + page_order_set = 1; + } + else if(i == 1) { + doc->pageorder = ASCEND; + page_order_set = 1; + } + } + case 1: + if(maxpages > 0) + doc->pages = pages_new(NULL, 0, maxpages); + } + } + } + else if(doc->numsizes == NONE && iscomment(line + 2, "DocumentMedia:")) { + float w, h; + doc->size = g_new0(GtkGSPaperSize, 1); + doc->size[0].name = + get_next_text(line + length("%%DocumentMedia:"), &next_char); + if(doc->size[0].name != NULL) { + if(sscanf(next_char, "%f %f", &w, &h) == 2) { + doc->size[0].width = w + 0.5; + doc->size[0].height = h + 0.5; + } + if(doc->size[0].width != 0 && doc->size[0].height != 0) + doc->numsizes = 1; + else + g_free(doc->size[0].name); + } + preread = 1; + while(readline(line, sizeof line, file, &position, &line_len) && + DSCcomment(line) && iscomment(line + 2, "+")) { + section_len += line_len; + doc->size = g_renew(GtkGSPaperSize, doc->size, doc->numsizes + 1); + doc->size[doc->numsizes].name = + get_next_text(line + length("%%+"), &next_char); + if(doc->size[doc->numsizes].name != NULL) { + if(sscanf(next_char, "%f %f", &w, &h) == 2) { + doc->size[doc->numsizes].width = w + 0.5; + doc->size[doc->numsizes].height = h + 0.5; + } + if(doc->size[doc->numsizes].width != 0 && + doc->size[doc->numsizes].height != 0) + doc->numsizes++; + else + g_free(doc->size[doc->numsizes].name); + } + } + section_len += line_len; + if(doc->numsizes != 0) + doc->default_page_size = doc->size; + } + else if(doc->numsizes == NONE && iscomment(line + 2, "DocumentPaperSizes:")) { + + doc->size = g_new0(GtkGSPaperSize, 1); + doc->size[0].name = + get_next_text(line + length("%%DocumentPaperSizes:"), &next_char); + if(doc->size[0].name != NULL) { + doc->size[0].width = 0; + doc->size[0].height = 0; + for(dmp = papersizes; dmp->name != NULL; dmp++) { + /* Note: Paper size comment uses down cased paper size + * name. Case insensitive compares are only used for + * PaperSize comments. + */ + if(strcasecmp(doc->size[0].name, dmp->name) == 0) { + g_free(doc->size[0].name); + doc->size[0].name = g_strdup(dmp->name); + doc->size[0].width = dmp->width; + doc->size[0].height = dmp->height; + break; + } + } + if(doc->size[0].width != 0 && doc->size[0].height != 0) + doc->numsizes = 1; + else + g_free(doc->size[0].name); + } + while((cp = get_next_text(next_char, &next_char))) { + doc->size = g_renew(GtkGSPaperSize, doc->size, doc->numsizes + 1); + doc->size[doc->numsizes].name = cp; + doc->size[doc->numsizes].width = 0; + doc->size[doc->numsizes].height = 0; + for(dmp = papersizes; dmp->name != NULL; dmp++) { + /* Note: Paper size comment uses down cased paper size + * name. Case insensitive compares are only used for + * PaperSize comments. + */ + if(strcasecmp(doc->size[doc->numsizes].name, dmp->name) == 0) { + g_free(doc->size[doc->numsizes].name); + doc->size[doc->numsizes].name = g_strdup(dmp->name); + doc->size[doc->numsizes].name = dmp->name; + doc->size[doc->numsizes].width = dmp->width; + doc->size[doc->numsizes].height = dmp->height; + break; + } + } + if(doc->size[doc->numsizes].width != 0 && + doc->size[doc->numsizes].height != 0) + doc->numsizes++; + else + g_free(doc->size[doc->numsizes].name); + } + preread = 1; + while(readline(line, sizeof line, file, &position, &line_len) && + DSCcomment(line) && iscomment(line + 2, "+")) { + section_len += line_len; + next_char = line + length("%%+"); + while((cp = get_next_text(next_char, &next_char))) { + doc->size = g_renew(GtkGSPaperSize, doc->size, doc->numsizes + 1); + doc->size[doc->numsizes].name = cp; + doc->size[doc->numsizes].width = 0; + doc->size[doc->numsizes].height = 0; + for(dmp = papersizes; dmp->name != NULL; dmp++) { + /* Note: Paper size comment uses down cased paper size + * name. Case insensitive compares are only used for + * PaperSize comments. + */ + if(strcasecmp(doc->size[doc->numsizes].name, dmp->name) == 0) { + doc->size[doc->numsizes].width = dmp->width; + doc->size[doc->numsizes].height = dmp->height; + break; + } + } + if(doc->size[doc->numsizes].width != 0 && + doc->size[doc->numsizes].height != 0) + doc->numsizes++; + else + g_free(doc->size[doc->numsizes].name); + } + } + section_len += line_len; + if(doc->numsizes != 0) + doc->default_page_size = doc->size; + } + } + + if(DSCcomment(line) && iscomment(line + 2, "EndComments")) { + readline(line, sizeof line, file, &position, &line_len); + section_len += line_len; + } + doc->endheader = position; + doc->lenheader = section_len - line_len; + + /* Optional Preview comments for encapsulated PostScript files */ + + beginsection = position; + section_len = line_len; + while(blank(line) && readline(line, sizeof line, file, &position, &line_len)) { + section_len += line_len; + } + + if(doc->epsf && DSCcomment(line) && iscomment(line + 2, "BeginPreview")) { + doc->beginpreview = beginsection; + beginsection = 0; + while(readline(line, sizeof line, file, &position, &line_len) && + !(DSCcomment(line) && iscomment(line + 2, "EndPreview"))) { + section_len += line_len; + } + section_len += line_len; + readline(line, sizeof line, file, &position, &line_len); + section_len += line_len; + doc->endpreview = position; + doc->lenpreview = section_len - line_len; + } + + /* Page Defaults for Version 3.0 files */ + + if(beginsection == 0) { + beginsection = position; + section_len = line_len; + } + while(blank(line) && readline(line, sizeof line, file, &position, &line_len)) { + section_len += line_len; + } + + if(DSCcomment(line) && iscomment(line + 2, "BeginDefaults")) { + doc->begindefaults = beginsection; + beginsection = 0; + while(readline(line, sizeof line, file, &position, &line_len) && + !(DSCcomment(line) && iscomment(line + 2, "EndDefaults"))) { + section_len += line_len; + if(!DSCcomment(line)) { + /* Do nothing */ + } + else if(doc->default_page_orientation == NONE && + iscomment(line + 2, "PageOrientation:")) { + sscanf(line + length("%%PageOrientation:"), "%256s", text); + if(strcmp(text, "Portrait") == 0) { + doc->default_page_orientation = GTK_GS_ORIENTATION_PORTRAIT; + } + else if(strcmp(text, "Landscape") == 0) { + doc->default_page_orientation = GTK_GS_ORIENTATION_LANDSCAPE; + } + else if(strcmp(text, "Seascape") == 0) { + doc->default_page_orientation = GTK_GS_ORIENTATION_SEASCAPE; + } + } + else if(page_size_set == NONE && iscomment(line + 2, "PageMedia:")) { + cp = get_next_text(line + length("%%PageMedia:"), NULL); + for(dmp = doc->size, i = 0; i < doc->numsizes; i++, dmp++) { + if(strcmp(cp, dmp->name) == 0) { + doc->default_page_size = dmp; + page_size_set = 1; + break; + } + } + g_free(cp); + } + else if(page_bb_set == NONE && iscomment(line + 2, "PageBoundingBox:")) { + if(sscanf(line + length("%%PageBoundingBox:"), "%d %d %d %d", + &(doc->default_page_boundingbox[LLX]), + &(doc->default_page_boundingbox[LLY]), + &(doc->default_page_boundingbox[URX]), + &(doc->default_page_boundingbox[URY])) == 4) + page_bb_set = 1; + else { + float fllx, flly, furx, fury; + if(sscanf + (line + length("%%PageBoundingBox:"), "%f %f %f %f", + &fllx, &flly, &furx, &fury) == 4) { + page_bb_set = 1; + doc->default_page_boundingbox[LLX] = fllx; + doc->default_page_boundingbox[LLY] = flly; + doc->default_page_boundingbox[URX] = furx; + doc->default_page_boundingbox[URY] = fury; + if(fllx < doc->default_page_boundingbox[LLX]) + doc->default_page_boundingbox[LLX]--; + if(flly < doc->default_page_boundingbox[LLY]) + doc->default_page_boundingbox[LLY]--; + if(furx > doc->default_page_boundingbox[URX]) + doc->default_page_boundingbox[URX]++; + if(fury > doc->default_page_boundingbox[URY]) + doc->default_page_boundingbox[URY]++; + } + } + } + } + section_len += line_len; + readline(line, sizeof line, file, &position, &line_len); + section_len += line_len; + doc->enddefaults = position; + doc->lendefaults = section_len - line_len; + } + + /* Document Prolog */ + + if(beginsection == 0) { + beginsection = position; + section_len = line_len; + } + while(blank(line) && readline(line, sizeof line, file, &position, &line_len)) { + section_len += line_len; + } + + if(!(DSCcomment(line) && + (iscomment(line + 2, "BeginSetup") || + iscomment(line + 2, "Page:") || + iscomment(line + 2, "Trailer") || iscomment(line + 2, "EOF")))) { + doc->beginprolog = beginsection; + beginsection = 0; + preread = 1; + + while((preread || + readline(line, sizeof line, file, &position, &line_len)) && + !(DSCcomment(line) && + (iscomment(line + 2, "EndProlog") || + iscomment(line + 2, "BeginSetup") || + iscomment(line + 2, "Page:") || + iscomment(line + 2, "Trailer") || iscomment(line + 2, "EOF")))) { + if(!preread) + section_len += line_len; + preread = 0; + } + section_len += line_len; + if(DSCcomment(line) && iscomment(line + 2, "EndProlog")) { + readline(line, sizeof line, file, &position, &line_len); + section_len += line_len; + } + doc->endprolog = position; + doc->lenprolog = section_len - line_len; + } + + /* Document Setup, Page Defaults found here for Version 2 files */ + + if(beginsection == 0) { + beginsection = position; + section_len = line_len; + } + while(blank(line) && readline(line, sizeof line, file, &position, &line_len)) { + section_len += line_len; + } + + if(!(DSCcomment(line) && + (iscomment(line + 2, "Page:") || + iscomment(line + 2, "Trailer") || + (respect_eof && iscomment(line + 2, "EOF"))))) { + doc->beginsetup = beginsection; + beginsection = 0; + preread = 1; + while((preread || + readline(line, sizeof line, file, &position, &line_len)) && + !(DSCcomment(line) && + (iscomment(line + 2, "EndSetup") || + iscomment(line + 2, "Page:") || + iscomment(line + 2, "Trailer") || + (respect_eof && iscomment(line + 2, "EOF"))))) { + if(!preread) + section_len += line_len; + preread = 0; + if(!DSCcomment(line)) { + /* Do nothing */ + } + else if(doc->default_page_orientation == NONE && + iscomment(line + 2, "PageOrientation:")) { + sscanf(line + length("%%PageOrientation:"), "%256s", text); + if(strcmp(text, "Portrait") == 0) { + doc->default_page_orientation = GTK_GS_ORIENTATION_PORTRAIT; + } + else if(strcmp(text, "Landscape") == 0) { + doc->default_page_orientation = GTK_GS_ORIENTATION_LANDSCAPE; + } + else if(strcmp(text, "Seascape") == 0) { + doc->default_page_orientation = GTK_GS_ORIENTATION_SEASCAPE; + } + } + else if(page_size_set == NONE && iscomment(line + 2, "PaperSize:")) { + cp = get_next_text(line + length("%%PaperSize:"), NULL); + for(dmp = doc->size, i = 0; i < doc->numsizes; i++, dmp++) { + /* Note: Paper size comment uses down cased paper size + * name. Case insensitive compares are only used for + * PaperSize comments. + */ + if(strcasecmp(cp, dmp->name) == 0) { + doc->default_page_size = dmp; + page_size_set = 1; + break; + } + } + g_free(cp); + } + else if(page_bb_set == NONE && iscomment(line + 2, "PageBoundingBox:")) { + if(sscanf(line + length("%%PageBoundingBox:"), "%d %d %d %d", + &(doc->default_page_boundingbox[LLX]), + &(doc->default_page_boundingbox[LLY]), + &(doc->default_page_boundingbox[URX]), + &(doc->default_page_boundingbox[URY])) == 4) + page_bb_set = 1; + else { + float fllx, flly, furx, fury; + if(sscanf + (line + length("%%PageBoundingBox:"), "%f %f %f %f", + &fllx, &flly, &furx, &fury) == 4) { + page_bb_set = 1; + doc->default_page_boundingbox[LLX] = fllx; + doc->default_page_boundingbox[LLY] = flly; + doc->default_page_boundingbox[URX] = furx; + doc->default_page_boundingbox[URY] = fury; + if(fllx < doc->default_page_boundingbox[LLX]) + doc->default_page_boundingbox[LLX]--; + if(flly < doc->default_page_boundingbox[LLY]) + doc->default_page_boundingbox[LLY]--; + if(furx > doc->default_page_boundingbox[URX]) + doc->default_page_boundingbox[URX]++; + if(fury > doc->default_page_boundingbox[URY]) + doc->default_page_boundingbox[URY]++; + } + } + } + } + section_len += line_len; + if(DSCcomment(line) && iscomment(line + 2, "EndSetup")) { + readline(line, sizeof line, file, &position, &line_len); + section_len += line_len; + } + doc->endsetup = position; + doc->lensetup = section_len - line_len; + } + + /* Added this (Nov. 2, 1999) when I noticed that + a Postscript file would load in gv but not in ggv + + dmg@csg.uwaterloo.ca */ + + /* BEGIN Windows NT fix ###jp### + Mark Pfeifer (pfeiferm%ppddev@comet.cmis.abbott.com) told me + about problems when viewing Windows NT 3.51 generated postscript + files with gv. He found that the relevant postscript files + show important postscript code after the '%%EndSetup' and before + the first page comment '%%Page: x y'. + */ + if(doc->beginsetup) { + while(!(DSCcomment(line) && + (iscomment(line + 2, "EndSetup") || + (iscomment(line + 2, "Page:") || + iscomment(line + 2, "Trailer") || + (respect_eof && iscomment(line + 2, "EOF"))))) && + (readline(line, sizeof line, file, &position, &line_len))) { + section_len += line_len; + doc->lensetup = section_len - line_len; + doc->endsetup = position; + } + } + /* END Windows NT fix ###jp## */ + + /* Individual Pages */ + + if(beginsection == 0) { + beginsection = position; + section_len = line_len; + } + while(blank(line) && readline(line, sizeof line, file, &position, &line_len)) { + section_len += line_len; + } + + +newpage: + while(DSCcomment(line) && iscomment(line + 2, "Page:")) { + if(maxpages == 0) { + maxpages = 1; + doc->pages = pages_new(NULL, 0, maxpages); + } + label = get_next_text(line + length("%%Page:"), &next_char); + if(sscanf(next_char, "%d", &thispage) != 1) + thispage = 0; + if(nextpage == 1) { + ignore = thispage != 1; + } + if(!ignore && thispage != nextpage) { + g_free(label); + doc->numpages--; + goto continuepage; + } + nextpage++; + if(doc->numpages == maxpages) { + maxpages++; + doc->pages = pages_new(doc->pages, maxpages - 1, maxpages); + } + page_bb_set = NONE; + doc->pages[doc->numpages].label = label; + if(beginsection) { + doc->pages[doc->numpages].begin = beginsection; + beginsection = 0; + } + else { + doc->pages[doc->numpages].begin = position; + section_len = line_len; + } + continuepage: + while(readline(line, sizeof line, file, &position, &line_len) && + !(DSCcomment(line) && + (iscomment(line + 2, "Page:") || + iscomment(line + 2, "Trailer") || + (respect_eof && iscomment(line + 2, "EOF"))))) { + section_len += line_len; + if(!DSCcomment(line)) { + /* Do nothing */ + } + else if(doc->pages[doc->numpages].orientation == NONE && + iscomment(line + 2, "PageOrientation:")) { + sscanf(line + length("%%PageOrientation:"), "%256s", text); + if(strcmp(text, "Portrait") == 0) { + doc->pages[doc->numpages].orientation = GTK_GS_ORIENTATION_PORTRAIT; + } + else if(strcmp(text, "Landscape") == 0) { + doc->pages[doc->numpages].orientation = GTK_GS_ORIENTATION_LANDSCAPE; + } + else if(strcmp(text, "Seascape") == 0) { + doc->pages[doc->numpages].orientation = GTK_GS_ORIENTATION_SEASCAPE; + } + } + else if(doc->pages[doc->numpages].size == NULL && + iscomment(line + 2, "PageMedia:")) { + cp = get_next_text(line + length("%%PageMedia:"), NULL); + for(dmp = doc->size, i = 0; i < doc->numsizes; i++, dmp++) { + if(strcmp(cp, dmp->name) == 0) { + doc->pages[doc->numpages].size = dmp; + break; + } + } + g_free(cp); + } + else if(doc->pages[doc->numpages].size == NULL && + iscomment(line + 2, "PaperSize:")) { + cp = get_next_text(line + length("%%PaperSize:"), NULL); + for(dmp = doc->size, i = 0; i < doc->numsizes; i++, dmp++) { + /* Note: Paper size comment uses down cased paper size + * name. Case insensitive compares are only used for + * PaperSize comments. + */ + if(strcasecmp(cp, dmp->name) == 0) { + doc->pages[doc->numpages].size = dmp; + break; + } + } + g_free(cp); + } + else if((page_bb_set == NONE || page_bb_set == ATEND) && + iscomment(line + 2, "PageBoundingBox:")) { + sscanf(line + length("%%PageBoundingBox:"), "%256s", text); + if(strcmp(text, "(atend)") == 0) { + page_bb_set = ATEND; + } + else { + if(sscanf + (line + length("%%PageBoundingBox:"), "%d %d %d %d", + &(doc->pages[doc->numpages].boundingbox[LLX]), + &(doc->pages[doc->numpages].boundingbox[LLY]), + &(doc->pages[doc->numpages].boundingbox[URX]), + &(doc->pages[doc->numpages].boundingbox[URY])) == 4) { + if(page_bb_set == NONE) + page_bb_set = 1; + } + else { + float fllx, flly, furx, fury; + if(sscanf(line + length("%%PageBoundingBox:"), + "%f %f %f %f", &fllx, &flly, &furx, &fury) == 4) { + if(page_bb_set == NONE) + page_bb_set = 1; + doc->pages[doc->numpages].boundingbox[LLX] = fllx; + doc->pages[doc->numpages].boundingbox[LLY] = flly; + doc->pages[doc->numpages].boundingbox[URX] = furx; + doc->pages[doc->numpages].boundingbox[URY] = fury; + if(fllx < doc->pages[doc->numpages].boundingbox[LLX]) + doc->pages[doc->numpages].boundingbox[LLX]--; + if(flly < doc->pages[doc->numpages].boundingbox[LLY]) + doc->pages[doc->numpages].boundingbox[LLY]--; + if(furx > doc->pages[doc->numpages].boundingbox[URX]) + doc->pages[doc->numpages].boundingbox[URX]++; + if(fury > doc->pages[doc->numpages].boundingbox[URY]) + doc->pages[doc->numpages].boundingbox[URY]++; + } + } + } + } + } + section_len += line_len; + doc->pages[doc->numpages].end = position; + doc->pages[doc->numpages].len = section_len - line_len; + doc->numpages++; + } + + /* Document Trailer */ + + if(beginsection) { + doc->begintrailer = beginsection; + beginsection = 0; + } + else { + doc->begintrailer = position; + section_len = line_len; + } + + preread = 1; + while((preread || + readline(line, sizeof line, file, &position, &line_len)) && + !(respect_eof && DSCcomment(line) && iscomment(line + 2, "EOF"))) { + if(!preread) + section_len += line_len; + preread = 0; + if(!DSCcomment(line)) { + /* Do nothing */ + } + else if(iscomment(line + 2, "Page:")) { + g_free(get_next_text(line + length("%%Page:"), &next_char)); + if(sscanf(next_char, "%d", &thispage) != 1) + thispage = 0; + if(!ignore && thispage == nextpage) { + if(doc->numpages > 0) { + doc->pages[doc->numpages - 1].end = position; + doc->pages[doc->numpages - 1].len += section_len - line_len; + } + else { + if(doc->endsetup) { + doc->endsetup = position; + doc->endsetup += section_len - line_len; + } + else if(doc->endprolog) { + doc->endprolog = position; + doc->endprolog += section_len - line_len; + } + } + goto newpage; + } + } + else if(!respect_eof && iscomment(line + 2, "Trailer")) { + /* What we thought was the start of the trailer was really */ + /* the trailer of an EPS on the page. */ + /* Set the end of the page to this trailer and keep scanning. */ + if(doc->numpages > 0) { + doc->pages[doc->numpages - 1].end = position; + doc->pages[doc->numpages - 1].len += section_len - line_len; + } + doc->begintrailer = position; + section_len = line_len; + } + else if(bb_set == ATEND && iscomment(line + 2, "BoundingBox:")) { + if(sscanf(line + length("%%BoundingBox:"), "%d %d %d %d", + &(doc->boundingbox[LLX]), + &(doc->boundingbox[LLY]), + &(doc->boundingbox[URX]), &(doc->boundingbox[URY])) != 4) { + float fllx, flly, furx, fury; + if(sscanf(line + length("%%BoundingBox:"), "%f %f %f %f", + &fllx, &flly, &furx, &fury) == 4) { + doc->boundingbox[LLX] = fllx; + doc->boundingbox[LLY] = flly; + doc->boundingbox[URX] = furx; + doc->boundingbox[URY] = fury; + if(fllx < doc->boundingbox[LLX]) + doc->boundingbox[LLX]--; + if(flly < doc->boundingbox[LLY]) + doc->boundingbox[LLY]--; + if(furx > doc->boundingbox[URX]) + doc->boundingbox[URX]++; + if(fury > doc->boundingbox[URY]) + doc->boundingbox[URY]++; + } + } + } + else if(orientation_set == ATEND && iscomment(line + 2, "Orientation:")) { + sscanf(line + length("%%Orientation:"), "%256s", text); + if(strcmp(text, "Portrait") == 0) { + doc->orientation = GTK_GS_ORIENTATION_PORTRAIT; + } + else if(strcmp(text, "Landscape") == 0) { + doc->orientation = GTK_GS_ORIENTATION_LANDSCAPE; + } + else if(strcmp(text, "Seascape") == 0) { + doc->orientation = GTK_GS_ORIENTATION_SEASCAPE; + } + } + else if(page_order_set == ATEND && iscomment(line + 2, "PageOrder:")) { + sscanf(line + length("%%PageOrder:"), "%256s", text); + if(strcmp(text, "Ascend") == 0) { + doc->pageorder = ASCEND; + } + else if(strcmp(text, "Descend") == 0) { + doc->pageorder = DESCEND; + } + else if(strcmp(text, "Special") == 0) { + doc->pageorder = SPECIAL; + } + } + else if(pages_set == ATEND && iscomment(line + 2, "Pages:")) { + if(sscanf(line + length("%%Pages:"), "%*u %d", &i) == 1) { + if(page_order_set == NONE) { + if(i == -1) + doc->pageorder = DESCEND; + else if(i == 0) + doc->pageorder = SPECIAL; + else if(i == 1) + doc->pageorder = ASCEND; + } + } + } + } + section_len += line_len; + if(DSCcomment(line) && iscomment(line + 2, "EOF")) { + readline(line, sizeof line, file, &position, &line_len); + section_len += line_len; + } + doc->endtrailer = position; + doc->lentrailer = section_len - line_len; + +#if 0 + section_len = line_len; + preread = 1; + while(preread || readline(line, sizeof line, file, &position, &line_len)) { + if(!preread) + section_len += line_len; + preread = 0; + if(DSCcomment(line) && iscomment(line + 2, "Page:")) { + g_free(get_next_text(line + length("%%Page:"), &next_char)); + if(sscanf(next_char, "%d", &thispage) != 1) + thispage = 0; + if(!ignore && thispage == nextpage) { + if(doc->numpages > 0) { + doc->pages[doc->numpages - 1].end = position; + doc->pages[doc->numpages - 1].len += doc->lentrailer + + section_len - line_len; + } + else { + if(doc->endsetup) { + doc->endsetup = position; + doc->endsetup += doc->lentrailer + section_len - line_len; + } + else if(doc->endprolog) { + doc->endprolog = position; + doc->endprolog += doc->lentrailer + section_len - line_len; + } + } + goto newpage; + } + } + } +#endif + return doc; +} + +/* + * psfree -- free dynamic storage associated with document structure. + */ + +void +psfree(doc) + struct document *doc; +{ + int i; + + if(doc) { + /* + printf("This document exists\n"); + */ + for(i = 0; i < doc->numpages; i++) { + if(doc->pages[i].label) + g_free(doc->pages[i].label); + } + for(i = 0; i < doc->numsizes; i++) { + if(doc->size[i].name) + g_free(doc->size[i].name); + } + if(doc->title) + g_free(doc->title); + if(doc->date) + g_free(doc->date); + if(doc->pages) + g_free(doc->pages); + if(doc->size) + g_free(doc->size); + g_free(doc); + } +} + +/* + * gettextine -- skip over white space and return the rest of the line. + * If the text begins with '(' return the text string + * using get_next_text(). + */ + +static char * +gettextline(char *line) +{ + char *cp; + + while(*line && (*line == ' ' || *line == '\t')) + line++; + if(*line == '(') { + return get_next_text(line, NULL); + } + else { + if(strlen(line) == 0) + return NULL; + + cp = g_strdup(line); + + /* Remove end of line */ + if(cp[strlen(line) - 2] == '\r' && cp[strlen(line) - 1] == '\n') + /* Handle DOS \r\n */ + cp[strlen(line) - 2] = '\0'; + else if(cp[strlen(line) - 1] == '\n' || cp[strlen(line) - 1] == '\r') + /* Handle mac and unix */ + cp[strlen(line) - 1] = '\0'; + + return cp; + } +} + +/* + * get_next_text -- return the next text string on the line. + * return NULL if nothing is present. + */ + +static char * +get_next_text(line, next_char) + char *line; + char **next_char; +{ + char text[PSLINELENGTH]; /* Temporary storage for text */ + char *cp; + int quoted = 0; + + while(*line && (*line == ' ' || *line == '\t')) + line++; + cp = text; + if(*line == '(') { + int level = 0; + quoted = 1; + line++; + while(*line && !(*line == ')' && level == 0)) { + if(*line == '\\') { + if(*(line + 1) == 'n') { + *cp++ = '\n'; + line += 2; + } + else if(*(line + 1) == 'r') { + *cp++ = '\r'; + line += 2; + } + else if(*(line + 1) == 't') { + *cp++ = '\t'; + line += 2; + } + else if(*(line + 1) == 'b') { + *cp++ = '\b'; + line += 2; + } + else if(*(line + 1) == 'f') { + *cp++ = '\f'; + line += 2; + } + else if(*(line + 1) == '\\') { + *cp++ = '\\'; + line += 2; + } + else if(*(line + 1) == '(') { + *cp++ = '('; + line += 2; + } + else if(*(line + 1) == ')') { + *cp++ = ')'; + line += 2; + } + else if(*(line + 1) >= '0' && *(line + 1) <= '9') { + if(*(line + 2) >= '0' && *(line + 2) <= '9') { + if(*(line + 3) >= '0' && *(line + 3) <= '9') { + *cp++ = + ((*(line + 1) - '0') * 8 + *(line + 2) - + '0') * 8 + *(line + 3) - '0'; + line += 4; + } + else { + *cp++ = (*(line + 1) - '0') * 8 + *(line + 2) - '0'; + line += 3; + } + } + else { + *cp++ = *(line + 1) - '0'; + line += 2; + } + } + else { + line++; + *cp++ = *line++; + } + } + else if(*line == '(') { + level++; + *cp++ = *line++; + } + else if(*line == ')') { + level--; + *cp++ = *line++; + } + else { + *cp++ = *line++; + } + } + } + else { + while(*line && !(*line == ' ' || *line == '\t' || *line == '\n')) + *cp++ = *line++; + } + *cp = '\0'; + if(next_char) + *next_char = line; + if(!quoted && strlen(text) == 0) + return NULL; + return g_strdup(text); +} + +/* + * readline -- Read the next line in the postscript file. + * Automatically skip over data (as indicated by + * %%BeginBinary/%%EndBinary or %%BeginData/%%EndData + * comments.) + * Also, skip over included documents (as indicated by + * %%BeginDocument/%%EndDocument comments.) + */ +/* +static char * readline (fd, lineP, positionP, line_lenP) + FileData fd; + char **lineP; + long *positionP; + unsigned int *line_lenP; +*/ + +#ifdef WE_MIGHT_WANT_TO_INCLUDE_THIS_NEW_READLINE + + +static char * +readline(lineP, size, fp, positionP, line_lenP) + char *lineP; + int size; + FILE *fp; + long *positionP; + unsigned int *line_lenP; +{ + unsigned int nbytes = 0; + int skipped = 0; + char text[PSLINELENGTH]; + char line[PSLINELENGTH]; + char save[PSLINELENGTH]; + char buf[BUFSIZ]; + char *cp; + unsigned int num; + int i; + + if(positionP) + *positionP = ftell(fp); + cp = fgets(line, size, fp); + if(cp == NULL) { + *line_lenP = 0; + *lineP = '\0'; + return (NULL); + } + + *line_lenP = strlen(line); + +# define IS_COMMENT(comment) \ + (DSCcomment(line) && iscomment(line+2,(comment))) +# define IS_BEGIN(comment) \ + (iscomment(line+7,(comment))) + +# define SKIP_WHILE(cond) \ + while (readline(line, size, fp, NULL, &nbytes) \ + && (cond)) *line_lenP += nbytes;\ + skipped=1; + +# define SKIP_UNTIL_1(comment) { \ + SKIP_WHILE((!IS_COMMENT(comment))) \ + } +# define SKIP_UNTIL_2(comment1,comment2) { \ + SKIP_WHILE((!IS_COMMENT(comment1) && !IS_COMMENT(comment2)))\ + } + + if(!IS_COMMENT("Begin")) { + } /* Do nothing */ + else + ifIS_BEGIN("Document:") SKIP_UNTIL_1("EndDocument") + else + ifIS_BEGIN("Feature:") SKIP_UNTIL_1("EndFeature") +# ifdef USE_ACROREAD_WORKAROUND + else + ifIS_BEGIN("File") SKIP_UNTIL_2("EndFile", "EOF") +# else + else + ifIS_BEGIN("File") SKIP_UNTIL_1("EndFile") +# endif + else + ifIS_BEGIN("Font") SKIP_UNTIL_1("EndFont") + else + ifIS_BEGIN("ProcSet") SKIP_UNTIL_1("EndProcSet") + else + ifIS_BEGIN("Resource") SKIP_UNTIL_1("EndResource") + else + ifIS_BEGIN("Data:") { + text[0] = '\0'; + strcpy(save, line + 7); + if(sscanf(line + length("%%BeginData:"), "%d %*s %256s", &num, text) + >= 1) { + if(strcmp(text, "Lines") == 0) { + for(i = 0; i < num; i++) { + cp = fgets(line, size, fp); + *line_lenP += cp ? strlen(line) : 0; + } + } + else { + while(num > BUFSIZ) { + fread(buf, sizeof(char), BUFSIZ, fp); + *line_lenP += BUFSIZ; + num -= BUFSIZ; + } + fread(buf, sizeof(char), num, fp); + *line_lenP += num; + } + } + SKIP_UNTIL_1("EndData")} + else + ifIS_BEGIN("Binary:") { + strcpy(save, line + 7); + if(sscanf(line + length("%%BeginBinary:"), "%d", &num) == 1) { + while(num > BUFSIZ) { + fread(buf, sizeof(char), BUFSIZ, fp); + *line_lenP += BUFSIZ; + num -= BUFSIZ; + } + fread(buf, sizeof(char), num, fp); + *line_lenP += num; + } + SKIP_UNTIL_1("EndBinary") * line_lenP += nbytes; + } + + if(skipped) { + *line_lenP += nbytes; + strcpy(lineP, skipped_line); + } + else { + strcpy(lineP, line); + } + return lineP; +} + +#endif + +static char * +readline(line, size, fp, position, line_len) + char *line; + int size; + FILE *fp; + long *position; + unsigned int *line_len; +{ + char text[PSLINELENGTH]; /* Temporary storage for text */ + char save[PSLINELENGTH]; /* Temporary storage for text */ + char *cp; + unsigned int num; + unsigned int nbytes; + int i, j; + char buf[BUFSIZ]; + + if(position) + *position = ftell(fp); + cp = fgets(line, size, fp); + if(cp == NULL) + line[0] = '\0'; + for(i = 0; + line[i] != '\0' && (line[i] == 0x0c || line[i] == ' ' + || line[i] == '\t'); i++) ; + if(i > 0 && line[i] == '%' && line[i + 1] == '%') { + for(j = i; line[j] != '\0'; j++) + line[j - i] = line[j]; + line[j - i] = '\0'; + } + *line_len = strlen(line); + if(!(DSCcomment(line) && iscomment(line + 2, "Begin"))) { + /* Do nothing */ + } + else if(iscomment(line + 7, "Document:")) { + strcpy(save, line + 7); + while(readline(line, size, fp, NULL, &nbytes) && + !(DSCcomment(line) && iscomment(line + 2, "EndDocument"))) { + *line_len += nbytes; + } + *line_len += nbytes; + strcpy(line, save); + } + else if(iscomment(line + 7, "Feature:")) { + strcpy(save, line + 7); + while(readline(line, size, fp, NULL, &nbytes) && + !(DSCcomment(line) && iscomment(line + 2, "EndFeature"))) { + *line_len += nbytes; + } + *line_len += nbytes; + strcpy(line, save); + } + else if(iscomment(line + 7, "File:")) { + strcpy(save, line + 7); + while(readline(line, size, fp, NULL, &nbytes) && + !(DSCcomment(line) && iscomment(line + 2, "EndFile"))) { + *line_len += nbytes; + } + *line_len += nbytes; + strcpy(line, save); + } + else if(iscomment(line + 7, "Font:")) { + strcpy(save, line + 7); + while(readline(line, size, fp, NULL, &nbytes) && + !(DSCcomment(line) && iscomment(line + 2, "EndFont"))) { + *line_len += nbytes; + } + *line_len += nbytes; + strcpy(line, save); + } + else if(iscomment(line + 7, "ProcSet:")) { + strcpy(save, line + 7); + while(readline(line, size, fp, NULL, &nbytes) && + !(DSCcomment(line) && iscomment(line + 2, "EndProcSet"))) { + *line_len += nbytes; + } + *line_len += nbytes; + strcpy(line, save); + } + else if(iscomment(line + 7, "Resource:")) { + strcpy(save, line + 7); + while(readline(line, size, fp, NULL, &nbytes) && + !(DSCcomment(line) && iscomment(line + 2, "EndResource"))) { + *line_len += nbytes; + } + *line_len += nbytes; + strcpy(line, save); + } + else if(iscomment(line + 7, "Data:")) { + text[0] = '\0'; + strcpy(save, line + 7); + if(sscanf(line + length("%%BeginData:"), "%d %*s %256s", &num, text) + >= 1) { + if(strcmp(text, "Lines") == 0) { + for(i = 0; i < num; i++) { + cp = fgets(line, size, fp); + *line_len += cp ? strlen(line) : 0; + } + } + else { + while(num > BUFSIZ) { + fread(buf, sizeof(char), BUFSIZ, fp); + *line_len += BUFSIZ; + num -= BUFSIZ; + } + fread(buf, sizeof(char), num, fp); + *line_len += num; + } + } + while(readline(line, size, fp, NULL, &nbytes) && + !(DSCcomment(line) && iscomment(line + 2, "EndData"))) { + *line_len += nbytes; + } + *line_len += nbytes; + strcpy(line, save); + } + else if(iscomment(line + 7, "Binary:")) { + strcpy(save, line + 7); + if(sscanf(line + length("%%BeginBinary:"), "%d", &num) == 1) { + while(num > BUFSIZ) { + fread(buf, sizeof(char), BUFSIZ, fp); + *line_len += BUFSIZ; + num -= BUFSIZ; + } + fread(buf, sizeof(char), num, fp); + *line_len += num; + } + while(readline(line, size, fp, NULL, &nbytes) && + !(DSCcomment(line) && iscomment(line + 2, "EndBinary"))) { + *line_len += nbytes; + } + *line_len += nbytes; + strcpy(line, save); + } + return cp; +} + + +/* + * pscopy -- copy lines of Postscript from a section of one file + * to another file. + * Automatically switch to binary copying whenever + * %%BeginBinary/%%EndBinary or %%BeginData/%%EndData + * comments are encountered. + */ + +void +pscopy(from, to, begin, end) + FILE *from; + GtkGSDocSink *to; + long begin; /* set negative to avoid initial seek */ + long end; +{ + char line[PSLINELENGTH]; /* 255 characters + 1 newline + 1 NULL */ + char text[PSLINELENGTH]; /* Temporary storage for text */ + unsigned int num; + int i; + char buf[BUFSIZ]; + + if(begin >= 0) + fseek(from, begin, SEEK_SET); + while(ftell(from) < end) { + fgets(line, sizeof line, from); + gtk_gs_doc_sink_write(to, line, strlen(line)); + + if(!(DSCcomment(line) && iscomment(line + 2, "Begin"))) { + /* Do nothing */ + } + else if(iscomment(line + 7, "Data:")) { + text[0] = '\0'; + if(sscanf(line + length("%%BeginData:"), "%d %*s %256s", &num, text) >= 1) { + if(strcmp(text, "Lines") == 0) { + for(i = 0; i < num; i++) { + fgets(line, sizeof(line), from); + gtk_gs_doc_sink_write(to, line, strlen(line)); + } + } + else { + while(num > BUFSIZ) { + fread(buf, sizeof(char), BUFSIZ, from); + gtk_gs_doc_sink_write(to, buf, BUFSIZ); + num -= BUFSIZ; + } + fread(buf, sizeof(char), num, from); + gtk_gs_doc_sink_write(to, buf, num); + } + } + } + else if(iscomment(line + 7, "Binary:")) { + if(sscanf(line + length("%%BeginBinary:"), "%d", &num) == 1) { + while(num > BUFSIZ) { + fread(buf, sizeof(char), BUFSIZ, from); + gtk_gs_doc_sink_write(to, buf, BUFSIZ); + num -= BUFSIZ; + } + fread(buf, sizeof(char), num, from); + gtk_gs_doc_sink_write(to, buf, num); + } + } + } +} + +/* + * pscopyuntil -- copy lines of Postscript from a section of one file + * to another file until a particular comment is reached. + * Automatically switch to binary copying whenever + * %%BeginBinary/%%EndBinary or %%BeginData/%%EndData + * comments are encountered. + */ + +char * +pscopyuntil(FILE * from, GtkGSDocSink * to, long begin, long end, + const char *comment) +{ + char line[PSLINELENGTH]; /* 255 characters + 1 newline + 1 NULL */ + char text[PSLINELENGTH]; /* Temporary storage for text */ + unsigned int num; + int comment_length; + int i; + char buf[BUFSIZ]; + + if(comment != NULL) + comment_length = strlen(comment); + else + comment_length = 0; + if(begin >= 0) + fseek(from, begin, SEEK_SET); + + while(ftell(from) < end && !feof(from)) { + fgets(line, sizeof line, from); + + /* iscomment cannot be used here, + * because comment_length is not known at compile time. */ + if(comment != NULL && strncmp(line, comment, comment_length) == 0) { + return g_strdup(line); + } + gtk_gs_doc_sink_write(to, line, strlen(line)); + if(!(DSCcomment(line) && iscomment(line + 2, "Begin"))) { + /* Do nothing */ + } + else if(iscomment(line + 7, "Data:")) { + text[0] = '\0'; + if(sscanf(line + length("%%BeginData:"), "%d %*s %256s", &num, text) >= 1) { + if(strcmp(text, "Lines") == 0) { + for(i = 0; i < num; i++) { + fgets(line, sizeof line, from); + gtk_gs_doc_sink_write(to, line, strlen(line)); + } + } + else { + while(num > BUFSIZ) { + fread(buf, sizeof(char), BUFSIZ, from); + gtk_gs_doc_sink_write(to, buf, BUFSIZ); + num -= BUFSIZ; + } + fread(buf, sizeof(char), num, from); + gtk_gs_doc_sink_write(to, buf, num); + } + } + } + else if(iscomment(line + 7, "Binary:")) { + if(sscanf(line + length("%%BeginBinary:"), "%d", &num) == 1) { + while(num > BUFSIZ) { + fread(buf, sizeof(char), BUFSIZ, from); + gtk_gs_doc_sink_write(to, buf, BUFSIZ); + num -= BUFSIZ; + } + fread(buf, sizeof(char), num, from); + gtk_gs_doc_sink_write(to, buf, num); + } + } + } + return NULL; +} + +/* + * blank -- determine whether the line contains nothing but whitespace. + */ + +static int +blank(char *line) +{ + char *cp = line; + + while(*cp == ' ' || *cp == '\t') + cp++; + return *cp == '\n' || (*cp == '%' && (line[0] != '%' || line[1] != '%')); +} + +/*##########################################################*/ +/* pscopydoc */ +/* Copy the headers, marked pages, and trailer to fp */ +/*##########################################################*/ + +void +pscopydoc(GtkGSDocSink * dest, + char *src_filename, struct document *d, gint * pagelist) +{ + FILE *src_file; + char text[PSLINELENGTH]; + char *comment; + gboolean pages_written = FALSE; + gboolean pages_atend = FALSE; + int pages; + int page = 1; + int i, j; + int here; + + src_file = fopen(src_filename, "r"); + i = 0; + pages = 0; + for(i = 0; i < d->numpages; i++) { + if(pagelist[i]) + pages++; + } + + here = d->beginheader; + + while((comment = pscopyuntil(src_file, dest, here, d->endheader, "%%Pages:"))) { + here = ftell(src_file); + if(pages_written || pages_atend) { + g_free(comment); + continue; + } + sscanf(comment + length("%%Pages:"), "%256s", text); + if(strcmp(text, "(atend)") == 0) { + gtk_gs_doc_sink_write(dest, comment, strlen(comment)); + pages_atend = TRUE; + } + else { + switch (sscanf(comment + length("%%Pages:"), "%*d %d", &i)) { + case 1: + gtk_gs_doc_sink_printf(dest, "%%%%Pages: %d %d\n", pages, i); + break; + default: + gtk_gs_doc_sink_printf(dest, "%%%%Pages: %d\n", pages); + break; + } + pages_written = TRUE; + } + g_free(comment); + } + pscopyuntil(src_file, dest, d->beginpreview, d->endpreview, NULL); + pscopyuntil(src_file, dest, d->begindefaults, d->enddefaults, NULL); + pscopyuntil(src_file, dest, d->beginprolog, d->endprolog, NULL); + pscopyuntil(src_file, dest, d->beginsetup, d->endsetup, NULL); + + for(i = 0; i < d->numpages; i++) { + if(d->pageorder == DESCEND) + j = (d->numpages - 1) - i; + else + j = i; + j = i; + if(pagelist[j]) { + comment = pscopyuntil(src_file, dest, + d->pages[i].begin, d->pages[i].end, "%%Page:"); + gtk_gs_doc_sink_printf(dest, "%%%%Page: %s %d\n", + d->pages[i].label, page++); + g_free(comment); + pscopyuntil(src_file, dest, -1, d->pages[i].end, NULL); + } + } + + here = d->begintrailer; + while((comment = pscopyuntil(src_file, dest, here, d->endtrailer, + "%%Pages:"))) { + here = ftell(src_file); + if(pages_written) { + g_free(comment); + continue; + } + switch (sscanf(comment + length("%%Pages:"), "%*d %d", &i)) { + case 1: + gtk_gs_doc_sink_printf(dest, "%%%%Pages: %d %d\n", pages, i); + break; + default: + gtk_gs_doc_sink_printf(dest, "%%%%Pages: %d\n", pages); + break; + } + pages_written = TRUE; + g_free(comment); + } + + fclose(src_file); +} diff --git a/ps/ps.h b/ps/ps.h new file mode 100644 index 0000000..b539b22 --- /dev/null +++ b/ps/ps.h @@ -0,0 +1,106 @@ +/* + * ps.h -- Include file for PostScript routines. + * Copyright (C) 1992 Timothy O. Theisen + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + * + * Author: Tim Theisen Systems Programmer + * Internet: tim@cs.wisc.edu Department of Computer Sciences + * UUCP: uwvax!tim University of Wisconsin-Madison + * Phone: (608)262-0438 1210 West Dayton Street + * FAX: (608)262-9777 Madison, WI 53706 + */ +#ifndef __GGV_PS_H__ +#define __GGV_PS_H__ + +#include + +#include +#include + +G_BEGIN_DECLS + +/* Constants used to index into the bounding box array. */ +#define LLX 0 +#define LLY 1 +#define URX 2 +#define URY 3 + +/* Constants used to store keywords that are scanned. */ +/* NONE is not a keyword, it tells when a field was not set */ + +enum { ATEND = -1, NONE = 0, ASCEND, DESCEND, SPECIAL }; + +#define PSLINELENGTH 257 /* 255 characters + 1 newline + 1 NULL */ + +struct document { + int epsf; /* Encapsulated PostScript flag. */ + char *title; /* Title of document. */ + char *date; /* Creation date. */ + int pageorder; /* ASCEND, DESCEND, SPECIAL */ + long beginheader, endheader; /* offsets into file */ + unsigned int lenheader; + long beginpreview, endpreview; + unsigned int lenpreview; + long begindefaults, enddefaults; + unsigned int lendefaults; + long beginprolog, endprolog; + unsigned int lenprolog; + long beginsetup, endsetup; + unsigned int lensetup; + long begintrailer, endtrailer; + unsigned int lentrailer; + int boundingbox[4]; + int default_page_boundingbox[4]; + int orientation; /* GTK_GS_ORIENTATION_PORTRAIT, GTK_GS_ORIENTATION_LANDSCAPE */ + int default_page_orientation; /* GTK_GS_ORIENTATION_PORTRAIT, GTK_GS_ORIENTATION_LANDSCAPE */ + unsigned int numsizes; + GtkGSPaperSize *size; + GtkGSPaperSize *default_page_size; + unsigned int numpages; + struct page *pages; +}; + +struct page { + char *label; + int boundingbox[4]; + GtkGSPaperSize *size; + int orientation; /* GTK_GS_ORIENTATION_PORTRAIT, GTK_GS_ORIENTATION_LANDSCAPE */ + long begin, end; /* offsets into file */ + unsigned int len; +}; + +/* scans a PostScript file and return a pointer to the document + structure. Returns NULL if file does not Conform to commenting + conventions . */ +struct document *psscan(FILE * fileP, int respect_eof, const gchar * fname); + +/* free data structure malloc'ed by psscan */ +void psfree(struct document *); + +/* Copy a portion of the PostScript file */ +void pscopy(FILE * from, GtkGSDocSink * to, long begin, long end); + +/* Copy a portion of the PostScript file upto a comment */ +char *pscopyuntil(FILE * from, GtkGSDocSink * to, long begin, long end, + const char *comment); + +/* Copy the headers, marked pages, and trailer to fp */ +void pscopydoc(GtkGSDocSink * dest_file, char *src_filename, + struct document *d, int *pagelist); + +G_END_DECLS + +#endif /* __GGV_PS_H__ */ -- cgit v0.9.1