GNU TeXmacsUser manualReferenceAboutEnglish
The Qt implementation

1.Overview

The Qt port lives in

src/src/Plugins/Qt

. A second copy with the same structure,

Plugins/Qt6

, is used by the configure build when the option --enable-qt-new is given (it is the default on Android); it adds for instance QTMMainTabWindow. The CMake build always uses Plugins/Qt. Both variants support Qt 5 and 6 through QT_VERSION tests. Changes to the widget layer must usually be made in both directories. The description below refers to Plugins/Qt.

Two other ports depend on this one. The Qtwk port (--with-gui=qtwk) compiles only the platform files of Plugins/Qt (renderer, fonts, pictures, pipes, sockets) and uses the Widkit widgets instead of the classes described here; since it also defines QTTEXMACS, code which must only apply to native Qt widgets tests QTWKTEXMACS as well. The Cocoa port (

Plugins/NS

) shares no code with this one, but copies its structure class by class (ns_widget_rep, ns_ui_element_rep with as_nsview and as_menuitem, ns_tm_widget_rep, ns_simple_widget_rep, ns_gui_rep), so that what follows mostly applies to it too. How the other ports differ is summarized in “Adding new widgets and porting to other toolkits”.

The files relevant for widgets are:

qt_widget.hpp/cpp

the base class qt_widget_rep and the implementation of all the constructors of

widget.hpp

;

qt_ui_element.hpp/cpp

the class qt_ui_element_rep, which implements most constructors;

qt_window_widget.hpp/cpp

windows (qt_window_widget_rep) and popups (qt_popup_widget_rep);

qt_tm_widget.hpp/cpp

the main TeXmacs widget (qt_tm_widget_rep) and its embedded variant (qt_tm_embedded_widget_rep);

qt_simple_widget.hpp/cpp

the canvas class qt_simple_widget_rep (alias simple_widget_rep), with the Qt widgets QTMWidget and QTMScrollView;

qt_menu.hpp/cpp

contextual menus (qt_menu_rep);

qt_dialogues.hpp/cpp, qt_chooser_widget.*, qt_color_picker_widget.*, qt_printer_widget.*

input fields and dialogs;

QTMMenuHelper.hpp/cpp

Qt helper classes: QTMCommand, QTMLazyMenu, QTMAction, QTMLineEdit, QTMRefreshWidget, QTMRefreshableWidget, …;

qt_gui.hpp/cpp, QTMGuiHelper.*

the qt_gui_rep singleton the_gui, the event queue and the functions of

gui.hpp

.

2.The base class qt_widget_rep

All widgets of the port derive from qt_widget_rep, itself derived from widget_rep. It holds

The casts concrete (widget) and abstract (qt_widget) convert between abstract and Qt widgets.

2.1.Four ways of becoming a Qt object

A TeXmacs widget can end up in very different places: in a menu bar, in a menu, in a toolbar, in a layout, in a window. Qt uses different classes for these, so qt_widget_rep has four virtual methods which create the corresponding Qt object on demand:

QAction* as_qaction ()
(for menus and toolbars)

Returns a new QAction, to be inserted in a QMenu, a menu bar or a toolbar. Buttons with submenus return an action carrying a lazy menu.

QWidget* as_qwidget (QWidget* parent)
(for windows and layouts)

Returns a new QWidget. The pointer qwid is set to it, but ownership goes to the caller (usually through the parent or a layout).

QLayoutItem* as_qlayoutitem (QWidget* parent)
(for layouts)

Returns a layout item: for lists a QHBoxLayout or QVBoxLayout filled recursively with the layout items of the children, for glue a QSpacerItem, and otherwise the result of as_qwidget wrapped in a QWidgetItem (the default).

QList<QAction*>* get_qactionlist ()
(for menu contents)

For menus and lists, returns the actions of all children (as_qaction of each), which is how a vertical_menu fills a QMenu and a horizontal_menu fills a menu bar or a toolbar.

