Pen and palette C reference

These private services distinguish counted named-pen references from borrowed normal-palette entries. See Pens and style palettes for lifetime and selection rules.

Pen ownership and palette records

typedef struct PenStruct Pen
struct PenStruct

Common prefix of concrete drawing pens.

Named pens use counted references and deferred deletion; element-embedded pens follow their concrete owner lifetime. Keep this prefix compatible with concrete pen records.

Public Members

char *name

Named-pen identifier; embedded/default pens need not have a registry name.

Rbc_Uid classUid

Interned component class identifier.

char *typeId

Concrete pen type identifier used for compatibility checks.

unsigned int flags

Pen state bits, including PEN_DELETE_PENDING.

int refCount

Number of retained named-pen references.

Tcl_HashEntry *hashPtr

Registry entry referring to this record; NULL after detachment.

const Tk_OptionSpec *optionSpecs

Borrowed immutable option specifications for the concrete component type.

Tk_OptionTable optionTable

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

int optionsInitialized

Nonzero once Tk option initialization has completed.

int tkResourcesReleased

Nonzero after the guarded Tk-resource release pass.

PenConfigureProc *configProc

Concrete configuration hook; rebuilds resources for the owning graph.

PenDestroyProc *destroyProc

Concrete resource-release hook; generic pen teardown manages the record lifetime.

struct Weight

Cached numeric interval used for palette selection.

SetWeight initializes the endpoints and SetRange uses DBL_EPSILON when the endpoints do not form a positive interval.

Public Members

double min

Lower interval endpoint in weight units.

double max

Upper interval endpoint in weight units.

double range

Positive cached extent; max-min or DBL_EPSILON.

struct PenStyle

Palette entry and per-pen slices of mapped element geometry.

Named pen references are released with the palette; normal/default entries can borrow an embedded pen. Error-segment pointers borrow slices of element-owned storage.

Public Members

Weight weight

Weight range where this pen is valid.

Pen *penPtr

Selected pen; reference ownership follows the palette entry creation path.

Segment2D *xErrorBars

Borrowed start of this style X-error segment slice.

Segment2D *yErrorBars

Borrowed start of this style Y-error segment slice.

Tcl_Size xErrorBarCnt

Number of mapped X-error segments in this style slice.

Tcl_Size yErrorBarCnt

Number of mapped Y-error segments in this style slice.

int errorBarCapWidth

Mapped cap length in display pixels.

int symbolSize

Mapped symbol size in display pixels.

Pen lifecycle callback types

typedef Pen *PenCreateProc(void)

Allocate and initialize the common prefix of a concrete pen.

Return:

New pen record for the caller lifecycle; allocation policy belongs to the concrete constructor.

typedef int PenConfigureProc(Graph *graphPtr, Pen *penPtr)

Validate configured pen state and rebuild concrete drawing resources.

Param graphPtr:

[inout] Borrowed live owning graph; the callback must respect its current lifecycle phase.

Param penPtr:

[inout] Borrowed concrete pen whose resource state may be updated or released by this hook.

Return:

TCL_OK on success or TCL_ERROR with interpreter diagnostics.

typedef void PenDestroyProc(Graph *graphPtr, Pen *penPtr)

Release concrete pen drawing resources without freeing the common record.

Param graphPtr:

[inout] Borrowed live owning graph; the callback must respect its current lifecycle phase.

Param penPtr:

[inout] Borrowed concrete pen whose resource state may be updated or released by this hook.

Named pen references

int Rbc_GetPen(Graph *graphPtr, const char *name, Rbc_Uid classUid, Pen **penPtrPtr)

Acquire a reference to a named pen of a compatible concrete type.

Pair each successful acquisition with Rbc_FreePen. The returned pointer is graph-owned and must not outlive graph teardown.

Parameters:
  • graphPtr – Owning graph and interpreter for diagnostics.

  • name – Pen name to resolve; delete-pending pens are not found.

  • classUid – Required element class; strip and polar use line pens.

  • penPtrPtr – Receives the referenced pen on success.

Returns:

TCL_OK after incrementing refCount, or TCL_ERROR without acquisition.

void Rbc_FreePen(Graph *graphPtr, Pen *penPtr)

Release one acquired named-pen reference.

Decrements refCount and destroys the pen only when it reaches zero and PEN_DELETE_PENDING is set. Does not request deletion of a live named pen. Do not use for an uncounted embedded pen or a palette’s borrowed first entry.

Parameters:
  • graphPtr – Owning graph.

  • penPtr – Non-NULL pen for which the caller owns a counted reference.

Graph resource teardown

void Rbc_ReleasePenTkResources(Graph *graphPtr)

Release registered pen resources while the graph window is live.

Releases derived resources before Tk-owned option resources. Skips records not initialized or already released; leaves records and registry entries intact for later destruction. Does not release element-embedded pens.

