Skip to content

[Issue-196] feat(mouse-control): add speed control horizontal scrolling and repair Cloud Sync - #197

Merged
CYoJkoY merged 4 commits into
mainfrom
issue-196-mouse-control-cloud-sync
Oct 30, 2026
Merged

CYoJkoY merged 4 commits into
mainfrom
issue-196-mouse-control-cloud-sync

Conversation

@CYoJkoY

@CYoJkoY CYoJkoY commented Oct 30, 2026 •

Copy link
Copy Markdown
Owner

Linked Issue

Closes #196: Add an adjustable cursor speed and horizontal scrolling to mouse control mode, require a double Shift to enter it, and repair Cloud Sync settings that vanished after Save and connection tests that failed with "This value of type GitHubGistProvider has no property named ApiBase".

  • Stacked Branch Dependencies: None (Directly branched from main)

Change summary

Staged breakdown of all diffs against main by commit:

  • e5b601a: Mouse control gains an adjustable cursor speed stored as [MouseControl] speedPercent, clamped to 20-300 with a default of 100 and edited from a new Settings card. Q and E drive horizontal wheel scrolling through MOUSEEVENTF_HWHEEL, with Alt selecting the larger step and the repeat timer stopped on exit. Entry now requires two Shift taps within 450 ms, while one Shift or Esc still exits. The hotkey reference, README, and translations describe the new gesture, speed field, and horizontal scroll.
  • 23a1970: Cloud Sync providers declare ApiBase and FileName as instance properties, which resolves the missing-property error raised by the Gist connection test. AppState now declares the ten Cloud Sync fields that ConfigManager.Save() wrote but ConfigManager.Load() could leave unassigned on a fresh install, so saving no longer throws before the values reach the INI. The dialog restores the WebDAV username, labels stored credentials, explains that blank secret fields keep the saved value, and shows the save confirmation only after a successful save. The regression suite gains provider instantiation checks and a save/load round trip that uses a unique file under the temp directory.
  • 6b1e1e7: SaveSettings() wraps the configuration write in an explicit try/catch, reports MSG_CLOUD_SYNC_SAVE_FAILED with the runtime message, and returns false so Connect and Sync stop before using settings that were not persisted. The regression suite now asserts the guard, checks that all ten Cloud Sync fields are declared and survive a temporary INI round trip, and exercises Load() followed by Save() on a nonexistent config path to reproduce the fresh-install path where the original save failure occurred.
  • 35848c4: ConfigManager.Load() no longer converts the stored cursor speed with Integer() before normalization. That conversion wrapped scientific notation and values beyond the signed 64-bit range into negative numbers, which then clamped to 20 percent. NormalizeSpeedPercent() converts to floating point, rejects NaN, clamps against the configured bounds, and rounds only after the clamp, so positive overflow yields 300 percent. Regression checks cover 1e309, 1e1000, a 64-bit overflow literal, a large decimal literal, negative overflow, and hexadecimal input.
  • Behavioral Guarantees: Existing configuration keys, their defaults, and all previously documented shortcuts keep their current meaning. The new speed key is optional; a missing value loads as 100 percent, which reproduces the previous movement rate exactly. Horizontal scrolling is bound only inside the mouse control layer, so the CapsLock Q and E tab shortcuts are unchanged. The mouse control gesture change from one Shift to a double Shift is the behavior requested by the issue. Cloud Sync keeps every existing provider name, endpoint, and file name.

Verification & Dependencies

  • Status of Assertions:
    • Command-line checks: scripts/ci/Check-DllPaths.ps1 (PASS, 82 files); Invoke-Ahk.ps1 .\CapsLock-.ahk -Validate (PASS, exit 0); Invoke-Ahk.ps1 .\scripts\HotkeyRegression.ahk (PASS, 224 checks, 0 failures); Invoke-Ahk.ps1 .\scripts\HistoryGuiPaging.ahk (PASS); git diff --check (PASS, no whitespace errors).
    • Runtime & Visual assertions: The double Shift boundary is asserted directly at 450 ms and 451 ms. Speed normalization is asserted at 20, 100, 300, the two clamp edges, a numeric string, scientific notation, and signed 64-bit overflow. Provider instances are constructed without network access and expose gist, github, google-drive, https://api.github.com, and capslock-sync.json as expected. A temporary INI round trip asserts the Gist target, the mouse speed, and all ten Cloud Sync provider fields. A separate probe loads a nonexistent config, saves, and verifies that the file is created without throwing, which covers the fresh-install failure. The Settings card occupies 64 px in the existing 624 px content column, and the Cloud Sync row and gap arrays stay aligned at 37 entries each after the new hint row. No interactive window capture was performed.
    • Unverified external facts: Live authentication against GitHub, Google Drive, OneDrive, and WebDAV was not exercised; those endpoints require real tokens and accounts, so the connection path is verified only up to request construction.
  • Dependency Pinning:
    • No new dependencies, package versions, or userscript headers are introduced. The code targets the AutoHotkey v2 runtime already used by the project, and the CI workflow keeps its pinned AutoHotkey install action at commit 37e2ba93564d85ce51426c4e77efcbda81b65c24.

