XCreateGC(3)

πŸ’… XCreateGC β€” straight outta XLIB FUNCTIONS ✨

Okay bestie, gather round, because this is the page where X11 hands you a graphics context β€” the GC, aka the little bundle of drawing settings that the entire rest of your rendering life depends on. This family of functions (XCreateGC, XCopyGC, XChangeGC, XGetGCValues, XFreeGC, XGContextFromGC, plus the XGCValues struct) is all about creating, copying, tweaking, reading, and yeeting graphics contexts. Iconic behavior honestly. πŸŽ€


🌸 NAME 🌸

XCreateGC, XCopyGC, XChangeGC, XGetGCValues, XFreeGC, XGContextFromGC, XGCValues β€” literally the whole squad for creating or freeing graphics contexts and the graphics context structure itself. Periodt. πŸ’–


✨ SYNTAX ✨

Copy these exactly, no cap, character for character:

GC XCreateGC(Display *display, Drawable d, unsigned long valuemask,
       XGCValues *values);

int XCopyGC(Display *display, GC src, unsigned long valuemask, GC dest);

int XChangeGC(Display *display, GC gc, unsigned long valuemask,
       XGCValues *values);

Status XGetGCValues(Display *display, GC gc, unsigned long valuemask,
       XGCValues *values_return);

int XFreeGC(Display *display, GC gc);

GContext XGContextFromGC(GC gc);

🫢 ARGUMENTS 🫢

Here's who's who in the group chat:

  • d β€” Specifies the drawable. Your canvas, your main character. πŸ–ΌοΈ
  • dest β€” Specifies the destination GC. Where the copying lands. πŸ“₯
  • display β€” Specifies the connection to the X server. The line to the mothership. πŸ”Œ
  • gc β€” Specifies the GC. The one and only. πŸ‘‘
  • src β€” Specifies the components of the source GC. Where the copying comes from. πŸ“€
  • valuemask β€” Specifies which components in the GC are to be set, copied, changed, or returned. This argument is the bitwise inclusive OR of zero or more of the valid GC component mask bits. So you're stacking bits like it's a fit check. 🧚
  • values β€” Specifies any values as specified by the valuemask. Matches up with the mask, one-to-one. πŸ“
  • values_return β€” Returns the GC values in the specified XGCValues structure. The receipts. 🧾

πŸ’œ DESCRIPTION πŸ’œ

🌈 XCreateGC

The XCreateGC function creates a graphics context and returns a GC. The GC can be used with any destination drawable having the same root and depth as the specified drawable. Use with other drawables results in a BadMatch error. So like… it's loyal, and it does NOT do long distance. 😭

XCreateGC can generate BadAlloc, BadDrawable, BadFont, BadMatch, BadPixmap, and BadValue errors.

🌈 XCopyGC

The XCopyGC function copies the specified components from the source GC to the destination GC. The source and destination GCs must have the same root and depth, or a BadMatch error results. The valuemask specifies which component to copy, as for XCreateGC. πŸ¦‹

XCopyGC can generate BadAlloc, BadGC, and BadMatch errors.

🌈 XChangeGC

The XChangeGC function changes the components specified by valuemask for the specified GC. The values argument contains the values to be set. The values and restrictions are the same as for XCreateGC.

A couple of the way that… details you genuinely need to know:

  • Changing the clip-mask overrides any previous XSetClipRectangles request on the context.
  • Changing the dash-offset or dash-list overrides any previous XSetDashes request on the context.
  • The order in which components are verified and altered is server dependent. πŸ™ˆ
  • If an error is generated, a subset of the components may have been altered. So it's not all-or-nothing, bestie β€” that's the scary part. πŸ’€

XChangeGC can generate BadAlloc, BadFont, BadGC, BadMatch, BadPixmap, and BadValue errors.

🌈 XGetGCValues

The XGetGCValues function returns the components specified by valuemask for the specified GC. If the valuemask contains a valid set of GC mask bits β€” and here's the full baddie list, read 'em and weep: GCFunction, GCPlaneMask, GCForeground, GCBackground, GCLineWidth, GCLineStyle, GCCapStyle, GCJoinStyle, GCFillStyle, GCFillRule, GCTile, GCStipple, GCTileStipXOrigin, GCTileStipYOrigin, GCFont, GCSubwindowMode, GCGraphicsExposures, GCClipXOrigin, GCClipYOrigin, GCDashOffset, or GCArcMode β€” and no error occurs, XGetGCValues sets the requested components in values_return and returns a nonzero status. Otherwise, it returns a zero status.

