Black Mesa Core and Misc QML Files

From Valve Developer Community
Jump to navigation Jump to search
English (en)Translate (Translate)

This page contains information about core and misc QML Black Mesa Black Mesa files and their code from Resonance Decade Update. This includes: devtest.qml, input-bindings-manager.qml, l10n.qml, main.qml, qmldir., sound.qml, theme.qml, triangle.qml, utils.qml.

devtest.qml

devtest.qml is a standalone developer test harness. It is not registered in qmldir, is not referenced anywhere in the codebase, and has no corresponding entry in routes.qml. It cannot be loaded through any normal UI flow and exists solely as an offline development tool for exercising engine API calls.

The root element is a FocusScope (id: rootItem) with a fixed size of 1600×900. It does not use Theme, L10n, Sound, or any other singleton from the production UI.

Private State — d

A QtObject (id: d) holds one private property:

Property Type Purpose
queryHandle string Stores the handle returned by BlackMesaEngine.requestInternetServerList(), used later to cancel the query.

Deferred Startup Timer — deferredCompletedTimer

A Timer with interval: 1250, repeat: false, and running: true. It fires automatically 1250 ms after construction and performs three engine calls:

  1. BlackMesaEngine.listSaveEntries() — result is JSON-logged and assigned to listSaveEntriesGrid.model.
  2. BlackMesaEngine.requestInternetServerList() — handle is stored in d.queryHandle.
  3. BlackMesaEngine.listAchievementEntries() — result is JSON-logged to the console only; not displayed in the UI.

Server Response Handler — Connections

Listens to BlackMesaEngine.onMatchmakingServerResponded. On each response:

  1. Logs queryHandle, serverEntry.steamApplicationId, and BlackMesaEngine.getSteamApplicationId() to the console.
  2. Filters the entry: only appends to serverEntriesList.model if serverEntry.steamApplicationId === BlackMesaEngine.getSteamApplicationId() and serverEntry.gameDirectory === "bms".

Two alternative filter conditions are present as comments: one for CS:GO (app ID 730, directory csgo) and one for Black Mesa (app ID 362890). The comment notes that the CS:GO filter was used because the Black Mesa server list was empty at the time of writing.

The inline comment also documents the full shape of a server entry object:

Field Type Notes
botsOnServerCurrently integer
connectionAddressString string e.g. 193.104.68.59:27032
gameDescription string
gameDirectory string e.g. csgo, bms
isPasswordProtected boolean
isSecure boolean VAC-secured
lastPlayed string ISO 8601; valid only for Favorites/History lists
map string
name string
ping integer milliseconds
playersOnServerCurrently integer
playersOnServerMaximum integer
steamApplicationId integer

Visual Layout

The root Rectangle fills the parent with a grey background and contains a ColumnLayout with three vertically-stacked sections.

Save Entries Grid — listSaveEntriesGrid

A GridView with cellWidth: 160 and cellHeight: 90. Its model is populated by the startup timer. Each cell renders the save thumbnail via modelData.thumbnailUrl. A right-click MouseArea (acceptedButtons: Qt.RightButton) calls BlackMesaEngine.removeSaveEntry(modelData.name) and immediately refreshes the model by calling BlackMesaEngine.listSaveEntries() again.

Steam Overlay Buttons

A RowLayout containing nine native Qt Button elements, each calling a BlackMesaEngine method:

Label Call
friends BlackMesaEngine.activateSteamOverlay("friends")
community BlackMesaEngine.activateSteamOverlay("community")
players BlackMesaEngine.activateSteamOverlay("players")
settings BlackMesaEngine.activateSteamOverlay("settings")
officialgamegroup BlackMesaEngine.activateSteamOverlay("officialgamegroup")
stats BlackMesaEngine.activateSteamOverlay("stats")
achievements BlackMesaEngine.activateSteamOverlay("achievements")
web - workshop BlackMesaEngine.activateSteamOverlayToWebPage("https://steamcommunity.com/app/362890/workshop")
matchmaking cancel query BlackMesaEngine.matchmakingCancelQuery(d.queryHandle)
Server Entries List — serverEntriesList

A ListView with an initially empty ListModel {}. Entries are appended by the onMatchmakingServerResponded handler. Each row is a RowLayout with four columns:

Column Width Alignment Content
Server name fill left model.name
Address 200 px center model.connectionAddressString
Ping 100 px right model.ping
Players 100 px center "%1(%3)/%2".arg(playersOnServerCurrently).arg(playersOnServerMaximum).arg(botsOnServerCurrently) — renders as e.g. 5(1)/12 (current(bots)/max)

Notable Issues

1. queryHandle is referenced unqualified in the Connections block. Line 69 logs queryHandle directly. In QML scope resolution, this does not resolve to d.queryHandle — queryHandle is a property of the d object, not of rootItem or any enclosing scope. The value logged will be undefined. The correct reference is d.queryHandle.

2. QtGraphicalEffects 1.0 is imported but unused. No graphical effect type is instantiated anywhere in the file.

3. QtQuick.Layouts 1.2 differs from the rest of the codebase. All production files use QtQuick.Layouts 1.1. This is a minor inconsistency with no functional impact.

4. Fixed 1600×900 size with no Theme scaling. The root item is hardcoded to 1600×900 and no Theme.widthScale or Theme.heightScale is applied to any dimension. The file is not intended for production display.

5. Native Qt Button elements instead of custom button components. The production UI uses CTAButton, DefaultButton, etc. This file uses the unstyled QtQuick.Controls 2.2 Button directly.

6. listAchievementEntries() output is console-only. The achievement data is fetched and logged but never displayed in the UI, unlike the save entries and server entries which have dedicated visual sections.

7. The Rectangle border overlay inside RowLayout uses anchors.fill: parent. The RowLayout is not an Item subtype that supports anchors.fill children in the same way as a plain Item. The border rectangle will fill the layout but may not clip correctly against the button children.

input-bindings-manager.qml

input-bindings-manager.qml is registered in qmldir as singleton InputBindingsManager 1.0. It is the central state manager for the key bindings system, responsible for:

  • Translating between Qt key/mouse enum values and Source engine key name strings.
  • Mapping engine command strings to localized human-readable labels.
  • Loading and reverse-indexing the current bindings from config.cfg.
  • Managing the key-capture lifecycle (selection → capture → conflict resolution → write).
  • Emitting signals that cause binding display components to refresh.

It is a pragma Singleton QtObject with 374 lines.

Static lookup tables

All three tables are built as immediately-invoked function expressions (IIFEs) and frozen with Object.freeze() at construction time. They are readonly property variant.

commandMap

Maps engine command strings to localized label strings sourced from L10n.strings.options.bindings. Contains 49 entries across five logical groups:

Group Commands
Movement +forward, +back, +moveleft, +moveright, +jump, +duck, +speed
Combat +use, +attack, +attack2, +reload, impulse 100, +zoom
Weapons invnext, invprev, lastinv, slot1–slot6, use weapon_crowbar, use weapon_glock, use weapon_357, use weapon_mp5, use weapon_shotgun, use weapon_crossbow, use weapon_rpg, use weapon_tau, use weapon_gluon, use weapon_hivehand, use weapon_frag, use weapon_tripmine, use weapon_satchel, use weapon_snark
Misc save quick, load quick, toggleconsole, incrementvar closecaption 0 1 1, +moveup, +movedown, +lookup, +lookdown, +left, +right
Multiplayer chooseteam, +voicerecord
mouseMap