Review conclusion

Evaluation across the four engineering dimensions:

  • Correctness & Regression: PASS (Both reported Cloud Sync failures have a direct cause and a fix. Class variables are no longer read through an instance, and the undeclared state fields are now part of AppState, so Save() completes on a fresh install. A failed configuration write now surfaces a localized error instead of an uncaught GUI event. Cursor speed overflow clamps to the intended bound rather than the minimum. The double Shift window is inclusive at 450 ms and rejects zero, reversed, and late timestamps.)
  • Performance Gain: PASS (The speed multiplier is one clamp and one division per 16 ms movement tick, with no allocation in the hot path. Horizontal scrolling reuses the existing 80 ms cadence and its timer is cancelled by Stop() alongside the movement and vertical scroll timers.)
  • Compatibility & Architecture: PASS (Native AutoHotkey v2 only, no frameworks or new runtime dependencies. Provider subclasses keep their existing public names and endpoints, configuration keys are preserved, and the mouse layer remains separated from the CapsLock shortcut layers.)
  • Readability & Commit Completeness: PASS (Four atomic Conventional Commits carry the issue number, mouse-control and Cloud Sync changes are separated, the diff is pure ASCII, and every commit state passes the regression suite independently.)

Overall Verdict: PASS

Permission Notice

AI has completed staged development and review loops. Merging is an exclusive user privilege. Awaiting manual merge.

@CYoJkoY

CYoJkoY commented Oct 30, 2026

Copy link
Copy Markdown
Owner Author

1. Change Scope and Completeness Assessment (Overview)

  • Change scope: PR #197 (Issue Improve mouse control and repair Cloud Sync persistence #196), 4 commits, 14 files, +639 / -39 in total. Includes mouse speed adjustment, mouse-mode horizontal scrolling, and double-tap Shift to enter; fixes cloud sync credential persistence, Provider endpoint access errors, configuration save failure prompts, and boundary handling for speed overflow.
  • Requirement contract alignment: Fully aligned. Double-tap Shift to enter, single-tap Shift to exit; horizontal scrolling uses Q / E, with Alt for acceleration; speed is adjustable in the settings UI, range 20%–300%. The original failures in cloud sync save and connection test have both been addressed.
  • Overall score: 4.9 / 5.0 (pre-fix assessment was 4.5 / 5.0). The remaining 0.1 is for two minor refinement suggestions that do not block delivery; see Section 2 for details.