The general rule is that each call builds new Qt objects and gives them to the caller. The only Qt objects owned by TeXmacs widgets are the windows: a qt_window_widget_rep owns its top-level QWidget, which in turn owns (as Qt parent) all widgets built for its contents.

2.2.Windows and popups

qt_widget_rep also has the virtual methods plain_window_widget, make_popup_widget, popup_window_widget and tooltip_window_widget, to which the global functions of the same name delegate. The default plain_window_widget creates a QTMPlainWindow, puts the layout item or widget of the contents into it and returns a new qt_window_widget_rep; subclasses such as qt_tm_widget_rep (which already is a window) or qt_inputs_list_widget_rep override it.

2.3.Default message handling

qt_widget_rep::send handles a few slots valid for any widget (SLOT_KEYBOARD_FOCUS, SLOT_KEYBOARD_FOCUS_ON, which looks for a child QWidget whose object name is the requested field, SLOT_NAME, SLOT_DESTROY, which is forwarded to the children) and ignores the others. query returns neutral values for common queries (identifier 0, default sizes, invisible bars) and fails otherwise; read, write and notify do nothing. When the debugging flag DEBUG_QT_WIDGETS is on (debug option qt-widgets), unhandled messages are logged, which is the easiest way to find out which slots a widget is expected to support.

2.4.Headless mode

When TeXmacs runs without a display (headless_mode), every constructor returns a headless_widget (), an instance of qt_headless_widget_rep which accepts all messages and never creates Qt objects. (The Vue port does it differently: it builds and lays out the real widgets in virtual windows, so that dialogs can be tested without a display.)

3.UI elements: widgets as descriptions

Most constructors do not create any Qt object. They create a qt_ui_element_rep, which merely stores its type and its arguments in a blackbox (the payload):

widget text_widget (string s, int style, color col, bool tsp) {
  if (headless_mode) return headless_widget ();
  qt_widget wid = qt_ui_element_rep::create (qt_widget_rep::text_widget,
                                             s, style, col, tsp);
  return abstract (wid);
}

The static templates qt_ui_element_rep::create pack one to six arguments into pair, triple, …, sextuple and call the constructor qt_ui_element_rep (types, blackbox). Container constructors also register their subwidgets with add_children, so that the whole description tree stays alive.

The actual Qt objects are created later, in the methods as_qaction, as_qwidget, as_qlayoutitem and get_qactionlist of qt_ui_element_rep, which are big switch statements on type. Each case unpacks the payload with the same tuple type that was used for packing, for example:

case text_widget:
{
  typedef quartet<string, int, color, bool> T;
  T x = open_box<T>(load);
  QLabel* w = new QLabel(parent_widget);
  w->setText (to_qstring (x.x1));
  …
  qt_apply_tm_style (w, x.x2, x.x3);
  qwid = w;
}

The static function get_payload gives access to the payload of another UI element; it is used when the rendering of a widget depends on its child. For instance a menu_button whose label is an xpm_widget becomes a QToolButton with an icon, whereas one with a text_widget becomes a QPushButton.

This lazy design has several advantages. The same description can be materialized several times and in different forms (a menu may appear both in the menu bar and in a toolbar); building a menu item that is never shown costs almost nothing; and dynamic menus are cheap, because the description is rebuilt by Scheme but Qt objects are only created for what is displayed. Accordingly, the results must not be cached in general: the comment “DON'T try to always cache the action returned: this breaks dynamic menus!” in as_qaction is to be taken seriously. The exception is get_qactionlist, which caches its list in cachedActionList, since menu bars and toolbars take the actions from it.

A few constructors do not use UI elements because their widgets have state or a complex behaviour: input_text_widget (qt_input_text_widget_rep), inputs_list_widget (qt_inputs_list_widget_rep with qt_field_widget_rep fields), file_chooser_widget (qt_chooser_widget_rep), color_picker_widget (qt_color_picker_widget_rep), printer_widget (qt_printer_widget_rep), wrapped_widget (qt_wrapped_widget_rep), the colored glue_widget (qt_glue_widget_rep) and texmacs_widget. empty_widget, ink_widget and wait_widget are not implemented, and extend_widget returns its first argument.

