# C++ and Qt coding guide These conventions implement Vincent's naming and structure decisions from October 1-15, 2026. Instructor suggestions are recorded through Vincent's account. ## Names - Project-owned classes use `tkr`: a literal lowercase `tkr` prefix followed by PascalCase components. The specification suffix is optional and identifies a specialization: `tkrMainWindow` and `tkrTikzParserExplicit`. Existing Qt/vendor types retain their names. - Structs and enums use PascalCase: `SourceRange`, `DragKind`. - Methods use camelCase and describe an operation: `applyCoordinateEdits()`. - Variables and parameters combine a type/category prefix with a descriptive name. Include coordinate space or units where relevant: `ptTikzPosition`, `rSceneUnitsPerCentimeter`. - Private member variables add `m_`: `m_baSource`, `m_pScene`. `m_` means member; restricting it to private members is our project convention. - Header and implementation filenames match their primary class. - Enum values use PascalCase: `DragKind::WholeElement`. | Prefix | Type or category | Example | |---|---|---| | `i` | `int` | `iArgumentCount` | | `n` | `qsizetype` size or index | `nStart` | | `u` | `quint64` ID or revision | `uDocumentRevision` | | `b` | `bool` | `bSafeToEdit` | | `r` | `qreal` | `rLineWidthPoints` | | `str` | `QString` | `strFilePath` | | `ba` | `QByteArray` | `baSource` | | `pt` | `QPointF` | `ptScenePosition` | | `vec` | `QVector` | `vecElements` | | `list` | `QStringList` | `listDiagnostics` | | `p` | Raw pointer | `pParent` | | `ref` | Reference to another object | `m_refDocument` | | `up` | `std::unique_ptr` | `m_upController` | | `iter` | Iterator | `iterEdit` | For domain records and concrete objects, use a readable type/category word, such as `coordinateEdit`, `parseResult`, `resultSave`, `mapper`, or `fileSource`. Extend this table when a new category appears. Update names when types change. Prefixes do not establish ownership; declarations and documented lifetimes do. ## Files and dependencies Each primary class has its own `.h` and `.cpp`, grouped by responsibility: `model`, `parsing`, `geometry`, `editing`, `controller`, and `ui`. Small cross-component records share `model/EditorTypes.h`. An inheritance path may contain at most three project-defined class levels: main/base class, child, and grandchild (two levels after the main class). Qt's existing ancestry is excluded. This is a maximum, not a target. The initial classes are `final` and introduce no custom inheritance chains. The extracted rectangle implementation is also `final` and realizes `tkrShapeProvider`, a two-level project-defined interface chain. Favor composition and explicit references. A specialization suffix describes the role; it does not itself imply inheritance. The explicit parser has no project-defined base. Do not create base classes solely to satisfy a name. The report's Developer Requirements subsection controls these conventions: REQ-A-005 retains its historical ID after moving out of Architecture; REQ-DEV-001 through REQ-DEV-005 govern class names, other identifiers, inheritance depth, documented ownership, and named numeric values. Checks TC-030 through TC-033 and TC-066 are planned review/build procedures. The document, parser and mapper depend on Qt Core, without widgets or a LaTeX process. Widgets request actions; parsing identifies source; the model applies validated edits; the controller coordinates them and performs file I/O. ## Named numeric values Keep numeric literals in named definitions. Give each value a name that describes its purpose and units, such as `iHitRadiusViewportPixels`. Use a local `constexpr` when one method needs it, a file-local constant when several helpers share it, or a class member when the class owns the value. Use named enum values for numeric keys. Derive related values from the same definition instead of giving each occurrence of a number a separate name. Start the review in `tkrDiagramScene`: name the default scene dimensions, the hit radius, and the item-data keys. Keep related PGF arrow geometry coefficients together in a named definition with their source reference. These are review examples, not a claim that the existing code conforms. ## Ownership - `main.cpp` owns one `tkrMainWindow` on the stack. The accepted final-window close ends the event loop, then stack destruction releases the window. - The document owns `tkrEditHistory` by value; only the document records/traverses its session snapshots. Candidate source, parsed records and history are prepared before document acceptance publishes them with non-allocating swaps. - The window owns its document by value and controller through `unique_ptr`. The controller is destroyed before the document. - The window owns its scene through QObject parenting. Widgets and actions also have Qt parents. The scene owns its graphics items. - The window's central widget tree owns `tkrWorkspaceSidebar`, which parents its tab strip, content stack and Shapes/Files pages. The pages own their controls. Provider description text is copied; no provider pointer is retained. - The controller holds non-owning document/scene references and owns its parser, mapper and stateless edit service by value. Referenced objects must outlive it. - The scene owns its `tkrShapePluginStore` and mapper calibration by value. The store owns a `QPluginLoader` and borrows its root provider interface. The binding is fixed for the scene lifetime; the native module remains resident. The edit service borrows the interface only for a request. API records contain values, without private source ranges, widgets or graphics pointers. - Do not combine QObject-parent ownership and `unique_ptr` ownership of the same object. `WA_DeleteOnClose` must not be set on this stack-owned window. ## Source and editing contracts - Preserve source as bytes. Use byte offsets consistently for source ranges. Decoding the read-only source view must never become the saved representation. - Coordinate values are in centimeters; scene positions use scene units. Viewport pixels and zoom must not alter source geometry. - Element IDs are scoped to a document revision. Reparse after a committed edit and discard stale element records. IDs are not yet persistent identities. - Apply coordinate replacements as one validated batch, from the end backwards. Check revision, bounds, overlaps and expected original text before mutation. - Whole-element and rectangle-corner dragging preview geometry during movement and commits source once on release. Escape, focus loss, or cancelling an interaction restores geometry from the unchanged document. Endpoint dragging remains unimplemented. - Drag displacement is rounded to 0.000001 cm on release. Decimal string addition preserves the original coordinate precision and element dimensions; only values on changed axes are replaced. A candidate source/scene is validated before the model is changed. The edit service constrains both preview and release to the same stroke-aware extent and independent 0.01 cm rectangle minima; crossing flips around the fixed corner. Limits are normal interaction. - Saving uses `QSaveFile` with direct-write fallback disabled. Mark saved only after successful replacement. A baseline comparison detects observed external changes, but does not eliminate a concurrent-write race after that comparison. ## Implementation status The parser conservatively interprets explicit-coordinate rectangles, lines and arrows, retaining numeric byte ranges and a separate non-movable comparison extent. The scene draws these records through the mapper, including PGF's default curved `to` arrowheads for `->`, `<-` and `<->`. Items are selectable; scene event handlers control whole-element movement instead of Qt's `ItemIsMovable` flag. The edit service prepares geometry and source replacements; the controller coordinates candidate validation and the document applies guarded source changes. No item pointers survive a reparse/rebuild. Endpoint handlers remain unsupported. Unsupported input returns diagnostics without a partial diagram. Core parsing remains independent of Widgets. The separate rectangle module supplies geometry, presentation, selection and operations; host validation/source rewriting and document acceptance stay in the application. See [the SDK](plugin-api/README.md). No integrated LaTeX/PDF, undo stack, provider management, creation, zoom controls or loop support is implemented. General product acceptance remains pending. Keep TODOs specific, and return a clear unavailable/failure result from unfinished operations. Avoid reporting an empty parse as successful editable interpretation. ## Reference documentation - [Qt CMake setup](https://doc.qt.io/qt-6/cmake-get-started.html) - [QObject ownership](https://doc.qt.io/qt-6/objecttrees.html) - [Window close behavior](https://doc.qt.io/qt-6/qwidget.html#close) - [QSaveFile replacement and failure behavior](https://doc.qt.io/qt-6/qsavefile.html) ## Current sidebar shell and planned shared-service refactor The [planned sidebar design](../documents/latex/tkrSidebarDesign.tex) moves shared store/catalogue ownership to the main window and gives views borrowed access. The current shell already has bounded sidebar, palette and folder-placeholder classes, parented through the main window central widget tree. Provider summary text is copied; the scene still owns the store. The catalogue and shared-service refactor remain planned. The current ownership list above remains the code's actual contract. Concrete constructor, teardown and API signatures require review before implementation.