home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 1996 February / PCWK0296.iso / sharewar / dos / program / gs300sr1 / gs300sr1.exe / GDEVXINI.C < prev    next >
C/C++ Source or Header  |  1994-07-27  |  30KB  |  899 lines

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