Add native self-hosted instance connection to fluxer_desktop
Trimmed monorepo checkout (fluxer_desktop + packages/voice_engine_v2 + tools/ci) with a "Connect to a Different Server" menu item and popout that lets the desktop app switch to any self-hosted Fluxer instance, plus fixes for well-known discovery on single-domain self-hosted deployments and a false-positive ERR_ABORTED on same-origin client redirects during the switch. Defaults to chat.fluxr.chat and uses an isolated userData directory from the official build.
This commit is contained in:
+466
@@ -0,0 +1,466 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8"
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cdd35008169921d80bc60d3d0ab416eecb028c4cd653352907921d95084790be"
|
||||
dependencies = [
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
|
||||
|
||||
[[package]]
|
||||
name = "const-oid"
|
||||
version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
|
||||
|
||||
[[package]]
|
||||
name = "convert_case"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "affbf0190ed2caf063e3def54ff444b449371d55c58e513a95ab98eca50adb49"
|
||||
dependencies = [
|
||||
"unicode-segmentation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
|
||||
dependencies = [
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ctor"
|
||||
version = "1.0.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "01334b89b69ff726750c5ce5073fc8bd860e99aa9a8fc5ca11b04730e3aee97a"
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.11.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"const-oid",
|
||||
"crypto-common",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fluxer_desktop_native"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"sha2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fluxer_windows_input_hook"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"fluxer_desktop_native",
|
||||
"napi",
|
||||
"napi-build",
|
||||
"napi-derive",
|
||||
"windows",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "futures"
|
||||
version = "0.3.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d"
|
||||
dependencies = [
|
||||
"futures-channel",
|
||||
"futures-core",
|
||||
"futures-executor",
|
||||
"futures-io",
|
||||
"futures-sink",
|
||||
"futures-task",
|
||||
"futures-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "futures-channel"
|
||||
version = "0.3.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"futures-sink",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "futures-core"
|
||||
version = "0.3.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"
|
||||
|
||||
[[package]]
|
||||
name = "futures-executor"
|
||||
version = "0.3.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d"
|
||||
dependencies = [
|
||||
"futures-core",
|
||||
"futures-task",
|
||||
"futures-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "futures-io"
|
||||
version = "0.3.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718"
|
||||
|
||||
[[package]]
|
||||
name = "futures-macro"
|
||||
version = "0.3.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "futures-sink"
|
||||
version = "0.3.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893"
|
||||
|
||||
[[package]]
|
||||
name = "futures-task"
|
||||
version = "0.3.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"
|
||||
|
||||
[[package]]
|
||||
name = "futures-util"
|
||||
version = "0.3.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"
|
||||
dependencies = [
|
||||
"futures-channel",
|
||||
"futures-core",
|
||||
"futures-io",
|
||||
"futures-macro",
|
||||
"futures-sink",
|
||||
"futures-task",
|
||||
"memchr",
|
||||
"pin-project-lite",
|
||||
"slab",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hybrid-array"
|
||||
version = "0.4.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9155a582abd142abc056962c29e3ce5ff2ad5469f4246b537ed42c5deba857da"
|
||||
dependencies = [
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.186"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
|
||||
|
||||
[[package]]
|
||||
name = "libloading"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "754ca22de805bb5744484a5b151a9e1a8e837d5dc232c2d7d8c2e3492edc8b60"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6b947ae49db0d222b1dbc6b113ce7248a3fc3a6ca21b696717bfc000ba4484d8"
|
||||
|
||||
[[package]]
|
||||
name = "napi"
|
||||
version = "3.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ad513ff22558f1830b595ea6eb4091da48145d09a222ce157e781896f78be0b9"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"ctor",
|
||||
"futures",
|
||||
"napi-build",
|
||||
"napi-sys",
|
||||
"nohash-hasher",
|
||||
"rustc-hash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "napi-build"
|
||||
version = "2.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c9c366d2c8c60b86fa632df75f745509b52f9128f91a6bad4c796e44abb505e1"
|
||||
|
||||
[[package]]
|
||||
name = "napi-derive"
|
||||
version = "3.5.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "89b3f766e04667e6da0e181e2da4f85475d5a6513b7cf6a80bea184e224a5b42"
|
||||
dependencies = [
|
||||
"convert_case",
|
||||
"ctor",
|
||||
"napi-derive-backend",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "napi-derive-backend"
|
||||
version = "5.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0d5af30503edf933ce7377cf6d4c877a62b0f1107ea05585f1b5e430e88d5baf"
|
||||
dependencies = [
|
||||
"convert_case",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"semver",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "napi-sys"
|
||||
version = "3.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1f5bcdf71abd3a50d00b49c1c2c75251cb3c913777d6139cd37dabc093a5e400"
|
||||
dependencies = [
|
||||
"libloading",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nohash-hasher"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451"
|
||||
|
||||
[[package]]
|
||||
name = "pin-project-lite"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.106"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.45"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustc-hash"
|
||||
version = "2.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe"
|
||||
|
||||
[[package]]
|
||||
name = "semver"
|
||||
version = "1.0.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
|
||||
|
||||
[[package]]
|
||||
name = "sha2"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "slab"
|
||||
version = "0.4.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.117"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "typenum"
|
||||
version = "1.20.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "40ce102ab67701b8526c123c1bab5cbe42d7040ccfd0f64af1a385808d2f43de"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-segmentation"
|
||||
version = "1.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9629274872b2bfaf8d66f5f15725007f635594914870f65218920345aa11aa8c"
|
||||
|
||||
[[package]]
|
||||
name = "windows"
|
||||
version = "0.62.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
|
||||
dependencies = [
|
||||
"windows-collections",
|
||||
"windows-core",
|
||||
"windows-future",
|
||||
"windows-numerics",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-collections"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
|
||||
dependencies = [
|
||||
"windows-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-core"
|
||||
version = "0.62.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
|
||||
dependencies = [
|
||||
"windows-implement",
|
||||
"windows-interface",
|
||||
"windows-link",
|
||||
"windows-result",
|
||||
"windows-strings",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-future"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
|
||||
dependencies = [
|
||||
"windows-core",
|
||||
"windows-link",
|
||||
"windows-threading",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-implement"
|
||||
version = "0.60.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-interface"
|
||||
version = "0.59.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||
|
||||
[[package]]
|
||||
name = "windows-numerics"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"
|
||||
dependencies = [
|
||||
"windows-core",
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-result"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-strings"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-threading"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
@@ -0,0 +1,30 @@
|
||||
[package]
|
||||
name = "fluxer_windows_input_hook"
|
||||
version = "0.0.0"
|
||||
edition = "2024"
|
||||
license = "AGPL-3.0-or-later"
|
||||
publish = false
|
||||
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
fluxer_desktop_native = {path = "../rust"}
|
||||
napi = {version = "3.9.1", default-features = false, features = ["dyn-symbols", "napi8"]}
|
||||
napi-derive = "3.5.6"
|
||||
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
windows = {version = "0.62.2", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_System_LibraryLoader",
|
||||
"Win32_System_SystemInformation",
|
||||
"Win32_System_Threading",
|
||||
"Win32_UI_Input_KeyboardAndMouse",
|
||||
"Win32_UI_WindowsAndMessaging",
|
||||
]}
|
||||
|
||||
[build-dependencies]
|
||||
napi-build = "2.3.2"
|
||||
@@ -0,0 +1,5 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
fn main() {
|
||||
napi_build::setup();
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
export type InputEvent =
|
||||
| {
|
||||
type: 'keydown' | 'keyup';
|
||||
keycode: number;
|
||||
keyName: string;
|
||||
ctrlKey: boolean;
|
||||
altKey: boolean;
|
||||
shiftKey: boolean;
|
||||
metaKey: boolean;
|
||||
}
|
||||
| {
|
||||
type: 'mousedown' | 'mouseup';
|
||||
button: number;
|
||||
ctrlKey: boolean;
|
||||
altKey: boolean;
|
||||
shiftKey: boolean;
|
||||
metaKey: boolean;
|
||||
x?: number;
|
||||
y?: number;
|
||||
}
|
||||
| {
|
||||
type: 'mousemove';
|
||||
x: number;
|
||||
y: number;
|
||||
ctrlKey: boolean;
|
||||
altKey: boolean;
|
||||
shiftKey: boolean;
|
||||
metaKey: boolean;
|
||||
}
|
||||
| {
|
||||
type: 'wheel';
|
||||
x?: number;
|
||||
y?: number;
|
||||
deltaX: number;
|
||||
deltaY: number;
|
||||
ctrlKey: boolean;
|
||||
altKey: boolean;
|
||||
shiftKey: boolean;
|
||||
metaKey: boolean;
|
||||
};
|
||||
|
||||
export declare class InputHook {
|
||||
constructor(callback: (event: InputEvent) => void);
|
||||
|
||||
start(): void;
|
||||
|
||||
stop(): void;
|
||||
|
||||
readonly droppedEvents: number;
|
||||
readonly reinstallCount: number;
|
||||
}
|
||||
|
||||
export declare function isAvailable(): boolean;
|
||||
|
||||
export declare const loadError: Error | null;
|
||||
@@ -0,0 +1,62 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
const {existsSync} = require('node:fs');
|
||||
const {join, sep} = require('node:path');
|
||||
const {createNativeLoadError, loadNativeBinding} = require('./loader-diagnostics.cjs');
|
||||
const MODULE_NAME = '@fluxer/windows-input-hook';
|
||||
|
||||
function resolveNativeRoot() {
|
||||
const asarSegment = `${sep}app.asar${sep}`;
|
||||
if (!__dirname.includes(asarSegment)) return __dirname;
|
||||
const unpackedDir = __dirname.replace(asarSegment, `${sep}app.asar.unpacked${sep}`);
|
||||
return existsSync(unpackedDir) ? unpackedDir : __dirname;
|
||||
}
|
||||
|
||||
function nativeFileName() {
|
||||
if (process.platform !== 'win32') {
|
||||
throw new Error(`@fluxer/windows-input-hook is only supported on Windows, got ${process.platform}`);
|
||||
}
|
||||
switch (process.arch) {
|
||||
case 'x64':
|
||||
return 'windows-input-hook.win32-x64-msvc.node';
|
||||
case 'arm64':
|
||||
return 'windows-input-hook.win32-arm64-msvc.node';
|
||||
default:
|
||||
throw new Error(`Unsupported Windows architecture: ${process.arch}`);
|
||||
}
|
||||
}
|
||||
|
||||
let binding = null;
|
||||
let loadError = null;
|
||||
|
||||
if (process.platform === 'win32') {
|
||||
try {
|
||||
const nativeRoot = resolveNativeRoot();
|
||||
const nativePath = join(nativeRoot, nativeFileName());
|
||||
const loaded = loadNativeBinding({
|
||||
moduleName: MODULE_NAME,
|
||||
nativePath,
|
||||
nativeRoot,
|
||||
packageDir: __dirname,
|
||||
probe: false,
|
||||
});
|
||||
binding = loaded.binding;
|
||||
loadError = loaded.loadError;
|
||||
if (loadError) throw loadError;
|
||||
} catch (error) {
|
||||
loadError = createNativeLoadError({
|
||||
moduleName: MODULE_NAME,
|
||||
nativeRoot: resolveNativeRoot(),
|
||||
packageDir: __dirname,
|
||||
reason: 'native loader threw before binding load completed',
|
||||
cause: error,
|
||||
});
|
||||
throw loadError;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
InputHook: binding ? binding.InputHook : null,
|
||||
isAvailable: binding ? binding.isAvailable : () => false,
|
||||
loadError,
|
||||
};
|
||||
@@ -0,0 +1,524 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
const {existsSync, readdirSync, readFileSync, statSync} = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const {basename} = require('node:path');
|
||||
const {spawnSync} = require('node:child_process');
|
||||
const NATIVE_LOAD_ERROR_MARKER = Symbol.for('fluxer.nativeLoadError');
|
||||
const MAX_TEXT_LENGTH = 6000;
|
||||
const MAX_DIRECTORY_ENTRIES = 80;
|
||||
|
||||
function trimText(value, limit = MAX_TEXT_LENGTH) {
|
||||
const text = Buffer.isBuffer(value) ? value.toString('utf8') : String(value ?? '');
|
||||
const trimmed = text.trim();
|
||||
if (!trimmed) return null;
|
||||
return trimmed.length > limit ? `${trimmed.slice(0, limit)}\n...<truncated>` : trimmed;
|
||||
}
|
||||
|
||||
function errorDiagnostic(error) {
|
||||
if (!error) return null;
|
||||
if (error instanceof Error) {
|
||||
return {
|
||||
name: error.name || 'Error',
|
||||
message: error.message,
|
||||
code: error.code || null,
|
||||
stack: trimText(error.stack || error.message),
|
||||
};
|
||||
}
|
||||
return {
|
||||
name: typeof error,
|
||||
message: trimText(String(error)),
|
||||
code: null,
|
||||
stack: null,
|
||||
};
|
||||
}
|
||||
|
||||
function formatErrorDiagnostic(diagnostic) {
|
||||
if (!diagnostic) return null;
|
||||
const lines = [];
|
||||
if (diagnostic.code) lines.push(`code=${diagnostic.code}`);
|
||||
if (diagnostic.stack) lines.push(diagnostic.stack);
|
||||
else if (diagnostic.message) lines.push(diagnostic.message);
|
||||
return trimText(lines.join('\n'));
|
||||
}
|
||||
|
||||
function fileDiagnostic(filePath) {
|
||||
if (!filePath) return {path: null, exists: false, error: 'not resolved'};
|
||||
try {
|
||||
const stat = statSync(filePath);
|
||||
return {
|
||||
path: filePath,
|
||||
exists: true,
|
||||
size: stat.size,
|
||||
mode: `0${(stat.mode & 0o777).toString(8)}`,
|
||||
mtime: stat.mtime.toISOString(),
|
||||
isFile: stat.isFile(),
|
||||
isDirectory: stat.isDirectory(),
|
||||
};
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message : String(error);
|
||||
return {path: filePath, exists: false, error: reason};
|
||||
}
|
||||
}
|
||||
|
||||
function formatFileDiagnostic(diagnostic) {
|
||||
if (!diagnostic) return 'not resolved';
|
||||
if (!diagnostic.exists) return `exists=false, statError=${diagnostic.error || '<unknown>'}`;
|
||||
return [
|
||||
`exists=true`,
|
||||
`size=${diagnostic.size}`,
|
||||
`mode=${diagnostic.mode}`,
|
||||
`mtime=${diagnostic.mtime}`,
|
||||
`isFile=${diagnostic.isFile}`,
|
||||
].join(', ');
|
||||
}
|
||||
|
||||
function directoryDiagnostic(dirPath) {
|
||||
if (!dirPath) return {path: null, ok: false, error: 'not resolved', entries: [], total: 0, omitted: 0};
|
||||
try {
|
||||
const entries = readdirSync(dirPath, {withFileTypes: true}).map((entry) => ({
|
||||
name: entry.name,
|
||||
type: entry.isDirectory() ? 'directory' : entry.isFile() ? 'file' : 'other',
|
||||
}));
|
||||
entries.sort((a, b) => a.name.localeCompare(b.name));
|
||||
const visible = entries.slice(0, MAX_DIRECTORY_ENTRIES);
|
||||
return {
|
||||
path: dirPath,
|
||||
ok: true,
|
||||
entries: visible,
|
||||
total: entries.length,
|
||||
omitted: Math.max(0, entries.length - visible.length),
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
path: dirPath,
|
||||
ok: false,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
entries: [],
|
||||
total: 0,
|
||||
omitted: 0,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function formatDirectoryDiagnostic(diagnostic) {
|
||||
if (!diagnostic) return '<unavailable>';
|
||||
if (!diagnostic.ok) return `directory listing failed: ${diagnostic.error || '<unknown>'}`;
|
||||
const entries = diagnostic.entries.map((entry) => `${entry.name}${entry.type === 'directory' ? '/' : ''}`);
|
||||
const suffix = diagnostic.omitted > 0 ? [`...<${diagnostic.omitted} more entries>`] : [];
|
||||
return [...entries, ...suffix].join('\n') || '<empty>';
|
||||
}
|
||||
|
||||
function selectedEnvironmentNames(skipNativeProbeEnv) {
|
||||
const names = [
|
||||
'ELECTRON_RUN_AS_NODE',
|
||||
'FLUXER_NATIVE_MODULE_PREFLIGHT_CHILD',
|
||||
'LD_LIBRARY_PATH',
|
||||
'DYLD_LIBRARY_PATH',
|
||||
'DISPLAY',
|
||||
'WAYLAND_DISPLAY',
|
||||
'XDG_CURRENT_DESKTOP',
|
||||
'XDG_SESSION_TYPE',
|
||||
'DBUS_SESSION_BUS_ADDRESS',
|
||||
'PULSE_SERVER',
|
||||
'PIPEWIRE_REMOTE',
|
||||
'PATH',
|
||||
];
|
||||
if (skipNativeProbeEnv) names.push(skipNativeProbeEnv);
|
||||
return names;
|
||||
}
|
||||
|
||||
function environmentDiagnostics(skipNativeProbeEnv) {
|
||||
return Object.fromEntries(
|
||||
selectedEnvironmentNames(skipNativeProbeEnv).map((name) => [name, process.env[name] ?? null]),
|
||||
);
|
||||
}
|
||||
|
||||
function formatEnvironment(diagnostic) {
|
||||
return Object.entries(diagnostic)
|
||||
.map(([name, value]) => `${name}=${value ?? '<unset>'}`)
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
function runtimeDiagnostics() {
|
||||
const versions = process.versions || {};
|
||||
let reportHeader = null;
|
||||
if (process.report && typeof process.report.getReport === 'function') {
|
||||
try {
|
||||
reportHeader = process.report.getReport().header || null;
|
||||
} catch {
|
||||
reportHeader = null;
|
||||
}
|
||||
}
|
||||
const glibcRuntime = versions.glibcVersionRuntime || reportHeader?.glibcVersionRuntime || '<unknown>';
|
||||
const glibcCompiler = versions.glibcVersionCompiler || reportHeader?.glibcVersionCompiler || '<unknown>';
|
||||
return {
|
||||
node: versions.node || null,
|
||||
electron: versions.electron || null,
|
||||
modules: versions.modules || null,
|
||||
napi: versions.napi || null,
|
||||
v8: versions.v8 || null,
|
||||
uv: versions.uv || null,
|
||||
openssl: versions.openssl || null,
|
||||
glibcRuntime,
|
||||
glibcCompiler,
|
||||
platform: process.platform,
|
||||
arch: process.arch,
|
||||
osType: os.type(),
|
||||
osRelease: os.release(),
|
||||
osVersion: typeof os.version === 'function' ? os.version() : null,
|
||||
execPath: process.execPath,
|
||||
resourcesPath: process.resourcesPath || null,
|
||||
cwd: process.cwd(),
|
||||
};
|
||||
}
|
||||
|
||||
function formatRuntimeDiagnostics(diagnostic) {
|
||||
return [
|
||||
`node=${diagnostic.node || '<unknown>'}`,
|
||||
`electron=${diagnostic.electron || '<none>'}`,
|
||||
`modules=${diagnostic.modules || '<unknown>'}`,
|
||||
`napi=${diagnostic.napi || '<unknown>'}`,
|
||||
`v8=${diagnostic.v8 || '<unknown>'}`,
|
||||
`uv=${diagnostic.uv || '<unknown>'}`,
|
||||
`openssl=${diagnostic.openssl || '<unknown>'}`,
|
||||
`glibcRuntime=${diagnostic.glibcRuntime || '<unknown>'}`,
|
||||
`glibcCompiler=${diagnostic.glibcCompiler || '<unknown>'}`,
|
||||
`process=${diagnostic.platform}/${diagnostic.arch}`,
|
||||
`os=${diagnostic.osType} ${diagnostic.osRelease} ${diagnostic.osVersion || '<unknown>'}`,
|
||||
`execPath=${diagnostic.execPath}`,
|
||||
`resourcesPath=${diagnostic.resourcesPath || '<unknown>'}`,
|
||||
`cwd=${diagnostic.cwd}`,
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
const REDISTRIBUTABLE_RUNTIME_PATTERNS = [
|
||||
/^vcruntime\d+(?:_\d+)?\.dll$/i,
|
||||
/^msvcp\d+(?:_\d+)?\.dll$/i,
|
||||
/^msvcr\d+(?:_\d+)?\.dll$/i,
|
||||
/^concrt\d+\.dll$/i,
|
||||
/^vcamp\d+\.dll$/i,
|
||||
/^vcomp\d+\.dll$/i,
|
||||
];
|
||||
|
||||
function readPeImports(filePath) {
|
||||
let buffer;
|
||||
try {
|
||||
buffer = readFileSync(filePath);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (buffer.length < 0x40) return null;
|
||||
const peOffset = buffer.readUInt32LE(0x3c);
|
||||
if (peOffset <= 0 || peOffset + 24 >= buffer.length) return null;
|
||||
if (buffer.readUInt32LE(peOffset) !== 0x4550) return null;
|
||||
const coffOffset = peOffset + 4;
|
||||
const numberOfSections = buffer.readUInt16LE(coffOffset + 2);
|
||||
const sizeOfOptionalHeader = buffer.readUInt16LE(coffOffset + 16);
|
||||
const optionalHeaderOffset = coffOffset + 20;
|
||||
if (optionalHeaderOffset + sizeOfOptionalHeader > buffer.length) return null;
|
||||
const magic = buffer.readUInt16LE(optionalHeaderOffset);
|
||||
if (magic !== 0x10b && magic !== 0x20b) return null;
|
||||
const dataDirectoriesOffset = optionalHeaderOffset + (magic === 0x20b ? 112 : 96);
|
||||
const importEntryOffset = dataDirectoriesOffset + 8;
|
||||
if (importEntryOffset + 8 > buffer.length) return null;
|
||||
const importRva = buffer.readUInt32LE(importEntryOffset);
|
||||
if (importRva === 0) return [];
|
||||
const sections = [];
|
||||
const sectionTableOffset = optionalHeaderOffset + sizeOfOptionalHeader;
|
||||
for (let i = 0; i < numberOfSections; i++) {
|
||||
const base = sectionTableOffset + i * 40;
|
||||
if (base + 40 > buffer.length) return null;
|
||||
sections.push({
|
||||
virtualSize: buffer.readUInt32LE(base + 8),
|
||||
virtualAddress: buffer.readUInt32LE(base + 12),
|
||||
rawSize: buffer.readUInt32LE(base + 16),
|
||||
rawPointer: buffer.readUInt32LE(base + 20),
|
||||
});
|
||||
}
|
||||
const rvaToOffset = (rva) => {
|
||||
for (const s of sections) {
|
||||
const span = Math.max(s.virtualSize, s.rawSize);
|
||||
if (rva >= s.virtualAddress && rva < s.virtualAddress + span) {
|
||||
return rva - s.virtualAddress + s.rawPointer;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
};
|
||||
const readCString = (offset) => {
|
||||
let end = offset;
|
||||
while (end < buffer.length && buffer[end] !== 0) end++;
|
||||
return buffer.toString('ascii', offset, end);
|
||||
};
|
||||
const importTableOffset = rvaToOffset(importRva);
|
||||
if (importTableOffset < 0) return [];
|
||||
const imports = new Set();
|
||||
for (let i = 0; i < 1024; i++) {
|
||||
const base = importTableOffset + i * 20;
|
||||
if (base + 20 > buffer.length) break;
|
||||
const lookupRva = buffer.readUInt32LE(base);
|
||||
const nameRva = buffer.readUInt32LE(base + 12);
|
||||
const iatRva = buffer.readUInt32LE(base + 16);
|
||||
if (lookupRva === 0 && nameRva === 0 && iatRva === 0) break;
|
||||
const nameOffset = rvaToOffset(nameRva);
|
||||
if (nameOffset < 0) continue;
|
||||
const name = readCString(nameOffset);
|
||||
if (name) imports.add(name);
|
||||
}
|
||||
return Array.from(imports);
|
||||
}
|
||||
|
||||
function windowsImportProbe(nativePath) {
|
||||
const imports = readPeImports(nativePath);
|
||||
if (imports === null) return null;
|
||||
const sortedImports = [...imports].sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
|
||||
const redistributable = sortedImports.filter((dll) =>
|
||||
REDISTRIBUTABLE_RUNTIME_PATTERNS.some((pattern) => pattern.test(dll)),
|
||||
);
|
||||
return {
|
||||
command: ['pe-imports', nativePath],
|
||||
status: 0,
|
||||
signal: null,
|
||||
error: null,
|
||||
stdout: sortedImports.join('\n') || null,
|
||||
stderr: null,
|
||||
missing: [],
|
||||
redistributable,
|
||||
};
|
||||
}
|
||||
|
||||
function dependencyProbe(nativePath) {
|
||||
if (!nativePath || !existsSync(nativePath)) return null;
|
||||
if (process.platform === 'win32') return windowsImportProbe(nativePath);
|
||||
const command =
|
||||
process.platform === 'linux'
|
||||
? ['ldd', nativePath]
|
||||
: process.platform === 'darwin'
|
||||
? ['otool', '-L', nativePath]
|
||||
: null;
|
||||
if (!command) return null;
|
||||
const [bin, ...args] = command;
|
||||
const result = spawnSync(bin, args, {
|
||||
encoding: 'utf8',
|
||||
timeout: 4000,
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
const stdout = trimText(result.stdout);
|
||||
const stderr = trimText(result.stderr);
|
||||
const missing =
|
||||
process.platform === 'linux' && stdout
|
||||
? stdout
|
||||
.split('\n')
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.includes('not found'))
|
||||
: [];
|
||||
return {
|
||||
command,
|
||||
status: result.status,
|
||||
signal: result.signal || null,
|
||||
error: result.error ? result.error.message : null,
|
||||
stdout,
|
||||
stderr,
|
||||
missing,
|
||||
redistributable: [],
|
||||
};
|
||||
}
|
||||
|
||||
function formatDependencyProbe(diagnostic) {
|
||||
if (!diagnostic) return null;
|
||||
const status = diagnostic.error
|
||||
? `error=${diagnostic.error}`
|
||||
: diagnostic.signal
|
||||
? `signal=${diagnostic.signal}`
|
||||
: `status=${diagnostic.status}`;
|
||||
return [
|
||||
`$ ${diagnostic.command.join(' ')}`,
|
||||
status,
|
||||
diagnostic.missing?.length ? `missing:\n${diagnostic.missing.join('\n')}` : null,
|
||||
diagnostic.redistributable?.length
|
||||
? `redistributableRuntimeImports (require VC++ redist on host):\n${diagnostic.redistributable.join('\n')}`
|
||||
: null,
|
||||
diagnostic.stdout ? `stdout:\n${diagnostic.stdout}` : null,
|
||||
diagnostic.stderr ? `stderr:\n${diagnostic.stderr}` : null,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
function formatExtraDiagnostic(diagnostic) {
|
||||
if (!diagnostic) return null;
|
||||
if (typeof diagnostic === 'string') return diagnostic;
|
||||
if (typeof diagnostic === 'object' && diagnostic.name && diagnostic.text) {
|
||||
return `${diagnostic.name}:\n${diagnostic.text}`;
|
||||
}
|
||||
return `extra:\n${trimText(JSON.stringify(diagnostic, null, 2))}`;
|
||||
}
|
||||
|
||||
function collectNativeDiagnostics({
|
||||
moduleName,
|
||||
nativePath,
|
||||
nativeRoot,
|
||||
packageDir,
|
||||
reason,
|
||||
cause,
|
||||
skipNativeProbeEnv,
|
||||
extraDiagnostics = [],
|
||||
}) {
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
moduleName,
|
||||
reason,
|
||||
target: {
|
||||
platform: process.platform,
|
||||
arch: process.arch,
|
||||
},
|
||||
packageDir: packageDir || null,
|
||||
nativeRoot: nativeRoot || null,
|
||||
nativePath: nativePath || null,
|
||||
nativeFile: nativePath ? basename(nativePath) : null,
|
||||
nativeFileStat: fileDiagnostic(nativePath),
|
||||
runtime: runtimeDiagnostics(),
|
||||
environment: environmentDiagnostics(skipNativeProbeEnv),
|
||||
nativeRootEntries: directoryDiagnostic(nativeRoot),
|
||||
dependencyProbe: dependencyProbe(nativePath),
|
||||
extraDiagnostics: extraDiagnostics.filter(Boolean),
|
||||
cause: errorDiagnostic(cause),
|
||||
};
|
||||
}
|
||||
|
||||
function formatNativeDiagnostics(diagnostics) {
|
||||
const sections = [
|
||||
`module=${diagnostics.moduleName}`,
|
||||
`reason=${diagnostics.reason}`,
|
||||
`target=${diagnostics.target.platform}/${diagnostics.target.arch}`,
|
||||
`packageDir=${diagnostics.packageDir || '<unknown>'}`,
|
||||
`nativeRoot=${diagnostics.nativeRoot || '<unknown>'}`,
|
||||
`nativePath=${diagnostics.nativePath || '<unknown>'}`,
|
||||
`nativeFile=${diagnostics.nativeFile || '<unknown>'}`,
|
||||
`nativeFileStat=${formatFileDiagnostic(diagnostics.nativeFileStat)}`,
|
||||
`runtime:\n${formatRuntimeDiagnostics(diagnostics.runtime)}`,
|
||||
`environment:\n${formatEnvironment(diagnostics.environment)}`,
|
||||
`nativeRootEntries:\n${formatDirectoryDiagnostic(diagnostics.nativeRootEntries)}`,
|
||||
...diagnostics.extraDiagnostics.map(formatExtraDiagnostic).filter(Boolean),
|
||||
];
|
||||
const dependencyOutput = formatDependencyProbe(diagnostics.dependencyProbe);
|
||||
if (dependencyOutput) sections.push(`dependencyProbe:\n${dependencyOutput}`);
|
||||
const causeText = formatErrorDiagnostic(diagnostics.cause);
|
||||
if (causeText) sections.push(`cause:\n${causeText}`);
|
||||
return sections.join('\n');
|
||||
}
|
||||
|
||||
function isNativeLoadError(error) {
|
||||
return Boolean(error?.[NATIVE_LOAD_ERROR_MARKER]);
|
||||
}
|
||||
|
||||
function createNativeLoadError({
|
||||
moduleName,
|
||||
nativePath,
|
||||
nativeRoot,
|
||||
packageDir,
|
||||
reason,
|
||||
cause,
|
||||
skipNativeProbeEnv,
|
||||
extraDiagnostics = [],
|
||||
}) {
|
||||
if (isNativeLoadError(cause)) return cause;
|
||||
const diagnostics = collectNativeDiagnostics({
|
||||
moduleName,
|
||||
nativePath,
|
||||
nativeRoot,
|
||||
packageDir,
|
||||
reason,
|
||||
cause,
|
||||
skipNativeProbeEnv,
|
||||
extraDiagnostics,
|
||||
});
|
||||
const error = new Error(`${moduleName} native module failed to load.\n${formatNativeDiagnostics(diagnostics)}`);
|
||||
error.name = 'NativeModuleLoadError';
|
||||
error[NATIVE_LOAD_ERROR_MARKER] = true;
|
||||
error.nativeDiagnostics = diagnostics;
|
||||
error.toJSON = () => ({
|
||||
name: error.name,
|
||||
message: error.message,
|
||||
nativeDiagnostics: diagnostics,
|
||||
});
|
||||
if (cause) error.cause = cause;
|
||||
return error;
|
||||
}
|
||||
|
||||
function probeNativeBinary({moduleName, nativePath, nativeRoot, packageDir, skipNativeProbeEnv, timeoutMs = 5000}) {
|
||||
if (!skipNativeProbeEnv || process.env[skipNativeProbeEnv] === '1') {
|
||||
return null;
|
||||
}
|
||||
const result = spawnSync(process.execPath, ['-e', 'require(process.argv[1])', nativePath], {
|
||||
env: {...process.env, ELECTRON_RUN_AS_NODE: '1', [skipNativeProbeEnv]: '1'},
|
||||
encoding: 'utf8',
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
timeout: timeoutMs,
|
||||
});
|
||||
if (result.status === 0) return null;
|
||||
const reason = result.error
|
||||
? result.error.message
|
||||
: result.signal
|
||||
? `safety probe terminated by signal ${result.signal}`
|
||||
: `safety probe exited with code ${result.status}`;
|
||||
return createNativeLoadError({
|
||||
moduleName,
|
||||
nativePath,
|
||||
nativeRoot,
|
||||
packageDir,
|
||||
reason,
|
||||
skipNativeProbeEnv,
|
||||
extraDiagnostics: [
|
||||
result.stdout ? {name: 'probeStdout', text: trimText(result.stdout)} : null,
|
||||
result.stderr ? {name: 'probeStderr', text: trimText(result.stderr)} : null,
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
function loadNativeBinding({moduleName, nativePath, nativeRoot, packageDir, skipNativeProbeEnv, probe = true}) {
|
||||
if (!existsSync(nativePath)) {
|
||||
return {
|
||||
binding: null,
|
||||
loadError: createNativeLoadError({
|
||||
moduleName,
|
||||
nativePath,
|
||||
nativeRoot,
|
||||
packageDir,
|
||||
reason: 'native binary not found',
|
||||
skipNativeProbeEnv,
|
||||
}),
|
||||
};
|
||||
}
|
||||
const nativeProbeError = probe
|
||||
? probeNativeBinary({moduleName, nativePath, nativeRoot, packageDir, skipNativeProbeEnv})
|
||||
: null;
|
||||
if (nativeProbeError) {
|
||||
return {binding: null, loadError: nativeProbeError};
|
||||
}
|
||||
try {
|
||||
return {binding: require(nativePath), loadError: null};
|
||||
} catch (error) {
|
||||
return {
|
||||
binding: null,
|
||||
loadError: createNativeLoadError({
|
||||
moduleName,
|
||||
nativePath,
|
||||
nativeRoot,
|
||||
packageDir,
|
||||
reason: 'require(nativePath) threw',
|
||||
cause: error,
|
||||
skipNativeProbeEnv,
|
||||
}),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
collectNativeDiagnostics,
|
||||
createNativeLoadError,
|
||||
formatNativeDiagnostics,
|
||||
isNativeLoadError,
|
||||
loadNativeBinding,
|
||||
probeNativeBinary,
|
||||
};
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "@fluxer/windows-input-hook",
|
||||
"version": "0.0.0",
|
||||
"description": "",
|
||||
"private": true,
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"cpu": [
|
||||
"x64",
|
||||
"arm64"
|
||||
],
|
||||
"main": "index.js",
|
||||
"types": "index.d.ts",
|
||||
"files": [
|
||||
"index.js",
|
||||
"index.d.ts",
|
||||
"loader-diagnostics.cjs",
|
||||
"windows-input-hook.win32-x64-msvc.node",
|
||||
"windows-input-hook.win32-arm64-msvc.node"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "cargo run --locked --quiet --manifest-path ../../../tools/ci/Cargo.toml -- build-desktop-native-addon",
|
||||
"test": "cargo test --manifest-path Cargo.toml",
|
||||
"check:windows:x64": "cargo check --manifest-path Cargo.toml --target x86_64-pc-windows-msvc --tests",
|
||||
"check:windows:arm64": "cargo check --manifest-path Cargo.toml --target aarch64-pc-windows-msvc --tests"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,811 @@
|
||||
#![cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||||
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
use napi::{
|
||||
Env,
|
||||
bindgen_prelude::{Function, Object, Result, ToNapiValue},
|
||||
sys,
|
||||
threadsafe_function::{ThreadsafeFunction, UnknownReturnValue},
|
||||
};
|
||||
use napi_derive::napi;
|
||||
|
||||
const RING_CAPACITY: usize = 1024;
|
||||
const KEY_NAME_BUF: usize = 32;
|
||||
const LLKHF_EXTENDED_FLAG: u32 = 0x01;
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub enum EventKind {
|
||||
KeyDown,
|
||||
KeyUp,
|
||||
MouseDown,
|
||||
MouseUp,
|
||||
|
||||
#[default]
|
||||
MouseMove,
|
||||
Wheel,
|
||||
}
|
||||
|
||||
impl EventKind {
|
||||
fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::KeyDown => "keydown",
|
||||
Self::KeyUp => "keyup",
|
||||
Self::MouseDown => "mousedown",
|
||||
Self::MouseUp => "mouseup",
|
||||
Self::MouseMove => "mousemove",
|
||||
Self::Wheel => "wheel",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub struct QueuedEvent {
|
||||
pub kind: EventKind,
|
||||
pub keycode: u32,
|
||||
pub button: u8,
|
||||
pub delta_x: i32,
|
||||
pub delta_y: i32,
|
||||
pub x: i32,
|
||||
pub y: i32,
|
||||
pub has_xy: bool,
|
||||
pub key_name_buf: [u8; KEY_NAME_BUF],
|
||||
pub key_name_len: u8,
|
||||
pub ctrl: bool,
|
||||
pub alt: bool,
|
||||
pub shift: bool,
|
||||
pub meta: bool,
|
||||
}
|
||||
|
||||
impl QueuedEvent {
|
||||
fn key_name(&self) -> &str {
|
||||
let len = (self.key_name_len as usize).min(KEY_NAME_BUF);
|
||||
std::str::from_utf8(&self.key_name_buf[..len]).unwrap_or("")
|
||||
}
|
||||
}
|
||||
|
||||
fn write_ascii_key_name(buf: &mut [u8; KEY_NAME_BUF], len_out: &mut u8, name: &str) {
|
||||
let bytes = name.as_bytes();
|
||||
let n = bytes.len().min(KEY_NAME_BUF);
|
||||
buf[..n].copy_from_slice(&bytes[..n]);
|
||||
*len_out = n as u8;
|
||||
}
|
||||
|
||||
fn scan_aware_key_name(vk: u16, flags: u32) -> Option<&'static str> {
|
||||
let extended = (flags & LLKHF_EXTENDED_FLAG) != 0;
|
||||
match (vk, extended) {
|
||||
(0x0d, true) => Some("NumpadEnter"),
|
||||
(0x2d, false) => Some("Numpad0"),
|
||||
(0x23, false) => Some("Numpad1"),
|
||||
(0x28, false) => Some("Numpad2"),
|
||||
(0x22, false) => Some("Numpad3"),
|
||||
(0x25, false) => Some("Numpad4"),
|
||||
(0x0c, false) => Some("Numpad5"),
|
||||
(0x27, false) => Some("Numpad6"),
|
||||
(0x24, false) => Some("Numpad7"),
|
||||
(0x26, false) => Some("Numpad8"),
|
||||
(0x21, false) => Some("Numpad9"),
|
||||
(0x2e, false) => Some("NumpadDecimal"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn write_key_name(buf: &mut [u8; KEY_NAME_BUF], len_out: &mut u8, vk: u16) {
|
||||
use fluxer_desktop_native::input::keymap::{fallback_name, windows::vk_to_name};
|
||||
if let Some(name) = vk_to_name(vk) {
|
||||
write_ascii_key_name(buf, len_out, name);
|
||||
} else {
|
||||
write_ascii_key_name(buf, len_out, &fallback_name(vk));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn write_key_name_from_hook(
|
||||
buf: &mut [u8; KEY_NAME_BUF],
|
||||
len_out: &mut u8,
|
||||
vk: u16,
|
||||
flags: u32,
|
||||
) {
|
||||
if let Some(name) = scan_aware_key_name(vk, flags) {
|
||||
write_ascii_key_name(buf, len_out, name);
|
||||
return;
|
||||
}
|
||||
write_key_name(buf, len_out, vk);
|
||||
}
|
||||
|
||||
impl ToNapiValue for QueuedEvent {
|
||||
unsafe fn to_napi_value(raw_env: sys::napi_env, event: Self) -> Result<sys::napi_value> {
|
||||
let env = Env::from_raw(raw_env);
|
||||
let mut object = Object::new(&env)?;
|
||||
object.set("type", event.kind.as_str())?;
|
||||
object.set("ctrlKey", event.ctrl)?;
|
||||
object.set("altKey", event.alt)?;
|
||||
object.set("shiftKey", event.shift)?;
|
||||
object.set("metaKey", event.meta)?;
|
||||
match event.kind {
|
||||
EventKind::KeyDown | EventKind::KeyUp => {
|
||||
object.set("keycode", event.keycode)?;
|
||||
object.set("keyName", event.key_name())?;
|
||||
}
|
||||
EventKind::MouseDown | EventKind::MouseUp => {
|
||||
object.set("button", u32::from(event.button))?;
|
||||
if event.has_xy {
|
||||
object.set("x", event.x)?;
|
||||
object.set("y", event.y)?;
|
||||
}
|
||||
}
|
||||
EventKind::MouseMove => {
|
||||
object.set("x", event.x)?;
|
||||
object.set("y", event.y)?;
|
||||
}
|
||||
EventKind::Wheel => {
|
||||
object.set("deltaX", event.delta_x)?;
|
||||
object.set("deltaY", event.delta_y)?;
|
||||
if event.has_xy {
|
||||
object.set("x", event.x)?;
|
||||
object.set("y", event.y)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
unsafe { <Object<'_> as ToNapiValue>::to_napi_value(raw_env, object) }
|
||||
}
|
||||
}
|
||||
|
||||
type EventThreadsafeFunction = ThreadsafeFunction<
|
||||
QueuedEvent,
|
||||
UnknownReturnValue,
|
||||
QueuedEvent,
|
||||
napi::Status,
|
||||
false,
|
||||
true,
|
||||
RING_CAPACITY,
|
||||
>;
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
mod platform {
|
||||
use super::{EventKind, EventThreadsafeFunction, QueuedEvent, write_key_name_from_hook};
|
||||
use napi::threadsafe_function::ThreadsafeFunctionCallMode;
|
||||
use std::sync::{
|
||||
Arc, Mutex, MutexGuard, OnceLock,
|
||||
atomic::{AtomicBool, AtomicI32, AtomicU64, Ordering},
|
||||
mpsc,
|
||||
};
|
||||
use std::thread::{self, JoinHandle};
|
||||
use std::time::Duration;
|
||||
use windows::Win32::Foundation::{LPARAM, LRESULT, POINT, WPARAM};
|
||||
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
|
||||
use windows::Win32::UI::Input::KeyboardAndMouse::{
|
||||
GetKeyState, GetKeyboardLayout, MAPVK_VSC_TO_VK_EX, MapVirtualKeyExW, VK_CONTROL, VK_LWIN,
|
||||
VK_MENU, VK_RWIN, VK_SHIFT,
|
||||
};
|
||||
use windows::Win32::UI::WindowsAndMessaging::{
|
||||
CallNextHookEx, DispatchMessageW, GetCursorPos, GetForegroundWindow, GetMessageW,
|
||||
GetWindowThreadProcessId, HHOOK, KBDLLHOOKSTRUCT, MSG, MSLLHOOKSTRUCT, PM_NOREMOVE,
|
||||
PeekMessageW, PostThreadMessageW, SetWindowsHookExW, TranslateMessage, UnhookWindowsHookEx,
|
||||
WH_KEYBOARD_LL, WH_MOUSE_LL, WM_APP, WM_KEYDOWN, WM_KEYUP, WM_QUIT, WM_SYSKEYDOWN,
|
||||
WM_SYSKEYUP,
|
||||
};
|
||||
|
||||
const WATCHDOG_INTERVAL_MS: u64 = 1000;
|
||||
const WATCHDOG_TIMEOUT_MS: u64 = 5000;
|
||||
const WM_APP_REINSTALL: u32 = WM_APP + 1;
|
||||
|
||||
pub(crate) struct HookHandle {
|
||||
pub(crate) tsfn: EventThreadsafeFunction,
|
||||
pub(crate) dropped_events: AtomicU64,
|
||||
pub(crate) keyboard_hook: Mutex<Option<HHOOK>>,
|
||||
pub(crate) mouse_hook: Mutex<Option<HHOOK>>,
|
||||
pub(crate) thread_id: AtomicU64,
|
||||
pub(crate) started: AtomicBool,
|
||||
pub(crate) watchdog_stop: AtomicBool,
|
||||
pub(crate) worker_thread: Mutex<Option<JoinHandle<()>>>,
|
||||
pub(crate) watchdog_thread: Mutex<Option<JoinHandle<()>>>,
|
||||
pub(crate) last_cursor_x: AtomicI32,
|
||||
pub(crate) last_cursor_y: AtomicI32,
|
||||
pub(crate) last_event_ms: AtomicU64,
|
||||
pub(crate) last_cursor_change_ms: AtomicU64,
|
||||
pub(crate) reinstall_count: AtomicU64,
|
||||
}
|
||||
|
||||
unsafe impl Send for HookHandle {}
|
||||
unsafe impl Sync for HookHandle {}
|
||||
|
||||
static G_HANDLE: OnceLock<Mutex<Option<Arc<HookHandle>>>> = OnceLock::new();
|
||||
|
||||
fn handle_slot() -> &'static Mutex<Option<Arc<HookHandle>>> {
|
||||
G_HANDLE.get_or_init(|| Mutex::new(None))
|
||||
}
|
||||
|
||||
fn lock_recover<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
|
||||
mutex
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
}
|
||||
|
||||
fn current_handle() -> Option<Arc<HookHandle>> {
|
||||
lock_recover(handle_slot()).clone()
|
||||
}
|
||||
|
||||
fn clear_handle_slot(handle: &HookHandle) {
|
||||
let mut slot = lock_recover(handle_slot());
|
||||
if let Some(existing) = slot.as_ref()
|
||||
&& std::ptr::eq(existing.as_ref(), handle)
|
||||
{
|
||||
*slot = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn now_ms() -> u64 {
|
||||
unsafe { windows::Win32::System::SystemInformation::GetTickCount64() }
|
||||
}
|
||||
|
||||
fn sample_modifiers() -> (bool, bool, bool, bool) {
|
||||
use fluxer_desktop_native::input::modifiers::windows::from_sampled;
|
||||
unsafe {
|
||||
let m = from_sampled(
|
||||
GetKeyState(VK_SHIFT.0 as i32) as u16,
|
||||
GetKeyState(VK_CONTROL.0 as i32) as u16,
|
||||
GetKeyState(VK_MENU.0 as i32) as u16,
|
||||
GetKeyState(VK_LWIN.0 as i32) as u16,
|
||||
GetKeyState(VK_RWIN.0 as i32) as u16,
|
||||
);
|
||||
(m.ctrl, m.alt, m.shift, m.meta)
|
||||
}
|
||||
}
|
||||
|
||||
fn foreground_keyboard_thread_id() -> u32 {
|
||||
let hwnd = unsafe { GetForegroundWindow() };
|
||||
if hwnd.0.is_null() {
|
||||
return 0;
|
||||
}
|
||||
unsafe { GetWindowThreadProcessId(hwnd, None) }
|
||||
}
|
||||
|
||||
fn layout_aware_vk_from_scan_code(fallback_vk: u16, scan_code: u32, flags: u32) -> u16 {
|
||||
let mut scan = scan_code;
|
||||
if (flags & super::LLKHF_EXTENDED_FLAG) != 0 {
|
||||
scan |= 0xe000;
|
||||
}
|
||||
let layout = unsafe { GetKeyboardLayout(foreground_keyboard_thread_id()) };
|
||||
let mapped = unsafe { MapVirtualKeyExW(scan, MAPVK_VSC_TO_VK_EX, Some(layout)) };
|
||||
if mapped == 0 {
|
||||
fallback_vk
|
||||
} else {
|
||||
mapped as u16
|
||||
}
|
||||
}
|
||||
|
||||
fn enqueue(handle: &HookHandle, event: QueuedEvent) {
|
||||
handle.last_event_ms.store(now_ms(), Ordering::Release);
|
||||
let status = handle
|
||||
.tsfn
|
||||
.call(event, ThreadsafeFunctionCallMode::NonBlocking);
|
||||
if !matches!(status, napi::Status::Ok) {
|
||||
handle.dropped_events.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe extern "system" fn keyboard_proc(code: i32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
|
||||
if code >= 0
|
||||
&& let Some(handle) = current_handle()
|
||||
{
|
||||
let info = unsafe { &*(lparam.0 as *const KBDLLHOOKSTRUCT) };
|
||||
let vk = info.vkCode as u16;
|
||||
let msg = wparam.0 as u32;
|
||||
let is_down = msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN;
|
||||
let is_up = msg == WM_KEYUP || msg == WM_SYSKEYUP;
|
||||
if is_down || is_up {
|
||||
let (ctrl, alt, shift, meta) = sample_modifiers();
|
||||
let mut event = QueuedEvent {
|
||||
kind: if is_down {
|
||||
EventKind::KeyDown
|
||||
} else {
|
||||
EventKind::KeyUp
|
||||
},
|
||||
keycode: info.vkCode,
|
||||
ctrl,
|
||||
alt,
|
||||
shift,
|
||||
meta,
|
||||
..QueuedEvent::default()
|
||||
};
|
||||
let layout_vk = layout_aware_vk_from_scan_code(vk, info.scanCode, info.flags.0);
|
||||
write_key_name_from_hook(
|
||||
&mut event.key_name_buf,
|
||||
&mut event.key_name_len,
|
||||
layout_vk,
|
||||
info.flags.0,
|
||||
);
|
||||
enqueue(&handle, event);
|
||||
}
|
||||
}
|
||||
unsafe { CallNextHookEx(None, code, wparam, lparam) }
|
||||
}
|
||||
|
||||
unsafe extern "system" fn mouse_proc(code: i32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
|
||||
use fluxer_desktop_native::input::windows_mouse::{Action, Axis, classify};
|
||||
if code >= 0
|
||||
&& let Some(handle) = current_handle()
|
||||
{
|
||||
let info = unsafe { &*(lparam.0 as *const MSLLHOOKSTRUCT) };
|
||||
let md = info.mouseData;
|
||||
let x_button = ((md >> 16) & 0xffff) as u16;
|
||||
let wheel_delta = ((md >> 16) & 0xffff) as i16;
|
||||
let (ctrl, alt, shift, meta) = sample_modifiers();
|
||||
let action = classify(wparam.0 as u32, x_button, wheel_delta);
|
||||
match action {
|
||||
Action::Button { down, button } => {
|
||||
enqueue(
|
||||
&handle,
|
||||
QueuedEvent {
|
||||
kind: if down {
|
||||
EventKind::MouseDown
|
||||
} else {
|
||||
EventKind::MouseUp
|
||||
},
|
||||
button,
|
||||
x: info.pt.x,
|
||||
y: info.pt.y,
|
||||
has_xy: true,
|
||||
ctrl,
|
||||
alt,
|
||||
shift,
|
||||
meta,
|
||||
..QueuedEvent::default()
|
||||
},
|
||||
);
|
||||
}
|
||||
Action::Move => {
|
||||
enqueue(
|
||||
&handle,
|
||||
QueuedEvent {
|
||||
kind: EventKind::MouseMove,
|
||||
x: info.pt.x,
|
||||
y: info.pt.y,
|
||||
has_xy: true,
|
||||
ctrl,
|
||||
alt,
|
||||
shift,
|
||||
meta,
|
||||
..QueuedEvent::default()
|
||||
},
|
||||
);
|
||||
}
|
||||
Action::Wheel { axis, delta } => {
|
||||
let (dx, dy) = match axis {
|
||||
Axis::Horizontal => (i32::from(delta), 0),
|
||||
Axis::Vertical => (0, i32::from(delta)),
|
||||
};
|
||||
enqueue(
|
||||
&handle,
|
||||
QueuedEvent {
|
||||
kind: EventKind::Wheel,
|
||||
delta_x: dx,
|
||||
delta_y: dy,
|
||||
x: info.pt.x,
|
||||
y: info.pt.y,
|
||||
has_xy: true,
|
||||
ctrl,
|
||||
alt,
|
||||
shift,
|
||||
meta,
|
||||
..QueuedEvent::default()
|
||||
},
|
||||
);
|
||||
}
|
||||
Action::Ignored => {}
|
||||
}
|
||||
}
|
||||
unsafe { CallNextHookEx(None, code, wparam, lparam) }
|
||||
}
|
||||
|
||||
fn install_hooks(handle: &HookHandle) -> Result<(), String> {
|
||||
unsafe {
|
||||
let hmod =
|
||||
GetModuleHandleW(None).map_err(|err| format!("GetModuleHandleW failed: {err}"))?;
|
||||
let mut kbd = lock_recover(&handle.keyboard_hook);
|
||||
if kbd.is_none() {
|
||||
let hook =
|
||||
SetWindowsHookExW(WH_KEYBOARD_LL, Some(keyboard_proc), Some(hmod.into()), 0)
|
||||
.map_err(|err| format!("SetWindowsHookExW keyboard failed: {err}"))?;
|
||||
*kbd = Some(hook);
|
||||
}
|
||||
drop(kbd);
|
||||
let mut mouse = lock_recover(&handle.mouse_hook);
|
||||
if mouse.is_none() {
|
||||
let hook = SetWindowsHookExW(WH_MOUSE_LL, Some(mouse_proc), Some(hmod.into()), 0)
|
||||
.map_err(|err| format!("SetWindowsHookExW mouse failed: {err}"))?;
|
||||
*mouse = Some(hook);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn uninstall_hooks(handle: &HookHandle) {
|
||||
if let Some(hook) = lock_recover(&handle.keyboard_hook).take() {
|
||||
let _ = unsafe { UnhookWindowsHookEx(hook) };
|
||||
}
|
||||
if let Some(hook) = lock_recover(&handle.mouse_hook).take() {
|
||||
let _ = unsafe { UnhookWindowsHookEx(hook) };
|
||||
}
|
||||
}
|
||||
|
||||
fn worker_main(handle: Arc<HookHandle>, ready: mpsc::Sender<Result<(), String>>) {
|
||||
unsafe {
|
||||
let mut msg = MSG::default();
|
||||
|
||||
let _ = PeekMessageW(
|
||||
&mut msg,
|
||||
None,
|
||||
WM_APP_REINSTALL,
|
||||
WM_APP_REINSTALL,
|
||||
PM_NOREMOVE,
|
||||
);
|
||||
}
|
||||
handle.thread_id.store(
|
||||
u64::from(unsafe { windows::Win32::System::Threading::GetCurrentThreadId() }),
|
||||
Ordering::Release,
|
||||
);
|
||||
if let Err(err) = install_hooks(&handle) {
|
||||
uninstall_hooks(&handle);
|
||||
handle.thread_id.store(0, Ordering::Release);
|
||||
let _ = ready.send(Err(err));
|
||||
return;
|
||||
}
|
||||
handle.last_event_ms.store(now_ms(), Ordering::Release);
|
||||
let _ = ready.send(Ok(()));
|
||||
let mut msg = MSG::default();
|
||||
loop {
|
||||
let got = unsafe { GetMessageW(&mut msg, None, 0, 0) };
|
||||
if got.0 <= 0 {
|
||||
break;
|
||||
}
|
||||
if msg.message == WM_APP_REINSTALL {
|
||||
uninstall_hooks(&handle);
|
||||
if install_hooks(&handle).is_ok() {
|
||||
handle.last_event_ms.store(now_ms(), Ordering::Release);
|
||||
handle.reinstall_count.fetch_add(1, Ordering::Relaxed);
|
||||
} else {
|
||||
uninstall_hooks(&handle);
|
||||
handle.last_event_ms.store(now_ms(), Ordering::Release);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
unsafe {
|
||||
let _ = TranslateMessage(&msg);
|
||||
DispatchMessageW(&msg);
|
||||
}
|
||||
}
|
||||
uninstall_hooks(&handle);
|
||||
handle.thread_id.store(0, Ordering::Release);
|
||||
}
|
||||
|
||||
fn watchdog_main(handle: Arc<HookHandle>) {
|
||||
while !handle.watchdog_stop.load(Ordering::Acquire) {
|
||||
thread::sleep(Duration::from_millis(WATCHDOG_INTERVAL_MS));
|
||||
if handle.watchdog_stop.load(Ordering::Acquire) {
|
||||
break;
|
||||
}
|
||||
let mut pt = POINT::default();
|
||||
if unsafe { GetCursorPos(&mut pt) }.is_err() {
|
||||
continue;
|
||||
}
|
||||
let now = now_ms();
|
||||
let lx = handle.last_cursor_x.load(Ordering::Relaxed);
|
||||
let ly = handle.last_cursor_y.load(Ordering::Relaxed);
|
||||
if pt.x != lx || pt.y != ly {
|
||||
handle.last_cursor_x.store(pt.x, Ordering::Relaxed);
|
||||
handle.last_cursor_y.store(pt.y, Ordering::Relaxed);
|
||||
handle.last_cursor_change_ms.store(now, Ordering::Release);
|
||||
}
|
||||
let last_event = handle.last_event_ms.load(Ordering::Acquire);
|
||||
let last_cursor_change = handle.last_cursor_change_ms.load(Ordering::Acquire);
|
||||
if last_cursor_change > last_event && now.wrapping_sub(last_event) > WATCHDOG_TIMEOUT_MS
|
||||
{
|
||||
let tid = handle.thread_id.load(Ordering::Acquire) as u32;
|
||||
if tid != 0 {
|
||||
unsafe {
|
||||
let _ = PostThreadMessageW(tid, WM_APP_REINSTALL, WPARAM(0), LPARAM(0));
|
||||
}
|
||||
handle.last_event_ms.store(now, Ordering::Release);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn start(handle: Arc<HookHandle>) -> Result<(), String> {
|
||||
let mut slot = lock_recover(handle_slot());
|
||||
if let Some(existing) = slot.as_ref()
|
||||
&& !Arc::ptr_eq(existing, &handle)
|
||||
{
|
||||
return Err("another InputHook is already active".to_owned());
|
||||
}
|
||||
if handle.started.swap(true, Ordering::AcqRel) {
|
||||
return Ok(());
|
||||
}
|
||||
*slot = Some(handle.clone());
|
||||
drop(slot);
|
||||
|
||||
handle.watchdog_stop.store(false, Ordering::Release);
|
||||
let now = now_ms();
|
||||
handle.last_event_ms.store(now, Ordering::Release);
|
||||
handle.last_cursor_change_ms.store(now, Ordering::Release);
|
||||
let mut pt = POINT::default();
|
||||
if unsafe { GetCursorPos(&mut pt) }.is_ok() {
|
||||
handle.last_cursor_x.store(pt.x, Ordering::Relaxed);
|
||||
handle.last_cursor_y.store(pt.y, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
let (ready_tx, ready_rx) = mpsc::channel();
|
||||
let worker = {
|
||||
let h = handle.clone();
|
||||
match thread::Builder::new()
|
||||
.name("fluxer-input-hook-worker".into())
|
||||
.spawn(move || worker_main(h, ready_tx))
|
||||
{
|
||||
Ok(worker) => worker,
|
||||
Err(_) => {
|
||||
handle.started.store(false, Ordering::Release);
|
||||
clear_handle_slot(&handle);
|
||||
return Err("failed to spawn worker thread".to_owned());
|
||||
}
|
||||
}
|
||||
};
|
||||
match ready_rx.recv() {
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(err)) => {
|
||||
handle.started.store(false, Ordering::Release);
|
||||
handle.thread_id.store(0, Ordering::Release);
|
||||
clear_handle_slot(&handle);
|
||||
let _ = worker.join();
|
||||
return Err(err);
|
||||
}
|
||||
Err(_) => {
|
||||
handle.started.store(false, Ordering::Release);
|
||||
handle.thread_id.store(0, Ordering::Release);
|
||||
clear_handle_slot(&handle);
|
||||
let _ = worker.join();
|
||||
return Err("worker thread exited before installing hooks".to_owned());
|
||||
}
|
||||
}
|
||||
*lock_recover(&handle.worker_thread) = Some(worker);
|
||||
|
||||
let watchdog = {
|
||||
let h = handle.clone();
|
||||
match thread::Builder::new()
|
||||
.name("fluxer-input-hook-watchdog".into())
|
||||
.spawn(move || watchdog_main(h))
|
||||
{
|
||||
Ok(watchdog) => watchdog,
|
||||
Err(_) => {
|
||||
stop(&handle);
|
||||
return Err("failed to spawn watchdog thread".to_owned());
|
||||
}
|
||||
}
|
||||
};
|
||||
*lock_recover(&handle.watchdog_thread) = Some(watchdog);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn stop(handle: &HookHandle) {
|
||||
if !handle.started.swap(false, Ordering::AcqRel) {
|
||||
return;
|
||||
}
|
||||
handle.watchdog_stop.store(true, Ordering::Release);
|
||||
let tid = handle.thread_id.swap(0, Ordering::AcqRel) as u32;
|
||||
if tid != 0 {
|
||||
unsafe {
|
||||
let _ = PostThreadMessageW(tid, WM_QUIT, WPARAM(0), LPARAM(0));
|
||||
}
|
||||
}
|
||||
if let Some(t) = lock_recover(&handle.worker_thread).take() {
|
||||
let _ = t.join();
|
||||
}
|
||||
if let Some(t) = lock_recover(&handle.watchdog_thread).take() {
|
||||
let _ = t.join();
|
||||
}
|
||||
clear_handle_slot(handle);
|
||||
}
|
||||
|
||||
pub(crate) fn new_handle(tsfn: EventThreadsafeFunction) -> Arc<HookHandle> {
|
||||
Arc::new(HookHandle {
|
||||
tsfn,
|
||||
dropped_events: AtomicU64::new(0),
|
||||
keyboard_hook: Mutex::new(None),
|
||||
mouse_hook: Mutex::new(None),
|
||||
thread_id: AtomicU64::new(0),
|
||||
started: AtomicBool::new(false),
|
||||
watchdog_stop: AtomicBool::new(false),
|
||||
worker_thread: Mutex::new(None),
|
||||
watchdog_thread: Mutex::new(None),
|
||||
last_cursor_x: AtomicI32::new(0),
|
||||
last_cursor_y: AtomicI32::new(0),
|
||||
last_event_ms: AtomicU64::new(0),
|
||||
last_cursor_change_ms: AtomicU64::new(0),
|
||||
reinstall_count: AtomicU64::new(0),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
mod platform {
|
||||
use super::EventThreadsafeFunction;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicU64;
|
||||
|
||||
pub(crate) struct HookHandle {
|
||||
pub(crate) tsfn: EventThreadsafeFunction,
|
||||
pub(crate) dropped_events: AtomicU64,
|
||||
pub(crate) reinstall_count: AtomicU64,
|
||||
}
|
||||
|
||||
pub(crate) fn new_handle(tsfn: EventThreadsafeFunction) -> Arc<HookHandle> {
|
||||
Arc::new(HookHandle {
|
||||
tsfn,
|
||||
dropped_events: AtomicU64::new(0),
|
||||
reinstall_count: AtomicU64::new(0),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn start(_handle: Arc<HookHandle>) -> Result<(), String> {
|
||||
Err("windows-input-hook is only supported on Windows".to_owned())
|
||||
}
|
||||
|
||||
pub(crate) fn stop(_handle: &HookHandle) {}
|
||||
}
|
||||
|
||||
use platform::HookHandle;
|
||||
|
||||
#[napi]
|
||||
pub struct InputHook {
|
||||
inner: std::sync::Arc<HookHandle>,
|
||||
}
|
||||
|
||||
#[napi]
|
||||
impl InputHook {
|
||||
#[napi(constructor)]
|
||||
pub fn new(callback: Function<QueuedEvent, UnknownReturnValue>) -> Result<Self> {
|
||||
let tsfn: EventThreadsafeFunction = callback
|
||||
.build_threadsafe_function::<QueuedEvent>()
|
||||
.weak::<true>()
|
||||
.callee_handled::<false>()
|
||||
.max_queue_size::<RING_CAPACITY>()
|
||||
.build()
|
||||
.map_err(|err| {
|
||||
napi::Error::new(
|
||||
napi::Status::GenericFailure,
|
||||
format!("failed to create InputHook callback: {}", err.reason),
|
||||
)
|
||||
})?;
|
||||
Ok(Self {
|
||||
inner: platform::new_handle(tsfn),
|
||||
})
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn start(&self) -> Result<()> {
|
||||
platform::start(self.inner.clone()).map_err(|msg| {
|
||||
napi::Error::new(
|
||||
napi::Status::GenericFailure,
|
||||
format!("InputHook.start failed: {msg}"),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn stop(&self) {
|
||||
platform::stop(&self.inner);
|
||||
}
|
||||
|
||||
#[napi(getter, js_name = "droppedEvents")]
|
||||
pub fn dropped_events(&self) -> f64 {
|
||||
self.inner
|
||||
.dropped_events
|
||||
.load(std::sync::atomic::Ordering::Relaxed) as f64
|
||||
}
|
||||
|
||||
#[napi(getter, js_name = "reinstallCount")]
|
||||
pub fn reinstall_count(&self) -> f64 {
|
||||
self.inner
|
||||
.reinstall_count
|
||||
.load(std::sync::atomic::Ordering::Relaxed) as f64
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for InputHook {
|
||||
fn drop(&mut self) {
|
||||
platform::stop(&self.inner);
|
||||
}
|
||||
}
|
||||
|
||||
#[napi(js_name = "isAvailable")]
|
||||
pub fn is_available() -> bool {
|
||||
cfg!(target_os = "windows")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use fluxer_desktop_native::input::ring::Ring;
|
||||
|
||||
#[test]
|
||||
fn write_key_name_known_vk() {
|
||||
let mut buf = [0u8; KEY_NAME_BUF];
|
||||
let mut len = 0u8;
|
||||
write_key_name(&mut buf, &mut len, 0x41);
|
||||
assert_eq!(&buf[..len as usize], b"A");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_key_name_function_keys() {
|
||||
let mut buf = [0u8; KEY_NAME_BUF];
|
||||
let mut len = 0u8;
|
||||
write_key_name(&mut buf, &mut len, 0x7b);
|
||||
assert_eq!(&buf[..len as usize], b"F12");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_key_name_from_hook_distinguishes_keypad_navigation() {
|
||||
let mut buf = [0u8; KEY_NAME_BUF];
|
||||
let mut len = 0u8;
|
||||
|
||||
write_key_name_from_hook(&mut buf, &mut len, 0x2d, 0);
|
||||
assert_eq!(&buf[..len as usize], b"Numpad0");
|
||||
|
||||
buf = [0u8; KEY_NAME_BUF];
|
||||
len = 0;
|
||||
write_key_name_from_hook(&mut buf, &mut len, 0x2d, LLKHF_EXTENDED_FLAG);
|
||||
assert_eq!(&buf[..len as usize], b"Insert");
|
||||
|
||||
buf = [0u8; KEY_NAME_BUF];
|
||||
len = 0;
|
||||
write_key_name_from_hook(&mut buf, &mut len, 0x0d, LLKHF_EXTENDED_FLAG);
|
||||
assert_eq!(&buf[..len as usize], b"NumpadEnter");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_key_name_fallback() {
|
||||
let mut buf = [0u8; KEY_NAME_BUF];
|
||||
let mut len = 0u8;
|
||||
write_key_name(&mut buf, &mut len, 0x0fff);
|
||||
assert_eq!(&buf[..len as usize], b"Key4095");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queued_event_default_is_mouse_move_kind() {
|
||||
let event = QueuedEvent::default();
|
||||
assert_eq!(event.kind, EventKind::MouseMove);
|
||||
assert_eq!(event.key_name_len, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn event_kind_strings_match_contract() {
|
||||
assert_eq!(EventKind::KeyDown.as_str(), "keydown");
|
||||
assert_eq!(EventKind::KeyUp.as_str(), "keyup");
|
||||
assert_eq!(EventKind::MouseDown.as_str(), "mousedown");
|
||||
assert_eq!(EventKind::MouseUp.as_str(), "mouseup");
|
||||
assert_eq!(EventKind::MouseMove.as_str(), "mousemove");
|
||||
assert_eq!(EventKind::Wheel.as_str(), "wheel");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_available_matches_target() {
|
||||
assert_eq!(is_available(), cfg!(target_os = "windows"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ring_holds_queued_events() {
|
||||
let ring: Ring<QueuedEvent, 4> = Ring::new();
|
||||
let idx = ring.claim().expect("claim slot") as usize;
|
||||
|
||||
unsafe {
|
||||
let slots = ring.slots.as_ptr() as *mut QueuedEvent;
|
||||
(*slots.add(idx)).kind = EventKind::Wheel;
|
||||
(*slots.add(idx)).delta_y = 120;
|
||||
}
|
||||
let pop_idx = ring.pop().expect("pop slot") as usize;
|
||||
assert_eq!(ring.slots[pop_idx].kind, EventKind::Wheel);
|
||||
assert_eq!(ring.slots[pop_idx].delta_y, 120);
|
||||
ring.release();
|
||||
assert!(ring.pop().is_none());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user