Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

Tcl/Tk in a Nutshell

Dietmar Theobald

March 1996 STONE Report FZI.59.4

An earlier version of this report has also been published as FZI report 17/93.

STONE
A Structured and Open Environment

Title:

Tcl/Tk in a Nutshell

Author(s):

Dietmar Theobald

Date: Result #: Status: Distribution:

March 1996 FZI.59.4 nished public

Address:

Forschungszentrum Informatik (FZI) Database Research Group Haid-und-Neu-Strae 10-14 D-76131 Karlsruhe Germany email: {theobald, obst}@fzi.de An earlier version of this report has also been published as FZI report 17/93.

Tcl/Tk in a Nutshell
Dietmar Theobald
Forschungszentrum Informatik (FZI) Database Research Group Haid-und-Neu-Strae 10-14 D-76131 Karlsruhe email: {theobald,obst}@fzi.de March 1996 Abstract This text is a formatted excerpt compiled while studying some documentation related to Tcl/ Tk. It is intended to serve for a quick overview, as base material for presentations, as background information, and as a notebook which I will extend/modify in line with my ongoing work with the Tcl/Tk toolkit. The description covers Tcl 7.5 and Tk 4.1, as described in [Ous96] and [Ous94], plus XF as described in [Del93].

Table of Contents
1. Tcl / Tk - Overview 2. Core Tcl
2.1 2.2 2.3 3.1 3.2 Core Language Core Tcl Library Meta Level / Interface to Tcl Runtime System Overview Library Interface Tk - Overview Tk Widgets Widget Configuration Geometry Management Events Application Communication/Cooperation Miscellaneous Interface Builder Concepts Usage

2 4
4 5 10

3. Tcl and C/C++

12
12 13

4. Tk
4.1 4.2 4.3 4.4 4.5 4.6 4.7 5.1 5.2

16
16 18 22 23 25 26 27

5. XF - Interactive Interface Builder for Tcl/Tk

28
28 29

References

32

D. Theobald

1.

Tcl / Tk - Overview

Tcl - Tool Command Language (tickle) simple interpretative programming language - data type: string, lists as formatted strings - variables, (associative) arrays - C like expressions: string, arithmetic, boolean - conditionals, loops, procedures - le handling, program execution - meta level: name bindings, activation stack UNIX / C environment command set extendible (by C functions) not intended (suited) for programming-in-the-large Tk Motif-style X toolkit RPC-like communication mechanism on Tcl level for Tk applications embedded in Tcl - create, access, modify user interface elements on Tcl level at runtime - callback, event handlers: Tcl commands generic application: windowing shell wish command language centered approach command language necessary for interactive applications: command line options, textual, graphical typical command languages - added afterwards, ad hoc, limited, tied to specic program/purpose - difcult to (re)use, extent, modify - need to learn different command language for each application advantages of command language centered approach - general-purpose command language added to application * tailor, customize application * scripting, extensions: simple programs with low development effort * initial design no hard limit - uniform command language (one language for several applications) * decreased learning effort * application communication on level of command language - interpreted language: fast turn-around, rapid prototyping Tcl/Tk applications toolkit/component-oriented approach with Tcl/Tk as infrastructure (glue) - tool environment assembled from applications communicating using send (or sth. similar) - application-specic functionality embedded in basic command language Tcl * commands: extend Tcl command set * data: mapped directly to strings, indirectly onto names/handles * customized Tcl/Tk interpreter (Fwish) as generic application also possible: customized interpreter with just Tcl, not Tk (*tclsh) Tcl/Tk interface visible to - end user: additional shell-like interface - application programmer: top level of program

Tcl/Tk in a Nutshell

typical application - Fwish script - Tk (Tcl) level * not visible to end user * top level of application program interactive shell - like Unix shells - standard shells: initialization script (~/.tclshrc, ~/.wishrc) non-interactive mode script interactive mode
initialization script

customized wish - Fwish init commands parser result command line reader wish/main register application commands

arguments

result Tcl library

command function

Tk library

application library

Standard/X libraries

D. Theobald

2.
2.1

Core Tcl
Core Language

