PostScript token C reference

These private services are declared in rbcPs.h and implemented in rbcPs.c. See PostScript output and drawing state for ownership and prolog requirements.

Persistent graph PostScript configuration

struct PostScript

Persistent graph PostScript options and computed page placement.

Tk option cleanup releases configured objects and resources. Export temporarily computes bounding-box and scale fields; the graph owns this record.

Public Members

Tk_OptionTable optionTable

Tk option table associated with this record; managed by its configuration lifecycle.

Tcl_Obj *colorModeObjPtr

Tk option-managed Tcl representation for color mode; released with option state.

Tcl_Obj *heightObjPtr

Tk option-managed Tcl representation for height; released with option state.

Tcl_Obj *padXObjPtr

Tk option-managed Tcl representation for pad x; released with option state.

Tcl_Obj *padYObjPtr

Tk option-managed Tcl representation for pad y; released with option state.

Tcl_Obj *paperHeightObjPtr

Tk option-managed Tcl representation for paper height; released with option state.

Tcl_Obj *paperWidthObjPtr

Tk option-managed Tcl representation for paper width; released with option state.

Tcl_Obj *previewFormatObjPtr

Tk option-managed Tcl representation for preview format; released with option state.

Tcl_Obj *widthObjPtr

Tk option-managed Tcl representation for width; released with option state.

int decorations

If non-zero, print graph with color background and 3D borders.

int reqWidth

Requested graph width in pixels; nonpositive values use the current graph size.

int reqHeight

Requested graph height in pixels; nonpositive values use the current graph size.

int reqPaperWidth

Requested page width in pixels before PostScript page conversion.

int reqPaperHeight

Requested page height in pixels before PostScript page conversion.

Rbc_Pad padX

Requested horizontal exterior padding in pixels.

Rbc_Pad padY

Requested vertical exterior padding in pixels.

PsColorMode colorMode

Selects the color mode for PostScript page (0=monochrome, 1=greyscale, 2=color).

char *colorVarName

If non-NULL, is the name of a Tcl array variable containing X to PostScript color translations.

char *fontVarName

If non-NULL, is the name of a Tcl array variable containing X to PostScript font translations.

int landscape

If non-zero, orient the page 90 degrees.

int center

If non-zero, center the graph on the page.

int maxpect

If non-zero, indicates to scale the graph so that it fills the page (maintaining the aspect ratio of the graph).

int addPreview

If non-zero, generate a preview image and add it to the PostScript output.

int footer

If non-zero, a footer with the title, date and user will be added to the PostScript output outside of the bounding box.

int previewFormat

Format of EPS preview: PS_PREVIEW_WMF, PS_PREVIEW_EPSI, or PS_PREVIEW_TIFF.

int left

Computed page bounding-box left coordinate.

int bottom

Computed page bounding-box bottom coordinate.

int right

Computed page bounding-box right coordinate.

int top

Computed page bounding-box top coordinate.

double pageScale

Scale of page.

Set if “-maxpect” option is set, otherwise 1.0.

Token allocation and borrowed buffers

group PostScript token lifetime and buffers

Private ownership and borrowed buffer accessors.

Functions

PsToken Rbc_GetPsToken(Tcl_Interp *interp, Tk_Window tkwin)

Allocate an empty, color-mode PostScript token.

The caller owns the token and releases it with Rbc_ReleasePsToken(). The interpreter and window are borrowed; this function does not preserve them. Font and color mapping variable names initially are NULL.

Parameters:
  • interp – [in] Interpreter borrowed for later diagnostics and mapping lookups; see Interpreter arguments.

  • tkwin – [in] Tk window borrowed for font, color and display information throughout token use.

void Rbc_ReleasePsToken(struct PsTokenStruct *tokenPtr)

Release a non-NULL token and its output buffer.

Borrowed interpreter, window and mapping variable names are not released. All pointers returned into the token become invalid.

Parameters:
  • tokenPtr – [in] Owned non-NULL token to release; all pointers into its buffers become invalid.

char *Rbc_PostScriptFromToken(struct PsTokenStruct *tokenPtr)

Return the borrowed, NUL-terminated output buffer.

Do not free the result. Appending output may relocate it; releasing the token invalidates it. This accessor does not finalize a document.

Parameters:
  • tokenPtr – [in] Live token whose output buffer is borrowed until the next relocating append or release.

char *Rbc_ScratchBufferFromToken(struct PsTokenStruct *tokenPtr)

Return borrowed mutable scratch storage of PSTOKEN_BUFSIZ + 1 bytes.

Formatting and prolog reads reuse this storage. It is not the output buffer and must not be retained across those operations or token release.

Parameters:
  • tokenPtr – [in] Live token whose reusable scratch storage is borrowed; contents are not initialized by this accessor.

Appending syntax and loading prologs

group PostScript syntax and prolog appending

Private append services; framing and delivery remain with the graph command.

Functions

void Rbc_AppendToPostScript(struct PsTokenStruct *tokenPtr, ...)

Append a sequence of NUL-terminated strings, ending with a NULL pointer.

Strings are copied without escaping. Callers supply PostScript syntax and must not pass binary data or pointers invalidated by output growth.

Parameters:
  • tokenPtr – [inout] Live borrowed PostScript token receiving output; caller owns document framing, prolog and lifetime.

  • ... – [in] NUL-terminated C strings followed by a pointer-valued NULL sentinel; strings must survive output growth.

void Rbc_FormatToPostScript(struct PsTokenStruct *tokenPtr, const char *fmt, ...)

Append printf-formatted PostScript, using scratch storage or a temporary allocation when the formatted result exceeds the scratch capacity.

This void helper does not report a formatting failure to the interpreter. It performs no PostScript string escaping.

Parameters:
  • tokenPtr – [inout] Live borrowed PostScript token receiving output; caller owns document framing, prolog and lifetime.

  • fmt – [in] Borrowed printf format, not aliased with scratch storage overwritten by formatting.

  • ... – [in] Arguments matching the format; referenced strings must remain readable during formatting and output growth.

void Rbc_AppendPostScriptString(PsToken psToken, const char *string, Tcl_Size length)

