The Cancellable Work Pattern is a core design pattern in Terminal.Gui, used to structure workflows that can be executed in a default manner, modified by external code or subclasses, or cancelled entirely. This pattern is prevalent across various components of Terminal.Gui, including the View class for rendering, keyboard input, and command execution, as well as application-level input handling and property changes. Unlike traditional inheritance-based approaches that rely on overriding virtual methods (which often require subclasses to understand base class implementation details), the Cancellable Work Pattern prioritizes events for loose coupling, supplemented by optional virtual methods for flexibility.
This deep dive defines the Cancellable Work Pattern, outlines its components and goals, and illustrates its implementation through examples in View.Draw, View.Keyboard, View.Command, Application.Keyboard, and OrientationHelper.
The Cancellable Work Pattern is a design pattern for executing a structured workflow with one or more phases, where each phase can:
The pattern uses events as the primary mechanism for notification and customization, supplemented by virtual methods for subclassing when needed. It is a specialization of the Observer Pattern, extended with structured workflows, explicit cancellation mechanisms, and context-aware notifications. It also incorporates elements of the Template Method Pattern (via virtual methods) and Pipeline Pattern (via sequential phases).
The Cancellable Work Pattern is designed to achieve the following:
The Cancellable Work Pattern consists of the following components:
View.Draw), linear (e.g., key processing in View.Keyboard), per-unit (e.g., command execution in View.Command), or event-driven (e.g., key handling in Application.Keyboard, property changes in OrientationHelper).DrawingText, KeyDown, Activating, OrientationChanging) and virtual methods (e.g., OnDrawingText, OnKeyDown, OnActivating, OnOrientationChanging) raised at each phase to notify observers.Cancel/Handled properties in event arguments or returning bool from virtual methods.DrawContext (drawing), Key (keyboard), ICommandContext (commands), or CancelEventArgs<Orientation> (orientation).DrawText (drawing), InvokeCommands (keyboard and application-level), RaiseActivating (commands), or updating a property (OrientationHelper).The Cancellable Work Pattern is implemented consistently across several key areas of Terminal.Gui’s v2_develop branch. Below are five primary examples, each illustrating the pattern in a different domain: rendering, keyboard input at the view level, command execution, application-level keyboard input, and property changes.
The View.Draw method orchestrates the rendering of a view, including its adornments (margin, border, padding), viewport, text, content, subviews, and line canvas. It is a multi-phase workflow where each phase can be customized or cancelled.
DoDrawTextThe DoDrawText method, responsible for drawing a view’s text, exemplifies the pattern:
private void DoDrawText(DrawContext? context = null)
{
if (OnDrawingText(context)) // Virtual method for subclasses
{
return; // Cancel if true
}
if (OnDrawingText()) // Legacy virtual method
{
return; // Cancel if true
}
var dev = new DrawEventArgs(Viewport, Rectangle.Empty, context);
DrawingText?.Invoke(this, dev); // Notify observers
if (dev.Cancel) // Check for cancellation
{
return;
}
DrawText(context); // Default behavior
}
Draw workflow.OnDrawingText (virtual), DrawingText (event).OnDrawingText returning true or dev.Cancel = true.DrawContext and DrawEventArgs provide rendering details.DrawText renders the view’s text.The View.ProcessKeyDown method processes keyboard input for a view, mapping keys to commands or handling them directly. It is a linear workflow with a single phase per key event.
ProcessKeyDownpublic virtual bool ProcessKeyDown(Key key)
{
if (OnKeyDown(key)) // Virtual method
{
return true; // Cancel if true
}
KeyDown?.Invoke(this, key); // Notify observers
if (key.Handled) // Check for cancellation
{
return true;
}
bool handled = InvokeCommands(key, KeyBindingScope.HotKey | KeyBindingScope.Focused); // Default behavior
return handled;
}
OnKeyDown (virtual), KeyDown (event).OnKeyDown returning true or key.Handled = true.Key provides key details and bindings.InvokeCommands maps keys to commands (e.g., Command.Accept).TextField capturing input) or cancel default command execution.The View.Command APIs execute commands like Command.Activate and Command.Accept, used for state changes (e.g., CheckBox toggling) and action confirmation (e.g., dialog submission). It is a per-unit workflow, with one phase per command.
RaiseActivatingThe RaiseActivating method handles Command.Activate:
protected bool? RaiseActivating(ICommandContext? ctx)
{
CommandEventArgs args = new() { Context = ctx };
if (OnActivating(args) || args.Handled)
{
return true;
}
Activating?.Invoke(this, args);
return Activating is null ? null : args.Handled;
}
Command.Activate.OnActivating (virtual), Activating (event).OnActivating returning true or args.Handled = true.ICommandContext provides Command, Source, and Binding.SetFocus for Command.Activate (in SetupCommands).CheckBox toggling) or cancellation (e.g., preventing focus in MenuItemv2).Command.Activate is local, limiting hierarchical coordination (e.g., MenuBarv2 popovers). A proposed PropagatedCommands property addresses this, as detailed in the appendix.The Application.OnKeyDown method processes application-wide keyboard input, raising events for global key handling. It is an event-driven workflow, with a single phase per key event.
OnKeyDownpublic static bool OnKeyDown(Key key)
{
if (KeyDown is null)
{
return false;
}
KeyDown?.Invoke(null, key); // Notify observers
return key.Handled; // Check for cancellation
}
KeyDown (event, no virtual method).key.Handled = true.Key provides key details.Top view processing).Ctrl+Q to quit) or cancellation of default view handling.The OrientationHelper class manages orientation changes (e.g., in StackPanel), raising events for property updates. It is an event-driven workflow, with a single phase per change.
Orientation Setterpublic Orientation Orientation
{
get => _orientation;
set
{
if (_orientation == value)
{
return;
}
var oldOrientation = _orientation;
var args = new CancelEventArgs<Orientation>(_orientation, ref value);
if (OnOrientationChanging(args))
{
return; // Cancel if true
}
OrientationChanging?.Invoke(this, args);
if (args.Cancel)
{
return;
}
_orientation = value;
var changedArgs = new EventArgs<Orientation>(oldOrientation, _orientation);
OnOrientationChanged(changedArgs);
OrientationChanged?.Invoke(this, changedArgs);
}
}
OnOrientationChanging (virtual), OrientationChanging (event), OnOrientationChanged, OrientationChanged (post-event).OnOrientationChanging returning true or args.Cancel = true.CancelEventArgs<Orientation> provides old and new values._orientation and notifies via OrientationChanged.The Cancellable Work Pattern in View.Command currently supports local Command.Activate and propagating Command.Accept. To address hierarchical coordination needs (e.g., MenuBarv2 popovers, Dialog closing), a PropagatedCommands property is proposed (Issue #4050):
IReadOnlyList<Command> PropagatedCommands to View, defaulting to [Command.Accept]. Raise* methods propagate if the command is in SuperView?.PropagatedCommands and args.Handled is false.Example:
public IReadOnlyList<Command> PropagatedCommands { get; set; } = new List<Command> { Command.Accept };
protected bool? RaiseActivating(ICommandContext? ctx)
{
CommandEventArgs args = new() { Context = ctx };
if (OnActivating(args) || args.Handled)
{
return true;
}
Activating?.Invoke(this, args);
if (!args.Handled && SuperView?.PropagatedCommands.Contains(Command.Activate) == true)
{
return SuperView.InvokeCommand(Command.Activate, ctx);
}
return Activating is null ? null : args.Handled;
}
Impact: Enables Command.Activate propagation for MenuBarv2 while preserving Command.Accept propagation, maintaining decoupling and avoiding noise from irrelevant commands.
Conflation in FlagSelector:
CheckBox.Activating triggers Accepting, conflating state change and confirmation.Recommendation: Refactor to separate Activating and Accepting:
checkbox.Activating += (sender, args) =>
{
if (RaiseActivating(args.Context) is true)
{
args.Handled = true;
}
};
Propagation Limitations:
Command.Activate restricts MenuBarv2 coordination; Command.Accept uses hacks (#3925).PropagatedCommands to enable targeted propagation, as proposed.Documentation Gaps:
Handled semantics are not fully documented.View.Draw, View.Keyboard, View.Command, Application.Keyboard, and OrientationHelper.Complexity in Multi-Phase Workflows:
View.Draw’s multi-phase workflow can be complex for developers to customize.The Cancellable Work Pattern is a foundational design in Terminal.Gui, enabling extensible, cancellable, and decoupled workflows across rendering, input handling, command execution, and property changes. Its implementation in View.Draw, View.Keyboard, View.Command, Application.Keyboard, and OrientationHelper supports diverse use cases, from Menuv2’s hierarchical menus to CheckBox’s state toggling. The proposed PropagatedCommands property enhances the pattern’s applicability in View.Command, addressing propagation needs while maintaining its core principles. By refining implementation flaws (e.g., FlagSelector) and improving documentation, Terminal.Gui can further leverage this pattern for robust, flexible UI interactions.