Общий слой интерфейса
Назначение и место в пакете
Каталог src/gui_common — общий для всех программ Qt6-версии код интерфейса, который
не относится к конкретной программе: виджеты-хозяева, в которых живут виды
Windows-версии, оформление, перевод интерфейса, окно «О программе», окно выбора цвета,
печать, список последних файлов, положение окон и несколько средств надёжности.
Подкаталог gui_common/compute (выбор устройства расчёта, OpenCL) описан на странице
расчёт на видеокарте.
Слой стоит между слоем совместимости (классы CDC, CScrollView,
CDialog …) и оболочками программ apps/*:
apps/* (главные окна, меню, панели)
│ создают MfcViewWidget, вызывают theme::apply(), tmcprint::printView(), …
▼
gui_common ── tmc_ui_base (theme, aboutbox) ── tmc_i18n (перевод)
│ реализует MfcQtHost, переносит CCmdUI в QAction
▼
compat (CDC, CScrollView, CDialog, карта сообщений)
Все функции слоя работают в потоке интерфейса, если не сказано иное.
Состав и библиотеки
| Библиотека CMake | Файлы | Кто использует |
|---|---|---|
tmc_i18n |
i18n/tmci18n.* + ресурс resources/i18n/ui_strings.tsv |
все программы, включая FieldView и TPL Designer |
tmc_ui_base |
theme.*, aboutbox.* + ресурсы значков (resources/icons) и шрифтов (resources/fonts) |
все программы; не зависит от слоя совместимости, поэтому его берёт и TPL Designer |
tmc_gui_common |
файлы compat/mfc_*.cpp + colorpicker, mfcviewwidget, mfcglwidget, printsupport, recentfiles, commandupdate, dialogshot, windowplacement, mousewatchdog |
программы, использующие классы MFC (вьюверы, оболочки ядер, FieldView) |
| только заголовки | dllsafety.h, pathcheck.h |
оболочки программ |
| Файл | Роль |
|---|---|
theme.h/.cpp |
палитра, таблица стилей, шрифты, значки программ и команд |
aboutbox.h/.cpp |
единое окно «О программе», хранилище оформителя окон слоя совместимости |
colorpicker.h/.cpp |
окно выбора цвета |
commandupdate.h/.cpp |
перенос ON_UPDATE_COMMAND_UI в QAction |
mfcviewwidget.h/.cpp |
виджет-хозяин вида (QAbstractScrollArea) |
mfcglwidget.h/.cpp |
виджет-хозяин вида OpenGL (QOpenGLWidget) |
printsupport.h/.cpp |
печать, предпросмотр, печать в PDF |
recentfiles.h/.cpp |
список последних файлов |
windowplacement.h/.cpp |
положение окна между запусками |
dialogshot.h/.cpp |
снимки диалогов для проверки внешнего вида (средство разработки) |
mousewatchdog.h/.cpp |
сторож «залипшего» захвата мыши |
dllsafety.h |
безопасный поиск DLL |
pathcheck.h |
проверка пути на кодовую страницу Windows |
i18n/tmci18n.h/.cpp |
перевод интерфейса ru/en |
Оформление
theme::apply() вызывается оболочкой программы после создания QApplication (перед
ним — theme::setProgram("tmcgrout") и т. п.). Она:
- ставит числовую локаль C (
setlocale(LC_NUMERIC, "C")): числа в файлах TMC пишутся и читаются с точкой;QApplicationберёт локаль из окружения, и в русской локалиsscanf("%lg")спотыкался бы на точке, аprintf("%g")писал бы запятые; - регистрирует шрифты Inter и JetBrains Mono из ресурсов
:/tmcfonts/; - ставит значок приложения (
appIcon()); - подключает оформитель окна «О программе» (
tmcabout::install) и перевод интерфейса (tmci18n::install); - задаёт палитру Qt и таблицу стилей (
styleSheet()), шрифт подсказок и фильтр, показывающий простые подсказки одной строкой (<nobr>) уже переведёнными.
Палитра (функции theme::bg() … theme::warn()):
| Роль | Цвет | Роль | Цвет |
|---|---|---|---|
фон bg |
#0a0e16 |
акцент accent |
#34e3c4 |
панели surface |
#131a28 |
ошибка danger |
#ff6b6b |
рамки line |
#243049 |
успех ok |
#5ce08a |
текст text |
#e7eef7 |
предупреждение warn |
#e3b341 |
приглушённый textDim |
#9fb0c8 |
недоступный textMute |
#6c7d97 |
Таблица стилей учитывает происхождение диалогов: внутри QDialog шрифт 8 пунктов и
уменьшенные отступы (координаты из .rc рассчитаны на «MS Sans Serif 8»), рамки групп
прозрачные (в .rc рамка записана после своих элементов и иначе закрыла бы их),
значки флажков и переключателей уменьшены. Стандартные окна Qt (QDialogButtonBox,
QMessageBox) получают обычные размеры кнопок.
Значки команд (commandIcon(id)): сначала новый набор
:/tmcicons/toolbar/<программа>/<ID>.svg; у переключателей — пара <ID>_off.svg
(красный кружок) и <ID>_on.svg (зелёный), которые кладутся в состояния Off/On, и
отмеченное действие само показывает зелёный. Если нового рисунка нет — значок из
ресурсов Windows-версии :/icons/<ID>_dark.png или <ID>.png.
commandIconState(id, on) возвращает один из пары (кнопки запуска вьюверов: зелёный —
вьювер запущен). programRunning(exe) проверяет список процессов Windows не чаще раза в
секунду (вне Windows — всегда false).
fitToScreen(w) ограничивает окно 95 % ширины и 88 % высоты экрана и ставит его по
центру. Перекраску цветов внутри графиков выполняет не тема, а CDC слоя
совместимости (цвета темы).
Окно «О программе»
Одно окно на все программы пакета (tmcabout::show): значок и название программы,
описание на языке интерфейса, версия пакета 5.1, год, система и архитектура сборки,
автор и кнопки-ссылки на его профили, ссылки на сайт и руководство пользователя, кнопка
OK. Какая программа запущена, окно узнаёт из theme::program(); если программа не
задана, название берётся из переданных строк. Строки описания Copyright… и ©
отбрасываются, остальные строки, переданные программой (например, «Model : H»),
показываются под описанием.
Руководство пользователя ищется рядом с программой и в типовых каталогах поставки
(../share/tmc-suite, ../Resources, ../doc, ..): файл
TMC_Suite_User_Manual.pdf или самый новый по имени TMC_Suite_*.pdf (у TPL Designer —
своё руководство). Не найдено — кнопка открывает руководство на сайте.
Окно IDD_ABOUTBOX из ресурсов. Перенесённый код программ открывает собственный
диалог «О программе» через CDialog::DoModal. Чтобы и он выглядел единообразно, слой
совместимости после построения каждого окна вызывает оформитель
tmc_dialog_decorator(). tmcabout::install() регистрирует оформитель
tmcabout::decorate, который для окна с objectName() == "IDD_ABOUTBOX" прячет
разметку из ресурсов (код окна может к ней обращаться) и ставит поверх единое
содержимое; остальные окна не трогает.
Хранилище оформителя (tmc_set_dialog_decorator / tmc_dialog_decorator) объявлено в
compat/include/mfc_dialog.h, но определено в aboutbox.cpp, т. е. в библиотеке
tmc_ui_base: так окно «О программе» не тянет за собой слой совместимости, и его может
использовать TPL Designer, у которого слоя MFC нет. Слой совместимости оформитель
только вызывает.
aboutText() возвращает то же содержимое HTML-текстом — для мест, где нужен текст, а
не окно.
Окно выбора цвета
tmcPickColor(parent, initial, &result, title) открывает TmcColorPickerDialog и
возвращает true по OK. В Windows-сборке его вызывает CColorDialog::DoModal слоя
совместимости — так все окна настройки цветов линий и графиков получают это окно
вместо стандартного QColorDialog.
Элементы окна: область «насыщенность по горизонтали / яркость по вертикали», полоса
оттенка, образцы «было/стало» (щелчок по «было» возвращает исходный цвет), поле HEX
(#RRGGBB или #RGB), движки и числовые поля R, G, B (0…255), ряды образцов «Палитра
проекта», «Цвета графиков» (классические цвета вьюверов Windows-версии) и «Недавние»,
пипетка (взять цвет с любого места экрана; Esc — отмена, Enter или левая кнопка —
взять).
Цвет хранится одновременно в двух видах: RGB (m_color, то, что получит программа) и
HSV (m_h, m_s, m_v в диапазоне 0…1, то, что показывают область и полоса). При
переводе RGB → HSV оттенок не обновляется, если цвет серый () или чёрный
(), а насыщенность — если цвет чёрный: иначе ручка оттенка прыгала бы в ноль при
каждом проходе через серый. Переход к образцу анимируется (220 мс). Выбранный цвет
всегда непрозрачный.
Недавние цвета (до 12, последний выбранный первым, без повторов) хранятся в INI-файле
TMC_Suite_Qt/ColorPicker.ini профиля пользователя (Windows — %APPDATA%), ключ
Recent/Colors, одной строкой шестнадцатеричных кодов без # через пробел (# в INI
может начинать комментарий). Цвет добавляется по OK.
Обновление состояния команд
В MFC каркас перед показом меню опрашивал обработчики ON_UPDATE_COMMAND_UI: доступен
ли пункт (pCmdUI->Enable) и отмечен ли (SetCheck, SetRadio). Здесь это делает
tmccmd::updateActions(actions, target):
- строит карту сообщений цели (
target->TmcBuildMessageMap, вид активного окна или документ); если обработчиков обновления нет — выходит; - для каждой пары «номер команды →
QAction» создаётCCmdUIи вызывает обработчик; - переносит в действие только то, что обработчик задал:
Enable→setEnabled,SetCheck/SetRadio→ действие становится отмечаемым иsetChecked(Check() != 0)(неопределённое состояние 2 считается отмеченным). Пункт без обработчика остаётся прежним — как в MFC.
Оболочки вызывают функцию перед показом меню (QMenu::aboutToShow) и после каждой
выполненной команды. updateAction делает то же для одной команды.
Виджет-хозяин вида
MfcViewWidget (QAbstractScrollArea) реализует интерфейс MfcQtHost слоя
совместимости для вида CScrollView: вид определяет, что рисовать и как
реагировать (код Windows-версии), виджет — где рисовать и откуда берутся события.
| Событие Qt | Действие |
|---|---|
paintEvent |
заливка фоном, CDC над QPainter области просмотра, OnPrepareDC, OnDraw |
| нажатие левой / правой кнопки | OnLButtonDown / OnRButtonDown |
| отпускание левой кнопки | снятие «забытого» захвата мыши, OnLButtonUp |
| двойной щелчок левой | OnLButtonDblClk |
| движение мыши | OnMouseMove (слежение включено и без нажатой кнопки) |
| таймер Qt | OnTimer(номер MFC) |
Флаги кнопок и клавиш переводятся в MK_LBUTTON, MK_RBUTTON, MK_MBUTTON,
MK_SHIFT, MK_CONTROL; точка — в пиксели содержимого (с учётом прокрутки).
Вызовы вида:
hostInvalidateперерисовывает всё окно (логическая область не пересчитывается);hostUpdateWindow— немедленно (repaint), но во времяOnDrawи из чужого потока — отложенно (updateв очереди главного потока);hostSetScrollSizesзадаёт диапазоны полос: максимум = полный размер − размер области просмотра; шаг страницы по умолчанию — размер области, строки — 20 пикселей;hostMessageBoxпоказывает информационное окно и всегда возвращает 1 (IDOK); из потока расчёта — асинхронно;hostSetStatusTextпосылает сигналstatusTextChanged(pane, text), но не чаще раза в 50 мс (ядро сообщает о ходе работы на каждом такте); защищённыйhostSetStatusTextImmediate— без ограничения (в коде пакета не вызывается);hostSetCaptureнамеренно ничего не делает (подводные камни).
setDocumentBackground(color) задаёт фон: в Windows-сборке белый и чёрный (значения
Windows-версии по умолчанию) заменяются фоном темы, серый 192 — цветом панелей, другой
цвет, выбранный пользователем, ставится как есть.
Виджет-хозяин вида OpenGL
MfcGLWidget (QOpenGLWidget) — хозяин для вида, рисующего сцену через OpenGL
(FieldView из apps/fieldview, сборка вне Windows; в Windows-сборке библиотека его
содержит, но поле показывает apps/fieldview_rhi).
setupSurfaceFormat()(вызвать до создания виджетов) ставит формат по умолчанию: совместимый профиль OpenGL 2.1, глубина 24 бита, двойная буферизация — отрисовка Windows-версии написана в старом стиле (glBegin/glEnd, матрицы, без шейдеров);initializeGL→OnInitialUpdate(контекст уже создан и текущий),resizeGL→OnSize(0, w, h),paintGL→OnDrawс контекстом без холста в режиме отложенного текста; надписиTextOutзатем выводятсяQPainterповерх кадра;- прокрутки нет,
hostSetStatusTextпосылает сигнал сразу.
Печать
Печать идёт тем же кодом, что и рисование на экране: CDC подключается к
QPrinter, режим MM_HIMETRIC, начало координат — левый верхний угол листа, и вид
вызывает свой OnDraw. Масштаб получается сам: MM_HIMETRIC считает пиксели из
разрешения устройства, а у принтера оно своё.
Вид OpenGL контекстом устройства не пользуется — он рисует прямо в кадровый буфер, и
лист вышел бы пустым. Для него на бумагу переносится снимок кадра
(grabFramebuffer), вписанный по центру области печати с сохранением пропорций.
| Функция | Что делает |
|---|---|
tmcprint::printView |
диалог печати Qt, затем одна страница |
tmcprint::previewView |
окно предварительного просмотра |
tmcprint::printViewToPdf |
печать в файл PDF без диалога (для проверки печати без участия человека) |
tmcprint::pageSetup |
настройка страницы |
Принтер общий на всё время работы программы: выбранные параметры сохраняются между вызовами.
Последние файлы
TmcRecentFiles ведёт список последних файлов меню «File» (по умолчанию 4) и хранит
его в настройках программы (CWinApp, настройки) — раздел
Recent File List, ключи File1…FileN, как у MFC. Путь записывается с пометкой
utf8: в UTF-8: в кодовой странице Windows буквы вне неё терялись бы; старые записи
без пометки читаются в локальной кодовой странице. Пути абсолютные; один и тот же файл,
записанный в разном регистре или с разными разделителями, считается одной записью
(в Windows сравнение без учёта регистра).
attachToMenu(menu, before) вставляет пункты «&1 имя», «&2 имя» … перед пунктом
before; при пустом списке — недоступный пункт «Recent File», чтобы меню не «прыгало».
Выбор пункта посылает сигнал fileRequested(path); оболочка открывает файл и вызывает
add(path).
Положение окон
tmcui::keepPlacement(window, key) ставит окну сторожа: при первом показе окно
восстанавливается по сохранённому значению, при закрытии значение записывается. Значение
— строка «x y ширина высота» (пиксели) в разделе Window настроек программы. При
восстановлении окно ограничивается экраном, на котором его оставили (если такого экрана
больше нет — основным). Нет сохранённого значения или оно меньше 100x100 — окно ставится
по центру экрана (centerOnScreen). Переменная окружения TMC_NO_PLACEMENT отключает
восстановление (средства проверки задают размер сами).
Снимки диалогов
Средство разработки, в работе программы не используется. tmcshot::grabDialog(idd,
file) строит диалог по номеру ресурса тем же путём, что и при работе (TmcBuildIn +
оформитель), заполняет пустые поля пробным текстом, показывает окно и сохраняет снимок.
Заодно проверяет элементы и пишет в stderr строки ПРОБЛЕМА …:
- центр элемента закрыт другим элементом (до него нельзя дотянуться мышью);
- кнопка с текстом ниже 28 пикселей;
- подпись кнопки, флажка или переключателя не помещается.
grabAllDialogs(dir) снимает все диалоги, зарегистрированные программой, в файлы
dialog_<номер>.png.
Сторож захвата мыши
Вложенное окно MDI само захватывает мышь при перетаскивании. Если отпускание кнопки до
него не дошло, захват остаётся, и все щелчки уходят этому окну — меню и панели
перестают отвечать. tmcui::installMouseGrabWatchdog(owner) раз в 500 мс проверяет:
захват есть, а кнопки мыши отпущены — захват снимается. Те же проверки выполняют
обработчики отпускания мыши MfcViewWidget и MfcGLWidget.
Проверка пути
Перенесённый код открывает файлы ANSI-функциями (fopen), поэтому путь переводится в
кодовую страницу Windows. Буквы вне неё Windows молча заменяет похожими или ?, и
программа открыла бы файл из другой папки или не нашла бы его.
tmcui::pathFitsCodePage(path) проверяет, что путь переводится туда и обратно без
потерь; оболочки такой путь не передают расчётному коду, а сообщают пользователю.
Безопасный поиск DLL
tmcui::secureDllSearch() вызывает
SetDefaultDllDirectories(LOAD_LIBRARY_SEARCH_DEFAULT_DIRS): DLL, загружаемые во время
работы (например, OpenCL.dll), ищутся только в папке программы и в System32, а не в
текущей папке — у ядер ею становится папка задания, и подложенная туда DLL с именем
системной загрузилась бы в программу. На библиотеки, которые программа импортирует при
запуске (Qt6*.dll), это не влияет. Вне Windows функция пустая.
Перевод интерфейса
Язык интерфейса — русский или английский. Выбор общий для всех программ пакета и
хранится в TMC_Suite_Qt/Common.ini (Windows — %APPDATA%), [UI] Language = system |
ru | en. system — русский, если язык системы русский, иначе английский. Меню выбора
добавляет tmci18n::addLanguageMenu(parent) (пункты меню сами не переводятся).
Словарь. resources/i18n/ui_strings.tsv — строки «английский<табуляция>русский»;
\n и \t в тексте означают перевод строки и табуляцию; строки с # — комментарии.
После строки #TEMPLATES идут шаблоны со вставками. Словарь работает в обе стороны
(в каждую сторону побеждает первая пара для данного текста); к нему добавлены переводы
кнопок стандартных окон Qt. Для самих стандартных окон Qt (выбор файла, шрифта)
загружается перевод Qt qtbase_ru.qm — из каталога translations рядом с программой
или из установки Qt.
Поиск перевода (translate), по порядку:
- отступы по краям строки отделяются и сохраняются;
- точное совпадение;
- совпадение без «&» (подчёркнутых букв;
&&— настоящий амперсанд); если в исходной строке «&» не было, «&» убирается и из перевода; - пункт меню «Текст\tCtrl+N» — переводится часть до табуляции, сочетание клавиш остаётся;
- шаблоны со вставками.
Шаблоны. Вставки — printf-вставки (%d, %s, %.3f, %I64d …) и %1…%9. Из
исходной строки строится регулярное выражение: текст между вставками экранируется,
каждая новая вставка становится группой (.+?), повтор той же вставки — обратной
ссылкой на её группу. Ключ вставки: %N для %1…%9, #k для k-й по порядку
printf-вставки. При переводе вставки строки другого языка заменяются захваченными
значениями по тем же ключам — поэтому строка с повторённой вставкой (%2×%2) получает
числа на свои места.
Когда переводится. Фильтр событий приложения при QEvent::Show окна верхнего
уровня, вложенного окна MDI или плавающей панели переводит его целиком: заголовок,
подсказки, подписи, кнопки, рамки групп, пункты списков, вкладки, заголовки колонок,
текст-подсказку полей ввода, пункты меню и подменю. Поэтому меню и диалоги из .rc
переводятся без правки их кода. Фильтр приложения срабатывает раньше фильтров
самого окна, и подгонка диалога слоя совместимости меряет уже переведённый текст
(подгонка окна).
Что не переводится автоматически:
- текст, поставленный в виджет после показа окна. Для подписей диалогов из ресурсов
это делает слой совместимости (
SetDlgItemText,SetWindowText), подсказки переводит фильтр темы перед показом; - строки, которые код собирает сам с числами и именами файлов, — их нужно брать через
tmci18n::tr(ru, en)или описывать шаблоном в словаре; - объекты со свойством
tmcNoTranslate.
Если один и тот же английский текст в разных местах значит разное, пункту меню задаётся
своя пара setOwnText(act, ru, en). Смена языка (setSetting) переводит все открытые
окна сразу: словарь работает в обе стороны.
Подводные камни
- Строка состояния может «потерять» последнее сообщение.
MfcViewWidgetпоказывает текст не чаще раза в 50 мс; сообщение, пришедшее раньше, только запоминается и выводится со следующим вызовом. Если вызовов больше нет, оно не показывается. Метод без ограничения частотыhostSetStatusTextImmediateобъявлен защищённым и в коде пакета не вызывается. Обращение к таблице непоказанных сообщений из потока расчёта не защищено блокировкой. hostMessageBoxне задаёт вопросов. Тип кнопок не учитывается, ответ всегда 1. Для вопросов «да/нет» нуженAfxMessageBox(text, MB_YESNO)слоя совместимости.- Перевод и подгонка размеров. Всё, что меряет текст подписей, должно выполняться при показе окна или позже — до показа подписи ещё не переведены и не оформлены.
- Числовая локаль. Не вызывайте
setlocale(LC_ALL, "")послеtheme::apply(): числа в файлах пакета пишутся с точкой. - Формат OpenGL.
MfcGLWidget::setupSurfaceFormat()нужно вызвать до создания первого виджета OpenGL.
Связь с другими модулями
- Слой совместимости —
CDC, виды, диалоги, карта сообщений. - Оболочка счётного ядра, TMCGROUT, TMCROS, TMC_DN — программы, использующие слой.
- Расчёт на видеокарте —
gui_common/compute.
Common interface layer
Purpose and place in the package
The directory src/gui_common contains interface code shared by all programs of the Qt6 version that
does not belong to any particular program: the host widgets in which the views of the
Windows version live, the visual theme, interface translation, the About dialog, the colour picker,
printing, the recent-files list, window placement and several robustness aids.
The subdirectory gui_common/compute (choice of computing device, OpenCL) is described on the page
GPU computing.
The layer sits between the compatibility layer (the classes CDC, CScrollView,
CDialog …) and the program shells apps/*:
apps/* (main windows, menus, toolbars)
│ create MfcViewWidget, call theme::apply(), tmcprint::printView(), …
▼
gui_common ── tmc_ui_base (theme, aboutbox) ── tmc_i18n (translation)
│ implements MfcQtHost, maps CCmdUI onto QAction
▼
compat (CDC, CScrollView, CDialog, message map)
All functions of the layer run in the GUI thread unless stated otherwise.
Contents and libraries
| CMake library | Files | Who uses it |
|---|---|---|
tmc_i18n |
i18n/tmci18n.* + the resource resources/i18n/ui_strings.tsv |
all programs, including FieldView and TPL Designer |
tmc_ui_base |
theme.*, aboutbox.* + icon resources (resources/icons) and font resources (resources/fonts) |
all programs; does not depend on the compatibility layer, so TPL Designer uses it too |
tmc_gui_common |
the files compat/mfc_*.cpp + colorpicker, mfcviewwidget, mfcglwidget, printsupport, recentfiles, commandupdate, dialogshot, windowplacement, mousewatchdog |
programs that use MFC classes (viewers, kernel shells, FieldView) |
| headers only | dllsafety.h, pathcheck.h |
program shells |
| File | Role |
|---|---|
theme.h/.cpp |
palette, style sheet, fonts, program and command icons |
aboutbox.h/.cpp |
the single About dialog, storage for the window decorator of the compatibility layer |
colorpicker.h/.cpp |
colour picker dialog |
commandupdate.h/.cpp |
mapping of ON_UPDATE_COMMAND_UI onto QAction |
mfcviewwidget.h/.cpp |
view host widget (QAbstractScrollArea) |
mfcglwidget.h/.cpp |
OpenGL view host widget (QOpenGLWidget) |
printsupport.h/.cpp |
printing, print preview, printing to PDF |
recentfiles.h/.cpp |
recent-files list |
windowplacement.h/.cpp |
window position between runs |
dialogshot.h/.cpp |
dialog snapshots for checking the appearance (a development tool) |
mousewatchdog.h/.cpp |
watchdog for a "stuck" mouse grab |
dllsafety.h |
safe DLL search |
pathcheck.h |
check of a path against the Windows code page |
i18n/tmci18n.h/.cpp |
ru/en interface translation |
Visual theme
theme::apply() is called by the program shell after QApplication has been created (preceded by
theme::setProgram("tmcgrout") and so on). It:
- sets the C numeric locale (
setlocale(LC_NUMERIC, "C")): numbers in TMC files are written and read with a decimal point;QApplicationtakes the locale from the environment, and under a Russian localesscanf("%lg")would stumble on the point, whileprintf("%g")would write commas; - registers the Inter and JetBrains Mono fonts from the resources
:/tmcfonts/; - sets the application icon (
appIcon()); - installs the About-dialog decorator (
tmcabout::install) and interface translation (tmci18n::install); - sets the Qt palette and the style sheet (
styleSheet()), the tooltip font and a filter that shows simple tooltips on a single line (<nobr>) already translated.
Palette (the functions theme::bg() … theme::warn()):
| Role | Colour | Role | Colour |
|---|---|---|---|
background bg |
#0a0e16 |
accent accent |
#34e3c4 |
panels surface |
#131a28 |
error danger |
#ff6b6b |
borders line |
#243049 |
success ok |
#5ce08a |
text text |
#e7eef7 |
warning warn |
#e3b341 |
dimmed textDim |
#9fb0c8 |
disabled textMute |
#6c7d97 |
The style sheet takes the origin of the dialogs into account: inside a QDialog the font is 8 points and
the margins are reduced (the coordinates from .rc are designed for "MS Sans Serif 8"), group boxes
are transparent (in .rc a group box is written after its controls and would otherwise cover them),
and the check-box and radio-button indicators are smaller. Standard Qt windows (QDialogButtonBox,
QMessageBox) get normal button sizes.
Command icons (commandIcon(id)): first the new set
:/tmcicons/toolbar/<program>/<ID>.svg; toggles have a pair <ID>_off.svg
(red dot) and <ID>_on.svg (green), which are placed into the Off/On states, so
a checked action shows green by itself. If there is no new image, the icon is taken from the
resources of the Windows version, :/icons/<ID>_dark.png or <ID>.png.
commandIconState(id, on) returns one of the pair (viewer launch buttons: green —
the viewer is running). programRunning(exe) checks the Windows process list at most once per
second (outside Windows — always false).
fitToScreen(w) limits the window to 95 % of the screen width and 88 % of its height and centres it.
Recolouring inside plots is done not by the theme but by the CDC of the compatibility
layer (theme colours).
The About dialog
One dialog for all programs of the package (tmcabout::show): program icon and name,
a description in the interface language, package version 5.1, year, system and architecture of the build,
the author and link buttons to his profiles, links to the website and the user manual, and an
OK button. The dialog finds out which program is running from theme::program(); if the program is not
set, the name is taken from the strings passed in. Description lines Copyright… and ©
are discarded; the remaining lines passed by the program (for example, "Model : H")
are shown below the description.
The user manual is searched for next to the program and in the typical distribution directories
(../share/tmc-suite, ../Resources, ../doc, ..): the file
TMC_Suite_User_Manual.pdf or the newest by name TMC_Suite_*.pdf (TPL Designer has
its own manual). If none is found, the button opens the manual on the website.
The IDD_ABOUTBOX dialog from resources. The ported program code opens its own
About dialog through CDialog::DoModal. To make it look uniform as well, the compatibility
layer calls the decorator tmc_dialog_decorator() after building every window.
tmcabout::install() registers the decorator
tmcabout::decorate, which, for a window with objectName() == "IDD_ABOUTBOX", hides the
layout from the resources (the dialog code may still access it) and places the uniform
content on top; other windows are left untouched.
The decorator storage (tmc_set_dialog_decorator / tmc_dialog_decorator) is declared in
compat/include/mfc_dialog.h but defined in aboutbox.cpp, i.e. in the
tmc_ui_base library: this way the About dialog does not drag the compatibility layer along, and it can
be used by TPL Designer, which has no MFC layer. The compatibility layer only
calls the decorator.
aboutText() returns the same content as HTML text — for places where text rather than
a window is needed.
The colour picker
tmcPickColor(parent, initial, &result, title) opens TmcColorPickerDialog and
returns true on OK. In the Windows build it is called by CColorDialog::DoModal of the compatibility
layer — so all dialogs for setting line and plot colours get this window
instead of the standard QColorDialog.
Elements of the dialog: an area "saturation horizontally / brightness vertically", a hue
strip, "before/after" swatches (clicking "before" restores the original colour), a HEX field
(#RRGGBB or #RGB), sliders and numeric fields R, G, B (0…255), rows of swatches "Project
palette", "Graph colors" (the classic viewer colours of the Windows version) and "Recent",
and an eyedropper (pick a colour from anywhere on the screen; Esc — cancel, Enter or the left button —
pick).
The colour is kept in two forms simultaneously: RGB (m_color, what the program will receive) and
HSV (m_h, m_s, m_v in the range 0…1, what the area and the strip show). When
converting RGB → HSV the hue is not updated if the colour is grey () or black
(), and the saturation is not updated if the colour is black: otherwise the hue handle would jump to zero
every time it passed through grey. The transition to a swatch is animated (220 ms). The chosen colour
is always opaque.
Recent colours (up to 12, the last chosen first, without duplicates) are stored in the INI file
TMC_Suite_Qt/ColorPicker.ini in the user profile (Windows — %APPDATA%), key
Recent/Colors, as a single line of hexadecimal codes without # separated by spaces (# in an INI file
may start a comment). A colour is added on OK.
Updating the command state
In MFC, before showing a menu the framework polled the ON_UPDATE_COMMAND_UI handlers: whether
an item is enabled (pCmdUI->Enable) and whether it is checked (SetCheck, SetRadio). Here this is done by
tmccmd::updateActions(actions, target):
- builds the message map of the target (
target->TmcBuildMessageMap, the view of the active window or the document); if there are no update handlers, it returns; - for each pair "command ID →
QAction" creates aCCmdUIand calls the handler; - transfers to the action only what the handler has set:
Enable→setEnabled,SetCheck/SetRadio→ the action becomes checkable andsetChecked(Check() != 0)(the indeterminate state 2 counts as checked). An item without a handler stays as it was — as in MFC.
The shells call the function before showing a menu (QMenu::aboutToShow) and after each
executed command. updateAction does the same for a single command.
The view host widget
MfcViewWidget (QAbstractScrollArea) implements the MfcQtHost interface of the compatibility
layer for a CScrollView view: the view decides what to draw and how to
react (code of the Windows version), the widget decides where to draw and where events come from.
| Qt event | Action |
|---|---|
paintEvent |
fill with the background, CDC over the QPainter of the viewport, OnPrepareDC, OnDraw |
| left / right button press | OnLButtonDown / OnRButtonDown |
| left button release | release of a "forgotten" mouse grab, OnLButtonUp |
| left double click | OnLButtonDblClk |
| mouse move | OnMouseMove (tracking is enabled, also without a pressed button) |
| Qt timer | OnTimer(MFC ID) |
Button and key flags are converted to MK_LBUTTON, MK_RBUTTON, MK_MBUTTON,
MK_SHIFT, MK_CONTROL; the point is converted to content pixels (taking scrolling into account).
Calls from the view:
hostInvalidaterepaints the whole window (the logical area is not recalculated);hostUpdateWindow— immediately (repaint), but duringOnDrawand from another thread — deferred (updatequeued to the main thread);hostSetScrollSizessets the scroll-bar ranges: maximum = full size − viewport size; the default page step is the viewport size, the line step is 20 pixels;hostMessageBoxshows an information box and always returns 1 (IDOK); from the computation thread — asynchronously;hostSetStatusTextemits the signalstatusTextChanged(pane, text), but at most once every 50 ms (the kernel reports progress on every time step); the protectedhostSetStatusTextImmediatehas no such limit (it is not called in the package code);hostSetCapturedeliberately does nothing (pitfalls).
setDocumentBackground(color) sets the background: in the Windows build white and black (the default values
of the Windows version) are replaced by the theme background, grey 192 by the panel colour, and any other
colour chosen by the user is used as is.
The OpenGL view host widget
MfcGLWidget (QOpenGLWidget) is the host for a view that draws a scene through OpenGL
(FieldView from apps/fieldview, the build outside Windows; in the Windows build the library
contains it, but the field is displayed by apps/fieldview_rhi).
setupSurfaceFormat()(call before creating widgets) sets the default format: OpenGL 2.1 compatibility profile, 24-bit depth, double buffering — the rendering of the Windows version is written in the old style (glBegin/glEnd, matrices, no shaders);initializeGL→OnInitialUpdate(the context has already been created and is current),resizeGL→OnSize(0, w, h),paintGL→OnDrawwith a canvas-less context in deferred-text mode;TextOutlabels are then drawn byQPainteron top of the frame;- there is no scrolling, and
hostSetStatusTextemits the signal immediately.
Printing
Printing uses the same code as on-screen drawing: the CDC is attached to a
QPrinter, the mapping mode is MM_HIMETRIC, the origin is the top-left corner of the sheet, and the view
calls its own OnDraw. The scale comes out by itself: MM_HIMETRIC computes pixels from the
device resolution, and the printer has its own.
An OpenGL view does not use a device context — it draws straight into the framebuffer, and
the sheet would come out empty. For it, a snapshot of the frame is transferred to paper
(grabFramebuffer), centred in the printable area with the aspect ratio preserved.
| Function | What it does |
|---|---|
tmcprint::printView |
Qt print dialog, then one page |
tmcprint::previewView |
print preview window |
tmcprint::printViewToPdf |
printing to a PDF file without a dialog (for testing printing without human involvement) |
tmcprint::pageSetup |
page setup |
The printer is shared for the whole lifetime of the program: the chosen settings are kept between calls.
Recent files
TmcRecentFiles maintains the recent-files list of the "File" menu (4 by default) and stores
it in the program settings (CWinApp, settings) — section
Recent File List, keys File1…FileN, as in MFC. The path is written in UTF-8 with the
utf8: prefix: in the Windows code page, letters outside it would be lost; old entries
without the prefix are read in the local code page. Paths are absolute; the same file
written in different case or with different separators is treated as one entry
(on Windows the comparison is case-insensitive).
attachToMenu(menu, before) inserts the items "&1 name", "&2 name" … before the item
before; when the list is empty — a disabled "Recent File" item, so that the menu does not "jump".
Choosing an item emits the signal fileRequested(path); the shell opens the file and calls
add(path).
Window placement
tmcui::keepPlacement(window, key) attaches a watcher to a window: on first show the window
is restored from the saved value, and on close the value is written. The value
is a string "x y width height" (pixels) in the Window section of the program settings. When
restored, the window is constrained to the screen on which it was left (if that screen
no longer exists — to the primary one). If there is no saved value or it is smaller than 100x100, the window is placed
in the centre of the screen (centerOnScreen). The environment variable TMC_NO_PLACEMENT disables
restoring (testing tools set the size themselves).
Dialog snapshots
A development tool, not used during normal operation of the program. tmcshot::grabDialog(idd,
file) builds a dialog by its resource ID the same way as at run time (TmcBuildIn +
decorator), fills empty fields with sample text, shows the window and saves a snapshot.
At the same time it checks the controls and writes lines ПРОБЛЕМА … (Russian for "PROBLEM") to stderr:
- the centre of a control is covered by another control (it cannot be reached with the mouse);
- a button with text is lower than 28 pixels;
- the caption of a button, check box or radio button does not fit.
grabAllDialogs(dir) captures all dialogs registered by the program into the files
dialog_<number>.png.
Mouse-grab watchdog
An MDI child window grabs the mouse by itself while dragging. If the button release did not
reach it, the grab remains, and all clicks go to that window — menus and toolbars
stop responding. tmcui::installMouseGrabWatchdog(owner) checks every 500 ms:
if there is a grab while the mouse buttons are released, the grab is released. The same checks are performed by
the mouse-release handlers of MfcViewWidget and MfcGLWidget.
Path check
The ported code opens files with ANSI functions (fopen), so the path is converted to the
Windows code page. Windows silently replaces letters outside it with similar ones or ?, and
the program would open a file from a different folder or fail to find it.
tmcui::pathFitsCodePage(path) checks that the path converts there and back without
loss; the shells do not pass such a path to the computational code but report it to the user.
Safe DLL search
tmcui::secureDllSearch() calls
SetDefaultDllDirectories(LOAD_LIBRARY_SEARCH_DEFAULT_DIRS): DLLs loaded at
run time (for example, OpenCL.dll) are searched for only in the program folder and in System32, not in
the current folder — for the kernels that is the task folder, and a DLL with the name of a
system library planted there would be loaded into the program. This does not affect libraries that the program imports at
startup (Qt6*.dll). Outside Windows the function is empty.
Interface translation
The interface language is Russian or English. The choice is shared by all programs of the package and
is stored in TMC_Suite_Qt/Common.ini (Windows — %APPDATA%), [UI] Language = system |
ru | en. system means Russian if the system language is Russian, otherwise English. The selection menu
is added by tmci18n::addLanguageMenu(parent) (the menu items themselves are not translated).
Dictionary. resources/i18n/ui_strings.tsv — lines "English\n and \t in the text mean a line feed and a tab; lines starting with # are comments.
After the line #TEMPLATES come templates with placeholders. The dictionary works in both directions
(in each direction the first pair for a given text wins); translations of the
buttons of standard Qt windows are added to it. For the standard Qt windows themselves (file dialog, font dialog)
the Qt translation qtbase_ru.qm is loaded — from the translations directory next to the program
or from the Qt installation.
Translation lookup (translate), in order:
- leading and trailing whitespace is separated and preserved;
- exact match;
- match without "&" (underlined letters;
&&is a real ampersand); if the source string had no "&", the "&" is removed from the translation as well; - a menu item "Text\tCtrl+N" — the part before the tab is translated, the key combination remains;
- templates with placeholders.
Templates. Placeholders are printf conversions (%d, %s, %.3f, %I64d …) and %1…%9. A
regular expression is built from the source string: the text between placeholders is escaped,
each new placeholder becomes a group (.+?), and a repetition of the same placeholder becomes a back-reference
to its group. Placeholder key: %N for %1…%9, #k for the k-th printf
conversion in order. When translating, the placeholders of the string in the other language are replaced by the captured
values with the same keys — so a string with a repeated placeholder (%2×%2) gets
the numbers in their places.
When translation happens. The application event filter, on QEvent::Show of a top-level
window, an MDI child window or a floating panel, translates it entirely: the title,
tooltips, labels, buttons, group boxes, list items, tabs, column headers,
placeholder text of input fields, menu items and submenus. That is why menus and dialogs from .rc
are translated without editing their code. The application filter fires before the filters of
the window itself, so the dialog fitting of the compatibility layer measures text that is already translated
(dialog fitting).
What is not translated automatically:
- text set in a widget after the window has been shown. For labels of dialogs from resources
this is done by the compatibility layer (
SetDlgItemText,SetWindowText), and tooltips are translated by the theme filter before they are shown; - strings that the code assembles itself with numbers and file names — they must be obtained through
tmci18n::tr(ru, en)or described by a template in the dictionary; - objects with the
tmcNoTranslateproperty.
If the same English text means different things in different places, a menu item is given
its own pair setOwnText(act, ru, en). Changing the language (setSetting) translates all open
windows at once: the dictionary works in both directions.
Pitfalls
- The status bar may "lose" the last message.
MfcViewWidgetshows text at most once every 50 ms; a message that arrives earlier is only remembered and shown with the next call. If there are no more calls, it is not shown. The method without rate limiting,hostSetStatusTextImmediate, is declared protected and is not called in the package code. Access to the table of unshown messages from the computation thread is not protected by a lock. hostMessageBoxdoes not ask questions. The button type is ignored, the answer is always 1. For yes/no questions useAfxMessageBox(text, MB_YESNO)of the compatibility layer.- Translation and size fitting. Everything that measures label text must run when the window is shown or later — before it is shown, the labels are not yet translated or styled.
- Numeric locale. Do not call
setlocale(LC_ALL, "")aftertheme::apply(): numbers in the package files are written with a decimal point. - OpenGL format.
MfcGLWidget::setupSurfaceFormat()must be called before the first OpenGL widget is created.
Relation to other modules
- Compatibility layer —
CDC, views, dialogs, message map. - Compute kernel shell, TMCGROUT, TMCROS, TMC_DN — programs that use the layer.
- GPU computing —
gui_common/compute.