diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9bfc022..bf6b227 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -130,6 +130,9 @@ jobs: build-windows: name: Build (Windows) runs-on: windows-latest + env: + # Keep the deliverable independent of a separately installed VC runtime. + RUSTFLAGS: -Dwarnings -C target-feature=+crt-static steps: - uses: actions/checkout@v5 - uses: dtolnay/rust-toolchain@stable @@ -141,13 +144,28 @@ jobs: - run: cargo check -p smartkey-win - run: cargo check -p smartkey-playground - run: cargo clippy -p smartkey-win -- -D warnings - - name: Build Windows pilot payload + - name: Build Windows standalone payload run: cargo build --locked -p smartkey-win --release - - name: Stage complete Windows pilot payload + - name: Verify standalone binary dependencies + shell: pwsh + run: | + $ErrorActionPreference = 'Stop' + $vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" + $dumpbin = & $vswhere -latest -products '*' -find 'VC\Tools\MSVC\**\bin\Hostx64\x64\dumpbin.exe' | Select-Object -First 1 + if (-not $dumpbin) { throw 'dumpbin was not found' } + foreach ($binary in @('smartkey-register.exe', 'smartkey_win.dll')) { + $imports = & $dumpbin /DEPENDENTS "target/release/$binary" + if ($LASTEXITCODE -ne 0) { throw "Cannot inspect $binary" } + $imports + if ($imports -match '(?i)(VCRUNTIME[0-9_]*|MSVCP[0-9_]*|ucrtbase)\.dll') { + throw "$binary still depends on a separately installed C/C++ runtime" + } + } + - name: Stage complete Windows standalone payload shell: pwsh run: | $ErrorActionPreference = 'Stop' - $stage = Join-Path $env:RUNNER_TEMP "smartkey-windows-pilot-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT" + $stage = Join-Path $env:RUNNER_TEMP "smartkey-windows-standalone-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT" if (Test-Path -LiteralPath $stage) { throw "Refusing to reuse staging directory: $stage" } @@ -156,12 +174,19 @@ jobs: $payload = @( @{ Source = 'target/release/smartkey-register.exe'; Name = 'smartkey-register.exe' }, @{ Source = 'target/release/smartkey_win.dll'; Name = 'smartkey_win.dll' }, - @{ Source = 'crates/smartkey-win/pilot-runtime-manifest.json'; Name = 'pilot-runtime-manifest.json' }, + @{ Source = 'crates/smartkey-win/windows-runtime-manifest.json'; Name = 'windows-runtime-manifest.json' }, @{ Source = 'config/smartkey.json'; Name = 'smartkey.json' }, @{ Source = 'corpus/corpus_en.json'; Name = 'corpus_en.json' }, @{ Source = 'corpus/corpus_bg.json'; Name = 'corpus_bg.json' }, @{ Source = 'corpus/corpus_tech.json'; Name = 'corpus_tech.json' }, - @{ Source = 'crates/smartkey-win/tests/windows_pilot_manual.md'; Name = 'PILOT_README.md' }, + @{ Source = 'crates/smartkey-win/packaging/Install-Machine-SmartKey.cmd'; Name = 'Install-Machine-SmartKey.cmd' }, + @{ Source = 'crates/smartkey-win/packaging/Uninstall-Machine-SmartKey.cmd'; Name = 'Uninstall-Machine-SmartKey.cmd' }, + @{ Source = 'crates/smartkey-win/packaging/Install-SmartKey.cmd'; Name = 'Install-SmartKey.cmd' }, + @{ Source = 'crates/smartkey-win/packaging/Status-SmartKey.cmd'; Name = 'Status-SmartKey.cmd' }, + @{ Source = 'crates/smartkey-win/packaging/Enable-SmartKey.cmd'; Name = 'Enable-SmartKey.cmd' }, + @{ Source = 'crates/smartkey-win/packaging/Disable-SmartKey.cmd'; Name = 'Disable-SmartKey.cmd' }, + @{ Source = 'crates/smartkey-win/packaging/Uninstall-SmartKey.cmd'; Name = 'Uninstall-SmartKey.cmd' }, + @{ Source = 'crates/smartkey-win/packaging/README-WINDOWS.md'; Name = 'README-WINDOWS.md' }, @{ Source = 'LICENSE'; Name = 'LICENSE' }, @{ Source = 'LICENSE-GPL'; Name = 'LICENSE-GPL' }, @{ Source = 'LICENSE-APACHE'; Name = 'LICENSE-APACHE' } @@ -193,14 +218,199 @@ jobs: if (Compare-Object -ReferenceObject $expected -DifferenceObject $actual) { throw 'Staged payload differs from the exact allowlist.' } - - name: Upload Windows pilot payload + - name: Upload Windows standalone payload uses: actions/upload-artifact@v4 with: - name: smartkey-windows-pilot - path: ${{ runner.temp }}/smartkey-windows-pilot-${{ github.run_id }}-${{ github.run_attempt }} + name: smartkey-windows-standalone + path: ${{ runner.temp }}/smartkey-windows-standalone-${{ github.run_id }}-${{ github.run_attempt }} if-no-files-found: error retention-days: 14 + - name: Check machine setup and standard-user install and reversal + id: user-smoke + timeout-minutes: 8 + shell: pwsh + run: | + $ErrorActionPreference = 'Stop' + $root = "C:\Users\Public\SmartKeySmoke-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT" + $name = "SKSmoke$env:GITHUB_RUN_ATTEMPT" + $stage = Join-Path $env:RUNNER_TEMP "smartkey-windows-standalone-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT" + $stageHelper = Join-Path $stage 'smartkey-register.exe' + $machineDirectory = Join-Path ([Environment]::GetFolderPath([Environment+SpecialFolder]::ProgramFiles)) 'SmartKey' + $machineHelper = Join-Path $machineDirectory 'smartkey-register.exe' + $guid = '{7A3B9E1F-4C2D-4E5A-8F6B-1D2E3F4A5B6C}' + $machineClass = "HKLM:\Software\Classes\CLSID\$guid" + $machineTip = "HKLM:\Software\Microsoft\CTF\TIP\$guid" + $identity = [Security.Principal.WindowsIdentity]::GetCurrent() + $principal = [Security.Principal.WindowsPrincipal]::new($identity) + if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { + throw 'The disposable runner must provide an actual elevated token for machine setup.' + } + if (Get-LocalUser -Name $name -ErrorAction SilentlyContinue) { throw 'Smoke account already exists' } + foreach ($path in @($root, $machineDirectory, $machineClass, $machineTip)) { + if (Test-Path -LiteralPath $path) { throw "Refusing preexisting smoke/machine state: $path" } + } + $secret = ConvertTo-SecureString ([Guid]::NewGuid().ToString('N') + 'aA!4') -AsPlainText -Force + $credential = [PSCredential]::new("$env:COMPUTERNAME\$name", $secret) + $created = $false + $machineAttempted = $false + $failure = $null + $result = [ordered]@{ + status='NOT_RUN'; elevated_machine_token=$true + standard_user_prerequisite=$false; standard_user_lifecycle=$false + machine_install_exit=$null; machine_verify_exit=$null; machine_cleanup_exit=$null + frozen_bundle_matches=$false; machine_state_removed=$false + typing_exercised=$false; logon_exercised=$false; cleanup_errors=@() + machine_tip_snapshots=[ordered]@{} + } + function Save-OwnedTipSnapshot([string]$phase) { + try { + $present = Test-Path -LiteralPath $machineTip + $snapshot = [ordered]@{ present=$present; query_exit=$null } + if ($present) { + # Read only SmartKey's exact owned subtree; never modify CTF state. + $PSNativeCommandUseErrorActionPreference = $false + $lines = & reg.exe query "HKLM\Software\Microsoft\CTF\TIP\$guid" /s 2>&1 + $snapshot.query_exit = $LASTEXITCODE + $lines | Set-Content -LiteralPath (Join-Path $root "machine-tip-$phase.txt") -Encoding utf8 + if ($snapshot.query_exit -ne 0) { throw "Owned TIP query failed: $($snapshot.query_exit)" } + } + $result.machine_tip_snapshots[$phase] = $snapshot + } catch { + # A diagnostic failure must not prevent the cleanup attempt. + $result.cleanup_errors += "TIP snapshot ${phase}: $($_.Exception.Message)" + } + } + function Invoke-MachineHelper([string]$helper, [string]$action, [string]$exitField) { + $process = [Diagnostics.Process]::new() + try { + $process.StartInfo = [Diagnostics.ProcessStartInfo]::new($helper, "$action --no-dialog") + $process.StartInfo.UseShellExecute = $false + $process.StartInfo.CreateNoWindow = $true + $process.StartInfo.RedirectStandardOutput = $true + $process.StartInfo.RedirectStandardError = $true + if (-not $process.Start()) { throw "Cannot start $action" } + $stdout = $process.StandardOutput.ReadToEndAsync() + $stderr = $process.StandardError.ReadToEndAsync() + $timedOut = -not $process.WaitForExit(45000) + if ($timedOut) { + $process.Kill($true) + if (-not $process.WaitForExit(5000)) { throw "$action did not exit after timeout/termination" } + } + $stem = $action.TrimStart('-') + [IO.File]::WriteAllText((Join-Path $root "$stem.stdout.txt"), $stdout.GetAwaiter().GetResult()) + [IO.File]::WriteAllText((Join-Path $root "$stem.stderr.txt"), $stderr.GetAwaiter().GetResult()) + $exitCode = $process.ExitCode + if ($null -eq $exitCode) { throw "$action has no real exit code; inferred success is refused" } + $result[$exitField] = [int]$exitCode + if ($timedOut) { throw "$action exceeded 45 seconds" } + if ($exitCode -ne 0) { throw "$action failed with exit $exitCode" } + } finally { $process.Dispose() } + } + function Invoke-UserSmoke([string]$phase, [string]$expectedStatus, [int]$timeout) { + $output = Join-Path $root "user-$($phase.ToLowerInvariant())" + $arguments = "-NoProfile -NonInteractive -File `"$script`" -Bundle `"$bundle`" -OutDir `"$output`" -Phase $phase" + $child = Start-Process -FilePath 'powershell.exe' -ArgumentList $arguments -Credential $credential -LoadUserProfile -UseNewEnvironment -PassThru -RedirectStandardOutput (Join-Path $root "$phase.launcher.stdout.txt") -RedirectStandardError (Join-Path $root "$phase.launcher.stderr.txt") + try { + if (-not $child.WaitForExit($timeout)) { + & taskkill /PID $child.Id /T /F + throw "Standard-user $phase exceeded its bounded timeout" + } + $child.Refresh() + if ($null -eq $child.ExitCode -or $child.ExitCode -ne 0) { + throw "Standard-user $phase failed or its real exit code is unavailable: $($child.ExitCode)" + } + } finally { $child.Dispose() } + $receipt = Get-Content -LiteralPath (Join-Path $output 'smoke-result.json') -Raw | ConvertFrom-Json + if ($receipt.status -ne $expectedStatus -or $receipt.phase -ne $phase -or + -not $receipt.standard_nonadmin -or -not $receipt.current_user_profile_confirmed -or + -not $receipt.keyboard_defaults_preserved) { + throw "Missing successful standard-user $phase receipt" + } + if ($phase -eq 'Prerequisite' -and -not $receipt.machine_prerequisite_refused) { + throw 'Missing explicit machine-prerequisite refusal' + } + if ($phase -eq 'Lifecycle' -and (-not $receipt.machine_install_preserved -or -not $receipt.personal_sentinel_preserved)) { + throw 'Lifecycle did not preserve the machine install and personal sentinel' + } + } + try { + New-Item -ItemType Directory -Path $root | Out-Null + New-LocalUser -Name $name -Password $secret -AccountNeverExpires | Out-Null + $created = $true + Add-LocalGroupMember -Group (Get-LocalGroup -SID 'S-1-5-32-545').Name -Member $name + Copy-Item -LiteralPath $stage -Destination (Join-Path $root 'bundle') -Recurse + Copy-Item -LiteralPath 'crates/smartkey-win/packaging/smoke-user.ps1' -Destination $root + & icacls $root /grant "${name}:(OI)(CI)M" /T /Q + if ($LASTEXITCODE -ne 0) { throw 'Cannot grant disposable account its smoke directory' } + $script = Join-Path $root 'smoke-user.ps1' + $bundle = Join-Path $root 'bundle' + Invoke-UserSmoke 'Prerequisite' 'PASS_NATIVE_STANDARD_USER_PREREQUISITE' 60000 + $result.standard_user_prerequisite = $true + + # Elevation uses the original frozen stage, never the user-writable copy. + # Set ownership before the attempt so partial installation is cleaned too. + $machineAttempted = $true + Invoke-MachineHelper $stageHelper '--install-machine' 'machine_install_exit' + $expected = @(Get-ChildItem -LiteralPath $stage -Force | ForEach-Object Name | Sort-Object) + $actual = @(Get-ChildItem -LiteralPath $machineDirectory -Force | ForEach-Object Name | Sort-Object) + if (Compare-Object -ReferenceObject $expected -DifferenceObject $actual) { + throw 'Protected machine directory differs from the exact frozen bundle' + } + foreach ($file in $expected) { + if ((Get-FileHash -LiteralPath (Join-Path $stage $file) -Algorithm SHA256).Hash -ne + (Get-FileHash -LiteralPath (Join-Path $machineDirectory $file) -Algorithm SHA256).Hash) { + throw "Protected machine file differs from frozen source: $file" + } + } + $result.frozen_bundle_matches = $true + Invoke-MachineHelper $machineHelper '--verify-machine' 'machine_verify_exit' + Invoke-UserSmoke 'Lifecycle' 'PASS_NATIVE_STANDARD_USER_MAINTENANCE' 180000 + $result.standard_user_lifecycle = $true + $result.status = 'PASS_NATIVE_MACHINE_AND_STANDARD_USER_MAINTENANCE' + } catch { + $failure = $_.Exception.Message + $result.status = 'FAIL_NATIVE_MACHINE_AND_STANDARD_USER_MAINTENANCE' + $result['error'] = $failure + } finally { + if ($machineAttempted) { + Save-OwnedTipSnapshot 'before-cleanup' + try { + # The original archive helper can remove the installed EXE; + # the product deliberately refuses to delete its running self. + Invoke-MachineHelper $stageHelper '--uninstall-machine' 'machine_cleanup_exit' + foreach ($path in @($machineClass, $machineTip, $machineDirectory)) { + if (Test-Path -LiteralPath $path) { throw "Owned machine state remains after cleanup: $path" } + } + $result.machine_state_removed = $true + } catch { $result.cleanup_errors += "Machine cleanup: $($_.Exception.Message)" } + finally { Save-OwnedTipSnapshot 'after-cleanup' } + } + if ($created) { + try { Remove-LocalUser -Name $name } + catch { $result.cleanup_errors += "Disposable account cleanup: $($_.Exception.Message)" } + } + if ($result.cleanup_errors.Count -ne 0) { + $result.status = 'FAIL_NATIVE_MACHINE_AND_STANDARD_USER_MAINTENANCE' + } + if (Test-Path -LiteralPath $root) { + $result | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $root 'machine-and-user-result.json') -Encoding utf8 + Get-ChildItem -LiteralPath $root -Recurse -File | Where-Object { + $_.Name -like '*.stdout.txt' -or $_.Name -like '*.stderr.txt' -or $_.Name -like '*result.json' + } | Sort-Object FullName | ForEach-Object { Get-Content -LiteralPath $_.FullName } + } + } + if ($null -ne $failure) { throw $failure } + if ($result.cleanup_errors.Count -ne 0) { throw ($result.cleanup_errors -join '; ') } + - name: Retain native standard-user result + if: always() + uses: actions/upload-artifact@v4 + with: + name: smartkey-windows-standard-user-result + path: C:/Users/Public/SmartKeySmoke-${{ github.run_id }}-${{ github.run_attempt }} + if-no-files-found: warn + retention-days: 14 + build-macos: name: Build (macOS) runs-on: macos-latest diff --git a/README.md b/README.md index 414b17b..8b0c2a7 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,9 @@ All prediction happens in pure Rust. Zero network. Zero cloud. Sub-millisecond p ### Windows pilot status -The Windows package is an **experimental pre-release pilot**, not a daily-ready input method. A future pilot must use a disposable, non-elevated Windows account and pass the separately gated registration, clean-uninstall, and native-app checks; packaging alone does not establish those results or fix the known ReplaceWord/composing defects. Its runtime payload is limited to the helper, DLL, reviewed public corpora, and starter configuration; the archive also carries the pilot safety form and repository license notices. Copying data to `%APPDATA%\smartkey` and any later registration are manual, separately authorized actions: the package creates no autostart, sends no network traffic, and excludes `personal.json` and private corpora. +The Windows standalone package is an **experimental pre-release candidate**, not a daily-ready input method. An administrator explicitly installs the shared COM/TSF service once; the intended user then installs, enables, disables or removes their own setup without elevation. User setup copies only missing public starter data and adds a reversible login entry and Start menu commands. Personal data is preserved and never packaged. See the [Windows installation and removal instructions](crates/smartkey-win/packaging/README-WINDOWS.md). + +The candidate includes the shared-core changes through 31 October 2026, while retaining its Windows composition and Unicode replacement handling. Native Windows CI checks the frozen payload, elevated machine setup/removal, and maintenance under an actual nonadministrator account. Those checks establish installation behavior only: interactive typing, Win+Space, real logon and application-specific behavior still require a Windows desktop pilot. A successful build alone does not establish those results. The Rust core (`smartkey-core`) is platform-agnostic — all prediction logic and key event state machine are shared. Each platform crate is a thin adapter (~200-400 LoC) that bridges OS input events to the shared `InputMethodCore`. diff --git a/crates/smartkey-win/Cargo.toml b/crates/smartkey-win/Cargo.toml index b08aa64..7e8099f 100644 --- a/crates/smartkey-win/Cargo.toml +++ b/crates/smartkey-win/Cargo.toml @@ -17,11 +17,16 @@ log = { workspace = true } windows-core = "0.58" windows = { version = "0.58", features = [ "Win32_UI_TextServices", + "Win32_UI_WindowsAndMessaging", "Win32_System_Com", "Win32_Foundation", "Win32_UI_Input_KeyboardAndMouse", "Win32_System_Registry", "Win32_System_LibraryLoader", + "Win32_UI_Shell", + "Win32_Security", + "Win32_Security_Authorization", + "Win32_Storage_FileSystem", "implement", ] } diff --git a/crates/smartkey-win/packaging/Disable-SmartKey.cmd b/crates/smartkey-win/packaging/Disable-SmartKey.cmd new file mode 100644 index 0000000..b9c496f --- /dev/null +++ b/crates/smartkey-win/packaging/Disable-SmartKey.cmd @@ -0,0 +1,16 @@ +@echo off +setlocal +set "SMARTKEY_HELPER=%~dp0smartkey-register.exe" +if not exist "%SMARTKEY_HELPER%" set "SMARTKEY_HELPER=%ProgramFiles%\SmartKey\smartkey-register.exe" +if not exist "%SMARTKEY_HELPER%" ( + echo SmartKey helper is missing. Extract the whole archive, then install the machine package once. + pause + exit /b 1 +) +"%SMARTKEY_HELPER%" --disable +if errorlevel 1 ( + echo SmartKey could not complete the action. The error window describes the failure. + pause + exit /b 1 +) +exit /b 0 diff --git a/crates/smartkey-win/packaging/Enable-SmartKey.cmd b/crates/smartkey-win/packaging/Enable-SmartKey.cmd new file mode 100644 index 0000000..b44aa4e --- /dev/null +++ b/crates/smartkey-win/packaging/Enable-SmartKey.cmd @@ -0,0 +1,16 @@ +@echo off +setlocal +set "SMARTKEY_HELPER=%~dp0smartkey-register.exe" +if not exist "%SMARTKEY_HELPER%" set "SMARTKEY_HELPER=%ProgramFiles%\SmartKey\smartkey-register.exe" +if not exist "%SMARTKEY_HELPER%" ( + echo SmartKey helper is missing. Extract the whole archive, then install the machine package once. + pause + exit /b 1 +) +"%SMARTKEY_HELPER%" --enable +if errorlevel 1 ( + echo SmartKey could not complete the action. The error window describes the failure. + pause + exit /b 1 +) +exit /b 0 diff --git a/crates/smartkey-win/packaging/Install-Machine-SmartKey.cmd b/crates/smartkey-win/packaging/Install-Machine-SmartKey.cmd new file mode 100644 index 0000000..0a24031 --- /dev/null +++ b/crates/smartkey-win/packaging/Install-Machine-SmartKey.cmd @@ -0,0 +1,16 @@ +@echo off +setlocal +rem Explicit machine action. Right-click this command in the extracted archive +rem and choose Run as administrator. No automatic elevation is attempted. +if not exist "%~dp0smartkey-register.exe" ( + echo Extract the whole original SmartKey archive before this machine action. + pause + exit /b 1 +) +"%~dp0smartkey-register.exe" --install-machine +if errorlevel 1 ( + echo Machine action was incomplete. The error window describes the failure. + pause + exit /b 1 +) +exit /b 0 diff --git a/crates/smartkey-win/packaging/Install-SmartKey.cmd b/crates/smartkey-win/packaging/Install-SmartKey.cmd new file mode 100644 index 0000000..bec8598 --- /dev/null +++ b/crates/smartkey-win/packaging/Install-SmartKey.cmd @@ -0,0 +1,16 @@ +@echo off +setlocal +set "SMARTKEY_HELPER=%~dp0smartkey-register.exe" +if not exist "%SMARTKEY_HELPER%" set "SMARTKEY_HELPER=%ProgramFiles%\SmartKey\smartkey-register.exe" +if not exist "%SMARTKEY_HELPER%" ( + echo SmartKey helper is missing. Extract the whole archive, then install the machine package once. + pause + exit /b 1 +) +"%SMARTKEY_HELPER%" --install +if errorlevel 1 ( + echo SmartKey could not complete the action. The error window describes the failure. + pause + exit /b 1 +) +exit /b 0 diff --git a/crates/smartkey-win/packaging/README-WINDOWS.md b/crates/smartkey-win/packaging/README-WINDOWS.md new file mode 100644 index 0000000..b7f5e66 --- /dev/null +++ b/crates/smartkey-win/packaging/README-WINDOWS.md @@ -0,0 +1,82 @@ +# SmartKey for Windows 10/11 x64 + +This archive contains the complete application and public starter data. No Git, +Rust, Python or Visual C++ installer is required. Extract the whole archive; +keep it available for machine removal. Source/native acceptance status is +recorded separately in the supplied manifests; actual typing still needs a +Windows desktop check. + +## November refresh + +This candidate incorporates the shared-core changes through 31 October 2026. +Automatic word correction remains off by default. Pending typed text is delivered +before application shortcuts, without accepting the displayed completion; the +shortcut itself is forwarded. No pause-based commit timer is introduced on Windows. +The explicit administrator installation and reversible user commands are retained. +The exact build source and file hashes are in `artifact-source-manifest.json`. + +Installation tests and desktop typing are separate checks. Before relying on this +candidate, try synthetic BG/EN text, Tab acceptance, Ctrl+C/Ctrl+V after a partial +word, navigation, Win+Space and a real sign-out/sign-in in the intended applications. +Do not infer those results from the CI installation checks. + +## Install once on a permitted computer + +If an older SmartKey Windows version is installed, remove that version before +installing this shared machine package. If this package is already installed and +user setup reports an old per-user COM conflict, ask an administrator to review +that exact registration. Do not blindly run the legacy uninstaller at that point: +it may remove the shared TSF catalog. Setup preserves the conflict rather than +deleting an unknown registration. + +An administrator is needed once to register the shared Windows text service. +Right-click **Install-Machine-SmartKey.cmd** in the extracted archive and choose +**Run as administrator**. It copies the complete bundle to the Windows Program +Files known folder, in **SmartKey**, and registers the machine COM/TSF catalog. +This phase does not enable SmartKey for the administrator, edit their AppData, +change their keyboards, or add a login entry. It refuses an existing machine +installation; remove it explicitly before replacing it. + +Then close the administrator window. As the person who will type, double-click +**Install-SmartKey.cmd normally**. This enables SmartKey for that account, copies +only missing starter data to that user's **AppData\Roaming\smartkey**, verifies +it in a separate process, and adds one user login entry and Start menu commands. +Existing configuration, public corpus changes and personal files are preserved. +If machine installation is missing, this step stops with instructions before +changing user data or keyboard settings. It never triggers automatic elevation. +Each additional permitted user runs this normal step in their own account. + +## Use and return to your ordinary keyboard + +Press **Win+Space** and choose SmartKey. Press **Win+Space** again to select your +ordinary keyboard. Existing layouts and your default choice remain available. +Open a new text app after installation. The login entry is intended to restore +availability at the user's next Windows login; verify this in the desktop pilot. +SmartKey does not force itself to become the default keyboard. + +Start menu > SmartKey provides **Status**, **Enable**, **Disable** and **Uninstall**. +Disable removes this user's SmartKey login entry. Enable restores availability +and login. Run these commands normally, without administrator elevation. + +## Remove + +**Uninstall-SmartKey.cmd** removes only the current user's availability, login +entry and menu commands. It preserves personal data and the shared machine files. + +When no one needs the shared installation, close apps using SmartKey. Right-click +**Uninstall-Machine-SmartKey.cmd in the original extracted archive** and choose +**Run as administrator**. It removes the exact shared catalog/COM registration and +allowlisted Program Files bundle. Run it from the archive, not the installed +Program Files directory, so the running helper can delete every machine file. +Other keyboards and all users' personal data are preserved. Machine removal does +not access other users' profiles; each configured user can remove their own login +entry using Uninstall-SmartKey.cmd from the archive. Locked files or failed +registration operations produce an error and can be retried; no success is claimed +for a partial removal. + +## Files and privacy + +The archive contains EXE/DLL, seven visible CMD commands, two manifests, public +JSON starter data, this README and license notices. It never includes personal.json. +User data stays in the user's AppData; no network connection is needed for setup +or typing. No service, scheduled task or PowerShell policy bypass is installed. diff --git a/crates/smartkey-win/packaging/Status-SmartKey.cmd b/crates/smartkey-win/packaging/Status-SmartKey.cmd new file mode 100644 index 0000000..47d7a4f --- /dev/null +++ b/crates/smartkey-win/packaging/Status-SmartKey.cmd @@ -0,0 +1,16 @@ +@echo off +setlocal +set "SMARTKEY_HELPER=%~dp0smartkey-register.exe" +if not exist "%SMARTKEY_HELPER%" set "SMARTKEY_HELPER=%ProgramFiles%\SmartKey\smartkey-register.exe" +if not exist "%SMARTKEY_HELPER%" ( + echo SmartKey helper is missing. Extract the whole archive, then install the machine package once. + pause + exit /b 1 +) +"%SMARTKEY_HELPER%" --status +if errorlevel 1 ( + echo SmartKey could not complete the action. The error window describes the failure. + pause + exit /b 1 +) +exit /b 0 diff --git a/crates/smartkey-win/packaging/Uninstall-Machine-SmartKey.cmd b/crates/smartkey-win/packaging/Uninstall-Machine-SmartKey.cmd new file mode 100644 index 0000000..1375fa5 --- /dev/null +++ b/crates/smartkey-win/packaging/Uninstall-Machine-SmartKey.cmd @@ -0,0 +1,16 @@ +@echo off +setlocal +rem Explicit machine action. Right-click this command in the extracted archive +rem and choose Run as administrator. No automatic elevation is attempted. +if not exist "%~dp0smartkey-register.exe" ( + echo Extract the whole original SmartKey archive before this machine action. + pause + exit /b 1 +) +"%~dp0smartkey-register.exe" --uninstall-machine +if errorlevel 1 ( + echo Machine action was incomplete. The error window describes the failure. + pause + exit /b 1 +) +exit /b 0 diff --git a/crates/smartkey-win/packaging/Uninstall-SmartKey.cmd b/crates/smartkey-win/packaging/Uninstall-SmartKey.cmd new file mode 100644 index 0000000..6507bea --- /dev/null +++ b/crates/smartkey-win/packaging/Uninstall-SmartKey.cmd @@ -0,0 +1,20 @@ +@echo off +setlocal +set "SMARTKEY_HELPER=%~dp0smartkey-register.exe" +if not exist "%SMARTKEY_HELPER%" set "SMARTKEY_HELPER=%ProgramFiles%\SmartKey\smartkey-register.exe" +if not exist "%SMARTKEY_HELPER%" ( + echo SmartKey helper is missing. Extract the whole archive, then install the machine package once. + pause + exit /b 1 +) +"%SMARTKEY_HELPER%" --uninstall +if errorlevel 1 ( + echo SmartKey could not complete the action. The error window describes the failure. + pause + exit /b 1 +) +rem Remove this currently running user menu command only in the final block. +( + del /q "%APPDATA%\Microsoft\Windows\Start Menu\Programs\SmartKey\Uninstall-SmartKey.cmd" 2>nul + exit /b 0 +) diff --git a/crates/smartkey-win/packaging/smoke-user.ps1 b/crates/smartkey-win/packaging/smoke-user.ps1 new file mode 100644 index 0000000..97db786 --- /dev/null +++ b/crates/smartkey-win/packaging/smoke-user.ps1 @@ -0,0 +1,273 @@ +# One bounded native maintenance smoke. Run ONLY in an ephemeral standard account. +# The parent CI job supplies/loads that user's profile; this script never elevates. +[CmdletBinding()] +param( + [Parameter(Mandatory=$true)][string]$Bundle, + [Parameter(Mandatory=$true)][string]$OutDir, + [ValidateSet('Prerequisite', 'Lifecycle')][string]$Phase = 'Lifecycle' +) +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version Latest + +$identity = [Security.Principal.WindowsIdentity]::GetCurrent() +$principal = New-Object Security.Principal.WindowsPrincipal($identity) +$adminSid = 'S-1-5-32-544' +if ($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) -or + @($identity.Groups | Where-Object { $_.Value -eq $adminSid }).Count -ne 0) { + throw 'Refusing smoke: this must be a standard NONADMIN account, not an elevated or split-token administrator.' +} +if (-not $env:LOCALAPPDATA -or -not $env:APPDATA -or -not $env:USERPROFILE) { + throw 'The standard user profile must be loaded (APPDATA, LOCALAPPDATA, USERPROFILE required).' +} +# Credential launchers can inherit the administrator's environment even when +# the token/profile is correct. Cross-check actual SID profile + shell folders +# before constructing any destination, and fail rather than touching that home. +$profileKey = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey( + 'SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\' + $identity.User.Value) +if ($null -eq $profileKey) { throw 'No loaded Windows profile is registered for the current standard-user SID.' } +try { $actualProfile = [Environment]::ExpandEnvironmentVariables([string]$profileKey.GetValue('ProfileImagePath', $null)) } +finally { $profileKey.Dispose() } +$actualLocal = [Environment]::GetFolderPath([Environment+SpecialFolder]::LocalApplicationData) +$actualRoaming = [Environment]::GetFolderPath([Environment+SpecialFolder]::ApplicationData) +foreach ($pair in @(@($env:USERPROFILE, $actualProfile), @($env:LOCALAPPDATA, $actualLocal), @($env:APPDATA, $actualRoaming))) { + if (-not $pair[1] -or -not [string]::Equals( + [IO.Path]::GetFullPath($pair[0]).TrimEnd('\'), + [IO.Path]::GetFullPath($pair[1]).TrimEnd('\'), [StringComparison]::OrdinalIgnoreCase)) { + throw 'Inherited USERPROFILE/APPDATA/LOCALAPPDATA does not match the actual standard-user profile. The parent must supply the correct user environment.' + } +} +$bundlePath = (Resolve-Path -LiteralPath $Bundle).Path +$install = Join-Path ([Environment]::GetFolderPath([Environment+SpecialFolder]::ProgramFiles)) 'SmartKey' +$localInstall = Join-Path $env:LOCALAPPDATA 'SmartKey' +$data = Join-Path $env:APPDATA 'smartkey' +$run = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run' +$clsid = 'HKCU:\SOFTWARE\Classes\CLSID\{7A3B9E1F-4C2D-4E5A-8F6B-1D2E3F4A5B6C}' +$tip = 'HKCU:\Software\Microsoft\CTF\TIP\{7A3B9E1F-4C2D-4E5A-8F6B-1D2E3F4A5B6C}' +$machineClass = 'HKLM:\SOFTWARE\Classes\CLSID\{7A3B9E1F-4C2D-4E5A-8F6B-1D2E3F4A5B6C}' +$machineTip = 'HKLM:\Software\Microsoft\CTF\TIP\{7A3B9E1F-4C2D-4E5A-8F6B-1D2E3F4A5B6C}' +$menu = Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu\Programs\SmartKey' +New-Item -ItemType Directory -Path $OutDir -Force | Out-Null + +function Assert-True([bool]$condition, [string]$message) { + if (-not $condition) { throw $message } +} +function Get-Login { + if (-not (Test-Path -LiteralPath $run)) { return $null } + return (Get-Item -LiteralPath $run).GetValue('SmartKey', $null) +} +function Keyboard-Snapshot { + # Only the ephemeral account's bounded keyboard configuration is read. + $snapshot = [ordered]@{} + foreach ($name in @('Keyboard Layout\Preload', 'Keyboard Layout\Substitutes')) { + $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($name) + $values = [ordered]@{} + if ($null -ne $key) { + try { foreach ($value in @($key.GetValueNames() | Sort-Object)) { $values[$value] = $key.GetValue($value) } } + finally { $key.Dispose() } + } + $snapshot[$name] = $values + } + $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Control Panel\International\User Profile') + try { + $snapshot['InputMethodOverride'] = if ($null -ne $key) { $key.GetValue('InputMethodOverride', $null) } else { $null } + $snapshot['DefaultInputMethodOverride'] = if ($null -ne $key) { $key.GetValue('DefaultInputMethodOverride', $null) } else { $null } + } + finally { if ($null -ne $key) { $key.Dispose() } } + $default = Get-WinDefaultInputMethodOverride + $snapshot['WindowsDefaultInputTip'] = if ($null -ne $default) { $default.InputTip } else { $null } + return ($snapshot | ConvertTo-Json -Depth 4 -Compress) +} +function Machine-Snapshot { + # Only this product's protected files and exact machine identities are read. + $files = @(Get-ChildItem -LiteralPath $install -File -Force | Sort-Object Name | ForEach-Object { + [ordered]@{ name=$_.Name; sha256=(Get-FileHash -LiteralPath $_.FullName -Algorithm SHA256).Hash } + }) + $registry = foreach ($path in @($machineClass, $machineTip)) { + Assert-True (Test-Path -LiteralPath $path) "Missing machine registration: $path" + $keys = @((Get-Item -LiteralPath $path)) + @(Get-ChildItem -LiteralPath $path -Recurse | Sort-Object Name) + foreach ($key in $keys) { + $values = [ordered]@{} + foreach ($name in @($key.GetValueNames() | Sort-Object)) { $values[$name] = $key.GetValue($name) } + [ordered]@{ path=$key.Name; values=$values } + } + } + return ([ordered]@{ files=$files; registry=@($registry) } | ConvertTo-Json -Depth 8 -Compress) +} +$steps = New-Object System.Collections.Generic.List[object] +function Invoke-Helper([string]$exe, [string]$action, [int]$expectedExit = 0) { + $stem = '{0:D2}-{1}' -f $steps.Count, $action.TrimStart('-') + $stdout = Join-Path $OutDir "$stem.stdout.txt" + $stderr = Join-Path $OutDir "$stem.stderr.txt" + # Keep our own .NET Process/handle from Start through ExitCode. Windows + # PowerShell Start-Process -PassThru can yield a null cached ExitCode even + # after WaitForExit/Refresh; null must never be recorded as native success. + $process = New-Object System.Diagnostics.Process + $process.StartInfo = New-Object System.Diagnostics.ProcessStartInfo + $process.StartInfo.FileName = $exe + $process.StartInfo.Arguments = "$action --no-dialog" + $process.StartInfo.UseShellExecute = $false + $process.StartInfo.CreateNoWindow = $true + $process.StartInfo.RedirectStandardOutput = $true + $process.StartInfo.RedirectStandardError = $true + try { + if (-not $process.Start()) { throw "Cannot start $action." } + # Drain both streams asynchronously before waiting, avoiding pipe + # deadlocks while preserving the real helper HRESULT/error output. + $stdoutTask = $process.StandardOutput.ReadToEndAsync() + $stderrTask = $process.StandardError.ReadToEndAsync() + if (-not $process.WaitForExit(45000)) { + $process.Kill() + if (-not $process.WaitForExit(5000)) { throw "$action timed out and did not exit after termination." } + [IO.File]::WriteAllText($stdout, $stdoutTask.GetAwaiter().GetResult()) + [IO.File]::WriteAllText($stderr, $stderrTask.GetAwaiter().GetResult()) + throw "$action exceeded 45 seconds; the smoke stopped." + } + $exitCode = $process.ExitCode + if ($null -eq $exitCode) { throw "$action exited but its real exit code was unavailable; refusing an inferred result." } + $stdoutText = $stdoutTask.GetAwaiter().GetResult() + $stderrText = $stderrTask.GetAwaiter().GetResult() + [IO.File]::WriteAllText($stdout, $stdoutText) + [IO.File]::WriteAllText($stderr, $stderrText) + $steps.Add([ordered]@{ action=$action; exit_code=[int]$exitCode; expected_exit=$expectedExit }) + if ($exitCode -ne $expectedExit) { + throw "$action returned exit $exitCode (required $expectedExit); see $stderr." + } + return [pscustomobject]@{ stdout=$stdoutText; stderr=$stderrText } + } finally { $process.Dispose() } + +} +$receipt = [ordered]@{ + status='NOT_RUN'; standard_nonadmin=$true; current_user_profile_confirmed=$true; no_dialog=$true + phase=$Phase; typing_exercised=$false; logon_exercised=$false + steps=$steps; keyboard_defaults_preserved=$false; personal_sentinel_preserved=$false + keyboard_allowed_language_additions_observed=$false + machine_prerequisite_refused=$false; machine_install_preserved=$false +} +$before = Keyboard-Snapshot +$before | Set-Content -LiteralPath (Join-Path $OutDir 'keyboard-before.json') -Encoding UTF8 +function Assert-KeyboardPreserved([string]$message) { + $after = Keyboard-Snapshot + $after | Set-Content -LiteralPath (Join-Path $OutDir ('keyboard-after-{0:D2}.json' -f $steps.Count)) -Encoding UTF8 + if ($Phase -eq 'Prerequisite') { Assert-True ($after -ceq $before) $message; return } + $baseline = $before | ConvertFrom-Json + $current = $after | ConvertFrom-Json + foreach ($name in @('InputMethodOverride', 'DefaultInputMethodOverride', 'WindowsDefaultInputTip')) { + Assert-True (($current.$name | ConvertTo-Json -Compress) -ceq ($baseline.$name | ConvertTo-Json -Compress)) $message + } + foreach ($name in @('Keyboard Layout\Preload', 'Keyboard Layout\Substitutes')) { + $old = @($baseline.$name.PSObject.Properties) + $new = @($current.$name.PSObject.Properties) + $oldNames = @($old | ForEach-Object Name) + $newNames = @($new | ForEach-Object Name) + foreach ($entry in $old) { + Assert-True ($newNames -ccontains $entry.Name) $message + $value = $current.$name.PSObject.Properties[$entry.Name].Value + Assert-True (($value | ConvertTo-Json -Compress) -ceq ($entry.Value | ConvertTo-Json -Compress)) $message + } + $added = @($new | Where-Object { $oldNames -cnotcontains $_.Name }) + Assert-True ($added.Count -le 1) $message + if ($added.Count -eq 0) { continue } + # Permit only the observed LANG 0402 addition on this known CI baseline. + $first = $baseline.'Keyboard Layout\Preload'.PSObject.Properties['1'] + Assert-True ($null -ne $first -and $first.Value -is [string] -and $first.Value -ceq '00000409') $message + $entry = $added[0] + Assert-True ($entry.Value -is [string]) $message + if ($name -eq 'Keyboard Layout\Preload') { + Assert-True (@($oldNames | Where-Object { $_ -cnotmatch '^[1-9][0-9]*$' }).Count -eq 0) $message + $max = ($oldNames | ForEach-Object { [int]$_ } | Measure-Object -Maximum).Maximum + Assert-True ($entry.Name -cmatch '^[1-9][0-9]*$' -and [int]$entry.Name -gt $max -and $entry.Value -ceq '00000402') $message + Assert-True (@($old | Where-Object { $_.Value -ceq '00000402' }).Count -eq 0) $message + } else { + Assert-True ($entry.Name -ceq '00000402' -and $entry.Value -ceq $first.Value) $message + } + $receipt['keyboard_allowed_language_additions_observed']=$true + } +} +try { + # Never use a daily account or delete a prior installation for this smoke. + Assert-True (-not (Test-Path -LiteralPath $localInstall)) 'The ephemeral user already has a SmartKey install folder.' + Assert-True (-not (Test-Path -LiteralPath $data)) 'The ephemeral user already has SmartKey data.' + Assert-True (-not (Test-Path -LiteralPath $clsid)) 'The ephemeral user already has SmartKey COM registration.' + Assert-True (-not (Test-Path -LiteralPath $tip)) 'The ephemeral user already has SmartKey user enablement.' + Assert-True (-not (Test-Path -LiteralPath $menu)) 'The ephemeral user already has a SmartKey Start menu folder.' + Assert-True ($null -eq (Get-Login)) 'An existing SmartKey Run value must not be overwritten by this smoke.' + if ($Phase -eq 'Prerequisite') { + foreach ($path in @($install, $machineClass, $machineTip)) { + Assert-True (-not (Test-Path -LiteralPath $path)) 'The prerequisite refusal requires a fresh machine without SmartKey.' + } + $refusal = Invoke-Helper (Join-Path $bundlePath 'smartkey-register.exe') '--install' 1 + Assert-True ($refusal.stderr.Contains('SmartKey machine installation is missing.') -and + $refusal.stderr.Contains('Install-Machine-SmartKey.cmd')) 'Missing-machine refusal did not explain the supported administrator setup.' + foreach ($path in @($data, $menu, $localInstall, $clsid, $tip, $install, $machineClass, $machineTip)) { + Assert-True (-not (Test-Path -LiteralPath $path)) "Prerequisite refusal created unexpected state: $path" + } + Assert-True ($null -eq (Get-Login)) 'Prerequisite refusal created a login entry.' + Assert-KeyboardPreserved 'Prerequisite refusal changed keyboard/default settings.' + $receipt['machine_prerequisite_refused']=$true + $receipt['keyboard_defaults_preserved']=$true + $receipt['status']='PASS_NATIVE_STANDARD_USER_PREREQUISITE' + return + } + + $expectedFiles = @(Get-ChildItem -LiteralPath $bundlePath -Force | ForEach-Object Name | Sort-Object) + $actualFiles = @(Get-ChildItem -LiteralPath $install -Force | ForEach-Object Name | Sort-Object) + Assert-True (-not (Compare-Object -ReferenceObject $expectedFiles -DifferenceObject $actualFiles)) 'Protected install does not contain the exact frozen bundle.' + foreach ($name in $expectedFiles) { + Assert-True ((Get-FileHash -LiteralPath (Join-Path $bundlePath $name) -Algorithm SHA256).Hash -eq + (Get-FileHash -LiteralPath (Join-Path $install $name) -Algorithm SHA256).Hash) "Protected file differs from frozen bundle: $name" + } + $machineBefore = Machine-Snapshot + $helper = Join-Path $install 'smartkey-register.exe' + $initialStatus = Invoke-Helper $helper '--status' + Assert-True ($initialStatus.stdout -match '(?m)^TSF profile: disabled\.') 'Machine registration enabled SmartKey before this user opted in.' + Keyboard-Snapshot | Set-Content -LiteralPath (Join-Path $OutDir 'keyboard-after-initial-status.json') -Encoding UTF8 + New-Item -ItemType Directory -Path $data | Out-Null + $personal = Join-Path $data 'personal.json' + [IO.File]::WriteAllText($personal, '{"synthetic_smoke_sentinel":true}') + $personalHash = (Get-FileHash -LiteralPath $personal -Algorithm SHA256).Hash + + Invoke-Helper (Join-Path $bundlePath 'smartkey-register.exe') '--install' | Out-Null + foreach ($name in @('smartkey-register.exe','smartkey_win.dll','Install-SmartKey.cmd','Status-SmartKey.cmd','Enable-SmartKey.cmd','Disable-SmartKey.cmd','Uninstall-SmartKey.cmd')) { + Assert-True (Test-Path -LiteralPath (Join-Path $install $name) -PathType Leaf) "Missing staged file: $name" + } + foreach ($name in @('smartkey.json','corpus_en.json','corpus_bg.json','corpus_tech.json')) { + Assert-True (Test-Path -LiteralPath (Join-Path $data $name) -PathType Leaf) "Missing runtime data: $name" + } + foreach ($name in @('Status-SmartKey.cmd','Enable-SmartKey.cmd','Disable-SmartKey.cmd','Uninstall-SmartKey.cmd')) { + Assert-True (Test-Path -LiteralPath (Join-Path $menu $name) -PathType Leaf) "Missing Start menu command: $name" + } + Assert-True ((Get-Login) -eq ('"' + $helper + '" --login')) 'Login entry does not identify the stable installed helper.' + Assert-KeyboardPreserved 'Installation changed existing keyboard/default settings.' + Invoke-Helper $helper '--status' | Out-Null + Invoke-Helper $helper '--disable' | Out-Null + Assert-True ($null -eq (Get-Login)) 'Disable left the owned login entry.' + Assert-KeyboardPreserved 'Disable changed existing keyboard/default settings.' + Invoke-Helper $helper '--enable' | Out-Null + Assert-True ((Get-Login) -eq ('"' + $helper + '" --login')) 'Enable did not restore the exact owned login entry.' + Assert-KeyboardPreserved 'Enable changed existing keyboard/default settings.' + Invoke-Helper $helper '--uninstall' | Out-Null + Assert-True ($null -eq (Get-Login)) 'Uninstall left the owned login entry.' + Assert-True (-not (Test-Path -LiteralPath $clsid)) 'Uninstall left own HKCU COM registration.' + # Windows may retain an explicit per-user disabled marker. Verify the API + # state in a fresh process instead of deleting that supported state by hand. + $status = Invoke-Helper $helper '--status' + Assert-True ($status.stdout -match '(?m)^TSF profile: disabled\.') 'Fresh process did not report the uninstalled user profile disabled.' + Invoke-Helper $helper '--verify-machine' | Out-Null + foreach ($name in @('Status-SmartKey.cmd','Enable-SmartKey.cmd','Disable-SmartKey.cmd')) { + Assert-True (-not (Test-Path -LiteralPath (Join-Path $menu $name))) "Uninstall left a user maintenance command: $name" + } + Assert-KeyboardPreserved 'Maintenance changed existing keyboard/default settings.' + Assert-True ((Get-FileHash -LiteralPath $personal -Algorithm SHA256).Hash -eq $personalHash) 'Maintenance changed the synthetic personal file.' + Assert-True (-not (Test-Path -LiteralPath $localInstall)) 'User setup created an unprotected local binary folder.' + Assert-True ((Machine-Snapshot) -eq $machineBefore) 'User maintenance changed the protected bundle or machine registration.' + $receipt['keyboard_defaults_preserved']=$true + $receipt['personal_sentinel_preserved']=$true + $receipt['machine_install_preserved']=$true + $receipt['status']='PASS_NATIVE_STANDARD_USER_MAINTENANCE' +} catch { + $receipt['status']='FAIL_NATIVE_STANDARD_USER_' + $Phase.ToUpperInvariant() + $receipt['error']=$_.Exception.Message + throw +} finally { + $receipt | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $OutDir 'smoke-result.json') -Encoding UTF8 +} diff --git a/crates/smartkey-win/packaging/user_setup.rs b/crates/smartkey-win/packaging/user_setup.rs new file mode 100644 index 0000000..f5a2c86 --- /dev/null +++ b/crates/smartkey-win/packaging/user_setup.rs @@ -0,0 +1,295 @@ +//! Filesystem-only staging, shared by the installer and portable tests. +use std::fs; +use std::io; +use std::path::{Path, PathBuf}; + +pub const BINARIES: &[&str] = &["smartkey-register.exe", "smartkey_win.dll"]; +pub const DATA: &[&str] = &[ + "smartkey.json", + "corpus_en.json", + "corpus_bg.json", + "corpus_tech.json", +]; +pub const SUPPORT: &[&str] = &[ + "Install-SmartKey.cmd", + "Install-Machine-SmartKey.cmd", + "Uninstall-Machine-SmartKey.cmd", + "windows-runtime-manifest.json", + "artifact-source-manifest.json", + "Status-SmartKey.cmd", + "Enable-SmartKey.cmd", + "Disable-SmartKey.cmd", + "Uninstall-SmartKey.cmd", + "README-WINDOWS.md", + "LICENSE", + "LICENSE-GPL", + "LICENSE-APACHE", +]; + +/// Validate every required payload before touching any destination. +pub fn validate_bundle(bundle: &Path) -> io::Result<()> { + for name in BINARIES.iter().chain(DATA).chain(SUPPORT) { + let path = bundle.join(name); + let metadata = fs::symlink_metadata(&path)?; + if !metadata.is_file() || metadata.file_type().is_symlink() || metadata.len() == 0 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("Incomplete or redirected SmartKey bundle: {name}. Extract the whole archive first."), + )); + } + } + Ok(()) +} + +/// Machine phase: destination must be new, with a protected parent validated +/// by the Windows caller. It never creates or reads any user's data folder. +pub fn stage_machine(bundle: &Path, install: &Path) -> io::Result { + validate_bundle(bundle)?; + create_machine_directory(install)?; + for name in BINARIES.iter().chain(DATA).chain(SUPPORT) { + let mut source = fs::File::open(bundle.join(name))?; + let mut destination = fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(install.join(name))?; + set_machine_file_owner(&install.join(name))?; + io::copy(&mut source, &mut destination)?; + } + Ok(install.join("smartkey-register.exe")) +} + +#[cfg(not(windows))] +fn set_machine_file_owner(_path: &Path) -> io::Result<()> { + Ok(()) +} + +#[cfg(windows)] +fn set_machine_file_owner(path: &Path) -> io::Result<()> { + use windows::core::*; + use windows::Win32::Security::Authorization::{SetNamedSecurityInfoW, SE_FILE_OBJECT}; + use windows::Win32::Security::{ + CreateWellKnownSid, WinBuiltinAdministratorsSid, OWNER_SECURITY_INFORMATION, PSID, + }; + let mut storage = [0u32; 17]; + let sid = PSID(storage.as_mut_ptr().cast()); + let mut size = std::mem::size_of_val(&storage) as u32; + unsafe { CreateWellKnownSid(WinBuiltinAdministratorsSid, PSID::default(), sid, &mut size) } + .map_err(io::Error::other)?; + let name: Vec = path + .as_os_str() + .to_string_lossy() + .encode_utf16() + .chain(Some(0)) + .collect(); + let status = unsafe { + SetNamedSecurityInfoW( + PCWSTR(name.as_ptr()), + SE_FILE_OBJECT, + OWNER_SECURITY_INFORMATION, + sid, + PSID::default(), + None, + None, + ) + }; + if status.0 != 0 { + return Err(io::Error::other(Error::from(HRESULT::from_win32(status.0)))); + } + Ok(()) +} + +#[cfg(not(windows))] +fn create_machine_directory(path: &Path) -> io::Result<()> { + fs::create_dir(path) +} + +#[cfg(windows)] +fn create_machine_directory(path: &Path) -> io::Result<()> { + use windows::core::*; + use windows::Win32::Foundation::{LocalFree, HLOCAL}; + use windows::Win32::Security::Authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW; + use windows::Win32::Security::{PSECURITY_DESCRIPTOR, SECURITY_ATTRIBUTES}; + use windows::Win32::Storage::FileSystem::CreateDirectoryW; + let mut descriptor = PSECURITY_DESCRIPTOR::default(); + unsafe { + // Administrators own the directory. Only SYSTEM/Administrators can + // write; users can read/execute. Children inherit the same grants. + ConvertStringSecurityDescriptorToSecurityDescriptorW( + w!("O:BAG:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;FRFX;;;BU)"), + 1, + &mut descriptor, + None, + ) + } + .map_err(io::Error::other)?; + let attributes = SECURITY_ATTRIBUTES { + nLength: std::mem::size_of::() as u32, + lpSecurityDescriptor: descriptor.0, + bInheritHandle: false.into(), + }; + let name: Vec = path + .as_os_str() + .to_string_lossy() + .encode_utf16() + .chain(Some(0)) + .collect(); + let result = unsafe { CreateDirectoryW(PCWSTR(name.as_ptr()), Some(&attributes)) }; + unsafe { + LocalFree(HLOCAL(descriptor.0)); + } + result.map_err(io::Error::other) +} + +/// Normal-user phase: copy only missing starter data from the verified machine +/// bundle. It never stages DLLs/EXEs and preserves existing personal files. +pub fn stage_user_data(bundle: &Path, data: &Path) -> io::Result<()> { + validate_bundle(bundle)?; + fs::create_dir_all(data)?; + for name in DATA { + let to = data.join(name); + if !to.exists() { + let mut destination = fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(to)?; + let mut source = fs::File::open(bundle.join(name))?; + io::copy(&mut source, &mut destination)?; + } + } + Ok(()) +} + +/// Remove only allowlisted files in the exact verified machine directory. +/// Refuse unknown objects before deleting anything; never recursive-delete. +pub fn remove_machine_files(install: &Path) -> io::Result<()> { + if !install.exists() { + return Ok(()); + } + let expected: Vec<_> = BINARIES + .iter() + .chain(DATA) + .chain(SUPPORT) + .copied() + .collect(); + for entry in fs::read_dir(install)? { + let entry = entry?; + if !entry.file_type()?.is_file() + || !expected + .iter() + .any(|name| entry.file_name() == std::ffi::OsStr::new(name)) + { + return Err(io::Error::other( + "Unexpected object in SmartKey machine directory; it was preserved", + )); + } + } + for name in expected { + let path = install.join(name); + if path.exists() { + fs::remove_file(path)?; + } + } + fs::remove_dir(install) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + static SEQUENCE: AtomicUsize = AtomicUsize::new(0); + struct Scratch(PathBuf); + impl Scratch { + fn new() -> Self { + let p = std::env::temp_dir().join(format!( + "smartkey-stage-{}-{}", + std::process::id(), + SEQUENCE.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir(&p).unwrap(); + Self(p) + } + fn bundle(&self) -> PathBuf { + let p = self.0.join("bundle with spaces"); + fs::create_dir(&p).unwrap(); + for name in BINARIES.iter().chain(DATA).chain(SUPPORT) { + fs::write(p.join(name), format!("public bundle {name}")).unwrap(); + } + p + } + } + impl Drop for Scratch { + fn drop(&mut self) { + fs::remove_dir_all(&self.0).unwrap(); + } + } + #[test] + fn machine_stage_does_not_create_user_data_and_refuses_existing_destination() { + let s = Scratch::new(); + let bundle = s.bundle(); + let install = s.0.join("ProgramFiles-SmartKey"); + let personal = s.0.join("Roaming-smartkey"); + stage_machine(&bundle, &install).unwrap(); + assert!(!personal.exists()); + fs::write(install.join("smartkey_win.dll"), "existing machine binary").unwrap(); + assert!(stage_machine(&bundle, &install).is_err()); + assert_eq!( + fs::read(install.join("smartkey_win.dll")).unwrap(), + b"existing machine binary" + ); + } + + #[test] + fn user_stage_preserves_personal_data_and_never_stages_binaries() { + let s = Scratch::new(); + let bundle = s.bundle(); + let data = s.0.join("Roaming-smartkey"); + fs::create_dir(&data).unwrap(); + fs::write(data.join("smartkey.json"), "existing config").unwrap(); + fs::write(data.join("personal.json"), "private sentinel").unwrap(); + fs::write(data.join("corpus_en.json"), "custom corpus").unwrap(); + stage_user_data(&bundle, &data).unwrap(); + stage_user_data(&bundle, &data).unwrap(); + assert_eq!( + fs::read(data.join("smartkey.json")).unwrap(), + b"existing config" + ); + assert_eq!( + fs::read(data.join("personal.json")).unwrap(), + b"private sentinel" + ); + assert_eq!( + fs::read(data.join("corpus_en.json")).unwrap(), + b"custom corpus" + ); + assert!(data.join("corpus_bg.json").is_file()); + assert!(!data.join("smartkey_win.dll").exists()); + assert!(!data.join("smartkey-register.exe").exists()); + } + + #[test] + fn incomplete_bundle_refuses_machine_and_user_destinations() { + let s = Scratch::new(); + let bundle = s.bundle(); + fs::remove_file(bundle.join("smartkey_win.dll")).unwrap(); + let install = s.0.join("install"); + let data = s.0.join("data"); + assert!(stage_machine(&bundle, &install).is_err()); + assert!(stage_user_data(&bundle, &data).is_err()); + assert!(!install.exists()); + assert!(!data.exists()); + } + + #[test] + fn machine_removal_refuses_unknown_objects_before_deleting_known_files() { + let s = Scratch::new(); + let bundle = s.bundle(); + let install = s.0.join("install"); + stage_machine(&bundle, &install).unwrap(); + fs::write(install.join("unexpected.txt"), "preserved").unwrap(); + assert!(remove_machine_files(&install).is_err()); + assert!(install.join("smartkey_win.dll").is_file()); + fs::remove_file(install.join("unexpected.txt")).unwrap(); + remove_machine_files(&install).unwrap(); + assert!(!install.exists()); + } +} diff --git a/crates/smartkey-win/src/display.rs b/crates/smartkey-win/src/display.rs index 60273ec..cf2cd78 100644 --- a/crates/smartkey-win/src/display.rs +++ b/crates/smartkey-win/src/display.rs @@ -76,6 +76,12 @@ pub struct SingleItemEnum { yielded: std::cell::Cell, } +impl Default for SingleItemEnum { + fn default() -> Self { + Self::new() + } +} + impl SingleItemEnum { pub fn new() -> Self { Self { diff --git a/crates/smartkey-win/src/edit_session.rs b/crates/smartkey-win/src/edit_session.rs index a753bd4..c79ea1a 100644 --- a/crates/smartkey-win/src/edit_session.rs +++ b/crates/smartkey-win/src/edit_session.rs @@ -1,11 +1,4 @@ -// TSF Edit Session — executes text operations within a granted edit cookie. -// -// TSF requires all text modifications to go through ITfEditSession::DoEditSession(). -// The framework calls back with an `ec` (edit cookie) that grants write access. -// -// Architecture: Single SmartKeyEditSession with EditOp enum instead of 3 COM classes. -// Rationale: 3 operations don't justify 3 COM classes; one struct reduces COM lifetime bugs. - +// Text operations run only inside the edit cookie granted by TSF. use std::cell::RefCell; use std::mem::ManuallyDrop; use std::rc::Rc; @@ -14,203 +7,235 @@ use windows::core::*; use windows::Win32::Foundation::*; use windows::Win32::UI::TextServices::*; -/// The operation to perform inside the edit session. pub enum EditOp { - /// Display ghost text as a TSF composition. ShowGhost { text: String, + /// Zero for a suffix-only ghost; typed-prefix UTF-16 length for preedit. + typed_units: usize, composition: Rc>>, - /// Composition sink to receive OnCompositionTerminated callbacks. comp_sink: ITfCompositionSink, - /// TfGuidAtom for ghost display attribute (grey styling). 0 = no styling. ghost_attr_atom: u32, }, - /// Remove ghost text and end the composition. HideGhost { composition: Rc>>, }, - /// Commit (finalize) text into the document. CommitText { text: String, composition: Rc>>, }, + ReplaceWord { + replace_len: usize, + text: String, + composition: Rc>>, + }, } -/// A one-shot edit session that executes a single EditOp. #[implement(ITfEditSession)] pub struct SmartKeyEditSession { context: ITfContext, - #[allow(dead_code)] // reserved for display attribute operations - client_id: u32, op: EditOp, } -impl SmartKeyEditSession { - pub fn new(context: ITfContext, client_id: u32, op: EditOp) -> Self { - Self { - context, - client_id, - op, - } - } -} - impl ITfEditSession_Impl for SmartKeyEditSession_Impl { fn DoEditSession(&self, ec: u32) -> Result<()> { match &self.op { EditOp::ShowGhost { text, + typed_units, composition, comp_sink, ghost_attr_atom, - } => self.do_show_ghost(ec, text, composition, comp_sink, *ghost_attr_atom), - EditOp::HideGhost { composition } => self.do_hide_ghost(ec, composition), - EditOp::CommitText { text, composition } => self.do_commit_text(ec, text, composition), + } => self.show( + ec, + text, + *typed_units, + composition, + comp_sink, + *ghost_attr_atom, + ), + EditOp::HideGhost { composition } => self.hide(ec, composition), + EditOp::CommitText { text, composition } => { + // CommitText is an exact insertion, including partial Right acceptance. + self.hide(ec, composition)?; + self.insert(ec, text) + } + EditOp::ReplaceWord { + replace_len, + text, + composition, + } => { + self.hide(ec, composition)?; + self.replace(ec, *replace_len, text) + } } } } impl SmartKeyEditSession_Impl { - /// Show or update ghost text via a TSF composition. - /// - /// After inserting/updating ghost text, the selection (caret) is moved to the - /// START of the ghost range so that forwarded keys are inserted before the ghost. - fn do_show_ghost( + fn own_range(&self, active: &ITfComposition) -> Result { + unsafe { + let range = active.GetRange()?; + if range.GetContext()? != self.context { + return Err(Error::from_hresult(E_INVALIDARG)); + } + Ok(range) + } + } + + fn show( &self, ec: u32, text: &str, + typed_units: usize, composition: &Rc>>, comp_sink: &ITfCompositionSink, - ghost_attr_atom: u32, + atom: u32, ) -> Result<()> { - let text_utf16: Vec = text.encode_utf16().collect(); - let mut comp = composition.borrow_mut(); - - if let Some(ref active) = *comp { - // Update existing composition range. - unsafe { - let range = active.GetRange()?; - range.SetText(ec, 0, &text_utf16)?; - // Re-apply attribute after SetText (SetText clears properties). - self.apply_ghost_attr(ec, &range, ghost_attr_atom)?; - self.set_caret_to_range_start(ec, &range)?; - } - } else { - // Start a new composition. - unsafe { + let utf16: Vec = text.encode_utf16().collect(); + let offset = i32::try_from(typed_units).map_err(|_| Error::from_hresult(E_INVALIDARG))?; + if typed_units > utf16.len() { + return Err(Error::from_hresult(E_INVALIDARG)); + } + // Never retain a RefCell borrow across COM: callbacks can reenter the sink. + let active = composition.borrow().clone(); + unsafe { + let range = if let Some(active) = active { + let range = self.own_range(&active)?; + range.SetText(ec, 0, &utf16)?; + range + } else { let insert: ITfInsertAtSelection = self.context.cast()?; - let range = insert.InsertTextAtSelection(ec, TF_IAS_NOQUERY, &text_utf16)?; - + let range = insert.InsertTextAtSelection(ec, TF_IAS_NOQUERY, &utf16)?; let ctx_comp: ITfContextComposition = self.context.cast()?; let new_comp = ctx_comp.StartComposition(ec, &range, Some(comp_sink))?; - *comp = Some(new_comp); + *composition.borrow_mut() = Some(new_comp); + range + }; + let prop = self.context.GetProperty(&GUID_PROP_ATTRIBUTE)?; + prop.Clear(ec, &range)?; + if atom != 0 && typed_units < utf16.len() { + let ghost = range.Clone()?; + let mut shifted = 0; + ghost.ShiftStart(ec, offset, &mut shifted, std::ptr::null())?; + if shifted != offset { + return Err(Error::from_hresult(E_FAIL)); + } + prop.SetValue(ec, &ghost, &VARIANT::from(atom as i32))?; + } + let caret = range.Clone()?; + caret.Collapse(ec, TF_ANCHOR_START)?; + let mut shifted = 0; + caret.ShiftEnd(ec, offset, &mut shifted, std::ptr::null())?; + if shifted != offset { + return Err(Error::from_hresult(E_FAIL)); + } + caret.Collapse(ec, TF_ANCHOR_END)?; + self.select(ec, caret) + } + } - self.apply_ghost_attr(ec, &range, ghost_attr_atom)?; - self.set_caret_to_range_start(ec, &range)?; + fn hide(&self, ec: u32, composition: &Rc>>) -> Result<()> { + let active = composition.borrow().clone(); + if let Some(active) = active { + let range = self.own_range(&active)?; + // Clear the slot before EndComposition so our own callback cannot reset + // the core state that has already generated the remaining action batch. + unsafe { + // A refused deletion must keep ownership of the surviving preedit. + range.SetText(ec, 0, &[])?; + composition.borrow_mut().take(); + if let Err(error) = active.EndComposition(ec) { + *composition.borrow_mut() = Some(active); + return Err(error); + } } } Ok(()) } - /// Set GUID_PROP_ATTRIBUTE on a range to apply ghost text styling (grey). - /// - /// The atom is a TfGuidAtom obtained from ITfCategoryMgr::RegisterGUID. - /// TSF resolves it back through our ITfDisplayAttributeProvider to get - /// the actual TF_DISPLAYATTRIBUTE (grey foreground). - fn apply_ghost_attr(&self, ec: u32, range: &ITfRange, atom: u32) -> Result<()> { - if atom == 0 { + fn insert(&self, ec: u32, text: &str) -> Result<()> { + if text.is_empty() { return Ok(()); } unsafe { - let prop = self.context.GetProperty(&GUID_PROP_ATTRIBUTE)?; - let variant = VARIANT::from(atom as i32); - prop.SetValue(ec, range, &variant)?; + let insert: ITfInsertAtSelection = self.context.cast()?; + let range = insert.InsertTextAtSelection( + ec, + TF_IAS_NOQUERY, + &text.encode_utf16().collect::>(), + )?; + let caret = range.Clone()?; + caret.Collapse(ec, TF_ANCHOR_END)?; + self.select(ec, caret) } - Ok(()) } - /// Remove ghost text and end the active composition. - fn do_hide_ghost( - &self, - ec: u32, - composition: &Rc>>, - ) -> Result<()> { - let mut comp = composition.borrow_mut(); - if let Some(active) = comp.take() { - unsafe { - // Clear the composition text before ending. - let range = active.GetRange()?; - range.SetText(ec, 0, &[])?; - active.EndComposition(ec)?; - } - } - Ok(()) - } - - /// Commit text: end the ghost composition so the suffix becomes permanent. - /// - /// When a ghost composition is active, the typed prefix is already in the - /// document (via ForwardKey) and the ghost suffix is in the composition range. - /// EndComposition makes the suffix permanent — no text replacement needed. - /// The `text` parameter is only used when there's no active composition - /// (e.g. direct commit without prior ghost). - fn do_commit_text( - &self, - ec: u32, - text: &str, - composition: &Rc>>, - ) -> Result<()> { - let mut comp = composition.borrow_mut(); - if let Some(active) = comp.take() { - unsafe { - // Ghost suffix is already in the document. Just finalize it. - active.EndComposition(ec)?; + fn replace(&self, ec: u32, count: usize, text: &str) -> Result<()> { + let lookback = count + .checked_mul(2) + .and_then(|n| i32::try_from(n).ok()) + .ok_or_else(|| Error::from_hresult(E_INVALIDARG))?; + unsafe { + let mut selection = [TF_SELECTION::default()]; + let mut fetched = 0; + let result = + self.context + .GetSelection(ec, TF_DEFAULT_SELECTION, &mut selection, &mut fetched); + let caret = ManuallyDrop::take(&mut selection[0].range); + result?; + let caret = caret + .filter(|_| fetched == 1) + .ok_or_else(|| Error::from_hresult(E_FAIL))?; + if !caret.IsEmpty(ec)?.as_bool() { + return Err(Error::from_hresult(E_INVALIDARG)); } - } else { - // No active composition — insert the full text at selection. - let text_utf16: Vec = text.encode_utf16().collect(); - unsafe { - let insert: ITfInsertAtSelection = self.context.cast()?; - insert.InsertTextAtSelection(ec, TF_IAS_NOQUERY, &text_utf16)?; + let previous = caret.Clone()?; + let mut shifted = 0; + previous.ShiftStart(ec, -lookback, &mut shifted, std::ptr::null())?; + let mut buffer = vec![0u16; lookback as usize]; + let mut read = 0; + previous.GetText(ec, 0, &mut buffer, &mut read)?; + buffer.truncate(read as usize); + let units = crate::text_contract::suffix_units(&buffer, count) + .ok_or_else(|| Error::from_hresult(E_INVALIDARG))?; + let replacement = caret.Clone()?; + let requested = -(units as i32); + replacement.ShiftStart(ec, requested, &mut shifted, std::ptr::null())?; + if shifted != requested { + return Err(Error::from_hresult(E_FAIL)); } + replacement.SetText(ec, 0, &text.encode_utf16().collect::>())?; + replacement.Collapse(ec, TF_ANCHOR_END)?; + self.select(ec, replacement) } - Ok(()) } - /// Move the caret (selection) to the start of the given range. - /// - /// This ensures forwarded keys are inserted before the ghost text, not after. - unsafe fn set_caret_to_range_start(&self, ec: u32, range: &ITfRange) -> Result<()> { - let caret = range.Clone()?; - caret.Collapse(ec, TF_ANCHOR_START)?; - - let selection = TF_SELECTION { + fn select(&self, ec: u32, caret: ITfRange) -> Result<()> { + let mut selection = [TF_SELECTION { range: ManuallyDrop::new(Some(caret)), style: TF_SELECTIONSTYLE { ase: TF_AE_END, fInterimChar: BOOL(0), }, - }; - self.context.SetSelection(ec, &[selection])?; - Ok(()) + }]; + unsafe { + let result = self.context.SetSelection(ec, &selection); + ManuallyDrop::drop(&mut selection[0].range); + result + } } } -// -- Public helper to request an edit session from outside --------------- - -/// Request a synchronous edit session on the given context. -/// -/// Creates a `SmartKeyEditSession` with the specified operation and asks TSF -/// to execute it. Returns Ok(()) if the session completed successfully. -/// -/// # Safety -/// Must be called from a TSF key event handler (OnKeyDown) for TF_ES_SYNC -/// to succeed — TSF only grants synchronous sessions during key callbacks. +/// Synchronous write sessions are requested only from TSF key callbacks. pub fn request_edit_session(context: &ITfContext, client_id: u32, op: EditOp) -> Result<()> { - let session: ITfEditSession = SmartKeyEditSession::new(context.clone(), client_id, op).into(); - - let hr = - unsafe { context.RequestEditSession(client_id, &session, TF_ES_READWRITE | TF_ES_SYNC)? }; - - hr.ok() + let session: ITfEditSession = SmartKeyEditSession { + context: context.clone(), + op, + } + .into(); + unsafe { + context + .RequestEditSession(client_id, &session, TF_ES_READWRITE | TF_ES_SYNC)? + .ok() + } } diff --git a/crates/smartkey-win/src/lib.rs b/crates/smartkey-win/src/lib.rs index fed2a0e..7b590f6 100644 --- a/crates/smartkey-win/src/lib.rs +++ b/crates/smartkey-win/src/lib.rs @@ -19,6 +19,8 @@ pub mod dll; mod edit_session; #[cfg(windows)] pub mod registration; +#[cfg(any(windows, test))] +mod text_contract; #[cfg(windows)] mod tsf; diff --git a/crates/smartkey-win/src/register.rs b/crates/smartkey-win/src/register.rs index fc68a37..4d6a69d 100644 --- a/crates/smartkey-win/src/register.rs +++ b/crates/smartkey-win/src/register.rs @@ -1,95 +1,553 @@ -// COM/TSF registration helper for SmartKey Windows IME. -// -// Usage: -// smartkey-register.exe --install Register as a TSF Text Input Processor -// smartkey-register.exe --uninstall Remove registration +//! Visible current-user setup and maintenance for a self-contained bundle. +#[cfg(windows)] +#[path = "../packaging/user_setup.rs"] +mod user_setup; fn main() { - let args: Vec = std::env::args().collect(); - - match args.get(1).map(|s| s.as_str()) { - Some("--install") => { - println!("SmartKey IME registration"); - println!("CLSID: {{{}}}", smartkey_win::config::CLSID_SMARTKEY_STR); - - #[cfg(windows)] - { - let dll_path = find_dll_path(); - println!("DLL: {dll_path}"); - - init_com(); - match smartkey_win::registration::register(&dll_path) { - Ok(system_wide) => { - if system_wide { - println!("SmartKey IME registered system-wide (HKLM)."); - } else { - println!("SmartKey IME registered per-user (HKCU)."); - } + #[cfg(windows)] + { + let arguments: Vec = std::env::args().skip(1).collect(); + let no_dialog = arguments.iter().any(|argument| argument == "--no-dialog"); + let actions: Vec<_> = arguments + .iter() + .filter(|argument| argument.as_str() != "--no-dialog") + .collect(); + let action = actions + .first() + .map_or("--install", |argument| argument.as_str()); + let quiet = no_dialog || action == "--login" || action == "--verify"; + let result = if actions.len() > 1 { + Err("Specify one SmartKey action, optionally followed by --no-dialog.".into()) + } else { + run(action) + }; + match result { + Ok(message) => { + println!("{message}"); + if !quiet { + show(&message, false); + } + } + Err(message) => { + eprintln!("SmartKey: {message}"); + // Login failures are visible too; a broken install must not + // appear silently successful just because it ran at login. + if !no_dialog && action != "--verify" { + show(&message, true); + } + std::process::exit(1); + } + } + } + #[cfg(not(windows))] + { + eprintln!("SmartKey Windows setup requires Windows 10/11 x64."); + std::process::exit(1); + } +} + +#[cfg(windows)] +fn run(action: &str) -> Result { + use smartkey_win::registration; + let install = machine_install_dir()?; + let installed_exe = install.join("smartkey-register.exe"); + let expected_dll = install.join("smartkey_win.dll"); + let exe = std::env::current_exe().map_err(|e| e.to_string())?; + let bundle = exe.parent().ok_or("Cannot locate SmartKey bundle")?; + let _com = Com::new()?; + match action { + "--install-machine" => { + require_elevation(true)?; + let parent = install.parent().ok_or("Cannot locate Program Files")?; + validate_protected_path(parent)?; + if registry_class_exists(windows::Win32::System::Registry::HKEY_LOCAL_MACHINE) + .map_err(api_error)? || install.exists() { + return Err("A SmartKey machine installation or destination already exists. It was preserved. Run Uninstall-Machine-SmartKey.cmd from the extracted archive before installing a replacement.".into()); + } + user_setup::stage_machine(bundle, &install) + .map_err(|e| format!("Cannot stage protected machine bundle: {e}. Any partial destination was retained for explicit machine removal."))?; + validate_machine_objects(&install)?; + registration::register_machine(expected_dll.to_str().ok_or("DLL path is not Unicode")?) + .map_err(api_error)?; + fresh_verification(&installed_exe, "--verify-machine")?; + Ok("SmartKey machine files and TSF catalog installed. No user's data, keyboard availability or login entry was configured.\n\nClose this administrator window, then double-click Install-SmartKey.cmd normally as each user who wants SmartKey.".into()) + } + "--verify-machine" => { + verify_machine_install(&install)?; + registration::profile_present().map_err(api_error)?; + Ok("SmartKey protected machine COM path and persistent TSF profile verified. User enablement was not required or changed.".into()) + } + "--uninstall-machine" => { + require_elevation(true)?; + if exe.starts_with(&install) { + return Err("Run Uninstall-Machine-SmartKey.cmd from the extracted original archive, outside Program Files\\SmartKey, so the running helper can remove all machine files.".into()); + } + validate_protected_path(install.parent().ok_or("Cannot locate Program Files")?)?; + if install.exists() { validate_machine_objects(&install)?; } + if registry_class_exists(windows::Win32::System::Registry::HKEY_LOCAL_MACHINE).map_err(api_error)? { + verify_com_path(&expected_dll).map_err(api_error)?; + } + registration::unregister_machine().map_err(api_error)?; + user_setup::remove_machine_files(&install) + .map_err(|e| format!("Machine registration removed, but machine file removal failed: {e}. Close apps using SmartKey and retry this command from the extracted archive."))?; + Ok("SmartKey machine catalog, COM registration and protected files removed. User data, other keyboards and user login entries were preserved. Each configured user can run Uninstall-SmartKey.cmd to remove their own login/menu entries.".into()) + } + "--install" | "--enable" | "--disable" | "--login" | "--uninstall" => { + require_elevation(false)?; + refuse_user_com_override()?; + if action != "--uninstall" { verify_machine_install(&install)?; } + let roaming = known_folder(&windows::Win32::UI::Shell::FOLDERID_RoamingAppData)?; + let menu = roaming.join("Microsoft/Windows/Start Menu/Programs/SmartKey"); + match action { + "--install" => { + // Machine prerequisite above precedes every user mutation. + registration::profile_present().map_err(api_error)?; + user_setup::stage_user_data(&install, &roaming.join("smartkey")) + .map_err(|e| format!("Cannot stage missing user data: {e}"))?; + registration::set_user_enabled(true).map_err(api_error)?; + fresh_verification(&installed_exe, "--verify")?; + set_login(true, &installed_exe).map_err(api_error)?; + std::fs::create_dir_all(&menu).map_err(|e| e.to_string())?; + for name in ["Status-SmartKey.cmd", "Enable-SmartKey.cmd", "Disable-SmartKey.cmd", "Uninstall-SmartKey.cmd"] { + std::fs::copy(install.join(name), menu.join(name)).map_err(|e| e.to_string())?; } - Err(e) => { - log::error!("Registration failed: {e}"); - uninit_com(); - std::process::exit(1); + Ok("SmartKey enabled for this user.\n\nPress Win+Space and select SmartKey; press Win+Space again to return to your ordinary keyboard. Existing layouts and default choice were preserved.\n\nSmartKey is available at Windows login. Start menu > SmartKey provides Status, Enable, Disable and Uninstall. Existing personal data/configuration were preserved. Open a new text app to begin.".into()) + } + "--enable" | "--login" => { + registration::set_user_enabled(true).map_err(api_error)?; + if !registration::profile_enabled().map_err(api_error)? { return Err("Windows did not enable the SmartKey profile".into()); } + if action == "--enable" { set_login(true, &installed_exe).map_err(api_error)?; } + Ok("SmartKey enabled for this user and available at login. Select it with Win+Space; your default keyboard was preserved.".into()) + } + "--disable" => { + registration::set_user_enabled(false).map_err(api_error)?; + set_login(false, &installed_exe).map_err(api_error)?; + if registration::profile_enabled().map_err(api_error)? { return Err("Windows still reports SmartKey enabled".into()); } + Ok("SmartKey disabled and its login entry removed. Use Win+Space to select your ordinary keyboard. Enable-SmartKey restores it; personal data is unchanged.".into()) + } + "--uninstall" => { + // User removal remains usable after the machine package is removed. + set_login(false, &installed_exe).map_err(api_error)?; + if install.exists() { + verify_machine_install(&install)?; + registration::unregister_user().map_err(api_error)?; + if registration::profile_enabled().map_err(api_error)? { return Err("Windows still reports this user's SmartKey profile enabled after removal".into()); } } + for name in ["Status-SmartKey.cmd", "Enable-SmartKey.cmd", "Disable-SmartKey.cmd"] { + let path = menu.join(name); + if path.exists() { std::fs::remove_file(path).map_err(|e| e.to_string())?; } + } + Ok("SmartKey removed for this user. Its login entry was removed; ordinary keyboards, personal data and shared machine files were preserved. Use Uninstall-Machine-SmartKey.cmd from the extracted archive as administrator only when shared machine removal is wanted.".into()) } - uninit_com(); + _ => unreachable!(), } + } + "--verify" | "--status" => { + refuse_user_com_override()?; + verify_machine_install(&install)?; + let enabled = registration::profile_enabled().map_err(api_error)?; + if action == "--verify" && !enabled { return Err("SmartKey profile exists but is disabled".into()); } + Ok(format!("SmartKey protected machine COM path verified.\nTSF profile: {}.\nUse Win+Space to choose SmartKey or an existing ordinary keyboard.", if enabled { "enabled" } else { "disabled" })) + } + _ => Err("Use --install, --status, --enable, --disable, --uninstall, --install-machine or --uninstall-machine.".into()), + } +} + +#[cfg(windows)] +fn api_error(error: windows::core::Error) -> String { + format!( + "{} (HRESULT 0x{:08X}). Existing keyboards remain available through Win+Space.", + error, + error.code().0 as u32 + ) +} + +#[cfg(windows)] +fn fresh_verification(helper: &std::path::Path, action: &str) -> Result<(), String> { + let result = std::process::Command::new(helper) + .arg(action) + .arg("--no-dialog") + .output() + .map_err(|e| format!("Cannot verify in a fresh process: {e}"))?; + if !result.status.success() { + return Err(format!( + "Fresh-process SmartKey verification failed.\n{}", + String::from_utf8_lossy(&result.stderr) + )); + } + Ok(()) +} + +#[cfg(windows)] +fn machine_install_dir() -> Result { + Ok(known_folder(&windows::Win32::UI::Shell::FOLDERID_ProgramFiles)?.join("SmartKey")) +} + +#[cfg(windows)] +fn known_folder(id: &windows::core::GUID) -> Result { + use windows::Win32::UI::Shell::{SHGetKnownFolderPath, KF_FLAG_DEFAULT}; + let raw = unsafe { SHGetKnownFolderPath(id, KF_FLAG_DEFAULT, None) }.map_err(api_error)?; + let result = unsafe { raw.to_string() }.map_err(|e| e.to_string()); + unsafe { + windows::Win32::System::Com::CoTaskMemFree(Some(raw.0.cast())); + } + Ok(std::path::PathBuf::from(result?)) +} + +#[cfg(windows)] +fn require_elevation(required: bool) -> Result<(), String> { + use windows::Win32::Foundation::BOOL; + use windows::Win32::Security::{ + CheckTokenMembership, CreateWellKnownSid, WinBuiltinAdministratorsSid, PSID, + }; + let mut storage = [0u32; 17]; + let sid = PSID(storage.as_mut_ptr().cast()); + let mut size = std::mem::size_of_val(&storage) as u32; + unsafe { CreateWellKnownSid(WinBuiltinAdministratorsSid, PSID::default(), sid, &mut size) } + .map_err(api_error)?; + let mut elevated = BOOL::default(); + unsafe { CheckTokenMembership(None, sid, &mut elevated) }.map_err(api_error)?; + if elevated.as_bool() != required { + return Err(if required { + "This explicit machine action requires administrator rights. Right-click the matching Machine-SmartKey.cmd in the extracted archive and choose Run as administrator." + } else { + "Run this user action normally, without Run as administrator, in the account that will use SmartKey." + }.into()); + } + Ok(()) +} + +#[cfg(windows)] +fn missing_machine_error() -> String { + "SmartKey machine installation is missing. Ask an administrator to right-click Install-Machine-SmartKey.cmd and choose Run as administrator, then run Install-SmartKey.cmd normally.".into() +} + +#[cfg(windows)] +fn verify_machine_install(install: &std::path::Path) -> Result<(), String> { + if !install.is_dir() { + return Err(missing_machine_error()); + } + validate_protected_path(install.parent().ok_or("Cannot locate Program Files")?)?; + validate_machine_objects(install)?; + user_setup::validate_bundle(install) + .map_err(|e| format!("SmartKey machine installation is incomplete: {e}"))?; + verify_com_path(&install.join("smartkey_win.dll")).map_err(api_error) +} + +#[cfg(windows)] +fn validate_machine_objects(install: &std::path::Path) -> Result<(), String> { + validate_protected_path(install)?; + let allowed: Vec<_> = user_setup::BINARIES + .iter() + .chain(user_setup::DATA) + .chain(user_setup::SUPPORT) + .copied() + .collect(); + for entry in std::fs::read_dir(install).map_err(|e| e.to_string())? { + let entry = entry.map_err(|e| e.to_string())?; + if !allowed + .iter() + .any(|name| entry.file_name() == std::ffi::OsStr::new(name)) + { + return Err("Unexpected object in machine destination; it was preserved".into()); + } + validate_protected_path(&entry.path())?; + if !entry.file_type().map_err(|e| e.to_string())?.is_file() { + return Err("Machine payload contains a non-file object".into()); + } + } + Ok(()) +} - #[cfg(not(windows))] - println!("(dry run — not on Windows)"); +#[cfg(windows)] +fn validate_protected_path(path: &std::path::Path) -> Result<(), String> { + use std::os::windows::fs::MetadataExt; + use windows::core::*; + use windows::Win32::Foundation::{LocalFree, HLOCAL}; + use windows::Win32::Security::Authorization::*; + use windows::Win32::Security::*; + // Reject junctions/symlinks anywhere in the path before copying/loading. + for ancestor in path.ancestors().filter(|p| !p.as_os_str().is_empty()) { + let metadata = std::fs::symlink_metadata(ancestor).map_err(|e| e.to_string())?; + if metadata.file_attributes() & 0x400 != 0 { + return Err("Refusing a reparse point in the machine destination".into()); } - Some("--uninstall") => { - println!("Unregistering SmartKey IME..."); - - #[cfg(windows)] - { - init_com(); - match smartkey_win::registration::unregister() { - Ok(()) => println!("SmartKey IME unregistered successfully."), - Err(e) => { - log::error!("Unregistration failed: {e}"); - uninit_com(); - std::process::exit(1); - } + } + let text: Vec = path + .as_os_str() + .to_string_lossy() + .encode_utf16() + .chain(Some(0)) + .collect(); + let mut owner = PSID::default(); + let mut dacl = std::ptr::null_mut(); + let mut descriptor = PSECURITY_DESCRIPTOR::default(); + let status = unsafe { + GetNamedSecurityInfoW( + PCWSTR(text.as_ptr()), + SE_FILE_OBJECT, + OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, + Some(&mut owner), + None, + Some(&mut dacl), + None, + &mut descriptor, + ) + }; + if status.0 != 0 { + return Err(api_error(Error::from(HRESULT::from_win32(status.0)))); + } + let checked = (|| { + let trusted_sid = |sid: PSID| -> std::result::Result { + let mut string = PWSTR::null(); + unsafe { ConvertSidToStringSidW(sid, &mut string) }.map_err(api_error)?; + let sid_text = unsafe { string.to_string() }.map_err(|e| e.to_string()); + unsafe { + LocalFree(HLOCAL(string.0.cast())); + } + Ok(matches!( + sid_text?.as_str(), + "S-1-5-18" + | "S-1-5-32-544" + | "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464" + )) + }; + if !trusted_sid(owner)? { + return Err( + "Machine object is not owned by SYSTEM, Administrators or TrustedInstaller".into(), + ); + } + if dacl.is_null() { + return Err("Refusing an unprotected machine destination (NULL DACL)".into()); + } + for index in 0..u32::from(unsafe { (*dacl).AceCount }) { + let mut raw = std::ptr::null_mut(); + unsafe { GetAce(dacl, index, &mut raw) }.map_err(api_error)?; + let header = unsafe { &*(raw as *const ACE_HEADER) }; + if header.AceFlags & 8 != 0 || header.AceType == 1 { + continue; + } // inherit-only / deny + if header.AceType != 0 { + return Err("Machine destination has an unsupported access-grant ACE".into()); + } + let ace = unsafe { &*(raw as *const ACCESS_ALLOWED_ACE) }; + // Write/delete/permission-change rights; read/synchronize are allowed. + if ace.Mask & 0x500D0156 != 0 { + let sid = PSID(std::ptr::addr_of!(ace.SidStart).cast_mut().cast()); + if !trusted_sid(sid)? { + return Err( + "Machine destination grants write/delete access to an untrusted principal" + .into(), + ); } - uninit_com(); } + } + Ok(()) + })(); + unsafe { + LocalFree(HLOCAL(descriptor.0)); + } + checked +} + +#[cfg(windows)] +fn refuse_user_com_override() -> Result<(), String> { + if registry_class_exists(windows::Win32::System::Registry::HKEY_CURRENT_USER) + .map_err(api_error)? + { + return Err("An existing per-user SmartKey COM registration could override the protected machine DLL. It was preserved. Ask an administrator to review this exact old user registration before retrying. Do not run a legacy SmartKey uninstaller after machine installation: it may remove the shared TSF catalog.".into()); + } + Ok(()) +} + +#[cfg(windows)] +fn registry_class_exists( + root: windows::Win32::System::Registry::HKEY, +) -> windows::core::Result { + use windows::core::*; + use windows::Win32::Foundation::ERROR_FILE_NOT_FOUND; + use windows::Win32::System::Registry::*; + let key = format!( + "SOFTWARE\\Classes\\CLSID\\{{{}}}", + smartkey_win::config::CLSID_SMARTKEY_STR + ); + let key: Vec = key.encode_utf16().chain(Some(0)).collect(); + let mut opened = HKEY::default(); + let status = unsafe { RegOpenKeyExW(root, PCWSTR(key.as_ptr()), 0, KEY_READ, &mut opened) }; + if status == ERROR_FILE_NOT_FOUND { + return Ok(false); + } + if status.0 != 0 { + return Err(Error::from(HRESULT::from_win32(status.0))); + } + let closed = unsafe { RegCloseKey(opened) }; + if closed.0 != 0 { + return Err(Error::from(HRESULT::from_win32(closed.0))); + } + Ok(true) +} - #[cfg(not(windows))] - println!("(dry run — not on Windows)"); +#[cfg(windows)] +struct Com; +#[cfg(windows)] +impl Com { + fn new() -> Result { + unsafe { + windows::Win32::System::Com::CoInitializeEx( + None, + windows::Win32::System::Com::COINIT_APARTMENTTHREADED, + ) } - _ => { - log::error!("Usage: smartkey-register [--install | --uninstall]"); - std::process::exit(1); + .ok() + .map_err(|e| format!("COM initialization failed: {e}"))?; + Ok(Self) + } +} +#[cfg(windows)] +impl Drop for Com { + fn drop(&mut self) { + unsafe { + windows::Win32::System::Com::CoUninitialize(); } } } -/// Find the DLL in the same directory as this executable. #[cfg(windows)] -fn find_dll_path() -> String { - let exe = std::env::current_exe().expect("cannot determine exe path"); - let dir = exe.parent().expect("exe has no parent directory"); - dir.join("smartkey_win.dll").to_string_lossy().into_owned() +fn show(message: &str, failed: bool) { + use windows::core::*; + use windows::Win32::UI::WindowsAndMessaging::*; + let text: Vec = message.encode_utf16().chain(Some(0)).collect(); + unsafe { + MessageBoxW( + None, + PCWSTR(text.as_ptr()), + w!("SmartKey"), + MB_OK + | if failed { + MB_ICONERROR + } else { + MB_ICONINFORMATION + }, + ); + } } #[cfg(windows)] -fn init_com() { - let hr = unsafe { - windows::Win32::System::Com::CoInitializeEx( +fn read_value( + root: windows::Win32::System::Registry::HKEY, + key: &str, + name: Option<&str>, +) -> windows::core::Result> { + use windows::core::*; + use windows::Win32::Foundation::ERROR_FILE_NOT_FOUND; + use windows::Win32::System::Registry::*; + let key: Vec = key.encode_utf16().chain(Some(0)).collect(); + let name: Option> = name.map(|s| s.encode_utf16().chain(Some(0)).collect()); + let name = name.as_ref().map_or(PCWSTR::null(), |s| PCWSTR(s.as_ptr())); + let mut data = vec![0u16; 32768]; + let mut size = (data.len() * 2) as u32; + let result = unsafe { + RegGetValueW( + root, + PCWSTR(key.as_ptr()), + name, + RRF_RT_REG_SZ, None, - windows::Win32::System::Com::COINIT_APARTMENTTHREADED, + Some(data.as_mut_ptr().cast()), + Some(&mut size), ) }; - if hr.is_err() { - log::error!("COM initialization failed: {hr:?}"); - std::process::exit(1); + if result == ERROR_FILE_NOT_FOUND { + return Ok(None); + } + if result.0 != 0 { + return Err(Error::from(HRESULT::from_win32(result.0))); } + let length = data.iter().position(|&v| v == 0).unwrap_or(data.len()); + Ok(Some(String::from_utf16_lossy(&data[..length]))) } #[cfg(windows)] -fn uninit_com() { - unsafe { - windows::Win32::System::Com::CoUninitialize(); +fn verify_com_path(expected: &std::path::Path) -> windows::core::Result<()> { + use windows::core::Error; + use windows::Win32::Foundation::E_FAIL; + let key = format!( + "SOFTWARE\\Classes\\CLSID\\{{{}}}\\InProcServer32", + smartkey_win::config::CLSID_SMARTKEY_STR + ); + let value = read_value( + windows::Win32::System::Registry::HKEY_LOCAL_MACHINE, + &key, + None, + ) + .map_err(|e| { + Error::new( + e.code(), + format!("Verification HKLM protected machine COM path / RegGetValueW: {e}"), + ) + })? + .ok_or_else(|| { + Error::new( + E_FAIL, + "Verification HKLM protected machine COM path: SmartKey registration is missing", + ) + })?; + if std::path::Path::new(&value) != expected || !expected.is_file() { + return Err(Error::new( + E_FAIL, + "Verification HKLM protected machine COM path: registration does not point to the installed DLL", + )); + } + Ok(()) +} + +#[cfg(windows)] +fn set_login(enabled: bool, exe: &std::path::Path) -> windows::core::Result<()> { + use windows::core::*; + use windows::Win32::Foundation::{ERROR_FILE_NOT_FOUND, E_FAIL}; + use windows::Win32::System::Registry::*; + const KEY: &str = "Software\\Microsoft\\Windows\\CurrentVersion\\Run"; + const NAME: &str = "SmartKey"; + let expected = format!("\"{}\" --login", exe.display()); + let existing = read_value(HKEY_CURRENT_USER, KEY, Some(NAME))?; + if existing.as_ref().is_some_and(|value| value != &expected) { + return Err(Error::new( + E_FAIL, + "An unrelated SmartKey login value already exists; it was preserved", + )); + } + if !enabled && existing.is_none() { + return Ok(()); + } + let key: Vec = KEY.encode_utf16().chain(Some(0)).collect(); + let mut handle = HKEY::default(); + let opened = unsafe { RegCreateKeyW(HKEY_CURRENT_USER, PCWSTR(key.as_ptr()), &mut handle) }; + if opened.0 != 0 { + return Err(Error::from(HRESULT::from_win32(opened.0))); + } + let value: Vec = expected.encode_utf16().chain(Some(0)).collect(); + let result = unsafe { + if enabled { + RegSetValueExW( + handle, + w!("SmartKey"), + 0, + REG_SZ, + Some(std::slice::from_raw_parts( + value.as_ptr().cast(), + value.len() * 2, + )), + ) + } else { + RegDeleteValueW(handle, w!("SmartKey")) + } + }; + let close = unsafe { RegCloseKey(handle) }; + if result.0 != 0 && result != ERROR_FILE_NOT_FOUND { + return Err(Error::from(HRESULT::from_win32(result.0))); + } + if close.0 != 0 { + return Err(Error::from(HRESULT::from_win32(close.0))); } + Ok(()) } diff --git a/crates/smartkey-win/src/registration.rs b/crates/smartkey-win/src/registration.rs index 023de12..0d99d85 100644 --- a/crates/smartkey-win/src/registration.rs +++ b/crates/smartkey-win/src/registration.rs @@ -4,10 +4,10 @@ //! the standalone smartkey-register.exe binary. //! //! Registration creates: -//! 1. HKLM\SOFTWARE\Classes\CLSID\{CLSID}\InProcServer32 → DLL path + Apartment -//! (or HKCU equivalent when the current user lacks admin privileges) +//! 1. HKCU\SOFTWARE\Classes\CLSID\{CLSID}\InProcServer32 → DLL path + Apartment //! 2. TSF TIP profile via ITfInputProcessorProfileMgr::RegisterProfile -//! 3. TSF keyboard category via ITfCategoryMgr::RegisterCategory +//! 3. TSF keyboard/display categories via ITfCategoryMgr::RegisterCategory +//! 4. Current-user availability via input.dll InstallLayoutOrTipUserReg //! //! Precondition: COM must be initialized (CoInitializeEx) before calling. @@ -26,95 +26,195 @@ const LANGID_BG: u16 = 0x0402; /// Display name shown in Windows language settings. const DISPLAY_NAME: &str = "SmartKey"; -/// TSF flag: register profile as process-local only (required for HKCU installs). -const TF_RP_LOCALPROCESS: u32 = 0x4; +// Persistent registration uses flags 0. TF_RP_LOCALPROCESS is NOT per-user: +// it vanishes with the installer process. User availability is configured by +// the documented input.dll InstallLayoutOrTipUserReg API below. -// -- Public API --------------------------------------------------------- - -/// Register the SmartKey IME. `dll_path` is the absolute path to the DLL. -/// -/// Attempts HKLM (system-wide) first; falls back to HKCU (per-user) if -/// the current user lacks admin privileges. -/// -/// Returns `true` if registered system-wide (HKLM), `false` for per-user (HKCU). +/// Register COM only in HKCU, then the persistent TSF profile/categories and +/// enable exactly this profile for the current user. No elevation fallback. +/// Returns false for compatibility with DllRegisterServer's existing caller. +/// Any denied TSF operation is a real installation failure, not a skipped step. pub fn register(dll_path: &str) -> Result { - if is_hklm_writable() { - register_com_server(dll_path)?; - register_tip_profile(dll_path, 0)?; - register_categories()?; - Ok(true) - } else { - register_com_server_hkcu(dll_path).map_err(|e| { - log::error!(" [FAIL] COM server (HKCU): {e}"); - e - })?; - log::info!(" [OK] COM server registered (HKCU)"); - register_tip_profile(dll_path, TF_RP_LOCALPROCESS).map_err(|e| { - log::error!(" [FAIL] TIP profile: {e}"); - e - })?; - log::info!(" [OK] TIP profile registered"); - match register_categories() { - Ok(()) => log::info!(" [OK] Categories registered"), - Err(e) => log::warn!(" [SKIP] Categories (needs admin): {e}"), - } - Ok(false) - } + register_com_server_hkcu(dll_path).map_err(|e| step_error("HKCU COM registration", e))?; + register_tip_profile(dll_path, 0, true).map_err(|e| step_error("Persistent TSF profile", e))?; + register_categories().map_err(|e| step_error("TSF categories", e))?; + set_user_enabled(true)?; + Ok(false) +} + +/// Explicit elevated machine phase. The caller must stage and validate a +/// protected machine DLL first. Never changes any user's availability or data. +pub fn register_machine(dll_path: &str) -> Result<()> { + register_com_server(HKEY_LOCAL_MACHINE, dll_path) + .map_err(|e| step_error("Machine COM registration", e))?; + register_tip_profile(dll_path, 0, false) + .map_err(|e| step_error("Persistent machine TSF profile", e))?; + register_categories().map_err(|e| step_error("Machine TSF categories", e)) +} + +/// Remove only the executing user's availability. Shared catalog/COM remain. +pub fn unregister_user() -> Result<()> { + install_layout_or_tip(1).map_err(|e| step_error("Current-user profile removal", e)) } -/// Unregister the SmartKey IME. Errors are non-fatal (best-effort cleanup). +/// Explicit elevated machine cleanup; never changes a user's Run/data/menu. +pub fn unregister_machine() -> Result<()> { + collect_removal_errors([ + ("Machine categories", unregister_categories()), + ("Machine text service", unregister_text_service()), + ("Machine COM", unregister_com_server(HKEY_LOCAL_MACHINE)), + ]) +} + +/// Attempt each own-identity cleanup and return failures rather than claiming +/// success after partial removal. Never deletes HKLM or another keyboard. pub fn unregister() -> Result<()> { - let _ = unregister_categories(); - let _ = unregister_tip_profile(); - // Clean both hives (best-effort). - let _ = unregister_com_server_hklm(); - let _ = unregister_com_server_hkcu(); + let operations = [ + ("Current-user profile removal", install_layout_or_tip(1)), + ("Categories", unregister_categories()), + ("TSF profile", unregister_tip_profile()), + ("HKCU COM", unregister_com_server_hkcu()), + ]; + collect_removal_errors(operations) +} + +fn collect_removal_errors(operations: [(&str, Result<()>); N]) -> Result<()> { + let errors: Vec<_> = operations + .into_iter() + .filter_map(|(name, result)| result.err().map(|e| (e.code(), format!("{name}: {e}")))) + .collect(); + if let Some((code, _)) = errors.first() { + return Err(Error::new( + *code, + errors + .iter() + .map(|(_, text)| text.as_str()) + .collect::>() + .join("; "), + )); + } Ok(()) } -// -- COM server registration (registry) -------------------------------- +fn step_error(step: &str, error: Error) -> Error { + Error::new(error.code(), format!("{step}: {error}")) +} -fn is_hklm_writable() -> bool { - let subkey = "SOFTWARE\\Classes"; - let subkey_w: Vec = subkey.encode_utf16().chain(std::iter::once(0)).collect(); - let mut hkey = HKEY::default(); - let result = unsafe { - RegOpenKeyExW( - HKEY_LOCAL_MACHINE, - PCWSTR(subkey_w.as_ptr()), - 0, - KEY_WRITE, - &mut hkey, - ) +/// Microsoft documents NULL user path as HKCU. No DEFPROFILE/CLEANINSTALL flag: +/// existing layouts and default selection remain under the user's control. +pub fn set_user_enabled(enabled: bool) -> Result<()> { + install_layout_or_tip(if enabled { 0 } else { 0x80 }) +} + +fn install_layout_or_tip(flags: u32) -> Result<()> { + use windows::Win32::Foundation::{FreeLibrary, BOOL, E_FAIL, HANDLE}; + use windows::Win32::System::LibraryLoader::{ + GetProcAddress, LoadLibraryExW, LOAD_LIBRARY_SEARCH_SYSTEM32, }; - if result.0 == 0 { - let _ = unsafe { RegCloseKey(hkey) }; - true - } else { - false + type Install = unsafe extern "system" fn(PCWSTR, PCWSTR, PCWSTR, PCWSTR, u32) -> BOOL; + // Restrict resolution to the Windows system directory; do not load input.dll + // from the portable bundle/current working directory. + let module = unsafe { + LoadLibraryExW( + w!("input.dll"), + HANDLE::default(), + LOAD_LIBRARY_SEARCH_SYSTEM32, + )? + }; + let result = (|| { + let pointer = unsafe { GetProcAddress(module, s!("InstallLayoutOrTipUserReg")) } + .ok_or_else(|| { + Error::new( + E_FAIL, + "input.dll does not export InstallLayoutOrTipUserReg", + ) + })?; + let install: Install = unsafe { std::mem::transmute(pointer) }; + let profile = format!( + "0x0402:{{{}}}{{{}}}", + CLSID_SMARTKEY_STR, + crate::config::GUID_PROFILE_STR + ); + let profile_w: Vec = profile.encode_utf16().chain(Some(0)).collect(); + let ok = unsafe { + install( + PCWSTR::null(), + PCWSTR::null(), + PCWSTR::null(), + PCWSTR(profile_w.as_ptr()), + flags, + ) + }; + if ok.as_bool() { + Ok(()) + } else { + // Documented BOOL failure has no guaranteed last-error contract. + Err(Error::new(E_FAIL, "InstallLayoutOrTipUserReg returned FALSE; current-user availability was not applied")) + } + })(); + unsafe { + FreeLibrary(module)?; } + result } -fn register_com_server(dll_path: &str) -> Result<()> { - let subkey = format!( - "SOFTWARE\\Classes\\CLSID\\{{{}}}\\InProcServer32", - CLSID_SMARTKEY_STR - ); - let subkey_w: Vec = subkey.encode_utf16().chain(std::iter::once(0)).collect(); +/// Verify exact registration metadata before querying current-user enablement. +/// API failures remain failures; a missing profile is never treated as disabled. +pub fn profile_enabled() -> Result { + profile_present()?; + let profiles = + input_processor_profiles("Enabled-state CoCreateInstance(ITfInputProcessorProfiles)")?; + unsafe { profiles.IsEnabledLanguageProfile(&CLSID_SMARTKEY, LANGID_BG, &GUID_PROFILE) } + .map(|enabled| enabled.as_bool()) + .map_err(|e| step_error("ITfInputProcessorProfiles::IsEnabledLanguageProfile", e)) +} - let mut hkey = HKEY::default(); - check_win32(unsafe { - RegCreateKeyW(HKEY_LOCAL_MACHINE, PCWSTR(subkey_w.as_ptr()), &mut hkey) +/// Machine verification reads registered metadata without requiring enablement. +/// The caller's fresh process must see this exact CLSID/language/profile tuple. +pub fn profile_present() -> Result<()> { + let profiles = input_processor_profiles( + "Registration metadata CoCreateInstance(ITfInputProcessorProfiles)", + )?; + let description = unsafe { + profiles.GetLanguageProfileDescription(&CLSID_SMARTKEY, LANGID_BG, &GUID_PROFILE) + } + .map_err(|e| { + step_error( + "ITfInputProcessorProfiles::GetLanguageProfileDescription", + e, + ) })?; + if description != DISPLAY_NAME { + return Err(Error::new( + windows::Win32::Foundation::E_FAIL, + "Registered SmartKey profile description does not match the expected metadata", + )); + } + Ok(()) +} - set_reg_sz(hkey, None, dll_path)?; - set_reg_sz(hkey, Some("ThreadingModel"), "Apartment")?; +fn input_processor_profiles(operation: &str) -> Result { + unsafe { CoCreateInstance(&CLSID_TF_InputProcessorProfiles, None, CLSCTX_INPROC_SERVER) } + .map_err(|e| step_error(operation, e)) +} - let _ = unsafe { RegCloseKey(hkey) }; - Ok(()) +/// Explicit machine removal owns the entire SmartKey text service. This is not +/// called by ordinary user removal, and does not edit CTF registry keys directly. +fn unregister_text_service() -> Result<()> { + let profiles = input_processor_profiles( + "Machine service removal CoCreateInstance(ITfInputProcessorProfiles)", + )?; + unsafe { profiles.Unregister(&CLSID_SMARTKEY) } + .map_err(|e| step_error("ITfInputProcessorProfiles::Unregister", e)) } +// -- COM server registration (registry) -------------------------------- + fn register_com_server_hkcu(dll_path: &str) -> Result<()> { + register_com_server(HKEY_CURRENT_USER, dll_path) +} + +fn register_com_server(root: HKEY, dll_path: &str) -> Result<()> { let subkey = format!( "SOFTWARE\\Classes\\CLSID\\{{{}}}\\InProcServer32", CLSID_SMARTKEY_STR @@ -122,51 +222,54 @@ fn register_com_server_hkcu(dll_path: &str) -> Result<()> { let subkey_w: Vec = subkey.encode_utf16().chain(std::iter::once(0)).collect(); let mut hkey = HKEY::default(); - check_win32(unsafe { RegCreateKeyW(HKEY_CURRENT_USER, PCWSTR(subkey_w.as_ptr()), &mut hkey) })?; + check_win32(unsafe { RegCreateKeyW(root, PCWSTR(subkey_w.as_ptr()), &mut hkey) })?; - set_reg_sz(hkey, None, dll_path)?; - set_reg_sz(hkey, Some("ThreadingModel"), "Apartment")?; - - let _ = unsafe { RegCloseKey(hkey) }; - Ok(()) + let result = set_reg_sz(hkey, None, dll_path) + .and_then(|_| set_reg_sz(hkey, Some("ThreadingModel"), "Apartment")); + let closed = check_win32(unsafe { RegCloseKey(hkey) }); + result.and(closed) } -fn unregister_com_server_hklm() -> Result<()> { - let subkey = format!("SOFTWARE\\Classes\\CLSID\\{{{}}}", CLSID_SMARTKEY_STR); - let subkey_w: Vec = subkey.encode_utf16().chain(std::iter::once(0)).collect(); - let _ = unsafe { RegDeleteTreeW(HKEY_LOCAL_MACHINE, PCWSTR(subkey_w.as_ptr())) }; - Ok(()) +fn unregister_com_server_hkcu() -> Result<()> { + unregister_com_server(HKEY_CURRENT_USER) } -fn unregister_com_server_hkcu() -> Result<()> { +fn unregister_com_server(root: HKEY) -> Result<()> { let subkey = format!("SOFTWARE\\Classes\\CLSID\\{{{}}}", CLSID_SMARTKEY_STR); let subkey_w: Vec = subkey.encode_utf16().chain(std::iter::once(0)).collect(); - let _ = unsafe { RegDeleteTreeW(HKEY_CURRENT_USER, PCWSTR(subkey_w.as_ptr())) }; - Ok(()) + let result = unsafe { RegDeleteTreeW(root, PCWSTR(subkey_w.as_ptr())) }; + if result == windows::Win32::Foundation::ERROR_FILE_NOT_FOUND { + Ok(()) + } else { + check_win32(result) + } } // -- TSF TIP profile registration -------------------------------------- -fn register_tip_profile(dll_path: &str, flags: u32) -> Result<()> { +fn register_tip_profile(dll_path: &str, flags: u32, enabled_by_default: bool) -> Result<()> { let profile_mgr: ITfInputProcessorProfileMgr = - unsafe { CoCreateInstance(&CLSID_TF_InputProcessorProfiles, None, CLSCTX_INPROC_SERVER)? }; + unsafe { CoCreateInstance(&CLSID_TF_InputProcessorProfiles, None, CLSCTX_INPROC_SERVER) } + .map_err(|e| step_error("CoCreateInstance(ITfInputProcessorProfileMgr)", e))?; let name_w: Vec = DISPLAY_NAME.encode_utf16().collect(); let icon_w: Vec = dll_path.encode_utf16().collect(); unsafe { - profile_mgr.RegisterProfile( - &CLSID_SMARTKEY, - LANGID_BG, - &GUID_PROFILE, - &name_w, - &icon_w, - 0, // icon index - HKL::default(), // no substitute layout - 0, // no preferred layout - true, // enable by default - flags, - )?; + profile_mgr + .RegisterProfile( + &CLSID_SMARTKEY, + LANGID_BG, + &GUID_PROFILE, + &name_w, + &icon_w, + 0, // icon index + HKL::default(), // no substitute layout + 0, // no preferred layout + enabled_by_default, + flags, + ) + .map_err(|e| step_error("ITfInputProcessorProfileMgr::RegisterProfile", e))?; } Ok(()) @@ -206,12 +309,15 @@ fn unregister_categories() -> Result<()> { unsafe { CoCreateInstance(&CLSID_TF_CategoryMgr, None, CLSCTX_INPROC_SERVER)? }; unsafe { - cat_mgr.UnregisterCategory(&CLSID_SMARTKEY, &GUID_TFCAT_TIP_KEYBOARD, &CLSID_SMARTKEY)?; - let _ = cat_mgr.UnregisterCategory( + let keyboard = + cat_mgr.UnregisterCategory(&CLSID_SMARTKEY, &GUID_TFCAT_TIP_KEYBOARD, &CLSID_SMARTKEY); + let display = cat_mgr.UnregisterCategory( &CLSID_SMARTKEY, &GUID_TFCAT_DISPLAYATTRIBUTEPROVIDER, &CLSID_SMARTKEY, ); + keyboard?; + display?; } Ok(()) diff --git a/crates/smartkey-win/src/text_contract.rs b/crates/smartkey-win/src/text_contract.rs new file mode 100644 index 0000000..2ec4572 --- /dev/null +++ b/crates/smartkey-win/src/text_contract.rs @@ -0,0 +1,322 @@ +//! Platform-independent parts of the core-to-TSF text contract. + +use smartkey_core::input::{Action, Key, KeyEvent, Modifiers}; +use smartkey_core::MasterLoop; + +pub fn handle_key(core: &mut MasterLoop, event: KeyEvent) -> Vec { + if bypasses_core(&event.key, event.modifiers) { + return vec![Action::ForwardKey]; + } + if core.is_enabled() && is_editing_shortcut(&event.key, event.modifiers) { + // Deliver only the typed prefix before the application edits or moves + // it. A shortcut is not acceptance of a prediction or a learning event. + let mut actions = core.handoff_preedit_for_delivery(); + actions.extend(core.reset()); + actions.push(Action::ForwardKey); + return actions; + } + core.handle_key(event) +} + +fn bypasses_core(key: &Key, modifiers: Modifiers) -> bool { + modifiers.contains(Modifiers::RELEASE) + // Windows virtual keys, not the X11 modifier keysyms used by the core. + || matches!(key, Key::Other(0 | 0x10..=0x12 | 0x14 | 0x5b | 0x5c | 0x90 | 0x91 | 0xa0..=0xa5)) + // ToUnicodeEx can resolve AltGr as a printable character with Ctrl+Alt. + // Leave that character to the layout instead of treating it as a chord. + || (modifiers.contains(Modifiers::CTRL | Modifiers::ALT) + && matches!(key, Key::Char(_))) +} + +fn is_editing_shortcut(key: &Key, modifiers: Modifiers) -> bool { + modifiers.intersects(Modifiers::CTRL | Modifiers::ALT | Modifiers::SUPER) + && !(matches!(key, Key::Escape) && modifiers.contains(Modifiers::SUPER)) +} + +/// TSF offsets count UTF-16 units; ReplaceWord counts Unicode scalar values. +/// Validate only the requested suffix: a bounded lookback can start mid-pair. +pub fn suffix_units(text: &[u16], scalars: usize) -> Option { + let mut start = text.len(); + for _ in 0..scalars { + start = start.checked_sub(1)?; + match text[start] { + 0xDC00..=0xDFFF => { + start = start.checked_sub(1)?; + if !(0xD800..=0xDBFF).contains(&text[start]) { + return None; + } + } + 0xD800..=0xDBFF => return None, + _ => {} + } + } + Some(text.len() - start) +} + +pub fn consumes_key(actions: &[Action]) -> bool { + !actions.is_empty() + && !actions + .iter() + .any(|action| matches!(action, Action::ForwardKey)) +} + +pub fn claims_key(key: &Key, mods: Modifiers, enabled: bool, pending: bool) -> bool { + if bypasses_core(key, mods) { + return false; + } + if matches!(key, Key::Escape) && mods.contains(Modifiers::SUPER) { + return true; + } + if !enabled { + return false; + } + if pending && is_editing_shortcut(key, mods) { + // Ctrl+letter often resolves to Other(VK_*) because its Unicode result + // is a control character. It still needs OnKeyDown to retire preedit. + return true; + } + match key { + Key::Tab + | Key::Right + | Key::Escape + | Key::Left + | Key::Up + | Key::Down + | Key::Home + | Key::End + | Key::PageUp + | Key::PageDown => pending, + Key::Space | Key::Return | Key::Backspace | Key::Char(_) | Key::RawCode(_) => true, + Key::Other(_) => false, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use smartkey_core::input::InputConfig; + use smartkey_core::lang_detect::LangId; + + fn prefix(raw: bool) -> MasterLoop { + let mut core = MasterLoop::new(InputConfig { + ghost_text_separation_margin: 0.0, + use_ppm: false, + use_reranker: false, + ..InputConfig::default() + }); + core.load_word_lang("здравей", 1_000_000, LangId::Bg); + let keys: Vec = if raw { + [44, 32, 19, 30].into_iter().map(Key::RawCode).collect() + } else { + "здра".chars().map(Key::Char).collect() + }; + for key in keys { + handle_key( + &mut core, + KeyEvent { + key, + modifiers: Modifiers::empty(), + }, + ); + } + assert_eq!(core.current_word(), "здра"); + assert_eq!(core.ghost_text(), "вей"); + core + } + + fn commits(actions: &[Action]) -> String { + actions + .iter() + .filter_map(|action| match action { + Action::CommitText(text) => Some(text.as_str()), + _ => None, + }) + .collect() + } + + #[test] + fn shortcut_test_callback_claims_control_character_virtual_keys_with_pending_text() { + for (key, modifiers) in [ + (Key::Other(0x43), Modifiers::CTRL), // ToUnicodeEx filters Ctrl+C's control character. + (Key::Other(0x56), Modifiers::CTRL), + (Key::Other(0x53), Modifiers::CTRL | Modifiers::SHIFT), + (Key::Other(0x44), Modifiers::SUPER), + ] { + assert!( + claims_key(&key, modifiers, true, true), + "{key:?} {modifiers:?}" + ); + assert!(!claims_key(&key, modifiers, true, false)); + assert!(!claims_key(&key, modifiers, false, true)); + } + assert!(!claims_key( + &Key::Char('€'), + Modifiers::CTRL | Modifiers::ALT, + true, + true + )); + } + + #[test] + fn editing_shortcuts_deliver_only_typed_text_then_retire_without_learning() { + for raw in [false, true] { + for (key, modifiers) in [ + (Key::Other(0x43), Modifiers::CTRL), + (Key::Other(0x56), Modifiers::CTRL), + (Key::Char('c'), Modifiers::CTRL), + (Key::Space, Modifiers::CTRL), + (Key::Tab, Modifiers::ALT), + (Key::Other(0x44), Modifiers::SUPER), + ] { + let mut core = prefix(raw); + let metrics = core.metrics().summary(); + let prior = core.light_profile().lang_prior; + let event = KeyEvent { key, modifiers }; + let actions = handle_key(&mut core, event.clone()); + assert_eq!( + commits(&actions), + if raw { "здра" } else { "" }, + "{event:?}: {actions:?}" + ); + assert!( + !consumes_key(&actions), + "the original chord belongs to the application" + ); + assert!(!actions.iter().any(|action| matches!( + action, + Action::ShowGhost(_) + | Action::ShowComposing { .. } + | Action::ReplaceWord { .. } + ))); + assert!( + core.current_word().is_empty(), + "shortcut must retire the old token" + ); + assert!(!core.has_ghost()); + assert!(!core.native_completion_owned()); + assert_eq!( + core.metrics().summary().total_commits, + metrics.total_commits + ); + assert_eq!( + core.metrics().summary().accepted_predictions, + metrics.accepted_predictions + ); + assert_eq!(core.light_profile().lang_prior, prior); + assert!( + commits(&handle_key(&mut core, event)).is_empty(), + "repeated shortcut must not duplicate text" + ); + let next = handle_key( + &mut core, + KeyEvent { + key: Key::RawCode(44), + modifiers: Modifiers::empty(), + }, + ); + assert!(commits(&next).is_empty()); + assert!(next + .iter() + .any(|action| matches!(action, Action::ShowComposing { .. }))); + } + } + } + + #[test] + fn modifier_taps_releases_and_altgr_do_not_finalize_pending_text() { + for (key, modifiers) in [ + (Key::Other(0x10), Modifiers::SHIFT), + (Key::Other(0x11), Modifiers::CTRL), + (Key::Other(0x12), Modifiers::ALT), + (Key::Other(0x5b), Modifiers::SUPER), + (Key::Other(0xa3), Modifiers::CTRL), + (Key::Other(0xa5), Modifiers::CTRL | Modifiers::ALT), + (Key::Other(0x43), Modifiers::CTRL | Modifiers::RELEASE), + (Key::Char('€'), Modifiers::CTRL | Modifiers::ALT), + ] { + let mut core = prefix(true); + assert!( + !claims_key(&key, modifiers, true, true), + "{key:?} {modifiers:?}" + ); + let actions = handle_key(&mut core, KeyEvent { key, modifiers }); + assert_eq!(actions, [Action::ForwardKey]); + assert_eq!(core.current_word(), "здра"); + assert_eq!(core.ghost_text(), "вей"); + } + } + + #[test] + fn kill_switch_discards_pending_text_and_disabled_shortcuts_stay_forwarded() { + let mut core = prefix(true); + let actions = handle_key( + &mut core, + KeyEvent { + key: Key::Escape, + modifiers: Modifiers::SUPER, + }, + ); + assert_eq!(actions, [Action::HideGhost]); + assert!(!core.is_enabled()); + assert!(core.current_word().is_empty()); + assert_eq!( + handle_key( + &mut core, + KeyEvent { + key: Key::Other(0x43), + modifiers: Modifiers::CTRL + } + ), + [Action::ForwardKey] + ); + } + + #[test] + fn replaces_scalar_suffix_without_splitting_surrogates() { + let text: Vec = "old здра😀в".encode_utf16().collect(); + assert_eq!(suffix_units(&text, 2), Some(3)); + assert_eq!(suffix_units(&text, 6), Some(7)); + assert_eq!(suffix_units(&text, 0), Some(0)); + assert_eq!(suffix_units(&text, 11), None); + } + + #[test] + fn bounded_prefix_may_be_split_but_replaced_suffix_must_be_valid() { + assert_eq!(suffix_units(&[0xDC00, 0x0061], 1), Some(1)); + assert_eq!(suffix_units(&[0xDC00, 0x0061], 2), None); + assert_eq!(suffix_units(&[0x0061, 0xD800], 1), None); + assert_eq!(suffix_units(&[0xD800, 0xDC00], 1), Some(2)); + } + + #[test] + fn post_commit_correction_does_not_swallow_delimiter() { + let actions = [ + Action::HideGhost, + Action::ForwardKey, + Action::ReplaceWord { + replace_len: 4, + text: "Word".into(), + }, + ]; + assert!(!consumes_key(&actions)); + assert!(consumes_key(&[Action::CommitText("a".into())])); + assert!(!consumes_key(&[])); + } + + #[test] + fn reversible_switch_and_navigation_reach_core_without_prediction() { + for enabled in [true, false] { + assert!(claims_key(&Key::Escape, Modifiers::SUPER, enabled, false)); + } + for key in [Key::Tab, Key::Right, Key::Left, Key::Home, Key::Escape] { + assert!(claims_key(&key, Modifiers::empty(), true, true)); + assert!(!claims_key(&key, Modifiers::empty(), true, false)); + } + assert!(!claims_key( + &Key::Char('a'), + Modifiers::empty(), + false, + true + )); + } +} diff --git a/crates/smartkey-win/src/tsf.rs b/crates/smartkey-win/src/tsf.rs index 76a766c..1bdbe0f 100644 --- a/crates/smartkey-win/src/tsf.rs +++ b/crates/smartkey-win/src/tsf.rs @@ -72,6 +72,44 @@ impl SmartKeyTextService { } } + /// Respect the application's TSF eligibility flags before inspecting keys. + /// Unset compartments are normal; unavailable or malformed state is not. + fn context_accepts_input(context: Option<&ITfContext>) -> bool { + let Some(context) = context else { + return false; + }; + let allowed = (|| -> Result { + let status = unsafe { context.GetStatus()? }; + if status.dwDynamicFlags & TF_SD_READONLY != 0 { + return Ok(false); + } + let compartments: ITfCompartmentMgr = context.cast()?; + for guid in [ + GUID_COMPARTMENT_KEYBOARD_DISABLED, + GUID_COMPARTMENT_EMPTYCONTEXT, + ] { + let value = unsafe { compartments.GetCompartment(&guid)?.GetValue()? }; + if !compartment_allows_input(&value) { + return Ok(false); + } + } + Ok(true) + })(); + allowed.unwrap_or(false) + } + + fn admit_context(&self, context: Option<&ITfContext>) -> bool { + if Self::context_accepts_input(context) { + return true; + } + // reset discards pending text; focus_lost would commit and learn it. + // Do not dispatch an edit through a missing/disabled/new context. + let _ = self.core.borrow_mut().reset(); + let stale_composition = self.composition.borrow_mut().take(); + drop(stale_composition); + false + } + /// Translate a Windows virtual key code to our platform-neutral Key. /// /// Uses `ToUnicodeEx` for layout-aware character resolution — supports @@ -82,6 +120,13 @@ impl SmartKeyTextService { VK_TAB => return Key::Tab, VK_ESCAPE => return Key::Escape, VK_RIGHT => return Key::Right, + VK_LEFT => return Key::Left, + VK_UP => return Key::Up, + VK_DOWN => return Key::Down, + VK_HOME => return Key::Home, + VK_END => return Key::End, + VK_PRIOR => return Key::PageUp, + VK_NEXT => return Key::PageDown, VK_BACK => return Key::Backspace, VK_SPACE => return Key::Space, VK_RETURN => return Key::Return, @@ -133,103 +178,68 @@ impl SmartKeyTextService { /// Execute actions returned by InputMethodCore. fn execute_actions(&self, actions: &[Action], context: &ITfContext) -> bool { - let mut consumed = false; + let consumed = crate::text_contract::consumes_key(actions); let cid = self.client_id.get(); - for action in actions { - match action { - Action::ShowGhost(text) => { + let op = match action { + Action::ForwardKey => continue, + Action::ShowGhost(text) | Action::ShowComposing { typed: text, .. } => { let sink: Result = unsafe { self.cast() }; - match sink { - Ok(comp_sink) => { - let op = EditOp::ShowGhost { - text: text.clone(), - composition: self.composition.clone(), - comp_sink, - ghost_attr_atom: self.ghost_attr_atom.get(), - }; - if let Err(e) = edit_session::request_edit_session(context, cid, op) { - log::error!("smartkey: ShowGhost failed: {e}"); - } + let comp_sink = match sink { + Ok(sink) => sink, + Err(error) => { + log::error!("smartkey: composition sink failed: {error}"); + let _ = self.core.borrow_mut().reset(); + return true; } - Err(e) => log::error!("smartkey: failed to get composition sink: {e}"), - } - consumed = true; - } - Action::HideGhost => { - let op = EditOp::HideGhost { - composition: self.composition.clone(), }; - if let Err(e) = edit_session::request_edit_session(context, cid, op) { - log::error!("smartkey: HideGhost failed: {e}"); - } - consumed = true; - } - Action::CommitText(text) => { - let op = EditOp::CommitText { - text: text.clone(), - composition: self.composition.clone(), + let (full, typed_units) = match action { + Action::ShowComposing { typed, ghost } => { + (format!("{typed}{ghost}"), typed.encode_utf16().count()) + } + _ => (text.clone(), 0), }; - if let Err(e) = edit_session::request_edit_session(context, cid, op) { - log::error!("smartkey: CommitText failed: {e}"); - } - consumed = true; - } - Action::ForwardKey => { - // Key must reach the application — override any prior consumption. - consumed = false; - } - Action::ReplaceWord { - replace_len: _, - text, - } => { - // LIMITATION: Proper ITfRange-based replacement not yet implemented. - // This falls back to CommitText which replaces the entire composition - // rather than just the last `replace_len` characters. As a result, - // transliteration on Windows may produce incorrect behavior when - // partially through a word. Full implementation requires: - // 1. Get composition range via ITfComposition::GetRange - // 2. Create a sub-range covering the last `replace_len` chars - // 3. Set text on that sub-range via ITfRange::SetText - let op = EditOp::CommitText { - text: text.clone(), + EditOp::ShowGhost { + text: full, + typed_units, composition: self.composition.clone(), - }; - if let Err(e) = edit_session::request_edit_session(context, cid, op) { - log::error!("smartkey: ReplaceWord failed: {e}"); - } - consumed = true; - } - Action::ShowComposing { - ref typed, - ref ghost, - } => { - // Fallback: treat as regular ghost with full text. - // TODO: implement styled composing for Windows TSF. - let full = format!("{}{}", typed, ghost); - let sink: Result = unsafe { self.cast() }; - match sink { - Ok(comp_sink) => { - let op = EditOp::ShowGhost { - text: full, - composition: self.composition.clone(), - comp_sink, - ghost_attr_atom: self.ghost_attr_atom.get(), - }; - if let Err(e) = edit_session::request_edit_session(context, cid, op) { - log::error!("smartkey: ShowComposing failed: {e}"); - } - } - Err(e) => log::error!("smartkey: failed to get composition sink: {e}"), + comp_sink, + ghost_attr_atom: self.ghost_attr_atom.get(), } - consumed = true; } + Action::HideGhost => EditOp::HideGhost { + composition: self.composition.clone(), + }, + Action::CommitText(text) => EditOp::CommitText { + text: text.clone(), + composition: self.composition.clone(), + }, + Action::ReplaceWord { replace_len, text } => EditOp::ReplaceWord { + replace_len: *replace_len, + text: text.clone(), + composition: self.composition.clone(), + }, + }; + if let Err(error) = edit_session::request_edit_session(context, cid, op) { + log::error!("smartkey: text edit failed; stopping dependent actions: {error}"); + let _ = self.core.borrow_mut().reset(); + // Some edits may already have succeeded. Replaying the raw key can + // duplicate committed text, so do not forward a partially applied batch. + return true; } } consumed } } +fn compartment_allows_input(value: &VARIANT) -> bool { + // The TSF compartments are VT_I4 flags. Do not coerce strings or booleans. + const VT_I4: u16 = 3; + value.is_empty() + || (unsafe { value.as_raw().Anonymous.Anonymous.vt } == VT_I4 + && i32::try_from(value).is_ok_and(|flag| flag == 0)) +} + // -- ITfTextInputProcessor implementation (base trait: Activate + Deactivate) -- impl ITfTextInputProcessor_Impl for SmartKeyTextService_Impl { @@ -331,37 +341,26 @@ impl ITfKeyEventSink_Impl for SmartKeyTextService_Impl { fn OnTestKeyDown( &self, - _pic: Option<&ITfContext>, + pic: Option<&ITfContext>, wparam: WPARAM, lparam: LPARAM, ) -> Result { + if !self.admit_context(pic) { + return Ok(BOOL::from(false)); + } let scan_code = ((lparam.0 >> 16) & 0xFF) as u32; let key = SmartKeyTextService::vk_to_key(wparam.0 as u32, scan_code); let core = self.core.borrow(); - if !core.is_enabled() { - // Only claim Super+Escape (kill switch to re-enable). - if matches!(key, Key::Escape) - && SmartKeyTextService::get_modifiers().contains(Modifiers::SUPER) - { - return Ok(BOOL::from(true)); - } - return Ok(BOOL::from(false)); - } - - let has_ghost = core.has_ghost(); - let should_claim = match &key { - Key::Tab | Key::Right | Key::Escape => has_ghost, - Key::Left - | Key::Up - | Key::Down - | Key::Home - | Key::End - | Key::PageUp - | Key::PageDown => false, - Key::Space | Key::Return | Key::Backspace | Key::Char(_) | Key::RawCode(_) => true, - Key::Other(_) => false, - }; + let pending = core.has_ghost() + || !core.current_word().is_empty() + || self.composition.borrow().is_some(); + let should_claim = crate::text_contract::claims_key( + &key, + SmartKeyTextService::get_modifiers(), + core.is_enabled(), + pending, + ); Ok(BOOL::from(should_claim)) } @@ -375,6 +374,9 @@ impl ITfKeyEventSink_Impl for SmartKeyTextService_Impl { } fn OnKeyDown(&self, pic: Option<&ITfContext>, wparam: WPARAM, lparam: LPARAM) -> Result { + if !self.admit_context(pic) { + return Ok(BOOL::from(false)); + } let vk = wparam.0 as u32; let scan_code = ((lparam.0 >> 16) & 0xFF) as u32; let key = SmartKeyTextService::vk_to_key(vk, scan_code); @@ -384,7 +386,7 @@ impl ITfKeyEventSink_Impl for SmartKeyTextService_Impl { modifiers: mods, }; - let actions = self.core.borrow_mut().handle_key(event); + let actions = crate::text_contract::handle_key(&mut self.core.borrow_mut(), event); let consumed = if let Some(ctx) = pic { self.execute_actions(&actions, ctx) @@ -425,11 +427,50 @@ impl ITfCompositionSink_Impl for SmartKeyTextService_Impl { fn OnCompositionTerminated( &self, _ecwrite: u32, - _pcomposition: Option<&ITfComposition>, + pcomposition: Option<&ITfComposition>, ) -> Result<()> { - // External termination (e.g. application or another TIP ended our composition). - // Clean up our state to stay in sync. - *self.composition.borrow_mut() = None; + let matches_active = { + let active = self.composition.borrow(); + active + .as_ref() + .is_some_and(|current| Some(current) == pcomposition) + }; + if matches_active { + self.composition.borrow_mut().take(); + // An external termination finalized the range; discard stale predictions. + // Own Hide/Commit removes the slot before its termination callback. + let _ = self.core.borrow_mut().reset(); + } Ok(()) } } + +#[cfg(test)] +mod context_tests { + use super::*; + + #[test] + fn unset_and_zero_compartments_allow_input_but_other_values_do_not() { + assert!(compartment_allows_input(&VARIANT::new())); + assert!(compartment_allows_input(&VARIANT::from(0i32))); + assert!(!compartment_allows_input(&VARIANT::from(1i32))); + assert!(!compartment_allows_input(&VARIANT::from(-1i32))); + assert!(!compartment_allows_input(&VARIANT::from(false))); + assert!(!compartment_allows_input(&VARIANT::from("0"))); + } + + #[test] + fn missing_context_neither_claims_nor_feeds_a_key_and_discards_pending_text() { + let service = windows_core::ComObject::new(SmartKeyTextService::new()); + let sink: ITfKeyEventSink = service.to_interface(); + let _ = service.core.borrow_mut().handle_key(KeyEvent { + key: Key::Char('q'), + modifiers: Modifiers::empty(), + }); + assert_eq!(service.core.borrow().current_word(), "q"); + assert!(!unsafe { sink.OnTestKeyDown(None, WPARAM(0x41), LPARAM(0)).unwrap() }.as_bool()); + assert!(service.core.borrow().current_word().is_empty()); + assert!(!unsafe { sink.OnKeyDown(None, WPARAM(0x41), LPARAM(0)).unwrap() }.as_bool()); + assert!(service.core.borrow().current_word().is_empty()); + } +} diff --git a/crates/smartkey-win/tests/windows_pilot_manual.md b/crates/smartkey-win/tests/windows_pilot_manual.md index 05dca73..fdefc0e 100644 --- a/crates/smartkey-win/tests/windows_pilot_manual.md +++ b/crates/smartkey-win/tests/windows_pilot_manual.md @@ -1,5 +1,12 @@ # SmartKey Windows experimental pilot evidence form +> Historical form for the superseded `smartkey-windows-pilot` package. It does not +> describe the current `smartkey-windows-standalone` candidate. For that package, +> use [README-WINDOWS.md](../packaging/README-WINDOWS.md): explicit administrator +> machine setup, then normal-user controls. Native maintenance CI does not replace +> the interactive typing, Win+Space and real-logon checks. The old staging and +> unavailable-registration instructions below are retained only as historical evidence. + This form is for a future disposable, standard-user Windows pilot. Packaging is not registration, native acceptance, or daily-readiness evidence. Do not use a daily account, elevation, employer data, private corpora, or real keystrokes. ## Artifact identity and completeness diff --git a/crates/smartkey-win/windows-runtime-manifest.json b/crates/smartkey-win/windows-runtime-manifest.json new file mode 100644 index 0000000..9f2dc28 --- /dev/null +++ b/crates/smartkey-win/windows-runtime-manifest.json @@ -0,0 +1,134 @@ +{ + "schema_version": 1, + "package_name": "smartkey-windows-standalone", + "status": "candidate_native_acceptance_pending", + "native_artifact_layout": "Extract complete19-file ZIP. Explicit administrator Install-Machine-SmartKey.cmd installs protected ProgramFiles knownfolder\\SmartKey once; normal Install-SmartKey.cmd enables the executing user.", + "runtime_data_destination_directory": "%APPDATA%\\smartkey", + "native_files": [ + { + "name": "smartkey-register.exe", + "repository_source": "target/release/smartkey-register.exe", + "purpose": "Visible explicit machine install/remove; normal-user enable/data/login/maintenance; separate persistent profile verification." + }, + { + "name": "smartkey_win.dll", + "repository_source": "target/release/smartkey_win.dll", + "purpose": "Windows TSF COM server." + } + ], + "runtime_data_files": [ + { + "name": "smartkey.json", + "repository_source": "config/smartkey.json", + "destination": "%APPDATA%\\smartkey\\smartkey.json", + "optional": true, + "provenance": "Tracked, reviewed non-personal starter configuration; GPL-3.0 under repository LICENSE." + }, + { + "name": "corpus_en.json", + "repository_source": "corpus/corpus_en.json", + "destination": "%APPDATA%\\smartkey\\corpus_en.json", + "optional": false, + "provenance": "Tracked public repository corpus; GPL-3.0 under repository LICENSE." + }, + { + "name": "corpus_bg.json", + "repository_source": "corpus/corpus_bg.json", + "destination": "%APPDATA%\\smartkey\\corpus_bg.json", + "optional": false, + "provenance": "Tracked public repository corpus; GPL-3.0 under repository LICENSE." + }, + { + "name": "corpus_tech.json", + "repository_source": "corpus/corpus_tech.json", + "destination": "%APPDATA%\\smartkey\\corpus_tech.json", + "optional": false, + "provenance": "Tracked public repository corpus; GPL-3.0 under repository LICENSE." + } + ], + "artifact_ancillary_files": [ + { + "name": "LICENSE", + "repository_source": "LICENSE", + "purpose": "Repository dual-license notice." + }, + { + "name": "LICENSE-GPL", + "repository_source": "LICENSE-GPL", + "purpose": "GPL-3.0 license text for application and corpus payload." + }, + { + "name": "LICENSE-APACHE", + "repository_source": "LICENSE-APACHE", + "purpose": "Apache-2.0 license text for smartkey-core." + }, + { + "name": "artifact-source-manifest.json", + "repository_source": null, + "purpose": "CI-generated source SHA, source URL, and per-file SHA-256 receipt for every other archive file." + }, + { + "name": "Install-SmartKey.cmd", + "repository_source": "crates/smartkey-win/packaging/Install-SmartKey.cmd", + "purpose": "Current-user standalone setup and maintenance" + }, + { + "name": "Status-SmartKey.cmd", + "repository_source": "crates/smartkey-win/packaging/Status-SmartKey.cmd", + "purpose": "Current-user standalone setup and maintenance" + }, + { + "name": "Enable-SmartKey.cmd", + "repository_source": "crates/smartkey-win/packaging/Enable-SmartKey.cmd", + "purpose": "Current-user standalone setup and maintenance" + }, + { + "name": "Disable-SmartKey.cmd", + "repository_source": "crates/smartkey-win/packaging/Disable-SmartKey.cmd", + "purpose": "Current-user standalone setup and maintenance" + }, + { + "name": "Uninstall-SmartKey.cmd", + "repository_source": "crates/smartkey-win/packaging/Uninstall-SmartKey.cmd", + "purpose": "Current-user standalone setup and maintenance" + }, + { + "name": "README-WINDOWS.md", + "repository_source": "crates/smartkey-win/packaging/README-WINDOWS.md", + "purpose": "Current-user standalone setup and maintenance" + }, + { + "name": "Install-Machine-SmartKey.cmd", + "repository_source": "crates/smartkey-win/packaging/Install-Machine-SmartKey.cmd", + "purpose": "Explicit one-time administrator machine catalog/protectedbundle installation; no user enablement" + }, + { + "name": "Uninstall-Machine-SmartKey.cmd", + "repository_source": "crates/smartkey-win/packaging/Uninstall-Machine-SmartKey.cmd", + "purpose": "Explicit administrator exact shared machine removal, run from original archive" + } + ], + "excluded_files": [ + { + "name": "personal.json", + "reason": "Optional user-specific profile; never packaged." + }, + { + "pattern": "corpus_*.bin", + "reason": "Runtime-generated caches are not source payload." + } + ], + "runtime_contract": { + "network_required": false, + "autostart_created": "One owned HKCU Run value after successful setup; removed by Disable/Uninstall", + "automatic_registration": "Only explicit --install-machine with actual elevated token. No automatic elevation/fallback.", + "automatic_appdata_mutation": "Setup copies only missing public starter data; preserves personal files", + "missing_public_corpus_is_package_failure": true, + "machine_user_split": "Machine profile enabledByDefaultfalse. Normal originaluser --install applies only missingdata/userenable/login/menu after machine prerequisite." + }, + "uninstall_boundary": "Normal user removal only useravailability/Run/menu; preserves globalcatalog/sharedfiles/personaldata. Explicit elevated machine removal removes exact globalcatalog/COM+allowlistedprotectedfiles from originalarchive; never edits otherusers profiles. Errors/lockedfiles are reported.", + "dependency_evidence": { + "build_assumption": "x64 MSVC static CRT; CI inspects both PE import lists", + "runtime_dll_completeness": "Requires successful CI dependency check; Windows 10/11 system DLLs supplied by OS" + } +}