Maps Qt mouse button enum values and wheel direction strings to Source engine key name strings. References src/inputsystem/key_translation.cpp in a comment.

Qt value Source key name
Qt.LeftButton MOUSE1
Qt.RightButton MOUSE2
Qt.MidButton MOUSE3
Qt.BackButton MOUSE4
Qt.ForwardButton MOUSE5
wheelUp (string key) MWHEELUP
wheelDown (string key) MWHEELDOWN
keyMap

Maps Qt key enum values to Source engine key name strings. References src/inputsystem/key_translation.cpp in a comment. Contains 72 entries:

Category Entries
Letters Qt.Key_A–Qt.Key_Z → a–z
Digits Qt.Key_0–Qt.Key_9 → 0–9
Function keys Qt.Key_F1–Qt.Key_F12 → F1–F12
Modifiers Qt.Key_Shift → SHIFT, Qt.Key_Alt → ALT, Qt.Key_Control → CTRL
Navigation Qt.Key_Left → LEFTARROW, Qt.Key_Right → RIGHTARROW, Qt.Key_Up → UPARROW, Qt.Key_Down → DOWNARROW, Qt.Key_Home → HOME, Qt.Key_End → END, Qt.Key_PageUp → PGUP, Qt.Key_PageDown → PGDN, Qt.Key_Insert → INS, Qt.Key_Delete → DEL
Whitespace / control Qt.Key_Space → SPACE, Qt.Key_Tab → TAB, Qt.Key_Backspace → BACKSPACE, Qt.Key_Escape → ESCAPE, Qt.Return → ENTER
Lock keys Qt.Key_CapsLock → CAPSLOCK, Qt.Key_ScrollLock → SCROLLLOCK, Qt.Key_NumLock → NUMLOCK
Punctuation ', ;, =, \, `, /, ., ,, [, ], -

Mutable state properties

Property Type Description
bindings variant Command → key array map loaded from config.cfg by getBindings(). Keyed by command string; values are arrays of bound key name strings.
bindingsKeyMap variant Reverse index of bindings. Keyed by key name string; values are arrays of command strings. Used for conflict detection.
inputBindingCallback var (default null) The closure set during key capture. Non-null while capture is in progress.
isBinding bool Computed as !!inputBindingCallback. true while key capture is active.
isSelected bool Computed as !!selectedCfg. true while a binding cell is selected but capture has not yet started.
selectedCfg variant The binding configuration object for the currently selected cell. Set by selectBinding(); cleared by clearSelection().
conflicts variant Array of human-readable command label strings that conflict with the key pressed during capture. null when no conflict is pending.
conflictCfg variant Object containing bindingCfg, key, confirm (function), and cancel (function). Set when a conflict is detected; consumed by routeview-bindings.qml to display the conflict alert.

Signals

Signal Fired when
bindingSet() A key is successfully bound (no conflict, or conflict confirmed).
bindingClear() A binding is cleared via clearSelectedBinding().
defaultsRestored() Default bindings are restored via restoreDefaultBindings().

All three signals are connected in component-binding.qml to call refreshBindings(), which re-reads config.cfg and updates the displayed key labels.

Functions

Private helpers

_readConfigFile(url, callback) — Opens a VFS file via XMLHttpRequest, splits the response on newlines, and matches each line against the regex /bind\s+"(.*)"\s+"(.*)"/. Builds a command → key array map and passes it to callback. Used to read both vfs:///cfg/config.cfg and vfs:///cfg/config_default.cfg.

_saveBindingModifications() — Executes exec userconfig.cfg; host_writeconfig via BlackMesaEngine.executeClientCommandUnrestricted() to persist all in-memory binding changes to disk.

_resetConflicts() — Sets both conflicts and conflictCfg to null.

Public API

getBindingComponentConfig(command) — Returns a plain object {label, type: 'binding', command, key1: '', key2: ''} for initializing a binding row in a ListModel.

getBindings(commands, callback) — Reads config.cfg, populates bindings and bindingsKeyMap, then calls callback with a filtered map containing only the entries whose command strings appear in the commands array. Called by component-binding.qml on load and after every bindingSet/bindingClear/defaultsRestored signal.

selectBinding(cfg) — Sets selectedCfg to cfg, making isSelected true. Called by component-optionslist-input-binding.qml when the user first clicks a BindingCell.

clearSelection() — Sets selectedCfg to null.

handleBindingResponse(event) — Invokes inputBindingCallback(event) and immediately sets inputBindingCallback to null, ending the capture session. Called by main.qml from three sources: onKeyCaptured (keyboard), a full-screen MouseArea onClicked (mouse buttons), and the same MouseArea onWheel (scroll wheel).

startBindingRequest() — Begins the key capture sequence:

  1. Snapshots selectedCfg into a local cfg variable.
  2. Calls clearSelection() (sets isSelected to false).
  3. Calls cfg.begin() to put the BindingCell into the "binding" visual state.
  4. Calls BlackMesaEngine.requestKeyCapture() to tell the engine to route the next key event to the UI.
  5. Sets inputBindingCallback to a closure that handles the captured event (see below).

clearSelectedBinding() — Unbinds the key at selectedCfg[selectedCfg.ordinal] via BlackMesaEngine.executeClientCommandUnrestricted('unbind ...'), saves, and emits bindingClear().

restoreDefaultBindings() — Reads config_default.cfg via XHR (result is discarded), then executes unbindall and exec config_default.cfg, saves, and emits defaultsRestored().

Key capture lifecycle

The full flow from user interaction to engine write:

  1. User clicks a BindingCell (first click) → component-optionslist-input-binding.qml calls InputBindingsManager.selectBinding(cfg) → isSelected becomes true.
  2. User clicks the same cell again (second click) → BindingCell.startBinding() calls InputBindingsManager.startBindingRequest() → isBinding becomes true.
  3. main.qml activates a full-screen MouseArea at z: 2000 (enabled only while isBinding is true) to intercept mouse input.
  4. The engine fires onKeyCaptured (keyboard) or the MouseArea fires onClicked/onWheel → handleBindingResponse(event) is called.
  5. Inside inputBindingCallback:
    • If event.key = 'ESCAPE': calls cancel(), which calls cfg.end() with the original key and resets conflicts. No binding change occurs.
    • If the pressed key is already bound to a different command: sets conflicts and conflictCfg. The UI (routeview-bindings.qml) shows a conflict alert with Confirm/Cancel buttons. conflictCfg.confirm and conflictCfg.cancel are the resolution callbacks.
    • Otherwise: calls the inner setBinding() helper, which executes unbind on the old key and bind KEY "COMMAND" for each of key1 and key2, then saves and emits bindingSet().

Notable Issues

1. bindingsKeyMap.push(command) is a bug. In getBindings(), when a key is already present in bindingsKeyMap, the code calls bindingsKeyMap.push(command) instead of bindingsKeyMap[key].push(command). bindingsKeyMap is a plain object, not an array, so push is undefined and this call throws a TypeError. The second command for any multiply-bound key is never added to the reverse map, meaning conflicts involving keys bound to more than one command are silently missed.

2. restoreDefaultBindings reads config_default.cfg but discards the result. The XHR parse is entirely redundant. The function executes unbindall; exec config_default.cfg unconditionally regardless of the parsed content. The commented-out block that would have used the parsed data was never re-enabled.