4.Menus

Lazy submenus.
A pulldown_button or pullright_button stores its label and its promise<widget>. Its as_qaction creates the action of the label and attaches a QTMLazyMenu to it. This QMenu subclass connects its signal aboutToShow to its slot force, which evaluates the promise, asks the resulting widget for its get_qactionlist () and moves these actions into itself:
void
QTMLazyMenu::force () {
BEGIN_SLOT
  QList<QAction*>* list = concrete (promise_widget())->get_qactionlist();
  transferActions (list);
END_SLOT
}

Hence the Scheme closure behind the promise is called each time the menu opens. as_qwidget does the same for buttons inside dialogs and toolbars, using a QToolButton or QPushButton with the lazy menu.

Menu entries.
For a menu_button, as_qaction returns the action of the label and connects its triggered signal to a QTMCommand wrapping the TeXmacs command. If the entry has a keyboard shortcut, the shortcut is installed on the action (so that it is displayed in the menu), and the command is replaced by a qt_key_command_rep, which simulates the key press in the editor (via the_gui->process_keypress), so that the keyboard and the menu always do the same thing; QTMWidget intercepts the shortcut events so that key presses still reach the editor. (When the preference use experimental keyboard patches is on, the shortcut is only appended to the text of the action and the original command is kept.) The check mark prefix and WIDGET_STYLE_PRESSED make the action checkable, and WIDGET_STYLE_INERT disables it.
The menu bar.
The main menu (a horizontal_menu of pulldown buttons) is installed by qt_tm_widget_rep::install_main_menu, which takes the menus of the actions of get_qactionlist () and adds them to the QMenuBar (or to a QTMToolbar when the native menu bar is not used). Since Qt may not replace a menu bar while one of its menus is open, a new menu arriving during menu interaction (menu_count > 0) is postponed: the widget is appended to waiting_widgets and installed by QTMGuiHelper::doPopWaitingWidgets when the menu closes.
Contextual menus.
qt_ui_element_rep::make_popup_widget turns a vertical_menu into a qt_menu_rep, which owns a QAction with a QMenu and shows it when it receives SLOT_VISIBILITY or SLOT_MOUSE_GRAB. Other widgets are wrapped in a qt_popup_widget_rep.

5.Commands and the event queue

QTMCommand is a QObject wrapping a command; its slot apply does not execute the command but queues it:

void
QTMCommand::apply()  {
BEGIN_SLOT
  if (!is_nil (cmd)) {
    the_gui->process_command (cmd);
    …

All inputs of the TeXmacs kernel go through the queue of qt_gui_rep: process_keypress, process_keyboard_focus, process_mouse and process_resize (called by QTMWidget) and process_command append queued_events tagged by qp_type (QP_KEYPRESS, QP_MOUSE, QP_COMMAND, QP_COMMAND_ARGS, …) and call need_update, which starts a zero-delay timer. The timer calls qt_gui_rep::update, which:

  1. queues the pending delayed commands (exec_delayed of Scheme) when their time has come;

  2. processes the queued events with process_queued_events, dispatching them to the handle_* methods of the target qt_simple_widget_rep or applying the commands;

  3. calls the interpose handler of the server, which lets the editors apply their changes and update the menus, and repaints all canvases with qt_simple_widget_rep::repaint_all; when only ordinary key presses were processed in this pass, these two steps are postponed by a few milliseconds, so that fast typing is handled in batches;

  4. restarts the timer, so that the interpose handler also runs periodically when nothing happens.

All Qt slots of the port are enclosed in the macros BEGIN_SLOT and END_SLOT, which catch TeXmacs exceptions so that they do not propagate through Qt.

Input widgets need to pass values to their commands. Instead of subclassing QTMCommand, the port wraps the user command in small command classes which read the state of the Qt widget when applied: qt_toggle_command_rep (checkbox state), qt_enum_command_rep (current text of a combo box), qt_choice_command_rep (selected items of a list, as a Scheme list), … For example:

void apply () { if (qwid) cmd (list_object (object (qwid->isChecked()))); }

6.Windows

Plain windows.
qt_window_widget_rep wraps a top-level QWidget (a QTMPlainWindow for dialogs). It stores a pointer to itself in the Qt property texmacs_window_widget, so that widget_from_qwidget can find the TeXmacs window of any Qt widget, assigns the identifier returned for SLOT_IDENTIFIER (and increments the global window count nr_windows, which ends the application when it drops to zero), and connects the closed () signal emitted by closeEvent to the quit command. It implements the window slots (visibility, title, position, size, full screen) and forwards SLOT_REFRESH (see below). If the contents have no resizable children, the window gets a fixed size.
The main window.
qt_tm_widget_rep, the result of texmacs_widget (mask, quit) for a non-zero mask, is a window widget around a QTMWindow (a QMainWindow). Its constructor decodes the mask into the array visibility and creates the Qt furniture: tool bars (mainToolBar, modeToolBar, focusToolBar, userToolBar, and menuToolBar for the non-native menu bar), dock widgets for the tools (sideTools, leftTools, bottomTools, extraTools), the footer labels leftLabel and rightLabel and an interactive prompt. Its message handlers map the slots of the main widget to this furniture:

With mask 0, texmacs_widget returns a qt_tm_embedded_widget_rep instead: no window and no bars, just the canvas, for editors embedded in dialogs.

7.Canvases

qt_simple_widget_rep is the base class of the editor and of box widgets. Its as_qwidget creates a QTMWidget (derived from QTMScrollView, a QAbstractScrollArea), which translates Qt events into calls of the_gui->process_keypress, process_mouse, … and paints from a backing pixmap. Painting is driven by TeXmacs: SLOT_INVALIDATE records invalid rectangles, and repaint_all (called from qt_gui_rep::update) calls handle_repaint on the invalid regions of all canvases with a renderer drawing into the backing store. Since the QTMWidget may be created after the kernel started to send messages (for instance extents or scroll positions), the last value sent to each slot is remembered in sent_slots and replayed with reapply_sent_slots when the Qt widget is created. The renderer itself is described in “The renderer interface”.

8.Refresh widgets

refresh_widget and refreshable_widget are UI elements whose as_qwidget creates a QTMRefreshWidget or a QTMRefreshableWidget. Both connect to the signal tmSlotRefresh (string) of the global QTMGuiHelper, compute their contents a first time with the kind "init", and recompute them in the slot doRefresh:

In both cases the old QWidget is scheduled for deletion and replaced by as_qwidget of the new contents; if the enclosing window had a fixed size, it is adjusted. The signal is emitted by QTMGuiHelper::emitTmSlotRefresh, which is called when a qt_window_widget_rep receives SLOT_REFRESH. Consequently a refresh sent to any window reaches all refresh widgets; the kind argument is what limits the work. (Cocoa does the same with the notification TMRefresh; Vue obtains the same effect lazily, see “Windows, the main TeXmacs widget and the flow of events”.)

When the interface language changes, gui_refresh calls qt_gui_rep::refresh_language, which makes QTMGuiHelper emit its refresh signal; QTMActions listen to it to retranslate their text.

9.Input fields and dialogs

qt_input_text_widget_rep creates a QTMLineEdit, with a QCompleter offering the proposals (or file names); the helper QTMInputTextWidgetHelper calls the command with the text when the user validates or leaves the field. The type string of the field becomes the Qt object name of the line edit, which is what SLOT_KEYBOARD_FOCUS_ON looks for. It may have the form name#serial:type, which QTMLineEdit::set_type splits; the type selects special behaviour (password, file names, search and replace fields) and fields whose serial starts with form- are committed continuously.

qt_inputs_list_widget_rep implements the multi-field dialogs of tm_frame_rep::interactive; its fields are qt_field_widget_reps, returned by SLOT_FORM_FIELD. For simple questions it may use a native message box. The file chooser, the color picker and the print dialog are implemented with the corresponding Qt dialogs (QTMFileDialog, …).

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License".