Append escaped PostScript literal-string contents from Tcl UTF text.

A negative length selects strlen; otherwise length is a byte count ending at a character boundary. NULL input is ignored. The caller supplies the surrounding parentheses. Delimiters, controls and non-ASCII characters use octal escapes; characters above ISO-8859-1 are replaced with a space.

Parameters:
  • psToken – [inout] Live borrowed PostScript token receiving output.

  • string – [in] Borrowed Tcl UTF text, or NULL to append nothing; must remain readable across output appends.

  • length – [in] UTF byte count ending at a character boundary, or negative to use strlen; not a character count.

int Rbc_FileToPostScript(struct PsTokenStruct *tokenPtr, char *fileName)

Append a text prolog from fileName relative to the rbc::library variable.

Return TCL_ERROR for library lookup, open or read failure, with an interpreter diagnostic; otherwise return TCL_OK. Partial output is not rolled back. The channel is closed, but its close status is not propagated. Reads overwrite token scratch storage. Tcl variable and channel operations may execute callbacks; the enclosing export owns lifetime protection.

Parameters:
  • tokenPtr – [inout] Live borrowed PostScript token receiving output; caller owns document framing, prolog and lifetime.

  • fileName – [in] Borrowed NUL-terminated prolog filename appended to the global rbc::library directory.

Legacy drawing primitives

group Legacy PostScript drawing primitives

Append drawing programs to a borrowed token; no page delivery.

Functions

static void XColorToPostScript(struct PsTokenStruct *tokenPtr, XColor *colorPtr)

Append three normalized RGB operands from a borrowed XColor.

Uses only the upper eight bits of each 16-bit component, divided by 255. Emits no color-setting operator and performs no variable lookup.

Parameters:
  • tokenPtr – [inout] Live borrowed PostScript token receiving output; caller owns document framing, prolog and lifetime.

  • colorPtr – [in] Non-NULL borrowed color; only the upper eight bits of each RGB component are emitted.

void Rbc_BackgroundToPostScript(struct PsTokenStruct *tokenPtr, XColor *colorPtr)

Append mapped background code or RGB operands followed by SetBgColor.

If colorVarName is set, look up the color name in that Tcl array and append a found value verbatim, bypassing the default operator. Missing entries fall back to RGB conversion. Variable reads may run traces; the enclosing caller must protect token, interpreter and borrowed input lifetimes. This void helper neither reports lookup failure nor rolls back output.

Parameters:
  • tokenPtr – [inout] Live borrowed PostScript token receiving output; caller owns document framing, prolog and lifetime.

  • colorPtr – [in] Non-NULL borrowed color; keep it valid across optional mapping-variable traces.

void Rbc_ForegroundToPostScript(struct PsTokenStruct *tokenPtr, XColor *colorPtr)

Append mapped foreground code or RGB operands followed by SetFgColor.

Uses the same optional Tcl color-array lookup as background output, with the same trace/lifetime requirements. Found values are executable source, not escaped color names. Otherwise the prolog controls color, greyscale and monochrome conversion. No graphics-state save is emitted.

Parameters:
  • tokenPtr – [inout] Live borrowed PostScript token receiving output; caller owns document framing, prolog and lifetime.

  • colorPtr – [in] Non-NULL borrowed color; keep it valid across optional mapping-variable traces.

void Rbc_ClearBackgroundToPostScript(struct PsTokenStruct *tokenPtr)

Select white through the prolog background-color operator.

Appends SetBgColor operands only; it does not erase or fill any region. It bypasses the optional Tcl color map and does not restore prior color.

Parameters:
  • tokenPtr – [inout] Live borrowed PostScript token receiving output; caller owns document framing, prolog and lifetime.

void Rbc_CapStyleToPostScript(struct PsTokenStruct *tokenPtr, int capStyle)

Append an X11-to-PostScript line-cap conversion.

CapNotLast and CapButt both map to butt; positive X11 values are reduced by one. The caller supplies a valid cap enumeration; no range validation or graphics-state restoration is performed.

Parameters:
  • tokenPtr – [inout] Live borrowed PostScript token receiving output; caller owns document framing, prolog and lifetime.

  • capStyle – [in] Valid X cap-style enumeration; CapNotLast and CapButt both produce butt caps.

void Rbc_JoinStyleToPostScript(struct PsTokenStruct *tokenPtr, int joinStyle)

Append the join enumeration directly to setlinejoin.

X11 and PostScript share miter=0, round=1 and bevel=2. The caller must supply a valid enumeration; the previous setting is not restored.

Parameters:
  • tokenPtr – [inout] Live borrowed PostScript token receiving output; caller owns document framing, prolog and lifetime.

  • joinStyle – [in] Valid X join-style enumeration, directly compatible with PostScript.

void Rbc_LineWidthToPostScript(struct PsTokenStruct *tokenPtr, int lineWidth)

Append an integer line width, clamped to at least one.

Zero and negative inputs become one rather than a PostScript hairline. Width is expressed in the current user coordinate system.

Parameters:
  • tokenPtr – [inout] Live borrowed PostScript token receiving output; caller owns document framing, prolog and lifetime.

  • lineWidth – [in] Integer width in current user units; values below one are clamped to one.

void Rbc_LineDashesToPostScript(struct PsTokenStruct *tokenPtr, Rbc_Dashes *dashesPtr)

Append a zero-terminated byte dash list with zero phase.

A NULL pointer or empty values array emits a solid-line dash array. A non-NULL values array must contain a zero terminator. The stored dash offset is not emitted; this helper always uses phase zero.

Parameters:
  • tokenPtr – [inout] Live borrowed PostScript token receiving output; caller owns document framing, prolog and lifetime.

  • dashesPtr – [in] Borrowed zero-terminated byte pattern, or NULL for solid lines; offset is ignored.

void Rbc_LineAttributesToPostScript(struct PsTokenStruct *tokenPtr, XColor *colorPtr, int lineWidth, Rbc_Dashes *dashesPtr, int capStyle, int joinStyle)

Append join, cap, foreground, width and dashes in that order.

