kanata-parser-0.190.0/.cargo_vcs_info.json0000644000000001440000000000100137330ustar { "git": { "sha1": "b111e370d2ec9fcff17a8a5193a1dbee775b88d9" }, "path_in_vcs": "parser" }kanata-parser-0.190.0/.gitignore000064400000000000000000000001031046102023000145060ustar 00000000000000# Ignore Cargo.lock since this is a library crate Cargo.lock targetkanata-parser-0.190.0/Cargo.lock0000644000000464070000000000100117220ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 4 [[package]] name = "addr2line" version = "0.24.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dfbe277e56a376000877090da837660b4427aad530e3028d44e0bffe4f89a1c1" dependencies = [ "gimli", ] [[package]] name = "adler2" version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "512761e0bb2578dd7380c6baaa0f4ce03e84f95e960231d1dec8bf4d7d6e2627" [[package]] name = "anyhow" version = "1.0.91" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c042108f3ed77fd83760a5fd79b53be043192bb3b9dba91d8c574c0ada7850c8" [[package]] name = "arraydeque" version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d902e3d592a523def97af8f317b08ce16b7ab854c1985a0c671e6f15cebc236" [[package]] name = "atomic-polyfill" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8cf2bce30dfe09ef0bfaef228b9d414faaf7e563035494d7fe092dba54b300f4" dependencies = [ "critical-section", ] [[package]] name = "autocfg" version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" [[package]] name = "backtrace" version = "0.3.74" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8d82cb332cdfaed17ae235a638438ac4d4839913cc2af585c3c6746e8f8bee1a" dependencies = [ "addr2line", "cfg-if", "libc", "miniz_oxide", "object", "rustc-demangle", "windows-targets", ] [[package]] name = "backtrace-ext" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "537beee3be4a18fb023b570f80e3ae28003db9167a751266b259926e25539d50" dependencies = [ "backtrace", ] [[package]] name = "bitflags" version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de" [[package]] name = "bytemuck" version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8334215b81e418a0a7bdb8ef0849474f40bb10c8b71f1c4ed315cff49f32494d" [[package]] name = "byteorder" version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "critical-section" version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" [[package]] name = "deranged" version = "0.3.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b42b6fa04a440b495c8b04d0e71b707c585f83cb9cb28cf8cd0d976c315e31b4" dependencies = [ "powerfmt", ] [[package]] name = "either" version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0" [[package]] name = "gimli" version = "0.31.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f" [[package]] name = "hash32" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b0c35f58762feb77d74ebe43bdbc3210f09be9fe6742234d573bacc26ed92b67" dependencies = [ "byteorder", ] [[package]] name = "heapless" version = "0.7.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cdc6457c0eb62c71aac4bc17216026d8410337c4126773b9c5daba343f17964f" dependencies = [ "atomic-polyfill", "hash32", "rustc_version", "spin", "stable_deref_trait", ] [[package]] name = "hermit-abi" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fbf6a919d6cf397374f7dfeeea91d974c7c0a7221d0d0f4f20d859d329e53fcc" [[package]] name = "is-terminal" version = "0.4.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "261f68e344040fbd0edea105bef17c66edf46f984ddb1115b775ce31be948f4b" dependencies = [ "hermit-abi", "libc", "windows-sys 0.52.0", ] [[package]] name = "is_ci" version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7655c9839580ee829dfacba1d1278c2b7883e50a277ff7541299489d6bdfdc45" [[package]] name = "itertools" version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569" dependencies = [ "either", ] [[package]] name = "itoa" version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" [[package]] name = "kanata-keyberon" version = "0.190.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bc5ef0641559249e72d2d4675bdbb5060b729f024fe4c01d704c3ef390e5de1d" dependencies = [ "arraydeque", "heapless", "kanata-keyberon-macros", "rustc-hash", ] [[package]] name = "kanata-keyberon-macros" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "73f6f83f03390a5c13bbf68abea76a2b9527e197f5c00026805fd7af62a34752" dependencies = [ "proc-macro2", "quote", ] [[package]] name = "kanata-parser" version = "0.190.0" dependencies = [ "anyhow", "bitflags", "bytemuck", "itertools", "kanata-keyberon", "log", "miette", "once_cell", "parking_lot", "patricia_tree", "rustc-hash", "simplelog", "thiserror", ] [[package]] name = "libc" version = "0.2.161" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9489c2807c139ffd9c1794f4af0ebe86a828db53ecdc7fea2111d0fed085d1" [[package]] name = "lock_api" version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17" dependencies = [ "autocfg", "scopeguard", ] [[package]] name = "log" version = "0.4.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" [[package]] name = "memchr" version = "2.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" [[package]] name = "miette" version = "5.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "59bb584eaeeab6bd0226ccf3509a69d7936d148cf3d036ad350abe35e8c6856e" dependencies = [ "backtrace", "backtrace-ext", "is-terminal", "miette-derive", "once_cell", "owo-colors", "supports-color", "supports-hyperlinks", "supports-unicode", "terminal_size", "textwrap", "thiserror", "unicode-width", ] [[package]] name = "miette-derive" version = "5.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49e7bc1560b95a3c4a25d03de42fe76ca718ab92d1a22a55b9b4cf67b3ae635c" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "miniz_oxide" version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2d80299ef12ff69b16a84bb182e3b9df68b5a91574d3d4fa6e41b65deec4df1" dependencies = [ "adler2", ] [[package]] name = "num-conv" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" [[package]] name = "num_threads" version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c7398b9c8b70908f6371f47ed36737907c87c52af34c268fed0bf0ceb92ead9" dependencies = [ "libc", ] [[package]] name = "object" version = "0.36.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aedf0a2d09c573ed1d8d85b30c119153926a2b36dce0ab28322c09a117a4683e" dependencies = [ "memchr", ] [[package]] name = "once_cell" version = "1.20.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1261fe7e33c73b354eab43b1273a57c8f967d0391e80353e51f764ac02cf6775" [[package]] name = "owo-colors" version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1b04fb49957986fdce4d6ee7a65027d55d4b6d2265e5848bbb507b58ccfdb6f" [[package]] name = "parking_lot" version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27" dependencies = [ "lock_api", "parking_lot_core", ] [[package]] name = "parking_lot_core" version = "0.9.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" dependencies = [ "cfg-if", "libc", "redox_syscall", "smallvec", "windows-targets", ] [[package]] name = "patricia_tree" version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "31f2f4539bffe53fc4b4da301df49d114b845b077bd5727b7fe2bd9d8df2ae68" dependencies = [ "bitflags", ] [[package]] name = "powerfmt" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" [[package]] name = "proc-macro2" version = "1.0.89" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f139b0662de085916d1fb67d2b4169d1addddda1919e696f3252b740b629986e" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.37" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af" dependencies = [ "proc-macro2", ] [[package]] name = "redox_syscall" version = "0.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b6dfecf2c74bce2466cabf93f6664d6998a69eb21e39f4207930065b27b771f" dependencies = [ "bitflags", ] [[package]] name = "rustc-demangle" version = "0.1.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" [[package]] name = "rustc-hash" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" [[package]] name = "rustc_version" version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" dependencies = [ "semver", ] [[package]] name = "scopeguard" version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" [[package]] name = "semver" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "61697e0a1c7e512e84a621326239844a24d8207b4669b41bc18b32ea5cbf988b" [[package]] name = "serde" version = "1.0.213" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ea7893ff5e2466df8d720bb615088341b295f849602c6956047f8f80f0e9bc1" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.213" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7e85ad2009c50b58e87caa8cd6dac16bdf511bbfb7af6c33df902396aa480fa5" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "simplelog" version = "0.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "16257adbfaef1ee58b1363bdc0664c9b8e1e30aed86049635fb5f147d065a9c0" dependencies = [ "log", "termcolor", "time", ] [[package]] name = "smallvec" version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" [[package]] name = "smawk" version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7c388c1b5e93756d0c740965c41e8822f866621d41acbdf6336a6a168f8840c" [[package]] name = "spin" version = "0.9.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" dependencies = [ "lock_api", ] [[package]] name = "stable_deref_trait" version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" [[package]] name = "supports-color" version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6398cde53adc3c4557306a96ce67b302968513830a77a95b2b17305d9719a89" dependencies = [ "is-terminal", "is_ci", ] [[package]] name = "supports-hyperlinks" version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f84231692eb0d4d41e4cdd0cabfdd2e6cd9e255e65f80c9aa7c98dd502b4233d" dependencies = [ "is-terminal", ] [[package]] name = "supports-unicode" version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f850c19edd184a205e883199a261ed44471c81e39bd95b1357f5febbef00e77a" dependencies = [ "is-terminal", ] [[package]] name = "syn" version = "2.0.85" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5023162dfcd14ef8f32034d8bcd4cc5ddc61ef7a247c024a33e24e1f24d21b56" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "termcolor" version = "1.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" dependencies = [ "winapi-util", ] [[package]] name = "terminal_size" version = "0.1.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "633c1a546cee861a1a6d0dc69ebeca693bf4296661ba7852b9d21d159e0506df" dependencies = [ "libc", "winapi", ] [[package]] name = "textwrap" version = "0.15.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7b3e525a49ec206798b40326a44121291b530c963cfb01018f63e135bac543d" dependencies = [ "smawk", "unicode-linebreak", "unicode-width", ] [[package]] name = "thiserror" version = "1.0.65" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d11abd9594d9b38965ef50805c5e469ca9cc6f197f883f717e0269a3057b3d5" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" version = "1.0.65" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae71770322cbd277e69d762a16c444af02aa0575ac0d174f0b9562d3b37f8602" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "time" version = "0.3.36" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5dfd88e563464686c916c7e46e623e520ddc6d79fa6641390f2e3fa86e83e885" dependencies = [ "deranged", "itoa", "libc", "num-conv", "num_threads", "powerfmt", "serde", "time-core", "time-macros", ] [[package]] name = "time-core" version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3" [[package]] name = "time-macros" version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f252a68540fde3a3877aeea552b832b40ab9a69e318efd078774a01ddee1ccf" dependencies = [ "num-conv", "time-core", ] [[package]] name = "unicode-ident" version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e91b56cd4cadaeb79bbf1a5645f6b4f8dc5bde8834ad5894a8db35fda9efa1fe" [[package]] name = "unicode-linebreak" version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f" [[package]] name = "unicode-width" version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" [[package]] name = "winapi" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" dependencies = [ "winapi-i686-pc-windows-gnu", "winapi-x86_64-pc-windows-gnu", ] [[package]] name = "winapi-i686-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-util" version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb" dependencies = [ "windows-sys 0.59.0", ] [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "windows-sys" version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ "windows-targets", ] [[package]] name = "windows-sys" version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" dependencies = [ "windows-targets", ] [[package]] name = "windows-targets" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ "windows_aarch64_gnullvm", "windows_aarch64_msvc", "windows_i686_gnu", "windows_i686_gnullvm", "windows_i686_msvc", "windows_x86_64_gnu", "windows_x86_64_gnullvm", "windows_x86_64_msvc", ] [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" [[package]] name = "windows_i686_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" [[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" kanata-parser-0.190.0/Cargo.toml0000644000000033430000000000100117350ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" name = "kanata-parser" version = "0.190.0" authors = ["jtroo "] build = false autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "A parser for configuration language of kanata, a keyboard remapper." homepage = "https://github.com/jtroo/kanata" readme = "README.md" keywords = [ "kanata", "parser", ] license = "LGPL-3.0-only" repository = "https://github.com/jtroo/kanata" [features] cmd = [] gui = [] interception_driver = [] lsp = [] win_llhook_read_scancodes = [] win_sendinput_send_scancodes = [] zippychord = [] [lib] name = "kanata_parser" path = "src/lib.rs" [dependencies.anyhow] version = "1" [dependencies.bitflags] version = "2.5.0" [dependencies.bytemuck] version = "1.15.0" [dependencies.itertools] version = "0.12" [dependencies.kanata-keyberon] version = "0.190.0" [dependencies.log] version = "0.4.8" default-features = false [dependencies.miette] version = "5.7.0" features = ["fancy"] [dependencies.once_cell] version = "1" [dependencies.parking_lot] version = "0.12" [dependencies.patricia_tree] version = "0.8" [dependencies.rustc-hash] version = "1.1.0" [dependencies.thiserror] version = "1.0.38" [dev-dependencies.simplelog] version = "0.12.0" kanata-parser-0.190.0/Cargo.toml.orig000064400000000000000000000016241046102023000154160ustar 00000000000000[package] name = "kanata-parser" version = "0.190.0" authors = ["jtroo "] description = "A parser for configuration language of kanata, a keyboard remapper." keywords = ["kanata", "parser"] homepage = "https://github.com/jtroo/kanata" repository = "https://github.com/jtroo/kanata" readme = "README.md" license = "LGPL-3.0-only" edition = "2021" [dependencies] anyhow = "1" bitflags = "2.5.0" bytemuck = "1.15.0" itertools = "0.12" log = { version = "0.4.8", default-features = false } miette = { version = "5.7.0", features = ["fancy"] } once_cell = "1" parking_lot = "0.12" patricia_tree = "0.8" rustc-hash = "1.1.0" thiserror = "1.0.38" kanata-keyberon = { path = "../keyberon", version = "0.190.0" } [dev-dependencies] simplelog = "0.12.0" [features] cmd = [] interception_driver = [] gui = [] lsp = [] win_llhook_read_scancodes = [] win_sendinput_send_scancodes = [] zippychord = [] kanata-parser-0.190.0/LICENSE000064400000000000000000000167431046102023000135440ustar 00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library.kanata-parser-0.190.0/README.md000064400000000000000000000002501046102023000140000ustar 00000000000000# kanata-parser A parser for configuration language of [kanata](https://github.com/jtroo/kanata). This crate does not follow semver. It tracks the version of kanata. kanata-parser-0.190.0/src/cfg/alloc.rs000064400000000000000000000052651046102023000155220ustar 00000000000000//! This module contains a helper struct for generating 'static lifetime allocations while still //! keeping track of them so that they can be freed later. use parking_lot::Mutex; use std::sync::Arc; /// This struct tracks the allocations that are leaked by its provided methods and frees them when /// dropped. The `new` function is unsafe because dropping the struct can create dangling /// references. Care must be taken to ensure that all allocations made by this struct's methods are /// no longer referenced when the struct gets dropped. /// /// In practice, this is not difficult to do in the `cfg` module which only exposes a single public /// method. pub(crate) struct Allocations { allocations: Mutex>, } impl std::fmt::Debug for Allocations { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Allocations").finish() } } impl Drop for Allocations { fn drop(&mut self) { log::debug!( "freeing allocations of length {}", self.allocations.lock().len() ); for p in self.allocations.lock().iter().rev().copied() { unsafe { drop(Box::from_raw(p as *mut usize)) }; } } } impl Allocations { /// Create a new allocations group. /// /// # Safety /// /// Ensure that all associated allocations are no longer referenced before dropping all /// clones of the `Arc`. pub(crate) unsafe fn new() -> Arc { Arc::new(Self { allocations: Mutex::new(vec![]), }) } /// Returns a `&'static T` by leaking a newly created Box of `v`. pub(crate) fn sref(&self, v: T) -> &'static T { let p = Box::into_raw(Box::new(v)); if (p as usize) < 16 { panic!("sref bad ptr"); } self.allocations.lock().push(p as usize); Box::leak(unsafe { Box::from_raw(p) }) } pub(crate) fn bref_slice(&self, v: Box<[T]>) -> &'static [T] { // An empty slice has no backing allocation. `Box<[T]>` is a fat pointer so the leaked return // will contain a length of 0 and an invalid pointer. if !v.is_empty() { self.allocations.lock().push(v.as_ptr() as usize); } Box::leak(v) } /// Returns a &'static [&'static T] from a `Vec` by converting to a boxed slice and leaking it. pub(crate) fn sref_vec(&self, v: Vec) -> &'static [T] { self.bref_slice(v.into_boxed_slice()) } /// Returns a `&'static [&'static T]` by leaking a newly created box and boxed slice of `v`. pub(crate) fn sref_slice(&self, v: T) -> &'static [&'static T] { self.bref_slice(vec![self.sref(v)].into_boxed_slice()) } } kanata-parser-0.190.0/src/cfg/chord.rs000064400000000000000000000264651046102023000155340ustar 00000000000000use itertools::Itertools; use kanata_keyberon::chord::{ChordV2, ChordsForKey, ChordsForKeys, ReleaseBehaviour}; use rustc_hash::{FxHashMap, FxHashSet}; use std::fs; use crate::{anyhow_expr, bail_expr}; use super::*; pub(crate) fn parse_defchordv2( exprs: &[SExpr], s: &ParserState, ) -> Result> { if exprs[0].atom(None).expect("should be atom") == "defchordsv2-experimental" { log::warn!( "You should replace defchordsv2-experimental with defchordsv2.\n\ Using -experimental will be invalid in the future." ); } let mut chunks = exprs[1..].chunks_exact(5); let mut chords_container = ChordsForKeys::<'static, KanataCustom> { mapping: FxHashMap::default(), }; let mut all_participating_key_sets = FxHashSet::default(); let all_chords = chunks .by_ref() .flat_map(|chunk| match chunk[0] { // Match a line like // (include filename.txt) () 100 all-released (layer1 layer2) SExpr::List(Spanned { t: ref exprs, span: _, }) if matches!(exprs.first(), Some(SExpr::Atom(a)) if a.t == "include") => { let file_name = exprs[1].atom(s.vars()).unwrap(); let chord_translation = ChordTranslation::create( file_name, &chunk[2], &chunk[3], &chunk[4], &s.layers[0][0], ); let chord_definitions = parse_chord_file(file_name).unwrap(); let processed = chord_definitions.iter().map(|chord_def| { let chunk = chord_translation.translate_chord(chord_def); parse_single_chord(&chunk, s, &mut all_participating_key_sets) }); Ok::<_, ParseError>(processed.collect_vec()) } _ => Ok(vec![parse_single_chord( chunk, s, &mut all_participating_key_sets, )]), }) .flat_map(|vec_result| vec_result.into_iter()) .collect::>>(); let unsuccessful = all_chords .iter() .filter_map(|r| r.as_ref().err()) .collect::>(); if let Some(e) = unsuccessful.first() { return Err((*e).clone()); } let successful = all_chords.into_iter().filter_map(Result::ok).collect_vec(); for chord in successful { for pkey in chord.participating_keys.iter().copied() { //log::trace!("chord for key:{pkey:?} > {chord:?}"); chords_container .mapping .entry(pkey) .or_insert(ChordsForKey { chords: vec![] }) .chords .push(s.a.sref(chord.clone())); } } let rem = chunks.remainder(); if !rem.is_empty() { bail_expr!( rem.last().unwrap(), "Incomplete chord entry. Each chord entry must have 5 items:\n\ particpating-keys, action, timeout, release-type, disabled-layers" ); } Ok(chords_container) } fn parse_single_chord( chunk: &[SExpr], s: &ParserState, all_participating_key_sets: &mut FxHashSet>, ) -> Result> { let participants = parse_participating_keys(&chunk[0], s)?; if !all_participating_key_sets.insert(participants.clone()) { bail_expr!( &chunk[0], "Duplicate participating-keys, key sets may be used only once." ); } let action = parse_action(&chunk[1], s)?; let timeout = parse_timeout(&chunk[2], s)?; let release_behaviour = parse_release_behaviour(&chunk[3], s)?; let disabled_layers = parse_disabled_layers(&chunk[4], s)?; let chord: ChordV2<'static, KanataCustom> = ChordV2 { action, participating_keys: s.a.sref_vec(participants.clone()), pending_duration: timeout, disabled_layers: s.a.sref_vec(disabled_layers), release_behaviour, }; Ok(s.a.sref(chord).clone()) } fn parse_participating_keys(keys: &SExpr, s: &ParserState) -> Result> { let mut participants = keys .list(s.vars()) .map(|l| { l.iter() .try_fold(vec![], |mut keys, key| -> Result> { let k = key.atom(s.vars()).and_then(str_to_oscode).ok_or_else(|| { anyhow_expr!( key, "The first chord item must be a list of keys.\nInvalid key name." ) })?; keys.push(k.into()); Ok(keys) }) }) .ok_or_else(|| anyhow_expr!(keys, "The first chord item must be a list of keys."))??; if participants.len() < 2 { bail_expr!(keys, "The minimum number of participating chord keys is 2"); } participants.sort(); Ok(participants) } fn parse_timeout(chunk: &SExpr, s: &ParserState) -> Result { let timeout = parse_non_zero_u16(chunk, s, "chord timeout")?; Ok(timeout) } fn parse_release_behaviour( release_behaviour_string: &SExpr, s: &ParserState, ) -> Result { let release_behaviour = release_behaviour_string .atom(s.vars()) .and_then(|r| { Some(match r { "first-release" => ReleaseBehaviour::OnFirstRelease, "all-released" => ReleaseBehaviour::OnLastRelease, _ => return None, }) }) .ok_or_else(|| { anyhow_expr!( release_behaviour_string, "Chord release behaviour must be one of:\n\ first-release | all-released" ) })?; Ok(release_behaviour) } fn parse_disabled_layers(disabled_layers: &SExpr, s: &ParserState) -> Result> { let disabled_layers = disabled_layers .list(s.vars()) .map(|dl| { dl.iter() .try_fold(vec![], |mut layers, layer| -> Result> { let l_idx = layer .atom(s.vars()) .and_then(|l| s.layer_idxs.get(l)) .ok_or_else(|| anyhow_expr!(layer, "Not a known layer name."))?; layers.push((*l_idx) as u16); Ok(layers) }) }) .ok_or_else(|| { anyhow_expr!( disabled_layers, "Disabled layers must be a list of layer names" ) })??; Ok(disabled_layers) } fn parse_chord_file(file_name: &str) -> Result> { let input_data = fs::read_to_string(file_name) .unwrap_or_else(|_| panic!("Unable to read file {}", file_name)); let parsed_chords = parse_input(&input_data).unwrap(); Ok(parsed_chords) } fn parse_input(input: &str) -> Result> { input .lines() .filter(|line| !line.trim().is_empty() && !line.trim().starts_with("//")) .map(|line| { let mut caps = line.split('\t'); let error_message = format!( "Each line needs to have an action separated by a tab character, got '{}'", line ); let keys = caps.next().expect(&error_message); let action = caps.next().expect(&error_message); Ok(ChordDefinition { keys: keys.to_string(), action: action.to_string(), }) }) .collect() } #[derive(Debug)] struct ChordDefinition { keys: String, action: String, } struct ChordTranslation<'a> { file_name: &'a str, target_map: FxHashMap, postprocess_map: FxHashMap, timeout: &'a SExpr, release_behaviour: &'a SExpr, disabled_layers: &'a SExpr, } impl<'a> ChordTranslation<'a> { fn create( file_name: &'a str, timeout: &'a SExpr, release_behaviour: &'a SExpr, disabled_layers: &'a SExpr, first_layer: &[Action<'static, &&[&CustomAction]>], ) -> Self { let postprocess_map: FxHashMap = [ ("semicolon", ";"), ("colon", "S-."), ("slash", "/"), ("apostrophe", "'"), ("dot", "."), (" ", "spc"), ] .iter() .cloned() .map(|(k, v)| (k.to_string(), v.to_string())) .collect(); let target_map = first_layer .iter() .enumerate() .filter_map(|(idx, layout)| { layout .key_codes() .next() .map(|kc| kc.to_string().to_lowercase()) .zip( idx.try_into() .ok() .and_then(OsCode::from_u16) .map(|osc| osc.to_string().to_lowercase()), ) }) .collect::>() .into_iter() .chain(vec![(" ".to_string(), "spc".to_string())]) .collect::>(); ChordTranslation { file_name, target_map, postprocess_map, timeout, release_behaviour, disabled_layers, } } fn post_process(&self, converted: &str) -> String { self.postprocess_map .get(converted) .map(|c| c.to_string()) .unwrap_or_else(|| { if converted.chars().all(|c| c.is_uppercase()) { format!("S-{}", converted.to_lowercase()) } else { converted.to_string() } }) } fn participant_keys(&self, keys: &str) -> Vec { keys.chars() .map(|key| { self.target_map .get(key.to_string().to_lowercase().as_str()) .map(|c| self.postprocess_map.get(c).unwrap_or(c).to_string()) .unwrap_or_else(|| key.to_string()) }) .collect::>() } fn action(&self, action: &str) -> Vec { let mut action_strings = action .chars() .map(|c| self.post_process(&c.to_string())) .collect_vec(); // Wait 50ms for one-shot Shift to release // TODO: This would be better handled by a (multi (release-key lsft)(release-key rsft)) // but I haven't gotten that to work yet. action_strings.insert(1, "50".to_string()); action_strings.extend_from_slice(&[ "sldr".to_string(), "spc".to_string(), "nop0".to_string(), ]); action_strings } fn translate_chord(&self, chord_def: &ChordDefinition) -> Vec { let sexpr_string = format!( "(({}) (macro {}))", self.participant_keys(&chord_def.keys).join(" "), self.action(&chord_def.action).join(" ") ); let mut participant_action = sexpr::parse(&sexpr_string, self.file_name).unwrap()[0] .t .clone(); participant_action.extend_from_slice(&[ self.timeout.clone(), self.release_behaviour.clone(), self.disabled_layers.clone(), ]); participant_action } } kanata-parser-0.190.0/src/cfg/custom_tap_hold.rs000064400000000000000000000044061046102023000176100ustar 00000000000000use kanata_keyberon::layout::{Event, QueuedIter, WaitingAction}; use crate::keys::OsCode; use super::alloc::Allocations; /// Returns a closure that can be used in `HoldTapConfig::Custom`, which will return early with a /// Tap action in the case that any of `keys` are pressed. Otherwise it behaves as /// `HoldTapConfig::PermissiveHold` would. pub(crate) fn custom_tap_hold_release( keys: &[OsCode], a: &Allocations, ) -> &'static (dyn Fn(QueuedIter) -> (Option, bool) + Send + Sync) { let keys = a.sref_vec(Vec::from_iter(keys.iter().copied())); a.sref( move |mut queued: QueuedIter| -> (Option, bool) { while let Some(q) = queued.next() { if q.event().is_press() { let (i, j) = q.event().coord(); // If any key matches the input, do a tap right away. if keys.iter().copied().map(u16::from).any(|j2| j2 == j) { return (Some(WaitingAction::Tap), false); } // Otherwise do the PermissiveHold algorithm. let target = Event::Release(i, j); if queued.clone().copied().any(|q| q.event() == target) { return (Some(WaitingAction::Hold), false); } } } (None, false) }, ) } pub(crate) fn custom_tap_hold_except( keys: &[OsCode], a: &Allocations, ) -> &'static (dyn Fn(QueuedIter) -> (Option, bool) + Send + Sync) { let keys = a.sref_vec(Vec::from_iter(keys.iter().copied())); a.sref( move |mut queued: QueuedIter| -> (Option, bool) { for q in queued.by_ref() { if q.event().is_press() { let (_i, j) = q.event().coord(); // If any key matches the input, do a tap. if keys.iter().copied().map(u16::from).any(|j2| j2 == j) { return (Some(WaitingAction::Tap), false); } // Otherwise continue with default behavior return (None, false); } } // Otherwise skip timeout (None, true) }, ) } kanata-parser-0.190.0/src/cfg/defcfg.rs000064400000000000000000001356001046102023000156430ustar 00000000000000use super::sexpr::SExpr; use super::HashSet; use super::{error::*, TrimAtomQuotes}; use crate::cfg::check_first_expr; use crate::custom_action::*; use crate::keys::*; #[allow(unused)] use crate::{anyhow_expr, anyhow_span, bail, bail_expr, bail_span}; #[cfg(any(target_os = "linux", target_os = "unknown"))] #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum DeviceDetectMode { KeyboardOnly, KeyboardMice, Any, } #[cfg(any(target_os = "linux", target_os = "unknown"))] impl std::fmt::Display for DeviceDetectMode { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{:?}", self) } } #[cfg(any(target_os = "linux", target_os = "unknown"))] #[derive(Debug, Clone)] pub struct CfgLinuxOptions { pub linux_dev: Vec, pub linux_dev_names_include: Option>, pub linux_dev_names_exclude: Option>, pub linux_continue_if_no_devs_found: bool, pub linux_unicode_u_code: crate::keys::OsCode, pub linux_unicode_termination: UnicodeTermination, pub linux_x11_repeat_delay_rate: Option, pub linux_use_trackpoint_property: bool, pub linux_output_name: String, pub linux_output_bus_type: LinuxCfgOutputBusType, pub linux_device_detect_mode: Option, } #[cfg(any(target_os = "linux", target_os = "unknown"))] impl Default for CfgLinuxOptions { fn default() -> Self { Self { linux_dev: vec![], linux_dev_names_include: None, linux_dev_names_exclude: None, linux_continue_if_no_devs_found: false, // historically was the only option, so make KEY_U the default linux_unicode_u_code: crate::keys::OsCode::KEY_U, // historically was the only option, so make Enter the default linux_unicode_termination: UnicodeTermination::Enter, linux_x11_repeat_delay_rate: None, linux_use_trackpoint_property: false, linux_output_name: "kanata".to_owned(), linux_output_bus_type: LinuxCfgOutputBusType::BusI8042, linux_device_detect_mode: None, } } } #[cfg(any(target_os = "linux", target_os = "unknown"))] #[derive(Debug, Clone, Copy)] pub enum LinuxCfgOutputBusType { BusUsb, BusI8042, } #[cfg(any(target_os = "macos", target_os = "unknown"))] #[derive(Debug, Default, Clone)] pub struct CfgMacosOptions { pub macos_dev_names_include: Option>, pub macos_dev_names_exclude: Option>, } #[cfg(any( all(feature = "interception_driver", target_os = "windows"), target_os = "unknown" ))] #[derive(Debug, Clone, Default)] pub struct CfgWinterceptOptions { pub windows_interception_mouse_hwids: Option>, pub windows_interception_mouse_hwids_exclude: Option>, pub windows_interception_keyboard_hwids: Option>, pub windows_interception_keyboard_hwids_exclude: Option>, } #[cfg(any(target_os = "windows", target_os = "unknown"))] #[derive(Debug, Clone, Default)] pub struct CfgWindowsOptions { pub windows_altgr: AltGrBehaviour, pub sync_keystates: bool, } #[cfg(all(any(target_os = "windows", target_os = "unknown"), feature = "gui"))] #[derive(Debug, Clone)] pub struct CfgOptionsGui { /// File name / path to the tray icon file. pub tray_icon: Option, /// Whether to match layer names to icon files without an explicit 'icon' field pub icon_match_layer_name: bool, /// Show tooltip on layer changes showing layer icons pub tooltip_layer_changes: bool, /// Show tooltip on layer changes for the default/base layer pub tooltip_no_base: bool, /// Show tooltip on layer changes even for layers without an icon pub tooltip_show_blank: bool, /// Show tooltip on layer changes for this duration (ms) pub tooltip_duration: u16, /// Show system notification message on config reload pub notify_cfg_reload: bool, /// Disable sound for the system notification message on config reload pub notify_cfg_reload_silent: bool, /// Show system notification message on errors pub notify_error: bool, /// Set tooltip size (width, height) pub tooltip_size: (u16, u16), } #[cfg(all(any(target_os = "windows", target_os = "unknown"), feature = "gui"))] impl Default for CfgOptionsGui { fn default() -> Self { Self { tray_icon: None, icon_match_layer_name: true, tooltip_layer_changes: false, tooltip_show_blank: false, tooltip_no_base: true, tooltip_duration: 500, notify_cfg_reload: true, notify_cfg_reload_silent: false, notify_error: true, tooltip_size: (24, 24), } } } #[derive(Debug)] pub struct CfgOptions { pub process_unmapped_keys: bool, pub process_unmapped_keys_exceptions: Option>, pub block_unmapped_keys: bool, pub allow_hardware_repeat: bool, pub start_alias: Option, pub enable_cmd: bool, pub sequence_timeout: u16, pub sequence_input_mode: SequenceInputMode, pub sequence_backtrack_modcancel: bool, pub sequence_always_on: bool, pub log_layer_changes: bool, pub delegate_to_first_layer: bool, pub movemouse_inherit_accel_state: bool, pub movemouse_smooth_diagonals: bool, pub override_release_on_activation: bool, pub dynamic_macro_max_presses: u16, pub dynamic_macro_replay_delay_behaviour: ReplayDelayBehaviour, pub concurrent_tap_hold: bool, pub rapid_event_delay: u16, pub trans_resolution_behavior_v2: bool, pub chords_v2_min_idle: u16, #[cfg(any( all(target_os = "windows", feature = "interception_driver"), target_os = "linux", target_os = "unknown" ))] pub mouse_movement_key: Option, #[cfg(any(target_os = "linux", target_os = "unknown"))] pub linux_opts: CfgLinuxOptions, #[cfg(any(target_os = "macos", target_os = "unknown"))] pub macos_opts: CfgMacosOptions, #[cfg(any(target_os = "windows", target_os = "unknown"))] pub windows_opts: CfgWindowsOptions, #[cfg(any( all(feature = "interception_driver", target_os = "windows"), target_os = "unknown" ))] pub wintercept_opts: CfgWinterceptOptions, #[cfg(all(any(target_os = "windows", target_os = "unknown"), feature = "gui"))] pub gui_opts: CfgOptionsGui, } impl Default for CfgOptions { fn default() -> Self { Self { process_unmapped_keys: false, process_unmapped_keys_exceptions: None, block_unmapped_keys: false, allow_hardware_repeat: true, start_alias: None, enable_cmd: false, sequence_timeout: 1000, sequence_input_mode: SequenceInputMode::HiddenSuppressed, sequence_backtrack_modcancel: true, sequence_always_on: false, log_layer_changes: true, delegate_to_first_layer: false, movemouse_inherit_accel_state: false, movemouse_smooth_diagonals: false, override_release_on_activation: false, dynamic_macro_max_presses: 128, dynamic_macro_replay_delay_behaviour: ReplayDelayBehaviour::Recorded, concurrent_tap_hold: false, rapid_event_delay: 5, trans_resolution_behavior_v2: true, chords_v2_min_idle: 5, #[cfg(any( all(target_os = "windows", feature = "interception_driver"), target_os = "linux", target_os = "unknown" ))] mouse_movement_key: None, #[cfg(any(target_os = "linux", target_os = "unknown"))] linux_opts: Default::default(), #[cfg(any(target_os = "windows", target_os = "unknown"))] windows_opts: Default::default(), #[cfg(any( all(feature = "interception_driver", target_os = "windows"), target_os = "unknown" ))] wintercept_opts: Default::default(), #[cfg(any(target_os = "macos", target_os = "unknown"))] macos_opts: Default::default(), #[cfg(all(any(target_os = "windows", target_os = "unknown"), feature = "gui"))] gui_opts: Default::default(), } } } /// Parse configuration entries from an expression starting with defcfg. pub fn parse_defcfg(expr: &[SExpr]) -> Result { let mut seen_keys = HashSet::default(); let mut cfg = CfgOptions::default(); let mut exprs = check_first_expr(expr.iter(), "defcfg")?; let mut is_process_unmapped_keys_defined = false; // Read k-v pairs from the configuration loop { let key = match exprs.next() { Some(k) => k, None => { if !is_process_unmapped_keys_defined { log::warn!("The item process-unmapped-keys is not defined in defcfg. Consider whether process-unmapped-keys should be yes vs. no."); } return Ok(cfg); } }; let val = match exprs.next() { Some(v) => v, None => bail_expr!(key, "Found a defcfg option missing a value"), }; match key { SExpr::Atom(k) => { let label = k.t.as_str(); if !seen_keys.insert(label) { bail_expr!(key, "Duplicate defcfg option {}", label); } match label { "sequence-timeout" => { cfg.sequence_timeout = parse_cfg_val_u16(val, label, true)?; } "sequence-input-mode" => { let v = sexpr_to_str_or_err(val, label)?; cfg.sequence_input_mode = SequenceInputMode::try_from_str(v) .map_err(|e| anyhow_expr!(val, "{}", e.to_string()))?; } "sequence-always-on" => { cfg.sequence_always_on = parse_defcfg_val_bool(val, label)? } "dynamic-macro-max-presses" => { cfg.dynamic_macro_max_presses = parse_cfg_val_u16(val, label, false)?; } "dynamic-macro-replay-delay-behaviour" => { cfg.dynamic_macro_replay_delay_behaviour = val .atom(None) .map(|v| match v { "constant" => Ok(ReplayDelayBehaviour::Constant), "recorded" => Ok(ReplayDelayBehaviour::Recorded), _ => bail_expr!( val, "this option must be one of: constant | recorded" ), }) .ok_or_else(|| { anyhow_expr!(val, "this option must be one of: constant | recorded") })??; } "linux-dev" => { #[cfg(any(target_os = "linux", target_os = "unknown"))] { cfg.linux_opts.linux_dev = parse_dev(val)?; if cfg.linux_opts.linux_dev.is_empty() { bail_expr!( val, "device list is empty, no devices will be intercepted" ); } } } "linux-dev-names-include" => { #[cfg(any(target_os = "linux", target_os = "unknown"))] { let dev_names = parse_dev(val)?; if dev_names.is_empty() { log::warn!("linux-dev-names-include is empty"); } cfg.linux_opts.linux_dev_names_include = Some(dev_names); } } "linux-dev-names-exclude" => { #[cfg(any(target_os = "linux", target_os = "unknown"))] { cfg.linux_opts.linux_dev_names_exclude = Some(parse_dev(val)?); } } "linux-unicode-u-code" => { #[cfg(any(target_os = "linux", target_os = "unknown"))] { let v = sexpr_to_str_or_err(val, label)?; cfg.linux_opts.linux_unicode_u_code = crate::keys::str_to_oscode(v) .ok_or_else(|| { anyhow_expr!(val, "unknown code for {label}: {}", v) })?; } } "linux-unicode-termination" => { #[cfg(any(target_os = "linux", target_os = "unknown"))] { let v = sexpr_to_str_or_err(val, label)?; cfg.linux_opts.linux_unicode_termination = match v { "enter" => UnicodeTermination::Enter, "space" => UnicodeTermination::Space, "enter-space" => UnicodeTermination::EnterSpace, "space-enter" => UnicodeTermination::SpaceEnter, _ => bail_expr!( val, "{label} got {}. It accepts: enter|space|enter-space|space-enter", v ), } } } "linux-x11-repeat-delay-rate" => { #[cfg(any(target_os = "linux", target_os = "unknown"))] { let v = sexpr_to_str_or_err(val, label)?; let delay_rate = v.split(',').collect::>(); const ERRMSG: &str = "Invalid value for linux-x11-repeat-delay-rate.\nExpected two numbers 0-65535 separated by a comma, e.g. 200,25"; if delay_rate.len() != 2 { bail_expr!(val, "{}", ERRMSG) } cfg.linux_opts.linux_x11_repeat_delay_rate = Some(KeyRepeatSettings { delay: match str::parse::(delay_rate[0]) { Ok(delay) => delay, Err(_) => bail_expr!(val, "{}", ERRMSG), }, rate: match str::parse::(delay_rate[1]) { Ok(rate) => rate, Err(_) => bail_expr!(val, "{}", ERRMSG), }, }); } } "linux-use-trackpoint-property" => { #[cfg(any(target_os = "linux", target_os = "unknown"))] { cfg.linux_opts.linux_use_trackpoint_property = parse_defcfg_val_bool(val, label)? } } "linux-output-device-name" => { #[cfg(any(target_os = "linux", target_os = "unknown"))] { let device_name = sexpr_to_str_or_err(val, label)?; if device_name.is_empty() { log::warn!("linux-output-device-name is empty, using kanata as default value"); } else { cfg.linux_opts.linux_output_name = device_name.to_owned(); } } } "linux-output-device-bus-type" => { let bus_type = sexpr_to_str_or_err(val, label)?; match bus_type { "USB" | "I8042" => {}, _ => bail_expr!(val, "Invalid value for linux-output-device-bus-type.\nExpected one of: USB or I8042"), }; #[cfg(any(target_os = "linux", target_os = "unknown"))] { let bus_type = match bus_type { "USB" => LinuxCfgOutputBusType::BusUsb, "I8042" => LinuxCfgOutputBusType::BusI8042, _ => unreachable!("validated earlier"), }; cfg.linux_opts.linux_output_bus_type = bus_type; } } "linux-device-detect-mode" => { let detect_mode = sexpr_to_str_or_err(val, label)?; match detect_mode { "any" | "keyboard-only" | "keyboard-mice" => {}, _ => bail_expr!(val, "Invalid value for linux-device-detect-mode.\nExpected one of: any | keyboard-only | keyboard-mice"), }; #[cfg(any(target_os = "linux", target_os = "unknown"))] { let detect_mode = Some(match detect_mode { "any" => DeviceDetectMode::Any, "keyboard-only" => DeviceDetectMode::KeyboardOnly, "keyboard-mice" => DeviceDetectMode::KeyboardMice, _ => unreachable!("validated earlier"), }); cfg.linux_opts.linux_device_detect_mode = detect_mode; } } "windows-altgr" => { #[cfg(any(target_os = "windows", target_os = "unknown"))] { const CANCEL: &str = "cancel-lctl-press"; const ADD: &str = "add-lctl-release"; let v = sexpr_to_str_or_err(val, label)?; cfg.windows_opts.windows_altgr = match v { CANCEL => AltGrBehaviour::CancelLctlPress, ADD => AltGrBehaviour::AddLctlRelease, _ => bail_expr!( val, "Invalid value for {label}: {}. Valid values are {},{}", v, CANCEL, ADD ), } } } "windows-sync-keystates" => { #[cfg(any(target_os = "windows", target_os = "unknown"))] { cfg.windows_opts.sync_keystates = parse_defcfg_val_bool(val, label)?; } } "windows-interception-mouse-hwid" => { #[cfg(any( all(feature = "interception_driver", target_os = "windows"), target_os = "unknown" ))] { if cfg .wintercept_opts .windows_interception_mouse_hwids_exclude .is_some() { bail_expr!(val, "{label} and windows-interception-mouse-hwid-exclude cannot both be included"); } let v = sexpr_to_str_or_err(val, label)?; let hwid = v; log::trace!("win hwid: {hwid}"); let hwid_vec = hwid .split(',') .try_fold(vec![], |mut hwid_bytes, hwid_byte| { hwid_byte.trim_matches(' ').parse::().map(|b| { hwid_bytes.push(b); hwid_bytes }) }).map_err(|_| anyhow_expr!(val, "{label} format is invalid. It should consist of numbers [0,255] separated by commas"))?; let hwid_slice = hwid_vec.iter().copied().enumerate() .try_fold([0u8; HWID_ARR_SZ], |mut hwid, idx_byte| { let (i, b) = idx_byte; if i > HWID_ARR_SZ { bail_expr!(val, "{label} is too long; it should be up to {HWID_ARR_SZ} numbers [0,255]") } hwid[i] = b; Ok(hwid) })?; match cfg .wintercept_opts .windows_interception_mouse_hwids .as_mut() { Some(v) => { v.push(hwid_slice); } None => { cfg.wintercept_opts.windows_interception_mouse_hwids = Some(vec![hwid_slice]); } } cfg.wintercept_opts .windows_interception_mouse_hwids .as_mut() .unwrap() .shrink_to_fit(); } } "windows-interception-mouse-hwids" => { #[cfg(any( all(feature = "interception_driver", target_os = "windows"), target_os = "unknown" ))] { if cfg .wintercept_opts .windows_interception_mouse_hwids_exclude .is_some() { bail_expr!(val, "{label} and windows-interception-mouse-hwid-exclude cannot both be included"); } let parsed_hwids = sexpr_to_hwids_vec( val, label, "entry in windows-interception-mouse-hwids", )?; match cfg .wintercept_opts .windows_interception_mouse_hwids .as_mut() { Some(v) => { v.extend(parsed_hwids); } None => { cfg.wintercept_opts.windows_interception_mouse_hwids = Some(parsed_hwids); } } cfg.wintercept_opts .windows_interception_mouse_hwids .as_mut() .unwrap() .shrink_to_fit(); } } "windows-interception-mouse-hwids-exclude" => { #[cfg(any( all(feature = "interception_driver", target_os = "windows"), target_os = "unknown" ))] { if cfg .wintercept_opts .windows_interception_mouse_hwids .is_some() { bail_expr!(val, "{label} and windows-interception-mouse-hwid(s) cannot both be used"); } let parsed_hwids = sexpr_to_hwids_vec( val, label, "entry in windows-interception-mouse-hwids-exclude", )?; cfg.wintercept_opts.windows_interception_mouse_hwids_exclude = Some(parsed_hwids); } } "windows-interception-keyboard-hwids" => { #[cfg(any( all(feature = "interception_driver", target_os = "windows"), target_os = "unknown" ))] { if cfg .wintercept_opts .windows_interception_keyboard_hwids_exclude .is_some() { bail_expr!(val, "{label} and windows-interception-keyboard-hwid-exclude cannot both be used"); } let parsed_hwids = sexpr_to_hwids_vec( val, label, "entry in windows-interception-keyboard-hwids", )?; cfg.wintercept_opts.windows_interception_keyboard_hwids = Some(parsed_hwids); } } "windows-interception-keyboard-hwids-exclude" => { #[cfg(any( all(feature = "interception_driver", target_os = "windows"), target_os = "unknown" ))] { if cfg .wintercept_opts .windows_interception_keyboard_hwids .is_some() { bail_expr!(val, "{label} and windows-interception-keyboard-hwid cannot both be used"); } let parsed_hwids = sexpr_to_hwids_vec( val, label, "entry in windows-interception-keyboard-hwids-exclude", )?; cfg.wintercept_opts .windows_interception_keyboard_hwids_exclude = Some(parsed_hwids); } } "macos-dev-names-include" => { #[cfg(any(target_os = "macos", target_os = "unknown"))] { let dev_names = parse_dev(val)?; if dev_names.is_empty() { log::warn!("macos-dev-names-include is empty"); } cfg.macos_opts.macos_dev_names_include = Some(dev_names); } } "macos-dev-names-exclude" => { #[cfg(any(target_os = "macos", target_os = "unknown"))] { let dev_names = parse_dev(val)?; if dev_names.is_empty() { log::warn!("macos-dev-names-exclude is empty"); } cfg.macos_opts.macos_dev_names_exclude = Some(dev_names); } } "tray-icon" => { #[cfg(all( any(target_os = "windows", target_os = "unknown"), feature = "gui" ))] { let icon_path = sexpr_to_str_or_err(val, label)?; if icon_path.is_empty() { log::warn!("tray-icon is empty"); } cfg.gui_opts.tray_icon = Some(icon_path.to_string()); } } "icon-match-layer-name" => { #[cfg(all( any(target_os = "windows", target_os = "unknown"), feature = "gui" ))] { cfg.gui_opts.icon_match_layer_name = parse_defcfg_val_bool(val, label)? } } "tooltip-layer-changes" => { #[cfg(all( any(target_os = "windows", target_os = "unknown"), feature = "gui" ))] { cfg.gui_opts.tooltip_layer_changes = parse_defcfg_val_bool(val, label)? } } "tooltip-show-blank" => { #[cfg(all( any(target_os = "windows", target_os = "unknown"), feature = "gui" ))] { cfg.gui_opts.tooltip_show_blank = parse_defcfg_val_bool(val, label)? } } "tooltip-no-base" => { #[cfg(all( any(target_os = "windows", target_os = "unknown"), feature = "gui" ))] { cfg.gui_opts.tooltip_no_base = parse_defcfg_val_bool(val, label)? } } "tooltip-duration" => { #[cfg(all( any(target_os = "windows", target_os = "unknown"), feature = "gui" ))] { cfg.gui_opts.tooltip_duration = parse_cfg_val_u16(val, label, false)? } } "notify-cfg-reload" => { #[cfg(all( any(target_os = "windows", target_os = "unknown"), feature = "gui" ))] { cfg.gui_opts.notify_cfg_reload = parse_defcfg_val_bool(val, label)? } } "notify-cfg-reload-silent" => { #[cfg(all( any(target_os = "windows", target_os = "unknown"), feature = "gui" ))] { cfg.gui_opts.notify_cfg_reload_silent = parse_defcfg_val_bool(val, label)? } } "notify-error" => { #[cfg(all( any(target_os = "windows", target_os = "unknown"), feature = "gui" ))] { cfg.gui_opts.notify_error = parse_defcfg_val_bool(val, label)? } } "tooltip-size" => { #[cfg(all( any(target_os = "windows", target_os = "unknown"), feature = "gui" ))] { let v = sexpr_to_str_or_err(val, label)?; let tooltip_size = v.split(',').collect::>(); const ERRMSG: &str = "Invalid value for tooltip-size.\nExpected two numbers 0-65535 separated by a comma, e.g. 24,24"; if tooltip_size.len() != 2 { bail_expr!(val, "{}", ERRMSG) } cfg.gui_opts.tooltip_size = ( match str::parse::(tooltip_size[0]) { Ok(w) => w, Err(_) => bail_expr!(val, "{}", ERRMSG), }, match str::parse::(tooltip_size[1]) { Ok(h) => h, Err(_) => bail_expr!(val, "{}", ERRMSG), }, ); } } "process-unmapped-keys" => { is_process_unmapped_keys_defined = true; if let Some(list) = val.list(None) { let err = "Expected (all-except key1 ... keyN)."; if list.len() < 2 { bail_expr!(val, "{err}"); } match list[0].atom(None) { Some("all-except") => {} _ => { bail_expr!(val, "{err}"); } }; // Note: deflocalkeys should already be parsed when parsing defcfg, // so can use safely use str_to_oscode here; it will include user // configurations already. let mut key_exceptions: Vec<(OsCode, SExpr)> = vec![]; for key_expr in list[1..].iter() { let key = key_expr.atom(None).and_then(str_to_oscode).ok_or_else( || anyhow_expr!(key_expr, "Expected a known key name."), )?; if key_exceptions.iter().any(|k_exc| k_exc.0 == key) { bail_expr!(key_expr, "Duplicate key name is not allowed."); } key_exceptions.push((key, key_expr.clone())); } cfg.process_unmapped_keys = true; cfg.process_unmapped_keys_exceptions = Some(key_exceptions); } else { cfg.process_unmapped_keys = parse_defcfg_val_bool(val, label)? } } "block-unmapped-keys" => { cfg.block_unmapped_keys = parse_defcfg_val_bool(val, label)? } "allow-hardware-repeat" => { cfg.allow_hardware_repeat = parse_defcfg_val_bool(val, label)? } "alias-to-trigger-on-load" => { cfg.start_alias = parse_defcfg_val_string(val, label)? } "danger-enable-cmd" => cfg.enable_cmd = parse_defcfg_val_bool(val, label)?, "sequence-backtrack-modcancel" => { cfg.sequence_backtrack_modcancel = parse_defcfg_val_bool(val, label)? } "log-layer-changes" => { cfg.log_layer_changes = parse_defcfg_val_bool(val, label)? } "delegate-to-first-layer" => { cfg.delegate_to_first_layer = parse_defcfg_val_bool(val, label)?; if cfg.delegate_to_first_layer { log::info!("delegating transparent keys on other layers to first defined layer"); } } "linux-continue-if-no-devs-found" => { #[cfg(any(target_os = "linux", target_os = "unknown"))] { cfg.linux_opts.linux_continue_if_no_devs_found = parse_defcfg_val_bool(val, label)? } } "movemouse-smooth-diagonals" => { cfg.movemouse_smooth_diagonals = parse_defcfg_val_bool(val, label)? } "movemouse-inherit-accel-state" => { cfg.movemouse_inherit_accel_state = parse_defcfg_val_bool(val, label)? } "override-release-on-activation" => { cfg.override_release_on_activation = parse_defcfg_val_bool(val, label)? } "concurrent-tap-hold" => { cfg.concurrent_tap_hold = parse_defcfg_val_bool(val, label)? } "rapid-event-delay" => { cfg.rapid_event_delay = parse_cfg_val_u16(val, label, false)? } "transparent-key-resolution" => { let v = sexpr_to_str_or_err(val, label)?; cfg.trans_resolution_behavior_v2 = match v { "to-base-layer" => false, "layer-stack" => true, _ => bail_expr!( val, "{label} got {}. It accepts: 'to-base-layer' or 'layer-stack'", v ), }; } "chords-v2-min-idle" | "chords-v2-min-idle-experimental" => { if label == "chords-v2-min-idle-experimental" { log::warn!("You should replace chords-v2-min-idle-experimental with chords-v2-min-idle\n\ Using -experimental will be invalid in the future.") } let min_idle = parse_cfg_val_u16(val, label, true)?; if min_idle < 5 { bail_expr!(val, "{label} must be 5-65535"); } cfg.chords_v2_min_idle = min_idle; } "mouse-movement-key" => { #[cfg(any( all(target_os = "windows", feature = "interception_driver"), target_os = "linux", target_os = "unknown" ))] { if let Some(keystr) = parse_defcfg_val_string(val, label)? { if let Some(key) = str_to_oscode(&keystr) { cfg.mouse_movement_key = Some(key); } else { bail_expr!(val, "{label} not a recognised key code"); } } else { bail_expr!(val, "{label} not a string for a key code"); } } } _ => bail_expr!(key, "Unknown defcfg option {}", label), }; } SExpr::List(_) => { bail_expr!(key, "Lists are not allowed in as keys in defcfg"); } } } } fn parse_defcfg_val_string(expr: &SExpr, _label: &str) -> Result> { match expr { SExpr::Atom(v) => Ok(Some(v.t.clone())), _ => Ok(None), } } pub const FALSE_VALUES: [&str; 3] = ["no", "false", "0"]; pub const TRUE_VALUES: [&str; 3] = ["yes", "true", "1"]; pub const BOOLEAN_VALUES: [&str; 6] = ["yes", "true", "1", "no", "false", "0"]; fn parse_defcfg_val_bool(expr: &SExpr, label: &str) -> Result { match &expr { SExpr::Atom(v) => { let val = v.t.trim_atom_quotes().to_ascii_lowercase(); if TRUE_VALUES.contains(&val.as_str()) { Ok(true) } else if FALSE_VALUES.contains(&val.as_str()) { Ok(false) } else { bail_expr!( expr, "The value for {label} must be one of: {}", BOOLEAN_VALUES.join(", ") ); } } SExpr::List(_) => { bail_expr!( expr, "The value for {label} cannot be a list, it must be one of: {}", BOOLEAN_VALUES.join(", "), ) } } } fn parse_cfg_val_u16(expr: &SExpr, label: &str, exclude_zero: bool) -> Result { let start = if exclude_zero { 1 } else { 0 }; match &expr { SExpr::Atom(v) => Ok(str::parse::(v.t.trim_atom_quotes()) .ok() .and_then(|u| { if exclude_zero && u == 0 { None } else { Some(u) } }) .ok_or_else(|| anyhow_expr!(expr, "{label} must be {start}-65535"))?), SExpr::List(_) => { bail_expr!( expr, "The value for {label} cannot be a list, it must be a number {start}-65535", ) } } } pub fn parse_colon_separated_text(paths: &str) -> Vec { let mut all_paths = vec![]; let mut full_dev_path = String::new(); let mut dev_path_iter = paths.split(':').peekable(); while let Some(dev_path) = dev_path_iter.next() { if dev_path.ends_with('\\') && dev_path_iter.peek().is_some() { full_dev_path.push_str(dev_path.trim_end_matches('\\')); full_dev_path.push(':'); continue; } else { full_dev_path.push_str(dev_path); } all_paths.push(full_dev_path.clone()); full_dev_path.clear(); } all_paths.shrink_to_fit(); all_paths } #[cfg(any(target_os = "linux", target_os = "macos", target_os = "unknown"))] pub fn parse_dev(val: &SExpr) -> Result> { Ok(match val { SExpr::Atom(a) => { let devs = parse_colon_separated_text(a.t.trim_atom_quotes()); if devs.len() == 1 && devs[0].is_empty() { bail_expr!(val, "an empty string is not a valid device name or path") } devs } SExpr::List(l) => { let r: Result> = l.t.iter() .try_fold(Vec::with_capacity(l.t.len()), |mut acc, expr| match expr { SExpr::Atom(path) => { let trimmed_path = path.t.trim_atom_quotes().to_string(); if trimmed_path.is_empty() { bail_span!( path, "an empty string is not a valid device name or path" ) } acc.push(trimmed_path); Ok(acc) } SExpr::List(inner_list) => { bail_span!(inner_list, "expected strings, found a list") } }); r? } }) } fn sexpr_to_str_or_err<'a>(expr: &'a SExpr, label: &str) -> Result<&'a str> { match expr { SExpr::Atom(a) => Ok(a.t.trim_atom_quotes()), SExpr::List(_) => bail_expr!(expr, "The value for {label} can't be a list"), } } #[cfg(any( all(feature = "interception_driver", target_os = "windows"), target_os = "unknown" ))] fn sexpr_to_list_or_err<'a>(expr: &'a SExpr, label: &str) -> Result<&'a [SExpr]> { match expr { SExpr::Atom(_) => bail_expr!(expr, "The value for {label} must be a list"), SExpr::List(l) => Ok(&l.t), } } #[cfg(any( all(feature = "interception_driver", target_os = "windows"), target_os = "unknown" ))] fn sexpr_to_hwids_vec( val: &SExpr, label: &str, entry_label: &str, ) -> Result> { let hwids = sexpr_to_list_or_err(val, label)?; let mut parsed_hwids = vec![]; for hwid_expr in hwids.iter() { let hwid = sexpr_to_str_or_err(hwid_expr, entry_label)?; log::trace!("win hwid: {hwid}"); let hwid_vec = hwid .split(',') .try_fold(vec![], |mut hwid_bytes, hwid_byte| { hwid_byte.trim_matches(' ').parse::().map(|b| { hwid_bytes.push(b); hwid_bytes }) }).map_err(|_| anyhow_expr!(hwid_expr, "Entry in {label} is invalid. Entries should be numbers [0,255] separated by commas"))?; let hwid_slice = hwid_vec.iter().copied().enumerate() .try_fold([0u8; HWID_ARR_SZ], |mut hwid, idx_byte| { let (i, b) = idx_byte; if i > HWID_ARR_SZ { bail_expr!(hwid_expr, "entry in {label} is too long; it should be up to {HWID_ARR_SZ} 8-bit unsigned integers") } hwid[i] = b; Ok(hwid) }); parsed_hwids.push(hwid_slice?); } parsed_hwids.shrink_to_fit(); Ok(parsed_hwids) } #[cfg(any(target_os = "linux", target_os = "unknown"))] #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struct KeyRepeatSettings { pub delay: u16, pub rate: u16, } #[cfg(any(target_os = "linux", target_os = "unknown"))] #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum UnicodeTermination { Enter, Space, SpaceEnter, EnterSpace, } #[cfg(any(target_os = "windows", target_os = "unknown"))] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum AltGrBehaviour { DoNothing, CancelLctlPress, AddLctlRelease, } #[cfg(any(target_os = "windows", target_os = "unknown"))] impl Default for AltGrBehaviour { fn default() -> Self { Self::DoNothing } } #[cfg(any( all(feature = "interception_driver", target_os = "windows"), target_os = "unknown" ))] pub const HWID_ARR_SZ: usize = 1024; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ReplayDelayBehaviour { /// Always use a fixed number of ticks between presses and releases. /// This is the original kanata behaviour. /// This means that held action activations like in tap-hold do not behave as intended. Constant, /// Use the recorded number of ticks between presses and releases. /// This is newer behaviour. Recorded, } kanata-parser-0.190.0/src/cfg/deftemplate.rs000064400000000000000000000505641046102023000167240ustar 00000000000000//! This file is responsible for template expansion. //! For simplicity of implementation, there is performance left off the table. //! This code runs at parse time and not in runtime //! so it is not performance critical. //! //! The known performance left off the table is: //! //! - Creating the expanded template recurses through all SExprs every time. //! Instead the code could pre-compute the paths to access every variable //! that needs substition. (perf_1) //! //! - Replacing the `template-expand|if-equal` items with the appropriate values //! recreates the Vec for every replacement that happens at that recursion depth. //! Instead the code could do recreate the vec only once //! and insert SExprs at the proper places. (perf_2) use crate::anyhow_expr; use crate::anyhow_span; use crate::bail_expr; use crate::bail_span; use crate::err_expr; use crate::err_span; use super::error::*; use super::sexpr::*; use super::*; #[derive(Debug)] struct Template { name: String, vars: Vec, // Same as vars above but all names are prefixed with '$'. vars_substitute_names: Vec, content: Vec, } /// Parse `deftemplate`s and expand `template-expand`s. /// /// Syntax of `deftemplate` is: /// /// `(deftemplate