2. Multi-Dimensional Defect List (Findings)

  • Correctness and boundary defense - Issue (fixed)

    • Location/code anchor: UI/CloudSyncGui.ahk → SaveSettings(), CloudSyncGui.ahk
    • Root cause analysis: The original implementation called ConfigManager.Save(false) directly without catching write exceptions. When the disk is not writable or the INI write fails, the exception escapes the GUI event; the UI neither shows the failure reason nor does the subsequent Connect / Sync clearly stop.
    • Remediation strategy: Wrap the save call in try/catch as err; on failure, refresh the credential labels, show a localized error, and return false. Callers already abort subsequent flow via if !SaveSettings() return.
  • Correctness and boundary defense - Issue (fixed)

    • Location/code anchor: Config/ConfigManager.ahk → Load(), ConfigManager.ahk; Core/MouseControl.ahk → NormalizeSpeedPercent(), MouseControl.ahk
    • Root cause analysis: The original implementation performed Integer() before normalization. Inputs exceeding the 64-bit integer range such as "1e309" and "9223372036854775808" would wrap to zero or a negative number and then be incorrectly clamped to 20 instead of the upper bound 300.
    • Remediation strategy: Remove the pre-conversion; inside the normalization function, first convert to floating point, reject NaN, and perform the lower/upper bound comparison before rounding. Scientific notation, 64-bit overflow, negative overflow, and hexadecimal text are all covered.
  • Contract completeness and regression risk - Issue (fixed)

    • Location/code anchor: scripts/HotkeyRegression.ahk → CheckConfigCloudSyncRoundTrip(), CheckConfigFreshInstallSave(), HotkeyRegression.ahk
    • Root cause analysis: The original regression only verified the Gist target and mouse speed; it did not cover the ten cloud sync fields, nor did it reproduce the "fresh install with no Config.ini → Load() → Save()" path. That path is exactly what exposed the save crash caused by undeclared properties.
    • Remediation strategy: Assert each of the ten fields is declared and perform a temporary INI round trip; add a load-and-save test with no configuration file present.
  • Performance and resource lifecycle - Nitpick (unchanged)

    • Location/code anchor: UI/CloudSyncGui.ahk → RefreshCredentialLabels(), CloudSyncGui.ahk
    • Root cause analysis: Each refresh calls CloudSyncCredentials.Get() separately for the four credentials, and each Get() re-reads and decrypts the entire credential store. This is a low-frequency operation in the settings panel and has not caused actual performance problems.
    • Remediation strategy: A one-shot batch query interface could be added, or the decryption result reused within the same refresh cycle. This item does not affect current delivery.
  • Correctness and boundary defense - Nitpick (unchanged)

    • Location/code anchor: Core/MouseControl.ahk → IsDoubleShiftWithinWindow(), MouseControl.ahk
    • Root cause analysis: Double-tap detection uses A_TickCount. After the system runs for about 49.7 days the counter wraps, and the time difference between two key presses spanning the wrap becomes negative and is rejected. This manifests as needing to press twice again, which is fail-closed and does not cause false triggers.
    • Remediation strategy: If strict continuous timing for long-running operation is desired, a monotonic high-precision timing source could be used. The current behavior is safe and does not constitute a blocker.
  • Code style and type safety - Nitpick (fixed)

    • Location/code anchor: UI/CloudSyncGui.ahk row layout comment, CloudSyncGui.ahk
    • Root cause analysis: The comment was spelled one-to-one withrows, reducing readability.
    • Remediation strategy: Corrected to one-to-one with rows; no runtime behavior involved.

3. Improved Code Implementation (Remediation)

Below is the complete Unified Diff for commits 23a1970..35848c4, covering error handling, numeric boundaries, test additions, and comment corrections. It can be applied directly as a patch, with no omitted code.