Borrows all inputs and inherits the foreground color-map callback boundary. Finally defines an empty DashesProc in the current dictionary. This is not a scoped state change; subsequent strokes use the emitted attributes.

Parameters:
  • tokenPtr – [inout] Live borrowed PostScript token receiving output; caller owns document framing, prolog and lifetime.

  • colorPtr – [in] Non-NULL borrowed color; keep it valid across optional mapping-variable traces.

  • lineWidth – [in] Integer width in current user units; values below one are clamped to one.

  • dashesPtr – [in] Borrowed zero-terminated byte pattern, or NULL for solid lines; offset is ignored.

  • capStyle – [in] Valid X cap-style enumeration; CapNotLast and CapButt both produce butt caps.

  • joinStyle – [in] Valid X join-style enumeration, directly compatible with PostScript.

void Rbc_RectangleToPostScript(struct PsTokenStruct *tokenPtr, double x, double y, int width, int height)

Append a Box followed by the built-in fill operator.

Receives already mapped coordinates and dimensions. The prolog Box starts a fresh closed path; fill consumes it. No color, clipping or validation is added, and no outline is stroked.

Parameters:
  • tokenPtr – [inout] Live borrowed PostScript token receiving output; caller owns document framing, prolog and lifetime.

  • x – [in] Finite mapped horizontal position in the current PostScript user coordinate system.

  • y – [in] Finite mapped vertical position in the current PostScript user coordinate system.

  • width – [in] Rectangle width in mapped user units; caller supplies valid bounded geometry.

  • height – [in] Rectangle height in mapped user units; caller supplies valid bounded geometry.

void Rbc_RegionToPostScript(struct PsTokenStruct *tokenPtr, double x, double y, int width, int height)

Append a fresh closed rectangular path without painting it.

Uses the prolog Box procedure. The caller decides whether to fill, stroke or clip the resulting path and supplies valid mapped dimensions.

Parameters:
  • tokenPtr – [inout] Live borrowed PostScript token receiving output; caller owns document framing, prolog and lifetime.

  • x – [in] Finite mapped horizontal position in the current PostScript user coordinate system.

  • y – [in] Finite mapped vertical position in the current PostScript user coordinate system.

  • width – [in] Rectangle width in mapped user units; caller supplies valid bounded geometry.

  • height – [in] Rectangle height in mapped user units; caller supplies valid bounded geometry.

void Rbc_PathToPostScript(struct PsTokenStruct *tokenPtr, Point2D *screenPts, Tcl_Size nScreenPts)

Append a new open path from borrowed floating-point vertices.

A nonpositive count appends nothing and leaves the prior path untouched. For a positive count, screenPts must contain that many points. Emits one moveto and remaining lineto operations, with no stroke, close, clipping or path-size splitting. Numeric inputs must be suitable for PostScript.

Parameters:
  • tokenPtr – [inout] Live borrowed PostScript token receiving output; caller owns document framing, prolog and lifetime.

  • screenPts – [in] Borrowed array of nScreenPts mapped finite vertices when the count is positive.

  • nScreenPts – [in] Vertex count; nonpositive counts leave output and the current path unchanged.

void Rbc_PolygonToPostScript(struct PsTokenStruct *tokenPtr, Point2D *screenPts, Tcl_Size nScreenPts)

Close and fill a borrowed floating-point polygon through Fill.

Nonpositive counts append nothing. Otherwise builds a fresh path, adds an explicit line back to the first point, closes it and calls the prolog Fill procedure. Unlike built-in fill, Fill preserves the path. This helper does not validate polygon area, split large paths or select a color.

Parameters:
  • tokenPtr – [inout] Live borrowed PostScript token receiving output; caller owns document framing, prolog and lifetime.

  • screenPts – [in] Borrowed array of nScreenPts mapped finite vertices when the count is positive.

  • nScreenPts – [in] Vertex count; nonpositive counts append nothing; polygon validity is not checked.

void Rbc_SegmentsToPostScript(struct PsTokenStruct *tokenPtr, XSegment *segPtr, int nSegments)

Append independent integer segments with DashesProc stroke.

Borrows nSegments XSegment entries; nonpositive counts append nothing. No initial newpath is emitted, so callers must ensure there is no pending path to stroke along with the first segment. Requires DashesProc to be defined. Each stroke consumes its path and restarts the dash pattern.

Parameters:
  • tokenPtr – [inout] Live borrowed PostScript token receiving output; caller owns document framing, prolog and lifetime.

  • segPtr – [in] Borrowed array of nSegments integer segments when the count is positive.

  • nSegments – [in] Number of segment records; nonpositive counts append nothing.

void Rbc_RectanglesToPostScript(struct PsTokenStruct *tokenPtr, XRectangle rectArr[], int nRects)

Fill each borrowed integer rectangle with the current color.

Delegates each entry to Rbc_RectangleToPostScript; nonpositive counts append nothing. No outline, color selection or clipping is supplied.

Parameters:
  • tokenPtr – [inout] Live borrowed PostScript token receiving output; caller owns document framing, prolog and lifetime.

  • rectArr – [in] Borrowed array of nRects mapped integer rectangles when the count is positive.

  • nRects – [in] Number of rectangle records; nonpositive counts append nothing.

void Rbc_Draw3DRectangleToPostScript(struct PsTokenStruct *tokenPtr, Tk_3DBorder border, double x, double y, int width, int height, int borderWidth, int relief)

Append the border bands of a Tk relief rectangle.

Borrows a live border and the token window. Requires nonnegative bounded dimensions and borderWidth with representable integer arithmetic. Returns without output if either dimension is smaller than twice borderWidth. Initializes Tk shadow colors before querying them. Groove and ridge use two recursive half-width relief bands; raised and sunken swap light/dark top-left and bottom-right colors. Other cases retain the existing solid or background-color selection. Emits bottom/right rectangles and a top/left polygon; does not fill the whole interior or restore color/path. Color-map reads inherit the enclosing export callback requirements.

