'\" '\" Generated from file 'snitfaq\&.man' by tcllib/doctools with format 'nroff' '\" Copyright (c) 2003-2006, by William H\&. Duquette '\" .TH "snitfaq" 3tcl 2\&.2 tcllib "Snit's Not Incr Tcl, OO system" .\" The -*- nroff -*- definitions below are for supplemental macros used .\" in Tcl/Tk manual entries. .\" .\" .AP type name in/out ?indent? .\" Start paragraph describing an argument to a library procedure. .\" type is type of argument (int, etc.), in/out is either "in", "out", .\" or "in/out" to describe whether procedure reads or modifies arg, .\" and indent is equivalent to second arg of .IP (shouldn't ever be .\" needed; use .AS below instead) .\" .\" .AS ?type? ?name? .\" Give maximum sizes of arguments for setting tab stops. Type and .\" name are examples of largest possible arguments that will be passed .\" to .AP later. If args are omitted, default tab stops are used. .\" .\" .BS .\" Start box enclosure. From here until next .BE, everything will be .\" enclosed in one large box. .\" .\" .BE .\" End of box enclosure. .\" .\" .CS .\" Begin code excerpt. .\" .\" .CE .\" End code excerpt. .\" .\" .VS ?version? ?br? .\" Begin vertical sidebar, for use in marking newly-changed parts .\" of man pages. The first argument is ignored and used for recording .\" the version when the .VS was added, so that the sidebars can be .\" found and removed when they reach a certain age. If another argument .\" is present, then a line break is forced before starting the sidebar. .\" .\" .VE .\" End of vertical sidebar. .\" .\" .DS .\" Begin an indented unfilled display. .\" .\" .DE .\" End of indented unfilled display. .\" .\" .SO ?manpage? .\" Start of list of standard options for a Tk widget. The manpage .\" argument defines where to look up the standard options; if .\" omitted, defaults to "options". The options follow on successive .\" lines, in three columns separated by tabs. .\" .\" .SE .\" End of list of standard options for a Tk widget. .\" .\" .OP cmdName dbName dbClass .\" Start of description of a specific option. cmdName gives the .\" option's name as specified in the class command, dbName gives .\" the option's name in the option database, and dbClass gives .\" the option's class in the option database. .\" .\" .UL arg1 arg2 .\" Print arg1 underlined, then print arg2 normally. .\" .\" .QW arg1 ?arg2? .\" Print arg1 in quotes, then arg2 normally (for trailing punctuation). .\" .\" .PQ arg1 ?arg2? .\" Print an open parenthesis, arg1 in quotes, then arg2 normally .\" (for trailing punctuation) and then a closing parenthesis. .\" .\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages. .if t .wh -1.3i ^B .nr ^l \n(.l .ad b .\" # Start an argument description .de AP .ie !"\\$4"" .TP \\$4 .el \{\ . ie !"\\$2"" .TP \\n()Cu . el .TP 15 .\} .ta \\n()Au \\n()Bu .ie !"\\$3"" \{\ \&\\$1 \\fI\\$2\\fP (\\$3) .\".b .\} .el \{\ .br .ie !"\\$2"" \{\ \&\\$1 \\fI\\$2\\fP .\} .el \{\ \&\\fI\\$1\\fP .\} .\} .. .\" # define tabbing values for .AP .de AS .nr )A 10n .if !"\\$1"" .nr )A \\w'\\$1'u+3n .nr )B \\n()Au+15n .\" .if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n .nr )C \\n()Bu+\\w'(in/out)'u+2n .. .AS Tcl_Interp Tcl_CreateInterp in/out .\" # BS - start boxed text .\" # ^y = starting y location .\" # ^b = 1 .de BS .br .mk ^y .nr ^b 1u .if n .nf .if n .ti 0 .if n \l'\\n(.lu\(ul' .if n .fi .. .\" # BE - end boxed text (draw box now) .de BE .nf .ti 0 .mk ^t .ie n \l'\\n(^lu\(ul' .el \{\ .\" Draw four-sided box normally, but don't draw top of .\" box if the box started on an earlier page. .ie !\\n(^b-1 \{\ \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .el \}\ \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .\} .fi .br .nr ^b 0 .. .\" # VS - start vertical sidebar .\" # ^Y = starting y location .\" # ^v = 1 (for troff; for nroff this doesn't matter) .de VS .if !"\\$2"" .br .mk ^Y .ie n 'mc \s12\(br\s0 .el .nr ^v 1u .. .\" # VE - end of vertical sidebar .de VE .ie n 'mc .el \{\ .ev 2 .nf .ti 0 .mk ^t \h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n' .sp -1 .fi .ev .\} .nr ^v 0 .. .\" # Special macro to handle page bottom: finish off current .\" # box/sidebar if in box/sidebar mode, then invoked standard .\" # page bottom macro. .de ^B .ev 2 'ti 0 'nf .mk ^t .if \\n(^b \{\ .\" Draw three-sided box if this is the box's first page, .\" draw two sides but no top otherwise. .ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .\} .if \\n(^v \{\ .nr ^x \\n(^tu+1v-\\n(^Yu \kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c .\} .bp 'fi .ev .if \\n(^b \{\ .mk ^y .nr ^b 2 .\} .if \\n(^v \{\ .mk ^Y .\} .. .\" # DS - begin display .de DS .RS .nf .sp .. .\" # DE - end display .de DE .fi .RE .sp .. .\" # SO - start of list of standard options .de SO 'ie '\\$1'' .ds So \\fBoptions\\fR 'el .ds So \\fB\\$1\\fR .SH "STANDARD OPTIONS" .LP .nf .ta 5.5c 11c .ft B .. .\" # SE - end of list of standard options .de SE .fi .ft R .LP See the \\*(So manual entry for details on the standard options. .. .\" # OP - start of full description for a single option .de OP .LP .nf .ta 4c Command-Line Name: \\fB\\$1\\fR Database Name: \\fB\\$2\\fR Database Class: \\fB\\$3\\fR .fi .IP .. .\" # CS - begin code excerpt .de CS .RS .nf .ta .25i .5i .75i 1i .. .\" # CE - end code excerpt .de CE .fi .RE .. .\" # UL - underline word .de UL \\$1\l'|0\(ul'\\$2 .. .\" # QW - apply quotation marks to word .de QW .ie '\\*(lq'"' ``\\$1''\\$2 .\"" fix emacs highlighting .el \\*(lq\\$1\\*(rq\\$2 .. .\" # PQ - apply parens and quotation marks to word .de PQ .ie '\\*(lq'"' (``\\$1''\\$2)\\$3 .\"" fix emacs highlighting .el (\\*(lq\\$1\\*(rq\\$2)\\$3 .. .\" # QR - quoted range .de QR .ie '\\*(lq'"' ``\\$1''\\-``\\$2''\\$3 .\"" fix emacs highlighting .el \\*(lq\\$1\\*(rq\\-\\*(lq\\$2\\*(rq\\$3 .. .\" # MT - "empty" string .de MT .QW "" .. .BS .SH NAME snitfaq \- Snit Frequently Asked Questions .SH DESCRIPTION .PP .SH OVERVIEW .SS "WHAT IS THIS DOCUMENT?" This is an atypical FAQ list, in that few of the questions are frequently asked\&. Rather, these are the questions I think a newcomer to Snit should be asking\&. This file is not a complete reference to Snit, however; that information is in the \fBsnit\fR man page\&. .SS "WHAT IS SNIT?" Snit is a framework for defining abstract data types and megawidgets in pure Tcl\&. The name "Snit" stands for "Snit's Not Incr Tcl", signifying that Snit takes a different approach to defining objects than does Incr Tcl, the best known object framework for Tcl\&. Had I realized that Snit would become at all popular, I'd probably have chosen something else\&. .PP The primary purpose of Snit is to be \fIobject glue\fR--to help you compose diverse objects from diverse sources into types and megawidgets with clean, convenient interfaces so that you can more easily build your application\&. .PP Snit isn't about theoretical purity or minimalist design; it's about being able to do powerful things easily and consistently without having to think about them--so that you can concentrate on building your application\&. .PP Snit isn't about implementing thousands of nearly identical carefully-specified lightweight thingamajigs--not as individual Snit objects\&. Traditional Tcl methods will be much faster, and not much more complicated\&. But Snit \fIis\fR about implementing a clean interface to manage a collection of thousands of nearly identical carefully-specified lightweight thingamajigs (e\&.g\&., think of the text widget and text tags, or the canvas widget and canvas objects)\&. Snit lets you hide the details of just how those thingamajigs are stored--so that you can ignore it, and concentrate on building your application\&. .PP Snit isn't a way of life, a silver bullet, or the Fountain of Youth\&. It's just a way of managing complexity--and of managing some of the complexity of managing complexity--so that you can concentrate on building your application\&. .SS "WHAT VERSION OF TCL DOES SNIT REQUIRE?" Snit 1\&.3 requires Tcl 8\&.3 or later; Snit 2\&.2 requires Tcl 8\&.5 or later\&. See \fBSNIT VERSIONS\fR for the differences between Snit 1\&.3 and Snit 2\&.2\&. .SS "WHERE CAN I DOWNLOAD SNIT?" Snit is part of Tcllib, the standard Tcl library, so you might already have it\&. It's also available at the Snit Home Page, \fIhttp://www\&.wjduquette\&.com/snit\fR\&. .SS "WHAT ARE SNIT'S GOALS?" .PP .IP \(bu A Snit object should be at least as efficient as a hand-coded Tcl object (see \fIhttp://www\&.wjduquette\&.com/tcl/objects\&.html\fR)\&. .IP \(bu The fact that Snit was used in an object's implementation should be transparent (and irrelevant) to clients of that object\&. .IP \(bu Snit should be able to encapsulate objects from other sources, particularly Tk widgets\&. .IP \(bu Snit megawidgets should be (to the extent possible) indistinguishable in interface from Tk widgets\&. .IP \(bu Snit should be Tclish--that is, rather than trying to emulate C++, Smalltalk, or anything else, it should try to emulate Tcl itself\&. .IP \(bu It should have a simple, easy-to-use, easy-to-remember syntax\&. .PP .SS "HOW IS SNIT DIFFERENT FROM OTHER OO FRAMEWORKS?" Snit is unique among Tcl object systems in that it is based not on inheritance but on delegation\&. Object systems based on inheritance only allow you to inherit from classes defined using the same system, and that's a shame\&. In Tcl, an object is anything that acts like an object; it shouldn't matter how the object was implemented\&. I designed Snit to help me build applications out of the materials at hand; thus, Snit is designed to be able to incorporate and build on any object, whether it's a hand-coded object, a Tk widget, an Incr Tcl object, a BWidget or almost anything else\&. .PP Note that you can achieve the effect of inheritance using \fBCOMPONENTS\fR and \fBDELEGATION\fR--and you can inherit from anything that looks like a Tcl object\&. .SS "WHAT CAN I DO WITH SNIT?" Using Snit, a programmer can: .IP \(bu Create abstract data types and Tk megawidgets\&. .IP \(bu Define instance variables, type variables, and Tk-style options\&. .IP \(bu Define constructors, destructors, instance methods, type methods, procs\&. .IP \(bu Assemble a type out of component types\&. Instance methods and options can be delegated to the component types automatically\&. .PP .SH "SNIT VERSIONS" .SS "WHICH VERSION OF SNIT SHOULD I USE?" The current Snit distribution includes two versions, Snit 1\&.3 and Snit 2\&.2\&. The reason that both are included is that Snit 2\&.2 takes advantage of a number of new features of Tcl 8\&.5 to improve run-time efficiency; as a side-effect, the ugliness of Snit's error messages and stack traces has been reduced considerably\&. The cost of using Snit 2\&.2, of course, is that you must target Tcl 8\&.5\&. .PP Snit 1\&.3, on the other hand, lacks Snit 2\&.2's optimizations, but requires only Tcl 8\&.3 and later\&. .PP In short, if you're targetting Tcl 8\&.3 or 8\&.4 you should use Snit 1\&.3\&. If you can afford to target Tcl 8\&.5, you should definitely use Snit 2\&.2\&. If you will be targetting both, you can use Snit 1\&.3 exclusively, or (if your code is unaffected by the minor incompatibilities between the two versions) you can use Snit 1\&.3 for Tcl 8\&.4 and Snit 2\&.2 for Tcl 8\&.5\&. .SS "HOW DO I SELECT THE VERSION OF SNIT I WANT TO USE?" To always use Snit 1\&.3 (or a later version of Snit 1\&.x), invoke Snit as follows: .CS package require snit 1\&.3 .CE To always use Snit 2\&.2 (or a later version of Snit 2\&.x), say this instead: .CS package require snit 2\&.2 .CE Note that if you request Snit 2\&.2 explicitly, your application will halt with Tcl 8\&.4, since Snit 2\&.2 is unavailable for Tcl 8\&.4\&. .PP If you wish your application to always use the latest available version of Snit, don't specify a version number: .CS package require snit .CE Tcl will find and load the latest version that's available relative to the version of Tcl being used\&. In this case, be careful to avoid using any incompatible features\&. .SS "HOW ARE SNIT 1\&.3 AND SNIT 2\&.2 INCOMPATIBLE?" To the extent possible, Snit 2\&.2 is intended to be a drop-in replacement for Snit 1\&.3\&. Unfortunately, some incompatibilities were inevitable because Snit 2\&.2 uses Tcl 8\&.5's new \fBnamespace ensemble\fR mechanism to implement subcommand dispatch\&. This approach is much faster than the mechanism used in Snit 1\&.3, and also results in much better error messages; however, it also places new constraints on the implementation\&. .PP There are four specific incompatibilities between Snit 1\&.3 and Snit 2\&.2\&. .PP .IP \(bu Snit 1\&.3 supports implicit naming of objects\&. Suppose you define a new \fBsnit::type\fR called \fBdog\fR\&. You can create instances of \fBdog\fR in three ways: .CS dog spot ;# Explicit naming set obj1 [dog %AUTO%] ;# Automatic naming set obj2 [dog] ;# Implicit naming .CE .IP In Snit 2\&.2, type commands are defined using the \fBnamespace ensemble\fR mechanism; and \fBnamespace ensemble\fR doesn't allow an ensemble command to be called without a subcommand\&. In short, using \fBnamespace ensemble\fR there's no way to support implicit naming\&. .sp All is not lost, however\&. If the type has no type methods, then the type command is a simple command rather than an ensemble, and \fBnamespace ensemble\fR is not used\&. In this case, implicit naming is still possible\&. .sp In short, you can have implicit naming if you're willing to do without type methods (including the standard type methods, like \fB$type info\fR)\&. To do so, use the \fB-hastypemethods\fR pragma: .CS pragma -hastypemethods 0 .CE .IP \(bu Hierarchical methods and type methods are implemented differently in Snit 2\&.2\&. .sp A hierarchical method is an instance method which has subcommands; these subcommands are themselves methods\&. The Tk text widget's \fBtag\fR command and its subcommands are examples of hierarchical methods\&. You can implement such subcommands in Snit simply by including multiple words in the method names: .CS method {tag configure} {tag args} { \&.\&.\&. } method {tag cget} {tag option} {\&.\&.\&.} .CE .IP Here we've implicitly defined a \fBtag\fR method which has two subcommands, \fBconfigure\fR and \fBcget\fR\&. .sp In Snit 1\&.3, hierarchical methods could be called in two ways: .CS $obj tag cget -myoption ;# The good way $obj {tag cget} -myoption ;# The weird way .CE .IP In the second call, we see that a hierarchical method or type method is simply one whose name contains multiple words\&. .sp In Snit 2\&.2 this is no longer the case, and the "weird" way of calling hierarchical methods and type methods no longer works\&. .IP \(bu The third incompatibility derives from the second\&. In Snit 1\&.3, hierarchical methods were also simply methods whose name contains multiple words\&. As a result, \fB$obj info methods\fR returned the full names of all hierarchical methods\&. In the example above, the list returned by \fB$obj info methods\fR would include \fBtag configure\fR and \fBtag cget\fR but not \fBtag\fR, since \fBtag\fR is defined only implicitly\&. .sp In Snit 2\&.2, hierarchical methods and type methods are no longer simply ones whose name contains multiple words; in the above example, the list returned by \fB$obj info methods\fR would include \fBtag\fR but not \fBtag configure\fR or \fBtag cget\fR\&. .IP \(bu The fourth incompatibility is due to a new feature\&. Snit 2\&.2 uses the new \fBnamespace path\fR command so that a type's code can call any command defined in the type's parent namespace without qualification or importation\&. For example, suppose you have a package called \fBmypackage\fR which defines a number of commands including a type, \fB::mypackage::mytype\fR\&. Thanks to \fBnamespace path\fR, the type's code can call any of the other commands defined in \fB::mypackage::\fR\&. .sp This is extremely convenient\&. However, it also means that commands defined in the parent namespace, \fB::mypackage::\fR can block the type's access to identically named commands in the global namespace\&. This can lead to bugs\&. For example, Tcllib includes a type called \fB::tie::std::file\fR\&. This type's code calls the standard \fBfile\fR command\&. When run with Snit 2\&.2, the code broke-- the type's command, \fB::tie::std::file\fR, is itself a command in the type's parent namespace, and so instead of calling the standard \fBfile\fR command, the type found itself calling itself\&. .PP .SS "ARE THERE OTHER DIFFERENCES BETWEEN SNIT 1\&.X AND SNIT 2\&.2?" Yes\&. .IP \(bu Method dispatch is considerably faster\&. .IP \(bu Many error messages and stack traces are cleaner\&. .IP \(bu The \fB-simpledispatch\fR pragma is obsolete, and ignored if present\&. In Snit 1\&.x, \fB-simpledispatch\fR substitutes a faster mechanism for method dispatch, at the cost of losing certain features\&. Snit 2\&.2 method dispatch is faster still in all cases, so \fB-simpledispatch\fR is no longer needed\&. .IP \(bu In Snit 2\&.2, a type's code (methods, type methods, etc\&.) can call commands from the type's parent namespace without qualifying or importing them, i\&.e\&., type \fB::parentns::mytype\fR's code can call \fB::parentns::someproc\fR as just \fBsomeproc\fR\&. .sp This is extremely useful when a type is defined as part of a larger package, and shares a parent namespace with the rest of the package; it means that the type can call other commands defined by the package without any extra work\&. .sp This feature depends on the new Tcl 8\&.5 \fBnamespace path\fR command, which is why it hasn't been implemented for V1\&.x\&. V1\&.x code can achieve something similar by placing .CS namespace import [namespace parent]::* .CE .IP in a type constructor\&. This is less useful, however, as it picks up only those commands which have already been exported by the parent namespace at the time the type is defined\&. .PP .SH OBJECTS .SS "WHAT IS AN OBJECT?" A full description of object-oriented programming is beyond the scope of this FAQ, obviously\&. In simple terms, an object is an instance of an abstract data type--a coherent bundle of code and data\&. There are many ways to represent objects in Tcl/Tk; the best known examples are the Tk widgets\&. .PP A Tk widget is an object; it is represented by a Tcl command\&. The object's methods are subcommands of the Tcl command\&. The object's properties are options accessed using the \fBconfigure\fR and \fBcget\fR methods\&. Snit uses the same conventions as Tk widgets do\&. .SS "WHAT IS AN ABSTRACT DATA TYPE?" In computer science terms, an abstract data type is a complex data structure along with a set of operations--a stack, a queue, a binary tree, etc--that is to say, in modern terms, an object\&. In systems that include some form of inheritance the word \fIclass\fR is usually used instead of \fIabstract data type\fR, but as Snit doesn't implement inheritance as it's ordinarily understood the older term seems more appropriate\&. Sometimes this is called \fIobject-based\fR programming as opposed to object-oriented programming\&. Note that you can easily create the effect of inheritance using \fBCOMPONENTS\fR and \fBDELEGATION\fR\&. .PP In Snit, as in Tk, a \fItype\fR is a command that creates instances -- objects -- which belong to the type\&. Most types define some number of \fIoptions\fR which can be set at creation time, and usually can be changed later\&. .PP Further, an \fIinstance\fR is also a Tcl command--a command that gives access to the operations which are defined for that abstract data type\&. Conventionally, the operations are defined as subcommands of the instance command\&. For example, to insert text into a Tk text widget, you use the text widget's \fBinsert\fR subcommand: .PP .CS # Create a text widget and insert some text in it\&. text \&.mytext -width 80 -height 24 \&.mytext insert end "Howdy!" .CE .PP In this example, \fBtext\fR is the \fItype\fR command and \fB\&.mytext\fR is the \fIinstance\fR command\&. .PP In Snit, object subcommands are generally called \fBINSTANCE METHODS\fR\&. .SS "WHAT KINDS OF ABSTRACT DATA TYPES DOES SNIT PROVIDE?" Snit allows you to define three kinds of abstract data type: .PP .IP \(bu \fBsnit::type\fR .IP \(bu \fBsnit::widget\fR .IP \(bu \fBsnit::widgetadaptor\fR .PP .SS "WHAT IS A SNIT::TYPE?" A \fBsnit::type\fR is a non-GUI abstract data type, e\&.g\&., a stack or a queue\&. \fBsnit::type\fRs are defined using the \fBsnit::type\fR command\&. For example, if you were designing a kennel management system for a dog breeder, you'd need a dog type\&. .PP .CS % snit::type dog { # \&.\&.\&. } ::dog % .CE .PP This definition defines a new command (\fB::dog\fR, in this case) that can be used to define dog objects\&. .PP An instance of a \fBsnit::type\fR can have \fBINSTANCE METHODS\fR, \fBINSTANCE VARIABLES\fR, \fBOPTIONS\fR, and \fBCOMPONENTS\fR\&. The type itself can have \fBTYPE METHODS\fR, \fBTYPE VARIABLES\fR, \fBTYPE COMPONENTS\fR, and \fBPROCS\fR\&. .SS "WHAT IS A SNIT::WIDGET?, THE SHORT STORY" A \fBsnit::widget\fR is a Tk megawidget built using Snit; it is very similar to a \fBsnit::type\fR\&. See \fBWIDGETS\fR\&. .SS "WHAT IS A SNIT::WIDGETADAPTOR?, THE SHORT STORY" A \fBsnit::widgetadaptor\fR uses Snit to wrap an existing widget type (e\&.g\&., a Tk label), modifying its interface to a lesser or greater extent\&. It is very similar to a \fBsnit::widget\fR\&. See \fBWIDGET ADAPTORS\fR\&. .SS "HOW DO I CREATE AN INSTANCE OF A SNIT::TYPE?" You create an instance of a \fBsnit::type\fR by passing the new instance's name to the type's create method\&. In the following example, we create a \fBdog\fR object called \fBspot\fR\&. .PP .CS % snit::type dog { # \&.\&.\&.\&. } ::dog % dog create spot ::spot % .CE .PP In general, the \fBcreate\fR method name can be omitted so long as the instance name doesn't conflict with any defined \fBTYPE METHODS\fR\&. (See \fBTYPE COMPONENTS\fR for the special case in which this doesn't work\&.) So the following example is identical to the previous example: .PP .CS % snit::type dog { # \&.\&.\&.\&. } ::dog % dog spot ::spot % .CE .PP This document generally uses the shorter form\&. .PP If the \fBdog\fR type defines \fBOPTIONS\fR, these can usually be given defaults at creation time: .PP .CS % snit::type dog { option -breed mongrel option -color brown method bark {} { return "$self barks\&." } } ::dog % dog create spot -breed dalmation -color spotted ::spot % spot cget -breed dalmation % spot cget -color spotted % .CE .PP Once created, the instance name now names a new Tcl command that is used to manipulate the object\&. For example, the following code makes the dog bark: .PP .CS % spot bark ::spot barks\&. % .CE .PP .SS "HOW DO I REFER TO AN OBJECT INDIRECTLY?" Some programmers prefer to save the object name in a variable, and reference it that way\&. For example, .PP .CS % snit::type dog { \&.\&.\&. } ::dog % set d [dog spot -breed dalmation -color spotted] ::spot % $d cget -breed dalmation % $d bark ::spot barks\&. % .CE .PP If you prefer this style, you might prefer to have Snit generate the instance's name automatically\&. .SS "HOW CAN I GENERATE THE OBJECT NAME AUTOMATICALLY?" If you'd like Snit to generate an object name for you, use the \fB%AUTO%\fR keyword as the requested name: .PP .CS % snit::type dog { \&.\&.\&. } ::dog % set d [dog %AUTO%] ::dog2 % $d bark ::dog2 barks\&. % .CE .PP The \fB%AUTO%\fR keyword can be embedded in a longer string: .PP .CS % set d [dog obj_%AUTO%] ::obj_dog4 % $d bark ::obj_dog4 barks\&. % .CE .PP .SS "CAN TYPES BE RENAMED?" Tcl's \fBrename\fR command renames other commands\&. It's a common technique in Tcl to modify an existing command by renaming it and defining a new command with the original name; the new command usually calls the renamed command\&. .PP \fBsnit::type\fR commands, however, should never be renamed; to do so breaks the connection between the type and its objects\&. .SS "CAN OBJECTS BE RENAMED?" Tcl's \fBrename\fR command renames other commands\&. It's a common technique in Tcl to modify an existing command by renaming it and defining a new command with the original name; the new command usually calls the renamed command\&. .PP All Snit objects (including \fIwidgets\fR and \fIwidgetadaptors\fR) can be renamed, though this flexibility has some consequences: .PP .IP \(bu In an instance method, the implicit argument \fBself\fR will always contain the object's current name, so instance methods can always call other instance methods using \fB$self\fR\&. .IP \(bu If the object is renamed, however, then \fB$self\fR's value will change\&. Therefore, don't use \fB$self\fR for anything that will break if \fB$self\fR changes\&. For example, don't pass a callback command to another object like this: .CS \&.btn configure -command [list $self ButtonPress] .CE .IP You'll get an error if \fB\&.btn\fR calls your command after your object is renamed\&. .IP \(bu Instead, your object should define its callback command like this: .CS \&.btn configure -command [mymethod ButtonPress] .CE .IP The \fBmymethod\fR command returns code that will call the desired method safely; the caller of the callback can add additional arguments to the end of the command as usual\&. .IP \(bu Every object has a private namespace; the name of this namespace is available in method bodies, etc\&., as the value of the implicit argument \fBselfns\fR\&. This value is constant for the life of the object\&. Use \fB$selfns\fR instead of \fB$self\fR if you need a unique token to identify the object\&. .IP \(bu When a \fBsnit::widget\fR's instance command is renamed, its Tk window name remains the same -- and is still extremely important\&. Consequently, the Tk window name is available in method bodies as the value of the implicit argument \fBwin\fR\&. This value is constant for the life of the object\&. When creating child windows, it's best to use \fB$win\&.child\fR rather than \fB$self\&.child\fR as the name of the child window\&. .PP .SS "HOW DO I DESTROY A SNIT OBJECT?" Any Snit object of any type can be destroyed by renaming it to the empty string using the Tcl \fBrename\fR command\&. .PP Snit megawidgets (i\&.e\&., instances of \fBsnit::widget\fR and \fBsnit::widgetadaptor\fR) can be destroyed like any other widget: by using the Tk \fBdestroy\fR command on the widget or on one of its ancestors in the window hierarchy\&. .PP Every instance of a \fBsnit::type\fR has a \fBdestroy\fR method: .PP .CS % snit::type dog { \&.\&.\&. } ::dog % dog spot ::spot % spot bark ::spot barks\&. % spot destroy % spot barks invalid command name "spot" % .CE .PP Finally, every Snit type has a type method called \fBdestroy\fR; calling it destroys the type and all of its instances: .CS % snit::type dog { \&.\&.\&. } ::dog % dog spot ::spot % spot bark ::spot barks\&. % dog destroy % spot bark invalid command name "spot" % dog fido invalid command name "dog" % .CE .SH "INSTANCE METHODS" .SS "WHAT IS AN INSTANCE METHOD?" An instance method is a procedure associated with a specific object and called as a subcommand of the object's command\&. It is given free access to all of the object's type variables, instance variables, and so forth\&. .SS "HOW DO I DEFINE AN INSTANCE METHOD?" Instance methods are defined in the type definition using the \fBmethod\fR statement\&. Consider the following code that might be used to add dogs to a computer simulation: .PP .CS % snit::type dog { method bark {} { return "$self barks\&." } method chase {thing} { return "$self chases $thing\&." } } ::dog % .CE .PP A dog can bark, and it can chase things\&. .PP The \fBmethod\fR statement looks just like a normal Tcl \fBproc\fR, except that it appears in a \fBsnit::type\fR definition\&. Notice that every instance method gets an implicit argument called \fBself\fR; this argument contains the object's name\&. (There's more on implicit method arguments below\&.) .SS "HOW DOES A CLIENT CALL AN INSTANCE METHOD?" The method name becomes a subcommand of the object\&. For example, let's put a simulated dog through its paces: .PP .CS % dog spot ::spot % spot bark ::spot barks\&. % spot chase cat ::spot chases cat\&. % .CE .PP .SS "HOW DOES AN INSTANCE METHOD CALL ANOTHER INSTANCE METHOD?" If method A needs to call method B on the same object, it does so just as a client does: it calls method B as a subcommand of the object itself, using the object name stored in the implicit argument \fBself\fR\&. .PP Suppose, for example, that our dogs never chase anything without barking at them: .PP .CS % snit::type dog { method bark {} { return "$self barks\&." } method chase {thing} { return "$self chases $thing\&. [$self bark]" } } ::dog % dog spot ::spot % spot bark ::spot barks\&. % spot chase cat ::spot chases cat\&. ::spot barks\&. % .CE .PP .SS "ARE THERE ANY LIMITATIONS ON INSTANCE METHOD NAMES?" Not really, so long as you avoid the standard instance method names: \fBconfigure\fR, \fBconfigurelist\fR, \fBcget\fR, \fBdestroy\fR, and \fBinfo\fR\&. Also, method names consisting of multiple words define hierarchical methods\&. .SS "WHAT IS A HIERARCHICAL METHOD?" An object's methods are subcommands of the object's instance command\&. Hierarchical methods allow an object's methods to have subcommands of their own; and these can in turn have subcommands, and so on\&. This allows the programmer to define a tree-shaped command structure, such as is used by many of the Tk widgets--the subcommands of the Tk \fBtext\fR widget's \fBtag\fR method are hierarchical methods\&. .SS "HOW DO I DEFINE A HIERARCHICAL METHOD?" Define methods whose names consist of multiple words\&. These words define the hierarchy implicitly\&. For example, the following code defines a \fBtag\fR method with subcommands \fBcget\fR and \fBconfigure\fR: .CS snit::widget mytext { method {tag configure} {tag args} { \&.\&.\&. } method {tag cget} {tag option} {\&.\&.\&.} } .CE Note that there is no explicit definition for the \fBtag\fR method; it is implicit in the definition of \fBtag configure\fR and \fBtag cget\fR\&. If you tried to define \fBtag\fR explicitly in this example, you'd get an error\&. .SS "HOW DO I CALL HIERARCHICAL METHODS?" As subcommands of subcommands\&. .CS % mytext \&.text \&.text % \&.text tag configure redtext -foreground red -background black % \&.text tag cget redtext -foreground red % .CE .SS "HOW DO I MAKE AN INSTANCE METHOD PRIVATE?" It's often useful to define private methods, that is, instance methods intended to be called only by other methods of the same object\&. .PP Snit doesn't implement any access control on instance methods, so all methods are \fIde facto\fR public\&. Conventionally, though, the names of public methods begin with a lower-case letter, and the names of private methods begin with an upper-case letter\&. .PP For example, suppose our simulated dogs only bark in response to other stimuli; they never bark just for fun\&. So the \fBbark\fR method becomes \fBBark\fR to indicate that it is private: .PP .CS % snit::type dog { # Private by convention: begins with uppercase letter\&. method Bark {} { return "$self barks\&." } method chase {thing} { return "$self chases $thing\&. [$self Bark]" } } ::dog % dog fido ::fido % fido chase cat ::fido chases cat\&. ::fido barks\&. % .CE .PP .SS "ARE THERE ANY LIMITATIONS ON INSTANCE METHOD ARGUMENTS?" Method argument lists are defined just like normal Tcl \fBproc\fR argument lists; in particular, they can include arguments with default values and the \fBargs\fR argument\&. .PP However, every method also has a number of implicit arguments provided by Snit in addition to those explicitly defined\&. The names of these implicit arguments may not used to name explicit arguments\&. .SS "WHAT IMPLICIT ARGUMENTS ARE PASSED TO EACH INSTANCE METHOD?" The arguments implicitly passed to every method are \fBtype\fR, \fBselfns\fR, \fBwin\fR, and \fBself\fR\&. .SS "WHAT IS $TYPE?" The implicit argument \fBtype\fR contains the fully qualified name of the object's type: .PP .CS % snit::type thing { method mytype {} { return $type } } ::thing % thing something ::something % something mytype ::thing % .CE .PP .SS "WHAT IS $SELF?" The implicit argument \fBself\fR contains the object's fully qualified name\&. .PP If the object's command is renamed, then \fB$self\fR will change to match in subsequent calls\&. Thus, your code should not assume that \fB$self\fR is constant unless you know for sure that the object will never be renamed\&. .PP .CS % snit::type thing { method myself {} { return $self } } ::thing % thing mutt ::mutt % mutt myself ::mutt % rename mutt jeff % jeff myself ::jeff % .CE .PP .SS "WHAT IS $SELFNS?" Each Snit object has a private namespace in which to store its \fBINSTANCE VARIABLES\fR and \fBOPTIONS\fR\&. The implicit argument \fBselfns\fR contains the name of this namespace; its value never changes, and is constant for the life of the object, even if the object's name changes: .PP .CS % snit::type thing { method myNameSpace {} { return $selfns } } ::thing % thing jeff ::jeff % jeff myNameSpace ::thing::Snit_inst3 % rename jeff mutt % mutt myNameSpace ::thing::Snit_inst3 % .CE .PP The above example reveals how Snit names an instance's private namespace; however, you should not write code that depends on the specific naming convention, as it might change in future releases\&. .SS "WHAT IS $WIN?" The implicit argument \fBwin\fR is defined for all Snit methods, though it really makes sense only for those of \fBWIDGETS\fR and \fBWIDGET ADAPTORS\fR\&. \fB$win\fR is simply the original name of the object, whether it's been renamed or not\&. For widgets and widgetadaptors, it is also therefore the name of a Tk window\&. .PP When a \fBsnit::widgetadaptor\fR is used to modify the interface of a widget or megawidget, it must rename the widget's original command and replace it with its own\&. .PP Thus, using \fBwin\fR whenever the Tk window name is called for means that a \fBsnit::widget\fR or \fBsnit::widgetadaptor\fR can be adapted by a \fBsnit::widgetadaptor\fR\&. See \fBWIDGETS\fR for more information\&. .SS "HOW DO I PASS AN INSTANCE METHOD AS A CALLBACK?" It depends on the context\&. .PP Suppose in my application I have a \fBdog\fR object named \fBfido\fR, and I want \fBfido\fR to bark when a Tk button called \fB\&.bark\fR is pressed\&. In this case, I create the callback command in the usual way, using \fBlist\fR: .PP .CS button \&.bark -text "Bark!" -command [list fido bark] .CE .PP In typical Tcl style, we use a callback to hook two independent components together\&. But suppose that the \fBdog\fR object has a graphical interface and owns the button itself? In this case, the \fBdog\fR must pass one of its own instance methods to the button it owns\&. The obvious thing to do is this: .PP .CS % snit::widget dog { constructor {args} { #\&.\&.\&. button $win\&.barkbtn -text "Bark!" -command [list $self bark] #\&.\&.\&. } } ::dog % .CE .PP (Note that in this example, our \fBdog\fR becomes a \fBsnit::widget\fR, because it has GUI behavior\&. See \fBWIDGETS\fR for more\&.) Thus, if we create a \fBdog\fR called \fB\&.spot\fR, it will create a Tk button called \fB\&.spot\&.barkbtn\fR; when pressed, the button will call \fB$self bark\fR\&. .PP Now, this will work--provided that \fB\&.spot\fR is never renamed to something else\&. But surely renaming widgets is abnormal? And so it is--unless \fB\&.spot\fR is the hull component of a \fBsnit::widgetadaptor\fR\&. If it is, then it will be renamed, and \fB\&.spot\fR will become the name of the \fBsnit::widgetadaptor\fR object\&. When the button is pressed, the command \fB$self bark\fR will be handled by the \fBsnit::widgetadaptor\fR, which might or might not do the right thing\&. .PP There's a safer way to do it, and it looks like this: .PP .CS % snit::widget dog { constructor {args} { #\&.\&.\&. button $win\&.barkbtn -text "Bark!" -command [mymethod bark] #\&.\&.\&. } } ::dog % .CE .PP The command \fBmymethod\fR takes any number of arguments, and can be used like \fBlist\fR to build up a callback command; the only difference is that \fBmymethod\fR returns a form of the command that won't change even if the instance's name changes\&. .PP On the other hand, you might prefer to allow a widgetadaptor to override a method such that your renamed widget will call the widgetadaptor's method instead of its own\&. In this case, using \fB[list $self bark]\fR will do what you want\&.\&.\&.but this is a technique which should be used only in carefully controlled circumstances\&. .SS "HOW DO I DELEGATE INSTANCE METHODS TO A COMPONENT?" See \fBDELEGATION\fR\&. .SH "INSTANCE VARIABLES" .SS "WHAT IS AN INSTANCE VARIABLE?" An instance variable is a private variable associated with some particular Snit object\&. Instance variables can be scalars or arrays\&. .SS "HOW IS A SCALAR INSTANCE VARIABLE DEFINED?" Scalar instance variables are defined in the type definition using the \fBvariable\fR statement\&. You can simply name it, or you can initialize it with a value: .PP .CS snit::type mytype { # Define variable "greeting" and initialize it with "Howdy!" variable greeting "Howdy!" } .CE .PP .SS "HOW IS AN ARRAY INSTANCE VARIABLE DEFINED?" Array instance variables are also defined in the type definition using the \fBvariable\fR command\&. You can initialize them at the same time by specifying the \fB-array\fR option: .PP .CS snit::type mytype { # Define array variable "greetings" variable greetings -array { formal "Good Evening" casual "Howdy!" } } .CE .PP .SS "WHAT HAPPENS IF I DON'T INITIALIZE AN INSTANCE VARIABLE?" Variables do not really exist until they are given values\&. If you do not initialize a variable when you define it, then you must be sure to assign a value to it (in the constructor, say, or in some method) before you reference it\&. .SS "ARE THERE ANY LIMITATIONS ON INSTANCE VARIABLE NAMES?" Just a few\&. .PP First, every Snit object has a built-in instance variable called \fBoptions\fR, which should never be redefined\&. .PP Second, all names beginning with "Snit_" are reserved for use by Snit internal code\&. .PP Third, instance variable names containing the namespace delimiter (\fB::\fR) are likely to cause great confusion\&. .SS "DO I NEED TO DECLARE MY INSTANCE VARIABLES IN MY METHODS?" No\&. Once you've defined an instance variable in the type definition, it can be used in any instance code (instance methods, the constructor, and the destructor) without declaration\&. This differs from normal Tcl practice, in which all non-local variables in a proc need to be declared\&. .PP There is a speed penalty to having all instance variables implicitly available in all instance code\&. Even though your code need not declare the variables explicitly, Snit must still declare them, and that takes time\&. If you have ten instance variables, a method that uses none of them must still pay the declaration penalty for all ten\&. In most cases, the additional runtime cost is negligible\&. If extreme cases, you might wish to avoid it; there are two methods for doing so\&. .PP The first is to define a single instance variable, an array, and store all of your instance data in the array\&. This way, you're only paying the declaration penalty for one variable--and you probably need the variable most of the time anyway\&. This method breaks down if your instance variables include multiple arrays; in Tcl 8\&.5, however, the \fBdict\fR command might come to your rescue\&. .PP The second method is to declare your instance variables explicitly in your instance code, while \fInot\fR including them in the type definition: .CS snit::type dog { constructor {} { variable mood set mood happy } method setmood {newMood} { variable mood set mood $newMood } method getmood {} { variable mood return $mood } } .CE This allows you to ensure that only the required variables are included in each method, at the cost of longer code and run-time errors when you forget to declare a variable you need\&. .SS "HOW DO I PASS AN INSTANCE VARIABLE'S NAME TO ANOTHER OBJECT?" In Tk, it's common to pass a widget a variable name; for example, Tk label widgets have a \fB-textvariable\fR option which names the variable which will contain the widget's text\&. This allows the program to update the label's value just by assigning a new value to the variable\&. .PP If you naively pass the instance variable name to the label widget, you'll be confused by the result; Tk will assume that the name names a global variable\&. Instead, you need to provide a fully-qualified variable name\&. From within an instance method or a constructor, you can fully qualify the variable's name using the \fBmyvar\fR command: .PP .CS snit::widget mywidget { variable labeltext "" constructor {args} { # \&.\&.\&. label $win\&.label -textvariable [myvar labeltext] # \&.\&.\&. } } .CE .PP .SS "HOW DO I MAKE AN INSTANCE VARIABLE PUBLIC?" Practically speaking, you don't\&. Instead, you'll implement public variables as \fBOPTIONS\fR\&. Alternatively, you can write \fBINSTANCE METHODS\fR to set and get the variable's value\&. .SH OPTIONS .SS "WHAT IS AN OPTION?" A type's options are the equivalent of what other object-oriented languages would call public member variables or properties: they are data values which can be retrieved and (usually) set by the clients of an object\&. .PP Snit's implementation of options follows the Tk model fairly exactly, except that \fBsnit::type\fR objects usually don't interact with \fBTHE TK OPTION DATABASE\fR; \fBsnit::widget\fR and \fBsnit::widgetadaptor\fR objects, on the other hand, always do\&. .SS "HOW DO I DEFINE AN OPTION?" Options are defined in the type definition using the \fBoption\fR statement\&. Consider the following type, to be used in an application that manages a list of dogs for a pet store: .PP .CS snit::type dog { option -breed -default mongrel option -color -default brown option -akc -default 0 option -shots -default 0 } .CE .PP According to this, a dog has four notable properties: a breed, a color, a flag that says whether it's pedigreed with the American Kennel Club, and another flag that says whether it has had its shots\&. The default dog, evidently, is a brown mutt\&. .PP There are a number of options you can specify when defining an option; if \fB-default\fR is the only one, you can omit the word \fB-default\fR as follows: .PP .CS snit::type dog { option -breed mongrel option -color brown option -akc 0 option -shots 0 } .CE .PP If no \fB-default\fR value is specified, the option's default value will be the empty string (but see \fBTHE TK OPTION DATABASE\fR)\&. .PP The Snit man page refers to options like these as "locally defined" options\&. .SS "HOW CAN A CLIENT SET OPTIONS AT OBJECT CREATION?" The normal convention is that the client may pass any number of options and their values after the object's name at object creation\&. For example, the \fB::dog\fR command defined in the previous answer can now be used to create individual dogs\&. Any or all of the options may be set at creation time\&. .PP .CS % dog spot -breed beagle -color "mottled" -akc 1 -shots 1 ::spot % dog fido -shots 1 ::fido % .CE .PP So \fB::spot\fR is a pedigreed beagle; \fB::fido\fR is a typical mutt, but his owners evidently take care of him, because he's had his shots\&. .PP \fINote:\fR If the type defines a constructor, it can specify a different object-creation syntax\&. See \fBCONSTRUCTORS\fR for more information\&. .SS "HOW CAN A CLIENT RETRIEVE AN OPTION'S VALUE?" Retrieve option values using the \fBcget\fR method: .PP .CS % spot cget -color mottled % fido cget -breed mongrel % .CE .PP .SS "HOW CAN A CLIENT SET OPTIONS AFTER OBJECT CREATION?" Any number of options may be set at one time using the \fBconfigure\fR instance method\&. Suppose that closer inspection shows that ::fido is not a brown mongrel, but rather a rare Arctic Boar Hound of a lovely dun color: .PP .CS % fido configure -color dun -breed "Arctic Boar Hound" % fido cget -color dun % fido cget -breed Arctic Boar Hound .CE .PP Alternatively, the \fBconfigurelist\fR method takes a list of options and values; occasionally this is more convenient: .PP .CS % set features [list -color dun -breed "Arctic Boar Hound"] -color dun -breed {Arctic Boar Hound} % fido configurelist $features % fido cget -color dun % fido cget -breed Arctic Boar Hound % .CE .PP In Tcl 8\&.5, the \fB*\fR keyword can be used with \fBconfigure\fR in this case: .PP .CS % set features [list -color dun -breed "Arctic Boar Hound"] -color dun -breed {Arctic Boar Hound} % fido configure {*}$features % fido cget -color dun % fido cget -breed Arctic Boar Hound % .CE .PP The results are the same\&. .SS "HOW SHOULD AN INSTANCE METHOD ACCESS AN OPTION VALUE?" There are two ways an instance method can set and retrieve an option's value\&. One is to use the \fBconfigure\fR and \fBcget\fR methods, as shown below\&. .PP .CS % snit::type dog { option -weight 10 method gainWeight {} { set wt [$self cget -weight] incr wt $self configure -weight $wt } } ::dog % dog fido ::fido % fido cget -weight 10 % fido gainWeight % fido cget -weight 11 % .CE .PP Alternatively, Snit provides a built-in array instance variable called \fBoptions\fR\&. The indices are the option names; the values are the option values\&. The method \fBgainWeight\fR can thus be rewritten as follows: .PP .CS method gainWeight {} { incr options(-weight) } .CE .PP As you can see, using the \fBoptions\fR variable involves considerably less typing and is the usual way to do it\&. But if you use \fB-configuremethod\fR or \fB-cgetmethod\fR (described in the following answers), you might wish to use the \fBconfigure\fR and \fBcget\fR methods anyway, just so that any special processing you've implemented is sure to get done\&. Also, if the option is delegated to a component then \fBconfigure\fR and \fBcget\fR are the only way to access it without accessing the component directly\&. See \fBDELEGATION\fR for more information\&. .SS "HOW CAN I MAKE AN OPTION READ-ONLY?" Define the option with \fB-readonly yes\fR\&. .PP Suppose you've got an option that determines how instances of your type are constructed; it must be set at creation time, after which it's constant\&. For example, a dog never changes its breed; it might or might not have had its shots, and if not can have them at a later time\&. \fB-breed\fR should be read-only, but \fB-shots\fR should not be\&. .PP .CS % snit::type dog { option -breed -default mongrel -readonly yes option -shots -default no } ::dog % dog fido -breed retriever ::fido % fido configure -shots yes % fido configure -breed terrier option -breed can only be set at instance creation % .CE .PP .SS "HOW CAN I CATCH ACCESSES TO AN OPTION'S VALUE?" Define a \fB-cgetmethod\fR for the option\&. .SS "WHAT IS A -CGETMETHOD?" A \fB-cgetmethod\fR is a method that's called whenever the related option's value is queried via the \fBcget\fR instance method\&. The handler can compute the option's value, retrieve it from a database, or do anything else you'd like it to do\&. .PP Here's what the default behavior would look like if written using a \fB-cgetmethod\fR: .PP .CS snit::type dog { option -color -default brown -cgetmethod GetOption method GetOption {option} { return $options($option) } } .CE .PP Any instance method can be used, provided that it takes one argument, the name of the option whose value is to be retrieved\&. .SS "HOW CAN I CATCH CHANGES TO AN OPTION'S VALUE?" Define a \fB-configuremethod\fR for the option\&. .SS "WHAT IS A -CONFIGUREMETHOD?" A \fB-configuremethod\fR is a method that's called whenever the related option is given a new value via the \fBconfigure\fR or \fBconfigurelist\fR instance methods\&. The method can pass the value on to some other object, store it in a database, or do anything else you'd like it to do\&. .PP Here's what the default configuration behavior would look like if written using a \fB-configuremethod\fR: .PP .CS snit::type dog { option -color -default brown -configuremethod SetOption method SetOption {option value} { set options($option) $value } } .CE .PP Any instance method can be used, provided that it takes two arguments, the name of the option and the new value\&. .PP Note that if your method doesn't store the value in the \fBoptions\fR array, the \fBoptions\fR array won't get updated\&. .SS "HOW CAN I VALIDATE AN OPTION'S VALUE?" Define a \fB-validatemethod\fR\&. .SS "WHAT IS A -VALIDATEMETHOD?" A \fB-validatemethod\fR is a method that's called whenever the related option is given a new value via the \fBconfigure\fR or \fBconfigurelist\fR instance methods\&. It's the method's responsibility to determine whether the new value is valid, and throw an error if it isn't\&. The \fB-validatemethod\fR, if any, is called before the value is stored in the \fBoptions\fR array; in particular, it's called before the \fB-configuremethod\fR, if any\&. .PP For example, suppose an option always takes a Boolean value\&. You can ensure that the value is in fact a valid Boolean like this: .CS % snit::type dog { option -shots -default no -validatemethod BooleanOption method BooleanOption {option value} { if {![string is boolean -strict $value]} { error "expected a boolean value, got \\"$value\\"" } } } ::dog % dog fido % fido configure -shots yes % fido configure -shots NotABooleanValue expected a boolean value, got "NotABooleanValue" % .CE Note that the same \fB-validatemethod\fR can be used to validate any number of boolean options\&. .PP Any method can be a \fB-validatemethod\fR provided that it takes two arguments, the option name and the new option value\&. .SH "TYPE VARIABLES" .SS "WHAT IS A TYPE VARIABLE?" A type variable is a private variable associated with a Snit type rather than with a particular instance of the type\&. In C++ and Java, the term \fIstatic member variable\fR is used for the same notion\&. Type variables can be scalars or arrays\&. .SS "HOW IS A SCALAR TYPE VARIABLE DEFINED?" Scalar type variables are defined in the type definition using the \fBtypevariable\fR statement\&. You can simply name it, or you can initialize it with a value: .PP .CS snit::type mytype { # Define variable "greeting" and initialize it with "Howdy!" typevariable greeting "Howdy!" } .CE .PP Every object of type \fBmytype\fR now has access to a single variable called \fBgreeting\fR\&. .SS "HOW IS AN ARRAY-VALUED TYPE VARIABLE DEFINED?" Array-valued type variables are also defined using the \fBtypevariable\fR command; to initialize them, include the \fB-array\fR option: .PP .CS snit::type mytype { # Define typearray variable "greetings" typevariable greetings -array { formal "Good Evening" casual "Howdy!" } } .CE .PP .SS "WHAT HAPPENS IF I DON'T INITIALIZE A TYPE VARIABLE?" Variables do not really exist until they are given values\&. If you do not initialize a variable when you define it, then you must be sure to assign a value to it (in the type constructor, say) before you reference it\&. .SS "ARE THERE ANY LIMITATIONS ON TYPE VARIABLE NAMES?" Type variable names have the same restrictions as the names of \fBINSTANCE VARIABLES\fR do\&. .SS "DO I NEED TO DECLARE MY TYPE VARIABLES IN MY METHODS?" No\&. Once you've defined a type variable in the type definition, it can be used in \fBINSTANCE METHODS\fR or \fBTYPE METHODS\fR without declaration\&. This differs from normal Tcl practice, in which all non-local variables in a proc need to be declared\&. .PP Type variables are subject to the same speed/readability tradeoffs as instance variables; see \fBDo I need to declare my instance variables in my methods?\fR .SS "HOW DO I PASS A TYPE VARIABLE'S NAME TO ANOTHER OBJECT?" In Tk, it's common to pass a widget a variable name; for example, Tk label widgets have a \fB-textvariable\fR option which names the variable which will contain the widget's text\&. This allows the program to update the label's value just by assigning a new value to the variable\&. .PP If you naively pass a type variable name to the label widget, you'll be confused by the result; Tk will assume that the name names a global variable\&. Instead, you need to provide a fully-qualified variable name\&. From within an instance method or a constructor, you can fully qualify the type variable's name using the \fBmytypevar\fR command: .PP .CS snit::widget mywidget { typevariable labeltext "" constructor {args} { # \&.\&.\&. label $win\&.label -textvariable [mytypevar labeltext] # \&.\&.\&. } } .CE .PP .SS "HOW DO I MAKE A TYPE VARIABLE PUBLIC?" There are two ways to do this\&. The preferred way is to write a pair of \fBTYPE METHODS\fR to set and query the type variable's value\&. .PP Type variables are stored in the type's namespace, which has the same name as the type itself\&. Thus, you can also publicize the type variable's name in your documentation so that clients can access it directly\&. For example, .PP .CS snit::type mytype { typevariable myvariable } set ::mytype::myvariable "New Value" .CE .PP .SH "TYPE METHODS" .SS "WHAT IS A TYPE METHOD?" A type method is a procedure associated with the type itself rather than with any specific instance of the type, and called as a subcommand of the type command\&. .SS "HOW DO I DEFINE A TYPE METHOD?" Type methods are defined in the type definition using the \fBtypemethod\fR statement: .PP .CS snit::type dog { # List of pedigreed dogs typevariable pedigreed typemethod pedigreedDogs {} { return $pedigreed } } .CE .PP Suppose the \fBdog\fR type maintains a list of the names of the dogs that have pedigrees\&. The \fBpedigreedDogs\fR type method returns this list\&. .PP The \fBtypemethod\fR statement looks just like a normal Tcl \fBproc\fR, except that it appears in a \fBsnit::type\fR definition\&. Notice that every type method gets an implicit argument called \fBtype\fR, which contains the fully-qualified type name\&. .SS "HOW DOES A CLIENT CALL A TYPE METHOD?" The type method name becomes a subcommand of the type's command\&. For example, assuming that the constructor adds each pedigreed dog to the list of \fBpedigreedDogs\fR, .PP .CS snit::type dog { option -pedigreed 0 # List of pedigreed dogs typevariable pedigreed typemethod pedigreedDogs {} { return $pedigreed } # \&.\&.\&. } dog spot -pedigreed 1 dog fido foreach dog [dog pedigreedDogs] { \&.\&.\&. } .CE .PP .SS "ARE THERE ANY LIMITATIONS ON TYPE METHOD NAMES?" Not really, so long as you avoid the standard type method names: \fBcreate\fR, \fBdestroy\fR, and \fBinfo\fR\&. .SS "HOW DO I MAKE A TYPE METHOD PRIVATE?" It's sometimes useful to define private type methods, that is, type methods intended to be called only by other type or instance methods of the same object\&. .PP Snit doesn't implement any access control on type methods; by convention, the names of public methods begin with a lower-case letter, and the names of private methods begin with an upper-case letter\&. .PP Alternatively, a Snit \fBproc\fR can be used as a private type method; see \fBPROCS\fR\&. .SS "ARE THERE ANY LIMITATIONS ON TYPE METHOD ARGUMENTS?" Method argument lists are defined just like normal Tcl proc argument lists; in particular, they can include arguments with default values and the \fBargs\fR argument\&. .PP However, every type method is called with an implicit argument called \fBtype\fR that contains the name of the type command\&. In addition, type methods should by convention avoid using the names of the arguments implicitly defined for \fBINSTANCE METHODS\fR\&. .SS "HOW DOES AN INSTANCE OR TYPE METHOD CALL A TYPE METHOD?" If an instance or type method needs to call a type method, it should use \fB$type\fR to do so: .PP .CS snit::type dog { typemethod pedigreedDogs {} { \&.\&.\&. } typemethod printPedigrees {} { foreach obj [$type pedigreedDogs] { \&.\&.\&. } } } .CE .PP .SS "HOW DO I PASS A TYPE METHOD AS A CALLBACK?" It's common in Tcl to pass a snippet of code to another object, for it to call later\&. Because types cannot be renamed, you can just use the type name, or, if the callback is registered from within a type method, \fBtype\fR\&. For example, suppose we want to print a list of pedigreed dogs when a Tk button is pushed: .PP .CS button \&.btn -text "Pedigrees" -command [list dog printPedigrees] pack \&.btn .CE Alternatively, from a method or type method you can use the \fBmytypemethod\fR command, just as you would use \fBmymethod\fR to define a callback command for \fBINSTANCE METHODS\fR\&. .SS "CAN TYPE METHODS BE HIERARCHICAL?" Yes, you can define hierarchical type methods in just the same way as you can define hierarchical instance methods\&. See \fBINSTANCE METHODS\fR for more\&. .SH PROCS .SS "WHAT IS A PROC?" A Snit \fBproc\fR is really just a Tcl proc defined within the type's namespace\&. You can use procs for private code that isn't related to any particular instance\&. .SS "HOW DO I DEFINE A PROC?" Procs are defined by including a \fBproc\fR statement in the type definition: .PP .CS snit::type mytype { # Pops and returns the first item from the list stored in the # listvar, updating the listvar proc pop {listvar} { \&.\&.\&. } # \&.\&.\&. } .CE .PP .SS "ARE THERE ANY LIMITATIONS ON PROC NAMES?" Any name can be used, so long as it does not begin with \fBSnit_\fR; names beginning with \fBSnit_\fR are reserved for Snit's own use\&. However, the wise programmer will avoid \fBproc\fR names (\fBset\fR, \fBlist\fR, \fBif\fR, etc\&.) that would shadow standard Tcl command names\&. .PP \fBproc\fR names, being private, should begin with a capital letter according to convention; however, as there are typically no public \fBproc\fRs in the type's namespace it doesn't matter much either way\&. .SS "HOW DOES A METHOD CALL A PROC?" Just like it calls any Tcl command\&. For example, .PP .CS snit::type mytype { # Pops and returns the first item from the list stored in the # listvar, updating the listvar proc pop {listvar} { \&.\&.\&. } variable requestQueue {} # Get one request from the queue and process it\&. method processRequest {} { set req [pop requestQueue] } } .CE .PP .SS "HOW CAN I PASS A PROC TO ANOTHER OBJECT AS A CALLBACK?" The \fBmyproc\fR command returns a callback command for the \fBproc\fR, just as \fBmymethod\fR does for a method\&. .SH "TYPE CONSTRUCTORS" .SS "WHAT IS A TYPE CONSTRUCTOR?" A type constructor is a body of code that initializes the type as a whole, rather like a C++ static initializer\&. The body of a type constructor is executed once when the type is defined, and never again\&. .PP A type can have at most one type constructor\&. .SS "HOW DO I DEFINE A TYPE CONSTRUCTOR?" A type constructor is defined by using the \fBtypeconstructor\fR statement in the type definition\&. For example, suppose the type uses an array-valued type variable as a look-up table, and the values in the array have to be computed at start-up\&. .PP .CS % snit::type mytype { typevariable lookupTable typeconstructor { array set lookupTable {key value\&.\&.\&.} } } .CE .PP .SH CONSTRUCTORS .SS "WHAT IS A CONSTRUCTOR?" In object-oriented programming, an object's constructor is responsible for initializing the object completely at creation time\&. The constructor receives the list of options passed to the \fBsnit::type\fR command's \fBcreate\fR method and can then do whatever it likes\&. That might include computing instance variable values, reading data from files, creating other objects, updating type and instance variables, and so forth\&. .PP The constructor's return value is ignored (unless it's an error, of course)\&. .SS "HOW DO I DEFINE A CONSTRUCTOR?" A constructor is defined by using the \fBconstructor\fR statement in the type definition\&. Suppose that it's desired to keep a list of all pedigreed dogs\&. The list can be maintained in a type variable and retrieved by a type method\&. Whenever a dog is created, it can add itself to the list--provided that it's registered with the American Kennel Club\&. .PP .CS % snit::type dog { option -akc 0 typevariable akcList {} constructor {args} { $self configurelist $args if {$options(-akc)} { lappend akcList $self } } typemethod akclist {} { return $akcList } } ::dog % dog spot -akc 1 ::spot % dog fido ::fido % dog akclist ::spot % .CE .PP .SS "WHAT DOES THE DEFAULT CONSTRUCTOR DO?" If you don't provide a constructor explicitly, you get the default constructor, which is identical to the explicitly-defined constructor shown here: .PP .CS snit::type dog { constructor {args} { $self configurelist $args } } .CE .PP When the constructor is called, \fBargs\fR will be set to the list of arguments that follow the object's name\&. The constructor is allowed to interpret this list any way it chooses; the normal convention is to assume that it's a list of option names and values, as shown in the example above\&. If you simply want to save the option values, you should use the \fBconfigurelist\fR method, as shown\&. .SS "CAN I CHOOSE A DIFFERENT SET OF ARGUMENTS FOR THE CONSTRUCTOR?" Yes, you can\&. For example, suppose we wanted to be sure that the breed was explicitly stated for every dog at creation time, and couldn't be changed thereafter\&. One way to do that is as follows: .PP .CS % snit::type dog { variable breed option -color brown option -akc 0 constructor {theBreed args} { set breed $theBreed $self configurelist $args } method breed {} { return $breed } } ::dog % dog spot dalmatian -color spotted -akc 1 ::spot % spot breed dalmatian .CE .PP The drawback is that this syntax is non-standard, and may limit the compatibility of your new type with other people's code\&. For example, Snit assumes that it can create \fBCOMPONENTS\fR using the standard creation syntax\&. .SS "ARE THERE ANY LIMITATIONS ON CONSTRUCTOR ARGUMENTS?" Constructor argument lists are subject to the same limitations as those on instance method argument lists\&. It has the same implicit arguments, and can contain default values and the \fBargs\fR argument\&. .SS "IS THERE ANYTHING SPECIAL ABOUT WRITING THE CONSTRUCTOR?" Yes\&. Writing the constructor can be tricky if you're delegating options to components, and there are specific issues relating to \fBsnit::widget\fRs and \fBsnit::widgetadaptor\fRs\&. See \fBDELEGATION\fR, \fBWIDGETS\fR, \fBWIDGET ADAPTORS\fR, and \fBTHE TK OPTION DATABASE\fR\&. .SH DESTRUCTORS .SS "WHAT IS A DESTRUCTOR?" A destructor is a special kind of method that's called when an object is destroyed\&. It's responsible for doing any necessary clean-up when the object goes away: destroying \fBCOMPONENTS\fR, closing files, and so forth\&. .SS "HOW DO I DEFINE A DESTRUCTOR?" Destructors are defined by using the \fBdestructor\fR statement in the type definition\&. .PP Suppose we're maintaining a list of pedigreed dogs; then we'll want to remove dogs from it when they are destroyed\&. .PP .CS snit::type dog { option -akc 0 typevariable akcList {} constructor {args} { $self configurelist $args if {$options(-akc)} { lappend akcList $self } } destructor { set ndx [lsearch $akcList $self] if {$ndx != -1} { set akcList [lreplace $akcList $ndx $ndx] } } typemethod akclist {} { return $akcList } } .CE .PP .SS "ARE THERE ANY LIMITATIONS ON DESTRUCTOR ARGUMENTS?" Yes; a destructor has no explicit arguments\&. .SS "WHAT IMPLICIT ARGUMENTS ARE PASSED TO THE DESTRUCTOR?" The destructor gets the same implicit arguments that are passed to \fBINSTANCE METHODS\fR: \fBtype\fR, \fBselfns\fR, \fBwin\fR, and \fBself\fR\&. .SS "MUST COMPONENTS BE DESTROYED EXPLICITLY?" Yes and no\&. .PP Any Tk widgets created by a \fBsnit::widget\fR or \fBsnit::widgetadaptor\fR will be destroyed automatically by Tk when the megawidget is destroyed, in keeping with normal Tk behavior (destroying a parent widget destroys the whole tree)\&. .PP Components of normal \fBsnit::types\fR, on the other hand, are never destroyed automatically, nor are non-widget components of Snit megawidgets\&. If your object creates them in its constructor, then it should generally destroy them in its destructor\&. .SS "IS THERE ANY SPECIAL ABOUT WRITING A DESTRUCTOR?" Yes\&. If an object's constructor throws an error, the object's destructor will be called to clean up; this means that the object might not be completely constructed when the destructor is called\&. This can cause the destructor to throw its own error; the result is usually misleading, confusing, and unhelpful\&. Consequently, it's important to write your destructor so that it's fail-safe\&. .PP For example, a \fBdog\fR might create a \fBtail\fR component; the component will need to be destroyed\&. But suppose there's an error while processing the creation options--the destructor will be called, and there will be no \fBtail\fR to destroy\&. The simplest solution is generally to catch and ignore any errors while destroying components\&. .CS snit::type dog { component tail constructor {args} { $self configurelist $args set tail [tail %AUTO%] } destructor { catch {$tail destroy} } } .CE .SH COMPONENTS .SS "WHAT IS A COMPONENT?" Often an object will create and manage a number of other objects\&. A Snit megawidget, for example, will often create a number of Tk widgets\&. These objects are part of the main object; it is composed of them, so they are called components of the object\&. .PP But Snit also has a more precise meaning for \fBCOMPONENT\fR\&. The components of a Snit object are those objects to which methods or options can be delegated\&. (See \fBDELEGATION\fR for more information about delegation\&.) .SS "HOW DO I DECLARE A COMPONENT?" First, you must decide what role a component plays within your object, and give the role a name\&. Then, you declare the component using its role name and the \fBcomponent\fR statement\&. The \fBcomponent\fR statement declares an \fIinstance variable\fR which is used to store the component's command name when the component is created\&. .PP For example, suppose your \fBdog\fR object creates a \fBtail\fR object (the better to wag with, no doubt): .PP .CS snit::type dog { component mytail constructor {args} { # Create and save the component's command set mytail [tail %AUTO% -partof $self] $self configurelist $args } method wag {} { $mytail wag } } .CE .PP As shown here, it doesn't matter what the \fBtail\fR object's real name is; the \fBdog\fR object refers to it by its component name\&. .PP The above example shows one way to delegate the \fBwag\fR method to the \fBmytail\fR component; see \fBDELEGATION\fR for an easier way\&. .SS "HOW IS A COMPONENT NAMED?" A component has two names\&. The first name is that of the component variable; this represents the role the component object plays within the Snit object\&. This is the component name proper, and is the name used to refer to the component within Snit code\&. The second name is the name of the actual component object created by the Snit object's constructor\&. This second name is always a Tcl command name, and is referred to as the component's object name\&. .PP In the example in the previous question, the component name is \fBmytail\fR; the \fBmytail\fR component's object name is chosen automatically by Snit since \fB%AUTO%\fR was used when the component object was created\&. .SS "ARE THERE ANY LIMITATIONS ON COMPONENT NAMES?" Yes\&. \fBsnit::widget\fR and \fBsnit::widgetadaptor\fR objects have a special component called the \fBhull\fR component; thus, the name \fBhull\fR should be used for no other purpose\&. .PP Otherwise, since component names are in fact instance variable names they must follow the rules for \fBINSTANCE VARIABLES\fR\&. .SS "WHAT IS AN OWNED COMPONENT?" An \fIowned\fR component is a component whose object command's lifetime is controlled by the \fBsnit::type\fR or \fBsnit::widget\fR\&. .PP As stated above, a component is an object to which our object can delegate methods or options\&. Under this definition, our object will usually create its component objects, but not necessarily\&. Consider the following: a dog object has a tail component; but tail knows that it's part of the dog: .CS snit::type dog { component mytail constructor {args} { set mytail [tail %AUTO% -partof $self] $self configurelist $args } destructor { catch {$mytail destroy} } delegate method wagtail to mytail as wag method bark {} { return "$self barked\&." } } snit::type tail { component mydog option -partof -readonly yes constructor {args} { $self configurelist $args set mydog $options(-partof) } method wag {} { return "Wag, wag\&." } method pull {} { $mydog bark } } .CE Thus, if you ask a dog to wag its tail, it tells its tail to wag; and if you pull the dog's tail, the tail tells the dog to bark\&. In this scenario, the tail is a component of the dog, and the dog is a component of the tail, but the dog owns the tail and not the other way around\&. .SS "WHAT DOES THE INSTALL COMMAND DO?" The \fBinstall\fR command creates an owned component using a specified command, and assigns the result to the component's instance variable\&. For example: .CS snit::type dog { component mytail constructor {args} { # set mytail [tail %AUTO% -partof $self] install mytail using tail %AUTO% -partof $self $self configurelist $args } } .CE In a \fBsnit::type\fR's code, the \fBinstall\fR command shown above is equivalent to the \fBset mytail\fR command that's commented out\&. In a \fBsnit::widget\fR's or \fBsnit::widgetadaptor\fR's, code, however, the \fBinstall\fR command also queries \fBTHE TK OPTION DATABASE\fR and initializes the new component's options accordingly\&. For consistency, it's a good idea to get in the habit of using \fBinstall\fR for all owned components\&. .SS "MUST OWNED COMPONENTS BE CREATED IN THE CONSTRUCTOR?" No, not necessarily\&. In fact, there's no reason why an object can't destroy and recreate a component multiple times over its own lifetime\&. .SS "ARE THERE ANY LIMITATIONS ON COMPONENT OBJECT NAMES?" Yes\&. .PP Component objects which are Tk widgets or megawidgets must have valid Tk window names\&. .PP Component objects which are not widgets or megawidgets must have fully-qualified command names, i\&.e\&., names which include the full namespace of the command\&. Note that Snit always creates objects with fully qualified names\&. .PP Next, the object names of components and owned by your object must be unique\&. This is no problem for widget components, since widget names are always unique; but consider the following code: .PP .CS snit::type tail { \&.\&.\&. } snit::type dog { delegate method wag to mytail constructor {} { install mytail using tail mytail } } .CE .PP This code uses the component name, \fBmytail\fR, as the component object name\&. This is not good, and here's why: Snit instance code executes in the Snit type's namespace\&. In this case, the \fBmytail\fR component is created in the \fB::dog::\fR namespace, and will thus have the name \fB::dog::mytail\fR\&. .PP Now, suppose you create two dogs\&. Both dogs will attempt to create a tail called \fB::dog::mytail\fR\&. The first will succeed, and the second will fail, since Snit won't let you create an object if its name is already a command\&. Here are two ways to avoid this situation: .PP First, if the component type is a \fBsnit::type\fR you can specify \fB%AUTO%\fR as its name, and be guaranteed to get a unique name\&. This is the safest thing to do: .PP .CS install mytail using tail %AUTO% .CE .PP If the component type isn't a \fBsnit::type\fR you can create the component in the object's instance namespace: .PP .CS install mytail using tail ${selfns}::mytail .CE .PP Make sure you pick a unique name within the instance namespace\&. .SS "MUST I DESTROY THE COMPONENTS I OWN?" That depends\&. When a parent widget is destroyed, all child widgets are destroyed automatically\&. Thus, if your object is a \fBsnit::widget\fR or \fBsnit::widgetadaptor\fR you don't need to destroy any components that are widgets, because they will generally be children or descendants of your megawidget\&. .PP If your object is an instance of \fBsnit::type\fR, though, none of its owned components will be destroyed automatically, nor will be non-widget components of a \fBsnit::widget\fR be destroyed automatically\&. All such owned components must be destroyed explicitly, or they won't be destroyed at all\&. .SS "CAN I EXPOSE A COMPONENT'S OBJECT COMMAND AS PART OF MY INTERFACE?" Yes, and there are two ways to do it\&. The most appropriate way is usually to use \fBDELEGATION\fR\&. Delegation allows you to pass the options and methods you specify along to particular components\&. This effectively hides the components from the users of your type, and ensures good encapsulation\&. .PP However, there are times when it's appropriate, not to mention simpler, just to make the entire component part of your type's public interface\&. .SS "HOW DO I EXPOSE A COMPONENT'S OBJECT COMMAND?" When you declare the component, specify the \fBcomponent\fR statement's \fB-public\fR option\&. The value of this option is the name of a method which will be delegated to your component's object command\&. .PP For example, supposed you've written a combobox megawidget which owns a listbox widget, and you want to make the listbox's entire interface public\&. You can do it like this: .PP .CS snit::widget combobox { component listbox -public listbox constructor {args} { install listbox using listbox $win\&.listbox \&.\&.\&.\&. } } combobox \&.mycombo \&.mycombo listbox configure -width 30 .CE .PP Your comobox widget, \fB\&.mycombo\fR, now has a \fBlistbox\fR method which has all of the same subcommands as the listbox widget itself\&. Thus, the above code sets the listbox component's width to 30\&. .PP Usually you'll let the method name be the same as the component name; however, you can name it anything you like\&. .SH "TYPE COMPONENTS" .SS "WHAT IS A TYPE COMPONENT?" A type component is a component that belongs to the type itself instead of to a particular instance of the type\&. The relationship between components and type components is the same as the relationship between \fBINSTANCE VARIABLES\fR and \fBTYPE VARIABLES\fR\&. Both \fBINSTANCE METHODS\fR and \fBTYPE METHODS\fR can be delegated to type components\&. .PP Once you understand \fBCOMPONENTS\fR and \fBDELEGATION\fR, type components are just more of the same\&. .SS "HOW DO I DECLARE A TYPE COMPONENT?" Declare a type component using the \fBtypecomponent\fR statement\&. It takes the same options (\fB-inherit\fR and \fB-public\fR) as the \fBcomponent\fR statement does, and defines a type variable to hold the type component's object command\&. .PP Suppose in your model you've got many dogs, but only one veterinarian\&. You might make the veterinarian a type component\&. .CS snit::type veterinarian { \&.\&.\&. } snit::type dog { typecomponent vet # \&.\&.\&. } .CE .SS "HOW DO I INSTALL A TYPE COMPONENT?" Just use the \fBset\fR command to assign the component's object command to the type component\&. Because types (even \fBsnit::widget\fR types) are not widgets, and do not have options anyway, the extra features of the \fBinstall\fR command are not needed\&. .PP You'll usually install type components in the type constructor, as shown here: .CS snit::type veterinarian { \&.\&.\&. } snit::type dog { typecomponent vet typeconstructor { set vet [veterinarian %AUTO%] } } .CE .SS "ARE THERE ANY LIMITATIONS ON TYPE COMPONENT NAMES?" Yes, the same as on \fBINSTANCE VARIABLES\fR, \fBTYPE VARIABLES\fR, and normal \fBCOMPONENTS\fR\&. .SH DELEGATION .SS "WHAT IS DELEGATION?" Delegation, simply put, is when you pass a task you've been given to one of your assistants\&. (You do have assistants, don't you?) Snit objects can do the same thing\&. The following example shows one way in which the \fBdog\fR object can delegate its \fBwag\fR method and its \fB-taillength\fR option to its \fBtail\fR component\&. .PP .CS snit::type dog { variable mytail option -taillength -configuremethod SetTailOption -cgetmethod GetTailOption method SetTailOption {option value} { $mytail configure $option $value } method GetTailOption {option} { $mytail cget $option } method wag {} { $mytail wag } constructor {args} { install mytail using tail %AUTO% -partof $self $self configurelist $args } } .CE .PP This is the hard way to do it, by it demonstrates what delegation is all about\&. See the following answers for the easy way to do it\&. .PP Note that the constructor calls the \fBconfigurelist\fR method \fBafter\fR it creates its \fBtail\fR; otherwise, if \fB-taillength\fR appeared in the list of \fBargs\fR we'd get an error\&. .SS "HOW CAN I DELEGATE A METHOD TO A COMPONENT OBJECT?" Delegation occurs frequently enough that Snit makes it easy\&. Any method can be delegated to any component or type component by placing a single \fBdelegate\fR statement in the type definition\&. (See \fBCOMPONENTS\fR and \fBTYPE COMPONENTS\fR for more information about component names\&.) .PP For example, here's a much better way to delegate the \fBdog\fR object's \fBwag\fR method: .PP .CS % snit::type dog { delegate method wag to mytail constructor {} { install mytail using tail %AUTO% } } ::dog % snit::type tail { method wag {} { return "Wag, wag, wag\&."} } ::tail % dog spot ::spot % spot wag Wag, wag, wag\&. .CE .PP This code has the same effect as the code shown under the previous question: when a \fBdog\fR's \fBwag\fR method is called, the call and its arguments are passed along automatically to the \fBtail\fR object\&. .PP Note that when a component is mentioned in a \fBdelegate\fR statement, the component's instance variable is defined implicitly\&. However, it's still good practice to declare it explicitly using the \fBcomponent\fR statement\&. .PP Note also that you can define a method name using the \fBmethod\fR statement, or you can define it using \fBdelegate\fR; you can't do both\&. .SS "CAN I DELEGATE TO A METHOD WITH A DIFFERENT NAME?" Suppose you wanted to delegate the \fBdog\fR's \fBwagtail\fR method to the \fBtail\fR's \fBwag\fR method\&. After all you wag the tail, not the dog\&. It's easily done: .PP .CS snit::type dog { delegate method wagtail to mytail as wag constructor {args} { install mytail using tail %AUTO% -partof $self $self configurelist $args } } .CE .PP .SS "CAN I DELEGATE TO A METHOD WITH ADDITIONAL ARGUMENTS?" Suppose the \fBtail\fR's \fBwag\fR method takes as an argument the number of times the tail should be wagged\&. You want to delegate the \fBdog\fR's \fBwagtail\fR method to the \fBtail\fR's \fBwag\fR method, specifying that the tail should be wagged exactly three times\&. This is easily done, too: .PP .CS snit::type dog { delegate method wagtail to mytail as {wag 3} # \&.\&.\&. } snit::type tail { method wag {count} { return [string repeat "Wag " $count] } # \&.\&.\&. } .CE .PP .SS "CAN I DELEGATE A METHOD TO SOMETHING OTHER THAN AN OBJECT?" Normal method delegation assumes that you're delegating a method (a subcommand of an object command) to a method of another object (a subcommand of a different object command)\&. But not all Tcl objects follow Tk conventions, and not everything you'd to which you'd like to delegate a method is necessary an object\&. Consequently, Snit makes it easy to delegate a method to pretty much anything you like using the \fBdelegate\fR statement's \fBusing\fR clause\&. .PP Suppose your dog simulation stores dogs in a database, each dog as a single record\&. The database API you're using provides a number of commands to manage records; each takes the record ID (a string you choose) as its first argument\&. For example, \fBsaverec\fR saves a record\&. If you let the record ID be the name of the dog object, you can delegate the dog's \fBsave\fR method to the \fBsaverec\fR command as follows: .CS snit::type dog { delegate method save using {saverec %s} } .CE The \fB%s\fR is replaced with the instance name when the \fBsave\fR method is called; any additional arguments are the appended to the resulting command\&. .PP The \fBusing\fR clause understands a number of other %-conversions; in addition to the instance name, you can substitute in the method name (\fB%m\fR), the type name (\fB%t\fR), the instance namespace (\fB%n\fR), the Tk window name (\fB%w\fR), and, if a component or typecomponent name was given in the \fBdelegate\fR statement, the component's object command (\fB%c\fR)\&. .SS "HOW CAN I DELEGATE A METHOD TO A TYPE COMPONENT OBJECT?" Just exactly as you would to a component object\&. The \fBdelegate method\fR statement accepts both component and type component names in its \fBto\fR clause\&. .SS "HOW CAN I DELEGATE A TYPE METHOD TO A TYPE COMPONENT OBJECT?" Use the \fBdelegate typemethod\fR statement\&. It works like \fBdelegate method\fR, with these differences: first, it defines a type method instead of an instance method; second, the \fBusing\fR clause ignores the \fB%s\fR, \fB%n\fR, and \fB%w\fR %-conversions\&. .PP Naturally, you can't delegate a type method to an instance component\&.\&.\&.Snit wouldn't know which instance should receive it\&. .SS "HOW CAN I DELEGATE AN OPTION TO A COMPONENT OBJECT?" The first question in this section (see \fBDELEGATION\fR) shows one way to delegate an option to a component; but this pattern occurs often enough that Snit makes it easy\&. For example, every \fBtail\fR object has a \fB-length\fR option; we want to allow the creator of a \fBdog\fR object to set the tail's length\&. We can do this: .PP .CS % snit::type dog { delegate option -length to mytail constructor {args} { install mytail using tail %AUTO% -partof $self $self configurelist $args } } ::dog % snit::type tail { option -partof option -length 5 } ::tail % dog spot -length 7 ::spot % spot cget -length 7 .CE .PP This produces nearly the same result as the \fB-configuremethod\fR and \fB-cgetmethod\fR shown under the first question in this section: whenever a \fBdog\fR object's \fB-length\fR option is set or retrieved, the underlying \fBtail\fR object's option is set or retrieved in turn\&. .PP Note that you can define an option name using the \fBoption\fR statement, or you can define it using \fBdelegate\fR; you can't do both\&. .SS "CAN I DELEGATE TO AN OPTION WITH A DIFFERENT NAME?" In the previous answer we delegated the \fBdog\fR's \fB-length\fR option down to its \fBtail\fR\&. This is, of course, wrong\&. The dog has a length, and the tail has a length, and they are different\&. What we'd really like to do is give the \fBdog\fR a \fB-taillength\fR option, but delegate it to the \fBtail\fR's \fB-length\fR option: .PP .CS snit::type dog { delegate option -taillength to mytail as -length constructor {args} { set mytail [tail %AUTO% -partof $self] $self configurelist $args } } .CE .PP .SS "HOW CAN I DELEGATE ANY UNRECOGNIZED METHOD OR OPTION TO A COMPONENT OBJECT?" It may happen that a Snit object gets most of its behavior from one of its components\&. This often happens with \fBsnit::widgetadaptors\fR, for example, where we wish to slightly the modify the behavior of an existing widget\&. To carry on with our \fBdog\fR example, however, suppose that we have a \fBsnit::type\fR called \fBanimal\fR that implements a variety of animal behaviors--moving, eating, sleeping, and so forth\&. We want our \fBdog\fR objects to inherit these same behaviors, while adding dog-like behaviors of its own\&. Here's how we can give a \fBdog\fR methods and options of its own while delegating all other methods and options to its \fBanimal\fR component: .PP .CS snit::type dog { delegate option * to animal delegate method * to animal option -akc 0 constructor {args} { install animal using animal %AUTO% -name $self $self configurelist $args } method wag {} { return "$self wags its tail" } } .CE .PP That's it\&. A \fBdog\fR is now an \fBanimal\fR that has a \fB-akc\fR option and can \fBwag\fR its tail\&. .PP Note that we don't need to specify the full list of method names or option names that \fBanimal\fR will receive\&. It gets anything \fBdog\fR doesn't recognize--and if it doesn't recognize it either, it will simply throw an error, just as it should\&. .PP You can also delegate all unknown type methods to a type component using \fBdelegate typemethod *\fR\&. .SS "HOW CAN I DELEGATE ALL BUT CERTAIN METHODS OR OPTIONS TO A COMPONENT?" In the previous answer, we said that every \fBdog\fR is an \fBanimal\fR by delegating all unknown methods and options to the \fBanimal\fR component\&. But what if the \fBanimal\fR type has some methods or options that we'd like to suppress? .PP One solution is to explicitly delegate all the options and methods, and forgo the convenience of \fBdelegate method *\fR and \fBdelegate option *\fR\&. But if we wish to suppress only a few options or methods, there's an easier way: .PP .CS snit::type dog { delegate option * to animal except -numlegs delegate method * to animal except {fly climb} # \&.\&.\&. constructor {args} { install animal using animal %AUTO% -name $self -numlegs 4 $self configurelist $args } # \&.\&.\&. } .CE .PP Dogs have four legs, so we specify that explicitly when we create the \fBanimal\fR component, and explicitly exclude \fB-numlegs\fR from the set of delegated options\&. Similarly, dogs can neither \fBfly\fR nor \fBclimb\fR, so we exclude those \fBanimal\fR methods as shown\&. .SS "CAN A HIERARCHICAL METHOD BE DELEGATED?" Yes; just specify multiple words in the delegated method's name: .PP .CS snit::type tail { method wag {} {return "Wag, wag"} method droop {} {return "Droop, droop"} } snit::type dog { delegate method {tail wag} to mytail delegate method {tail droop} to mytail # \&.\&.\&. constructor {args} { install mytail using tail %AUTO% $self configurelist $args } # \&.\&.\&. } .CE .PP Unrecognized hierarchical methods can also be delegated; the following code delegates all subcommands of the "tail" method to the "mytail" component: .PP .CS snit::type dog { delegate method {tail *} to mytail # \&.\&.\&. } .CE .PP .SH WIDGETS .SS "WHAT IS A SNIT::WIDGET?" A \fBsnit::widget\fR is the Snit version of what Tcl programmers usually call a \fImegawidget\fR: a widget-like object usually consisting of one or more Tk widgets all contained within a Tk frame\&. .PP A \fBsnit::widget\fR is also a special kind of \fBsnit::type\fR\&. Just about everything in this FAQ list that relates to \fBsnit::types\fR also applies to \fBsnit::widgets\fR\&. .SS "HOW DO I DEFINE A SNIT::WIDGET?" \fBsnit::widgets\fR are defined using the \fBsnit::widget\fR command, just as \fBsnit::types\fR are defined by the \fBsnit::type\fR command\&. .PP The body of the definition can contain all of the same kinds of statements, plus a couple of others which will be mentioned below\&. .SS "HOW DO SNIT::WIDGETS DIFFER FROM SNIT::TYPES?" .IP \(bu The name of an instance of a \fBsnit::type\fR can be any valid Tcl command name, in any namespace\&. The name of an instance of a \fBsnit::widget\fR must be a valid Tk widget name, and its parent widget must already exist\&. .IP \(bu An instance of a \fBsnit::type\fR can be destroyed by calling its \fBdestroy\fR method\&. Instances of a \fBsnit::widget\fR have no destroy method; use the Tk \fBdestroy\fR command instead\&. .IP \(bu Every instance of a \fBsnit::widget\fR has one predefined component called its \fBhull\fR component\&. The hull is usually a Tk \fBframe\fR or \fBtoplevel\fR widget; any other widgets created as part of the \fBsnit::widget\fR will usually be contained within the hull\&. .IP \(bu \fBsnit::widget\fRs can have their options receive default values from \fBTHE TK OPTION DATABASE\fR\&. .PP .SS "WHAT IS A HULL COMPONENT?" Snit can't create a Tk widget object; only Tk can do that\&. Thus, every instance of a \fBsnit::widget\fR must be wrapped around a genuine Tk widget; this Tk widget is called the \fIhull component\fR\&. Snit effectively piggybacks the behavior you define (methods, options, and so forth) on top of the hull component so that the whole thing behaves like a standard Tk widget\&. .PP For \fBsnit::widget\fRs the hull component must be a Tk widget that defines the \fB-class\fR option\&. .PP \fBsnit::widgetadaptor\fRs differ from \fBsnit::widget\fRs chiefly in that any kind of widget can be used as the hull component; see \fBWIDGET ADAPTORS\fR\&. .SS "HOW CAN I SET THE HULL TYPE FOR A SNIT::WIDGET?" A \fBsnit::widget\fR's hull component will usually be a Tk \fBframe\fR widget; however, it may be any Tk widget that defines the \fB-class\fR option\&. You can explicitly choose the hull type you prefer by including the \fBhulltype\fR command in the widget definition: .PP .CS snit::widget mytoplevel { hulltype toplevel # \&.\&.\&. } .CE .PP If no \fBhulltype\fR command appears, the hull will be a \fBframe\fR\&. .PP By default, Snit recognizes the following hull types: the Tk widgets \fBframe\fR, \fBlabelframe\fR, \fBtoplevel\fR, and the Tile widgets \fBttk::frame\fR, \fBttk::labelframe\fR, and \fBttk::toplevel\fR\&. To enable the use of some other kind of widget as the hull type, you can \fBlappend\fR the widget command to the variable \fBsnit::hulltypes\fR (always provided the widget defines the \fB-class\fR option\&. For example, suppose Tk gets a new widget type called a \fBprettyframe\fR: .PP .CS lappend snit::hulltypes prettyframe snit::widget mywidget { hulltype prettyframe # \&.\&.\&. } .CE .PP .SS "HOW SHOULD I NAME WIDGETS WHICH ARE COMPONENTS OF A SNIT::WIDGET?" Every widget, whether a genuine Tk widget or a Snit megawidget, has to have a valid Tk window name\&. When a \fBsnit::widget\fR is first created, its instance name, \fBself\fR, is a Tk window name; however, if the \fBsnit::widget\fR is used as the hull component by a \fBsnit::widgetadaptor\fR its instance name will be changed to something else\&. For this reason, every \fBsnit::widget\fR method, constructor, destructor, and so forth is passed another implicit argument, \fBwin\fR, which is the window name of the megawidget\&. Any children should be named using \fBwin\fR as the root\&. .PP Thus, suppose you're writing a toolbar widget, a frame consisting of a number of buttons placed side-by-side\&. It might look something like this: .PP .CS snit::widget toolbar { delegate option * to hull constructor {args} { button $win\&.open -text Open -command [mymethod open] button $win\&.save -text Save -command [mymethod save] # \&.\&.\&.\&. $self configurelist $args } } .CE .PP See also the question on renaming objects, toward the top of this file\&. .SH "WIDGET ADAPTORS" .SS "WHAT IS A SNIT::WIDGETADAPTOR?" A \fBsnit::widgetadaptor\fR is a kind of \fBsnit::widget\fR\&. Whereas a \fBsnit::widget\fR's hull is automatically created and is always a Tk frame, a \fBsnit::widgetadaptor\fR can be based on any Tk widget--or on any Snit megawidget, or even (with luck) on megawidgets defined using some other package\&. .PP It's called a \fIwidget adaptor\fR because it allows you to take an existing widget and customize its behavior\&. .SS "HOW DO I DEFINE A SNIT::WIDGETADAPTOR?" Use the \fBsnit::widgetadaptor\fR command\&. The definition for a \fBsnit::widgetadaptor\fR looks just like that for a \fBsnit::type\fR or \fBsnit::widget\fR, except that the constructor must create and install the hull component\&. .PP For example, the following code creates a read-only text widget by the simple device of turning its \fBinsert\fR and \fBdelete\fR methods into no-ops\&. Then, we define new methods, \fBins\fR and \fBdel\fR, which get delegated to the hull component as \fBinsert\fR and \fBdelete\fR\&. Thus, we've adapted the text widget and given it new behavior while still leaving it fundamentally a text widget\&. .PP .CS ::snit::widgetadaptor rotext { constructor {args} { # Create the text widget; turn off its insert cursor installhull using text -insertwidth 0 # Apply any options passed at creation time\&. $self configurelist $args } # Disable the text widget's insert and delete methods, to # make this readonly\&. method insert {args} {} method delete {args} {} # Enable ins and del as synonyms, so the program can insert and # delete\&. delegate method ins to hull as insert delegate method del to hull as delete # Pass all other methods and options to the real text widget, so # that the remaining behavior is as expected\&. delegate method * to hull delegate option * to hull } .CE .PP The most important part is in the constructor\&. Whereas \fBsnit::widget\fR creates the hull for you, \fBsnit::widgetadaptor\fR cannot -- it doesn't know what kind of widget you want\&. So the first thing the constructor does is create the hull component (a Tk text widget in this case), and then installs it using the \fBinstallhull\fR command\&. .PP \fINote:\fR There is no instance command until you create one by installing a hull component\&. Any attempt to pass methods to \fB$self\fR prior to calling \fBinstallhull\fR will fail\&. .SS "CAN I ADAPT A WIDGET CREATED ELSEWHERE IN THE PROGRAM?" Yes\&. .PP At times, it can be convenient to adapt a pre-existing widget instead of creating your own\&. For example, the Bwidget \fBPagesManager\fR widget manages a set of \fBframe\fR widgets, only one of which is visible at a time\&. The application chooses which \fBframe\fR is visible\&. All of the These \fBframe\fRs are created by the \fBPagesManager\fR itself, using its \fBadd\fR method\&. It's convenient to adapt these frames to do what we'd like them to do\&. .PP In a case like this, the Tk widget will already exist when the \fBsnit::widgetadaptor\fR is created\&. Snit provides an alternate form of the \fBinstallhull\fR command for this purpose: .PP .CS snit::widgetadaptor pageadaptor { constructor {args} { # The widget already exists; just install it\&. installhull $win # \&.\&.\&. } } .CE .SS "CAN I ADAPT ANOTHER MEGAWIDGET?" Maybe\&. If the other megawidget is a \fBsnit::widget\fR or \fBsnit::widgetadaptor\fR, then yes\&. If it isn't then, again, maybe\&. You'll have to try it and see\&. You're most likely to have trouble with widget destruction--you have to make sure that your megawidget code receives the \fB\fR event before the megawidget you're adapting does\&. .SH "THE TK OPTION DATABASE" .SS "WHAT IS THE TK OPTION DATABASE?" The Tk option database is a database of default option values maintained by Tk itself; every Tk application has one\&. The concept of the option database derives from something called the X Windows resource database; however, the option database is available in every Tk implementation, including those which do not use the X Windows system (e\&.g\&., Microsoft Windows)\&. .PP Full details about the Tk option database are beyond the scope of this document; both \fIPractical Programming in Tcl and Tk\fR by Welch, Jones, and Hobbs, and \fIEffective Tcl/Tk Programming\fR by Harrison and McClennan\&., have good introductions to it\&. .PP Snit is implemented so that most of the time it will simply do the right thing with respect to the option database, provided that the widget developer does the right thing by Snit\&. The body of this section goes into great deal about what Snit requires\&. The following is a brief statement of the requirements, for reference\&. .PP .IP \(bu If the widget's default widget class is not what is desired, set it explicitly using the \fBwidgetclass\fR statement in the widget definition\&. .IP \(bu When defining or delegating options, specify the resource and class names explicitly when necessary\&. .IP \(bu Use the \fBinstallhull using\fR command to create and install the hull for \fBsnit::widgetadaptor\fRs\&. .IP \(bu Use the \fBinstall\fR command to create and install all components which are widgets\&. .IP \(bu Use the \fBinstall\fR command to create and install components which aren't widgets if you'd like them to receive option values from the option database\&. .PP .PP The interaction of Tk widgets with the option database is a complex thing; the interaction of Snit with the option database is even more so, and repays attention to detail\&. .SS "DO SNIT::TYPES USE THE TK OPTION DATABASE?" No, they don't; querying the option database requires a Tk window name, and \fBsnit::type\fRs don't have one\&. .PP If you create an instance of a \fBsnit::type\fR as a component of a \fBsnit::widget\fR or \fBsnit::widgetadaptor\fR, on the other hand, and if any options are delegated to the component, and if you use \fBinstall\fR to create and install it, then the megawidget will query the option database on the \fBsnit::type\fR's behalf\&. This might or might not be what you want, so take care\&. .SS "WHAT IS MY SNIT::WIDGET'S WIDGET CLASS?" Every Tk widget has a "widget class": a name that is used when adding option settings to the database\&. For Tk widgets, the widget class is the same as the widget command name with an initial capital\&. For example, the widget class of the Tk \fBbutton\fR widget is \fBButton\fR\&. .PP Similarly, the widget class of a \fBsnit::widget\fR defaults to the unqualified type name with the first letter capitalized\&. For example, the widget class of .PP .CS snit::widget ::mylibrary::scrolledText { \&.\&.\&. } .CE .PP is \fBScrolledText\fR\&. .PP The widget class can also be set explicitly using the \fBwidgetclass\fR statement within the \fBsnit::widget\fR definition: .PP .CS snit::widget ::mylibrary::scrolledText { widgetclass Text # \&.\&.\&. } .CE .PP The above definition says that a \fBscrolledText\fR megawidget has the same widget class as an ordinary \fBtext\fR widget\&. This might or might not be a good idea, depending on how the rest of the megawidget is defined, and how its options are delegated\&. .SS "WHAT IS MY SNIT::WIDGETADAPTOR'S WIDGET CLASS?" The widget class of a \fBsnit::widgetadaptor\fR is just the widget class of its hull widget; Snit has no control over this\&. .PP Note that the widget class can be changed only for \fBframe\fR and \fBtoplevel\fR widgets, which is why these are the valid hull types for \fBsnit::widget\fRs\&. .PP Try to use \fBsnit::widgetadaptor\fRs only to make small modifications to another widget's behavior\&. Then, it will usually not make sense to change the widget's widget class anyway\&. .SS "WHAT ARE OPTION RESOURCE AND CLASS NAMES?" Every Tk widget option has three names: the option name, the resource name, and the class name\&. The option name begins with a hyphen and is all lowercase; it's used when creating widgets, and with the \fBconfigure\fR and \fBcget\fR commands\&. .PP The resource and class names are used to initialize option default values by querying the option database\&. The resource name is usually just the option name minus the hyphen, but may contain uppercase letters at word boundaries; the class name is usually just the resource name with an initial capital, but not always\&. For example, here are the option, resource, and class names for several Tk \fBtext\fR widget options: .PP .CS -background background Background -borderwidth borderWidth BorderWidth -insertborderwidth insertBorderWidth BorderWidth -padx padX Pad .CE .PP As is easily seen, sometimes the resource and class names can be inferred from the option name, but not always\&. .SS "WHAT ARE THE RESOURCE AND CLASS NAMES FOR MY MEGAWIDGET'S OPTIONS?" For options implicitly delegated to a component using \fBdelegate option *\fR, the resource and class names will be exactly those defined by the component\&. The \fBconfigure\fR method returns these names, along with the option's default and current values: .PP .CS % snit::widget mytext { delegate option * to text constructor {args} { install text using text \&.text # \&.\&.\&. } # \&.\&.\&. } ::mytext % mytext \&.text \&.text % \&.text configure -padx -padx padX Pad 1 1 % .CE .PP For all other options (whether locally defined or explicitly delegated), the resource and class names can be defined explicitly, or they can be allowed to have default values\&. .PP By default, the resource name is just the option name minus the hyphen; the the class name is just the option name with an initial capital letter\&. For example, suppose we explicitly delegate "-padx": .PP .CS % snit::widget mytext { option -myvalue 5 delegate option -padx to text delegate option * to text constructor {args} { install text using text \&.text # \&.\&.\&. } # \&.\&.\&. } ::mytext % mytext \&.text \&.text % \&.text configure -myvalue -myvalue myvalue Myvalue 5 5 % \&.text configure -padx -padx padx Padx 1 1 % .CE .PP Here the resource and class names are chosen using the default rules\&. Often these rules are sufficient, but in the case of "-padx" we'd most likely prefer that the option's resource and class names are the same as for the built-in Tk widgets\&. This is easily done: .PP .CS % snit::widget mytext { delegate option {-padx padX Pad} to text # \&.\&.\&. } ::mytext % mytext \&.text \&.text % \&.text configure -padx -padx padX Pad 1 1 % .CE .SS "HOW DOES SNIT INITIALIZE MY MEGAWIDGET'S LOCALLY-DEFINED OPTIONS?" The option database is queried for each of the megawidget's locally-defined options, using the option's resource and class name\&. If the result isn't "", then it replaces the default value given in widget definition\&. In either case, the default can be overridden by the caller\&. For example, .PP .CS option add *Mywidget\&.texture pebbled snit::widget mywidget { option -texture smooth # \&.\&.\&. } mywidget \&.mywidget -texture greasy .CE .PP Here, \fB-texture\fR would normally default to "smooth", but because of the entry added to the option database it defaults to "pebbled"\&. However, the caller has explicitly overridden the default, and so the new widget will be "greasy"\&. .SS "HOW DOES SNIT INITIALIZE DELEGATED OPTIONS?" That depends on whether the options are delegated to the hull, or to some other component\&. .SS "HOW DOES SNIT INITIALIZE OPTIONS DELEGATED TO THE HULL?" A \fBsnit::widget\fR's hull is a widget, and given that its class has been set it is expected to query the option database for itself\&. The only exception concerns options that are delegated to it with a different name\&. Consider the following code: .PP .CS option add *Mywidget\&.borderWidth 5 option add *Mywidget\&.relief sunken option add *Mywidget\&.hullbackground red option add *Mywidget\&.background green snit::widget mywidget { delegate option -borderwidth to hull delegate option -hullbackground to hull as -background delegate option * to hull # \&.\&.\&. } mywidget \&.mywidget set A [\&.mywidget cget -relief] set B [\&.mywidget cget -hullbackground] set C [\&.mywidget cget -background] set D [\&.mywidget cget -borderwidth] .CE .PP The question is, what are the values of variables A, B, C and D? .PP The value of A is "sunken"\&. The hull is a Tk frame which has been given the widget class \fBMywidget\fR; it will automatically query the option database and pick up this value\&. Since the \fB-relief\fR option is implicitly delegated to the hull, Snit takes no action\&. .PP The value of B is "red"\&. The hull will automatically pick up the value "green" for its \fB-background\fR option, just as it picked up the \fB-relief\fR value\&. However, Snit knows that \fB-hullbackground\fR is mapped to the hull's \fB-background\fR option; hence, it queries the option database for \fB-hullbackground\fR and gets "red" and updates the hull accordingly\&. .PP The value of C is also "red", because \fB-background\fR is implicitly delegated to the hull; thus, retrieving it is the same as retrieving \fB-hullbackground\fR\&. Note that this case is unusual; the \fB-background\fR option should probably have been excluded using the delegate statement's \fBexcept\fR clause, or (more likely) delegated to some other component\&. .PP The value of D is "5", but not for the reason you think\&. Note that as it is defined above, the resource name for \fB-borderwidth\fR defaults to \fBborderwidth\fR, whereas the option database entry is \fBborderWidth\fR, in accordance with the standard Tk naming for this option\&. As with \fB-relief\fR, the hull picks up its own \fB-borderwidth\fR option before Snit does anything\&. Because the option is delegated under its own name, Snit assumes that the correct thing has happened, and doesn't worry about it any further\&. To avoid confusion, the \fB-borderwidth\fR option should have been delegated like this: .PP .CS delegate option {-borderwidth borderWidth BorderWidth} to hull .CE .PP For \fBsnit::widgetadaptor\fRs, the case is somewhat altered\&. Widget adaptors retain the widget class of their hull, and the hull is not created automatically by Snit\&. Instead, the \fBsnit::widgetadaptor\fR must call \fBinstallhull\fR in its constructor\&. The normal way to do this is as follows: .PP .CS snit::widgetadaptor mywidget { # \&.\&.\&. constructor {args} { # \&.\&.\&. installhull using text -foreground white # \&.\&.\&. } # \&.\&.\&. } .CE .PP In this case, the \fBinstallhull\fR command will create the hull using a command like this: .PP .CS set hull [text $win -foreground white] .CE .PP The hull is a \fBtext\fR widget, so its widget class is \fBText\fR\&. Just as with \fBsnit::widget\fR hulls, Snit assumes that it will pick up all of its normal option values automatically, without help from Snit\&. Options delegated from a different name are initialized from the option database in the same way as described above\&. .PP In earlier versions of Snit, \fBsnit::widgetadaptor\fRs were expected to call \fBinstallhull\fR like this: .PP .CS installhull [text $win -foreground white] .CE .PP This form still works--but Snit will not query the option database as described above\&. .SS "HOW DOES SNIT INITIALIZE OPTIONS DELEGATED TO OTHER COMPONENTS?" For hull components, Snit assumes that Tk will do most of the work automatically\&. Non-hull components are somewhat more complicated, because they are matched against the option database twice\&. .PP A component widget remains a widget still, and is therefore initialized from the option database in the usual way\&. A \fBtext\fR widget remains a \fBtext\fR widget whether it is a component of a megawidget or not, and will be created as such\&. .PP But then, the option database is queried for all options delegated to the component, and the component is initialized accordingly--provided that the \fBinstall\fR command is used to create it\&. .PP Before option database support was added to Snit, the usual way to create a component was to simply create it in the constructor and assign its command name to the component variable: .PP .CS snit::widget mywidget { delegate option -background to myComp constructor {args} { set myComp [text $win\&.text -foreground black] } } .CE .PP The drawback of this method is that Snit has no opportunity to initialize the component properly\&. Hence, the following approach is now used: .PP .CS snit::widget mywidget { delegate option -background to myComp constructor {args} { install myComp using text $win\&.text -foreground black } } .CE .PP The \fBinstall\fR command does the following: .PP .IP \(bu Builds a list of the options explicitly included in the \fBinstall\fR command--in this case, \fB-foreground\fR\&. .IP \(bu Queries the option database for all options delegated explicitly to the named component\&. .IP \(bu Creates the component using the specified command, after inserting into it a list of options and values read from the option database\&. Thus, the explicitly included options (like \fB-foreground\fR) will override anything read from the option database\&. .IP \(bu If the widget definition implicitly delegated options to the component using \fBdelegate option *\fR, then Snit calls the newly created component's \fBconfigure\fR method to receive a list of all of the component's options\&. From this Snit builds a list of options implicitly delegated to the component which were not explicitly included in the \fBinstall\fR command\&. For all such options, Snit queries the option database and configures the component accordingly\&. .PP You don't really need to know all of this; just use \fBinstall\fR to install your components, and Snit will try to do the right thing\&. .SS "WHAT HAPPENS IF I INSTALL A NON-WIDGET AS A COMPONENT OF WIDGET?" A \fBsnit::type\fR never queries the option database\&. However, a \fBsnit::widget\fR can have non-widget components\&. And if options are delegated to those components, and if the \fBinstall\fR command is used to install those components, then they will be initialized from the option database just as widget components are\&. .PP However, when used within a megawidget, \fBinstall\fR assumes that the created component uses a reasonably standard widget-like creation syntax\&. If it doesn't, don't use \fBinstall\fR\&. .SH "ENSEMBLE COMMANDS" .SS "WHAT IS AN ENSEMBLE COMMAND?" An ensemble command is a command with subcommands\&. Snit objects are all ensemble commands; however, the term more usually refers to commands like the standard Tcl commands \fBstring\fR, \fBfile\fR, and \fBclock\fR\&. In a sense, these are singleton objects--there's only one instance of them\&. .SS "HOW CAN I CREATE AN ENSEMBLE COMMAND USING SNIT?" There are two ways--as a \fBsnit::type\fR, or as an instance of a \fBsnit::type\fR\&. .SS "HOW CAN I CREATE AN ENSEMBLE COMMAND USING AN INSTANCE OF A SNIT::TYPE?" Define a type whose \fBINSTANCE METHODS\fR are the subcommands of your ensemble command\&. Then, create an instance of the type with the desired name\&. .PP For example, the following code uses \fBDELEGATION\fR to create a work-alike for the standard \fBstring\fR command: .CS snit::type ::mynamespace::mystringtype { delegate method * to stringhandler constructor {} { set stringhandler string } } ::mynamespace::mystringtype mystring .CE We create the type in a namespace, so that the type command is hidden; then we create a single instance with the desired name-- \fBmystring\fR, in this case\&. .PP This method has two drawbacks\&. First, it leaves the type command floating about\&. More seriously, your shiny new ensemble command will have \fBinfo\fR and \fBdestroy\fR subcommands that you probably have no use for\&. But read on\&. .SS "HOW CAN I CREATE AN ENSEMBLE COMMAND USING A SNIT::TYPE?" Define a type whose \fBTYPE METHODS\fR are the subcommands of your ensemble command\&. .PP For example, the following code uses \fBDELEGATION\fR to create a work-alike for the standard \fBstring\fR command: .CS snit::type mystring { delegate typemethod * to stringhandler typeconstructor { set stringhandler string } } .CE Now the type command itself is your ensemble command\&. .PP This method has only one drawback, and though it's major, it's also surmountable\&. Your new ensemble command will have \fBcreate\fR, \fBinfo\fR and \fBdestroy\fR subcommands you don't want\&. And worse yet, since the \fBcreate\fR method can be implicit, users of your command will accidentally be creating instances of your \fBmystring\fR type if they should mispell one of the subcommands\&. The command will succeed--the first time--but won't do what's wanted\&. This is very bad\&. .PP The work around is to set some \fBPRAGMAS\fR, as shown here: .CS snit::type mystring { pragma -hastypeinfo no pragma -hastypedestroy no pragma -hasinstances no delegate typemethod * to stringhandler typeconstructor { set stringhandler string } } .CE Here we've used the \fBpragma\fR statement to tell Snit that we don't want the \fBinfo\fR typemethod or the \fBdestroy\fR typemethod, and that our type has no instances; this eliminates the \fBcreate\fR typemethod and all related code\&. As a result, our ensemble command will be well-behaved, with no unexpected subcommands\&. .SH PRAGMAS .SS "WHAT IS A PRAGMA?" A pragma is an option you can set in your type definitions that affects how the type is defined and how it works once it is defined\&. .SS "HOW DO I SET A PRAGMA?" Use the \fBpragma\fR statement\&. Each pragma is an option with a value; each time you use the \fBpragma\fR statement you can set one or more of them\&. .SS "HOW CAN I GET RID OF THE "INFO" TYPE METHOD?" Set the \fB-hastypeinfo\fR pragma to \fBno\fR: .CS snit::type dog { pragma -hastypeinfo no # \&.\&.\&. } .CE Snit will refrain from defining the \fBinfo\fR type method\&. .SS "HOW CAN I GET RID OF THE "DESTROY" TYPE METHOD?" Set the \fB-hastypedestroy\fR pragma to \fBno\fR: .CS snit::type dog { pragma -hastypedestroy no # \&.\&.\&. } .CE Snit will refrain from defining the \fBdestroy\fR type method\&. .SS "HOW CAN I GET RID OF THE "CREATE" TYPE METHOD?" Set the \fB-hasinstances\fR pragma to \fBno\fR: .CS snit::type dog { pragma -hasinstances no # \&.\&.\&. } .CE Snit will refrain from defining the \fBcreate\fR type method; if you call the type command with an unknown method name, you'll get an error instead of a new instance of the type\&. .PP This is useful if you wish to use a \fBsnit::type\fR to define an ensemble command rather than a type with instances\&. .PP Pragmas \fB-hastypemethods\fR and \fB-hasinstances\fR cannot both be false (or there'd be nothing left)\&. .SS "HOW CAN I GET RID OF TYPE METHODS ALTOGETHER?" Normal Tk widget type commands don't have subcommands; all they do is create widgets--in Snit terms, the type command calls the \fBcreate\fR type method directly\&. To get the same behavior from Snit, set the \fB-hastypemethods\fR pragma to \fBno\fR: .CS snit::type dog { pragma -hastypemethods no #\&.\&.\&. } # Creates ::spot dog spot # Tries to create an instance called ::create dog create spot .CE Pragmas \fB-hastypemethods\fR and \fB-hasinstances\fR cannot both be false (or there'd be nothing left)\&. .SS "WHY CAN'T I CREATE AN OBJECT THAT REPLACES AN OLD OBJECT WITH THE SAME NAME?" Up until Snit 0\&.95, you could use any name for an instance of a \fBsnit::type\fR, even if the name was already in use by some other object or command\&. You could do the following, for example: .CS snit::type dog { \&.\&.\&. } dog proc .CE You now have a new dog named "proc", which is probably not something that you really wanted to do\&. As a result, Snit now throws an error if your chosen instance name names an existing command\&. To restore the old behavior, set the \fB-canreplace\fR pragma to \fByes\fR: .CS snit::type dog { pragma -canreplace yes # \&.\&.\&. } .CE .SS "HOW CAN I MAKE MY SIMPLE TYPE RUN FASTER?" In Snit 1\&.x, you can set the \fB-simpledispatch\fR pragma to \fByes\fR\&. .PP Snit 1\&.x method dispatch is both flexible and fast, but the flexibility comes with a price\&. If your type doesn't require the flexibility, the \fB-simpledispatch\fR pragma allows you to substitute a simpler dispatch mechanism that runs quite a bit faster\&. The limitations are these: .IP \(bu Methods cannot be delegated\&. .IP \(bu \fBuplevel\fR and \fBupvar\fR do not work as expected: the caller's scope is two levels up rather than one\&. .IP \(bu The option-handling methods (\fBcget\fR, \fBconfigure\fR, and \fBconfigurelist\fR) are very slightly slower\&. .PP In Snit 2\&.2, the \fB-simpledispatch\fR macro is obsolete, and ignored; all Snit 2\&.2 method dispatch is faster than Snit 1\&.x's \fB-simpledispatch\fR\&. .SH MACROS .SS "WHAT IS A MACRO?" A Snit macro is nothing more than a Tcl proc that's defined in the Tcl interpreter used to compile Snit type definitions\&. .SS "WHAT ARE MACROS GOOD FOR?" You can use Snit macros to define new type definition syntax, and to support conditional compilation\&. .SS "HOW DO I DO CONDITIONAL COMPILATION?" Suppose you want your type to use a fast C extension if it's available; otherwise, you'll fallback to a slower Tcl implementation\&. You want to define one set of methods in the first case, and another set in the second case\&. But how can your type definition know whether the fast C extension is available or not? .PP It's easily done\&. Outside of any type definition, define a macro that returns 1 if the extension is available, and 0 otherwise: .CS if {$gotFastExtension} { snit::macro fastcode {} {return 1} } else { snit::macro fastcode {} {return 0} } .CE Then, use your macro in your type definition: .CS snit::type dog { if {[fastcode]} { # Fast methods method bark {} {\&.\&.\&.} method wagtail {} {\&.\&.\&.} } else { # Slow methods method bark {} {\&.\&.\&.} method wagtail {} {\&.\&.\&.} } } .CE .SS "HOW DO I DEFINE NEW TYPE DEFINITION SYNTAX?" Use a macro\&. For example, your \fBsnit::widget\fR's \fB-background\fR option should be propagated to a number of component widgets\&. You could implement that like this: .CS snit::widget mywidget { option -background -default white -configuremethod PropagateBackground method PropagateBackground {option value} { $comp1 configure $option $value $comp2 configure $option $value $comp3 configure $option $value } } .CE For one option, this is fine; if you've got a number of options, it becomes tedious and error prone\&. So package it as a macro: .CS snit::macro propagate {option "to" components} { option $option -configuremethod Propagate$option set body "\\n" foreach comp $components { append body "\\$$comp configure $option \\$value\\n" } method Propagate$option {option value} $body } .CE Then you can use it like this: .CS snit::widget mywidget { option -background default -white option -foreground default -black propagate -background to {comp1 comp2 comp3} propagate -foreground to {comp1 comp2 comp3} } .CE .SS "ARE THERE ARE RESTRICTIONS ON MACRO NAMES?" Yes, there are\&. You can't redefine any standard Tcl commands or Snit type definition statements\&. You can use any other command name, including the name of a previously defined macro\&. .PP If you're using Snit macros in your application, go ahead and name them in the global namespace, as shown above\&. But if you're using them to define types or widgets for use by others, you should define your macros in the same namespace as your types or widgets\&. That way, they won't conflict with other people's macros\&. .PP If my fancy \fBsnit::widget\fR is called \fB::mylib::mywidget\fR, for example, then I should define my \fBpropagate\fR macro as \fB::mylib::propagate\fR: .CS snit::macro mylib::propagate {option "to" components} { \&.\&.\&. } snit::widget ::mylib::mywidget { option -background default -white option -foreground default -black mylib::propagate -background to {comp1 comp2 comp3} mylib::propagate -foreground to {comp1 comp2 comp3} } .CE .SH "BUGS, IDEAS, FEEDBACK" This document, and the package it describes, will undoubtedly contain bugs and other problems\&. Please report such in the category \fIsnit\fR of the \fITcllib Trackers\fR [http://core\&.tcl\&.tk/tcllib/reportlist]\&. Please also report any ideas for enhancements you may have for either package and/or documentation\&. .PP When proposing code changes, please provide \fIunified diffs\fR, i\&.e the output of \fBdiff -u\fR\&. .PP Note further that \fIattachments\fR are strongly preferred over inlined patches\&. Attachments can be made by going to the \fBEdit\fR form of the ticket immediately after its creation, and then using the left-most button in the secondary navigation bar\&. .SH KEYWORDS BWidget, C++, Incr Tcl, adaptors, class, mega widget, object, object oriented, widget, widget adaptors .SH CATEGORY Programming tools .SH COPYRIGHT .nf Copyright (c) 2003-2006, by William H\&. Duquette .fi