Parameters:
  • graphPtr – Graph with initialized pen registry and live Tk window.

void Rbc_DestroyPens(Graph *graphPtr)

Destroy the graph’s remaining registered pens and pen hash table.

Does not wait for reference counts: element references must already have been released. Tk-dependent resources must be released before the window disappears. This destroys registry infrastructure and is not repeatable.

Parameters:
  • graphPtr – Owning graph during final teardown.

Element palettes

void Rbc_FreePalette(Graph *graphPtr, Rbc_Chain *palette)

Release named style entries while retaining the normal palette entry.

Releases pen references and removes links after the first entry. Does not release the first entry’s pen or destroy the chain itself. The caller owns the remaining chain and must destroy it when appropriate.

Parameters:
  • graphPtr – Owning graph used to release pen references.

  • palette – Valid palette chain; its first entry borrows the normal pen.

PenStyle **Rbc_StyleMap(Element *elemPtr)

Allocate a per-data-point map of borrowed palette style pointers.

Unmatched or unweighted points retain the first (normal) style. Weighted points search entries from last to first using normalized range tests with DBL_EPSILON tolerance. The map acquires no pen references and must not outlive its palette entries. Allocation-size overflow invokes Tcl_Panic.

Parameters:
  • elemPtr – Element with a valid nonempty palette and current data.

Returns:

Allocated pointer array owned by the caller; release with ckfree, including for zero points. Entries borrow styles from the element palette.

Named pen implementation

The implementation group uses a documentation-only rbcGrPen scope to separate file-local handler names (such as DeleteOp) from identical names in other modules. This does not rename C symbols or introduce a runtime namespace.

group Named pen internals

Private helpers; no new public API.

Functions

static int InitPenOptions(Graph *graphPtr, Pen *penPtr)

Initialize a named pen from its Pen option-database component.

Parameters:
  • graphPtr – Live owning graph with window and component proxy.

  • penPtr – Concrete pen with name and optionSpecs installed.

Returns:

TCL_OK when initialized (including an already initialized record), TCL_ERROR after releasing partial Tk options and the new table on failure. Normalizes the component resource name, releases that temporary name, and sets optionsInitialized only on success. Does not construct derived drawing GCs; the caller must run the concrete configurator afterward.

static int ConfigurePenOptions(Graph *graphPtr, Pen *penPtr, Tcl_Size objc, Tcl_Obj *const objv[])

Apply one named pen’s explicit Tk options and derived configuration.

Parameters:
  • graphPtr – Live owning graph and interpreter.

  • penPtr – Initialized concrete pen.

  • objc – Even number of option/value objects.

  • objv – Borrowed option/value array, valid throughout configuration.

Returns:

TCL_OK on commit, TCL_ERROR with a diagnostic on failure. Tk_SetOptions handles option conversion errors. If configProc fails, restore saved Tk options while preserving its diagnostic. Concrete configProc must stage its own derived resources before commit. On success release saved old options. This helper neither schedules redraw nor preserves objects across arbitrary callbacks; its caller owns their lifetime.

static void ReleasePenResources(Graph *graphPtr, Pen *penPtr)

Release a named pen’s drawing and Tk resources once.

Parameters:
  • graphPtr – Owning graph; a live Tk window is required for actual release.

  • penPtr – Concrete pen record retained after this call. Does nothing before successful option initialization or after prior release. Calls destroyProc before freeing Tk options, then deletes and clears the option table and marks tkResourcesReleased. Does not free the name, registry entry or record, nor change reference counts.

static Pen *NameToPen(Graph *graphPtr, Tcl_Obj *nameObj)

Find a visible named pen without acquiring a reference.

Parameters:
  • graphPtr – Live graph with initialized pen table and Tk window.

  • nameObj – Borrowed pen-name object.

Returns:

Borrowed Pen pointer, or NULL with a graph-interpreter diagnostic. Delete-pending records are hidden even when retained in the table. Does not check concrete type or increment refCount; use Rbc_GetPen for owned references.

static void DestroyPen(Graph *graphPtr, Pen *penPtr)

Remove a pen record and its registry entry without a reference check.

Parameters:
  • graphPtr – Owning graph in normal operation or ordered teardown.

  • penPtr – Pen whose users have already released their references. Releases Tk resources if still needed and the window remains live, then frees the nonempty owned name, deletes a non-NULL hash entry and frees the record. After window destruction, the caller must already have run resource release. Graph-wide teardown clears hashPtr first and deletes the table separately.

Pen *Rbc_CreatePen(Graph *graphPtr, const char *penName, Rbc_Uid classUid, Tcl_Size nOpts, Tcl_Obj *const options[])

Create a named concrete pen or revive a matching retained record.