Parameters:
  • tokenPtr – [inout] Live borrowed PostScript token receiving output; caller owns document framing, prolog and lifetime.

  • border – [in] Borrowed live Tk border compatible with the token window.

  • x – [in] Finite mapped horizontal position in the current PostScript user coordinate system.

  • y – [in] Finite mapped vertical position in the current PostScript user coordinate system.

  • width – [in] Rectangle width in mapped user units; caller supplies valid bounded geometry.

  • height – [in] Rectangle height in mapped user units; caller supplies valid bounded geometry.

  • borderWidth – [in] Nonnegative band width with representable doubling and inset arithmetic.

  • relief – [in] Tk relief selecting solid, raised, sunken, groove, ridge or flat band treatment.

void Rbc_Fill3DRectangleToPostScript(struct PsTokenStruct *tokenPtr, Tk_3DBorder border, double x, double y, int width, int height, int borderWidth, int relief)

Fill the background rectangle, then append its relief border.

Borrows the border and token window. Selects its background with SetBgColor semantics before the fill, then delegates border geometry to Rbc_Draw3DRectangleToPostScript. Inherits that helper arithmetic and lifetime requirements; border omission does not undo the initial fill.

Parameters:
  • tokenPtr – [inout] Live borrowed PostScript token receiving output; caller owns document framing, prolog and lifetime.

  • border – [in] Borrowed live Tk border compatible with the token window.

  • x – [in] Finite mapped horizontal position in the current PostScript user coordinate system.

  • y – [in] Finite mapped vertical position in the current PostScript user coordinate system.

  • width – [in] Rectangle width in mapped user units; caller supplies valid bounded geometry.

  • height – [in] Rectangle height in mapped user units; caller supplies valid bounded geometry.

  • borderWidth – [in] Nonnegative band width with representable doubling and inset arithmetic.

  • relief – [in] Tk relief applied after filling the entire background rectangle.

void Rbc_LineToPostScript(struct PsTokenStruct *tokenPtr, XPoint *pointPtr, int nPoints)

Append a stroked integer polyline with bounded path batches.

Counts below two are no-ops, without reading the point array or changing the output. Otherwise pointPtr must contain nPoints readable entries. Starts a new path, then emits DashesProc stroke at each PS_MAXPATH boundary and restarts at the shared endpoint. Stroke boundaries retain connected positions but restart stroke/dash processing. Requires a previously defined DashesProc; borrows the array.

Parameters:
  • tokenPtr – [inout] Live borrowed PostScript token receiving output; caller owns document framing, prolog and lifetime.

  • pointPtr – [in] Borrowed array of nPoints mapped integer vertices when the count is at least two.

  • nPoints – [in] Vertex count; fewer than two appends nothing.

void Rbc_2DSegmentsToPostScript(PsToken psToken, Segment2D *segPtr, Tcl_Size nSegments)

Append independent floating segments after clearing any pending path.

Nonpositive counts append nothing. Otherwise starts with newpath, then emits each segment followed by DashesProc stroke. This prevents a path retained by Fill from being stroked accidentally. Requires a defined DashesProc and a readable borrowed array of nSegments entries. No numeric validation, clipping or state restoration is performed.

Parameters:
  • psToken – [inout] Live borrowed PostScript token receiving output.

  • segPtr – [in] Borrowed array of nSegments finite mapped floating segments when the count is positive.

  • nSegments – [in] Number of segment records; nonpositive counts append nothing.

Raster payloads and capture

The bitmap entry below describes the X11 implementation. The Windows source has a separate contract for its DIB acquisition and failure path; see the platform comparison in PostScript output and drawing state.

group PostScript raster and bitmap encoding

Legacy image conversion, bitmap payloads and capture wrappers.

Functions

static unsigned char ReverseBits(unsigned char byte)

Return a byte with its eight bit positions reversed.

Swaps adjacent bits, pairs and nibbles. No allocation or output state is involved; bitmap serializers use it to place the first pixel in bit seven.

Parameters:
  • byte – [in] Eight-bit value whose bit positions are reversed.

static void ByteToHex(unsigned char byte, char *string)

Write two uppercase hexadecimal digits into caller-owned storage.

string must have at least two writable bytes. No NUL terminator is written; callers add delimiters, line breaks or a terminator separately.

Parameters:
  • byte – [in] Byte to encode as two uppercase hexadecimal digits.

  • string – [out] At least two writable bytes; no terminating NUL is added.

void Rbc_BitmapDataToPostScript(struct PsTokenStruct *tokenPtr, Display *display, Pixmap bitmap, int width, int height)

Append an X11 depth-one bitmap as a PostScript hex string.

Borrows a valid bitmap and token with positive matching dimensions. Captures plane one with XGetImage, reads rows top-to-bottom with XGetPixel, and packs the first pixel into the high bit of each output byte. Partial bytes are zero-padded per row. Emits angle-bracket delimiters, uppercase hex and wrapping after batches of thirty complete bytes, then destroys the XImage. A failed capture returns without appending a payload, matching the Windows failure policy. No Tcl status is returned.

Parameters:
  • tokenPtr – [inout] Live borrowed PostScript token receiving output; caller owns document framing, prolog and lifetime.

  • display – [in] Display owning the borrowed bitmap.

  • bitmap – [in] Live borrowed depth-one bitmap; not freed by this helper.

  • width – [in] Positive bitmap width in pixels, matching the captured bitmap.

  • height – [in] Positive bitmap height in pixels, matching the captured bitmap.

int Rbc_ColorImageToPsData(Rbc_ColorImage image, int nComponents, Tcl_DString *resultPtr, char *prefix)

Append bottom-to-top raster samples as wrapped hexadecimal text.

Borrows a valid image, initialized result DString and NUL-terminated prefix. Three components emit RGB bytes; one component emits the complement of each red byte, assuming greyscale conversion was already performed. Other component counts append nothing and return zero. Alpha is ignored. Each physical data line starts with prefix plus a space, holds up to sixty hex digits, and ends with a newline, including a partial final line. Row boundaries do not force line breaks. Returns the number of appended data lines, not a Tcl status; caller sizes must keep this int count valid. The image is unchanged. No image operator or surrounding hex delimiters are emitted; prefix must not alias storage invalidated by DString growth.

