- Adding a driver
- Keeping things simple
- Driver structure
- Coordinates and types
- Coding conventions
- Printer drivers
- Driver procedures
For other information, see the Ghostscript overview and the documentation on how to build Ghostscript.
To add a driver to Ghostscript, first pick a name for your device, say "smurf". (Device names must be 1 to 8 characters, begin with a letter, and consist only of letters, digits, and underscores. Case is significant: all current device names are lower case.) Then all you need do is edit contrib.mak in two places.
Suppose the files containing the smurf driver are called "joe" and "fred". Then you should add the following lines:
# ------ The SMURF device ------ # smurf_=$(GLOBJ)joe.$(OBJ) $(GLOBJ)fred.$(OBJ) $(DD)smurf.dev: $(smurf_) $(SETDEV) $(DD)smurf $(smurf_) $(GLOBJ)joe.$(OBJ) : $(GLSRC)joe.c $(GLCC) $(GLO_)joe.$(OBJ) $(C_) $(GLSRC)joe.c $(GLOBJ)fred.$(OBJ) : $(GLSRC)fred.c $(GLCC) $(GLO_)fred.$(OBJ) $(C_) $(GLSRC)fred.c
and whatever joe.c and fred.c depend on. If the smurf driver also needs special libraries, for instance a library named "gorf", then the entry should look like this:
$(DD)smurf.dev : $(smurf_) $(SETDEV) $(DD)smurf $(smurf_) $(ADDMOD) $(DD)smurf -lib gorf
If, as will usually be the case, your driver is a printer driver (as discussed below), the device entry should look like this:
$(DD)smurf.dev : $(smurf_) $(GLD)page.dev $(SETPDEV) $(DD)smurf $(smurf_)
or
$(DD)smurf.dev : $(smurf_) $(GLD)page.dev $(SETPDEV) $(DD)smurf $(smurf_) $(ADDMOD) $(DD)smurf -lib gorf
Note that the space before the :, and the explicit compilation rules for the .c files, are required for portability,
If you want to add a simple device (specifically, a monochrome printer), you probably don't need to read the rest of this document; just use the code in an existing driver as a guide. The Epson and Canon BubbleJet drivers gdevepsn.c and gdevbj10.c are good models for dot-matrix printers, which require presenting the data for many scan lines at once; the DeskJet/LaserJet drivers in gdevdjet.c are good models for laser printers, which take a single scan line at a time but support data compression. For color printers, there are unfortunately no good models: the two major color inkjet printer drivers, gdevcdj.c and gdevstc.c, are far too complex to read.
On the other hand, if you're writing a driver for some more esoteric device, you probably do need at least some of the information in the rest of this document. It might be a good idea for you to read it in conjunction with one of the existing drivers.
Duplication of code, and sheer volume of code, is a serious maintenance and distribution problem for Ghostscript. If your device is similar to an existing one, try to implement your driver by adding some parameterization to an existing driver rather than by copying code to create an entirely new source module. gdevepsn.c and gdevdjet.c are good examples of this approach.
A device is represented by a structure divided into three parts:
Normally the procedure structure is defined and initialized at compile time. A prototype of the parameter structure (including both generic and device-specific parameters) is defined and initialized at compile time, but is copied and filled in when an instance of the device is created. Both of these structures should be declared as const, but for backward compatibility reasons the latter is not.
The gx_device_common macro defines the common structure elements, with the intent that devices define and export a structure along the following lines. Do not fill in the individual generic parameter values in the usual way for C structures: use the macros defined for this purpose in gxdevice.h or, if applicable, gdevprn.h.
typedef struct smurf_device_s { gx_device_common; ... device-specific parameters ... } smurf_device; smurf_device gs_smurf_device = { ... macro for generic parameter values ..., { ... procedures ... }, /* std_procs */ ... device-specific parameter values if any ... };
The device structure instance must have the name gs_smurf_device, where smurf is the device name used in contrib.mak. gx_device_common is a macro consisting only of the element definitions.
All the device procedures are called with the device as the first argument. Since each device type is actually a different structure type, the device procedures must be declared as taking a gx_device * as their first argument, and must cast it to smurf_device * internally. For example, in the code for the "memory" device, the first argument to all routines is called dev, but the routines actually use mdev to refer to elements of the full structure, using the following standard initialization statement at the beginning of each procedure:
gx_memory_device *const mdev = (gx_device_memory *)dev;
(This is a cheap version of "object-oriented" programming: in C++, for example, the cast would be unnecessary, and in fact the procedure table would be constructed by the compiler.)
You should consult the definition of struct gx_device_s in gxdevice.h for the complete details of the generic device structure. Some of the most important members of this structure for ordinary drivers are:
const char *dname; The device name bool is_open; True if device has been opened gx_device_color_info color_info; Color information int width; Width in pixels int height; Height in pixels
The name in the structure (dname) should be the same as the name in contrib.mak.
If for any reason you need to change the definition of the basic device structure, or to add procedures, you must change the following places:
- This document and the news document (if you want to keep the documentation up to date).
- The definition of gx_device_common and the procedures in gxdevcli.h.
- Possibly, the default forwarding procedures declared in gxdevice.h and implemented in gdevnfwd.c.
- The device procedure record completion routines in gdevdflt.c.
- Possibly, the default device implementation in gdevdflt.c, gdevddrw.c, and gxcmap.c.
- The bounding box device in gdevbbox.c (probably just adding NULL procedure entries if the new procedures don't produce output).
- These devices that must have complete (non-defaulted) procedure vectors:
- The null device in gdevnfwd.c.
- The command list "device" in gxclist.c. This is not an actual device; it only defines procedures.
- The "memory" devices in gdevmem.h and gdevm*.c.
- The halftoning device in gdevht.c.
- The clip list accumulation "device" in gxacpath.c.
- The clipping "devices" gxclip.c, gxclip2.c, and gxclipm.c.
- The pattern accumulation "device" in gxpcmap.c.
- The hit detection "device" in gdevhit.c.
- The generic printer device macros in gdevprn.h.
- The generic printer device code in gdevprn.c.
- The RasterOp source device in gdevrops.c.
You may also have to change the code for gx_default_get_params or gx_default_put_params in gsdparam.c.
You should not have to change any of the real devices in the standard Ghostscript distribution (listed in devs.mak and contrib.mak) or any of your own devices, because all of them are supposed to use the macros in gxdevice.h or gdevprn.h to define and initialize their state.
Since each driver specifies the initial transformation from user coordinates to device coordinates, the driver can use any coordinate system it wants, as long as a device coordinate will fit in an int. (This is only an issue on DOS systems, where ints are only 16 bits. User coordinates are represented as floats.) Most current drivers use a coordinate system with (0,0) in the upper left corner, with X increasing to the right and Y increasing toward the bottom. However, there is supposed to be nothing in the rest of Ghostscript that assumes this, and indeed some drivers use a coordinate system with (0,0) in the lower left corner.
Drivers must check (and, if necessary, clip) the coordinate parameters given to them: they should not assume the coordinates will be in bounds. The fit_fill and fit_copy macros in gxdevice.h are very helpful in doing this.
Ghostscript represents colors internally as RGB or CMYK values. In communicating with devices, however, it assumes that each device has a palette of colors identified by integers (to be precise, elements of type gx_color_index). Drivers may provide a uniformly spaced gray ramp or color cube for halftoning, or they may do their own color approximation, or both.
The color_info member of the device structure defines the color and gray-scale capabilities of the device. Its type is defined as follows:
typedef struct gx_device_color_info_s { int num_components; /* 1 = gray only, 3 = RGB, */ /* 4 = CMYK */ int depth; /* # of bits per pixel */ gx_color_value max_gray; /* # of distinct gray levels -1 */ gx_color_value max_rgb; /* # of distinct color levels -1 */ /* (only relevant if num_comp. > 1) */ gx_color_value dither_gray; /* size of gray ramp for halftoning */ gx_color_value dither_rgb; /* size of color cube ditto */ /* (only relevant if num_comp. > 1) */ } gx_device_color_info;
The following macros (in gxdevice.h) provide convenient shorthands for initializing this structure for ordinary black-and-white or color devices:
#define dci_black_and_white ...
#define dci_color(depth,maxv,dither) ...
The idea is that a device has a certain number of gray levels (max_gray+1) and a certain number of colors (max_rgb+1) that it can produce directly. When Ghostscript wants to render a given RGB or CMYK color as a device color, it first tests whether the color is a gray level (if num_components is 1, it converts all colors to gray levels), and if so:
If max_gray is large (>= 31), Ghostscript asks the device to approximate the gray level directly. If the device returns a valid gx_color_index, Ghostscript uses it. Otherwise, Ghostscript assumes that the device can represent dither_gray distinct gray levels, equally spaced along the diagonal of the color cube, and uses the two nearest ones to the desired color for halftoning.
If the color is not a gray level:
If max_rgb is large (>= 31), Ghostscript asks the device to approximate the color directly. If the device returns a valid gx_color_index, Ghostscript uses it. Otherwise, Ghostscript assumes that the device can representdither_rgb × dither_rgb × dither_rgbdistinct colors, equally spaced throughout the color cube, and uses two of the nearest ones to the desired color for halftoning.
Here is a brief explanation of the various types that appear as parameters or results of the drivers.
typedef unsigned long gx_color_index;
/* * Structure for describing stored bitmaps. * Bitmaps are stored bit-big-endian (i.e., the 2^7 bit of the first * byte corresponds to x=0), as a sequence of bytes (i.e., you can't * do word-oriented operations on them if you're on a little-endian * platform like the Intel 80x86 or VAX). Each scan line must start on * a (32-bit) word boundary, and hence is padded to a word boundary, * although this should rarely be of concern, since the raster and width * are specified individually. The first scan line corresponds to y=0 * in whatever coordinate system is relevant. * * For bitmaps used as halftone tiles, we may replicate the tile in * X and/or Y, but it is still valuable to know the true tile dimensions * (i.e., the dimensions prior to replication). Requirements: * width % rep_width = 0 * height % rep_height = 0 * * For halftones at arbitrary angles, we provide for storing the halftone * data as a strip that must be shifted in X for different values of Y. * For an ordinary (non-shifted) halftone that has a repetition width of * W and a repetition height of H, the pixel at coordinate (X,Y) * corresponds to halftone pixel (X mod W, Y mod H), ignoring phase; * for a shifted halftone with shift S, the pixel at (X,Y) corresponds * to halftone pixel ((X + S * floor(Y/H)) mod W, Y mod H). Requirements: * strip_shift < rep_width * strip_height % rep_height = 0 * shift = (strip_shift * (size.y / strip_height)) % rep_width */ typedef struct gx_strip_bitmap_s { byte *data; int raster; /* bytes per scan line */ gs_int_point size; /* width, height */ gx_bitmap_id id; ushort rep_width, rep_height; /* true size of tile */ ushort strip_height; ushort strip_shift; ushort shift; } gx_strip_bitmap;
All the driver procedures defined below that return int results return 0 on success, or an appropriate negative error code in the case of error conditions. The error codes are defined in gserrors.h; they correspond directly to the errors defined in the PostScript language reference manuals. The most common ones for drivers are:
- gs_error_invalidfileaccess
- An attempt to open a file failed.
- gs_error_ioerror
- An error occurred in reading or writing a file.
- gs_error_limitcheck
- An otherwise valid parameter value was too large for the implementation.
- gs_error_rangecheck
- A parameter was outside the valid range.
- gs_error_VMerror
- An attempt to allocate memory failed. (If this happens, the procedure should release all memory it allocated before it returns.)
If a driver does return an error, rather than a simple return statement it should use the return_error macro defined in gx.h, which is automatically included by gdevprn.h but not by gserrors.h. For example
return_error(gs_error_VMerror);
While most drivers (especially printer drivers) follow a very similar template, there is one important coding convention that is not obvious from reading the code for existing drivers: driver procedures must not use malloc to allocate any storage that stays around after the procedure returns. Instead, they must use gs_malloc and gs_free, which have slightly different calling conventions. (The prototypes for these are in gsmemory.h, which is included in gx.h, which is included in gdevprn.h.) This is necessary so that Ghostscript can clean up all allocated memory before exiting, which is essential in environments that provide only single-address-space multi-tasking (some versions of Microsoft Windows).
char *gs_malloc(uint num_elements, uint element_size, const char *client_name);
Like calloc, but unlike malloc, gs_malloc takes an element count and an element size. For structures, num_elements is 1 and element_size is sizeof the structure; for byte arrays, num_elements is the number of bytes and element_size is 1. Unlike calloc, gs_malloc does not clear the block of storage.
The client_name is used for tracing and debugging. It must be a real string, not NULL. Normally it is the name of the procedure in which the call occurs.
void gs_free(char *data, uint num_elements, uint element_size, const char *client_name);
Unlike free, gs_free demands that num_elements and element_size be supplied. It also requires a client name, like gs_malloc.
All driver instances allocated by Ghostscript's standard allocator must point to a "structure descriptor" that tells the garbage collector how to trace pointers in the structure. For drivers registered in the normal way (using the makefile approach described above), no special care is needed as long as instances are created only by calling the gs_copydevice procedure defined in gsdevice.h. If you have a need to define devices that are not registered in this way, you must fill in the stype member in any dynamically allocated instances with a pointer to the same structure descriptor used to allocate the instance. For more information about structure descriptors, see gsmemory.h and gsstruct.h.
Printer drivers (which include drivers that write some kind of raster file) are especially simple to implement. Of the driver procedures defined in the next section, they only need implement two: map_rgb_color (or map_cmyk_color) and map_color_rgb. In addition, they must implement a print_page or print_page_copies procedure. There are macros in gdevprn.h that generate the device structure for such devices, of which the simplest is prn_device; for an example, see gdevbj10.c. If you are writing a printer driver, we suggest you start by reading gdevprn.h and the subsection on "Color mapping" below; you may be able to ignore all the rest of the driver procedures.
The print_page procedures are defined as follows:
int (*print_page)(P2(gx_device_printer *, FILE *)) int (*print_page_copies)(P3(gx_device_printer *, FILE *, int))
This procedure must read out the rendered image from the device and write whatever is appropriate to the file. To read back one or more scan lines of the image, the print_page procedure must call one of the following procedures:
int gdev_prn_copy_scan_lines(P4(gx_device_printer *pdev, int y, byte *str, uint size)
For this procedure, str is where the data should be copied to, and size is the size of the buffer starting at str. This procedure returns the number of scan lines copied, or <0 for an error. str need not be aligned.
int gdev_prn_get_bits(gx_device_printer *pdev, int y, byte *str, byte **actual_data)
This procedure reads out exactly one scan line. If the scan line is available in the correct format already, *actual_data is set to point to it; otherwise, the scan line is copied to the buffer starting at str, and *actual_data is set to str. This saves a copying step most of the time. str need not be aligned; however, if *actual_data is set to point to an existing scan line, it will be aligned. (See the description of the get_bits procedure below for more details.)
In either case, each row of the image is stored in the form described in the comment under gx_tile_bitmap above; each pixel takes the number of bits specified as color_info.depth in the device structure, and holds values returned by the device's map_{rgb,cmyk}_color procedure.
The print_page procedure can determine the number of bytes required to hold a scan line by calling:
uint gdev_prn_raster(P1(gx_device_printer *))
For a very simple concrete example, we suggest reading the code in bit_print_page in gdevbit.c.
If the device provides print_page, Ghostscript will call print_page the requisite number of times to print the desired number of copies; if the device provides print_page_copies, Ghostscript will call print_page_copies once per page, passing it the desired number of copies.
Most of the procedures that a driver may implement are optional. If a device doesn't supply an optional procedure WXYZ, the entry in the procedure structure may be either gx_default_WXYZ, for instance gx_default_tile_rectangle, or NULL or 0. (The device procedure must also call the gx_default_ procedure if it doesn't implement the function for particular values of the arguments.) Since C compilers supply 0 as the value for omitted structure elements, this convention means that statically initialized procedure structures continue to work even if new (optional) members are added.
A device instance begins life in a closed state. In this state, no output operations will occur. Only the following procedures may be called:
open_device
finish_copydevice
get_initial_matrix
get_params
put_params
get_hardware_params
When setdevice installs a device instance in the graphics state, it checks whether the instance is closed or open. If the instance is closed, setdevice calls the open routine, and then sets the state to open. There is currently no user-accessible operation to close a device instance. Device instances are only closed when they are about to be freed, which occurs in three situations:
xx = x_pixels_per_inch/72, xy = 0,
yx = 0, yy = -y_pixels_per_inch/72,
tx = 0, ty = height.
A given driver normally implements either map_rgb_color or map_cmyk_color, but not both. Black-and-white drivers need implement neither. Note that the map_xxx_color procedures must not return gx_no_color_index (all 1s).
Note that code in the Ghostscript library may cache the results of calling one or more of the color mapping procedures. If the result returned by any of these procedures would change (other than as a result of a change made by the driver's put_params procedure), the driver must call gx_device_decache_colors(dev).
Ghostscript assumes that for devices that have color capability (that is, color_info.num_components > 1), map_rgb_color returns a color index for a gray level (as opposed to a non-gray color) iff red = green = blue.
Ghostscript assumes that for devices that have color capability (that is, color_info.num_components > 1), map_cmyk_color returns a color index for a gray level (as opposed to a non-gray color) iff cyan = magenta = yellow.
Note that if a driver implements map_rgb_alpha_color, it must also implement map_rgb_color, and must implement them in such a way that map_rgb_alpha_color(dev, r, g, b, gx_max_color_value) returns the same value as map_rgb_color(dev, r, g, b).
Note that if a driver implements map_color_rgb_alpha, it must also implement map_color_rgb, and must implement them in such a way that the first 3 values returned by map_color_rgb_alpha are the same as the values returned by map_color_rgb.
Note that CMYK devices currently do not support variable opacity; alpha is ignored on such devices.
This group of drawing operations specifies data at the pixel level. All drawing operations use device coordinates and device color values.
Note that fill_rectangle is the only non-optional procedure in the driver interface.
Bitmap (or pixmap) images are stored in memory in a nearly standard way. The first byte corresponds to (0,0) in the image coordinate system: bits (or polybit color values) are packed into it left to right. There may be padding at the end of each scan line: the distance from one scan line to the next is always passed as an explicit argument.
This operation, with color0 = gx_no_color_index, is the workhorse for text display in Ghostscript, so implementing it efficiently is very important.
If color0 and color1 are both gx_no_color_index, then the tile is a color pixmap, not a bitmap: see the next section.
This operation is the workhorse for halftone filling in Ghostscript, so implementing it efficiently for solid tiles (that is, where either color0 and color1 are both gx_no_color_index, for colored halftones, or neither one is gx_no_color_index, for monochrome halftones) is very important.
Pixmaps are just like bitmaps, except that each pixel occupies more than one bit. All the bits for each pixel are grouped together (this is sometimes called "chunky" or "Z" format). For copy_color, the number of bits per pixel is given by the color_info.depth parameter in the device structure: the legal values are 1, 2, 4, 8, 16, 24, or 32. The pixel values are device color codes (that is, whatever it is that map_rgb_color returns).
We do not provide a separate procedure for tiling with a pixmap; instead, tile_rectangle can also take colored tiles. This is indicated by the color0 and color1 arguments' both being gx_no_color_index. In this case, as for copy_color, the raster and height in the "bitmap" are interpreted as for real bitmaps, but the x and width are in pixels, not bits.
In addition to direct writing of opaque pixels, devices must also support compositing. Currently two kinds of compositing are defined (RasterOp and alpha-based), but more may be added in the future.
THIS AREA OF THE INTERFACE IS SOMEWHAT UNSTABLE: USE AT YOUR OWN RISK.
Fill a given region with a given color modified by an individual alpha value for each pixel. For each pixel, this is equivalent to alpha-compositing with a source pixel whose alpha value is obtained from the pixmap (data, data_x, and raster) and whose color is the given color (which has not been premultiplied by the alpha value), using the Sover rule. depth, the number of bits per alpha value, is either 2 or 4, and in any case is always a value returned by a previous call on the get_alpha_bits procedure. Note that if get_alpha_bits always returns 1, this procedure will never be called.
Other kinds of forwarding devices, which don't fall into any of these categories, require special treatment. In principle, what they do is ask their target to create a compositor, and then create and return a copy of themselves with the target's new compositor as the target of the copy. There is a possible default implementation of this approach: if the original device was D with target T, and T creates a compositor C, then the default implementation creates a device F that for each operation temporarily changes D's target to C, forwards the operation to D, and then changes D's target back to T. However, the Ghostscript library currently only creates a compositor with an imaging forwarding device as target in a few specialized situations (banding, and bounding box computation), and these are handled as special cases.
Note that the compositor may have a different color space, color representation, or bit depth from the device to which it is compositing. For example, alpha-compositing devices use standard-format chunky color even if the underlying device doesn't.
Closing a compositor frees all of its storage, including the compositor itself. However, since the create_compositor call may return the same device, clients must check for this case, and only call the close procedure if a separate device was created.
[strip_]copy_rop WILL BE SUPERSEDED BY COMPOSITORS
dev the device, as for all driver procedures sdata, sourcex, sraster, id, scolors specify S, see below texture, tcolors specify T, see below x, y, width, height as for the other copy and fill procedures phase_x, phase_y part of T specification, see below command see below
As noted above, the source S may be a solid color, a bitmap, or a pixmap. If S is a solid color:
If S is a bitmap:
If S is a pixmap:
Note that if the source is a bitmap with background=0 and foreground=1, and the destination is 1 bit deep, then the source can be treated as a pixmap (scolors=NULL).
Similar to the source, the texture T may be a solid color, a bitmap, or a pixmap. If T is a solid color:
If T is a bitmap:
If T is a pixmap:
Again, if the texture is a bitmap with background=0 and foreground=1, and the destination depth is 1, the texture bitmap can be treated as a pixmap (tcolors=NULL).
Note that while a source bitmap or pixmap has the same width and height as the destination, a texture bitmap or pixmap has its own width and height specified in the gx_tile_bitmap structure, and is replicated or clipped as needed.
"Command" indicates the raster operation and transparency as follows:
Bits 7-0 raster op 8 0 if source opaque, 1 if source transparent 9 0 if texture opaque, 1 if texture transparent ?-10 unused, must be 0
The raster operation follows the Microsoft and H-P specification. It is an 8-element truth table that specifies the output value for each of the possible 2×2×2 input values as follows:
Bit Texture Source Destination
7 1 1 1 6 1 1 0 5 1 0 1 4 1 0 0 3 0 1 1 2 0 1 0 1 0 0 1 0 0 0 0
Transparency affects the output in the following way. A source or texture pixel is considered transparent if its value is all 1s (for instance, 1 for bitmaps, 0xffffff for 24-bit RGB pixmaps) and the corresponding transparency bit is set in the command. For each pixel, the result of the Boolean operation is written into the destination iff neither the source nor the texture pixel is transparent. (Note that the H-P RasterOp specification, on which this is based, specifies that if the source and texture are both all 1s and the command specifies transparent source and opaque texture, the result should be written in the output. We think this is an error in the documentation.)
copy_rop is defined to operate on pixels in RGB space, again following the H-P and Microsoft specification. For devices that don't use RGB (or gray-scale with black = 0, white = all 1s) as their native color representation, the implementation of copy_rop must convert to RGB or gray space, do the operation, and convert back (or do the equivalent of this). Here are the copy_rop equivalents of the most important previous imaging calls. We assume the declaration:
static const gx_color_index white2[2] = { 1, 1 };
Note that rop3_S may be replaced by any other Boolean operation. For monobit devices, we assume that black = 1.
/* For all devices: */ (*fill_rectangle)(dev, x, y, w, h, color) ==> { gx_color_index colors[2]; colors[0] = colors[1] = color; (*dev_proc(dev, copy_rop))(dev, NULL, 0, 0, gx_no_bitmap_id, colors, NULL, colors /*irrelevant*/, x, y, w, h, 0, 0, rop3_S); } /* For black-and-white devices only: */ (*copy_mono)(dev, base, sourcex, sraster, id, x, y, w, h, (gx_color_index)0, (gx_color_index)1) ==> (*dev_proc(dev, copy_rop))(dev, base, sourcex, sraster, id, NULL, NULL, white2 /*irrelevant*/, x, y, w, h, 0, 0, rop3_S); /* For color devices, where neither color0 nor color1 is gx_no_color_index: */ (*copy_mono)(dev, base, sourcex, sraster, id, x, y, w, h, color0, color1) ==> { gx_color_index colors[2]; colors[0] = color0, colors[1] = color1; (*dev_proc(dev, copy_rop))(dev, base, sourcex, sraster, id, colors, NULL, white2 /*irrelevant*/, x, y, w, h, 0, 0, rop3_S); } /* For black-and-white devices only: */ (*copy_mono)(dev, base, sourcex, sraster, id, x, y, w, h, gx_no_color_index, (gx_color_index)1) ==> (*dev_proc(dev, copy_rop))(dev, base, sourcex, sraster, id, NULL, NULL, white2 /*irrelevant*/, x, y, w, h, 0, 0, rop3_S | lop_S_transparent); /* For all devices: */ (*copy_color)(dev, base, sourcex, sraster, id, x, y, w, h) ==> [same as first copy_mono above] /* For black-and-white devices only: */ (*tile_rectangle)(dev, tile, x, y, w, h, (gx_color_index)0, (gx_color_index)1, px, py) ==> (*dev_proc(dev, copy_rop))(dev, NULL, 0, 0, gx_no_bitmap_id, white2 /*irrelevant*/, tile, NULL, x, y, w, h, px, py, rop3_T)
In addition to the pixel-level drawing operations that take integer device coordinates and pure device colors, the driver interface includes higher-level operations that draw polygons using fixed-point coordinates, possibly halftoned colors, and possibly a non-default logical operation.
The fill_* drawing operations all use the center-of-pixel rule: a pixel is colored iff its center falls within the polygonal region being filled. If a pixel center (X+0.5,Y+0.5) falls exactly on the boundary, the pixel is filled iff the boundary is horizontal and the filled region is above it, or the boundary is not horizontal and the filled region is to the right of it.
In addition to the lower-level drawing operations described above, the driver interface provides a set of high-level operations. Normally these will have their default implementation, which converts the high-level operation to the low-level ones just described; however, drivers that generate high-level output formats such as CGM, or communicate with devices that have firmware for higher-level operations such as polygon fills, may implement these high-level operations directly. For more details, please consult the source code, specifically:
Header Defines gxpaint.h gx_fill_params, gx_stroke_params gxfixed.h fixed, gs_fixed_point (used by gx_*_params) gxistate.h gs_imager_state (used by gx_*_params) gxline.h gx_line_params (used by gs_imager_state) gslparam.h line cap/join values (used by gx_line_params) gxmatrix.h gs_matrix_fixed (used by gs_imager_state) gspath.h, gxpath.h, gzpath.h gx_path gxcpath.h, gzcpath.h gx_clip_path
For a minimal example of how to implement the high-level drawing operations, see gdevtrac.c.
Similar to the high-level interface for fill and stroke graphics, a high-level interface exists for bitmap images. The procedures in this part of the interface are optional.
Bitmap images come in a variety of types, corresponding closely (but not precisely) to the PostScript ImageTypes. The generic or common part of all bitmap images is defined by:
typedef struct { const gx_image_type_t *type; gs_matrix ImageMatrix; } gs_image_common_t;
Bitmap images that supply data (all image types except image_type_from_device (2)) are defined by:
#define gs_image_max_components 5 typedef struct { << gs_image_common_t >> int Width; int Height; int BitsPerComponent; float Decode[gs_image_max_components * 2]; bool Interpolate; } gs_data_image_t;
Images that supply pixel (as opposed to mask) data are defined by:
typedef enum { /* Single plane, chunky pixels. */ gs_image_format_chunky = 0, /* num_components planes, chunky components. */ gs_image_format_component_planar = 1, /* BitsPerComponent * num_components planes, 1 bit per plane */ gs_image_format_bit_planar = 2 } gs_image_format_t; typedef struct { << gs_data_image_t >> const gs_color_space *ColorSpace; bool CombineWithColor; } gs_pixel_image_t;
Ordinary PostScript Level 1 or Level 2 (ImageType 1) images are defined by:
typedef enum { /* No alpha. */ gs_image_alpha_none = 0, /* Alpha precedes color components. */ gs_image_alpha_first, /* Alpha follows color components. */ gs_image_alpha_last } gs_image_alpha_t; typedef struct { << gs_pixel_image_t >> bool ImageMask; bool adjust; gs_image_alpha_t Alpha; } gs_image1_t; typedef gs_image1_t gs_image_t;
Of course, standard PostScript images don't have an alpha component. For more details, consult the source code in gsiparam.h and gsiparm*.h, which define parameters for an image.
The begin[_typed_]image driver procedures create image enumeration structures. The common part of these structures consists of:
typedef struct gx_image_enum_common_s { const gx_image_type_t *image_type; const gx_image_enum_procs_t *procs; gx_device *dev; gs_id id; int num_planes; int plane_depths[gs_image_max_planes]; /* [num_planes] */ int plane_widths[gs_image_max_planes] /* [num_planes] */ } gx_image_enum_common_t;
where procs consists of:
typedef struct gx_image_enum_procs_s { /* * Pass the next batch of data for processing. */ #define image_enum_proc_plane_data(proc)\ int proc(P4(gx_device *dev,\ gx_image_enum_common_t *info, const gx_image_plane_t *planes,\ int height)) image_enum_proc_plane_data((*plane_data)); /* * End processing an image, freeing the enumerator. */ #define image_enum_proc_end_image(proc)\ int proc(P3(gx_device *dev,\ gx_image_enum_common_t *info, bool draw_last)) image_enum_proc_end_image((*end_image)); /* * Flush any intermediate buffers to the target device. * We need this for situations where two images interact * (currently, only the mask and the data of ImageType 3). * This procedure is optional (may be 0). */ #define image_enum_proc_flush(proc)\ int proc(P1(gx_image_enum_common_t *info)) image_enum_proc_flush((*flush)); } gx_image_enum_procs_t;
In other words, begin[_typed]_image sets up an enumeration structure that contains the procedures that will process the image data, together with all variables needed to maintain the state of the process. Since this is somewhat tricky to get right, if you plan to create one of your own you should probably read an existing implementation of begin[_typed]_image, such as the one in gdevbbox.c or gdevps.c.
The data passed at each call of image_plane_data consists of one or more planes, as appropriate for the type of image. begin[_typed]_image must initialize the plane_depths array in the enumeration structure with the depths (bits per element) of the planes. The array of gx_image_plane_t structures passed to each call of image_plane_data then defines where the data are stored, as follows:
typedef struct gx_image_plane_s { const byte *data; int data_x; uint raster; } gx_image_plane_t;
pis pointer to an imager state. The only relevant elements of the imager state are the CTM (coordinate transformation matrix), the logical operation (RasterOp or transparency), and the color rendering information. pim pointer to the gs_image_t structure that defines the image parameters format defines how pixels are represented for image_plane_data. See the description of image_plane_data below prect if not NULL, defines a subrectangle of the image; only the data for this subrectangle will be passed to image_plane_data, and only this subrectangle should be drawn pdcolor defines a drawing color, only needed for masks or if CombineWithColor is true pcpath if not NULL, defines an optional clipping path memory defines the allocator to be used for allocating bookkeeping information pinfo the implementation should return a pointer to its state structure here
begin_image is expected to allocate a structure for its bookkeeping needs, using the allocator defined by the memory parameter, and return it in *pinfo. begin_image should not assume that the structures in *pim, *prect, or *pdcolor will survive the call on begin_image (except for the color space in *pim->ColorSpace): it should copy any necessary parts of them into its own bookkeeping structure. It may, however, assume that *pis, *pcpath, and of course *memory will live at least until end_image is called.
begin_image returns 0 normally, or 1 if the image does not need any data. In the latter case, begin_image does not allocate an enumeration structure.
The actual transmission of data uses the procedures in the enumeration structure, not driver procedures, since the handling of the data usually depends on the image type and parameters rather than the device. These procedures are specified as follows.
The data for each row are packed big-endian within each byte, as for copy_color. The data_x (starting X position within the row) and raster (number of bytes per row) are specified separately for each plane, and may include some padding at the beginning or end of each row. Note that for non-mask images, the input data may be in any color space and may have any number of bits per component (1, 2, 4, 8, 12); currently mask images always have 1 bit per component, but in the future, they might allow multiple bits of alpha. Note also that each call of image_plane_data passes complete pixels: for example, for a chunky image with 24 bits per pixel, each call of image_plane_data passes 3N bytes of data (specifically, 3 × Width × height).
The interpretation of planes depends on the format member of the gs_image[_common]_t structure:
If, as a result of this call, image_plane_data has been called with all the data for the (sub-)image, it returns 1; otherwise, it returns 0 or an error code as usual.
image_plane_data, unlike most other procedures that take bitmaps as arguments, does not require the data to be aligned in any way.
Note that for some image types, different planes may have different numbers of bits per pixel, as defined in the plane_depths array.
While there will almost never be more than one image enumeration in progress -- that is, after a begin_image, end_image will almost always be called before the next begin_image -- driver code should not rely on this property; in particular, it should store all information regarding the image in the info structure, not in the driver structure.
Note that if begin_[typed_]image saves its parameters in the info structure, it can decide on each call whether to use its own algorithms or to use the default implementation. (It may need to call gx_default_begin/end_image partway through.) [A later revision of this document may include an example here.]
The third high-level interface handles text. As for images, the interface is based on creating an enumerator which then may execute the operation in multiple steps. As for the other high-level interfaces, the procedures are optional.
dev The usual pointer to the device. pis A pointer to an imager state. All elements may be relevant, depending on how the text is rendered. text A pointer to the structure that defines the text operation and parameters. See gstext.h for details. font Defines the font for drawing. path Defines the path where the character outline will be appended (if the text operation includes TEXT_DO_...PATH), and whose current point indicates where drawing should occur and will be updated by the string width (unless the text operation includes TEXT_DO_NONE). pdcolor Defines the drawing color for the text. Only relevant if the text operation includes TEXT_DO_DRAW. pcpath If not NULL, defines an optional clipping path. Only relevant if the text operation includes TEXT_DO_DRAW. memory Defines the allocator to be used for allocating bookkeeping information. ppte The implementation should return a pointer to its state structure here.
text_begin must allocate a structure for its bookkeeping needs, using the allocator defined by the memory parameter, and return it in *ppte. text_begin may assume that the structures passed as parameters will survive until text processing is complete.
Clients should not call the driver text_begin procedure directly. Instead, they should call gx_device_text_begin, which takes the same parameters and also initializes certain common elements of the text enumeration structure, or gs_text_begin, which takes many of the parameters from a graphics state structure. For details, see gstext.h.
The actual processing of text uses the procedures in the enumeration structure, not driver procedures, since the handling of the text may depend on the font and parameters rather than the device. Text processing may also require the client to take action between characters, either because the client requested it (TEXT_INTERVENE in the operation) or because rendering a character requires suspending text processing to call an external package such as the PostScript interpreter. (It is a deliberate design decision to handle this by returning to the client, rather than calling out of the text renderer, in order to avoid potentially unknown stack requirements.) Specifically, the client must call the following procedures, which in turn call the procedures in the text enumerator.
TEXT_PROCESS_RENDER The client must cause the current character to be rendered. This currently only is used for PostScript Type 0-4 fonts and their CID-keyed relatives. TEXT_PROCESS_INTERVENE The client has asked to intervene between characters. This is used for cshow and kshow.
There are numerous other procedures that clients may call during text processing. See gstext.h for details.
Note that unlike many other optional procedures, the default implementation of text_begin cannot simply return: like the default implementation of begin[_typed]_image, it must create and return an enumerator. Furthermore, the implementation of the process procedure (in the enumerator structure, called by gs_text_process) cannot simply return without doing anything, even if it doesn't want to draw anything on the output. See the comments in gxtext.h for details.
options | the allowable formats for returning the data | |
data[32] | pointers to the returned data | |
x_offset | the X offset of the first returned pixel in data | |
raster | the distance between scan lines in the returned data |
options is a bit mask specifying what formats the client is willing to accept. (If the client has more flexibility, the implementation may be able to return the data more efficiently, by avoiding representation conversions.) The options are divided into groups.
- alignment
- Specifies whether the returned data must be aligned in the normal manner for bitmaps, or whether unaligned data are acceptable.
- pointer or copy
- Specifies whether the data may be copied into storage provided by the client and/or returned as pointers to existing storage. (Note that if copying is not allowed, it is much more likely that the implementation will return an error, since this requires that the client accept the data in the implementation's internal format.)
- X offset
- Specifies whether the returned data must have a specific X offset (usually zero, but possibly other values to avoid skew at some later stage of processing) or whether it may have any X offset (which may avoid skew in the get_bits_rectangle operation itself).
- raster
- Specifies whether the raster (distance between returned scan lines) must have its standard value, must have some other specific value, or may have any value. The standard value for the raster is the device width padded out to the alignment modulus when using pointers, or the minimum raster to accommodate the X offset + width when copying (padded out to the alignment modulus if standard alignment is required).
- format
- Specifies whether the data are returned in chunky (all components of a single pixel together), component-planar (each component has its own scan lines), or bit-planar (each bit has its own scan lines) format.
- color space
- Specifies whether the data are returned as native device pixels, or in a standard color space. Currently the only supported standard space is RGB.
- standard component depth
- Specifies the number of bits per component if the data are returned in the standard color space. (Native device pixels use dev->color_info.depth bits per pixel.)
- alpha
- Specifies whether alpha channel information should be returned as the first component, the last component, or not at all. Note that for devices that have no alpha capability, the returned alpha values will be all 1s.
The client may set more than one option in each of the above groups; the implementation will choose one of the selected options in each group to determine the actual form of the returned data, and will update params[].options to indicate the form. The returned params[].options will normally have only one option set per group.
For further details on params, see gxgetbit.h. For further details on options, see gxbitfmt.h.
Define w = prect->q.x - prect->p.x, h = prect->q.y - prect->p.y. If the bits cannot be read back (for example, from a printer), return gs_error_unknownerror; if raster bytes is not enough space to hold offset_x + w pixels, or if the source rectangle goes outside the device dimensions (p.x < 0 || p.y < 0 || q.x > dev->width || q.y > dev->height), return gs_error_rangecheck; if any regions could not be read, return gs_error_ioerror if unpainted is NULL, otherwise the number of rectangles (see below); otherwise return 0.
The caller supplies a buffer of raster × h bytes starting at data[0] for the returned data in chunky format, or N buffers of raster × h bytes starting at data[0] through data[N-1] in planar format where N is the number of components or bits. The contents of the bits beyond the last valid bit in each scan line (as defined by w) are unpredictable. data need not be aligned in any way. If x_offset is non-zero, the bits before the first valid bit in each scan line are undefined. If the implementation returns pointers to the data, it stores them into data[0] or data[0..N-1].
If not all the source data are available (for example, because the source was a partially obscured window and backing store was not available or not used), or if the rectangle does not fall completely within the device's coordinate system, any unread bits are undefined, and the value returned depends on whether unread is NULL. If unread is NULL, return gs_error_ioerror; in this case, some bits may or may not have been read. If unread is not NULL, allocate (using dev->memory) and fill in a list of rectangles that could not be read, store the pointer to the list in *unread, and return the number of rectangles; in this case, all bits not listed in the rectangle list have been read back properly. The list is not sorted in any particular order, but the rectangles do not overlap. Note that the rectangle list may cover a superset of the region actually obscured: for example, a lazy implementation could return a single rectangle that was the bounding box of the region.
(*get_bits_rectangle) (dev, {0, y, dev->width, y+1}, {(GB_ALIGN_ANY | (GB_RETURN_COPY | GB_RETURN_POINTER) | GB_OFFSET_0 | GB_RASTER_STANDARD | GB_FORMAT_CHUNKY | GB_COLORS_NATIVE | GB_ALPHA_NONE), {data}})
with the returned value of params->data[0] stored in *actual_data, and will in fact be implemented this way if the device defines a get_bits_rectangle procedure and does not define one for get_bits. (If actual_data is NULL, GB_RETURN_POINTER is omitted from the options.)
Devices may have an open-ended set of parameters, which are simply pairs consisting of a name and a value. The value may be of various types: integer (int or long), boolean, float, string, name, NULL, array of integer, array of float, or arrays or dictionaries of mixed types. For example, the Name of a device is a string; the Margins of a device is an array of two floats. See gsparam.h for more details.
If a device has parameters other than the ones applicable to all devices (or, in the case of printer devices, all printer devices), it must provide get_params and put_params procedures. If your device has parameters beyond those of a straightforward display or printer, we strongly advise using the _get_params and _put_params procedures in an existing device (for example, gdevcdj.c or gdevbit.c) as a model for your own code.
Drivers that want to provide one or more default CIE color rendering dictionaries (CRDs) can do so through get_params. To do this, they create the CRD in the usual way (normally using the gs_cie_render1_build and _initialize procedures defined in gscrd.h), and then write it as a parameter using param_write_cie_render1 defined in gscrdp.h. However, the TransformPQR procedure requires special handling. If the CRD uses a TransformPQR procedure different from the default (identity), the driver must do the following:
For a complete example, see the bit_get_params procedure in gdevbit.c. Note that it is essential that the driver return the CRD or the procedure address only if specifically requested (param_requested(...) > 0); otherwise, errors will occur.
Drivers may include the ability to display text. More precisely, they may supply a set of procedures that in turn implement some font and text handling capabilities, described in a separate document. The link between the two is the driver procedure that supplies the font and text procedures:
For technical reasons, a second procedure is also needed:
Copyright © 1996, 2000 Aladdin Enterprises. All rights reserved.
This file is part of AFPL Ghostscript. See the Aladdin Free Public License (the "License") for full details of the terms of using, copying, modifying, and redistributing AFPL Ghostscript.
Ghostscript version 7.03, 20 October 2001