3. isBinding and isSelected are writable. Both are declared as property bool rather than readonly property bool. External code can overwrite them, breaking the invariant that they reflect !!inputBindingCallback and !!selectedCfg respectively.

4. Qt.Return instead of Qt.Key_Return. The Enter key entry in keyMap uses Qt.Return while every other entry uses the Qt.Key_* form. Qt.Return is a valid alias in Qt 5 but is inconsistent with the rest of the map.

5. onKeyCaptured escape-to-deselect branch references undefined event. In main.qml, the onKeyCaptured handler contains an else if branch that checks InputBindingsManager.isSelected && event.key === Qt.Key_Escape. The onKeyCaptured signal provides keyButtonCode, not event. The event identifier is undefined in this scope, so the condition always evaluates to false (or throws a TypeError). Pressing Escape while a cell is selected but not in capture mode does not clear the selection via this path.

6. keyMap does not cover numpad keys. The Source engine supports KP_INS, KP_END, KP_UPARROW, etc. None of the Qt.Key_0–Qt.Key_9 entries distinguish between the main row and the numpad (Qt.KeypadModifier is not checked), and no Qt.Key_* numpad-specific constants are mapped.

l10n.qml

l10n.qml is the central localization singleton for the entire UI. It is registered in qmldir as singleton L10n 1.0 l10n.qml and imported implicitly by every QML file in the module. Its sole purpose is to expose all UI-facing strings as a single frozen JavaScript object tree, fetched from the engine's localization system at construction time.

The file is 410 lines and is a pragma Singleton QtObject.

Properties

Property Type Description
strings variant The full string map. Initialized by calling _getStringMap() at construction time. Not readonly — it can be reassigned from outside the singleton (see Notable Issues).

Functions

getString(key)

A thin public wrapper around BlackMesaEngine.getLocalizedString(key). Returns the localized string for the given engine localization key. Used internally by _getStringMap() to populate every entry in the string map, and also called directly by a small number of files (see Notable Issues).

refreshStrings()

Reassigns strings by calling _getStringMap() again. Intended to be called after a language change to rebuild the string map with the new locale. However, refreshStrings() is never called from any other QML file in the codebase — it is defined but has no callers. Language changes at runtime therefore cannot update the UI without a full restart.

_getStringMap()

Private function. Builds and returns the complete string map as a deeply frozen JavaScript object (Object.freeze() applied at every level). Called once at construction time and again if refreshStrings() is ever invoked. All string values are fetched via getString() at the moment of the call; the map is a snapshot, not a live binding.

strings — Top-Level Structure

The strings object has ten top-level keys, each a frozen sub-object.