Parameters:
  • image – [in] Borrowed readable image; RGB output ignores alpha, and one-component output assumes greyscale already computed.

  • nComponents – [in] Three for RGB or one for complemented red-channel samples; other values append nothing.

  • resultPtr – [inout] Caller-initialized DString receiving hex text and line separators.

  • prefix – [in] NUL-terminated prefix for each physical data line; must not alias storage relocated by result growth.

void Rbc_StippleToPostScript(struct PsTokenStruct *tokenPtr, Display *display, Pixmap bitmap)

Fill the current clipping shape with a borrowed Tk bitmap pattern.

Queries bitmap dimensions, saves graphics state, intersects the clip with the current path, emits bitmap data and calls prolog StippleFill before restoring state. Requires a valid current path and registered Tk bitmap. Bitmap acquisition failure has no status return and is not rolled back.

Parameters:
  • tokenPtr – [inout] Live borrowed PostScript token receiving output; caller owns document framing, prolog and lifetime.

  • display – [in] Display owning the borrowed bitmap.

  • bitmap – [in] Borrowed registered Tk bitmap with valid dimensions; repeated within the current path clip.

void Rbc_ColorImageToPostScript(struct PsTokenStruct *tokenPtr, Rbc_ColorImage image, double x, double y)

Append a positioned RGB or greyscale raster image program.

Borrows a valid image and token; does not release the image. Color mode selects three-component colorimage; other modes convert image RGB values to greyscale in place and emit complemented red samples through image. Alpha is not composited or encoded. Translation and scaling are enclosed in gsave/grestore, but tmpStr is a dictionary definition, not saved state. Uses an eight-bit image matrix with negative vertical scale. No Tcl error status is returned. The row-byte count is formatted as size_t without narrowing to int.

Parameters:
  • tokenPtr – [inout] Live borrowed PostScript token receiving output; caller owns document framing, prolog and lifetime.

  • image – [inout] Borrowed valid image; noncolor modes replace RGB values with greyscale in place, and all modes ignore alpha.

  • x – [in] Finite mapped horizontal position in the current PostScript user coordinate system.

  • y – [in] Finite mapped vertical position in the current PostScript user coordinate system.

void Rbc_WindowToPostScript(struct PsTokenStruct *tokenPtr, Tk_Window tkwin, double x, double y)

Capture a window into an owned temporary image and serialize it.

Borrows a live window and token; captures its current dimensions at GAMMA. On success frees the temporary image after serialization. A failed capture instead emits a comment and a grey background rectangle of the same size. The fallback changes background color without restoring it and does not report a Tcl error. This is capture of native pixels, not widget commands.

Parameters:
  • tokenPtr – [inout] Live borrowed PostScript token receiving output; caller owns document framing, prolog and lifetime.

  • tkwin – [in] Live window with native pixels available for capture at its current dimensions.

  • x – [in] Finite mapped horizontal position in the current PostScript user coordinate system.

  • y – [in] Finite mapped vertical position in the current PostScript user coordinate system.

void Rbc_PhotoToPostScript(struct PsTokenStruct *tokenPtr, Tk_PhotoHandle photo, double x, double y)

Copy a Tk photo into a temporary color image and serialize it.

Borrows the photo and token. Releases the temporary image after output, so greyscale conversion does not modify the original photo. Requires a valid photo handle; no conversion failure status is propagated. Inherits the serializer alpha omission and positioning conventions.

Parameters:
  • tokenPtr – [inout] Live borrowed PostScript token receiving output; caller owns document framing, prolog and lifetime.

  • photo – [in] Valid borrowed Tk photo; a temporary image copy absorbs any greyscale conversion.

  • x – [in] Finite mapped horizontal position in the current PostScript user coordinate system.

  • y – [in] Finite mapped vertical position in the current PostScript user coordinate system.

void Rbc_BitmapToPostScript(struct PsTokenStruct *tokenPtr, Display *display, Pixmap bitmap, double scaleX, double scaleY)

Emit a scaled bitmap mask centered on the current origin.

Borrows a registered Tk bitmap and token. Queries dimensions, translates by negative half scaled width and positive half scaled height, then scales by scaled width and negative scaled height. Emits a byte-packed one-bit imagemask with true polarity, restoring graphics state afterward. Paints set bits with the current color; unset bits remain unpainted. The caller supplies finite usable scale factors. Capture failures are not returned or rolled back, and no bitmap resource is transferred.

Parameters:
  • tokenPtr – [inout] Live borrowed PostScript token receiving output; caller owns document framing, prolog and lifetime.

  • display – [in] Display owning the borrowed bitmap.

  • bitmap – [in] Borrowed registered Tk bitmap, drawn as a one-bit mask centered on the current origin.

  • scaleX – [in] Finite usable horizontal scale factor, yielding a nonsingular image transform.

  • scaleY – [in] Finite usable vertical scale factor, yielding a nonsingular image transform.

Font mapping and text placement

The X11 property helpers below supplement the shared font-selection path; Windows goes directly to the final fallback when family recognition fails.

group PostScript font mapping and text placement

Legacy font names and screen-metric text, without embedded outlines.

Functions

static const char *NameOfAtom(Tk_Window tkwin, Atom atom)

Borrow an X11 atom name, translating Tk’s bad-atom sentinel to NULL.

Requires a live Tk window. The returned name belongs to Tk and must not be freed. The helper does not acquire a font or allocate output storage.

Parameters:
  • tkwin – [in] Live window selecting the Tk display/atom cache.

  • atom – [in] Atom whose Tk-owned name is requested.

static const char *XFontStructToPostScript(Tk_Window tkwin, XFontStruct *fontPtr, Tcl_DString *resultPtr)

Build a legacy PostScript name from borrowed X11 font properties.

Requires an initialized result DString and a valid XFontStruct. Missing FULL_NAME, FOUNDRY or FAMILY_NAME returns NULL without replacing the result. Adobe families are kept; other foundries remove an optional ITC prefix and use an exact case-insensitive alias match, defaulting to Helvetica. If the full name starts with the original family, its remaining typeface is appended after a dash with spaces and dashes removed. Success replaces resultPtr and returns a borrowed pointer into it. No font is released here.