Two little gotchas that will absolutely humble you:

Note that the clip-mask and dash-list (represented by the GCClipMask and GCDashList bits, respectively, in the valuemask) cannot be requested. Not available, not asking, don't try. 🚫
Also note that an invalid resource ID (with one or more of the three most significant bits set to 1) will be returned for GCFont, GCTile, and GCStipple if the component has never been explicitly set by the client. So if it looks cursed, it's because it is β€” nobody ever set it. 😭

🌈 XFreeGC

The XFreeGC function destroys the specified GC as well as all the associated storage. Cleanup queen. 🧹✨

XFreeGC can generate a BadGC error.


πŸŽ€ STRUCTURES πŸŽ€

The XGCValues structure contains:

/* GC attribute value mask bits */
#define   GCFunction                  (1L<<0)
#define   GCPlaneMask                 (1L<<1)
#define   GCForeground                (1L<<2)
#define   GCBackground                (1L<<3)
#define   GCLineWidth                 (1L<<4)
#define   GCLineStyle                 (1L<<5)
#define   GCCapStyle                  (1L<<6)
#define   GCJoinStyle                 (1L<<7)
#define   GCFillStyle                 (1L<<8)
#define   GCFillRule                  (1L<<9)
#define   GCTile                      (1L<<10)
#define   GCStipple                   (1L<<11)
#define   GCTileStipXOrigin           (1L<<12)
#define   GCTileStipYOrigin           (1L<<13)
#define   GCFont                      (1L<<14)
#define   GCSubwindowMode             (1L<<15)
#define   GCGraphicsExposures         (1L<<16)
#define   GCClipXOrigin               (1L<<17)
#define   GCClipYOrigin               (1L<<18)
#define   GCClipMask                  (1L<<19)
#define   GCDashOffset                (1L<<20)
#define   GCDashList                  (1L<<21)
#define   GCArcMode                   (1L<<22)

/* Values */

typedef struct {
        int function;   /* logical operation */
        unsigned long plane_mask;       /* plane mask */
        unsigned long foreground;       /* foreground pixel */
        unsigned long background;       /* background pixel */
        int line_width; /* line width (in pixels) */
        int line_style; /* LineSolid, LineOnOffDash, LineDoubleDash */
        int cap_style;  /* CapNotLast, CapButt, CapRound, CapProjecting */
        int join_style; /* JoinMiter, JoinRound, JoinBevel */
        int fill_style; /* FillSolid, FillTiled, FillStippled FillOpaqueStippled*/
        int fill_rule;  /* EvenOddRule, WindingRule */
        int arc_mode;   /* ArcChord, ArcPieSlice */
        Pixmap tile;    /* tile pixmap for tiling operations */
        Pixmap stipple; /* stipple 1 plane pixmap for stippling */
        int ts_x_origin;        /* offset for tile or stipple operations */
        int ts_y_origin;
        Font font;      /* default text font for text operations */
        int subwindow_mode;     /* ClipByChildren, IncludeInferiors */
        Bool graphics_exposures;        /* boolean, should exposures be generated */
        int clip_x_origin;      /* origin for clipping */
        int clip_y_origin;
        Pixmap clip_mask;       /* bitmap clipping; other calls for rects */
        int dash_offset;        /* patterned/dashed line information */
        char dashes;
} XGCValues;

πŸ¦‹ the function attribute, explained πŸ¦‹

The function attributes of a GC are used when you update a section of a drawable (the destination) with bits from somewhere else (the source). The function in a GC defines how the new destination bits are to be computed from the source bits and the old destination bits. GXcopy is typically the most useful because it will work on a color display, but special applications may use other functions, particularly in concert with particular planes of a color display. πŸ”₯

The 16 GC functions, defined in X11/X.h, are:

  • GXclear β€” 0x0 β€” 0
  • GXand β€” 0x1 β€” src AND dst
  • GXandReverse β€” 0x2 β€” src AND NOT dst
  • GXcopy β€” 0x3 β€” src
  • GXandInverted β€” 0x4 β€” (NOT src) AND dst
  • GXnoop β€” 0x5 β€” dst
  • GXxor β€” 0x6 β€” src XOR dst
  • GXor β€” 0x7 β€” src OR dst
  • GXnor β€” 0x8 β€” (NOT src) AND (NOT dst)
  • GXequiv β€” 0x9 β€” (NOT src) XOR dst
  • GXinvert β€” 0xa β€” NOT dst
  • GXorReverse β€” 0xb β€” src OR (NOT dst)
  • GXcopyInverted β€” 0xc β€” NOT src
  • GXorInverted β€” 0xd β€” (NOT src) OR dst
  • GXnand β€” 0xe β€” (NOT src) OR (NOT dst)
  • GXset β€” 0xf β€” 1

