Слой совместимости

Назначение и место в пакете

Расчётный код Qt6-версии TMC Suite (каталог src/libs, src/kernels, src/viewers: ядра, библиотеки, классы документов, видов и диалогов программ) исторически написан на MFC и обращается к её классам: CString, CDocument, CScrollView, CDC, CDialog, DDX_Text, AfxBeginThread и другим. Слой совместимости (каталог src/compat) реализует эти классы на Qt 6. Самой библиотеки MFC в Qt6-версии нет: под знакомыми именами работают QPainter, QDialog, QThread, QTimer, QSettings-подобный ini-файл.

Главное свойство слоя — код src/libs, src/kernels, src/viewers компилируется без правок. Поэтому формулы, порядок вычислений, форматы файлов и картинка графиков остаются теми же; всё, что меняется, — то, чем выполнены вызовы окон, рисования и потоков.

Место слоя в сборке:

 src/libs, src/kernels, src/viewers (ядра, библиотеки, документы, виды, диалоги — код на классах MFC)
        │  #include <afxwin.h>, <afx.h> …   → находятся в compat/include
        ▼
 compat/include  — объявления классов и типов (без Qt)
 compat/*.cpp    — реализация на Qt 6 (кроме tmc_mfc_doc.cpp — без Qt)
        │
        ▼
 gui_common      — виджеты-хозяева видов, тема, перевод, печать (страница gui-common)
 apps/*          — оболочки программ: главные окна, меню, запуск расчёта

Слой собирается в три цели CMake (src/CMakeLists.txt, src/gui_common/CMakeLists.txt):

Цель Что входит Кто использует
tmc_compat (INTERFACE) каталоги заголовков compat/include, в Windows ещё compat/include_win, вне Windows — compat/include_posix все библиотеки и программы
tmc_platform (STATIC) tmc_mfc_doc.cpp; в Windows (MinGW) — ucrt_libm_win.cpp как интерфейсный источник; вне Windows — tmc_textmode.cpp и флаг -Wl,--wrap=fopen каждая программа, включая счётные ядра
tmc_gui_common (STATIC) mfc_gdi.cpp, mfc_view.cpp, mfc_dialog.cpp, mfc_thread.cpp, mfc_wgl.cpp + файлы gui_common все графические программы

Каждый файл src/libs, src/kernels, src/viewers дополнительно получает преамбулу tmc_win_prelude.h (ключ компилятора -include): то, что MSVC давал неявно (__max, __min, разделитель каталогов TMC_PATH_SEP, вне Windows — тип _complex).

Слой не содержит ни одной расчётной формулы.

Состав

Файл Роль
include/afx.h, afxwin.h, afxext.h, afxcmn.h, afxdisp.h, afxmt.h, cstringt.h, afxdtctl.h заглушки заголовков MFC: подключают нужную часть слоя
include/afxres.h стандартные номера команд каркаса (ID_FILE_OPEN …), стили панелей и окон
include/tmc_mfc.h CString, базовые типы Windows (вне Windows), AfxMessageBox(text)
include/tmc_winapi.h подключение настоящего windows.h в Windows-сборке и перехват функций Windows API, работающих с объектами слоя
include/tmc_mfc_doc.h, tmc_mfc_doc.cpp CObject, CDocument, CWinApp (настройки), CCmdUI, CException, цвета, LOGFONT, запуск программ пакета
include/mfc_gdi.h, mfc_gdi.cpp рисование: CDC, CPen, CBrush, CFont, CPoint, CSize, CRect
include/mfc_view.h, mfc_view.cpp окна и виды: CWnd, CView, CScrollView, CClientDC, интерфейс-мост MfcQtHost
include/mfc_dialog.h, mfc_dialog.cpp диалоги, элементы, DDX/DDV, карты сообщений, страницы свойств, стандартные диалоги, реестр разметок
include/mfc_thread.h, mfc_thread.cpp потоки CWinThread/AfxBeginThread, ожидание с прокачкой событий
include/mfc_wgl.h, mfc_wgl.cpp CPalette; вне Windows — заглушки wgl* и формата пикселей
include/tmc_win_prelude.h преамбула для каждого файла src/libs, src/kernels, src/viewers
ucrt_libm_win.cpp Windows (MinGW): sin, cos, exp, pow … из ucrtbase.dll
include_win/execinfo.h Windows: заглушка backtrace/alarm для средств проверки интерфейса (в поставку не входит)
tmc_textmode.cpp только сборка под Linux: текстовый режим fopen (CRLF) и поиск файла без учёта регистра
include_posix/windows.h, io.h, conio.h, gl/gl.h, gl/glu.h только сборка под Linux: заглушки системных заголовков Windows

afxdtctl.h подключается единственным файлом — src/fieldview/stdafx.h, а этот FieldView собирается только вне Windows; в Windows-сборке поле показывает apps/fieldview_rhi.

Заголовки-заглушки

Код src/libs, src/kernels, src/viewers подключает <afxwin.h>, <afx.h>, <windows.h> и т. п. Каталог compat/include стоит в пути поиска первым, поэтому эти имена находят файлы слоя, а те по цепочке подключают нужное:

afxwin.h ─► mfc_thread.h ─► mfc_dialog.h ─► mfc_view.h ─► mfc_gdi.h ─► tmc_mfc_doc.h ─► tmc_mfc.h
        └─► mfc_wgl.h                     └─► afxres.h                                   └─► tmc_winapi.h (Windows)

Все файлы слоя действуют при условии !defined(_WIN32) || defined(TMC_QT_WIN): вне Windows всегда, в Windows — в сборке Qt6-версии (макрос TMC_QT_WIN задаёт корневой CMakeLists.txt).

В Windows-сборке типы и функции Windows API (BOOL, DWORD, HANDLE, RECT, COLORREF, CreateFile, Sleep …) настоящие — из windows.h. Слой объявляет их сам только вне Windows (ветки #ifndef _WIN32). Каталог compat/include_posix с заглушками windows.h, io.h, conio.h, gl/*.h подключается только вне Windows, чтобы под MinGW не заслонить настоящие системные заголовки.

Строки и базовые типы

CString (tmc_mfc.h) — тривиально копируемый класс с единственным членом char*. Это требование ABI: код src/libs, src/kernels, src/viewers передаёт CString в printf/Format через "%s" как переменный аргумент. Объект, равный по размеру и устройству одному указателю, ложится на стек так же, как у MFC, и "%s" читает именно указатель. Если бы CString был обёрткой над std::string, компилятор передал бы его по скрытой ссылке и в выходной строке оказался бы мусор. Свойство закреплено static_assert(std::is_trivially_copyable<CString>).

Следствия:

  • каждое изменение строки выделяет новый буфер malloc; прежний не освобождается (деструктор сделал бы тип нетривиальным). Объём утечки мал: строки в коде пакета — имена файлов и подписи;
  • копия CString разделяет буфер с оригиналом; методы, меняющие строку, создают новый буфер, поэтому копии не затрагиваются — кроме DDV_MaxChars, которая обрезает буфер на месте (см. подводные камни);
  • все позиции и длины — в байтах; кодировка строк кода — CP1251.

AfxMessageBox(text) с одним аргументом вызывает обработчик, установленный tmc_set_message_handler. По умолчанию (mfc_dialog.cpp) это окно сообщения в потоке интерфейса; из другого потока или без графического приложения текст пишется в stderr. Оболочки ядер ставят свой обработчик (apps/planarrt_common/mainwindow.cpp). Вариант AfxMessageBox(text, type) с кнопками описан в разделе о диалогах.

Перехват функций Windows API

В Windows-сборке API настоящий, но несколько функций работают с объектами слоя, а не системы. Их имена tmc_winapi.h переопределяет макросами — код src/libs, src/kernels, src/viewers остаётся прежним, а вызов попадает в слой:

Вызов в коде Реализация Что делает
PeekMessage, TranslateMessage, DispatchMessage mfc_thread.cpp обрабатывают накопившиеся события Qt (до 10 мс); PeekMessage всегда отвечает «сообщений нет»
WaitForSingleObject, MsgWaitForMultipleObjects, GetExitCodeThread mfc_thread.cpp ожидание и код завершения потоков слоя (QThread)
GetDeviceCaps mfc_gdi.cpp разрешение и размер устройства Qt / основного экрана
CreateProcess tmc_mfc_doc.cpp имя соседней программы пакета (TMCROS.EXE, FLDVIEW.EXE, PLANRT_H.EXE …) переводится в имя Qt-версии рядом с текущей программой; остальное — настоящий CreateProcessA
PostMessage, IsWindow mfc_view.cpp сообщение окну слоя передаётся обработчику программы (tmc_set_post_message_handler; у ядер — закрытие главного окна после пакетного расчёта, planrt_compat.cpp); IsWindow проверяет только, что описатель не нулевой

Перевод имени программы (TmcResolveProgramName): существующий путь не меняется; иначе отбрасываются каталог и .exe, имя приводится к нижнему регистру, fldview → fieldview, planrt_h/planrt_x → planarrt_h/planarrt_x, и программа ищется в каталоге текущей. Если файла там нет, в Windows запускается исходное имя (поиск по PATH, так открывается NOTEPAD.EXE).

Макрос заменяет имя везде, в том числе имя метода: CDC::GetDeviceCaps и CWnd::PostMessage в Windows-сборке фактически называются TmcGetDeviceCaps и TmcPostMessage. Для вызывающего кода это незаметно, но видно в отладчике.

INPUT из winuser.h на время подключения windows.h переименовывается: так же называется структура задания TMC (run.h).

Ресурсы .rc → диалоги Qt

Диалог Windows-версии состоит из двух частей: разметки в ресурсе .rc и поведения в классе (DoDataExchange, обработчики кнопок, OnInitDialog). Слой сохраняет обе.

Разметка: от .rc к функции построения

Разметку переводит скрипт tools/rc2ui.py (запускается при подготовке исходников, не при сборке):

  1. Читает .rc (CP1251) и resource.h. Каждый блок DIALOG/DIALOGEX превращается в файл IDD_<имя>.ui с элементами на абсолютных координатах, без раскладок.
  2. Координаты переводятся из диалоговых единиц в пиксели по шрифту диалогов TMC «MS Sans Serif 8» при 96 dpi:
xpx=xdu·64=1,5xdu,ypx=ydu·138=1,625ydu.(1)
  1. objectName каждого виджета — символьное имя элемента из resource.h (IDC_GRPAR_XMAX). Если один номер описан несколькими именами, берётся первое по файлу.
  2. Виджеты записываются в обратном порядке (в Windows выше лежит элемент, записанный раньше; в Qt — созданный позже), а порядок Tab восстанавливается разделом <tabstops> в порядке записи .rc.
  3. Переключатели делятся на группы по WS_GROUP и получают QButtonGroup.
  4. Порождается apps/<программа>/dialogs/dialog_registry.cpp: включает ui_*.h (их делает uic) и регистрирует в MfcDialogRegistry пары «номер диалога → функция setupUi» и «номер элемента → символьное имя» для всех определений resource.h.

Построение окна

CDialog::DoModal() (модальное окно) и CDialog::Create() (немодальное) создают TmcModalDialog — наследника QDialog, знающего свой диалог MFC, — и вызывают CDialog::TmcBuildIn():

  1. функция разметки из реестра строит виджеты;
  2. кнопки с номерами IDOK и IDCANCEL подключаются к OnOK() и OnCancel();
  3. карта сообщений класса (TmcBuildMessageMap) строится, и каждая запись-команда подключается к сигналу clicked элемента с тем же номером — только если элемент кнопка (QAbstractButton);
  4. OnInitDialog(), затем UpdateData(FALSE) — значения переменных попадают в элементы, как в MFC;
  5. tmcFitDialogContent() — подготовка подгонки (ниже).

Затем вызывается оформитель окна tmc_dialog_decorator() (если установлен; так окно «О программе» получает единое содержимое — см. gui-common), и окно показывается. Если для номера диалога разметка не зарегистрирована, DoModal пишет сообщение в stderr и возвращает IDCANCEL, Create — FALSE.

Элемент находится по номеру так: номер → символьное имя (реестр) → QDialog::findChild<QWidget*>(имя). Поэтому GetDlgItem(IDC_EDIT1) в коде Windows-версии продолжает работать. GetDlgItem возвращает обёртку CWndCtrl (кэшируется в диалоге); если элемента нет, обёртка пустая и её методы ничего не делают.

Тексты между кодом и виджетами перекодируются: CP1251 → Unicode при записи, Unicode → CP1251 при чтении (символы вне CP1251 становятся ?).

Закрытие окна:

Действие пользователя Вызов
кнопка OK OnOK() → UpdateData(TRUE) → EndDialog(IDOK)
кнопка «Отмена», клавиша Esc OnCancel() → EndDialog(IDCANCEL)
крестик окна OnClose() → по умолчанию EndDialog(IDCANCEL)

DoModal возвращает IDOK, только если окно закрыто через EndDialog(IDOK). Немодальное окно живёт до DestroyWindow() (тогда GetSafeHwnd() снова возвращает NULL, и код Windows-версии создаёт окно заново) или до удаления объекта диалога.

OnPaint() диалога вызывается после каждой перерисовки окна — так диалоги рисуют образцы цвета и линий. Рисование поверх элемента вне перерисовки (GetDlgItem(id)->GetDC()) идёт в картинку размером с элемент; ReleaseDC ставит её в элемент-подпись (QLabel::setPixmap).

AfxMessageBox(text, type) показывает QMessageBox с кнопками MB_OK, MB_OKCANCEL или MB_YESNO и значком MB_ICON*, возвращает IDOK, IDCANCEL, IDYES или IDNO. Без графического приложения отвечает IDYES/IDOK.

Подгонка окна

Координаты .rc рассчитаны на шрифт Windows и английские подписи. Чтобы ничего не обрезалось, слой подгоняет окно в два этапа.

При построении (tmcFitDialogContent): все элементы переносятся в виджет-содержимое внутри QScrollArea (положение сохраняется); порядок Tab, запомненный до переноса, восстанавливается; окно получает размер по содержимому, но не больше 95 % ширины и 92 % высоты экрана, и может растягиваться.

При первом показе (TmcDialogFitter → tmcRefitAfterShow), когда тема и перевод уже применены:

  1. подписи и рамки групп опускаются под остальные элементы, рамки пропускают мышь (подводные камни);
  2. равномерное растяжение под текст (tmcScaleForText): для каждого элемента считается нужная ширина wineed и высота hineed (текст + отступы; у кнопок высота не меньше 28 пикселей), и вся разметка умножается на
sx=min(1,7, maxiwineedwi),sy=min(1,7, maxihineedhi)(2)

(только если хотя бы один из них больше 1) — взаимное расположение сохраняется; 3. многострочные поля высотой до 40 пикселей теряют внутренние отступы и полосы; 4. пустая подпись размером 16–64 пикселя получает значок программы (элемент ICON ресурса); 5. подписи и кнопки, которым всё ещё не хватает места, расширяются вправо — до ближайшего соседа в том же ряду (tmcGrowLabels); 6. окно получает итоговый размер (в тех же пределах экрана).

Переменная окружения TMC_DIALOG_DEBUG печатает в stderr размеры и коэффициенты.

Страницы свойств

CPropertySheet::DoModal() строит QDialog с QTabWidget и кнопками OK / Cancel / Apply. Каждая CPropertyPage строится своим TmcBuildIn в отдельном QDialog, который становится вкладкой. Подпись вкладки — заголовок окна из ресурса, иначе m_strCaption, иначе «Page N»; одинаковые подписи страниц одного шаблона нумеруются («Melody 1», «Melody 2»). Смена вкладки вызывает OnKillActive прежней и OnSetActive новой страницы (возврат FALSE из OnKillActive переход не запрещает). Apply и OK вызывают у всех страниц UpdateData(TRUE) и OnApply(). Кнопка Apply доступна, пока хоть одна страница отмечена SetModified(TRUE).

Стандартные диалоги

Класс Реализация
CFileDialog QFileDialog::getOpenFileName/getSaveFileName; фильтр MFC "Описание|шаблон||" переводится в фильтр Qt; путь — в локальной 8-битной кодировке
CColorDialog Windows-сборка — окно tmcPickColor (gui-common); иначе QColorDialog
CFontDialog QFontDialog; результат пишется в LOGFONT (высота — минус пиксели или пункты)

Карта сообщений

В MFC макросы BEGIN_MESSAGE_MAP … END_MESSAGE_MAP строили статическую таблицу указателей на методы. В слое они разворачиваются в виртуальный метод, который заполняет таблицу MfcMessageMap замыканиями:

// Код Windows-версии                        // Во что разворачивается
BEGIN_MESSAGE_MAP(CMyDlg, CDialog)           void CMyDlg::TmcBuildMessageMap(MfcMessageMap& tmcMap)
    ON_BN_CLICKED(IDC_APPLY, OnApply)        {   CDialog::TmcBuildMessageMap(tmcMap);
    ON_MESSAGE(WM_USER + 1, OnBye)               tmcMap.add(IDC_APPLY, [this]{ this->OnApply(); });
END_MESSAGE_MAP()                                tmcMap.addMessage(UINT(WM_USER + 1), …OnBye…);
                                             }

DECLARE_MESSAGE_MAP() объявляет этот метод в классе. Карта базового класса вызывается первой, поэтому записи наследника перекрывают её.

В таблице три вида записей:

Макросы Таблица Кто вызывает
ON_COMMAND, ON_BN_CLICKED, ON_STN_CLICKED, ON_EN_CHANGE, ON_CBN_SELCHANGE, ON_LBN_SELCHANGE команда → void() диалог: сигнал clicked кнопки с тем же номером; оболочки программ: пункты меню и панелей
ON_UPDATE_COMMAND_UI команда → void(CCmdUI*) tmccmd::updateActions перед показом меню (gui-common)
ON_MESSAGE сообщение → LRESULT(WPARAM, LPARAM) CWnd::SendMessage (сразу) и CWnd::PostMessage (через очередь главного потока)

Карта строится заново при каждом использовании (построение диалога, SendMessage, опрос состояния команд) — она дешёвая и всегда отражает текущий объект.

Не поддерживаются (разворачиваются в пустоту): ON_COMMAND_RANGE, ON_UPDATE_COMMAND_UI_RANGE, ON_NOTIFY. Макросы ON_WM_* (ON_WM_TIMER, ON_WM_SIZE, ON_WM_LBUTTONDOWN …) пустые: эти события приходят через виртуальные методы вида и диалога, которые зовёт виджет-хозяин.

В tmc_mfc_doc.h есть «пустой» вариант тех же макросов для кода без окон (документы, ядра); mfc_dialog.h переопределяет их рабочими.

Обмен данными DDX/DDV

UpdateData(bSave) создаёт CDataExchange с направлением и вызывает DoDataExchange класса. Функции DDX_* находят виджет через GetDlgItem:

Функция Виджет Запись в элемент Чтение из элемента
DDX_Text (CString, char*) поле, подпись, кнопка, список, многострочное поле CP1251 → Unicode Unicode → CP1251
DDX_Text (int, UINT, long) то же %d toInt(); нечисловой текст → 0
DDX_Text (double, float) то же %g toDouble(); нечисловой текст → 0
DDX_Check флажок 0/1 0/1
DDX_Radio группа переключателей номер отмеченного номер отмеченного, -1 — ни одного
DDX_CBIndex, DDX_LBIndex выпадающий список / список номер пункта номер пункта
DDX_Control любой привязывает переменную-обёртку к виджету —

DDX_Radio. В MFC значение — номер переключателя в группе, начинающейся с элемента с WS_GROUP, в порядке записи в .rc; номера элементов при этом не обязаны идти подряд (в TMC_DN «ДН» = 1048, «ДН, дБ» = 1053). Слой берёт группу из QButtonGroup разметки, а порядок — из цепочки фокуса, начиная с первого переключателя: она выстроена по порядку .rc (поэтому подгонка окна сохраняет порядок Tab). Переключатели группы, не попавшие в цепочку, идут в конец. Если группы нет, перебираются элементы id, id+1, … пока существуют.

Проверки DDV не показывают окон и не прерывают обмен: DDV_MaxChars обрезает строку, DDV_MinMax* ничего не делают. UpdateData всегда возвращает TRUE.

Документ и вид

Классы документов программ (CTMCGROUTDoc и др.) наследуются от CDocument (tmc_mfc_doc.h) — без окон: путь к файлу (в Windows приводится к полному пути с обратными косыми чертами, как в MFC), заголовок, флаг изменения и признак «виды нужно перерисовать» (UpdateAllViews ставит, оболочка снимает TakeViewsDirty). Файлы документ читает и пишет своим кодом через FILE*; сериализация MFC (CArchive) не используется. Объекты документов и видов создаёт оболочка программы через фабрику TmcCreate(), которую добавляет DECLARE_DYNCREATE.

Вид (CScrollView и наследники, mfc_view.h) не знает о Qt. Всё, что ему нужно от окна, он получает через интерфейс MfcQtHost, который реализует виджет-хозяин из gui_common (MfcViewWidget, для OpenGL — MfcGLWidget):

        Qt-события                         вызовы вида
QAbstractScrollArea ─┐                ┌─ Invalidate / UpdateWindow ─► hostInvalidate / hostUpdateWindow
  paintEvent ────────┼─► OnPrepareDC  │  SetTimer / KillTimer ───────► hostSetTimer / hostKillTimer
  mouse*Event ───────┼─► OnLButton*   │  MessageBox ─────────────────► hostMessageBox
  timerEvent ────────┼─► OnTimer      │  SetScrollSizes ─────────────► hostSetScrollSizes
                     │   OnDraw(CDC*) │  CStatusBar::SetPaneText ────► hostSetStatusText
   MfcViewWidget  ◄──┴── CScrollView ─┘
   (MfcQtHost)

Жизненный цикл: оболочка создаёт документ и вид, виджет вызывает setView(view) (вид получает хозяина через SetHost), после получения размера — initialUpdate() → OnInitialUpdate() (один раз). На каждую перерисовку виджет создаёт CDC над своим QPainter, вызывает OnPrepareDC (режим отображения и сдвиг на прокрутку) и OnDraw. При удалении виджет отвязывает вид (SetHost(nullptr)); пока хозяина нет, вызовы окна у вида ничего не делают.

Координаты мыши вид получает в пикселях содержимого (с учётом прокрутки) и сам переводит их в логические через CClientDC + DPtoLP. CClientDC холста не имеет — это только масштаб MM_HIMETRIC по разрешению окна.

CScrollView переводит размеры и позицию прокрутки между логическими единицами и пикселями: для MM_HIMETRIC (0,01 мм, ось Y вверх) пикселей на единицу p=dpi/25,4/100, позиция по Y получает обратный знак; для остальных режимов — 1:1. В OnPrepareDC начало области вывода сдвигается на (−xscroll,−yscroll) — так содержимое «уезжает» под полосой прокрутки.

Настройки программы

CWinApp::GetProfileString/WriteProfileString/GetProfileInt/WriteProfileInt вместо реестра работают с ini-файлом: Windows — %APPDATA%\TMC_Suite_Qt\<программа>.conf, Linux — ~/.config/TMC_Suite/<программа>.conf. Имя программы задаёт оболочка (CWinApp::SetAppName). Файл читается в память при первом обращении; каждая запись перечитывает файл и перезаписывает его целиком — значения, записанные другим экземпляром программы, не теряются. Ошибка записи не сообщается. Если в Windows по новому пути файла нет, а по старому ошибочному пути <APPDATA>TMC_Suite_Qt\… (без разделителя) он есть, файл копируется.

Нехватка памяти в new бросает CMemoryException*, как в MFC: обработчик new ставит статический объект в tmc_mfc_doc.cpp, а код расчёта ловит catch (CException* e) и завершает шаг с кодом ошибки.

Таймеры

Где Как устроен Срабатывание
вид (CWnd::SetTimer) хозяин запускает QObject::startTimer, хранит пару «номер Qt → номер MFC» timerEvent хозяина → OnTimer(номер MFC) вида
диалог (CDialog::SetTimer) QTimer — дочерний объект окна диалога; повторный запуск того же номера перезапускает таймер OnTimer(id) диалога

Таймеры работают в потоке интерфейса; функция обратного вызова (третий параметр SetTimer) не поддерживается. Таймер диалога можно запустить только когда окно существует (SetTimer из OnInitDialog — можно, из конструктора — нет, вернётся 0).

Потоки

Счётные ядра запускают расчёт так же, как в Windows-версии: AfxBeginThread(RunAllGlobal, pDoc, priority, 0, CREATE_SUSPENDED), затем ResumeThread(). Слой создаёт CWinThread с внутренним QThread (MfcThread::run() вызывает функцию потока и запоминает код возврата):

  • описатель m_hThread — указатель на внутренний поток; по нему функции ожидания находят поток в таблице;
  • приоритет Windows запоминается и передаётся в QThread::start (<= LOWEST → LowestPriority, BELOW_NORMAL → LowPriority, NORMAL, ABOVE_NORMAL → HighPriority, >= HIGHEST → HighestPriority): Qt не умеет задавать приоритет незапущенному потоку;
  • SuspendThread не поддерживается — расчёт останавливается флагом в расчётном классе (Stop()), как и в Windows-версии;
  • WaitForSingleObject ждёт поток без обработки событий; MsgWaitForMultipleObjects ждёт короткими шагами, между ними обрабатывая события Qt порциями до 20 мс, — окно не «замерзает», пока закрытие ждёт конца расчёта;
  • GetExitCodeThread возвращает 259 (STILL_ACTIVE), пока поток работает, затем — код возврата функции потока.

Порядок вычислений от этого не зависит: поток исполняет ту же функцию с теми же данными.

Вызовы окон из расчётного потока. Код Windows-версии зовёт из потока расчёта Invalidate, RedrawWindow, MessageBox, строку состояния. В Qt трогать виджеты можно только из главного потока, поэтому:

  • hostInvalidate, hostUpdateWindow, hostMessageBox хозяина вида, вызванные не из главного потока, ставят действие в очередь главного потока (QMetaObject::invokeMethod(…, Qt::QueuedConnection)); окно сообщения при этом показывается асинхронно, а расчёт продолжается (ответ такого окна код не использует);
  • CWnd::PostMessage всегда доставляет сообщение через очередь главного потока (у потока расчёта своего цикла событий нет);
  • строка состояния передаётся сигналом statusTextChanged (межпоточное соединение Qt) и прорежена до одного обновления в 50 мс;
  • CStatusBar::RedrawWindow/UpdateWindow/Invalidate пустые: перерисовка «хозяина» на каждом такте расчёта перерисовывала бы весь вид и замедляла счёт.

Beep вне Windows подаёт системный сигнал (QApplication::beep) вместо тона заданной частоты; в Windows — настоящий Beep.

Рисование GDI поверх QPainter

Код OnDraw видов (графики, диаграммы) рисует через CDC: MoveTo/LineTo, перья, кисти, шрифты, режимы отображения. CDC повторяет формулу GDI буквально, а не подменяет её преобразованием QPainter:

xd=round((xl−Xwo)Vext,xWext,x)+Xvo,yd=round((yl−Ywo)Vext,yWext,y)+Yvo,(3)

где (Xwo,Ywo) — начало логического окна (SetWindowOrg), (Xvo,Yvo) — начало области вывода в пикселях (SetViewportOrg), Wext и Vext — расширения окна и области (SetWindowExt, SetViewportExt). Обратный перевод (DPtoLP) — та же формула, решённая относительно xl.

Режимы:

Режим Логическая единица Расширения, которые ставит SetMapMode
MM_TEXT пиксель Wext=Vext=(1,1)
MM_HIMETRIC 0,01 мм, ось Y вверх Wext=(105,105), Vext=(px·105, −py·105), p=dpi/25,4/100
MM_LOMETRIC 0,1 мм, ось Y вверх то же с p=dpi/25,4/10
MM_ISOTROPIC, MM_ANISOTROPIC задаёт код вида расширения не меняются

Большие целые расширения (105) сохраняют точность при целочисленном представлении масштаба. Разрешение (LOGPIXELSX/Y) берётся у устройства рисования: у экрана — логическое dpi, у принтера — его собственное, поэтому печать получает правильный масштаб тем же кодом.

Почему не QPainter::setWindow/setViewport: толщина пера и высота шрифта в GDI заданы в логических единицах и пересчитываются тем же масштабом. Повторяя формулу, слой получает те же целые пиксели, что и Windows-версия, — толщину линии, шаг сетки, положение подписи.

Перевод объектов рисования:

  • перо — цвет, стиль PS_* → Qt::PenStyle, толщина wpx=wlog·|sx|; меньше 1 пикселя — «косметическое» перо в один пиксель (как перо толщиной 0 в GDI);
  • кисть — сплошная заливка или «пустая» кисть;
  • шрифт (LOGFONT) — высота hpx=|lfHeight|·|sy|, насыщенность, курсив, подчёркивание; гарнитура заменяется (Windows-сборка: Courier → JetBrains Mono, остальные → Inter; вне Windows — исходное имя и метрически совместимые замены Liberation, Nimbus, DejaVu);
  • текст — TextOut(x, y) в GDI ставит строку левым верхним углом в точку, в Qt отсчёт идёт от базовой линии, поэтому строка рисуется на yd+ascent; в режиме OPAQUE под текстом заливается прямоугольник цвета фона. Строки перекодируются из CP1251. GetTextExtent и GetTextMetrics возвращают размеры в логических единицах.

Поддерживаются: MoveTo, LineTo, Polyline, Rectangle, Ellipse, FillSolidRect, PatBlt (BLACKNESS, WHITENESS, иначе цвет кисти), TextOut, GetTextExtent, GetTextMetrics, SetTextColor, SetBkColor, SetBkMode, GetClipBox, SelectObject, SelectStockObject (чёрное/белое/пустое перо и кисть), LPtoDP/DPtoLP, GetDeviceCaps. Палитры (SelectPalette, RealizePalette) — пустые: поверхность Qt всегда полноцветная.

Цвета темы

В Windows-сборке (TMC_QT_WIN) CDC перекрашивает только стандартные цвета VGA, которыми код видов рисует по умолчанию, в палитру оформления пакета: белый и чёрный фон → тёмный фон, чёрная линия → светлая, серая сетка → цвет линий, чистые красный, зелёный, синий и т. д. → акцентные цвета. Цвет, выбранный пользователем в настройках (любой другой), выводится как есть; координаты и данные не меняются. Дополнительно в Windows-сборке включено сглаживание, цветные перья толщиной в пиксель рисуются толщиной 1,7 пикселя, высота шрифта умножается на 0,9 (Inter шире Times/Arial), а строки-числа выводятся JetBrains Mono размером 0,78 от исходного. Вне Windows-сборки цвета и шрифты не меняются.

Текст поверх OpenGL

Вид OpenGL рисует сцену через OpenGL, но сообщения выводит обычным TextOut. В режиме SetDeferText(true) (его включает MfcGLWidget) или без QPainter надписи запоминаются (deferredText(), координаты в пикселях) и выводятся виджетом поверх готового кадра.

OpenGL (wgl)

В Windows-сборке функции wgl*, ChoosePixelFormat, SwapBuffers настоящие (из системы), а mfc_wgl.cpp пуст. Вне Windows (FieldView из src/fieldview) контекстом OpenGL владеет QOpenGLWidget: он создан и сделан текущим до paintGL, а буферы меняются сами. Поэтому wglCreateContext/wglGetCurrentContext/ wglGetCurrentDC возвращают общую ненулевую метку, остальные функции — «успех», а DescribePixelFormat описывает то, что даёт Qt: RGBA 32 бита, глубина 24 бита, двойная буферизация. Отрисовка (glBegin, glVertex3f, матрицы) — настоящая, из системного OpenGL, в совместимом профиле 2.1.

Математика из ucrtbase.dll

Расчёт, собранный компилятором MSVC, берёт sin, cos, exp, atan2 … из системной библиотеки UCRT (ucrtbase.dll). Библиотека MinGW округляет последний бит иначе, и числа в выходных файлах .s, .AMP, .FAZ расходились бы в младших разрядах. ucrt_libm_win.cpp определяет sin, cos, tan, asin, acos, atan, sinh, cosh, tanh, exp, log, log10, atan2, pow, fmod как вызовы одноимённых функций ucrtbase.dll (адрес находится при первом вызове и кэшируется), а sincos — через них же (g++ объединяет sin(x) и cos(x) одного аргумента в один вызов). Формулы и порядок вычислений не меняются. Если ucrtbase.dll не найдена, программа показывает сообщение и завершается с кодом 99.

macOS: что заменяет систему

Версия для macOS собрана из того же кода и того же слоя MFC, что версия для Linux, но вместо вызовов /proc и glibc стоят средства Mach и libSystem. Код: github.com/klimov-kn/TMC_Suite_MacOS.

Файл Что делает на macOS
include/tmc_win32_posix.h время потока — thread_info, память процесса — task_info, свободная память — host_statistics64 и sysctl, имя процессора — machdep.cpu.brand_string, командная строка — _NSGetArgv, признак завершения потока — pthread_kill с сигналом 0
include/tmc_dlopen.h LoadLibraryA("OpenCL.framework") загружает системную рамку /System/Library/Frameworks/OpenCL.framework
include/tmc_fileflag.h признак «кадр прочитан» в расширенном атрибуте com.tmc.read_stamp
include/tmc_win_prelude.h подмена fopen препроцессором: компоновщик Apple не знает --wrap; sprintf через vsnprintf: в SDK macOS он объявлен устаревшим
tmc_textmode.cpp поток со своими функциями обмена создаёт funopen
tmc_mfc_doc.cpp свой путь — _NSGetExecutablePath; соседние программы ищутся как пакеты .app рядом с программой и в /Applications и запускаются через /usr/bin/open, редактор — open -e (TextEdit)

Пакеты .app

Функция tmc_mac_bundle (build/macos/TmcMacBundle.cmake) делает из цели CMake пакет: Info.plist из образца build/macos/Info.plist.in, значок .icns, типы файлов для Finder, rpath на Contents/Frameworks. Библиотеки Qt и OpenCASCADE вкладывает installer/macdeploy.py: он заменяет macdeployqt, который на сборочной машине с Linux не запускается, правит пути загрузки и ставит простую подпись. Без подписи файл на Apple Silicon не запускается.

Полоса меню и файлы из Finder

gui_common/menuroles.cpp задаёт роли пунктов меню: в меню программы уходят только «О программе» и «Выход», остальное остаётся на местах Windows-версии. Роли ставятся по номеру команды, а не по тексту: иначе перевод интерфейса менял бы состав меню. gui_common/fileopenfilter.h принимает событие QEvent::FileOpen: двойной щелчок в Finder передаёт файл им, а не командной строкой.

Значки

Значки программ лежат в src/resources/icons/macos: на холсте 1024 плитка 824 с полем 100 и тенью, по сетке Apple. Каждый размер от 16 до 1024 точек, в том числе вторые размеры для Retina (ic11…ic14, ic10), нарисован из вектора. Значок в Dock берётся из .icns: программа его не заменяет. Значки панелей векторные, поэтому на экранах Retina рисуются в двойном разрешении; нужны модули Qt iconengines и imageformats, они есть в пакете.

Linux: что заменяет систему

Версия для Linux собрана из того же кода и того же слоя MFC, но системные вызовы Windows там заменены своими. Код: репозиторий TMC_Suite_Linux_GUI, папка src/compat. Всё перечисленное ниже — переносимость: на вычисления не влияет.

Файл Что заменяет
include_posix/windows.h, io.h, psapi.h системные заголовки Windows: ведут в слой совместимости
include/tmc_win32_posix.h функции Windows API на POSIX
include/tmc_dlopen.h LoadLibraryA, GetProcAddress, FreeLibrary через dlopen: так загружается OpenCL
include/tmc_fileflag.h признак «архивный»
tmc_textmode.cpp текстовый режим файлов и поиск имени без учёта регистра
include/tmc_win_prelude.h имена MSVC CRT: _snprintf, _stricmp, _access, _finite, __int64, разделитель каталогов TMC_IS_SEP и TMC_PATH_SEP

Функции Windows API на POSIX

tmc_win32_posix.h даёт коду расчёта то, что он ждёт от Windows. Часы и время: QueryPerformanceCounter, GetLocalTime, GetThreadTimes — для отчёта -Time. Сведения о машине: GetSystemInfo, GlobalMemoryStatusEx, название процессора из /proc/cpuinfo. Память процесса: GetProcessMemoryInfo. Критические секции — рекурсивный pthread_mutex. Командная строка: GetCommandLineA читает /proc/self/cmdline. Полный путь: GetFullPathNameA. Ожидание потоков: WaitForMultipleObjects. Вывод пакетного режима: GetStdHandle, WriteFile, WriteConsoleW пишут в стандартный вывод те же байты.

Форматы %I64d библиотека glibc не понимает, поэтому CString::Format заменяет их на %lld.

Признак «архивный»

В Windows система сама ставит бит ARCHIVE при записи файла, а снять его может программа. На этом держится слежение FieldView за расчётом: ядро записало кадр — бит взведён; FieldView прочитал кадр и снял бит — ядро может писать следующий.

В Linux такого бита нет. tmc_fileflag.h повторяет его смысл: снимая признак, программа запоминает в расширенном атрибуте user.tmc_read_stamp время изменения файла. Признак считается снятым, пока файл с тех пор не менялся. Любая новая запись снова взводит его, как в Windows.

Если файловая система расширенных атрибутов не поддерживает (раздел Windows в /mnt), признак считается взведённым: ядро не ждёт просмотрщика, иначе оно простаивало бы по 25 секунд на каждом кадре, а FieldView узнаёт новый кадр по времени и размеру файла.

Настройки и запуск программ

Настройки лежат в ~/.config/TMC_Suite/<программа>.conf. Запуск внешних программ (TmcCreateProcess) — fork и execvp; неудачный запуск ядро узнаёт через канал и сообщает о нём, как в Windows. Имена из настроек Windows переводятся: расширение .exe отбрасывается, notepad, write, wordpad, winword заменяются первым найденным текстовым редактором или xdg-open.

Текстовый режим файлов (только Linux)

В Windows fopen(…, "r") открывает поток в текстовом режиме: при чтении пара CR LF становится LF, при записи наоборот. На Linux такого режима нет, и файлы, записанные пакетом, перестали бы совпадать с файлами Windows. tmc_textmode.cpp (подключается только вне Windows вместе с флагом -Wl,--wrap=fopen) подменяет fopen всей программы:

  • режим с b — настоящий fopen без изменений (двоичные форматы, S-матрицы);
  • режим без b — двоичный поток, обёрнутый fopencookie: чтение блоками по 64 КБ удаляет все символы CR, запись заменяет каждый LF на CR LF; позиционирование — по байтам файла с CRLF;
  • имя файла ищется без учёта регистра последнего элемента пути (если точного имени нет и совпадение ровно одно).

Что поддержано и что нет

Область Поддержано Не поддержано / отличается
Строки CString (поиск, подстроки, замена, Format, склейка) освобождение памяти; CStringW
Документ путь, заголовок, флаг изменения, UpdateAllViews (как флаг) CArchive/Serialize; шаблоны документов MFC
Вид CScrollView, мышь (левая кнопка, нажатие правой), таймеры, прокрутка, печать через OnDraw OnSize у MfcViewWidget не вызывается; колёсико, клавиатура, отпускание правой кнопки виду не передаются; SetCapture намеренно ничего не делает
Диалоги разметка из .rc, OK/Отмена/крестик/Esc, кнопки из карты сообщений, DDX, таймеры, немодальные окна, страницы свойств ON_EN_CHANGE, ON_CBN_SELCHANGE, ON_LBN_SELCHANGE к полям и спискам не подключаются; ON_NOTIFY, *_RANGE; проверки DDV
Элементы поле, подпись, кнопка, флажок, переключатель, выпадающий список, список, индикатор, список с колонками, набор значков растры ресурсов (CImageList::Create(bitmapId) создаёт пустой набор)
Рисование см. GDI регионы, пути, растровые операции кроме PatBlt, BitBlt, палитры
Потоки AfxBeginThread, ожидание, код завершения, приоритеты SuspendThread; автоудаление CWinThread
Рамки CStatusBar::SetPaneText CFrameWnd, CToolBar, CMDIFrameWnd — пустые заглушки: главное окно, меню и панели строит оболочка программы на Qt

Подводные камни

Рамки групп перехватывали щелчки. В Windows рамка GROUPBOX и статическая подпись прозрачны для мыши: щелчок по кнопке внутри рамки попадает в кнопку при любом порядке элементов в .rc. В Qt щелчок получает верхний виджет, и рамка, созданная позже кнопки, перехватывала его (в окне параметров TMC_DN не нажимались «Графики», «Нормировка», «Прореживать»). Поэтому при показе окна подписи и рамки опускаются под остальные элементы, а рамки (кроме отмечаемых флажком) получают Qt::WA_TransparentForMouseEvents. Кроме того, rc2ui.py записывает виджеты в обратном порядке, а тема делает фон рамок прозрачным.

DDX_Radio и порядок Tab. Номер переключателя определяется по цепочке фокуса. Любая операция, перестраивающая её (setParent при переносе элементов в область прокрутки), обязана восстановить порядок Tab — иначе DDX_Radio читает и пишет не тот переключатель. tmcFitDialogContent запоминает порядок до переноса и восстанавливает его после.

AfxMessageBox(text) без окна. Вариант с одним аргументом раньше писал только в stderr, и во вьюверах сообщения об ошибках пропадали (кнопка выглядела неработающей). Теперь обработчик по умолчанию — окно сообщения в потоке интерфейса; из потока расчёта текст по-прежнему уходит в stderr, если программа не поставила свой обработчик.

Перевод применяется после Show. Подписи окон переводит фильтр событий приложения при QEvent::Show (gui-common). Фильтр приложения срабатывает раньше фильтра самого окна, поэтому tmcRefitAfterShow меряет уже переведённый текст. Любая подгонка размеров по тексту должна выполняться при показе или позже, а не при построении. Текст, который код ставит в подпись сам после показа (SetDlgItemText), в Windows-сборке переводится на месте; поля ввода с данными пользователя не переводятся.

Захват мыши. SetCapture вида намеренно ничего не делает: Qt и так доставляет движения нажатой мыши тому же виджету, а «забытый» захват (отпускание не дошло до вида) отправлял бы все щелчки в график, и программа выглядела бы зависшей.

Модальное окно позади главного. Окно диалога при показе поднимается и активируется; родитель — главное окно программы (tmcOwnerWindow).

DDV_MaxChars и копии строк. Обрезка выполняется на месте в буфере CString; копии, разделяющие этот буфер, тоже обрезаются.

setWidgetText и отсутствующий элемент. В Windows-сборке SetDlgItemText/CWndCtrl::SetWindowText для элемента, которого нет в разметке, разыменовывают NULL (проверка доступности поля выполняется до проверки типа).

Таймеры диалога после DoModal. Таймеры, не остановленные KillTimer до закрытия окна, удаляются вместе с окном, но остаются в таблице m_timers объекта диалога.

Compatibility layer

Purpose and place in the package

The computational code of the Qt6 version of TMC Suite (directory src/libs, src/kernels, src/viewers: kernels, libraries, the document, view and dialog classes of the programs) was historically written for MFC and uses its classes: CString, CDocument, CScrollView, CDC, CDialog, DDX_Text, AfxBeginThread and others. The compatibility layer (directory src/compat) implements these classes on Qt 6. The MFC library itself is not present in the Qt6 version: under the familiar names, what actually works is QPainter, QDialog, QThread, QTimer and a QSettings-like ini file.

The main property of the layer is that the src/libs, src/kernels, src/viewers code compiles without edits. Therefore the formulas, the order of computations, the file formats and the appearance of the plots remain the same; all that changes is what performs the window, drawing and thread calls.

Place of the layer in the build:

 src/libs, src/kernels, src/viewers (kernels, libraries, documents, views, dialogs — code on MFC classes)
        │  #include <afxwin.h>, <afx.h> …   → found in compat/include
        ▼
 compat/include  — declarations of classes and types (no Qt)
 compat/*.cpp    — implementation on Qt 6 (except tmc_mfc_doc.cpp — no Qt)
        │
        ▼
 gui_common      — view host widgets, theme, translation, printing (gui-common page)
 apps/*          — program shells: main windows, menus, starting the computation

The layer is built into three CMake targets (src/CMakeLists.txt, src/gui_common/CMakeLists.txt):

Target What it contains Who uses it
tmc_compat (INTERFACE) header directories compat/include, on Windows also compat/include_win, outside Windows — compat/include_posix all libraries and programs
tmc_platform (STATIC) tmc_mfc_doc.cpp; on Windows (MinGW) — ucrt_libm_win.cpp as an interface source; outside Windows — tmc_textmode.cpp and the flag -Wl,--wrap=fopen every program, including the compute kernels
tmc_gui_common (STATIC) mfc_gdi.cpp, mfc_view.cpp, mfc_dialog.cpp, mfc_thread.cpp, mfc_wgl.cpp + the gui_common files all graphical programs

Every src/libs, src/kernels, src/viewers file additionally gets the prelude tmc_win_prelude.h (the compiler option -include): what MSVC provided implicitly (__max, __min, the directory separator TMC_PATH_SEP, outside Windows — the _complex type).

The layer contains not a single computational formula.

Contents

File Role
include/afx.h, afxwin.h, afxext.h, afxcmn.h, afxdisp.h, afxmt.h, cstringt.h, afxdtctl.h stub MFC headers: include the required part of the layer
include/afxres.h standard framework command numbers (ID_FILE_OPEN …), bar and window styles
include/tmc_mfc.h CString, basic Windows types (outside Windows), AfxMessageBox(text)
include/tmc_winapi.h inclusion of the real windows.h in the Windows build and interception of Windows API functions that work with layer objects
include/tmc_mfc_doc.h, tmc_mfc_doc.cpp CObject, CDocument, CWinApp (settings), CCmdUI, CException, colors, LOGFONT, launching package programs
include/mfc_gdi.h, mfc_gdi.cpp drawing: CDC, CPen, CBrush, CFont, CPoint, CSize, CRect
include/mfc_view.h, mfc_view.cpp windows and views: CWnd, CView, CScrollView, CClientDC, the bridge interface MfcQtHost
include/mfc_dialog.h, mfc_dialog.cpp dialogs, controls, DDX/DDV, message maps, property pages, common dialogs, layout registry
include/mfc_thread.h, mfc_thread.cpp threads CWinThread/AfxBeginThread, waiting with event pumping
include/mfc_wgl.h, mfc_wgl.cpp CPalette; outside Windows — stubs of wgl* and the pixel format
include/tmc_win_prelude.h prelude for every src/libs, src/kernels, src/viewers file
ucrt_libm_win.cpp Windows (MinGW): sin, cos, exp, pow … from ucrtbase.dll
include_win/execinfo.h Windows: a backtrace/alarm stub for the interface testing tools (not included in the distribution)
tmc_textmode.cpp Linux build only: text mode of fopen (CRLF) and case-insensitive file lookup
include_posix/windows.h, io.h, conio.h, gl/gl.h, gl/glu.h Linux build only: stubs of the Windows system headers

afxdtctl.h is included by a single file — src/fieldview/stdafx.h, and that FieldView is built only outside Windows; in the Windows build the field is shown by apps/fieldview_rhi.

Stub headers

The src/libs, src/kernels, src/viewers code includes <afxwin.h>, <afx.h>, <windows.h> and so on. The compat/include directory comes first in the search path, so these names find the layer files, and those in turn include what is needed:

afxwin.h ─► mfc_thread.h ─► mfc_dialog.h ─► mfc_view.h ─► mfc_gdi.h ─► tmc_mfc_doc.h ─► tmc_mfc.h
        └─► mfc_wgl.h                     └─► afxres.h                                   └─► tmc_winapi.h (Windows)

All layer files take effect under the condition !defined(_WIN32) || defined(TMC_QT_WIN): always outside Windows, and on Windows — in the Qt6 version build (the macro TMC_QT_WIN is set by the root CMakeLists.txt).

In the Windows build the Windows API types and functions (BOOL, DWORD, HANDLE, RECT, COLORREF, CreateFile, Sleep …) are the real ones — from windows.h. The layer declares them itself only outside Windows (#ifndef _WIN32 branches). The compat/include_posix directory with the stubs windows.h, io.h, conio.h, gl/*.h is included only outside Windows, so as not to shadow the real system headers under MinGW.

Strings and basic types

CString (tmc_mfc.h) is a trivially copyable class with a single member char*. This is an ABI requirement: the src/libs, src/kernels, src/viewers code passes CString to printf/Format through "%s" as a variadic argument. An object equal in size and layout to a single pointer is placed on the stack the same way as in MFC, and "%s" reads exactly the pointer. If CString were a wrapper around std::string, the compiler would pass it by a hidden reference and garbage would appear in the output string. This property is enforced by static_assert(std::is_trivially_copyable<CString>).

Consequences:

  • every change of a string allocates a new buffer with malloc; the previous one is not freed (a destructor would make the type non-trivial). The amount leaked is small: the strings in the package code are file names and captions;
  • a copy of a CString shares the buffer with the original; methods that change the string create a new buffer, so copies are not affected — except DDV_MaxChars, which truncates the buffer in place (see pitfalls);
  • all positions and lengths are in bytes; the encoding of strings in the code is CP1251.

AfxMessageBox(text) with one argument calls the handler installed by tmc_set_message_handler. By default (mfc_dialog.cpp) this is a message box in the interface thread; from another thread or without a graphical application the text is written to stderr. The kernel shells install their own handler (apps/planarrt_common/mainwindow.cpp). The variant AfxMessageBox(text, type) with buttons is described in the section on dialogs.

Interception of Windows API functions

In the Windows build the API is the real one, but several functions work with objects of the layer rather than of the system. tmc_winapi.h redefines their names with macros — the src/libs, src/kernels, src/viewers code stays the same, and the call goes to the layer:

Call in the code Implementation What it does
PeekMessage, TranslateMessage, DispatchMessage mfc_thread.cpp process the accumulated Qt events (up to 10 ms); PeekMessage always answers "no messages"
WaitForSingleObject, MsgWaitForMultipleObjects, GetExitCodeThread mfc_thread.cpp waiting for and the exit code of the layer threads (QThread)
GetDeviceCaps mfc_gdi.cpp resolution and size of the Qt device / the primary screen
CreateProcess tmc_mfc_doc.cpp the name of a neighboring package program (TMCROS.EXE, FLDVIEW.EXE, PLANRT_H.EXE …) is translated into the name of the Qt version next to the current program; everything else goes to the real CreateProcessA
PostMessage, IsWindow mfc_view.cpp a message to a layer window is passed to the program's handler (tmc_set_post_message_handler; for the kernels — closing the main window after a batch computation, planrt_compat.cpp); IsWindow only checks that the handle is not null

Translation of the program name (TmcResolveProgramName): an existing path is not changed; otherwise the directory and .exe are dropped, the name is converted to lower case, fldview → fieldview, planrt_h/planrt_x → planarrt_h/planarrt_x, and the program is looked up in the directory of the current one. If the file is not there, on Windows the original name is launched (search through PATH; this is how NOTEPAD.EXE is opened).

The macro replaces the name everywhere, including a method name: CDC::GetDeviceCaps and CWnd::PostMessage in the Windows build are actually called TmcGetDeviceCaps and TmcPostMessage. This is invisible to the calling code but visible in the debugger.

INPUT from winuser.h is renamed while windows.h is being included: the TMC task structure (run.h) has the same name.

.rc resources → Qt dialogs

A dialog of the Windows version consists of two parts: the layout in the .rc resource and the behavior in the class (DoDataExchange, button handlers, OnInitDialog). The layer preserves both.

Layout: from .rc to a build function

The layout is converted by the script tools/rc2ui.py (run when preparing the sources, not during the build):

  1. Reads the .rc (CP1251) and resource.h. Each DIALOG/DIALOGEX block becomes a file IDD_<name>.ui with controls at absolute coordinates, without layouts.
  2. Coordinates are converted from dialog units to pixels using the TMC dialog font "MS Sans Serif 8" at 96 dpi:
xpx=xdu·64=1,5xdu,ypx=ydu·138=1,625ydu.(1)
  1. The objectName of each widget is the symbolic name of the control from resource.h (IDC_GRPAR_XMAX). If one number is defined by several names, the first one in the file is taken.
  2. Widgets are written in reverse order (in Windows the control written earlier lies on top; in Qt — the one created later), and the Tab order is restored by the <tabstops> section in the .rc writing order.
  3. Radio buttons are divided into groups by WS_GROUP and get a QButtonGroup.
  4. apps/<program>/dialogs/dialog_registry.cpp is generated: it includes ui_*.h (produced by uic) and registers in MfcDialogRegistry the pairs "dialog number → setupUi function" and "control number → symbolic name" for all definitions in resource.h.

Building the window

CDialog::DoModal() (modal window) and CDialog::Create() (modeless) create TmcModalDialog — a descendant of QDialog that knows its MFC dialog — and call CDialog::TmcBuildIn():

  1. the layout function from the registry builds the widgets;
  2. the buttons with numbers IDOK and IDCANCEL are connected to OnOK() and OnCancel();
  3. the message map of the class (TmcBuildMessageMap) is built, and each command entry is connected to the clicked signal of the control with the same number — only if the control is a button (QAbstractButton);
  4. OnInitDialog(), then UpdateData(FALSE) — variable values go into the controls, as in MFC;
  5. tmcFitDialogContent() — preparation for fitting (below).

Then the window decorator tmc_dialog_decorator() is called (if installed; this is how the About dialog gets uniform content — see gui-common), and the window is shown. If no layout is registered for the dialog number, DoModal writes a message to stderr and returns IDCANCEL, Create returns FALSE.

A control is found by number as follows: number → symbolic name (registry) → QDialog::findChild<QWidget*>(name). Therefore GetDlgItem(IDC_EDIT1) in the Windows version code keeps working. GetDlgItem returns a CWndCtrl wrapper (cached in the dialog); if there is no such control, the wrapper is empty and its methods do nothing.

Texts between the code and the widgets are re-encoded: CP1251 → Unicode on writing, Unicode → CP1251 on reading (characters outside CP1251 become ?).

Closing the window:

User action Call
OK button OnOK() → UpdateData(TRUE) → EndDialog(IDOK)
"Cancel" button, Esc key OnCancel() → EndDialog(IDCANCEL)
window close button OnClose() → by default EndDialog(IDCANCEL)

DoModal returns IDOK only if the window was closed through EndDialog(IDOK). A modeless window lives until DestroyWindow() (then GetSafeHwnd() returns NULL again, and the Windows version code creates the window anew) or until the dialog object is deleted.

OnPaint() of a dialog is called after every repaint of the window — this is how dialogs draw color and line samples. Drawing on top of a control outside a repaint (GetDlgItem(id)->GetDC()) goes into an image the size of the control; ReleaseDC puts it into the label control (QLabel::setPixmap).

AfxMessageBox(text, type) shows a QMessageBox with the buttons MB_OK, MB_OKCANCEL or MB_YESNO and the icon MB_ICON*, and returns IDOK, IDCANCEL, IDYES or IDNO. Without a graphical application it answers IDYES/IDOK.

Window fitting

The .rc coordinates are designed for the Windows font and English captions. So that nothing gets clipped, the layer fits the window in two stages.

At build time (tmcFitDialogContent): all controls are moved into a content widget inside a QScrollArea (positions are preserved); the Tab order remembered before the move is restored; the window gets a size based on the content, but not more than 95 % of the width and 92 % of the height of the screen, and can be resized.

On first show (TmcDialogFitter → tmcRefitAfterShow), when the theme and the translation have already been applied:

  1. labels and group frames are lowered beneath the other controls, frames let the mouse through (pitfalls);
  2. uniform stretching to fit the text (tmcScaleForText): for each control the required width wineed and height hineed are computed (text + margins; for buttons the height is at least 28 pixels), and the whole layout is multiplied by
sx=min(1,7, maxiwineedwi),sy=min(1,7, maxihineedhi)(2)

(only if at least one of them is greater than 1) — the relative placement is preserved; 3. multiline fields up to 40 pixels high lose their inner margins and scroll bars; 4. an empty label of size 16–64 pixels gets the program icon (the ICON element of the resource); 5. labels and buttons that still lack space are widened to the right — up to the nearest neighbor in the same row (tmcGrowLabels); 6. the window gets its final size (within the same screen limits).

The environment variable TMC_DIALOG_DEBUG prints the sizes and coefficients to stderr.

Property pages

CPropertySheet::DoModal() builds a QDialog with a QTabWidget and the OK / Cancel / Apply buttons. Each CPropertyPage is built by its own TmcBuildIn in a separate QDialog, which becomes a tab. The tab caption is the window title from the resource, otherwise m_strCaption, otherwise "Page N"; identical captions of pages from one template are numbered ("Melody 1", "Melody 2"). Switching tabs calls OnKillActive of the previous page and OnSetActive of the new one (returning FALSE from OnKillActive does not prevent the switch). Apply and OK call UpdateData(TRUE) and OnApply() on all pages. The Apply button is enabled as long as at least one page is marked with SetModified(TRUE).

Common dialogs

Class Implementation
CFileDialog QFileDialog::getOpenFileName/getSaveFileName; the MFC filter "Description|pattern||" is converted into a Qt filter; the path is in the local 8-bit encoding
CColorDialog Windows build — the tmcPickColor window (gui-common); otherwise QColorDialog
CFontDialog QFontDialog; the result is written to LOGFONT (height — minus pixels or points)

Message map

In MFC the macros BEGIN_MESSAGE_MAP … END_MESSAGE_MAP built a static table of pointers to methods. In the layer they expand into a virtual method that fills the MfcMessageMap table with closures:

// Windows version code                      // What it expands into
BEGIN_MESSAGE_MAP(CMyDlg, CDialog)           void CMyDlg::TmcBuildMessageMap(MfcMessageMap& tmcMap)
    ON_BN_CLICKED(IDC_APPLY, OnApply)        {   CDialog::TmcBuildMessageMap(tmcMap);
    ON_MESSAGE(WM_USER + 1, OnBye)               tmcMap.add(IDC_APPLY, [this]{ this->OnApply(); });
END_MESSAGE_MAP()                                tmcMap.addMessage(UINT(WM_USER + 1), …OnBye…);
                                             }

DECLARE_MESSAGE_MAP() declares this method in the class. The map of the base class is called first, so the entries of the derived class override it.

The table has three kinds of entries:

Macros Table Who calls
ON_COMMAND, ON_BN_CLICKED, ON_STN_CLICKED, ON_EN_CHANGE, ON_CBN_SELCHANGE, ON_LBN_SELCHANGE command → void() dialog: the clicked signal of the button with the same number; program shells: menu and toolbar items
ON_UPDATE_COMMAND_UI command → void(CCmdUI*) tmccmd::updateActions before a menu is shown (gui-common)
ON_MESSAGE message → LRESULT(WPARAM, LPARAM) CWnd::SendMessage (immediately) and CWnd::PostMessage (through the main thread queue)

The map is rebuilt on every use (building a dialog, SendMessage, polling command states) — it is cheap and always reflects the current object.

Not supported (expand to nothing): ON_COMMAND_RANGE, ON_UPDATE_COMMAND_UI_RANGE, ON_NOTIFY. The ON_WM_* macros (ON_WM_TIMER, ON_WM_SIZE, ON_WM_LBUTTONDOWN …) are empty: these events arrive through virtual methods of the view and the dialog, which are called by the host widget.

tmc_mfc_doc.h has an "empty" variant of the same macros for code without windows (documents, kernels); mfc_dialog.h redefines them with working ones.

DDX/DDV data exchange

UpdateData(bSave) creates a CDataExchange with a direction and calls the DoDataExchange of the class. The DDX_* functions find the widget through GetDlgItem:

Function Widget Writing to the control Reading from the control
DDX_Text (CString, char*) edit field, label, button, list, multiline field CP1251 → Unicode Unicode → CP1251
DDX_Text (int, UINT, long) the same %d toInt(); non-numeric text → 0
DDX_Text (double, float) the same %g toDouble(); non-numeric text → 0
DDX_Check check box 0/1 0/1
DDX_Radio radio button group index of the checked one index of the checked one, -1 — none
DDX_CBIndex, DDX_LBIndex combo box / list box item index item index
DDX_Control any binds a wrapper variable to the widget —

DDX_Radio. In MFC the value is the index of the radio button in the group that starts with the control having WS_GROUP, in the order of writing in the .rc; the control numbers need not be consecutive (in TMC_DN "RP" = 1048, "RP, dB" = 1053). The layer takes the group from the QButtonGroup of the layout, and the order from the focus chain, starting with the first radio button: the chain is built in the .rc order (which is why window fitting preserves the Tab order). Radio buttons of the group that are not in the chain go to the end. If there is no group, the controls id, id+1, … are iterated while they exist.

DDV checks show no windows and do not interrupt the exchange: DDV_MaxChars truncates the string, DDV_MinMax* do nothing. UpdateData always returns TRUE.

Document and view

The document classes of the programs (CTMCGROUTDoc and others) derive from CDocument (tmc_mfc_doc.h) — without windows: the file path (on Windows converted to a full path with backslashes, as in MFC), the title, the modified flag and the "views need to be repainted" flag (UpdateAllViews sets it, the shell clears it with TakeViewsDirty). The document reads and writes files with its own code through FILE*; MFC serialization (CArchive) is not used. Document and view objects are created by the program shell through the factory TmcCreate(), which is added by DECLARE_DYNCREATE.

The view (CScrollView and descendants, mfc_view.h) knows nothing about Qt. Everything it needs from the window it gets through the MfcQtHost interface, which is implemented by the host widget from gui_common (MfcViewWidget, for OpenGL — MfcGLWidget):

        Qt events                          view calls
QAbstractScrollArea ─┐                ┌─ Invalidate / UpdateWindow ─► hostInvalidate / hostUpdateWindow
  paintEvent ────────┼─► OnPrepareDC  │  SetTimer / KillTimer ───────► hostSetTimer / hostKillTimer
  mouse*Event ───────┼─► OnLButton*   │  MessageBox ─────────────────► hostMessageBox
  timerEvent ────────┼─► OnTimer      │  SetScrollSizes ─────────────► hostSetScrollSizes
                     │   OnDraw(CDC*) │  CStatusBar::SetPaneText ────► hostSetStatusText
   MfcViewWidget  ◄──┴── CScrollView ─┘
   (MfcQtHost)

Life cycle: the shell creates the document and the view, the widget calls setView(view) (the view gets the host through SetHost), and after it has received its size — initialUpdate() → OnInitialUpdate() (once). On every repaint the widget creates a CDC over its QPainter, calls OnPrepareDC (mapping mode and scroll offset) and OnDraw. When deleted, the widget detaches the view (SetHost(nullptr)); while there is no host, the window calls of the view do nothing.

The view receives mouse coordinates in pixels of the content (taking scrolling into account) and itself converts them to logical ones through CClientDC + DPtoLP. CClientDC has no canvas — it is only the MM_HIMETRIC scale at the window resolution.

CScrollView converts sizes and the scroll position between logical units and pixels: for MM_HIMETRIC (0.01 mm, Y axis upward) the number of pixels per unit is p=dpi/25,4/100, and the Y position gets the opposite sign; for the other modes — 1:1. In OnPrepareDC the viewport origin is shifted by (−xscroll,−yscroll) — this is how the content "slides" under the scroll bar.

Program settings

CWinApp::GetProfileString/WriteProfileString/GetProfileInt/WriteProfileInt work with an ini file instead of the registry: Windows — %APPDATA%\TMC_Suite_Qt\<program>.conf, Linux — ~/.config/TMC_Suite/<program>.conf. The program name is set by the shell (CWinApp::SetAppName). The file is read into memory on first access; each write re-reads the file and rewrites it entirely — values written by another instance of the program are not lost. A write error is not reported. If on Windows there is no file at the new path, but there is one at the old erroneous path <APPDATA>TMC_Suite_Qt\… (without a separator), the file is copied.

Out of memory in new throws CMemoryException*, as in MFC: the new handler is installed by a static object in tmc_mfc_doc.cpp, and the computation code catches catch (CException* e) and ends the step with an error code.

Timers

Where How it works Firing
view (CWnd::SetTimer) the host starts QObject::startTimer and stores the pair "Qt number → MFC number" timerEvent of the host → OnTimer(MFC number) of the view
dialog (CDialog::SetTimer) a QTimer — a child object of the dialog window; starting the same number again restarts the timer OnTimer(id) of the dialog

Timers run in the interface thread; a callback function (the third parameter of SetTimer) is not supported. A dialog timer can be started only when the window exists (SetTimer from OnInitDialog — yes, from the constructor — no, 0 is returned).

Threads

The compute kernels start the computation the same way as in the Windows version: AfxBeginThread(RunAllGlobal, pDoc, priority, 0, CREATE_SUSPENDED), then ResumeThread(). The layer creates a CWinThread with an internal QThread (MfcThread::run() calls the thread function and stores the return code):

  • the handle m_hThread is a pointer to the internal thread; the wait functions use it to find the thread in the table;
  • the Windows priority is remembered and passed to QThread::start (<= LOWEST → LowestPriority, BELOW_NORMAL → LowPriority, NORMAL, ABOVE_NORMAL → HighPriority, >= HIGHEST → HighestPriority): Qt cannot set the priority of a thread that has not been started;
  • SuspendThread is not supported — the computation is stopped by a flag in the computation class (Stop()), as in the Windows version;
  • WaitForSingleObject waits for the thread without processing events; MsgWaitForMultipleObjects waits in short steps, processing Qt events between them in portions of up to 20 ms — the window does not "freeze" while closing waits for the computation to end;
  • GetExitCodeThread returns 259 (STILL_ACTIVE) while the thread is running, then the return code of the thread function.

The order of computations does not depend on this: the thread executes the same function with the same data.

Window calls from the computation thread. The Windows version code calls Invalidate, RedrawWindow, MessageBox and the status bar from the computation thread. In Qt widgets may be touched only from the main thread, therefore:

  • hostInvalidate, hostUpdateWindow, hostMessageBox of the view host, when called not from the main thread, queue the action into the main thread (QMetaObject::invokeMethod(…, Qt::QueuedConnection)); the message box is then shown asynchronously, and the computation continues (the code does not use the answer of such a box);
  • CWnd::PostMessage always delivers the message through the queue of the main thread (the computation thread has no event loop of its own);
  • the status bar text is passed by the statusTextChanged signal (a cross-thread Qt connection) and thinned out to one update per 50 ms;
  • CStatusBar::RedrawWindow/UpdateWindow/Invalidate are empty: repainting the "host" on every time step of the computation would repaint the whole view and slow down the computation.

Beep outside Windows plays the system signal (QApplication::beep) instead of a tone of the given frequency; on Windows — the real Beep.

GDI drawing on top of QPainter

The OnDraw code of the views (plots, diagrams) draws through CDC: MoveTo/LineTo, pens, brushes, fonts, mapping modes. CDC reproduces the GDI formula literally rather than replacing it with a QPainter transformation:

xd=round((xl−Xwo)Vext,xWext,x)+Xvo,yd=round((yl−Ywo)Vext,yWext,y)+Yvo,(3)

where (Xwo,Ywo) is the origin of the logical window (SetWindowOrg), (Xvo,Yvo) is the viewport origin in pixels (SetViewportOrg), Wext and Vext are the extents of the window and the viewport (SetWindowExt, SetViewportExt). The inverse conversion (DPtoLP) is the same formula solved for xl.

Modes:

Mode Logical unit Extents set by SetMapMode
MM_TEXT pixel Wext=Vext=(1,1)
MM_HIMETRIC 0.01 mm, Y axis upward Wext=(105,105), Vext=(px·105, −py·105), p=dpi/25,4/100
MM_LOMETRIC 0.1 mm, Y axis upward the same with p=dpi/25,4/10
MM_ISOTROPIC, MM_ANISOTROPIC set by the view code extents are not changed

Large integer extents (105) preserve precision when the scale is represented by integers. The resolution (LOGPIXELSX/Y) is taken from the drawing device: for the screen — the logical dpi, for a printer — its own, so printing gets the correct scale with the same code.

Why not QPainter::setWindow/setViewport: the pen width and the font height in GDI are specified in logical units and are converted with the same scale. By reproducing the formula, the layer gets the same integer pixels as the Windows version — the line width, the grid spacing, the label position.

Conversion of drawing objects:

  • pen — color, style PS_* → Qt::PenStyle, width wpx=wlog·|sx|; less than 1 pixel — a one-pixel "cosmetic" pen (like a pen of width 0 in GDI);
  • brush — solid fill or a "null" brush;
  • font (LOGFONT) — height hpx=|lfHeight|·|sy|, weight, italic, underline; the typeface is substituted (Windows build: Courier → JetBrains Mono, others → Inter; outside Windows — the original name and the metric-compatible substitutes Liberation, Nimbus, DejaVu);
  • text — TextOut(x, y) in GDI places the string with its top-left corner at the point, in Qt the reference is the baseline, so the string is drawn at yd+ascent; in OPAQUE mode a rectangle of the background color is filled under the text. Strings are re-encoded from CP1251. GetTextExtent and GetTextMetrics return sizes in logical units.

Supported: MoveTo, LineTo, Polyline, Rectangle, Ellipse, FillSolidRect, PatBlt (BLACKNESS, WHITENESS, otherwise the brush color), TextOut, GetTextExtent, GetTextMetrics, SetTextColor, SetBkColor, SetBkMode, GetClipBox, SelectObject, SelectStockObject (black/white/null pen and brush), LPtoDP/DPtoLP, GetDeviceCaps. Palettes (SelectPalette, RealizePalette) are empty: a Qt surface is always full-color.

Theme colors

In the Windows build (TMC_QT_WIN) CDC recolors only the standard VGA colors that the view code draws with by default into the package theme palette: white and black background → dark background, black line → light one, gray grid → line color, pure red, green, blue and so on → accent colors. A color chosen by the user in the settings (any other) is output as is; coordinates and data are not changed. In addition, in the Windows build antialiasing is enabled, colored pens one pixel wide are drawn 1.7 pixels wide, the font height is multiplied by 0.9 (Inter is wider than Times/Arial), and number strings are output in JetBrains Mono at 0.78 of the original size. Outside the Windows build colors and fonts are not changed.

Text on top of OpenGL

An OpenGL view draws the scene through OpenGL but outputs messages with the ordinary TextOut. In SetDeferText(true) mode (it is enabled by MfcGLWidget) or without a QPainter the captions are remembered (deferredText(), coordinates in pixels) and are output by the widget on top of the finished frame.

OpenGL (wgl)

In the Windows build the functions wgl*, ChoosePixelFormat, SwapBuffers are the real ones (from the system), and mfc_wgl.cpp is empty. Outside Windows (FieldView from src/fieldview) the OpenGL context is owned by QOpenGLWidget: it is created and made current before paintGL, and the buffers are swapped automatically. Therefore wglCreateContext/wglGetCurrentContext/ wglGetCurrentDC return a common non-null token, the other functions return "success", and DescribePixelFormat describes what Qt provides: RGBA 32 bits, depth 24 bits, double buffering. Rendering (glBegin, glVertex3f, matrices) is real, from the system OpenGL, in the 2.1 compatibility profile.

Math from ucrtbase.dll

A computation built with the MSVC compiler takes sin, cos, exp, atan2 … from the system UCRT library (ucrtbase.dll). The MinGW library rounds the last bit differently, and the numbers in the output files .s, .AMP, .FAZ would differ in the least significant digits. ucrt_libm_win.cpp defines sin, cos, tan, asin, acos, atan, sinh, cosh, tanh, exp, log, log10, atan2, pow, fmod as calls to the functions of the same name in ucrtbase.dll (the address is found on the first call and cached), and sincos through them as well (g++ fuses sin(x) and cos(x) of the same argument into a single call). Formulas and the order of computations do not change. If ucrtbase.dll is not found, the program shows a message and exits with code 99.

macOS: what replaces the system

The macOS edition is built from the same code and the same MFC layer as the Linux edition, with Mach and libSystem instead of /proc and glibc calls. Code: github.com/klimov-kn/TMC_Suite_MacOS.

File What it does on macOS
include/tmc_win32_posix.h thread time — thread_info, process memory — task_info, free memory — host_statistics64 and sysctl, processor name — machdep.cpu.brand_string, command line — _NSGetArgv, finished-thread check — pthread_kill with signal 0
include/tmc_dlopen.h LoadLibraryA("OpenCL.framework") loads the system framework /System/Library/Frameworks/OpenCL.framework
include/tmc_fileflag.h the "frame read" mark in the extended attribute com.tmc.read_stamp
include/tmc_win_prelude.h fopen is replaced by the preprocessor: the Apple linker has no --wrap; sprintf goes through vsnprintf: the macOS SDK declares it deprecated
tmc_textmode.cpp a stream with its own exchange functions is created by funopen
tmc_mfc_doc.cpp own path — _NSGetExecutablePath; neighbour programs are looked for as .app bundles next to the program and in /Applications and started through /usr/bin/open, the editor — open -e (TextEdit)

.app bundles

The function tmc_mac_bundle (build/macos/TmcMacBundle.cmake) makes a bundle of a CMake target: Info.plist from the template build/macos/Info.plist.in, the .icns icon, file types for Finder, rpath to Contents/Frameworks. Qt and OpenCASCADE are put in by installer/macdeploy.py: it replaces macdeployqt, which does not run on a Linux build machine, fixes the load paths and sets a simple signature. Without a signature a file does not start on Apple Silicon.

Menu bar and files from Finder

gui_common/menuroles.cpp sets the roles of menu items: only About and Quit go to the application menu, the rest stays where it is in the Windows edition. Roles are set by command number, not by text: otherwise translating the interface would change the menus. gui_common/fileopenfilter.h takes the QEvent::FileOpen event: a double click in Finder passes the file there, not on the command line.

Icons

Program icons are in src/resources/icons/macos: on a 1024 canvas, an 824 tile with a margin of 100 and a shadow, on the Apple grid. Every size from 16 to 1024 points, including the second sizes for Retina (ic11…ic14, ic10), is drawn from the vector source. The Dock icon comes from the .icns file: the program does not replace it. Toolbar icons are vector, so on Retina displays they are drawn at double resolution; this needs the Qt modules iconengines and imageformats, which are in the bundle.

Linux: what replaces the system

The Linux edition is built from the same code and the same MFC layer, but the Windows system calls are replaced there. The code is in the TMC_Suite_Linux_GUI repository, folder src/compat. Everything below is portability: it does not affect the calculation.

File What it replaces
include_posix/windows.h, io.h, psapi.h Windows system headers: they lead into the compatibility layer
include/tmc_win32_posix.h Windows API functions on POSIX
include/tmc_dlopen.h LoadLibraryA, GetProcAddress, FreeLibrary through dlopen: this is how OpenCL is loaded
include/tmc_fileflag.h the "archive" mark
tmc_textmode.cpp text file mode and case-insensitive file name lookup
include/tmc_win_prelude.h MSVC CRT names: _snprintf, _stricmp, _access, _finite, __int64, the directory separators TMC_IS_SEP and TMC_PATH_SEP

Windows API functions on POSIX

tmc_win32_posix.h gives the calculation code what it expects from Windows. Clocks and time: QueryPerformanceCounter, GetLocalTime, GetThreadTimes, for the -Time report. Machine information: GetSystemInfo, GlobalMemoryStatusEx, the processor name from /proc/cpuinfo. Process memory: GetProcessMemoryInfo. Critical sections are a recursive pthread_mutex. Command line: GetCommandLineA reads /proc/self/cmdline. Full path: GetFullPathNameA. Waiting for threads: WaitForMultipleObjects. Batch output: GetStdHandle, WriteFile, WriteConsoleW write the same bytes to standard output.

glibc does not understand %I64d, so CString::Format turns it into %lld.

The "archive" mark

On Windows the system sets the ARCHIVE bit when a file is written, and a program can clear it. FieldView following a calculation relies on this: the kernel writes a frame and the bit is set; FieldView reads the frame and clears the bit, and the kernel may write the next one.

Linux has no such bit. tmc_fileflag.h repeats its meaning: when clearing the mark, a program stores the file modification time in the extended attribute user.tmc_read_stamp. The mark counts as cleared while the file has not changed since. Any new write sets it again, as on Windows.

If the file system has no extended attributes (a Windows partition in /mnt), the mark counts as set: the kernel does not wait for the viewer, otherwise it would idle for 25 seconds on every frame, and FieldView recognizes a new frame by file time and size.

Settings and starting programs

Settings are in ~/.config/TMC_Suite/<program>.conf. External programs (TmcCreateProcess) start with fork and execvp; the kernel learns of a failed start through a pipe and reports it, as on Windows. Names from Windows settings are translated: the .exe extension is dropped, and notepad, write, wordpad, winword become the first text editor found, or xdg-open.

Text mode of files (Linux only)

On Windows fopen(…, "r") opens a stream in text mode: on reading, the CR LF pair becomes LF, on writing the reverse. Linux has no such mode, and files written by the package would no longer match the Windows files. tmc_textmode.cpp (included only outside Windows together with the flag -Wl,--wrap=fopen) replaces fopen for the whole program:

  • a mode with b — the real fopen without changes (binary formats, S-matrices);
  • a mode without b — a binary stream wrapped with fopencookie: reading in 64 KB blocks removes all CR characters, writing replaces each LF with CR LF; positioning is by the bytes of the file with CRLF;
  • the file name is looked up ignoring the case of the last path element (if there is no exact name and there is exactly one match).

What is supported and what is not

Area Supported Not supported / differs
Strings CString (search, substrings, replacement, Format, concatenation) freeing memory; CStringW
Document path, title, modified flag, UpdateAllViews (as a flag) CArchive/Serialize; MFC document templates
View CScrollView, mouse (left button, right button press), timers, scrolling, printing through OnDraw OnSize is not called by MfcViewWidget; wheel, keyboard and right button release are not passed to the view; SetCapture deliberately does nothing
Dialogs layout from .rc, OK/Cancel/close button/Esc, buttons from the message map, DDX, timers, modeless windows, property pages ON_EN_CHANGE, ON_CBN_SELCHANGE, ON_LBN_SELCHANGE are not connected to fields and lists; ON_NOTIFY, *_RANGE; DDV checks
Controls edit field, label, button, check box, radio button, combo box, list box, progress bar, list view with columns, image list resource bitmaps (CImageList::Create(bitmapId) creates an empty list)
Drawing see GDI regions, paths, raster operations other than PatBlt, BitBlt, palettes
Threads AfxBeginThread, waiting, exit code, priorities SuspendThread; auto-deletion of CWinThread
Frames CStatusBar::SetPaneText CFrameWnd, CToolBar, CMDIFrameWnd — empty stubs: the main window, menus and toolbars are built by the program shell on Qt

Pitfalls

Group frames intercepted clicks. In Windows a GROUPBOX frame and a static label are transparent to the mouse: a click on a button inside the frame reaches the button regardless of the order of the controls in the .rc. In Qt the click goes to the topmost widget, and a frame created after the button intercepted it (in the TMC_DN parameters window "Graphs", "Normalization" and "Thinning" could not be pressed). Therefore, when the window is shown, labels and frames are lowered beneath the other controls, and frames (except those with a check box) get Qt::WA_TransparentForMouseEvents. In addition, rc2ui.py writes the widgets in reverse order, and the theme makes the frame background transparent.

DDX_Radio and the Tab order. The radio button index is determined from the focus chain. Any operation that rebuilds it (setParent when moving the controls into the scroll area) must restore the Tab order — otherwise DDX_Radio reads and writes the wrong radio button. tmcFitDialogContent remembers the order before the move and restores it afterwards.

AfxMessageBox(text) without a window. The one-argument variant used to write only to stderr, and in the viewers error messages were lost (the button looked broken). Now the default handler is a message box in the interface thread; from the computation thread the text still goes to stderr unless the program has installed its own handler.

The translation is applied after Show. Window captions are translated by the application event filter on QEvent::Show (gui-common). The application filter fires before the filter of the window itself, so tmcRefitAfterShow measures the already translated text. Any fitting of sizes to the text must be performed on show or later, not at build time. Text that the code sets into a label itself after the show (SetDlgItemText) is translated in place in the Windows build; input fields with user data are not translated.

Mouse capture. SetCapture of the view deliberately does nothing: Qt already delivers the movements of a pressed mouse to the same widget, and a "forgotten" capture (the release did not reach the view) would send all clicks to the plot, and the program would look frozen.

A modal window behind the main one. A dialog window is raised and activated when shown; its parent is the main window of the program (tmcOwnerWindow).

DDV_MaxChars and string copies. Truncation is performed in place in the CString buffer; copies sharing this buffer are truncated too.

setWidgetText and a missing control. In the Windows build SetDlgItemText/CWndCtrl::SetWindowText for a control that is not in the layout dereference NULL (the field availability check is performed before the type check).

Dialog timers after DoModal. Timers not stopped by KillTimer before the window is closed are deleted together with the window but remain in the m_timers table of the dialog object.