Parameters:
  • tkwin – [in] Live window used to resolve property atom names.

  • fontPtr – [in] Borrowed valid X font structure with the required name/family/foundry properties.

  • resultPtr – [inout] Initialized DString replaced on success; returned name borrows this buffer.

void Rbc_FontToPostScript(struct PsTokenStruct *tokenPtr, Tk_Font font)

Append a PostScript font name and size using the legacy fallback chain.

Borrows the token and Tk font. A found font-map array entry takes priority: its first list element supplies the raw font name; exactly two elements with an integer second element supply the size. Otherwise size remains twelve, including one-element entries. Parse errors do not stop output. Without a mapped entry, recognized family prefixes use Tk_PostscriptFontName. Other X11 families attempt XLoadQueryFont and property-based mapping, freeing the loaded font after copying its name into a temporary DString. Windows skips this attempt. Final fallback is Helvetica-Bold, normally at size twelve. Releases temporary Tcl descriptions, split lists and DStrings. No glyphs are embedded. Variable reads can execute traces; enclosing export code owns callback lifetime protection. This void helper does not report failure.

Parameters:
  • tokenPtr – [inout] Live borrowed PostScript token receiving output; caller owns document framing, prolog and lifetime.

  • font – [in] Borrowed Tk font, kept valid across optional font-map variable traces; no program is embedded.

static void TextLayoutToPostScript(PsToken psToken, int x, int y, TextLayout *textPtr)

Append nonempty layout fragments as adjusted PostScript text.

Borrows a live token and layout. Empty fragments are skipped, avoiding the prolog division by string length. Each other fragment uses escaped Latin-1 literal contents and its measured width with DrawAdjText. Coordinates add x/y to fragment baselines in Tcl_WideInt and emit the full sum, avoiding signed int overflow. Does not choose fonts, colors or transforms.

Parameters:
  • psToken – [inout] Live borrowed PostScript token receiving output.

  • x – [in] Horizontal offset added to fragment baselines using wide arithmetic.

  • y – [in] Vertical offset added to fragment baselines using wide arithmetic.

  • textPtr – [in] Borrowed layout with live UTF fragment strings, byte counts and measured screen widths.

void Rbc_TextToPostScript(struct PsTokenStruct *tokenPtr, char *string, TextStyle *tsPtr, double x, double y)

Append anchored, optionally shadowed text under a saved transform.

NULL or empty strings append nothing. Borrows the string, style and Tk resources; allocates and frees a temporary layout. Requires finite bounded geometry and angles compatible with FMOD and ROUND. The bounding-box calculation normalizes the remainder into [0, 360), while BeginText receives the original style angle. Selects the font, optional positive-offset shadow, then active or normal foreground. Does not implement native disabled/emphasis two-pass relief. BeginText/EndText save and restore graphics state; style fields are not modified. Font/color array traces require enclosing lifetime protection, including the borrowed string retained by layout fragments.

Parameters:
  • tokenPtr – [inout] Live borrowed PostScript token receiving output; caller owns document framing, prolog and lifetime.

  • string – [in] Borrowed NUL-terminated Tcl UTF text; NULL/empty emits nothing; must survive mapping traces.

  • tsPtr – [in] Borrowed style and live font/colors; theta is unchanged and must satisfy FMOD/ROUND bounds.

  • x – [in] Finite horizontal anchor coordinate in mapped user units.

  • y – [in] Finite vertical anchor coordinate in mapped user units.

struct FontMap

Immutable family alias and PostScript fallback-name pair.

Strings are static; lookup does not create or own font resources.

Public Members

const char *alias

Borrowed alias recognized by the resolver.

const char *fontName

Borrowed PostScript font name.

Graph options and document assembly

These contracts describe the shared graph-facing command layer in rbcGrPs.c. The parameter lists distinguish full command vectors from option slices and borrowed output buffers from owned component state. Windows binary preview packaging has its source-level contract on CreateWindowsEPS and its platform behavior described in PostScript output and drawing state.

group Graph PostScript command internals

Functions

static int IsOptionPrefix(const char *string, Tcl_Size length, const char *fullName)

Match a nonempty, case-sensitive prefix of an option value.

Borrows both strings. The supplied length must describe readable string storage; lengths beyond fullName are rejected before comparison. Returns a boolean without changing the interpreter or either string.

Parameters:
  • string – [in] Borrowed candidate bytes, readable for length bytes.

  • length – [in] Candidate byte count; nonpositive lengths never match.

  • fullName – [in] Borrowed NUL-terminated full option spelling.

static int GetColorModeFromObj(Tcl_Interp *interp, Tcl_Obj *objPtr, PsColorMode *modePtr)

Parse a color level without changing the destination on failure.

Accepts nonempty prefixes of color, grayscale, greyscale and monochrome. Borrows objPtr and writes modePtr only on TCL_OK; TCL_ERROR leaves a diagnostic in interp. Does not retain the object.

Parameters:
  • interp – [in] Interpreter receiving conversion errors; see Interpreter arguments.

  • objPtr – [in] Borrowed option object; not retained.

  • modePtr – [out] Required result storage; unchanged on failure.

static int GetPreviewFormatFromObj(Tcl_Interp *interp, Tcl_Obj *objPtr, int *formatPtr)

Parse a preview format supported by this build.

EPSI is available everywhere and WMF on Windows. Accepts nonempty prefixes. Writes formatPtr only on TCL_OK; TCL_ERROR reports the build-specific choices in interp. TIFF has no encoder and is rejected regardless of HAVE_TIFF_H.

Parameters:
  • interp – [in] Interpreter receiving unsupported-format errors; see Interpreter arguments.

  • objPtr – [in] Borrowed preview-format object; not retained.

  • formatPtr – [out] Required result storage; changed only on TCL_OK.

static int ConfigurePostScript(Graph *graphPtr, PostScript *psPtr, int mask)

Validate changed option objects before committing derived fields.