Key Entry count Purpose
maps 20 Chapter title strings for chapters 1–20 (#QTUI_Maps_Chapter1_Title through #QTUI_Maps_Chapter20_Title). Used by routeview-newgame.qml and routeview-addons.qml to label carousel items.
loading 6 Loading screen strings: one loadingLevel label and five loading quotes (quote01–quote05). Used by component-footer.qml.
quit 6 Six humorous quit dialog quotes (quote01–quote06, keys #QTUI_Quit_Quote01–#QTUI_Quit_Quote06). Used by routeview-quit.qml, which picks one at random via Math.floor(Math.random() * quotes.length).
labels 4 Save slot type labels: quickSave, autoSave, manualSave, newSave. Used by component-carousel-item-loadgame.qml and routeview-savegame.qml.
buttons 20 Button label strings for all interactive buttons across the UI. See buttons sub-object below.
menus 24 Navigation tab label strings for all main nav, sub-nav, and sub-nav-secondary tabs. See menus sub-object below.
headers 13 Page and dialog header strings. See headers sub-object below.
modalMessages 7 Modal dialog body text strings. See modalMessages sub-object below.
options — Nested object with three sub-keys: bindings (49 entries), labels (92 entries), values (69 entries). See options sub-object below.
navigation 4 Controller/keyboard guide hint strings: select, discard, options, change_tabs. Used exclusively by component-menu-navigation-guide.qml.
buttons sub-object
Key Localization key Used by
back #QTUI_Buttons_Back component-footer.qml
backToGame #QTUI_Buttons_BackToGame component-footer.qml
cancel #QTUI_Buttons_Cancel routeview-quit.qml, routeview-savebeforequit.qml, routeview-video.qml, routeview-bindings.qml
apply #QTUI_Buttons_Apply component-footer.qml
confirm #QTUI_Buttons_Confirm (defined; no observed caller)
applyChanges #QTUI_Buttons_ApplyChanges component-footer.qml
quit #QTUI_Buttons_Quit routeview-quit.qml
resume #QTUI_Buttons_Resume routeview-index.qml
startGame #QTUI_Buttons_StartGame routeview-index.qml
discard #QTUI_Buttons_Discard routeview-video.qml
discardChanges #QTUI_Buttons_DiscardChanges component-footer.qml
createSave #QTUI_Buttons_CreateSave routeview-savegame.qml
overwriteSave #QTUI_Buttons_OverwriteSave routeview-savegame.qml
deleteSave #QTUI_Buttons_DeleteSave routeview-loadgame.qml
saveGame #QTUI_Buttons_SaveGame routeview-index.qml
quicksave #QTUI_Buttons_Quicksave routeview-index.qml
save #QTUI_Buttons_Save routeview-savebeforequit.qml
dontSave #QTUI_Buttons_DontSave routeview-savebeforequit.qml
disconnect #QTUI_Buttons_Disconnect routeview-index.qml
resetAllDefaults #QTUI_Buttons_ResetAllDefaults component-footer.qml
editBinding #QTUI_Buttons_EditBinding routeview-bindings.qml
clearBinding #QTUI_Buttons_ClearBinding routeview-bindings.qml
menus sub-object
Key Localization key Nav level
campaign #QTUI_Menu_Campaign Main nav
multiplayer #QTUI_Menu_Multiplayer Main nav
options #QTUI_Menu_Options Main nav
achievements #QTUI_Menu_Achievements Main nav
workshop #QTUI_Menu_Workshop Main nav
newgame #QTUI_Menu_Campaign_NewGame Campaign sub-nav
savegame #QTUI_Menu_Campaign_SaveGame Campaign sub-nav
loadgame #QTUI_Menu_Campaign_LoadGame Campaign sub-nav
game #QTUI_Menu_Options_Game Options sub-nav
input #QTUI_Menu_Options_Input Options sub-nav
bindings #QTUI_Menu_Options_Bindings Options sub-nav
video #QTUI_Menu_Options_Video Options sub-nav
audio #QTUI_Menu_Options_Audio Options sub-nav
policy #QTUI_Menu_Options_Policy Options sub-nav
translators #QTUI_Menu_Options_Translators Options sub-nav
join #QTUI_Menu_Multiplayer_Join Multiplayer sub-nav
refresh #QTUI_Menu_Multiplayer_Refresh Multiplayer sub-nav
host #QTUI_Menu_Multiplayer_Host Multiplayer sub-nav
campaigns #QTUI_Menu_Workshop_Campaigns Workshop sub-nav (unused — no route)
addons #QTUI_Menu_Workshop_Addons Workshop sub-nav (unused — see Notable Issues)
installed #QTUI_Menu_Workshop_Installed Workshop sub-nav (used by component-header.qml for the Addons tab label)
browse #QTUI_Menu_Workshop_Browse Workshop sub-nav
headers sub-object
Key Used by
gameOptions routeview-game.qml
controls routeview-bindings.qml
videoOptions routeview-video.qml
advancedSettings routeview-video.qml
audioOptions routeview-audio.qml
inputOptions routeview-input.qml
mouseOptions routeview-input.qml
controllerOptions routeview-input.qml
bindings routeview-bindings.qml
quit routeview-quit.qml
saveBeforeQuit routeview-savebeforequit.qml
unsavedWarning routeview-video.qml
resetAllDefaultsWarning component-optionslist.qml
overwriteSaveConfirmation routeview-savegame.qml
deleteSaveConfirmation routeview-savegame.qml, routeview-loadgame.qml
confirmBindingOverwrite routeview-bindings.qml
modalMessages sub-object
Key Used by
unsavedWarning routeview-video.qml
resetAllDefaultsWarning component-optionslist.qml
deleteSaveConfirmation routeview-savegame.qml, routeview-loadgame.qml
overwriteSaveConfirmation routeview-savegame.qml
bindingInstructions routeview-bindings.qml
confirmBindingOverwrite routeview-bindings.qml
saveBeforeQuit routeview-savebeforequit.qml
options sub-object

The options sub-object has three nested frozen objects.

options.bindings — 49 entries mapping binding setting keys to their localized label strings. Grouped semantically into movement (7), combat (16), misc (10), multiplayer (2), and weapons (14). Used by component-binding-movement.qml, component-binding-combat.qml, component-binding-misc.qml, component-binding-weapons.qml, and component-binding-multiplayer.qml.

options.labels — 92 entries providing row label strings for all options pages. Organized into logical groups by prefix:

Prefix Count Options page
game_ 12 routeview-game.qml
video_ (setting labels) 28 routeview-video.qml
video_desc_help_ 20 routeview-video.qml (option description panel)
video_desc_usage_ 7 routeview-video.qml (CPU/GPU/RAM impact labels)
audio_ 7 routeview-audio.qml
controller_ 7 routeview-input.qml
mouse_ 6 routeview-input.qml
binding_ 5 routeview-bindings.qml (category list labels)

options.values — 69 entries providing localized display strings for select/carousel option values. Groups: boolean (no/yes/on/off), quality presets (Potato through Custom), difficulty levels, announcer types, aspect ratios, display modes, water detail levels, texture filtering modes, speaker configurations, captioning modes, and 29 language names.

Usage across the codebase

L10n.strings.* is the standard access pattern and is used by 22 QML files. The four files that call L10n.getString() directly — component-optionslist-input-select.qml, component-optionslist-row.qml, routeview-game.qml, and utils.qml — bypass the frozen map and always fetch a live value from the engine, meaning those strings would update immediately if refreshStrings() were ever called, while all other strings would not.

Notable Issues

1. refreshStrings() is never called. The function is defined but has no callers in the codebase. A language change at runtime cannot update any L10n.strings.* binding without a full UI reload.

2. strings is not readonly. The property is declared as property variant strings, not readonly property variant strings. Any component can reassign the entire string map from outside the singleton, bypassing Object.freeze().

3. video_desc_usage_ram key name is misleading. The property is named ram but its localization key is #QTUI_Option_Video_Desc_Usage_VRAM. The label describes VRAM (video memory), not system RAM.

4. menus.addons is never used. component-header.qml uses L10n.strings.menus.installed (#QTUI_Menu_Workshop_Installed) for the Workshop Addons tab label, not menus.addons (#QTUI_Menu_Workshop_Addons). The addons key is defined but has no callers.

5. menus.campaigns references an unreachable route. routeview-campaigns.qml is an unregistered stub with no entry in routes.qml. The menus.campaigns string is defined but cannot be displayed through any normal navigation flow.

6. Trailing comma in navigation sub-object. The last entry (change_tabs) is followed by a trailing comma. This is valid in ES5+ JavaScript but is inconsistent with all other sub-objects in the file, which do not have trailing commas.

7. options.labels mixes two localization key namespaces. Most keys use #QTUI_* keys, but game_multiplayermodel uses #GameUI_CharacterModel and game_multiplayerskin uses #GameUI_CharacterSkin — legacy GameUI keys from the Source engine's original localization system, inconsistent with the rest of the file.

main.qml

main.qml is the root QML document of the Black Mesa menu UI. It is the top-level Item instantiated by the engine and acts as the orchestration layer: it owns all global state, wires the engine's C++ signals to the QML layer, and composes the three primary visual regions (Header, Router, Footer) into a single full-screen layout.

It is not registered in qmldir and is not a named component — it is loaded directly by the engine as the entry point.

Properties

Property Type Default Purpose
emptyRoute readonly Route Routes.empty Convenience alias for the empty route, used throughout the engine event handlers.
mainMenuIndexRoute readonly Route Routes.index Convenience alias for the index route.
isLoadingLevel bool false Set to true between onLevelLoadingStarted and onLevelLoadingFinished. Hides the Header and suppresses wallpaper animations during loads.
didLoadLevel bool false Hack flag: set to true in onLevelLoadingFinished and consumed in onGameUIHidden to distinguish a level-load hide (no fade animation) from a player-initiated ESC hide (fade animation).
isInGame bool false Custom in-game tracking flag. Not derived from BlackMesaEngine.isInGame() directly because the engine considers the main menu background map to be "in game". Updated in multiple engine event handlers.
isInMultiplayerMode bool false Set to true in onLevelLoadingFinished when the loaded level is a multiplayer session. Used by component-header.qml to disable the Load Game and Save Game sub-nav buttons.
isSaving bool false Set to true while a save is in progress. Disables the appRoot opacity animation and hides the root panel to prevent the menu overlay from appearing in the save thumbnail screenshot.
_isInitialLoad bool true Tracks whether the UI has ever completed a level load. Cleared in onLevelLoadingFinished and in autoBackgroundMusicTimer. Used to suppress the "in game" state and loading progress bar on the very first startup load.
loadingErrorFlag bool false Set to true when onLevelLoadingFinished fires with isError === true. Consumed in the next onGameUIActived to redirect to the multiplayer route after a failed server connection.
levelLoadingFinished_FailureReason string "" Stores the failureReason string injected by the engine when a level load fails. Displayed as the message body of alertLoadFailed.
loadPercent real 0.0 Updated by onUpdateProgressValue. Passed to Footer to drive the loading progress bar.
isMenuBlocked bool false Set to true during the appRoot opacity animation. The Connections block is enabled: !isMenuBlocked, so all engine signals are ignored while the menu is animating open or closed.

Theme Scaling Bindings

Two Binding elements keep Theme.widthScale and Theme.heightScale in sync with the window dimensions at all times:

  • Theme.widthScale = appRoot.width / 1920
  • Theme.heightScale = appRoot.height / 1080

onWidthChanged and onHeightChanged additionally write Theme.rootWidth and Theme.rootHeight (which cannot be driven by Binding because they are plain writable properties, not bindable targets in the same way) and call wallpaper.updateBackgroundImage() to re-evaluate the widescreen threshold.

Focus, Visibility, and Key Handling

appRoot holds focus: true so it is the root of the keyboard focus chain. Keys.onPressed delegates all key events to BlackMesaUtils.navigationUIHandle(event) unless BlackMesaUtils.disableUINavigation is true (set by InputBindingsManager during key capture).

onVisibleChanged calls BlackMesaEngine.setRootPanelVisibility(visible) to notify the engine whenever the root panel is shown or hidden.

Opacity Animation

A Behavior on opacity wraps the root fade in a SequentialAnimation:

  1. Sets isMenuBlocked = true (disabling engine signal processing).
  2. Runs a 625 ms NumberAnimation on appRoot.opacity.
  3. Sets isMenuBlocked = false.

The behavior is enabled: !didLoadLevel && !appRoot.isSaving, so it is bypassed when the UI is hiding due to a completed level load (instant cut) or a save operation (instant hide for screenshot).

Layout

The three primary UI regions are arranged in a GridLayout with flow: GridLayout.TopToBottom and rows: 3:

Row Component id Height
1 Header header 128 * Theme.heightScale
2 Router router Fill remaining height (Layout.fillHeight: true)
3 Footer footer 72 * Theme.heightScale
Wallpaper

A Wallpaper (component-wallpaper.qml) fills the entire appRoot behind the layout. It is not part of the GridLayout. Key bindings:

  • showSkrim: isInGame || router.currentRoute !== Routes.index — applies a dark overlay whenever the player is in-game or on any route other than the main index.
  • darkenSkrim: isInGame — uses the darker skrim opacity (Theme.opacity.pageSkrimDark) when in-game.
  • suppressAnimations: isLoadingLevel — disables crossfade animations during level loads to reduce GPU load.

Wallpaper internally maintains a map of 19 background image keys (background01–background19) to .vtf file paths, with separate widescreen variants. The widescreen path is chosen when appRoot.width / appRoot.height >= 1.586. It also renders a bottom-right Black Mesa logo watermark, a left-edge gradient using Theme.colors.highlight, and a secondary gradient using Theme.colors.subNavBackground, all of which fade in/out via showExtras.

Header

The Header (component-header.qml) is the top navigation bar. It is passed:

  • currentRoute: router.currentRoute — used to highlight the active main-nav and sub-nav tabs and to determine the header state.
  • isInGame: appRoot.isInGame — used to enable/disable the Save Game sub-nav button.
  • hide: true — starts hidden; set to false by engine event handlers once the UI is ready.
  • visible: !appRoot.isLoadingLevel — completely hidden (not just off-screen) during level loads.

The header has three states: hidden, subnav-closed, and subnav-open. State transitions are 250 ms NumberAnimation slides using Easing.OutQuint. The sub-nav row switches its ListModel based on the first path segment of currentRoute.path (campaign, multiplayer, options, steamworkshop).

The header also executes BlackMesaEngine.executeClientCommandUnrestricted("exec server.cfg;") in the multiplayerNavModel.Component.onCompleted handler to pre-load server configuration when the multiplayer sub-nav model is first created.

Router

The Router (router.qml) fills the space between the header and footer. It receives isInGame: appRoot.isInGame and propagates three signals upward to main.qml:

Signal Handler in main.qml Action
onLoadGameRequest Sets footer.levelName to savegame.chapterName Calls BlackMesaUtils.loadGame(savegame.savename)
onLoadMapRequest Sets footer.levelName to mapname Calls BlackMesaUtils.loadMap(filename)
onSaveGameRequest Sets appRoot.isSaving = true, hides appRoot Calls BlackMesaUtils.saveGame(filename, callback); callback resets isSaving

The save handler hides appRoot before saving so the menu overlay does not appear in the save thumbnail. A TODO comment acknowledges this as a hack requiring proper state management.

Footer

The Footer (component-footer.qml) is the bottom bar. It switches between two Component instances via a Loader:

  • menuFooter — shown when isLoading is false. Contains a compass icon, a Quit button, a Back/Back to Game button, a MenuNavGuide, and a Discord link.
  • loadingFooter — shown when isLoading is true. Contains a rotating loading quote (cycling every 5 seconds from L10n.strings.loading.quotes), a level name label, and a progress bar driven by loadPercent.

The Quit button routes to Routes.savebeforequit when isInGame is true, or Routes.quit otherwise. The Back button routes to Routes.back (pop) when _showBackButton is true, or calls BlackMesaEngine.executeClientCommand('gameui_hide') when _showBackToGameButton is true.

The Discord link opens BlackMesaUtils.discordLink via Qt.openUrlExternally after a 500 ms setTimeout delay (to allow the click sound to play first).

Binding Capture MouseArea

A full-screen MouseArea with z: 2000 sits above all other content. It is enabled only when InputBindingsManager.isBinding is true. When active, it intercepts all mouse button clicks and scroll wheel events and forwards them to InputBindingsManager.handleBindingResponse with the appropriate key string from InputBindingsManager.mouseMap.

Engine Event Handlers

All engine signals are handled in a single Connections block targeting BlackMesaEngine, with ignoreUnknownSignals: true and enabled: !isMenuBlocked.

onKeyCaptured

Converts the raw keyButtonCode to a string via BlackMesaEngine.keyButtonCodeToString(). If InputBindingsManager.isBinding is true, forwards to handleBindingResponse. If a binding cell is selected and Escape is pressed, calls InputBindingsManager.clearSelection().

onGameUIActived

Note: the signal name is onGameUIActived (missing the 't' in "Activated") — this matches the engine's signal name.

  1. Calls BlackMesaEngine.grabInputForGameUI() to capture keyboard/mouse input.
  2. Recomputes isInGame: true only if the engine reports in-game, _isInitialLoad is false, the level is not the main menu background, and no level is currently loading.
  3. On the initial load, calls wallpaper.updateBackgroundImage() with the main menu background name.
  4. If loadingErrorFlag is set, clears it and routes to Routes.multiplayer to show the server list after a failed connection.
  5. Otherwise, if not currently loading and either this is the initial load or the UI was not already visible, unhides the header and routes to Routes.index.
  6. Makes appRoot visible and forces active focus.
  7. If single-player and in-game, executes setpause with nomsg to pause the game silently.
onGameUIHidden
  1. Resets didLoadLevel to false.
  2. Closes the dev console.
  3. Hides appRoot.
  4. Hides the header (the footer fades with appRoot and does not need explicit hiding).
  5. Routes to emptyRoute, passing didLoadLevel as the immediate flag — if true, the transition is instant (level just loaded); if false, the normal fade-out animation plays.
  6. Calls BlackMesaEngine.releaseInputFromGameUI().
  7. If single-player and in-game, executes unpause with nomsg.
onLevelLoadingStarted
  1. Executes unpause with nomsg.
  2. Determines shouldUpdateProgressBar: true if the engine's showProgressDialog flag is set, or if the level is the main menu background, or if the level name is empty.
  3. If shouldUpdateProgressBar and the UI is already visible, manually fires BlackMesaEngine.gameUIActived() to trigger the onGameUIActived handler. This is acknowledged as a cross-handler hack.
  4. Updates the wallpaper to the loading level's background.
  5. Calls BlackMesaEngine.setShouldUpdateProgressBar(shouldUpdateProgressBar).
  6. Releases input, sets isInGame = false, isLoadingLevel = true, shows the wallpaper image, hides extras, stops the background music timer, routes to emptyRoute immediately, and hides the header.
onLevelLoadingFinished

The most complex handler. Receives isError, failureReason, showProgressDialog, and levelName as injected variables from the engine.

  1. Clears _isInitialLoad, isLoadingLevel, sets didLoadLevel = true.
  2. Recomputes isInGame and isInMultiplayerMode.
  3. Resets loadPercent and footer.levelName.

Then branches on three cases:

Case Condition Actions
Load error isError === true Stores failureReason, shows alertLoadFailed, sets loadingErrorFlag = true, resets didLoadLevel and isInGame to false.
Main menu background loaded isLevelMainMenuBackground Calls Sound.startMusic(), unhides header, routes to index, updates wallpaper, grabs input.
Game level loaded else Sets didLoadLevel = false, isInGame = false, unhides header, calls Sound.stopMusic(), routes to index, updates wallpaper.

The "game level loaded" branch sets isInGame = false temporarily. The correct isInGame value is recomputed in the subsequent onGameUIActived call when the player opens the menu.

onDisconnectedFromServer

Updates both footer.isInGame and appRoot.isInGame from BlackMesaEngine.isInGame() filtered by isLevelMainMenuBackground().

onUpdateProgressValue

Sets appRoot.loadPercent = progressValue. Drives the loading progress bar in loadingFooter.

autoBackgroundMusicTimer

A one-shot Timer with a 1250 ms interval that starts running immediately on construction. It is a fallback for the case where the engine never fires onLevelLoadingFinished (e.g., the UI is loaded without a level load event, or the engine starts in a state where the loading sequence is already complete).

On trigger:

1. Sets _isInitialLoad = false and isLoadingLevel = false.

2. Unhides the header.

3. Shows wallpaper extras.

4. Routes to Routes.index.

5. Updates the wallpaper.

6. Calls Sound.startMusic().

The timer is stopped in onLevelLoadingStarted to prevent it from firing during a level load. A TODO comment describes this as "bitfucking".

alertLoadFailed

An inline Alert (component-alert.qml) shown when a level load fails (e.g., failed server connection). It uses BlackMesaEngine.getLocalizedString() directly for both its title (#BlackMesaUI_Error) and button label (#GameUI_OK), bypassing the L10n singleton. It has a single DefaultButton that resets levelLoadingFinished_FailureReason and calls alertLoadFailed.hide().

The Alert component itself (component-alert.qml) is a full-screen MouseArea that intercepts all pointer events to prevent click-through. It animates the modal panel in from y+300 over 600 ms using Easing.InOutQuint, and out to y+300 then immediately to y+30000 (off-screen) on hide. On show, it calls BlackMesaUtils.traverseUIElements() and BlackMesaUtils.afterTraverseCallback() after a 450 ms delay to register the alert's buttons with the controller navigation system.

Notable Issues

1. onGameUIActived typo. The signal handler name is missing the 't' in "Activated". This matches the engine's signal name (gameUIActived), so it works correctly, but it is a persistent typo in both the engine and the QML layer.

2. Cross-handler invocation in onLevelLoadingStarted. The handler manually calls BlackMesaEngine.gameUIActived() to trigger onGameUIActived under certain conditions. The comment acknowledges this as "not good" and explains that it is the reason for the complex conditional logic in onGameUIActived.

3. isInGame is set to false in the "game level loaded" branch of onLevelLoadingFinished. This is a temporary state: the correct value is recomputed in the next onGameUIActived. However, between onLevelLoadingFinished and onGameUIActived, any code that reads appRoot.isInGame will see false even though the player is in-game.

4. _isInitialLoad check in onLevelLoadingFinished line 301 is redundant. _isInitialLoad is set to false on the immediately preceding line, so the expression !_isInitialLoad && ... always evaluates to true && ....

5. autoBackgroundMusicTimer and onLevelLoadingFinished both clear _isInitialLoad. If the engine fires onLevelLoadingFinished normally, the timer fires 1250 ms later and redundantly re-runs the index routing and music start logic. The timer is not stopped in onLevelLoadingFinished.

6. component-wallpaper.qml has mismatched widescreen file mappings. background06_widescreen maps to background02_widescreen.vtf (should be background06_widescreen.vtf). background09_widescreen, background10_widescreen, and background11_widescreen are each off by one index.

7. component-wallpaper.qml references subNavBackground without the Theme.colors. prefix. The gradient stop on line 147 uses the bare identifier subNavBackground, which is not in scope. This resolves to undefined, making the gradient stop effectively transparent.

8. alertLoadFailed bypasses L10n. Both the title and button label use BlackMesaEngine.getLocalizedString() directly, inconsistent with all other alert dialogs in the codebase.

9. component-alert.qml positions the hidden modal at anchors.verticalCenterOffset: 30000. This is a hack to move the modal off-screen in the hidden state without using visible: false (which would prevent the show animation from running). The value 30000 is large enough to guarantee the modal is off-screen at any resolution.

10. Connections block is disabled during menu animation. Setting enabled: !isMenuBlocked means that if the engine fires onGameUIHidden or onLevelLoadingStarted while the 625 ms open/close animation is playing, those signals are silently dropped. This is the intended behavior (to prevent visual artifacts from rapid ESC presses), but it means the UI can get into an inconsistent state if the engine fires critical signals during the animation window.

qmldir.

qmldir is the QML module manifest for the Black Mesa UI module. It is read by the QML engine at startup to register all named types and singletons that can be imported by other .qml files in the same module. It does not need to be explicitly imported — all registered types are available globally within the module.

The file has 40 lines and registers 34 named types across six logical groups, separated by blank lines.

Format

Each non-blank line follows one of two forms:

Form Meaning
singleton TypeName 1.0 filename.qml Registers a pragma Singleton QtObject as a module-wide singleton. Only one instance exists for the lifetime of the application.
TypeName 1.0 filename.qml Registers a reusable component. A new instance is created each time the type is used in QML.

The version number is 1.0 for every entry.

Singletons (lines 1–6)

Registered name Source file Purpose
L10n l10n.qml Localization singleton. Exposes all UI strings via L10n.strings.* and provides getDateTimeString() and locale helpers.
Theme theme.qml Design system singleton. Provides scaling properties (widthScale, heightScale), colors, opacities, sounds, fonts, and the locale dictionary.
Sound sound.qml Audio singleton. Wraps BlackMesaEngine audio calls for music (startMusic, stopMusic) and UI sound effects (playEffect).
BlackMesaUtils utils.qml Utility singleton. Provides save/load game helpers, a setTimeout polyfill, and the entire keyboard/controller UI navigation system (navigationUIHandle, traverseUIElements, etc.).
InputBindingsManager input-bindings-manager.qml Key binding singleton. Manages the in-memory binding state, conflict detection, and flush/reset operations for the bindings page.
Routes routes.qml Route registry singleton. Declares all 22 named Route objects as readonly property Route members.

Primitive (line 8)

Registered name Source file Purpose
Triangle triangle.qml A clipped, rotated Rectangle that renders a triangle. Controlled by a corner property (0–3) and a color alias.

Buttons (lines 10–16)

Registered name Source file Purpose
TriangleButton button-triangle.qml A Triangle-based directional button used as carousel pagination arrows.
CarouselButton button-carouselnav.qml A navigation button used inside carousels.
CTAButton button-cta.qml Call-to-action button. Extends DefaultButton with boxColor set to Theme.colors.highlight (orange). Used for primary/safe actions.
DefaultButton button-default.qml The base button component. Renders a bordered box with text; supports focused, blurred, and disabled states with color transitions and sound effects.
WarningButton button-warning.qml Extends DefaultButton with boxColor set to Theme.colors.warning (red). Used for destructive actions.
LetterboxButton button-letterbox.qml A wide tab-style button used in the main navigation header and sub-navigation bars.
MainNavButton button-mainnav.qml A navigation button used in the top-level main nav bar.

Developer Console (line 18)

Registered name Source file Purpose
DevConsole component-devconsole.qml The in-game developer console overlay. Uses Theme.devConsole colors and Theme.fonts.devConsole (Fira Mono).

Carousel (lines 20–23)

Registered name Source file Purpose
Carousel component-carousel.qml The carousel container. Manages a ListModel of items, left/right pagination arrows, and item selection.
CarouselItem component-carousel-item.qml The base carousel item delegate. Provides thumbnail, text, and selection signal infrastructure.
CarouselNewGameItem component-carousel-item-newgame.qml A CarouselItem variant for campaign/chapter selection. Displays a chapter name, type label, and thumbnail.
CarouselLoadGameItem component-carousel-item-loadgame.qml A CarouselItem variant for save game slots. Displays chapter name, date, save type, and an optional secondary (delete) button.

Layout Components (lines 25–28)

Registered name Source file Purpose
Wallpaper component-wallpaper.qml The animated background image component. Manages background image selection and transitions.
Header component-header.qml The top navigation bar. Renders the main nav, sub-nav, and sub-nav-nav tab rows; manages tab highlight state based on currentRoute.
Footer component-footer.qml The bottom bar. Renders action buttons, the loading screen overlay, and the controller navigation guide. Decides whether to route to quit or savebeforequit.

Routing (lines 30–32)

Registered name Source file Purpose
Route route.qml Data object describing a single route. Properties: name, path, qmlFile, alert, action, passthrough, destination, rank.
Router router.qml The StackView-based navigation controller. Handles setRoute, push/replace/pop logic, transition selection, and signal propagation for saveGameRequest, loadGameRequest, and loadMapRequest.
RouteView routeview.qml The base class for all route pages. A FocusScope with opacity: 0 and signals: routeRequest, loadGameRequest, loadMapRequest, saveGameRequest.

UI Components (lines 34–40)

Registered name Source file Purpose
Alert component-alert.qml A modal dialog overlay. Accepts titleText, messageText, and a VisualItemModel of buttons. Used by quit, save-before-quit, video unsaved changes, and binding overwrite dialogs.
OptionsList component-optionslist.qml The options page container. Manages a list of OptionsListRow items, pending-change tracking, flush/reset, and the savereloadaftersettingschange command.
OptionsListRow component-optionslist-row.qml A single row in an options list. Renders a label and an input widget (slider, select, checkbox, map, binding cell, or separator) based on the row's type property.
VerticalScrollBar component-scrollbar-vertical.qml A styled vertical scroll bar used in the options list, policy page, translators page, and achievements page.
BindingList component-binding.qml The key binding list for a single category. Renders a ListView of binding rows, each with a label and one or two BindingCell inputs.
BindingCell component-optionslist-input-bindingcell.qml A single key binding input cell. Displays the current bound key and enters capture mode on click to accept a new key press.
MenuNavGuide component-menu-navigation-guide.qml The controller button legend shown at the bottom of the screen, indicating which buttons perform which actions in the current context.

Files present in the directory but not registered

The following .qml files exist in bms/ui/ but have no entry in qmldir. They are either loaded by filename string at runtime, used as inline sub-components via Qt.createComponent, or are unreachable stubs.

File Reason not registered
main.qml The application root. Loaded directly by the engine as the entry point, not imported as a named type.
devtest.qml A development/testing file. Not part of the production UI flow.
routeview-achievements.qml Loaded dynamically by router.qml via the qmlFile string on the corresponding Route object.
routeview-addons.qml (same as above)
routeview-audio.qml (same as above)
routeview-bindings.qml (same as above)
routeview-campaigns.qml Unregistered stub. Has no corresponding entry in routes.qml and is unreachable through any normal navigation flow.
routeview-empty.qml Loaded dynamically by router.qml.
routeview-game.qml (same as above)
routeview-host.qml (same as above)
routeview-index.qml (same as above)
routeview-input.qml (same as above)
routeview-join.qml (same as above)
routeview-loadgame.qml (same as above)
routeview-newgame.qml (same as above)
routeview-policy.qml (same as above)
routeview-quit.qml (same as above)
routeview-savebeforequit.qml (same as above)
routeview-savegame.qml (same as above)
routeview-translators.qml (same as above)
routeview-unavailable.qml Loaded dynamically by the engine or router as a fallback when a requested route cannot be loaded. Not referenced by name anywhere in the QML layer.
routeview-video.qml Loaded dynamically by router.qml.
component-binding-combat.qml Instantiated inline inside component-binding.qml (BindingList) via a Loader or direct reference, not as a named module type.
component-binding-misc.qml (same as above)
component-binding-movement.qml (same as above)
component-binding-multiplayer.qml (same as above)
component-binding-weapons.qml (same as above)
component-optionslist-input-binding.qml Used as an inline sub-component of component-optionslist-row.qml (OptionsListRow), not as a named module type.
component-optionslist-input-checkbox.qml (same as above)
component-optionslist-input-map.qml (same as above)
component-optionslist-input-select.qml (same as above)
component-optionslist-input-separator.qml (same as above)
component-optionslist-input-slider.qml (same as above)
component-optionslist-input-text.qml (same as above)

Notable Issues

1. No explicit module declaration. A qmldir file can begin with a module directive (e.g. module com.crowbarcollective.blackmesa) to give the module a qualified import path. This file has none, meaning the module is identified only by its file system location and is imported implicitly by the engine rather than via an import statement.

2. All versions are 1.0. No component has been versioned beyond 1.0. QML's versioning system allows older consumers to pin to a specific API version, but since all types share the same version, the versioning provides no practical isolation.

3. BindingCell is registered but its sibling input types are not. component-optionslist-input-bindingcell.qml is registered as BindingCell 1.0, but the six other input types (slider, select, checkbox, map, binding, separator, text) are not registered. This inconsistency suggests BindingCell was promoted to a named type because it is also used directly by component-binding.qml outside of the OptionsListRow context, while the other input types are only ever used inside OptionsListRow.

sound.qml

Registered as the Sound singleton in qmldir. It is a pragma Singleton QtObject that wraps BlackMesaEngine's audio API into a clean, named interface for the rest of the UI.

Properties

  • ambientId — a writable int that stores the handle returned by BlackMesaEngine.playAmbientSound, used to track and stop the currently playing ambient/music track.
  • music — a readonly array of the two music track paths pulled from Theme.sounds.music1 and Theme.sounds.music2.

Functions

  • startMusic() - picks one of the two music tracks at random and calls startAmbient() with it.
  • stopMusic() - delegates to stopAmbient().
  • playEffect(filestr) - plays a one-shot UI sound effect via BlackMesaEngine.playSoundEffect.
  • isPlayingAmbient() - returns true if ambientId is non-null/non-zero.
  • startAmbient(filestr) - stops any current ambient, reads snd_musicvolume from the console, then calls BlackMesaEngine.playAmbientSound and stores the returned ID in ambientId.
  • stopAmbient() - if ambientId is set and the sound is still playing, stops it via BlackMesaEngine.stopSoundById and nulls ambientId.

Bug

There is a typo on line 41: ambiendId (extra d) instead of ambientId. This means stopAmbient() will throw a ReferenceError at runtime when it tries to stop a playing sound, so ambient tracks can never actually be stopped once started. sound.qml:39-44

Usage across the codebase

Sound is used in two distinct patterns.


Music lifecycle — startMusic/stopMusic are called from:

  • main.qml (5 matches) — likely on gameui_activated/gameui_hidden signals.
  • routeview-index.qml (6 matches) — starts/stops music when the main menu index page is entered/exited.
  • component-footer.qml (4 matches) — manages music during the loading screen.


UI sound effects — playEffect is called from virtually every interactive component, passing Theme.sounds.buttonFocused on hover and Theme.sounds.buttonClicked on press:

  • All button types: button-default.qml, button-letterbox.qml, button-triangle.qml, button-carouselnav.qml.
  • All options list inputs: component-optionslist-input-slider.qml, component-optionslist-input-select.qml, component-optionslist-input-map.qml, component-optionslist-input-checkbox.qml, component-optionslist-input-bindingcell.qml.
  • List rows and carousel items: component-optionslist-row.qml, component-carousel-item.qml.
  • Route views: routeview-bindings.qml, routeview-join.qml.

theme.qml

Registered as the Theme singleton in qmldir and serves as the global design system for the entire UI — fonts, colors, opacities, sounds, and locale utilities all live here.

Layout

It is a pragma Singleton QtObject with multiple top-level members.

Scaling properties

rootWidth, rootHeight, widthScale, and heightScale are writable properties (no readonly). They are set externally, in main.qml, the primary source, using Binding elements for the scale properties and onWidthChanged/onHeightChanged handlers for the raw dimensions, and routeview-video.qml — directly reassigns all four when the user applies a resolution change from the video settings page, so the UI rescales immediately without waiting for a window resize event. Also used throughout the UI to scale elements to the current resolution. Triangle for example uses Theme.heightScale directly.

dictionary — locale map

A nested QtObject mapping Steam language names (e.g. "english", "schinese", "koreana") to BCP 47 locale codes (e.g. "en_US", "zh_CN", "ko_KR"). Used by getDateTimeString.

getDateTimeString(date) — locale-aware date formatter

Reads cl_language from the engine console, looks it up in dictionary, then formats the date using Qt's toLocaleString with a localized format string fetched from BlackMesaEngine.getLocalizedString.

colors — color palette

All named colors used across the UI:

  • highlight - #e47125 (orange).
  • text/buttonText/headerText - white.
  • dimmedText - #888888 (gray).
  • subNavBackground - #111111 (black).
  • skrim - #2d2d2d (dark gray).
  • modalBackground - #222222 (darker gray).
  • warning - #c72424 (red).
  • navigationHighlight - #e88849 (lighter orange), for controller-focused active buttons.
opacity — named opacity levels

Seven named opacity values for different UI layers: subNav (0.5), mainNav (0.75), modal (0.95), modalHeader (0.85), modalSkrim (0.9), pageSkrimLight (0.75), pageSkrimDark (0.85).

sounds — UI sound effect paths

Four named sound paths: buttonFocused, buttonClicked, and two music tracks (music1, music2). The music paths are prefixed with #.

fonts — font family strings

Loads six font files via FontLoader from the VFS (vfs:///ui/fonts/): Fira Mono (dev console), and NotoSans in Light/Bold/Regular plus their CJK variants. The public fonts.light, fonts.bold, and fonts.regular properties are comma-joined font family strings that list the CJK font first so it takes priority for CJK characters.

devConsole — dev console sub-theme

A nested color palette specifically for the developer console: background (#d0202020), message (lightgray), inputText (#ffd0d0d0). The fonts.devConsole property (Fira Mono) pairs with this.

triangle.qml

This a small, reusable primitive that renders a triangle shape using a rotated, clipped Rectangle. It is registered in qmldir as the Triangle component (not a singleton).

How it works

The component is an Item with clip: true. Inside it sits a Rectangle that is rotated 45° and scaled up by 1.4 * Theme.heightScale, so only one corner of the rotated square peeks out through the clipping boundary — producing a triangle.

The position of that corner is controlled by the corner property (an integer, default 0). The x and y of the inner rectangle are calculated using modular arithmetic on corner to snap it to one of the four corners of the parent Item (triangle.qml around lines 14-15):

x = component.width  * ((corner+1) % 4 < 2 ? 0 : 1) - width/2  
y = component.height * ( corner    % 4 < 2 ? 0 : 1) - height/2

The color property is aliased directly to the inner rect.color, so consumers can set it like any normal color property.

Usage

Triangle is used by button-triangle.qml (TriangleButton), which sets rotation on the Triangle instance to point it left or right, and animates its color between blurredColor and focusedColor on hover.

utils.qml

Registered as the BlackMesaUtils singleton in qmldir and serves as the central utility and UI navigation hub for the entire menu system. Stores some utils and helpers.

Structure Overview

It is a pragma Singleton QtObject with two main responsibilities, save/load game helpers and controller/keyboard UI navigation.

General Utilities

  • discordLink — a hardcoded string "https://discord.gg/crowbarcollective", used as invite link to Crowbar Collective's server in Discord.
  • setTimeout(cb, delay) — a polyfill for JavaScript's setTimeout, since Qt has no native equivalent. Uses a shared globalTimer and properly disconnects signals after firing.

Save/Load Game Functions

  • getSaveGames() — calls BlackMesaEngine.listSaveEntries(), sorts by date descending, and maps each entry into a normalized object with savename, chapter, chapterName, type ("manual", "autosave", or "quick"), dateCreated, and thumbnail.
  • saveGame(filename, callback) — auto-generates a zero-padded file name like bms-001 if none is provided, then issues a gameui_hide;save engine command and calls back.
  • loadGame(filename)/loadMap(filename) — issue disconnect;wait;wait;sv_cheats 0; maxplayers 1; load/map engine commands.

UI Navigation System

This is the bulk of the file. It implements a regex-based UI traversal and keyboard/controller navigation system.

State Properties

Tracks the current/previous focused element, a flat tabs array, indices for main/sub/sub-nav tab levels, actionButtons (APPLY, CANCEL, DISCARD, QUIT, BACK), and optionItems (list rows and carousel items).

Key Functions
  • clearUIElementsData() - resets all navigation state before a screen transition.
  • traverseUIElements(root) - recursively walks the QML tree, classifying elements by objectName regex into tabs, buttons, option items, or carousel items.
  • afterTraverseCallback() - post-traversal: sets sub-tab start indices and focuses the first option item.
  • processOptionSelection(sign) - moves up/down through optionItems, skipping disabled ones.
  • processCarouselItemSelection(sign) - moves left/right through carousel items, triggering pagination arrows as needed.
  • processTabsNavigation(sign) - handles left/right navigation across 3 levels of tabs (main -> sub -> sub-nav).
  • navigationUIHandle(event) - entry point called from Keys.onPressed in main.qml; dispatches all key events (Enter, Backspace, A/D, arrows) to the above functions.
  • updateCurrentUISelection() - applies "focused"/"blurred" states to elements and scrolls lists to keep the selection visible.
Navigation Priority (Backspace/Back button)

When backspace is pressed, it checks in order: in-game -> DISCARD -> CANCEL -> BACK, giving a clear priority chain for controller "B button" behavior.