home *** CD-ROM | disk | FTP | other *** search
/ PC Pro 2002 April / pcpro0402.iso / essentials / graphics / Gimp / gimp-src-20001226.exe / src / gimp / plug-ins / common / ps.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-12-17  |  86.7 KB  |  3,021 lines

  1. /* The GIMP -- an image manipulation program
  2.  * Copyright (C) 1995 Spencer Kimball and Peter Mattis
  3.  * PostScript file plugin
  4.  * PostScript writing and GhostScript interfacing code
  5.  * Copyright (C) 1997-98 Peter Kirchgessner
  6.  * (email: peter@kirchgessner.net, WWW: http://www.kirchgessner.net)
  7.  *
  8.  * Added controls for TextAlphaBits and GraphicsAlphaBits
  9.  *   George White <aa056@chebucto.ns.ca>
  10.  *
  11.  * Added Ascii85 encoding
  12.  *   Austin Donnelly <austin@gimp.org>
  13.  *
  14.  * This program is free software; you can redistribute it and/or modify
  15.  * it under the terms of the GNU General Public License as published by
  16.  * the Free Software Foundation; either version 2 of the License, or
  17.  * (at your option) any later version.
  18.  *
  19.  * This program is distributed in the hope that it will be useful,
  20.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  22.  * GNU General Public License for more details.
  23.  *
  24.  * You should have received a copy of the GNU General Public License
  25.  * along with this program; if not, write to the Free Software
  26.  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  27.  *
  28.  */
  29.  
  30. /* Event history:
  31.  * V 0.90, PK, 28-Mar-97: Creation.
  32.  * V 0.91, PK, 03-Apr-97: Clip everything outside BoundingBox.
  33.  *             24-Apr-97: Multi page read support.
  34.  * V 1.00, PK, 30-Apr-97: PDF support.
  35.  * V 1.01, PK, 05-Oct-97: Parse rc-file.
  36.  * V 1.02, GW, 09-Oct-97: Antialiasing support.
  37.  *         PK, 11-Oct-97: No progress bars when running non-interactive.
  38.  *                        New procedure file_ps_load_setargs to set
  39.  *                        load-arguments non-interactively.
  40.  *                        If GS_OPTIONS are not set, use at least "-dSAFER"
  41.  * V 1.03, nn, 20-Dec-97: Initialize some variables
  42.  * V 1.04, PK, 20-Dec-97: Add Encapsulated PostScript output and preview
  43.  * V 1.05, PK, 21-Sep-98: Write b/w-images (indexed) using image-operator
  44.  * V 1.06, PK, 22-Dec-98: Fix problem with writing color PS files.
  45.  *                        Ghostview may hang when displaying the files.
  46.  * V 1.07, PK, 14-Sep-99: Add resolution to image
  47.  * V 1.08, PK, 16-Jan-2000: Add PostScript-Level 2 by Austin Donnelly
  48.  * V 1.09, PK, 15-Feb-2000: Force showpage on EPS-files
  49.  *                          Add "RunLength" compression
  50.  *                          Fix problem with "Level 2" toggle
  51.  * V 1.10, PK, 15-Mar-2000: For load EPSF, allow negative Bounding Box Values
  52.  *                          Save PS: dont start lines of image data with %%
  53.  *                          to prevent problems with stupid PostScript
  54.  *                          analyzer programs (Stanislav Brabec)
  55.  *                          Add BeginData/EndData comments
  56.  *                          Save PS: Set default rotation to 0
  57.  * V 1.11, PK, 20-Aug-2000: Fix problem with BoundingBox recognition
  58.  *                          for Mac files.
  59.  *                          Fix problem with loop when reading not all
  60.  *                          images of a multi page file.
  61.  *         PK, 31-Aug-2000: Load PS: Add checks for space in filename.
  62.  */
  63. #define VERSIO 1.11
  64. static char dversio[] = "v1.11  31-Aug-2000";
  65. static char ident[] = "@(#) GIMP PostScript/PDF file-plugin v1.11  31-Aug-2000";
  66.  
  67. #include "config.h"
  68.  
  69. #include <stdio.h>
  70. #include <stdlib.h>
  71. #include <string.h>
  72. #include <time.h>
  73.  
  74. #include <libgimp/gimp.h>
  75. #include <libgimp/gimpui.h>
  76.  
  77. #include "libgimp/stdplugins-intl.h"
  78.  
  79.  
  80. #ifdef G_OS_WIN32
  81. #include <process.h>        /* For _getpid() */
  82.  
  83. #define USE_REAL_OUTPUTFILE
  84. #endif
  85.  
  86. #define STR_LENGTH 64
  87.  
  88. /* Load info */
  89. typedef struct
  90. {
  91.   guint resolution;        /* resolution (dpi) at which to run ghostscript */
  92.   guint width, height;     /* desired size (ghostscript may ignore this) */
  93.   gint  use_bbox;          /* 0: use width/height, 1: try to use BoundingBox */
  94.   gchar pages[STR_LENGTH]; /* Pages to load (eg.: 1,3,5-7) */
  95.   gint  pnm_type;          /* 4: pbm, 5: pgm, 6: ppm, 7: automatic */
  96.   gint  textalpha;         /* antialiasing: 1,2, or 4 TextAlphaBits */
  97.   gint  graphicsalpha;     /* antialiasing: 1,2, or 4 GraphicsAlphaBits */
  98. } PSLoadVals;
  99.  
  100. typedef struct
  101. {
  102.   gint  run;  /*  run  */
  103. } PSLoadInterface;
  104.  
  105. static PSLoadVals plvals =
  106. {
  107.   100,                  /* 100 dpi */
  108.   826, 1170,            /* default width/height (A4) */
  109.   1,                    /* try to use BoundingBox */
  110.   "1-99",               /* pages to load */
  111.   6,                    /* use ppm (colour) */
  112.   1,                    /* dont use text antialiasing */
  113.   1                     /* dont use graphics antialiasing */
  114. };
  115.  
  116. static PSLoadInterface plint =
  117. {
  118.   FALSE     /* run */
  119. };
  120.  
  121.  
  122. /* Save info  */
  123. typedef struct
  124. {
  125.   gdouble width, height;      /* Size of image */
  126.   gdouble x_offset, y_offset; /* Offset to image on page */
  127.   gint    unit_mm;            /* Unit of measure (0: inch, 1: mm) */
  128.   gint    keep_ratio;         /* Keep aspect ratio */
  129.   gint    rotate;             /* Rotation (0, 90, 180, 270) */
  130.   gint    level;              /* PostScript Level */
  131.   gint    eps;                /* Encapsulated PostScript flag */
  132.   gint    preview;            /* Preview Flag */
  133.   gint    preview_size;       /* Preview size */
  134. } PSSaveVals;
  135.  
  136. typedef struct
  137. {
  138.   gint  run;  /*  run  */
  139. } PSSaveInterface;
  140.  
  141. static PSSaveVals psvals =
  142. {
  143.   287.0, 200.0,   /* Image size (A4) */
  144.   5.0, 5.0,       /* Offset */
  145.   1,              /* Unit is mm */
  146.   1,              /* Keep edge ratio */
  147.   0,              /* Rotate */
  148.   2,              /* PostScript Level */
  149.   0,              /* Encapsulated PostScript flag */
  150.   0,              /* Preview flag */
  151.   256             /* Preview size */
  152. };
  153.  
  154. static PSSaveInterface psint =
  155. {
  156.   FALSE     /* run */
  157. };
  158.  
  159.  
  160. /* Declare some local functions.
  161.  */
  162. static void   query      (void);
  163. static void   run        (gchar   *name,
  164.                           gint     nparams,
  165.                           GimpParam  *param,
  166.                           gint    *nreturn_vals,
  167.                           GimpParam **return_vals);
  168.  
  169. static gint32 load_image (gchar   *filename);
  170. static gint   save_image (gchar   *filename,
  171.                           gint32   image_ID,
  172.                           gint32   drawable_ID);
  173.  
  174. static gint save_gray  (FILE   *ofp,
  175.                         gint32  image_ID,
  176.                         gint32  drawable_ID);
  177. static gint save_bw    (FILE   *ofp,
  178.                         gint32  image_ID,
  179.                         gint32  drawable_ID);
  180. static gint save_index (FILE   *ofp,
  181.                         gint32  image_ID,
  182.                         gint32  drawable_ID);
  183. static gint save_rgb   (FILE   *ofp,
  184.                         gint32  image_ID,
  185.                         gint32  drawable_ID);
  186.  
  187. static gint32 create_new_image (gchar      *filename,
  188.                 guint       pagenum,
  189.                 guint       width,
  190.                 guint       height,
  191.                 GimpImageBaseType  type,
  192.                 gint32     *layer_ID,
  193.                 GimpDrawable **drawable,
  194.                 GimpPixelRgn  *pixel_rgn);
  195.  
  196. static void   check_load_vals  (void);
  197. static void   check_save_vals  (void);
  198.  
  199. static gint   page_in_list  (gchar *list,
  200.                  guint  pagenum);
  201.  
  202. static gint   get_bbox      (gchar *filename,
  203.                  gint  *x0,
  204.                  gint  *y0,
  205.                  gint  *x1,
  206.                  gint  *y1);
  207.  
  208. static FILE  *ps_open       (gchar            *filename,
  209.                  const PSLoadVals *loadopt,
  210.                  gint             *llx,
  211.                  gint             *lly,
  212.                  gint             *urx,
  213.                  gint             *ury,
  214.                  gint             *is_epsf);
  215.  
  216. static void   ps_close      (FILE *ifp);
  217.  
  218. static gint32 skip_ps       (FILE *ifp);
  219.  
  220. static gint32 load_ps       (gchar *filename,
  221.                  guint  pagenum,
  222.                  FILE  *ifp,
  223.                  gint   llx,
  224.                  gint   lly,
  225.                  gint   urx,
  226.                  gint   ury);
  227.  
  228. static void save_ps_header  (FILE   *ofp,
  229.                  gchar  *filename);
  230. static void save_ps_setup   (FILE   *ofp,
  231.                  gint32  drawable_ID,
  232.                  gint    width,
  233.                  gint    height,
  234.                  gint    bpp);
  235. static void save_ps_trailer (FILE   *ofp);
  236. static void save_ps_preview (FILE   *ofp,
  237.                              gint32  drawable_ID);
  238. static void dither_grey     (guchar *grey,
  239.                  guchar *bw,
  240.                  gint    npix,
  241.                  gint    linecount);
  242.  
  243.  
  244. /* Dialog-handling */
  245.  
  246. static gint   load_dialog               (void);
  247. static void   load_ok_callback          (GtkWidget *widget,
  248.                      gpointer   data);
  249. static void   load_pages_entry_callback (GtkWidget *widget,
  250.                      gpointer   data);
  251.  
  252. typedef struct
  253. {
  254.   GtkObject *adjustment[4];
  255.   gint       level;
  256. } SaveDialogVals;
  257.  
  258. static gint   save_dialog              (void);
  259. static void   save_ok_callback         (GtkWidget *widget,
  260.                                         gpointer   data);
  261. static void   save_unit_toggle_update  (GtkWidget *widget,
  262.                                         gpointer   data);
  263.  
  264. GimpPlugInInfo PLUG_IN_INFO =
  265. {
  266.   NULL,  /* init_proc  */
  267.   NULL,  /* quit_proc  */
  268.   query, /* query_proc */
  269.   run,   /* run_proc   */
  270. };
  271.  
  272.  
  273. /* The run mode */
  274. static GimpRunModeType l_run_mode;
  275.  
  276. static void compress_packbits (int nin,
  277.                                unsigned char *src,
  278.                                int *nout,
  279.                                unsigned char *dst);
  280.  
  281.  
  282. static guint32 ascii85_buf;
  283. static int ascii85_len = 0;
  284. static int ascii85_linewidth = 0;
  285.  
  286. static void
  287. ascii85_init (void)
  288. {
  289.   ascii85_len = 0;
  290.   ascii85_linewidth = 0;
  291. }
  292.  
  293. static void
  294. ascii85_flush (FILE *ofp)
  295. {
  296.   char c[5];
  297.   int i;
  298.   gboolean zero_case = (ascii85_buf == 0);
  299.   static int max_linewidth = 75;
  300.  
  301.   for (i=4; i >= 0; i--)
  302.     {
  303.       c[i] = (ascii85_buf % 85) + '!';
  304.       ascii85_buf /= 85;
  305.     }
  306.   /* check for special case: "!!!!!" becomes "z", but only if not
  307.    * at end of data. */
  308.   if (zero_case && (ascii85_len == 4))
  309.     {
  310.       if (ascii85_linewidth >= max_linewidth)
  311.       {
  312.         putc ('\n', ofp);
  313.         ascii85_linewidth = 0;
  314.       }
  315.       putc ('z', ofp);
  316.       ascii85_linewidth++;
  317.     }
  318.   else
  319.     {
  320.       for (i=0; i < ascii85_len+1; i++)
  321.       {
  322.         if ((ascii85_linewidth >= max_linewidth) && (c[i] != '%'))
  323.         {
  324.           putc ('\n', ofp);
  325.           ascii85_linewidth = 0;
  326.         }
  327.     putc (c[i], ofp);
  328.         ascii85_linewidth++;
  329.       }
  330.     }
  331.  
  332.   ascii85_len = 0;
  333.   ascii85_buf = 0;
  334. }
  335.  
  336. static inline void
  337. ascii85_out (unsigned char byte, FILE *ofp)
  338. {
  339.   if (ascii85_len == 4)
  340.     ascii85_flush (ofp);
  341.  
  342.   ascii85_buf <<= 8;
  343.   ascii85_buf |= byte;
  344.   ascii85_len++;
  345. }
  346.  
  347. static void
  348. ascii85_nout (int n, unsigned char *uptr, FILE *ofp)
  349. {
  350.  while (n-- > 0)
  351.  {
  352.    ascii85_out (*uptr, ofp);
  353.    uptr++;
  354.  }
  355. }
  356.  
  357. static void
  358. ascii85_done (FILE *ofp)
  359. {
  360.   if (ascii85_len)
  361.     {
  362.       /* zero any unfilled buffer portion, then flush */
  363.       ascii85_buf <<= (8 * (4-ascii85_len));
  364.       ascii85_flush (ofp);
  365.     }
  366.  
  367.   putc ('~', ofp);
  368.   putc ('>', ofp);
  369.   putc ('\n', ofp);
  370. }
  371.  
  372.  
  373. static void
  374. compress_packbits (int nin,
  375.                    unsigned char *src,
  376.                    int *nout,
  377.                    unsigned char *dst)
  378.  
  379. {register unsigned char c;
  380.  int nrepeat, nliteral;
  381.  unsigned char *run_start;
  382.  unsigned char *start_dst = dst;
  383.  unsigned char *last_literal = NULL;
  384.  
  385.  for (;;)
  386.  {
  387.    if (nin <= 0) break;
  388.  
  389.    run_start = src;
  390.    c = *run_start;
  391.  
  392.    /* Search repeat bytes */
  393.    if ((nin > 1) && (c == src[1]))
  394.    {
  395.      nrepeat = 1;
  396.      nin -= 2;
  397.      src += 2;
  398.      while ((nin > 0) && (c == *src))
  399.      {
  400.        nrepeat++;
  401.        src++;
  402.        nin--;
  403.        if (nrepeat == 127) break; /* Maximum repeat */
  404.      }
  405.  
  406.      /* Add two-byte repeat to last literal run ? */
  407.      if (   (nrepeat == 1)
  408.          && (last_literal != NULL) && (((*last_literal)+1)+2 <= 128))
  409.      {
  410.        *last_literal += 2;
  411.        *(dst++) = c;
  412.        *(dst++) = c;
  413.        continue;
  414.      }
  415.  
  416.      /* Add repeat run */
  417.      *(dst++) = (unsigned char)((-nrepeat) & 0xff);
  418.      *(dst++) = c;
  419.      last_literal = NULL;
  420.      continue;
  421.    }
  422.    /* Search literal bytes */
  423.    nliteral = 1;
  424.    nin--;
  425.    src++;
  426.  
  427.    for (;;)
  428.    {
  429.      if (nin <= 0) break;
  430.  
  431.      if ((nin >= 2) && (src[0] == src[1])) /* A two byte repeat ? */
  432.        break;
  433.  
  434.      nliteral++;
  435.      nin--;
  436.      src++;
  437.      if (nliteral == 128) break; /* Maximum literal run */
  438.    }
  439.  
  440.    /* Could be added to last literal run ? */
  441.    if ((last_literal != NULL) && (((*last_literal)+1)+nliteral <= 128))
  442.    {
  443.      *last_literal += nliteral;
  444.    }
  445.    else
  446.    {
  447.      last_literal = dst;
  448.      *(dst++) = (unsigned char)(nliteral-1);
  449.    }
  450.    while (nliteral-- > 0) *(dst++) = *(run_start++);
  451.  }
  452.  *nout = dst - start_dst;
  453. }
  454.  
  455.  
  456. typedef struct
  457. {
  458.   long eol;
  459.   long begin_data;
  460. } PS_DATA_POS;
  461.  
  462. static PS_DATA_POS ps_data_pos = { 0, 0 };
  463.  
  464. static void
  465. ps_begin_data (FILE *ofp)
  466.  
  467. {
  468.                    /* %%BeginData: 123456789012 ASCII Bytes */
  469.  fprintf (ofp, "%s", "%%BeginData:                         ");
  470.  fflush (ofp);
  471.  ps_data_pos.eol = ftell (ofp);
  472.  fprintf (ofp, "\n");
  473.  fflush (ofp);
  474.  ps_data_pos.begin_data = ftell (ofp);
  475. }
  476.  
  477. static void
  478. ps_end_data (FILE *ofp)
  479.  
  480. {long end_data;
  481.  char s[64];
  482.  
  483.  if ((ps_data_pos.begin_data > 0) && (ps_data_pos.eol > 0))
  484.  {
  485.    fflush (ofp);
  486.    end_data = ftell (ofp);
  487.    if (end_data > 0)
  488.    {
  489.      sprintf (s, "%ld ASCII Bytes", end_data-ps_data_pos.begin_data);
  490.      if (fseek (ofp, ps_data_pos.eol - strlen (s), SEEK_SET) == 0)
  491.      {
  492.        fprintf (ofp, "%s", s);
  493.        fseek (ofp, 0, SEEK_END);
  494.      }
  495.    }
  496.  }
  497.  fprintf (ofp, "%s\n", "%%EndData");
  498. }
  499.  
  500.  
  501. MAIN ()
  502.  
  503. static void
  504. query (void)
  505. {
  506.   static GimpParamDef load_args[] =
  507.   {
  508.     { GIMP_PDB_INT32, "run_mode", "Interactive, non-interactive" },
  509.     { GIMP_PDB_STRING, "filename", "The name of the file to load" },
  510.     { GIMP_PDB_STRING, "raw_filename", "The name of the file to load" }
  511.   };
  512.   static GimpParamDef load_return_vals[] =
  513.   {
  514.     { GIMP_PDB_IMAGE, "image", "Output image" },
  515.   };
  516.   static gint nload_args = sizeof (load_args) / sizeof (load_args[0]);
  517.   static gint nload_return_vals = (sizeof (load_return_vals) /
  518.                    sizeof (load_return_vals[0]));
  519.  
  520.   static GimpParamDef set_load_args[] =
  521.   {
  522.     { GIMP_PDB_INT32, "resolution", "Resolution to interprete image (dpi)" },
  523.     { GIMP_PDB_INT32, "width", "Desired width" },
  524.     { GIMP_PDB_INT32, "height", "Desired height" },
  525.     { GIMP_PDB_INT32, "check_bbox", "0: Use width/height, 1: Use BoundingBox" },
  526.     { GIMP_PDB_STRING, "pages", "Pages to load (e.g.: 1,3,5-7)" },
  527.     { GIMP_PDB_INT32, "coloring", "4: b/w, 5: grey, 6: colour image, 7: automatic" },
  528.     { GIMP_PDB_INT32, "TextAlphaBits", "1, 2, or 4" },
  529.     { GIMP_PDB_INT32, "GraphicsAlphaBits", "1, 2, or 4" }
  530.   };
  531.   static gint nset_load_args = (sizeof (set_load_args) /
  532.                 sizeof (set_load_args[0]));
  533.  
  534.   static GimpParamDef save_args[] =
  535.   {
  536.     { GIMP_PDB_INT32, "run_mode", "Interactive, non-interactive" },
  537.     { GIMP_PDB_IMAGE, "image", "Input image" },
  538.     { GIMP_PDB_DRAWABLE, "drawable", "Drawable to save" },
  539.     { GIMP_PDB_STRING, "filename", "The name of the file to save the image in" },
  540.     { GIMP_PDB_STRING, "raw_filename",
  541.             "The name of the file to save the image in" },
  542.     { GIMP_PDB_FLOAT, "width", "Width of the image in PostScript file (0: use input image size)" },
  543.     { GIMP_PDB_FLOAT, "height", "Height of image in PostScript file (0: use input image size)" },
  544.     { GIMP_PDB_FLOAT, "x_offset", "X-offset to image from lower left corner" },
  545.     { GIMP_PDB_FLOAT, "y_offset", "Y-offset to image from lower left corner" },
  546.     { GIMP_PDB_INT32, "unit", "Unit for width/height/offset. 0: inches, 1: millimeters" },
  547.     { GIMP_PDB_INT32, "keep_ratio", "0: use width/height, 1: keep aspect ratio" },
  548.     { GIMP_PDB_INT32, "rotation", "0, 90, 180, 270" },
  549.     { GIMP_PDB_INT32, "eps_flag", "0: PostScript, 1: Encapsulated PostScript" },
  550.     { GIMP_PDB_INT32, "preview", "0: no preview, >0: max. size of preview" },
  551.     { GIMP_PDB_INT32, "level", "1: PostScript Level 1, 2: PostScript Level 2" }
  552.   };
  553.   static gint nsave_args = sizeof (save_args) / sizeof (save_args[0]);
  554.  
  555.   gimp_install_procedure ("file_ps_load",
  556.                           "load file of PostScript/PDF file format",
  557.                           "load file of PostScript/PDF file format",
  558.                           "Peter Kirchgessner <peter@kirchgessner.net>",
  559.                           "Peter Kirchgessner",
  560.                           dversio,
  561.                           "<Load>/PostScript",
  562.                           NULL,
  563.                           GIMP_PLUGIN,
  564.                           nload_args, nload_return_vals,
  565.                           load_args, load_return_vals);
  566.  
  567.   gimp_install_procedure ("file_ps_load_setargs",
  568.                           "set additional parameters for procedure file_ps_load",
  569.                           "set additional parameters for procedure file_ps_load",
  570.                           "Peter Kirchgessner <peter@kirchgessner.net>",
  571.                           "Peter Kirchgessner",
  572.                           dversio,
  573.                           NULL,
  574.                           NULL,
  575.                           GIMP_PLUGIN,
  576.                           nset_load_args, 0,
  577.                           set_load_args, NULL);
  578.  
  579.   gimp_install_procedure ("file_ps_save",
  580.                           "save file in PostScript file format",
  581.                           "PostScript saving handles all image types except those with alpha channels.",
  582.                           "Peter Kirchgessner <peter@kirchgessner.net>",
  583.                           "Peter Kirchgessner",
  584.                           dversio,
  585.                           "<Save>/PostScript",
  586.                           "RGB, GRAY, INDEXED",
  587.                           GIMP_PLUGIN,
  588.                           nsave_args, 0,
  589.                           save_args, NULL);
  590.  
  591.   gimp_register_magic_load_handler ("file_ps_load",
  592.                     "ps,eps,pdf",
  593.                     "",
  594.                                     "0,string,%!,0,string,%PDF");
  595.   gimp_register_save_handler       ("file_ps_save",
  596.                     "ps,eps",
  597.                     "");
  598. }
  599.  
  600.  
  601. #ifdef GIMP_HAVE_RESOLUTION_INFO
  602. static void
  603. ps_set_save_size (PSSaveVals *vals,
  604.                   gint32      image_ID)
  605. {
  606.   gdouble  xres, yres, factor, iw, ih;
  607.   guint    width, height;
  608.   GimpUnit unit;
  609.  
  610.   gimp_image_get_resolution (image_ID, &xres, &yres);
  611.   if ((xres < 1e-5) || (yres < 1e-5))
  612.     {
  613.       xres = yres = 72.0;
  614.     }
  615.   /* Calculate size of image in inches */
  616.   width  = gimp_image_width (image_ID);
  617.   height = gimp_image_height (image_ID);
  618.   iw = width  / xres;
  619.   ih = height / yres;
  620.  
  621.   unit = gimp_image_get_unit (image_ID);
  622.   factor = gimp_unit_get_factor (unit);
  623.   if (factor == 0.0254 ||
  624.       factor == 0.254 ||
  625.       factor == 2.54 ||
  626.       factor == 25.4)
  627.     {
  628.       vals->unit_mm = TRUE;
  629.     }
  630.  
  631.   if (vals->unit_mm)
  632.     {
  633.       iw *= 25.4;
  634.       ih *= 25.4;
  635.     }
  636.   vals->width  = iw;
  637.   vals->height = ih;
  638. }
  639. #endif
  640.  
  641. static void
  642. run (gchar   *name,
  643.      gint     nparams,
  644.      GimpParam  *param,
  645.      gint    *nreturn_vals,
  646.      GimpParam **return_vals)
  647. {
  648.   static GimpParam values[2];
  649.   GimpRunModeType  run_mode;
  650.   GimpPDBStatusType   status = GIMP_PDB_SUCCESS;
  651.   gint32        image_ID = -1;
  652.   gint32        drawable_ID = -1;
  653.   gint32        orig_image_ID = -1;
  654.   GimpExportReturnType export = GIMP_EXPORT_CANCEL;
  655.   gint k;
  656.  
  657.   l_run_mode = run_mode = param[0].data.d_int32;
  658.  
  659.   *nreturn_vals = 1;
  660.   *return_vals  = values;
  661.   values[0].type          = GIMP_PDB_STATUS;
  662.   values[0].data.d_status = GIMP_PDB_EXECUTION_ERROR;
  663.  
  664.   if (strcmp (name, "file_ps_load") == 0)
  665.     {
  666.       INIT_I18N_UI();
  667.  
  668.       switch (run_mode)
  669.     {
  670.         case GIMP_RUN_INTERACTIVE:
  671.           /*  Possibly retrieve data  */
  672.           gimp_get_data ("file_ps_load", &plvals);
  673.  
  674.           if (! load_dialog ())
  675.         status = GIMP_PDB_CANCEL;
  676.           break;
  677.  
  678.         case GIMP_RUN_NONINTERACTIVE:
  679.           /*  Make sure all the arguments are there!  */
  680.           if (nparams != 3)
  681.             status = GIMP_PDB_CALLING_ERROR;
  682.           else    /* Get additional interpretation arguments */
  683.             gimp_get_data ("file_ps_load", &plvals);
  684.           break;
  685.  
  686.         case GIMP_RUN_WITH_LAST_VALS:
  687.           /* Possibly retrieve data */
  688.           gimp_get_data ("file_ps_load", &plvals);
  689.           break;
  690.  
  691.         default:
  692.           break;
  693.     }
  694.  
  695.       if (status == GIMP_PDB_SUCCESS)
  696.     {
  697.       check_load_vals ();
  698.       image_ID = load_image (param[1].data.d_string);
  699.  
  700.       if (image_ID != -1)
  701.         {
  702.           *nreturn_vals = 2;
  703.           values[1].type         = GIMP_PDB_IMAGE;
  704.           values[1].data.d_image = image_ID;
  705.         }
  706.       else
  707.         {
  708.           status = GIMP_PDB_EXECUTION_ERROR;
  709.         }
  710.     }
  711.  
  712.       /*  Store plvals data  */
  713.       if (status == GIMP_PDB_SUCCESS)
  714.     gimp_set_data ("file_ps_load", &plvals, sizeof (PSLoadVals));
  715.     }
  716.   else if (strcmp (name, "file_ps_save") == 0)
  717.     {
  718.       INIT_I18N_UI();
  719.  
  720.       image_ID = orig_image_ID = param[1].data.d_int32;
  721.       drawable_ID = param[2].data.d_int32;
  722.  
  723.       /* eventually export the image */
  724.       switch (run_mode)
  725.     {
  726.     case GIMP_RUN_INTERACTIVE:
  727.     case GIMP_RUN_WITH_LAST_VALS:
  728.       gimp_ui_init ("ps", FALSE);
  729.       export = gimp_export_image (&image_ID, &drawable_ID, "PS",
  730.                       (GIMP_EXPORT_CAN_HANDLE_RGB |
  731.                        GIMP_EXPORT_CAN_HANDLE_GRAY |
  732.                        GIMP_EXPORT_CAN_HANDLE_INDEXED));
  733.       if (export == GIMP_EXPORT_CANCEL)
  734.         {
  735.           values[0].data.d_status = GIMP_PDB_CANCEL;
  736.           return;
  737.         }
  738.       break;
  739.     default:
  740.       break;
  741.     }
  742.  
  743.       switch (run_mode)
  744.         {
  745.         case GIMP_RUN_INTERACTIVE:
  746.           /*  Possibly retrieve data  */
  747.           gimp_get_data ("file_ps_save", &psvals);
  748.  
  749.           /* About to save an EPS-file ? Switch on eps-flag in dialog */
  750.           k = strlen (param[3].data.d_string);
  751.           if ((k >= 4) && (strcmp (param[3].data.d_string+k-4, ".eps") == 0))
  752.             psvals.eps = 1;
  753.  
  754. #ifdef GIMP_HAVE_RESOLUTION_INFO
  755.           ps_set_save_size (&psvals, orig_image_ID);
  756. #endif
  757.           /*  First acquire information with a dialog  */
  758.           if (! save_dialog ())
  759.             status = GIMP_PDB_CANCEL;
  760.           break;
  761.  
  762.         case GIMP_RUN_NONINTERACTIVE:
  763.           /*  Make sure all the arguments are there!  */
  764.           if (nparams != 15)
  765.         {
  766.           status = GIMP_PDB_CALLING_ERROR;
  767.         }
  768.           else
  769.         {
  770.           psvals.width        = param[5].data.d_float;
  771.           psvals.height       = param[6].data.d_float;
  772.           psvals.x_offset     = param[7].data.d_float;
  773.           psvals.y_offset     = param[8].data.d_float;
  774.           psvals.unit_mm      = (param[9].data.d_int32 != 0);
  775.           psvals.keep_ratio   = (param[10].data.d_int32 != 0);
  776.           psvals.rotate       = param[11].data.d_int32;
  777.           psvals.eps          = param[12].data.d_int32;
  778.           psvals.preview      = (param[13].data.d_int32 != 0);
  779.           psvals.preview_size = param[13].data.d_int32;
  780.           psvals.level        = param[14].data.d_int32;
  781.         }
  782.           break;
  783.  
  784.         case GIMP_RUN_WITH_LAST_VALS:
  785.           /*  Possibly retrieve data  */
  786.           gimp_get_data ("file_ps_save", &psvals);
  787.           break;
  788.  
  789.         default:
  790.           break;
  791.         }
  792.  
  793.       if (status == GIMP_PDB_SUCCESS)
  794.     {
  795. #ifdef GIMP_HAVE_RESOLUTION_INFO
  796.       if ((psvals.width == 0.0) || (psvals.height == 0.0))
  797.         ps_set_save_size (&psvals, orig_image_ID);
  798. #endif
  799.       check_save_vals ();
  800.       if (save_image (param[3].data.d_string, image_ID, drawable_ID))
  801.         {
  802.           /*  Store psvals data  */
  803.           gimp_set_data ("file_ps_save", &psvals, sizeof (PSSaveVals));
  804.         }
  805.       else
  806.         {
  807.           status = GIMP_PDB_EXECUTION_ERROR;
  808.         }
  809.     }
  810.  
  811.       if (export == GIMP_EXPORT_EXPORT)
  812.     gimp_image_delete (image_ID);
  813.     }
  814.   else if (strcmp (name, "file_ps_load_setargs") == 0)
  815.     {
  816.       /*  Make sure all the arguments are there!  */
  817.       if (nparams != 8)
  818.     {
  819.       status = GIMP_PDB_CALLING_ERROR;
  820.     }
  821.       else
  822.     {
  823.       plvals.resolution = param[0].data.d_int32;
  824.       plvals.width      = param[1].data.d_int32;
  825.       plvals.height     = param[2].data.d_int32;
  826.       plvals.use_bbox   = param[3].data.d_int32;
  827.       if (param[4].data.d_string != NULL)
  828.         strncpy (plvals.pages, param[4].data.d_string,
  829.              sizeof (plvals.pages));
  830.       else
  831.         plvals.pages[0] = '\0';
  832.       plvals.pages[sizeof (plvals.pages) - 1] = '\0';
  833.       plvals.pnm_type      = param[5].data.d_int32;
  834.       plvals.textalpha     = param[6].data.d_int32;
  835.       plvals.graphicsalpha = param[7].data.d_int32;
  836.       check_load_vals ();
  837.       gimp_set_data ("file_ps_load", &plvals, sizeof (PSLoadVals));
  838.     }
  839.     }
  840.   else
  841.     {
  842.       status = GIMP_PDB_CALLING_ERROR;
  843.     }
  844.  
  845.   values[0].data.d_status = status;
  846. }
  847.  
  848.  
  849. static gint32
  850. load_image (gchar *filename)
  851. {
  852.   gint32 image_ID, *image_list, *nl;
  853.   guint page_count;
  854.   FILE *ifp;
  855.   char *temp;
  856.   int  llx, lly, urx, ury;
  857.   int  k, n_images, max_images, max_pagenum;
  858.   int  is_epsf;
  859.  
  860. #ifdef PS_DEBUG
  861.   g_print ("load_image:\n resolution = %d\n", plvals.resolution);
  862.   g_print (" %dx%d pixels\n", plvals.width, plvals.height);
  863.   g_print (" BoundingBox: %d\n", plvals.use_bbox);
  864.   g_print (" Colouring: %d\n", plvals.pnm_type);
  865.   g_print (" TextAlphaBits: %d\n", plvals.textalpha);
  866.   g_print (" GraphicsAlphaBits: %d\n", plvals.graphicsalpha);
  867. #endif
  868.  
  869.   /* Try to see if PostScript file is available */
  870.   ifp = fopen (filename, "r");
  871.   if (ifp == NULL)
  872.     {
  873.       g_message (_("PS: can't open file for reading"));
  874.       return (-1);
  875.     }
  876.   fclose (ifp);
  877.  
  878.   if (l_run_mode != GIMP_RUN_NONINTERACTIVE)
  879.     {
  880.       temp = g_strdup_printf (_("Interpreting and Loading %s:"), filename);
  881.       gimp_progress_init (temp);
  882.       g_free (temp);
  883.     }
  884.  
  885.   ifp = ps_open (filename, &plvals, &llx, &lly, &urx, &ury, &is_epsf);
  886.   if (!ifp)
  887.     {
  888.       g_message (_("PS: can't interprete file"));
  889.       return (-1);
  890.     }
  891.  
  892.   image_list = (gint32 *)g_malloc (10 * sizeof (gint32));
  893.   n_images = 0;
  894.   max_images = 10;
  895.  
  896.   max_pagenum = 9999;  /* Try to get the maximum pagenumber to read */
  897.   if (is_epsf) max_pagenum = 1;
  898.   if (!page_in_list (plvals.pages, max_pagenum)) /* Is there a limit in list ? */
  899.     {
  900.       max_pagenum = -1;
  901.       for (temp = plvals.pages; *temp != '\0'; temp++)
  902.     {
  903.       if ((*temp < '0') || (*temp > '9')) continue; /* Search next digit */
  904.       sscanf (temp, "%d", &k);
  905.       if (k > max_pagenum) max_pagenum = k;
  906.       while ((*temp >= '0') && (*temp <= '9')) temp++;
  907.       temp--;
  908.     }
  909.       if (max_pagenum < 1) max_pagenum = 9999;
  910.     }
  911.  
  912.   /* Load all images */
  913.   for (page_count = 1; page_count <= max_pagenum; page_count++)
  914.     {
  915.       if (page_in_list (plvals.pages, page_count))
  916.     {
  917.       image_ID = load_ps (filename, page_count, ifp, llx, lly, urx, ury);
  918.       if (image_ID == -1) break;
  919. #ifdef GIMP_HAVE_RESOLUTION_INFO
  920.       gimp_image_set_resolution (image_ID,
  921.                      (double) plvals.resolution,
  922.                      (double) plvals.resolution);
  923. #endif
  924.       if (n_images == max_images)
  925.         {
  926.           nl = (gint32 *) g_realloc (image_list,
  927.                      (max_images+10)*sizeof (gint32));
  928.           if (nl == NULL) break;
  929.           image_list = nl;
  930.           max_images += 10;
  931.         }
  932.       image_list[n_images++] = image_ID;
  933.     }
  934.       else  /* Skip an image */
  935.     {
  936.       image_ID = skip_ps (ifp);
  937.       if (image_ID == -1) break;
  938.     }
  939.     }
  940.   ps_close (ifp);
  941.  
  942.   /* Display images in reverse order. The last will be displayed by GIMP itself*/
  943.   if (l_run_mode != GIMP_RUN_NONINTERACTIVE)
  944.     {
  945.       for (k = n_images-1; k >= 1; k--)
  946.     gimp_display_new (image_list[k]);
  947.     }
  948.  
  949.   image_ID = (n_images > 0) ? image_list[0] : -1;
  950.   g_free (image_list);
  951.  
  952.   return (image_ID);
  953. }
  954.  
  955.  
  956. static gint
  957. save_image (gchar  *filename,
  958.             gint32  image_ID,
  959.             gint32  drawable_ID)
  960. {
  961.   FILE* ofp;
  962.   GimpImageType drawable_type;
  963.   gint retval;
  964.   char *temp = ident; /* Just to satisfy lint/gcc */
  965.  
  966.   /* initialize */
  967.  
  968.   retval = 0;
  969.  
  970.   drawable_type = gimp_drawable_type (drawable_ID);
  971.  
  972.   /*  Make sure we're not saving an image with an alpha channel  */
  973.   if (gimp_drawable_has_alpha (drawable_ID))
  974.     {
  975.       g_message (_("PostScript save cannot handle images with alpha channels"));
  976.       return FALSE;
  977.     }
  978.  
  979.   switch (drawable_type)
  980.     {
  981.     case GIMP_INDEXED_IMAGE:
  982.     case GIMP_GRAY_IMAGE:
  983.     case GIMP_RGB_IMAGE:
  984.       break;
  985.     default:
  986.       g_message (_("PS: cannot operate on unknown image types"));
  987.       return (FALSE);
  988.       break;
  989.     }
  990.  
  991.   /* Open the output file. */
  992.   ofp = fopen (filename, "wb");
  993.   if (!ofp)
  994.     {
  995.       g_message (_("PS: can't open file for writing"));
  996.       return (FALSE);
  997.     }
  998.  
  999.   if (l_run_mode != GIMP_RUN_NONINTERACTIVE)
  1000.     {
  1001.       temp = g_strdup_printf (_("Saving %s:"), filename);
  1002.       gimp_progress_init (temp);
  1003.       g_free (temp);
  1004.     }
  1005.  
  1006.   save_ps_header (ofp, filename);
  1007.  
  1008.   if (drawable_type == GIMP_GRAY_IMAGE)
  1009.     retval = save_gray (ofp, image_ID, drawable_ID);
  1010.   else if (drawable_type == GIMP_INDEXED_IMAGE)
  1011.     retval = save_index (ofp, image_ID, drawable_ID);
  1012.   else if (drawable_type == GIMP_RGB_IMAGE)
  1013.     retval = save_rgb (ofp, image_ID, drawable_ID);
  1014.  
  1015.   save_ps_trailer (ofp);
  1016.  
  1017.   fclose (ofp);
  1018.  
  1019.   return (retval);
  1020. }
  1021.  
  1022.  
  1023. /* Check (and correct) the load values plvals */
  1024. static void
  1025. check_load_vals (void)
  1026. {
  1027.   if (plvals.resolution < 5)
  1028.     plvals.resolution = 5;
  1029.   else if (plvals.resolution > 1440)
  1030.     plvals.resolution = 1440;
  1031.  
  1032.   if (plvals.width < 2)
  1033.     plvals.width = 2;
  1034.   if (plvals.height < 2)
  1035.     plvals.height = 2;
  1036.   plvals.use_bbox = (plvals.use_bbox != 0);
  1037.   if (plvals.pages[0] == '\0')
  1038.     strcpy (plvals.pages, "1-99");
  1039.   if ((plvals.pnm_type < 4) || (plvals.pnm_type > 7))
  1040.     plvals.pnm_type = 6;
  1041.   if (   (plvals.textalpha != 1) && (plvals.textalpha != 2)
  1042.       && (plvals.textalpha != 4))
  1043.     plvals.textalpha = 1;
  1044.   if (   (plvals.graphicsalpha != 1) && (plvals.graphicsalpha != 2)
  1045.       && (plvals.graphicsalpha != 4))
  1046.     plvals.graphicsalpha = 1;
  1047. }
  1048.  
  1049.  
  1050. /* Check (and correct) the save values psvals */
  1051. static void
  1052. check_save_vals (void)
  1053. {
  1054.   int i;
  1055.  
  1056.   i = psvals.rotate;
  1057.   if ((i != 0) && (i != 90) && (i != 180) && (i != 270))
  1058.     psvals.rotate = 90;
  1059.   if (psvals.preview_size <= 0)
  1060.     psvals.preview = FALSE;
  1061. }
  1062.  
  1063.  
  1064. /* Check if a page is in a given list */
  1065. static gint
  1066. page_in_list (gchar *list,
  1067.               guint  page_num)
  1068. {
  1069.   char tmplist[STR_LENGTH], *c0, *c1;
  1070.   int state, start_num, end_num;
  1071. #define READ_STARTNUM  0
  1072. #define READ_ENDNUM    1
  1073. #define CHK_LIST(a,b,c) {int low=(a),high=(b),swp; \
  1074.   if ((low>0) && (high>0)) { \
  1075.   if (low>high) {swp=low; low=high; high=swp;} \
  1076.   if ((low<=(c))&&(high>=(c))) return (1); } }
  1077.  
  1078.   if ((list == NULL) || (*list == '\0')) return (1);
  1079.  
  1080.   strncpy (tmplist, list, STR_LENGTH);
  1081.   tmplist[STR_LENGTH-1] = '\0';
  1082.  
  1083.   c0 = c1 = tmplist;
  1084.   while (*c1)    /* Remove all whitespace and break on unsupported characters */
  1085.     {
  1086.       if ((*c1 >= '0') && (*c1 <= '9'))
  1087.     {
  1088.       *(c0++) = *c1;
  1089.     }
  1090.       else if ((*c1 == '-') || (*c1 == ','))
  1091.     { /* Try to remove double occurances of these characters */
  1092.       if (c0 == tmplist)
  1093.         {
  1094.           *(c0++) = *c1;
  1095.         }
  1096.       else
  1097.         {
  1098.           if (*(c0-1) != *c1)
  1099.         *(c0++) = *c1;
  1100.         }
  1101.     }
  1102.       else break;
  1103.       c1++;
  1104.     }
  1105.   if (c0 == tmplist) return (1);
  1106.   *c0 = '\0';
  1107.  
  1108.   /* Now we have a comma separated list like 1-4-1,-3,1- */
  1109.  
  1110.   start_num = end_num = -1;
  1111.   state = READ_STARTNUM;
  1112.   for (c0 = tmplist; *c0 != '\0'; c0++)
  1113.     {
  1114.       switch (state)
  1115.     {
  1116.     case READ_STARTNUM:
  1117.       if (*c0 == ',')
  1118.         {
  1119.           if ((start_num > 0) && (start_num == (int)page_num)) return (-1);
  1120.           start_num = -1;
  1121.         }
  1122.       else if (*c0 == '-')
  1123.         {
  1124.           if (start_num < 0) start_num = 1;
  1125.           state = READ_ENDNUM;
  1126.         }
  1127.       else /* '0' - '9' */
  1128.         {
  1129.           if (start_num < 0) start_num = 0;
  1130.           start_num *= 10;
  1131.           start_num += *c0 - '0';
  1132.         }
  1133.       break;
  1134.  
  1135.     case READ_ENDNUM:
  1136.       if (*c0 == ',')
  1137.         {
  1138.           if (end_num < 0) end_num = 9999;
  1139.           CHK_LIST (start_num, end_num, (int)page_num);
  1140.           start_num = end_num = -1;
  1141.           state = READ_STARTNUM;
  1142.         }
  1143.       else if (*c0 == '-')
  1144.         {
  1145.           CHK_LIST (start_num, end_num, (int)page_num);
  1146.           start_num = end_num;
  1147.           end_num = -1;
  1148.         }
  1149.       else /* '0' - '9' */
  1150.         {
  1151.           if (end_num < 0) end_num = 0;
  1152.           end_num *= 10;
  1153.           end_num += *c0 - '0';
  1154.         }
  1155.       break;
  1156.     }
  1157.     }
  1158.   if (state == READ_STARTNUM)
  1159.     {
  1160.       if (start_num > 0)
  1161.     return (start_num == (int)page_num);
  1162.     }
  1163.   else
  1164.     {
  1165.       if (end_num < 0) end_num = 9999;
  1166.       CHK_LIST (start_num, end_num, (int)page_num);
  1167.     }
  1168.   return (0);
  1169. #undef CHK_LIST
  1170. }
  1171.  
  1172.  
  1173. /* A function like fgets, but treats single CR-character as line break. */
  1174. /* As a line break the newline-character is returned. */
  1175. static char *psfgets (char *s, int size, FILE *stream)
  1176.  
  1177. {int c;
  1178.  char *sptr = s;
  1179.  
  1180.  if (size <= 0) return NULL;
  1181.  if (size == 1)
  1182.  {
  1183.    *s = '\0';
  1184.    return NULL;
  1185.  }
  1186.  c = getc (stream);
  1187.  if (c == EOF) return NULL;
  1188.  
  1189.  for (;;)
  1190.  {
  1191.    /* At this point we have space in sptr for at least two characters */
  1192.    if (c == '\n')    /* Got end of line (UNIX line end) ? */
  1193.    {
  1194.      *(sptr++) = '\n';
  1195.      break;
  1196.    }
  1197.    else if (c == '\r')  /* Got a carriage return. Check next charcater */
  1198.    {
  1199.      c = getc (stream);
  1200.      if ((c == EOF) || (c == '\n')) /* EOF or DOS line end ? */
  1201.      {
  1202.        *(sptr++) = '\n';  /* Return UNIX line end */
  1203.        break;
  1204.      }
  1205.      else  /* Single carriage return. Return UNIX line end. */
  1206.      {
  1207.        ungetc (c, stream);  /* Save the extra character */
  1208.        *(sptr++) = '\n';
  1209.        break;
  1210.      }
  1211.    }
  1212.    else   /* no line end character */
  1213.    {
  1214.      *(sptr++) = (char)c;
  1215.      size--;
  1216.    }
  1217.    if (size == 1) break;  /* Only space for the nul-character ? */
  1218.    c = getc (stream);
  1219.    if (c == EOF) break;
  1220.  }
  1221.  *sptr = '\0';
  1222.  return s;
  1223. }
  1224.  
  1225.  
  1226. /* Get the BoundingBox of a PostScript file. On success, 0 is returned. */
  1227. /* On failure, -1 is returned. */
  1228. static gint
  1229. get_bbox (gchar *filename,
  1230.           gint  *x0,
  1231.           gint  *y0,
  1232.           gint  *x1,
  1233.           gint  *y1)
  1234. {
  1235.   char line[1024], *src;
  1236.   FILE *ifp;
  1237.   int retval = -1;
  1238.  
  1239.   ifp = fopen (filename, "rb");
  1240.   if (ifp == NULL) return (-1);
  1241.  
  1242.   for (;;)
  1243.     {
  1244.       if (psfgets (line, sizeof (line)-1, ifp) == NULL) break;
  1245.       if ((line[0] != '%') || (line[1] != '%')) continue;
  1246.       src = &(line[2]);
  1247.       while ((*src == ' ') || (*src == '\t')) src++;
  1248.       if (strncmp (src, "BoundingBox", 11) != 0) continue;
  1249.       src += 11;
  1250.       while ((*src == ' ') || (*src == '\t') || (*src == ':')) src++;
  1251.       if (strncmp (src, "(atend)", 7) == 0) continue;
  1252.       if (sscanf (src, "%d%d%d%d", x0, y0, x1, y1) == 4)
  1253.     retval = 0;
  1254.       break;
  1255.     }
  1256.   fclose (ifp);
  1257.   return (retval);
  1258. }
  1259.  
  1260. static gchar *pnmfile;
  1261. #ifdef G_OS_WIN32
  1262. static gchar *indirfile = NULL;
  1263. #endif
  1264.  
  1265. /* Open the PostScript file. On failure, NULL is returned. */
  1266. /* The filepointer returned will give a PNM-file generated */
  1267. /* by the PostScript-interpreter. */
  1268. static FILE *
  1269. ps_open (gchar            *filename,
  1270.          const PSLoadVals *loadopt,
  1271.          gint             *llx,
  1272.          gint             *lly,
  1273.          gint             *urx,
  1274.          gint             *ury,
  1275.          gint             *is_epsf)
  1276. {
  1277.   char *cmd, *gs, *gs_opts, *driver, *fnbuf = NULL;
  1278.   FILE *fd_popen;
  1279.   int width, height, resolution;
  1280.   int x0, y0, x1, y1;
  1281.   int offx = 0, offy = 0;
  1282.   int is_pdf;
  1283.   int blank, anf, apo;
  1284.   char TextAlphaBits[64], GraphicsAlphaBits[64], geometry[32];
  1285.   char offset[32];
  1286.  
  1287.   resolution = loadopt->resolution;
  1288.   *llx = *lly = 0;
  1289.   width = loadopt->width;
  1290.   height = loadopt->height;
  1291.   *urx = width-1;
  1292.   *ury = height-1;
  1293.  
  1294.   /* Check if the file is a PDF. For PDF, we cant set geometry */
  1295.   is_pdf = 0;
  1296.   /* Check if it is a EPS-file */
  1297.   *is_epsf = 0;
  1298.   fd_popen = fopen (filename, "rb");
  1299.   if (fd_popen != NULL)
  1300.     {
  1301.       char hdr[512];
  1302.  
  1303.       fread (hdr, 1, sizeof(hdr), fd_popen);
  1304.       is_pdf = (strncmp (hdr, "%PDF", 4) == 0);
  1305.  
  1306.       if (!is_pdf)  /* Check for EPSF */
  1307.       {char *adobe, *epsf;
  1308.        int ds = 0;
  1309.  
  1310.         hdr[sizeof(hdr)-1] = '\0';
  1311.         adobe = strstr (hdr, "PS-Adobe-");
  1312.         epsf = strstr (hdr, "EPSF-");
  1313.         if ((adobe != NULL) && (epsf != NULL))
  1314.           ds = epsf - adobe;
  1315.         *is_epsf = ((ds >= 11) && (ds <= 15));
  1316.       }
  1317.       fclose (fd_popen);
  1318.     }
  1319.  
  1320.   if ((!is_pdf) && (loadopt->use_bbox))    /* Try the BoundingBox ? */
  1321.     {
  1322.       if (get_bbox (filename, &x0, &y0, &x1, &y1) == 0)
  1323.         {
  1324.           if (*is_epsf)  /* Handle negative BoundingBox for EPSF */
  1325.             {
  1326.               offx = -x0; x1 += offx; x0 += offx;
  1327.               offy = -y0; y1 += offy; y0 += offy;
  1328.             }
  1329.           if ((x0 >= 0) && (y0 >= 0) && (x1 > x0) && (y1 > y0))
  1330.             {
  1331.                *llx = (int)((x0/72.0) * resolution + 0.01);
  1332.                *lly = (int)((y0/72.0) * resolution + 0.01);
  1333.                *urx = (int)((x1/72.0) * resolution + 0.01);
  1334.                *ury = (int)((y1/72.0) * resolution + 0.01);
  1335.                width = *urx + 1;
  1336.                height = *ury + 1;
  1337.             }
  1338.         }
  1339.     }
  1340.   if (loadopt->pnm_type == 4) driver = "pbmraw";
  1341.   else if (loadopt->pnm_type == 5) driver = "pgmraw";
  1342.   else if (loadopt->pnm_type == 7) driver = "pnmraw";
  1343.   else driver = "ppmraw";
  1344.  
  1345. #ifdef USE_REAL_OUTPUTFILE
  1346.   /* For instance, the Win32 port of ghostscript doesn't work correctly when
  1347.    * using standard output as output file.
  1348.    * Thus, use a real output file.
  1349.    */
  1350.   pnmfile = g_strdup_printf ("%s" G_DIR_SEPARATOR_S "p%lx",
  1351.                  g_get_tmp_dir (), getpid ());
  1352. #else
  1353.   pnmfile = "-";
  1354. #endif
  1355.  
  1356.   gs = getenv ("GS_PROG");
  1357. #ifndef G_OS_WIN32
  1358.   if (gs == NULL) gs = "gs";
  1359.  
  1360.   /* Escape special characters. Escaping " does not work with call of shell. */
  1361.   /* fnbuf points to memory that should be freed. */
  1362.   filename = fnbuf = gimp_strescape (filename, "\"");
  1363.   blank = (strchr (filename, ' ') != NULL);
  1364.   apo = (strchr (filename, '\'') != NULL);
  1365.   anf = (strchr (filename, '"') != NULL);
  1366.  
  1367.   /* Must the filename be enclosed ? */
  1368.   /* If we have " and ' it will not work */
  1369.   if (blank || anf || apo)
  1370.   {
  1371.     if (!anf) /* No " ? Enclose with " */
  1372.     {
  1373.       filename = g_strdup_printf ("\"%s\"", filename);
  1374.       g_free (fnbuf);
  1375.       fnbuf = filename;
  1376.     }
  1377.     else if (!apo) /* No ' ? Enclose with ' */
  1378.     {
  1379.       filename = g_strdup_printf ("'%s'", filename);
  1380.       g_free (fnbuf);
  1381.       fnbuf = filename;
  1382.     }
  1383.   }
  1384.  
  1385. #else
  1386.   /* We want the console ghostscript application. It should be in the PATH */
  1387.   if (gs == NULL)
  1388.     gs = "gswin32c";
  1389.   /* Quote the filename in case it contains spaces. Ignore memory leak,
  1390.    * this is a short-lived plug-in.
  1391.    */
  1392.   filename = g_strdup_printf ("\"%s\"", filename);
  1393. #endif
  1394.  
  1395.   gs_opts = getenv ("GS_OPTIONS");
  1396.   if (gs_opts == NULL)
  1397.     gs_opts = "-dSAFER";
  1398.   else
  1399.     gs_opts = "";  /* Ghostscript will add these options */
  1400.  
  1401.   TextAlphaBits[0] = GraphicsAlphaBits[0] = geometry[0] = '\0';
  1402.   offset[0] = '\0';
  1403.  
  1404.   /* Offset command for gs to get image part with negative x/y-coord. */
  1405.   if ((offx != 0) || (offy != 0))
  1406.     sprintf (offset, "-c %d %d translate -- ", offx, offy);
  1407.  
  1408.   /* Antialiasing not available for PBM-device */
  1409.   if ((loadopt->pnm_type != 4) && (loadopt->textalpha != 1))
  1410.     sprintf (TextAlphaBits, "-dTextAlphaBits=%d ", (int)loadopt->textalpha);
  1411.  
  1412.   if ((loadopt->pnm_type != 4) && (loadopt->graphicsalpha != 1))
  1413.     sprintf (GraphicsAlphaBits, "-dGraphicsAlphaBits=%d ",
  1414.          (int)loadopt->graphicsalpha);
  1415.  
  1416.   if (!is_pdf)    /* For PDF, we cant set geometry */
  1417.     sprintf (geometry,"-g%dx%d ", width, height);
  1418.  
  1419.   cmd = g_strdup_printf ("%s -sDEVICE=%s -r%d %s%s%s-q -dNOPAUSE %s \
  1420. -sOutputFile=%s %s%s %s-c quit",
  1421.              gs, driver, resolution, geometry,
  1422.              TextAlphaBits, GraphicsAlphaBits,
  1423.              gs_opts, pnmfile, offset, filename,
  1424.                          *is_epsf ? "-c showpage " : "");
  1425. #ifdef PS_DEBUG
  1426.   g_print ("Going to start ghostscript with:\n%s\n", cmd);
  1427. #endif
  1428.  
  1429. #ifndef USE_REAL_OUTPUTFILE
  1430.   /* Start the command and use a pipe for reading the PNM-file. */
  1431. #ifndef __EMX__
  1432.   fd_popen = popen (cmd, "r");
  1433. #else
  1434.   fd_popen = popen (cmd, "rb");
  1435. #endif
  1436. #else
  1437.   /* If someone does not like the pipe (or it does not work), just start */
  1438.   /* ghostscript with a real outputfile. When ghostscript has finished,  */
  1439.   /* open the outputfile and return its filepointer. But be sure         */
  1440.   /* to close and remove the file within ps_close().                     */
  1441. #ifdef G_OS_WIN32
  1442.   /* Work around braindead command line length limit.
  1443.    * Hmm, I wonder if this is necessary, but it doesn't harm...
  1444.    */
  1445.   if (strlen (cmd) >= 100)
  1446.     {
  1447.       FILE *indf;
  1448.       indirfile = g_strdup_printf ("%s" G_DIR_SEPARATOR_S "i%lx",
  1449.                    g_get_tmp_dir (), getpid ());
  1450.       indf = fopen (indirfile, "w");
  1451.       fprintf (indf, "%s\n", cmd + strlen (gs) + 1);
  1452.       sprintf (cmd, "%s @%s", gs, indirfile);
  1453.       fclose (indf);
  1454.     }
  1455. #endif
  1456.   system (cmd);
  1457.   fd_popen = fopen (pnmfile, "rb");
  1458. #endif
  1459.   g_free (cmd);
  1460.   g_free (fnbuf);
  1461.  
  1462.   return (fd_popen);
  1463. }
  1464.  
  1465.  
  1466. /* Close the PNM-File of the PostScript interpreter */
  1467. static void
  1468. ps_close (FILE *ifp)
  1469. {
  1470. #ifndef USE_REAL_OUTPUTFILE
  1471.  
  1472.   /* Even if we dont want all images, we have to read the pipe until EOF. */
  1473.   /* Otherwise the subprocess and therefore pclose() may not finish. */
  1474.   while (getc (ifp) != EOF) ;
  1475.  
  1476.   /* Finish reading from pipe. */
  1477.   pclose (ifp);
  1478. #else
  1479.  /* If a real outputfile was used, close the file and remove it. */
  1480.   fclose (ifp);
  1481.   unlink (pnmfile);
  1482. #ifdef G_OS_WIN32
  1483.   if (indirfile != NULL)
  1484.     unlink (indirfile);
  1485. #endif
  1486. #endif
  1487. }
  1488.  
  1489.  
  1490. /* Read the header of a raw PNM-file and return type (4-6) or -1 on failure */
  1491. static gint
  1492. read_pnmraw_type (FILE *ifp,
  1493.                   gint *width,
  1494.                   gint *height,
  1495.                   gint *maxval)
  1496. {
  1497.   register int frst, scnd, thrd;
  1498.   gint pnmtype;
  1499.   char line[1024];
  1500.  
  1501.   /* GhostScript may write some informational messages infront of the header. */
  1502.   /* We are just looking at a Px\n in the input stream. */
  1503.   frst = getc (ifp);
  1504.   scnd = getc (ifp);
  1505.   thrd = getc (ifp);
  1506.   for (;;)
  1507.     {
  1508.       if (thrd == EOF) return (-1);
  1509. #if defined (__EMX__) || defined (WIN32)
  1510.       if (thrd == '\r') thrd = getc (ifp);
  1511. #endif
  1512.       if ((thrd == '\n') && (frst == 'P') && (scnd >= '1') && (scnd <= '6'))
  1513.     break;
  1514.       frst = scnd;
  1515.       scnd = thrd;
  1516.       thrd = getc (ifp);
  1517.     }
  1518.   pnmtype = scnd - '0';
  1519.   /* We dont use the ASCII-versions */
  1520.   if ((pnmtype >= 1) && (pnmtype <= 3)) return (-1);
  1521.  
  1522.   /* Read width/height */
  1523.   for (;;)
  1524.     {
  1525.       if (fgets (line, sizeof (line)-1, ifp) == NULL) return (-1);
  1526.       if (line[0] != '#') break;
  1527.     }
  1528.   if (sscanf (line, "%d%d", width, height) != 2) return (-1);
  1529.   *maxval = 255;
  1530.  
  1531.   if (pnmtype != 4)  /* Read maxval */
  1532.     {
  1533.       for (;;)
  1534.     {
  1535.       if (fgets (line, sizeof (line)-1, ifp) == NULL) return (-1);
  1536.       if (line[0] != '#') break;
  1537.     }
  1538.       if (sscanf (line, "%d", maxval) != 1) return (-1);
  1539.     }
  1540.   return (pnmtype);
  1541. }
  1542.  
  1543.  
  1544. /* Create an image. Sets layer_ID, drawable and rgn. Returns image_ID */
  1545. static gint32
  1546. create_new_image (gchar       *filename,
  1547.                   guint        pagenum,
  1548.                   guint        width,
  1549.                   guint        height,
  1550.                   GimpImageBaseType   type,
  1551.                   gint32      *layer_ID,
  1552.                   GimpDrawable  **drawable,
  1553.                   GimpPixelRgn   *pixel_rgn)
  1554. {
  1555.   gint32 image_ID;
  1556.   GimpImageType gdtype;
  1557.   char *tmp;
  1558.  
  1559.   if (type == GIMP_GRAY) gdtype = GIMP_GRAY_IMAGE;
  1560.   else if (type == GIMP_INDEXED) gdtype = GIMP_INDEXED_IMAGE;
  1561.   else gdtype = GIMP_RGB_IMAGE;
  1562.  
  1563.   image_ID = gimp_image_new (width, height, type);
  1564.   tmp = g_strdup_printf ("%s-pg%ld", filename, (long)pagenum);
  1565.   gimp_image_set_filename (image_ID, tmp);
  1566.   g_free (tmp);
  1567.  
  1568.   *layer_ID = gimp_layer_new (image_ID, "Background", width, height,
  1569.                   gdtype, 100, GIMP_NORMAL_MODE);
  1570.   gimp_image_add_layer (image_ID, *layer_ID, 0);
  1571.  
  1572.   *drawable = gimp_drawable_get (*layer_ID);
  1573.   gimp_pixel_rgn_init (pixel_rgn, *drawable, 0, 0, (*drawable)->width,
  1574.                (*drawable)->height, TRUE, FALSE);
  1575.  
  1576.   return (image_ID);
  1577. }
  1578.  
  1579.  
  1580. /* Skip PNM image generated from PostScript file. */
  1581. /* Returns 0 on success, -1 on failure. */
  1582. static gint32
  1583. skip_ps (FILE *ifp)
  1584. {
  1585.   register int k, c;
  1586.   int i, pnmtype, width, height, maxval, bpl;
  1587.  
  1588.   pnmtype = read_pnmraw_type (ifp, &width, &height, &maxval);
  1589.  
  1590.   if (pnmtype == 4)    /* Portable bitmap */
  1591.     bpl = (width + 7)/8;
  1592.   else if (pnmtype == 5)
  1593.     bpl = width;
  1594.   else if (pnmtype == 6)
  1595.     bpl = width*3;
  1596.   else
  1597.     return (-1);
  1598.  
  1599.   for (i = 0; i < height; i++)
  1600.     {
  1601.       k = bpl;  c = EOF;
  1602.       while (k-- > 0) c = getc (ifp);
  1603.       if (c == EOF) return (-1);
  1604.  
  1605.       if ((l_run_mode != GIMP_RUN_NONINTERACTIVE) && ((i % 20) == 0))
  1606.     gimp_progress_update ((double)(i+1) / (double)height);
  1607.     }
  1608.  
  1609.   return (0);
  1610. }
  1611.  
  1612.  
  1613. /* Load PNM image generated from PostScript file */
  1614. static gint32
  1615. load_ps (gchar *filename,
  1616.          guint  pagenum,
  1617.          FILE  *ifp,
  1618.          gint   llx,
  1619.          gint   lly,
  1620.          gint   urx,
  1621.          gint   ury)
  1622. {
  1623.   register guchar *dest;
  1624.   guchar *data, *bitline = NULL, *byteline = NULL, *byteptr, *temp;
  1625.   guchar bit2byte[256*8];
  1626.   int width, height, tile_height, scan_lines, total_scan_lines;
  1627.   int image_width, image_height;
  1628.   int skip_left, skip_bottom;
  1629.   int i, j, pnmtype, maxval, bpp, nread;
  1630.   GimpImageBaseType imagetype;
  1631.   gint32 layer_ID, image_ID;
  1632.   GimpPixelRgn pixel_rgn;
  1633.   GimpDrawable *drawable;
  1634.   int err = 0, e;
  1635.  
  1636.   pnmtype = read_pnmraw_type (ifp, &width, &height, &maxval);
  1637.  
  1638.   if ((width == urx+1) && (height == ury+1))  /* gs respected BoundingBox ? */
  1639.     {
  1640.       skip_left = llx;    skip_bottom = lly;
  1641.       image_width = width - skip_left;
  1642.       image_height = height - skip_bottom;
  1643.     }
  1644.   else
  1645.     {
  1646.       skip_left = skip_bottom = 0;
  1647.       image_width = width;
  1648.       image_height = height;
  1649.     }
  1650.   if (pnmtype == 4)   /* Portable Bitmap */
  1651.     {
  1652.       imagetype = GIMP_INDEXED;
  1653.       nread = (width+7)/8;
  1654.       bpp = 1;
  1655.       bitline = (guchar *)g_malloc (nread);
  1656.       byteline = (guchar *)g_malloc (nread*8);
  1657.  
  1658.       /* Get an array for mapping 8 bits in a byte to 8 bytes */
  1659.       temp = bit2byte;
  1660.       for (j = 0; j < 256; j++)
  1661.     for (i = 7; i >= 0; i--)
  1662.       *(temp++) = ((j & (1 << i)) != 0);
  1663.     }
  1664.   else if (pnmtype == 5)  /* Portable Greymap */
  1665.     {
  1666.       imagetype = GIMP_GRAY;
  1667.       nread = width;
  1668.       bpp = 1;
  1669.       byteline = (unsigned char *)g_malloc (nread);
  1670.     }
  1671.   else if (pnmtype == 6)  /* Portable Pixmap */
  1672.     {
  1673.       imagetype = GIMP_RGB;
  1674.       nread = width * 3;
  1675.       bpp = 3;
  1676.       byteline = (guchar *)g_malloc (nread);
  1677.     }
  1678.   else return (-1);
  1679.  
  1680.   image_ID = create_new_image (filename, pagenum,
  1681.                    image_width, image_height, imagetype,
  1682.                    &layer_ID, &drawable, &pixel_rgn);
  1683.  
  1684.   tile_height = gimp_tile_height ();
  1685.   data = g_malloc (tile_height * image_width * bpp);
  1686.  
  1687.   dest = data;
  1688.   total_scan_lines = scan_lines = 0;
  1689.  
  1690.   if (pnmtype == 4)   /* Read bitimage ? Must be mapped to indexed */
  1691.     {static unsigned char BWColorMap[2*3] = { 255, 255, 255, 0, 0, 0 };
  1692.  
  1693.     gimp_image_set_cmap (image_ID, BWColorMap, 2);
  1694.  
  1695.     for (i = 0; i < height; i++)
  1696.       {
  1697.     e = (fread (bitline, 1, nread, ifp) != nread);
  1698.     if (total_scan_lines >= image_height) continue;
  1699.     err |= e;
  1700.     if (err) break;
  1701.  
  1702.     j = width;      /* Map 1 byte of bitimage to 8 bytes of indexed image */
  1703.     temp = bitline;
  1704.     byteptr = byteline;
  1705.     while (j >= 8)
  1706.       {
  1707.         memcpy (byteptr, bit2byte + *(temp++)*8, 8);
  1708.         byteptr += 8;
  1709.         j -= 8;
  1710.       }
  1711.     if (j > 0)
  1712.       memcpy (byteptr, bit2byte + *temp*8, j);
  1713.  
  1714.     memcpy (dest, byteline+skip_left, image_width);
  1715.     dest += image_width;
  1716.     scan_lines++;
  1717.     total_scan_lines++;
  1718.  
  1719.     if ((l_run_mode != GIMP_RUN_NONINTERACTIVE) && ((i % 20) == 0))
  1720.       gimp_progress_update ((double)(i+1) / (double)image_height);
  1721.  
  1722.     if ((scan_lines == tile_height) || ((i+1) == image_height))
  1723.       {
  1724.         gimp_pixel_rgn_set_rect (&pixel_rgn, data, 0, i-scan_lines+1,
  1725.                      image_width, scan_lines);
  1726.         scan_lines = 0;
  1727.         dest = data;
  1728.       }
  1729.     if (err) break;
  1730.       }
  1731.     }
  1732.   else   /* Read gray/rgb-image */
  1733.     {
  1734.       for (i = 0; i < height; i++)
  1735.     {
  1736.       e = (fread (byteline, bpp, width, ifp) != width);
  1737.       if (total_scan_lines >= image_height) continue;
  1738.       err |= e;
  1739.       if (err) break;
  1740.  
  1741.       memcpy (dest, byteline+skip_left*bpp, image_width*bpp);
  1742.       dest += image_width*bpp;
  1743.       scan_lines++;
  1744.       total_scan_lines++;
  1745.  
  1746.       if ((l_run_mode != GIMP_RUN_NONINTERACTIVE) && ((i % 20) == 0))
  1747.         gimp_progress_update ((double)(i+1) / (double)image_height);
  1748.  
  1749.       if ((scan_lines == tile_height) || ((i+1) == image_height))
  1750.         {
  1751.           gimp_pixel_rgn_set_rect (&pixel_rgn, data, 0, i-scan_lines+1,
  1752.                        image_width, scan_lines);
  1753.           scan_lines = 0;
  1754.           dest = data;
  1755.         }
  1756.       if (err) break;
  1757.     }
  1758.     }
  1759.  
  1760.   g_free (data);
  1761.   if (byteline) g_free (byteline);
  1762.   if (bitline) g_free (bitline);
  1763.  
  1764.   if (err)
  1765.     g_message ("EOF encountered on reading");
  1766.  
  1767.   gimp_drawable_flush (drawable);
  1768.  
  1769.   return (err ? -1 : image_ID);
  1770. }
  1771.  
  1772.  
  1773. /* Write out the PostScript file header */
  1774. static void save_ps_header (FILE  *ofp,
  1775.                             gchar *filename)
  1776. {
  1777.   time_t cutime = time (NULL);
  1778.  
  1779.   fprintf (ofp, "%%!PS-Adobe-3.0%s\n", psvals.eps ? " EPSF-3.0" : "");
  1780.   fprintf (ofp, "%%%%Creator: GIMP PostScript file plugin V %4.2f \
  1781. by Peter Kirchgessner\n", VERSIO);
  1782.   fprintf (ofp, "%%%%Title: %s\n", filename);
  1783.   fprintf (ofp, "%%%%CreationDate: %s", ctime (&cutime));
  1784.   fprintf (ofp, "%%%%DocumentData: Clean7Bit\n");
  1785.   if (psvals.eps || (psvals.level > 1)) fprintf (ofp,"%%%%LanguageLevel: 2\n");
  1786.   fprintf (ofp, "%%%%Pages: 1\n");
  1787. }
  1788.  
  1789.  
  1790. /* Write out transformation for image */
  1791. static void
  1792. save_ps_setup (FILE   *ofp,
  1793.                gint32  drawable_ID,
  1794.                gint    width,
  1795.                gint    height,
  1796.                gint    bpp)
  1797. {
  1798.   double x_offset, y_offset, x_size, y_size;
  1799.   double x_scale, y_scale;
  1800.   double width_inch, height_inch;
  1801.   double f1, f2, dx, dy;
  1802.   int xtrans, ytrans;
  1803.  
  1804.   /* initialize */
  1805.  
  1806.   dx = 0.0;
  1807.   dy = 0.0;
  1808.  
  1809.   x_offset = psvals.x_offset;
  1810.   y_offset = psvals.y_offset;
  1811.   width_inch = fabs (psvals.width);
  1812.   height_inch = fabs (psvals.height);
  1813.  
  1814.   if (psvals.unit_mm)
  1815.     {
  1816.       x_offset /= 25.4; y_offset /= 25.4;
  1817.       width_inch /= 25.4; height_inch /= 25.4;
  1818.     }
  1819.   if (psvals.keep_ratio)   /* Proportions to keep ? */
  1820.     {                        /* Fit the image into the allowed size */
  1821.       f1 = width_inch / width;
  1822.       f2 = height_inch / height;
  1823.       if (f1 < f2)
  1824.     height_inch = width_inch * (double)(height)/(double)(width);
  1825.       else
  1826.     width_inch = fabs (height_inch) * (double)(width)/(double)(height);
  1827.     }
  1828.   if ((psvals.rotate == 0) || (psvals.rotate == 180))
  1829.     {
  1830.       x_size = width_inch; y_size = height_inch;
  1831.     }
  1832.   else
  1833.   {
  1834.     y_size = width_inch; x_size = height_inch;
  1835.   }
  1836.  
  1837.   fprintf (ofp, "%%%%BoundingBox: %d %d %d %d\n",(int)(x_offset*72.0),
  1838.            (int)(y_offset*72.0), (int)((x_offset+x_size)*72.0)+1,
  1839.            (int)((y_offset+y_size)*72.0)+1);
  1840.   fprintf (ofp, "%%%%EndComments\n");
  1841.  
  1842.   if (psvals.preview && (psvals.preview_size > 0))
  1843.     {
  1844.       save_ps_preview (ofp, drawable_ID);
  1845.     }
  1846.  
  1847.   fprintf (ofp, "%%%%BeginProlog\n");
  1848.   fprintf (ofp, "%% Use own dictionary to avoid conflicts\n");
  1849.   fprintf (ofp, "10 dict begin\n");
  1850.   fprintf (ofp, "%%%%EndProlog\n");
  1851.   fprintf (ofp, "%%%%Page: 1 1\n");
  1852.   fprintf (ofp, "%% Translate for offset\n");
  1853.   fprintf (ofp, "%f %f translate\n", x_offset*72.0, y_offset*72.0);
  1854.  
  1855.   /* Calculate translation to startpoint of first scanline */
  1856.   switch (psvals.rotate)
  1857.     {
  1858.     case   0: dx = 0.0; dy = y_size*72.0;
  1859.       break;
  1860.     case  90: dx = dy = 0.0;
  1861.       x_scale = 72.0 * width_inch;
  1862.       y_scale = -72.0 * height_inch;
  1863.       break;
  1864.     case 180: dx = x_size*72.0; dy = 0.0;
  1865.       break;
  1866.     case 270: dx = x_size*72.0; dy = y_size*72.0;
  1867.       break;
  1868.     }
  1869.   if ((dx != 0.0) || (dy != 0.0))
  1870.     fprintf (ofp, "%% Translate to begin of first scanline\n%f %f translate\n",
  1871.              dx, dy);
  1872.   if (psvals.rotate)
  1873.     fprintf (ofp, "%d rotate\n", (int)psvals.rotate);
  1874.   fprintf (ofp, "%f %f scale\n", 72.0*width_inch, -72.0*height_inch);
  1875.  
  1876.   /* Write the PostScript procedures to read the image */
  1877.   if (psvals.level <= 1)
  1878.   {
  1879.     fprintf (ofp, "%% Variable to keep one line of raster data\n");
  1880.     if (bpp == 1)
  1881.       fprintf (ofp, "/scanline %d string def\n", (width+7)/8);
  1882.     else
  1883.       fprintf (ofp, "/scanline %d %d mul string def\n", width, bpp/8);
  1884.   }
  1885.   fprintf (ofp, "%% Image geometry\n%d %d %d\n", width, height,
  1886.            (bpp == 1) ? 1 : 8);
  1887.   fprintf (ofp, "%% Transformation matrix\n");
  1888.   xtrans = ytrans = 0;
  1889.   if (psvals.width < 0.0) { width = -width; xtrans = -width; }
  1890.   if (psvals.height < 0.0) { height = -height; ytrans = -height; }
  1891.   fprintf (ofp, "[ %d 0 0 %d %d %d ]\n", width, height, xtrans, ytrans);
  1892. }
  1893.  
  1894.  
  1895. static void
  1896. save_ps_trailer (FILE *ofp)
  1897. {
  1898.   fprintf (ofp, "%%%%Trailer\n");
  1899.   fprintf (ofp, "end\n%%%%EOF\n");
  1900. }
  1901.  
  1902. /* Do a Floyd-Steinberg dithering on a greyscale scanline. */
  1903. /* linecount must keep the counter for the actual scanline (0, 1, 2, ...). */
  1904. /* If linecount is less than zero, all used memory is freed. */
  1905.  
  1906. static void
  1907. dither_grey (guchar *grey,
  1908.              guchar *bw,
  1909.              gint    npix,
  1910.              gint    linecount)
  1911. {
  1912.   register guchar *greyptr, *bwptr, mask;
  1913.   register int *fse;
  1914.   int x, greyval, fse_inline;
  1915.   static int *fs_error = NULL;
  1916.   static int do_init_arrays = 1;
  1917.   static int limit_array[1278];
  1918.   static int east_error[256],seast_error[256],south_error[256],swest_error[256];
  1919.   int *limit = &(limit_array[512]);
  1920.  
  1921.   if (linecount <= 0)
  1922.     {
  1923.       if (fs_error) g_free (fs_error-1);
  1924.       if (linecount < 0) return;
  1925.       fs_error = (int *)g_malloc ((npix+2)*sizeof (int));
  1926.       memset ((char *)fs_error, 0, (npix+2)*sizeof (int));
  1927.       fs_error++;
  1928.  
  1929.       /* Initialize some arrays that speed up dithering */
  1930.       if (do_init_arrays)
  1931.     {
  1932.       do_init_arrays = 0;
  1933.       for (x = -511; x <= 766; x++)
  1934.         limit[x] = (x < 0) ? 0 : ((x > 255) ? 255 : x);
  1935.       for (greyval = 0; greyval < 256; greyval++)
  1936.         {
  1937.           east_error[greyval] = (greyval < 128) ? ((greyval * 79) >> 8)
  1938.         : (((greyval-255)*79) >> 8);
  1939.           seast_error[greyval] = (greyval < 128) ? ((greyval * 34) >> 8)
  1940.         : (((greyval-255)*34) >> 8);
  1941.           south_error[greyval] = (greyval < 128) ? ((greyval * 56) >> 8)
  1942.         : (((greyval-255)*56) >> 8);
  1943.           swest_error[greyval] = (greyval < 128) ? ((greyval * 12) >> 8)
  1944.         : (((greyval-255)*12) >> 8);
  1945.         }
  1946.     }
  1947.     }
  1948.   if (fs_error == NULL) return;
  1949.  
  1950.   memset (bw, 0, (npix+7)/8); /* Initialize with white */
  1951.  
  1952.   greyptr = grey;
  1953.   bwptr = bw;
  1954.   mask = 0x80;
  1955.   fse_inline = fs_error[0];
  1956.   for (x = 0, fse = fs_error; x < npix; x++, fse++)
  1957.     {
  1958.       greyval = limit[*(greyptr++) + fse_inline];  /* 0 <= greyval <= 255 */
  1959.       if (greyval < 128) *bwptr |= mask;  /* Set a black pixel */
  1960.  
  1961.       /* Error distribution */
  1962.       fse_inline = east_error[greyval] + fse[1];
  1963.       fse[1] = seast_error[greyval];
  1964.       fse[0] += south_error[greyval];
  1965.       fse[-1] += swest_error[greyval];
  1966.  
  1967.       mask >>= 1;   /* Get mask for next b/w-pixel */
  1968.       if (!mask)
  1969.     {
  1970.       mask = 0x80;
  1971.       bwptr++;
  1972.     }
  1973.     }
  1974. }
  1975.  
  1976. /* Write a device independant screen preview */
  1977. static void
  1978. save_ps_preview (FILE   *ofp,
  1979.                  gint32  drawable_ID)
  1980. {
  1981.   register guchar *bwptr, *greyptr;
  1982.   GimpImageType drawable_type;
  1983.   GimpDrawable *drawable;
  1984.   GimpPixelRgn src_rgn;
  1985.   int width, height, x, y, nbsl, out_count;
  1986.   int nchar_pl = 72, src_y;
  1987.   double f1, f2;
  1988.   guchar *grey, *bw, *src_row, *src_ptr;
  1989.   guchar *cmap;
  1990.   gint ncols, cind;
  1991.  
  1992.   if (psvals.preview_size <= 0) return;
  1993.  
  1994.   drawable = gimp_drawable_get (drawable_ID);
  1995.   drawable_type = gimp_drawable_type (drawable_ID);
  1996.  
  1997.   /* Calculate size of preview */
  1998.   if (   (drawable->width <= psvals.preview_size)
  1999.      && (drawable->height <= psvals.preview_size))
  2000.     {
  2001.       width = drawable->width;
  2002.       height = drawable->height;
  2003.     }
  2004.   else
  2005.     {
  2006.       f1 = (double)psvals.preview_size / (double)drawable->width;
  2007.       f2 = (double)psvals.preview_size / (double)drawable->height;
  2008.       if (f1 < f2)
  2009.     {
  2010.       width = psvals.preview_size;
  2011.       height = drawable->height * f1;
  2012.       if (height <= 0) height = 1;
  2013.     }
  2014.       else
  2015.     {
  2016.       height = psvals.preview_size;
  2017.       width = drawable->width * f1;
  2018.       if (width <= 0) width = 1;
  2019.     }
  2020.     }
  2021.  
  2022.   nbsl = (width+7)/8;  /* Number of bytes per scanline in bitmap */
  2023.  
  2024.   grey = (guchar *)g_malloc (width);
  2025.   bw = (guchar *)g_malloc (nbsl);
  2026.   src_row = (guchar *)g_malloc (drawable->width * drawable->bpp);
  2027.  
  2028.   fprintf (ofp, "%%%%BeginPreview: %d %d 1 %d\n", width, height,
  2029.        ((nbsl*2+nchar_pl-1)/nchar_pl)*height);
  2030.  
  2031.   gimp_pixel_rgn_init (&src_rgn, drawable, 0, 0, drawable->width,
  2032.                drawable->height, FALSE, FALSE);
  2033.  
  2034.   cmap = NULL;     /* Check if we need a colour table */
  2035.   if (gimp_drawable_type (drawable_ID) == GIMP_INDEXED_IMAGE)
  2036.     cmap = (guchar *)
  2037.       gimp_image_get_cmap (gimp_drawable_image_id (drawable_ID), &ncols);
  2038.  
  2039.   for (y = 0; y < height; y++)
  2040.     {
  2041.       /* Get a scanline from the input image and scale it to the desired width */
  2042.       src_y = (y * drawable->height) / height;
  2043.       gimp_pixel_rgn_get_row (&src_rgn, src_row, 0, src_y, drawable->width);
  2044.  
  2045.       greyptr = grey;
  2046.       if (drawable->bpp == 3)   /* RGB-image */
  2047.     {
  2048.       for (x = 0; x < width; x++)
  2049.         {                       /* Convert to grey */
  2050.           src_ptr = src_row + ((x * drawable->width) / width) * 3;
  2051.           *(greyptr++) = (3*src_ptr[0] + 6*src_ptr[1] + src_ptr[2]) / 10;
  2052.         }
  2053.     }
  2054.       else if (cmap)    /* Indexed image */
  2055.     {
  2056.       for (x = 0; x < width; x++)
  2057.         {
  2058.           src_ptr = src_row + ((x * drawable->width) / width);
  2059.           cind = *src_ptr;   /* Get colour index and convert to grey */
  2060.           src_ptr = (cind >= ncols) ? cmap : (cmap + 3*cind);
  2061.           *(greyptr++) = (3*src_ptr[0] + 6*src_ptr[1] + src_ptr[2]) / 10;
  2062.         }
  2063.     }
  2064.       else             /* Grey image */
  2065.     {
  2066.       for (x = 0; x < width; x++)
  2067.         *(greyptr++) = *(src_row + ((x * drawable->width) / width));
  2068.     }
  2069.  
  2070.       /* Now we have a greyscale line for the desired width. */
  2071.       /* Dither it to b/w */
  2072.       dither_grey (grey, bw, width, y);
  2073.  
  2074.       /* Write out the b/w line */
  2075.       out_count = 0;
  2076.       bwptr = bw;
  2077.       for (x = 0; x < nbsl; x++)
  2078.     {
  2079.       if (out_count == 0) fprintf (ofp, "%% ");
  2080.       fprintf (ofp, "%02x", *(bwptr++));
  2081.       out_count += 2;
  2082.       if (out_count >= nchar_pl)
  2083.         {
  2084.           fprintf (ofp, "\n");
  2085.           out_count = 0;
  2086.         }
  2087.     }
  2088.       if (out_count != 0)
  2089.     fprintf (ofp, "\n");
  2090.  
  2091.       if ((l_run_mode != GIMP_RUN_NONINTERACTIVE) && ((y % 20) == 0))
  2092.     gimp_progress_update ((double)(y) / (double)height);
  2093.     }
  2094.  
  2095.   fprintf (ofp, "%%%%EndPreview\n");
  2096.  
  2097.   dither_grey (grey, bw, width, -1);
  2098.   g_free (src_row);
  2099.   g_free (bw);
  2100.   g_free (grey);
  2101.  
  2102.   gimp_drawable_detach (drawable);
  2103. }
  2104.  
  2105. static gint
  2106. save_gray  (FILE   *ofp,
  2107.             gint32  image_ID,
  2108.             gint32  drawable_ID)
  2109. {
  2110.   int height, width, i, j;
  2111.   int tile_height;
  2112.   unsigned char *data, *src;
  2113.   unsigned char *packb = NULL;
  2114.   GimpPixelRgn pixel_rgn;
  2115.   GimpDrawable *drawable;
  2116.   GimpImageType drawable_type;
  2117.   static char *hex = "0123456789abcdef";
  2118.   int level2 = (psvals.level > 1);
  2119.  
  2120.   drawable = gimp_drawable_get (drawable_ID);
  2121.   drawable_type = gimp_drawable_type (drawable_ID);
  2122.   width = drawable->width;
  2123.   height = drawable->height;
  2124.   tile_height = gimp_tile_height ();
  2125.   gimp_pixel_rgn_init (&pixel_rgn, drawable, 0, 0, width, height, FALSE, FALSE);
  2126.  
  2127.   /* allocate a buffer for retrieving information from the pixel region  */
  2128.   src = data = (guchar *)g_malloc (tile_height * width * drawable->bpp);
  2129.  
  2130.   /* Set up transformation in PostScript */
  2131.   save_ps_setup (ofp, drawable_ID, width, height, 1*8);
  2132.  
  2133.   /* Write read image procedure */
  2134.   if (!level2)
  2135.   {
  2136.     fprintf (ofp, "{ currentfile scanline readhexstring pop }\n");
  2137.   }
  2138.   else
  2139.   {
  2140.     fprintf (ofp,"currentfile /ASCII85Decode filter /RunLengthDecode filter\n");
  2141.     ascii85_init ();
  2142.     /* Allocate buffer for packbits data. Worst case: Less than 1% increase */
  2143.     packb = (guchar *)g_malloc ((width * 105)/100+2);
  2144.   }
  2145.   ps_begin_data (ofp);
  2146.   fprintf (ofp, "image\n");
  2147.  
  2148. #define GET_GRAY_TILE(begin) \
  2149.   {int scan_lines; \
  2150.     scan_lines = (i+tile_height-1 < height) ? tile_height : (height-i); \
  2151.     gimp_pixel_rgn_get_rect (&pixel_rgn, begin, 0, i, width, scan_lines); \
  2152.     src = begin; }
  2153.  
  2154.   for (i = 0; i < height; i++)
  2155.     {
  2156.       if ((i % tile_height) == 0) GET_GRAY_TILE (data); /* Get more data */
  2157.       if (!level2)
  2158.     {
  2159.       for (j = 0; j < width; j++)
  2160.         {
  2161.           putc (hex[(*src) >> 4], ofp);
  2162.           putc (hex[(*(src++)) & 0x0f], ofp);
  2163.           if (((j+1) % 39) == 0) putc ('\n', ofp);
  2164.         }
  2165.       putc ('\n', ofp);
  2166.     }
  2167.       else
  2168.     {int nout;
  2169.  
  2170.           compress_packbits (width, src, &nout, packb);
  2171.           ascii85_nout (nout, packb, ofp);
  2172.           src += width;
  2173.     }
  2174.       if ((l_run_mode != GIMP_RUN_NONINTERACTIVE) && ((i % 20) == 0))
  2175.     gimp_progress_update ((double) i / (double) height);
  2176.     }
  2177.   if (level2)
  2178.   {
  2179.     ascii85_out (128, ofp); /* Write EOD of RunLengthDecode filter */
  2180.     ascii85_done (ofp);
  2181.   }
  2182.   ps_end_data (ofp);
  2183.   fprintf (ofp, "showpage\n");
  2184.   g_free (data);
  2185.   if (packb) g_free (packb);
  2186.  
  2187.   gimp_drawable_detach (drawable);
  2188.  
  2189.   if (ferror (ofp))
  2190.     {
  2191.       g_message (_("write error occured"));
  2192.       return (FALSE);
  2193.     }
  2194.   return (TRUE);
  2195. #undef GET_GRAY_TILE
  2196. }
  2197.  
  2198.  
  2199. static gint
  2200. save_bw (FILE   *ofp,
  2201.          gint32  image_ID,
  2202.          gint32  drawable_ID)
  2203. {
  2204.   int height, width, i, j;
  2205.   int ncols, nbsl, nwrite;
  2206.   int tile_height;
  2207.   guchar *cmap, *ct;
  2208.   guchar *data, *src;
  2209.   guchar *packb = NULL;
  2210.   guchar *scanline, *dst, mask;
  2211.   guchar *hex_scanline;
  2212.   GimpPixelRgn pixel_rgn;
  2213.   GimpDrawable *drawable;
  2214.   GimpImageType drawable_type;
  2215.   static char *hex = "0123456789abcdef";
  2216.   int level2 = (psvals.level > 1);
  2217.  
  2218.   cmap = gimp_image_get_cmap (image_ID, &ncols);
  2219.  
  2220.   drawable = gimp_drawable_get (drawable_ID);
  2221.   drawable_type = gimp_drawable_type (drawable_ID);
  2222.   width = drawable->width;
  2223.   height = drawable->height;
  2224.   tile_height = gimp_tile_height ();
  2225.   gimp_pixel_rgn_init (&pixel_rgn, drawable, 0, 0, width, height, FALSE, FALSE);
  2226.  
  2227.   /* allocate a buffer for retrieving information from the pixel region  */
  2228.   src = data = (guchar *)g_malloc (tile_height * width * drawable->bpp);
  2229.   nbsl = (width+7)/8;
  2230.   scanline = (char *)g_malloc (nbsl + 1);
  2231.   hex_scanline = (char *)g_malloc ((nbsl + 1)*2);
  2232.  
  2233.   /* Set up transformation in PostScript */
  2234.   save_ps_setup (ofp, drawable_ID, width, height, 1);
  2235.  
  2236.   /* Write read image procedure */
  2237.   if (!level2)
  2238.   {
  2239.     fprintf (ofp, "{ currentfile scanline readhexstring pop }\n");
  2240.   }
  2241.   else
  2242.   {
  2243.     fprintf (ofp,"currentfile /ASCII85Decode filter /RunLengthDecode filter\n");
  2244.     ascii85_init ();
  2245.     /* Allocate buffer for packbits data. Worst case: Less than 1% increase */
  2246.     packb = (guchar *)g_malloc (((nbsl+1) * 105)/100+2);
  2247.   }
  2248.   ps_begin_data (ofp);
  2249.   fprintf (ofp, "image\n");
  2250.  
  2251. #define GET_BW_TILE(begin) \
  2252.   {int scan_lines; \
  2253.     scan_lines = (i+tile_height-1 < height) ? tile_height : (height-i); \
  2254.     gimp_pixel_rgn_get_rect (&pixel_rgn, begin, 0, i, width, scan_lines); \
  2255.     src = begin; }
  2256.  
  2257.   for (i = 0; i < height; i++)
  2258.     {
  2259.       if ((i % tile_height) == 0) GET_BW_TILE (data); /* Get more data */
  2260.       dst = scanline;
  2261.       memset (dst, 0, nbsl);
  2262.       mask = 0x80;
  2263.       /* Build a bitmap for a scanline */
  2264.       for (j = 0; j < width; j++)
  2265.     {
  2266.       ct = cmap + *(src++)*3;
  2267.       if (ct[0] || ct[1] || ct[2])
  2268.         *dst |= mask;
  2269.       if (mask == 0x01) { mask = 0x80; dst++; } else mask >>= 1;
  2270.     }
  2271.       if (!level2)
  2272.     {
  2273.       /* Convert to hexstring */
  2274.       for (j = 0; j < nbsl; j++)
  2275.         {
  2276.           hex_scanline[j*2] = (unsigned char)hex[scanline[j] >> 4];
  2277.           hex_scanline[j*2+1] = (unsigned char)hex[scanline[j] & 0x0f];
  2278.         }
  2279.       /* Write out hexstring */
  2280.       j = nbsl * 2;
  2281.       dst = hex_scanline;
  2282.       while (j > 0)
  2283.         {
  2284.           nwrite = (j > 78) ? 78 : j;
  2285.           fwrite (dst, nwrite, 1, ofp);
  2286.           putc ('\n', ofp);
  2287.           j -= nwrite;
  2288.           dst += nwrite;
  2289.         }
  2290.     }
  2291.       else
  2292.     {int nout;
  2293.  
  2294.           compress_packbits (nbsl, scanline, &nout, packb);
  2295.           ascii85_nout (nout, packb, ofp);
  2296.     }
  2297.       if ((l_run_mode != GIMP_RUN_NONINTERACTIVE) && ((i % 20) == 0))
  2298.     gimp_progress_update ((double) i / (double) height);
  2299.     }
  2300.   if (level2)
  2301.   {
  2302.     ascii85_out (128, ofp); /* Write EOD of RunLengthDecode filter */
  2303.     ascii85_done (ofp);
  2304.   }
  2305.   ps_end_data (ofp);
  2306.   fprintf (ofp, "showpage\n");
  2307.  
  2308.   g_free (hex_scanline);
  2309.   g_free (scanline);
  2310.   g_free (data);
  2311.   if (packb != NULL) g_free (packb);
  2312.  
  2313.   gimp_drawable_detach (drawable);
  2314.  
  2315.   if (ferror (ofp))
  2316.     {
  2317.       g_message (_("write error occured"));
  2318.       return (FALSE);
  2319.     }
  2320.   return (TRUE);
  2321. #undef GET_BW_TILE
  2322. }
  2323.  
  2324.  
  2325. static gint
  2326. save_index (FILE   *ofp,
  2327.             gint32  image_ID,
  2328.             gint32  drawable_ID)
  2329. {
  2330.   int height, width, i, j;
  2331.   int ncols, bw;
  2332.   int tile_height;
  2333.   guchar *cmap, *cmap_start;
  2334.   guchar *data, *src;
  2335.   guchar *packb = NULL, *plane = NULL;
  2336.   char coltab[256*6], *ct;
  2337.   GimpPixelRgn pixel_rgn;
  2338.   GimpDrawable *drawable;
  2339.   GimpImageType drawable_type;
  2340.   static char *hex = "0123456789abcdef";
  2341.   static char *background = "000000";
  2342.   int level2 = (psvals.level > 1);
  2343.  
  2344.   cmap = cmap_start = gimp_image_get_cmap (image_ID, &ncols);
  2345.  
  2346.   ct = coltab;
  2347.   bw = 1;
  2348.   for (j = 0; j < 256; j++)
  2349.     {
  2350.       if (j >= ncols)
  2351.     {
  2352.       memcpy (ct, background, 6);
  2353.       ct += 6;
  2354.     }
  2355.       else
  2356.     {
  2357.       bw &=    ((cmap[0] == 0) && (cmap[1] == 0) && (cmap[2] == 0))
  2358.             || ((cmap[0] == 255) && (cmap[1] == 255) && (cmap[2] == 255));
  2359.       *(ct++) = (guchar)hex[(*cmap) >> 4];
  2360.       *(ct++) = (guchar)hex[(*(cmap++)) & 0x0f];
  2361.       *(ct++) = (guchar)hex[(*cmap) >> 4];
  2362.       *(ct++) = (guchar)hex[(*(cmap++)) & 0x0f];
  2363.       *(ct++) = (guchar)hex[(*cmap) >> 4];
  2364.       *(ct++) = (guchar)hex[(*(cmap++)) & 0x0f];
  2365.     }
  2366.     }
  2367.   if (bw) return (save_bw (ofp, image_ID, drawable_ID));
  2368.  
  2369.   drawable = gimp_drawable_get (drawable_ID);
  2370.   drawable_type = gimp_drawable_type (drawable_ID);
  2371.   width = drawable->width;
  2372.   height = drawable->height;
  2373.   tile_height = gimp_tile_height ();
  2374.   gimp_pixel_rgn_init (&pixel_rgn, drawable, 0, 0, width, height, FALSE, FALSE);
  2375.  
  2376.   /* allocate a buffer for retrieving information from the pixel region  */
  2377.   src = data = (guchar *)g_malloc (tile_height * width * drawable->bpp);
  2378.  
  2379.   /* Set up transformation in PostScript */
  2380.   save_ps_setup (ofp, drawable_ID, width, height, 3*8);
  2381.  
  2382.   /* Write read image procedure */
  2383.   if (!level2)
  2384.   {
  2385.     fprintf (ofp, "{ currentfile scanline readhexstring pop } false 3\n");
  2386.   }
  2387.   else
  2388.   {
  2389.     fprintf (ofp, "%% Strings to hold RGB-samples per scanline\n");
  2390.     fprintf (ofp, "/rstr %d string def\n", width);
  2391.     fprintf (ofp, "/gstr %d string def\n", width);
  2392.     fprintf (ofp, "/bstr %d string def\n", width);
  2393.     fprintf (ofp,
  2394.             "{currentfile /ASCII85Decode filter /RunLengthDecode filter\
  2395.  rstr readstring pop}\n");
  2396.     fprintf (ofp,
  2397.             "{currentfile /ASCII85Decode filter /RunLengthDecode filter\
  2398.  gstr readstring pop}\n");
  2399.     fprintf (ofp,
  2400.             "{currentfile /ASCII85Decode filter /RunLengthDecode filter\
  2401.  bstr readstring pop}\n");
  2402.     fprintf (ofp, "true 3\n");
  2403.  
  2404.     /* Allocate buffer for packbits data. Worst case: Less than 1% increase */
  2405.     packb = (guchar *)g_malloc ((width * 105)/100+2);
  2406.     plane = (guchar *)g_malloc (width);
  2407.   }
  2408.   ps_begin_data (ofp);
  2409.   fprintf (ofp, "colorimage\n");
  2410.  
  2411. #define GET_INDEX_TILE(begin) \
  2412.   {int scan_lines; \
  2413.     scan_lines = (i+tile_height-1 < height) ? tile_height : (height-i); \
  2414.     gimp_pixel_rgn_get_rect (&pixel_rgn, begin, 0, i, width, scan_lines); \
  2415.     src = begin; }
  2416.  
  2417.   for (i = 0; i < height; i++)
  2418.     {
  2419.       if ((i % tile_height) == 0) GET_INDEX_TILE (data); /* Get more data */
  2420.       if (!level2)
  2421.     {
  2422.       for (j = 0; j < width; j++)
  2423.         {
  2424.           fwrite (coltab+(*(src++))*6, 6, 1, ofp);
  2425.           if (((j+1) % 13) == 0) putc ('\n', ofp);
  2426.         }
  2427.       putc ('\n', ofp);
  2428.     }
  2429.       else
  2430.         {guchar *plane_ptr, *src_ptr;
  2431.          int rgb, nout;
  2432.  
  2433.           for (rgb = 0; rgb < 3; rgb++)
  2434.           {
  2435.             src_ptr = src;
  2436.             plane_ptr = plane;
  2437.             for (j = 0; j < width; j++)
  2438.               *(plane_ptr++) = cmap_start[3 * *(src_ptr++) + rgb];
  2439.             compress_packbits (width, plane, &nout, packb);
  2440.             ascii85_init ();
  2441.             ascii85_nout (nout, packb, ofp);
  2442.             ascii85_out (128, ofp); /* Write EOD of RunLengthDecode filter */
  2443.             ascii85_done (ofp);
  2444.           }
  2445.           src += width;
  2446.         }
  2447.       if ((l_run_mode != GIMP_RUN_NONINTERACTIVE) && ((i % 20) == 0))
  2448.     gimp_progress_update ((double) i / (double) height);
  2449.     }
  2450.   ps_end_data (ofp);
  2451.   fprintf (ofp, "showpage\n");
  2452.  
  2453.   g_free (data);
  2454.   if (packb != NULL) g_free (packb);
  2455.   if (plane != NULL) g_free (plane);
  2456.  
  2457.   gimp_drawable_detach (drawable);
  2458.  
  2459.   if (ferror (ofp))
  2460.     {
  2461.       g_message (_("write error occured"));
  2462.       return (FALSE);
  2463.     }
  2464.   return (TRUE);
  2465. #undef GET_INDEX_TILE
  2466. }
  2467.  
  2468.  
  2469. static gint
  2470. save_rgb (FILE   *ofp,
  2471.           gint32  image_ID,
  2472.           gint32  drawable_ID)
  2473. {
  2474.   int height, width, tile_height;
  2475.   int i, j;
  2476.   guchar *data, *src;
  2477.   guchar *packb = NULL, *plane = NULL;
  2478.   GimpPixelRgn pixel_rgn;
  2479.   GimpDrawable *drawable;
  2480.   GimpImageType drawable_type;
  2481.   static char *hex = "0123456789abcdef";
  2482.   int level2 = (psvals.level > 1);
  2483.  
  2484.   drawable = gimp_drawable_get (drawable_ID);
  2485.   drawable_type = gimp_drawable_type (drawable_ID);
  2486.   width = drawable->width;
  2487.   height = drawable->height;
  2488.   tile_height = gimp_tile_height ();
  2489.   gimp_pixel_rgn_init (&pixel_rgn, drawable, 0, 0, width, height, FALSE, FALSE);
  2490.  
  2491.   /* allocate a buffer for retrieving information from the pixel region  */
  2492.   src = data = (guchar *)g_malloc (tile_height * width * drawable->bpp);
  2493.  
  2494.   /* Set up transformation in PostScript */
  2495.   save_ps_setup (ofp, drawable_ID, width, height, 3*8);
  2496.  
  2497.   /* Write read image procedure */
  2498.   if (!level2)
  2499.   {
  2500.     fprintf (ofp, "{ currentfile scanline readhexstring pop } false 3\n");
  2501.   }
  2502.   else
  2503.   {
  2504.     fprintf (ofp, "%% Strings to hold RGB-samples per scanline\n");
  2505.     fprintf (ofp, "/rstr %d string def\n", width);
  2506.     fprintf (ofp, "/gstr %d string def\n", width);
  2507.     fprintf (ofp, "/bstr %d string def\n", width);
  2508.     fprintf (ofp,
  2509.             "{currentfile /ASCII85Decode filter /RunLengthDecode filter\
  2510.  rstr readstring pop}\n");
  2511.     fprintf (ofp,
  2512.             "{currentfile /ASCII85Decode filter /RunLengthDecode filter\
  2513.  gstr readstring pop}\n");
  2514.     fprintf (ofp,
  2515.             "{currentfile /ASCII85Decode filter /RunLengthDecode filter\
  2516.  bstr readstring pop}\n");
  2517.     fprintf (ofp, "true 3\n");
  2518.  
  2519.     /* Allocate buffer for packbits data. Worst case: Less than 1% increase */
  2520.     packb = (guchar *)g_malloc ((width * 105)/100+2);
  2521.     plane = (guchar *)g_malloc (width);
  2522.   }
  2523.   ps_begin_data (ofp);
  2524.   fprintf (ofp, "colorimage\n");
  2525.  
  2526. #define GET_RGB_TILE(begin) \
  2527.   {int scan_lines; \
  2528.     scan_lines = (i+tile_height-1 < height) ? tile_height : (height-i); \
  2529.     gimp_pixel_rgn_get_rect (&pixel_rgn, begin, 0, i, width, scan_lines); \
  2530.     src = begin; }
  2531.  
  2532.   for (i = 0; i < height; i++)
  2533.     {
  2534.       if ((i % tile_height) == 0) GET_RGB_TILE (data); /* Get more data */
  2535.       if (!level2)
  2536.     {
  2537.       for (j = 0; j < width; j++)
  2538.         {
  2539.           putc (hex[(*src) >> 4], ofp);        /* Red */
  2540.           putc (hex[(*(src++)) & 0x0f], ofp);
  2541.           putc (hex[(*src) >> 4], ofp);        /* Green */
  2542.           putc (hex[(*(src++)) & 0x0f], ofp);
  2543.           putc (hex[(*src) >> 4], ofp);        /* Blue */
  2544.           putc (hex[(*(src++)) & 0x0f], ofp);
  2545.           if (((j+1) % 13) == 0) putc ('\n', ofp);
  2546.         }
  2547.       putc ('\n', ofp);
  2548.     }
  2549.       else
  2550.     {guchar *plane_ptr, *src_ptr;
  2551.          int rgb, nout;
  2552.  
  2553.           for (rgb = 0; rgb < 3; rgb++)
  2554.           {
  2555.             src_ptr = src + rgb;
  2556.             plane_ptr = plane;
  2557.             for (j = 0; j < width; j++)
  2558.         {
  2559.               *(plane_ptr++) = *src_ptr;
  2560.               src_ptr += 3;
  2561.             }
  2562.             compress_packbits (width, plane, &nout, packb);
  2563.             ascii85_init ();
  2564.         ascii85_nout (nout, packb, ofp);
  2565.             ascii85_out (128, ofp); /* Write EOD of RunLengthDecode filter */
  2566.             ascii85_done (ofp);
  2567.           }
  2568.           src += 3*width;
  2569.     }
  2570.       if ((l_run_mode != GIMP_RUN_NONINTERACTIVE) && ((i % 20) == 0))
  2571.     gimp_progress_update ((double) i / (double) height);
  2572.     }
  2573.   ps_end_data (ofp);
  2574.   fprintf (ofp, "showpage\n");
  2575.   g_free (data);
  2576.   if (packb != NULL) g_free (packb);
  2577.   if (plane != NULL) g_free (plane);
  2578.  
  2579.   gimp_drawable_detach (drawable);
  2580.  
  2581.   if (ferror (ofp))
  2582.     {
  2583.       g_message (_("write error occured"));
  2584.       return (FALSE);
  2585.     }
  2586.   return (TRUE);
  2587. #undef GET_RGB_TILE
  2588. }
  2589.  
  2590. /*  Load interface functions  */
  2591.  
  2592. static gint
  2593. load_dialog (void)
  2594. {
  2595.   GtkWidget *dialog;
  2596.   GtkWidget *main_vbox;
  2597.   GtkWidget *hbox;
  2598.   GtkWidget *frame;
  2599.   GtkWidget *vbox;
  2600.   GtkWidget *table;
  2601.   GtkWidget *spinbutton;
  2602.   GtkObject *adj;
  2603.   GtkWidget *pages_entry;
  2604.   GtkWidget *toggle;
  2605.  
  2606.   gimp_ui_init ("ps", FALSE);
  2607.  
  2608.   dialog = gimp_dialog_new (_("Load PostScript"), "ps",
  2609.                 gimp_standard_help_func, "filters/ps.html",
  2610.                 GTK_WIN_POS_MOUSE,
  2611.                 FALSE, TRUE, FALSE,
  2612.  
  2613.                 _("OK"), load_ok_callback,
  2614.                 NULL, NULL, NULL, TRUE, FALSE,
  2615.                 _("Cancel"), gtk_widget_destroy,
  2616.                 NULL, 1, NULL, FALSE, TRUE,
  2617.  
  2618.                 NULL);
  2619.  
  2620.   gtk_signal_connect (GTK_OBJECT (dialog), "destroy",
  2621.                       GTK_SIGNAL_FUNC (gtk_main_quit),
  2622.                       NULL);
  2623.  
  2624.   main_vbox = gtk_vbox_new (FALSE, 6);
  2625.   gtk_container_set_border_width (GTK_CONTAINER (main_vbox), 6);
  2626.   gtk_box_pack_start (GTK_BOX (GTK_DIALOG (dialog)->vbox), main_vbox,
  2627.                       FALSE, FALSE, 0);
  2628.   gtk_widget_show (main_vbox);
  2629.  
  2630.   hbox = gtk_hbox_new (FALSE, 6);
  2631.   gtk_box_pack_start (GTK_BOX (main_vbox), hbox, FALSE, FALSE, 0);
  2632.   gtk_widget_show (hbox);
  2633.  
  2634.   /* Rendering */
  2635.   frame = gtk_frame_new (_("Rendering"));
  2636.   gtk_frame_set_shadow_type (GTK_FRAME (frame), GTK_SHADOW_ETCHED_IN);
  2637.   gtk_box_pack_start (GTK_BOX (hbox), frame, TRUE, TRUE, 0);
  2638.  
  2639.   vbox = gtk_vbox_new (FALSE, 4);
  2640.   gtk_container_set_border_width (GTK_CONTAINER (vbox), 4);
  2641.   gtk_container_add (GTK_CONTAINER (frame), vbox);
  2642.  
  2643.   /* Resolution/Width/Height/Pages labels */
  2644.   table = gtk_table_new (4, 2, FALSE);
  2645.   gtk_table_set_row_spacings (GTK_TABLE (table), 2);
  2646.   gtk_table_set_col_spacings (GTK_TABLE (table), 4);
  2647.   gtk_box_pack_start (GTK_BOX (vbox), table, FALSE, FALSE, 0);
  2648.   gtk_widget_show (table);
  2649.  
  2650.   spinbutton = gimp_spin_button_new (&adj, plvals.resolution,
  2651.                      5, 1440, 1, 10, 0, 1, 0);
  2652.   gimp_table_attach_aligned (GTK_TABLE (table), 0, 0,
  2653.                  _("Resolution:"), 1.0, 0.5,
  2654.                  spinbutton, 1, TRUE);
  2655.   gtk_signal_connect (GTK_OBJECT (adj), "value_changed",
  2656.               GTK_SIGNAL_FUNC (gimp_int_adjustment_update),
  2657.               &plvals.resolution);
  2658.  
  2659.   spinbutton = gimp_spin_button_new (&adj, plvals.width,
  2660.                      1, GIMP_MAX_IMAGE_SIZE, 1, 10, 0, 1, 0);
  2661.   gimp_table_attach_aligned (GTK_TABLE (table), 0, 1,
  2662.                  _("Width:"), 1.0, 0.5,
  2663.                  spinbutton, 1, TRUE);
  2664.   gtk_signal_connect (GTK_OBJECT (adj), "value_changed",
  2665.               GTK_SIGNAL_FUNC (gimp_int_adjustment_update),
  2666.               &plvals.width);
  2667.  
  2668.   spinbutton = gimp_spin_button_new (&adj, plvals.height,
  2669.                      1, GIMP_MAX_IMAGE_SIZE, 1, 10, 0, 1, 0);
  2670.   gimp_table_attach_aligned (GTK_TABLE (table), 0, 2,
  2671.                  _("Height:"), 1.0, 0.5,
  2672.                  spinbutton, 1, TRUE);
  2673.   gtk_signal_connect (GTK_OBJECT (adj), "value_changed",
  2674.               GTK_SIGNAL_FUNC (gimp_int_adjustment_update),
  2675.               &plvals.height);
  2676.  
  2677.   pages_entry = gtk_entry_new ();
  2678.   gtk_widget_set_usize (pages_entry, 80, 0);
  2679.   gtk_entry_set_text (GTK_ENTRY (pages_entry), plvals.pages);
  2680.   gimp_table_attach_aligned (GTK_TABLE (table), 0, 3,
  2681.                  _("Pages:"), 1.0, 0.5,
  2682.                  pages_entry, 1, TRUE);
  2683.   gtk_signal_connect (GTK_OBJECT (pages_entry), "changed",
  2684.               GTK_SIGNAL_FUNC (load_pages_entry_callback),
  2685.               NULL);
  2686.  
  2687.   toggle = gtk_check_button_new_with_label (_("Try Bounding Box"));
  2688.   gtk_box_pack_start (GTK_BOX (vbox), toggle, FALSE, FALSE, 0);
  2689.   gtk_signal_connect (GTK_OBJECT (toggle), "toggled",
  2690.                       GTK_SIGNAL_FUNC (gimp_toggle_button_update),
  2691.                       &plvals.use_bbox);
  2692.   gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (toggle), plvals.use_bbox);
  2693.   gtk_widget_show (toggle);
  2694.  
  2695.   gtk_widget_show (vbox);
  2696.   gtk_widget_show (frame);
  2697.  
  2698.   /* Colouring */
  2699.   frame = gimp_radio_group_new2 (TRUE, _("Coloring"),
  2700.                  gimp_radio_button_update,
  2701.                  &plvals.pnm_type, (gpointer) plvals.pnm_type,
  2702.  
  2703.                  _("B/W"),       (gpointer) 4, NULL,
  2704.                  _("Gray"),      (gpointer) 5, NULL,
  2705.                  _("Color"),     (gpointer) 6, NULL,
  2706.                  _("Automatic"), (gpointer) 7, NULL,
  2707.  
  2708.                  NULL);
  2709.   gtk_box_pack_start (GTK_BOX (hbox), frame, FALSE, FALSE, 0);
  2710.   gtk_widget_show (frame);
  2711.  
  2712.   hbox = gtk_hbox_new (TRUE, 6);
  2713.   gtk_box_pack_start (GTK_BOX (main_vbox), hbox, FALSE, FALSE, 0);
  2714.   gtk_widget_show (hbox);
  2715.  
  2716.   frame = gimp_radio_group_new2 (TRUE, _("Text Antialiasing"),
  2717.                  gimp_radio_button_update,
  2718.                  &plvals.textalpha, (gpointer) plvals.textalpha,
  2719.  
  2720.                  _("None"),   (gpointer) 1, NULL,
  2721.                  _("Weak"),   (gpointer) 2, NULL,
  2722.                  _("Strong"), (gpointer) 4, NULL,
  2723.  
  2724.                  NULL);
  2725.   gtk_box_pack_start (GTK_BOX (hbox), frame, FALSE, TRUE, 0);
  2726.   gtk_widget_show (frame);
  2727.  
  2728.   frame = gimp_radio_group_new2 (TRUE, _("Graphic Antialiasing"),
  2729.                  gimp_radio_button_update,
  2730.                  &plvals.graphicsalpha,
  2731.                  (gpointer) plvals.graphicsalpha,
  2732.  
  2733.                  _("None"),   (gpointer) 1, NULL,
  2734.                  _("Weak"),   (gpointer) 2, NULL,
  2735.                  _("Strong"), (gpointer) 4, NULL,
  2736.  
  2737.                  NULL);
  2738.   gtk_box_pack_start (GTK_BOX (hbox), frame, FALSE, TRUE, 0);
  2739.   gtk_widget_show (frame);
  2740.  
  2741.   gtk_widget_show (dialog);
  2742.  
  2743.   gtk_main ();
  2744.   gdk_flush ();
  2745.  
  2746.   return plint.run;
  2747. }
  2748.  
  2749.  
  2750. static void
  2751. load_ok_callback (GtkWidget *widget,
  2752.                   gpointer   data)
  2753. {
  2754.   plint.run = TRUE;
  2755.  
  2756.   gtk_widget_destroy (GTK_WIDGET (data));
  2757. }
  2758.  
  2759. static void
  2760. load_pages_entry_callback (GtkWidget *widget,
  2761.                gpointer   data)
  2762. {
  2763.   gint nelem = sizeof (plvals.pages);
  2764.  
  2765.   strncpy (plvals.pages, gtk_entry_get_text (GTK_ENTRY (widget)), nelem);
  2766.   plvals.pages[nelem-1] = '\0';
  2767. }
  2768.  
  2769. /*  Save interface functions  */
  2770.  
  2771. static gint
  2772. save_dialog (void)
  2773. {
  2774.   SaveDialogVals *vals;
  2775.   GtkWidget *dialog;
  2776.   GtkWidget *toggle;
  2777.   GtkWidget *frame, *uframe;
  2778.   GtkWidget *hbox, *vbox;
  2779.   GtkWidget *main_vbox[2];
  2780.   GtkWidget *table;
  2781.   GtkWidget *spinbutton;
  2782.   GtkObject *adj;
  2783.   gint       j;
  2784.  
  2785.   gimp_help_init ();
  2786.  
  2787.   vals = g_new (SaveDialogVals, 1);
  2788.   vals->level = (psvals.level > 1);
  2789.  
  2790.   dialog = gimp_dialog_new (_("Save as PostScript"), "ps",
  2791.                 gimp_standard_help_func, "filters/ps.html",
  2792.                 GTK_WIN_POS_MOUSE,
  2793.                 FALSE, TRUE, FALSE,
  2794.  
  2795.                 _("OK"), save_ok_callback,
  2796.                 NULL, NULL, NULL, TRUE, FALSE,
  2797.                 _("Cancel"), gtk_widget_destroy,
  2798.                 NULL, 1, NULL, FALSE, TRUE,
  2799.  
  2800.                 NULL);
  2801.  
  2802.   gtk_signal_connect (GTK_OBJECT (dialog), "destroy",
  2803.                       GTK_SIGNAL_FUNC (gtk_main_quit),
  2804.                       NULL);
  2805.  
  2806.   /* Main hbox */
  2807.   hbox = gtk_hbox_new (FALSE, 6);
  2808.   gtk_container_set_border_width (GTK_CONTAINER (hbox), 6);
  2809.   gtk_box_pack_start (GTK_BOX (GTK_DIALOG (dialog)->vbox), hbox,
  2810.                       FALSE, FALSE, 0);
  2811.   main_vbox[0] = main_vbox[1] = NULL;
  2812.  
  2813.   for (j = 0; j < sizeof (main_vbox) / sizeof (main_vbox[0]); j++)
  2814.     {
  2815.       main_vbox[j] = gtk_vbox_new (FALSE, 4);
  2816.       gtk_box_pack_start (GTK_BOX (hbox), main_vbox[j], TRUE, TRUE, 0);
  2817.     }
  2818.  
  2819.   /* Image Size */
  2820.   frame = gtk_frame_new (_("Image Size"));
  2821.   gtk_frame_set_shadow_type (GTK_FRAME (frame), GTK_SHADOW_ETCHED_IN);
  2822.   gtk_box_pack_start (GTK_BOX (main_vbox[0]), frame, TRUE, TRUE, 0);
  2823.  
  2824.   vbox = gtk_vbox_new (FALSE, 4);
  2825.   gtk_container_set_border_width (GTK_CONTAINER (vbox), 4);
  2826.   gtk_container_add (GTK_CONTAINER (frame), vbox);
  2827.  
  2828.   /* Width/Height/X-/Y-offset labels */
  2829.   table = gtk_table_new (4, 2, FALSE);
  2830.   gtk_table_set_row_spacings (GTK_TABLE (table), 2);
  2831.   gtk_table_set_col_spacings (GTK_TABLE (table), 4);
  2832.   gtk_box_pack_start (GTK_BOX (vbox), table, FALSE, FALSE, 0);
  2833.   gtk_widget_show (table);
  2834.  
  2835.   spinbutton = gimp_spin_button_new (&vals->adjustment[0], psvals.width,
  2836.                      1e-5, GIMP_MAX_IMAGE_SIZE, 1, 10, 0, 1, 2);
  2837.   gimp_table_attach_aligned (GTK_TABLE (table), 0, 0,
  2838.                  _("Width:"), 1.0, 0.5,
  2839.                  spinbutton, 1, FALSE);
  2840.   gtk_signal_connect (GTK_OBJECT (vals->adjustment[0]), "value_changed",
  2841.               GTK_SIGNAL_FUNC (gimp_double_adjustment_update),
  2842.               &psvals.width);
  2843.  
  2844.   spinbutton = gimp_spin_button_new (&vals->adjustment[1], psvals.height,
  2845.                      1e-5, GIMP_MAX_IMAGE_SIZE, 1, 10, 0, 1, 2);
  2846.   gimp_table_attach_aligned (GTK_TABLE (table), 0, 1,
  2847.                  _("Height:"), 1.0, 0.5,
  2848.                  spinbutton, 1, FALSE);
  2849.   gtk_signal_connect (GTK_OBJECT (vals->adjustment[1]), "value_changed",
  2850.               GTK_SIGNAL_FUNC (gimp_double_adjustment_update),
  2851.               &psvals.height);
  2852.  
  2853.   spinbutton = gimp_spin_button_new (&vals->adjustment[2], psvals.x_offset,
  2854.                      1e-5, GIMP_MAX_IMAGE_SIZE, 1, 10, 0, 1, 2);
  2855.   gimp_table_attach_aligned (GTK_TABLE (table), 0, 2,
  2856.                  _("X-Offset:"), 1.0, 0.5,
  2857.                  spinbutton, 1, FALSE);
  2858.   gtk_signal_connect (GTK_OBJECT (vals->adjustment[2]), "value_changed",
  2859.               GTK_SIGNAL_FUNC (gimp_double_adjustment_update),
  2860.               &psvals.x_offset);
  2861.  
  2862.   spinbutton = gimp_spin_button_new (&vals->adjustment[3], psvals.y_offset,
  2863.                      1e-5, GIMP_MAX_IMAGE_SIZE, 1, 10, 0, 1, 2);
  2864.   gimp_table_attach_aligned (GTK_TABLE (table), 0, 3,
  2865.                  _("Y-Offset:"), 1.0, 0.5,
  2866.                  spinbutton, 1, FALSE);
  2867.   gtk_signal_connect (GTK_OBJECT (vals->adjustment[3]), "value_changed",
  2868.               GTK_SIGNAL_FUNC (gimp_double_adjustment_update),
  2869.               &psvals.y_offset);
  2870.  
  2871.   toggle = gtk_check_button_new_with_label (_("Keep Aspect Ratio"));
  2872.   gimp_help_set_help_data (toggle, _("When toggled, the resulting image will be scaled to fit "
  2873.                      "into the given size without changing the aspect ratio."),
  2874.                "#keep_aspect_ratio"), 
  2875.   gtk_box_pack_start (GTK_BOX (vbox), toggle, TRUE, TRUE, 0);
  2876.   gtk_signal_connect (GTK_OBJECT (toggle), "toggled",
  2877.                       GTK_SIGNAL_FUNC (gimp_toggle_button_update),
  2878.                       &psvals.keep_ratio);
  2879.   gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (toggle), psvals.keep_ratio);
  2880.   gtk_widget_show (toggle);
  2881.  
  2882.   /* Unit */
  2883.   uframe = gimp_radio_group_new2 (TRUE, _("Unit"),
  2884.                   save_unit_toggle_update,
  2885.                   vals, (gpointer) psvals.unit_mm,
  2886.  
  2887.                   _("Inch"),       (gpointer) FALSE, NULL,
  2888.                   _("Millimeter"), (gpointer) TRUE, NULL,
  2889.  
  2890.                   NULL);
  2891.   gtk_box_pack_start (GTK_BOX (vbox), uframe, FALSE, FALSE, 0);
  2892.   gtk_widget_show (uframe);
  2893.  
  2894.   gtk_widget_show (vbox);
  2895.   gtk_widget_show (frame);
  2896.  
  2897.   /* Rotation */
  2898.   frame = gimp_radio_group_new2 (TRUE, _("Rotation"),
  2899.                  gimp_radio_button_update,
  2900.                  &psvals.rotate, (gpointer) psvals.rotate,
  2901.  
  2902.                  "0",   (gpointer) 0, NULL,
  2903.                  "90",  (gpointer) 90, NULL,
  2904.                  "180", (gpointer) 180, NULL,
  2905.                  "270", (gpointer) 270, NULL,
  2906.  
  2907.                  NULL);
  2908.   gtk_box_pack_start (GTK_BOX (main_vbox[1]), frame, FALSE, FALSE, 0);
  2909.   gtk_widget_show (frame);
  2910.  
  2911.   /* Format */
  2912.   frame = gtk_frame_new (_("Output"));
  2913.   gtk_frame_set_shadow_type (GTK_FRAME (frame), GTK_SHADOW_ETCHED_IN);
  2914.   gtk_box_pack_start (GTK_BOX (main_vbox[1]), frame, TRUE, TRUE, 0);
  2915.  
  2916.   vbox = gtk_vbox_new (FALSE, 2);
  2917.   gtk_container_set_border_width (GTK_CONTAINER (vbox), 4);
  2918.   gtk_container_add (GTK_CONTAINER (frame), vbox);
  2919.  
  2920.   toggle = gtk_check_button_new_with_label (_("PostScript Level 2"));
  2921.   gtk_box_pack_start (GTK_BOX (vbox), toggle, TRUE, TRUE, 0);
  2922.   gtk_signal_connect (GTK_OBJECT (toggle), "toggled",
  2923.                       GTK_SIGNAL_FUNC (gimp_toggle_button_update),
  2924.                       &(vals->level));
  2925.   gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (toggle), vals->level);
  2926.   gtk_widget_show (toggle);
  2927.  
  2928.   toggle = gtk_check_button_new_with_label (_("Encapsulated PostScript"));
  2929.   gtk_box_pack_start (GTK_BOX (vbox), toggle, TRUE, TRUE, 0);
  2930.   gtk_signal_connect (GTK_OBJECT (toggle), "toggled",
  2931.                       GTK_SIGNAL_FUNC (gimp_toggle_button_update),
  2932.                       &psvals.eps);
  2933.   gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (toggle), psvals.eps);
  2934.   gtk_widget_show (toggle);
  2935.  
  2936.   toggle = gtk_check_button_new_with_label (_("Preview"));
  2937.   gtk_box_pack_start (GTK_BOX (vbox), toggle, TRUE, TRUE, 0);
  2938.   gtk_signal_connect (GTK_OBJECT (toggle), "toggled",
  2939.                       GTK_SIGNAL_FUNC (gimp_toggle_button_update),
  2940.                       &psvals.preview);
  2941.   gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (toggle), psvals.preview);
  2942.   gtk_widget_show (toggle);
  2943.  
  2944.   /* Preview size label/entry */
  2945.   table = gtk_table_new (1, 2, FALSE);
  2946.   gtk_table_set_col_spacings (GTK_TABLE (table), 4);
  2947.   gtk_box_pack_start (GTK_BOX (vbox), table, FALSE, FALSE, 0);
  2948.   gtk_widget_show (table);
  2949.  
  2950.   gtk_object_set_data (GTK_OBJECT (toggle), "set_sensitive", table);
  2951.   gtk_widget_set_sensitive (table, psvals.preview);
  2952.  
  2953.   spinbutton = gimp_spin_button_new (&adj, psvals.preview_size,
  2954.                      0, 1024, 1, 10, 0, 1, 0);
  2955.   gimp_table_attach_aligned (GTK_TABLE (table), 0, 0,
  2956.                  _("Preview Size:"), 1.0, 0.5,
  2957.                  spinbutton, 1, FALSE);
  2958.   gtk_signal_connect (GTK_OBJECT (adj), "value_changed",
  2959.               GTK_SIGNAL_FUNC (gimp_int_adjustment_update),
  2960.               &psvals.preview_size);
  2961.   gtk_widget_show (spinbutton);
  2962.  
  2963.   gtk_widget_show (vbox);
  2964.   gtk_widget_show (frame);
  2965.  
  2966.   for (j = 0; j < sizeof (main_vbox) / sizeof (main_vbox[0]); j++)
  2967.     gtk_widget_show (main_vbox[j]);
  2968.  
  2969.   gtk_widget_show (hbox);
  2970.   gtk_widget_show (dialog);
  2971.  
  2972.   gtk_main ();
  2973.   gdk_flush ();
  2974.  
  2975.   psvals.level = (vals->level) ? 2 : 1;
  2976.  
  2977.   g_free (vals);
  2978.  
  2979.   return psint.run;
  2980. }
  2981.  
  2982. static void
  2983. save_ok_callback (GtkWidget *widget,
  2984.                   gpointer   data)
  2985. {
  2986.   psint.run = TRUE;
  2987.  
  2988.   gtk_widget_destroy (GTK_WIDGET (data));
  2989. }
  2990.  
  2991. static void
  2992. save_unit_toggle_update (GtkWidget *widget,
  2993.              gpointer   data)
  2994. {
  2995.   if (GTK_TOGGLE_BUTTON (widget)->active)
  2996.     {
  2997.       SaveDialogVals *vals;
  2998.       gdouble factor;
  2999.       gdouble value;
  3000.       gint    unit_mm;
  3001.       gint    i;
  3002.  
  3003.       vals    = (SaveDialogVals *) data;
  3004.       unit_mm = (gint) gtk_object_get_user_data (GTK_OBJECT (widget));
  3005.  
  3006.       psvals.unit_mm = unit_mm;
  3007.  
  3008.       if (unit_mm)
  3009.     factor = 25.4;
  3010.       else
  3011.     factor = 1.0 / 25.4;
  3012.  
  3013.       for (i = 0; i < 4; i++)
  3014.     {
  3015.       value = GTK_ADJUSTMENT (vals->adjustment[i])->value * factor;
  3016.  
  3017.       gtk_adjustment_set_value (GTK_ADJUSTMENT (vals->adjustment[i]), value);
  3018.     }
  3019.     }
  3020. }
  3021.