🌸 planes, and why they matter 🌸

Many graphics operations depend on either pixel values or planes in a GC. The planes attribute is of type long, and it specifies which planes of the destination are to be modified, one bit per plane. A monochrome display has only one plane and will be the least significant bit of the word. As planes are added to the display hardware, they will occupy more significant bits in the plane mask. 🧚

In graphics operations, given a source and destination pixel, the result is computed bitwise on corresponding bits of the pixels. That is, a Boolean operation is performed in each bit plane. The plane_mask restricts the operation to a subset of planes. A macro constant AllPlanes can be used to refer to all planes of the screen simultaneously. The result is computed by the following:

((src FUNC dst) AND plane-mask) OR (dst AND (NOT plane-mask))

Range checking is not performed on the values for foreground, background, or plane_mask. They are simply truncated to the appropriate number of bits. (Rude, but okay. πŸ’€) The line-width is measured in pixels and either can be greater than or equal to one (wide line) or can be the special value zero (thin line).


⭐ wide lines ⭐

Wide lines are drawn centered on the path described by the graphics request. Unless otherwise specified by the join-style or cap-style, the bounding box of a wide line with endpoints [x1, y1], [x2, y2] and width w is a rectangle with vertices at the following real coordinates:

[x1-(w*sn/2), y1+(w*cs/2)], [x1+(w*sn/2), y1-(w*cs/2)],
[x2-(w*sn/2), y2+(w*cs/2)], [x2+(w*sn/2), y2-(w*cs/2)]

Here sn is the sine of the angle of the line, and cs is the cosine of the angle of the line. A pixel is part of the line and so is drawn if the center of the pixel is fully inside the bounding box (which is viewed as having infinitely thin edges). If the center of the pixel is exactly on the bounding box, it is part of the line if and only if the interior is immediately to its right (x increasing direction). Pixels with centers on a horizontal edge are a special case and are part of the line if and only if the interior or the boundary is immediately below (y increasing direction) and the interior or the boundary is immediately to the right (x increasing direction). Like, geometry said "be precise or be nothing." 😀


πŸ“ thin lines πŸ“

Thin lines (zero line-width) are one-pixel-wide lines drawn using an unspecified, device-dependent algorithm. There are only two constraints on this algorithm.

  1. If a line is drawn unclipped from [x1,y1] to [x2,y2] and if another line is drawn unclipped from [x1+dx,y1+dy] to [x2+dx,y2+dy], a point [x,y] is touched by drawing the first line if and only if the point [x+dx,y+dy] is touched by drawing the second line.
  2. Okay so, bestie, the effective set of points that make up a line cannot be changed by clipping. Like, a point is touched in a clipped line if and only if that point is inside the clipping region and it would have been touched by the line if you drew it unclipped. No cap. 🫢

A wide line drawn from [x1,y1] to [x2,y2] always draws the same pixels as a wide line drawn from [x2,y2] to [x1,y1] β€” not counting cap-style and join-style. It is recommended that this property be true for thin lines too, but it is not required. A line-width of zero may differ from a line-width of one in which pixels are drawn. This permits the use of many manufacturers’ line drawing hardware, which may run many times faster than the more precisely specified wide lines.

In general, drawing a thin line will be faster than drawing a wide line of width one. But because of their different drawing algorithms, thin lines may not mix well aesthetically with wide lines. If it is desirable to obtain precise and uniform results across all displays, a client should always use a line-width of one rather than a line-width of zero. That’s the vibe check: 1 for consistency, 0 for β€œtrust the hardware, bestie.” ✨

The line-style defines which sections of a line are drawn:

  • LineSolid β€” the full path of the line is drawn.
  • LineDoubleDash β€” the full path of the line is drawn, but the even dashes are filled differently from the odd dashes (see fill-style) with CapButt style used where even and odd dashes meet.
  • LineOnOffDash β€” only the even dashes are drawn, and cap-style applies to all internal ends of the individual dashes, except CapNotLast is treated as CapButt.

