diff --git a/src/device/controller.ts b/src/device/controller.ts index 877f6213..da95a308 100644 --- a/src/device/controller.ts +++ b/src/device/controller.ts @@ -60,61 +60,33 @@ import { type InterfaceTheme, } from "../features/settings/interface-preferences"; import { displayText, displayTemplate, batteryStateText, connectionText, ensureDisplayLocale, layerLabel, t, tp, type I18nKey } from "../i18n/index"; -import { - EGG_BUTTON_NAMES, +import type { + EggButtonIndex, + EggButtonMapping, + EggSpdtMode, EggOp1HidClient, - type EggButtonIndex, - type EggButtonMapping, - type EggSpdtMode, } from "@openmouse/protocol/drivers/endgame/egg-op1-hid"; -import { - EGG_WE_DISPLAY_NAME, - eggWeAuthorizedPool, - eggWeFromAuthorized, - eggWeIsSupported, - eggWeOwnsDevice, - eggWePrepare, - eggWeResolveConnect, - isEggWeClient, - type EggWeHidClient, -} from "@openmouse/protocol/drivers/endgame/egg-we-control"; -import { AtkBitmouseHidClient } from "@openmouse/protocol/drivers/atk/bitmouse-hid"; -import { AtkHidClient } from "@openmouse/protocol/drivers/atk/hid"; -import { LamzuAtlantisHidClient } from "@openmouse/protocol/drivers/lamzu-atlantis/hid"; -import { LamzuHidClient } from "@openmouse/protocol/drivers/lamzu/hid"; -import { - LogitechHidppClient, - NotAMouseError, - PROFILE_DPI_WRITES_ENABLED, - type OnboardProfile, -} from "@openmouse/protocol/drivers/logitech/hidpp"; -import { - BUNNY_HOP_LIMITS, - PROFILE_STAGE_LOD, - capabilitiesForFormat, - clampDpi, - describeOffset, - dpiStageCapabilitiesForOptions, - reportRateCapabilitiesFor, - reportRatesForDevice, - validateProfileName, - reproduceProfile, - supportsFactoryReset, - supportsProfileWriteProbe, - validateBunnyHoppingMs, - type DpiStageCapabilities, - type DpiStagePlan, - type LogitechButtonAction, - type LogitechButtonBinding, - type LogitechMacroStep, +import type { EggWeHidClient } from "@openmouse/protocol/drivers/endgame/egg-we-control"; +import type { AtkBitmouseHidClient } from "@openmouse/protocol/drivers/atk/bitmouse-hid"; +import type { AtkHidClient } from "@openmouse/protocol/drivers/atk/hid"; +import type { LamzuAtlantisHidClient } from "@openmouse/protocol/drivers/lamzu-atlantis/hid"; +import type { LamzuHidClient } from "@openmouse/protocol/drivers/lamzu/hid"; +import type { LogitechHidppClient, OnboardProfile } from "@openmouse/protocol/drivers/logitech/hidpp"; +import type { + DpiStageCapabilities, + DpiStagePlan, + LogitechButtonAction, + LogitechButtonBinding, + LogitechMacroStep, } from "@openmouse/protocol/drivers/logitech/onboard-profiles"; +import type { MagneticButtonClient } from "@openmouse/protocol/drivers/magnetic"; import { setCaptureContext } from "../features/capture/capture-context"; import { decodeProfileKey, encodeProfileKey, profileKeyMatchesDevice, type ProfileKeyPayload, } from "./profile-key"; import { hasCapturedFactoryProfiles } from "./logitech-factory"; +import { ensureDriverModules, driverModules, type DriverModules } from "./driver-classes"; import type { MagneticButtonStatus, MouseLighting, MouseStatus } from "@openmouse/protocol/drivers/mouse-types"; -import { isMagneticButtonClient, type MagneticButtonClient } from "@openmouse/protocol/drivers/magnetic"; import type { KsnakeMacroProfile } from "@openmouse/protocol/ksnake"; import type { WallhackCurvePoint, WallhackMacroStep } from "@openmouse/protocol/wallhack"; import { @@ -129,82 +101,42 @@ import { type M2NexProfile, } from "./m2nex-profiles"; import { isNoirE1Status, isNoirKsnakeStatus as isNoirKsnakeIdentity, isNoirS1Status as isNoirS1Identity } from "./noir.ts"; -import { - LOGITECH_HAPTIC_EFFECTS, - LOGITECH_HAPTIC_PRESETS, - LOGITECH_SMART_SHIFT_OFF, - logitechControlName, - type LogitechHapticPreset, - type LogitechReprogrammableControl, +import type { + LogitechHapticPreset, + LogitechReprogrammableControl, } from "@openmouse/protocol/logitech"; -import { PulsarHidClient } from "@openmouse/protocol/drivers/pulsar/pulsar-hid"; -import { PulsarProHidClient } from "@openmouse/protocol/drivers/pulsar/pulsar-pro-hid"; -import { PulsarXs1HidClient } from "@openmouse/protocol/drivers/pulsar/pulsar-xs1-hid"; -import { OrbitalHidClient } from "@openmouse/protocol/drivers/orbital/hid"; -import { RazerHidClient, razerProbeControlInterface } from "@openmouse/protocol/drivers/razer/hid"; -import { - RAZER_BUTTON_CONTROL_LABEL, - RAZER_TOGGLE_CONTROL_INFO, - type RazerButtonControl, - type RazerButtonMapping, - type RazerToggleControl, +import type { OrbitalHidClient } from "@openmouse/protocol/drivers/orbital/hid"; +import type { RazerHidClient } from "@openmouse/protocol/drivers/razer/hid"; +import type { + RazerButtonControl, + RazerButtonMapping, + RazerToggleControl, } from "@openmouse/protocol/razer"; -import { RazerViperMiniHidClient } from "@openmouse/protocol/drivers/razer/viper-mini-hid"; -import { RazerCobraHidClient } from "@openmouse/protocol/drivers/razer/cobra-hid"; -import { RazerViperHidClient } from "@openmouse/protocol/drivers/razer/viper-hid"; -import { RazerViperV4ProHidClient } from "@openmouse/protocol/drivers/razer/viper-v4-pro-hid"; -import { RAZER_PRODUCTS } from "@openmouse/protocol/razer-devices"; -import { FinalmouseHidClient } from "@openmouse/protocol/drivers/finalmouse/hid"; -import { ModdoHidClient } from "@openmouse/protocol/drivers/moddo/hid"; -import { NinjutsoHidClient } from "@openmouse/protocol/drivers/ninjutso/hid"; -import { ZaunkoenigHidClient } from "@openmouse/protocol/drivers/zaunkoenig/hid"; -import { CorsairHidClient } from "@openmouse/protocol/drivers/corsair/hid"; -import { CorsairBragiHidClient } from "@openmouse/protocol/drivers/corsair/bragi-hid"; -import { TeevolutionHidClient } from "@openmouse/protocol/drivers/teevolution/hid"; -import { teevolutionProfileForCid } from "@openmouse/protocol/teevolution"; -import { VgnF2HidClient } from "@openmouse/protocol/drivers/vgn/hid"; -import { KeychronNapeHidClient } from "@openmouse/protocol/drivers/keychron/nape-hid"; -import { Keychron8kHidClient } from "@openmouse/protocol/drivers/keychron/mouse-8k-hid"; -import { Keychron1kHidClient } from "@openmouse/protocol/drivers/keychron/mouse-1k-hid"; -import { Keychron4kHidClient } from "@openmouse/protocol/drivers/keychron/mouse-4k-hid"; -import { Keychron8kNordicHidClient } from "@openmouse/protocol/drivers/keychron/mouse-8k-nordic-hid"; +import type { RazerViperMiniHidClient } from "@openmouse/protocol/drivers/razer/viper-mini-hid"; +import type { RazerCobraHidClient } from "@openmouse/protocol/drivers/razer/cobra-hid"; +import type { RazerViperHidClient } from "@openmouse/protocol/drivers/razer/viper-hid"; +import type { RazerViperV4ProHidClient } from "@openmouse/protocol/drivers/razer/viper-v4-pro-hid"; +import type { FinalmouseHidClient } from "@openmouse/protocol/drivers/finalmouse/hid"; +import type { NinjutsoHidClient } from "@openmouse/protocol/drivers/ninjutso/hid"; +import type { TeevolutionHidClient } from "@openmouse/protocol/drivers/teevolution/hid"; +import type { VgnF2HidClient } from "@openmouse/protocol/drivers/vgn/hid"; +import type { KeychronNapeHidClient } from "@openmouse/protocol/drivers/keychron/nape-hid"; +import type { Keychron8kHidClient } from "@openmouse/protocol/drivers/keychron/mouse-8k-hid"; +import type { Keychron1kHidClient } from "@openmouse/protocol/drivers/keychron/mouse-1k-hid"; +import type { Keychron4kHidClient } from "@openmouse/protocol/drivers/keychron/mouse-4k-hid"; import type { GloriousLighting } from "@openmouse/protocol/glorious"; -import { GloriousHidClient } from "@openmouse/protocol/drivers/glorious/hid"; -import { GloriousClassicHidClient } from "@openmouse/protocol/drivers/glorious/classic-hid"; -import { GloriousCore2HidClient } from "@openmouse/protocol/drivers/glorious/core2-hid"; -import { MchoseHidClient } from "@openmouse/protocol/drivers/mchose/hid"; -import { MchoseDockHidClient } from "@openmouse/protocol/drivers/mchose/dock-hid"; -import { MchoseA5ProMaxHidClient } from "@openmouse/protocol/drivers/mchose/a5-gen1-hid"; -import { MchoseV3HidClient } from "@openmouse/protocol/drivers/mchose/v3-hid"; -import { FantechHidClient } from "@openmouse/protocol/drivers/fantech/hid"; -import { WallhackMouseHidClient } from "@openmouse/protocol/drivers/wallhack/mouse-hid"; -import { WallhackKeyboardHidClient } from "@openmouse/protocol/drivers/wallhack/keyboard-hid"; -import { WootingHidClient } from "@openmouse/protocol/drivers/wooting/hid"; -import { - KEYCHRON_NAPE_KEYCODE, - KEYCHRON_NAPE_KEY_CONTROLS, - keychronActionForKeycode, - keychronKeycodeForAction, - keychronLayerKeymapFromCodes, - keychronLayerLabel, - keychronOrientationIndex, - keychronOrientationLabel, - type KeychronNapeButtonAction, - type KeychronNapeLayerKeymap, +import type { WallhackMouseHidClient } from "@openmouse/protocol/drivers/wallhack/mouse-hid"; +import type { + KeychronNapeButtonAction, + KeychronNapeLayerKeymap, } from "@openmouse/protocol/keychron"; -import { VENDOR_ID } from "@openmouse/protocol/drivers/vendors"; +import type { WLMouseHidClient } from "@openmouse/protocol/drivers/wlmouse/hid"; +import type { WLMouseBeastX4kHidClient } from "@openmouse/protocol/drivers/wlmouse/beast-x-4k-hid"; +import type { DareuHidClient } from "@openmouse/protocol/drivers/dareu/hid"; +import type { IncottHidClient } from "@openmouse/protocol/drivers/incott/hid"; import { BASILISK_V3_PRO_BLUETOOTH, HID_FILTERS } from "./hid-filters"; -import { WLMouseHidClient } from "@openmouse/protocol/drivers/wlmouse/hid"; -import { WLMouseBeastX4kHidClient } from "@openmouse/protocol/drivers/wlmouse/beast-x-4k-hid"; -import { MicrosoftHidClient } from "@openmouse/protocol/drivers/microsoft/hid"; -import { DareuHidClient } from "@openmouse/protocol/drivers/dareu/hid"; -import { IncottHidClient } from "@openmouse/protocol/drivers/incott/hid"; -import { BytechHidClient } from "@openmouse/protocol/drivers/bytech/hid"; -import { FaterHidClient } from "@openmouse/protocol/drivers/fater/hid"; -import { RapooHidClient } from "@openmouse/protocol/drivers/rapoo/hid"; -import { CoolerMasterHidClient } from "@openmouse/protocol/drivers/coolermaster/hid"; -import { AjazzHidClient } from "@openmouse/protocol/drivers/ajazz/hid"; -import { RedragonM690ProHidClient } from "@openmouse/protocol/drivers/redragon/m690-pro-hid"; +import { VENDOR_ID } from "@openmouse/protocol/drivers/vendors"; +import { RAZER_PRODUCTS } from "@openmouse/protocol/razer-devices"; import { parsePreviewMode, previewsEnabled, type FixturePreviewMode, type PreviewMode } from "./preview/preview-modes"; import { sleepLabel } from "./options"; import { traitsFor } from "./traits"; @@ -293,42 +225,79 @@ export function isNativeAttackSharkX11(status: MouseStatus | null | undefined): type ClientClass = abstract new (...args: never[]) => T; -function activeAs(...classes: ClientClass[]): T | null { - for (const cls of classes) if (active instanceof cls) return active as T; +function activeAs(...classes: Array | undefined>): T | null { + for (const cls of classes) if (cls && active instanceof cls) return active as T; return null; } -const DM_CLASSES = [WLMouseHidClient, LamzuHidClient, LamzuAtlantisHidClient, AtkHidClient, AtkBitmouseHidClient, NinjutsoHidClient] as const; -const RAZER_CLASSES = [RazerHidClient, RazerViperMiniHidClient, RazerViperHidClient, RazerCobraHidClient] as const; -const NEEDS_OPEN = [LamzuAtlantisHidClient, TeevolutionHidClient, VgnF2HidClient, KeychronNapeHidClient, Keychron8kNordicHidClient, WLMouseBeastX4kHidClient, ModdoHidClient, ZaunkoenigHidClient, CorsairHidClient, CorsairBragiHidClient, FantechHidClient, WallhackMouseHidClient, WallhackKeyboardHidClient, GloriousHidClient, GloriousClassicHidClient, GloriousCore2HidClient, MchoseHidClient, MchoseDockHidClient, MchoseA5ProMaxHidClient, MchoseV3HidClient, MicrosoftHidClient, DareuHidClient, IncottHidClient, BytechHidClient, RapooHidClient, FaterHidClient, CoolerMasterHidClient, RedragonM690ProHidClient, AjazzHidClient] as const; -const PULSAR_CLASSES = [PulsarHidClient, PulsarProHidClient, PulsarXs1HidClient] as const; +/** Class identity test that tolerates the driver modules not being loaded yet. */ +function isA(client: unknown, cls: ClientClass | undefined): client is T { + return cls !== undefined && client instanceof cls; +} + +/** Strict driver-module read. Call only where a device context already exists. */ +function C(): DriverModules { + const mods = driverModules(); + if (!mods) throw new Error("Driver modules are not loaded yet"); + return mods; +} + +/** Pre-load tolerant driver-module read: null before the lazy chunk lands. */ +function CM(): DriverModules | null { + return driverModules(); +} + +// The class tables read the lazy modules at call time. Before the load +// resolves every entry is undefined, so activeAs returns null — which matches +// the pre-load state, where no client is active anyway. +const dmClasses = (): Array | undefined> => + [CM()?.WLMouseHidClient, CM()?.LamzuHidClient, CM()?.LamzuAtlantisHidClient, CM()?.AtkHidClient, CM()?.AtkBitmouseHidClient, CM()?.NinjutsoHidClient]; +const razerClasses = (): Array | undefined> => + [CM()?.RazerHidClient, CM()?.RazerViperMiniHidClient, CM()?.RazerViperHidClient, CM()?.RazerCobraHidClient]; +const needsOpenClasses = (): Array | undefined> => [ + CM()?.LamzuAtlantisHidClient, CM()?.TeevolutionHidClient, CM()?.VgnF2HidClient, CM()?.KeychronNapeHidClient, + CM()?.Keychron8kNordicHidClient, CM()?.WLMouseBeastX4kHidClient, CM()?.ModdoHidClient, CM()?.ZaunkoenigHidClient, + CM()?.CorsairHidClient, CM()?.CorsairBragiHidClient, CM()?.FantechHidClient, CM()?.WallhackMouseHidClient, + CM()?.WallhackKeyboardHidClient, CM()?.GloriousHidClient, CM()?.GloriousClassicHidClient, CM()?.GloriousCore2HidClient, + CM()?.MchoseHidClient, CM()?.MchoseDockHidClient, CM()?.MchoseA5ProMaxHidClient, CM()?.MchoseV3HidClient, + CM()?.MicrosoftHidClient, CM()?.DareuHidClient, CM()?.IncottHidClient, CM()?.BytechHidClient, CM()?.RapooHidClient, + CM()?.FaterHidClient, CM()?.CoolerMasterHidClient, CM()?.RedragonM690ProHidClient, CM()?.AjazzHidClient, +]; +const pulsarClasses = (): Array | undefined> => + [CM()?.PulsarHidClient, CM()?.PulsarProHidClient, CM()?.PulsarXs1HidClient]; -const logitechClient = (): LogitechHidppClient | null => activeAs(LogitechHidppClient); -const eggClient = (): EggOp1HidClient | null => activeAs(EggOp1HidClient); +const logitechClient = (): LogitechHidppClient | null => activeAs(CM()?.LogitechHidppClient); +const eggClient = (): EggOp1HidClient | null => activeAs(CM()?.EggOp1HidClient); const eggWeClient = (): EggWeHidClient | null => - active !== null && isEggWeClient(active) ? active : null; + active !== null && CM()?.isEggWeClient(active) === true ? active : null; const dmClient = (): WLMouseHidClient | LamzuHidClient | LamzuAtlantisHidClient | AtkHidClient | AtkBitmouseHidClient | NinjutsoHidClient | null => - activeAs(...DM_CLASSES); + activeAs(...dmClasses()); const razerClient = (): RazerHidClient | RazerViperMiniHidClient | RazerViperHidClient | RazerCobraHidClient | null => - activeAs(...RAZER_CLASSES); -const viperClient = (): RazerViperV4ProHidClient | null => activeAs(RazerViperV4ProHidClient); + activeAs(...razerClasses()); +const viperClient = (): RazerViperV4ProHidClient | null => activeAs(CM()?.RazerViperV4ProHidClient); -const teevolutionClient = (): TeevolutionHidClient | null => activeAs(TeevolutionHidClient); +const teevolutionClient = (): TeevolutionHidClient | null => activeAs(CM()?.TeevolutionHidClient); const dpiLightingClient = (): TeevolutionHidClient | AtkHidClient | DareuHidClient | null => - activeAs(TeevolutionHidClient, AtkHidClient, DareuHidClient); -const finalmouseClient = (): FinalmouseHidClient | null => activeAs(FinalmouseHidClient); -const orbitalClient = (): OrbitalHidClient | null => activeAs(OrbitalHidClient); -const vgnClient = (): VgnF2HidClient | null => activeAs(VgnF2HidClient); -const keychronNapeClient = (): KeychronNapeHidClient | null => activeAs(KeychronNapeHidClient); -const keychron8kClient = (): Keychron8kHidClient | null => activeAs(Keychron8kHidClient); -const keychron1kClient = (): Keychron1kHidClient | null => activeAs(Keychron1kHidClient); -const keychron4kClient = (): Keychron4kHidClient | null => activeAs(Keychron4kHidClient); -const wlmouse4kClient = (): WLMouseBeastX4kHidClient | null => activeAs(WLMouseBeastX4kHidClient); -const wallhackMouseClient = (): WallhackMouseHidClient | null => activeAs(WallhackMouseHidClient); -const incottClient = (): IncottHidClient | null => activeAs(IncottHidClient); + activeAs(CM()?.TeevolutionHidClient, CM()?.AtkHidClient, CM()?.DareuHidClient); +const finalmouseClient = (): FinalmouseHidClient | null => activeAs(CM()?.FinalmouseHidClient); +const orbitalClient = (): OrbitalHidClient | null => activeAs(CM()?.OrbitalHidClient); +const vgnClient = (): VgnF2HidClient | null => activeAs(CM()?.VgnF2HidClient); +const keychronNapeClient = (): KeychronNapeHidClient | null => activeAs(CM()?.KeychronNapeHidClient); +const keychron8kClient = (): Keychron8kHidClient | null => activeAs(CM()?.Keychron8kHidClient); +const keychron1kClient = (): Keychron1kHidClient | null => activeAs(CM()?.Keychron1kHidClient); +const keychron4kClient = (): Keychron4kHidClient | null => activeAs(CM()?.Keychron4kHidClient); +const wlmouse4kClient = (): WLMouseBeastX4kHidClient | null => activeAs(CM()?.WLMouseBeastX4kHidClient); +const wallhackMouseClient = (): WallhackMouseHidClient | null => activeAs(CM()?.WallhackMouseHidClient); +const incottClient = (): IncottHidClient | null => activeAs(CM()?.IncottHidClient); /** Pulsar is the only family with the collection-explorer onboarding path. */ const pulsarClient = (): PulsarClient | null => - active !== null ? activeAs(...PULSAR_CLASSES) : null; + active !== null ? activeAs(...pulsarClasses()) : null; + +// The driver chunk starts loading as soon as this module is imported; every +// flow that can set the active client awaits it first (see activateClient, +// refreshSidebar and the connect paths), so the tables above are populated +// before any client can exist. +void ensureDriverModules(); let onboardProfiles: OnboardProfile[] | null = null; let buttons: LogitechReprogrammableControl[] | null = null; @@ -487,7 +456,7 @@ export function getActiveDevice(): HIDDevice | null { function buildProfileView(): ProfileView { const entry = editedProfileEntry(); const rates = lastProfileFormat - ? reportRateCapabilitiesFor(lastProfileFormat.id, latestDeviceStatus?.transportIds?.USB) + ? C().reportRateCapabilitiesFor(lastProfileFormat.id, latestDeviceStatus?.transportIds?.USB) : null; return { entry, @@ -495,7 +464,7 @@ function buildProfileView(): ProfileView { slotsAvailable: dpiSlotsAvailable(), slotsLocked: dpiSlotsLocked(), slotLimits: dpiSlotLimits(), - lodLevels: lastProfileFormat ? capabilitiesForFormat(lastProfileFormat.id).supportedLods : [], + lodLevels: lastProfileFormat ? C().capabilitiesForFormat(lastProfileFormat.id).supportedLods : [], rateOptions: { wireless: profileReportRateOptions("wireless"), wired: profileReportRateOptions("wired"), @@ -635,7 +604,7 @@ function buildSnapshot(): ControlSnapshot { captureAvailable: logitechClient() !== null && latestDeviceStatus?.brand === "Logitech", resetProfilesAvailable: logitechClient() !== null && latestDeviceStatus?.brand === "Logitech" - && supportsFactoryReset(latestDeviceStatus?.onboardProfileFormat?.id ?? null), + && C().supportsFactoryReset(latestDeviceStatus?.onboardProfileFormat?.id ?? null), setupProfilesAvailable: logitechClient() !== null && latestDeviceStatus?.brand === "Logitech" && hasCapturedFactoryProfiles(latestDeviceStatus?.onboardProfileFormat) @@ -1381,7 +1350,7 @@ export function clearWallhackMacroSlot(slot: number): void { } function readCapabilities(): DeviceCapabilities { - const razer = activeAs(RazerHidClient); + const razer = activeAs(CM()?.RazerHidClient); const dm = dmClient(); const keychron = keychronNapeClient(); return { @@ -1414,7 +1383,7 @@ function readCapabilities(): DeviceCapabilities { razerLowPowerOptions: razer?.getLowPowerOptions() ?? null, lowPowerPollingCeiling: razer?.getLowPowerPollingCeiling() ?? null, teevolutionProfile: (teevolutionClient()?.getModelProfile() - ?? teevolutionProfileForCid(14)) as TeevolutionProfile | null, + ?? C().teevolutionProfileForCid(14)) as TeevolutionProfile | null, }; } @@ -1602,8 +1571,8 @@ async function writeStagedHaptics(): Promise { if (stagedHapticIntensity !== null) await client.setHapticIntensity(stagedHapticIntensity); if (stagedHapticIntensity !== null || stagedHapticEnabled === true) { const effect = stagedHapticEnabled === true && stagedHapticIntensity === null - ? LOGITECH_HAPTIC_EFFECTS.enableConfirmation - : LOGITECH_HAPTIC_EFFECTS.strengthSample; + ? C().LOGITECH_HAPTIC_EFFECTS.enableConfirmation + : C().LOGITECH_HAPTIC_EFFECTS.strengthSample; await client.playHapticEffect(effect).catch(() => undefined); } } @@ -1624,12 +1593,12 @@ async function writeStagedWheelMode(): Promise { export function applyHapticIntensity(preset: LogitechHapticPreset): void { if (!logitechClient()) return; - stagedHapticIntensity = LOGITECH_HAPTIC_PRESETS[preset]; + stagedHapticIntensity = C().LOGITECH_HAPTIC_PRESETS[preset]; stageChange({ key: "haptic-strength", group: HAPTIC_GROUP, label: `Haptics ${preset.toLowerCase()}`, command: `Set haptic strength to ${preset} (${stagedHapticIntensity})`, progress: `Setting haptic strength to ${preset.toLowerCase()}…`, - preview: (status) => { status.hapticIntensity = LOGITECH_HAPTIC_PRESETS[preset]; }, + preview: (status) => { status.hapticIntensity = C().LOGITECH_HAPTIC_PRESETS[preset]; }, apply: writeStagedHaptics, }); } @@ -1671,12 +1640,12 @@ export function applyWheelMode(mode: NonNullable): voi export function applySmartShiftThreshold(threshold: number | null): void { if (!logitechClient()) return; stagedSmartShift = threshold; - const off = threshold === null || threshold === LOGITECH_SMART_SHIFT_OFF; + const off = threshold === null || threshold === C().LOGITECH_SMART_SHIFT_OFF; stageChange({ key: "smart-shift", group: RATCHET_GROUP, label: off ? "SmartShift off" : `SmartShift ${threshold}`, command: off ? "Turn SmartShift off" : `Set the SmartShift threshold to ${threshold}`, progress: off ? "Turning SmartShift off…" : `Setting the SmartShift threshold to ${threshold}…`, - preview: (status) => { status.smartShiftThreshold = threshold ?? LOGITECH_SMART_SHIFT_OFF; }, + preview: (status) => { status.smartShiftThreshold = threshold ?? C().LOGITECH_SMART_SHIFT_OFF; }, apply: writeStagedRatchet, }); } @@ -1797,7 +1766,7 @@ const PULSAR_TOGGLE_FIELDS = [ ] as const satisfies readonly PulsarToggleSetting[]; function nearestHapticPreset(intensity: number): LogitechHapticPreset { - const presets = Object.entries(LOGITECH_HAPTIC_PRESETS) as [LogitechHapticPreset, number][]; + const presets = Object.entries(C().LOGITECH_HAPTIC_PRESETS) as [LogitechHapticPreset, number][]; return presets.reduce((best, entry) => Math.abs(entry[1] - intensity) < Math.abs(best[1] - intensity) ? entry : best)[0]; } @@ -1861,7 +1830,7 @@ export function applyGameProfileSnapshot(snapshot: GameProfileSnapshot): void { if (s.debounceMs != null) applyPulsarValue("debounce", s.debounceMs); if (s.sleepTimeout != null) applyPulsarValue("sleep", s.sleepTimeout); if (s.lowBatteryWarning != null) applyLowPowerThreshold(s.lowBatteryWarning); - const pulsarPro = pulsarClient() instanceof PulsarProHidClient; + const pulsarPro = isA(pulsarClient(), CM()?.PulsarProHidClient); if (s.angleTuning != null) { if (pulsarPro) applyProSetting("angleTuning", s.angleTuning); else applyAngleTuning(s.angleTuning); @@ -2005,7 +1974,7 @@ export function applyButtonMapping(controlId: number, targetControlId: number): return; } stagedButtonMappings.set(controlId, targetControlId); - const target = logitechControlName(targetControlId); + const target = C().logitechControlName(targetControlId); stageChange({ key: `button-${controlId}`, group: BUTTON_GROUP, @@ -2054,7 +2023,7 @@ export async function restoreDivertedButtons(): Promise { } export async function selectAtkR1Profile(profile: number): Promise { - const client = activeAs(AtkHidClient); + const client = activeAs(CM()?.AtkHidClient); if (!client || refreshInProgress || settingInProgress) return; if (hasPendingChanges()) { setReadStatus(st("ctl.atkPending")); @@ -2147,7 +2116,7 @@ export function selectAtkDongleLight(mode: number): void { export async function pairAtkR1SePlusReceiver(): Promise { if (blockedByGameProfileDraft()) return; - const client = activeAs(AtkHidClient); + const client = activeAs(CM()?.AtkHidClient); if (!client || !isVxeR1SePlusReceiver(activeDevice) || refreshInProgress || settingInProgress) return; const device = activeDevice; settingInProgress = true; @@ -2450,13 +2419,13 @@ function configureProfileCapture(status: MouseStatus | null): void { })), }; }, - describeOffset: (offset) => describeOffset(formatId, offset), - reproduce: (before, after) => reproduceProfile(before, after, formatId), + describeOffset: (offset) => C().describeOffset(formatId, offset), + reproduce: (before, after) => C().reproduceProfile(before, after, formatId), } : null, writeProbe: profileClient === null ? null - : supportsProfileWriteProbe(formatId) + : C().supportsProfileWriteProbe(formatId) ? { supported: true, reason: `Run the guarded write probe for profile format ${formatId}`, @@ -2754,9 +2723,9 @@ function applyStatusInner(deviceStatus: MouseStatus, statusKey?: string): void { /** Whether a client appears as a keyboard or a mouse in the sidebar. */ function sidebarEntryForm(client: SupportedClient): "mouse" | "keyboard" { - if (client instanceof KeychronNapeHidClient - || client instanceof WootingHidClient - || client instanceof WallhackKeyboardHidClient) return "keyboard"; + if (isA(client, CM()?.KeychronNapeHidClient) + || isA(client, CM()?.WootingHidClient) + || isA(client, CM()?.WallhackKeyboardHidClient)) return "keyboard"; return "mouse"; } @@ -2794,9 +2763,9 @@ async function sidebarEntries(devices: HIDDevice[]): Promise { const status = deviceStatuses.get(device); const name = status?.name ?? status?.ui?.defaultDisplayName - ?? (isEggWeClient(client) - ? EGG_WE_DISPLAY_NAME - : client instanceof FinalmouseHidClient + ?? (C().isEggWeClient(client) + ? C().EGG_WE_DISPLAY_NAME + : isA(client, CM()?.FinalmouseHidClient) ? client.displayName() : (device.productName ?? `${await deviceBrand(client)} mouse`)); const detail = status @@ -2817,6 +2786,9 @@ async function sidebarEntries(devices: HIDDevice[]): Promise { } async function refreshSidebar(devices?: HIDDevice[]): Promise { + // Sidebar entries name and classify devices through the lazy driver modules; + // make sure they are here before reading them. + await ensureDriverModules(); let all: HIDDevice[]; if (devices) { all = devices; @@ -2894,6 +2866,7 @@ async function authorizedDeviceGroups(): Promise { /** Activate the authorized device group the user picked in the device list. */ export async function selectAuthorizedDevice(index: number): Promise { + await ensureDriverModules(); await waitForControllerIdle(); const groups = await authorizedDeviceGroups(); if (!groups) return; @@ -2997,7 +2970,7 @@ export async function removeAuthorizedDevice(index: number): Promise { const group = groups?.[index]; if (!group) return; const name = sidebarDevices[index]?.name ?? group[0]?.productName ?? ""; - const isOpen = group.some((device) => device === activeDevice || eggWeOwnsDevice(eggWeClient(), device)) + const isOpen = group.some((device) => device === activeDevice || C().eggWeOwnsDevice(eggWeClient(), device)) || (activeKeyboard !== null && group.some((device) => device === activeDevice)); if (isOpen) { const client = active; @@ -3176,8 +3149,8 @@ export async function showDeviceDashboard(): Promise { } function statusNameForClient(client: SupportedClient): string { - if (isEggWeClient(client)) return EGG_WE_DISPLAY_NAME; - if (client instanceof FinalmouseHidClient) return client.displayName(); + if (C().isEggWeClient(client)) return C().EGG_WE_DISPLAY_NAME; + if (isA(client, CM()?.FinalmouseHidClient)) return client.displayName(); return client.device.productName || st("ctl.selectedMouse"); } @@ -3209,7 +3182,7 @@ function clearActiveKeyboard(): void { */ async function probeReceiverFirmware(client: SupportedClient, connectionType: string | undefined): Promise { latestReceiverFirmware = null; - if (!(client instanceof LogitechHidppClient)) { + if (!isA(client, CM()?.LogitechHidppClient)) { if (import.meta.env?.DEV === true) console.log('[firmware] receiver probe skipped: not a Logitech client'); return; } @@ -3426,8 +3399,8 @@ async function activateClientNow(client: SupportedClient): Promise { activeWorkspaceTab = "overview"; try { - if (isEggWeClient(client)) await eggWePrepare(client); - if (NEEDS_OPEN.some((cls) => client instanceof cls)) await (client as { open(): Promise }).open(); + if (C().isEggWeClient(client)) await C().eggWePrepare(client); + if (needsOpenClasses().some((cls) => cls !== undefined && client instanceof cls)) await (client as { open(): Promise }).open(); if (pulsarClient() !== null) { await showPulsarExplorer(client as PulsarClient); @@ -3554,6 +3527,9 @@ async function loadKeyboardTrigger(client: KeyboardClient): Promise { /** Queue a device activation so only one keyboard/mouse switch runs at a time. */ function activateClient(target: SupportedClient | KeyboardClient, autoConnect = false): Promise { const run = activationQueue.then(async () => { + // The queued body reads the lazy driver tables (accessors, preview + // stand-ins); nothing may set `active` before they exist. + await ensureDriverModules(); activationInProgress = true; try { if (autoConnect && !isKeyboardClient(target)) { @@ -3647,16 +3623,17 @@ function handleHidConnect(event: HIDConnectionEvent): void { return; } void (async () => { + await ensureDriverModules(); const client = await createSupportedClient(event.device); if (!client) { void refreshSidebar(); return; } - if (isEggWeClient(client)) { + if (C().isEggWeClient(client)) { const all = await navigator.hid?.getDevices() ?? []; await refreshSidebar(all); - const result = await eggWeResolveConnect(event.device, eggWeClient(), activeDevice, all); + const result = await C().eggWeResolveConnect(event.device, eggWeClient(), activeDevice, all); if (result.action === "ignore") return; if (result.action === "refresh") { try { @@ -3671,7 +3648,7 @@ function handleHidConnect(event: HIDConnectionEvent): void { deviceStatusText = result.reason === "path" ? st("ctl.switchingPath") : st("ctl.newDevice"); readStatus = result.reason === "path" ? st("ctl.preferUsb") - : st("ctl.reading", { name: EGG_WE_DISPLAY_NAME }); + : st("ctl.reading", { name: C().EGG_WE_DISPLAY_NAME }); emit(); await activateClient(result.client); return; @@ -3690,7 +3667,7 @@ function handleHidConnect(event: HIDConnectionEvent): void { function handleHidDisconnect(event: HIDConnectionEvent): void { deviceStatuses.delete(event.device); // Multi-collection drivers (cmd + notify) treat either handle as the active mouse. - if (event.device !== activeDevice && !eggWeOwnsDevice(eggWeClient(), event.device)) { + if (event.device !== activeDevice && !C().eggWeOwnsDevice(eggWeClient(), event.device)) { void refreshSidebar(); return; } @@ -3717,6 +3694,9 @@ function handleHidDisconnect(event: HIDConnectionEvent): void { async function requestSupportedClient( onSelected?: (device: HIDDevice) => void, ): Promise { + // Connect flows classify devices and read module-level tables (Razer probe, + // egg-we control) from the lazy driver chunk below; load it before the picker. + await ensureDriverModules(); if (!navigator.hid) throw new Error(st("ctl.noWebHid")); const devices = await navigator.hid.requestDevice({ filters: HID_FILTERS }); if (devices.length === 0) { @@ -3736,8 +3716,8 @@ async function requestSupportedClient( // whichever one happens to be active when the error lands. onSelected?.(devices[0]); - if (devices.some((device) => eggWeIsSupported(device))) { - const weClient = eggWeFromAuthorized(await eggWeAuthorizedPool(devices)); + if (devices.some((device) => C().eggWeIsSupported(device))) { + const weClient = C().eggWeFromAuthorized(await C().eggWeAuthorizedPool(devices)); if (weClient) return weClient; } @@ -3750,7 +3730,7 @@ async function requestSupportedClient( .sort((left, right) => right.score - left.score); const best = ranked[0]; if (best?.client) { - if (isEggWeClient(best.client)) await eggWePrepare(best.client); + if (C().isEggWeClient(best.client)) await C().eggWePrepare(best.client); return best.client; } @@ -3792,7 +3772,7 @@ async function requestSupportedClient( let probedRazer = false; if (razerCandidates.length > 0) { probedRazer = true; - const probed = await razerProbeControlInterface(devices); + const probed = await C().razerProbeControlInterface(devices); if (probed) return probed; } @@ -3856,7 +3836,7 @@ export async function connect(): Promise { track("device_connected", deviceProps(attempted)); } catch (error) { const message = error instanceof Error ? error.message : "Unable to read the mouse."; - const wrongDevice = error instanceof NotAMouseError; + const wrongDevice = isA(error, CM()?.NotAMouseError); if (!wrongDevice) recordDiagnosticError(error, message, false); track(wrongDevice ? "device_not_a_mouse" : "device_connection_failed", { ...deviceProps(attempted), @@ -4349,7 +4329,8 @@ export function applyLogitechAnalogButton(button: 0 | 1): void { function magneticClient(): MagneticButtonClient | null { const client = activeSettingsClient(); - return isMagneticButtonClient(client) ? client : null; + const magnetic = CM()?.isMagneticButtonClient; + return magnetic !== undefined && magnetic(client) ? client : null; } const MAGNETIC_SIDE = ["Left", "Right"] as const; @@ -4553,7 +4534,7 @@ function syncEditedProfile(): void { export function dpiSlotLimits(): DpiStageCapabilities | null { const format = lastProfileFormat; return format - ? dpiStageCapabilitiesForOptions(capabilitiesForFormat(format.id).dpiStages, dpiOptions) + ? C().dpiStageCapabilitiesForOptions(C().capabilitiesForFormat(format.id).dpiStages, dpiOptions) : null; } @@ -4563,7 +4544,7 @@ export function dpiSlotsAvailable(): boolean { /** True while the flash write sequence for stage tables is still unproven. */ export function dpiSlotsLocked(): boolean { - return !PROFILE_DPI_WRITES_ENABLED || lastProfileFormat?.writable !== true; + return !(CM()?.PROFILE_DPI_WRITES_ENABLED ?? true) || lastProfileFormat?.writable !== true; } function syncDpiSlotPlan(): void { @@ -4635,8 +4616,8 @@ export function setDpiSlotCount(count: number): void { stageDpiSlots(); } -function snapSlotDpi(value: number, limits: Parameters[1]): number { - if (dpiOptions.length === 0 || !Number.isFinite(value)) return clampDpi(value, limits); +function snapSlotDpi(value: number, limits: Parameters[1]): number { + if (dpiOptions.length === 0 || !Number.isFinite(value)) return C().clampDpi(value, limits); const target = Math.min(limits.maxDpi, Math.max(limits.minDpi, value)); let best = dpiOptions[0]; for (const option of dpiOptions) { @@ -4666,7 +4647,7 @@ export function setDpiSlotLod(index: number, level: LiftOffLevel): void { if (blockedByGameProfileDraft()) return; const stage = dpiSlotPlan?.stages[index]; if (!stage || dpiSlotsLocked()) return; - stage.lod = PROFILE_STAGE_LOD[level]; + stage.lod = C().PROFILE_STAGE_LOD[level]; stageDpiSlots(); } @@ -4871,22 +4852,22 @@ function napeAssignmentKey(layer: number, control: NapeAssignmentControl): strin function napeControlLabel(control: NapeAssignmentControl): string { if (control.kind === "orientation") return "Orientation"; if (control.kind === "wheel") return control.clockwise ? "Scroll wheel CW" : "Scroll wheel CCW"; - return KEYCHRON_NAPE_KEY_CONTROLS.find((entry) => entry.col === control.col)?.name ?? `0${control.col}`; + return C().KEYCHRON_NAPE_KEY_CONTROLS.find((entry) => entry.col === control.col)?.name ?? `0${control.col}`; } function previewNapeKeymap(layer: number): KeychronNapeLayerKeymap { - return keychronLayerKeymapFromCodes( + return C().keychronLayerKeymapFromCodes( layer, [ - KEYCHRON_NAPE_KEYCODE.leftClick, - KEYCHRON_NAPE_KEYCODE.scrollMode, - KEYCHRON_NAPE_KEYCODE.rightClick, - KEYCHRON_NAPE_KEYCODE.dpiCycle, - KEYCHRON_NAPE_KEYCODE.forward, - KEYCHRON_NAPE_KEYCODE.backward, + C().KEYCHRON_NAPE_KEYCODE.leftClick, + C().KEYCHRON_NAPE_KEYCODE.scrollMode, + C().KEYCHRON_NAPE_KEYCODE.rightClick, + C().KEYCHRON_NAPE_KEYCODE.dpiCycle, + C().KEYCHRON_NAPE_KEYCODE.forward, + C().KEYCHRON_NAPE_KEYCODE.backward, ], - KEYCHRON_NAPE_KEYCODE.volumeDown, - KEYCHRON_NAPE_KEYCODE.volumeUp, + C().KEYCHRON_NAPE_KEYCODE.volumeDown, + C().KEYCHRON_NAPE_KEYCODE.volumeUp, 2, ); } @@ -4926,11 +4907,11 @@ function patchNapeKeymap(layer: number, control: NapeAssignmentControl, keycode: if (napeKeymap?.layer === layer) napeKeymap = next; return; } - const columns = KEYCHRON_NAPE_KEY_CONTROLS.map((entry) => { + const columns = C().KEYCHRON_NAPE_KEY_CONTROLS.map((entry) => { if (control.kind === "key" && entry.col === control.col) return keycode; return map.keys.find((key) => key.col === entry.col)?.keycode ?? 0; }); - const next = keychronLayerKeymapFromCodes( + const next = C().keychronLayerKeymapFromCodes( layer, columns, control.kind === "wheel" && !control.clockwise ? keycode : map.wheel.ccw.keycode, @@ -4986,15 +4967,15 @@ export function applyNapeAssignment( ): void { if (blockedByGameProfileDraft()) return; if (!isAnyPreview && !keychronNapeClient()) return; - const keycode = keychronKeycodeForAction(action); - applyNapeAssignmentValue(layer, control, keychronActionForKeycode(keycode), keycode); + const keycode = C().keychronKeycodeForAction(action); + applyNapeAssignmentValue(layer, control, C().keychronActionForKeycode(keycode), keycode); } export function applyNapeOrientation(layer: number, index: number): void { if (blockedByGameProfileDraft()) return; if (!isAnyPreview && !keychronNapeClient()) return; - const next = keychronOrientationIndex(index); - applyNapeAssignmentValue(layer, { kind: "orientation" }, keychronOrientationLabel(next), next); + const next = C().keychronOrientationIndex(index); + applyNapeAssignmentValue(layer, { kind: "orientation" }, C().keychronOrientationLabel(next), next); } function applyNapeAssignmentValue( @@ -5018,9 +4999,9 @@ function applyNapeAssignmentValue( stageChange({ key, group: NAPE_REMAP_GROUP, - label: `${layerLabel(interfacePreferences.locale, keychronLayerLabel(layer))} · ${name} → ${action}`, - command: `${verb} ${keychronLayerLabel(layer)} ${name} to ${action}`, - progress: `${gerund} ${keychronLayerLabel(layer)} ${name} to ${action}…`, + label: `${layerLabel(interfacePreferences.locale, C().keychronLayerLabel(layer))} · ${name} → ${action}`, + command: `${verb} ${C().keychronLayerLabel(layer)} ${name} to ${action}`, + progress: `${gerund} ${C().keychronLayerLabel(layer)} ${name} to ${action}…`, apply: writeStagedNapeAssignments, }); } @@ -5064,7 +5045,7 @@ function syncEditedNapeLayer(status: MouseStatus): void { editedNapeLayer = status.napeLayer ?? 1; } const active = status.napeLayer ?? 1; - onboardStatus = st("ctl.runningFrom", { label: layerLabel(interfacePreferences.locale, keychronLayerLabel(active)), layers: st("ctl.layersCount", { n: count, s: count === 1 ? "" : "s" }) }); + onboardStatus = st("ctl.runningFrom", { label: layerLabel(interfacePreferences.locale, C().keychronLayerLabel(active)), layers: st("ctl.layersCount", { n: count, s: count === 1 ? "" : "s" }) }); } export function openNapeLayer(layer: number): void { @@ -5116,20 +5097,20 @@ export async function switchNapeLayer(layer: number): Promise { editedNapeLayer = layer; applyStatus({ ...status, napeLayer: layer }); installPreviewNapeKeymap(layer); - setReadStatus(st("ctl.previewSwitched", { label: layerLabel(interfacePreferences.locale, keychronLayerLabel(layer)) })); + setReadStatus(st("ctl.previewSwitched", { label: layerLabel(interfacePreferences.locale, C().keychronLayerLabel(layer)) })); return; } const client = keychronNapeClient(); if (!client || refreshInProgress || settingInProgress) return; settingInProgress = true; - readStatus = st("ctl.switchingLayer", { label: layerLabel(interfacePreferences.locale, keychronLayerLabel(layer)) }); + readStatus = st("ctl.switchingLayer", { label: layerLabel(interfacePreferences.locale, C().keychronLayerLabel(layer)) }); emit(); recordDiagnosticCommand(`Select Keychron layer ${layer}`); try { await client.setLayer(layer); editedNapeLayer = layer; applyStatus(await statusAfterWrite(client)); - onboardStatus = st("ctl.runningFromLabel", { label: layerLabel(interfacePreferences.locale, keychronLayerLabel(layer)) }); + onboardStatus = st("ctl.runningFromLabel", { label: layerLabel(interfacePreferences.locale, C().keychronLayerLabel(layer)) }); await loadNapeKeymap(layer); } catch (error) { recordDiagnosticError(error, st("ctl.unableLayer")); @@ -5231,7 +5212,7 @@ export function renameOnboardProfile(sector: number): void { if (blockedByGameProfileDraft()) return; const entry = onboardProfiles?.find((profile) => profile.sector === sector); if (!entry || !logitechClient()) return; - const maxLength = lastProfileFormat ? capabilitiesForFormat(lastProfileFormat.id).maxNameLength : null; + const maxLength = lastProfileFormat ? C().capabilitiesForFormat(lastProfileFormat.id).maxNameLength : null; if (maxLength === null) { setOnboardStatus(st("ctl.noNameField")); return; @@ -5242,7 +5223,7 @@ export function renameOnboardProfile(sector: number): void { const input = window.prompt(displayText(interfacePreferences.locale, `Profile name (up to ${maxLength} characters)`), current); if (input === null) return; - const invalid = validateProfileName(input, maxLength); + const invalid = C().validateProfileName(input, maxLength); if (invalid) { setOnboardStatus(invalid); return; @@ -5269,7 +5250,7 @@ export function renameOnboardProfile(sector: number): void { export async function resetLogitechProfiles(): Promise { if (blockedByGameProfileDraft()) return; const client = logitechClient(); - if (!client || settingInProgress || !supportsFactoryReset(lastProfileFormat?.id)) return; + if (!client || settingInProgress || !C().supportsFactoryReset(lastProfileFormat?.id)) return; const stagedWarning = hasPendingChanges() ? "\n\nYour staged, unflashed changes will also be discarded." @@ -5355,7 +5336,7 @@ export async function setUpLogitechProfiles(): Promise { } export function bunnyHopSupported(): boolean { - return editedProfileEntry() !== null && capabilitiesForFormat(lastProfileFormat?.id).bunnyHop; + return editedProfileEntry() !== null && C().capabilitiesForFormat(lastProfileFormat?.id).bunnyHop; } /** @@ -5367,7 +5348,7 @@ export function applyBunnyHopMs(milliseconds: number): void { if (blockedByGameProfileDraft()) return; if (!logitechClient()) return; - const invalid = validateBunnyHoppingMs(milliseconds); + const invalid = C().validateBunnyHoppingMs(milliseconds); if (invalid) { setOnboardStatus(invalid); return; @@ -5392,13 +5373,16 @@ export function applyBunnyHopMs(milliseconds: number): void { }); } -export { BUNNY_HOP_LIMITS }; - export function profileReportRateOptions(link: "wireless" | "wired"): number[] { const format = lastProfileFormat; - const rates = format ? reportRateCapabilitiesFor(format.id, latestDeviceStatus?.transportIds?.USB) : null; + // The snapshot build runs before the lazy driver chunk has landed (this is + // also called during the boot render); with no module there are no rate + // options to compute yet, which matches the no-device state. + const mods = CM(); + if (!mods) return []; + const rates = format ? mods.reportRateCapabilitiesFor(format.id, latestDeviceStatus?.transportIds?.USB) : null; const activeLink = latestDeviceStatus?.connectionType === "Wireless" ? "wireless" : "wired"; - return reportRatesForDevice( + return mods.reportRatesForDevice( rates, link, latestDeviceStatus?.supportedPollingRates ?? [], @@ -5692,16 +5676,16 @@ export function applyLowPowerThreshold(percent: number): void { * and have never been checked against it. */ function razerButtonClient(): RazerHidClient | null { - return activeAs(RazerHidClient); + return activeAs(CM()?.RazerHidClient); } export function applyRazerButtonMapping(control: RazerButtonControl, mapping: RazerButtonMapping): void { if (!razerButtonClient()) return; stageChange({ key: `razer-button-${control}`, - label: `${RAZER_BUTTON_CONTROL_LABEL[control]} → ${mapping}`, - command: `Change ${RAZER_BUTTON_CONTROL_LABEL[control]} mapping`, - progress: `Changing ${RAZER_BUTTON_CONTROL_LABEL[control]} mapping…`, + label: `${C().RAZER_BUTTON_CONTROL_LABEL[control]} → ${mapping}`, + command: `Change ${C().RAZER_BUTTON_CONTROL_LABEL[control]} mapping`, + progress: `Changing ${C().RAZER_BUTTON_CONTROL_LABEL[control]} mapping…`, preview: (status) => { if (status.razerButtonMappings) status.razerButtonMappings[control] = mapping; }, @@ -5715,7 +5699,7 @@ export function applyRazerButtonMapping(control: RazerButtonControl, mapping: Ra export function applyRazerToggleControl(control: RazerToggleControl, label: string): void { if (!razerButtonClient()) return; - const name = RAZER_TOGGLE_CONTROL_INFO[control].label; + const name = C().RAZER_TOGGLE_CONTROL_INFO[control].label; stageChange({ key: `razer-toggle-${control}`, label: `${name} → ${label}`, @@ -6073,8 +6057,8 @@ export function applyEggGlassMode(enabled: boolean): void { export function applyEggMulticlick(button: EggButtonIndex, value: number): void { stageEggChange({ key: `egg-multiclick-${button}`, - label: `${EGG_BUTTON_NAMES[button]} multiclick ${value}`, - what: `${EGG_BUTTON_NAMES[button]} multiclick filter`, + label: `${C().EGG_BUTTON_NAMES[button]} multiclick ${value}`, + what: `${C().EGG_BUTTON_NAMES[button]} multiclick filter`, preview: (status) => { if (status.eggMulticlickFilters) status.eggMulticlickFilters[button] = value; }, @@ -6085,8 +6069,8 @@ export function applyEggMulticlick(button: EggButtonIndex, value: number): void export function applyEggButtonMapping(button: EggButtonIndex, mapping: EggButtonMapping): void { stageEggChange({ key: `egg-mapping-${button}`, - label: `${EGG_BUTTON_NAMES[button]} → ${mapping}`, - what: `${EGG_BUTTON_NAMES[button]} mapping`, + label: `${C().EGG_BUTTON_NAMES[button]} → ${mapping}`, + what: `${C().EGG_BUTTON_NAMES[button]} mapping`, preview: (status) => { if (status.eggButtonMappings) status.eggButtonMappings[button] = mapping; }, @@ -6287,7 +6271,7 @@ export function applyProSetting( setting: "wheelAcceleration" | "angleTuning" | "profile", value: boolean | number, ): void { - if (!(pulsarClient() instanceof PulsarProHidClient)) return; + if (!isA(pulsarClient(), CM()?.PulsarProHidClient)) return; const what = setting === "wheelAcceleration" ? "wheel acceleration" : setting === "angleTuning" ? "angle tuning" : "onboard profile"; @@ -6305,7 +6289,7 @@ export function applyProSetting( }, apply: async () => { const client = pulsarClient(); - if (!(client instanceof PulsarProHidClient)) throw new Error(st("ctl.gone")); + if (!isA(client, CM()?.PulsarProHidClient)) throw new Error(st("ctl.gone")); if (setting === "wheelAcceleration") await client.setWheelAcceleration(Boolean(value)); if (setting === "angleTuning") await client.setAngleTuning(Number(value)); if (setting === "profile") await client.setProfile(Number(value)); @@ -6796,7 +6780,7 @@ function finalmousePreviewClient(initial: MouseStatus): FinalmouseHidClient { const status = structuredClone(initial) as SlxStatus & MouseStatus; const slx = (status as SlxStatus).finalmouseIsSlx === true; const count = (): number => (status as SlxStatus).finalmouseProfileCount ?? 5; - const client = Object.assign(Object.create(FinalmouseHidClient.prototype) as FinalmouseHidClient, { + const client = Object.assign(Object.create(C().FinalmouseHidClient.prototype) as FinalmouseHidClient, { device: {} as HIDDevice, open: async () => undefined, close: async () => undefined, @@ -6882,7 +6866,7 @@ function previewClient(): LogitechHidppClient { throw new Error(st("ctl.previewNoMouse")); }; // Real prototype: the driver accessors test with instanceof. - return Object.assign(Object.create(LogitechHidppClient.prototype) as LogitechHidppClient, { + return Object.assign(Object.create(C().LogitechHidppClient.prototype) as LogitechHidppClient, { writeActiveProfile: async () => undefined, setBunnyHoppingMs: refuse, setProfileDpiStages: refuse, @@ -7088,6 +7072,9 @@ function previewShelfEntry(index: number, name: string, selected: boolean): Side } async function showFixturePreview(name: PreviewMode): Promise { + // Fixture previews build stand-in clients from the real driver prototypes; + // the module has to be here before the fixture activates. + await ensureDriverModules(); const { PREVIEW_FIXTURES } = await import("./preview/preview-fixtures"); await loadPreviewEntries(); const fixture = name === "list" || name === "slots" || name === "superstrike" diff --git a/src/device/driver-classes.ts b/src/device/driver-classes.ts new file mode 100644 index 00000000..49114273 --- /dev/null +++ b/src/device/driver-classes.ts @@ -0,0 +1,153 @@ +/** + * The driver modules that controller.ts uses for runtime identity: the + * `instanceof` class checks behind every per-brand accessor, plus the small + * value helpers its settings logic calls (DPI clamping, profile capabilities, + * keycode maps). Loading them behind one shared dynamic import keeps roughly + * 800 kB of driver code out of the initial bundle: a session only ever talks + * to one brand, and by the time any of this can run (a device is connected) + * the module has long since arrived. Rollup merges the literal imports into + * one lazy chunk. + * + * Two access rules: + * - `ensureDriverModules()` awaits the load. Every flow that can set the + * active client or classify a device awaits it first, and the controller + * module also kicks it off at import time so the fetch overlaps app boot. + * - `driverModules()` peeks. Before the load resolves it returns null; call + * sites tolerate that (`isA`/`activeAs` treat a missing class as "not + * this client", which matches the pre-load state where no client is + * active anyway). Strict reads use `C()` in controller.ts, which throws + * loudly rather than computing with half a module. + */ +export type DriverModules = typeof import("@openmouse/protocol/drivers/endgame/egg-op1-hid") + & typeof import("@openmouse/protocol/drivers/endgame/egg-we-control") + & typeof import("@openmouse/protocol/drivers/atk/bitmouse-hid") + & typeof import("@openmouse/protocol/drivers/atk/hid") + & typeof import("@openmouse/protocol/drivers/lamzu-atlantis/hid") + & typeof import("@openmouse/protocol/drivers/lamzu/hid") + & typeof import("@openmouse/protocol/drivers/logitech/hidpp") + & typeof import("@openmouse/protocol/drivers/logitech/onboard-profiles") + & typeof import("@openmouse/protocol/drivers/magnetic") + & typeof import("@openmouse/protocol/logitech") + & typeof import("@openmouse/protocol/drivers/pulsar/pulsar-hid") + & typeof import("@openmouse/protocol/drivers/pulsar/pulsar-pro-hid") + & typeof import("@openmouse/protocol/drivers/pulsar/pulsar-xs1-hid") + & typeof import("@openmouse/protocol/drivers/orbital/hid") + & typeof import("@openmouse/protocol/drivers/razer/hid") + & typeof import("@openmouse/protocol/razer") + & typeof import("@openmouse/protocol/drivers/razer/viper-mini-hid") + & typeof import("@openmouse/protocol/drivers/razer/cobra-hid") + & typeof import("@openmouse/protocol/drivers/razer/viper-hid") + & typeof import("@openmouse/protocol/drivers/razer/viper-v4-pro-hid") + & typeof import("@openmouse/protocol/razer-devices") + & typeof import("@openmouse/protocol/drivers/finalmouse/hid") + & typeof import("@openmouse/protocol/drivers/moddo/hid") + & typeof import("@openmouse/protocol/drivers/ninjutso/hid") + & typeof import("@openmouse/protocol/drivers/zaunkoenig/hid") + & typeof import("@openmouse/protocol/drivers/corsair/hid") + & typeof import("@openmouse/protocol/drivers/corsair/bragi-hid") + & typeof import("@openmouse/protocol/drivers/teevolution/hid") + & typeof import("@openmouse/protocol/teevolution") + & typeof import("@openmouse/protocol/drivers/vgn/hid") + & typeof import("@openmouse/protocol/drivers/keychron/nape-hid") + & typeof import("@openmouse/protocol/drivers/keychron/mouse-8k-hid") + & typeof import("@openmouse/protocol/drivers/keychron/mouse-1k-hid") + & typeof import("@openmouse/protocol/drivers/keychron/mouse-4k-hid") + & typeof import("@openmouse/protocol/drivers/keychron/mouse-8k-nordic-hid") + & typeof import("@openmouse/protocol/drivers/glorious/hid") + & typeof import("@openmouse/protocol/drivers/glorious/classic-hid") + & typeof import("@openmouse/protocol/drivers/glorious/core2-hid") + & typeof import("@openmouse/protocol/drivers/mchose/hid") + & typeof import("@openmouse/protocol/drivers/mchose/dock-hid") + & typeof import("@openmouse/protocol/drivers/mchose/a5-gen1-hid") + & typeof import("@openmouse/protocol/drivers/mchose/v3-hid") + & typeof import("@openmouse/protocol/drivers/fantech/hid") + & typeof import("@openmouse/protocol/drivers/wallhack/mouse-hid") + & typeof import("@openmouse/protocol/drivers/wallhack/keyboard-hid") + & typeof import("@openmouse/protocol/drivers/wooting/hid") + & typeof import("@openmouse/protocol/keychron") + & typeof import("@openmouse/protocol/drivers/vendors") + & typeof import("@openmouse/protocol/drivers/wlmouse/hid") + & typeof import("@openmouse/protocol/drivers/wlmouse/beast-x-4k-hid") + & typeof import("@openmouse/protocol/drivers/microsoft/hid") + & typeof import("@openmouse/protocol/drivers/dareu/hid") + & typeof import("@openmouse/protocol/drivers/incott/hid") + & typeof import("@openmouse/protocol/drivers/bytech/hid") + & typeof import("@openmouse/protocol/drivers/fater/hid") + & typeof import("@openmouse/protocol/drivers/rapoo/hid") + & typeof import("@openmouse/protocol/drivers/coolermaster/hid") + & typeof import("@openmouse/protocol/drivers/ajazz/hid") + & typeof import("@openmouse/protocol/drivers/redragon/m690-pro-hid"); + +let loaded: DriverModules | null = null; +let loading: Promise | null = null; + +/** Fetch and merge every driver module above. Idempotent; the promise is shared. */ +export function ensureDriverModules(): Promise { + loading ??= Promise.all([ + import("@openmouse/protocol/drivers/endgame/egg-op1-hid"), + import("@openmouse/protocol/drivers/endgame/egg-we-control"), + import("@openmouse/protocol/drivers/atk/bitmouse-hid"), + import("@openmouse/protocol/drivers/atk/hid"), + import("@openmouse/protocol/drivers/lamzu-atlantis/hid"), + import("@openmouse/protocol/drivers/lamzu/hid"), + import("@openmouse/protocol/drivers/logitech/hidpp"), + import("@openmouse/protocol/drivers/logitech/onboard-profiles"), + import("@openmouse/protocol/drivers/magnetic"), + import("@openmouse/protocol/logitech"), + import("@openmouse/protocol/drivers/pulsar/pulsar-hid"), + import("@openmouse/protocol/drivers/pulsar/pulsar-pro-hid"), + import("@openmouse/protocol/drivers/pulsar/pulsar-xs1-hid"), + import("@openmouse/protocol/drivers/orbital/hid"), + import("@openmouse/protocol/drivers/razer/hid"), + import("@openmouse/protocol/razer"), + import("@openmouse/protocol/drivers/razer/viper-mini-hid"), + import("@openmouse/protocol/drivers/razer/cobra-hid"), + import("@openmouse/protocol/drivers/razer/viper-hid"), + import("@openmouse/protocol/drivers/razer/viper-v4-pro-hid"), + import("@openmouse/protocol/razer-devices"), + import("@openmouse/protocol/drivers/finalmouse/hid"), + import("@openmouse/protocol/drivers/moddo/hid"), + import("@openmouse/protocol/drivers/ninjutso/hid"), + import("@openmouse/protocol/drivers/zaunkoenig/hid"), + import("@openmouse/protocol/drivers/corsair/hid"), + import("@openmouse/protocol/drivers/corsair/bragi-hid"), + import("@openmouse/protocol/drivers/teevolution/hid"), + import("@openmouse/protocol/teevolution"), + import("@openmouse/protocol/drivers/vgn/hid"), + import("@openmouse/protocol/drivers/keychron/nape-hid"), + import("@openmouse/protocol/drivers/keychron/mouse-8k-hid"), + import("@openmouse/protocol/drivers/keychron/mouse-1k-hid"), + import("@openmouse/protocol/drivers/keychron/mouse-4k-hid"), + import("@openmouse/protocol/drivers/keychron/mouse-8k-nordic-hid"), + import("@openmouse/protocol/drivers/glorious/hid"), + import("@openmouse/protocol/drivers/glorious/classic-hid"), + import("@openmouse/protocol/drivers/glorious/core2-hid"), + import("@openmouse/protocol/drivers/mchose/hid"), + import("@openmouse/protocol/drivers/mchose/dock-hid"), + import("@openmouse/protocol/drivers/mchose/a5-gen1-hid"), + import("@openmouse/protocol/drivers/mchose/v3-hid"), + import("@openmouse/protocol/drivers/fantech/hid"), + import("@openmouse/protocol/drivers/wallhack/mouse-hid"), + import("@openmouse/protocol/drivers/wallhack/keyboard-hid"), + import("@openmouse/protocol/drivers/wooting/hid"), + import("@openmouse/protocol/keychron"), + import("@openmouse/protocol/drivers/vendors"), + import("@openmouse/protocol/drivers/wlmouse/hid"), + import("@openmouse/protocol/drivers/wlmouse/beast-x-4k-hid"), + import("@openmouse/protocol/drivers/microsoft/hid"), + import("@openmouse/protocol/drivers/dareu/hid"), + import("@openmouse/protocol/drivers/incott/hid"), + import("@openmouse/protocol/drivers/bytech/hid"), + import("@openmouse/protocol/drivers/fater/hid"), + import("@openmouse/protocol/drivers/rapoo/hid"), + import("@openmouse/protocol/drivers/coolermaster/hid"), + import("@openmouse/protocol/drivers/ajazz/hid"), + import("@openmouse/protocol/drivers/redragon/m690-pro-hid"), + ]).then((mods) => (loaded = Object.assign({}, ...mods) as DriverModules)); + return loading; +} + +/** The loaded modules, or null before the load resolves. */ +export function driverModules(): DriverModules | null { + return loaded; +}