Parameters:
  • graphPtr – Live owning graph.

  • penName – Borrowed name to register.

  • classUid – Default pen class; strip and polar are normalized to line.

  • nOpts – Number of explicit option/value objects, expected to be even.

  • options – Borrowed options, valid throughout initialization/configuration.

Returns:

Graph-owned Pen pointer without a new counted reference, or NULL on error. Scans -type prefixes of length three through five before allocation; the last recognized occurrence selects bar or line (strip selects line). Existing live names and incompatible pending types fail. New records are removed on failed initialization or configuration. A matching pending record is reused, but its PEN_DELETE_PENDING flag is cleared only after configuration succeeds, so failed revival keeps the retained record hidden. No redraw is scheduled here; acquiring a long-lived reference requires Rbc_GetPen.

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

Return the current value of one named pen option.

Parameters:
  • graphPtr – Live owning graph.

  • interp – Command interpreter.

  • objc – Full widget-command argument count, already checked by dispatch.

  • objv – Borrowed full argument vector, with pen subcommand at index two. Looks up objv[3] without acquiring a reference, then uses Tk_GetOptionValue for objv[4]. Returns TCL_ERROR on lookup/conversion failure; otherwise installs the returned Tcl object as the result. No configuration or redraw occurs.

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

Query or configure one or more named pens.

Parameters:
  • graphPtr – Live owning graph.

  • interp – Command interpreter.

  • objc – Full widget-command argument count, already checked by dispatch.

  • objv – Borrowed full argument vector, with pen subcommand at index two. Treats the first argument beginning with a dash as the option boundary and checks preceding names before applying changes. Zero or one option arguments query only the first pen. Updates run in name order and stop at the first failure; earlier commits remain. Successfully changed referenced pens cause backing-store and margin redraw, including when a later pen fails. Returns TCL_OK or TCL_ERROR; does not provide a transaction across all named pens.

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

Create a pen using the graph class as the default.

Parameters:
  • graphPtr – Live owning graph.

  • interp – Command interpreter.

  • objc – Full widget-command argument count, already checked by dispatch.

  • objv – Borrowed full argument vector, with pen subcommand at index two. Passes objv[3] and trailing options to Rbc_CreatePen. Returns TCL_ERROR on failure, otherwise sets the original name object as the result and returns TCL_OK. Does not acquire a counted reference to the returned pen.

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

Hide named pens and destroy those with no remaining references.

Parameters:
  • graphPtr – Live owning graph.

  • interp – Command interpreter.

  • objc – Full widget-command argument count, already checked by dispatch.

  • objv – Borrowed full argument vector, with pen subcommand at index two. Processes names in order, sets PEN_DELETE_PENDING and immediately destroys zero-reference records. Returns TCL_ERROR at the first unavailable name; earlier deletions remain. An empty name sequence succeeds. Repeated names therefore fail after the first deletion rather than being silently ignored.

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

List visible pen names matching any supplied glob pattern.

Parameters:
  • graphPtr – Live owning graph.

  • interp – Command interpreter.

  • objc – Full widget-command argument count, already checked by dispatch.

  • objv – Borrowed full argument vector, with pen subcommand at index two. Walks the hash table, skips pending records and appends each matching name once, even if multiple patterns match. With no patterns, returns all visible names. Result order is hash traversal order, not sorting or creation order. Returns TCL_OK without acquiring references to listed pens.

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

Return the concrete class identifier of a visible pen.

Parameters:
  • graphPtr – Live owning graph.

  • interp – Command interpreter.

  • objc – Full widget-command argument count, already checked by dispatch.

  • objv – Borrowed full argument vector, with pen subcommand at index two. Looks up objv[3] and returns its classUid as a Tcl string. Returns TCL_ERROR for unknown or delete-pending names. Strip/polar uses report the normalized line implementation rather than a distinct pen class.

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

Dispatch a typed named-pen subcommand.

Parameters:
  • graphPtr – Live owning graph.

  • interp – Command interpreter.

  • objc – Full widget-command argument count, already checked by dispatch.

  • objv – Borrowed full argument vector, with pen subcommand at index two. Uses Rbc_GetOpIndexFromObj to validate the subcommand and argument bounds, then invokes its typed handler. Returns the handler result or TCL_ERROR from dispatch. Handler-specific parsing still validates option/value structure. This dispatcher supplies no independent graph or pen lifetime protection.

Palette implementation

group Element palette internals

Private helpers; no new public API.

Functions

static int GetPenStyleFromObj(Graph *graphPtr, Tcl_Obj *objPtr, Rbc_Uid type, PenStyle *stylePtr)

Parse one palette style and acquire its named pen reference.

Parameters:
  • graphPtr – Live graph and interpreter for lookup/errors.

  • objPtr – Borrowed list containing penName or penName/min/max.

  • type – Required element pen class, normalized by Rbc_GetPen.

  • stylePtr – Candidate style with default weight already initialized.