The cap-style defines how the endpoints of a path are drawn:

  • CapNotLast β€” this is equivalent to CapButt except that for a line-width of zero the final endpoint is not drawn.
  • CapButt β€” the line is square at the endpoint (perpendicular to the slope of the line) with no projection beyond.
  • CapRound β€” the line has a circular arc with the diameter equal to the line-width, centered on the endpoint. (This is equivalent to CapButt for line-width of zero.)
  • CapProjecting β€” the line is square at the end, but the path continues beyond the endpoint for a distance equal to half the line-width. (This is equivalent to CapButt for line-width of zero.)

The join-style defines how corners are drawn for wide lines:

  • JoinMiter β€” the outer edges of two lines extend to meet at an angle. However, if the angle is less than 11 degrees, then a JoinBevel join-style is used instead.
  • JoinRound β€” the corner is a circular arc with the diameter equal to the line-width, centered on the joinpoint.
  • JoinBevel β€” the corner has CapButt endpoint styles with the triangular notch filled.

For a line with coincident endpoints (x1=x2, y1=y2), when the cap-style is applied to both endpoints, the semantics depends on the line-width and the cap-style:

  • CapNotLast, thin β€” the results are device dependent, but the desired effect is that nothing is drawn.
  • CapButt, thin β€” the results are device dependent, but the desired effect is that a single pixel is drawn.
  • CapRound, thin β€” the results are the same as for CapButt/thin.
  • CapProjecting, thin β€” the results are the same as for CapButt/thin.
  • CapButt, wide β€” nothing is drawn.
  • CapRound, wide β€” the closed path is a circle, centered at the endpoint, and with the diameter equal to the line-width.
  • CapProjecting, wide β€” the closed path is a square, aligned with the coordinate axes, centered at the endpoint, and with the sides equal to the line-width.

For a line with coincident endpoints (x1=x2, y1=y2), when the join-style is applied at one or both endpoints, the effect is as if the line was removed from the overall path. However, if the total path consists of or is reduced to a single point joined with itself, the effect is the same as when the cap-style is applied at both endpoints. Tiny chaos, but make it fashion. πŸ’…

The tile/stipple represents an infinite two-dimensional plane, with the tile/stipple replicated in all dimensions. When that plane is superimposed on the drawable for use in a graphics operation, the upper-left corner of some instance of the tile/stipple is at the coordinates within the drawable specified by the tile/stipple origin. The tile/stipple and clip origins are interpreted relative to the origin of whatever destination drawable is specified in a graphics request. The tile pixmap must have the same root and depth as the GC, or a BadMatch error results. The stipple pixmap must have depth one and must have the same root as the GC, or a BadMatch error results. For stipple operations where the fill-style is FillStippled but not FillOpaqueStippled, the stipple pattern is tiled in a single plane and acts as an additional clip mask to be ANDed with the clip-mask. Although some sizes may be faster to use than others, any size pixmap can be used for tiling or stippling. Slay, but respect the depth rules. πŸ¦‹

The fill-style defines the contents of the source for line, text, and fill requests. For all text and fill requests (for example, XDrawText, XDrawText16, XFillRectangle, XFillPolygon, and XFillArc); for line requests with line-style LineSolid (for example, XDrawLine, XDrawSegments, XDrawRectangle, XDrawArc); and for the even dashes for line requests with line-style LineOnOffDash or LineDoubleDash, the following apply:

  • FillSolid β€” Foreground
  • FillTiled β€” Tile
  • FillOpaqueStippled β€” A tile with the same width and height as stipple, but with background everywhere stipple has a zero and with foreground everywhere stipple has a one
  • FillStippled β€” Foreground masked by stipple

When drawing lines with line-style LineDoubleDash, the odd dashes are controlled by the fill-style in the following manner:

  • FillSolid β€” Background
  • FillTiled β€” Same as for even dashes
  • FillOpaqueStippled β€” Same as for even dashes
  • FillStippled β€” Background masked by stipple

Storing a pixmap in a GC might or might not result in a copy being made. If the pixmap is later used as the destination for a graphics request, the change might or might not be reflected in the GC. If the pixmap is used simultaneously in a graphics request both as a destination and as a tile or stipple, the results are undefined. Bestie, that last one is a do not do it β€” undefined behavior is not cute. πŸ’€

For optimum performance, you should draw as much as possible with the same GC (without changing its components). The costs of changing GC components relative to using different GCs depend on the display hardware and the server implementation. It is quite likely that some amount of GC information will be cached in display hardware and that such hardware can only cache a small number of GCs.

The dashes value is actually a simplified form of the more general patterns that can be set with XSetDashes. Specifying a value of N is equivalent to specifying the two-element list [N, N] in XSetDashes. The value must be nonzero, or a BadValue error results.

