<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE TIP SYSTEM "http://www.tcl.tk/cgi-bin/tct/tip/tipxml.dtd">
<!-- Converted at Wed May 22 14:18:41 GMT 2013 -->
<!-- TIP AutoGenerator - written by Donal K. Fellows -->

<TIP number='379'>
<header><title>Add a Command for Delivering Events Without Tk</title><author address="mailto:will@wjduquette.com">Will Duquette</author><status type='project' state='draft' tclversion="8.7" vote='prior'>$Revision: 1.9 $</status><history></history><created day='17' month='oct' year='2010' /><keyword>event</keyword></header>
<abstract>This proposal defines the <emph style="bold">hook</emph> ensemble command, which implements the Subject/Observer pattern. It allows <emph style="italic">subjects</emph>, which may be modules, objects, widgets, and so forth, to synchronously call <emph style="italic">hooks</emph> which may be bound to an arbitrary number of subscribers, called <emph style="italic">observers</emph>. A subject may call any number of distinct hooks, and any number of observers can bind callbacks to a particular hook called by a particular subject. Hook bindings can be queried and deleted.</abstract>
<body><section title="Rationale">
<para>Tcl modules usually send notifications to other modules in two ways: via Tk events, and via callback options like the text widget&apos;s <emph style="bold">-yscrollcommand</emph> option. Tk events are available only in Tk, and callback options require tight coupling between the modules sending and receiving the notification.</para>
<para>Loose coupling between sender and receiver is often desirable, however. In Model/View/Controller terms, a View can send a command (stemming from user input) to the Controller, which updates the Model. The Model can then call a hook <emph style="italic">to which all relevant Views subscribe.</emph> The Model is decoupled from the Views, and indeed need not know whether any Views actually exist.</para>
<para>At present, Tcl/Tk has no standard mechanism for implementing loose coupling of this kind. This proposal defines a new command, <emph style="bold">hook</emph>, which implements just such a mechanism.</para>
</section>
<section title="Hook Bindings">
<para>The <emph style="bold">hook</emph> command manages a collection of hook bindings. A hook binding has four elements:</para>
<itemize><item.i><para>A <emph style="italic">subject</emph>: the name of the entity that will be calling the hook.</para></item.i><item.i><para>The <emph style="italic">hook</emph> itself. A hook usually reflects some occurrence in the life of the <emph style="italic">subject</emph> that other entities might care to know about. A <emph style="italic">hook</emph> has a name, and may also have arguments. Hook names are arbitrary strings. Each <emph style="italic">subject</emph> must document the names and arguments of the hooks it can call.</para></item.i><item.i><para>The name of the <emph style="italic">observer</emph> that wishes to receive the <emph style="italic">hook</emph> from the <emph style="italic">subject</emph>.</para></item.i><item.i><para>A command prefix to which the <emph style="italic">hook</emph> arguments will be appended when the binding is executed.</para></item.i></itemize>
<subsection title="Subjects and Observers">
<para>For convenience, this TIP collectively refers to subjects and observers as <emph style="italic">objects</emph>, while placing no requirements on how these <emph style="italic">objects</emph> are actually implemented. An object can be a a TclOO or Snit or XOTcl object, a Tcl command, a namespace, a module, a pseudo-object managed by some other object (as tags are managed by the Tk text widget) or simply a well-known name.</para>
<para>Subject and observer names are arbitrary strings; however, as <emph style="bold">hook</emph> might be used at the package level, it&apos;s necessary to have conventions that avoid name collisions between packages written by different people.</para>
<para>Therefore, any subject or observer name used in core or package level code should look like a Tcl command name, and should be defined in a namespace owned by the package. Consider, for example, an ensemble command <emph style="bold">::foo</emph> that creates a set of pseudo-objects and uses <emph style="bold">hook</emph> to send notifications. The pseudo-objects have names that are not commands and exist in their own namespace, rather like file handles do. To avoid name collisions with subjects defined by other packages, users of <emph style="bold">hook</emph>, these <emph style="bold">::foo</emph> handles should have names like <emph style="bold">::foo::1</emph>, <emph style="bold">::foo::2</emph>, and so on.</para>
<para>Because object names are arbitrary strings, application code can use whatever additional conventions are dictated by the needs of the application.</para>
</subsection>
</section>
<section title="Specification">
<para>The <emph style="bold">hook</emph> command is an ensemble command with the following subcommands:</para>
<subsection title="Bind Subcommand">
<para>This subcommand is used to create, update, delete, and query hook bindings.</para>
<quote><emph style="bold">hook bind</emph> ?<emph style="italic">subject</emph>? ?<emph style="italic">hook</emph>? ?<emph style="italic">observer</emph>? ?<emph style="italic">cmdPrefix</emph>?</quote>
<para>Called with no arguments, <emph style="bold">hook bind</emph> returns a list of the subjects with hooks to which observers are currently bound.</para>
<para>Called with one argument, a <emph style="italic">subject</emph>, <emph style="bold">hook bind</emph> returns a list of the subject&apos;s hooks to which observers are currently bound.</para>
<para>Called with two arguments, a <emph style="italic">subject</emph> and a <emph style="italic">hook</emph>, <emph style="bold">hook bind</emph> returns a list of the observers which are currently bound to this <emph style="italic">subject</emph> and <emph style="italic">hook</emph>.</para>
<para>Called with three arguments, a <emph style="italic">subject</emph>, a <emph style="italic">hook</emph>, and an <emph style="italic">observer</emph>, <emph style="bold">hook bind</emph> returns the binding proper, the command prefix to be called when the hook is called, or the empty string if there is no such binding.</para>
<para>Called with four arguments, <emph style="bold">hook bind</emph> creates, updates, or deletes a binding. If <emph style="italic">cmdPrefix</emph> is the empty string, <emph style="bold">hook bind</emph> deletes any existing binding for the <emph style="italic">subject</emph>, <emph style="italic">hook</emph>, and <emph style="italic">observer</emph>; nothing is returned. Otherwise, <emph style="italic">cmdPrefix</emph> must be a command prefix taking as many additional arguments as are documented for the <emph style="italic">subject</emph> and <emph style="italic">hook</emph>. The binding is added or updated, and the observer is returned.</para>
<para>If the <emph style="italic">observer</emph> is the empty string, &quot;&quot;, <emph style="bold">hook</emph> will create a new binding using an automatically generated observer name of the form <emph style="bold">::hook::ob</emph>&lt;<emph style="italic">number</emph>&gt;. The automatically generated name will be returned, and can be used to query, update, and delete the binding as usual. If automated observer names are always used, the observer name effectively becomes a unique binding ID.</para>
<subsubsection title="Binds During Calls">
<para>It is possible to call <emph style="bold">hook bind</emph> to create or delete a binding to a <emph style="italic">subject</emph> and <emph style="italic">hook</emph> while in an observer binding for that same <emph style="italic">subject</emph> and <emph style="italic">hook</emph>. The following rules determine what happens when <emph style="bold">hook bind $s $h $o $binding</emph> is called during the execution of <emph style="bold">hook call $s $h</emph>:</para>
<itemize><item.i><para>No binding is ever called after it is deleted.</para></item.i><item.i><para>When a binding is called, the most recently given command prefix is always used.</para></item.i><item.i><para>The set of observers whose bindings are to be called is determined when <emph style="bold">hook call</emph> begins to execute, and does not change thereafter, except that deleted bindings are not called.</para></item.i></itemize>
<para>In particular:</para>
<itemize><item.i><para>If $o&apos;s binding to $s and $h is deleted, and $o&apos;s binding has not yet been called during this execution of <emph style="bold">hook call $s $h</emph>, it will not be called. (Note that it might already have been called; and in all likelihood, it is probably deleting itself.)</para></item.i><item.i><para>If $o changes the command prefix that&apos;s bound to $s and $h, and if $o&apos;s binding has not yet been called during this execution of <emph style="bold">hook call $s $h</emph>, the new binding will be called when the time comes. (But again, it is probably $o&apos;s binding that is is making the change.)</para></item.i><item.i><para>If a new observer is bound to $s and $h, its binding will not be called until the next invocation of <emph style="bold">hook call $s $h</emph>.</para></item.i></itemize>
</subsubsection>
<subsubsection title="Discussion">
<para><emph style="bold">Optional Observers:</emph> It has been suggested that the <emph style="italic">observer</emph> argument should follow the <emph style="italic">cmdprefix</emph> argument; if it is omitted, an observer name would be automatically generated. However, the <emph style="italic">observer</emph> name is frequently used in practice, and is likely to be much shorter than the <emph style="italic">cmdprefix</emph>, which might be quite long. As a general rule, short arguments following long ones tend to get lost visually; keeping the <emph style="italic">observer</emph> before the <emph style="italic">cmdprefix</emph> leads to more easily readable code.</para>
</subsubsection>
</subsection>
<subsection title="Call Subcommand">
<quote><emph style="bold">hook call</emph> <emph style="italic">subject hook</emph> ?<emph style="italic">args...</emph>?</quote>
<para>This command is called when the named <emph style="italic">subject</emph> wishes to call the named <emph style="italic">hook</emph>. All relevant bindings are called with the specified arguments in the global namespace. Note that the bindings are called synchronously, before <emph style="bold">hook call</emph> returns; this allows the <emph style="italic">args</emph> to include references to entities that will be cleaned up as soon as the hook has been called.</para>
<para>The order in which the bindings are called is not guaranteed. If sequence among observers must be preserved, define one observer and have its bindings call the other callbacks directly in the proper sequence.</para>
<para>Because the <emph style="bold">hook</emph> mechanism is intended to support loose coupling, it is presumed that the <emph style="italic">subject</emph> has no knowledge of the observers, nor any expectation regarding return values. This has a number of implications:</para>
<itemize><item.i><para><emph style="bold">hook call</emph> returns the empty string.</para></item.i><item.i><para>Normal return values from observer bindings are ignored.</para></item.i><item.i><para>Errors and other exceptional returns propagate normally by default. This will rarely be what is wanted, because the subjects usually have no knowledge of the observers and will therefore have no particular competence at handling their errors. That makes it an application issue, and so applications will usually want to define an <emph style="bold">-errorcommand</emph>.</para></item.i></itemize>
<para>If the <emph style="bold">-errorcommand</emph> configuration option has a non-empty value, its value will be invoked for all errors and other exceptional returns in observer bindings. See <emph style="bold">hook configure</emph>, below, for more information on configuration options.</para>
<para>Also, see below for possible extensions to <emph style="bold">hook call</emph>.</para>
</subsection>
<subsection title="Forget Subcommand">
<quote><emph style="bold">hook forget</emph> <emph style="italic">object</emph></quote>
<para>This command deletes any existing bindings in which the named object appears as either the <emph style="italic">subject</emph> or the <emph style="italic">observer</emph>.</para>
<para>Bindings deleted by <emph style="bold">hook forget</emph> will never be called again. In particular,</para>
<itemize><item.i><para>If an observer is forgotten during a call to <emph style="bold">hook call</emph>, any uncalled binding it might have had to the relevant subject and hook will <emph style="bold">not</emph> be called subsequently.</para></item.i><item.i><para>If a subject $s is forgotten during a call to <emph style="bold">hook call $s $h</emph>, <emph style="bold">hook call</emph> will return as soon as the current binding returns. No further bindings will be called.</para></item.i></itemize>
</subsection>
<subsection title="Configuration Subcommands">
<quote><emph style="bold">hook cget</emph> <emph style="italic">option</emph></quote>
<para>This command returns the value of one of the <emph style="bold">hook</emph> command&apos;s configuration options.</para>
<quote><emph style="bold">hook configure</emph> <emph style="italic">option value</emph> ...</quote>
<para>This command sets the value of one or more of the <emph style="bold">hook</emph> command&apos;s configuration options:</para>
<describe><item.d name='-errorcommand'><para>If the value of this option is the empty string, &quot;&quot;, then errors and other exception returns in binding scripts are propagated normally. Otherwise, it must be a command prefix taking three additional arguments: a list {<emph style="italic">subject hook arglist observer</emph>}, the result string, and the return options dictionary. Given this information, the <emph style="bold">-errorcommand</emph> can choose to log the error, call <emph style="bold">interp bgerror</emph>, delete the errant binding (thus preventing the error from arising a second time) and so forth.</para></item.d><item.d name='-tracecommand'><para>The option&apos;s value should be a command prefix taking four arguments: a <emph style="italic">subject</emph>, a <emph style="italic">hook</emph>, a list of the hook&apos;s <emph style="italic">argument values</emph>, and a list of <emph style="italic">objects</emph> the hook. The command will be called for each hook that is called. This allows the application to trace hook execution for debugging purposes.</para></item.d></describe>
</subsection>
</section>
<section title="Example">
<para>The ::model module calls the &lt;Update&gt; hook in response to commands that change the model&apos;s data:</para>
<verbatim><vline encoding='base64'>ICAgaG9vayBjYWxsIDo6bW9kZWwgPFVwZGF0ZT4=</vline></verbatim>
<para>The .view megawidget displays the model state, and needs to know about model updates. Consequently, it subscribes to the ::model&apos;s &lt;Update&gt; hook.</para>
<verbatim><vline encoding='base64'>ICAgaG9vayBiaW5kIDo6bW9kZWwgPFVwZGF0ZT4gLnZpZXcgW2xpc3QgLnZpZXcgTW9kZWxVcGRhdGVd</vline></verbatim>
<para>When the ::model calls the hook, the .view&apos;s ModelUpdate subcommand will be called.</para>
<para>Later the .view megawidget is destroyed. In its destructor, it tells the <emph style="bold">hook</emph> that it no longer exists:</para>
<verbatim><vline encoding='base64'>ICAgaG9vayBmb3JnZXQgLnZpZXc=</vline></verbatim>
<para>All bindings involving .view are deleted.</para>
</section>
<section title="Possible Additions">
<para>During discussions on the tcl-core mailing list, members suggested a number of possible additions to the functionality described in the first draft of this TIP. Some small capabilities have been added in this draft; however, there are two significant ones that I have elected to defer, for two reasons:</para>
<itemize><item.i><para>Though reasonable additions, they are somewhat orthogonal to the functionality provided here.</para></item.i><item.i><para>They are somewhat speculative, as they reflect patterns I&apos;ve not actually used, whereas the functionality described above has been in use in real applications for the past five years.</para></item.i></itemize>
<para>Consequently, I&apos;d rather not delay this TIP until these suggested additions are mature. If this TIP is accepted, then these additions can be considered as TIPs in their own right.</para>
<para>On the other hand, they are genuinely interesting, so I want to mention them here.</para>
<subsection title="Asynchronous Dispatch">
<para>The <emph style="bold">hook call</emph> command calls bindings synchronously, returning after all bindings have been called. An asychronous mode has been proposed, where bindings would be called in the context of the event loop for even looser coupling between the subject and the observers. This is certainly doable; however, the same effect can be achieved by calling <emph style="bold">hook call</emph> in an <emph style="bold">after</emph> handler.</para>
<para>I&apos;ve often considered adding a mode like this to our existing implementation, but have always thought better of it in the end.</para>
</subsection>
<subsection title="Accumulating Binding Return Values">
<para>Two members of tcl-core have suggested that <emph style="bold">hook call</emph> would be useful to support plug-in architectures if the return values of all bindings called were properly captured. This is an interesting notion; but I&apos;m not sure how to get it right. In some use cases, it would be enough just to get a list of the return values. In other uses cases, the caller might want to know the observer, the return value, and the complete dictionary of return options.</para>
<para>I don&apos;t want to build up all of this return information in the usual case; if it isn&apos;t needed, there&apos;s no reason to spend the time accumulating it. Consequently, what makes sense to me is an option or options that determine what kind of information should be returned, e.g., <emph style="bold">hook call ?options...? $s $h ...</emph></para>
<para>Given that <emph style="bold">hook call</emph> currently returns the empty string, this functionality can easily be added at a later time.</para>
</subsection>
</section>
<section title="Prototype Implementation">
<para>A prototype implementation is available at [<url ref="http://www.wjduquette.com/notifier/hook-0.1.zip"/>]. It is written in Tcl. The prototype implementation should work in both Tcl 8.5 and Tcl 8.6.</para>
</section>
<section title="Copyright">
<para>This document has been placed in the public domain.</para>
</section>
</body></TIP>