Borrows the graph and its PostScript record. Converts only mask-selected dimensions, padding, color mode and preview format into local values. Plot dimensions may be zero; paper dimensions must be positive. On TCL_ERROR no derived field is committed. This does not restore the Tk option objects themselves; SetPostScriptOptions handles that rollback.

Parameters:
  • graphPtr – [in] Borrowed graph providing interpreter and Tk distance-conversion context.

  • psPtr – [inout] Initialized component; selected derived fields commit together after validation.

  • mask – [in] PS_*_CHANGED bits selecting conversions; unselected derived values are retained.

static int SetPostScriptOptions(Graph *graphPtr, PostScript *psPtr, Tcl_Size objc, Tcl_Obj *const objv[], Tk_SavedOptions *savedOptionsPtr, int *maskPtr)

Apply Tk options and validate their derived PostScript values.

Requires initialized component options and caller-provided saved-options and mask storage. Returns TCL_ERROR on Tk or conversion failure; derived conversion failure restores saved Tk options while preserving the error. On TCL_OK the caller must release saved options with Tk_FreeSavedOptions. Successful settings belong to the component, not a temporary export.

Parameters:
  • graphPtr – [in] Borrowed graph providing the interpreter and live Tk configuration context.

  • psPtr – [inout] Initialized component receiving persistent option values.

  • objc – [in] Number of objects in the option/value slice, not the full widget command.

  • objv – [in] Borrowed option/value slice; see Tcl command arguments for object lifetime.

  • savedOptionsPtr – [out] Required Tk saved-options storage; caller frees it after TCL_OK.

  • maskPtr – [out] Required storage for Tk changed-option bits; not a success indicator.

void Rbc_DestroyPostScript(Graph *graphPtr)

Detach and release the graph-owned PostScript option record.

A NULL graph->postscript is a no-op. Otherwise clears that pointer before freeing Tk configuration resources, deleting the option table and freeing the record. Requires the graph and Tk option context to remain valid; does not destroy the graph, its window or an independently owned token.

Parameters:
  • graphPtr – [inout] Graph whose component is detached and freed; a NULL component is allowed, a NULL graph is not.

static int CgetOp(Graph *graphPtr, Tcl_Interp *interp, Tcl_Size objc, Tcl_Obj *const objv[])

Return one PostScript option value through the Tcl result.

Requires dispatch-validated arguments with the option at objv[3]. Borrows the component and arguments. Returns TCL_OK with the Tk option value or TCL_ERROR with the lookup diagnostic; does not configure or render.

Parameters:
  • graphPtr – [inout] Borrowed graph with initialized PostScript component; enclosing widget dispatch owns lifetime protection.

  • interp – [in] Interpreter receiving command results and errors; see Interpreter arguments.

  • objc – [in] Exactly four full-command objects; option name is objv[3].

  • objv – [in] Borrowed full widget-command vector; see Tcl command arguments.

static int ConfigureOp(Graph *graphPtr, Tcl_Interp *interp, Tcl_Size objc, Tcl_Obj *const objv[])

Query or update the persistent PostScript component options.

With three words returns all option descriptions; with four returns one. Otherwise applies option/value pairs transactionally and frees saved options on success. Returns the Tk query or configuration status. Does not emit a document or open a destination file.

Parameters:
  • graphPtr – [inout] Borrowed graph with initialized PostScript component; enclosing widget dispatch owns lifetime protection.

  • interp – [in] Interpreter receiving command results and errors; see Interpreter arguments.

  • objc – [in] Full-command count: three lists all options, four queries one, otherwise option/value pairs follow objv[2].

  • objv – [in] Borrowed full widget-command vector; see Tcl command arguments.

static Tcl_WideInt PostScriptLayoutSize(Tcl_WideInt value)

Clamp a wide layout size to the positive int range.

Returns at least one and at most INT_MAX, represented as Tcl_WideInt. Used before narrowing page and plot dimensions; has no side effects.

Parameters:
  • value – [in] Wide intermediate pixel size, including zero or negative values.

static int ComputeBoundingBox(Graph *graphPtr, PostScript *psPtr)

Compute page bounds and lay out the graph at export dimensions.

Uses requested plot dimensions when positive, exchanges oriented extents for landscape, and fits within paper minus padding. Maxpect also permits enlargement. Stores pageScale and inclusive bounds in psPtr; centering replaces the initial padding origin when paper is larger than the plot. Wide arithmetic and clamping bound intermediate layout sizes. Sets layout and mapping flags, invokes Rbc_LayoutGraph, and returns paper height in pixels or -1 on layout failure. The caller must restore screen geometry through the export lifecycle; this function does not save it.

Parameters:
  • graphPtr – [inout] Borrowed graph whose export dimensions, flags and mapped layout are changed.

  • psPtr – [inout] Component supplying page settings and receiving scale and inclusive pixel bounds.

static void PreviewImage(Graph *graphPtr, PsToken psToken)

Append an eight-bit grayscale EPSI preview from a native snapshot.

Borrows the graph and token. Owns and frees the temporary pixmap, captured color image and encoding DString. Drawing may run callbacks; invalidation is checked before capture. Capture failure silently omits the preview. THUMBNAIL_PREVIEW enables optional resampling; otherwise uses the export layout size. Landscape rotates the grayscale image by 90 degrees. The caller checks graph validity again because this void helper has no status.

Parameters:
  • graphPtr – [inout] Borrowed, caller-protected graph at export layout dimensions; drawing may invoke callbacks.

  • psToken – [inout] Borrowed output token receiving EPSI comments; remains owned by the caller.

static int PostScriptPreamble(Graph *graphPtr, const char *fileName, PsToken psToken)

Lay out the export and append EPS metadata, prolog and transforms.

Borrows fileName (NULL selects the widget path) and psToken. Returns TCL_ERROR on layout failure, preview invalidation or prolog load failure. Converts display pixels to points using screen pixel/mm dimensions, escapes metadata strings, optionally appends EPSI, loads rbcGraph.pro, then emits any footer and establishes page orientation and scaling. Reads rbc_version and the prolog library path through Tcl, so variable traces are possible. Checks graph validity after successful callback-capable reads before resuming component access. Partial output remains in the token on failure; the enclosing operation owns graph lifetime protection and export cleanup.