no grammar as in other programming languages, just command sequences as structure command script sequence of commands separated by ; or <newline> line continuation by \<newline>: break plus leading space in next line replaced by single blank evaluation - script le: source <filename> result: last command, return <value> - procedure body: invoke as command result: last command, return <value> - eval/uplevel <command script> command sequence of words separated by white space - rst word: command name - remaining words * (positional) arguments: arbitrary string values * interpretation left completely to command, Tcl parser doesnt know argument types procedure or C function (built-in / application-dened) returns string plus result code: normal / exceptional returns standard commands accept (unique) abbreviations for command options substitutions 3 basic rules - each character scanned just once - no further substitutions in substitution result - substitutions do not change how commands are broken into words variable value ($<variable name>, ${<simple variable name>}) command (script) result ([<command script>]) quoting - special characters: backslash substitution (\<character code>; cf. ANSI-C) - word (string) with substitutions applied (<string>) - word (string) without substitutions (except for \<newline>) applied ({<string>}) defers evaluation, e.g. for passing command scripts as arguments (line) comments (# as rst non-blank character of command, extend until line end, \<newline> extends line) name scopes global: variables, procedures, commands local to procedure: variables variables name, value: string name of simple variables (no arrays) may be bracketed for variable substitutions (${<name>}) operations - read, write, (efciently) append string, increment integer value by integer - created at rst assignment (set), no preceding declaration - remove (unset): simple variable, array element, array - trigger on read, write, remove (trace) array - collection of related variables (== elements) - array elements can be used whereever simple variables are admissible - array name, array index: string ( associative arrays)

Tcl/Tk in a Nutshell

- multidimensional array: can be simulated by formatted index string - iteration via (efcient) array cursors - queries: size, current index names - no direct array copy, contents can be set/queried as list of successive indexvalue elements data types string: arbitrary 8-bit characters except for NUL (\0) dynamic (pseudo) types: string formats, interpreted/checked at time of use - command script * each list is a well-formed command where the lists elements are the commands words - expression, numeric literal - list - application-dened array (operationally dened: variable substitution, array, (un)set) expressions command result result code plus associated string value normal return exceptional return - unwind activation stack (script les, commands, procedures) until result code processable / at top level - error * error information - error message (string associated to error; accessible via catch) - data added when unwinding activation stack ($errorInfo) - optional, geared to processing in programs ($errorCode): list, 1st element selector for error class * processing: catch, (re)raise (error, return)
exception code (code value) other commandsa

string value

catch

proc/source

loop commands

normal return (0) error (1) return (2) break (3) / continue (4) other

result value error message script / procedure value (optional) user-dened

process process process process process

process pass on, add error info process error pass on

process pass on, add error info pass on process pass on

process pass on, add error info pass on pass on pass on

a. Only applicable to commands which recursively evaluate command scripts. Depending on the command, the handling of return codes might also differ from the shown standard behavior.

2.2

Core Tcl Library

list processing ordered collection of elements (strings), including (sub)lists operations - constructors (from elements/partial lists), modiers (insert/replace partial list, append (efciently) to list variable), convert list to/from string - querying (length, search for pattern), extractors (element, partial list by index) - sorting (increasing/decreasing, lexicographic/numeric/application-dened order)

D. Theobald

expression evaluation literals - numeric: decimal, octal, hexadecimal, oating-point (ANSI-C literals) - boolean (0/false/off/no, 0/true/on/yes) operators - as in ANSI-C: arithmetic, relational, logical, bitwise, choice (..?..:..) - differences to ANSI-C: no ++/--, relational operators also applicable to strings, / truncates result of integer operands to integer, result of % (remainder) always positive - some operators work only on integers/numbers functions as in ANSI-C math library: trigonometric, exponentation, square (root), logarithms, conversions command, variable substitution coercions: integer oating-point string; explicit conversions: integer oating-point string double-precision oating-point arithmetic conversion to string only when required, with adjustable precision ($tcl_precision) functions but not types, operators extendible by application: via Tcls C library interface general hook: Tcl command substitution command script evaluation (cf. 2.1) control structures (ordinary) commands which take command scripts as arguments, no special grammar for control structures can be implemented by procedures selection - if...elseif...else... - switch: pattern matching (exact, csh-style, regular expression, default label) to select a single case loops - for (analogous to C/C++), while - foreach * loop over single list / several lists * one/several loop variables per input list take consecutive elements, #variables is #elements processed per iteration - break (leave innermost loop), continue (next iteration of innermost loop) procedures command implemented by command script, usage equivalent to C function commands return <result>, optionally add (exceptional) return code dynamic: denition / renaming / deletion at run-time (proc, rename) parameters - positional arguments - trailing part of parameter list may have default arguments - variable argument number in call: last parameter (named args) takes remaining tail of argument list - parameter denes (initialized) local variable variables - local by default - global variables must be explicitly imported (global, upvar), will then hide local names - import establishes only name binding, imported variable does not have to exist yet - only global variables retain values across procedure invocations (no local static variables as in C/C++) procedure context can be changed to any active procedure (relative to current/absolute), or global level for: - variables (upvar): import variable from other scope, giving it a local name reference parameters by passing variable names from another scope to a procedure - commands (uplevel): execute in other name scope macros/control structures can be implemented by procedures

Tcl/Tk in a Nutshell

string handling analogue of C/C++ functionality - string library string: length, (lexicographic) comparison, case conversion, remove specic leading/ trailing characters, access character/substring, nd word boundaries/substring - scan/format (cf. scanf/printf) - most simple usages covered by standard parsing/substitution rules (e.g. construction using ...-, {...}-quoting) regular expression matching / substitutions: sed/egrep-like, (c)sh-style pattern matching interpreter (interp / <interpreter name>) central internal abstraction - name bindings / name spaces: variables, procedures, commands - procedure activation stack - named (master slave) hierarchy of interpreters - hierarchical path name for slaves relative to one of its masters, concatenated list of interpreter names ({} current interpreter) - slaves controlled by / dependent on master, destroyed with master - create/delete slave(s), check for specic slave, check whether interpreter is safe or trusted safe interpreters - restricted command set: cant cause harmful side effects - automatic restriction for core Tcl, conforming extensions restrict too information sharing between interpreters - only if explicitly established by an (indirect) master - between master slave, between slaves of common (indirect) master - via environment variables - via extension ( Tks send), interprocess communication, les, ... - via IO channels * default: channels not shared between interpreters * share between master slave, slave slave: same permissions, all must close to close channel * transfer channel to another interpreter - via command script evaluation - not: via Tcl variables command script evaluation - master may invoke any command in slave - only with explicit permission: slave invoking commands in sibling slave / master - alias: by any master grant execution rights for target command in master / sibling * analogy: kernel call in operating systems * mapping: slave command target command + head of argument list (optional) * invocation: target command + head of argument list + argument list from slave * loose coupling: target command doesnt have to exist until execution * dene/delete alias; query: list all / specic alias(es) in slave, target interpreter where alias executes security - alias name as seen from master doesnt change by renaming it in slave - data ( arguments) from slave are not evaluated in target interpreter unless explicitly requested target commands must not trigger substitutions on / evaluate received data - restrictions for safe interpreters * only safe slaves are created * no side effects outside of safe interpreter, e.g. not: process execution, IO operations, ... * no access to environment variables

D. Theobald

event handling event loop - core Tcl * only processed on-demand (update, vwait) * commands requiring processing: timer / idle events (after), server-side socket connections - event-driven programs ( Tk interpreters): built around event loop event handler - identiable ( ID returned upon creation) representation for event that is waited for - create / delete / query for handler action ( Tcl command script) command scheduling (after) - execute Tcl command script once: after delay (in ms), when no other events are pending (when idle) - scheduled command identied by: handler ID, command script process events until variable is written (vwait) IO channel handling generic common channel interface - uniform treatment: les, pipes, sockets - open channel identied by handle, automatically closed when destroying interpreter - standard IO channels: stdin, stdout, stderr - properties * asynchronous (non-blocking; not for standard IO channels of process) / synchronous (blocking; default) affects: read, write, ush, close * buffering - none / by line (default for terminals) / until buffer full (default otherwise) - buffer size; transparently (temporarily) extended for non-blocking channel if full * treatment of line ends internally always \n, externally: \r, or \r\n, or \n; set explicitly / automatically - operations * open (per channel type), close, ush, byte-/line-oriented read/write, random access (query/set position) * query/set property/-ies, check for eof / whether input data is available - IO event handler * execute when channel becomes readable / writable, always when error condition on channel * at most one readable and one writable handler per channel * destroyed by: closing channel / when execution yields error * intended for use with non-blocking channels (unnamed) pipe: created by executing sub-processes (see below) sockets (socket) - TCP network connection: client / server side - servers * separate communication channel for each connection to client * upon connection request: create channel, invoke application-dened callback * server channel itself: only used to accept clients / close down server (by closing channel) le handling - analogue of POSIX C/C++ le IO library - file: le attributes (type, permissions, size, time tags, ownership) via predicate functions, query all attribute values, target of symbolic link - query/set current working directory (pwd, cd)

Tcl/Tk in a Nutshell

- le names * consistent universal treatment throughout Tcl * native form: platform-specic (Mac, Unix, Windows) * network form - Tcl-specic format, portable: supported on any platform if at all possible to evaluate there - interpretation as network name takes precedence when ambiguous * tilde substitution: home directory of any (Unix only) / this user * conversions: network native form (file ...) * expansion of path name pattern; like csh, but: not sorted, yields only existing les * operations on pathnames handling directory part, base part, extension (file ...) process handling ID of current process / processes connected via pipe exit current process, return exit code read/modify environment variables via env array (automatically mapped to process environment) sub-processes - execute single process / process pipeline (exec ...) - open pipe connection to sub-proces(ses) (open |...) - I/O redirection: standard output/error, append to/overwrite le/channel, input from le/channel/string, Tcl IDs of open channels can be used - background execution (then no error handling, list of process IDs as result) - result: standard output of last sub-process in pipeline - error if any output to standard error, or abnormal exit of any sub-process miscellaneous error handling - application denable hook (bgerror) for displaying/processing unhandled errors - default if not present: log onto standard error stream clock / time processing (clock) - normalized format: seconds since reference time point, standard Tcl time representation ( file) - print/parse date in variety of formats, perform time zone conversion, standard names as modiers (today, ...) library / package management base mechanisms - load Tcl code (source) - load binary code le (load) into current / named trusted/safe interpreter * load statically / on-demand (behaviour/error detection and handling depends on platform) * invoke initialization function in loaded code name derived by default rule / from package name and interpreter kind (trusted / safe) on-demand loading - concept * directory search path, index le per directory * handler for event access non-available resource: process indices, loads resource - default action in index le: load code - index le: cached in Tcl array, contains standard Tcl code simple, extensible, general basic Tcl code libraries: autoloading facility - directory search path (dened via $auto_path, $tcl_library, $env(TCL_LIBRARY)) - execute action dened in directory-local index le (auto_load), using the procedure name as key - utility to generate default index le (auto_mkindex): conventions for indexed / hidden procedures - default unknown handler: unknown (see below)

D. Theobald

10

packages (package) - versioned code base: binary and/or Tcl code - predened version number semantics * major version number, optional: (several) minor version number(s) * major number increases iff package API changes in incompatible manner * denes relations: earlier version, compatible version - set/query unknown package handler, query: known packages, known version of specic package - declare package interface: dene load action for a package version, declare package as loaded - request package: exact / newest compatible / newest version, use already loaded version if its compatible - load package on-demand * actions dened in package index, key: package name and package version * default index le generated by pkg_mkIndex utility * default unknown package handler: load index le(s) into main memory, prepare loading, load code at latest on rst use of command (load, auto_load) standard library with Tcl code (info library) - similar use of library directories often by Tcl extensions (notably Tk) - code that is not intimately tied to the Tcl language, or to Tcl extensions unknown exception handler, triggered by invocation of unknown command default handler: autoloading (can be disabled: $auto_noload), execute program as sub-process if found (can be disabled: $auto_noexec), command abbreviations, history substitutions history list simple csh-like history substitutions implemented based on operations below and unknown list of pairs: event index command usually in shell applications to record interactively typed commands operations: print list, append command, retrieve/re-execute by relative/absolute index / pattern, modify in list/ before (re)execution, get event index, set maximum list size

2.3

Meta Level / Interface to Tcl Runtime System

interpreter dene / query alias(es) dene / query slave interpreter(s), check whether interpreter is safe variables / arrays variable / array element / array - dene, remove ((un)set) - exact name match (exists, array exists) - global/local variables by pattern (info vars/globals/locals) - set/remove/retrieve operation triggers (trace) * triggering operations: read/write/remove * trigger action - command script - executed in context of triggering operation after the variable has been written/removed, respectively before it is read - read/write triggers may abort read/write operation, or change the read/written value * execution order - inverse denition order (most recently dened rst) - array triggers are activated before triggers for array elements * triggers can be set on not yet existing variables * trigger removed implicitly by variable removal

11

Tcl/Tk in a Nutshell

* remove-trigger not activated when Tcl interpreter gets destroyed procedure dene / remove / rename (proc, rename) queries - retrieve names: all/by pattern (info procs) - retrieve by name: body, parameter list, default argument (info body/args/default) - (procedure) activation stack (info level) * depth, procedure name, argument list by stack index * local variables at current level (info locals) commands remove / rename (rename) retrieve names: all/by pattern (info commands) unknown command parsing ( interactive shells): command complete/missing text ? (info complete) standard Tcl/Tk shell access command line arguments ($argc, $argv, $argv0) interactive? ($tcl_interactive); prompts used by interactive shells ($tcl_prompt1/2) miscellaneous platform - analogue of uname on Unix (array tcl_platform), shared libraries (info sharedlibextension) - current host (info hostname) - currently executed script le (info script) / binary (info nameofexecutable) version (info tclversion, $tcl_version), patchlevel (info patchlevel, $tcl_patchlevel) performance - command (script) timing (time) - number of command executions so far (info cmdcount)

D. Theobald

12

3.
3.1

Tcl and C/C++


Overview

Tcl applications in C/C++ Tcl/Tk programming interface (header les) usable in C/C++ programs use of Tcl/Tk only as library: string handling, hash module, Tk utilities, ... standard Tcl interpreter usage - create interpreter object - initialize Tcl extensions: register commands, initialize data - command loop * read command string (script) * evaluate * print/process result/error typical application development: based on customized wish choose/built Tcl/Tk extensions (packages) - publicly available (extended Tcl (TclX), networking communication, additional widgets, ...) - application-specic * should be structured as externally usable package if possible * guidelines/conventions for naming of types, functions, Tcl commands, variables: use at least unique prex to avoid name clashes * package initialization: should cope with several invocations (for different interpreters) wish customization: add extension initialization to initialization code (Tcl_AppInit function) application: script le for customized wish - Tk (Tcl) level often not directly visible to end user Tcl commands implemented in C/C++ used in Tcl scripts like (Tcl) procedures design guidelines - only basic commands in C/C++ * clean, orthogonal set of primitives * level high enough to hide details / allow efcient implementation - combination of basic functionality in Tcl scripts - command interface should be oriented towards usability (simple processing) in Tcl scripts - pro Tcl (procedure) * smaller * shorter turn-around time - pro C/C++ (function) * access to C/C++ libraries * efciency * structuring concepts for larger programs - unique command names (e.g. unique prexes) command style - action-oriented * one command per action, parameter: object name * many objects, or objects with short or unpredictable life span - object-oriented * one command per object, 1st parameter: action name

13

Tcl/Tk in a Nutshell

map application data to strings direct (e.g. numbers, ...) indirect using handles - unambiguous name space (e.g. unique prexes) - no internal/implementation oriented names, employ mapping instead (e.g. name address) - object-oriented command style: command name == data handle

3.2

Library Interface

interpreter central data structure - bindings for: variable / procedure / command names / application-specic data - (Tcl-)procedure activation stack (activation of C command implementations handled via CPU stack) - result (string) for active / last completed command, managed by Tcl library several interpreters per process possible operations - create / destroy interpreter (fast): top-level, slave; make interpreter safe (removes all extensions) - get named slave / direct master, get interpreter path name, check whether interpreter is safe - create command alias / query alias(es) - evaluate * at local / global procedure activation level * script (must be writable string) / script le, optionally enter in history list (for interactively typed code) * expression with constrained result type: general (string), integer, oating-point, boolean - application-specic data associated with interpreter * key: string; data: word ( C/C++ pointer / int); callbacks: to be overwritten, interpreter deletion * dene / overwrite, look up, delete command function C/C++ representation of Tcl command, treated identical to built-in Tcl/Tk command functions signature - associated data (one word, cf. clientData in X11 callbacks), command ID (unchanged when renaming) - argc/argv interface for command arguments arguments will have all substitutions applied, should not be modied - interpreter (execution context) - result code operations - register / remove command function, callback: command/interpreter deletion one function can be registered under several names (used for object-oriented command style; cf. 3.1) - get current command name by ID, get/set associated data, check for existence - manage result string * attached to interpreter * default: xed size result area for short results, initially empty * further admissible result strings: statically/dynamically allocated by standard/application dened storage allocator * reset, append one/several strings mathematical function dene / override function for expr: name, list of arguments and their types (integer, oating-point, both) command completion codes (see 2.1) OK / exception code if exception: unwind command activation stack until reaching global level or command handling exception

D. Theobald

14

special exception: error occurred - error message created/returned like normal result string - error origin * store readable error message as result string * dene program-processable error description - optional, should be done if error could be catched and handled - list, rst element names error category (no restrictions except to prevent name clashes) - core Tcl uses error categories ARITH, CHILDKILLED, CHILDSTATUS, CHILDSUSP, POSIX, NONE (no description) - add information when unwinding command stack, i.e. evaluation of a command script returned error * automatically done by Tcl library except for recursive evaluations inside command functions * about this command * error location in command script (provided via associated interpreter) variables procedural interface analogous to Tcl language level (see 2.1): read/write/remove/trace variables/array elements/arrays - 2 variants: variable name to be parsed by Tcl library, or not (parsing tells array elements from simple variables) special support - append string, append as list element, convert new value to list element - access variable at global level - set error message in error case (e.g. unknown variable name) triggers analogous to Tcl level, except - C/C++ action functions (no Tcl script) - additional (arbitrary) value, dened at trigger registration time - remove-trigger activated by interpreter destruction (not possible on Tcl level due to missing interpreter) (un)link Tcl variable to C variable (double, int, boolean int, char*) - value is actually stored in C variable, Tcl variable can be read-only - Tcl variable automatically re-created after removal - except for char*: type check when changing Tcl variable event handling handlers - identied by tokens, returned by create operation - create (and activate) / delete lower layer: event notier module - mostly platform-independent, except for procedures that handle waiting / basic event detection - event sources: extensible set; core functionality for event handler creation / event detection - event queue * one queue per process * add at head / near head / at end; remove and process / keep event on queue - wait for (optional: timeout, process only ready events) and then process next event kinds any / window system / le / timer / idle event types - asynchronous le events: create / delete / trigger for safe evaluation / query / process pending handler(s) - channel events: create / delete handler events writable, readable, exception, channel closed / unregistered - timer events: create / delete - idle events: install / remove callback (no handler created here) - window event (added by extensions Tk): create / delete handler for selected user interface event types

15

Tcl/Tk in a Nutshell

IO channel interface lower level - channel type specic drivers: le, sockets - operations: create / open / close / read / write / set IO position / set blocking mode / get/set properties - access channel data (input/output stream, name, properties) / (un)register channel - access standard channels: stdin, stdout, stderr generic level - device / platform independent, extensible: buffered, (non-)blocking IO - generic: close, read, write, ush, set/get IO position, check for eof / blocked channel, set/get channel option / buffersize / line translation mode - type specic (le, (sub)process pipeline, client/server side socket): open channel, convert platform-specic resource representation into channel representation application (shell executable) hook for application-specic initialization, callbacks for application exit: create / delete standard Tcl/Tk main function contained in libraries explicit exit point to end application typical programming tasks for shell/application builder: initialization, invoke Tcl/Tk main function utilities (C functions) parsing - parse literal: integer, oating-point, boolean - check if string contains open braces (otherwise: syntactically complete command script) string utilities - split list in argc/argv array holding list elements, create list from such array - csh-style pattern matching - regular expressions: pre-compile expression, execute / match, extract matched (sub-)range(s) - dynamic strings * efcient handling of strings which can grow large by appending to the end * initialize / free storage, append string / list element, start/end sublist, get string / string length, shorten string, use string as / initialize string from interpreters result hash table module - self-reorganizing - data: up to size of C/C++ pointer; key types: string, memory word, xed-length byte array - operations * table: initialize/destroy, cursor-based (one-directional) iteration, statistics * entry: nd or enter / nd / delete, get key, get/set data operation system utilities (POSIX) - le names: get platform-specic name by tilde substitution, translation of network name representation - get/set error status, report Tcl-style error messages, names for error codes / signal codes, signal descriptions - create process pipeline, optionally including I/O redirection - announce possibly terminated / collect terminated sub-processes misc - process background error - library management * request / declare package and its version * declare package code as already statically linked to executable

D. Theobald

16

4.
4.1

Tk
Tk - Overview

Tk X widget set on Unix - layered on top of the basic X11 layer (Xlib), not on top of other X toolkits (such as Xt) - optimized (reduced) communication with X server through delayed screen updates, caches for sharing X11 resources in an application (graphic contexts, colors, cursors, fonts, bitmaps/images, ...) C library interface - interface for extension by additional widgets / geometry managers / image formats - auxiliary functions embedded in Tcl by extending Tcl command set Tk library can be loaded dynamically into trusted master/slave interpreter, but not into safe interpreter builtin widgets implement Motif look&feel (loose/strict compliance ($tk_strictMotif)) dynamic with sensible defaults: almost everything can be changed at any time, with the display automatically (re)conguring itself widget user interface element synonym: (X) window widget class: similar appearance, behaviour widget instance - instance specic display attributes (geometry, color, ...) - instance specic behaviour: event handlers (user actions, structural changes of widget (hierarchy), redraw) top-level widget - decorated by window manager - displayed/hidden independent of parent widget internal widget - managed completely by Tk hierarchical widget tree - one per Tk application - application represented by root widget - leaves: user interface elements manipulated by user - internal nodes: structuring/grouping widget name - hierarchical pathname with separator . (cf. naming in X resource les, UNIX pathnames) - root widget: . - (Tcl) command name for actions on widget (object-oriented command style; see 3.1) * should not be renamed application root widget (a top-level widget) plus descendents associated (single) Tcl interpreter(s), including (command) bindings several (Tk) applications per single process possible event-driven, no pre-determined global control-ow structure - initialization (application-dened Tcl command script) - event loop: events processed by event handlers (application-dened Tcl command scripts)

17

Tcl/Tk in a Nutshell

standard generic application: windowing shell wish - core Tcl + standard Tk + ... - application: wish script le - X11 command-line: select display/screen/visual, private colormap y/n, set application (class) name Tk command groups widget creation ( (single) class method of widget class) - command name: widget class - parameters * path name of new widget (parents must exist) * conguration options: defaults if not explicitly specied, consistent for all (standard) widgets - (X) display screen xed at creation time widget commands - Tcl command per existing widget - command name: pathname of widget - command options * instance methods of widget class * exception: widget destruction as global command (removes widget command) destruction of root widget terminates application widget arrangement - geometry managers * input: widget structure, controlling information * output: widget size, location * widgets only visible after association with geometry manager - standard general managers * placer: simple, xed-placement * packer: constraint-based * grid: row-column table manager - inside special widgets * canvas: mix structured graphics, widgets * text: mix text, widgets - external manager for top-level widgets: window manager application/widget interconnection/cooperation - event handlers: Tcl/Tk command scripts - input focus: distinguished widget receiving keystrokes - grabs: restricting mouse/keyboard events to part of the widget tree - Tk application communication: on Tcl level via send command - X selection/clipboard support meta level: access to/modication of window manager widget tree widget state widget arrangement event bindings applications accessible via Tk application communication code management: version number ($tk_version), standard Tk script library ($tk_library)

D. Theobald

18

4.2

Tk Widgets

standard widget states normal active - mouse cursor passes over widget and widget could respond to button presses - light up disabled - can not be activated, unresponsive to events, no editing if contains selectable items (e.g. text): export selection as X selection (default) can receive focus implicitly by keyboard traversal, highlighted frame for focus widget standard button event bindings <button 1>: place, pick, press, set selection <shift-button 1>: modify selection <button 2>: scan - move viewport of visible data over total data kept by widget container widgets frame - rectangular region with border/color / (optional) private color map / (optional) different visual - non-interactive by default - main purpose: container for other widgets, structure widget tree for geometry management toplevel: frame + ... - managed by window manager, not by geometry manager of master widget - may appear on different (X) screen wrt. parent widget menu: toplevel + management of column of menu entries - additional states: posted (visible), unposted - supported menu kinds (in particular those supported by the default bindings) * pull-down - for each pull-down menu: one menubutton + associated arbitrary standard menu - arranged in menu bar: frame holding menubuttons, no separate widget class * option - one menubutton + associated special menu, all created by tk_optionMenu - for selecting from a range of values: similar to group of radiobuttons that is only visible during selection, otherwise only the menubutton with the current value is shown * pop-up - arbitrary standard menu, displayed using tk_popup - menu entries * no separate widgets, part of menu widget * analogue to label/button widgets - separator (like a xed-text label), command (button), checkbutton, radiobutton - optional text eld at the right, shows keyboard accelerator (typically <ctrl>+<key>) * + cascade button: posts sub-menu when activated * + tear-off entry: no real entry, appears depending on menu conguration option - torn-off menu: copy of original menu, independent top-level - operations * entries denoted by: ordinal number, pseudo index (active/last added/all/none), y-coordinate wrt. menu widget, csh-style pattern that is matched against the entry labels * add entry at end/index, delete entry (range), (de)activate/enable/disable/invoke/congure entry, (un)post this menu / a sub-menu, convert among the index formats, get entry type - menu hierarchy must follow widget hierarchy * menu child of menu button, sub-menu child of higher-level menu

19

Tcl/Tk in a Nutshell

- default bindings provide keyboard control * traverse pull-down menus, select entry via keystrokes (cursor keys/<return> or <space>/<escape>) * select menu entry by single keystroke: the associated accelerator key label / button widgets optional 2-way constraint: displayed text == current value of a Tcl variable, automatically maintained justied text that can occupy multiple lines, automatic word wrap at maximum length possible label - rectangular region with border/color, non-interactive by default - + display of text/bitmap/image message - label + improved formatting: handles control characters, width/height ratio of widget may be given - label - display of bitmap/image button: label + ... - interactive behavior: default bindings, states (normal, active, disabled) - ashing - button press / <space> key / explicit command: invoke event handler menubutton: label + ... - interactive behavior: default bindings, states (normal, active, disabled) - associated pull-down/option menu (menu) - default bindings: modal dialog for selecting menu entry / leaving menu area - activation of associated menu: mouse button, keyboard control (<F10> / <Alt>+<key>) checkbutton: button + ... - selector representing a binary value / two states; can be explicitly (de)selected/toggled - additional state * selected (on/off values, defaults to boolean), toggles on button press/<space> * shown by indicator besides the button label/image, or by a highlighted label/image optional: additionally different images for the two states - optional 2-way constraint: displayed state current value of a Tcl variable radiobutton: checkbutton + ... - group of related radio buttons represents a set of values/states ( enumeration type in programming languages) - optional 2-way constraint: selected button current value of Tcl variable (of the enumeration type) controller widgets scale - horizontal or vertical - selection/display of numerical value within interval by moving slider/slider position - annotations (independent): ruler (numerical tick marks), current value, text label - application dened resolution, moved by<button-1>, keyboard control: * by minimal resolution, big skip, to start/end, random positioning by dragging with mouse - classify mouse position wrt. slider - optional 2-way constraint: displayed value/position current value of a Tcl variable - callback: slider moved scrollbar - horizontal or vertical - represents visible part of data held by other widget - associated to other widget which supports scrollbar protocol: canvas, entry, listbox, text, ... - application dened movements: <button-1/2>, keyboard control * small skip (e.g. by line), big skip (e.g. by page), to start/end, random by dragging with mouse

D. Theobald

20

- optional 2-way attachment to other widget: scrollbar position/slider size visible data part * tentative changes via scrollbar: may be ignored by widget * scrollbar/widget commands designed for support of attachment protocol - get/set scrollbar data (as fraction of total data), convert widget coordinates to fraction of total data listbox list of one-line strings (<newline>s are automatically discarded) supports: (horizontal, vertical) scolling/scanning, gridded coordinate systems, selection of single line/line range, X selection (selected entries as <newline>-separated string) default bindings: mouse / keyboard control, two major selection modes (two minor variations for each) - selection of single entry / selection of entry range (including a discontiguous range) operations - entry indices: ordinal number, logical (active/last/selection anchor), nearest to pixel coordinates - delete/get entry (range), add entry/ies at index, get number of entries, convert arbitrary to ordinal index, set active element, selection management (get current, set anchor, query selection status of entry, (de)select entry (range)), scrollbar/scanning protocol + make entry visible, geometry (bounding box of entry, nd entry closest to coordinate) editor widgets entry - display/type in/edit one-line string - optional 2-way constraint: displayed text == current value of a Tcl variable - content can be hidden (e.g. for password entry) - insertion cursor if enabled and has focus; otherwise not editable (scanning/selecting still possible) - supports: (horizontal) scrolling/scanning, (X) selection of character range - default bindings * standard X mouse bindings (select character/word/line, set insertion cursor, dene/extend/insert selection) + scanning * emacs-like keyboard bindings (moving cursor, set selection anchor, delete character/word) - operations * character indices (rounded to nearest valid if out of range): ordinal number, logical (last, selection anchor/ start/end), pixel coordinate * bounding box of character at index, get text, delete character (range), add character(s) at index, move insertion cursor, convert arbitrary to ordinal index, set active element, selection management (get current, query selection status of whole entry, set anchor, select range / from anchor to index), scrollbar/scanning protocol text: entry + multi-line text (even very large texts) - supports: (horizontal, vertical) scrolling/scanning, gridded coordinate systems, (X) selection of character range(s), embedded widgets, (justied) tab stops, line wrapping (none, at character/word; additional vertical spacing for lines that (do not) wrap) - last character is always a <newline> - annotations (different name spaces for each kind) * mark - single text position between two characters - oating: moved by insertions/deletions; gravity: moved with either left/right character neighbor - special marks: insert: insertion cursor, current: mouse position (if no button is pressed) * tag: list of character ranges - characters may be associated with any number of tags; efciency optimized for many small ranges - optional event bindings: hypertext; only for mouse-related events - formatting/display options font, color, border, stipple pattern, underlining/overstriking, justication, tab stops, left/right indentation, additional vertical spacing above/below wrapped/standard lines, line-wrapping mode, tab stops

21

Tcl/Tk in a Nutshell

- priority scheme for overlapping tag extents . default: denition order, global settings (i.e. those for the widget) have lowest priority . for each display/formatting option: use denition with highest priority . for events: execute the most specic binding for each tag, in order of decreasing priority, nally execute bindings for text widget break/continue may be used as for widget event bindings - current X selection: sel tag * embedded widgets: arbitrary other widget, handled as single character (includes deletion) - must be child of text widget, or child of the text widgets parent - vertical alignment wrt. text line, stretch vertically to ll line, vertical/horizontal padding - options: either created elsewhere, or automatically (re)created via congurable command script - character indices * base index: ordinal (character in line), pixel coordinate, last character, wrt. annotations (rst/last character with given tag, position of mark, position of embedded window) * + relative adjustment by optional list of modiers (by number of characters/lines, to line/word end/start) - operations * get content/process content by handler (select content kind: pure text, tag range start/end, mark position, window name), get/delete character (range), add (tagged) character(s) at index, search line-wise (start/end index/wrap-around, forward/backward, exact pattern/regular expression, case (in)sensitive), * geometry (bounding box for character/line), index management (comparison, convert arbitrary to ordinal index), scrollbar/scanning protocol, make index visible/move line to top of display * mark management (query all/next/previous mark(s), set/delete mark(s), congure), embedded widgets (create, list, congure), tag management (add to range(s)/remove from range(s)/delete/congure, change priority, list all/at index, set/query/append to tag event binding, search for previous/next/all range(s) of a tag) - default bindings * standard X mouse bindings (select character/word/line, set insertion cursor, dene/extend/insert selection) + scanning * emacs-like keyboard bindings (move cursor/view by character/line/paragraph/page / to start/end, set selection anchor, delete character/word) canvas rectangular drawing surface containing structured graphics supports: (horizontal, vertical) scrolling/scanning, user-dened scroll region (bounding box + scroll resolution, view may be conned to box), selection in text items operations: generate postscript representation (all/region, to le/string, ...), geometry (convert screen in canvas coordinates), scanning/scrolling protocol item - denoted by unique (integer) identier (within canvas widget) - item types * arc (section of oval delimited by start/end angle), bitmap/image, circle/ellipsis, bzier curve / (poly)line, lled bzier curve / polygon, rectangle, multi-line justied text (similar to entry), embedded widget * extensible via C library interface - ordered display list (order determines if items are hidden by others) item tag - (non-numerical) name for item group: arbitrary number of items (including none) - item can be in any number of item groups - tag-specic event bindings - special tags: all, current (topmost item under mouse cursor) - (item) search specication: all/specic item/tag, wrt. display list / boundary box, closest to coordinate - operations: add tag / nd items given search specication, remove tag, query tags of item

D. Theobald

22

operations: also applicable to item tags (except for creation) - create (and add tags) / delete, type-specic conguration, change position in display list - query type / coordinates/bounding box, move absolute/relative, scale, rotate (only via item conguration) - indexable items (text-like) * local focus item: gets focus if canvas takes focus * add character(s) at index, delete at index/index range, move insertion cursor, convert arbitrary to ordinal index, manage selection (set start/end, clear, get item), set/query focus item - event bindings (only for mouse- and keyboard-related events): execute the most specic binding for each tag (in order of decreasing priority, starting with all), then bindings for the item, nally execute bindings for canvas widget break/continue may be used as for widget event bindings

4.3

Widget Conguration

widget queries class explore widget tree - children/parent/name in parent/associated top-level, existence of a widget X display attributes - associated X screen, visibility of widget, conversion to/from X window ID, handling of X atoms, nd visuals for widget/X screen, size of color map / color depth of widget/X screen, map color specication to rgb representation geometry - (requested) widget size, associated geometry manager, coordinates wrt. parent widget/X root window/X screen, coordinate transformations (screen distance to pixels), nd widget given a screen position conguration options several (short) synonyms for most commonly used options state of widget / common state of widget with complex internal structure (e.g. canvas) retrieve - available options - current / default value, or name of synonym holding the options denition by (with decreasing priority): - configure operation during widget lifetime - widget creation option - option database associated to Tk application * name of application/application class, class name of frame widgets can be set at initialization * X11r3/r4-style resource database with Tk-specic priority scheme - newer options (denition order) take priority (insertion/parsing time) not the more specic ones as usuall with X11 - optional (integer) priority level specication, symbolic names for some priority levels * clear database, add line/le, retrieve value for specic option - class defaults compiled into Tk library option kinds anchor: orientation relative to parent widget (rectangle), or relative to reference point 3D appearance (relief): raised, sunken, flat (no 3D effect), ridge, groove bitmap: le name, or name of preloaded/statically dened (compiled-in) bitmap takes usually precedence over display of text boolean: as in Tcl (cf. 2.2) color - symbolic name (not case-sensitive), or numeric value as common for X - replaced by black/white if color not possible (monochrome display, color map overow)

23

Tcl/Tk in a Nutshell

- color associated with widget state (default fore-/background, fore-/background when active/selected/disabled/has focus, insertion mark color) (Tcl) command script - callback, event handler - full command script - partial script, completed at invocation time * scrollbar protocol: script prex (requires standardized widget command options) * event binding: placeholders replaced by event specic data cursor - cursor form when over widget (default: inherit from parent widget) - foreground/background color - name * standard X cursor name (without XC_ prex) * lenames dening cursor bitmap, transparent portions of bitmap (optional) screen distance: pixel value, or oating-point number in centimeters, ..., point durations: in milliseconds font: standard X font names image: name of existing image (cf. 4.7), empty name to disable image display takes usually precedence over display of bitmaps, text text justication: left, center, or right orientation: horizontal, vertical text: string to be displayed text variable - name of (global) Tcl variable - display kept up-to-date * widget internal callback to change variable if widget changes * Tcl variable trigger: variable change triggers widget change

4.4

Geometry Management

window manager distinguished X process controlling decoration/geometry of top-level windows on a single X display large variety: some operations not/differently implemented by different window manager implementations operations (set/retrieve): - constraints for resizing: by user/program (x-, y-dimension handled independently), minimum/maximum size/width-height ratio, by gridsteps (grid usually determined by an internal window) - set/query top-level states: normal (or: deiconied), iconied, withdrawn - top-level attributes (title, absolute size, absolute/relative position, X window ID of outermost frame) - icon attributes (name/title, position, bitmap/window used as icon) - X11 window properties for session managers / managing private color maps, callbacks for X11 window protocol events, intra-application focus model top-level types: normal, transient (e.g. dialog box), ignored by window manager (e.g. menus) stacking order determines which of overlapping widgets appears on top children always on top of parent, default otherwise: widget created last is highest in order change stacking order for internal widgets wrt. its siblings: to bottom/top, below/on top of other sibling

D. Theobald

24

geometry manager determine position/size of (internal) widgets - (geometric) widget hierarchy: master slave not necessarily same as parentchildren hierarchy (often: additional frames added for grouping) - input * size request of slave widget (typically: required minimum) * parameters/constraints from application designer * geometry of master widget - slave request may be ignored, slave might even not be displayed at all - requests propagate upward until window manager determines size for top-level, geometry propagates then downward - top-level widget managed by window manager - output * geometry of slaves * size request of master widget geometry manager - only visible if attached to geometry manager - attachment may differ: over time, for different slaves of same master - slave must be higher in stacking order than master, otherwise obscured by master standard Tk geometry managers - operations: manage/unmanage slave, set/retrieve management parameters/slaves/masters - master either parent or descendent of slaves parent (except for slave itself) independent widget hierarchies for content / geometry management possible/recommended - slaves not displayed (i.e. unmapped) when master is not displayed placer (place) slaves independent from each other, master geometry independent from slaves slave placed wrt. master - absolute/relative position of anchor point / slave size - orientation wrt. anchor point master may differ from parent widget specify how widget borders are counted packer (pack) slaves depend on each other, master depends on slave(s) shrink master until slaves just t (if no other constraints) process slaves in packing order, one at a time - slice off parcel from available (rectangular) space in master - choose slave size - position slave in its parcel - compute available space for next slave; rest space in parcel of positioned slaves not used - dont display slaves if no place left options - control slave (packing) order - parcel geometry: attach to one side of master, extend parcel by xed space / to maximum size available in master - control slave size: stretch slave in x-, y-dimension - slave position in its parcel: wrt. anchor point, insert space between slave and parcel border - select master (default: parent widget of slave widget) - disable geometry propagation: master slave

25

Tcl/Tk in a Nutshell

row-column manager (grid) slaves depend on each other, master depends on slave(s) shrink master until slaves just t (if no other constraints) rows/columns handled independently options - row/column position; abbreviations for position and row/column spanning wrt. previous slave specication - per row/column: minimum size, weight for apportioning remaining space in master - padding: between adjacent rows/columns, around slave (within slaves parcel) - slaves parcel: takes up one row/column, spans (specied xed) number of rows/columns - slave geometry wrt. its parcel: attached to one/several sides, ll in x-/y-dimension - select master (default: parent widget of rst managed slave widget) - disable geometry propagation: master slave queries - size of master (rows and columns), screen position row/column index - access slaves: all, all in row/column, slave at row and column

4.5

Events

event standard X event: notication using typed record, describes occurrence that is potentially interesting for an application symbolic names - event types, mouse buttons, modier keys (shift, ...), repetition counts (double click, ...), keyboard codes - special shortcuts: mouse button events, key codes event binding association of Tcl script with sequence of X events (often: single event), denoted by tag name - default tag names: widget name, widget class name (capitalized: Text, Entry, ...), all - X determines widget that receives event(s), tags of that widget determine further processing - widget tags * default (in processing order): class, widget, widgets top-level, all * tags and their order may be freely changed (bindtags) create/append to/remove/retrieve binding script - by tag (widget/widget class/all/user-dened) and given event sequence (bind) - default class bindings/all bindings dened in les of the Tk script library binding script - contains placeholders substituted with attributes of activating event - process binding for next widget tag (continue), stop event processing (break) - invoked in global context in interpreter where binding was established processing - process all tags in order, select most specic event sequence (longest, most detail) for each tag - ignore unbound events (no error) (keyboard) input focus focus widget - one focus widget per top-level - receives keystrokes (may trigger event binding) - bindings for keyboard control must be present for (some binding tag of) each focus widget - visual feedback (depending on widget conguration): highlighting of frame around widget

D. Theobald

26

- widget ordering wrt. focus (tk_focusNext, tk_focusPrev) * based on widget hierarchy and state (visible, not disabled, bindings exist, can take focus) * default keyboard bindings for moving focus (<tab>, <shift-tab>) (external) focus model: - passive (default): Tk handles focus inside a top-level (application), window manager moves focus among top-levels/applications - active: application claims focus from another application (internal) focus model - explicit (default): focus doesnt automatically follow mouse, may be moved explicitly by program - implicit (tk_focusFollowsMouse): focus follows mouse inside top-levels query/set focus widget of top-level / application on some X display interaction modality modal interaction: restrict possible user interactions, force ordering default: modeless mechanisms - grab * discard mouse events except for part of widget tree within application / display wide * keyboard events still received by any (local grab) / grabbing (global grab) application * set/release/query grab for widget - waiting * until widget is destroyed / changes visibility * until (Tcl) variable is modied * until time interval expires (without processing X events) * process X events while waiting (some event handler is to eventually trigger wait condition)

4.6

Application Communication/Cooperation

X selection mechanism to pass information between widgets/applications - select objects (e.g. text) in a widget: automatically clears previous selection - retrieve selection in context of (another) widget * on demand retrieval: triggers request to handler for widget holding selection * typed request * larger selections retrieved in parts: request includes maximum expected size in bytes Tk supports full X11 selection mechanism, default is the primary selection on the current X display - clear/query/claim selection, dene selection handler for widget and request type, dene handler for loosing selection - selection request types: standard X11 types (STRING, FILE_NAME, ...) plus some Tk specic types - selection handlers provided for standard widgets clipboard implementation (selection CLIPBOARD) - supports one clipboard per X display - clear clipboard, append to entry of given type and format application communication application-dened implicit using X selection, clipboard using le events, sockets (cf. 2.2) Tk rpc - send - synchronous/asynchronous execution of (Tcl) command script by (another) Tk interpreter on same/other X display - while waiting for reply: defer processing of X events but not of incomming send requests

27

Tcl/Tk in a Nutshell

- query name of this/other interpreters on same/other display, change name of this interpreter, (re)enable send command - default interpreter name set at startup: given prex is made unique by Tk library - possible security loophole * full access to Tk application (and thus to the permissions of the account posessing the application) simple, once another Tk application can be started on same X display * send command can be deleted to explicitly block external requests (rename) * default Tk library conguration disables send if security level of X display too low - usage * debugging, interactive (re)conguration of Tk applications * hypertools: cooperating ensembles of Tk applications

4.7

Miscellaneous

utilities error handling: bgerror implementation as dialog box (show message, stack trace) process (possibly) pending display operations create modal dialog (tk_dialog) - based on window title, message text, (optional) bitmap, and a set of buttons (optional: default button) - wait for response: index of the activated button ring X displays bell images extensible set of image processors, default set: bitmap, photo query supported image types, currently known images, image size, delete image (as soon as no longer needed anywhere) object-oriented command style: command binding established for each image instance (cf. 3.1) bitmaps: foreground/background color, contents/transparency mask from le/string photo - 24 bit color images, extensible by format converters (default: PPM format) - set image size, resolution of color cube (includes grayscale), -correction - clear image, read from string, read from/write to le: complete image/image region, read pixel, set pixel region, copy image region (to another image) optionally applying transformations

D. Theobald

28

5.
5.1

XF - Interactive Interface Builder for Tcl/Tk


Interface Builder Concepts

need for interface builder (size) complexity of user interface code - often dominating total application code - parametrization of user interface elements - geometric dependencies between user interface elements development methodology - prototypical, experimental, trial and error - traditional edit-compile-debug cycle unsuitable - object-oriented user interface toolkits not sufcient conceptual mismatch - difcult to build mental model of interface look&feel by code study - application developer concerned about look&feel / functionality not UI implementation interactive interface builder display of interface under construction direct manipulation of interface elements - creation (+ suitable defaults) - parametrization (color, fonts, ...) - layout (position/size: absolute/relative/by constraints) coupling: user interface application functionality application code - basic functionality (application programmer) - user interface * generated (interface builder) * callback handlers (application programmer) relation to application - separated with/without application simulation * consistent mapping to real application? * turn-around time? - monitored, with interface builder running in same/different process * interface builder application builder XFs goals rapid application construction - interactive, graphical dialogs for creating, layouting, conguring user interface elements - support for coupling interface/basic application - construct complete application, not just interface: no separate build step - library with common interface/functional parts support life/development cycle - (optional) coupling to version control system - re-engineering: load Tk application * XF-based but (manually) modied * non XF-based - modularization * within constructed procedure * extendable library of reusable interface/functional parts * granularity: widget subtree, Tcl procedure

29

Tcl/Tk in a Nutshell

* on-demand loading of modules supported - user-oriented names for widget pathnames, procedures extendible, adaptable - add (non-standard) Tk widgets plus appropriate XF dialogs - customize XF (appearance, event bindings, ...) - toolkit approach for building XF good user interface - non-modal, user has control - intuitive, problem-oriented dialogs complete wrt. Tk - all standard widgets, standard conguration options - geometry managers: packer, placer XF based on Tcl/Tk interpreted: dynamic environment, smaller code, no compile time Tk: high graphic performance but still dynamic meta level: snapshot of global state (variables, procedures, widgets) possible extendible command set XF run load Tk application/start from scratch modify/edit - create, congure, layout widgets - add/edit callback/event handlers, procedures, variables test/use application dump snapshot Tk interpreter

query UI elements

XF
modify congure

application

load save

snapshot

XFs problems run by same (Tcl) interpreter than application: interference possible save snapshot of global state: looses description how state is reached - variables: initialization by current value, not by computation - code: must be bound to some procedure, no free code possible - widget state: as variables, e.g. use-the-default information may get lost does not (yet) support Tk version 4.0 or later

5.2

Usage

concepts/elements main window - repository of applicable user interface elements: widgets, templates - current position within widget tree of application layouting, geometry management: packer, placer

D. Theobald

30

cut buffer - holds widget structure - clear, copy, cut, delete, paste, load, save - display - associated generating Tk command script: show, store as template, convert into procedure (body) application - initially: empty root widget - clear - associated Tk command script (snapshot): merge, load, save with division into modules, save/show/edit without division into modules widget conguration - dialogs specic to widget class * standardized dialog for similar widget classes * class specic additional dialog - congure (freely dened) widget group - event bindings: specic widget / all widgets / widget class widget tree - display using edge (extensible public-domain graph display/manipulation tool) - display in canvas widget * hierarchical display focus * dump postscript representation * apply conguration/cutbuffer operations, set current widget position procedures, commands - application specic - callback/event handlers - added/generated by XF * auxiliary support procedures * per top-level widget: creation/destruction of associated widget structure variables (global) template - Tk script le: widget structure creation and/or procedures - creation * current cut buffer * select part of widget tree, procedures - basic template library * widget structures: scrollable widgets with associated scrollbars * procedures: le selector dialog, message/text box, ... * on-demand loadable variants of procedure templates module - set of procedures - independent store/load - on-demand loading supported complexity management - symbolic name for widget pathname, procedure alias - modules - classication and selective handling (display/save) of procedures/event bindings - current widget position plus overview capabilities - separate dialogs: standard/special conguration options XF toolkit externally usable tools

31

Tcl/Tk in a Nutshell

- editor: application resource le - hardcopy utility * part of widget tree of Tk application * dump to postscript, bitmap, ... le - help system * two hierarchy levels * book marks, editable notes * stored as editable text les in (optionally) several help directories - pixmap editor - tutorial player * interprets scripts mixing text pages and actions * one action (== Tk command script) per page external tools used by XF - edge: display, layout widget tree - shape: version control - text editors - hardcopy generators extension support - per widget class: standardized procedural interfaces * insert new widget * congure: geometry, bindings, default/additional conguration options * save widget - run arbitrary XF initialization code generated code generated procedures - creation/destruction of toplevel widget plus attached widget structure - hooks for application initialization/nalization code support procedures (added on request) - load (XF) module - load/apply X application defaults - symbolic name mapping, procedure alias creation/destruction - popup menu support application dened procedures initialization code - load modules - application dened initialization - set global variables - create visible toplevel widgets (plus attached widget structure) - load event bindings - load application defaults - application dened initialization restrictions for application code - reserved name prexes: indicate XF-specic semantics - search paths for on-demand loading should not be modied

D. Theobald

32

References
[Del93] Sven Delmas. XF Design and Implementation of a Programming Environment for Interactive Construction of Graphical User Interfaces. Diplomarbeit, Technical University of Berlin, Institut fr Angewandte Informatik, Mrz 1993. John K. Ousterhout. Tcl and the Tk toolkit. Addison-Wesley, Reading, MA, 1994. John K. Ousterhout. Tcl/Tk Manual Pages, 1996. Tcl/Tk distribution, version 7.5b3/4.1b3.

[Ous94] [Ous96]

You might also like