Returns:

TCL_OK transferring one pen reference, or TCL_ERROR without changing stylePtr. Numeric endpoints are converted before acquiring the reference. The one-name form preserves the candidate weight. Three items replace it via SetWeight; no ascending-range check is performed here. This helper does not release an existing destination pen and does not evaluate Tcl expressions.

static ElemPenOption GetElemPenOption(Element *elemPtr, Tcl_Obj *objPtr)

Recover the canonical active or normal pen option identity.

Parameters:
  • elemPtr – Element with its concrete optionSpecs.

  • objPtr – Borrowed original option-name object.

Returns:

ELEM_PEN_OPTION_ACTIVE, ELEM_PEN_OPTION_NORMAL or NONE. Uses Rbc_GetCanonicalOptionName after Tk option validation, recognizing aliases and accepted abbreviations. Does not acquire references or alter the element.

static int StageElemPen(Graph *graphPtr, Tcl_Obj *objPtr, Rbc_Uid penType, ElemPenTransaction *transactionPtr, Pen **candidatePtrPtr, ElemPenOption option)

Acquire a candidate pen before releasing an earlier staged reference.

Parameters:
  • graphPtr – Live owning graph.

  • objPtr – Borrowed pen name; NULL/empty stages no named pen.

  • penType – Required concrete pen class.

  • transactionPtr – Initialized pen transaction owning previous candidates.

  • candidatePtrPtr – Address of the corresponding candidate pointer.

  • option – ACTIVE or NORMAL, matching candidatePtrPtr.

Returns:

TCL_OK on staging, TCL_ERROR retaining the prior candidate on lookup failure. Marks the option staged even for NULL. The later normal-pen commit substitutes the built-in pen; active NULL disables the active pen. The live element is untouched, and any acquired reference belongs to the transaction.

static int IsElemStylesOption(Element *elemPtr, Tcl_Obj *objPtr)

Recognize the canonical styles option after Tk validation.

Parameters:
  • elemPtr – Element with concrete optionSpecs.

  • objPtr – Borrowed original option-name object.

Returns:

Nonzero for -styles, zero for unrelated or unresolved names. Does not parse the option value, acquire pens or modify the element.

static int StageElemStyles(Graph *graphPtr, Element *elemPtr, Tcl_Obj *objPtr, Rbc_Uid penType, size_t styleSize, ElemStylesTransaction *transactionPtr)

Replace a staged palette only after parsing its successor.

Parameters:
  • graphPtr – Live owning graph.

  • elemPtr – Element supplying class and borrowed normal pen.

  • objPtr – Borrowed style-list object; NULL means no additional styles.

  • penType – Retained interface argument; currently unused by this helper.

  • styleSize – Concrete style-record size, at least sizeof(PenStyle).

  • transactionPtr – Initialized transaction owning any previous palette.

Returns:

TCL_OK on staging; TCL_ERROR retains the previous candidate. ParseStylesObj checks pens against elemPtr’s class. Success destroys the prior candidate, stores the new chain and marks it staged, without replacing the live element palette.

static void DestroyPalette(Graph *graphPtr, Rbc_Chain *palette)

Destroy an entire candidate or retired palette chain.

Parameters:
  • graphPtr – Owning graph used to release counted named-pen references.

  • palette – Owned chain or NULL. Releases entries after the reserved first entry through Rbc_FreePalette, then destroys the chain including that first entry. Its normal pen is borrowed and is not released. NULL is accepted; no live element pointer is changed.

static int ParseStylesObj(Graph *graphPtr, Element *elemPtr, Tcl_Obj *objPtr, size_t styleSize, Rbc_Chain **palettePtrPtr)

Build a candidate palette with a reserved normal-style entry.

Parameters:
  • graphPtr – Live graph and interpreter.

  • elemPtr – Element supplying class and normal-pen pointer.

  • objPtr – Borrowed list of styles; NULL represents an empty list.

  • styleSize – Concrete record size, at least sizeof(PenStyle).

  • palettePtrPtr – [out] Cleared first; receives an owned chain on success.

Returns:

TCL_OK on success, TCL_ERROR after releasing partial storage and pen references. Does not dispose of a prior output pointer or change the element. The first entry always borrows the normal pen. Additional entries acquire pens and default to weight intervals i through i+1 (zero-based). Explicit endpoints replace those defaults. An invalid unattached entry is freed separately before destroying the partial chain. Caller must eventually commit or destroy output.

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 PenOpSpec

Typed command dispatch entry with shared argument validation metadata.

Public Members

Rbc_OpSpecHeader header

Operation name, total argument bounds and usage suffix.

RbcGrPenOp *proc

Typed command handler for this operation.