The clip-mask restricts writes to the destination drawable. If the clip-mask is set to a pixmap, it must have depth one and have the same root as the GC, or a BadMatch error results. If clip-mask is set to None, the pixels are always drawn regardless of the clip origin. The clip-mask also can be set by calling the XSetClipRectangles or XSetRegion functions. Only pixels where the clip-mask has a bit set to 1 are drawn. Pixels are not drawn outside the area covered by the clip-mask or where the clip-mask has a bit set to 0. The clip-mask affects all graphics requests. The clip-mask does not clip sources. The clip-mask origin is interpreted relative to the origin of whatever destination drawable is specified in a graphics request. It’s giving β€œVIP list, but for pixels.” πŸŽ€

You can set the subwindow-mode to ClipByChildren or IncludeInferiors. For ClipByChildren, both source and destination windows are additionally clipped by all viewable InputOutput children. For IncludeInferiors, neither source nor destination window is clipped by inferiors. This will result in including subwindow contents in the source and drawing through subwindow boundaries of the destination. The use of IncludeInferiors on a window of one depth with mapped inferiors of differing depth is not illegal, but the semantics are undefined by the core protocol. Not illegal, just unhinged. πŸ™ˆ

The fill-rule defines what pixels are inside (drawn) for paths given in XFillPolygon requests and can be set to EvenOddRule or WindingRule. For EvenOddRule, a point is inside if an infinite ray with the point as origin crosses the path an odd number of times. For WindingRule, a point is inside if an infinite ray with the point as origin crosses an unequal number of clockwise and counterclockwise directed path segments. A clockwise directed path segment is one that crosses the ray from left to right as observed from the point. A counterclockwise segment is one that crosses the ray from right to left as observed from the point. The case where a directed line segment is coincident with the ray is uninteresting because you can simply choose a different ray that is not coincident with a segment. Problem solved, no drama. ✨

For both EvenOddRule and WindingRule, a point is infinitely small, and the path is an infinitely thin line. A pixel is inside if the center point of the pixel is inside and the center point is not on the boundary. If the center point is on the boundary, the pixel is inside if and only if the polygon interior is immediately to its right (x increasing direction). Pixels with centers on a horizontal edge are a special case and are inside if and only if the polygon interior is immediately below (y increasing direction). That’s the boundary tea, and yes, it is that specific. β˜•

The arc-mode controls filling in the XFillArcs function and can be set to ArcPieSlice or ArcChord. For ArcPieSlice, the arcs are pie-slice filled. For ArcChord, the arcs are chord filled. Both iconic, different vibes. πŸ“

The graphics-exposure flag controls GraphicsExpose event generation for XCopyArea and XCopyPlane requests (and any similar requests defined by extensions).

🚨 DIAGNOSTICS 🚨

okay bestie so when things go wrong (and they will, no cap) this is the roster of errors you might catch. each one is its own little vibe check fail πŸ’€

  • BadAlloc β€” the server literally could not allocate the resource or the server memory you asked for. it's giving "no thoughts, empty head, out of RAM" 😭
  • BadDrawable β€” you passed a Drawable argument that doesn't actually name a defined Window or Pixmap. like girl, that drawable does not exist πŸ™ˆ
  • BadFont β€” a Font or GContext argument doesn't name a defined Font. the font is not fonting ✨
  • BadGC β€” a GContext argument doesn't name a defined GContext. wrong GC, bestie, try again πŸ’…
  • BadMatch β€” an InputOnly window got used as a Drawable. input-only means input-only, she's not a canvas πŸŽ€
  • BadMatch β€” some argument (or pair of arguments) has the correct type and range but fails to match in some other way the request requires. so close yet so far 😭
  • BadPixmap β€” a Pixmap argument doesn't name a defined Pixmap. that pixmap is a ghost πŸ‘»
  • BadValue β€” some numeric value falls outside the range of values the request accepts. and listen: unless a specific range is specified for an argument, the full range defined by the argument's type is accepted. any argument defined as a set of alternatives can generate this error. so read your ranges, queen πŸ“

πŸ’– SEE ALSO πŸ’–

go off and read more, i promise these are all worth the hyperfixation πŸ¦‹

and obvi the big one: Xlib - C Language X Interface πŸ“š


that's the whole page babes, you made it to the end 🫢 this little masterpiece came to you courtesy of X Version 11, libX11 1.8.14, filed under XCreateGC(3). go forth and create some GCs, you absolute icon πŸ‘‘πŸ’œ

πŸ“¦ where this page comes from