Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

fix(picker): vendor skim-tuikit with write_all in Output::flush (#2226)

Maximilian Rooseac94579d37a
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 9d0e32d9d..a4838a6bd 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -3,12 +3,13 @@ repos:
rev: v6.0.0
hooks:
- id: end-of-file-fixer
- exclude: '.*\.snap$'
+ exclude: '.*\.snap$|^vendor/'
- id: check-yaml
- id: mixed-line-ending
+ exclude: '^vendor/'
- id: trailing-whitespace
# rustfmt handles rust files, and in snapshots we expect trailing spaces.
- exclude: '.*\.(rs|snap)$'
+ exclude: '.*\.(rs|snap)$|^vendor/'
# pre-commit autoupdate reverts to mutable v1 tag; update manually
- repo: https://github.com/crate-ci/typos
rev: v1.45.0
@@ -20,6 +21,7 @@ repos:
rev: v1.0.1
hooks:
- id: fmt
+ exclude: '^vendor/'
- repo: https://github.com/r0x0d/pre-commit-rust
rev: v1.0.1
hooks:
@@ -58,7 +60,7 @@ repos:
# format.rs strips ANSI codes injected by wrap_ansi crate
# picker tests verify ANSI dimming behavior
# src/testing: validate_ansi_codes tests raw escape sequences
- exclude: '^(tests/|.*_test\.rs$|src/styling/(mod|format)\.rs$|src/commands/picker/|src/testing/)'
+ exclude: '^(tests/|.*_test\.rs$|src/styling/(mod|format)\.rs$|src/commands/picker/|src/testing/|vendor/)'
- id: no-std-canonicalize-in-tests
name: no-std-canonicalize-in-tests
description: Use dunce::canonicalize in tests to avoid Windows \\?\ prefix issues
diff --git a/.typos.toml b/.typos.toml
index fc41584bc..66c2d3be3 100644
--- a/.typos.toml
+++ b/.typos.toml
@@ -1,5 +1,5 @@
[files]
-extend-exclude = ["docs/demos/vhs-keystrokes/", "*.snap"]
+extend-exclude = ["docs/demos/vhs-keystrokes/", "*.snap", "vendor/"]
[default.extend-words]
# Git commit hashes that typos flags as potential typos
diff --git a/Cargo.lock b/Cargo.lock
index 4ad245dd0..d8911ff6e 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2242,8 +2242,6 @@ checksum = "d8312ae7ca1a5883e68042b9c6bce05bfc12f06b814ecfda06c34abfb6c88175"
[[package]]
name = "skim-tuikit"
version = "0.6.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cb54242783b4234134359fea4d11f26879c49ace6c00c5d402fd04a5ab2ad7bd"
dependencies = [
"bitflags 1.3.2",
"lazy_static",
diff --git a/Cargo.toml b/Cargo.toml
index 54a7463c0..0b6c2ad4c 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -175,3 +175,14 @@ unsafe_code = "forbid"
[profile.dist]
inherits = "release"
lto = "thin"
+
+[patch.crates-io]
+# Local fork of skim-tuikit 0.6.6 with a one-line fix for a dropped-bytes
+# bug in `Output::flush` — it used `write()` instead of `write_all()`, so
+# when the kernel accepted a partial write (common under load or in tmux
+# PTYs with small pipe buffers) the remainder of the buffer was dropped by
+# the subsequent `buffer.clear()`, leaving the picker's first render
+# missing whichever rows didn't fit in the first chunk. Upstream fix
+# proposed in skim-rs/skim#1056; drop this patch once merged and released.
+# See vendor/skim-tuikit/src/output.rs and `task vendor-diff`.
+skim-tuikit = { path = "vendor/skim-tuikit" }
diff --git a/Taskfile.yaml b/Taskfile.yaml
index 3bff1359d..5d38abba8 100644
--- a/Taskfile.yaml
+++ b/Taskfile.yaml
@@ -13,6 +13,29 @@ tasks:
desc: Run tests with coverage report
cmd: cargo llvm-cov --html --features shell-integration-tests {{.CLI_ARGS}}
+ vendor-diff:
+ desc: Show the patch we carry in vendor/ vs the pristine upstream crate source
+ cmds:
+ - |
+ set -e
+ VENDORED=vendor/skim-tuikit
+ if [ ! -d "$VENDORED" ]; then
+ echo "no vendored source at $VENDORED"
+ exit 0
+ fi
+ VERSION=$(sed -n 's/^version = "\(.*\)"/\1/p' "$VENDORED/Cargo.toml" | head -1)
+ # Fetch the pristine tarball directly from crates.io rather than relying
+ # on ~/.cargo/registry — `[patch.crates-io]` suppresses the download, so
+ # that cache is never populated on a fresh checkout.
+ TMP=$(mktemp -d)
+ trap 'rm -rf "$TMP"' EXIT
+ URL="https://static.crates.io/crates/skim-tuikit/skim-tuikit-${VERSION}.crate"
+ if ! curl -sSfL "$URL" | tar -xz -C "$TMP"; then
+ echo "failed to fetch pristine skim-tuikit-${VERSION} from $URL"
+ exit 1
+ fi
+ diff -ruN "$TMP/skim-tuikit-${VERSION}" "$VENDORED" || true
+
setup-web:
desc: Setup Claude Code web environment for development
platforms: [linux]
diff --git a/vendor/skim-tuikit/.cargo-ok b/vendor/skim-tuikit/.cargo-ok
new file mode 100644
index 000000000..5f8b79583
--- /dev/null
+++ b/vendor/skim-tuikit/.cargo-ok
@@ -0,0 +1 @@
+{"v":1}
\ No newline at end of file
diff --git a/vendor/skim-tuikit/.cargo_vcs_info.json b/vendor/skim-tuikit/.cargo_vcs_info.json
new file mode 100644
index 000000000..179f66cd6
--- /dev/null
+++ b/vendor/skim-tuikit/.cargo_vcs_info.json
@@ -0,0 +1,6 @@
+{
+ "git": {
+ "sha1": "06c3a13ba7b8b8a3f5101031215807b0b9672107"
+ },
+ "path_in_vcs": "skim-tuikit"
+}
\ No newline at end of file
diff --git a/vendor/skim-tuikit/.gitignore b/vendor/skim-tuikit/.gitignore
new file mode 100644
index 000000000..2bb8d2531
--- /dev/null
+++ b/vendor/skim-tuikit/.gitignore
@@ -0,0 +1,3 @@
+/target
+**/*.rs.bk
+.idea
diff --git a/vendor/skim-tuikit/Cargo.lock b/vendor/skim-tuikit/Cargo.lock
new file mode 100644
index 000000000..956dd1163
--- /dev/null
+++ b/vendor/skim-tuikit/Cargo.lock
@@ -0,0 +1,516 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "aho-corasick"
+version = "1.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "anstream"
+version = "0.6.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3ae563653d1938f79b1ab1b5e668c87c76a9930414574a6583a7b7e11a8e6192"
+dependencies = [
+ "anstyle",
+ "anstyle-parse",
+ "anstyle-query",
+ "anstyle-wincon",
+ "colorchoice",
+ "is_terminal_polyfill",
+ "utf8parse",
+]
+
+[[package]]
+name = "anstyle"
+version = "1.0.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "862ed96ca487e809f1c8e5a8447f6ee2cf102f846893800b20cebdf541fc6bbd"
+
+[[package]]
+name = "anstyle-parse"
+version = "0.2.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2"
+dependencies = [
+ "utf8parse",
+]
+
+[[package]]
+name = "anstyle-query"
+version = "1.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9e231f6134f61b71076a3eab506c379d4f36122f2af15a9ff04415ea4c3339e2"
+dependencies = [
+ "windows-sys",
+]
+
+[[package]]
+name = "anstyle-wincon"
+version = "3.0.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3e0633414522a32ffaac8ac6cc8f748e090c5717661fddeea04219e2344f5f2a"
+dependencies = [
+ "anstyle",
+ "once_cell_polyfill",
+ "windows-sys",
+]
+
+[[package]]
+name = "bitflags"
+version = "1.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
+
+[[package]]
+name = "bitflags"
+version = "2.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1b8e56985ec62d17e9c1001dc89c88ecd7dc08e47eba5ec7c29c7b5eeecde967"
+
+[[package]]
+name = "cfg-if"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9555578bc9e57714c812a1f84e4fc5b4d21fcb063490c624de019f7464c91268"
+
+[[package]]
+name = "cfg_aliases"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
+
+[[package]]
+name = "colorchoice"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75"
+
+[[package]]
+name = "dirs-next"
+version = "2.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b98cf8ebf19c3d1b223e151f99a4f9f0690dca41414773390fc824184ac833e1"
+dependencies = [
+ "cfg-if",
+ "dirs-sys-next",
+]
+
+[[package]]
+name = "dirs-sys-next"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ebda144c4fe02d1f7ea1a7d9641b6fc6b580adcfa024ae48797ecdeb6825b4d"
+dependencies = [
+ "libc",
+ "redox_users",
+ "winapi",
+]
+
+[[package]]
+name = "env_filter"
+version = "0.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "186e05a59d4c50738528153b83b0b0194d3a29507dfec16eccd4b342903397d0"
+dependencies = [
+ "log",
+ "regex",
+]
+
+[[package]]
+name = "env_logger"
+version = "0.11.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "13c863f0904021b108aa8b2f55046443e6b1ebde8fd4a15c399893aae4fa069f"
+dependencies = [
+ "anstream",
+ "anstyle",
+ "env_filter",
+ "jiff",
+ "log",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.2.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "wasi",
+]
+
+[[package]]
+name = "is_terminal_polyfill"
+version = "1.70.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf"
+
+[[package]]
+name = "jiff"
+version = "0.2.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "be1f93b8b1eb69c77f24bbb0afdf66f54b632ee39af40ca21c4365a1d7347e49"
+dependencies = [
+ "jiff-static",
+ "log",
+ "portable-atomic",
+ "portable-atomic-util",
+ "serde",
+]
+
+[[package]]
+name = "jiff-static"
+version = "0.2.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "03343451ff899767262ec32146f6d559dd759fdadf42ff0e227c7c48f72594b4"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "lazy_static"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
+
+[[package]]
+name = "libc"
+version = "0.2.174"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1171693293099992e19cddea4e8b849964e9846f4acee11b3948bcc337be8776"
+
+[[package]]
+name = "libredox"
+version = "0.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "391290121bad3d37fbddad76d8f5d1c1c314cfc646d143d7e07a3086ddff0ce3"
+dependencies = [
+ "bitflags 2.9.1",
+ "libc",
+]
+
+[[package]]
+name = "log"
+version = "0.4.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94"
+
+[[package]]
+name = "memchr"
+version = "2.7.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a282da65faaf38286cf3be983213fcf1d2e2a58700e808f83f4ea9a4804bc0"
+
+[[package]]
+name = "nix"
+version = "0.29.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46"
+dependencies = [
+ "bitflags 2.9.1",
+ "cfg-if",
+ "cfg_aliases",
+ "libc",
+]
+
+[[package]]
+name = "once_cell_polyfill"
+version = "1.70.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a4895175b425cb1f87721b59f0f286c2092bd4af812243672510e1ac53e2e0ad"
+
+[[package]]
+name = "portable-atomic"
+version = "1.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f84267b20a16ea918e43c6a88433c2d54fa145c92a811b5b047ccbe153674483"
+
+[[package]]
+name = "portable-atomic-util"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d8a2f0d8d040d7848a709caf78912debcc3f33ee4b3cac47d73d1e1069e83507"
+dependencies = [
+ "portable-atomic",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.95"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.40"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "redox_users"
+version = "0.4.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43"
+dependencies = [
+ "getrandom",
+ "libredox",
+ "thiserror",
+]
+
+[[package]]
+name = "regex"
+version = "1.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-automata",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-automata"
+version = "0.4.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-syntax"
+version = "0.8.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c"
+
+[[package]]
+name = "rustversion"
+version = "1.0.22"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
+
+[[package]]
+name = "serde"
+version = "1.0.219"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.219"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "skim-common"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d8312ae7ca1a5883e68042b9c6bce05bfc12f06b814ecfda06c34abfb6c88175"
+
+[[package]]
+name = "skim-tuikit"
+version = "0.6.6"
+dependencies = [
+ "bitflags 1.3.2",
+ "env_logger",
+ "lazy_static",
+ "log",
+ "nix",
+ "skim-common",
+ "term",
+ "unicode-width",
+]
+
+[[package]]
+name = "syn"
+version = "2.0.104"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "17b6f705963418cdb9927482fa304bc562ece2fdd4f616084c50b7023b435a40"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "term"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c59df8ac95d96ff9bede18eb7300b0fda5e5d8d90960e76f8e14ae765eedbf1f"
+dependencies = [
+ "dirs-next",
+ "rustversion",
+ "winapi",
+]
+
+[[package]]
+name = "thiserror"
+version = "1.0.69"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
+dependencies = [
+ "thiserror-impl",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "1.0.69"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512"
+
+[[package]]
+name = "unicode-width"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4a1a07cc7db3810833284e8d372ccdc6da29741639ecc70c9ec107df0fa6154c"
+
+[[package]]
+name = "utf8parse"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
+
+[[package]]
+name = "wasi"
+version = "0.11.1+wasi-snapshot-preview1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
+
+[[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-x86_64-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
+
+[[package]]
+name = "windows-link"
+version = "0.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a"
+
+[[package]]
+name = "windows-sys"
+version = "0.60.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"
+dependencies = [
+ "windows-targets",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.53.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d5fe6031c4041849d7c496a8ded650796e7b6ecc19df1a431c1a363342e5dc91"
+dependencies = [
+ "windows-link",
+ "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.53.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "86b8d5f90ddd19cb4a147a5fa63ca848db3df085e25fee3cc10b39b6eebae764"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.53.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c7651a1f62a11b8cbd5e0d42526e55f2c99886c77e007179efff86c2b137e66c"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.53.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c1dc67659d35f387f5f6c479dc4e28f1d4bb90ddd1a5d3da2e5d97b42d6272c3"
+
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.53.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ce6ccbdedbf6d6354471319e781c0dfef054c81fbc7cf83f338a4296c0cae11"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.53.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "581fee95406bb13382d2f65cd4a908ca7b1e4c2f1917f143ba16efe98a589b5d"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.53.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2e55b5ac9ea33f2fc1716d1742db15574fd6fc8dadc51caab1c16a3d3b4190ba"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.53.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0a6e035dd0599267ce1ee132e51c27dd29437f63325753051e71dd9e42406c57"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.53.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486"
diff --git a/vendor/skim-tuikit/Cargo.toml b/vendor/skim-tuikit/Cargo.toml
new file mode 100644
index 000000000..490db32aa
--- /dev/null
+++ b/vendor/skim-tuikit/Cargo.toml
@@ -0,0 +1,115 @@
+# 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 = "2024"
+name = "skim-tuikit"
+version = "0.6.6"
+authors = ["Jinzhou Zhang <[email protected]>"]
+build = false
+autolib = false
+autobins = false
+autoexamples = false
+autotests = false
+autobenches = false
+description = "Toolkit for writing TUI applications"
+homepage = "https://github.com/skim-rs/skim"
+documentation = "https://docs.rs/skim-tuikit"
+readme = "README.md"
+keywords = [
+ "tui",
+ "terminal",
+ "tty",
+ "color",
+]
+license = "MIT"
+repository = "https://github.com/skim-rs/skim"
+resolver = "2"
+
+[lib]
+name = "skim_tuikit"
+path = "src/lib.rs"
+
+[[example]]
+name = "256color"
+path = "examples/256color.rs"
+
+[[example]]
+name = "256color_on_screen"
+path = "examples/256color_on_screen.rs"
+
+[[example]]
+name = "custom-event"
+path = "examples/custom-event.rs"
+
+[[example]]
+name = "get_keys"
+path = "examples/get_keys.rs"
+
+[[example]]
+name = "hello-world"
+path = "examples/hello-world.rs"
+
+[[example]]
+name = "split"
+path = "examples/split.rs"
+
+[[example]]
+name = "stack"
+path = "examples/stack.rs"
+
+[[example]]
+name = "term_size"
+path = "examples/term_size.rs"
+
+[[example]]
+name = "termbox"
+path = "examples/termbox.rs"
+
+[[example]]
+name = "true_color"
+path = "examples/true_color.rs"
+
+[[example]]
+name = "win"
+path = "examples/win.rs"
+
+[dependencies.bitflags]
+version = "1.3.2"
+
+[dependencies.lazy_static]
+version = "1.2.0"
+
+[dependencies.log]
+version = "0.4.27"
+
+[dependencies.nix]
+version = "0.29.0"
+features = [
+ "fs",
+ "fs",
+ "poll",
+ "signal",
+ "term",
+]
+default-features = false
+
+[dependencies.skim-common]
+version = "0.2.0"
+
+[dependencies.term]
+version = "0.7"
+
+[dependencies.unicode-width]
+version = "0.2.1"
+
+[dev-dependencies.env_logger]
+version = "0.11.6"
diff --git a/vendor/skim-tuikit/Cargo.toml.orig b/vendor/skim-tuikit/Cargo.toml.orig
new file mode 100644
index 000000000..afcf3bfe6
--- /dev/null
+++ b/vendor/skim-tuikit/Cargo.toml.orig
@@ -0,0 +1,24 @@
+[package]
+name = "skim-tuikit"
+version = "0.6.6"
+authors = ["Jinzhou Zhang <[email protected]>"]
+description = "Toolkit for writing TUI applications"
+documentation = "https://docs.rs/skim-tuikit"
+homepage = "https://github.com/skim-rs/skim"
+repository = "https://github.com/skim-rs/skim"
+readme = "README.md"
+keywords = ["tui", "terminal", "tty", "color"]
+license = "MIT"
+edition = "2024"
+
+[dependencies]
+bitflags = { workspace = true }
+skim-common = { path = "../skim-common/", version = "0.2.0" }
+lazy_static = { workspace = true }
+log = { workspace = true }
+nix = { workspace = true, default-features = false, features = ["fs", "poll", "signal", "term"] }
+term = { workspace = true }
+unicode-width = { workspace = true }
+
+[dev-dependencies]
+env_logger = { workspace = true }
diff --git a/vendor/skim-tuikit/LICENSE b/vendor/skim-tuikit/LICENSE
new file mode 100644
index 000000000..456b81bc5
--- /dev/null
+++ b/vendor/skim-tuikit/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2016 Jinzhou Zhang
+
+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.
diff --git a/vendor/skim-tuikit/README.md b/vendor/skim-tuikit/README.md
new file mode 100644
index 000000000..a3f824d0d
--- /dev/null
+++ b/vendor/skim-tuikit/README.md
@@ -0,0 +1,142 @@
+[![Crates.io](https://img.shields.io/crates/v/skim-tuikit.svg)](https://crates.io/crates/skim-tuikit)
+
+## Tuikit
+
+Tuikit is a TUI library for writing terminal UI applications. Highlights:
+
+- Thread safe.
+- Support non-fullscreen mode as well as fullscreen mode.
+- Support `Alt` keys, mouse events, etc.
+- Buffering for efficient rendering.
+
+Tuikit is modeld after [termbox](https://github.com/nsf/termbox) which views the
+terminal as a table of fixed-size cells and input being a stream of structured
+messages.
+
+**WARNING**: The library is not stable yet, the API might change.
+
+## Usage
+
+In your `Cargo.toml` add the following:
+
+```toml
+[dependencies]
+skim-tuikit = "*"
+```
+
+
+Here is an example (could also be run by `cargo run --example hello-world`):
+
+```rust
+use skim_tuikit::prelude::*;
+use std::cmp::{min, max};
+
+fn main() {
+ let term: Term<()> = Term::with_height(TermHeight::Percent(30)).unwrap();
+ let mut row = 1;
+ let mut col = 0;
+
+ let _ = term.print(0, 0, "press arrow key to move the text, (q) to quit");
+ let _ = term.present();
+
+ while let Ok(ev) = term.poll_event() {
+ let _ = term.clear();
+ let _ = term.print(0, 0, "press arrow key to move the text, (q) to quit");
+
+ let (width, height) = term.term_size().unwrap();
+ match ev {
+ Event::Key(Key::ESC) | Event::Key(Key::Char('q')) => break,
+ Event::Key(Key::Up) => row = max(row-1, 1),
+ Event::Key(Key::Down) => row = min(row+1, height-1),
+ Event::Key(Key::Left) => col = max(col, 1)-1,
+ Event::Key(Key::Right) => col = min(col+1, width-1),
+ _ => {}
+ }
+
+ let attr = Attr{ fg: Color::RED, ..Attr::default() };
+ let _ = term.print_with_attr(row, col, "Hello World! 你好!今日は。", attr);
+ let _ = term.set_cursor(row, col);
+ let _ = term.present();
+ }
+}
+```
+
+## Layout
+
+`tuikit` provides `HSplit`, `VSplit` and `Win` for managing layouts:
+
+1. `HSplit` allow you to split area horizontally into pieces.
+2. `VSplit` works just like `HSplit` but splits vertically.
+3. `Win` do not split, it could have margin, padding and border.
+
+For example:
+
+```rust
+use skim_tuikit::prelude::*;
+
+struct Model(String);
+
+impl Draw for Model {
+ fn draw(&self, canvas: &mut dyn Canvas) -> DrawResult<()> {
+ let (width, height) = canvas.size()?;
+ let message_width = self.0.len();
+ let left = (width - message_width) / 2;
+ let top = height / 2;
+ let _ = canvas.print(top, left, &self.0);
+ Ok(())
+ }
+}
+
+impl Widget for Model{}
+
+fn main() {
+ let term: Term<()> = Term::with_height(TermHeight::Percent(50)).unwrap();
+ let model = Model("middle!".to_string());
+
+ while let Ok(ev) = term.poll_event() {
+ if let Event::Key(Key::Char('q')) = ev {
+ break;
+ }
+ let _ = term.print(0, 0, "press 'q' to exit");
+
+ let hsplit = HSplit::default()
+ .split(
+ VSplit::default()
+ .basis(Size::Percent(30))
+ .split(Win::new(&model).border(true).basis(Size::Percent(30)))
+ .split(Win::new(&model).border(true).basis(Size::Percent(30)))
+ )
+ .split(Win::new(&model).border(true));
+
+ let _ = term.draw(&hsplit);
+ let _ = term.present();
+ }
+}
+```
+
+The split algorithm is simple:
+
+1. Both `HSplit` and `VSplit` will take several `Split` where a `Split` would
+ contains:
+ 1. basis, the original size
+ 2. grow, the factor to grow if there is still enough room
+ 3. shrink, the factor to shrink if there is not enough room
+2. `HSplit/VSplit` will count the total width/height(basis) of the split items
+3. Judge if the current width/height is enough or not for the split items
+4. shrink/grow the split items according to their grow/shrink: `factor / sum(factors)`
+5. If still not enough room, the last one(s) would be set width/height 0
+
+## References
+
+`Tuikit` borrows ideas from lots of other projects:
+
+- [rustyline](https://github.com/kkawakam/rustyline) Readline Implementation in Rust.
+ - How to enter the raw mode.
+ - Part of the keycode parsing logic.
+- [termion](https://gitlab.redox-os.org/redox-os/termion) A bindless library for controlling terminals/TTY.
+ - How to parse mouse events.
+ - How to enter raw mode.
+- [rustbox](https://github.com/gchp/rustbox) and [termbox](https://github.com/nsf/termbox)
+ - The idea of viewing terminal as table of fixed cells.
+- [termfest](https://github.com/agatan/termfest) Easy TUI library written in Rust
+ - The buffering idea.
diff --git a/vendor/skim-tuikit/examples/256color.rs b/vendor/skim-tuikit/examples/256color.rs
new file mode 100644
index 000000000..dae0ebbde
--- /dev/null
+++ b/vendor/skim-tuikit/examples/256color.rs
@@ -0,0 +1,31 @@
+use skim_tuikit::attr::Color;
+use skim_tuikit::output::Output;
+use std::io;
+
+fn main() {
+ let mut output = Output::new(Box::new(io::stdout())).unwrap();
+
+ for fg in 0..=255 {
+ output.set_fg(Color::AnsiValue(fg));
+ output.write(format!("{:5}", fg).as_str());
+ if fg % 16 == 15 {
+ output.reset_attributes();
+ output.write("\n");
+ output.flush()
+ }
+ }
+
+ output.reset_attributes();
+
+ for bg in 0..=255 {
+ output.set_bg(Color::AnsiValue(bg));
+ output.write(format!("{:5}", bg).as_str());
+ if bg % 16 == 15 {
+ output.reset_attributes();
+ output.write("\n");
+ output.flush()
+ }
+ }
+
+ output.flush()
+}
diff --git a/vendor/skim-tuikit/examples/256color_on_screen.rs b/vendor/skim-tuikit/examples/256color_on_screen.rs
new file mode 100644
index 000000000..493b0a499
--- /dev/null
+++ b/vendor/skim-tuikit/examples/256color_on_screen.rs
@@ -0,0 +1,48 @@
+use skim_tuikit::attr::{Attr, Color};
+use skim_tuikit::canvas::Canvas;
+use skim_tuikit::output::Output;
+use skim_tuikit::screen::Screen;
+use std::io;
+
+fn main() {
+ let mut output = Output::new(Box::new(io::stdout())).unwrap();
+ let (width, height) = output.terminal_size().unwrap();
+ let mut screen = Screen::new(width, height);
+
+ for fg in 0..=255 {
+ let _ = screen.print_with_attr(
+ fg / 16,
+ (fg % 16) * 5,
+ format!("{:5}", fg).as_str(),
+ Color::AnsiValue(fg as u8).into(),
+ );
+ }
+
+ let _ = screen.set_cursor(15, 80);
+ let commands = screen.present();
+
+ commands.into_iter().for_each(|cmd| output.execute(cmd));
+ output.flush();
+
+ let _ = screen.print_with_attr(0, 78, "HELLO WORLD", Attr::default());
+ let commands = screen.present();
+
+ commands.into_iter().for_each(|cmd| output.execute(cmd));
+ output.flush();
+
+ for bg in 0..=255 {
+ let _ = screen.print_with_attr(
+ bg / 16,
+ (bg % 16) * 5,
+ format!("{:5}", bg).as_str(),
+ Attr {
+ bg: Color::AnsiValue(bg as u8),
+ ..Attr::default()
+ },
+ );
+ }
+ let commands = screen.present();
+ commands.into_iter().for_each(|cmd| output.execute(cmd));
+ output.reset_attributes();
+ output.flush()
+}
diff --git a/vendor/skim-tuikit/examples/custom-event.rs b/vendor/skim-tuikit/examples/custom-event.rs
new file mode 100644
index 000000000..9873e9ca4
--- /dev/null
+++ b/vendor/skim-tuikit/examples/custom-event.rs
@@ -0,0 +1,24 @@
+use bitflags::_core::result::Result::Ok;
+
+use skim_tuikit::prelude::*;
+
+fn main() {
+ let term: Term<String> = Term::with_height(TermHeight::Percent(30)).expect("term creation error");
+ let _ = term.print(0, 0, "Press 'q' or 'Ctrl-c' to quit!");
+ while let Ok(ev) = term.poll_event() {
+ match ev {
+ Event::Key(Key::Char('q')) | Event::Key(Key::Ctrl('c')) => break,
+ Event::Key(key) => {
+ let _ = term.print(1, 0, format!("get key: {:?}", key).as_str());
+ let _ = term.send_event(Event::User(format!("key: {:?}", key)));
+ }
+ Event::User(ev_str) => {
+ let _ = term.print(2, 0, format!("user event: {}", &ev_str).as_str());
+ }
+ _ => {
+ let _ = term.print(3, 0, format!("event: {:?}", ev).as_str());
+ }
+ }
+ let _ = term.present();
+ }
+}
diff --git a/vendor/skim-tuikit/examples/get_keys.rs b/vendor/skim-tuikit/examples/get_keys.rs
new file mode 100644
index 000000000..6d518d29b
--- /dev/null
+++ b/vendor/skim-tuikit/examples/get_keys.rs
@@ -0,0 +1,25 @@
+use skim_tuikit::input::KeyBoard;
+use skim_tuikit::key::Key;
+use skim_tuikit::output::Output;
+use skim_tuikit::raw::IntoRawMode;
+use std::time::Duration;
+
+fn main() {
+ let _stdout = std::io::stdout().into_raw_mode().unwrap();
+ let mut output = Output::new(Box::new(_stdout)).unwrap();
+ output.enable_mouse_support();
+ output.flush();
+
+ println!("program will exit on pressing `q` or wait 5 seconds");
+
+ // let mut keyboard = KeyBoard::new(Box::new(std::io::stdin()));
+ let mut keyboard = KeyBoard::new_with_tty();
+ while let Ok(key) = keyboard.next_key_timeout(Duration::from_secs(5)) {
+ if key == Key::Char('q') {
+ break;
+ }
+ println!("print: {:?}", key);
+ }
+ output.disable_mouse_support();
+ output.flush();
+}
diff --git a/vendor/skim-tuikit/examples/hello-world.rs b/vendor/skim-tuikit/examples/hello-world.rs
new file mode 100644
index 000000000..c1148b13e
--- /dev/null
+++ b/vendor/skim-tuikit/examples/hello-world.rs
@@ -0,0 +1,30 @@
+use skim_tuikit::prelude::*;
+use std::cmp::{max, min};
+
+fn main() {
+ let term: Term<()> = Term::with_height(TermHeight::Percent(30)).unwrap();
+ let mut row = 1;
+ let mut col = 0;
+
+ let _ = term.print(0, 0, "press arrow key to move the text, (q) to quit");
+ let _ = term.present();
+
+ while let Ok(ev) = term.poll_event() {
+ let _ = term.clear();
+ let _ = term.print(0, 0, "press arrow key to move the text, (q) to quit");
+
+ let (width, height) = term.term_size().unwrap();
+ match ev {
+ Event::Key(Key::ESC) | Event::Key(Key::Char('q')) | Event::Key(Key::Ctrl('c')) => break,
+ Event::Key(Key::Up) => row = max(row - 1, 1),
+ Event::Key(Key::Down) => row = min(row + 1, height - 1),
+ Event::Key(Key::Left) => col = max(col, 1) - 1,
+ Event::Key(Key::Right) => col = min(col + 1, width - 1),
+ _ => {}
+ }
+
+ let _ = term.print_with_attr(row, col, "Hello World! 你好!今日は。", Color::RED);
+ let _ = term.set_cursor(row, col);
+ let _ = term.present();
+ }
+}
diff --git a/vendor/skim-tuikit/examples/split.rs b/vendor/skim-tuikit/examples/split.rs
new file mode 100644
index 000000000..c3783884d
--- /dev/null
+++ b/vendor/skim-tuikit/examples/split.rs
@@ -0,0 +1,59 @@
+use skim_tuikit::prelude::*;
+
+struct Fit(String);
+
+impl Draw for Fit {
+ fn draw(&self, canvas: &mut dyn Canvas) -> DrawResult<()> {
+ let (_width, height) = canvas.size()?;
+ let top = height / 2;
+ let _ = canvas.print(top, 0, &self.0);
+ Ok(())
+ }
+}
+impl Widget for Fit {
+ fn size_hint(&self) -> (Option<usize>, Option<usize>) {
+ (Some(self.0.len()), None)
+ }
+}
+
+struct Model(String);
+
+impl Draw for Model {
+ fn draw(&self, canvas: &mut dyn Canvas) -> DrawResult<()> {
+ let (width, height) = canvas.size()?;
+ let message_width = self.0.len();
+ let left = (width - message_width) / 2;
+ let top = height / 2;
+ let _ = canvas.print_with_attr(0, left, "press 'q' to exit", Effect::UNDERLINE.into());
+ let _ = canvas.print(top, left, &self.0);
+ Ok(())
+ }
+}
+
+impl Widget for Model {}
+
+fn main() {
+ let term: Term<()> = Term::with_height(TermHeight::Percent(50)).unwrap();
+ let model = Model("Hey, I'm in middle!".to_string());
+ let fit = Fit("Short Text That Fits".to_string());
+
+ while let Ok(ev) = term.poll_event() {
+ match ev {
+ Event::Key(Key::Char('q')) | Event::Key(Key::Ctrl('c')) => break,
+ _ => (),
+ }
+
+ let hsplit = HSplit::default()
+ .split(
+ VSplit::default()
+ .shrink(0)
+ .grow(0)
+ .split(Win::new(&fit).border(true))
+ .split(Win::new(&fit).border(true)),
+ )
+ .split(Win::new(&model).border(true));
+
+ let _ = term.draw(&hsplit);
+ let _ = term.present();
+ }
+}
diff --git a/vendor/skim-tuikit/examples/stack.rs b/vendor/skim-tuikit/examples/stack.rs
new file mode 100644
index 000000000..d2c1e2540
--- /dev/null
+++ b/vendor/skim-tuikit/examples/stack.rs
@@ -0,0 +1,83 @@
+use skim_tuikit::prelude::*;
+
+struct Model {
+ win: String,
+}
+
+impl Draw for Model {
+ fn draw(&self, canvas: &mut dyn Canvas) -> DrawResult<()> {
+ let (width, height) = canvas.size()?;
+ let _ = canvas.clear();
+ let message_width = self.win.len();
+ let left = (width - message_width) / 2;
+ let top = height / 2;
+ let _ = canvas.print(top, left, &self.win);
+ Ok(())
+ }
+}
+
+impl Widget<String> for Model {
+ fn on_event(&self, event: Event, _rect: Rectangle) -> Vec<String> {
+ if let Event::Key(Key::SingleClick(_, _, _)) = event {
+ vec![format!("{} clicked", self.win)]
+ } else {
+ vec![]
+ }
+ }
+}
+
+fn main() {
+ let term = Term::with_options(TermOptions::default().mouse_enabled(true)).unwrap();
+ let (mut width, mut height) = term.term_size().unwrap();
+
+ while let Ok(ev) = term.poll_event() {
+ match ev {
+ Event::Key(Key::Char('q')) | Event::Key(Key::Ctrl('c')) => break,
+ Event::Key(Key::MouseRelease(_, _)) => continue,
+ Event::Resize { width: w, height: h } => {
+ width = w;
+ height = h;
+ }
+ _ => (),
+ }
+ let stack = Stack::<String>::new()
+ .top(
+ Win::new(Model {
+ win: "win floating on top".to_string(),
+ })
+ .border(true)
+ .margin(Size::Percent(30)),
+ )
+ .bottom(
+ HSplit::default()
+ .split(
+ Win::new(Model {
+ win: String::from("left"),
+ })
+ .border(true),
+ )
+ .split(
+ Win::new(Model {
+ win: String::from("right"),
+ })
+ .border(true),
+ ),
+ );
+
+ let message = stack.on_event(
+ ev,
+ Rectangle {
+ width,
+ height,
+ top: 0,
+ left: 0,
+ },
+ );
+ let click_message = if message.is_empty() { "" } else { &message[0] };
+ let _ = term.draw(&stack);
+ let _ = term.print(1, 1, "press 'q' to exit, try clicking on windows");
+ let _ = term.print(2, 1, &(String::from(click_message) + " "));
+ let _ = term.present();
+ }
+ let _ = term.show_cursor(false);
+}
diff --git a/vendor/skim-tuikit/examples/term_size.rs b/vendor/skim-tuikit/examples/term_size.rs
new file mode 100644
index 000000000..634837a1c
--- /dev/null
+++ b/vendor/skim-tuikit/examples/term_size.rs
@@ -0,0 +1,8 @@
+use skim_tuikit::output::Output;
+use std::io;
+
+fn main() {
+ let output = Output::new(Box::new(io::stdout())).unwrap();
+ let (width, height) = output.terminal_size().unwrap();
+ println!("width: {}, height: {}", width, height);
+}
diff --git a/vendor/skim-tuikit/examples/termbox.rs b/vendor/skim-tuikit/examples/termbox.rs
new file mode 100644
index 000000000..99de58026
--- /dev/null
+++ b/vendor/skim-tuikit/examples/termbox.rs
@@ -0,0 +1,73 @@
+use skim_tuikit::prelude::*;
+use std::sync::Arc;
+use std::thread;
+use std::time::{Duration, Instant};
+
+extern crate env_logger;
+
+/// This example is testing tuikit with multi-threads.
+
+const COL: usize = 4;
+
+fn main() {
+ env_logger::init();
+ let term = Arc::new(Term::with_height(TermHeight::Fixed(10)).unwrap());
+ let _ = term.enable_mouse_support();
+ let now = Instant::now();
+
+ print_banner(&term);
+
+ let th = thread::spawn(move || {
+ while let Ok(ev) = term.poll_event() {
+ match ev {
+ Event::Key(Key::Char('q')) | Event::Key(Key::Ctrl('c')) => break,
+ Event::Key(Key::Char('r')) => {
+ let term = term.clone();
+ thread::spawn(move || {
+ let _ = term.pause();
+ println!("restart in 2 seconds");
+ thread::sleep(Duration::from_secs(2));
+ let _ = term.restart();
+ let _ = term.clear();
+ });
+ }
+ _ => (),
+ }
+
+ print_banner(&term);
+ print_event(&term, ev, &now);
+ }
+ });
+ let _ = th.join();
+}
+
+fn print_banner(term: &Term) {
+ let (_, height) = term.term_size().unwrap_or((5, 5));
+ for row in 0..height {
+ let _ = term.print(row, 0, format!("{} ", row).as_str());
+ }
+ let attr = Attr {
+ fg: Color::GREEN,
+ effect: Effect::UNDERLINE,
+ ..Attr::default()
+ };
+ let _ = term.print_with_attr(0, COL, "How to use: (q)uit, (r)estart", attr);
+ let _ = term.present();
+}
+
+fn print_event(term: &Term, ev: Event, now: &Instant) {
+ let elapsed = now.elapsed();
+ let (_, height) = term.term_size().unwrap_or((5, 5));
+ let _ = term.print(1, COL, format!("{:?}", ev).as_str());
+ let _ = term.print(
+ height - 1,
+ COL,
+ format!(
+ "time elapsed since program start: {}s + {}ms",
+ elapsed.as_secs(),
+ elapsed.subsec_millis()
+ )
+ .as_str(),
+ );
+ let _ = term.present();
+}
diff --git a/vendor/skim-tuikit/examples/true_color.rs b/vendor/skim-tuikit/examples/true_color.rs
new file mode 100644
index 000000000..c4de1ce16
--- /dev/null
+++ b/vendor/skim-tuikit/examples/true_color.rs
@@ -0,0 +1,80 @@
+use skim_tuikit::attr::Color;
+use skim_tuikit::output::Output;
+use std::io;
+
+// ported from: https://github.com/gnachman/iTerm2/blob/master/tests/24-bit-color.sh
+// should be run in terminals that supports true color
+
+// given a color idx/22 along HSV, return (r, g, b)
+fn rainbow_color(idx: u8) -> (u8, u8, u8) {
+ let h = idx / 43;
+ let f = idx - 43 * h;
+ let t = ((f as i32 * 255) / 43) as u8;
+ let q = 255 - t;
+
+ match h {
+ 0 => (255, t, 0),
+ 1 => (q, 255, 0),
+ 2 => (0, 255, t),
+ 3 => (0, q, 255),
+ 4 => (t, 0, 255),
+ 5 => (255, 0, q),
+ _ => unreachable!(),
+ }
+}
+
+fn try_background(output: &mut Output, r: u8, g: u8, b: u8) {
+ output.set_bg(Color::Rgb(r, g, b));
+ output.write(" ")
+}
+
+fn reset_output(output: &mut Output) {
+ output.reset_attributes();
+ output.write("\n");
+ output.flush();
+}
+
+fn main() {
+ let mut output = Output::new(Box::new(io::stdout())).unwrap();
+ for i in 0..=127 {
+ try_background(&mut output, i, 0, 0);
+ }
+ reset_output(&mut output);
+
+ for i in (128..=255).rev() {
+ try_background(&mut output, i, 0, 0);
+ }
+ reset_output(&mut output);
+
+ for i in 0..=127 {
+ try_background(&mut output, 0, i, 0);
+ }
+ reset_output(&mut output);
+
+ for i in (128..=255).rev() {
+ try_background(&mut output, 0, i, 0);
+ }
+ reset_output(&mut output);
+
+ for i in 0..=127 {
+ try_background(&mut output, 0, 0, i);
+ }
+ reset_output(&mut output);
+
+ for i in (128..=255).rev() {
+ try_background(&mut output, 0, 0, i);
+ }
+ reset_output(&mut output);
+
+ for i in 0..=127 {
+ let (r, g, b) = rainbow_color(i);
+ try_background(&mut output, r, g, b);
+ }
+ reset_output(&mut output);
+
+ for i in (128..=255).rev() {
+ let (r, g, b) = rainbow_color(i);
+ try_background(&mut output, r, g, b);
+ }
+ reset_output(&mut output);
+}
diff --git a/vendor/skim-tuikit/examples/win.rs b/vendor/skim-tuikit/examples/win.rs
new file mode 100644
index 000000000..75ec8ce57
--- /dev/null
+++ b/vendor/skim-tuikit/examples/win.rs
@@ -0,0 +1,63 @@
+use skim_tuikit::prelude::*;
+
+struct Model(String);
+
+impl Draw for Model {
+ fn draw(&self, canvas: &mut dyn Canvas) -> DrawResult<()> {
+ let (width, height) = canvas.size()?;
+ let message_width = self.0.len();
+ let left = (width - message_width) / 2;
+ let top = height / 2;
+ let _ = canvas.print(top, left, &self.0);
+ Ok(())
+ }
+}
+
+impl Widget for Model {}
+
+fn main() {
+ let term: Term<()> = Term::with_options(
+ TermOptions::default()
+ .height(TermHeight::Percent(50))
+ .disable_alternate_screen(true)
+ .clear_on_start(false),
+ )
+ .unwrap();
+ let model = Model("Hey, I'm in middle!".to_string());
+
+ while let Ok(ev) = term.poll_event() {
+ match ev {
+ Event::Key(Key::Char('q')) | Event::Key(Key::Ctrl('c')) => break,
+ _ => (),
+ }
+ let _ = term.print(0, 0, "press 'q' to exit");
+
+ let inner_win = Win::new(&model)
+ .fn_draw_header(Box::new(|canvas| {
+ let _ = canvas.print(0, 0, "header printed with function");
+ Ok(())
+ }))
+ .border(true);
+
+ let win_bottom_title = Win::new(&inner_win)
+ .title_align(HorizontalAlign::Center)
+ .title("Title (at bottom) center aligned")
+ .right_prompt("Right Prompt stays")
+ .title_on_top(false)
+ .border_bottom(true);
+
+ let win = Win::new(&win_bottom_title)
+ .margin(Size::Percent(10))
+ .padding(1)
+ .title("Window Title")
+ .right_prompt("Right Prompt")
+ .border(true)
+ .border_top_attr(Color::BLUE)
+ .border_right_attr(Color::YELLOW)
+ .border_bottom_attr(Color::RED)
+ .border_left_attr(Color::GREEN);
+
+ let _ = term.draw(&win);
+ let _ = term.present();
+ }
+}
diff --git a/vendor/skim-tuikit/src/attr.rs b/vendor/skim-tuikit/src/attr.rs
new file mode 100644
index 000000000..232fdeea5
--- /dev/null
+++ b/vendor/skim-tuikit/src/attr.rs
@@ -0,0 +1,103 @@
+//! attr modules defines the attributes(colors, effects) of a terminal cell
+
+use bitflags::bitflags;
+
+pub use crate::color::Color;
+
+/// `Attr` is a rendering attribute that contains fg color, bg color and text effect.
+///
+/// ```
+/// use skim_tuikit::attr::{Attr, Effect, Color};
+///
+/// let attr = Attr { fg: Color::RED, effect: Effect::BOLD, ..Attr::default() };
+/// ```
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct Attr {
+ pub fg: Color,
+ pub bg: Color,
+ pub effect: Effect,
+}
+
+impl Default for Attr {
+ fn default() -> Self {
+ Attr {
+ fg: Color::default(),
+ bg: Color::default(),
+ effect: Effect::empty(),
+ }
+ }
+}
+
+impl Attr {
+ /// extend the properties with the new attr's if the properties in new attr is not default.
+ /// ```
+ /// use skim_tuikit::attr::{Attr, Color, Effect};
+ ///
+ /// let default = Attr{fg: Color::BLUE, bg: Color::YELLOW, effect: Effect::BOLD};
+ /// let new = Attr{fg: Color::Default, bg: Color::WHITE, effect: Effect::REVERSE};
+ /// let extended = default.extend(new);
+ ///
+ /// assert_eq!(Color::BLUE, extended.fg);
+ /// assert_eq!(Color::WHITE, extended.bg);
+ /// assert_eq!(Effect::BOLD | Effect::REVERSE, extended.effect);
+ /// ```
+ pub fn extend(&self, new_attr: Self) -> Attr {
+ Attr {
+ fg: if new_attr.fg != Color::default() {
+ new_attr.fg
+ } else {
+ self.fg
+ },
+ bg: if new_attr.bg != Color::default() {
+ new_attr.bg
+ } else {
+ self.bg
+ },
+ effect: self.effect | new_attr.effect,
+ }
+ }
+
+ pub fn fg(mut self, fg: Color) -> Self {
+ self.fg = fg;
+ self
+ }
+
+ pub fn bg(mut self, bg: Color) -> Self {
+ self.bg = bg;
+ self
+ }
+
+ pub fn effect(mut self, effect: Effect) -> Self {
+ self.effect = effect;
+ self
+ }
+}
+
+bitflags! {
+ /// `Effect` is the effect of a text
+ pub struct Effect: u8 {
+ const BOLD = 0b00000001;
+ const DIM = 0b00000010;
+ const UNDERLINE = 0b00000100;
+ const BLINK = 0b00001000;
+ const REVERSE = 0b00010000;
+ }
+}
+
+impl From<Color> for Attr {
+ fn from(fg: Color) -> Self {
+ Attr {
+ fg,
+ ..Default::default()
+ }
+ }
+}
+
+impl From<Effect> for Attr {
+ fn from(effect: Effect) -> Self {
+ Attr {
+ effect,
+ ..Default::default()
+ }
+ }
+}
diff --git a/vendor/skim-tuikit/src/canvas.rs b/vendor/skim-tuikit/src/canvas.rs
new file mode 100644
index 000000000..bf007bf71
--- /dev/null
+++ b/vendor/skim-tuikit/src/canvas.rs
@@ -0,0 +1,116 @@
+use crate::Result;
+/// A canvas is a trait defining the draw actions
+use crate::attr::Attr;
+use crate::cell::Cell;
+use unicode_width::UnicodeWidthChar;
+
+pub trait Canvas {
+ /// Get the canvas size (width, height)
+ fn size(&self) -> Result<(usize, usize)>;
+
+ /// clear the canvas
+ fn clear(&mut self) -> Result<()>;
+
+ /// change a cell of position `(row, col)` to `cell`
+ /// if `(row, col)` is out of boundary, `Ok` is returned, but no operation is taken
+ /// return the width of the character/cell
+ fn put_cell(&mut self, row: usize, col: usize, cell: Cell) -> Result<usize>;
+
+ /// just like put_cell, except it accept (char & attr)
+ /// return the width of the character/cell
+ fn put_char_with_attr(&mut self, row: usize, col: usize, ch: char, attr: Attr) -> Result<usize> {
+ self.put_cell(row, col, Cell { ch, attr })
+ }
+
+ /// print `content` starting with position `(row, col)` with `attr`
+ ///
+ /// - canvas should NOT wrap to y+1 if the content is too long
+ /// - canvas should handle wide characters
+ ///
+ /// returns the printed width of the content
+ fn print_with_attr(&mut self, row: usize, col: usize, content: &str, attr: Attr) -> Result<usize> {
+ let mut cell = Cell {
+ attr,
+ ..Cell::default()
+ };
+
+ let mut width = 0;
+ for ch in content.chars() {
+ cell.ch = ch;
+ width += self.put_cell(row, col + width, cell)?;
+ }
+ Ok(width)
+ }
+
+ /// print `content` starting with position `(row, col)` with default attribute
+ fn print(&mut self, row: usize, col: usize, content: &str) -> Result<usize> {
+ self.print_with_attr(row, col, content, Attr::default())
+ }
+
+ /// move cursor position (row, col) and show cursor
+ fn set_cursor(&mut self, row: usize, col: usize) -> Result<()>;
+
+ /// show/hide cursor, set `show` to `false` to hide the cursor
+ fn show_cursor(&mut self, show: bool) -> Result<()>;
+}
+
+/// A sub-area of a canvas.
+/// It will handle the adjustments of cursor movement, so that you could write
+/// to for example (0, 0) and BoundedCanvas will adjust it to real position.
+pub struct BoundedCanvas<'a> {
+ canvas: &'a mut dyn Canvas,
+ top: usize,
+ left: usize,
+ width: usize,
+ height: usize,
+}
+
+impl<'a> BoundedCanvas<'a> {
+ pub fn new(top: usize, left: usize, width: usize, height: usize, canvas: &'a mut dyn Canvas) -> Self {
+ Self {
+ canvas,
+ top,
+ left,
+ width,
+ height,
+ }
+ }
+}
+
+impl Canvas for BoundedCanvas<'_> {
+ fn size(&self) -> Result<(usize, usize)> {
+ Ok((self.width, self.height))
+ }
+
+ fn clear(&mut self) -> Result<()> {
+ for row in self.top..(self.top + self.height) {
+ for col in self.left..(self.left + self.width) {
+ let _ = self.canvas.put_cell(row, col, Cell::empty());
+ }
+ }
+
+ Ok(())
+ }
+
+ fn put_cell(&mut self, row: usize, col: usize, cell: Cell) -> Result<usize> {
+ if row >= self.height || col >= self.width {
+ // do nothing
+ Ok(cell.ch.width().unwrap_or(2))
+ } else {
+ self.canvas.put_cell(row + self.top, col + self.left, cell)
+ }
+ }
+
+ fn set_cursor(&mut self, row: usize, col: usize) -> Result<()> {
+ if row >= self.height || col >= self.width {
+ // do nothing
+ Ok(())
+ } else {
+ self.canvas.set_cursor(row + self.top, col + self.left)
+ }
+ }
+
+ fn show_cursor(&mut self, show: bool) -> Result<()> {
+ self.canvas.show_cursor(show)
+ }
+}
diff --git a/vendor/skim-tuikit/src/cell.rs b/vendor/skim-tuikit/src/cell.rs
new file mode 100644
index 000000000..d5e4fce9f
--- /dev/null
+++ b/vendor/skim-tuikit/src/cell.rs
@@ -0,0 +1,65 @@
+/// `Cell` is a cell of the terminal.
+/// It has a display character and an attribute (fg and bg color, effects).
+use crate::attr::{Attr, Color, Effect};
+
+const EMPTY_CHAR: char = '\0';
+
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct Cell {
+ pub ch: char,
+ pub attr: Attr,
+}
+
+impl Default for Cell {
+ fn default() -> Self {
+ Self {
+ ch: ' ',
+ attr: Attr::default(),
+ }
+ }
+}
+
+impl Cell {
+ pub fn empty() -> Self {
+ Self::default().ch(EMPTY_CHAR)
+ }
+
+ pub fn ch(mut self, ch: char) -> Self {
+ self.ch = ch;
+ self
+ }
+
+ pub fn fg(mut self, fg: Color) -> Self {
+ self.attr.fg = fg;
+ self
+ }
+
+ pub fn bg(mut self, bg: Color) -> Self {
+ self.attr.bg = bg;
+ self
+ }
+
+ pub fn effect(mut self, effect: Effect) -> Self {
+ self.attr.effect = effect;
+ self
+ }
+
+ pub fn attribute(mut self, attr: Attr) -> Self {
+ self.attr = attr;
+ self
+ }
+
+ /// check if a cell is empty
+ pub fn is_empty(self) -> bool {
+ self.ch == EMPTY_CHAR && self.attr == Attr::default()
+ }
+}
+
+impl From<char> for Cell {
+ fn from(ch: char) -> Self {
+ Cell {
+ ch,
+ attr: Attr::default(),
+ }
+ }
+}
diff --git a/vendor/skim-tuikit/src/color.rs b/vendor/skim-tuikit/src/color.rs
new file mode 100644
index 000000000..5e8ba9389
--- /dev/null
+++ b/vendor/skim-tuikit/src/color.rs
@@ -0,0 +1,34 @@
+/// Color of a character, could be 8 bit(256 color) or RGB color
+///
+/// ```
+/// use skim_tuikit::attr::Color;
+/// Color::RED; // predefined values
+/// Color::Rgb(255, 0, 0); // RED
+/// ```
+#[derive(Debug, Clone, Copy, PartialEq, Default)]
+#[non_exhaustive]
+pub enum Color {
+ #[default]
+ Default,
+ AnsiValue(u8),
+ Rgb(u8, u8, u8),
+}
+
+impl Color {
+ pub const BLACK: Color = Color::AnsiValue(0);
+ pub const RED: Color = Color::AnsiValue(1);
+ pub const GREEN: Color = Color::AnsiValue(2);
+ pub const YELLOW: Color = Color::AnsiValue(3);
+ pub const BLUE: Color = Color::AnsiValue(4);
+ pub const MAGENTA: Color = Color::AnsiValue(5);
+ pub const CYAN: Color = Color::AnsiValue(6);
+ pub const WHITE: Color = Color::AnsiValue(7);
+ pub const LIGHT_BLACK: Color = Color::AnsiValue(8);
+ pub const LIGHT_RED: Color = Color::AnsiValue(9);
+ pub const LIGHT_GREEN: Color = Color::AnsiValue(10);
+ pub const LIGHT_YELLOW: Color = Color::AnsiValue(11);
+ pub const LIGHT_BLUE: Color = Color::AnsiValue(12);
+ pub const LIGHT_MAGENTA: Color = Color::AnsiValue(13);
+ pub const LIGHT_CYAN: Color = Color::AnsiValue(14);
+ pub const LIGHT_WHITE: Color = Color::AnsiValue(15);
+}
diff --git a/vendor/skim-tuikit/src/draw.rs b/vendor/skim-tuikit/src/draw.rs
new file mode 100644
index 000000000..bef104dab
--- /dev/null
+++ b/vendor/skim-tuikit/src/draw.rs
@@ -0,0 +1,43 @@
+/// A trait defines something that could be drawn
+use crate::canvas::Canvas;
+
+pub type DrawResult<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
+
+/// Something that knows how to draw itself onto the canvas
+#[allow(unused_variables)]
+pub trait Draw {
+ fn draw(&self, canvas: &mut dyn Canvas) -> DrawResult<()> {
+ Ok(())
+ }
+ fn draw_mut(&mut self, canvas: &mut dyn Canvas) -> DrawResult<()> {
+ self.draw(canvas)
+ }
+}
+
+impl<T: Draw> Draw for &T {
+ fn draw(&self, canvas: &mut dyn Canvas) -> DrawResult<()> {
+ (*self).draw(canvas)
+ }
+ fn draw_mut(&mut self, canvas: &mut dyn Canvas) -> DrawResult<()> {
+ (*self).draw(canvas)
+ }
+}
+
+impl<T: Draw> Draw for &mut T {
+ fn draw(&self, canvas: &mut dyn Canvas) -> DrawResult<()> {
+ (**self).draw(canvas)
+ }
+ fn draw_mut(&mut self, canvas: &mut dyn Canvas) -> DrawResult<()> {
+ (**self).draw_mut(canvas)
+ }
+}
+
+impl<T: Draw + ?Sized> Draw for Box<T> {
+ fn draw(&self, canvas: &mut dyn Canvas) -> DrawResult<()> {
+ self.as_ref().draw(canvas)
+ }
+
+ fn draw_mut(&mut self, canvas: &mut dyn Canvas) -> DrawResult<()> {
+ self.as_mut().draw_mut(canvas)
+ }
+}
diff --git a/vendor/skim-tuikit/src/error.rs b/vendor/skim-tuikit/src/error.rs
new file mode 100644
index 000000000..627e1a1c1
--- /dev/null
+++ b/vendor/skim-tuikit/src/error.rs
@@ -0,0 +1,81 @@
+use std::error::Error;
+use std::fmt::{Display, Formatter};
+use std::string::FromUtf8Error;
+use std::time::Duration;
+
+#[derive(Debug)]
+pub enum TuikitError {
+ UnknownSequence(String),
+ NoCursorReportResponse,
+ IndexOutOfBound(usize, usize),
+ Timeout(Duration),
+ Interrupted,
+ TerminalNotStarted,
+ DrawError(Box<dyn std::error::Error + Send + Sync>),
+ SendEventError(String),
+ FromUtf8Error(std::string::FromUtf8Error),
+ ParseIntError(std::num::ParseIntError),
+ IOError(std::io::Error),
+ NixError(nix::Error),
+ ChannelReceiveError(std::sync::mpsc::RecvError),
+}
+
+impl Display for TuikitError {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ match self {
+ TuikitError::UnknownSequence(sequence) => {
+ write!(f, "unsupported esc sequence: {sequence}")
+ }
+ TuikitError::NoCursorReportResponse => {
+ write!(f, "buffer did not contain cursor position response")
+ }
+ TuikitError::IndexOutOfBound(row, col) => {
+ write!(f, "({row}, {col}) is out of bound")
+ }
+ TuikitError::Timeout(duration) => write!(f, "timeout with duration: {duration:?}"),
+ TuikitError::Interrupted => write!(f, "interrupted"),
+ TuikitError::TerminalNotStarted => {
+ write!(f, "terminal not started, call `restart` to start it")
+ }
+ TuikitError::DrawError(error) => write!(f, "draw error: {error}"),
+ TuikitError::SendEventError(error) => write!(f, "send event error: {error}"),
+ TuikitError::FromUtf8Error(error) => write!(f, "{error}"),
+ TuikitError::ParseIntError(error) => write!(f, "{error}"),
+ TuikitError::IOError(error) => write!(f, "{error}"),
+ TuikitError::NixError(error) => write!(f, "{error}"),
+ TuikitError::ChannelReceiveError(error) => write!(f, "{error}"),
+ }
+ }
+}
+
+impl Error for TuikitError {}
+
+impl From<std::string::FromUtf8Error> for TuikitError {
+ fn from(error: FromUtf8Error) -> Self {
+ TuikitError::FromUtf8Error(error)
+ }
+}
+
+impl From<std::num::ParseIntError> for TuikitError {
+ fn from(error: std::num::ParseIntError) -> Self {
+ TuikitError::ParseIntError(error)
+ }
+}
+
+impl From<nix::Error> for TuikitError {
+ fn from(error: nix::Error) -> Self {
+ TuikitError::NixError(error)
+ }
+}
+
+impl From<std::io::Error> for TuikitError {
+ fn from(error: std::io::Error) -> Self {
+ TuikitError::IOError(error)
+ }
+}
+
+impl From<std::sync::mpsc::RecvError> for TuikitError {
+ fn from(error: std::sync::mpsc::RecvError) -> Self {
+ TuikitError::ChannelReceiveError(error)
+ }
+}
diff --git a/vendor/skim-tuikit/src/event.rs b/vendor/skim-tuikit/src/event.rs
new file mode 100644
index 000000000..72a69a1ea
--- /dev/null
+++ b/vendor/skim-tuikit/src/event.rs
@@ -0,0 +1,18 @@
+//! events a `Term` could return
+
+pub use crate::key::Key;
+
+#[derive(Eq, PartialEq, Hash, Debug, Copy, Clone)]
+pub enum Event<UserEvent: Send + 'static = ()> {
+ Key(Key),
+ Resize {
+ width: usize,
+ height: usize,
+ },
+ Restarted,
+ /// user defined signal 1
+ User(UserEvent),
+
+ #[doc(hidden)]
+ __Nonexhaustive,
+}
diff --git a/vendor/skim-tuikit/src/input.rs b/vendor/skim-tuikit/src/input.rs
new file mode 100644
index 000000000..66532a6f3
--- /dev/null
+++ b/vendor/skim-tuikit/src/input.rs
@@ -0,0 +1,600 @@
+//! module to handle keystrokes
+//!
+//! ```no_run
+//! use skim_tuikit::input::KeyBoard;
+//! use skim_tuikit::key::Key;
+//! use std::time::Duration;
+//! let mut keyboard = KeyBoard::new_with_tty();
+//! let key = keyboard.next_key();
+//! ```
+
+use std::fs::File;
+use std::io::prelude::*;
+use std::os::fd::AsFd as _;
+use std::os::unix::io::AsRawFd;
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use nix::fcntl::{FcntlArg, OFlag, fcntl};
+
+use crate::Result;
+use crate::error::TuikitError;
+use crate::key::Key::*;
+use crate::key::{Key, MouseButton};
+use crate::raw::get_tty;
+use crate::spinlock::SpinLock;
+use crate::sys::file::wait_until_ready;
+
+pub trait ReadAndAsRawFd: Read + AsRawFd + Send {}
+
+const KEY_WAIT: Duration = Duration::from_millis(10);
+const DOUBLE_CLICK_DURATION: u128 = 300;
+
+impl<T> ReadAndAsRawFd for T where T: Read + AsRawFd + Send {}
+
+pub struct KeyBoard {
+ file: File,
+ sig_tx: Arc<SpinLock<File>>,
+ sig_rx: File,
+ // bytes will be poped from front, normally the buffer size will be small(< 10 bytes)
+ byte_buf: Vec<u8>,
+
+ raw_mouse: bool,
+ next_key: Option<Result<Key>>,
+ last_click: Key,
+ last_click_time: SpinLock<Instant>,
+}
+
+// https://www.xfree86.org/4.8.0/ctlseqs.html
+// http://man7.org/linux/man-pages/man4/console_codes.4.html
+impl KeyBoard {
+ pub fn new(file: File) -> Self {
+ // the self-pipe trick for interrupt `select`
+ let (rx, tx) = nix::unistd::pipe().expect("failed to set pipe");
+
+ // set the signal pipe to non-blocking mode
+ let flag = fcntl(rx.as_raw_fd(), FcntlArg::F_GETFL).expect("Get fcntl failed");
+ let mut flag = OFlag::from_bits_truncate(flag);
+ flag.insert(OFlag::O_NONBLOCK);
+ let _ = fcntl(rx.as_raw_fd(), FcntlArg::F_SETFL(flag));
+
+ // set file to non-blocking mode
+ let flag = fcntl(file.as_raw_fd(), FcntlArg::F_GETFL).expect("Get fcntl failed");
+ let mut flag = OFlag::from_bits_truncate(flag);
+ flag.insert(OFlag::O_NONBLOCK);
+ let _ = fcntl(file.as_raw_fd(), FcntlArg::F_SETFL(flag));
+
+ KeyBoard {
+ file,
+ sig_tx: Arc::new(SpinLock::new(File::from(tx))),
+ sig_rx: File::from(rx),
+ byte_buf: Vec::new(),
+ raw_mouse: false,
+ next_key: None,
+ last_click: Key::Null,
+ last_click_time: SpinLock::new(Instant::now()),
+ }
+ }
+
+ pub fn new_with_tty() -> Self {
+ Self::new(get_tty().expect("KeyBoard::new_with_tty: failed to get tty"))
+ }
+
+ pub fn raw_mouse(mut self, raw_mouse: bool) -> Self {
+ self.raw_mouse = raw_mouse;
+ self
+ }
+
+ pub fn get_interrupt_handler(&self) -> KeyboardHandler {
+ KeyboardHandler {
+ handler: self.sig_tx.clone(),
+ }
+ }
+
+ fn fetch_bytes(&mut self, timeout: Duration) -> Result<()> {
+ let mut reader_buf = [0; 1];
+
+ // clear interrupt signal
+ while self.sig_rx.read(&mut reader_buf).is_ok() {}
+
+ wait_until_ready(self.file.as_fd(), Some(self.sig_rx.as_fd()), timeout)?; // wait timeout
+
+ self.read_unread_bytes();
+ Ok(())
+ }
+
+ fn read_unread_bytes(&mut self) {
+ let mut reader_buf = [0; 1];
+ while self.file.read(&mut reader_buf).is_ok() {
+ self.byte_buf.push(reader_buf[0]);
+ }
+ }
+
+ #[allow(dead_code)]
+ fn next_byte(&mut self) -> Result<u8> {
+ self.next_byte_timeout(Duration::new(0, 0))
+ }
+
+ fn next_byte_timeout(&mut self, timeout: Duration) -> Result<u8> {
+ trace!("next_byte_timeout: timeout: {timeout:?}");
+ if self.byte_buf.is_empty() {
+ self.fetch_bytes(timeout)?;
+ }
+
+ trace!("next_byte_timeout: after fetch, buf = {:?}", self.byte_buf);
+ Ok(self.byte_buf.remove(0))
+ }
+
+ #[allow(dead_code)]
+ fn next_char(&mut self) -> Result<char> {
+ self.next_char_timeout(Duration::new(0, 0))
+ }
+
+ fn next_char_timeout(&mut self, timeout: Duration) -> Result<char> {
+ trace!("next_char_timeout: timeout: {timeout:?}");
+ if self.byte_buf.is_empty() {
+ self.fetch_bytes(timeout)?;
+ }
+
+ trace!("get_chars: buf: {:?}", self.byte_buf);
+ let bytes = std::mem::take(&mut self.byte_buf);
+ match String::from_utf8(bytes) {
+ Ok(string) => {
+ let ret = string.chars().next().expect("failed to get next char from input");
+ self.byte_buf.extend_from_slice(&string.as_bytes()[ret.len_utf8()..]);
+ Ok(ret)
+ }
+ Err(error) => {
+ let valid_up_to = error.utf8_error().valid_up_to();
+ let bytes = error.into_bytes();
+ let string = String::from_utf8_lossy(&bytes[..valid_up_to]);
+ let ret = string.chars().next().expect("failed to get next char from input");
+ self.byte_buf.extend_from_slice(&bytes[ret.len_utf8()..]);
+ Ok(ret)
+ }
+ }
+ }
+
+ fn merge_wheel(&mut self, current_key: Result<Key>) -> (Result<Key>, Option<Result<Key>>) {
+ match current_key {
+ Ok(Key::MousePress(key @ MouseButton::WheelUp, row, col))
+ | Ok(Key::MousePress(key @ MouseButton::WheelDown, row, col)) => {
+ let mut count = 1;
+ let mut o_next_key;
+ loop {
+ o_next_key = self.try_next_raw_key();
+ match o_next_key {
+ Some(Ok(Key::MousePress(k, r, c))) if key == k && row == r && col == c => count += 1,
+ _ => break,
+ }
+ }
+
+ match key {
+ MouseButton::WheelUp => (Ok(Key::WheelUp(row, col, count)), o_next_key),
+ MouseButton::WheelDown => (Ok(Key::WheelDown(row, col, count)), o_next_key),
+ _ => unreachable!(),
+ }
+ }
+ _ => (current_key, None),
+ }
+ }
+
+ pub fn next_key(&mut self) -> Result<Key> {
+ self.next_key_timeout(Duration::new(0, 0))
+ }
+
+ pub fn next_key_timeout(&mut self, timeout: Duration) -> Result<Key> {
+ if self.raw_mouse {
+ return self.next_raw_key_timeout(timeout);
+ }
+
+ let next_key = if self.next_key.is_some() {
+ self.next_key.take().unwrap()
+ } else {
+ // fetch next key
+ let next_key = self.next_raw_key_timeout(timeout);
+ let (next_key, next_next_key) = self.merge_wheel(next_key);
+ self.next_key = next_next_key;
+ next_key
+ };
+
+ // parse double click
+ match next_key {
+ Ok(key @ MousePress(..)) => {
+ if let MousePress(button, row, col) = key {
+ let ret = if key == self.last_click
+ && self.last_click_time.lock().elapsed().as_millis() < DOUBLE_CLICK_DURATION
+ {
+ DoubleClick(button, row, col)
+ } else {
+ self.last_click = key;
+ SingleClick(button, row, col)
+ };
+
+ *self.last_click_time.lock() = Instant::now();
+ Ok(ret)
+ } else {
+ unreachable!();
+ }
+ }
+ _ => next_key,
+ }
+ }
+
+ #[allow(dead_code)]
+ fn next_raw_key(&mut self) -> Result<Key> {
+ self.next_raw_key_timeout(Duration::new(0, 0))
+ }
+
+ fn try_next_raw_key(&mut self) -> Option<Result<Key>> {
+ match self.next_raw_key_timeout(KEY_WAIT) {
+ Ok(key) => Some(Ok(key)),
+ Err(TuikitError::Timeout(_)) => None,
+ Err(error) => Some(Err(error)),
+ }
+ }
+
+ /// Wait `timeout` until next key stroke
+ fn next_raw_key_timeout(&mut self, timeout: Duration) -> Result<Key> {
+ trace!("next_raw_key_timeout: {timeout:?}");
+ let ch = self.next_char_timeout(timeout)?;
+ match ch {
+ '\u{00}' => Ok(Ctrl(' ')),
+ '\u{01}' => Ok(Ctrl('a')),
+ '\u{02}' => Ok(Ctrl('b')),
+ '\u{03}' => Ok(Ctrl('c')),
+ '\u{04}' => Ok(Ctrl('d')),
+ '\u{05}' => Ok(Ctrl('e')),
+ '\u{06}' => Ok(Ctrl('f')),
+ '\u{07}' => Ok(Ctrl('g')),
+ '\u{08}' => Ok(Ctrl('h')),
+ '\u{09}' => Ok(Tab),
+ '\u{0A}' => Ok(Ctrl('j')),
+ '\u{0B}' => Ok(Ctrl('k')),
+ '\u{0C}' => Ok(Ctrl('l')),
+ '\u{0D}' => Ok(Enter),
+ '\u{0E}' => Ok(Ctrl('n')),
+ '\u{0F}' => Ok(Ctrl('o')),
+ '\u{10}' => Ok(Ctrl('p')),
+ '\u{11}' => Ok(Ctrl('q')),
+ '\u{12}' => Ok(Ctrl('r')),
+ '\u{13}' => Ok(Ctrl('s')),
+ '\u{14}' => Ok(Ctrl('t')),
+ '\u{15}' => Ok(Ctrl('u')),
+ '\u{16}' => Ok(Ctrl('v')),
+ '\u{17}' => Ok(Ctrl('w')),
+ '\u{18}' => Ok(Ctrl('x')),
+ '\u{19}' => Ok(Ctrl('y')),
+ '\u{1A}' => Ok(Ctrl('z')),
+ '\u{1B}' => self.escape_sequence(),
+ '\u{7F}' => Ok(Backspace),
+ ch => Ok(Char(ch)),
+ }
+ }
+
+ fn escape_sequence(&mut self) -> Result<Key> {
+ let seq1 = self.next_char_timeout(KEY_WAIT).unwrap_or('\u{1B}');
+ match seq1 {
+ '[' => self.escape_csi(),
+ 'O' => self.escape_o(),
+ _ => self.parse_alt(seq1),
+ }
+ }
+
+ fn parse_alt(&mut self, ch: char) -> Result<Key> {
+ match ch {
+ '\u{1B}' => {
+ match self.next_byte_timeout(KEY_WAIT) {
+ Ok(b'[') => {}
+ Ok(c) => {
+ return Err(TuikitError::UnknownSequence(format!("ESC ESC {c}")));
+ }
+ Err(_) => return Ok(ESC),
+ }
+
+ match self.escape_csi() {
+ Ok(Up) => Ok(AltUp),
+ Ok(Down) => Ok(AltDown),
+ Ok(Left) => Ok(AltLeft),
+ Ok(Right) => Ok(AltRight),
+ Ok(PageUp) => Ok(AltPageUp),
+ Ok(PageDown) => Ok(AltPageDown),
+ _ => Err(TuikitError::UnknownSequence("ESC ESC [ ...".to_string())),
+ }
+ }
+ '\u{00}' => Ok(CtrlAlt(' ')),
+ '\u{01}' => Ok(CtrlAlt('a')),
+ '\u{02}' => Ok(CtrlAlt('b')),
+ '\u{03}' => Ok(CtrlAlt('c')),
+ '\u{04}' => Ok(CtrlAlt('d')),
+ '\u{05}' => Ok(CtrlAlt('e')),
+ '\u{06}' => Ok(CtrlAlt('f')),
+ '\u{07}' => Ok(CtrlAlt('g')),
+ '\u{08}' => Ok(CtrlAlt('h')),
+ '\u{09}' => Ok(AltTab),
+ '\u{0A}' => Ok(CtrlAlt('j')),
+ '\u{0B}' => Ok(CtrlAlt('k')),
+ '\u{0C}' => Ok(CtrlAlt('l')),
+ '\u{0D}' => Ok(AltEnter),
+ '\u{0E}' => Ok(CtrlAlt('n')),
+ '\u{0F}' => Ok(CtrlAlt('o')),
+ '\u{10}' => Ok(CtrlAlt('p')),
+ '\u{11}' => Ok(CtrlAlt('q')),
+ '\u{12}' => Ok(CtrlAlt('r')),
+ '\u{13}' => Ok(CtrlAlt('s')),
+ '\u{14}' => Ok(CtrlAlt('t')),
+ '\u{15}' => Ok(CtrlAlt('u')),
+ '\u{16}' => Ok(CtrlAlt('v')),
+ '\u{17}' => Ok(CtrlAlt('w')),
+ '\u{18}' => Ok(CtrlAlt('x')),
+ '\u{19}' => Ok(AltBackTab),
+ '\u{1A}' => Ok(CtrlAlt('z')),
+ '\u{7F}' => Ok(AltBackspace),
+ ch => Ok(Alt(ch)),
+ }
+ }
+
+ fn escape_csi(&mut self) -> Result<Key> {
+ let cursor_pos = self.parse_cursor_report();
+ if cursor_pos.is_ok() {
+ return cursor_pos;
+ }
+
+ let seq2 = self.next_byte_timeout(KEY_WAIT)?;
+ match seq2 {
+ b'0' | b'9' => Err(TuikitError::UnknownSequence(format!("ESC [ {seq2:x?}"))),
+ b'1'..=b'8' => self.extended_escape(seq2),
+ b'[' => {
+ // Linux Console ESC [ [ _
+ let seq3 = self.next_byte_timeout(KEY_WAIT)?;
+ match seq3 {
+ b'A' => Ok(F(1)),
+ b'B' => Ok(F(2)),
+ b'C' => Ok(F(3)),
+ b'D' => Ok(F(4)),
+ b'E' => Ok(F(5)),
+ _ => Err(TuikitError::UnknownSequence(format!("ESC [ [ {seq3:x?}"))),
+ }
+ }
+ b'A' => Ok(Up), // kcuu1
+ b'B' => Ok(Down), // kcud1
+ b'C' => Ok(Right), // kcuf1
+ b'D' => Ok(Left), // kcub1
+ b'H' => Ok(Home), // khome
+ b'F' => Ok(End),
+ b'Z' => Ok(BackTab),
+ b'M' => {
+ // X10 emulation mouse encoding: ESC [ M Bxy (6 characters only)
+ let cb = self.next_byte_timeout(KEY_WAIT)?;
+ // (1, 1) are the coords for upper left.
+ let cx = self.next_byte_timeout(KEY_WAIT)?.saturating_sub(32) as u16 - 1; // 0 based
+ let cy = self.next_byte_timeout(KEY_WAIT)?.saturating_sub(32) as u16 - 1; // 0 based
+ match cb & 0b11 {
+ 0 => {
+ if cb & 0x40 != 0 {
+ Ok(MousePress(MouseButton::WheelUp, cy, cx))
+ } else {
+ Ok(MousePress(MouseButton::Left, cy, cx))
+ }
+ }
+ 1 => {
+ if cb & 0x40 != 0 {
+ Ok(MousePress(MouseButton::WheelDown, cy, cx))
+ } else {
+ Ok(MousePress(MouseButton::Middle, cy, cx))
+ }
+ }
+ 2 => Ok(MousePress(MouseButton::Right, cy, cx)),
+ 3 => Ok(MouseRelease(cy, cx)),
+ _ => Err(TuikitError::UnknownSequence(format!("ESC M {cb:?}{cx:?}{cy:?}"))),
+ }
+ }
+ b'<' => {
+ // xterm mouse encoding:
+ // ESC [ < Cb ; Cx ; Cy ; (M or m)
+ self.read_unread_bytes();
+ if !self.byte_buf.contains(&b'm') && !self.byte_buf.contains(&b'M') {
+ return Err(TuikitError::UnknownSequence(
+ "ESC [ < (not ending with m/M)".to_string(),
+ ));
+ }
+
+ let mut str_buf = String::new();
+ let mut c = self.next_char_timeout(KEY_WAIT)?;
+ while c != 'm' && c != 'M' {
+ str_buf.push(c);
+ c = self.next_char_timeout(KEY_WAIT)?;
+ }
+ let nums = &mut str_buf.split(';');
+
+ let cb = nums.next().unwrap().parse::<u16>().unwrap();
+ let cx = nums.next().unwrap().parse::<u16>().unwrap() - 1; // 0 based
+ let cy = nums.next().unwrap().parse::<u16>().unwrap() - 1; // 0 based
+
+ match cb {
+ 0..=2 | 64..=65 => {
+ let button = match cb {
+ 0 => MouseButton::Left,
+ 1 => MouseButton::Middle,
+ 2 => MouseButton::Right,
+ 64 => MouseButton::WheelUp,
+ 65 => MouseButton::WheelDown,
+ _ => {
+ return Err(TuikitError::UnknownSequence(format!("ESC [ < {str_buf} {c}")));
+ }
+ };
+
+ match c {
+ 'M' => Ok(MousePress(button, cy, cx)),
+ 'm' => Ok(MouseRelease(cy, cx)),
+ _ => Err(TuikitError::UnknownSequence(format!("ESC [ < {str_buf} {c}"))),
+ }
+ }
+ 32 => Ok(MouseHold(cy, cx)),
+ _ => Err(TuikitError::UnknownSequence(format!("ESC [ < {str_buf} {c}"))),
+ }
+ }
+ _ => Err(TuikitError::UnknownSequence(format!("ESC [ {seq2:?}"))),
+ }
+ }
+
+ // Cursor position report (CPR): Answer is ESC [ y ; x R, where x,y is the cursor location.
+ fn parse_cursor_report(&mut self) -> Result<Key> {
+ self.read_unread_bytes();
+ let pos_semi = self.byte_buf.iter().position(|&b| b == b';');
+ let pos_r = self.byte_buf.iter().position(|&b| b == b'R');
+
+ if let Some(pos_semi) = pos_semi
+ && let Some(pos_r) = pos_r
+ {
+ if pos_r > pos_semi {
+ let remain = self.byte_buf.split_off(pos_r + 1);
+ let mut col_str = self.byte_buf.split_off(pos_semi + 1);
+ let mut row_str = std::mem::replace(&mut self.byte_buf, remain);
+
+ row_str.pop(); // remove the ';' character
+ col_str.pop(); // remove the 'R' character
+ let row = String::from_utf8(row_str)?;
+ let col = String::from_utf8(col_str)?;
+
+ let row_num = row.parse::<u16>()?;
+ let col_num = col.parse::<u16>()?;
+
+ return Ok(CursorPos(row_num - 1, col_num - 1));
+ }
+ }
+
+ Err(TuikitError::NoCursorReportResponse)
+ }
+
+ fn extended_escape(&mut self, seq2: u8) -> Result<Key> {
+ let seq3 = self.next_byte_timeout(KEY_WAIT)?;
+ if seq3 == b'~' {
+ match seq2 {
+ b'1' | b'7' => Ok(Home), // tmux, xrvt
+ b'2' => Ok(Insert),
+ b'3' => Ok(Delete), // kdch1
+ b'4' | b'8' => Ok(End), // tmux, xrvt
+ b'5' => Ok(PageUp), // kpp
+ b'6' => Ok(PageDown), // knp
+ _ => Err(TuikitError::UnknownSequence(format!("ESC [ {seq2} ~"))),
+ }
+ } else if seq3.is_ascii_digit() {
+ let mut str_buf = String::new();
+ str_buf.push(seq2 as char);
+ str_buf.push(seq3 as char);
+
+ let mut seq_last = self.next_byte_timeout(KEY_WAIT)?;
+ while seq_last != b'M' && seq_last != b'~' {
+ str_buf.push(seq_last as char);
+ seq_last = self.next_byte_timeout(KEY_WAIT)?;
+ }
+
+ match seq_last {
+ b'M' => {
+ // rxvt mouse encoding:
+ // ESC [ Cb ; Cx ; Cy ; M
+ let mut nums = str_buf.split(';');
+
+ let cb = nums.next().unwrap().parse::<u16>().unwrap();
+ let cx = nums.next().unwrap().parse::<u16>().unwrap() - 1; // 0 based
+ let cy = nums.next().unwrap().parse::<u16>().unwrap() - 1; // 0 based
+
+ match cb {
+ 32 => Ok(MousePress(MouseButton::Left, cy, cx)),
+ 33 => Ok(MousePress(MouseButton::Middle, cy, cx)),
+ 34 => Ok(MousePress(MouseButton::Right, cy, cx)),
+ 35 => Ok(MouseRelease(cy, cx)),
+ 64 => Ok(MouseHold(cy, cx)),
+ 96 | 97 => Ok(MousePress(MouseButton::WheelUp, cy, cx)),
+ _ => Err(TuikitError::UnknownSequence(format!("ESC [ {str_buf} M"))),
+ }
+ }
+ b'~' => {
+ let num: u8 = str_buf.parse().unwrap();
+ match num {
+ v @ 11..=15 => Ok(F(v - 10)),
+ v @ 17..=21 => Ok(F(v - 11)),
+ v @ 23..=24 => Ok(F(v - 12)),
+ 200 => Ok(BracketedPasteStart),
+ 201 => Ok(BracketedPasteEnd),
+ _ => Err(TuikitError::UnknownSequence(format!("ESC [ {str_buf} ~"))),
+ }
+ }
+ _ => unreachable!(),
+ }
+ } else if seq3 == b';' {
+ let seq4 = self.next_byte_timeout(KEY_WAIT)?;
+ if seq4.is_ascii_digit() {
+ let seq5 = self.next_byte_timeout(KEY_WAIT)?;
+ if seq2 == b'1' {
+ match (seq4, seq5) {
+ (b'5', b'A') => Ok(CtrlUp),
+ (b'5', b'B') => Ok(CtrlDown),
+ (b'5', b'C') => Ok(CtrlRight),
+ (b'5', b'D') => Ok(CtrlLeft),
+ (b'4', b'A') => Ok(AltShiftUp),
+ (b'4', b'B') => Ok(AltShiftDown),
+ (b'4', b'C') => Ok(AltShiftRight),
+ (b'4', b'D') => Ok(AltShiftLeft),
+ (b'3', b'H') => Ok(AltHome),
+ (b'3', b'F') => Ok(AltEnd),
+ (b'2', b'A') => Ok(ShiftUp),
+ (b'2', b'B') => Ok(ShiftDown),
+ (b'2', b'C') => Ok(ShiftRight),
+ (b'2', b'D') => Ok(ShiftLeft),
+ _ => Err(TuikitError::UnknownSequence(format!("ESC [ 1 ; {seq4:x?} {seq5:x?}"))),
+ }
+ } else {
+ Err(TuikitError::UnknownSequence(format!(
+ "ESC [ {seq2:x?} ; {seq4:x?} {seq5:x?}"
+ )))
+ }
+ } else {
+ Err(TuikitError::UnknownSequence(format!("ESC [ {seq2:x?} ; {seq4:x?}")))
+ }
+ } else {
+ match (seq2, seq3) {
+ (b'5', b'A') => Ok(CtrlUp),
+ (b'5', b'B') => Ok(CtrlDown),
+ (b'5', b'C') => Ok(CtrlRight),
+ (b'5', b'D') => Ok(CtrlLeft),
+ _ => Err(TuikitError::UnknownSequence(format!("ESC [ {seq2:x?} {seq3:x?}"))),
+ }
+ }
+ }
+
+ // SSS3
+ fn escape_o(&mut self) -> Result<Key> {
+ let seq2 = self.next_byte_timeout(KEY_WAIT)?;
+ match seq2 {
+ b'A' => Ok(Up), // kcuu1
+ b'B' => Ok(Down), // kcud1
+ b'C' => Ok(Right), // kcuf1
+ b'D' => Ok(Left), // kcub1
+ b'F' => Ok(End), // kend
+ b'H' => Ok(Home), // khome
+ b'P' => Ok(F(1)), // kf1
+ b'Q' => Ok(F(2)), // kf2
+ b'R' => Ok(F(3)), // kf3
+ b'S' => Ok(F(4)), // kf4
+ b'a' => Ok(CtrlUp),
+ b'b' => Ok(CtrlDown),
+ b'c' => Ok(CtrlRight), // rxvt
+ b'd' => Ok(CtrlLeft), // rxvt
+ _ => Err(TuikitError::UnknownSequence(format!("ESC O {seq2:x?}"))),
+ }
+ }
+}
+
+pub struct KeyboardHandler {
+ handler: Arc<SpinLock<File>>,
+}
+
+impl KeyboardHandler {
+ pub fn interrupt(&self) {
+ let mut handler = self.handler.lock();
+ let _ = handler.write_all(b"x");
+ let _ = handler.flush();
+ }
+}
diff --git a/vendor/skim-tuikit/src/key.rs b/vendor/skim-tuikit/src/key.rs
new file mode 100644
index 000000000..7abcf0cf1
--- /dev/null
+++ b/vendor/skim-tuikit/src/key.rs
@@ -0,0 +1,283 @@
+//! Defines all the keys `tuikit` recognizes.
+
+// http://ascii-table.com/ansi-escape-sequences.php
+/// Single key
+#[non_exhaustive]
+#[rustfmt::skip]
+#[derive(Eq, PartialEq, Hash, Debug, Copy, Clone)]
+pub enum Key {
+ Null,
+ ESC,
+
+ Ctrl(char),
+ Tab, // Ctrl-I
+ Enter, // Ctrl-M
+
+ BackTab, Backspace, AltBackTab,
+
+ Up, Down, Left, Right, Home, End, Insert, Delete, PageUp, PageDown,
+ CtrlUp, CtrlDown, CtrlLeft, CtrlRight,
+ ShiftUp, ShiftDown, ShiftLeft, ShiftRight,
+ AltUp, AltDown, AltLeft, AltRight, AltHome, AltEnd, AltPageUp, AltPageDown,
+ AltShiftUp, AltShiftDown, AltShiftLeft, AltShiftRight,
+
+ F(u8),
+
+ CtrlAlt(char), // chars are lower case
+ AltEnter,
+ AltBackspace,
+ AltTab,
+ Alt(char), // chars could be lower or upper case
+ Char(char), // chars could be lower or upper case
+ CursorPos(u16, u16), // row, col
+
+ // raw mouse events, will only generated if raw mouse mode is enabled
+ MousePress(MouseButton, u16, u16), // row, col
+ MouseRelease(u16, u16), // row, col
+ MouseHold(u16, u16), // row, col
+
+ // parsed mouse events, will be generated if raw mouse mode is disabled
+ SingleClick(MouseButton, u16, u16), // row, col
+ DoubleClick(MouseButton, u16, u16), // row, col, will only record left button double click
+ WheelUp(u16, u16, u16), // row, col, number of scroll
+ WheelDown(u16, u16, u16), // row, col, number of scroll
+
+ BracketedPasteStart,
+ BracketedPasteEnd,
+}
+
+/// A mouse button.
+#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
+pub enum MouseButton {
+ /// The left mouse button.
+ Left,
+ /// The right mouse button.
+ Right,
+ /// The middle mouse button.
+ Middle,
+ /// Mouse wheel is going up.
+ ///
+ /// This event is typically only used with MousePress.
+ WheelUp,
+ /// Mouse wheel is going down.
+ ///
+ /// This event is typically only used with MousePress.
+ WheelDown,
+}
+
+#[rustfmt::skip]
+pub fn from_keyname(keyname: &str) -> Option<Key> {
+ use self::Key::*;
+ match keyname.to_lowercase().as_ref() {
+ "ctrl-space" | "ctrl-`" | "ctrl-@" => Some(Ctrl(' ')),
+ "ctrl-a" => Some(Ctrl('a')),
+ "ctrl-b" => Some(Ctrl('b')),
+ "ctrl-c" => Some(Ctrl('c')),
+ "ctrl-d" => Some(Ctrl('d')),
+ "ctrl-e" => Some(Ctrl('e')),
+ "ctrl-f" => Some(Ctrl('f')),
+ "ctrl-g" => Some(Ctrl('g')),
+ "ctrl-h" => Some(Ctrl('h')),
+ "tab" | "ctrl-i" => Some(Tab),
+ "ctrl-j" => Some(Ctrl('j')),
+ "ctrl-k" => Some(Ctrl('k')),
+ "ctrl-l" => Some(Ctrl('l')),
+ "enter" | "return" | "ctrl-m" => Some(Enter),
+ "ctrl-n" => Some(Ctrl('n')),
+ "ctrl-o" => Some(Ctrl('o')),
+ "ctrl-p" => Some(Ctrl('p')),
+ "ctrl-q" => Some(Ctrl('q')),
+ "ctrl-r" => Some(Ctrl('r')),
+ "ctrl-s" => Some(Ctrl('s')),
+ "ctrl-t" => Some(Ctrl('t')),
+ "ctrl-u" => Some(Ctrl('u')),
+ "ctrl-v" => Some(Ctrl('v')),
+ "ctrl-w" => Some(Ctrl('w')),
+ "ctrl-x" => Some(Ctrl('x')),
+ "ctrl-y" => Some(Ctrl('y')),
+ "ctrl-z" => Some(Ctrl('z')),
+ "ctrl-up" => Some(CtrlUp),
+ "ctrl-down" => Some(CtrlDown),
+ "ctrl-left" => Some(CtrlLeft),
+ "ctrl-right" => Some(CtrlRight),
+
+ "ctrl-alt-space" => Some(Ctrl(' ')),
+ "ctrl-alt-a" => Some(CtrlAlt('a')),
+ "ctrl-alt-b" => Some(CtrlAlt('b')),
+ "ctrl-alt-c" => Some(CtrlAlt('c')),
+ "ctrl-alt-d" => Some(CtrlAlt('d')),
+ "ctrl-alt-e" => Some(CtrlAlt('e')),
+ "ctrl-alt-f" => Some(CtrlAlt('f')),
+ "ctrl-alt-g" => Some(CtrlAlt('g')),
+ "ctrl-alt-h" => Some(CtrlAlt('h')),
+ "ctrl-alt-j" => Some(CtrlAlt('j')),
+ "ctrl-alt-k" => Some(CtrlAlt('k')),
+ "ctrl-alt-l" => Some(CtrlAlt('l')),
+ "ctrl-alt-n" => Some(CtrlAlt('n')),
+ "ctrl-alt-o" => Some(CtrlAlt('o')),
+ "ctrl-alt-p" => Some(CtrlAlt('p')),
+ "ctrl-alt-q" => Some(CtrlAlt('q')),
+ "ctrl-alt-r" => Some(CtrlAlt('r')),
+ "ctrl-alt-s" => Some(CtrlAlt('s')),
+ "ctrl-alt-t" => Some(CtrlAlt('t')),
+ "ctrl-alt-u" => Some(CtrlAlt('u')),
+ "ctrl-alt-v" => Some(CtrlAlt('v')),
+ "ctrl-alt-w" => Some(CtrlAlt('w')),
+ "ctrl-alt-x" => Some(CtrlAlt('x')),
+ "ctrl-alt-y" => Some(CtrlAlt('y')),
+ "ctrl-alt-z" => Some(CtrlAlt('z')),
+
+ "esc" => Some(ESC),
+ "btab" | "shift-tab" => Some(BackTab),
+ "bspace" | "bs" => Some(Backspace),
+ "ins" | "insert" => Some(Insert),
+ "del" => Some(Delete),
+ "pgup" | "page-up" => Some(PageUp),
+ "pgdn" | "page-down" => Some(PageDown),
+ "up" => Some(Up),
+ "down" => Some(Down),
+ "left" => Some(Left),
+ "right" => Some(Right),
+ "home" => Some(Home),
+ "end" => Some(End),
+ "shift-up" => Some(ShiftUp),
+ "shift-down" => Some(ShiftDown),
+ "shift-left" => Some(ShiftLeft),
+ "shift-right" => Some(ShiftRight),
+
+ "f1" => Some(F(1)),
+ "f2" => Some(F(2)),
+ "f3" => Some(F(3)),
+ "f4" => Some(F(4)),
+ "f5" => Some(F(5)),
+ "f6" => Some(F(6)),
+ "f7" => Some(F(7)),
+ "f8" => Some(F(8)),
+ "f9" => Some(F(9)),
+ "f10" => Some(F(10)),
+ "f11" => Some(F(11)),
+ "f12" => Some(F(12)),
+
+ "alt-a" => Some(Alt('a')),
+ "alt-b" => Some(Alt('b')),
+ "alt-c" => Some(Alt('c')),
+ "alt-d" => Some(Alt('d')),
+ "alt-e" => Some(Alt('e')),
+ "alt-f" => Some(Alt('f')),
+ "alt-g" => Some(Alt('g')),
+ "alt-h" => Some(Alt('h')),
+ "alt-i" => Some(Alt('i')),
+ "alt-j" => Some(Alt('j')),
+ "alt-k" => Some(Alt('k')),
+ "alt-l" => Some(Alt('l')),
+ "alt-m" => Some(Alt('m')),
+ "alt-n" => Some(Alt('n')),
+ "alt-o" => Some(Alt('o')),
+ "alt-p" => Some(Alt('p')),
+ "alt-q" => Some(Alt('q')),
+ "alt-r" => Some(Alt('r')),
+ "alt-s" => Some(Alt('s')),
+ "alt-t" => Some(Alt('t')),
+ "alt-u" => Some(Alt('u')),
+ "alt-v" => Some(Alt('v')),
+ "alt-w" => Some(Alt('w')),
+ "alt-x" => Some(Alt('x')),
+ "alt-y" => Some(Alt('y')),
+ "alt-z" => Some(Alt('z')),
+ "alt-/" => Some(Alt('/')),
+
+ "shift-a" => Some(Char('A')),
+ "shift-b" => Some(Char('B')),
+ "shift-c" => Some(Char('C')),
+ "shift-d" => Some(Char('D')),
+ "shift-e" => Some(Char('E')),
+ "shift-f" => Some(Char('F')),
+ "shift-g" => Some(Char('G')),
+ "shift-h" => Some(Char('H')),
+ "shift-i" => Some(Char('I')),
+ "shift-j" => Some(Char('J')),
+ "shift-k" => Some(Char('K')),
+ "shift-l" => Some(Char('L')),
+ "shift-m" => Some(Char('M')),
+ "shift-n" => Some(Char('N')),
+ "shift-o" => Some(Char('O')),
+ "shift-p" => Some(Char('P')),
+ "shift-q" => Some(Char('Q')),
+ "shift-r" => Some(Char('R')),
+ "shift-s" => Some(Char('S')),
+ "shift-t" => Some(Char('T')),
+ "shift-u" => Some(Char('U')),
+ "shift-v" => Some(Char('V')),
+ "shift-w" => Some(Char('W')),
+ "shift-x" => Some(Char('X')),
+ "shift-y" => Some(Char('Y')),
+ "shift-z" => Some(Char('Z')),
+
+ "alt-shift-a" => Some(Alt('A')),
+ "alt-shift-b" => Some(Alt('B')),
+ "alt-shift-c" => Some(Alt('C')),
+ "alt-shift-d" => Some(Alt('D')),
+ "alt-shift-e" => Some(Alt('E')),
+ "alt-shift-f" => Some(Alt('F')),
+ "alt-shift-g" => Some(Alt('G')),
+ "alt-shift-h" => Some(Alt('H')),
+ "alt-shift-i" => Some(Alt('I')),
+ "alt-shift-j" => Some(Alt('J')),
+ "alt-shift-k" => Some(Alt('K')),
+ "alt-shift-l" => Some(Alt('L')),
+ "alt-shift-m" => Some(Alt('M')),
+ "alt-shift-n" => Some(Alt('N')),
+ "alt-shift-o" => Some(Alt('O')),
+ "alt-shift-p" => Some(Alt('P')),
+ "alt-shift-q" => Some(Alt('Q')),
+ "alt-shift-r" => Some(Alt('R')),
+ "alt-shift-s" => Some(Alt('S')),
+ "alt-shift-t" => Some(Alt('T')),
+ "alt-shift-u" => Some(Alt('U')),
+ "alt-shift-v" => Some(Alt('V')),
+ "alt-shift-w" => Some(Alt('W')),
+ "alt-shift-x" => Some(Alt('X')),
+ "alt-shift-y" => Some(Alt('Y')),
+ "alt-shift-z" => Some(Alt('Z')),
+
+ "alt-btab" | "alt-shift-tab" => Some(AltBackTab),
+ "alt-bspace" | "alt-bs" => Some(AltBackspace),
+ "alt-pgup" | "alt-page-up" => Some(AltPageUp),
+ "alt-pgdn" | "alt-page-down" => Some(AltPageDown),
+ "alt-up" => Some(AltUp),
+ "alt-down" => Some(AltDown),
+ "alt-left" => Some(AltLeft),
+ "alt-right" => Some(AltRight),
+ "alt-home" => Some(AltHome),
+ "alt-end" => Some(AltEnd),
+ "alt-shift-up" => Some(AltShiftUp),
+ "alt-shift-down" => Some(AltShiftDown),
+ "alt-shift-left" => Some(AltShiftLeft),
+ "alt-shift-right" => Some(AltShiftRight),
+ "alt-enter" | "alt-ctrl-m" => Some(AltEnter),
+ "alt-tab" | "alt-ctrl-i" => Some(AltTab),
+
+ "space" => Some(Char(' ')),
+ "alt-space" => Some(Alt(' ')),
+
+ ch if ch.chars().count() == 1 => {
+ Some(Char(ch.chars().next().expect("input:parse_key: no key is specified")))
+ },
+ _ => None,
+ }
+}
+
+#[cfg(test)]
+mod test {
+ use super::Key::*;
+ use super::*;
+
+ #[test]
+ fn bind_shift_key() {
+ // Without the "shift-" prefix, "from_keyname" ignores the case.
+ assert_eq!(from_keyname("A").unwrap(), Char('a'));
+
+ // A correct way to refer to an uppercase char.
+ assert_eq!(from_keyname("shift-a").unwrap(), Char('A'));
+ }
+}
diff --git a/vendor/skim-tuikit/src/lib.rs b/vendor/skim-tuikit/src/lib.rs
new file mode 100644
index 000000000..f0bdfa9d4
--- /dev/null
+++ b/vendor/skim-tuikit/src/lib.rs
@@ -0,0 +1,82 @@
+//!
+//! ## Tuikit
+//! Tuikit is a TUI library for writing terminal UI applications. Highlights:
+//!
+//! - Thread safe.
+//! - Support non-fullscreen mode as well as fullscreen mode.
+//! - Support `Alt` keys, mouse events, etc.
+//! - Buffering for efficient rendering.
+//!
+//! Tuikit is modeld after [termbox](https://github.com/nsf/termbox) which views the
+//! terminal as a table of fixed-size cells and input being a stream of structured
+//! messages.
+//!
+//! ## Usage
+//!
+//! In your `Cargo.toml` add the following:
+//!
+//! ```toml
+//! [dependencies]
+//! tuikit = "*"
+//! ```
+//!
+//! Here is an example:
+//!
+//! ```no_run
+//! use skim_tuikit::attr::*;
+//! use skim_tuikit::term::{Term, TermHeight};
+//! use skim_tuikit::event::{Event, Key};
+//! use std::cmp::{min, max};
+//!
+//! let term: Term<()> = Term::with_height(TermHeight::Percent(30)).unwrap();
+//! let mut row = 1;
+//! let mut col = 0;
+//!
+//! let _ = term.print(0, 0, "press arrow key to move the text, (q) to quit");
+//! let _ = term.present();
+//!
+//! while let Ok(ev) = term.poll_event() {
+//! let _ = term.clear();
+//! let _ = term.print(0, 0, "press arrow key to move the text, (q) to quit");
+//!
+//! let (width, height) = term.term_size().unwrap();
+//! match ev {
+//! Event::Key(Key::ESC) | Event::Key(Key::Char('q')) => break,
+//! Event::Key(Key::Up) => row = max(row-1, 1),
+//! Event::Key(Key::Down) => row = min(row+1, height-1),
+//! Event::Key(Key::Left) => col = max(col, 1)-1,
+//! Event::Key(Key::Right) => col = min(col+1, width-1),
+//! _ => {}
+//! }
+//!
+//! let attr = Attr{ fg: Color::RED, ..Attr::default() };
+//! let _ = term.print_with_attr(row, col, "Hello World! 你好!今日は。", attr);
+//! let _ = term.set_cursor(row, col);
+//! let _ = term.present();
+//! }
+//! ```
+pub mod attr;
+pub mod canvas;
+pub mod cell;
+mod color;
+pub mod draw;
+pub mod error;
+pub mod event;
+pub mod input;
+pub mod key;
+mod macros;
+pub mod output;
+pub mod prelude;
+pub mod raw;
+pub mod screen;
+use skim_common::spinlock;
+mod sys;
+pub mod term;
+pub mod widget;
+
+#[macro_use]
+extern crate log;
+
+use crate::error::TuikitError;
+
+pub type Result<T> = std::result::Result<T, TuikitError>;
diff --git a/vendor/skim-tuikit/src/macros.rs b/vendor/skim-tuikit/src/macros.rs
new file mode 100644
index 000000000..33b7479c9
--- /dev/null
+++ b/vendor/skim-tuikit/src/macros.rs
@@ -0,0 +1,23 @@
+#[macro_export]
+macro_rules! ok_or_return {
+ ($expr:expr, $default_val:expr) => {
+ match $expr {
+ Ok(val) => val,
+ Err(_) => {
+ return $default_val;
+ }
+ }
+ };
+}
+
+#[macro_export]
+macro_rules! some_or_return {
+ ($expr:expr, $default_val:expr) => {
+ match $expr {
+ Some(val) => val,
+ None => {
+ return $default_val;
+ }
+ }
+ };
+}
diff --git a/vendor/skim-tuikit/src/output.rs b/vendor/skim-tuikit/src/output.rs
new file mode 100644
index 000000000..7e9e18e5a
--- /dev/null
+++ b/vendor/skim-tuikit/src/output.rs
@@ -0,0 +1,410 @@
+//! `Output` is the output stream that deals with ANSI Escape codes.
+//! normally you should not use it directly.
+//!
+//! ```
+//! use std::io;
+//! use skim_tuikit::attr::Color;
+//! use skim_tuikit::output::Output;
+//!
+//! let Ok(mut output) = Output::new(Box::new(io::stdout())) else { return; };
+//! output.set_fg(Color::YELLOW);
+//! output.write("YELLOW\n");
+//! output.flush();
+//!
+//! ```
+
+use std::io;
+use std::io::Write;
+use std::os::unix::io::AsRawFd;
+
+use crate::attr::{Attr, Color, Effect};
+use crate::sys::size::terminal_size;
+
+use term::terminfo::TermInfo;
+use term::terminfo::parm::{Param, Variables, expand};
+
+// modeled after python-prompt-toolkit
+// term info: https://ftp.netbsd.org/pub/NetBSD/NetBSD-release-7/src/share/terminfo/terminfo
+
+const DEFAULT_BUFFER_SIZE: usize = 1024;
+
+/// Output is an abstraction over the ANSI codes.
+pub struct Output {
+ /// A callable which returns the `Size` of the output terminal.
+ buffer: Vec<u8>,
+ stdout: Box<dyn WriteAndAsRawFdAndSend>,
+ /// The terminal environment variable. (xterm, xterm-256color, linux, ...)
+ terminfo: TermInfo,
+}
+
+pub trait WriteAndAsRawFdAndSend: Write + AsRawFd + Send {}
+
+impl<T> WriteAndAsRawFdAndSend for T where T: Write + AsRawFd + Send {}
+
+impl Output {
+ pub fn new(stdout: Box<dyn WriteAndAsRawFdAndSend>) -> io::Result<Self> {
+ Result::Ok(Self {
+ buffer: Vec::with_capacity(DEFAULT_BUFFER_SIZE),
+ stdout,
+ terminfo: TermInfo::from_env()?,
+ })
+ }
+
+ fn write_cap(&mut self, cmd: &str) {
+ self.write_cap_with_params(cmd, &[])
+ }
+
+ fn write_cap_with_params(&mut self, cap: &str, params: &[Param]) {
+ if let Some(cmd) = self.terminfo.strings.get(cap)
+ && let Ok(s) = expand(cmd, params, &mut Variables::new())
+ {
+ self.buffer.extend(&s);
+ }
+ }
+
+ /// Write text (Terminal escape sequences will be removed/escaped.)
+ pub fn write(&mut self, data: &str) {
+ self.buffer.extend(data.replace("\x1b", "?").as_bytes());
+ }
+
+ /// Write raw texts to the terminal.
+ pub fn write_raw(&mut self, data: &[u8]) {
+ self.buffer.extend_from_slice(data);
+ }
+
+ /// Return the encoding for this output, e.g. 'utf-8'.
+ /// (This is used mainly to know which characters are supported by the
+ /// output the data, so that the UI can provide alternatives, when
+ /// required.)
+ pub fn encoding(&self) -> &str {
+ unimplemented!()
+ }
+
+ /// Set terminal title.
+ pub fn set_title(&mut self, title: &str) {
+ if self.terminfo.names.contains(&"linux".to_string())
+ || self.terminfo.names.contains(&"eterm-color".to_string())
+ {
+ return;
+ }
+
+ let title = title.replace("\x1b", "").replace("\x07", "");
+ self.write_raw(format!("\x1b]2;{title}\x07").as_bytes());
+ }
+
+ /// Clear title again. (or restore previous title.)
+ pub fn clear_title(&mut self) {
+ self.set_title("");
+ }
+
+ /// Write to output stream and flush.
+ pub fn flush(&mut self) {
+ let _ = self.stdout.write_all(&self.buffer);
+ self.buffer.clear();
+ let _ = self.stdout.flush();
+ }
+
+ /// Erases the screen with the background colour and moves the cursor to home.
+ pub fn erase_screen(&mut self) {
+ self.write_cap("clear");
+ }
+
+ /// Go to the alternate screen buffer. (For full screen applications).
+ pub fn enter_alternate_screen(&mut self) {
+ self.write_cap("smcup");
+ }
+
+ /// Leave the alternate screen buffer.
+ pub fn quit_alternate_screen(&mut self) {
+ self.write_cap("rmcup");
+ }
+
+ /// Enable mouse.
+ pub fn enable_mouse_support(&mut self) {
+ self.write_raw("\x1b[?1000h".as_bytes());
+
+ // Enable urxvt Mouse mode. (For terminals that understand this.)
+ self.write_raw("\x1b[?1015h".as_bytes());
+
+ // Also enable Xterm SGR mouse mode. (For terminals that understand this.)
+ self.write_raw("\x1b[?1006h".as_bytes());
+
+ // Note: E.g. lxterminal understands 1000h, but not the urxvt or sgr extensions.
+ }
+
+ /// Disable mouse.
+ pub fn disable_mouse_support(&mut self) {
+ self.write_raw("\x1b[?1000l".as_bytes());
+ self.write_raw("\x1b[?1015l".as_bytes());
+ self.write_raw("\x1b[?1006l".as_bytes());
+ }
+
+ /// Erases from the current cursor position to the end of the current line.
+ pub fn erase_end_of_line(&mut self) {
+ self.write_cap("el");
+ }
+
+ /// Erases the screen from the current line down to the bottom of the screen.
+ pub fn erase_down(&mut self) {
+ self.write_cap("ed");
+ }
+
+ /// Reset color and styling attributes.
+ pub fn reset_attributes(&mut self) {
+ self.write_cap("sgr0");
+ }
+
+ /// Set current foreground color
+ pub fn set_fg(&mut self, color: Color) {
+ match color {
+ Color::Default => {
+ self.write_raw("\x1b[39m".as_bytes());
+ }
+ Color::AnsiValue(x) => {
+ self.write_cap_with_params("setaf", &[Param::Number(x as i32)]);
+ }
+ Color::Rgb(r, g, b) => {
+ self.write_raw(format!("\x1b[38;2;{r};{g};{b}m").as_bytes());
+ }
+ }
+ }
+
+ /// Set current background color
+ pub fn set_bg(&mut self, color: Color) {
+ match color {
+ Color::Default => {
+ self.write_raw("\x1b[49m".as_bytes());
+ }
+ Color::AnsiValue(x) => {
+ self.write_cap_with_params("setab", &[Param::Number(x as i32)]);
+ }
+ Color::Rgb(r, g, b) => {
+ self.write_raw(format!("\x1b[48;2;{r};{g};{b}m").as_bytes());
+ }
+ }
+ }
+
+ /// Set current effect (underline, bold, etc)
+ pub fn set_effect(&mut self, effect: Effect) {
+ if effect.contains(Effect::BOLD) {
+ self.write_cap("bold");
+ }
+ if effect.contains(Effect::DIM) {
+ self.write_cap("dim");
+ }
+ if effect.contains(Effect::UNDERLINE) {
+ self.write_cap("smul");
+ }
+ if effect.contains(Effect::BLINK) {
+ self.write_cap("blink");
+ }
+ if effect.contains(Effect::REVERSE) {
+ self.write_cap("rev");
+ }
+ }
+
+ /// Set new color and styling attributes.
+ pub fn set_attribute(&mut self, attr: Attr) {
+ self.set_fg(attr.fg);
+ self.set_bg(attr.bg);
+ self.set_effect(attr.effect);
+ }
+
+ /// Disable auto line wrapping.
+ pub fn disable_autowrap(&mut self) {
+ self.write_cap("rmam");
+ }
+
+ /// Enable auto line wrapping.
+ pub fn enable_autowrap(&mut self) {
+ self.write_cap("smam");
+ }
+
+ /// Move cursor position.
+ pub fn cursor_goto(&mut self, row: usize, column: usize) {
+ self.write_cap_with_params("cup", &[Param::Number(row as i32), Param::Number(column as i32)]);
+ }
+
+ /// Move cursor `amount` place up.
+ pub fn cursor_up(&mut self, amount: usize) {
+ match amount {
+ 0 => {}
+ 1 => self.write_cap("cuu1"),
+ _ => self.write_cap_with_params("cuu", &[Param::Number(amount as i32)]),
+ }
+ }
+
+ /// Move cursor `amount` place down.
+ pub fn cursor_down(&mut self, amount: usize) {
+ match amount {
+ 0 => {}
+ 1 => self.write_cap("cud1"),
+ _ => self.write_cap_with_params("cud", &[Param::Number(amount as i32)]),
+ }
+ }
+
+ /// Move cursor `amount` place forward.
+ pub fn cursor_forward(&mut self, amount: usize) {
+ match amount {
+ 0 => {}
+ 1 => self.write_cap("cuf1"),
+ _ => self.write_cap_with_params("cuf", &[Param::Number(amount as i32)]),
+ }
+ }
+
+ /// Move cursor `amount` place backward.
+ pub fn cursor_backward(&mut self, amount: usize) {
+ match amount {
+ 0 => {}
+ 1 => self.write_cap("cub1"),
+ _ => self.write_cap_with_params("cub", &[Param::Number(amount as i32)]),
+ }
+ }
+
+ /// Hide cursor.
+ pub fn hide_cursor(&mut self) {
+ self.write_cap("civis");
+ }
+
+ /// Show cursor.
+ pub fn show_cursor(&mut self) {
+ self.write_cap("cnorm");
+ }
+
+ /// Asks for a cursor position report (CPR). (VT100 only.)
+ pub fn ask_for_cpr(&mut self) {
+ self.write_raw("\x1b[6n".as_bytes());
+ self.flush()
+ }
+
+ /// Sound bell.
+ pub fn bell(&mut self) {
+ self.write_cap("bel");
+ self.flush()
+ }
+
+ /// get terminal size (width, height)
+ pub fn terminal_size(&self) -> io::Result<(usize, usize)> {
+ terminal_size(self.stdout.as_raw_fd())
+ }
+
+ /// For vt100/xterm etc.
+ pub fn enable_bracketed_paste(&mut self) {
+ self.write_raw("\x1b[?2004h".as_bytes());
+ }
+
+ /// For vt100/xterm etc.
+ pub fn disable_bracketed_paste(&mut self) {
+ self.write_raw("\x1b[?2004l".as_bytes());
+ }
+
+ /// Execute the command
+ pub fn execute(&mut self, cmd: Command) {
+ match cmd {
+ Command::PutChar(c) => self.write(c.to_string().as_str()),
+ Command::Write(content) => self.write(&content),
+ Command::SetTitle(title) => self.set_title(&title),
+ Command::ClearTitle => self.clear_title(),
+ Command::Flush => self.flush(),
+ Command::EraseScreen => self.erase_screen(),
+ Command::AlternateScreen(enable) => {
+ if enable {
+ self.enter_alternate_screen()
+ } else {
+ self.quit_alternate_screen()
+ }
+ }
+ Command::MouseSupport(enable) => {
+ if enable {
+ self.enable_mouse_support();
+ } else {
+ self.disable_mouse_support();
+ }
+ }
+ Command::EraseEndOfLine => self.erase_end_of_line(),
+ Command::EraseDown => self.erase_down(),
+ Command::ResetAttributes => self.reset_attributes(),
+ Command::Fg(fg) => self.set_fg(fg),
+ Command::Bg(bg) => self.set_bg(bg),
+ Command::Effect(effect) => self.set_effect(effect),
+ Command::SetAttribute(attr) => self.set_attribute(attr),
+ Command::AutoWrap(enable) => {
+ if enable {
+ self.enable_autowrap();
+ } else {
+ self.disable_autowrap();
+ }
+ }
+ Command::CursorGoto { row, col } => self.cursor_goto(row, col),
+ Command::CursorUp(amount) => self.cursor_up(amount),
+ Command::CursorDown(amount) => self.cursor_down(amount),
+ Command::CursorLeft(amount) => self.cursor_backward(amount),
+ Command::CursorRight(amount) => self.cursor_forward(amount),
+ Command::CursorShow(show) => {
+ if show {
+ self.show_cursor()
+ } else {
+ self.hide_cursor()
+ }
+ }
+ Command::BracketedPaste(enable) => {
+ if enable {
+ self.enable_bracketed_paste()
+ } else {
+ self.disable_bracketed_paste()
+ }
+ }
+ }
+ }
+}
+
+/// Instead of calling functions of `Output`, we could send commands.
+#[derive(Debug, Clone)]
+pub enum Command {
+ /// Put a char to screen
+ PutChar(char),
+ /// Write content to screen (escape codes will be escaped)
+ Write(String),
+ /// Set the title of the terminal
+ SetTitle(String),
+ /// Clear the title of the terminal
+ ClearTitle,
+ /// Flush all the buffered contents
+ Flush,
+ /// Erase the entire screen
+ EraseScreen,
+ /// Enter(true)/Quit(false) the alternate screen mode
+ AlternateScreen(bool),
+ /// Enable(true)/Disable(false) mouse support
+ MouseSupport(bool),
+ /// Erase contents to the end of current line
+ EraseEndOfLine,
+ /// Erase contents till the bottom of the screen
+ EraseDown,
+ /// Reset attributes
+ ResetAttributes,
+ /// Set the foreground color
+ Fg(Color),
+ /// Set the background color
+ Bg(Color),
+ /// Set the effect(e.g. underline, dim, bold, ...)
+ Effect(Effect),
+ /// Set the fg, bg & effect.
+ SetAttribute(Attr),
+ /// Enable(true)/Disable(false) autowrap
+ AutoWrap(bool),
+ /// move the cursor to `(row, col)`
+ CursorGoto { row: usize, col: usize },
+ /// move cursor up `x` lines
+ CursorUp(usize),
+ /// move cursor down `x` lines
+ CursorDown(usize),
+ /// move cursor left `x` characters
+ CursorLeft(usize),
+ /// move cursor right `x` characters
+ CursorRight(usize),
+ /// Show(true)/Hide(false) cursor
+ CursorShow(bool),
+ /// Enable(true)/Disable(false) the bracketed paste mode
+ BracketedPaste(bool),
+}
diff --git a/vendor/skim-tuikit/src/prelude.rs b/vendor/skim-tuikit/src/prelude.rs
new file mode 100644
index 000000000..dd0518699
--- /dev/null
+++ b/vendor/skim-tuikit/src/prelude.rs
@@ -0,0 +1,11 @@
+pub use crate::Result;
+pub use crate::attr::{Attr, Color, Effect};
+pub use crate::canvas::Canvas;
+pub use crate::cell::Cell;
+pub use crate::draw::{Draw, DrawResult};
+pub use crate::event::Event;
+pub use crate::key::*;
+pub use crate::term::{Term, TermHeight, TermOptions};
+pub use crate::widget::{
+ AlignSelf, HSplit, HorizontalAlign, Rectangle, Size, Split, Stack, VSplit, VerticalAlign, Widget, Win,
+};
diff --git a/vendor/skim-tuikit/src/raw.rs b/vendor/skim-tuikit/src/raw.rs
new file mode 100644
index 000000000..0eb51e825
--- /dev/null
+++ b/vendor/skim-tuikit/src/raw.rs
@@ -0,0 +1,131 @@
+//! Managing raw mode.
+//!
+//! Raw mode is a particular state a TTY can have. It signifies that:
+//!
+//! 1. No line buffering (the input is given byte-by-byte).
+//! 2. The input is not written out, instead it has to be done manually by the programmer.
+//! 3. The output is not canonicalized (for example, `\n` means "go one line down", not "line
+//! break").
+//!
+//! # Example
+//!
+//! ```rust,no_run
+//! use skim_tuikit::raw::IntoRawMode;
+//! use std::io::{Write, stdout};
+//!
+//! let mut stdout = stdout().into_raw_mode().unwrap();
+//!
+//! write!(stdout, "Hey there.").unwrap();
+//! ```
+
+use std::io::{self, Write};
+use std::ops;
+use std::os::fd::{AsFd, AsRawFd, BorrowedFd};
+
+use nix::sys::termios::{SetArg, Termios, cfmakeraw, tcgetattr, tcsetattr};
+use nix::unistd::isatty;
+use std::fs;
+use std::os::unix::io::RawFd;
+
+// taken from termion
+/// Get the TTY device.
+///
+/// This allows for getting stdio representing _only_ the TTY, and not other streams.
+pub fn get_tty() -> io::Result<fs::File> {
+ fs::OpenOptions::new().read(true).write(true).open("/dev/tty")
+}
+
+/// A terminal restorer, which keeps the previous state of the terminal, and restores it, when
+/// dropped.
+///
+/// Restoring will entirely bring back the old TTY state.
+pub struct RawTerminal<W: Write + AsFd + AsRawFd> {
+ prev_ios: Termios,
+ output: W,
+}
+
+impl<W: Write + AsFd + AsRawFd> Drop for RawTerminal<W> {
+ fn drop(&mut self) {
+ let _ = tcsetattr(self.output.as_fd(), SetArg::TCSANOW, &self.prev_ios);
+ }
+}
+
+impl<W: Write + AsFd + AsRawFd> ops::Deref for RawTerminal<W> {
+ type Target = W;
+
+ fn deref(&self) -> &W {
+ &self.output
+ }
+}
+
+impl<W: Write + AsFd + AsRawFd> ops::DerefMut for RawTerminal<W> {
+ fn deref_mut(&mut self) -> &mut W {
+ &mut self.output
+ }
+}
+
+impl<W: Write + AsFd + AsRawFd> Write for RawTerminal<W> {
+ fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+ self.output.write(buf)
+ }
+
+ fn flush(&mut self) -> io::Result<()> {
+ self.output.flush()
+ }
+}
+
+impl<W: Write + AsFd + AsRawFd> AsFd for RawTerminal<W> {
+ fn as_fd(&self) -> BorrowedFd<'_> {
+ self.output.as_fd()
+ }
+}
+
+impl<W: Write + AsFd + AsRawFd> AsRawFd for RawTerminal<W> {
+ fn as_raw_fd(&self) -> RawFd {
+ self.output.as_raw_fd()
+ }
+}
+
+/// Types which can be converted into "raw mode".
+///
+/// # Why is this type defined on writers and not readers?
+///
+/// TTYs has their state controlled by the writer, not the reader. You use the writer to clear the
+/// screen, move the cursor and so on, so naturally you use the writer to change the mode as well.
+pub trait IntoRawMode: Write + AsFd + AsRawFd + Sized {
+ /// Switch to raw mode.
+ ///
+ /// Raw mode means that stdin won't be printed (it will instead have to be written manually by
+ /// the program). Furthermore, the input isn't canonicalised or buffered (that is, you can
+ /// read from stdin one byte of a time). The output is neither modified in any way.
+ fn into_raw_mode(self) -> io::Result<RawTerminal<Self>>;
+}
+
+impl<W: Write + AsFd + AsRawFd> IntoRawMode for W {
+ // modified after https://github.com/kkawakam/rustyline/blob/master/src/tty/unix.rs#L668
+ // refer: https://linux.die.net/man/3/termios
+ fn into_raw_mode(self) -> io::Result<RawTerminal<W>> {
+ use nix::errno::Errno::ENOTTY;
+ use nix::sys::termios::OutputFlags;
+
+ let istty = isatty(self.as_raw_fd()).map_err(nix_err_to_io_err)?;
+ if !istty {
+ Err(nix_err_to_io_err(ENOTTY))?
+ }
+
+ let prev_ios = tcgetattr(self.as_fd()).map_err(nix_err_to_io_err)?;
+ let mut ios = prev_ios.clone();
+ // set raw mode
+ cfmakeraw(&mut ios);
+ // enable output processing (so that '\n' will issue carriage return)
+ ios.output_flags |= OutputFlags::OPOST;
+
+ tcsetattr(&self, SetArg::TCSANOW, &ios).map_err(nix_err_to_io_err)?;
+
+ Ok(RawTerminal { prev_ios, output: self })
+ }
+}
+
+fn nix_err_to_io_err(err: nix::Error) -> io::Error {
+ io::Error::from(err)
+}
diff --git a/vendor/skim-tuikit/src/screen.rs b/vendor/skim-tuikit/src/screen.rs
new file mode 100644
index 000000000..14ddaeb67
--- /dev/null
+++ b/vendor/skim-tuikit/src/screen.rs
@@ -0,0 +1,387 @@
+//! Buffering screen cells and try to optimize rendering contents
+use crate::Result;
+use crate::attr::Attr;
+use crate::canvas::Canvas;
+use crate::cell::Cell;
+use crate::error::TuikitError;
+use crate::output::Command;
+use std::cmp::{max, min};
+use unicode_width::UnicodeWidthChar;
+
+// much of the code comes from https://github.com/agatan/termfest/blob/master/src/screen.rs
+
+/// A Screen is a table of cells to draw on.
+/// It's a buffer holding the contents
+#[derive(Debug)]
+pub struct Screen {
+ width: usize,
+ height: usize,
+ cursor: Cursor,
+ cells: Vec<Cell>,
+ painted_cells: Vec<Cell>,
+ painted_cursor: Cursor,
+ clear_on_start: bool,
+}
+
+impl Screen {
+ /// create an empty screen with size: (width, height)
+ pub fn new(width: usize, height: usize) -> Self {
+ Self {
+ width,
+ height,
+ cells: vec![Cell::default(); width * height],
+ cursor: Cursor::default(),
+ painted_cells: vec![Cell::default(); width * height],
+ painted_cursor: Cursor::default(),
+ clear_on_start: false,
+ }
+ }
+
+ pub fn clear_on_start(&mut self, clear_on_start: bool) {
+ self.clear_on_start = clear_on_start;
+ }
+
+ /// get the width of the screen
+ #[inline]
+ pub fn width(&self) -> usize {
+ self.width
+ }
+
+ /// get the height of the screen
+ #[inline]
+ pub fn height(&self) -> usize {
+ self.height
+ }
+
+ #[inline]
+ fn index(&self, row: usize, col: usize) -> Result<usize> {
+ if row >= self.height || col >= self.width {
+ Err(TuikitError::IndexOutOfBound(row, col))
+ } else {
+ Ok(row * self.width + col)
+ }
+ }
+
+ fn empty_canvas(&self, width: usize, height: usize) -> Vec<Cell> {
+ vec![Cell::empty(); width * height]
+ }
+
+ fn copy_cells(&self, original: &[Cell], width: usize, height: usize) -> Vec<Cell> {
+ let mut new_cells = self.empty_canvas(width, height);
+ use std::cmp;
+ let min_height = cmp::min(height, self.height);
+ let min_width = cmp::min(width, self.width);
+ for row in 0..min_height {
+ let orig_start = row * self.width;
+ let orig_end = min_width + orig_start;
+ let start = row * width;
+ let end = min_width + start;
+ new_cells[start..end].copy_from_slice(&original[orig_start..orig_end]);
+ }
+ new_cells
+ }
+
+ /// to resize the screen to `(width, height)`
+ pub fn resize(&mut self, width: usize, height: usize) {
+ self.cells = self.copy_cells(&self.cells, width, height);
+ self.painted_cells = self.empty_canvas(width, height);
+ self.width = width;
+ self.height = height;
+
+ self.cursor.row = min(self.cursor.row, height);
+ self.cursor.col = min(self.cursor.col, width);
+ }
+
+ /// sync internal buffer with the terminal
+ pub fn present(&mut self) -> Vec<Command> {
+ let mut commands = Vec::with_capacity(2048);
+ let default_attr = Attr::default();
+ let mut last_attr = default_attr;
+
+ // hide cursor && reset Attributes
+ commands.push(Command::CursorShow(false));
+ commands.push(Command::CursorGoto { row: 0, col: 0 });
+ commands.push(Command::ResetAttributes);
+
+ let mut last_cursor = Cursor::default();
+
+ for row in 0..self.height {
+ // calculate the last col that has contents
+ let mut empty_col_index = 0;
+ for col in (0..self.width).rev() {
+ let index = self.index(row, col).unwrap();
+ let cell = &self.cells[index];
+ if cell.is_empty() {
+ self.painted_cells[index] = *cell;
+ } else {
+ empty_col_index = col + 1;
+ break;
+ }
+ }
+
+ // compare cells and print necessary escape codes
+ let mut last_ch_is_wide = false;
+ for col in 0..empty_col_index {
+ let index = self.index(row, col).unwrap();
+
+ // advance if the last character is wide
+ if last_ch_is_wide {
+ last_ch_is_wide = false;
+ self.painted_cells[index] = self.cells[index];
+ continue;
+ }
+
+ let cell_to_paint = self.cells[index];
+ let cell_painted = self.painted_cells[index];
+
+ // no need to paint if the content did not change
+ if cell_to_paint == cell_painted {
+ continue;
+ }
+
+ // move cursor if necessary
+ if last_cursor.row != row || last_cursor.col != col {
+ commands.push(Command::CursorGoto { row, col });
+ }
+
+ if cell_to_paint.attr != last_attr {
+ commands.push(Command::ResetAttributes);
+ commands.push(Command::SetAttribute(cell_to_paint.attr));
+ last_attr = cell_to_paint.attr;
+ }
+
+ // correctly draw the characters
+ match cell_to_paint.ch {
+ '\n' | '\r' | '\t' | '\0' => {
+ commands.push(Command::PutChar(' '));
+ }
+ _ => {
+ commands.push(Command::PutChar(cell_to_paint.ch));
+ }
+ }
+
+ let display_width = cell_to_paint.ch.width().unwrap_or(2);
+
+ // wide character
+ if display_width == 2 {
+ last_ch_is_wide = true;
+ }
+
+ last_cursor.row = row;
+ last_cursor.col = col + display_width;
+ self.painted_cells[index] = cell_to_paint;
+ }
+
+ if empty_col_index != self.width {
+ commands.push(Command::CursorGoto {
+ row,
+ col: empty_col_index,
+ });
+ commands.push(Command::ResetAttributes);
+ if self.clear_on_start {
+ commands.push(Command::EraseEndOfLine);
+ }
+ last_attr = Attr::default();
+ }
+ }
+
+ // restore cursor
+ commands.push(Command::CursorGoto {
+ row: self.cursor.row,
+ col: self.cursor.col,
+ });
+ if self.cursor.visible {
+ commands.push(Command::CursorShow(true));
+ }
+
+ self.painted_cursor = self.cursor;
+
+ commands
+ }
+
+ /// ```
+ /// use skim_tuikit::cell::Cell;
+ /// use skim_tuikit::canvas::Canvas;
+ /// use skim_tuikit::screen::Screen;
+ ///
+ ///
+ /// let mut screen = Screen::new(1, 1);
+ /// screen.put_cell(0, 0, Cell{ ch: 'a', ..Cell::default()});
+ /// let mut iter = screen.iter_cell();
+ /// assert_eq!(Some((0, 0, &Cell{ ch: 'a', ..Cell::default()})), iter.next());
+ /// assert_eq!(None, iter.next());
+ /// ```
+ pub fn iter_cell(&self) -> CellIterator<'_> {
+ CellIterator {
+ width: self.width,
+ index: 0,
+ vec: &self.cells,
+ }
+ }
+}
+
+impl Canvas for Screen {
+ /// Get the canvas size (width, height)
+ fn size(&self) -> Result<(usize, usize)> {
+ Ok((self.width(), self.height()))
+ }
+
+ /// clear the screen buffer
+ fn clear(&mut self) -> Result<()> {
+ for cell in self.cells.iter_mut() {
+ *cell = Cell::empty();
+ }
+ Ok(())
+ }
+
+ /// change a cell of position `(row, col)` to `cell`
+ fn put_cell(&mut self, row: usize, col: usize, cell: Cell) -> Result<usize> {
+ let ch_width = cell.ch.width().unwrap_or(2);
+ if ch_width > 1 {
+ let _ = self.index(row, col + 1).map(|index| {
+ self.cells[index - 1] = cell;
+ self.cells[index].ch = ' ';
+ });
+ } else {
+ let _ = self.index(row, col).map(|index| {
+ self.cells[index] = cell;
+ });
+ }
+ Ok(ch_width)
+ }
+
+ /// move cursor position (row, col) and show cursor
+ fn set_cursor(&mut self, row: usize, col: usize) -> Result<()> {
+ self.cursor.row = min(row, max(self.height, 1) - 1);
+ self.cursor.col = min(col, max(self.width, 1) - 1);
+ self.cursor.visible = true;
+ Ok(())
+ }
+
+ /// show/hide cursor, set `show` to `false` to hide the cursor
+ fn show_cursor(&mut self, show: bool) -> Result<()> {
+ self.cursor.visible = show;
+ Ok(())
+ }
+}
+
+pub struct CellIterator<'a> {
+ width: usize,
+ index: usize,
+ vec: &'a Vec<Cell>,
+}
+
+impl<'a> Iterator for CellIterator<'a> {
+ type Item = (usize, usize, &'a Cell);
+
+ fn next(&mut self) -> Option<Self::Item> {
+ if self.index >= self.vec.len() {
+ return None;
+ }
+
+ let (row, col) = (self.index / self.width, self.index % self.width);
+ let ret = self.vec.get(self.index).map(|cell| (row, col, cell));
+ self.index += 1;
+ ret
+ }
+}
+
+#[derive(Debug, Clone, Copy, Default)]
+struct Cursor {
+ pub row: usize,
+ pub col: usize,
+ visible: bool,
+}
+
+#[cfg(test)]
+mod test {
+ use super::*;
+
+ #[test]
+ fn test_cell_iterator() {
+ let mut screen = Screen::new(2, 2);
+ let _ = screen.put_cell(
+ 0,
+ 0,
+ Cell {
+ ch: 'a',
+ attr: Attr::default(),
+ },
+ );
+ let _ = screen.put_cell(
+ 0,
+ 1,
+ Cell {
+ ch: 'b',
+ attr: Attr::default(),
+ },
+ );
+ let _ = screen.put_cell(
+ 1,
+ 0,
+ Cell {
+ ch: 'c',
+ attr: Attr::default(),
+ },
+ );
+ let _ = screen.put_cell(
+ 1,
+ 1,
+ Cell {
+ ch: 'd',
+ attr: Attr::default(),
+ },
+ );
+
+ let mut iter = screen.iter_cell();
+ assert_eq!(
+ Some((
+ 0,
+ 0,
+ &Cell {
+ ch: 'a',
+ attr: Attr::default()
+ }
+ )),
+ iter.next()
+ );
+ assert_eq!(
+ Some((
+ 0,
+ 1,
+ &Cell {
+ ch: 'b',
+ attr: Attr::default()
+ }
+ )),
+ iter.next()
+ );
+ assert_eq!(
+ Some((
+ 1,
+ 0,
+ &Cell {
+ ch: 'c',
+ attr: Attr::default()
+ }
+ )),
+ iter.next()
+ );
+ assert_eq!(
+ Some((
+ 1,
+ 1,
+ &Cell {
+ ch: 'd',
+ attr: Attr::default()
+ }
+ )),
+ iter.next()
+ );
+ assert_eq!(None, iter.next());
+
+ let empty_screen = Screen::new(0, 0);
+ let mut empty_iter = empty_screen.iter_cell();
+ assert_eq!(None, empty_iter.next());
+ }
+}
diff --git a/vendor/skim-tuikit/src/sys/file.rs b/vendor/skim-tuikit/src/sys/file.rs
new file mode 100644
index 000000000..0d9031375
--- /dev/null
+++ b/vendor/skim-tuikit/src/sys/file.rs
@@ -0,0 +1,36 @@
+use crate::Result;
+use std::os::fd::BorrowedFd;
+use std::time::Duration;
+
+use crate::error::TuikitError;
+use nix::sys::select;
+use nix::sys::time::{TimeVal, TimeValLike};
+
+fn duration_to_timeval(duration: Duration) -> TimeVal {
+ let sec = duration.as_secs() * 1000 + (duration.subsec_millis() as u64);
+ TimeVal::milliseconds(sec as i64)
+}
+
+pub fn wait_until_ready(fd: BorrowedFd, signal_fd: Option<BorrowedFd>, timeout: Duration) -> Result<()> {
+ let mut timeout_spec = if timeout == Duration::new(0, 0) {
+ None
+ } else {
+ Some(duration_to_timeval(timeout))
+ };
+
+ let mut fdset = select::FdSet::new();
+ fdset.insert(fd);
+
+ if let Some(f) = signal_fd {
+ fdset.insert(f);
+ }
+ let n = select::select(None, &mut fdset, None, None, &mut timeout_spec)?;
+
+ if n < 1 {
+ Err(TuikitError::Timeout(timeout)) // this error message will be used in input.rs
+ } else if fdset.contains(fd) {
+ Ok(())
+ } else {
+ Err(TuikitError::Interrupted)
+ }
+}
diff --git a/vendor/skim-tuikit/src/sys/mod.rs b/vendor/skim-tuikit/src/sys/mod.rs
new file mode 100644
index 000000000..acc7f30b1
--- /dev/null
+++ b/vendor/skim-tuikit/src/sys/mod.rs
@@ -0,0 +1,27 @@
+// copy from https://docs.rs/crate/termion/1.5.1/source/src/sys/unix/mod.rs
+use std::io;
+pub mod file;
+pub mod signal;
+pub mod size;
+
+trait IsMinusOne {
+ fn is_minus_one(&self) -> bool;
+}
+
+macro_rules! impl_is_minus_one {
+ ($($t:ident)*) => ($(impl IsMinusOne for $t {
+ fn is_minus_one(&self) -> bool {
+ *self == -1
+ }
+ })*)
+ }
+
+impl_is_minus_one! { i8 i16 i32 i64 isize }
+
+fn cvt<T: IsMinusOne>(t: T) -> io::Result<T> {
+ if t.is_minus_one() {
+ Err(io::Error::last_os_error())
+ } else {
+ Ok(t)
+ }
+}
diff --git a/vendor/skim-tuikit/src/sys/signal.rs b/vendor/skim-tuikit/src/sys/signal.rs
new file mode 100644
index 000000000..d78307c48
--- /dev/null
+++ b/vendor/skim-tuikit/src/sys/signal.rs
@@ -0,0 +1,68 @@
+use lazy_static::lazy_static;
+use nix::sys::signal::{SaFlags, SigAction, SigHandler, SigSet, SigmaskHow, Signal};
+use nix::sys::signal::{pthread_sigmask, sigaction};
+use std::collections::HashMap;
+use std::sync::Mutex;
+use std::sync::Once;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::mpsc::{Receiver, Sender, channel};
+use std::thread;
+
+lazy_static! {
+ static ref NOTIFIER_COUNTER: AtomicUsize = AtomicUsize::new(1);
+ static ref NOTIFIER: Mutex<HashMap<usize, Sender<()>>> = Mutex::new(HashMap::new());
+}
+
+static ONCE: Once = Once::new();
+
+pub fn initialize_signals() {
+ ONCE.call_once(listen_sigwinch);
+}
+
+pub fn notify_on_sigwinch() -> (usize, Receiver<()>) {
+ let (tx, rx) = channel();
+ let new_id = NOTIFIER_COUNTER.fetch_add(1, Ordering::Relaxed);
+ let mut notifiers = NOTIFIER.lock().unwrap();
+ notifiers.entry(new_id).or_insert(tx);
+ (new_id, rx)
+}
+
+pub fn unregister_sigwinch(id: usize) -> Option<Sender<()>> {
+ let mut notifiers = NOTIFIER.lock().unwrap();
+ notifiers.remove(&id)
+}
+
+extern "C" fn handle_sigwiwnch(_: i32) {}
+
+fn listen_sigwinch() {
+ let (tx_sig, rx_sig) = channel();
+
+ // register terminal resize event, `pthread_sigmask` should be run before any thread.
+ let mut sigset = SigSet::empty();
+ sigset.add(Signal::SIGWINCH);
+ let _ = pthread_sigmask(SigmaskHow::SIG_BLOCK, Some(&sigset), None);
+
+ // SIGWINCH is ignored by mac by default, thus we need to register an empty handler
+ let action = SigAction::new(SigHandler::Handler(handle_sigwiwnch), SaFlags::empty(), SigSet::empty());
+
+ unsafe {
+ let _ = sigaction(Signal::SIGWINCH, &action);
+ }
+
+ thread::spawn(move || {
+ // listen to the resize event;
+ loop {
+ let _errno = sigset.wait();
+ let _ = tx_sig.send(());
+ }
+ });
+
+ thread::spawn(move || {
+ while rx_sig.recv().is_ok() {
+ let notifiers = NOTIFIER.lock().unwrap();
+ for (_, sender) in notifiers.iter() {
+ let _ = sender.send(());
+ }
+ }
+ });
+}
diff --git a/vendor/skim-tuikit/src/sys/size.rs b/vendor/skim-tuikit/src/sys/size.rs
new file mode 100644
index 000000000..c661e8f41
--- /dev/null
+++ b/vendor/skim-tuikit/src/sys/size.rs
@@ -0,0 +1,21 @@
+use std::{io, mem};
+
+use super::cvt;
+use nix::libc::{TIOCGWINSZ, c_int, c_ushort, ioctl};
+
+#[repr(C)]
+struct TermSize {
+ row: c_ushort,
+ col: c_ushort,
+ _x: c_ushort,
+ _y: c_ushort,
+}
+
+/// Get the size of the terminal.
+pub fn terminal_size(fd: c_int) -> io::Result<(usize, usize)> {
+ unsafe {
+ let mut size: TermSize = mem::zeroed();
+ cvt(ioctl(fd, TIOCGWINSZ, &mut size as *mut _))?;
+ Ok((size.col as usize, size.row as usize))
+ }
+}
diff --git a/vendor/skim-tuikit/src/term.rs b/vendor/skim-tuikit/src/term.rs
new file mode 100644
index 000000000..3062b736e
--- /dev/null
+++ b/vendor/skim-tuikit/src/term.rs
@@ -0,0 +1,838 @@
+//! Term is a thread-safe "terminal".
+//!
+//! It allows you to:
+//! - Listen to key stroke events
+//! - Output contents to the terminal
+//!
+//! ```no_run
+//! use skim_tuikit::prelude::*;
+//!
+//! let term = Term::<()>::new().unwrap();
+//!
+//! while let Ok(ev) = term.poll_event() {
+//! if let Event::Key(Key::Char('q')) = ev {
+//! break;
+//! }
+//!
+//! term.print(0, 0, format!("got event: {:?}", ev).as_str());
+//! term.present();
+//! }
+//! ```
+//!
+//! Term is modeled after [termbox](https://github.com/nsf/termbox). The main idea is viewing
+//! terminals as a table of fixed-size cells and input being a stream of structured messages
+
+use std::cmp::{max, min};
+use std::sync::Arc;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::mpsc::{Receiver, Sender, channel};
+use std::thread;
+use std::time::Duration;
+
+use crate::Result;
+use crate::attr::Attr;
+use crate::canvas::Canvas;
+use crate::cell::Cell;
+use crate::draw::Draw;
+use crate::error::TuikitError;
+use crate::event::Event;
+use crate::input::{KeyBoard, KeyboardHandler};
+use crate::key::Key;
+use crate::output::Command;
+use crate::output::Output;
+use crate::raw::{IntoRawMode, get_tty};
+use crate::screen::Screen;
+use crate::spinlock::SpinLock;
+use crate::sys::signal::{initialize_signals, notify_on_sigwinch, unregister_sigwinch};
+
+const MIN_HEIGHT: usize = 1;
+const WAIT_TIMEOUT: Duration = Duration::from_millis(300);
+const POLLING_TIMEOUT: Duration = Duration::from_millis(10);
+
+#[derive(Debug, Copy, Clone)]
+pub enum TermHeight {
+ Fixed(usize),
+ Percent(usize),
+}
+
+pub struct Term<UserEvent: Send + 'static = ()> {
+ components_to_stop: Arc<AtomicUsize>,
+ keyboard_handler: SpinLock<Option<KeyboardHandler>>,
+ resize_signal_id: Arc<AtomicUsize>,
+ term_lock: SpinLock<TermLock>,
+ event_rx: SpinLock<Receiver<Event<UserEvent>>>,
+ event_tx: Arc<SpinLock<Sender<Event<UserEvent>>>>,
+ raw_mouse: bool, // to produce raw mouse event or the parsed event(e.g. DoubleClick)
+}
+
+pub struct TermOptions {
+ max_height: TermHeight,
+ min_height: TermHeight,
+ height: TermHeight,
+ clear_on_exit: bool,
+ clear_on_start: bool,
+ mouse_enabled: bool,
+ raw_mouse: bool,
+ hold: bool, // to start term or not on creation
+ disable_alternate_screen: bool,
+}
+
+impl Default for TermOptions {
+ fn default() -> Self {
+ Self {
+ max_height: TermHeight::Percent(100),
+ min_height: TermHeight::Fixed(3),
+ height: TermHeight::Percent(100),
+ clear_on_exit: true,
+ clear_on_start: true,
+ mouse_enabled: false,
+ raw_mouse: false,
+ hold: false,
+ disable_alternate_screen: false,
+ }
+ }
+}
+
+// Builder
+impl TermOptions {
+ pub fn max_height(mut self, max_height: TermHeight) -> Self {
+ self.max_height = max_height;
+ self
+ }
+
+ pub fn min_height(mut self, min_height: TermHeight) -> Self {
+ self.min_height = min_height;
+ self
+ }
+ pub fn height(mut self, height: TermHeight) -> Self {
+ self.height = height;
+ self
+ }
+ pub fn clear_on_exit(mut self, clear: bool) -> Self {
+ self.clear_on_exit = clear;
+ self
+ }
+ pub fn clear_on_start(mut self, clear: bool) -> Self {
+ self.clear_on_start = clear;
+ self
+ }
+ pub fn mouse_enabled(mut self, enabled: bool) -> Self {
+ self.mouse_enabled = enabled;
+ self
+ }
+ pub fn raw_mouse(mut self, enabled: bool) -> Self {
+ self.raw_mouse = enabled;
+ self
+ }
+ pub fn hold(mut self, hold: bool) -> Self {
+ self.hold = hold;
+ self
+ }
+ pub fn disable_alternate_screen(mut self, disable_alternate_screen: bool) -> Self {
+ self.disable_alternate_screen = disable_alternate_screen;
+ self
+ }
+}
+
+impl<UserEvent: Send + 'static> Term<UserEvent> {
+ /// Create a Term with height specified.
+ ///
+ /// Internally if the calculated height would fill the whole screen, `Alternate Screen` will
+ /// be enabled, otherwise only part of the screen will be used.
+ ///
+ /// If the preferred height is larger than the current screen, whole screen is used.
+ ///
+ /// ```no_run
+ /// use skim_tuikit::term::{Term, TermHeight};
+ ///
+ /// let term: Term<()> = Term::with_height(TermHeight::Percent(30)).unwrap(); // 30% of the terminal height
+ /// let term: Term<()> = Term::with_height(TermHeight::Fixed(20)).unwrap(); // fixed 20 lines
+ /// ```
+ pub fn with_height(height: TermHeight) -> Result<Term<UserEvent>> {
+ Term::with_options(TermOptions::default().height(height))
+ }
+
+ /// Create a Term (with 100% height)
+ ///
+ /// ```no_run
+ /// use skim_tuikit::term::{Term, TermHeight};
+ ///
+ /// let term: Term<()> = Term::new().unwrap();
+ /// let term: Term<()> = Term::with_height(TermHeight::Percent(100)).unwrap();
+ /// ```
+ pub fn new() -> Result<Term<UserEvent>> {
+ Term::with_options(TermOptions::default())
+ }
+
+ /// Create a Term with custom options
+ ///
+ /// ```no_run
+ /// use skim_tuikit::term::{Term, TermHeight, TermOptions};
+ ///
+ /// let term: Term<()> = Term::with_options(TermOptions::default().height(TermHeight::Percent(100))).unwrap();
+ /// ```
+ pub fn with_options(options: TermOptions) -> Result<Term<UserEvent>> {
+ initialize_signals();
+
+ let (event_tx, event_rx) = channel();
+ let raw_mouse = options.raw_mouse;
+ let ret = Term {
+ components_to_stop: Arc::new(AtomicUsize::new(0)),
+ keyboard_handler: SpinLock::new(None),
+ resize_signal_id: Arc::new(AtomicUsize::new(0)),
+ term_lock: SpinLock::new(TermLock::with_options(&options)),
+ event_tx: Arc::new(SpinLock::new(event_tx)),
+ event_rx: SpinLock::new(event_rx),
+ raw_mouse,
+ };
+ if options.hold {
+ Ok(ret)
+ } else {
+ ret.restart().map(|_| ret)
+ }
+ }
+
+ fn ensure_not_stopped(&self) -> Result<()> {
+ if self.components_to_stop.load(Ordering::SeqCst) == 2 {
+ Ok(())
+ } else {
+ Err(TuikitError::TerminalNotStarted)
+ }
+ }
+
+ fn get_cursor_pos(&self, keyboard: &mut KeyBoard, output: &mut Output) -> Result<(usize, usize)> {
+ output.ask_for_cpr();
+
+ if let Ok(Key::CursorPos(row, col)) = keyboard.next_key_timeout(WAIT_TIMEOUT) {
+ return Ok((row as usize, col as usize));
+ }
+
+ Ok((0, 0))
+ }
+
+ /// restart the terminal if it had been stopped
+ pub fn restart(&self) -> Result<()> {
+ let mut termlock = self.term_lock.lock();
+ if self.components_to_stop.load(Ordering::SeqCst) == 2 {
+ return Ok(());
+ }
+
+ let ttyout = get_tty()?.into_raw_mode()?;
+ let mut output = Output::new(Box::new(ttyout))?;
+ let mut keyboard = KeyBoard::new_with_tty().raw_mouse(self.raw_mouse);
+ self.keyboard_handler.lock().replace(keyboard.get_interrupt_handler());
+ let cursor_pos = self.get_cursor_pos(&mut keyboard, &mut output)?;
+ termlock.restart(output, cursor_pos)?;
+
+ // start two listener
+ self.start_key_listener(keyboard);
+ self.start_size_change_listener();
+
+ // wait for components to start
+ while self.components_to_stop.load(Ordering::SeqCst) < 2 {
+ debug!(
+ "restart: components: {}",
+ self.components_to_stop.load(Ordering::SeqCst)
+ );
+ thread::sleep(POLLING_TIMEOUT);
+ }
+
+ let event_tx = self.event_tx.lock();
+ let _ = event_tx.send(Event::Restarted);
+
+ Ok(())
+ }
+
+ /// Pause the Term
+ ///
+ /// This function will cause the Term to give away the control to the terminal(such as listening
+ /// to the key strokes). After the Term was "paused", `poll_event` will block indefinitely and
+ /// recover after the Term was `restart`ed.
+ pub fn pause(&self) -> Result<()> {
+ self.pause_internal(false)
+ }
+
+ fn pause_internal(&self, exiting: bool) -> Result<()> {
+ debug!("pause");
+ let mut termlock = self.term_lock.lock();
+
+ if self.components_to_stop.load(Ordering::SeqCst) == 0 {
+ return Ok(());
+ }
+
+ // wait for the components to stop
+ // i.e. key_listener & size_change_listener
+ if let Some(h) = self.keyboard_handler.lock().take() {
+ h.interrupt()
+ }
+ unregister_sigwinch(self.resize_signal_id.load(Ordering::Relaxed)).map(|tx| tx.send(()));
+
+ termlock.pause(exiting)?;
+
+ // wait for the components to stop
+ while self.components_to_stop.load(Ordering::SeqCst) > 0 {
+ debug!("pause: components: {}", self.components_to_stop.load(Ordering::SeqCst));
+ thread::sleep(POLLING_TIMEOUT);
+ }
+
+ Ok(())
+ }
+
+ fn start_key_listener(&self, mut keyboard: KeyBoard) {
+ let event_tx_clone = self.event_tx.clone();
+ let components_to_stop = self.components_to_stop.clone();
+ thread::spawn(move || {
+ components_to_stop.fetch_add(1, Ordering::SeqCst);
+ debug!("key listener start");
+ loop {
+ let next_key = keyboard.next_key();
+ trace!("next key: {next_key:?}");
+ match next_key {
+ Ok(key) => {
+ let event_tx = event_tx_clone.lock();
+ let _ = event_tx.send(Event::Key(key));
+ }
+ Err(TuikitError::Interrupted) => break,
+ _ => {} // ignored
+ }
+ }
+ components_to_stop.fetch_sub(1, Ordering::SeqCst);
+ debug!("key listener stop");
+ });
+ }
+
+ fn start_size_change_listener(&self) {
+ let event_tx_clone = self.event_tx.clone();
+ let resize_signal_id = self.resize_signal_id.clone();
+ let components_to_stop = self.components_to_stop.clone();
+
+ thread::spawn(move || {
+ let (id, sigwinch_rx) = notify_on_sigwinch();
+ resize_signal_id.store(id, Ordering::Relaxed);
+
+ components_to_stop.fetch_add(1, Ordering::SeqCst);
+ debug!("size change listener started");
+ loop {
+ if sigwinch_rx.recv().is_ok() {
+ let event_tx = event_tx_clone.lock();
+ let _ = event_tx.send(Event::Resize { width: 0, height: 0 });
+ } else {
+ break;
+ }
+ }
+ components_to_stop.fetch_sub(1, Ordering::SeqCst);
+ debug!("size change listener stop");
+ });
+ }
+
+ fn filter_event(&self, event: Event<UserEvent>) -> Event<UserEvent> {
+ match event {
+ Event::Resize { .. } => {
+ {
+ let mut termlock = self.term_lock.lock();
+ let _ = termlock.on_resize();
+ }
+ let (width, height) = self.term_size().unwrap_or((0, 0));
+ Event::Resize { width, height }
+ }
+ Event::Key(Key::MousePress(button, row, col)) => {
+ // adjust mouse event position
+ let cursor_row = self.term_lock.lock().get_term_start_row() as u16;
+ if row < cursor_row {
+ Event::__Nonexhaustive
+ } else {
+ Event::Key(Key::MousePress(button, row - cursor_row, col))
+ }
+ }
+ Event::Key(Key::MouseRelease(row, col)) => {
+ // adjust mouse event position
+ let cursor_row = self.term_lock.lock().get_term_start_row() as u16;
+ if row < cursor_row {
+ Event::__Nonexhaustive
+ } else {
+ Event::Key(Key::MouseRelease(row - cursor_row, col))
+ }
+ }
+ Event::Key(Key::MouseHold(row, col)) => {
+ // adjust mouse event position
+ let cursor_row = self.term_lock.lock().get_term_start_row() as u16;
+ if row < cursor_row {
+ Event::__Nonexhaustive
+ } else {
+ Event::Key(Key::MouseHold(row - cursor_row, col))
+ }
+ }
+ Event::Key(Key::SingleClick(button, row, col)) => {
+ let cursor_row = self.term_lock.lock().get_term_start_row() as u16;
+ if row < cursor_row {
+ Event::__Nonexhaustive
+ } else {
+ Event::Key(Key::SingleClick(button, row - cursor_row, col))
+ }
+ }
+ Event::Key(Key::DoubleClick(button, row, col)) => {
+ let cursor_row = self.term_lock.lock().get_term_start_row() as u16;
+ if row < cursor_row {
+ Event::__Nonexhaustive
+ } else {
+ Event::Key(Key::DoubleClick(button, row - cursor_row, col))
+ }
+ }
+ Event::Key(Key::WheelUp(row, col, num)) => {
+ let cursor_row = self.term_lock.lock().get_term_start_row() as u16;
+ if row < cursor_row {
+ Event::__Nonexhaustive
+ } else {
+ Event::Key(Key::WheelUp(row - cursor_row, col, num))
+ }
+ }
+ Event::Key(Key::WheelDown(row, col, num)) => {
+ let cursor_row = self.term_lock.lock().get_term_start_row() as u16;
+ if row < cursor_row {
+ Event::__Nonexhaustive
+ } else {
+ Event::Key(Key::WheelDown(row - cursor_row, col, num))
+ }
+ }
+ ev => ev,
+ }
+ }
+
+ /// Wait an event up to `timeout` and return it
+ pub fn peek_event(&self, timeout: Duration) -> Result<Event<UserEvent>> {
+ let event_rx = self.event_rx.lock();
+ event_rx
+ .recv_timeout(timeout)
+ .map(|ev| self.filter_event(ev))
+ .map_err(|_| TuikitError::Timeout(timeout))
+ }
+
+ /// Wait for an event indefinitely and return it
+ pub fn poll_event(&self) -> Result<Event<UserEvent>> {
+ let event_rx = self.event_rx.lock();
+ event_rx
+ .recv()
+ .map(|ev| self.filter_event(ev))
+ .map_err(TuikitError::ChannelReceiveError)
+ }
+
+ /// An interface to inject event to the terminal's event queue
+ pub fn send_event(&self, event: Event<UserEvent>) -> Result<()> {
+ let event_tx = self.event_tx.lock();
+ event_tx
+ .send(event)
+ .map_err(|err| TuikitError::SendEventError(err.to_string()))
+ }
+
+ /// Sync internal buffer with terminal
+ pub fn present(&self) -> Result<()> {
+ self.ensure_not_stopped()?;
+ let mut termlock = self.term_lock.lock();
+ termlock.present()
+ }
+
+ /// Return the printable size(width, height) of the term
+ pub fn term_size(&self) -> Result<(usize, usize)> {
+ self.ensure_not_stopped()?;
+ let termlock = self.term_lock.lock();
+ termlock.term_size()
+ }
+
+ /// Clear internal buffer
+ pub fn clear(&self) -> Result<()> {
+ self.ensure_not_stopped()?;
+ let mut termlock = self.term_lock.lock();
+ termlock.clear()
+ }
+
+ /// Change a cell of position `(row, col)` to `cell`
+ pub fn put_cell(&self, row: usize, col: usize, cell: Cell) -> Result<usize> {
+ self.ensure_not_stopped()?;
+ let mut termlock = self.term_lock.lock();
+ termlock.put_cell(row, col, cell)
+ }
+
+ /// Print `content` starting with position `(row, col)`
+ pub fn print(&self, row: usize, col: usize, content: &str) -> Result<usize> {
+ self.print_with_attr(row, col, content, Attr::default())
+ }
+
+ /// print `content` starting with position `(row, col)` with `attr`
+ pub fn print_with_attr(&self, row: usize, col: usize, content: &str, attr: impl Into<Attr>) -> Result<usize> {
+ self.ensure_not_stopped()?;
+ let mut termlock = self.term_lock.lock();
+ termlock.print_with_attr(row, col, content, attr)
+ }
+
+ /// Set cursor position to (row, col), and show the cursor
+ pub fn set_cursor(&self, row: usize, col: usize) -> Result<()> {
+ self.ensure_not_stopped()?;
+ let mut termlock = self.term_lock.lock();
+ termlock.set_cursor(row, col)
+ }
+
+ /// show/hide cursor, set `show` to `false` to hide the cursor
+ pub fn show_cursor(&self, show: bool) -> Result<()> {
+ self.ensure_not_stopped()?;
+ let mut termlock = self.term_lock.lock();
+ termlock.show_cursor(show)
+ }
+
+ /// Enable mouse support
+ pub fn enable_mouse_support(&self) -> Result<()> {
+ self.ensure_not_stopped()?;
+ let mut termlock = self.term_lock.lock();
+ termlock.enable_mouse_support()
+ }
+
+ /// Disable mouse support
+ pub fn disable_mouse_support(&self) -> Result<()> {
+ self.ensure_not_stopped()?;
+ let mut termlock = self.term_lock.lock();
+ termlock.disable_mouse_support()
+ }
+
+ /// Whether to clear the terminal upon exiting. Defaults to true.
+ pub fn clear_on_exit(&self, clear: bool) -> Result<()> {
+ self.ensure_not_stopped()?;
+ let mut termlock = self.term_lock.lock();
+ termlock.clear_on_exit(clear);
+ Ok(())
+ }
+
+ pub fn draw(&self, draw: &dyn Draw) -> Result<()> {
+ let mut canvas = TermCanvas { term: self };
+ draw.draw(&mut canvas).map_err(TuikitError::DrawError)
+ }
+
+ pub fn draw_mut(&self, draw: &mut dyn Draw) -> Result<()> {
+ let mut canvas = TermCanvas { term: self };
+ draw.draw_mut(&mut canvas).map_err(TuikitError::DrawError)
+ }
+}
+
+impl<UserEvent: Send + 'static> Drop for Term<UserEvent> {
+ fn drop(&mut self) {
+ let _ = self.pause_internal(true);
+ }
+}
+
+pub struct TermCanvas<'a, UserEvent: Send + 'static> {
+ term: &'a Term<UserEvent>,
+}
+
+impl<UserEvent: Send + 'static> Canvas for TermCanvas<'_, UserEvent> {
+ fn size(&self) -> Result<(usize, usize)> {
+ self.term.term_size()
+ }
+
+ fn clear(&mut self) -> Result<()> {
+ self.term.clear()
+ }
+
+ fn put_cell(&mut self, row: usize, col: usize, cell: Cell) -> Result<usize> {
+ self.term.put_cell(row, col, cell)
+ }
+
+ fn print_with_attr(&mut self, row: usize, col: usize, content: &str, attr: Attr) -> Result<usize> {
+ self.term.print_with_attr(row, col, content, attr)
+ }
+
+ fn set_cursor(&mut self, row: usize, col: usize) -> Result<()> {
+ self.term.set_cursor(row, col)
+ }
+
+ fn show_cursor(&mut self, show: bool) -> Result<()> {
+ self.term.show_cursor(show)
+ }
+}
+
+struct TermLock {
+ prefer_height: TermHeight,
+ max_height: TermHeight,
+ min_height: TermHeight,
+ // keep bottom intact when resize?
+ bottom_intact: bool,
+ clear_on_exit: bool,
+ clear_on_start: bool,
+ mouse_enabled: bool,
+ alternate_screen: bool,
+ disable_alternate_screen: bool,
+ cursor_row: usize,
+ screen_height: usize,
+ screen_width: usize,
+ screen: Screen,
+ output: Option<Output>,
+}
+
+impl Default for TermLock {
+ fn default() -> Self {
+ Self {
+ prefer_height: TermHeight::Percent(100),
+ max_height: TermHeight::Percent(100),
+ min_height: TermHeight::Fixed(3),
+ bottom_intact: false,
+ alternate_screen: false,
+ disable_alternate_screen: false,
+ cursor_row: 0,
+ screen_height: 0,
+ screen_width: 0,
+ screen: Screen::new(0, 0),
+ output: None,
+ clear_on_exit: true,
+ clear_on_start: true,
+ mouse_enabled: false,
+ }
+ }
+}
+
+impl TermLock {
+ pub fn with_options(options: &TermOptions) -> Self {
+ let mut term = TermLock::default();
+ term.prefer_height = options.height;
+ term.max_height = options.max_height;
+ term.min_height = options.min_height;
+ term.clear_on_exit = options.clear_on_exit;
+ term.clear_on_start = options.clear_on_start;
+ term.screen.clear_on_start(options.clear_on_start);
+ term.disable_alternate_screen = options.disable_alternate_screen;
+ term.mouse_enabled = options.mouse_enabled;
+ term
+ }
+
+ /// Present the content to the terminal
+ pub fn present(&mut self) -> Result<()> {
+ let output = self.output.as_mut().ok_or(TuikitError::TerminalNotStarted)?;
+ let mut commands = self.screen.present();
+
+ let cursor_row = self.cursor_row;
+ // add cursor_row to all CursorGoto commands
+ for cmd in commands.iter_mut() {
+ if let Command::CursorGoto { row, col } = *cmd {
+ *cmd = Command::CursorGoto {
+ row: row + cursor_row,
+ col,
+ }
+ }
+ }
+
+ for cmd in commands.into_iter() {
+ output.execute(cmd);
+ }
+ output.flush();
+ Ok(())
+ }
+
+ /// Resize the internal buffer to according to new terminal size
+ pub fn on_resize(&mut self) -> Result<()> {
+ let output = self.output.as_mut().ok_or(TuikitError::TerminalNotStarted)?;
+ let (screen_width, screen_height) = output.terminal_size().expect("term:restart get terminal size failed");
+ self.screen_height = screen_height;
+ self.screen_width = screen_width;
+
+ let width = screen_width;
+ let height =
+ Self::calc_preferred_height(&self.min_height, &self.max_height, &self.prefer_height, screen_height);
+
+ // update the cursor position
+ if self.cursor_row + height >= screen_height {
+ self.bottom_intact = true;
+ }
+
+ if self.bottom_intact {
+ self.cursor_row = screen_height - height;
+ }
+
+ // clear the screen
+ output.cursor_goto(self.cursor_row, 0);
+ if self.clear_on_start {
+ output.erase_down();
+ }
+
+ // clear the screen buffer
+ self.screen.resize(width, height);
+ Ok(())
+ }
+
+ fn calc_height(height_spec: &TermHeight, actual_height: usize) -> usize {
+ match *height_spec {
+ TermHeight::Fixed(h) => h,
+ TermHeight::Percent(p) => actual_height * min(p, 100) / 100,
+ }
+ }
+
+ fn calc_preferred_height(
+ min_height: &TermHeight,
+ max_height: &TermHeight,
+ prefer_height: &TermHeight,
+ height: usize,
+ ) -> usize {
+ let max_height = Self::calc_height(max_height, height);
+ let min_height = Self::calc_height(min_height, height);
+ let prefer_height = Self::calc_height(prefer_height, height);
+
+ // ensure the calculated height is in range (MIN_HEIGHT, height)
+ let max_height = max(min(max_height, height), MIN_HEIGHT);
+ let min_height = max(min(min_height, height), MIN_HEIGHT);
+ max(min(prefer_height, max_height), min_height)
+ }
+
+ /// Pause the terminal
+ fn pause(&mut self, exiting: bool) -> Result<()> {
+ self.disable_mouse()?;
+ if let Some(mut output) = self.output.take() {
+ output.show_cursor();
+ if self.clear_on_exit || !exiting {
+ // clear drawn contents
+ if !self.disable_alternate_screen {
+ output.quit_alternate_screen();
+ } else {
+ output.cursor_goto(self.cursor_row, 0);
+ output.erase_down();
+ }
+ } else {
+ output.cursor_goto(self.cursor_row + self.screen.height(), 0);
+ if self.bottom_intact {
+ output.write("\n");
+ }
+ }
+ output.flush();
+ }
+ Ok(())
+ }
+
+ /// ensure the screen had enough height
+ /// If the prefer height is full screen, it will enter alternate screen
+ /// otherwise it will ensure there are enough lines at the bottom
+ fn ensure_height(&mut self, cursor_pos: (usize, usize)) -> Result<()> {
+ let output = self.output.as_mut().ok_or(TuikitError::TerminalNotStarted)?;
+
+ // initialize
+
+ let (screen_width, screen_height) = output
+ .terminal_size()
+ .expect("termlock:ensure_height get terminal size failed");
+ let height_to_be =
+ Self::calc_preferred_height(&self.min_height, &self.max_height, &self.prefer_height, screen_height);
+
+ self.alternate_screen = false;
+ let (mut cursor_row, cursor_col) = cursor_pos;
+ if height_to_be >= screen_height {
+ // whole screen
+ self.alternate_screen = true;
+ self.bottom_intact = false;
+ self.cursor_row = 0;
+ if !self.disable_alternate_screen {
+ output.enter_alternate_screen();
+ }
+ } else {
+ // only use part of the screen
+
+ // go to a new line so that existing line won't be messed up
+ if cursor_col > 0 {
+ output.write("\n");
+ cursor_row += 1;
+ }
+
+ if (cursor_row + height_to_be) <= screen_height {
+ self.bottom_intact = false;
+ self.cursor_row = cursor_row;
+ } else {
+ for _ in 0..(height_to_be - 1) {
+ output.write("\n");
+ }
+ self.bottom_intact = true;
+ self.cursor_row = min(cursor_row, screen_height - height_to_be);
+ }
+ }
+
+ output.cursor_goto(self.cursor_row, 0);
+ output.flush();
+ self.screen_height = screen_height;
+ self.screen_width = screen_width;
+ Ok(())
+ }
+
+ /// get the start row of the terminal
+ pub fn get_term_start_row(&self) -> usize {
+ self.cursor_row
+ }
+
+ /// restart the terminal
+ pub fn restart(&mut self, output: Output, cursor_pos: (usize, usize)) -> Result<()> {
+ // ensure the output area had enough height
+ self.output.replace(output);
+ self.ensure_height(cursor_pos)?;
+ self.on_resize()?;
+ if self.mouse_enabled {
+ self.enable_mouse()?;
+ }
+ Ok(())
+ }
+
+ /// return the printable size(width, height) of the term
+ pub fn term_size(&self) -> Result<(usize, usize)> {
+ self.screen.size()
+ }
+
+ /// clear internal buffer
+ pub fn clear(&mut self) -> Result<()> {
+ self.screen.clear()
+ }
+
+ /// change a cell of position `(row, col)` to `cell`
+ pub fn put_cell(&mut self, row: usize, col: usize, cell: Cell) -> Result<usize> {
+ self.screen.put_cell(row, col, cell)
+ }
+
+ /// print `content` starting with position `(row, col)`
+ pub fn print_with_attr(&mut self, row: usize, col: usize, content: &str, attr: impl Into<Attr>) -> Result<usize> {
+ self.screen.print_with_attr(row, col, content, attr.into())
+ }
+
+ /// set cursor position to (row, col)
+ pub fn set_cursor(&mut self, row: usize, col: usize) -> Result<()> {
+ self.screen.set_cursor(row, col)
+ }
+
+ /// show/hide cursor, set `show` to `false` to hide the cursor
+ pub fn show_cursor(&mut self, show: bool) -> Result<()> {
+ self.screen.show_cursor(show)
+ }
+
+ /// Enable mouse support
+ pub fn enable_mouse_support(&mut self) -> Result<()> {
+ self.mouse_enabled = true;
+ self.enable_mouse()
+ }
+
+ /// Disable mouse support
+ pub fn disable_mouse_support(&mut self) -> Result<()> {
+ self.mouse_enabled = false;
+ self.disable_mouse()
+ }
+
+ pub fn clear_on_exit(&mut self, clear: bool) {
+ self.clear_on_exit = clear;
+ }
+
+ /// Enable mouse (send ANSI codes to enable mouse)
+ fn enable_mouse(&mut self) -> Result<()> {
+ let output = self.output.as_mut().ok_or(TuikitError::TerminalNotStarted)?;
+ output.enable_mouse_support();
+ Ok(())
+ }
+
+ /// Disable mouse (send ANSI codes to disable mouse)
+ fn disable_mouse(&mut self) -> Result<()> {
+ let output = self.output.as_mut().ok_or(TuikitError::TerminalNotStarted)?;
+ output.disable_mouse_support();
+ Ok(())
+ }
+}
+
+impl Drop for TermLock {
+ fn drop(&mut self) {
+ let _ = self.pause(true);
+ }
+}
diff --git a/vendor/skim-tuikit/src/widget/align.rs b/vendor/skim-tuikit/src/widget/align.rs
new file mode 100644
index 000000000..fede49fdd
--- /dev/null
+++ b/vendor/skim-tuikit/src/widget/align.rs
@@ -0,0 +1,119 @@
+pub trait AlignSelf {
+ /// say horizontal align, given container's (start, end) and self's size
+ /// Adjust the actual start position of self.
+ ///
+ /// Note that if the container's size < self_size, will return `start`
+ fn adjust(&self, start: usize, end_exclusive: usize, self_size: usize) -> usize;
+}
+
+pub enum HorizontalAlign {
+ Left,
+ Center,
+ Right,
+}
+
+pub enum VerticalAlign {
+ Top,
+ Middle,
+ Bottom,
+}
+
+impl AlignSelf for HorizontalAlign {
+ fn adjust(&self, start: usize, end: usize, self_size: usize) -> usize {
+ if start >= end {
+ // wrong input
+ return start;
+ }
+ let container_size = end - start;
+ if container_size <= self_size {
+ return start;
+ }
+
+ match self {
+ HorizontalAlign::Left => start,
+ HorizontalAlign::Center => start + (container_size - self_size) / 2,
+ HorizontalAlign::Right => end - self_size,
+ }
+ }
+}
+
+impl AlignSelf for VerticalAlign {
+ fn adjust(&self, start: usize, end: usize, self_size: usize) -> usize {
+ if start >= end {
+ // wrong input
+ return start;
+ }
+ let container_size = end - start;
+ if container_size <= self_size {
+ return start;
+ }
+
+ match self {
+ VerticalAlign::Top => start,
+ VerticalAlign::Middle => start + (container_size - self_size) / 2,
+ VerticalAlign::Bottom => end - self_size,
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::widget::align::{AlignSelf, HorizontalAlign, VerticalAlign};
+
+ #[test]
+ fn size_lt0_return_start() {
+ assert_eq!(0, HorizontalAlign::Left.adjust(0, 0, 2));
+ assert_eq!(0, HorizontalAlign::Center.adjust(0, 0, 2));
+ assert_eq!(0, HorizontalAlign::Right.adjust(0, 0, 2));
+ assert_eq!(0, VerticalAlign::Top.adjust(0, 0, 2));
+ assert_eq!(0, VerticalAlign::Middle.adjust(0, 0, 2));
+ assert_eq!(0, VerticalAlign::Bottom.adjust(0, 0, 2));
+
+ assert_eq!(2, HorizontalAlign::Left.adjust(2, 0, 2));
+ assert_eq!(2, HorizontalAlign::Center.adjust(2, 0, 2));
+ assert_eq!(2, HorizontalAlign::Right.adjust(2, 0, 2));
+ assert_eq!(2, VerticalAlign::Top.adjust(2, 0, 2));
+ assert_eq!(2, VerticalAlign::Middle.adjust(2, 0, 2));
+ assert_eq!(2, VerticalAlign::Bottom.adjust(2, 0, 2));
+ }
+
+ #[test]
+ fn container_size_too_small_return_start() {
+ assert_eq!(2, HorizontalAlign::Left.adjust(2, 3, 2));
+ assert_eq!(2, HorizontalAlign::Center.adjust(2, 3, 2));
+ assert_eq!(2, HorizontalAlign::Right.adjust(2, 3, 2));
+ assert_eq!(2, VerticalAlign::Top.adjust(2, 3, 2));
+ assert_eq!(2, VerticalAlign::Middle.adjust(2, 3, 2));
+ assert_eq!(2, VerticalAlign::Bottom.adjust(2, 3, 2));
+ }
+
+ #[test]
+ fn align_start() {
+ assert_eq!(2, HorizontalAlign::Left.adjust(2, 8, 2));
+ assert_eq!(2, VerticalAlign::Top.adjust(2, 8, 2));
+ assert_eq!(2, HorizontalAlign::Left.adjust(2, 7, 2));
+ assert_eq!(2, VerticalAlign::Top.adjust(2, 7, 2));
+ assert_eq!(2, HorizontalAlign::Left.adjust(2, 8, 3));
+ assert_eq!(2, VerticalAlign::Top.adjust(2, 8, 3));
+ }
+
+ #[test]
+ fn align_end() {
+ assert_eq!(6, HorizontalAlign::Right.adjust(2, 8, 2));
+ assert_eq!(6, VerticalAlign::Bottom.adjust(2, 8, 2));
+ assert_eq!(5, HorizontalAlign::Right.adjust(2, 7, 2));
+ assert_eq!(5, VerticalAlign::Bottom.adjust(2, 7, 2));
+ assert_eq!(5, HorizontalAlign::Right.adjust(2, 8, 3));
+ assert_eq!(5, VerticalAlign::Bottom.adjust(2, 8, 3));
+ }
+
+ #[test]
+ fn align_center() {
+ assert_eq!(4, HorizontalAlign::Center.adjust(2, 8, 2));
+ assert_eq!(4, VerticalAlign::Middle.adjust(2, 8, 2));
+ assert_eq!(3, HorizontalAlign::Center.adjust(2, 7, 2));
+ assert_eq!(3, VerticalAlign::Middle.adjust(2, 7, 2));
+ assert_eq!(3, HorizontalAlign::Center.adjust(2, 8, 3));
+ assert_eq!(3, VerticalAlign::Middle.adjust(2, 8, 3));
+ }
+}
diff --git a/vendor/skim-tuikit/src/widget/mod.rs b/vendor/skim-tuikit/src/widget/mod.rs
new file mode 100644
index 000000000..2d5a6382d
--- /dev/null
+++ b/vendor/skim-tuikit/src/widget/mod.rs
@@ -0,0 +1,137 @@
+pub use self::align::*;
+// Various pre-defined widget that implements Draw
+pub use self::split::*;
+pub use self::stack::*;
+pub use self::win::*;
+use crate::draw::Draw;
+use crate::event::Event;
+use std::cmp::min;
+mod align;
+mod split;
+mod stack;
+mod util;
+mod win;
+
+/// Whether fixed size or percentage
+#[derive(Debug, Copy, Clone, Default)]
+pub enum Size {
+ Fixed(usize),
+ Percent(usize),
+ #[default]
+ Default,
+}
+
+impl Size {
+ pub fn calc_fixed_size(&self, total_size: usize, default_size: usize) -> usize {
+ match *self {
+ Size::Fixed(fixed) => min(total_size, fixed),
+ Size::Percent(percent) => min(total_size, total_size * percent / 100),
+ Size::Default => default_size,
+ }
+ }
+}
+
+impl From<usize> for Size {
+ fn from(size: usize) -> Self {
+ Size::Fixed(size)
+ }
+}
+
+#[derive(Copy, Clone, Debug)]
+pub struct Rectangle {
+ pub top: usize,
+ pub left: usize,
+ pub width: usize,
+ pub height: usize,
+}
+
+impl Rectangle {
+ /// check if the given point(row, col) lies in the rectangle
+ pub fn contains(&self, row: usize, col: usize) -> bool {
+ if row < self.top || row >= self.top + self.height {
+ false
+ } else {
+ !(col < self.left || col >= self.left + self.width)
+ }
+ }
+
+ /// assume the point (row, col) lies in the rectangle, adjust the origin to the rectangle's
+ /// origin (top, left)
+ pub fn relative_to_origin(&self, row: usize, col: usize) -> (usize, usize) {
+ (row - self.top, col - self.left)
+ }
+
+ pub fn adjust_origin(&self) -> Rectangle {
+ Self {
+ top: 0,
+ left: 0,
+ width: self.width,
+ height: self.height,
+ }
+ }
+}
+
+/// A widget could be recursive nested
+pub trait Widget<Message = ()>: Draw {
+ /// the (width, height) of the content
+ /// it will be the hint for layouts to calculate the final size
+ fn size_hint(&self) -> (Option<usize>, Option<usize>) {
+ (None, None)
+ }
+
+ /// given a key event, emit zero or more messages
+ /// typical usage is the mouse click event where containers would pass the event down
+ /// to their children.
+ fn on_event(&self, event: Event, rect: Rectangle) -> Vec<Message> {
+ let _ = (event, rect); // avoid warning
+ Vec::new()
+ }
+
+ /// same as `on_event` except that the self reference is mutable
+ fn on_event_mut(&mut self, event: Event, rect: Rectangle) -> Vec<Message> {
+ let _ = (event, rect); // avoid warning
+ Vec::new()
+ }
+}
+
+impl<Message, T: Widget<Message>> Widget<Message> for &T {
+ fn size_hint(&self) -> (Option<usize>, Option<usize>) {
+ (*self).size_hint()
+ }
+
+ fn on_event(&self, event: Event, rect: Rectangle) -> Vec<Message> {
+ (*self).on_event(event, rect)
+ }
+
+ fn on_event_mut(&mut self, event: Event, rect: Rectangle) -> Vec<Message> {
+ (**self).on_event(event, rect)
+ }
+}
+
+impl<Message, T: Widget<Message>> Widget<Message> for &mut T {
+ fn size_hint(&self) -> (Option<usize>, Option<usize>) {
+ (**self).size_hint()
+ }
+
+ fn on_event(&self, event: Event, rect: Rectangle) -> Vec<Message> {
+ (**self).on_event(event, rect)
+ }
+
+ fn on_event_mut(&mut self, event: Event, rect: Rectangle) -> Vec<Message> {
+ (**self).on_event_mut(event, rect)
+ }
+}
+
+impl<Message, T: Widget<Message> + ?Sized> Widget<Message> for Box<T> {
+ fn size_hint(&self) -> (Option<usize>, Option<usize>) {
+ self.as_ref().size_hint()
+ }
+
+ fn on_event(&self, event: Event, rect: Rectangle) -> Vec<Message> {
+ self.as_ref().on_event(event, rect)
+ }
+
+ fn on_event_mut(&mut self, event: Event, rect: Rectangle) -> Vec<Message> {
+ self.as_mut().on_event_mut(event, rect)
+ }
+}
diff --git a/vendor/skim-tuikit/src/widget/split.rs b/vendor/skim-tuikit/src/widget/split.rs
new file mode 100644
index 000000000..62ff7b667
--- /dev/null
+++ b/vendor/skim-tuikit/src/widget/split.rs
@@ -0,0 +1,1267 @@
+use super::Size;
+use super::util::adjust_event;
+use super::{Rectangle, Widget};
+use crate::canvas::{BoundedCanvas, Canvas};
+use crate::draw::Draw;
+use crate::draw::DrawResult;
+use crate::event::Event;
+use std::cmp::{Ordering, min};
+
+/// A Split item would contain 3 things
+/// 0. inner_size, will be used if `basis` is `Size::Default`.
+/// 1. basis, the original size
+/// 2. grow, the factor to grow if there is still enough room
+/// 3. shrink, the factor to shrink if there is not enough room
+pub trait Split<Message = ()>: Widget<Message> {
+ fn get_basis(&self) -> Size;
+
+ fn get_grow(&self) -> usize;
+
+ fn get_shrink(&self) -> usize;
+
+ /// get the default size of inner content, will be used if `basis` is Default
+ fn inner_size(&self) -> (Size, Size) {
+ let (width, height) = self.size_hint();
+ let width = width.map(Size::Fixed).unwrap_or(Size::Default);
+ let height = height.map(Size::Fixed).unwrap_or(Size::Default);
+ (width, height)
+ }
+}
+
+impl<Message, T: Split<Message> + Widget<Message>> Split<Message> for &T {
+ fn get_basis(&self) -> Size {
+ (*self).get_basis()
+ }
+
+ fn get_grow(&self) -> usize {
+ (*self).get_grow()
+ }
+
+ fn get_shrink(&self) -> usize {
+ (*self).get_shrink()
+ }
+
+ fn inner_size(&self) -> (Size, Size) {
+ (*self).inner_size()
+ }
+}
+
+impl<Message, T: Split<Message> + Widget<Message>> Split<Message> for &mut T {
+ fn get_basis(&self) -> Size {
+ (**self).get_basis()
+ }
+
+ fn get_grow(&self) -> usize {
+ (**self).get_grow()
+ }
+
+ fn get_shrink(&self) -> usize {
+ (**self).get_shrink()
+ }
+
+ fn inner_size(&self) -> (Size, Size) {
+ (**self).inner_size()
+ }
+}
+
+enum Op {
+ Noop,
+ Grow,
+ Shrink,
+}
+
+enum SplitType {
+ Horizontal,
+ Vertical,
+}
+
+trait SplitContainer<'a, Message = ()> {
+ fn get_splits(&self) -> &[Box<dyn Split<Message> + 'a>];
+
+ fn get_split_type(&self) -> SplitType;
+
+ /// return the target sizes of the splits
+ fn retrieve_split_info(&self, actual_size: usize) -> Vec<usize> {
+ let split_type = self.get_split_type();
+
+ let split_sizes: Vec<usize> = self
+ .get_splits()
+ .iter()
+ .map(|split| {
+ let (width, height) = split.inner_size();
+ let default = match &split_type {
+ SplitType::Horizontal => width,
+ SplitType::Vertical => height,
+ };
+
+ match split.get_basis() {
+ Size::Default => default,
+ basis => basis,
+ }
+ })
+ .map(|size| size.calc_fixed_size(actual_size, actual_size))
+ .collect();
+
+ let target_total_size: usize = split_sizes.iter().sum();
+
+ let op = match target_total_size.cmp(&actual_size) {
+ Ordering::Equal => Op::Noop,
+ Ordering::Less => Op::Grow,
+ Ordering::Greater => Op::Shrink,
+ };
+
+ let size_diff = match op {
+ Op::Noop => 0,
+ Op::Grow => actual_size - target_total_size,
+ Op::Shrink => target_total_size - actual_size,
+ };
+
+ let split_factors: Vec<usize> = self
+ .get_splits()
+ .iter()
+ .map(|split| match op {
+ Op::Noop => 0,
+ Op::Shrink => split.get_shrink(),
+ Op::Grow => split.get_grow(),
+ })
+ .collect();
+
+ let total_factors: usize = split_factors.iter().sum();
+
+ let unit = if total_factors == 0 {
+ 0
+ } else {
+ size_diff / total_factors
+ };
+
+ (0..split_sizes.len())
+ .map(|idx| {
+ let diff = split_factors[idx] * unit;
+ match op {
+ Op::Noop => split_sizes[idx],
+ Op::Grow => split_sizes[idx] + diff,
+ Op::Shrink => split_sizes[idx] - min(split_sizes[idx], diff),
+ }
+ })
+ .collect()
+ }
+}
+
+/// HSplit will split the area horizontally. It will
+/// 1. Count the total width(basis) of the split items it contains
+/// 2. Judge if the current width is enough or not for the split items
+/// 3. shrink/grow the split items according to their factors / (total factors)
+/// 4. If still not enough room, the last one(s) would be set width 0
+pub struct HSplit<'a, Message = ()> {
+ basis: Size,
+ grow: usize,
+ shrink: usize,
+ splits: Vec<Box<dyn Split<Message> + 'a>>,
+}
+
+impl<Message> Default for HSplit<'_, Message> {
+ fn default() -> Self {
+ Self {
+ basis: Size::Default,
+ grow: 1,
+ shrink: 1,
+ splits: Vec::new(),
+ }
+ }
+}
+
+impl<'a, Message> HSplit<'a, Message> {
+ pub fn split(mut self, split: impl Split<Message> + 'a) -> Self {
+ self.splits.push(Box::new(split));
+ self
+ }
+
+ pub fn basis(mut self, basis: impl Into<Size>) -> Self {
+ self.basis = basis.into();
+ self
+ }
+
+ pub fn grow(mut self, grow: usize) -> Self {
+ self.grow = grow;
+ self
+ }
+
+ pub fn shrink(mut self, shrink: usize) -> Self {
+ self.shrink = shrink;
+ self
+ }
+}
+
+impl<'a, Message> SplitContainer<'a, Message> for HSplit<'a, Message> {
+ fn get_splits(&self) -> &[Box<dyn Split<Message> + 'a>] {
+ &self.splits
+ }
+
+ fn get_split_type(&self) -> SplitType {
+ SplitType::Horizontal
+ }
+}
+
+impl<Message> Draw for HSplit<'_, Message> {
+ fn draw(&self, canvas: &mut dyn Canvas) -> DrawResult<()> {
+ let (width, height) = canvas.size()?;
+ let target_widths = self.retrieve_split_info(width);
+
+ // iterate over the splits
+ let mut left = 0;
+ for (idx, split) in self.splits.iter().enumerate() {
+ let target_width = target_widths[idx];
+ let right = min(left + target_width, width);
+ let mut new_canvas = BoundedCanvas::new(0, left, right - left, height, canvas);
+ let _ = split.draw(&mut new_canvas);
+ left = right;
+ }
+
+ Ok(())
+ }
+
+ fn draw_mut(&mut self, canvas: &mut dyn Canvas) -> DrawResult<()> {
+ let (width, height) = canvas.size()?;
+ let target_widths = self.retrieve_split_info(width);
+
+ // iterate over the splits
+ let mut left = 0;
+ for (idx, split) in self.splits.iter_mut().enumerate() {
+ let target_width = target_widths[idx];
+ let right = min(left + target_width, width);
+ let mut new_canvas = BoundedCanvas::new(0, left, right - left, height, canvas);
+ let _ = split.draw_mut(&mut new_canvas);
+ left = right;
+ }
+
+ Ok(())
+ }
+}
+
+impl<Message> Widget<Message> for HSplit<'_, Message> {
+ fn size_hint(&self) -> (Option<usize>, Option<usize>) {
+ let has_width_hint = self.splits.iter().any(|split| split.size_hint().0.is_some());
+ let has_height_hint = self.splits.iter().any(|split| split.size_hint().1.is_some());
+
+ let width = if has_width_hint {
+ Some(self.splits.iter().map(|split| split.size_hint().0.unwrap_or(0)).sum())
+ } else {
+ None
+ };
+
+ let height = if has_height_hint {
+ Some(
+ self.splits
+ .iter()
+ .map(|split| split.size_hint().1.unwrap_or(0))
+ .max()
+ .unwrap_or(0),
+ )
+ } else {
+ None
+ };
+
+ (width, height)
+ }
+
+ fn on_event(&self, event: Event, rect: Rectangle) -> Vec<Message> {
+ // should collect events from every children
+ let target_widths = self.retrieve_split_info(rect.width);
+ let Rectangle { top, width, height, .. } = rect;
+ let mut messages = vec![];
+
+ // iterate over the splits
+ let mut left = 0;
+ for (idx, split) in self.splits.iter().enumerate() {
+ let target_width = target_widths[idx];
+ let right = min(left + target_width, width);
+ let sub_rect = Rectangle {
+ top,
+ left,
+ width: target_width,
+ height,
+ };
+
+ let mut sub_message = adjust_event(event, sub_rect)
+ .map(|ev| split.as_ref().on_event(ev, sub_rect.adjust_origin()))
+ .unwrap_or_default();
+ messages.append(&mut sub_message);
+ left = right;
+ }
+
+ messages
+ }
+
+ fn on_event_mut(&mut self, event: Event, rect: Rectangle) -> Vec<Message> {
+ // should collect events from every children
+ let target_widths = self.retrieve_split_info(rect.width);
+ let Rectangle { top, width, height, .. } = rect;
+ let mut messages = vec![];
+
+ // iterate over the splits
+ let mut left = 0;
+ for (idx, split) in self.splits.iter_mut().enumerate() {
+ let target_width = target_widths[idx];
+ let right = min(left + target_width, width);
+ let sub_rect = Rectangle {
+ top,
+ left,
+ width: target_width,
+ height,
+ };
+
+ let mut sub_message = adjust_event(event, sub_rect)
+ .map(|ev| split.as_mut().on_event_mut(ev, sub_rect.adjust_origin()))
+ .unwrap_or_default();
+ messages.append(&mut sub_message);
+ left = right;
+ }
+
+ messages
+ }
+}
+
+impl<Message> Split<Message> for HSplit<'_, Message> {
+ fn get_basis(&self) -> Size {
+ self.basis
+ }
+
+ fn get_grow(&self) -> usize {
+ self.grow
+ }
+
+ fn get_shrink(&self) -> usize {
+ self.shrink
+ }
+}
+
+/// VSplit will split the area vertically. It will
+/// 1. Count the total height(basis) of the split items it contains
+/// 2. Judge if the current height is enough or not for the split items
+/// 3. shrink/grow the split items according to their factors / (total factors)
+/// 4. If still not enough room, the last one(s) would be set height 0
+pub struct VSplit<'a, Message = ()> {
+ basis: Size,
+ grow: usize,
+ shrink: usize,
+ splits: Vec<Box<dyn Split<Message> + 'a>>,
+}
+
+impl<Message> Default for VSplit<'_, Message> {
+ fn default() -> Self {
+ Self {
+ basis: Size::Default,
+ grow: 1,
+ shrink: 1,
+ splits: Vec::new(),
+ }
+ }
+}
+
+impl<'a, Message> VSplit<'a, Message> {
+ pub fn split(mut self, split: impl Split<Message> + 'a) -> Self {
+ self.splits.push(Box::new(split));
+ self
+ }
+
+ pub fn basis(mut self, basis: impl Into<Size>) -> Self {
+ self.basis = basis.into();
+ self
+ }
+
+ pub fn grow(mut self, grow: usize) -> Self {
+ self.grow = grow;
+ self
+ }
+
+ pub fn shrink(mut self, shrink: usize) -> Self {
+ self.shrink = shrink;
+ self
+ }
+}
+
+impl<'a, Message> SplitContainer<'a, Message> for VSplit<'a, Message> {
+ fn get_splits(&self) -> &[Box<dyn Split<Message> + 'a>] {
+ &self.splits
+ }
+
+ fn get_split_type(&self) -> SplitType {
+ SplitType::Vertical
+ }
+}
+
+impl<Message> Draw for VSplit<'_, Message> {
+ fn draw(&self, canvas: &mut dyn Canvas) -> DrawResult<()> {
+ let (width, height) = canvas.size()?;
+ let target_heights = self.retrieve_split_info(height);
+
+ // iterate over the splits
+ let mut top = 0;
+ for (idx, split) in self.splits.iter().enumerate() {
+ let target_height = target_heights[idx];
+ let bottom = min(top + target_height, height);
+ let mut new_canvas = BoundedCanvas::new(top, 0, width, bottom - top, canvas);
+ let _ = split.draw(&mut new_canvas);
+ top = bottom;
+ }
+
+ Ok(())
+ }
+ fn draw_mut(&mut self, canvas: &mut dyn Canvas) -> DrawResult<()> {
+ let (width, height) = canvas.size()?;
+ let target_heights = self.retrieve_split_info(height);
+
+ // iterate over the splits
+ let mut top = 0;
+ for (idx, split) in self.splits.iter_mut().enumerate() {
+ let target_height = target_heights[idx];
+ let bottom = min(top + target_height, height);
+ let mut new_canvas = BoundedCanvas::new(top, 0, width, bottom - top, canvas);
+ let _ = split.draw_mut(&mut new_canvas);
+ top = bottom;
+ }
+
+ Ok(())
+ }
+}
+
+impl<Message> Widget<Message> for VSplit<'_, Message> {
+ fn size_hint(&self) -> (Option<usize>, Option<usize>) {
+ let has_width_hint = self.splits.iter().any(|split| split.size_hint().0.is_some());
+ let has_height_hint = self.splits.iter().any(|split| split.size_hint().1.is_some());
+
+ let width = if has_width_hint {
+ Some(
+ self.splits
+ .iter()
+ .map(|split| split.size_hint().0.unwrap_or(0))
+ .max()
+ .unwrap_or(0),
+ )
+ } else {
+ None
+ };
+
+ let height = if has_height_hint {
+ Some(self.splits.iter().map(|split| split.size_hint().1.unwrap_or(0)).sum())
+ } else {
+ None
+ };
+
+ (width, height)
+ }
+
+ fn on_event(&self, event: Event, rect: Rectangle) -> Vec<Message> {
+ // should collect events from every children
+ let target_heights = self.retrieve_split_info(rect.height);
+ let Rectangle {
+ left, width, height, ..
+ } = rect;
+ let mut messages = vec![];
+
+ // iterate over the splits
+ let mut top = 0;
+ for (idx, split) in self.splits.iter().enumerate() {
+ let target_height = target_heights[idx];
+ let bottom = min(top + target_height, height);
+ let sub_rect = Rectangle {
+ top,
+ left,
+ width,
+ height: target_height,
+ };
+ let mut sub_message = adjust_event(event, sub_rect)
+ .map(|ev| split.as_ref().on_event(ev, sub_rect.adjust_origin()))
+ .unwrap_or_default();
+ messages.append(&mut sub_message);
+ top = bottom;
+ }
+
+ messages
+ }
+
+ fn on_event_mut(&mut self, event: Event, rect: Rectangle) -> Vec<Message> {
+ // should collect events from every children
+ let target_heights = self.retrieve_split_info(rect.height);
+ let Rectangle {
+ left, width, height, ..
+ } = rect;
+ let mut messages = vec![];
+
+ // iterate over the splits
+ let mut top = 0;
+ for (idx, split) in self.splits.iter_mut().enumerate() {
+ let target_height = target_heights[idx];
+ let bottom = min(top + target_height, height);
+ let sub_rect = Rectangle {
+ top,
+ left,
+ width,
+ height: target_height,
+ };
+ let mut sub_message = adjust_event(event, sub_rect)
+ .map(|ev| split.as_mut().on_event_mut(ev, sub_rect.adjust_origin()))
+ .unwrap_or_default();
+ messages.append(&mut sub_message);
+ top = bottom;
+ }
+
+ messages
+ }
+}
+
+impl<Message> Split<Message> for VSplit<'_, Message> {
+ fn get_basis(&self) -> Size {
+ self.basis
+ }
+
+ fn get_grow(&self) -> usize {
+ self.grow
+ }
+
+ fn get_shrink(&self) -> usize {
+ self.shrink
+ }
+}
+
+#[cfg(test)]
+#[allow(dead_code)]
+mod test {
+ use super::*;
+ use crate::Result;
+ use crate::cell::Cell;
+ use crate::key::Key;
+ use crate::key::Key::*;
+ use crate::key::MouseButton;
+ use std::sync::Mutex;
+
+ struct TestCanvas {
+ pub width: usize,
+ pub height: usize,
+ }
+
+ impl Canvas for TestCanvas {
+ fn size(&self) -> Result<(usize, usize)> {
+ Ok((self.width, self.height))
+ }
+
+ fn clear(&mut self) -> Result<()> {
+ unimplemented!()
+ }
+
+ fn put_cell(&mut self, _row: usize, _col: usize, _cell: Cell) -> Result<usize> {
+ unimplemented!()
+ }
+
+ fn set_cursor(&mut self, _row: usize, _col: usize) -> Result<()> {
+ unimplemented!()
+ }
+
+ fn show_cursor(&mut self, _show: bool) -> Result<()> {
+ unimplemented!()
+ }
+ }
+
+ struct WSplit<'a> {
+ pub basis: Size,
+ pub grow: usize,
+ pub shrink: usize,
+ pub draw: &'a dyn Draw,
+ }
+
+ impl<'a> WSplit<'a> {
+ pub fn new(draw: &'a dyn Draw) -> Self {
+ Self {
+ basis: Size::Default,
+ grow: 1,
+ shrink: 1,
+ draw,
+ }
+ }
+
+ pub fn basis(mut self, basis: impl Into<Size>) -> Self {
+ self.basis = basis.into();
+ self
+ }
+
+ pub fn grow(mut self, grow: usize) -> Self {
+ self.grow = grow;
+ self
+ }
+
+ pub fn shrink(mut self, shrink: usize) -> Self {
+ self.shrink = shrink;
+ self
+ }
+ }
+
+ impl Split for WSplit<'_> {
+ fn get_basis(&self) -> Size {
+ self.basis
+ }
+
+ fn get_grow(&self) -> usize {
+ self.grow
+ }
+
+ fn get_shrink(&self) -> usize {
+ self.shrink
+ }
+ }
+
+ impl Draw for WSplit<'_> {
+ fn draw(&self, canvas: &mut dyn Canvas) -> DrawResult<()> {
+ self.draw.draw(canvas)
+ }
+ }
+
+ impl Widget for WSplit<'_> {}
+
+ #[derive(Default)]
+ struct SingleWindow {
+ pub width: usize,
+ pub height: usize,
+ }
+
+ impl Draw for SingleWindow {
+ fn draw(&self, canvas: &mut dyn Canvas) -> DrawResult<()> {
+ let (width, height) = canvas.size().unwrap();
+ assert_eq!(self.width, width);
+ assert_eq!(self.height, height);
+ Ok(())
+ }
+ }
+
+ #[test]
+ fn splits_should_create_on_empty_items() {
+ let mut canvas = TestCanvas { width: 80, height: 60 };
+ let hsplit = HSplit::<()>::default();
+ let vsplit = VSplit::<()>::default();
+ let _ = hsplit.draw(&mut canvas);
+ let _ = vsplit.draw(&mut canvas);
+ }
+
+ #[test]
+ fn single_splits_should_take_over_all_spaces() {
+ let width = 80;
+ let height = 60;
+ let mut canvas = TestCanvas { width, height };
+ let window = SingleWindow { width, height };
+ let hsplit = HSplit::default().split(WSplit::new(&window));
+ let vsplit = VSplit::default().split(WSplit::new(&window));
+ let _ = hsplit.draw(&mut canvas);
+ let _ = vsplit.draw(&mut canvas);
+ }
+
+ #[test]
+ fn two_splits_should_take_50_percent() {
+ let width = 80;
+ let height = 60;
+ let mut canvas = TestCanvas { width, height };
+
+ let h_window = SingleWindow {
+ width: width / 2,
+ height,
+ };
+ let v_window = SingleWindow {
+ width,
+ height: height / 2,
+ };
+
+ let hsplit = HSplit::default()
+ .split(WSplit::new(&h_window))
+ .split(WSplit::new(&h_window));
+ let vsplit = VSplit::default()
+ .split(WSplit::new(&v_window))
+ .split(WSplit::new(&v_window));
+
+ let _ = hsplit.draw(&mut canvas);
+ let _ = vsplit.draw(&mut canvas);
+ }
+
+ #[test]
+ fn exceeded_should_be_ignored() {
+ // |<-- screen width: 80 -->|
+ // |<-- 60 -->|<-- 60 -->|
+ // |<-- 60 -->|<-- | (will be cut)
+
+ let width = 80;
+ let height = 80;
+ let mut canvas = TestCanvas { width, height };
+
+ let h_first = SingleWindow { width: 60, height };
+ let h_second = SingleWindow { width: 20, height };
+ let h_third = SingleWindow { width: 0, height };
+
+ let hsplit = HSplit::default()
+ .split(WSplit::new(&h_first).basis(60).shrink(0))
+ .split(WSplit::new(&h_second).basis(60).shrink(0))
+ .split(WSplit::new(&h_third).basis(60).shrink(0));
+
+ let _ = hsplit.draw(&mut canvas);
+
+ let v_first = SingleWindow { width, height: 60 };
+ let v_second = SingleWindow { width, height: 20 };
+ let v_third = SingleWindow { width, height: 0 };
+
+ let vsplit = VSplit::default()
+ .split(WSplit::new(&v_first).basis(60).shrink(0))
+ .split(WSplit::new(&v_second).basis(60).shrink(0))
+ .split(WSplit::new(&v_third).basis(60).shrink(0));
+
+ let _ = vsplit.draw(&mut canvas);
+ }
+
+ #[test]
+ fn grow() {
+ // |<-- screen width: 80 -->|
+ // 1. 10 (with grow: 1) => 30
+ // 2. 10 (with grow: 2) => 50
+
+ let width = 80;
+ let height = 80;
+ let mut canvas = TestCanvas { width, height };
+
+ let h_first = SingleWindow { width: 30, height };
+ let h_second = SingleWindow { width: 50, height };
+
+ let hsplit = HSplit::default()
+ .split(WSplit::new(&h_first).basis(10).grow(1))
+ .split(WSplit::new(&h_second).basis(10).grow(2));
+
+ let _ = hsplit.draw(&mut canvas);
+
+ let v_first = SingleWindow { width, height: 30 };
+ let v_second = SingleWindow { width, height: 50 };
+
+ let vsplit = VSplit::default()
+ .split(WSplit::new(&v_first).basis(10).grow(1))
+ .split(WSplit::new(&v_second).basis(10).grow(2));
+
+ let _ = vsplit.draw(&mut canvas);
+ }
+
+ #[test]
+ fn shrink() {
+ // |<-- screen width: 80 -->|
+ // 1. 70 (with shrink: 1) => 30
+ // 2. 70 (with shrink: 2) => 50
+
+ let width = 80;
+ let height = 80;
+ let mut canvas = TestCanvas { width, height };
+
+ let h_first = SingleWindow { width: 50, height };
+ let h_second = SingleWindow { width: 30, height };
+
+ let hsplit = HSplit::default()
+ .split(WSplit::new(&h_first).basis(70).shrink(1))
+ .split(WSplit::new(&h_second).basis(70).shrink(2));
+
+ let _ = hsplit.draw(&mut canvas);
+
+ let v_first = SingleWindow { width, height: 50 };
+ let v_second = SingleWindow { width, height: 30 };
+
+ let vsplit = VSplit::default()
+ .split(WSplit::new(&v_first).basis(70).shrink(1))
+ .split(WSplit::new(&v_second).basis(70).shrink(2));
+
+ let _ = vsplit.draw(&mut canvas);
+ }
+
+ struct WinHint {
+ pub width_hint: Option<usize>,
+ pub height_hint: Option<usize>,
+ }
+
+ impl Draw for WinHint {
+ fn draw(&self, _canvas: &mut dyn Canvas) -> DrawResult<()> {
+ unimplemented!()
+ }
+ }
+
+ impl Widget for WinHint {
+ fn size_hint(&self) -> (Option<usize>, Option<usize>) {
+ (self.width_hint, self.height_hint)
+ }
+ }
+
+ impl Split for WinHint {
+ fn get_basis(&self) -> Size {
+ Size::Default
+ }
+ fn get_grow(&self) -> usize {
+ 0
+ }
+ fn get_shrink(&self) -> usize {
+ 0
+ }
+ }
+
+ #[test]
+ fn size_hint_of_hsplit() {
+ let hint_none = WinHint {
+ width_hint: None,
+ height_hint: None,
+ };
+ let hint_width_1 = WinHint {
+ width_hint: Some(1),
+ height_hint: None,
+ };
+ let hint_width_2 = WinHint {
+ width_hint: Some(2),
+ height_hint: None,
+ };
+ let hint_height_1 = WinHint {
+ width_hint: None,
+ height_hint: Some(1),
+ };
+ let hint_height_2 = WinHint {
+ width_hint: None,
+ height_hint: Some(2),
+ };
+
+ // sum(width), max(height)
+ let split = HSplit::default()
+ .split(&hint_none)
+ .split(&hint_width_1)
+ .split(&hint_width_2)
+ .split(&hint_height_1)
+ .split(&hint_height_2);
+
+ assert_eq!((Some(3), Some(2)), split.size_hint());
+
+ // None, max(height)
+ let split = HSplit::default()
+ .split(&hint_none)
+ .split(&hint_height_1)
+ .split(&hint_height_2);
+
+ assert_eq!((None, Some(2)), split.size_hint());
+
+ // sum(width), None
+ let split = HSplit::default()
+ .split(&hint_none)
+ .split(&hint_width_1)
+ .split(&hint_width_2);
+ assert_eq!((Some(3), None), split.size_hint());
+
+ // None
+ let split = HSplit::default().split(&hint_none).split(&hint_none);
+ assert_eq!((None, None), split.size_hint());
+ }
+
+ #[test]
+ fn size_hint_of_vsplit() {
+ let hint_none = WinHint {
+ width_hint: None,
+ height_hint: None,
+ };
+ let hint_width_1 = WinHint {
+ width_hint: Some(1),
+ height_hint: None,
+ };
+ let hint_width_2 = WinHint {
+ width_hint: Some(2),
+ height_hint: None,
+ };
+ let hint_height_1 = WinHint {
+ width_hint: None,
+ height_hint: Some(1),
+ };
+ let hint_height_2 = WinHint {
+ width_hint: None,
+ height_hint: Some(2),
+ };
+
+ // max(width), sum(height)
+ let split = VSplit::default()
+ .split(&hint_none)
+ .split(&hint_width_1)
+ .split(&hint_width_2)
+ .split(&hint_height_1)
+ .split(&hint_height_2);
+
+ assert_eq!((Some(2), Some(3)), split.size_hint());
+
+ // None, sum(height)
+ let split = VSplit::default()
+ .split(&hint_none)
+ .split(&hint_height_1)
+ .split(&hint_height_2);
+
+ assert_eq!((None, Some(3)), split.size_hint());
+
+ // max(width), None
+ let split = VSplit::default()
+ .split(&hint_none)
+ .split(&hint_width_1)
+ .split(&hint_width_2);
+ assert_eq!((Some(2), None), split.size_hint());
+
+ // None
+ let split = VSplit::default().split(&hint_none).split(&hint_none);
+ assert_eq!((None, None), split.size_hint());
+ }
+
+ #[derive(Copy, Clone, PartialOrd, PartialEq, Debug)]
+ enum Message {
+ Window(i32),
+ }
+
+ struct WindowWithId {
+ id: i32,
+ }
+
+ impl WindowWithId {
+ pub fn new(id: i32) -> Self {
+ Self { id }
+ }
+ }
+
+ impl Draw for WindowWithId {
+ fn draw(&self, _canvas: &mut dyn Canvas) -> DrawResult<()> {
+ unimplemented!()
+ }
+ }
+
+ impl Widget<Message> for WindowWithId {
+ fn on_event(&self, _event: Event, _rect: Rectangle) -> Vec<Message> {
+ vec![Message::Window(self.id)]
+ }
+ fn on_event_mut(&mut self, _event: Event, _rect: Rectangle) -> Vec<Message> {
+ vec![Message::Window(self.id)]
+ }
+ }
+
+ impl Split<Message> for WindowWithId {
+ fn get_basis(&self) -> Size {
+ Size::Default
+ }
+ fn get_grow(&self) -> usize {
+ 1
+ }
+ fn get_shrink(&self) -> usize {
+ 1
+ }
+ }
+
+ #[test]
+ fn message_should_be_dispatched_correctly() {
+ let width = 80;
+ let height = 60;
+ let rect = Rectangle {
+ top: 0,
+ left: 0,
+ width,
+ height,
+ };
+
+ let win1 = WindowWithId::new(1);
+ let win2 = WindowWithId::new(2);
+ let win3 = WindowWithId::new(3);
+ let win4 = WindowWithId::new(4);
+
+ let ev_left_1 = Event::Key(Key::MouseHold(0, 0));
+ let ev_left_2 = Event::Key(Key::MouseHold(0, 39));
+ let ev_right_1 = Event::Key(Key::MouseHold(20, 40));
+ let ev_right_2 = Event::Key(Key::MouseHold(20, 41));
+ let ev_right_3 = Event::Key(Key::MouseHold(59, 79));
+ let ev_out_of_bound = Event::Key(Key::MouseHold(60, 80));
+
+ let hsplit = HSplit::default().split(&win1).split(&win2);
+ let msg = hsplit.on_event(ev_left_1, rect);
+ assert!(!msg.is_empty());
+ assert_eq!(Message::Window(1), msg[0]);
+ let msg = hsplit.on_event(ev_left_2, rect);
+ assert!(!msg.is_empty());
+ assert_eq!(Message::Window(1), msg[0]);
+ let msg = hsplit.on_event(ev_right_1, rect);
+ assert!(!msg.is_empty());
+ assert_eq!(Message::Window(2), msg[0]);
+ let msg = hsplit.on_event(ev_right_2, rect);
+ assert!(!msg.is_empty());
+ assert_eq!(Message::Window(2), msg[0]);
+ let msg = hsplit.on_event(ev_right_3, rect);
+ assert!(!msg.is_empty());
+ assert_eq!(Message::Window(2), msg[0]);
+ let msg = hsplit.on_event(ev_out_of_bound, rect);
+ assert!(msg.is_empty());
+
+ let ev_top_1 = Event::Key(Key::MouseHold(0, 0));
+ let ev_top_2 = Event::Key(Key::MouseHold(29, 39));
+ let ev_bottom_1 = Event::Key(Key::MouseHold(30, 40));
+ let ev_bottom_2 = Event::Key(Key::MouseHold(31, 41));
+ let ev_bottom_3 = Event::Key(Key::MouseHold(59, 79));
+ let ev_out_of_bound = Event::Key(Key::MouseHold(60, 80));
+
+ let vsplit = VSplit::default().split(&win1).split(&win2);
+
+ let msg = vsplit.on_event(ev_top_1, rect);
+ assert!(!msg.is_empty());
+ assert_eq!(Message::Window(1), msg[0]);
+ let msg = vsplit.on_event(ev_top_2, rect);
+ assert!(!msg.is_empty());
+ assert_eq!(Message::Window(1), msg[0]);
+ let msg = vsplit.on_event(ev_bottom_1, rect);
+ assert!(!msg.is_empty());
+ assert_eq!(Message::Window(2), msg[0]);
+ let msg = vsplit.on_event(ev_bottom_2, rect);
+ assert!(!msg.is_empty());
+ assert_eq!(Message::Window(2), msg[0]);
+ let msg = vsplit.on_event(ev_bottom_3, rect);
+ assert!(!msg.is_empty());
+ assert_eq!(Message::Window(2), msg[0]);
+ let msg = vsplit.on_event(ev_out_of_bound, rect);
+ assert!(msg.is_empty());
+
+ // 1 | 2
+ // --|--
+ // 3 | 4
+ let nested = HSplit::default()
+ .split(VSplit::default().split(&win1).split(&win3))
+ .split(VSplit::default().split(&win2).split(&win4));
+ let row_col_event = [
+ ((0, 0), Message::Window(1)),
+ ((0, 39), Message::Window(1)),
+ ((29, 0), Message::Window(1)),
+ ((29, 39), Message::Window(1)),
+ ((0, 40), Message::Window(2)),
+ ((0, 79), Message::Window(2)),
+ ((29, 40), Message::Window(2)),
+ ((29, 79), Message::Window(2)),
+ ((30, 0), Message::Window(3)),
+ ((30, 39), Message::Window(3)),
+ ((59, 0), Message::Window(3)),
+ ((59, 39), Message::Window(3)),
+ ((30, 40), Message::Window(4)),
+ ((30, 79), Message::Window(4)),
+ ((59, 40), Message::Window(4)),
+ ((59, 79), Message::Window(4)),
+ ];
+
+ for &((row, col), event) in row_col_event.iter() {
+ let ev = Event::Key(MousePress(MouseButton::Left, row, col));
+ let msg = nested.on_event(ev, rect);
+ assert_eq!(msg[0], event);
+ let ev = Event::Key(MouseRelease(row, col));
+ let msg = nested.on_event(ev, rect);
+ assert_eq!(msg[0], event);
+ let ev = Event::Key(MouseHold(row, col));
+ let msg = nested.on_event(ev, rect);
+ assert_eq!(msg[0], event);
+ let ev = Event::Key(SingleClick(MouseButton::Left, row, col));
+ let msg = nested.on_event(ev, rect);
+ assert_eq!(msg[0], event);
+ let ev = Event::Key(DoubleClick(MouseButton::Left, row, col));
+ let msg = nested.on_event(ev, rect);
+ assert_eq!(msg[0], event);
+ let ev = Event::Key(Key::WheelUp(row, col, 1));
+ let msg = nested.on_event(ev, rect);
+ assert_eq!(msg[0], event);
+ let ev = Event::Key(Key::WheelDown(row, col, 1));
+ let msg = nested.on_event(ev, rect);
+ assert_eq!(msg[0], event);
+ }
+ }
+
+ #[test]
+ fn message_should_be_dispatched_correctly_mut() {
+ let width = 80;
+ let height = 60;
+ let rect = Rectangle {
+ top: 0,
+ left: 0,
+ width,
+ height,
+ };
+
+ let mut win1 = WindowWithId::new(1);
+ let mut win2 = WindowWithId::new(2);
+ let mut win3 = WindowWithId::new(3);
+ let mut win4 = WindowWithId::new(4);
+
+ let ev_left_1 = Event::Key(Key::MouseHold(0, 0));
+ let ev_left_2 = Event::Key(Key::MouseHold(0, 39));
+ let ev_right_1 = Event::Key(Key::MouseHold(20, 40));
+ let ev_right_2 = Event::Key(Key::MouseHold(20, 41));
+ let ev_right_3 = Event::Key(Key::MouseHold(59, 79));
+ let ev_out_of_bound = Event::Key(Key::MouseHold(60, 80));
+
+ {
+ let mut hsplit = HSplit::default().split(&mut win1).split(&mut win2);
+ let msg = hsplit.on_event_mut(ev_left_1, rect);
+ assert!(!msg.is_empty());
+ assert_eq!(Message::Window(1), msg[0]);
+ let msg = hsplit.on_event_mut(ev_left_2, rect);
+ assert!(!msg.is_empty());
+ assert_eq!(Message::Window(1), msg[0]);
+ let msg = hsplit.on_event_mut(ev_right_1, rect);
+ assert!(!msg.is_empty());
+ assert_eq!(Message::Window(2), msg[0]);
+ let msg = hsplit.on_event_mut(ev_right_2, rect);
+ assert!(!msg.is_empty());
+ assert_eq!(Message::Window(2), msg[0]);
+ let msg = hsplit.on_event_mut(ev_right_3, rect);
+ assert!(!msg.is_empty());
+ assert_eq!(Message::Window(2), msg[0]);
+ let msg = hsplit.on_event_mut(ev_out_of_bound, rect);
+ assert!(msg.is_empty());
+ }
+
+ let ev_top_1 = Event::Key(Key::MouseHold(0, 0));
+ let ev_top_2 = Event::Key(Key::MouseHold(29, 39));
+ let ev_bottom_1 = Event::Key(Key::MouseHold(30, 40));
+ let ev_bottom_2 = Event::Key(Key::MouseHold(31, 41));
+ let ev_bottom_3 = Event::Key(Key::MouseHold(59, 79));
+ let ev_out_of_bound = Event::Key(Key::MouseHold(60, 80));
+
+ {
+ let mut vsplit = VSplit::default().split(&mut win1).split(&mut win2);
+
+ let msg = vsplit.on_event_mut(ev_top_1, rect);
+ assert!(!msg.is_empty());
+ assert_eq!(Message::Window(1), msg[0]);
+ let msg = vsplit.on_event_mut(ev_top_2, rect);
+ assert!(!msg.is_empty());
+ assert_eq!(Message::Window(1), msg[0]);
+ let msg = vsplit.on_event_mut(ev_bottom_1, rect);
+ assert!(!msg.is_empty());
+ assert_eq!(Message::Window(2), msg[0]);
+ let msg = vsplit.on_event_mut(ev_bottom_2, rect);
+ assert!(!msg.is_empty());
+ assert_eq!(Message::Window(2), msg[0]);
+ let msg = vsplit.on_event_mut(ev_bottom_3, rect);
+ assert!(!msg.is_empty());
+ assert_eq!(Message::Window(2), msg[0]);
+ let msg = vsplit.on_event_mut(ev_out_of_bound, rect);
+ assert!(msg.is_empty());
+ }
+
+ // 1 | 2
+ // --|--
+ // 3 | 4
+ {
+ let mut nested = HSplit::default()
+ .split(VSplit::default().split(&mut win1).split(&mut win3))
+ .split(VSplit::default().split(&mut win2).split(&mut win4));
+ let row_col_event = [
+ ((0, 0), Message::Window(1)),
+ ((0, 39), Message::Window(1)),
+ ((29, 0), Message::Window(1)),
+ ((29, 39), Message::Window(1)),
+ ((0, 40), Message::Window(2)),
+ ((0, 79), Message::Window(2)),
+ ((29, 40), Message::Window(2)),
+ ((29, 79), Message::Window(2)),
+ ((30, 0), Message::Window(3)),
+ ((30, 39), Message::Window(3)),
+ ((59, 0), Message::Window(3)),
+ ((59, 39), Message::Window(3)),
+ ((30, 40), Message::Window(4)),
+ ((30, 79), Message::Window(4)),
+ ((59, 40), Message::Window(4)),
+ ((59, 79), Message::Window(4)),
+ ];
+
+ for &((row, col), event) in row_col_event.iter() {
+ let ev = Event::Key(MousePress(MouseButton::Left, row, col));
+ let msg = nested.on_event_mut(ev, rect);
+ assert_eq!(msg[0], event);
+ let ev = Event::Key(MouseRelease(row, col));
+ let msg = nested.on_event_mut(ev, rect);
+ assert_eq!(msg[0], event);
+ let ev = Event::Key(MouseHold(row, col));
+ let msg = nested.on_event_mut(ev, rect);
+ assert_eq!(msg[0], event);
+ let ev = Event::Key(SingleClick(MouseButton::Left, row, col));
+ let msg = nested.on_event_mut(ev, rect);
+ assert_eq!(msg[0], event);
+ let ev = Event::Key(DoubleClick(MouseButton::Left, row, col));
+ let msg = nested.on_event_mut(ev, rect);
+ assert_eq!(msg[0], event);
+ let ev = Event::Key(Key::WheelUp(row, col, 1));
+ let msg = nested.on_event_mut(ev, rect);
+ assert_eq!(msg[0], event);
+ let ev = Event::Key(Key::WheelDown(row, col, 1));
+ let msg = nested.on_event_mut(ev, rect);
+ assert_eq!(msg[0], event);
+ }
+ }
+ }
+
+ #[derive(PartialEq, Debug)]
+ enum Called {
+ No,
+ Mut,
+ Immut,
+ }
+
+ struct Drawn {
+ called: Mutex<Called>,
+ }
+
+ impl Draw for Drawn {
+ fn draw(&self, _canvas: &mut dyn Canvas) -> DrawResult<()> {
+ *self.called.lock().unwrap() = Called::Immut;
+ Ok(())
+ }
+ fn draw_mut(&mut self, _canvas: &mut dyn Canvas) -> DrawResult<()> {
+ *self.called.lock().unwrap() = Called::Mut;
+ Ok(())
+ }
+ }
+
+ impl Widget for Drawn {}
+
+ impl Split for Drawn {
+ fn get_basis(&self) -> Size {
+ Size::Default
+ }
+
+ fn get_grow(&self) -> usize {
+ 1
+ }
+
+ fn get_shrink(&self) -> usize {
+ 1
+ }
+ }
+
+ #[test]
+ fn mutable_widget() {
+ let mut canvas = TestCanvas { width: 80, height: 80 };
+
+ let mut mutable = Drawn {
+ called: Mutex::new(Called::No),
+ };
+ {
+ let mut hsplit = HSplit::default().split(&mut mutable);
+ hsplit.draw_mut(&mut canvas).unwrap();
+ }
+ assert_eq!(Called::Mut, *mutable.called.lock().unwrap());
+
+ let mut mutable = Drawn {
+ called: Mutex::new(Called::No),
+ };
+ {
+ let mut vsplit = VSplit::default().split(&mut mutable);
+ vsplit.draw_mut(&mut canvas).unwrap();
+ }
+ assert_eq!(Called::Mut, *mutable.called.lock().unwrap());
+
+ let immutable = Drawn {
+ called: Mutex::new(Called::No),
+ };
+ let hsplit = HSplit::default().split(&immutable);
+ hsplit.draw(&mut canvas).unwrap();
+ assert_eq!(Called::Immut, *immutable.called.lock().unwrap());
+ let immutable = Drawn {
+ called: Mutex::new(Called::No),
+ };
+ let vsplit = VSplit::default().split(&immutable);
+ vsplit.draw(&mut canvas).unwrap();
+ assert_eq!(Called::Immut, *immutable.called.lock().unwrap());
+ }
+}
diff --git a/vendor/skim-tuikit/src/widget/stack.rs b/vendor/skim-tuikit/src/widget/stack.rs
new file mode 100644
index 000000000..80fd30673
--- /dev/null
+++ b/vendor/skim-tuikit/src/widget/stack.rs
@@ -0,0 +1,222 @@
+use crate::canvas::Canvas;
+use crate::draw::{Draw, DrawResult};
+use crate::event::Event;
+use crate::widget::{Rectangle, Widget};
+
+/// A stack of widgets, will draw the including widgets back to front
+pub struct Stack<'a, Message = ()> {
+ inner: Vec<Box<dyn Widget<Message> + 'a>>,
+}
+
+impl<Message> Default for Stack<'_, Message> {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl<'a, Message> Stack<'a, Message> {
+ pub fn new() -> Self {
+ Self { inner: vec![] }
+ }
+
+ pub fn top(mut self, widget: impl Widget<Message> + 'a) -> Self {
+ self.inner.push(Box::new(widget));
+ self
+ }
+
+ pub fn bottom(mut self, widget: impl Widget<Message> + 'a) -> Self {
+ self.inner.insert(0, Box::new(widget));
+ self
+ }
+}
+
+impl<Message> Draw for Stack<'_, Message> {
+ fn draw(&self, canvas: &mut dyn Canvas) -> DrawResult<()> {
+ for widget in self.inner.iter() {
+ widget.draw(canvas)?
+ }
+
+ Ok(())
+ }
+ fn draw_mut(&mut self, canvas: &mut dyn Canvas) -> DrawResult<()> {
+ for widget in self.inner.iter_mut() {
+ widget.draw_mut(canvas)?
+ }
+
+ Ok(())
+ }
+}
+
+impl<Message> Widget<Message> for Stack<'_, Message> {
+ fn size_hint(&self) -> (Option<usize>, Option<usize>) {
+ // max of the inner widgets
+ let width = self
+ .inner
+ .iter()
+ .map(|widget| widget.size_hint().0)
+ .max()
+ .unwrap_or(None);
+ let height = self
+ .inner
+ .iter()
+ .map(|widget| widget.size_hint().1)
+ .max()
+ .unwrap_or(None);
+ (width, height)
+ }
+
+ fn on_event(&self, event: Event, rect: Rectangle) -> Vec<Message> {
+ // like javascript's capture, from top to bottom
+ for widget in self.inner.iter().rev() {
+ let message = widget.on_event(event, rect);
+ if !message.is_empty() {
+ return message;
+ }
+ }
+ vec![]
+ }
+
+ fn on_event_mut(&mut self, event: Event, rect: Rectangle) -> Vec<Message> {
+ // like javascript's capture, from top to bottom
+ for widget in self.inner.iter_mut().rev() {
+ let message = widget.on_event_mut(event, rect);
+ if !message.is_empty() {
+ return message;
+ }
+ }
+ vec![]
+ }
+}
+
+#[cfg(test)]
+#[allow(dead_code)]
+mod test {
+ use super::*;
+ use crate::cell::Cell;
+ use std::sync::Mutex;
+
+ struct WinHint {
+ pub width_hint: Option<usize>,
+ pub height_hint: Option<usize>,
+ }
+
+ impl Draw for WinHint {
+ fn draw(&self, _canvas: &mut dyn Canvas) -> DrawResult<()> {
+ unimplemented!()
+ }
+ }
+
+ impl Widget for WinHint {
+ fn size_hint(&self) -> (Option<usize>, Option<usize>) {
+ (self.width_hint, self.height_hint)
+ }
+ }
+
+ #[test]
+ fn size_hint() {
+ let stack = Stack::new().top(WinHint {
+ width_hint: None,
+ height_hint: None,
+ });
+ assert_eq!((None, None), stack.size_hint());
+
+ let stack = Stack::new().top(WinHint {
+ width_hint: Some(1),
+ height_hint: Some(1),
+ });
+ assert_eq!((Some(1), Some(1)), stack.size_hint());
+
+ let stack = Stack::new()
+ .top(WinHint {
+ width_hint: Some(1),
+ height_hint: Some(2),
+ })
+ .top(WinHint {
+ width_hint: Some(2),
+ height_hint: Some(1),
+ });
+ assert_eq!((Some(2), Some(2)), stack.size_hint());
+
+ let stack = Stack::new()
+ .top(WinHint {
+ width_hint: None,
+ height_hint: None,
+ })
+ .top(WinHint {
+ width_hint: Some(2),
+ height_hint: Some(1),
+ });
+ assert_eq!((Some(2), Some(1)), stack.size_hint());
+ }
+
+ #[derive(PartialEq, Debug)]
+ enum Called {
+ No,
+ Mut,
+ Immut,
+ }
+
+ struct Drawn {
+ called: Mutex<Called>,
+ }
+
+ impl Draw for Drawn {
+ fn draw(&self, _canvas: &mut dyn Canvas) -> DrawResult<()> {
+ *self.called.lock().unwrap() = Called::Immut;
+ Ok(())
+ }
+ fn draw_mut(&mut self, _canvas: &mut dyn Canvas) -> DrawResult<()> {
+ *self.called.lock().unwrap() = Called::Mut;
+ Ok(())
+ }
+ }
+
+ impl Widget for Drawn {}
+
+ #[derive(Default)]
+ struct TestCanvas {}
+
+ #[allow(unused_variables)]
+ impl Canvas for TestCanvas {
+ fn size(&self) -> crate::Result<(usize, usize)> {
+ Ok((100, 100))
+ }
+
+ fn clear(&mut self) -> crate::Result<()> {
+ unimplemented!()
+ }
+
+ fn put_cell(&mut self, row: usize, col: usize, cell: Cell) -> crate::Result<usize> {
+ Ok(1)
+ }
+
+ fn set_cursor(&mut self, row: usize, col: usize) -> crate::Result<()> {
+ unimplemented!()
+ }
+
+ fn show_cursor(&mut self, show: bool) -> crate::Result<()> {
+ unimplemented!()
+ }
+ }
+
+ #[test]
+ fn mutable_widget() {
+ let mut canvas = TestCanvas::default();
+
+ let mut mutable = Drawn {
+ called: Mutex::new(Called::No),
+ };
+ {
+ let mut stack = Stack::new().top(&mut mutable);
+ stack.draw_mut(&mut canvas).unwrap();
+ }
+ assert_eq!(Called::Mut, *mutable.called.lock().unwrap());
+
+ let immutable = Drawn {
+ called: Mutex::new(Called::No),
+ };
+ let stack = Stack::new().top(&immutable);
+ stack.draw(&mut canvas).unwrap();
+ assert_eq!(Called::Immut, *immutable.called.lock().unwrap());
+ }
+}
diff --git a/vendor/skim-tuikit/src/widget/util.rs b/vendor/skim-tuikit/src/widget/util.rs
new file mode 100644
index 000000000..fcb390776
--- /dev/null
+++ b/vendor/skim-tuikit/src/widget/util.rs
@@ -0,0 +1,65 @@
+use crate::event::Event;
+use crate::key::Key;
+use crate::widget::Rectangle;
+
+pub fn adjust_event(event: Event, inner_rect: Rectangle) -> Option<Event> {
+ match event {
+ Event::Key(Key::MousePress(button, row, col)) => {
+ if inner_rect.contains(row as usize, col as usize) {
+ let (row, col) = inner_rect.relative_to_origin(row as usize, col as usize);
+ Some(Event::Key(Key::MousePress(button, row as u16, col as u16)))
+ } else {
+ None
+ }
+ }
+ Event::Key(Key::MouseRelease(row, col)) => {
+ if inner_rect.contains(row as usize, col as usize) {
+ let (row, col) = inner_rect.relative_to_origin(row as usize, col as usize);
+ Some(Event::Key(Key::MouseRelease(row as u16, col as u16)))
+ } else {
+ None
+ }
+ }
+ Event::Key(Key::MouseHold(row, col)) => {
+ if inner_rect.contains(row as usize, col as usize) {
+ let (row, col) = inner_rect.relative_to_origin(row as usize, col as usize);
+ Some(Event::Key(Key::MouseHold(row as u16, col as u16)))
+ } else {
+ None
+ }
+ }
+ Event::Key(Key::SingleClick(button, row, col)) => {
+ if inner_rect.contains(row as usize, col as usize) {
+ let (row, col) = inner_rect.relative_to_origin(row as usize, col as usize);
+ Some(Event::Key(Key::SingleClick(button, row as u16, col as u16)))
+ } else {
+ None
+ }
+ }
+ Event::Key(Key::DoubleClick(button, row, col)) => {
+ if inner_rect.contains(row as usize, col as usize) {
+ let (row, col) = inner_rect.relative_to_origin(row as usize, col as usize);
+ Some(Event::Key(Key::DoubleClick(button, row as u16, col as u16)))
+ } else {
+ None
+ }
+ }
+ Event::Key(Key::WheelDown(row, col, count)) => {
+ if inner_rect.contains(row as usize, col as usize) {
+ let (row, col) = inner_rect.relative_to_origin(row as usize, col as usize);
+ Some(Event::Key(Key::WheelDown(row as u16, col as u16, count)))
+ } else {
+ None
+ }
+ }
+ Event::Key(Key::WheelUp(row, col, count)) => {
+ if inner_rect.contains(row as usize, col as usize) {
+ let (row, col) = inner_rect.relative_to_origin(row as usize, col as usize);
+ Some(Event::Key(Key::WheelUp(row as u16, col as u16, count)))
+ } else {
+ None
+ }
+ }
+ ev => Some(ev),
+ }
+}
diff --git a/vendor/skim-tuikit/src/widget/win.rs b/vendor/skim-tuikit/src/widget/win.rs
new file mode 100644
index 000000000..f49009ac9
--- /dev/null
+++ b/vendor/skim-tuikit/src/widget/win.rs
@@ -0,0 +1,736 @@
+use super::Size;
+use super::split::Split;
+use super::util::adjust_event;
+use super::{Rectangle, Widget};
+use crate::attr::Attr;
+use crate::canvas::{BoundedCanvas, Canvas};
+use crate::cell::Cell;
+use crate::draw::{Draw, DrawResult};
+use crate::event::Event;
+use crate::widget::align::{AlignSelf, HorizontalAlign};
+use crate::{ok_or_return, some_or_return};
+use std::cmp::max;
+use unicode_width::UnicodeWidthStr;
+
+type FnDrawHeader = dyn Fn(&mut dyn Canvas) -> DrawResult<()>;
+
+/// A Win is like a div in HTML, it has its margin/padding, and border
+pub struct Win<'a, Message = ()> {
+ margin_top: Size,
+ margin_right: Size,
+ margin_bottom: Size,
+ margin_left: Size,
+
+ padding_top: Size,
+ padding_right: Size,
+ padding_bottom: Size,
+ padding_left: Size,
+
+ border_top: bool,
+ border_right: bool,
+ border_bottom: bool,
+ border_left: bool,
+
+ border_top_attr: Attr,
+ border_right_attr: Attr,
+ border_bottom_attr: Attr,
+ border_left_attr: Attr,
+
+ fn_draw_header: Option<Box<FnDrawHeader>>,
+ title: Option<String>,
+ title_attr: Attr,
+ right_prompt: Option<String>,
+ right_prompt_attr: Attr,
+ title_align: HorizontalAlign,
+ title_on_top: bool,
+
+ basis: Size,
+ grow: usize,
+ shrink: usize,
+
+ inner: Box<dyn Widget<Message> + 'a>,
+}
+
+// Builder
+impl<'a, Message> Win<'a, Message> {
+ pub fn new(widget: impl Widget<Message> + 'a) -> Self {
+ Self {
+ margin_top: Default::default(),
+ margin_right: Default::default(),
+ margin_bottom: Default::default(),
+ margin_left: Default::default(),
+ padding_top: Default::default(),
+ padding_right: Default::default(),
+ padding_bottom: Default::default(),
+ padding_left: Default::default(),
+ border_top: false,
+ border_right: false,
+ border_bottom: false,
+ border_left: false,
+ border_top_attr: Default::default(),
+ border_right_attr: Default::default(),
+ border_bottom_attr: Default::default(),
+ border_left_attr: Default::default(),
+ fn_draw_header: None,
+ title: None,
+ title_attr: Default::default(),
+ right_prompt: None,
+ right_prompt_attr: Default::default(),
+ title_align: HorizontalAlign::Left,
+ title_on_top: true,
+ basis: Size::Default,
+ grow: 1,
+ shrink: 1,
+ inner: Box::new(widget),
+ }
+ }
+
+ pub fn margin_top(mut self, margin_top: impl Into<Size>) -> Self {
+ self.margin_top = margin_top.into();
+ self
+ }
+
+ pub fn margin_right(mut self, margin_right: impl Into<Size>) -> Self {
+ self.margin_right = margin_right.into();
+ self
+ }
+
+ pub fn margin_bottom(mut self, margin_bottom: impl Into<Size>) -> Self {
+ self.margin_bottom = margin_bottom.into();
+ self
+ }
+
+ pub fn margin_left(mut self, margin_left: impl Into<Size>) -> Self {
+ self.margin_left = margin_left.into();
+ self
+ }
+
+ pub fn margin(mut self, margin: impl Into<Size>) -> Self {
+ let margin = margin.into();
+ self.margin_top = margin;
+ self.margin_right = margin;
+ self.margin_bottom = margin;
+ self.margin_left = margin;
+ self
+ }
+
+ pub fn padding_top(mut self, padding_top: impl Into<Size>) -> Self {
+ self.padding_top = padding_top.into();
+ self
+ }
+
+ pub fn padding_right(mut self, padding_right: impl Into<Size>) -> Self {
+ self.padding_right = padding_right.into();
+ self
+ }
+
+ pub fn padding_bottom(mut self, padding_bottom: impl Into<Size>) -> Self {
+ self.padding_bottom = padding_bottom.into();
+ self
+ }
+
+ pub fn padding_left(mut self, padding_left: impl Into<Size>) -> Self {
+ self.padding_left = padding_left.into();
+ self
+ }
+
+ pub fn padding(mut self, padding: impl Into<Size>) -> Self {
+ let padding = padding.into();
+ self.padding_top = padding;
+ self.padding_right = padding;
+ self.padding_bottom = padding;
+ self.padding_left = padding;
+ self
+ }
+
+ pub fn border_top(mut self, border_top: bool) -> Self {
+ self.border_top = border_top;
+ self
+ }
+
+ pub fn border_right(mut self, border_right: bool) -> Self {
+ self.border_right = border_right;
+ self
+ }
+
+ pub fn border_bottom(mut self, border_bottom: bool) -> Self {
+ self.border_bottom = border_bottom;
+ self
+ }
+
+ pub fn border_left(mut self, border_left: bool) -> Self {
+ self.border_left = border_left;
+ self
+ }
+
+ pub fn border(mut self, border: bool) -> Self {
+ self.border_top = border;
+ self.border_right = border;
+ self.border_bottom = border;
+ self.border_left = border;
+ self
+ }
+
+ pub fn border_top_attr(mut self, border_top_attr: impl Into<Attr>) -> Self {
+ self.border_top_attr = border_top_attr.into();
+ self
+ }
+
+ pub fn border_right_attr(mut self, border_right_attr: impl Into<Attr>) -> Self {
+ self.border_right_attr = border_right_attr.into();
+ self
+ }
+
+ pub fn border_bottom_attr(mut self, border_bottom_attr: impl Into<Attr>) -> Self {
+ self.border_bottom_attr = border_bottom_attr.into();
+ self
+ }
+
+ pub fn border_left_attr(mut self, border_left_attr: impl Into<Attr>) -> Self {
+ self.border_left_attr = border_left_attr.into();
+ self
+ }
+
+ pub fn border_attr(mut self, attr: impl Into<Attr>) -> Self {
+ let attr = attr.into();
+ self.border_top_attr = attr;
+ self.border_right_attr = attr;
+ self.border_bottom_attr = attr;
+ self.border_left_attr = attr;
+ self
+ }
+
+ pub fn fn_draw_header(mut self, fn_draw_header: Box<FnDrawHeader>) -> Self {
+ self.fn_draw_header = Some(fn_draw_header);
+ self
+ }
+
+ pub fn title(mut self, title: impl Into<String>) -> Self {
+ self.title = Some(title.into());
+ self
+ }
+
+ pub fn title_attr(mut self, title_attr: impl Into<Attr>) -> Self {
+ self.title_attr = title_attr.into();
+ self
+ }
+
+ pub fn right_prompt(mut self, right_prompt: impl Into<String>) -> Self {
+ self.right_prompt = Some(right_prompt.into());
+ self
+ }
+
+ pub fn right_prompt_attr(mut self, right_prompt_attr: impl Into<Attr>) -> Self {
+ self.right_prompt_attr = right_prompt_attr.into();
+ self
+ }
+
+ pub fn title_align(mut self, align: HorizontalAlign) -> Self {
+ self.title_align = align;
+ self
+ }
+
+ pub fn title_on_top(mut self, title_on_top: bool) -> Self {
+ self.title_on_top = title_on_top;
+ self
+ }
+
+ pub fn basis(mut self, basis: impl Into<Size>) -> Self {
+ self.basis = basis.into();
+ self
+ }
+
+ pub fn grow(mut self, grow: usize) -> Self {
+ self.grow = grow;
+ self
+ }
+
+ pub fn shrink(mut self, shrink: usize) -> Self {
+ self.shrink = shrink;
+ self
+ }
+}
+
+impl<'a, Message> Win<'a, Message> {
+ fn rect_reserve_margin(&self, rect: Rectangle) -> DrawResult<Rectangle> {
+ let Rectangle { width, height, .. } = rect;
+
+ let margin_top = self.margin_top.calc_fixed_size(height, 0);
+ let margin_right = self.margin_right.calc_fixed_size(width, 0);
+ let margin_bottom = self.margin_bottom.calc_fixed_size(height, 0);
+ let margin_left = self.margin_left.calc_fixed_size(width, 0);
+
+ if margin_top + margin_bottom >= height || margin_left + margin_right >= width {
+ return Err("margin takes too much screen".into());
+ }
+
+ let top = margin_top;
+ let left = margin_left;
+ let width = width - (margin_left + margin_right);
+ let height = height - (margin_top + margin_bottom);
+ Ok(Rectangle {
+ top,
+ left,
+ width,
+ height,
+ })
+ }
+
+ fn rect_header(&self, rect_reserve_margin: Rectangle) -> Rectangle {
+ let Rectangle {
+ top,
+ mut left,
+ width,
+ height,
+ } = rect_reserve_margin;
+
+ let new_top = if self.title_on_top {
+ top
+ } else {
+ max(top + height, 1) - 1
+ };
+
+ let height_needed = if self.title_on_top && self.border_bottom { 2 } else { 1 };
+ if height_needed > height {
+ // not enough space, don't draw at all
+ return Rectangle {
+ top: new_top,
+ left,
+ width,
+ height: 0,
+ };
+ }
+
+ let mut width_needed = 0;
+ if self.border_left {
+ width_needed += 1;
+ left += 1;
+ }
+ if self.border_right {
+ width_needed += 1;
+ }
+ if width_needed > width {
+ return Rectangle {
+ top: new_top,
+ left,
+ width: 0,
+ height,
+ };
+ }
+
+ Rectangle {
+ top: new_top,
+ left,
+ width: width - width_needed,
+ height: 1,
+ }
+ }
+
+ fn rect_reserve_border(&self, rect: Rectangle) -> DrawResult<Rectangle> {
+ let Rectangle {
+ top,
+ left,
+ width,
+ height,
+ } = rect;
+
+ // title and right prompt will be displayed on top
+ let border_top =
+ self.border_top || (self.title_on_top && (self.title.is_some() || self.right_prompt.is_some()));
+ let border_bottom =
+ self.border_bottom || (!self.title_on_top && (self.title.is_some() || self.right_prompt.is_some()));
+
+ if (border_top || border_bottom) && ((height < 1) || (border_top && border_bottom && height < 2)) {
+ return Err("not enough height for border".into());
+ }
+
+ if (self.border_left || self.border_right)
+ && ((width < 1) || (self.border_left && self.border_right && width < 2))
+ {
+ return Err("not enough width for border".into());
+ }
+
+ let top = if border_top { top + 1 } else { top };
+ let left = if self.border_left { left + 1 } else { left };
+ let width = if self.border_left { width - 1 } else { width };
+ let width = if self.border_right { width - 1 } else { width };
+ let height = if border_top { height - 1 } else { height };
+ let height = if border_bottom { height - 1 } else { height };
+
+ Ok(Rectangle {
+ top,
+ left,
+ width,
+ height,
+ })
+ }
+
+ fn rect_reserve_padding(&self, rect: Rectangle) -> DrawResult<Rectangle> {
+ let Rectangle {
+ top,
+ left,
+ width,
+ height,
+ } = rect;
+
+ let padding_top = self.padding_top.calc_fixed_size(height, 0);
+ let padding_right = self.padding_right.calc_fixed_size(width, 0);
+ let padding_bottom = self.padding_bottom.calc_fixed_size(height, 0);
+ let padding_left = self.padding_left.calc_fixed_size(width, 0);
+
+ if padding_top + padding_bottom >= height || padding_left + padding_right >= width {
+ return Err("padding takes too much screen, won't draw".into());
+ }
+
+ let top = top + padding_top;
+ let left = left + padding_left;
+ let width = width - (padding_left + padding_right);
+ let height = height - (padding_top + padding_bottom);
+ Ok(Rectangle {
+ top,
+ left,
+ width,
+ height,
+ })
+ }
+
+ /// Calculate the inner rectangle(inside margin, border, padding)
+ fn calc_inner_rect(&self, rect: Rectangle) -> DrawResult<Rectangle> {
+ self.rect_reserve_padding(self.rect_reserve_border(self.rect_reserve_margin(rect)?)?)
+ }
+
+ /// draw border and return the position & size of the inner canvas
+ /// (top, left, width, height)
+ fn draw_border(&self, rect: Rectangle, canvas: &mut dyn Canvas) -> DrawResult<()> {
+ let Rectangle {
+ top,
+ left,
+ width,
+ height,
+ } = rect;
+
+ if (self.border_top || self.border_bottom)
+ && ((height < 1) || (self.border_top && self.border_bottom && height < 2))
+ {
+ return Err("not enough height for border".into());
+ }
+
+ if (self.border_left || self.border_right)
+ && ((width < 1) || (self.border_left && self.border_right && width < 2))
+ {
+ return Err("not enough width for border".into());
+ }
+
+ let bottom = max(top + height, 1) - 1;
+ let right = max(left + width, 1) - 1;
+
+ if self.border_top {
+ let _ = canvas.print_with_attr(top, left, &"─".repeat(width), self.border_top_attr);
+ }
+
+ if self.border_bottom {
+ let _ = canvas.print_with_attr(bottom, left, &"─".repeat(width), self.border_bottom_attr);
+ }
+
+ if self.border_left {
+ for i in top..(top + height) {
+ let _ = canvas.print_with_attr(i, left, "│", self.border_left_attr);
+ }
+ }
+
+ if self.border_right {
+ for i in top..(top + height) {
+ let _ = canvas.print_with_attr(i, right, "│", self.border_right_attr);
+ }
+ }
+
+ // draw 4 corners if necessary
+
+ if self.border_top && self.border_left {
+ let _ = canvas.put_cell(top, left, Cell::default().ch('┌').attribute(self.border_top_attr));
+ }
+
+ if self.border_top && self.border_right {
+ let _ = canvas.put_cell(top, right, Cell::default().ch('┐').attribute(self.border_top_attr));
+ }
+
+ if self.border_bottom && self.border_left {
+ let _ = canvas.put_cell(bottom, left, Cell::default().ch('└').attribute(self.border_bottom_attr));
+ }
+
+ if self.border_bottom && self.border_right {
+ let _ = canvas.put_cell(
+ bottom,
+ right,
+ Cell::default().ch('┘').attribute(self.border_bottom_attr),
+ );
+ }
+
+ Ok(())
+ }
+
+ fn draw_title_and_prompt(&self, canvas: &mut dyn Canvas) -> DrawResult<()> {
+ let (width, height) = canvas.size()?;
+ let row = if self.title_on_top { 0 } else { max(height, 1) - 1 };
+
+ if self.right_prompt.is_some() {
+ let prompt = self.right_prompt.as_ref().unwrap();
+ let text_width = prompt.width_cjk();
+ let left = HorizontalAlign::Right.adjust(0, width, text_width);
+ canvas.print_with_attr(row, left, prompt, self.right_prompt_attr)?;
+ }
+
+ if self.title.is_some() {
+ let title = self.title.as_ref().unwrap();
+ let text_width = title.width_cjk();
+ let left = self.title_align.adjust(0, width, text_width);
+ canvas.print_with_attr(row, left, title, self.right_prompt_attr)?;
+ }
+
+ Ok(())
+ }
+
+ fn draw_header(&self, canvas: &mut dyn Canvas) -> DrawResult<()> {
+ let (width, height) = canvas.size()?;
+ if width == 0 || height == 0 {
+ return Ok(());
+ }
+
+ if self.fn_draw_header.is_some() {
+ self.fn_draw_header.as_ref().unwrap()(canvas)?;
+ } else {
+ self.draw_title_and_prompt(canvas)?;
+ }
+
+ Ok(())
+ }
+
+ fn draw_context(&self, canvas: &'a mut dyn Canvas) -> DrawResult<BoundedCanvas<'a>> {
+ let (width, height) = canvas.size()?;
+ let outer_rect = Rectangle {
+ top: 0,
+ left: 0,
+ width,
+ height,
+ };
+
+ let rect_in_margin = self.rect_reserve_margin(outer_rect)?;
+ self.draw_border(rect_in_margin, canvas)?;
+
+ let Rectangle {
+ top,
+ left,
+ width,
+ height,
+ } = self.rect_header(rect_in_margin);
+ let mut header_canvas = BoundedCanvas::new(top, left, width, height, canvas);
+ self.draw_header(&mut header_canvas)?;
+
+ let Rectangle {
+ top,
+ left,
+ width,
+ height,
+ } = self.calc_inner_rect(outer_rect)?;
+
+ Ok(BoundedCanvas::new(top, left, width, height, canvas))
+ }
+}
+
+impl<Message> Draw for Win<'_, Message> {
+ /// Reserve margin & padding, draw border.
+ fn draw(&self, canvas: &mut dyn Canvas) -> DrawResult<()> {
+ let mut new_canvas = self.draw_context(canvas)?;
+ self.inner.draw(&mut new_canvas)
+ }
+
+ fn draw_mut(&mut self, canvas: &mut dyn Canvas) -> DrawResult<()> {
+ let mut new_canvas = self.draw_context(canvas)?;
+ self.inner.draw_mut(&mut new_canvas)
+ }
+}
+
+impl<Message> Widget<Message> for Win<'_, Message> {
+ fn size_hint(&self) -> (Option<usize>, Option<usize>) {
+ // plus border size
+ let (width, height) = self.inner.size_hint();
+ let width = width.map(|mut w| {
+ w += if self.border_left { 1 } else { 0 };
+ w += if self.border_right { 1 } else { 0 };
+ w
+ });
+
+ let height = height.map(|mut h| {
+ h += if self.border_top { 1 } else { 0 };
+ h += if self.border_bottom { 1 } else { 0 };
+ h
+ });
+
+ (width, height)
+ }
+
+ fn on_event(&self, event: Event, rect: Rectangle) -> Vec<Message> {
+ let empty = vec![];
+ let inner_rect = ok_or_return!(self.calc_inner_rect(rect), empty);
+ let adjusted_event = some_or_return!(adjust_event(event, inner_rect), empty);
+ self.inner.on_event(adjusted_event, inner_rect)
+ }
+
+ fn on_event_mut(&mut self, event: Event, rect: Rectangle) -> Vec<Message> {
+ let empty = vec![];
+ let inner_rect = ok_or_return!(self.calc_inner_rect(rect), empty);
+ let adjusted_event = some_or_return!(adjust_event(event, inner_rect), empty);
+ self.inner.on_event(adjusted_event, inner_rect)
+ }
+}
+
+impl<Message> Split<Message> for Win<'_, Message> {
+ fn get_basis(&self) -> Size {
+ self.basis
+ }
+
+ fn get_grow(&self) -> usize {
+ self.grow
+ }
+
+ fn get_shrink(&self) -> usize {
+ self.shrink
+ }
+}
+
+#[cfg(test)]
+#[allow(dead_code)]
+mod test {
+ use super::*;
+ use std::sync::Mutex;
+
+ struct WinHint {
+ pub width_hint: Option<usize>,
+ pub height_hint: Option<usize>,
+ }
+
+ impl Draw for WinHint {
+ fn draw(&self, _canvas: &mut dyn Canvas) -> DrawResult<()> {
+ unimplemented!()
+ }
+ }
+
+ impl Widget for WinHint {
+ fn size_hint(&self) -> (Option<usize>, Option<usize>) {
+ (self.width_hint, self.height_hint)
+ }
+ }
+
+ #[test]
+ fn size_hint_for_window_should_include_border() {
+ let inner = WinHint {
+ width_hint: None,
+ height_hint: None,
+ };
+ let win_border_top = Win::new(&inner).border_top(true);
+ assert_eq!((None, None), win_border_top.size_hint());
+ let win_border_right = Win::new(&inner).border_right(true);
+ assert_eq!((None, None), win_border_right.size_hint());
+ let win_border_bottom = Win::new(&inner).border_bottom(true);
+ assert_eq!((None, None), win_border_bottom.size_hint());
+ let win_border_left = Win::new(&inner).border_left(true);
+ assert_eq!((None, None), win_border_left.size_hint());
+
+ let inner = WinHint {
+ width_hint: Some(1),
+ height_hint: None,
+ };
+ let win_border_top = Win::new(&inner).border_top(true);
+ assert_eq!((Some(1), None), win_border_top.size_hint());
+ let win_border_right = Win::new(&inner).border_right(true);
+ assert_eq!((Some(2), None), win_border_right.size_hint());
+ let win_border_bottom = Win::new(&inner).border_bottom(true);
+ assert_eq!((Some(1), None), win_border_bottom.size_hint());
+ let win_border_left = Win::new(&inner).border_left(true);
+ assert_eq!((Some(2), None), win_border_left.size_hint());
+
+ let inner = WinHint {
+ width_hint: None,
+ height_hint: Some(1),
+ };
+ let win_border_top = Win::new(&inner).border_top(true);
+ assert_eq!((None, Some(2)), win_border_top.size_hint());
+ let win_border_right = Win::new(&inner).border_right(true);
+ assert_eq!((None, Some(1)), win_border_right.size_hint());
+ let win_border_bottom = Win::new(&inner).border_bottom(true);
+ assert_eq!((None, Some(2)), win_border_bottom.size_hint());
+ let win_border_left = Win::new(&inner).border_left(true);
+ assert_eq!((None, Some(1)), win_border_left.size_hint());
+ }
+
+ #[derive(PartialEq, Debug)]
+ enum Called {
+ No,
+ Mut,
+ Immut,
+ }
+
+ struct Drawn {
+ called: Mutex<Called>,
+ }
+
+ impl Draw for Drawn {
+ fn draw(&self, _canvas: &mut dyn Canvas) -> DrawResult<()> {
+ *self.called.lock().unwrap() = Called::Immut;
+ Ok(())
+ }
+ fn draw_mut(&mut self, _canvas: &mut dyn Canvas) -> DrawResult<()> {
+ *self.called.lock().unwrap() = Called::Mut;
+ Ok(())
+ }
+ }
+
+ impl Widget for Drawn {}
+
+ #[derive(Default)]
+ struct TestCanvas {}
+
+ #[allow(unused_variables)]
+ impl Canvas for TestCanvas {
+ fn size(&self) -> crate::Result<(usize, usize)> {
+ Ok((100, 100))
+ }
+
+ fn clear(&mut self) -> crate::Result<()> {
+ unimplemented!()
+ }
+
+ fn put_cell(&mut self, row: usize, col: usize, cell: Cell) -> crate::Result<usize> {
+ Ok(1)
+ }
+
+ fn set_cursor(&mut self, row: usize, col: usize) -> crate::Result<()> {
+ unimplemented!()
+ }
+
+ fn show_cursor(&mut self, show: bool) -> crate::Result<()> {
+ unimplemented!()
+ }
+ }
+
+ #[test]
+ fn mutable_widget() {
+ let mut canvas = TestCanvas::default();
+
+ let mut mutable = Drawn {
+ called: Mutex::new(Called::No),
+ };
+ {
+ let mut win = Win::new(&mut mutable);
+ win.draw_mut(&mut canvas).unwrap();
+ }
+ assert_eq!(Called::Mut, *mutable.called.lock().unwrap());
+
+ let immutable = Drawn {
+ called: Mutex::new(Called::No),
+ };
+ let win = Win::new(&immutable);
+ win.draw(&mut canvas).unwrap();
+ assert_eq!(Called::Immut, *immutable.called.lock().unwrap());
+ }
+}