home *** CD-ROM | disk | FTP | other *** search
/ Mega Top 1 / os2_top1.zip / os2_top1 / APPS / TEKST / GSPMSRC / SRC / GDEVXINI.C < prev    next >
C/C++ Source or Header  |  1993-12-16  |  32KB  |  982 lines

  1. /* Copyright (C) 1989, 1992, 1993 Aladdin Enterprises.  All rights reserved.
  2.  
  3. This file is part of Ghostscript.
  4.  
  5. Ghostscript is distributed in the hope that it will be useful, but
  6. WITHOUT ANY WARRANTY.  No author or distributor accepts responsibility
  7. to anyone for the consequences of using it or for whether it serves any
  8. particular purpose or works at all, unless he says so in writing.  Refer
  9. to the Ghostscript General Public License for full details.
  10.  
  11. Everyone is granted permission to copy, modify and redistribute
  12. Ghostscript, but only under the conditions described in the Ghostscript
  13. General Public License.  A copy of this license is supposed to have been
  14. given to you along with Ghostscript so you can know your rights and
  15. responsibilities.  It should be in a file named COPYING.  Among other
  16. things, the copyright notice and this notice must be preserved on all
  17. copies.  */
  18.  
  19. /* gdevxini.c */
  20. /* X Windows driver initialization for Ghostscript library */
  21. #include "gx.h"            /* for gx_bitmap; includes std.h */
  22. #include "memory_.h"
  23. #include "math_.h"
  24. #include "x_.h"
  25. #include "gxdevice.h"
  26. #include "gdevx.h"
  27.  
  28. extern char *getenv(P1(const char *));
  29.  
  30. private XtResource resources[] = {
  31.     {XtNbackground, XtCBackground, XtRPixel, sizeof(Pixel),
  32.      XtOffsetOf(gx_device_X, background),
  33.      XtRString, (XtPointer)"XtDefaultBackground"},
  34.     {XtNborderColor, XtCBorderColor, XtRPixel, sizeof(Pixel),
  35.      XtOffsetOf(gx_device_X, borderColor),
  36.      XtRString, (XtPointer)"XtDefaultForeground"},
  37.     {XtNborderWidth, XtCBorderWidth, XtRDimension, sizeof(Dimension),
  38.      XtOffsetOf(gx_device_X, borderWidth),
  39.      XtRImmediate, (XtPointer)1},
  40.     {"dingbatFonts", "DingbatFonts", XtRString, sizeof(String), 
  41.      XtOffsetOf(gx_device_X, dingbatFonts),
  42.      XtRString, "ZapfDingbats: -Adobe-ITC Zapf Dingbats-Medium-R-Normal--"},
  43.     {XtNforeground, XtCForeground, XtRPixel, sizeof(Pixel),
  44.      XtOffsetOf(gx_device_X, foreground),
  45.      XtRString, (XtPointer)"XtDefaultForeground"},
  46.     {XtNgeometry, XtCGeometry, XtRString, sizeof(String), 
  47.      XtOffsetOf(gx_device_X, geometry),
  48.      XtRString, NULL},
  49.     {"logExternalFonts", "LogExternalFonts", XtRBoolean, sizeof(Boolean), 
  50.      XtOffsetOf(gx_device_X, logXFonts),
  51.      XtRImmediate, (XtPointer)False},
  52.     {"maxGrayRamp", "MaxGrayRamp", XtRInt, sizeof(int), 
  53.      XtOffsetOf(gx_device_X, maxGrayRamp),
  54.      XtRImmediate, (XtPointer)128},
  55.     {"maxRGBRamp", "MaxRGBRamp", XtRInt, sizeof(int), 
  56.      XtOffsetOf(gx_device_X, maxRGBRamp),
  57.      XtRImmediate, (XtPointer)5},
  58.     {"palette", "Palette", XtRString, sizeof(String), 
  59.      XtOffsetOf(gx_device_X, palette),
  60.      XtRString, "Color"},
  61.  
  62.     /* I had to compress the whitespace out of the default string to
  63.      * satisfy certain balky compilers.
  64.      */
  65.     {"regularFonts", "RegularFonts", XtRString, sizeof(String), 
  66.      XtOffsetOf(gx_device_X, regularFonts),
  67.      XtRString, "\
  68. AvantGarde-Book:-Adobe-ITC Avant Garde Gothic-Book-R-Normal--\n\
  69. AvantGarde-BookOblique:-Adobe-ITC Avant Garde Gothic-Book-O-Normal--\n\
  70. AvantGarde-Demi:-Adobe-ITC Avant Garde Gothic-Demi-R-Normal--\n\
  71. AvantGarde-DemiOblique:-Adobe-ITC Avant Garde Gothic-Demi-O-Normal--\n\
  72. Bookman-Demi:-Adobe-ITC Bookman-Demi-R-Normal--\n\
  73. Bookman-DemiItalic:-Adobe-ITC Bookman-Demi-I-Normal--\n\
  74. Bookman-Light:-Adobe-ITC Bookman-Light-R-Normal--\n\
  75. Bookman-LightItalic:-Adobe-ITC Bookman-Light-I-Normal--\n\
  76. Courier:-Adobe-Courier-Medium-R-Normal--\n\
  77. Courier-Bold:-Adobe-Courier-Bold-R-Normal--\n\
  78. Courier-BoldOblique:-Adobe-Courier-Bold-O-Normal--\n\
  79. Courier-Oblique:-Adobe-Courier-Medium-O-Normal--\n\
  80. Helvetica:-Adobe-Helvetica-Medium-R-Normal--\n\
  81. Helvetica-Bold:-Adobe-Helvetica-Bold-R-Normal--\n\
  82. Helvetica-BoldOblique:-Adobe-Helvetica-Bold-O-Normal--\n\
  83. Helvetica-Narrow:-Adobe-Helvetica-Medium-R-Narrow--\n\
  84. Helvetica-Narrow-Bold:-Adobe-Helvetica-Bold-R-Narrow--\n\
  85. Helvetica-Narrow-BoldOblique:-Adobe-Helvetica-Bold-O-Narrow--\n\
  86. Helvetica-Narrow-Oblique:-Adobe-Helvetica-Medium-O-Narrow--\n\
  87. Helvetica-Oblique:-Adobe-Helvetica-Medium-O-Normal--\n\
  88. NewCenturySchlbk-Bold:-Adobe-New Century Schoolbook-Bold-R-Normal--\n\
  89. NewCenturySchlbk-BoldItalic:-Adobe-New Century Schoolbook-Bold-I-Normal--\n\
  90. NewCenturySchlbk-Italic:-Adobe-New Century Schoolbook-Medium-I-Normal--\n\
  91. NewCenturySchlbk-Roman:-Adobe-New Century Schoolbook-Medium-R-Normal--\n\
  92. Palatino-Bold:-Adobe-Palatino-Bold-R-Normal--\n\
  93. Palatino-BoldItalic:-Adobe-Palatino-Bold-I-Normal--\n\
  94. Palatino-Italic:-Adobe-Palatino-Medium-I-Normal--\n\
  95. Palatino-Roman:-Adobe-Palatino-Medium-R-Normal--\n\
  96. Times-Bold:-Adobe-Times-Bold-R-Normal--\n\
  97. Times-BoldItalic:-Adobe-Times-Bold-I-Normal--\n\
  98. Times-Italic:-Adobe-Times-Medium-I-Normal--\n\
  99. Times-Roman:-Adobe-Times-Medium-R-Normal--\n\
  100. ZapfChancery-MediumItalic:-Adobe-ITC Zapf Chancery-Medium-I-Normal--"},
  101.     {"symbolFonts", "SymbolFonts", XtRString, sizeof(String), 
  102.      XtOffsetOf(gx_device_X, symbolFonts),
  103.      XtRString, "Symbol: -Adobe-Symbol-Medium-R-Normal--"},
  104.     {"useBackingPixmap", "UseBackingPixmap", XtRBoolean, sizeof(Boolean), 
  105.      XtOffsetOf(gx_device_X, useBackingPixmap),
  106.      XtRImmediate, (XtPointer)True},
  107.     {"useExternalFonts", "UseExternalFonts", XtRBoolean, sizeof(Boolean), 
  108.      XtOffsetOf(gx_device_X, useXFonts),
  109.      XtRImmediate, (XtPointer)True},
  110.     {"useFontExtensions", "UseFontExtensions", XtRBoolean, sizeof(Boolean), 
  111.      XtOffsetOf(gx_device_X, useFontExtensions),
  112.      XtRImmediate, (XtPointer)True},
  113.     {"useScalableFonts", "UseScalableFonts", XtRBoolean, sizeof(Boolean), 
  114.      XtOffsetOf(gx_device_X, useScalableFonts),
  115.      XtRImmediate, (XtPointer)True},
  116.     {"useXPutImage", "UseXPutImage", XtRBoolean, sizeof(Boolean), 
  117.      XtOffsetOf(gx_device_X, useXPutImage),
  118.      XtRImmediate, (XtPointer)True},
  119.     {"useXSetTile", "UseXSetTile", XtRBoolean, sizeof(Boolean), 
  120.      XtOffsetOf(gx_device_X, useXSetTile),
  121.      XtRImmediate, (XtPointer)True},
  122.     {"xResolution", "Resolution", XtRFloat, sizeof(float),
  123.      XtOffsetOf(gx_device_X, xResolution),
  124.      XtRString, (XtPointer)"0.0"},
  125.     {"yResolution", "Resolution", XtRFloat, sizeof(float),
  126.      XtOffsetOf(gx_device_X, yResolution),
  127.      XtRString, (XtPointer)"0.0"},
  128. };
  129.  
  130. private String
  131. fallback_resources[] = {
  132.     "Ghostscript*Background: white",
  133.     "Ghostscript*Foreground: black",
  134.     NULL
  135. };
  136.  
  137. /* Define constants for orientation from ghostview */
  138. /* Number represents clockwise rotation of the paper in degrees */
  139. typedef enum {
  140.   Portrait = 0,        /* Normal portrait orientation */
  141.   Landscape = 90,    /* Normal landscape orientation */
  142.   Upsidedown = 180,    /* Don't think this will be used much */
  143.   Seascape = 270    /* Landscape rotated the wrong way */
  144. } orientation;
  145.  
  146. /* Forward references */
  147. private void gdev_x_setup_colors(P1(gx_device_X *));
  148. private void gdev_x_setup_fontmap(P1(gx_device_X *));
  149.  
  150. /* Catch the alloc error when there is not enough resources for the
  151.  * backing pixmap.  Automatically shut off backing pixmap and let the
  152.  * user know when this happens.
  153.  */
  154. private Boolean alloc_error;
  155. private XErrorHandler oldhandler;
  156.  
  157. private int
  158. x_catch_alloc(Display *dpy, XErrorEvent *err)
  159. {
  160.     if (err->error_code == BadAlloc)
  161.     alloc_error = True;
  162.     if (alloc_error)
  163.     return 0;
  164.     return oldhandler(dpy, err);
  165. }
  166.  
  167. int
  168. x_catch_free_colors(Display *dpy, XErrorEvent *err)
  169. {
  170.     if (err->request_code == X_FreeColors) return 0;
  171.     return oldhandler(dpy, err);
  172. }
  173.  
  174. /* Open the X device */
  175. int
  176. gdev_x_open(register gx_device_X *xdev)
  177. {
  178.     XSizeHints sizehints;
  179.     char *window_id;
  180.     XEvent event;
  181.     XVisualInfo xvinfo;
  182.     int nitems;
  183.     XtAppContext app_con;
  184.     Widget toplevel;
  185.     Display *dpy;
  186.     int zero = 0;
  187.  
  188. #ifdef DEBUG
  189.     if (gs_debug['X']) {
  190.     extern int _Xdebug;
  191.  
  192.     _Xdebug = 1;
  193.     }
  194. #endif
  195.     if (!(xdev->dpy = XOpenDisplay((char *)NULL))) {
  196.     char *dispname = getenv("DISPLAY");
  197.  
  198.     eprintf1("gs: Cannot open X display `%s'.\n",
  199.          (dispname == NULL ? "(null)" : dispname));
  200.     exit(1);
  201.     }
  202.     xdev->dest = 0;
  203.     if ((window_id = getenv("GHOSTVIEW"))) {
  204.     if (!(xdev->ghostview = sscanf(window_id, "%d %d",
  205.                        &(xdev->win), &(xdev->dest)))) {
  206.         eprintf("gs: Cannot get Window ID from ghostview.\n");
  207.         exit(1);
  208.     }
  209.     }
  210.     if (xdev->ghostview) {
  211.     XWindowAttributes attrib;
  212.     Atom type;
  213.     int format;
  214.     unsigned long nitems, bytes_after;
  215.     char *buf;
  216.     Atom ghostview_atom = XInternAtom(xdev->dpy, "GHOSTVIEW", False);
  217.  
  218.     if (XGetWindowAttributes(xdev->dpy, xdev->win, &attrib)) {
  219.         xdev->scr = attrib.screen;
  220.         xvinfo.visual = attrib.visual;
  221.         xdev->cmap = attrib.colormap;
  222.         xdev->width = attrib.width;
  223.         xdev->height = attrib.height;
  224.     }
  225.     /* Delete property if explicit dest is given */
  226.     if (XGetWindowProperty(xdev->dpy, xdev->win, ghostview_atom, 0,
  227.                    256, (xdev->dest != 0), XA_STRING,
  228.                    &type, &format, &nitems, &bytes_after,
  229.                    (unsigned char **)&buf) == 0 &&
  230.         type == XA_STRING) {
  231.         int llx, lly, urx, ury;
  232.         int left_margin = 0, bottom_margin = 0;
  233.         int right_margin = 0, top_margin = 0;
  234.  
  235.         /* We declare page_orientation as an int so that we can */
  236.         /* use an int * to reference it for sscanf; compilers */
  237.         /* might be tempted to use less space to hold it if */
  238.         /* it were declared as an orientation. */
  239.         int /*orientation*/ page_orientation;
  240.         float xppp, yppp;    /* pixels per point */
  241.         nitems = sscanf(buf,
  242.                 "%d %d %d %d %d %d %f %f %d %d %d %d",
  243.                 &(xdev->bpixmap), &page_orientation,
  244.                 &llx, &lly, &urx, &ury,
  245.                 &(xdev->x_pixels_per_inch),
  246.                 &(xdev->y_pixels_per_inch),
  247.                 &left_margin, &bottom_margin,
  248.                 &right_margin, &top_margin);
  249.         if (!(nitems == 8 || nitems == 12)) {
  250.         eprintf("gs: Cannot get ghostview property.\n");
  251.         exit(1);
  252.         }
  253.         if (xdev->dest && xdev->bpixmap) {
  254.         eprintf("gs: Both destination and backing pixmap specified.\n");
  255.         exit(1);
  256.         }
  257.         if (xdev->dest) {
  258.         Window root;
  259.         int x, y;
  260.         unsigned int width, height;
  261.         unsigned int border_width, depth;
  262.  
  263.         if (XGetGeometry(xdev->dpy, xdev->dest, &root, &x, &y,
  264.                  &width, &height, &border_width, &depth)) {
  265.             xdev->width = width;
  266.             xdev->height = height;
  267.         }
  268.         }
  269.         xppp = xdev->x_pixels_per_inch / 72.0;
  270.         yppp = xdev->y_pixels_per_inch / 72.0;
  271.         switch (page_orientation) {
  272.         case Portrait:
  273.         xdev->initial_matrix.xx = xppp;
  274.         xdev->initial_matrix.xy = 0.0;
  275.         xdev->initial_matrix.yx = 0.0;
  276.         xdev->initial_matrix.yy = -yppp;
  277.         xdev->initial_matrix.tx = -llx * xppp;
  278.         xdev->initial_matrix.ty = ury * yppp;
  279.         break;
  280.         case Landscape:
  281.         xdev->initial_matrix.xx = 0.0;
  282.         xdev->initial_matrix.xy = yppp;
  283.         xdev->initial_matrix.yx = xppp;
  284.         xdev->initial_matrix.yy = 0.0;
  285.         xdev->initial_matrix.tx = -lly * xppp;
  286.         xdev->initial_matrix.ty = -llx * yppp;
  287.         break;
  288.         case Upsidedown:
  289.         xdev->initial_matrix.xx = -xppp;
  290.         xdev->initial_matrix.xy = 0.0;
  291.         xdev->initial_matrix.yx = 0.0;
  292.         xdev->initial_matrix.yy = yppp;
  293.         xdev->initial_matrix.tx = urx * xppp;
  294.         xdev->initial_matrix.ty = -lly * yppp;
  295.         break;
  296.         case Seascape:
  297.         xdev->initial_matrix.xx = 0.0;
  298.         xdev->initial_matrix.xy = -yppp;
  299.         xdev->initial_matrix.yx = -xppp;
  300.         xdev->initial_matrix.yy = 0.0;
  301.         xdev->initial_matrix.tx = ury * xppp;
  302.         xdev->initial_matrix.ty = urx * yppp;
  303.         break;
  304.         }
  305.  
  306.         /* The following sets the imageable area according to the */
  307.         /* bounding box and margins sent by ghostview.            */
  308.         xdev->l_margin = (llx - left_margin) / 72.0;
  309.         xdev->b_margin = (lly - bottom_margin) / 72.0;
  310.         xdev->r_margin = xdev->width / xdev->x_pixels_per_inch -
  311.                  (urx + right_margin) / 72.0;
  312.         xdev->t_margin = xdev->height / xdev->y_pixels_per_inch -
  313.                  (ury + top_margin) / 72.0;
  314.     } else {
  315.         eprintf("gs: Cannot get ghostview property.\n");
  316.         exit(1);
  317.     }
  318.     } else {
  319.     Screen *scr = DefaultScreenOfDisplay(xdev->dpy);
  320.  
  321.     xdev->scr = scr;
  322.     xvinfo.visual = DefaultVisualOfScreen(scr);
  323.     xdev->cmap = DefaultColormapOfScreen(scr);
  324.     }
  325.  
  326.     xvinfo.visualid = XVisualIDFromVisual(xvinfo.visual);
  327.     xdev->vinfo = XGetVisualInfo(xdev->dpy, VisualIDMask, &xvinfo, &nitems);
  328.     if (xdev->vinfo == NULL) {
  329.     eprintf("gs: Cannot get XVisualInfo.\n");
  330.     exit(1);
  331.     }
  332.     /* Get X Resources.  Use the toolkit for this. */
  333. #if !defined(XtSpecificationRelease) || XtSpecificationRelease < 5
  334.     /* R4 and earlier toolkits may cause a Bad Access on XFreeColors. */
  335.     oldhandler = XSetErrorHandler(x_catch_free_colors);
  336. #endif
  337.     XtToolkitInitialize();
  338.     app_con = XtCreateApplicationContext();
  339.     XtAppSetFallbackResources(app_con, fallback_resources);
  340.     dpy = XtOpenDisplay(app_con, NULL, "ghostscript", "Ghostscript",
  341.             NULL, 0, &zero, NULL);
  342.     toplevel = XtAppCreateShell(NULL, "Ghostscript",
  343.                 applicationShellWidgetClass, dpy, NULL, 0);
  344.     XtGetApplicationResources(toplevel, (XtPointer) xdev,
  345.                   resources, XtNumber(resources), NULL, 0);
  346.     XtDestroyWidget(toplevel);
  347.     XtCloseDisplay(dpy);
  348.     XtDestroyApplicationContext(app_con);
  349. #if !defined(XtSpecificationRelease) || XtSpecificationRelease < 5
  350.     oldhandler = XSetErrorHandler(oldhandler);
  351. #endif
  352.  
  353.     gdev_x_setup_colors(xdev);
  354.     gdev_x_setup_fontmap(xdev);
  355.  
  356.     if (!xdev->ghostview) {
  357.     XWMHints wm_hints;
  358.     XSetWindowAttributes xswa;
  359.     gx_device *dev = (gx_device *)xdev;
  360.  
  361.     /* Take care of resolution and paper size. */
  362.     if (xdev->x_pixels_per_inch == FAKE_RES ||
  363.         xdev->y_pixels_per_inch == FAKE_RES) {
  364.         float xsize, ysize;
  365.  
  366.         xsize = (float)xdev->width / xdev->x_pixels_per_inch;
  367.         ysize = (float)xdev->height / xdev->y_pixels_per_inch;
  368.  
  369.         if (xdev->xResolution == 0.0 && xdev->yResolution == 0.0) {
  370.         float dpi, xdpi, ydpi;
  371.  
  372.         xdpi = 25.4 * WidthOfScreen(xdev->scr) /
  373.                WidthMMOfScreen(xdev->scr);
  374.         ydpi = 25.4 * HeightOfScreen(xdev->scr) /
  375.                HeightMMOfScreen(xdev->scr);
  376.         dpi = min(xdpi, ydpi);
  377.  
  378.         while (xsize*dpi > WidthOfScreen(xdev->scr)-32 ||
  379.                ysize*dpi > HeightOfScreen(xdev->scr)-32) {
  380.             dpi *= 0.95;
  381.         }
  382.         xdev->x_pixels_per_inch = dpi;
  383.         xdev->y_pixels_per_inch = dpi;
  384.         } else {
  385.         xdev->x_pixels_per_inch = xdev->xResolution;
  386.         xdev->y_pixels_per_inch = xdev->yResolution;
  387.         }
  388.         if (xdev->width > WidthOfScreen(xdev->scr)) {
  389.         xdev->width = xsize*xdev->x_pixels_per_inch;
  390.         }
  391.         if (xdev->height > HeightOfScreen(xdev->scr)) {
  392.         xdev->height = ysize*xdev->y_pixels_per_inch;
  393.         }
  394.     }
  395.  
  396.     sizehints.x = 0;
  397.     sizehints.y = 0;
  398.     sizehints.width = xdev->width;
  399.     sizehints.height = xdev->height;
  400.     sizehints.flags = 0;
  401.  
  402.     if (xdev->geometry != NULL) {
  403.         /*
  404.          * Note that border_width must be set first.  We can't use
  405.          * scr, because that is a Screen*, and XWMGeometry wants
  406.          * the screen number.
  407.          */
  408.         char gstr[40];
  409.         int bitmask;
  410.  
  411.         sprintf(gstr, "%dx%d+%d+%d", sizehints.width,
  412.             sizehints.height, sizehints.x, sizehints.y);
  413.         bitmask = XWMGeometry(xdev->dpy, DefaultScreen(xdev->dpy),
  414.                   xdev->geometry, gstr, xdev->borderWidth,
  415.                   &sizehints,
  416.                   &sizehints.x, &sizehints.y,
  417.                   &sizehints.width, &sizehints.height,
  418.                   &sizehints.win_gravity);
  419.  
  420.         if (bitmask & (XValue | YValue))
  421.         sizehints.flags |= USPosition;
  422.     }
  423.  
  424.     gx_default_get_initial_matrix(dev, &(xdev->initial_matrix));
  425.  
  426.     xswa.event_mask = ExposureMask;
  427.     xswa.background_pixel = xdev->background;
  428.     xswa.border_pixel = xdev->borderColor;
  429.     xswa.colormap = xdev->cmap;
  430.     xdev->win = XCreateWindow(xdev->dpy, RootWindowOfScreen(xdev->scr),
  431.                   sizehints.x, sizehints.y,    /* upper left */
  432.                   xdev->width, xdev->height,
  433.                   xdev->borderWidth,
  434.                   xdev->vinfo->depth,
  435.                   InputOutput,    /* class */
  436.                   xdev->vinfo->visual,    /* visual */
  437.                   CWEventMask | CWBackPixel |
  438.                   CWBorderPixel | CWColormap,
  439.                   &xswa);
  440.     XStoreName(xdev->dpy, xdev->win, "ghostscript");
  441.     XSetWMNormalHints(xdev->dpy, xdev->win, &sizehints);
  442.     wm_hints.flags = InputHint;
  443.     wm_hints.input = False;
  444.     XSetWMHints(xdev->dpy, xdev->win, &wm_hints); /* avoid input focus */
  445.     }
  446.  
  447.     xdev->ht.pixmap = (Pixmap) 0;
  448.     xdev->ht.id = gx_no_bitmap_id;;
  449.     xdev->fill_style = FillSolid;
  450.     xdev->function = GXcopy;
  451.     xdev->fid = (Font) 0;
  452.  
  453.     /* Set up a graphics context */
  454.     xdev->gc = XCreateGC(xdev->dpy, xdev->win, 0, (XGCValues *) NULL);
  455.     XSetFunction(xdev->dpy, xdev->gc, GXcopy);
  456.     XSetLineAttributes(xdev->dpy, xdev->gc, 0,
  457.                LineSolid, CapButt, JoinMiter);
  458.  
  459.     gdev_x_clear_window(xdev);
  460.  
  461.     if (!xdev->ghostview) {    /* Make the window appear. */
  462.     XMapWindow(xdev->dpy, xdev->win);
  463.  
  464.     /* Before anything else, do a flush and wait for */
  465.     /* an exposure event. */
  466.     XFlush(xdev->dpy);
  467.     XNextEvent(xdev->dpy, &event);
  468.     } else {
  469.     /* Create an unmapped window, that the window manager will ignore.
  470.      * This invisible window will be used to receive "next page"
  471.      * events from ghostview */
  472.     XSetWindowAttributes attributes;
  473.  
  474.     attributes.override_redirect = True;
  475.     xdev->mwin = XCreateWindow(xdev->dpy, RootWindowOfScreen(xdev->scr),
  476.                    0, 0, 1, 1, 0, CopyFromParent,
  477.                    CopyFromParent, CopyFromParent,
  478.                    CWOverrideRedirect, &attributes);
  479.     xdev->next = XInternAtom(xdev->dpy, "NEXT", False);
  480.     xdev->page = XInternAtom(xdev->dpy, "PAGE", False);
  481.     xdev->done = XInternAtom(xdev->dpy, "DONE", False);
  482.     }
  483.  
  484.     xdev->ht.no_pixmap = XCreatePixmap(xdev->dpy, xdev->win, 1, 1,
  485.                        xdev->vinfo->depth);
  486.  
  487.     XSync(xdev->dpy, 0);
  488.     return 0;
  489. }
  490.  
  491. /* Allocate the backing pixmap, if any, and clear the window. */
  492. void
  493. gdev_x_clear_window(gx_device_X *xdev)
  494. {
  495.     if (!xdev->ghostview) {
  496.     if (xdev->useBackingPixmap) {
  497.         oldhandler = XSetErrorHandler(x_catch_alloc);
  498.         alloc_error = False;
  499.         xdev->bpixmap =
  500.         XCreatePixmap(xdev->dpy, xdev->win,
  501.                   xdev->width, xdev->height,
  502.                   xdev->vinfo->depth);
  503.         XSync(xdev->dpy, False);    /* Force the error */
  504.         if (alloc_error) {
  505.         xdev->useBackingPixmap = False;
  506.         eprintf("Warning: Failed to allocated backing pixmap.\n");
  507.         if (xdev->bpixmap) {
  508.             XFreePixmap(xdev->dpy, xdev->bpixmap);
  509.             xdev->bpixmap = None;
  510.             XSync(xdev->dpy, False);    /* Force the error */
  511.         }
  512.         }
  513.         oldhandler = XSetErrorHandler(oldhandler);
  514.     } else
  515.         xdev->bpixmap = (Pixmap) 0;
  516.     }
  517.     /* Clear the destination pixmap to avoid initializing with garbage. */
  518.     if (xdev->dest != (Pixmap) 0) {
  519.     XSetForeground(xdev->dpy, xdev->gc, xdev->background);
  520.     XFillRectangle(xdev->dpy, xdev->dest, xdev->gc,
  521.                0, 0, xdev->width, xdev->height);
  522.     } else {
  523.     xdev->dest = (xdev->bpixmap != (Pixmap) 0 ?
  524.               xdev->bpixmap : (Pixmap) xdev->win);
  525.     }
  526.  
  527.     /* Clear the background pixmap to avoid initializing with garbage. */
  528.     if (xdev->bpixmap != (Pixmap) 0) {
  529.     if (!xdev->ghostview)
  530.         XSetWindowBackgroundPixmap(xdev->dpy, xdev->win, xdev->bpixmap);
  531.     XSetForeground(xdev->dpy, xdev->gc, xdev->background);
  532.     XFillRectangle(xdev->dpy, xdev->bpixmap, xdev->gc,
  533.                0, 0, xdev->width, xdev->height);
  534.     }
  535.     /* Initialize foreground and background colors */
  536.     xdev->back_color = xdev->background;
  537.     XSetBackground(xdev->dpy, xdev->gc, xdev->background);
  538.     xdev->fore_color = xdev->background;
  539.     XSetForeground(xdev->dpy, xdev->gc, xdev->background);
  540.     xdev->colors_or = xdev->colors_and = xdev->background;
  541. }
  542.  
  543. #if HaveStdCMap
  544. /* get Standard colormap if available */
  545. private XStandardColormap *
  546. x_get_std_cmap(gx_device_X *xdev, Atom prop)
  547. {
  548.     int i;
  549.     XStandardColormap *scmap, *sp;
  550.     int nitems;
  551.  
  552.     if (XGetRGBColormaps(xdev->dpy, RootWindowOfScreen(xdev->scr),
  553.              &scmap, &nitems, prop))
  554.     for (i = 0, sp = scmap; i < nitems; i++, sp++)
  555.         if (xdev->cmap == sp->colormap)
  556.         return sp;
  557.  
  558.     return NULL;
  559. }
  560. #endif
  561.  
  562. /* Setup color mapping. */
  563. private void
  564. gdev_x_setup_colors(gx_device_X *xdev)
  565. {
  566.     char palette;
  567.  
  568.     palette = ((xdev->vinfo->class != StaticGray) &&
  569.            (xdev->vinfo->class != GrayScale) ? 'C' :  /* Color */
  570.            (xdev->vinfo->colormap_size > 2) ?  'G' :  /* GrayScale */
  571.                            'M');  /* MonoChrome */
  572.     if (xdev->ghostview) {
  573.     Atom gv_colors = XInternAtom(xdev->dpy, "GHOSTVIEW_COLORS", False);
  574.     Atom type;
  575.     int format;
  576.     unsigned long nitems, bytes_after;
  577.     char *buf;
  578.  
  579.     /* Delete property if explicit dest is given */
  580.     if (XGetWindowProperty(xdev->dpy, xdev->win, gv_colors, 0,
  581.                    256, (xdev->dest != 0), XA_STRING,
  582.                    &type, &format, &nitems, &bytes_after,
  583.                    (unsigned char **)&buf) == 0 &&
  584.         type == XA_STRING) {
  585.         nitems = sscanf(buf, "%*s %d %d", &(xdev->foreground),
  586.                               &(xdev->background));
  587.         if (nitems != 2 || *buf != 'M' && *buf != 'G' && *buf != 'C') {
  588.         eprintf("gs: Malformed ghostview color property.\n");
  589.         exit(1);
  590.         }
  591.         palette = max(palette, *buf);
  592.     }
  593.     } else {
  594.     if      (xdev->palette[0] == 'c') xdev->palette[0] = 'C';
  595.     else if (xdev->palette[0] == 'g') xdev->palette[0] = 'G';
  596.     else if (xdev->palette[0] == 'm') xdev->palette[0] = 'M';
  597.     palette = max(palette, xdev->palette[0]);
  598.     }
  599.  
  600.     /* set up color mappings here */
  601.     xdev->color_mask = 0xffff - (0xffff >> xdev->vinfo->bits_per_rgb);
  602.     xdev->half_dev_color = 1 << (15 - xdev->vinfo->bits_per_rgb);
  603. #define num_rgb (1 << xdev->vinfo->bits_per_rgb)
  604.  
  605. #if HaveStdCMap
  606.     xdev->std_cmap = NULL;
  607. #endif
  608.     xdev->dither_colors = NULL;
  609.     xdev->dynamic_colors = NULL;
  610.     xdev->dynamic_size = 0;
  611.     xdev->dynamic_number = 0;
  612.     xdev->color_info.depth = xdev->vinfo->depth;
  613.  
  614.     if (palette == 'C') {
  615.     xdev->color_info.num_components = 3;
  616.     xdev->color_info.max_gray =
  617.         xdev->color_info.max_rgb = num_rgb - 1;
  618. #if HaveStdCMap
  619.     /* Get a standard color map if available */
  620.     if (xdev->vinfo->visual == DefaultVisualOfScreen(xdev->scr)) {
  621.         xdev->std_cmap = x_get_std_cmap(xdev, XA_RGB_DEFAULT_MAP);
  622.     } else {
  623.         xdev->std_cmap = x_get_std_cmap(xdev, XA_RGB_BEST_MAP);
  624.     }
  625.     if (xdev->std_cmap) {
  626.         xdev->color_info.dither_gray =
  627.         xdev->color_info.dither_rgb =
  628.         min(xdev->std_cmap->red_max,
  629.             min(xdev->std_cmap->green_max,
  630.             xdev->std_cmap->blue_max)) + 1;
  631.     } else
  632. #endif
  633.     /* Otherwise set up a rgb cube of our own */
  634.     /* The color cube is limited to about 1/2 of the available */
  635.     /* colormap, the user specified maxRGBRamp (usually 5), */
  636.     /* or the number of representable colors */
  637. #define cube(r) (r*r*r)
  638. #define cbrt(r) pow(r, 1.0/3.0)
  639.     {
  640.         int ramp_size =
  641.             min((int)cbrt((double)xdev->vinfo->colormap_size / 2.0),
  642.                 min(xdev->maxRGBRamp, num_rgb));
  643.  
  644.         while (!xdev->dither_colors && ramp_size >= 2) {
  645.         int max_rgb = ramp_size - 1;
  646.         int r, g, b;
  647.  
  648.         xdev->color_info.dither_gray =
  649.             xdev->color_info.dither_rgb = ramp_size;
  650.         xdev->dither_colors =
  651.             (x_pixel *) gs_malloc(sizeof(x_pixel), cube(ramp_size),
  652.                       "gdev_x_rgb_cube");
  653.         if (xdev->dither_colors == NULL) {
  654.             ramp_size--;
  655.             goto no_cube;
  656.         }
  657.         for (r = 0; r < ramp_size; r++) {
  658.             for (g = 0; g < ramp_size; g++) {
  659.             for (b = 0; b < ramp_size; b++) {
  660.                 if (r == 0 && g == 0 && b == 0) {
  661.                 xdev->dither_colors[0] = xdev->foreground;
  662.                 } else if (r == max_rgb && g == max_rgb &&
  663.                        b == max_rgb) {
  664.                 xdev->dither_colors[cube_index(r, g, b)] =
  665.                     xdev->background;
  666.                 } else {
  667.                 XColor xc;
  668.  
  669.                 xc.red = (0xffff * r / max_rgb) &
  670.                      xdev->color_mask;
  671.                 xc.green = (0xffff * g / max_rgb) &
  672.                      xdev->color_mask;
  673.                 xc.blue = (0xffff * b / max_rgb) &
  674.                      xdev->color_mask;
  675.                 if (XAllocColor(xdev->dpy, xdev->cmap, &xc)) {
  676.                     xdev->dither_colors[cube_index(r, g, b)] =
  677.                     xc.pixel;
  678.                 } else {
  679.                     eprintf3("Warning: failed to allocate %dx%dx%d RGB cube.\n",
  680.                          ramp_size, ramp_size, ramp_size);
  681.                     ramp_size--;
  682.                     if (cube_index(r, g, b) - 1 > 0) {
  683.                     oldhandler =
  684.                       XSetErrorHandler(x_catch_free_colors);
  685.                     XFreeColors(xdev->dpy, xdev->cmap,
  686.                             xdev->dither_colors + 1,
  687.                             cube_index(r, g, b) - 1, 0);
  688.                     /* Force any errors */
  689.                     XSync(xdev->dpy, False);
  690.                     oldhandler =
  691.                         XSetErrorHandler(oldhandler);
  692.                     }
  693.                     gs_free((char *)xdev->dither_colors,
  694.                         sizeof(x_pixel), cube(ramp_size),
  695.                         "gdev_x_rgb_cube");
  696.                     xdev->dither_colors = NULL;
  697.                     goto no_cube;
  698.                 }
  699.                 }
  700.             }
  701.             }
  702.         }
  703. no_cube:    ;
  704.         }
  705.  
  706.         if (!xdev->dither_colors) {
  707.         goto grayscale;
  708.         }
  709.     }
  710.  
  711.     /* Allocate space for dynamic colors, do at most 256 */
  712.     /* If there are more avaiaible, we ask the X server */
  713.     xdev->dynamic_size = min(256, xdev->vinfo->colormap_size -
  714.                       cube(xdev->color_info.dither_rgb));
  715.     if (xdev->dynamic_size) {
  716.         xdev->dynamic_colors =
  717.         (XColor *) gs_malloc(sizeof(XColor), xdev->dynamic_size,
  718.                      "gdev_x_dynamic_colors");
  719.         if (xdev->dynamic_colors == NULL) {
  720.         xdev->dynamic_size = 0;
  721.         }
  722.     }
  723. #undef cube
  724.     } else if (palette == 'G') {
  725. grayscale:
  726.     xdev->color_info.num_components = 1;
  727.     xdev->color_info.max_gray = num_rgb - 1;
  728. #if HaveStdCMap
  729.     /* Get a standard color map if available */
  730.     if (xdev->std_cmap = x_get_std_cmap(xdev, XA_RGB_GRAY_MAP)) {
  731.         xdev->color_info.dither_gray = xdev->std_cmap->red_max +
  732.         xdev->std_cmap->green_max +
  733.         xdev->std_cmap->blue_max + 1;
  734.     } else
  735. #endif
  736.     /* Otherwise set up a gray ramp of our own */
  737.     /* The gray ramp is limited to about 1/2 of the available */
  738.     /* colormap, the user specified maxGrayRamp (usually 128), */
  739.     /* or the number of representable grays */
  740.     {
  741.         int ramp_size = min(xdev->vinfo->colormap_size / 2,
  742.                 min(xdev->maxGrayRamp, num_rgb));
  743.  
  744.         while (!xdev->dither_colors && ramp_size >= 3) {
  745.         int max_gray = ramp_size - 1;
  746.         int i;
  747.  
  748.         xdev->color_info.dither_gray = ramp_size;
  749.         xdev->dither_colors =
  750.             (x_pixel *) gs_malloc(sizeof(x_pixel), ramp_size,
  751.                       "gdev_x_gray_ramp");
  752.         if (xdev->dither_colors == NULL) {
  753.             ramp_size--;
  754.             goto no_ramp;
  755.         }
  756.         for (i = 0; i < ramp_size; i++) {
  757.             XColor xc;
  758.  
  759.             xc.red = xc.green = xc.blue =
  760.             (0xffff * i / max_gray) & xdev->color_mask;
  761.             if (i == 0) {
  762.             xdev->dither_colors[i] = xdev->foreground;
  763.             } else if (i == max_gray) {
  764.             xdev->dither_colors[i] = xdev->background;
  765.             } else {
  766.             if (XAllocColor(xdev->dpy, xdev->cmap, &xc)) {
  767.                 xdev->dither_colors[i] = xc.pixel;
  768.             } else {
  769.                 eprintf1("Warning: failed to allocate %d level gray ramp.\n",
  770.                      ramp_size);
  771.                 ramp_size /= 2;
  772.                 if (i - 1 > 0) {
  773.                 oldhandler =
  774.                     XSetErrorHandler(x_catch_free_colors);
  775.                 XFreeColors(xdev->dpy, xdev->cmap,
  776.                         xdev->dither_colors + 1, i - 1, 0);
  777.                 XSync(xdev->dpy, False); /* Force any errors */
  778.                 oldhandler = XSetErrorHandler(oldhandler);
  779.                 }
  780.                 gs_free((char *)xdev->dither_colors,
  781.                     sizeof(x_pixel), ramp_size,
  782.                     "gdev_x_gray_ramp");
  783.                 xdev->dither_colors = NULL;
  784.                 goto no_ramp;
  785.             }
  786.             }
  787.         }
  788. no_ramp:    ;
  789.         }
  790.         if (!xdev->dither_colors) {
  791.         goto monochrome;
  792.         }
  793.     }
  794.  
  795.     /* Allocate space for dynamic colors, do at most 256 */
  796.     /* If there are more avaiaible, we ask the X server */
  797.     xdev->dynamic_size = min(256, xdev->vinfo->colormap_size -
  798.                       xdev->color_info.dither_gray);
  799.     if (xdev->dynamic_size) {
  800.         xdev->dynamic_colors =
  801.         (XColor *) gs_malloc(sizeof(XColor), xdev->dynamic_size,
  802.                      "gdev_x_dynamic_colors");
  803.         if (xdev->dynamic_colors == NULL) {
  804.         xdev->dynamic_size = 0;
  805.         }
  806.     }
  807.     } else if (palette == 'M') {
  808. monochrome:
  809.     xdev->color_info.num_components = 1;
  810.     xdev->color_info.max_gray = 1;
  811.     xdev->color_info.dither_gray = 2;
  812.     } else {
  813.     eprintf1("gs: Unknown palette: %s\n", xdev->palette);
  814.     exit(1);
  815.     }
  816. }
  817.  
  818. /* Setup X11 font mapping. */
  819. private char *
  820. get_ps_name(char **cpp, int *len)
  821. {
  822.     char *ret;
  823.     *len = 0;
  824.     /* skip over whitespace and newlines */
  825.     while (**cpp == ' ' || **cpp == '\t' || **cpp == '\n') {
  826.     (*cpp)++;
  827.     }
  828.     /* return font name up to ":", whitespace, or end of string */
  829.     if (**cpp == ':' || **cpp == '\0') {
  830.     return NULL;
  831.     }
  832.     ret = *cpp;
  833.     while (**cpp != ':' &&
  834.        **cpp != ' ' && **cpp != '\t' && **cpp != '\n' &&
  835.        **cpp != '\0') {
  836.     (*cpp)++;
  837.     (*len)++;
  838.     }
  839.     return ret;
  840. }
  841.  
  842. private char *
  843. get_x11_name(char **cpp, int *len)
  844. {
  845.     char *ret;
  846.     int dashes = 0;
  847.     *len = 0;
  848.     /* skip over whitespace and the colon */
  849.     while (**cpp == ' ' || **cpp == '\t' ||
  850.        **cpp == ':') {
  851.     (*cpp)++;
  852.     }
  853.     /* return font name up to end of line or string */
  854.     if (**cpp == '\0' || **cpp == '\n') {
  855.     return NULL;
  856.     }
  857.     ret = *cpp;
  858.     while (dashes != 7 &&
  859.        **cpp != '\0' && **cpp != '\n') {
  860.     if (**cpp == '-') dashes++;
  861.     (*cpp)++;
  862.     (*len)++;
  863.     }
  864.     while (**cpp != '\0' && **cpp != '\n') {
  865.     (*cpp)++;
  866.     }
  867.     if (dashes != 7) return NULL;
  868.     return ret;
  869. }
  870.  
  871. private void
  872. gdev_x_setup_fontmap(gx_device_X *xdev)
  873. {
  874.     char *ps_name;
  875.     char *x11_name;
  876.     int ps_name_len;
  877.     int x11_name_len;
  878.     x11fontmap *font;
  879.     char *cp;
  880.  
  881.     if (!xdev->useXFonts) return;    /* If no external fonts, don't bother */
  882.  
  883.     cp = xdev->regularFonts;
  884.     while (ps_name = get_ps_name(&cp, &ps_name_len)) {
  885.     if (x11_name = get_x11_name(&cp, &x11_name_len)) {
  886.         font = (x11fontmap *)gs_malloc(sizeof(x11fontmap), 1,
  887.                        "gdev_x_setup_fontmap");
  888.         if (font == NULL) continue;
  889.         font->ps_name = (char *)gs_malloc(sizeof(char), ps_name_len+1,
  890.                           "gdev_x_setup_fontmap");
  891.         if (font->ps_name == NULL) {
  892.         gs_free((char *)font, sizeof(x11fontmap), 1, "gdev_x_fontmap");
  893.         continue;
  894.         }
  895.         strncpy(font->ps_name, ps_name, ps_name_len);
  896.         font->ps_name[ps_name_len] = '\0';
  897.         font->x11_name = (char *)gs_malloc(sizeof(char), x11_name_len,
  898.                            "gdev_x_setup_fontmap");
  899.         if (font->x11_name == NULL) {
  900.         gs_free(font->ps_name, sizeof(char), strlen(font->ps_name)+1,
  901.             "gdev_x_font_psname");
  902.         gs_free((char *)font, sizeof(x11fontmap), 1, "gdev_x_fontmap");
  903.         continue;
  904.         }
  905.         strncpy(font->x11_name, x11_name, x11_name_len-1);
  906.         font->x11_name[x11_name_len-1] = '\0';
  907.         font->std_names = NULL;
  908.         font->iso_names = NULL;
  909.         font->std_count = -1;
  910.         font->iso_count = -1;
  911.         font->next = xdev->regular_fonts;
  912.         xdev->regular_fonts = font;
  913.     }
  914.     }
  915.  
  916.     cp = xdev->symbolFonts;
  917.     while (ps_name = get_ps_name(&cp, &ps_name_len)) {
  918.     if (x11_name = get_x11_name(&cp, &x11_name_len)) {
  919.         font = (x11fontmap *)gs_malloc(sizeof(x11fontmap), 1,
  920.                        "gdev_x_setup_fontmap");
  921.         if (font == NULL) continue;
  922.         font->ps_name = (char *)gs_malloc(sizeof(char), ps_name_len+1,
  923.                           "gdev_x_setup_fontmap");
  924.         if (font->ps_name == NULL) {
  925.         gs_free((char *)font, sizeof(x11fontmap), 1, "gdev_x_fontmap");
  926.         continue;
  927.         }
  928.         strncpy(font->ps_name, ps_name, ps_name_len);
  929.         font->ps_name[ps_name_len] = '\0';
  930.         font->x11_name = (char *)gs_malloc(sizeof(char), x11_name_len,
  931.                            "gdev_x_setup_fontmap");
  932.         if (font->x11_name == NULL) {
  933.         gs_free(font->ps_name, sizeof(char), strlen(font->ps_name)+1,
  934.             "gdev_x_font_psname");
  935.         gs_free((char *)font, sizeof(x11fontmap), 1, "gdev_x_fontmap");
  936.         continue;
  937.         }
  938.         strncpy(font->x11_name, x11_name, x11_name_len-1);
  939.         font->x11_name[x11_name_len-1] = '\0';
  940.         font->std_names = NULL;
  941.         font->iso_names = NULL;
  942.         font->std_count = -1;
  943.         font->iso_count = -1;
  944.         font->next = xdev->symbol_fonts;
  945.         xdev->symbol_fonts = font;
  946.     }
  947.     }
  948.  
  949.     cp = xdev->dingbatFonts;
  950.     while (ps_name = get_ps_name(&cp, &ps_name_len)) {
  951.     if (x11_name = get_x11_name(&cp, &x11_name_len)) {
  952.         font = (x11fontmap *)gs_malloc(sizeof(x11fontmap), 1,
  953.                        "gdev_x_setup_fontmap");
  954.         if (font == NULL) continue;
  955.         font->ps_name = (char *)gs_malloc(sizeof(char), ps_name_len+1,
  956.                           "gdev_x_setup_fontmap");
  957.         if (font->ps_name == NULL) {
  958.         gs_free((char *)font, sizeof(x11fontmap), 1, "gdev_x_fontmap");
  959.         continue;
  960.         }
  961.         strncpy(font->ps_name, ps_name, ps_name_len);
  962.         font->ps_name[ps_name_len] = '\0';
  963.         font->x11_name = (char *)gs_malloc(sizeof(char), x11_name_len,
  964.                            "gdev_x_setup_fontmap");
  965.         if (font->x11_name == NULL) {
  966.         gs_free(font->ps_name, sizeof(char), strlen(font->ps_name)+1,
  967.             "gdev_x_font_psname");
  968.         gs_free((char *)font, sizeof(x11fontmap), 1, "gdev_x_fontmap");
  969.         continue;
  970.         }
  971.         strncpy(font->x11_name, x11_name, x11_name_len-1);
  972.         font->x11_name[x11_name_len-1] = '\0';
  973.         font->std_names = NULL;
  974.         font->iso_names = NULL;
  975.         font->std_count = -1;
  976.         font->iso_count = -1;
  977.         font->next = xdev->dingbat_fonts;
  978.         xdev->dingbat_fonts = font;
  979.     }
  980.     }
  981. }
  982.