termbg-0.6.2/.cargo_vcs_info.json0000644000000001360000000000100123210ustar { "git": { "sha1": "c5b066a56bf3a20b4942768f5e0da8eb29292a5b" }, "path_in_vcs": "" }termbg-0.6.2/.github/FUNDING.yml000064400000000000000000000000771046102023000142720ustar 00000000000000# These are supported funding model platforms github: dalance termbg-0.6.2/.github/dependabot.yml000064400000000000000000000002211046102023000152740ustar 00000000000000version: 2 updates: - package-ecosystem: cargo directory: "/" schedule: interval: daily time: "20:00" open-pull-requests-limit: 10 termbg-0.6.2/.github/workflows/rust.yml000064400000000000000000000003301046102023000162220ustar 00000000000000name: Rust on: [push] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - name: Build run: cargo build --verbose - name: Run tests run: cargo test --verbose termbg-0.6.2/.gitignore000064400000000000000000000000351046102023000130770ustar 00000000000000/target Cargo.lock .DS_Store termbg-0.6.2/CHANGELOG.md000064400000000000000000000046551046102023000127340ustar 00000000000000# Change Log ## [Unreleased](https://github.com/dalance/termbg/compare/v0.6.2...Unreleased) - ReleaseDate ## [v0.6.2](https://github.com/dalance/termbg/compare/v0.6.1...v0.6.2) - 2025-01-06 ## [v0.6.1](https://github.com/dalance/termbg/compare/v0.6.0...v0.6.1) - 2024-11-15 ## [v0.6.0](https://github.com/dalance/termbg/compare/v0.5.2...v0.6.0) - 2024-10-21 * [Fixed] Stdin is blocked [#29](https://github.com/dalance/termbg/pull/29) ## [v0.5.2](https://github.com/dalance/termbg/compare/v0.5.1...v0.5.2) - 2024-10-11 ## [v0.5.1](https://github.com/dalance/termbg/compare/v0.5.0...v0.5.1) - 2024-09-13 ## [v0.5.0](https://github.com/dalance/termbg/compare/v0.4.4...v0.5.0) - 2024-03-06 * [Breaking Changed] feat: upgrade crossterm to 0.27.0 [#22](https://github.com/dalance/termbg/pull/22) * [Changed] Remove special case for VSCode [#21](https://github.com/dalance/termbg/pull/21) ## [v0.4.4](https://github.com/dalance/termbg/compare/v0.4.3...v0.4.4) - 2023-12-06 * [Fixed] Do not set the terminal to raw mode if it isn't actually a terminal [#19](https://github.com/dalance/termbg/pull/19) ## [v0.4.3](https://github.com/dalance/termbg/compare/v0.4.2...v0.4.3) - 2023-03-02 ## [v0.4.2](https://github.com/dalance/termbg/compare/v0.4.1...v0.4.2) - 2023-03-02 ## [v0.4.1](https://github.com/dalance/termbg/compare/v0.4.0...v0.4.1) - 2022-05-25 * [Added] emacs detection ## [v0.4.0](https://github.com/dalance/termbg/compare/v0.3.0...v0.4.0) - 2022-01-25 * [Breaking Changed] drop Terminal::RxvtCompatible * [Added] latency measurement function ## [v0.3.0](https://github.com/dalance/termbg/compare/v0.2.4...v0.3.0) - 2021-05-28 * [Fixed] unexpected stdin lock [#5](https://github.com/dalance/termbg/issues/5) ## [v0.2.4](https://github.com/dalance/termbg/compare/v0.2.3...v0.2.4) - 2021-05-20 * [Fixed] Panic at response check thread ## [v0.2.3](https://github.com/dalance/termbg/compare/v0.2.2...v0.2.3) - 2021-05-19 * [Fixed] Hung at VSCode ## [v0.2.2](https://github.com/dalance/termbg/compare/v0.2.1...v0.2.2) - 2021-05-18 ## [v0.2.1](https://github.com/dalance/termbg/compare/v0.2.0...v0.2.1) - 2021-05-18 * [Fixed] Bytes leak [#4](https://github.com/dalance/termbg/issues/4) ## [v0.2.0](https://github.com/dalance/termbg/compare/v0.1.0...v0.2.0) - 2020-11-10 * [Changed] Return type from `Option` to `Result` * [Changed] Remove rxvt detection ( rxvt is XtermCompatible ) * [Added] Windows Terminal detection * [Added] Windows console support termbg-0.6.2/Cargo.lock0000644000000405400000000000100102770ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 4 [[package]] name = "anstyle" version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "55cc3b69f167a1ef2e161439aa98aed94e6028e5f9a59be9a6ffb47aef1651f9" [[package]] name = "autocfg" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] name = "bitflags" version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" version = "2.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed570934406eb16438a4e976b1b4500774099c13b8cb96eec99f620f05090ddf" [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "crossterm" version = "0.28.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6" dependencies = [ "bitflags 2.4.2", "crossterm_winapi", "mio", "parking_lot", "rustix", "signal-hook", "signal-hook-mio", "winapi", ] [[package]] name = "crossterm_winapi" version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b" dependencies = [ "winapi", ] [[package]] name = "deranged" version = "0.3.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b42b6fa04a440b495c8b04d0e71b707c585f83cb9cb28cf8cd0d976c315e31b4" dependencies = [ "powerfmt", ] [[package]] name = "downcast" version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1435fa1053d8b2fbbe9be7e97eca7f33d37b28409959813daefc1446a14247f1" [[package]] name = "either" version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0" [[package]] name = "errno" version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a258e46cdc063eb8519c00b9fc845fc47bcfca4130e2f08e88665ceda8474245" dependencies = [ "libc", "windows-sys", ] [[package]] name = "fragile" version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6c2141d6d6c8512188a7891b4b01590a45f6dac67afb4f255c4124dbb86d4eaa" [[package]] name = "hermit-abi" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" [[package]] name = "itoa" version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" [[package]] name = "libc" version = "0.2.158" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8adc4bb1803a324070e64a98ae98f38934d91957a99cfb3a43dcbc01bc56439" [[package]] name = "linux-raw-sys" version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" [[package]] name = "lock_api" version = "0.4.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c168f8615b12bc01f9c17e2eb0cc07dcae1940121185446edc3744920e8ef45" dependencies = [ "autocfg", "scopeguard", ] [[package]] name = "log" version = "0.4.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c" [[package]] name = "mio" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "80e04d1dcff3aae0704555fe5fee3bcfaf3d1fdf8a7e521d5b9d2b42acb52cec" dependencies = [ "hermit-abi", "libc", "log", "wasi", "windows-sys", ] [[package]] name = "mockall" version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d4c28b3fb6d753d28c20e826cd46ee611fda1cf3cde03a443a974043247c065a" dependencies = [ "cfg-if", "downcast", "fragile", "mockall_derive", "predicates", "predicates-tree", ] [[package]] name = "mockall_derive" version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "341014e7f530314e9a1fdbc7400b244efea7122662c96bfa248c31da5bfb2020" dependencies = [ "cfg-if", "proc-macro2", "quote", "syn", ] [[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 = "parking_lot" version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f" dependencies = [ "lock_api", "parking_lot_core", ] [[package]] name = "parking_lot_core" version = "0.9.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4c42a9226546d68acdd9c0a280d17ce19bfe27a46bf68784e4066115788d008e" dependencies = [ "cfg-if", "libc", "redox_syscall", "smallvec", "windows-targets 0.48.5", ] [[package]] name = "powerfmt" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" [[package]] name = "predicates" version = "3.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7e9086cc7640c29a356d1a29fd134380bee9d8f79a17410aa76e7ad295f42c97" dependencies = [ "anstyle", "predicates-core", ] [[package]] name = "predicates-core" version = "1.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae8177bee8e75d6846599c6b9ff679ed51e882816914eec639944d7c9aa11931" [[package]] name = "predicates-tree" version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "41b740d195ed3166cd147c8047ec98db0e22ec019eb8eeb76d343b795304fb13" dependencies = [ "predicates-core", "termtree", ] [[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.35" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef" dependencies = [ "proc-macro2", ] [[package]] name = "redox_syscall" version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" dependencies = [ "bitflags 1.3.2", ] [[package]] name = "rustix" version = "0.38.37" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8acb788b847c24f28525660c4d7758620a7210875711f79e7f663cc152726811" dependencies = [ "bitflags 2.4.2", "errno", "libc", "linux-raw-sys", "windows-sys", ] [[package]] name = "scopeguard" version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" [[package]] name = "serde" version = "1.0.215" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6513c1ad0b11a9376da888e3e0baa0077f1aed55c17f50e7b2397136129fb88f" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.215" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ad1e866f866923f252f05c889987993144fb74e722403468a4ebd70c3cd756c0" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "signal-hook" version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8621587d4798caf8eb44879d42e56b9a93ea5dcd315a6487c357130095b62801" dependencies = [ "libc", "signal-hook-registry", ] [[package]] name = "signal-hook-mio" version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34db1a06d485c9142248b7a054f034b349b212551f3dfd19c94d45a754a217cd" dependencies = [ "libc", "mio", "signal-hook", ] [[package]] name = "signal-hook-registry" version = "1.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8229b473baa5980ac72ef434c4415e70c4b5e71b423043adb4ba059f89c99a1" dependencies = [ "libc", ] [[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.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6ecd384b10a64542d77071bd64bd7b231f4ed5940fba55e98c3de13824cf3d7" [[package]] name = "syn" version = "2.0.87" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "25aa4ce346d03a6dcd68dd8b4010bcb74e54e62c90c573f394c46eae99aba32d" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "termbg" version = "0.6.2" dependencies = [ "crossterm", "either", "log", "mockall", "scopeguard", "simplelog", "thiserror", "winapi", ] [[package]] name = "termcolor" version = "1.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" dependencies = [ "winapi-util", ] [[package]] name = "termtree" version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3369f5ac52d5eb6ab48c6b4ffdc8efbcad6b89c765749064ba298f2c68a16a76" [[package]] name = "thiserror" version = "2.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c006c85c7651b3cf2ada4584faa36773bd07bac24acfb39f3c431b36d7e667aa" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" version = "2.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f077553d607adc1caf65430528a576c757a71ed73944b66ebb58ef2bbd243568" 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.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" [[package]] name = "wasi" version = "0.11.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[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", ] [[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 0.52.4", ] [[package]] name = "windows-targets" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" dependencies = [ "windows_aarch64_gnullvm 0.48.5", "windows_aarch64_msvc 0.48.5", "windows_i686_gnu 0.48.5", "windows_i686_msvc 0.48.5", "windows_x86_64_gnu 0.48.5", "windows_x86_64_gnullvm 0.48.5", "windows_x86_64_msvc 0.48.5", ] [[package]] name = "windows-targets" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7dd37b7e5ab9018759f893a1952c9420d060016fc19a472b4bb20d1bdd694d1b" dependencies = [ "windows_aarch64_gnullvm 0.52.4", "windows_aarch64_msvc 0.52.4", "windows_i686_gnu 0.52.4", "windows_i686_msvc 0.52.4", "windows_x86_64_gnu 0.52.4", "windows_x86_64_gnullvm 0.52.4", "windows_x86_64_msvc 0.52.4", ] [[package]] name = "windows_aarch64_gnullvm" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" [[package]] name = "windows_aarch64_gnullvm" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bcf46cf4c365c6f2d1cc93ce535f2c8b244591df96ceee75d8e83deb70a9cac9" [[package]] name = "windows_aarch64_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" [[package]] name = "windows_aarch64_msvc" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da9f259dd3bcf6990b55bffd094c4f7235817ba4ceebde8e6d11cd0c5633b675" [[package]] name = "windows_i686_gnu" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" [[package]] name = "windows_i686_gnu" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b474d8268f99e0995f25b9f095bc7434632601028cf86590aea5c8a5cb7801d3" [[package]] name = "windows_i686_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" [[package]] name = "windows_i686_msvc" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1515e9a29e5bed743cb4415a9ecf5dfca648ce85ee42e15873c3cd8610ff8e02" [[package]] name = "windows_x86_64_gnu" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" [[package]] name = "windows_x86_64_gnu" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5eee091590e89cc02ad514ffe3ead9eb6b660aedca2183455434b93546371a03" [[package]] name = "windows_x86_64_gnullvm" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" [[package]] name = "windows_x86_64_gnullvm" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ca79f2451b49fa9e2af39f0747fe999fcda4f5e241b2898624dca97a1f2177" [[package]] name = "windows_x86_64_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" [[package]] name = "windows_x86_64_msvc" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32b752e52a2da0ddfbdbcc6fceadfeede4c939ed16d13e648833a61dfb611ed8" termbg-0.6.2/Cargo.toml0000644000000043350000000000100103240ustar # 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 = "2018" name = "termbg" version = "0.6.2" authors = ["dalance "] build = false autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "Terminal background color detection" readme = "README.md" keywords = [ "console", "terminal", "cli", ] categories = [ "command-line-utilities", "command-line-interface", ] license = "MIT OR Apache-2.0" repository = "https://github.com/dalance/termbg" [package.metadata.release] pre-release-commit-message = "Prepare to v{{version}}" tag-message = "Bump version to {{version}}" tag-prefix = "" [[package.metadata.release.pre-release-replacements]] file = "README.md" replace = 'termbg = "{{version}}"' search = 'termbg = "[a-z0-9\.-]+"' [[package.metadata.release.pre-release-replacements]] file = "CHANGELOG.md" replace = "v{{version}}" search = "Unreleased" [[package.metadata.release.pre-release-replacements]] file = "CHANGELOG.md" replace = "{{date}}" search = "ReleaseDate" [[package.metadata.release.pre-release-replacements]] file = "CHANGELOG.md" replace = """ Change Log ## [Unreleased](https://github.com/dalance/termbg/compare/v{{version}}...Unreleased) - ReleaseDate""" search = "Change Log" [lib] name = "termbg" path = "src/lib.rs" [[bin]] name = "termbg" path = "src/bin/termbg.rs" [dependencies.crossterm] version = "0.28" [dependencies.log] version = "0.4" [dependencies.mockall] version = "0.13.0" [dependencies.scopeguard] version = "1.2" [dependencies.simplelog] version = "0.12.2" [dependencies.thiserror] version = "2" [dev-dependencies.either] version = "1.13.0" [target.'cfg(target_os = "windows")'.dependencies.winapi] version = "0.3" features = [ "wincon", "winbase", "processenv", "impl-default", ] termbg-0.6.2/Cargo.toml.orig000064400000000000000000000024301046102023000137770ustar 00000000000000[package] name = "termbg" version = "0.6.2" authors = ["dalance "] repository = "https://github.com/dalance/termbg" keywords = ["console", "terminal", "cli"] categories = ["command-line-utilities", "command-line-interface"] license = "MIT OR Apache-2.0" readme = "README.md" description = "Terminal background color detection" edition = "2018" [package.metadata.release] pre-release-commit-message = "Prepare to v{{version}}" tag-message = "Bump version to {{version}}" tag-prefix = "" pre-release-replacements = [ { file = "README.md", search = "termbg = \"[a-z0-9\\.-]+\"", replace = "termbg = \"{{version}}\"" }, { file = "CHANGELOG.md", search = "Unreleased", replace = "v{{version}}" }, { file = "CHANGELOG.md", search = "ReleaseDate", replace = "{{date}}" }, { file = "CHANGELOG.md", search = "Change Log", replace = "Change Log\n\n## [Unreleased](https://github.com/dalance/termbg/compare/v{{version}}...Unreleased) - ReleaseDate" }, ] [dependencies] crossterm = "0.28" log = "0.4" mockall = "0.13.0" scopeguard = "1.2" simplelog = "0.12.2" thiserror = "2" [dev-dependencies] either = "1.13.0" [target.'cfg(target_os = "windows")'.dependencies] winapi = { version = "0.3", features = [ "wincon", "winbase", "processenv", "impl-default", ] } termbg-0.6.2/LICENSE-APACHE000064400000000000000000000261121046102023000130370ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2019 dalance Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. termbg-0.6.2/LICENSE-MIT000064400000000000000000000020621046102023000125450ustar 00000000000000The MIT License (MIT) Copyright (c) 2019 dalance Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. termbg-0.6.2/README.md000064400000000000000000000054741046102023000124020ustar 00000000000000# termbg A Rust library for terminal background color detection. The detected color is provided by RGB or theme ( dark or light ). [![Actions Status](https://github.com/dalance/termbg/workflows/Rust/badge.svg)](https://github.com/dalance/termbg/actions) [![Crates.io](https://img.shields.io/crates/v/termbg.svg)](https://crates.io/crates/termbg) [![Docs.rs](https://docs.rs/termbg/badge.svg)](https://docs.rs/termbg) ## Verified terminals * [Alacritty](https://github.com/alacritty/alacritty) * GNOME Terminal * GNU Screen * [kitty](https://sw.kovidgoyal.net/kitty/) * [iTerm2](https://iterm2.com) * macOS terminal * MATE Terminal * [mintty](https://mintty.github.io) * [RLogin](http://nanno.dip.jp/softlib/man/rlogin/) * rxvt-unicode * sakura * [PuTTY PRIVATE PATCHES](https://ice.hotmint.com/putty/) * [Tera Term](https://ttssh2.osdn.jp) * [Terminator](https://terminator-gtk3.readthedocs.io/en/latest/) * [tmux](https://github.com/tmux/tmux) * [Visual Studio Code](https://code.visualstudio.com) * xfce4-terminal * xterm * Win32 console If you check other terminals, please report through [issue](https://github.com/dalance/termbg/issues). ## Unsupported terminals * [Cmder](https://cmder.app) * [ConEmu](https://conemu.github.io) * [LilyTerm](https://github.com/Tetralet/LilyTerm) * [Poderosa](https://ja.poderosa-terminal.com) * [PuTTY](https://www.putty.org) * [QTerminal](https://github.com/lxqt/qterminal) * [Windows Terminal](https://github.com/microsoft/terminal) "Windows Terminal" may be supported in a future release: https://github.com/microsoft/terminal/issues/3718. ## Usage ```Cargo.toml [dependencies] termbg = "0.6.2" ``` ## Example ```rust fn main() { let timeout = std::time::Duration::from_millis(100); println!("Check terminal background color"); let term = termbg::terminal(); let rgb = termbg::rgb(timeout); let theme = termbg::theme(timeout); println!(" Term : {:?}", term); match rgb { Ok(rgb) => { println!(" Color: R={:x}, G={:x}, B={:x}", rgb.r, rgb.g, rgb.b); } Err(e) => { println!(" Color: detection failed {:?}", e); } } match theme { Ok(theme) => { println!(" Theme: {:?}", theme); } Err(e) => { println!(" Theme: detection failed {:?}", e); } } } ``` ## Check program This crate provides a simple program to check. ```console $ cargo run Check terminal background color Term : Tmux Color: R=0, G=0, B=0 Theme: Dark ``` ## Detecting mechanism If the terminal is win32 console, WIN32API is used for detection. If the terminal is xterm compatible, "Xterm Control Sequences" is used. When these method was failed, `COLORFGBG` environment variable is used. The detected RGB is converted to YCbCr. If Y > 0.5, the theme is detected as "light", otherwise "dark". termbg-0.6.2/src/bin/termbg.rs000064400000000000000000000034431046102023000143020ustar 00000000000000use simplelog::{ColorChoice, CombinedLogger, Config, LevelFilter, TermLogger, TerminalMode}; use std::env; fn main() { let args: Vec = env::args().collect(); let num_args = args.len(); if num_args > 1 { match args[1].as_str() { "--version" | "-V" => { println!("termbg {}", env!("CARGO_PKG_VERSION")); return; } "--debug" | "-d" => { CombinedLogger::init(vec![TermLogger::new( LevelFilter::Debug, Config::default(), TerminalMode::Mixed, ColorChoice::Auto, )]) .unwrap(); } _ => { eprintln!("Usage: {} [--debug/-d] [--version/-V]", args[0]); std::process::exit(1); } } } let timeout = std::time::Duration::from_millis(100); println!("Check terminal background color"); let term = termbg::terminal(); let latency = termbg::latency(std::time::Duration::from_millis(1000)); let rgb = termbg::rgb(timeout); let theme = termbg::theme(timeout); println!(" Term : {:?}", term); match latency { Ok(latency) => { println!(" Latency: {:?}", latency); } Err(e) => { println!(" Latency: detection failed {:?}", e); } } match rgb { Ok(rgb) => { println!(" Color: R={:x}, G={:x}, B={:x}", rgb.r, rgb.g, rgb.b); } Err(e) => { println!(" Color: detection failed {:?}", e); } } match theme { Ok(theme) => { println!(" Theme: {:?}", theme); } Err(e) => { println!(" Theme: detection failed {:?}", e); } } } termbg-0.6.2/src/lib.rs000064400000000000000000000727771046102023000130400ustar 00000000000000use crossterm::event::{poll, read, Event, KeyCode, KeyModifiers}; use crossterm::terminal::{self, is_raw_mode_enabled}; use log::debug; use mockall::automock; use scopeguard::defer; use std::env; use std::fmt::Debug; use std::io::IsTerminal; use std::io::{self, Read, Write}; use std::time::{Duration, Instant}; use thiserror::Error; #[cfg(target_os = "windows")] use { std::sync::OnceLock, winapi::um::consoleapi::SetConsoleMode, winapi::um::handleapi::INVALID_HANDLE_VALUE, winapi::um::processenv::GetStdHandle, winapi::um::winbase::STD_OUTPUT_HANDLE, winapi::um::wincon::{self, ENABLE_VIRTUAL_TERMINAL_PROCESSING}, }; /// Terminal #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum Terminal { Screen, Tmux, XtermCompatible, Windows, Emacs, } /// 16bit RGB color #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct Rgb { pub r: u16, pub g: u16, pub b: u16, } /// Background theme #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum Theme { Light, Dark, } /// Error #[derive(Error, Debug)] pub enum Error { #[error("io error")] Io { #[from] source: io::Error, }, #[error("parse error")] Parse(String), #[error("unsupported")] Unsupported, } /// A trait to allow mocking of the event reader for testing purposes. #[automock] pub trait EventReader { /// Read a terminal event. /// /// # Errors /// /// This function will bubble up any i/o or `crossterm` errors encountered. fn read_event(&self) -> Result; /// Poll for a terminal event. /// /// # Errors /// /// This function will bubble up any i/o or `crossterm` errors encountered. fn poll(&self, timeout: Duration) -> Result; } /// A struct to implement real-world use of the event reader, as opposed to use in testing. #[derive(Debug)] pub struct CrosstermEventReader; impl EventReader for CrosstermEventReader { fn read_event(&self) -> Result { crossterm::event::read().map_err(Into::::into) } fn poll(&self, timeout: Duration) -> Result { crossterm::event::poll(timeout).map_err(Into::::into) } } /// get detected terminal #[cfg(not(target_os = "windows"))] pub fn terminal() -> Terminal { if env::var("INSIDE_EMACS").is_ok() { return Terminal::Emacs; } if env::var("TMUX").is_ok() || env::var("TERM").is_ok_and(|x| x.starts_with("tmux-")) { Terminal::Tmux } else { let is_screen = if let Ok(term) = env::var("TERM") { term.starts_with("screen") } else { false }; if is_screen { Terminal::Screen } else { Terminal::XtermCompatible } } } /// get detected terminal #[cfg(target_os = "windows")] pub fn terminal() -> Terminal { // Although xterm OSC is MS's roadmap, as of 2024-10-16, only Windows Terminal 1.22 (preview) // supports *querying* rgb values. In the mean time, there is effectively no way to query // Windows color schemes. if let Ok(term_program) = env::var("TERM_PROGRAM") { if term_program == "vscode" { return Terminal::XtermCompatible; } } if env::var("INSIDE_EMACS").is_ok() { return Terminal::Emacs; } // Windows Terminal is Xterm-compatible // https://github.com/microsoft/terminal/issues/3718. // But this excludes OSC 10/11 colour queries until Windows Terminal 1.22 // https://devblogs.microsoft.com/commandline/windows-terminal-preview-1-22-release/: // "Applications can now query ... the default foreground (OSC 10 ?) [and] background (OSC 11 ?)" // Don't use WT_SESSION for this purpose: // https://github.com/Textualize/rich/issues/140 // if env::var("WT_SESSION").is_ok() { if enable_virtual_terminal_processing() { debug!( "This Windows terminal supports virtual terminal processing (but not OSC 10/11 colour queries if prior to Windows Terminal 1.22 Preview of August 2024)\r" ); Terminal::XtermCompatible } else { debug!("Terminal::Windows\r"); Terminal::Windows } } /// get background color by `RGB` #[cfg(not(target_os = "windows"))] pub fn rgb(timeout: Duration) -> Result { let term = terminal(); let rgb = match term { Terminal::Emacs => Err(Error::Unsupported), _ => from_xterm(term, timeout), }; let fallback = from_env_colorfgbg(); if rgb.is_ok() { rgb } else if fallback.is_ok() { fallback } else { rgb } } /// get background color by `RGB` #[cfg(target_os = "windows")] pub fn rgb(timeout: Duration) -> Result { let term = terminal(); let rgb = match term { Terminal::Emacs => Err(Error::Unsupported), Terminal::XtermCompatible => from_xterm(term, timeout), _ => from_winapi(), }; let fallback = from_env_colorfgbg(); debug!("rgb={rgb:?}, fallback={fallback:?}\r"); if rgb.is_ok() { rgb } else if fallback.is_ok() { fallback } else { rgb } } /// get terminal latency #[cfg(not(target_os = "windows"))] pub fn latency(timeout: Duration) -> Result { let term = terminal(); match term { Terminal::Emacs => Ok(Duration::from_millis(0)), _ => xterm_latency(timeout), } } /// get terminal latency #[cfg(target_os = "windows")] pub fn latency(timeout: Duration) -> Result { let term = terminal(); match term { Terminal::Emacs => Ok(Duration::from_millis(0)), Terminal::XtermCompatible => xterm_latency(timeout), _ => Ok(Duration::from_millis(0)), } } /// get background color by `Theme` pub fn theme(timeout: Duration) -> Result { let rgb = rgb(timeout)?; // ITU-R BT.601 let y = rgb.r as f64 * 0.299 + rgb.g as f64 * 0.587 + rgb.b as f64 * 0.114; if y > 32768.0 { Ok(Theme::Light) } else { Ok(Theme::Dark) } } // Function to enable virtual terminal processing for Windows #[cfg(target_os = "windows")] fn enable_virtual_terminal_processing() -> bool { static ENABLE_VT_PROCESSING: OnceLock = OnceLock::new(); *ENABLE_VT_PROCESSING.get_or_init(|| unsafe { let handle = GetStdHandle(STD_OUTPUT_HANDLE); if handle != INVALID_HANDLE_VALUE { let mut mode: u32 = 0; if winapi::um::consoleapi::GetConsoleMode(handle, &mut mode) != 0 { // Try to set virtual terminal processing mode if SetConsoleMode(handle, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING) != 0 { // Success in enabling VT debug!("Successfully enabled Virtual Terminal Processing.\r"); return true; } else { // Failed to enable VT, optionally log error debug!("Failed to enable Virtual Terminal Processing.\r"); } } } // Return false if enabling VT failed false }) } fn from_xterm(term: Terminal, timeout: Duration) -> Result { if !std::io::stdin().is_terminal() || !std::io::stdout().is_terminal() || !std::io::stderr().is_terminal() { // Not a terminal, so don't try to read the current background color. return Err(Error::Unsupported); } let raw_before = is_raw_mode_enabled()?; defer! { let is_raw = match is_raw_mode_enabled() { Ok(val) => val, Err(e) => { debug!("Failed to check raw mode status: {:?}\r", e); return; } }; if is_raw == raw_before { debug!("Raw mode status unchanged from raw={raw_before}.\r"); } else if let Err(e) = restore_raw_status(raw_before) { debug!("Failed to restore raw mode: {e:?} to raw={raw_before}\r"); } else { debug!("Raw mode restored to previous state (raw={raw_before}).\r"); } if let Err(e) = clear_stdin() { debug!("Failed to clear stdin: {e:?}\r"); } else { debug!("Cleared any excess from stdin.\r"); } } if !raw_before { terminal::enable_raw_mode()?; } #[cfg(target_os = "windows")] { if !enable_virtual_terminal_processing() { debug!( "Virtual Terminal Processing could not be enabled. Falling back to default behavior.\r" ); return from_winapi(); } } let event_reader = CrosstermEventReader; let mut stderr = io::stderr(); query_xterm(term, timeout, &event_reader, &mut stderr) } fn query_xterm( term: Terminal, timeout: Duration, event_reader: &R, buffer: &mut W, ) -> Result where R: EventReader + Debug, W: Write + Debug, { // Query by XTerm control sequence let query = match term { Terminal::Tmux => "\x1bPtmux;\x1b\x1b]11;?\x07\x1b\\", Terminal::Screen => "\x1bP\x1b]11;?\x07\x1b\\", _ => "\x1b]11;?\x1b\\", }; // Send query write!(buffer, "{query}")?; buffer.flush()?; let mut response = String::new(); let start_time = Instant::now(); // Main loop for capturing terminal response loop { if start_time.elapsed() > timeout { debug!("After timeout, found response={response}\r"); if response.contains("rgb:") { let rgb_slice = decode_unterminated(&response)?; debug!("Found a valid response {rgb_slice} in pre-timeout check despite unrecognized terminator in response code {response:#?}\r"); return parse_response(rgb_slice, start_time); } debug!("Failed to capture response\r"); return Err(io::Error::new(io::ErrorKind::TimedOut, "timeout 1").into()); } // Replaced expensive async_std with blocking loop. Terminal normally responds // fast or not at all, and in the latter case we still have the timeout on the // main loop. if event_reader.poll(Duration::from_millis(100))? { // Read the next event. // Replaced stdin read that was consuming legit user input in Windows // with non-blocking crossterm read event. if let Event::Key(key_event) = event_reader.read_event()? { // debug!("key_event={key_event:#?}\r"); match (key_event.code, key_event.modifiers) { (KeyCode::Char('\\'), KeyModifiers::ALT | KeyModifiers::NONE) // ST | (KeyCode::Char('g'), KeyModifiers::CONTROL) // BEL // Insurance in case BEL is not recognosed as ^g | (KeyCode::Char('\u{0007}'), KeyModifiers::NONE) //BEL => { debug!("End of response detected ({key_event:?}).\r"); // response.push('\\'); // debug!("response={response}\r"); return parse_response(&response, start_time); } // Append other characters to buffer (KeyCode::Char(c), KeyModifiers::NONE) => { debug!("pushing {c}\r"); response.push(c); } _ => { // Ignore other keys debug!("ignoring {key_event:?}\r"); } } } } } } fn decode_unterminated(response: &str) -> Result<&str, Error> { let resp_start = response.find("rgb:").ok_or(Error::Parse( "Required string `rgb:` not found in response".to_string(), ))?; let mid = resp_start + 4; // Point after "rgb:" let raw_rgb_slice = response.split_at(mid).1; // slash-delimited r/g/b string with any trailing characters debug!("raw_rgb_slice={raw_rgb_slice}\r"); // Identify where to trim trailing characters, by assuming the slash-delimited colour specifiers // are all supposed to be the same length. I.e. trim after 3 specifiers and 2 delimiters. let fragments = raw_rgb_slice.splitn(3, '/').collect::>(); if fragments.len() < 3 { // debug!("Incomplete response `{response}`: does not contain two forward slashes\r"); return Err(Error::Parse(format!( "Incomplete response `{response}`: does not contain two forward slashes" ))); } let frag_len = fragments[0].len(); if fragments[1].len() != frag_len || fragments[2].len() < frag_len { // debug!("Can't safely reconstitute unterminated response `{response}`from fragments of unequal length\r"); return Err(Error::Parse(format!("Can't safely reconstitute unterminated response `{response}`from fragments of unequal length"))); } // "Trim" extraneous trailing characters by excluding them from slice let rgb_str_len = frag_len * 3 + 2; let rgb_slice = &response[resp_start..mid + rgb_str_len]; Ok(rgb_slice) } fn parse_response(response: &str, start_time: Instant) -> Result { // debug!("response={response}\r"); let (r, g, b) = extract_rgb(response)?; let elapsed = start_time.elapsed(); debug!("Elapsed time: {:.2?}\r", elapsed); // debug!("Rgb {{ r, g, b }} = {:?}\r", Rgb { r, g, b }); Ok(Rgb { r, g, b }) } fn extract_rgb(response: &str) -> Result<(u16, u16, u16), Error> { let rgb_str = response .split_at( response.find("rgb:").ok_or(Error::Parse( "Could not find 'rgb:' in terminal response string".to_string(), ))? + 4, ) .1; let (r, g, b) = decode_x11_color(rgb_str)?; // debug!("(r, g, b)=({r}, {g}, {b})\r"); Ok((r, g, b)) } fn restore_raw_status(raw_before: bool) -> Result<(), Error> { let raw_now = is_raw_mode_enabled()?; if raw_now == raw_before { return Ok(()); } if raw_before { terminal::enable_raw_mode()?; } else { terminal::disable_raw_mode()?; } Ok(()) } /// Discard any unread input returned by the OSC 11 query. /// /// # Errors /// /// This function will return an error if Rust has decided that the "terminal" is not a terminal. // Helper function to discard extra characters fn clear_stdin() -> Result<(), Box> { while poll(Duration::from_millis(10))? { if let Event::Key(c) = read()? { // Discard the input by simply reading it debug!("discarding char{c:x?}\r"); } } Ok(()) } /// Seems to be for Rxvt terminal emulator only. fn from_env_colorfgbg() -> Result { let var = env::var("COLORFGBG").map_err(|_| Error::Unsupported)?; let fgbg: Vec<_> = var.split(";").collect(); let bg = fgbg.get(1).ok_or(Error::Unsupported)?; let bg = u8::from_str_radix(bg, 10).map_err(|_| Error::Parse(String::from(var)))?; // rxvt default color table #[allow(clippy::match_same_arms)] let (r, g, b) = match bg { // black 0 => (0, 0, 0), // red 1 => (205, 0, 0), // green 2 => (0, 205, 0), // yellow 3 => (205, 205, 0), // blue 4 => (0, 0, 238), // magenta 5 => (205, 0, 205), // cyan 6 => (0, 205, 205), // white 7 => (229, 229, 229), // bright black 8 => (127, 127, 127), // bright red 9 => (255, 0, 0), // bright green 10 => (0, 255, 0), // bright yellow 11 => (255, 255, 0), // bright blue 12 => (92, 92, 255), // bright magenta 13 => (255, 0, 255), // bright cyan 14 => (0, 255, 255), // bright white 15 => (255, 255, 255), _ => (0, 0, 0), }; Ok(Rgb { r: r * 256, g: g * 256, b: b * 256, }) } fn xterm_latency(timeout: Duration) -> Result { let query = "\x1b[5n"; let mut stderr = io::stderr(); let raw_before = is_raw_mode_enabled()?; defer! { let is_raw = match is_raw_mode_enabled() { Ok(val) => val, Err(e) => { debug!("Failed to check raw mode status: {:?}\r", e); return; } }; if is_raw == raw_before { debug!("Raw mode status unchanged from raw={raw_before}.\r"); } else if let Err(e) = restore_raw_status(raw_before) { debug!("Failed to restore raw mode: {e:?} to raw={raw_before}\r"); } else { debug!("Raw mode restored to previous state (raw={raw_before}).\r"); } if let Err(e) = clear_stdin() { debug!("Failed to clear stdin: {e:?}\r"); } else { debug!("Cleared any excess from stdin.\r"); } } if !raw_before { terminal::enable_raw_mode()?; } // Send the query stderr.write_all(query.as_bytes())?; stderr.flush()?; let start_time = Instant::now(); // Enter raw mode to capture input terminal::enable_raw_mode()?; let mut stdin = io::stdin(); let mut response = String::new(); // Main loop to capture response loop { // Check for timeout if start_time.elapsed() > timeout { terminal::disable_raw_mode()?; // Clean up raw mode return Err(io::Error::new(io::ErrorKind::TimedOut, "timeout 4").into()); } // Non-blocking read attempt from stdin let mut buffer = [0u8; 1]; if stdin.read(&mut buffer).is_ok() { response.push(buffer[0] as char); // End the loop once we detect the 'n' character if response.ends_with('n') { let elapsed = start_time.elapsed(); debug!("Latency full response: [{response:x?}]\r"); // debug!("Elapsed time: {elapsed:?}\r"); return Ok(elapsed); } } } } fn decode_x11_color(s: &str) -> Result<(u16, u16, u16), Error> { fn decode_hex(s: &str) -> Result { let len = s.len() as u32; let mut ret = u16::from_str_radix(s, 16).map_err(|_| Error::Parse(String::from(s)))?; ret = ret << ((4 - len) * 4); Ok(ret) } let rgb: Vec<_> = s.split('/').collect(); let r = rgb.get(0).ok_or_else(|| Error::Parse(String::from(s)))?; let g = rgb.get(1).ok_or_else(|| Error::Parse(String::from(s)))?; let b = rgb.get(2).ok_or_else(|| Error::Parse(String::from(s)))?; let r = decode_hex(r)?; let g = decode_hex(g)?; let b = decode_hex(b)?; Ok((r, g, b)) } /// Try to determine the background colour from the legacy Windows Console interface. /// Unfortunately, unless the colour was explicitly set by that interface, it will /// just return the default of rgb(0,0,0). This renders it effectively useless for /// modern Windows. /// /// # Errors /// /// This function will bubble up any errors returned by the Windows API. #[cfg(target_os = "windows")] fn from_winapi() -> Result { debug!("In from_winapi()\r"); let info = unsafe { let handle = winapi::um::processenv::GetStdHandle(winapi::um::winbase::STD_OUTPUT_HANDLE); let mut info: wincon::CONSOLE_SCREEN_BUFFER_INFO = Default::default(); wincon::GetConsoleScreenBufferInfo(handle, &mut info); info }; debug!("info.wAttributes={:x?}\r", info.wAttributes); let r = (wincon::BACKGROUND_RED & info.wAttributes) != 0; let g = (wincon::BACKGROUND_GREEN & info.wAttributes) != 0; let b = (wincon::BACKGROUND_BLUE & info.wAttributes) != 0; let i = (wincon::BACKGROUND_INTENSITY & info.wAttributes) != 0; let r: u8 = r as u8; let g: u8 = g as u8; let b: u8 = b as u8; let i: u8 = i as u8; let (r, g, b) = match (r, g, b, i) { (0, 0, 0, 0) => (0, 0, 0), (1, 0, 0, 0) => (128, 0, 0), (0, 1, 0, 0) => (0, 128, 0), (1, 1, 0, 0) => (128, 128, 0), (0, 0, 1, 0) => (0, 0, 128), (1, 0, 1, 0) => (128, 0, 128), (0, 1, 1, 0) => (0, 128, 128), (1, 1, 1, 0) => (192, 192, 192), (0, 0, 0, 1) => (128, 128, 128), (1, 0, 0, 1) => (255, 0, 0), (0, 1, 0, 1) => (0, 255, 0), (1, 1, 0, 1) => (255, 255, 0), (0, 0, 1, 1) => (0, 0, 255), (1, 0, 1, 1) => (255, 0, 255), (0, 1, 1, 1) => (0, 255, 255), (1, 1, 1, 1) => (255, 255, 255), _ => unreachable!(), }; Ok(Rgb { r: r * 256, g: g * 256, b: b * 256, }) } #[cfg(test)] mod tests { use super::*; use crossterm::event::{Event, KeyEvent}; use either::Either; use mockall::mock; use std::{ io::{self, Write}, iter::{self, Cloned}, slice::Iter, sync::{Arc, Mutex}, thread::sleep, time::Duration, }; // Xterm expected query const ESC_OSC_QUERY: &[u8; 8] = b"\x1b]11;?\x1b\\"; // Base constant response for successful RGB parsing. const RGB_RESPONSE: &[Event] = &[ Event::Key(KeyEvent::new(KeyCode::Char(']'), KeyModifiers::ALT)), Event::Key(KeyEvent::new(KeyCode::Char('1'), KeyModifiers::NONE)), Event::Key(KeyEvent::new(KeyCode::Char('1'), KeyModifiers::NONE)), Event::Key(KeyEvent::new(KeyCode::Char(';'), KeyModifiers::NONE)), Event::Key(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::NONE)), Event::Key(KeyEvent::new(KeyCode::Char('g'), KeyModifiers::NONE)), Event::Key(KeyEvent::new(KeyCode::Char('b'), KeyModifiers::NONE)), Event::Key(KeyEvent::new(KeyCode::Char(':'), KeyModifiers::NONE)), Event::Key(KeyEvent::new(KeyCode::Char('f'), KeyModifiers::NONE)), Event::Key(KeyEvent::new(KeyCode::Char('f'), KeyModifiers::NONE)), Event::Key(KeyEvent::new(KeyCode::Char('/'), KeyModifiers::NONE)), Event::Key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::NONE)), Event::Key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::NONE)), Event::Key(KeyEvent::new(KeyCode::Char('/'), KeyModifiers::NONE)), Event::Key(KeyEvent::new(KeyCode::Char('9'), KeyModifiers::NONE)), Event::Key(KeyEvent::new(KeyCode::Char('9'), KeyModifiers::NONE)), ]; const RGB_RESPONSE_LEN: usize = RGB_RESPONSE.len(); // Helper method for setting up and invoking call to query_xterm. fn run_query_xterm_test( emulate_response: bool, num_to_send: usize, // Excluding any terminator maybe_terminator: Option<&Event>, expected_rgb: Option<(u16, u16, u16)>, ) { eprintln!("Testing for terminator {maybe_terminator:?}"); // Set up the mock writer and mock event reader let mut mock_writer = MockWriter::new(); let mut mock_event_reader = MockEventReader::new(); // Expect the query write once with the appropriate OSC command mock_writer .expect_write() .withf(move |buf| buf == ESC_OSC_QUERY) .times(1) .returning(|_| Ok(ESC_OSC_QUERY.len())); // Expect flush to be called once, returning Ok mock_writer.expect_flush().times(1).returning(|| Ok(())); // Shared, thread-safe counter for events let event_count = Arc::new(Mutex::new(0)); let total_events = if emulate_response { num_to_send + if maybe_terminator.is_some() { 1 } else { 0 } } else { 0 }; // Clone `event_count` so each closure can access the same counter let poll_event_count = Arc::clone(&event_count); let read_event_count = Arc::clone(&event_count); // Mock the behavior of `poll()` using the counter mock_event_reader.expect_poll().returning(move |_| { let count = poll_event_count.lock().unwrap(); if *count < total_events { Ok(true) // More events to process } else { Ok(false) // No more events left, stop responding to polling } }); let base_iterator = RGB_RESPONSE.iter().cloned(); let mut response_iter: Either< Cloned>, std::iter::Chain>, iter::Once>, > = if let Some(terminator) = maybe_terminator { Either::Right(base_iterator.chain(iter::once(terminator.clone()))) } else { Either::Left(base_iterator) }; mock_event_reader.expect_read_event().returning(move || { let event_count = Arc::clone(&read_event_count); let mut count = event_count.lock().unwrap(); if *count < total_events { *count += 1; // Increment the count as we read each event // debug!("\rIn expect_read_event, increasing count to {count}, total_events={total_events}, responding"); response_iter.next().ok_or_else(|| { // Block here without returning, simulating a "wait" condition sleep(Duration::from_secs(2)); io::Error::new(io::ErrorKind::TimedOut, "timeout 2").into() }) } else { // debug!("\rIn expect_read_event, count={count}, total_events={total_events}, why are we here?"); // Block here without returning, simulating a "wait" condition sleep(Duration::from_secs(3)); Err(io::Error::new(io::ErrorKind::TimedOut, "timeout 3").into()) // Optionally return an error after some time } }); // Run the `query_xterm` function and assert the results let result = query_xterm( Terminal::XtermCompatible, Duration::from_secs(1), &mock_event_reader, &mut mock_writer, ); debug!("result={result:?}\r"); match expected_rgb { Some((r, g, b)) => { let rgb = result.expect("Expected successful RGB parsing"); assert_eq!( rgb, Rgb { r, g, b }, "RGB values do not match expected for terminator {maybe_terminator:?}", ); } None => { assert!(result.is_err(), "Expected an error for this scenario"); } } } // Mock the `Write` trait to use in testing mock! { #[derive(Debug)] Writer {} impl Write for Writer { fn write(&mut self, buf: &[u8]) -> io::Result; fn flush(&mut self) -> io::Result<()>; } } // Expect response values expressed in 16-bit space #[test] fn test_query_xterm_with_various_terminators() { const TERMINATORS: &[Event] = &[ Event::Key(KeyEvent::new( KeyCode::Char('g'), // BEL equivalent KeyModifiers::CONTROL, )), Event::Key(KeyEvent::new( KeyCode::Char(0x07_u8 as char), KeyModifiers::NONE, )), // Raw BEL Event::Key(KeyEvent::new( KeyCode::Char(0x09c_u8 as char), KeyModifiers::NONE, )), // Raw ST Event::Key(KeyEvent::new( KeyCode::Char(0x5c_u8 as char), KeyModifiers::ALT, )), // Esc-5c mapped to Alt-5c, equivalent to Alt-\ Event::Key(KeyEvent::new( KeyCode::Char(0x5c_u8 as char), KeyModifiers::NONE, )), // Esc-5c missing the Esc, equivalent to \ Event::Key(KeyEvent::new(KeyCode::Char('\\'), KeyModifiers::ALT)), // Esc-\ mapped to Alt-\ Event::Key(KeyEvent::new(KeyCode::Char('\\'), KeyModifiers::NONE)), // Esc-\ missing the Esc Event::Key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE)), // Represents any unrecognised value, should be corrected on timeout ]; let expected_rgb = Some((0xff * 256, 0xcc * 256, 0x99 * 256)); for terminator in TERMINATORS { run_query_xterm_test(true, RGB_RESPONSE_LEN, Some(terminator), expected_rgb); } } // Expect timeout #[test] fn test_query_xterm_timeout_no_response() { // Test timeout scenario: No response received run_query_xterm_test(false, RGB_RESPONSE_LEN, None, None); } // Expect timeout #[test] fn test_query_xterm_timeout_incomplete_response_1() { // Test timeout scenario: Incomplete response, e.g., missing terminator run_query_xterm_test(true, RGB_RESPONSE_LEN - 4, None, None); } // Expect timeout #[test] fn test_query_xterm_timeout_incomplete_response_2() { // Test timeout scenario: Incomplete response, e.g., missing terminator run_query_xterm_test(true, RGB_RESPONSE_LEN - 1, None, None); } // Expect query_xterm to pick it up and reconstitute the response on timeout check #[test] fn test_query_xterm_timeout_unterminated_response() { // Test timeout scenario: Incomplete response, e.g., missing terminator run_query_xterm_test( true, RGB_RESPONSE_LEN, None, Some((0xff * 256, 0xcc * 256, 0x99 * 256)), ); } #[test] fn test_decode_x11_color() { let s = "0000/0000/0000"; assert_eq!((0, 0, 0), decode_x11_color(s).unwrap()); let s = "1111/2222/3333"; assert_eq!((0x1111, 0x2222, 0x3333), decode_x11_color(s).unwrap()); let s = "111/222/333"; assert_eq!((0x1110, 0x2220, 0x3330), decode_x11_color(s).unwrap()); let s = "11/22/33"; assert_eq!((0x1100, 0x2200, 0x3300), decode_x11_color(s).unwrap()); let s = "1/2/3"; assert_eq!((0x1000, 0x2000, 0x3000), decode_x11_color(s).unwrap()); } }