diff --git a/Config/ConfigManager.ahk b/Config/ConfigManager.ahk
index ca3ea51..760153d 100644
--- a/Config/ConfigManager.ahk
+++ b/Config/ConfigManager.ahk
@@ -176,9 +176,7 @@ class ConfigManager {
 
         ; ---- Mouse Control ----
         mouseSpeed := IniRead(cfg, "MouseControl", "speedPercent", "100")
-        AppState.MouseControlSpeedPercent := IsNumber(mouseSpeed)
-            ? MouseControl.NormalizeSpeedPercent(Integer(mouseSpeed))
-            : 100
+        AppState.MouseControlSpeedPercent := MouseControl.NormalizeSpeedPercent(mouseSpeed)
 
         ; ---- Window Switcher ----
         AppState.WindowSwitcherShowIcons :=
diff --git a/Core/MouseControl.ahk b/Core/MouseControl.ahk
index 7ec2764..deb81ab 100644
--- a/Core/MouseControl.ahk
+++ b/Core/MouseControl.ahk
@@ -183,12 +183,18 @@ class MouseControl {
         if !IsNumber(value)
             return 100
 
-        percent := Round(value)
-        if (percent < AppState.MouseControlSpeedMin)
+        ; IsNumber also accepts scientific notation and hexadecimal text.
+        ; Convert before rounding so values beyond the integer range clamp to
+        ; the configured bound instead of wrapping to a negative number.
+        numeric := value * 1.0
+        if (numeric != numeric)
+            return 100
+
+        if (numeric <= AppState.MouseControlSpeedMin)
             return AppState.MouseControlSpeedMin
-        if (percent > AppState.MouseControlSpeedMax)
+        if (numeric >= AppState.MouseControlSpeedMax)
             return AppState.MouseControlSpeedMax
-        return percent
+        return Round(numeric)
     }
 
     static UpdateMovementTimer(*) {
diff --git a/UI/CloudSyncGui.ahk b/UI/CloudSyncGui.ahk
index 7706277..5874c21 100644
--- a/UI/CloudSyncGui.ahk
+++ b/UI/CloudSyncGui.ahk
@@ -275,7 +275,7 @@ ShowCloudSyncSettings(*) {
         [saveBtn, connectBtn, syncBtn, resetBtn, disconnectBtn, closeBtn]
     ]
 
-    ; Per-row "gap from the previous row", one-to-one withrows
+    ; Per-row "gap from the previous row", one-to-one with rows
     gaps := [
         8,   12, 6,   12, 6,   12, 6,   10, 6,   10, 6,
         12, 6,   10, 6,   12,
@@ -519,7 +519,20 @@ ShowCloudSyncSettings(*) {
         else 
             interval.Text := String(AppState.CloudSyncInterval)
 
-        ConfigManager.Save(false)
+        try {
+            ConfigManager.Save(false)
+        } catch as err {
+            RefreshCredentialLabels()
+            ShowToolTip(
+                Lang(
+                    "MSG_CLOUD_SYNC_SAVE_FAILED",
+                    "Could not save Cloud Sync settings."
+                ) " " err.Message,
+                3200
+            )
+            return false
+        }
+
         CloudSyncIdentity.Initialize()
 
         if previousProviderKey != CloudSyncCoordinator.GetProviderConfigKey()
diff --git a/lang.csv b/lang.csv
index 5737a14..00c2456 100644
--- a/lang.csv
+++ b/lang.csv
@@ -360,6 +360,7 @@ MSG_CLOUD_SYNC_CONFLICT,Cloud Sync conflict requires attention.,Un conflit de sy
 MSG_CLOUD_SYNC_AUTH_FAILED,Cloud Sync connection failed.,La connexion de synchronisation cloud a échoué.,云同步连接失败。,クラウド同期接続に失敗しました。,클라우드 동기화 연결에 실패했습니다.,雲端同步連線失敗。,Не удалось подключиться к облачной синхронизации.,Nie udało się nawiązać połączenia synchronizacji w chmurze.,La conexión de sincronización en la nube ha fallado.,Falha na conexão de sincronização na nuvem.,Verbindung der Cloud-Synchronisierung fehlgeschlagen.,Bulut Senkronizasyonu bağlantısı başarısız oldu.,Connessione di sincronizzazione cloud non riuscita.
 MSG_CLOUD_SYNC_SETTINGS_SAVED,Cloud Sync settings saved.,Paramètres de synchronisation cloud enregistrés.,云同步设置已保存。,クラウド同期設定を保存しました。,클라우드 동기화 설정이 저장되었습니다.,雲端同步設定已儲存。,Настройки облачной синхронизации сохранены.,Ustawienia synchronizacji w chmurze zostały zapisane.,Se ha guardado la configuración de sincronización en la nube.,As configurações de sincronização na nuvem foram salvas.,Einstellungen der Cloud-Synchronisierung gespeichert.,Bulut Senkronizasyonu ayarları kaydedildi.,Impostazioni di sincronizzazione cloud salvate.
 MSG_CLOUD_SYNC_CREDENTIAL_SAVE_FAILED,Could not save the encrypted credential.,Impossible d'enregistrer les identifiants chiffrés.,无法保存加密凭据。,暗号化された認証情報を保存できませんでした。,암호화된 자격 증명을 저장할 수 없습니다.,無法儲存加密認證資訊。,Не удалось сохранить зашифрованные учётные данные.,Nie można zapisać zaszyfrowanych danych uwierzytelniających.,No se pudieron guardar las credenciales cifradas.,Não foi possível salvar a credencial criptografada.,Die verschlüsselten Anmeldedaten konnten nicht gespeichert werden.,Şifrelenmiş kimlik bilgisi kaydedilemedi.,Impossibile salvare le credenziali crittografate.
+MSG_CLOUD_SYNC_SAVE_FAILED,Could not save Cloud Sync settings.,Impossible d'enregistrer les paramètres de synchronisation cloud.,无法保存云同步设置。,クラウド同期設定を保存できませんでした。,클라우드 동기화 설정을 저장하지 못했습니다.,無法儲存雲端同步設定。,Не удалось сохранить настройки облачной синхронизации.,Nie można zapisać ustawień synchronizacji w chmurze.,No se pudo guardar la configuración de sincronización en la nube.,Não foi possível salvar as configurações de sincronização na nuvem.,Einstellungen der Cloud-Synchronisierung konnten nicht gespeichert werden.,Bulut Senkronizasyonu ayarları kaydedilemedi.,Impossibile salvare le impostazioni di sincronizzazione cloud.
 MSG_CLOUD_SYNC_RESOLVED,Cloud Sync conflict resolution completed.,La résolution du conflit de synchronisation cloud est terminée.,云同步冲突处理完成。,クラウド同期の競合解決が完了しました。,클라우드 동기화 충돌 해결이 완료되었습니다.,雲端同步衝突處理完成。,Разрешение конфликта облачной синхронизации завершено.,Rozwiązywanie konfliktu synchronizacji w chmurze zostało zakończone.,Se completó la resolución del conflicto de sincronización en la nube.,A resolução do conflito de sincronização na nuvem foi concluída.,Konflikt der Cloud-Synchronisierung wurde aufgelöst.,Bulut Senkronizasyonu çakışma çözümü tamamlandı.,Risoluzione del conflitto di sincronizzazione cloud completata.
 CONFIRM_CLOUD_SYNC_RESET,Remove the saved credential target and synchronization metadata for the current provider?,"Supprimer les identifiants enregistrés, la cible et les métadonnées de synchronisation du fournisseur actuel ?",删除当前服务提供商的已保存凭据、目标和同步元数据?,現在のプロバイダーの保存済み認証情報、同期先、および同期メタデータを削除しますか?,현재 서비스 제공업체의 저장된 자격 증명과 대상 및 동기화 메타데이터를 삭제하시겠습니까?,要刪除目前服務提供商已儲存的認證資訊、目標和同步中繼資料嗎?,"Удалить сохранённые учётные данные, цель и метаданные синхронизации для текущего провайдера?","Usunąć zapisane dane uwierzytelniające, cel i metadane synchronizacji dla bieżącego dostawcy?","¿Eliminar las credenciales guardadas, el destino y los metadatos de sincronización del proveedor actual?","Remover a credencial salva, o destino e os metadados de sincronização do provedor atual?","Gespeicherte Anmeldedaten, Ziel und Synchronisierungsmetadaten für den aktuellen Anbieter entfernen?","Mevcut sağlayıcı için kaydedilmiş kimlik bilgisini, hedefi ve senkronizasyon meta verilerini kaldırmak ister misiniz?","Rimuovere le credenziali salvate, la destinazione e i metadati di sincronizzazione per il provider corrente?"
 GUI_CLOUD_SYNC_CONFLICT_TITLE,Cloud Sync Conflict,Conflit de synchronisation cloud,云同步冲突,クラウド同期の競合,클라우드 동기화 충돌,雲端同步衝突,Конфликт облачной синхронизации,Konflikt synchronizacji w chmurze,Conflicto de sincronización en la nube,Conflito de sincronização na nuvem,Konflikt der Cloud-Synchronisierung,Bulut Senkronizasyonu Çakışması,Conflitto di sincronizzazione cloud
diff --git a/scripts/HotkeyRegression.ahk b/scripts/HotkeyRegression.ahk
index d4550cc..ea91579 100644
--- a/scripts/HotkeyRegression.ahk
+++ b/scripts/HotkeyRegression.ahk
@@ -56,9 +56,9 @@ class ApplicationProfiles {
     }
 
     ; ConfigManager normalizes these two fields while loading and serializes
-    ; the group map while saving. The round-trip probe below only asserts the
-    ; Cloud Sync target and the mouse speed, so empty results keep the probe
-    ; independent of the real profile rules.
+    ; the group map while saving. The round-trip probe below asserts Cloud Sync
+    ; and mouse settings, so empty profile results keep it independent of the
+    ; real application rules.
     static NormalizeDisabledExecutables(value) {
         return []
     }
@@ -726,6 +726,16 @@ CheckCloudSyncRegressions(root) {
         "the save button reports success only when saving succeeds"
     )
 
+    saveCall := InStr(saveSection, "ConfigManager.Save(false)")
+    tryCall := InStr(saveSection, "try {")
+    catchCall := InStr(saveSection, "} catch as err {")
+    Check(
+        tryCall > 0 && saveCall > tryCall && catchCall > saveCall
+            && InStr(saveSection, "MSG_CLOUD_SYNC_SAVE_FAILED") > catchCall
+            && InStr(saveSection, "return false", false, catchCall) > catchCall,
+        "configuration save failures return false after showing a localized error"
+    )
+
     coordinatorText := ReadText(root "\Core\CloudSyncCoordinator.ahk")
     Check(
         RegExMatch(coordinatorText,
@@ -791,9 +801,31 @@ CheckCloudSyncProviderInstances() {
 ; encrypted credential store stay untouched.
 CheckConfigCloudSyncRoundTrip() {
     previousConfigFile := AppState.ConfigFile
-    previousTarget := AppState.CloudSyncTarget
-    previousProvider := AppState.CloudSyncProvider
-    previousSpeed := AppState.MouseControlSpeedPercent
+    fields := Map(
+        "CloudSyncGitHubOwner", "owner-196",
+        "CloudSyncGitHubRepository", "repository-196",
+        "CloudSyncGitHubBranch", "branch-196",
+        "CloudSyncGitHubPath", "sync/path-196.json",
+        "CloudSyncWebDavUrl", "https://dav.example.test/196",
+        "CloudSyncWebDavPath", "dav/path-196.json",
+        "CloudSyncGoogleClientId", "google-client-196",
+        "CloudSyncOneDriveClientId", "onedrive-client-196",
+        "CloudSyncOneDriveTenant", "tenant-196",
+        "CloudSyncOneDrivePath", "onedrive/path-196.json"
+    )
+    previous := Map(
+        "CloudSyncTarget", AppState.CloudSyncTarget,
+        "CloudSyncProvider", AppState.CloudSyncProvider,
+        "MouseControlSpeedPercent", AppState.MouseControlSpeedPercent
+    )
+    for field in fields {
+        previous[field] := AppState.%field%
+        Check(
+            AppState.HasProp(field),
+            "cloud sync state declares " field,
+            "missing from Config/Globals.ahk"
+        )
+    }
     tempPath := A_Temp "\capslock-196-config-" A_TickCount ".ini"
 
     try {
@@ -803,12 +835,16 @@ CheckConfigCloudSyncRoundTrip() {
         AppState.ConfigFile := tempPath
         AppState.CloudSyncProvider := "gist"
         AppState.CloudSyncTarget := "gist-round-trip-196"
+        for field, value in fields
+            AppState.%field% := value
         AppState.MouseControlSpeedPercent := 150
         ConfigManager.Save(false)
 
         Check(FileExist(tempPath), "temporary config is written", tempPath)
 
         AppState.CloudSyncTarget := ""
+        for field in fields
+            AppState.%field% := ""
         AppState.MouseControlSpeedPercent := 20
         ConfigManager.Load()
 
@@ -822,9 +858,54 @@ CheckConfigCloudSyncRoundTrip() {
             "mouse speed survives a save and load round trip",
             "got " AppState.MouseControlSpeedPercent
         )
+        for field, expected in fields {
+            actual := AppState.%field%
+            Check(
+                actual == expected,
+                field " survives a save and load round trip",
+                "got '" actual "'"
+            )
+        }
+    } finally {
+        AppState.ConfigFile := previousConfigFile
+        for field, value in previous
+            AppState.%field% := value
+        if FileExist(tempPath)
+            FileDelete(tempPath)
+    }
+}
+
+; A fresh installation has no Config.ini, so Load() returns before assigning
+; any field. Save() must still write every declared default without throwing.
+CheckConfigFreshInstallSave() {
+    previousConfigFile := AppState.ConfigFile
+    tempPath := A_Temp "\capslock-196-fresh-" A_TickCount ".ini"
+
+    try {
+        if FileExist(tempPath)
+            FileDelete(tempPath)
+
+        AppState.ConfigFile := tempPath
+        saveError := ""
+        try {
+            ConfigManager.Load()
+            ConfigManager.Save(false)
+        } catch as err {
+            saveError := err.Message
+        }
+
+        Check(
+            saveError == "",
+            "a fresh install can load defaults and save without throwing",
+            saveError
+        )
+        Check(
+            FileExist(tempPath),
+            "a fresh install creates its configuration file",
+            tempPath
+        )
     } finally {
         AppState.ConfigFile := previousConfigFile
-        AppState.CloudSyncTarget := previousTarget
-        AppState.CloudSyncProvider := previousProvider
-        AppState.MouseControlSpeedPercent := previousSpeed
         if FileExist(tempPath)
             FileDelete(tempPath)
     }
@@ -1127,6 +1206,18 @@ CheckMouseControlRegressions(root) {
         MouseControl.NormalizeSpeedPercent("150") == 150,
         "numeric cursor speed text is accepted"
     )
+    Check(
+        MouseControl.NormalizeSpeedPercent("1e309") == 300
+            && MouseControl.NormalizeSpeedPercent("1e1000") == 300
+            && MouseControl.NormalizeSpeedPercent("9223372036854775808") == 300
+            && MouseControl.NormalizeSpeedPercent("999999999999999999999") == 300,
+        "positive speed overflow clamps to the maximum instead of wrapping"
+    )
+    Check(
+        MouseControl.NormalizeSpeedPercent("-1e309") == 20
+            && MouseControl.NormalizeSpeedPercent("0x10") == 20,
+        "negative overflow and hexadecimal speed text clamp to the minimum"
+    )
 
     ; Horizontal wheel input needs its own bindings, flag, repeat timer, and
     ; Alt fast step, and Stop() must tear the timer down like the vertical one.
@@ -1243,6 +1334,7 @@ Main() {
     CheckCloudSyncRegressions(root)
     CheckCloudSyncProviderInstances()
     CheckConfigCloudSyncRoundTrip()
+    CheckConfigFreshInstallSave()
     CheckQuickPhraseRegressions(root)
     CheckImageToolsHotkeys(root)
     CheckImageToolsDefaultOutput(root)

4. Verification and Regression Checklist (Verification)

  • Boundary scenarios: invalid speed text falls back to 100; 1 and 19 clamp to 20; 301, 9999, 1e309, 1e1000, 64-bit integer overflow, and extra-long decimal numbers all clamp to 300; -1e309 and 0x10 clamp to 20.
  • Double-tap Shift: accepts exactly a 450 ms window, rejects beyond-window, zero-value, and reverse timestamps; single-tap exits, double-tap enters.
  • Horizontal scrolling: verified Q / E bindings, MOUSEEVENTF_HWHEEL, Alt acceleration, repeat timer creation, and Stop() cleanup.
  • Configuration round trip: the ten cloud sync fields, cloud sync provider, and mouse speed all save and reload successfully.
  • Fresh install path: with no Config.ini, executing Load() then Save() does not throw and creates the configuration file.
  • Save failure path: shows a localized error and returns false, and the connect and sync flows are aborted accordingly.
  • Local checks: Check-DllPaths.ps1 PASS (82 files); CapsLock-.ahk -Validate PASS (exit code 0); HotkeyRegression.ahk PASS (224 checks, 0 failures); HistoryGuiPaging.ahk PASS; git diff --check PASS.
  • CI: AutoHotkey Syntax Check (run 41120333207) PASS; PR status OPEN, MERGEABLE, MERGEABLE / CLEAN.
  • Potential breaking changes: no public API, config key name, or default value changes. Added [MouseControl] speedPercent, which defaults to 100 when absent from old configs; all newly added cloud sync fields have defaults.
  • To be confirmed: online authentication and real transfer for GitHub, Google Drive, OneDrive, and WebDAV were not executed locally. Current verification covers Provider construction, request configuration, credential persistence, and boundary logic; actual account authorization still requires online verification.
  • Runtime observation: recommended to observe double-tap Shift behavior after long-running operation, the impact of A_TickCount wraparound, horizontal scroll timer exit cleanup, and credential store read latency.
  • Merge status: Not merged. The PR is ready; merge permission is reserved for the user.

@CYoJkoY
CYoJkoY merged commit 3d56869 into main Oct 30, 2026
1 check passed
@CYoJkoY
CYoJkoY deleted the issue-196-mouse-control-cloud-sync branch October 30, 2026 20:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Improve mouse control and repair Cloud Sync persistence

1 participant