\documentclass[]{article}
\usepackage{amsmath,graphicx,supertabular,hyperref,tabularx,ifthen}
\title{TIP \#379: Add a Command for Delivering Events Without Tk}
\date{October 17, 2010}
\author{Will Duquette}
\urlstyle{sf}
\setlength{\parskip}{1ex}
\setlength{\parindent}{0pt}
\def\tipversion$#1${\texttt{\$#1\$}}
\def\tiplangle#1{\ensuremath{<}}
\def\tiprangle#1{\ensuremath{>}}
\def\tipbar#1{\ensuremath{|}}
\def\tipmail#1#2{\(\langle\){\small\expandafter\url{#1@#2}}\(\rangle\)}
\ifx\pdfoutput\undefined
\newcommand{\tipimage}[2]{\typeout{Make sure you download #1.eps}\ifthenelse{\lengthtest{0.8\textwidth>#2}\and\lengthtest{0pt<#2}}{\includegraphics{#1.eps}}{\includegraphics[width=0.8\textwidth]{#1.eps}}}
\newcommand{\tipxref}[1]{}
\newcommand{\tipxrefend}{}
\else
\newcommand{\tipimage}[2]{\typeout{Make sure you create #1.pdf}\ifthenelse{\lengthtest{0.8\textwidth>#2}\and\lengthtest{0pt<#2}}{\includegraphics{#1.pdf}}{\includegraphics[width=0.8\textwidth]{#1.pdf}}}
\pdfcatalog{/PageMode /UseOutlines}
\newcommand{\tipxref}[1]{\pdfannotlink attr {/C [0.5 0.5 1.0] /Border [0 0 1]} goto name {#1}}
\newcommand{\tipxrefend}{\pdfendlink}
\fi
\newenvironment{tipabstract}{\begin{abstract}}{\end{abstract}}
\begin{document}\maketitle
\begin{center}\begin{tabularx}{\linewidth}{|r@{: }X|}\hline
\textbf{TIP \#379}&\textbf{Add a Command for Delivering Events Without Tk}\\\hline
Author&

Will Duquette \tipmail{will}{wjduquette.com}
\\
Created&Sunday, \(\text{17}^{\text{th}}\) October 2010\\
Type&Project\\
Tcl Version&\(8.7\)\\
State&Draft\\
Vote&Pending\\
Version&\tipversion$Revision: 1.9 $\\
Keywords&event\\
Post History&\\
\hline\end{tabularx}\end{center}
\thispagestyle{empty}\pagestyle{empty}
\begin{tipabstract}

This proposal defines the \textbf{hook} ensemble command, which implements the Subject/Observer pattern. It allows \textit{subjects}, which may be modules, objects, widgets, and so forth, to synchronously call \textit{hooks} which may be bound to an arbitrary number of subscribers, called \textit{observers}. 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.
\end{tipabstract}
\tableofcontents\setcounter{page}{0}\clearpage\pagestyle{plain}

\section{Rationale}

Tcl modules usually send notifications to other modules in two ways: via Tk events, and via callback options like the text widget's \textbf{-yscrollcommand} option. Tk events are available only in Tk, and callback options require tight coupling between the modules sending and receiving the notification.

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 \textit{to which all relevant Views subscribe.} The Model is decoupled from the Views, and indeed need not know whether any Views actually exist.

At present, Tcl/Tk has no standard mechanism for implementing loose coupling of this kind. This proposal defines a new command, \textbf{hook}, which implements just such a mechanism.

\section{Hook Bindings}

The \textbf{hook} command manages a collection of hook bindings. A hook binding has four elements:
\begin{itemize}
\item{}
A \textit{subject}: the name of the entity that will be calling the hook.
\item{}
The \textit{hook} itself. A hook usually reflects some occurrence in the life of the \textit{subject} that other entities might care to know about. A \textit{hook} has a name, and may also have arguments. Hook names are arbitrary strings. Each \textit{subject} must document the names and arguments of the hooks it can call.
\item{}
The name of the \textit{observer} that wishes to receive the \textit{hook} from the \textit{subject}.
\item{}
A command prefix to which the \textit{hook} arguments will be appended when the binding is executed.
\end{itemize}

\subsection{Subjects and Observers}

For convenience, this TIP collectively refers to subjects and observers as \textit{objects}, while placing no requirements on how these \textit{objects} 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.

Subject and observer names are arbitrary strings; however, as \textbf{hook} might be used at the package level, it's necessary to have conventions that avoid name collisions between packages written by different people.

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 \textbf{::foo} that creates a set of pseudo-objects and uses \textbf{hook} 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 \textbf{hook}, these \textbf{::foo} handles should have names like \textbf{::foo::1}, \textbf{::foo::2}, and so on.

Because object names are arbitrary strings, application code can use whatever additional conventions are dictated by the needs of the application.

\section{Specification}

The \textbf{hook} command is an ensemble command with the following subcommands:

\subsection{Bind Subcommand}

This subcommand is used to create, update, delete, and query hook bindings.

\begin{quote}
\textbf{hook bind} ?\textit{subject}? ?\textit{hook}? ?\textit{observer}? ?\textit{cmdPrefix}?
\end{quote}

Called with no arguments, \textbf{hook bind} returns a list of the subjects with hooks to which observers are currently bound.

Called with one argument, a \textit{subject}, \textbf{hook bind} returns a list of the subject's hooks to which observers are currently bound.

Called with two arguments, a \textit{subject} and a \textit{hook}, \textbf{hook bind} returns a list of the observers which are currently bound to this \textit{subject} and \textit{hook}.

Called with three arguments, a \textit{subject}, a \textit{hook}, and an \textit{observer}, \textbf{hook bind} 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.

Called with four arguments, \textbf{hook bind} creates, updates, or deletes a binding. If \textit{cmdPrefix} is the empty string, \textbf{hook bind} deletes any existing binding for the \textit{subject}, \textit{hook}, and \textit{observer}; nothing is returned. Otherwise, \textit{cmdPrefix} must be a command prefix taking as many additional arguments as are documented for the \textit{subject} and \textit{hook}. The binding is added or updated, and the observer is returned.

If the \textit{observer} is the empty string, "", \textbf{hook} will create a new binding using an automatically generated observer name of the form \textbf{::hook::ob}\tiplangle{}\textit{number}\tiprangle{}. 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.

\subsubsection{Binds During Calls}

It is possible to call \textbf{hook bind} to create or delete a binding to a \textit{subject} and \textit{hook} while in an observer binding for that same \textit{subject} and \textit{hook}. The following rules determine what happens when \textbf{hook bind \$s \$h \$o \$binding} is called during the execution of \textbf{hook call \$s \$h}:
\begin{itemize}
\item{}
No binding is ever called after it is deleted.
\item{}
When a binding is called, the most recently given command prefix is always used.
\item{}
The set of observers whose bindings are to be called is determined when \textbf{hook call} begins to execute, and does not change thereafter, except that deleted bindings are not called.
\end{itemize}

In particular:
\begin{itemize}
\item{}
If \$o's binding to \$s and \$h is deleted, and \$o's binding has not yet been called during this execution of \textbf{hook call \$s \$h}, it will not be called. (Note that it might already have been called; and in all likelihood, it is probably deleting itself.)
\item{}
If \$o changes the command prefix that's bound to \$s and \$h, and if \$o's binding has not yet been called during this execution of \textbf{hook call \$s \$h}, the new binding will be called when the time comes. (But again, it is probably \$o's binding that is is making the change.)
\item{}
If a new observer is bound to \$s and \$h, its binding will not be called until the next invocation of \textbf{hook call \$s \$h}.
\end{itemize}

\subsubsection{Discussion}

\textbf{Optional Observers:} It has been suggested that the \textit{observer} argument should follow the \textit{cmdprefix} argument; if it is omitted, an observer name would be automatically generated. However, the \textit{observer} name is frequently used in practice, and is likely to be much shorter than the \textit{cmdprefix}, which might be quite long. As a general rule, short arguments following long ones tend to get lost visually; keeping the \textit{observer} before the \textit{cmdprefix} leads to more easily readable code.

\subsection{Call Subcommand}

\begin{quote}
\textbf{hook call} \textit{subject hook} ?\textit{args...}?
\end{quote}

This command is called when the named \textit{subject} wishes to call the named \textit{hook}. All relevant bindings are called with the specified arguments in the global namespace. Note that the bindings are called synchronously, before \textbf{hook call} returns; this allows the \textit{args} to include references to entities that will be cleaned up as soon as the hook has been called.

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.

Because the \textbf{hook} mechanism is intended to support loose coupling, it is presumed that the \textit{subject} has no knowledge of the observers, nor any expectation regarding return values. This has a number of implications:
\begin{itemize}
\item{}
\textbf{hook call} returns the empty string.
\item{}
Normal return values from observer bindings are ignored.
\item{}
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 \textbf{-errorcommand}.
\end{itemize}

If the \textbf{-errorcommand} configuration option has a non-empty value, its value will be invoked for all errors and other exceptional returns in observer bindings. See \textbf{hook configure}, below, for more information on configuration options.

Also, see below for possible extensions to \textbf{hook call}.

\subsection{Forget Subcommand}

\begin{quote}
\textbf{hook forget} \textit{object}
\end{quote}

This command deletes any existing bindings in which the named object appears as either the \textit{subject} or the \textit{observer}.

Bindings deleted by \textbf{hook forget} will never be called again. In particular,
\begin{itemize}
\item{}
If an observer is forgotten during a call to \textbf{hook call}, any uncalled binding it might have had to the relevant subject and hook will \textbf{not} be called subsequently.
\item{}
If a subject \$s is forgotten during a call to \textbf{hook call \$s \$h}, \textbf{hook call} will return as soon as the current binding returns. No further bindings will be called.
\end{itemize}

\subsection{Configuration Subcommands}

\begin{quote}
\textbf{hook cget} \textit{option}
\end{quote}

This command returns the value of one of the \textbf{hook} command's configuration options.

\begin{quote}
\textbf{hook configure} \textit{option value} ...
\end{quote}

This command sets the value of one or more of the \textbf{hook} command's configuration options:
\begin{description}
\item[-errorcommand]
If the value of this option is the empty string, "", 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 \{\textit{subject hook arglist observer}\}, the result string, and the return options dictionary. Given this information, the \textbf{-errorcommand} can choose to log the error, call \textbf{interp bgerror}, delete the errant binding (thus preventing the error from arising a second time) and so forth.
\item[-tracecommand]
The option's value should be a command prefix taking four arguments: a \textit{subject}, a \textit{hook}, a list of the hook's \textit{argument values}, and a list of \textit{objects} the hook. The command will be called for each hook that is called. This allows the application to trace hook execution for debugging purposes.
\end{description}

\section{Example}

The ::model module calls the \tiplangle{}Update\tiprangle{} hook in response to commands that change the model's data:
\begingroup\small\begin{verbatim}
   hook call ::model <Update>
\end{verbatim}
\endgroup

The .view megawidget displays the model state, and needs to know about model updates. Consequently, it subscribes to the ::model's \tiplangle{}Update\tiprangle{} hook.
\begingroup\small\begin{verbatim}
   hook bind ::model <Update> .view [list .view ModelUpdate]
\end{verbatim}
\endgroup

When the ::model calls the hook, the .view's ModelUpdate subcommand will be called.

Later the .view megawidget is destroyed. In its destructor, it tells the \textbf{hook} that it no longer exists:
\begingroup\small\begin{verbatim}
   hook forget .view
\end{verbatim}
\endgroup

All bindings involving .view are deleted.

\section{Possible Additions}

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:
\begin{itemize}
\item{}
Though reasonable additions, they are somewhat orthogonal to the functionality provided here.
\item{}
They are somewhat speculative, as they reflect patterns I've not actually used, whereas the functionality described above has been in use in real applications for the past five years.
\end{itemize}

Consequently, I'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.

On the other hand, they are genuinely interesting, so I want to mention them here.

\subsection{Asynchronous Dispatch}

The \textbf{hook call} 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 \textbf{hook call} in an \textbf{after} handler.

I've often considered adding a mode like this to our existing implementation, but have always thought better of it in the end.

\subsection{Accumulating Binding Return Values}

Two members of tcl-core have suggested that \textbf{hook call} 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'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.

I don't want to build up all of this return information in the usual case; if it isn't needed, there'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., \textbf{hook call ?options...? \$s \$h ...}

Given that \textbf{hook call} currently returns the empty string, this functionality can easily be added at a later time.

\section{Prototype Implementation}

A prototype implementation is available at [\url{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.

\section{Copyright}

This document has been placed in the public domain.

\section{Colophon}

\textit{TIP AutoGenerator --- written by Donal K. Fellows}
\end{document}