Parameters:
  • graphPtr – [inout] Caller-protected graph with initialized PostScript component; layout is changed.

  • fileName – [in] Borrowed NUL-terminated title, or NULL to use the widget path.

  • psToken – [inout] Borrowed token receiving metadata, prolog and transforms; partial output remains on error.

static int GraphToPostScript(Graph *graphPtr, const char *ident, PsToken psToken)

Render a complete PostScript graph through the shared export layer.

Borrows the token as backendData and its DString as the output buffer. Begins graph export, emits the preamble and shared graph traversal, then appends the trailer only on success. Always ends graph export and frees the export context, including on error. EndGraph restores live window dimensions and schedules remapping rather than synchronously restoring every screen coordinate. Returns the first failing stage or TCL_OK.

Parameters:
  • graphPtr – [inout] Caller-protected graph; export begin/end manage its temporary layout state.

  • ident – [in] Borrowed document title, or NULL to select the widget path.

  • psToken – [inout] Caller-owned token borrowed by renderer contexts; not released by export cleanup.

static int OutputOp(Graph *graphPtr, Tcl_Interp *interp, Tcl_Size objc, Tcl_Obj *const objv[])

Return PostScript text or write a completed document to a Tcl file.

A fourth word not starting with a dash is the filename; remaining words configure persistent output options. Successful options remain installed even if rendering or delivery fails. Owns the token and staging DString; token mapping names borrow component storage. Renders before opening the destination. String results omit the Windows binary-preview wrapper. File output uses binary channel translation, checks write and close failures, and preserves an earlier error across cleanup. A delivery failure can leave a partial file: this is not atomic file replacement. Returns TCL_OK with text or an empty file-output result, else TCL_ERROR. Caller must protect the graph across callbacks during rendering.

Parameters:
  • graphPtr – [inout] Borrowed graph with initialized PostScript component; enclosing widget dispatch owns lifetime protection.

  • interp – [in] Interpreter receiving command results and errors; see Interpreter arguments.

  • objc – [in] Full-command count; optional filename and option/value pairs follow objv[2].

  • objv – [in] Borrowed full widget-command vector; see Tcl command arguments.

int Rbc_CreatePostScript(Graph *graphPtr)

Create and initialize the graph-owned named PostScript component.

Requires a graph without an existing PostScript record and a live option context. Allocates the record/table, initializes resource name postscript and class Postscript through the option proxy, then validates derived fields. Returns TCL_OK on success. On TCL_ERROR destroys the partial component and leaves graph->postscript NULL; diagnostics remain in interp.

Parameters:
  • graphPtr – [inout] Graph with no existing PostScript component and a usable Tk configuration context; owns the new record on success.

int Rbc_PostScriptOp(Graph *graphPtr, Tcl_Interp *interp, Tcl_Size objc, Tcl_Obj *const objv[])

Validate and dispatch the graph postscript subcommand.

Borrows graph, interpreter and argument objects. Uses the strided psOps table to validate the operation at argument two and its arity, then returns the selected handler status. Does not independently preserve the graph or interpreter; the enclosing widget command owns that guard.

Parameters:
  • graphPtr – [inout] Borrowed graph with initialized PostScript component; enclosing widget dispatch owns lifetime protection.

  • interp – [in] Interpreter receiving command results and errors; see Interpreter arguments.

  • objc – [in] Full widget-command count, including the postscript operation at objv[2].

  • objv – [in] Borrowed full widget-command vector; see Tcl command arguments.

Windows binary preview packaging

The Windows-only helper is extracted in the separate platform project. It shares the graph command’s lifetime protection but owns its temporary native resources. See PostScript output and drawing state for the EPSI/WMF distinction.

group Windows EPS preview packaging

Private native preview assembly for the graph PostScript command.

Functions

static int CreateWindowsEPS(Graph *graphPtr, PsToken psToken, Tcl_DString *document)

Append a DOS EPS header, PostScript payload and Windows metafile preview.

Windows-only packaging used for file output with a WMF preview. Appends a newline to the token, captures a separate preview at live widget dimensions, and copies the header and both payloads into document. The PostScript byte count includes its terminating NUL. This is not the EPSI snapshot path.

Owns the temporary drawable wrapper, metafile, reference DC and global-memory block, releasing them before return. The caller retains graph lifetime protection and owns both output buffers. Once preview drawing has begun, cleanup marks mapping work and schedules redraw. Returns TCL_OK after assembly, or TCL_ERROR for the checked native failures or graph invalidation.

Parameters:
  • graphPtr – [inout] Caller-protected graph with a live, realized Tk window.

  • psToken – [inout] Caller-owned completed PostScript token; receives a trailing newline.

  • document – [inout] Initialized caller-owned DString receiving binary bytes; not freed here.

Data records and member contracts

These records describe stored state and resource ownership. Their presence in the reference does not make private layouts part of the installed C API.

struct PostScriptOpSpec

Typed command dispatch entry with shared argument validation metadata.

Public Members

Rbc_OpSpecHeader header

Operation name, total argument bounds and usage suffix.

RbcGrPsOp *proc

Typed command handler for this operation.

struct PsTokenStruct

PostScript accumulator with borrowed interpreter/window and color/font mapping names.

Public Members

Tcl_Interp *interp

Interpreter to report errors to.

Tk_Window tkwin

Tk_Window used to get font and color information.

Tcl_DString dString

Dynamic string used to contain the PostScript generated.

char *fontVarName

Name of a Tcl array variable to convert X font names to PostScript fonts.

char *colorVarName

Name of a Tcl array variable to convert X color names to PostScript.

PsColorMode colorMode

Mode: color or greyscale.

char scratchArr[PSTOKEN_BUFSIZ + 1]

Reusable formatting buffer, including a terminator slot.

Implementation selectors

enum PsColorMode

Selects monochrome, greyscale or colour conversion for PostScript output.

Values:

enumerator PS_MODE_MONOCHROME
enumerator PS_MODE_GREYSCALE
enumerator PS_MODE_COLOR