File iamb-0.0.8.obscpio of Package iamb
07070100000000000081A400000000000000000000000164A9007B0000000E000000000000000000000000000000000000001A00000000iamb-0.0.8/.gitattributes* text eol=lf
07070100000001000041ED00000000000000000000000264A9007B00000000000000000000000000000000000000000000001300000000iamb-0.0.8/.github07070100000002000081A400000000000000000000000164A9007B0000000F000000000000000000000000000000000000001F00000000iamb-0.0.8/.github/FUNDING.ymlko_fi: ulyssam
07070100000003000041ED00000000000000000000000264A9007B00000000000000000000000000000000000000000000001D00000000iamb-0.0.8/.github/workflows07070100000004000081A400000000000000000000000164A9007B000005F2000000000000000000000000000000000000002400000000iamb-0.0.8/.github/workflows/ci.ymlon:
push:
branches:
- main
pull_request:
branches:
- main
name: CI
jobs:
test:
strategy:
matrix:
platform: [ubuntu-latest, windows-latest, macos-latest]
runs-on: ${{ matrix.platform }}
steps:
- name: Checkout code
uses: actions/checkout@v3
with:
submodules: true
- name: Install Rust (1.66 w/ clippy)
uses: dtolnay/rust-toolchain@1.66
with:
components: clippy
- name: Install Rust (nightly w/ rustfmt)
run: rustup toolchain install nightly --component rustfmt
- name: Cache cargo registry
uses: actions/cache@v3
with:
path: ~/.cargo/registry
key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }}
- name: Cache cargo build
uses: actions/cache@v3
with:
path: target
key: ${{ runner.os }}-cargo-build-${{ hashFiles('**/Cargo.lock') }}
- name: Check formatting
run: cargo +nightly fmt --all -- --check
- name: Check Clippy
if: matrix.platform == 'ubuntu-latest'
uses: giraffate/clippy-action@v1
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
reporter: 'github-check'
- name: Run tests
run: cargo test
- name: Build artifacts
run: cargo build --release
- name: Upload artifacts
uses: actions/upload-artifact@master
with:
name: iamb-${{ matrix.platform }}
path: |
./target/release/iamb
./target/release/iamb.exe
07070100000005000081A400000000000000000000000164A9007B00000026000000000000000000000000000000000000001600000000iamb-0.0.8/.gitignore/target
/result
/TODO
/docs/iamb.[15]
07070100000006000081A400000000000000000000000164A9007B00000132000000000000000000000000000000000000001900000000iamb-0.0.8/.rustfmt.tomlunstable_features = true
max_width = 100
fn_call_width = 90
struct_lit_width = 50
struct_variant_width = 50
chain_width = 75
binop_separator = "Back"
force_multiline_blocks = true
match_block_trailing_comma = true
imports_layout = "HorizontalVertical"
newline_style = "Unix"
overflow_delimited_expr = true
07070100000007000081A400000000000000000000000164A9007B000002B7000000000000000000000000000000000000001B00000000iamb-0.0.8/CONTRIBUTING.md# Contributing to iamb
## Building
You can build `iamb` locally by using `cargo build`.
## Pull Requests
When making changes to `iamb`, please make sure to:
- Add new tests for fixed bugs and new features whenever possible
- Add new documentation with new features
If you're adding a large amount of new code, please make sure to look at a test
coverage report and ensure that your tests sufficiently cover your changes.
You can generate an HTML report with [cargo-tarpaulin] by running:
```
% cargo tarpaulin --avoid-cfg-tarpaulin --out html
```
## Tests
You can run the unit tests and documentation tests using `cargo test`.
[cargo-tarpaulin]: https://github.com/xd009642/tarpaulin
07070100000008000081A400000000000000000000000164A9007B0001BBD1000000000000000000000000000000000000001600000000iamb-0.0.8/Cargo.lock# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "adler"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe"
[[package]]
name = "aead"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b613b8e1e3cf911a086f53f03bf286f52fd7a7258e4fa606f0ef220d39d8877"
dependencies = [
"generic-array",
"rand_core 0.6.4",
]
[[package]]
name = "aes"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "433cfd6710c9986c576a25ca913c39d66a6474107b406f34f91d4a8923395241"
dependencies = [
"cfg-if",
"cipher 0.4.4",
"cpufeatures",
]
[[package]]
name = "ahash"
version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47"
dependencies = [
"getrandom 0.2.8",
"once_cell",
"version_check",
]
[[package]]
name = "aho-corasick"
version = "0.7.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc936419f96fa211c1b9166887b38e5e40b19958e5b895be7c1f93adec7071ac"
dependencies = [
"memchr",
]
[[package]]
name = "android_system_properties"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"
dependencies = [
"libc",
]
[[package]]
name = "anyhow"
version = "1.0.70"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7de8ce5e0f9f8d88245311066a578d72b7af3e7088f32783804676302df237e4"
[[package]]
name = "anymap2"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d301b3b94cb4b2f23d7917810addbbaff90738e0ca2be692bd027e70d7e0330c"
[[package]]
name = "arboard"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6041616acea41d67c4a984709ddab1587fd0b10efe5cc563fee954d2f011854"
dependencies = [
"clipboard-win",
"core-graphics",
"image",
"log",
"objc",
"objc-foundation",
"objc_id",
"once_cell",
"parking_lot 0.12.1",
"thiserror",
"winapi",
"x11rb",
]
[[package]]
name = "arrayref"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b4930d2cb77ce62f89ee5d5289b4ac049559b1c45539271f5ed4fdc7db34545"
[[package]]
name = "arrayvec"
version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8da52d66c7071e2e3fa2a1e5c6d088fec47b593032b254f5e980de8ea54454d6"
dependencies = [
"serde",
]
[[package]]
name = "assign"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f093eed78becd229346bf859eec0aa4dd7ddde0757287b2b4107a1f09c80002"
[[package]]
name = "async-lock"
version = "2.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa24f727524730b077666307f2734b4a1a1c57acb79193127dcc8914d5242dd7"
dependencies = [
"event-listener",
]
[[package]]
name = "async-once-cell"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72faff1fdc615a0199d7bf71e6f389af54d46a66e9beb5d76c39e48eda93ecce"
[[package]]
name = "async-stream"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad445822218ce64be7a341abfb0b1ea43b5c23aa83902542a4542e78309d8e5e"
dependencies = [
"async-stream-impl",
"futures-core",
"pin-project-lite",
]
[[package]]
name = "async-stream-impl"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4655ae1a7b0cdf149156f780c5bf3f1352bc53cbd9e0a361a7ef7b22947e965"
dependencies = [
"proc-macro2 1.0.53",
"quote 1.0.26",
"syn 1.0.109",
]
[[package]]
name = "async-trait"
version = "0.1.67"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "86ea188f25f0255d8f92797797c97ebf5631fa88178beb1a46fdf5622c9a00e4"
dependencies = [
"proc-macro2 1.0.53",
"quote 1.0.26",
"syn 2.0.8",
]
[[package]]
name = "atomic"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b88d82667eca772c4aa12f0f1348b3ae643424c8876448f3f7bd5787032e234c"
dependencies = [
"autocfg 1.1.0",
]
[[package]]
name = "autocfg"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0dde43e75fd43e8a1bf86103336bc699aa8d17ad1be60c76c0bdfd4828e19b78"
dependencies = [
"autocfg 1.1.0",
]
[[package]]
name = "autocfg"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
[[package]]
name = "backoff"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b62ddb9cb1ec0a098ad4bbf9344d0713fa193ae1a80af55febcff2627b6a00c1"
dependencies = [
"futures-core",
"getrandom 0.2.8",
"instant",
"pin-project-lite",
"rand 0.8.5",
"tokio",
]
[[package]]
name = "base64"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8"
[[package]]
name = "base64"
version = "0.21.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4a4ddaa51a5bc52a6948f74c06d20aaaddb71924eab79b8c97a8c556e942d6a"
[[package]]
name = "base64ct"
version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c3c1a368f70d6cf7302d78f8f7093da241fb8e8807c05cc9e51a125895a6d5b"
[[package]]
name = "bincode"
version = "1.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad"
dependencies = [
"serde",
]
[[package]]
name = "bit-set"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0700ddab506f33b20a03b13996eccd309a48e5ff77d0d95926aa0210fb4e95f1"
dependencies = [
"bit-vec",
]
[[package]]
name = "bit-vec"
version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb"
[[package]]
name = "bit_field"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc827186963e592360843fb5ba4b973e145841266c1357f7180c43526f2e5b61"
[[package]]
name = "bitflags"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "bitflags"
version = "2.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "487f1e0fcbe47deb8b0574e646def1c903389d95241dd1bbcc6ce4a715dfc0c1"
[[package]]
name = "blake3"
version = "1.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42ae2468a89544a466886840aa467a25b766499f4f04bf7d9fcd10ecee9fccef"
dependencies = [
"arrayref",
"arrayvec",
"cc",
"cfg-if",
"constant_time_eq",
"digest 0.10.6",
]
[[package]]
name = "block"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a"
[[package]]
name = "block-buffer"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4"
dependencies = [
"generic-array",
]
[[package]]
name = "block-buffer"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
dependencies = [
"generic-array",
]
[[package]]
name = "block-padding"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0a90ec2df9600c28a01c56c4784c9207a96d2451833aeceb8cc97e4c9548bb78"
dependencies = [
"generic-array",
]
[[package]]
name = "bumpalo"
version = "3.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d261e256854913907f67ed06efbc3338dfe6179796deefc1ff763fc1aee5535"
[[package]]
name = "bytemuck"
version = "1.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "17febce684fd15d89027105661fec94afb475cb995fbc59d2865198446ba2eea"
[[package]]
name = "byteorder"
version = "1.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610"
[[package]]
name = "bytes"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "89b2fd2a0dcf38d7971e2194b6b6eebab45ae01067456a7fd93d5547a61b70be"
[[package]]
name = "cassowary"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53"
[[package]]
name = "cbc"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6"
dependencies = [
"cipher 0.4.4",
]
[[package]]
name = "cc"
version = "1.0.79"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50d30906286121d95be3d479533b458f87493b30a4b5f79a607db8f5d11aa91f"
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "chacha20"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c80e5460aa66fe3b91d40bcbdab953a597b60053e34d684ac6903f863b680a6"
dependencies = [
"cfg-if",
"cipher 0.3.0",
"cpufeatures",
"zeroize",
]
[[package]]
name = "chacha20poly1305"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a18446b09be63d457bbec447509e85f662f32952b035ce892290396bc0b0cff5"
dependencies = [
"aead",
"chacha20",
"cipher 0.3.0",
"poly1305",
"zeroize",
]
[[package]]
name = "chrono"
version = "0.4.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e3c5919066adf22df73762e50cffcde3a758f2a848b113b586d1f86728b673b"
dependencies = [
"iana-time-zone",
"js-sys",
"num-integer",
"num-traits",
"time 0.1.45",
"wasm-bindgen",
"winapi",
]
[[package]]
name = "cipher"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ee52072ec15386f770805afd189a01c8841be8696bed250fa2f13c4c0d6dfb7"
dependencies = [
"generic-array",
]
[[package]]
name = "cipher"
version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
dependencies = [
"crypto-common",
"inout",
]
[[package]]
name = "clap"
version = "4.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76e21918af71fb4bcd813230cf549e33d14f73d0326b932b630ce2930332b131"
dependencies = [
"bitflags 2.0.2",
"clap_derive",
"clap_lex",
"is-terminal",
"once_cell",
"strsim",
"termcolor",
"terminal_size",
]
[[package]]
name = "clap_derive"
version = "4.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a932373bab67b984c790ddf2c9ca295d8e3af3b7ef92de5a5bacdccdee4b09b"
dependencies = [
"heck",
"proc-macro2 1.0.53",
"quote 1.0.26",
"syn 2.0.8",
]
[[package]]
name = "clap_lex"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "033f6b7a4acb1f358c742aaca805c939ee73b4c6209ae4318ec7aca81c42e646"
dependencies = [
"os_str_bytes",
]
[[package]]
name = "clipboard-win"
version = "4.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7191c27c2357d9b7ef96baac1773290d4ca63b24205b82a3fd8a0637afcf0362"
dependencies = [
"error-code",
"str-buf",
"winapi",
]
[[package]]
name = "cloudabi"
version = "0.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f"
dependencies = [
"bitflags 1.3.2",
]
[[package]]
name = "codespan-reporting"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3538270d33cc669650c4b093848450d380def10c331d38c768e34cac80576e6e"
dependencies = [
"termcolor",
"unicode-width",
]
[[package]]
name = "color_quant"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
[[package]]
name = "comrak"
version = "0.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "482aa5695bca086022be453c700a40c02893f1ba7098a2c88351de55341ae894"
dependencies = [
"clap",
"emojis",
"entities",
"memchr",
"once_cell",
"regex",
"shell-words",
"slug",
"syntect",
"typed-arena",
"unicode_categories",
"xdg",
]
[[package]]
name = "const-oid"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4c78c047431fee22c1a7bb92e00ad095a02a983affe4d8a72e2a2c62c1b94f3"
[[package]]
name = "constant_time_eq"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13418e745008f7349ec7e449155f419a61b92b58a99cc3616942b926825ec76b"
[[package]]
name = "convert_case"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e"
[[package]]
name = "core-foundation"
version = "0.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "194a7a9e6de53fa55116934067c844d9d749312f75c6f6d0980e8c252f8c2146"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "core-foundation-sys"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5827cebf4670468b8772dd191856768aedcb1b0278a04f989f7766351917b9dc"
[[package]]
name = "core-graphics"
version = "0.22.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2581bbab3b8ffc6fcbd550bf46c355135d16e9ff2a6ea032ad6b9bf1d7efe4fb"
dependencies = [
"bitflags 1.3.2",
"core-foundation",
"core-graphics-types",
"foreign-types",
"libc",
]
[[package]]
name = "core-graphics-types"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a68b68b3446082644c91ac778bf50cd4104bfb002b5a6a7c44cca5a2c70788b"
dependencies = [
"bitflags 1.3.2",
"core-foundation",
"foreign-types",
"libc",
]
[[package]]
name = "cpufeatures"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28d997bd5e24a5928dd43e46dc529867e207907fe0b239c3477d924f7f2ca320"
dependencies = [
"libc",
]
[[package]]
name = "crc32fast"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b540bd8bc810d3885c6ea91e2018302f68baba2129ab3e88f32389ee9370880d"
dependencies = [
"cfg-if",
]
[[package]]
name = "crossbeam-channel"
version = "0.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a33c2bf77f2df06183c3aa30d1e96c0695a313d4f9c453cc3762a6db39f99200"
dependencies = [
"cfg-if",
"crossbeam-utils",
]
[[package]]
name = "crossbeam-deque"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce6fd6f855243022dcecf8702fef0c297d4338e226845fe067f6341ad9fa0cef"
dependencies = [
"cfg-if",
"crossbeam-epoch",
"crossbeam-utils",
]
[[package]]
name = "crossbeam-epoch"
version = "0.9.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46bd5f3f85273295a9d14aedfb86f6aadbff6d8f5295c4a9edb08e819dcf5695"
dependencies = [
"autocfg 1.1.0",
"cfg-if",
"crossbeam-utils",
"memoffset 0.8.0",
"scopeguard",
]
[[package]]
name = "crossbeam-utils"
version = "0.8.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c063cd8cc95f5c377ed0d4b49a4b21f632396ff690e8470c29b3359b346984b"
dependencies = [
"cfg-if",
]
[[package]]
name = "crossterm"
version = "0.25.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e64e6c0fbe2c17357405f7c758c1ef960fce08bdfb2c03d88d2a18d7e09c4b67"
dependencies = [
"bitflags 1.3.2",
"crossterm_winapi",
"libc",
"mio",
"parking_lot 0.12.1",
"signal-hook",
"signal-hook-mio",
"winapi",
]
[[package]]
name = "crossterm"
version = "0.26.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a84cda67535339806297f1b331d6dd6320470d2a0fe65381e79ee9e156dd3d13"
dependencies = [
"bitflags 1.3.2",
"crossterm_winapi",
"libc",
"mio",
"parking_lot 0.12.1",
"signal-hook",
"signal-hook-mio",
"winapi",
]
[[package]]
name = "crossterm_winapi"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ae1b35a484aa10e07fe0638d02301c5ad24de82d310ccbd2f3693da5f09bf1c"
dependencies = [
"winapi",
]
[[package]]
name = "crunchy"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a81dae078cea95a014a339291cec439d2f232ebe854a9d672b796c6afafa9b7"
[[package]]
name = "crypto-common"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"
dependencies = [
"generic-array",
"typenum",
]
[[package]]
name = "css-color-parser"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ccb6ce7ef97e6dc6e575e51b596c9889a5cc88a307b5ef177d215c61fd7581d"
dependencies = [
"lazy_static 0.1.16",
]
[[package]]
name = "ctr"
version = "0.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835"
dependencies = [
"cipher 0.4.4",
]
[[package]]
name = "curve25519-dalek"
version = "3.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90f9d052967f590a76e62eb387bd0bbb1b000182c3cefe5364db6b7211651bc0"
dependencies = [
"byteorder",
"digest 0.9.0",
"rand_core 0.5.1",
"serde",
"subtle",
"zeroize",
]
[[package]]
name = "cxx"
version = "1.0.93"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a9c00419335c41018365ddf7e4d5f1c12ee3659ddcf3e01974650ba1de73d038"
dependencies = [
"cc",
"cxxbridge-flags",
"cxxbridge-macro",
"link-cplusplus",
]
[[package]]
name = "cxx-build"
version = "1.0.93"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb8307ad413a98fff033c8545ecf133e3257747b3bae935e7602aab8aa92d4ca"
dependencies = [
"cc",
"codespan-reporting",
"once_cell",
"proc-macro2 1.0.53",
"quote 1.0.26",
"scratch",
"syn 2.0.8",
]
[[package]]
name = "cxxbridge-flags"
version = "1.0.93"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "edc52e2eb08915cb12596d29d55f0b5384f00d697a646dbd269b6ecb0fbd9d31"
[[package]]
name = "cxxbridge-macro"
version = "1.0.93"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "631569015d0d8d54e6c241733f944042623ab6df7bc3be7466874b05fcdb1c5f"
dependencies = [
"proc-macro2 1.0.53",
"quote 1.0.26",
"syn 2.0.8",
]
[[package]]
name = "darling"
version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b750cb3417fd1b327431a470f388520309479ab0bf5e323505daf0290cd3850"
dependencies = [
"darling_core",
"darling_macro",
]
[[package]]
name = "darling_core"
version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "109c1ca6e6b7f82cc233a97004ea8ed7ca123a9af07a8230878fcfda9b158bf0"
dependencies = [
"fnv",
"ident_case",
"proc-macro2 1.0.53",
"quote 1.0.26",
"strsim",
"syn 1.0.109",
]
[[package]]
name = "darling_macro"
version = "0.14.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4aab4dbc9f7611d8b55048a3a16d2d010c2c8334e46304b40ac1cc14bf3b48e"
dependencies = [
"darling_core",
"quote 1.0.26",
"syn 1.0.109",
]
[[package]]
name = "dashmap"
version = "5.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "907076dfda823b0b36d2a1bb5f90c96660a5bbcd7729e10727f07858f22c4edc"
dependencies = [
"cfg-if",
"hashbrown",
"lock_api",
"once_cell",
"parking_lot_core 0.9.7",
]
[[package]]
name = "der"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6919815d73839e7ad218de758883aae3a257ba6759ce7a9992501efbb53d705c"
dependencies = [
"const-oid",
]
[[package]]
name = "derive_builder"
version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d07adf7be193b71cc36b193d0f5fe60b918a3a9db4dad0449f57bcfd519704a3"
dependencies = [
"derive_builder_macro",
]
[[package]]
name = "derive_builder_core"
version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f91d4cfa921f1c05904dc3c57b4a32c38aed3340cce209f3a6fd1478babafc4"
dependencies = [
"darling",
"proc-macro2 1.0.53",
"quote 1.0.26",
"syn 1.0.109",
]
[[package]]
name = "derive_builder_macro"
version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f0314b72bed045f3a68671b3c86328386762c93f82d98c65c3cb5e5f573dd68"
dependencies = [
"derive_builder_core",
"syn 1.0.109",
]
[[package]]
name = "derive_more"
version = "0.99.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4fb810d30a7c1953f91334de7244731fc3f3c10d7fe163338a35b9f640960321"
dependencies = [
"convert_case",
"proc-macro2 1.0.53",
"quote 1.0.26",
"rustc_version",
"syn 1.0.109",
]
[[package]]
name = "deunicode"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "850878694b7933ca4c9569d30a34b55031b9b139ee1fc7b94a527c4ef960d690"
[[package]]
name = "deunicode"
version = "1.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c1bba4f227a4a53d12b653f50ca7bf10c9119ae2aba56aff9e0338b5c98f36a"
[[package]]
name = "diff"
version = "0.1.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8"
[[package]]
name = "digest"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066"
dependencies = [
"generic-array",
]
[[package]]
name = "digest"
version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8168378f4e5023e7218c89c891c0fd8ecdb5e5e4f18cb78f38cf245dd021e76f"
dependencies = [
"block-buffer 0.10.4",
"crypto-common",
"subtle",
]
[[package]]
name = "dirs"
version = "4.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca3aa72a6f96ea37bbc5aa912f6788242832f75369bdfdadcb0e38423f100059"
dependencies = [
"dirs-sys",
]
[[package]]
name = "dirs-sys"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b1d1d91c932ef41c0f2663aa8b0ca0342d444d842c06914aa0a7e352d0bada6"
dependencies = [
"libc",
"redox_users",
"winapi",
]
[[package]]
name = "discard"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "212d0f5754cb6769937f4501cc0e67f4f4483c8d2c3e1e922ee9edbe4ab4c7c0"
[[package]]
name = "displaydoc"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bf95dc3f046b9da4f2d51833c0d3547d8564ef6910f5c1ed130306a75b92886"
dependencies = [
"proc-macro2 1.0.53",
"quote 1.0.26",
"syn 1.0.109",
]
[[package]]
name = "ed25519"
version = "1.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91cff35c70bba8a626e3185d8cd48cc11b5437e1a5bcd15b9b5fa3c64b6dfee7"
dependencies = [
"serde",
"signature",
]
[[package]]
name = "ed25519-dalek"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c762bae6dcaf24c4c84667b8579785430908723d5c889f469d76a41d59cc7a9d"
dependencies = [
"curve25519-dalek",
"ed25519",
"rand 0.7.3",
"serde",
"serde_bytes",
"sha2 0.9.9",
"zeroize",
]
[[package]]
name = "either"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7fcaabb2fef8c910e7f4c7ce9f67a1283a1715879a7c230ca9d6d1ae31f16d91"
[[package]]
name = "emojis"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44fe60b864b6544ad211d4053ced474a9b9d2c8d66b77f01d6c6bcfed10c6bf0"
dependencies = [
"phf 0.11.1",
]
[[package]]
name = "encoding_rs"
version = "0.8.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071a31f4ee85403370b58aca746f01041ede6f0da2730960ad001edc2b71b394"
dependencies = [
"cfg-if",
]
[[package]]
name = "endian-type"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c34f04666d835ff5d62e058c3995147c06f42fe86ff053337632bca83e42702d"
[[package]]
name = "entities"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5320ae4c3782150d900b79807611a59a99fc9a1d61d686faafc24b93fc8d7ca"
[[package]]
name = "errno"
version = "0.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f639046355ee4f37944e44f60642c6f3a7efa3cf6b78c78a0d989a8ce6c396a1"
dependencies = [
"errno-dragonfly",
"libc",
"winapi",
]
[[package]]
name = "errno"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50d6a0976c999d473fe89ad888d5a284e55366d9dc9038b1ba2aa15128c4afa0"
dependencies = [
"errno-dragonfly",
"libc",
"windows-sys 0.45.0",
]
[[package]]
name = "errno-dragonfly"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa68f1b12764fab894d2755d2518754e71b4fd80ecfb822714a1206c2aab39bf"
dependencies = [
"cc",
"libc",
]
[[package]]
name = "error-code"
version = "2.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "64f18991e7bf11e7ffee451b5318b5c1a73c52d0d0ada6e5a3017c8c1ced6a21"
dependencies = [
"libc",
"str-buf",
]
[[package]]
name = "event-listener"
version = "2.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0"
[[package]]
name = "exr"
version = "1.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bdd2162b720141a91a054640662d3edce3d50a944a50ffca5313cd951abb35b4"
dependencies = [
"bit_field",
"flume",
"half",
"lebe",
"miniz_oxide",
"rayon-core",
"smallvec",
"zune-inflate",
]
[[package]]
name = "fancy-regex"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d6b8560a05112eb52f04b00e5d3790c0dd75d9d980eb8a122fb23b92a623ccf"
dependencies = [
"bit-set",
"regex",
]
[[package]]
name = "flate2"
version = "1.0.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a8a2db397cb1c8772f31494cb8917e48cd1e64f0fa7efac59fbd741a0a8ce841"
dependencies = [
"crc32fast",
"miniz_oxide",
]
[[package]]
name = "flume"
version = "0.10.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1657b4441c3403d9f7b3409e47575237dac27b1b5726df654a6ecbf92f0f7577"
dependencies = [
"futures-core",
"futures-sink",
"nanorand",
"pin-project",
"spin 0.9.8",
]
[[package]]
name = "fnv"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "foreign-types"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1"
dependencies = [
"foreign-types-shared",
]
[[package]]
name = "foreign-types-shared"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"
[[package]]
name = "form_urlencoded"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a9c384f161156f5260c24a097c56119f9be8c798586aecc13afbcbe7b7e26bf8"
dependencies = [
"percent-encoding",
]
[[package]]
name = "fs2"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213"
dependencies = [
"libc",
"winapi",
]
[[package]]
name = "fs_extra"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"
[[package]]
name = "fuchsia-cprng"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba"
[[package]]
name = "futf"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df420e2e84819663797d1ec6544b13c5be84629e7bb00dc960d6917db2987843"
dependencies = [
"mac",
"new_debug_unreachable",
]
[[package]]
name = "futures"
version = "0.3.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "531ac96c6ff5fd7c62263c5e3c67a603af4fcaee2e1a0ae5565ba3a11e69e549"
dependencies = [
"futures-channel",
"futures-core",
"futures-executor",
"futures-io",
"futures-sink",
"futures-task",
"futures-util",
]
[[package]]
name = "futures-channel"
version = "0.3.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "164713a5a0dcc3e7b4b1ed7d3b433cabc18025386f9339346e8daf15963cf7ac"
dependencies = [
"futures-core",
"futures-sink",
]
[[package]]
name = "futures-core"
version = "0.3.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "86d7a0c1aa76363dac491de0ee99faf6941128376f1cf96f07db7603b7de69dd"
[[package]]
name = "futures-executor"
version = "0.3.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1997dd9df74cdac935c76252744c1ed5794fac083242ea4fe77ef3ed60ba0f83"
dependencies = [
"futures-core",
"futures-task",
"futures-util",
]
[[package]]
name = "futures-io"
version = "0.3.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "89d422fa3cbe3b40dca574ab087abb5bc98258ea57eea3fd6f1fa7162c778b91"
[[package]]
name = "futures-macro"
version = "0.3.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3eb14ed937631bd8b8b8977f2c198443447a8355b6e3ca599f38c975e5a963b6"
dependencies = [
"proc-macro2 1.0.53",
"quote 1.0.26",
"syn 1.0.109",
]
[[package]]
name = "futures-signals"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "36a12cb78961d5c0bc0e358599bba98ec09201090a22339cd8ea27e815c11b25"
dependencies = [
"discard",
"futures-channel",
"futures-core",
"futures-util",
"gensym",
"pin-project",
]
[[package]]
name = "futures-sink"
version = "0.3.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec93083a4aecafb2a80a885c9de1f0ccae9dbd32c2bb54b0c3a65690e0b8d2f2"
[[package]]
name = "futures-task"
version = "0.3.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd65540d33b37b16542a0438c12e6aeead10d4ac5d05bd3f805b8f35ab592879"
[[package]]
name = "futures-util"
version = "0.3.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ef6b17e481503ec85211fed8f39d1970f128935ca1f814cd32ac4a6842e84ab"
dependencies = [
"futures-channel",
"futures-core",
"futures-io",
"futures-macro",
"futures-sink",
"futures-task",
"memchr",
"pin-project-lite",
"pin-utils",
"slab",
]
[[package]]
name = "fxhash"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c31b6d751ae2c7f11320402d34e41349dd1016f8d5d45e48c4312bc8625af50c"
dependencies = [
"byteorder",
]
[[package]]
name = "generic-array"
version = "0.14.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bff49e947297f3312447abdca79f45f4738097cc82b06e72054d2223f601f1b9"
dependencies = [
"typenum",
"version_check",
]
[[package]]
name = "gensym"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fcb328fe25cbf075818a3e57bb5ee39b49b4f26c94d685356426154c5962cccd"
dependencies = [
"proc-macro2 0.4.30",
"quote 0.6.13",
"syn 0.15.44",
"uuid 0.7.4",
]
[[package]]
name = "gethostname"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1ebd34e35c46e00bb73e81363248d627782724609fe1b6396f553f68fe3862e"
dependencies = [
"libc",
"winapi",
]
[[package]]
name = "gethostname"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a329e22866dd78b35d2c639a4a23d7b950aeae300dfd79f4fb19f74055c2404"
dependencies = [
"libc",
"windows 0.43.0",
]
[[package]]
name = "getopts"
version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "14dbbfd5c71d70241ecf9e6f13737f7b5ce823821063188d7e46c41d371eebd5"
dependencies = [
"unicode-width",
]
[[package]]
name = "getrandom"
version = "0.1.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fc3cb4d91f53b50155bdcfd23f6a4c39ae1969c2ae85982b135750cccaf5fce"
dependencies = [
"cfg-if",
"js-sys",
"libc",
"wasi 0.9.0+wasi-snapshot-preview1",
"wasm-bindgen",
]
[[package]]
name = "getrandom"
version = "0.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c05aeb6a22b8f62540c194aac980f2115af067bfe15a0734d7277a768d396b31"
dependencies = [
"cfg-if",
"js-sys",
"libc",
"wasi 0.11.0+wasi-snapshot-preview1",
"wasm-bindgen",
]
[[package]]
name = "gif"
version = "0.11.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3edd93c6756b4dfaf2709eafcc345ba2636565295c198a9cfbf75fa5e3e00b06"
dependencies = [
"color_quant",
"weezl",
]
[[package]]
name = "h2"
version = "0.3.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5be7b54589b581f624f566bf5d8eb2bab1db736c51528720b6bd36b96b55924d"
dependencies = [
"bytes",
"fnv",
"futures-core",
"futures-sink",
"futures-util",
"http",
"indexmap",
"slab",
"tokio",
"tokio-util",
"tracing",
]
[[package]]
name = "half"
version = "2.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02b4af3693f1b705df946e9fe5631932443781d0aabb423b62fcd4d73f6d2fd0"
dependencies = [
"crunchy",
]
[[package]]
name = "hashbrown"
version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
dependencies = [
"ahash",
]
[[package]]
name = "heck"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
[[package]]
name = "hermit-abi"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee512640fe35acbfb4bb779db6f0d80704c2cacfa2e39b601ef3e3f47d1ae4c7"
dependencies = [
"libc",
]
[[package]]
name = "hermit-abi"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "443144c8cdadd93ebf52ddb4056d257f5b52c04d3c804e657d19eb73fc33668b"
[[package]]
name = "hkdf"
version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "791a029f6b9fc27657f6f188ec6e5e43f6911f6f878e0dc5501396e09809d437"
dependencies = [
"hmac",
]
[[package]]
name = "hmac"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
dependencies = [
"digest 0.10.6",
]
[[package]]
name = "html5ever"
version = "0.26.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bea68cab48b8459f17cf1c944c67ddc572d272d9f2b274140f223ecb1da4a3b7"
dependencies = [
"log",
"mac",
"markup5ever",
"proc-macro2 1.0.53",
"quote 1.0.26",
"syn 1.0.109",
]
[[package]]
name = "http"
version = "0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bd6effc99afb63425aff9b05836f029929e345a6148a14b7ecd5ab67af944482"
dependencies = [
"bytes",
"fnv",
"itoa",
]
[[package]]
name = "http-body"
version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d5f38f16d184e36f2408a55281cd658ecbd3ca05cce6d6510a176eca393e26d1"
dependencies = [
"bytes",
"http",
"pin-project-lite",
]
[[package]]
name = "httparse"
version = "1.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d897f394bad6a705d5f4104762e116a75639e470d80901eed05a860a95cb1904"
[[package]]
name = "httpdate"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4a1e36c821dbe04574f602848a19f742f4fb3c98d40449f11bcad18d6b17421"
[[package]]
name = "hyper"
version = "0.14.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc5e554ff619822309ffd57d8734d77cd5ce6238bc956f037ea06c58238c9899"
dependencies = [
"bytes",
"futures-channel",
"futures-core",
"futures-util",
"h2",
"http",
"http-body",
"httparse",
"httpdate",
"itoa",
"pin-project-lite",
"socket2",
"tokio",
"tower-service",
"tracing",
"want",
]
[[package]]
name = "hyper-rustls"
version = "0.23.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1788965e61b367cd03a62950836d5cd41560c3577d90e40e0819373194d1661c"
dependencies = [
"http",
"hyper",
"rustls",
"tokio",
"tokio-rustls",
]
[[package]]
name = "iamb"
version = "0.0.8"
dependencies = [
"arboard",
"bitflags 1.3.2",
"chrono",
"clap",
"comrak",
"css-color-parser",
"dirs",
"emojis",
"futures",
"gethostname 0.4.1",
"html5ever",
"image",
"lazy_static 1.4.0",
"libc",
"mandown",
"markup5ever_rcdom",
"matrix-sdk",
"mime",
"mime_guess",
"modalkit",
"open",
"pretty_assertions",
"regex",
"rpassword",
"serde",
"serde_json",
"thiserror",
"tokio",
"tracing",
"tracing-appender",
"tracing-subscriber",
"unicode-segmentation",
"unicode-width",
"url",
"vergen",
]
[[package]]
name = "iana-time-zone"
version = "0.1.54"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c17cc76786e99f8d2f055c11159e7f0091c42474dcc3189fbab96072e873e6d"
dependencies = [
"android_system_properties",
"core-foundation-sys",
"iana-time-zone-haiku",
"js-sys",
"wasm-bindgen",
"windows 0.46.0",
]
[[package]]
name = "iana-time-zone-haiku"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0703ae284fc167426161c2e3f1da3ea71d94b21bedbcc9494e92b28e334e3dca"
dependencies = [
"cxx",
"cxx-build",
]
[[package]]
name = "ident_case"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
[[package]]
name = "idna"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e14ddfc70884202db2244c223200c204c2bda1bc6e0998d11b5e024d657209e6"
dependencies = [
"unicode-bidi",
"unicode-normalization",
]
[[package]]
name = "image"
version = "0.24.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69b7ea949b537b0fd0af141fff8c77690f2ce96f4f41f042ccb6c69c6c965945"
dependencies = [
"bytemuck",
"byteorder",
"color_quant",
"exr",
"gif",
"jpeg-decoder",
"num-rational",
"num-traits",
"png",
"scoped_threadpool",
"tiff",
]
[[package]]
name = "indexed_db_futures"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d26ac735f676c52305becf53264b91cea9866a8de61ccbf464405b377b9cbca9"
dependencies = [
"cfg-if",
"js-sys",
"uuid 0.8.2",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
]
[[package]]
name = "indexmap"
version = "1.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1885e79c1fc4b10f0e172c475f458b7f7b93061064d98c3293e98c5ba0c8b399"
dependencies = [
"autocfg 1.1.0",
"hashbrown",
"serde",
]
[[package]]
name = "inout"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a0c10553d664a4d0bcff9f4215d0aac67a639cc68ef660840afe309b807bc9f5"
dependencies = [
"block-padding",
"generic-array",
]
[[package]]
name = "instant"
version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c"
dependencies = [
"cfg-if",
"js-sys",
"wasm-bindgen",
"web-sys",
]
[[package]]
name = "intervaltree"
version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "270bc34e57047cab801a8c871c124d9dc7132f6473c6401f645524f4e6edd111"
dependencies = [
"smallvec",
]
[[package]]
name = "io-lifetimes"
version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09270fd4fa1111bc614ed2246c7ef56239a3063d5be0d1ec3b589c505d400aeb"
dependencies = [
"hermit-abi 0.3.2",
"libc",
"windows-sys 0.45.0",
]
[[package]]
name = "ipnet"
version = "2.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "30e22bd8629359895450b59ea7a776c850561b96a3b1d31321c1949d9e6c9146"
[[package]]
name = "is-terminal"
version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8687c819457e979cc940d09cb16e42a1bf70aa6b60a549de6d3a62a0ee90c69e"
dependencies = [
"hermit-abi 0.3.2",
"io-lifetimes",
"rustix 0.36.11",
"windows-sys 0.45.0",
]
[[package]]
name = "itertools"
version = "0.10.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473"
dependencies = [
"either",
]
[[package]]
name = "itoa"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "453ad9f582a441959e5f0d088b02ce04cfe8d51a8eaf077f12ac6d3e94164ca6"
[[package]]
name = "jpeg-decoder"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc0000e42512c92e31c2252315bda326620a4e034105e900c98ec492fa077b3e"
dependencies = [
"rayon",
]
[[package]]
name = "js-sys"
version = "0.3.61"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "445dde2150c55e483f3d8416706b97ec8e8237c307e5b7b4b8dd15e6af2a0730"
dependencies = [
"wasm-bindgen",
]
[[package]]
name = "js_int"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d937f95470b270ce8b8950207715d71aa8e153c0d44c6684d59397ed4949160a"
dependencies = [
"serde",
]
[[package]]
name = "js_option"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68421373957a1593a767013698dbf206e2b221eefe97a44d98d18672ff38423c"
dependencies = [
"serde",
]
[[package]]
name = "lazy_static"
version = "0.1.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf186d1a8aa5f5bee5fd662bc9c1b949e0259e1bcc379d1f006847b0080c7417"
[[package]]
name = "lazy_static"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
[[package]]
name = "lebe"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "03087c2bad5e1034e8cace5926dec053fb3790248370865f5117a7d0213354c8"
[[package]]
name = "libc"
version = "0.2.140"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "99227334921fae1a979cf0bfdfcc6b3e5ce376ef57e16fb6fb3ea2ed6095f80c"
[[package]]
name = "line-wrap"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f30344350a2a51da54c1d53be93fade8a237e545dbcc4bdbe635413f2117cab9"
dependencies = [
"safemem",
]
[[package]]
name = "link-cplusplus"
version = "1.0.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ecd207c9c713c34f95a097a5b029ac2ce6010530c7b49d7fea24d977dede04f5"
dependencies = [
"cc",
]
[[package]]
name = "linked-hash-map"
version = "0.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f"
[[package]]
name = "linux-raw-sys"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f051f77a7c8e6957c0696eac88f26b0117e54f52d3fc682ab19397a8812846a4"
[[package]]
name = "linux-raw-sys"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d59d8c75012853d2e872fb56bc8a2e53718e2cafe1a4c823143141c6d90c322f"
[[package]]
name = "lock_api"
version = "0.4.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "435011366fe56583b16cf956f9df0095b405b82d76425bc8981c0e22e60ec4df"
dependencies = [
"autocfg 1.1.0",
"scopeguard",
]
[[package]]
name = "log"
version = "0.4.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e"
dependencies = [
"cfg-if",
]
[[package]]
name = "lru"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6e8aaa3f231bb4bd57b84b2d5dc3ae7f350265df8aa96492e0bc394a1571909"
dependencies = [
"hashbrown",
]
[[package]]
name = "mac"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4"
[[package]]
name = "malloc_buf"
version = "0.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "62bb907fe88d54d8d9ce32a3cceab4218ed2f6b7d35617cafe9adf84e43919cb"
dependencies = [
"libc",
]
[[package]]
name = "mandown"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12243a468e9660b178540f73c43bdc544d64bd3cde749de0bd851e0dbacfd683"
dependencies = [
"deunicode 1.3.3",
"pulldown-cmark",
]
[[package]]
name = "maplit"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d"
[[package]]
name = "markup5ever"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a2629bb1404f3d34c2e921f21fd34ba00b206124c81f65c50b43b6aaefeb016"
dependencies = [
"log",
"phf 0.10.1",
"phf_codegen",
"string_cache",
"string_cache_codegen",
"tendril",
]
[[package]]
name = "markup5ever_rcdom"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9521dd6750f8e80ee6c53d65e2e4656d7de37064f3a7a5d2d11d05df93839c2"
dependencies = [
"html5ever",
"markup5ever",
"tendril",
"xml5ever",
]
[[package]]
name = "matrix-sdk"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cbeafb4809f33f377165f2fbcf10e0613053ad206762194c3050a727fd3abcb2"
dependencies = [
"anymap2",
"async-once-cell",
"async-stream",
"async-trait",
"backoff",
"bytes",
"dashmap",
"derive_builder",
"event-listener",
"futures-core",
"futures-signals",
"futures-util",
"http",
"matrix-sdk-base",
"matrix-sdk-common",
"matrix-sdk-indexeddb",
"matrix-sdk-sled",
"mime",
"reqwest",
"ruma",
"serde",
"serde_json",
"thiserror",
"tokio",
"tracing",
"url",
"wasm-timer",
"zeroize",
]
[[package]]
name = "matrix-sdk-base"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b944f6d1fc8779ba790dd0b942ceff45c626c1f5da847f01122d355ad06511bd"
dependencies = [
"async-stream",
"async-trait",
"dashmap",
"futures-channel",
"futures-core",
"futures-signals",
"futures-util",
"lru",
"matrix-sdk-common",
"matrix-sdk-crypto",
"once_cell",
"ruma",
"serde",
"serde_json",
"thiserror",
"tracing",
"zeroize",
]
[[package]]
name = "matrix-sdk-common"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b85a6a743cc9dcf9385e61a26db78276078beddd27f3762d9d82baa2030695f1"
dependencies = [
"async-lock",
"futures-core",
"futures-util",
"instant",
"ruma",
"serde",
"tokio",
"wasm-bindgen-futures",
"wasm-timer",
]
[[package]]
name = "matrix-sdk-crypto"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68fa699e8dd54578a4b92e3fcd18a50da8e415a0c042da1706b0330fc2d8f949"
dependencies = [
"aes",
"async-trait",
"atomic",
"base64 0.13.1",
"byteorder",
"ctr",
"dashmap",
"event-listener",
"futures-util",
"hmac",
"matrix-sdk-common",
"pbkdf2",
"rand 0.8.5",
"ruma",
"serde",
"serde_json",
"sha2 0.10.6",
"thiserror",
"tokio",
"tracing",
"vodozemac",
"zeroize",
]
[[package]]
name = "matrix-sdk-indexeddb"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7847d36bba832bc787214323bc042b71dca7fdf2aee9f0e3eb573b64f2f7eb7f"
dependencies = [
"anyhow",
"async-trait",
"base64 0.13.1",
"dashmap",
"derive_builder",
"getrandom 0.2.8",
"indexed_db_futures",
"js-sys",
"matrix-sdk-base",
"matrix-sdk-crypto",
"matrix-sdk-store-encryption",
"ruma",
"serde",
"serde_json",
"thiserror",
"tracing",
"wasm-bindgen",
"web-sys",
]
[[package]]
name = "matrix-sdk-sled"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ded5a703ad8a82b8edfde808228711315c8761a5fbf7ac2b98ab4951dadd066"
dependencies = [
"async-stream",
"async-trait",
"dashmap",
"derive_builder",
"fs_extra",
"futures-core",
"futures-util",
"matrix-sdk-base",
"matrix-sdk-common",
"matrix-sdk-crypto",
"matrix-sdk-store-encryption",
"ruma",
"serde",
"serde_json",
"sled",
"thiserror",
"tokio",
"tracing",
]
[[package]]
name = "matrix-sdk-store-encryption"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ddee75c3cca58f3a323283dc4e849d19d52988903f907ed0fb53dcad5d6fd25"
dependencies = [
"blake3",
"chacha20poly1305",
"displaydoc",
"hmac",
"pbkdf2",
"rand 0.8.5",
"serde",
"serde_json",
"sha2 0.10.6",
"thiserror",
"zeroize",
]
[[package]]
name = "memchr"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d"
[[package]]
name = "memoffset"
version = "0.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce"
dependencies = [
"autocfg 1.1.0",
]
[[package]]
name = "memoffset"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d61c719bcfbcf5d62b3a09efa6088de8c54bc0bfcd3ea7ae39fcc186108b8de1"
dependencies = [
"autocfg 1.1.0",
]
[[package]]
name = "mime"
version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
[[package]]
name = "mime_guess"
version = "2.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4192263c238a5f0d0c6bfd21f336a313a4ce1c450542449ca191bb657b4642ef"
dependencies = [
"mime",
"unicase",
]
[[package]]
name = "minimal-lexical"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
[[package]]
name = "miniz_oxide"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b275950c28b37e794e8c55d88aeb5e139d0ce23fdbbeda68f8d7174abdf9e8fa"
dependencies = [
"adler",
]
[[package]]
name = "mio"
version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b9d9a46eff5b4ff64b45a9e316a6d1e0bc719ef429cbec4dc630684212bfdf9"
dependencies = [
"libc",
"log",
"wasi 0.11.0+wasi-snapshot-preview1",
"windows-sys 0.45.0",
]
[[package]]
name = "modalkit"
version = "0.0.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f38eef0b4f6377e73d1082d508cae1df4d99a94d25361538131d839f292aa49"
dependencies = [
"anymap2",
"arboard",
"bitflags 1.3.2",
"crossterm 0.25.0",
"derive_more",
"intervaltree",
"libc",
"nom",
"radix_trie",
"ratatui",
"regex",
"ropey",
"serde",
"textwrap",
"thiserror",
"unicode-segmentation",
"unicode-width",
]
[[package]]
name = "nanorand"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a51313c5820b0b02bd422f4b44776fbf47961755c74ce64afc73bfad10226c3"
dependencies = [
"getrandom 0.2.8",
]
[[package]]
name = "new_debug_unreachable"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4a24736216ec316047a1fc4252e27dabb04218aa4a3f37c6e7ddbf1f9782b54"
[[package]]
name = "nibble_vec"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77a5d83df9f36fe23f0c3648c6bbb8b0298bb5f1939c8f2704431371f4b84d43"
dependencies = [
"smallvec",
]
[[package]]
name = "nix"
version = "0.24.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa52e972a9a719cecb6864fb88568781eb706bac2cd1d4f04a648542dbf78069"
dependencies = [
"bitflags 1.3.2",
"cfg-if",
"libc",
"memoffset 0.6.5",
]
[[package]]
name = "nom"
version = "7.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
dependencies = [
"memchr",
"minimal-lexical",
]
[[package]]
name = "nu-ansi-term"
version = "0.46.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77a8165726e8236064dbb45459242600304b42a5ea24ee2948e18e023bf7ba84"
dependencies = [
"overload",
"winapi",
]
[[package]]
name = "num-integer"
version = "0.1.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9"
dependencies = [
"autocfg 1.1.0",
"num-traits",
]
[[package]]
name = "num-rational"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0638a1c9d0a3c0914158145bc76cff373a75a627e6ecbfb71cbe6f453a5a19b0"
dependencies = [
"autocfg 1.1.0",
"num-integer",
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd"
dependencies = [
"autocfg 1.1.0",
]
[[package]]
name = "num_cpus"
version = "1.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fac9e2da13b5eb447a6ce3d392f23a29d8694bff781bf03a16cd9ac8697593b"
dependencies = [
"hermit-abi 0.2.6",
"libc",
]
[[package]]
name = "objc"
version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "915b1b472bc21c53464d6c8461c9d3af805ba1ef837e1cac254428f4a77177b1"
dependencies = [
"malloc_buf",
]
[[package]]
name = "objc-foundation"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1add1b659e36c9607c7aab864a76c7a4c2760cd0cd2e120f3fb8b952c7e22bf9"
dependencies = [
"block",
"objc",
"objc_id",
]
[[package]]
name = "objc_id"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c92d4ddb4bd7b50d730c215ff871754d0da6b2178849f8a2a2ab69712d0c073b"
dependencies = [
"objc",
]
[[package]]
name = "once_cell"
version = "1.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7e5500299e16ebb147ae15a00a942af264cf3688f47923b8fc2cd5858f23ad3"
[[package]]
name = "onig"
version = "6.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c4b31c8722ad9171c6d77d3557db078cab2bd50afcc9d09c8b315c59df8ca4f"
dependencies = [
"bitflags 1.3.2",
"libc",
"once_cell",
"onig_sys",
]
[[package]]
name = "onig_sys"
version = "69.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b829e3d7e9cc74c7e315ee8edb185bf4190da5acde74afd7fc59c35b1f086e7"
dependencies = [
"cc",
"pkg-config",
]
[[package]]
name = "opaque-debug"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5"
[[package]]
name = "open"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2078c0039e6a54a0c42c28faa984e115fb4c2d5bf2208f77d1961002df8576f8"
dependencies = [
"pathdiff",
"windows-sys 0.42.0",
]
[[package]]
name = "os_str_bytes"
version = "6.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ceedf44fb00f2d1984b0bc98102627ce622e083e49a5bacdb3e514fa4238e267"
[[package]]
name = "overload"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39"
[[package]]
name = "parking_lot"
version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d17b78036a60663b797adeaee46f5c9dfebb86948d1255007a1d6be0271ff99"
dependencies = [
"instant",
"lock_api",
"parking_lot_core 0.8.6",
]
[[package]]
name = "parking_lot"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f"
dependencies = [
"lock_api",
"parking_lot_core 0.9.7",
]
[[package]]
name = "parking_lot_core"
version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60a2cfe6f0ad2bfc16aefa463b497d5c7a5ecd44a23efa72aa342d90177356dc"
dependencies = [
"cfg-if",
"instant",
"libc",
"redox_syscall",
"smallvec",
"winapi",
]
[[package]]
name = "parking_lot_core"
version = "0.9.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9069cbb9f99e3a5083476ccb29ceb1de18b9118cafa53e90c9551235de2b9521"
dependencies = [
"cfg-if",
"libc",
"redox_syscall",
"smallvec",
"windows-sys 0.45.0",
]
[[package]]
name = "password-hash"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7676374caaee8a325c9e7a2ae557f216c5563a171d6997b0ef8a65af35147700"
dependencies = [
"base64ct",
"rand_core 0.6.4",
"subtle",
]
[[package]]
name = "pathdiff"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8835116a5c179084a830efb3adc117ab007512b535bc1a21c991d3b32a6b44dd"
[[package]]
name = "pbkdf2"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "83a0692ec44e4cf1ef28ca317f14f8f07da2d95ec3fa01f86e4467b725e60917"
dependencies = [
"digest 0.10.6",
"hmac",
"password-hash",
"sha2 0.10.6",
]
[[package]]
name = "percent-encoding"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "478c572c3d73181ff3c2539045f6eb99e5491218eae919370993b890cdbdd98e"
[[package]]
name = "phf"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fabbf1ead8a5bcbc20f5f8b939ee3f5b0f6f281b6ad3468b84656b658b455259"
dependencies = [
"phf_shared 0.10.0",
]
[[package]]
name = "phf"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "928c6535de93548188ef63bb7c4036bd415cd8f36ad25af44b9789b2ee72a48c"
dependencies = [
"phf_shared 0.11.1",
]
[[package]]
name = "phf_codegen"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4fb1c3a8bc4dd4e5cfce29b44ffc14bedd2ee294559a294e2a4d4c9e9a6a13cd"
dependencies = [
"phf_generator",
"phf_shared 0.10.0",
]
[[package]]
name = "phf_generator"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d5285893bb5eb82e6aaf5d59ee909a06a16737a8970984dd7746ba9283498d6"
dependencies = [
"phf_shared 0.10.0",
"rand 0.8.5",
]
[[package]]
name = "phf_shared"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6796ad771acdc0123d2a88dc428b5e38ef24456743ddb1744ed628f9815c096"
dependencies = [
"siphasher",
]
[[package]]
name = "phf_shared"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1fb5f6f826b772a8d4c0394209441e7d37cbbb967ae9c7e0e8134365c9ee676"
dependencies = [
"siphasher",
]
[[package]]
name = "pin-project"
version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad29a609b6bcd67fee905812e544992d216af9d755757c05ed2d0e15a74c6ecc"
dependencies = [
"pin-project-internal",
]
[[package]]
name = "pin-project-internal"
version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "069bdb1e05adc7a8990dce9cc75370895fbe4e3d58b9b73bf1aee56359344a55"
dependencies = [
"proc-macro2 1.0.53",
"quote 1.0.26",
"syn 1.0.109",
]
[[package]]
name = "pin-project-lite"
version = "0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116"
[[package]]
name = "pin-utils"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
[[package]]
name = "pkcs7"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f7364e6d0e236473de91e042395d71e0e64715f99a60620b014a4a4c7d1619b"
dependencies = [
"der",
"spki",
]
[[package]]
name = "pkg-config"
version = "0.3.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ac9a59f73473f1b8d852421e59e64809f025994837ef743615c6d0c5b305160"
[[package]]
name = "plist"
version = "1.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9bd9647b268a3d3e14ff09c23201133a62589c658db02bb7388c7246aafe0590"
dependencies = [
"base64 0.21.0",
"indexmap",
"line-wrap",
"quick-xml",
"serde",
"time 0.3.20",
]
[[package]]
name = "png"
version = "0.17.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d708eaf860a19b19ce538740d2b4bdeeb8337fa53f7738455e706623ad5c638"
dependencies = [
"bitflags 1.3.2",
"crc32fast",
"flate2",
"miniz_oxide",
]
[[package]]
name = "poly1305"
version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "048aeb476be11a4b6ca432ca569e375810de9294ae78f4774e78ea98a9246ede"
dependencies = [
"cpufeatures",
"opaque-debug",
"universal-hash",
]
[[package]]
name = "ppv-lite86"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de"
[[package]]
name = "precomputed-hash"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
[[package]]
name = "pretty_assertions"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af7cee1a6c8a5b9208b3cb1061f10c0cb689087b3d8ce85fb9d2dd7a29b6ba66"
dependencies = [
"diff",
"yansi",
]
[[package]]
name = "proc-macro-crate"
version = "1.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919"
dependencies = [
"once_cell",
"toml_edit",
]
[[package]]
name = "proc-macro2"
version = "0.4.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf3d2011ab5c909338f7887f4fc896d35932e29146c12c8d01da6b22a80ba759"
dependencies = [
"unicode-xid 0.1.0",
]
[[package]]
name = "proc-macro2"
version = "1.0.53"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba466839c78239c09faf015484e5cc04860f88242cff4d03eb038f04b4699b73"
dependencies = [
"unicode-ident",
]
[[package]]
name = "prost"
version = "0.11.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e48e50df39172a3e7eb17e14642445da64996989bc212b583015435d39a58537"
dependencies = [
"bytes",
"prost-derive",
]
[[package]]
name = "prost-derive"
version = "0.11.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ea9b0f8cbe5e15a8a042d030bd96668db28ecb567ec37d691971ff5731d2b1b"
dependencies = [
"anyhow",
"itertools",
"proc-macro2 1.0.53",
"quote 1.0.26",
"syn 1.0.109",
]
[[package]]
name = "pulldown-cmark"
version = "0.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77a1a2f1f0a7ecff9c31abbe177637be0e97a0aef46cf8738ece09327985d998"
dependencies = [
"bitflags 1.3.2",
"getopts",
"memchr",
"unicase",
]
[[package]]
name = "quick-xml"
version = "0.28.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5c1a97b1bc42b1d550bfb48d4262153fe400a12bab1511821736f7eac76d7e2"
dependencies = [
"memchr",
]
[[package]]
name = "quote"
version = "0.6.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce23b6b870e8f94f81fb0a363d65d86675884b34a09043c81e5562f11c1f8e1"
dependencies = [
"proc-macro2 0.4.30",
]
[[package]]
name = "quote"
version = "1.0.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4424af4bf778aae2051a77b60283332f386554255d722233d09fbfc7e30da2fc"
dependencies = [
"proc-macro2 1.0.53",
]
[[package]]
name = "radix_trie"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c069c179fcdc6a2fe24d8d18305cf085fdbd4f922c041943e203685d6a1c58fd"
dependencies = [
"endian-type",
"nibble_vec",
]
[[package]]
name = "rand"
version = "0.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6d71dacdc3c88c1fde3885a3be3fbab9f35724e6ce99467f7d9c5026132184ca"
dependencies = [
"autocfg 0.1.8",
"libc",
"rand_chacha 0.1.1",
"rand_core 0.4.2",
"rand_hc 0.1.0",
"rand_isaac",
"rand_jitter",
"rand_os",
"rand_pcg",
"rand_xorshift",
"winapi",
]
[[package]]
name = "rand"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03"
dependencies = [
"getrandom 0.1.16",
"libc",
"rand_chacha 0.2.2",
"rand_core 0.5.1",
"rand_hc 0.2.0",
]
[[package]]
name = "rand"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
dependencies = [
"libc",
"rand_chacha 0.3.1",
"rand_core 0.6.4",
]
[[package]]
name = "rand_chacha"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "556d3a1ca6600bfcbab7c7c91ccb085ac7fbbcd70e008a98742e7847f4f7bcef"
dependencies = [
"autocfg 0.1.8",
"rand_core 0.3.1",
]
[[package]]
name = "rand_chacha"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402"
dependencies = [
"ppv-lite86",
"rand_core 0.5.1",
]
[[package]]
name = "rand_chacha"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
dependencies = [
"ppv-lite86",
"rand_core 0.6.4",
]
[[package]]
name = "rand_core"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b"
dependencies = [
"rand_core 0.4.2",
]
[[package]]
name = "rand_core"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c33a3c44ca05fa6f1807d8e6743f3824e8509beca625669633be0acbdf509dc"
[[package]]
name = "rand_core"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19"
dependencies = [
"getrandom 0.1.16",
]
[[package]]
name = "rand_core"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
dependencies = [
"getrandom 0.2.8",
]
[[package]]
name = "rand_hc"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b40677c7be09ae76218dc623efbf7b18e34bced3f38883af07bb75630a21bc4"
dependencies = [
"rand_core 0.3.1",
]
[[package]]
name = "rand_hc"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c"
dependencies = [
"rand_core 0.5.1",
]
[[package]]
name = "rand_isaac"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ded997c9d5f13925be2a6fd7e66bf1872597f759fd9dd93513dd7e92e5a5ee08"
dependencies = [
"rand_core 0.3.1",
]
[[package]]
name = "rand_jitter"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1166d5c91dc97b88d1decc3285bb0a99ed84b05cfd0bc2341bdf2d43fc41e39b"
dependencies = [
"libc",
"rand_core 0.4.2",
"winapi",
]
[[package]]
name = "rand_os"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b75f676a1e053fc562eafbb47838d67c84801e38fc1ba459e8f180deabd5071"
dependencies = [
"cloudabi",
"fuchsia-cprng",
"libc",
"rand_core 0.4.2",
"rdrand",
"winapi",
]
[[package]]
name = "rand_pcg"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "abf9b09b01790cfe0364f52bf32995ea3c39f4d2dd011eac241d2914146d0b44"
dependencies = [
"autocfg 0.1.8",
"rand_core 0.4.2",
]
[[package]]
name = "rand_xorshift"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cbf7e9e623549b0e21f6e97cf8ecf247c1a8fd2e8a992ae265314300b2455d5c"
dependencies = [
"rand_core 0.3.1",
]
[[package]]
name = "ratatui"
version = "0.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dcc0d032bccba900ee32151ec0265667535c230169f5a011154cdcd984e16829"
dependencies = [
"bitflags 1.3.2",
"cassowary",
"crossterm 0.26.1",
"unicode-segmentation",
"unicode-width",
]
[[package]]
name = "rayon"
version = "1.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d2df5196e37bcc87abebc0053e20787d73847bb33134a69841207dd0a47f03b"
dependencies = [
"either",
"rayon-core",
]
[[package]]
name = "rayon-core"
version = "1.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b8f95bd6966f5c87776639160a66bd8ab9895d9d4ab01ddba9fc60661aebe8d"
dependencies = [
"crossbeam-channel",
"crossbeam-deque",
"crossbeam-utils",
"num_cpus",
]
[[package]]
name = "rdrand"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "678054eb77286b51581ba43620cc911abf02758c91f93f479767aed0f90458b2"
dependencies = [
"rand_core 0.3.1",
]
[[package]]
name = "redox_syscall"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a"
dependencies = [
"bitflags 1.3.2",
]
[[package]]
name = "redox_users"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b033d837a7cf162d7993aded9304e30a83213c648b6e389db233191f891e5c2b"
dependencies = [
"getrandom 0.2.8",
"redox_syscall",
"thiserror",
]
[[package]]
name = "regex"
version = "1.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cce168fea28d3e05f158bda4576cf0c844d5045bc2cc3620fa0292ed5bb5814c"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.6.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1"
[[package]]
name = "reqwest"
version = "0.11.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ba30cc2c0cd02af1222ed216ba659cdb2f879dfe3181852fe7c50b1d0005949"
dependencies = [
"base64 0.21.0",
"bytes",
"encoding_rs",
"futures-core",
"futures-util",
"h2",
"http",
"http-body",
"hyper",
"hyper-rustls",
"ipnet",
"js-sys",
"log",
"mime",
"once_cell",
"percent-encoding",
"pin-project-lite",
"rustls",
"rustls-pemfile",
"serde",
"serde_json",
"serde_urlencoded",
"tokio",
"tokio-rustls",
"tower-service",
"url",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"webpki-roots",
"winreg",
]
[[package]]
name = "ring"
version = "0.16.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3053cf52e236a3ed746dfc745aa9cacf1b791d846bdaf412f60a8d7d6e17c8fc"
dependencies = [
"cc",
"libc",
"once_cell",
"spin 0.5.2",
"untrusted",
"web-sys",
"winapi",
]
[[package]]
name = "ropey"
version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53ce7a2c43a32e50d666e33c5a80251b31147bb4b49024bcab11fb6f20c671ed"
dependencies = [
"smallvec",
"str_indices",
]
[[package]]
name = "rpassword"
version = "7.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6678cf63ab3491898c0d021b493c94c9b221d91295294a2a5746eacbe5928322"
dependencies = [
"libc",
"rtoolbox",
"winapi",
]
[[package]]
name = "rtoolbox"
version = "0.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "034e22c514f5c0cb8a10ff341b9b048b5ceb21591f31c8f44c43b960f9b3524a"
dependencies = [
"libc",
"winapi",
]
[[package]]
name = "ruma"
version = "0.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8dc348e3a4a18abc4e97fffa5e2e623f6edd50ba3a1dd5f47eb249fea713b69f"
dependencies = [
"assign",
"js_int",
"js_option",
"ruma-client-api",
"ruma-common",
"ruma-federation-api",
]
[[package]]
name = "ruma-client-api"
version = "0.15.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d1e72bc731b4dc8b569aa83915f13e419144b67110d858c65bb74aa05e2dc4b7"
dependencies = [
"assign",
"bytes",
"http",
"js_int",
"maplit",
"percent-encoding",
"ruma-common",
"serde",
"serde_json",
]
[[package]]
name = "ruma-common"
version = "0.10.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "716889595f4edc3cfeb94d9f122e413f73e37d7d80ea1c14196e1004241a3889"
dependencies = [
"base64 0.13.1",
"bytes",
"form_urlencoded",
"getrandom 0.2.8",
"http",
"indexmap",
"itoa",
"js-sys",
"js_int",
"js_option",
"percent-encoding",
"rand 0.8.5",
"regex",
"ruma-identifiers-validation",
"ruma-macros",
"serde",
"serde_json",
"thiserror",
"tracing",
"url",
"uuid 1.3.0",
"wildmatch",
]
[[package]]
name = "ruma-federation-api"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f905d12f6144c7a754bd0339fa6893698c03d03a908abb20cc6eeb4ec7f9466"
dependencies = [
"js_int",
"ruma-common",
"serde",
"serde_json",
]
[[package]]
name = "ruma-identifiers-validation"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebefdab34311af44d07cd2cd91c36cfe6a8c770647c6b00f6ab47f1186b2bb72"
dependencies = [
"js_int",
"thiserror",
]
[[package]]
name = "ruma-macros"
version = "0.10.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f82e91eb61cd86d9287303133ee55b54618eccb75a522cc22a42c15f5bda340"
dependencies = [
"once_cell",
"proc-macro-crate",
"proc-macro2 1.0.53",
"quote 1.0.26",
"ruma-identifiers-validation",
"serde",
"syn 1.0.109",
"toml",
]
[[package]]
name = "rustc_version"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366"
dependencies = [
"semver",
]
[[package]]
name = "rustix"
version = "0.36.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db4165c9963ab29e422d6c26fbc1d37f15bace6b2810221f9d925023480fcf0e"
dependencies = [
"bitflags 1.3.2",
"errno 0.2.8",
"io-lifetimes",
"libc",
"linux-raw-sys 0.1.4",
"windows-sys 0.45.0",
]
[[package]]
name = "rustix"
version = "0.37.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2aae838e49b3d63e9274e1c01833cc8139d3fec468c3b84688c628f44b1ae11d"
dependencies = [
"bitflags 1.3.2",
"errno 0.3.0",
"io-lifetimes",
"libc",
"linux-raw-sys 0.3.1",
"windows-sys 0.45.0",
]
[[package]]
name = "rustls"
version = "0.20.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fff78fc74d175294f4e83b28343315ffcfb114b156f0185e9741cb5570f50e2f"
dependencies = [
"log",
"ring",
"sct",
"webpki",
]
[[package]]
name = "rustls-pemfile"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d194b56d58803a43635bdc398cd17e383d6f71f9182b9a192c127ca42494a59b"
dependencies = [
"base64 0.21.0",
]
[[package]]
name = "rustversion"
version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f3208ce4d8448b3f3e7d168a73f5e0c43a61e32930de3bceeccedb388b6bf06"
[[package]]
name = "ryu"
version = "1.0.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f91339c0467de62360649f8d3e185ca8de4224ff281f66000de5eb2a77a79041"
[[package]]
name = "safemem"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef703b7cb59335eae2eb93ceb664c0eb7ea6bf567079d843e09420219668e072"
[[package]]
name = "same-file"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
dependencies = [
"winapi-util",
]
[[package]]
name = "scoped_threadpool"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d51f5df5af43ab3f1360b429fa5e0152ac5ce8c0bd6485cae490332e96846a8"
[[package]]
name = "scopeguard"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd"
[[package]]
name = "scratch"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1792db035ce95be60c3f8853017b3999209281c24e2ba5bc8e59bf97a0c590c1"
[[package]]
name = "sct"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d53dcdb7c9f8158937a7981b48accfd39a43af418591a5d008c7b22b5e1b7ca4"
dependencies = [
"ring",
"untrusted",
]
[[package]]
name = "semver"
version = "1.0.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bebd363326d05ec3e2f532ab7660680f3b02130d780c299bca73469d521bc0ed"
[[package]]
name = "serde"
version = "1.0.158"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "771d4d9c4163ee138805e12c710dd365e4f44be8be0503cb1bb9eb989425d9c9"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_bytes"
version = "0.11.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "416bda436f9aab92e02c8e10d49a15ddd339cea90b6e340fe51ed97abb548294"
dependencies = [
"serde",
]
[[package]]
name = "serde_derive"
version = "1.0.158"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e801c1712f48475582b7696ac71e0ca34ebb30e09338425384269d9717c62cad"
dependencies = [
"proc-macro2 1.0.53",
"quote 1.0.26",
"syn 2.0.8",
]
[[package]]
name = "serde_json"
version = "1.0.94"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c533a59c9d8a93a09c6ab31f0fd5e5f4dd1b8fc9434804029839884765d04ea"
dependencies = [
"itoa",
"ryu",
"serde",
]
[[package]]
name = "serde_urlencoded"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
dependencies = [
"form_urlencoded",
"itoa",
"ryu",
"serde",
]
[[package]]
name = "sha2"
version = "0.9.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4d58a1e1bf39749807d89cf2d98ac2dfa0ff1cb3faa38fbb64dd88ac8013d800"
dependencies = [
"block-buffer 0.9.0",
"cfg-if",
"cpufeatures",
"digest 0.9.0",
"opaque-debug",
]
[[package]]
name = "sha2"
version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "82e6b795fe2e3b1e845bafcb27aa35405c4d47cdfc92af5fc8d3002f76cebdc0"
dependencies = [
"cfg-if",
"cpufeatures",
"digest 0.10.6",
]
[[package]]
name = "sharded-slab"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "900fba806f70c630b0a382d0d825e17a0f19fcd059a2ade1ff237bcddf446b31"
dependencies = [
"lazy_static 1.4.0",
]
[[package]]
name = "shell-words"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24188a676b6ae68c3b2cb3a01be17fbf7240ce009799bb56d5b1409051e78fde"
[[package]]
name = "signal-hook"
version = "0.3.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "732768f1176d21d09e076c23a93123d40bba92d50c4058da34d45c8de8e682b9"
dependencies = [
"libc",
"signal-hook-registry",
]
[[package]]
name = "signal-hook-mio"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29ad2e15f37ec9a6cc544097b78a1ec90001e9f71b81338ca39f430adaca99af"
dependencies = [
"libc",
"mio",
"signal-hook",
]
[[package]]
name = "signal-hook-registry"
version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8229b473baa5980ac72ef434c4415e70c4b5e71b423043adb4ba059f89c99a1"
dependencies = [
"libc",
]
[[package]]
name = "signature"
version = "1.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "74233d3b3b2f6d4b006dc19dee745e73e2a6bfb6f93607cd3b02bd5b00797d7c"
[[package]]
name = "simd-adler32"
version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "238abfbb77c1915110ad968465608b68e869e0772622c9656714e73e5a1a522f"
[[package]]
name = "siphasher"
version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7bd3e3206899af3f8b12af284fafc038cc1dc2b41d1b89dd17297221c5d225de"
[[package]]
name = "slab"
version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6528351c9bc8ab22353f9d776db39a20288e8d6c37ef8cfe3317cf875eecfc2d"
dependencies = [
"autocfg 1.1.0",
]
[[package]]
name = "sled"
version = "0.34.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f96b4737c2ce5987354855aed3797279def4ebf734436c6aa4552cf8e169935"
dependencies = [
"crc32fast",
"crossbeam-epoch",
"crossbeam-utils",
"fs2",
"fxhash",
"libc",
"log",
"parking_lot 0.11.2",
]
[[package]]
name = "slug"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b3bc762e6a4b6c6fcaade73e77f9ebc6991b676f88bb2358bddb56560f073373"
dependencies = [
"deunicode 0.4.3",
]
[[package]]
name = "smallvec"
version = "1.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0"
[[package]]
name = "smawk"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f67ad224767faa3c7d8b6d91985b78e70a1324408abcb1cfcc2be4c06bc06043"
[[package]]
name = "socket2"
version = "0.4.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "64a4a911eed85daf18834cfaa86a79b7d266ff93ff5ba14005426219480ed662"
dependencies = [
"libc",
"winapi",
]
[[package]]
name = "spin"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d"
[[package]]
name = "spin"
version = "0.9.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67"
dependencies = [
"lock_api",
]
[[package]]
name = "spki"
version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44d01ac02a6ccf3e07db148d2be087da624fea0221a16152ed01f0496a6b0a27"
dependencies = [
"der",
]
[[package]]
name = "str-buf"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e08d8363704e6c71fc928674353e6b7c23dcea9d82d7012c8faf2a3a025f8d0"
[[package]]
name = "str_indices"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f026164926842ec52deb1938fae44f83dfdb82d0a5b0270c5bd5935ab74d6dd"
[[package]]
name = "string_cache"
version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f91138e76242f575eb1d3b38b4f1362f10d3a43f47d182a5b359af488a02293b"
dependencies = [
"new_debug_unreachable",
"once_cell",
"parking_lot 0.12.1",
"phf_shared 0.10.0",
"precomputed-hash",
"serde",
]
[[package]]
name = "string_cache_codegen"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6bb30289b722be4ff74a408c3cc27edeaad656e06cb1fe8fa9231fa59c728988"
dependencies = [
"phf_generator",
"phf_shared 0.10.0",
"proc-macro2 1.0.53",
"quote 1.0.26",
]
[[package]]
name = "strsim"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
[[package]]
name = "subtle"
version = "2.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6bdef32e8150c2a081110b42772ffe7d7c9032b606bc226c8260fd97e0976601"
[[package]]
name = "syn"
version = "0.15.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ca4b3b69a77cbe1ffc9e198781b7acb0c7365a883670e8f1c1bc66fba79a5c5"
dependencies = [
"proc-macro2 0.4.30",
"quote 0.6.13",
"unicode-xid 0.1.0",
]
[[package]]
name = "syn"
version = "1.0.109"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
dependencies = [
"proc-macro2 1.0.53",
"quote 1.0.26",
"unicode-ident",
]
[[package]]
name = "syn"
version = "2.0.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bcc02725fd69ab9f26eab07fad303e2497fad6fb9eba4f96c4d1687bdf704ad9"
dependencies = [
"proc-macro2 1.0.53",
"quote 1.0.26",
"unicode-ident",
]
[[package]]
name = "synstructure"
version = "0.12.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f36bdaa60a83aca3921b5259d5400cbf5e90fc51931376a9bd4a0eb79aa7210f"
dependencies = [
"proc-macro2 1.0.53",
"quote 1.0.26",
"syn 1.0.109",
"unicode-xid 0.2.4",
]
[[package]]
name = "syntect"
version = "5.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6c454c27d9d7d9a84c7803aaa3c50cd088d2906fe3c6e42da3209aa623576a8"
dependencies = [
"bincode",
"bitflags 1.3.2",
"fancy-regex",
"flate2",
"fnv",
"lazy_static 1.4.0",
"once_cell",
"onig",
"plist",
"regex-syntax",
"serde",
"serde_derive",
"serde_json",
"thiserror",
"walkdir",
"yaml-rust",
]
[[package]]
name = "tendril"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d24a120c5fc464a3458240ee02c299ebcb9d67b5249c8848b09d639dca8d7bb0"
dependencies = [
"futf",
"mac",
"utf-8",
]
[[package]]
name = "termcolor"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be55cf8942feac5c765c2c993422806843c9a9a45d4d5c407ad6dd2ea95eb9b6"
dependencies = [
"winapi-util",
]
[[package]]
name = "terminal_size"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e6bf6f19e9f8ed8d4048dc22981458ebcf406d67e94cd422e5ecd73d63b3237"
dependencies = [
"rustix 0.37.7",
"windows-sys 0.48.0",
]
[[package]]
name = "textwrap"
version = "0.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "222a222a5bfe1bba4a77b45ec488a741b3cb8872e5e499451fd7d0129c9c7c3d"
dependencies = [
"smawk",
"unicode-linebreak",
"unicode-width",
]
[[package]]
name = "thiserror"
version = "1.0.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "978c9a314bd8dc99be594bc3c175faaa9794be04a5a5e153caba6915336cebac"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9456a42c5b0d803c8cd86e73dd7cc9edd429499f37a3550d286d5e86720569f"
dependencies = [
"proc-macro2 1.0.53",
"quote 1.0.26",
"syn 2.0.8",
]
[[package]]
name = "thread_local"
version = "1.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3fdd6f064ccff2d6567adcb3873ca630700f00b5ad3f060c25b5dcfd9a4ce152"
dependencies = [
"cfg-if",
"once_cell",
]
[[package]]
name = "tiff"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7449334f9ff2baf290d55d73983a7d6fa15e01198faef72af07e2a8db851e471"
dependencies = [
"flate2",
"jpeg-decoder",
"weezl",
]
[[package]]
name = "time"
version = "0.1.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b797afad3f312d1c66a56d11d0316f916356d11bd158fbc6ca6389ff6bf805a"
dependencies = [
"libc",
"wasi 0.10.0+wasi-snapshot-preview1",
"winapi",
]
[[package]]
name = "time"
version = "0.3.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd0cbfecb4d19b5ea75bb31ad904eb5b9fa13f21079c3b92017ebdf4999a5890"
dependencies = [
"itoa",
"serde",
"time-core",
"time-macros",
]
[[package]]
name = "time-core"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e153e1f1acaef8acc537e68b44906d2db6436e2b35ac2c6b42640fff91f00fd"
[[package]]
name = "time-macros"
version = "0.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd80a657e71da814b8e5d60d3374fc6d35045062245d80224748ae522dd76f36"
dependencies = [
"time-core",
]
[[package]]
name = "tinyvec"
version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50"
dependencies = [
"tinyvec_macros",
]
[[package]]
name = "tinyvec_macros"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]]
name = "tokio"
version = "1.26.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "03201d01c3c27a29c8a5cee5b55a93ddae1ccf6f08f65365c2c918f8c1b76f64"
dependencies = [
"autocfg 1.1.0",
"bytes",
"libc",
"memchr",
"mio",
"num_cpus",
"pin-project-lite",
"socket2",
"tokio-macros",
"windows-sys 0.45.0",
]
[[package]]
name = "tokio-macros"
version = "1.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d266c00fde287f55d3f1c3e96c500c362a2b8c695076ec180f27918820bc6df8"
dependencies = [
"proc-macro2 1.0.53",
"quote 1.0.26",
"syn 1.0.109",
]
[[package]]
name = "tokio-rustls"
version = "0.23.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c43ee83903113e03984cb9e5cebe6c04a5116269e900e3ddba8f068a62adda59"
dependencies = [
"rustls",
"tokio",
"webpki",
]
[[package]]
name = "tokio-util"
version = "0.7.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5427d89453009325de0d8f342c9490009f76e999cb7672d77e46267448f7e6b2"
dependencies = [
"bytes",
"futures-core",
"futures-sink",
"pin-project-lite",
"tokio",
"tracing",
]
[[package]]
name = "toml"
version = "0.5.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f4f7f0dd8d50a853a531c426359045b1998f04219d88799810762cd4ad314234"
dependencies = [
"serde",
]
[[package]]
name = "toml_datetime"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ab8ed2edee10b50132aed5f331333428b011c99402b5a534154ed15746f9622"
[[package]]
name = "toml_edit"
version = "0.19.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "239410c8609e8125456927e6707163a3b1fdb40561e4b803bc041f466ccfdc13"
dependencies = [
"indexmap",
"toml_datetime",
"winnow",
]
[[package]]
name = "tower-service"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6bc1c9ce2b5135ac7f93c72918fc37feb872bdc6a5533a8b85eb4b86bfdae52"
[[package]]
name = "tracing"
version = "0.1.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ce8c33a8d48bd45d624a6e523445fd21ec13d3653cd51f681abf67418f54eb8"
dependencies = [
"cfg-if",
"pin-project-lite",
"tracing-attributes",
"tracing-core",
]
[[package]]
name = "tracing-appender"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09d48f71a791638519505cefafe162606f706c25592e4bde4d97600c0195312e"
dependencies = [
"crossbeam-channel",
"time 0.3.20",
"tracing-subscriber",
]
[[package]]
name = "tracing-attributes"
version = "0.1.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4017f8f45139870ca7e672686113917c71c7a6e02d4924eda67186083c03081a"
dependencies = [
"proc-macro2 1.0.53",
"quote 1.0.26",
"syn 1.0.109",
]
[[package]]
name = "tracing-core"
version = "0.1.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24eb03ba0eab1fd845050058ce5e616558e8f8d8fca633e6b163fe25c797213a"
dependencies = [
"once_cell",
"valuable",
]
[[package]]
name = "tracing-log"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78ddad33d2d10b1ed7eb9d1f518a5674713876e97e5bb9b7345a7984fbb4f922"
dependencies = [
"lazy_static 1.4.0",
"log",
"tracing-core",
]
[[package]]
name = "tracing-subscriber"
version = "0.3.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6176eae26dd70d0c919749377897b54a9276bd7061339665dd68777926b5a70"
dependencies = [
"nu-ansi-term",
"sharded-slab",
"smallvec",
"thread_local",
"tracing-core",
"tracing-log",
]
[[package]]
name = "try-lock"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3528ecfd12c466c6f163363caf2d02a71161dd5e1cc6ae7b34207ea2d42d81ed"
[[package]]
name = "typed-arena"
version = "2.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6af6ae20167a9ece4bcb41af5b80f8a1f1df981f6391189ce00fd257af04126a"
[[package]]
name = "typenum"
version = "1.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "497961ef93d974e23eb6f433eb5fe1b7930b659f06d12dec6fc44a8f554c0bba"
[[package]]
name = "unicase"
version = "2.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50f37be617794602aabbeee0be4f259dc1778fabe05e2d67ee8f79326d5cb4f6"
dependencies = [
"version_check",
]
[[package]]
name = "unicode-bidi"
version = "0.3.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92888ba5573ff080736b3648696b70cafad7d250551175acbaa4e0385b3e1460"
[[package]]
name = "unicode-ident"
version = "1.0.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5464a87b239f13a63a501f2701565754bae92d243d4bb7eb12f6d57d2269bf4"
[[package]]
name = "unicode-linebreak"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c5faade31a542b8b35855fff6e8def199853b2da8da256da52f52f1316ee3137"
dependencies = [
"hashbrown",
"regex",
]
[[package]]
name = "unicode-normalization"
version = "0.1.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c5713f0fc4b5db668a2ac63cdb7bb4469d8c9fed047b1d0292cc7b0ce2ba921"
dependencies = [
"tinyvec",
]
[[package]]
name = "unicode-segmentation"
version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1dd624098567895118886609431a7c3b8f516e41d30e0643f03d94592a147e36"
[[package]]
name = "unicode-width"
version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0edd1e5b14653f783770bce4a4dabb4a5108a5370a5f5d8cfe8710c361f6c8b"
[[package]]
name = "unicode-xid"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc"
[[package]]
name = "unicode-xid"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f962df74c8c05a667b5ee8bcf162993134c104e96440b663c8daa176dc772d8c"
[[package]]
name = "unicode_categories"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e"
[[package]]
name = "universal-hash"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f214e8f697e925001e66ec2c6e37a4ef93f0f78c2eed7814394e10c62025b05"
dependencies = [
"generic-array",
"subtle",
]
[[package]]
name = "untrusted"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a"
[[package]]
name = "url"
version = "2.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d68c799ae75762b8c3fe375feb6600ef5602c883c5d21eb51c09f22b83c4643"
dependencies = [
"form_urlencoded",
"idna",
"percent-encoding",
"serde",
]
[[package]]
name = "utf-8"
version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"
[[package]]
name = "uuid"
version = "0.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90dbc611eb48397705a6b0f6e917da23ae517e4d127123d2cf7674206627d32a"
dependencies = [
"rand 0.6.5",
]
[[package]]
name = "uuid"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc5cf98d8186244414c848017f0e2676b3fcb46807f6668a97dfe67359a3c4b7"
dependencies = [
"getrandom 0.2.8",
]
[[package]]
name = "uuid"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1674845326ee10d37ca60470760d4288a6f80f304007d92e5c53bab78c9cfd79"
dependencies = [
"getrandom 0.2.8",
"wasm-bindgen",
]
[[package]]
name = "valuable"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "830b7e5d4d90034032940e4ace0d9a9a057e7a45cd94e6c007832e39edb82f6d"
[[package]]
name = "vergen"
version = "8.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b3c89c2c7e50f33e4d35527e5bf9c11d6d132226dbbd1753f0fbe9f19ef88c6"
dependencies = [
"anyhow",
"rustversion",
"time 0.3.20",
]
[[package]]
name = "version_check"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
[[package]]
name = "vodozemac"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6f20153a1c82ac5f1243b62e80f067ae608facc415c6ef82f88426a61c79886"
dependencies = [
"aes",
"arrayvec",
"base64 0.13.1",
"cbc",
"ed25519-dalek",
"hkdf",
"hmac",
"pkcs7",
"prost",
"rand 0.7.3",
"serde",
"serde_json",
"sha2 0.10.6",
"subtle",
"thiserror",
"x25519-dalek",
"zeroize",
]
[[package]]
name = "walkdir"
version = "2.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "36df944cda56c7d8d8b7496af378e6b16de9284591917d307c9b4d313c44e698"
dependencies = [
"same-file",
"winapi-util",
]
[[package]]
name = "want"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ce8a968cb1cd110d136ff8b819a556d6fb6d919363c61534f6860c7eb172ba0"
dependencies = [
"log",
"try-lock",
]
[[package]]
name = "wasi"
version = "0.9.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519"
[[package]]
name = "wasi"
version = "0.10.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f"
[[package]]
name = "wasi"
version = "0.11.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]
name = "wasm-bindgen"
version = "0.2.84"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "31f8dcbc21f30d9b8f2ea926ecb58f6b91192c17e9d33594b3df58b2007ca53b"
dependencies = [
"cfg-if",
"serde",
"serde_json",
"wasm-bindgen-macro",
]
[[package]]
name = "wasm-bindgen-backend"
version = "0.2.84"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95ce90fd5bcc06af55a641a86428ee4229e44e07033963a2290a8e241607ccb9"
dependencies = [
"bumpalo",
"log",
"once_cell",
"proc-macro2 1.0.53",
"quote 1.0.26",
"syn 1.0.109",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-futures"
version = "0.4.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f219e0d211ba40266969f6dbdd90636da12f75bee4fc9d6c23d1260dadb51454"
dependencies = [
"cfg-if",
"js-sys",
"wasm-bindgen",
"web-sys",
]
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.84"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c21f77c0bedc37fd5dc21f897894a5ca01e7bb159884559461862ae90c0b4c5"
dependencies = [
"quote 1.0.26",
"wasm-bindgen-macro-support",
]
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.84"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2aff81306fcac3c7515ad4e177f521b5c9a15f2b08f4e32d823066102f35a5f6"
dependencies = [
"proc-macro2 1.0.53",
"quote 1.0.26",
"syn 1.0.109",
"wasm-bindgen-backend",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.84"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0046fef7e28c3804e5e38bfa31ea2a0f73905319b677e57ebe37e49358989b5d"
[[package]]
name = "wasm-timer"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be0ecb0db480561e9a7642b5d3e4187c128914e58aa84330b9493e3eb68c5e7f"
dependencies = [
"futures",
"js-sys",
"parking_lot 0.11.2",
"pin-utils",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
]
[[package]]
name = "web-sys"
version = "0.3.61"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e33b99f4b23ba3eec1a53ac264e35a755f00e966e0065077d6027c0f575b0b97"
dependencies = [
"js-sys",
"wasm-bindgen",
]
[[package]]
name = "webpki"
version = "0.22.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f095d78192e208183081cc07bc5515ef55216397af48b873e5edcd72637fa1bd"
dependencies = [
"ring",
"untrusted",
]
[[package]]
name = "webpki-roots"
version = "0.22.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6c71e40d7d2c34a5106301fb632274ca37242cd0c9d3e64dbece371a40a2d87"
dependencies = [
"webpki",
]
[[package]]
name = "weezl"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9193164d4de03a926d909d3bc7c30543cecb35400c02114792c2cae20d5e2dbb"
[[package]]
name = "wildmatch"
version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee583bdc5ff1cf9db20e9db5bb3ff4c3089a8f6b8b31aff265c9aba85812db86"
[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
dependencies = [
"winapi-i686-pc-windows-gnu",
"winapi-x86_64-pc-windows-gnu",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-util"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178"
dependencies = [
"winapi",
]
[[package]]
name = "winapi-wsapoll"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44c17110f57155602a80dca10be03852116403c9ff3cd25b079d666f2aa3df6e"
dependencies = [
"winapi",
]
[[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"
version = "0.43.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04662ed0e3e5630dfa9b26e4cb823b817f1a9addda855d973a9458c236556244"
dependencies = [
"windows_aarch64_gnullvm 0.42.2",
"windows_aarch64_msvc 0.42.2",
"windows_i686_gnu 0.42.2",
"windows_i686_msvc 0.42.2",
"windows_x86_64_gnu 0.42.2",
"windows_x86_64_gnullvm 0.42.2",
"windows_x86_64_msvc 0.42.2",
]
[[package]]
name = "windows"
version = "0.46.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdacb41e6a96a052c6cb63a144f24900236121c6f63f4f8219fef5977ecb0c25"
dependencies = [
"windows-targets 0.42.2",
]
[[package]]
name = "windows-sys"
version = "0.42.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7"
dependencies = [
"windows_aarch64_gnullvm 0.42.2",
"windows_aarch64_msvc 0.42.2",
"windows_i686_gnu 0.42.2",
"windows_i686_msvc 0.42.2",
"windows_x86_64_gnu 0.42.2",
"windows_x86_64_gnullvm 0.42.2",
"windows_x86_64_msvc 0.42.2",
]
[[package]]
name = "windows-sys"
version = "0.45.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0"
dependencies = [
"windows-targets 0.42.2",
]
[[package]]
name = "windows-sys"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
dependencies = [
"windows-targets 0.48.0",
]
[[package]]
name = "windows-targets"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071"
dependencies = [
"windows_aarch64_gnullvm 0.42.2",
"windows_aarch64_msvc 0.42.2",
"windows_i686_gnu 0.42.2",
"windows_i686_msvc 0.42.2",
"windows_x86_64_gnu 0.42.2",
"windows_x86_64_gnullvm 0.42.2",
"windows_x86_64_msvc 0.42.2",
]
[[package]]
name = "windows-targets"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b1eb6f0cd7c80c79759c929114ef071b87354ce476d9d94271031c0497adfd5"
dependencies = [
"windows_aarch64_gnullvm 0.48.0",
"windows_aarch64_msvc 0.48.0",
"windows_i686_gnu 0.48.0",
"windows_i686_msvc 0.48.0",
"windows_x86_64_gnu 0.48.0",
"windows_x86_64_gnullvm 0.48.0",
"windows_x86_64_msvc 0.48.0",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91ae572e1b79dba883e0d315474df7305d12f569b400fcf90581b06062f7e1bc"
[[package]]
name = "windows_aarch64_msvc"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"
[[package]]
name = "windows_aarch64_msvc"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b2ef27e0d7bdfcfc7b868b317c1d32c641a6fe4629c171b8928c7b08d98d7cf3"
[[package]]
name = "windows_i686_gnu"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"
[[package]]
name = "windows_i686_gnu"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "622a1962a7db830d6fd0a69683c80a18fda201879f0f447f065a3b7467daa241"
[[package]]
name = "windows_i686_msvc"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"
[[package]]
name = "windows_i686_msvc"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4542c6e364ce21bf45d69fdd2a8e455fa38d316158cfd43b3ac1c5b1b19f8e00"
[[package]]
name = "windows_x86_64_gnu"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36"
[[package]]
name = "windows_x86_64_gnu"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca2b8a661f7628cbd23440e50b05d705db3686f894fc9580820623656af974b1"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7896dbc1f41e08872e9d5e8f8baa8fdd2677f29468c4e156210174edc7f7b953"
[[package]]
name = "windows_x86_64_msvc"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"
[[package]]
name = "windows_x86_64_msvc"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a"
[[package]]
name = "winnow"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "deac0939bd6e4f24ab5919fbf751c97a8cfc8543bb083a305ed5c0c10bb241d1"
dependencies = [
"memchr",
]
[[package]]
name = "winreg"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d"
dependencies = [
"winapi",
]
[[package]]
name = "x11rb"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "592b4883219f345e712b3209c62654ebda0bb50887f330cbd018d0f654bfd507"
dependencies = [
"gethostname 0.2.3",
"nix",
"winapi",
"winapi-wsapoll",
"x11rb-protocol",
]
[[package]]
name = "x11rb-protocol"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56b245751c0ac9db0e006dc812031482784e434630205a93c73cfefcaabeac67"
dependencies = [
"nix",
]
[[package]]
name = "x25519-dalek"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2392b6b94a576b4e2bf3c5b2757d63f10ada8020a2e4d08ac849ebcf6ea8e077"
dependencies = [
"curve25519-dalek",
"rand_core 0.5.1",
"serde",
"zeroize",
]
[[package]]
name = "xdg"
version = "2.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c4583db5cbd4c4c0303df2d15af80f0539db703fa1c68802d4cbbd2dd0f88f6"
dependencies = [
"dirs",
]
[[package]]
name = "xml5ever"
version = "0.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4034e1d05af98b51ad7214527730626f019682d797ba38b51689212118d8e650"
dependencies = [
"log",
"mac",
"markup5ever",
]
[[package]]
name = "yaml-rust"
version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85"
dependencies = [
"linked-hash-map",
]
[[package]]
name = "yansi"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09041cd90cf85f7f8b2df60c646f853b7f535ce68f85244eb6731cf89fa498ec"
[[package]]
name = "zeroize"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4756f7db3f7b5574938c3eb1c117038b8e07f95ee6718c0efad4ac21508f1efd"
dependencies = [
"zeroize_derive",
]
[[package]]
name = "zeroize_derive"
version = "1.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44bf07cb3e50ea2003396695d58bf46bc9887a1f362260446fad6bc4e79bd36c"
dependencies = [
"proc-macro2 1.0.53",
"quote 1.0.26",
"syn 1.0.109",
"synstructure",
]
[[package]]
name = "zune-inflate"
version = "0.2.54"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02"
dependencies = [
"simd-adler32",
]
07070100000009000081A400000000000000000000000164A9007B0000067B000000000000000000000000000000000000001600000000iamb-0.0.8/Cargo.toml[package]
name = "iamb"
version = "0.0.8"
edition = "2018"
authors = ["Ulyssa <git@ulyssa.dev>"]
repository = "https://github.com/ulyssa/iamb"
homepage = "https://iamb.chat"
readme = "README.md"
description = "A Matrix chat client that uses Vim keybindings"
license = "Apache-2.0"
exclude = [".github", "CONTRIBUTING.md"]
keywords = ["matrix", "chat", "tui", "vim"]
categories = ["command-line-utilities"]
rust-version = "1.66"
build = "build.rs"
[build-dependencies]
mandown = "0.1.3"
[build-dependencies.vergen]
version = "8"
default-features = false
features = ["build", "git", "gitcl",]
[dependencies]
arboard = "3.2.0"
bitflags = "1.3.2"
chrono = "0.4"
clap = {version = "4.0", features = ["derive"]}
comrak = {version = "0.18.0", features = ["shortcodes"]}
css-color-parser = "0.1.2"
dirs = "4.0.0"
emojis = "~0.5.2"
futures = "0.3"
gethostname = "0.4.1"
html5ever = "0.26.0"
image = "0.24.5"
libc = "0.2"
markup5ever_rcdom = "0.2.0"
mime = "^0.3.16"
mime_guess = "^2.0.4"
open = "3.2.0"
regex = "^1.5"
rpassword = "^7.2"
serde = "^1.0"
serde_json = "^1.0"
thiserror = "^1.0.37"
tracing = "~0.1.36"
tracing-appender = "~0.2.2"
tracing-subscriber = "0.3.16"
unicode-segmentation = "^1.7"
unicode-width = "0.1.10"
url = {version = "^2.2.2", features = ["serde"]}
[dependencies.modalkit]
version = "0.0.16"
[dependencies.matrix-sdk]
version = "0.6"
default-features = false
features = ["e2e-encryption", "sled", "rustls-tls"]
[dependencies.tokio]
version = "1.24.1"
features = ["macros", "net", "rt-multi-thread", "sync", "time"]
[dev-dependencies]
lazy_static = "1.4.0"
pretty_assertions = "1.4.0"
[profile.release]
lto = true
incremental = false
0707010000000A000081A400000000000000000000000164A9007B00002C5D000000000000000000000000000000000000001300000000iamb-0.0.8/LICENSE Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
0707010000000B000081A400000000000000000000000164A9007B000019FB000000000000000000000000000000000000001500000000iamb-0.0.8/README.md# iamb
[](https://github.com/ulyssa/iamb/actions?query=workflow%3ACI+)
[](https://crates.io/crates/iamb)
[](https://matrix.to/#/#iamb:0x.badd.cafe)
[](https://crates.io/crates/iamb)
## About
`iamb` is a Matrix client for the terminal that uses Vim keybindings.
This project is a work-in-progress, and there's still a lot to be implemented,
but much of the basic client functionality is already present.

## Documentation
You can find documentation for installing, configuring, and using iamb on its
website, [iamb.chat].
## Installation
Install Rust (1.66.0 or above) and Cargo, and then run:
```
cargo install --locked iamb
```
### NetBSD
On NetBSD a package is available from the official repositories. To install it simply run:
```
pkgin install iamb
```
### Arch Linux
On Arch Linux a [package](https://aur.archlinux.org/packages/iamb-git) is available in the
Arch User Repositories (AUR). To install it simply run with your favorite AUR helper:
```
paru iamb-git
```
### Nix / NixOS (flake)
```
nix profile install "github:ulyssa/iamb"
```
## Configuration
You can create a basic configuration in `$CONFIG_DIR/iamb/config.json` that looks like:
```json
{
"profiles": {
"example.com": {
"url": "https://example.com",
"user_id": "@user:example.com"
}
}
}
```
## Comparison With Other Clients
To get an idea of what is and isn't yet implemented, here is a subset of the
Matrix website's [features comparison table][client-comparison-matrix], showing
two other TUI clients and Element Web:
| | iamb | [gomuks] | [weechat-matrix] | Element Web/Desktop |
| --------------------------------------- | :---------- | :------: | :--------------: | :-----------------: |
| Room directory | ❌ ([#14]) | ❌ | ✔️ | ✔️ |
| Room tag showing | ✔️ | ✔️ | ❌ | ✔️ |
| Room tag editing | ✔️ | ✔️ | ❌ | ✔️ |
| Search joined rooms | ❌ ([#16]) | ✔️ | ❌ | ✔️ |
| Room user list | ✔️ | ✔️ | ✔️ | ✔️ |
| Display Room Description | ✔️ | ✔️ | ✔️ | ✔️ |
| Edit Room Description | ✔️ | ❌ | ✔️ | ✔️ |
| Highlights | ❌ ([#8]) | ✔️ | ✔️ | ✔️ |
| Pushrules | ❌ | ✔️ | ❌ | ✔️ |
| Send read markers | ✔️ | ✔️ | ✔️ | ✔️ |
| Display read markers | ✔️ | ❌ | ❌ | ✔️ |
| Sending Invites | ✔️ | ✔️ | ✔️ | ✔️ |
| Accepting Invites | ✔️ | ✔️ | ✔️ | ✔️ |
| Typing Notification | ✔️ | ✔️ | ✔️ | ✔️ |
| E2E | ✔️ | ✔️ | ✔️ | ✔️ |
| Replies | ✔️ | ✔️ | ❌ | ✔️ |
| Attachment uploading | ✔️ | ❌ | ✔️ | ✔️ |
| Attachment downloading | ✔️ | ✔️ | ✔️ | ✔️ |
| Send stickers | ❌ | ❌ | ❌ | ✔️ |
| Send formatted messages (markdown) | ✔️ | ✔️ | ✔️ | ✔️ |
| Rich Text Editor for formatted messages | ❌ | ❌ | ❌ | ✔️ |
| Display formatted messages | ✔️ | ✔️ | ✔️ | ✔️ |
| Redacting | ✔️ | ✔️ | ✔️ | ✔️ |
| Multiple Matrix Accounts | ✔️ | ❌ | ✔️ | ❌ |
| New user registration | ❌ | ❌ | ❌ | ✔️ |
| VOIP | ❌ | ❌ | ❌ | ✔️ |
| Reactions | ✔️ | ✔️ | ❌ | ✔️ |
| Message editing | ✔️ | ✔️ | ❌ | ✔️ |
| Room upgrades | ❌ ([#41]) | ✔️ | ❌ | ✔️ |
| Localisations | ❌ | 1 | ❌ | 44 |
| SSO Support | ❌ | ✔️ | ✔️ | ✔️ |
## License
iamb is released under the [Apache License, Version 2.0].
[Apache License, Version 2.0]: https://github.com/ulyssa/iamb/blob/master/LICENSE
[client-comparison-matrix]: https://matrix.org/clients-matrix/
[iamb.chat]: https://iamb.chat
[gomuks]: https://github.com/tulir/gomuks
[weechat-matrix]: https://github.com/poljar/weechat-matrix
[#8]: https://github.com/ulyssa/iamb/issues/8
[#14]: https://github.com/ulyssa/iamb/issues/14
[#16]: https://github.com/ulyssa/iamb/issues/16
[#41]: https://github.com/ulyssa/iamb/issues/41
0707010000000C000081A400000000000000000000000164A9007B00000352000000000000000000000000000000000000001400000000iamb-0.0.8/build.rsuse std::error::Error;
use std::fs;
use std::iter::FromIterator;
use std::path::PathBuf;
use mandown::convert;
use vergen::EmitBuilder;
const IAMB_1_MD: &str = include_str!("docs/iamb.1.md");
const IAMB_5_MD: &str = include_str!("docs/iamb.5.md");
fn main() -> Result<(), Box<dyn Error>> {
EmitBuilder::builder().git_sha(true).emit()?;
// Build the manual pages.
println!("cargo:rerun-if-changed=docs/iamb.1.md");
println!("cargo:rerun-if-changed=docs/iamb.5.md");
let iamb_1 = convert(IAMB_1_MD, "IAMB", 1);
let iamb_5 = convert(IAMB_5_MD, "IAMB", 5);
let out_dir = std::env::var("OUT_DIR");
let out_dir = out_dir.as_deref().unwrap_or("docs");
fs::write(PathBuf::from_iter([out_dir, "iamb.1"]), iamb_1.as_bytes())?;
fs::write(PathBuf::from_iter([out_dir, "iamb.5"]), iamb_5.as_bytes())?;
Ok(())
}
0707010000000D000041ED00000000000000000000000264A9007B00000000000000000000000000000000000000000000001000000000iamb-0.0.8/docs0707010000000E000081A400000000000000000000000164A9007B000002F1000000000000000000000000000000000000002400000000iamb-0.0.8/docs/example_config.json{
"default_profile": "default",
"profiles": {
"default": {
"user_id": "",
"url": "https://matrix.org",
"settings": {},
"dirs": {}
}
},
"settings": {
"log_level": "warn",
"reaction_display": true,
"reaction_shortcode_display": false,
"read_receipt_send": true,
"read_receipt_display": true,
"request_timeout": 10000,
"typing_notice_send": true,
"typing_notice_display": true,
"users": {
"@user:matrix.org": {
"name": "John Doe",
"color": "magenta"
}
},
"default_room": "#iamb-users:0x.badd.cafe"
},
"dirs": {
"cache": "~/.cache/iamb/",
"logs": "~/.local/share/iamb/logs/",
"downloads": "~/Downloads/"
}
0707010000000F000081A400000000000000000000000164A9007B0000028C000000000000000000000000000000000000001A00000000iamb-0.0.8/docs/iamb.1.md# NAME
iamb – a terminal-based client for Matrix for the Vim addict
# SYNOPSIS
**iamb** [**--profile** _profile_] [**--config-directory** _directory_] [**--help** | **--version**]
# OPTIONS
These options are primitives at the top-level of the file.
**--profile**, **-P**
> The profile to start with. Overrides **default_profile** from **iamb(5)**.
**--config-directory**, **-C**
> Path to the directory the configuration file is located in.
**--help**, **-h**
> Show a short help text and quit.
**--version**, **-V**
> Show the iamb version and quit.
# SEE ALSO
**iamb(5)**
Full documentation is available online at \<https://iamb.chat\>
07070100000010000081A400000000000000000000000164A9007B0000107C000000000000000000000000000000000000001A00000000iamb-0.0.8/docs/iamb.5.md# NAME
config.json – configuration file for iamb
# SYNOPSIS
Configuration must be placed under _~/.config/iamb/_ and is named config.json.
Example configuration usually comes bundled with your installation and can
typically be found in _/usr/share/iamb_.
As implied by the filename, the configuration is formatted in JSON. It's
structure and fields are described below.
# BASIC SETTINGS
These options are primitives at the top-level of the file.
**default_profile** (type: string)
> The default profile to connect to, unless overwritten by a commandline
> switch. It has to be defined in the *PROFILES* section.
# PROFILES
These options are configured as a map under the profiles name.
**user_id** (type: string)
> The user ID to use when connecting to the server. For example "user" for
> "@user:matrix.org".
**url** (type: string)
> The URL of the users server. For example "https://matrix.org" for
> "@user:matrix.org".
**settings** (type: settings object)
> Overwrite general settings for this account. The fields are identical to
> those in *TUNABLES*.
**layout** (type: startup layout object)
> Overwrite general settings for this account. The fields are identical to
> those in *STARTUP LAYOUT*.
**dirs** (type: XDG overrides object)
> Overwrite general settings for this account. The fields are identical to
> those in *DIRECTORIES*.
# TUNABLES
These options are configured as a map under the *settings* key and can be
overridden as described in *PROFILES*.
**log_level** (type: string)
> Specifies the lowest log level that should be shown. Possible values
> are: _trace_, _debug_, _info_, _warn_, and _error_.
**reaction_display** (type: boolean)
> Defines whether or not reactions should be shown.
**reaction_shortcode_display** (type: boolean)
> Defines whether or not reactions should be shown as their respective
> shortcode.
**read_receipt_send** (type: boolean)
> Defines whether or not read confirmations are sent.
**read_receipt_display** (type: boolean)
> Defines whether or not read confirmations are displayed.
**request_timeout** (type: uint64)
> Defines the maximum time per request in seconds.
**typing_notice_send** (type: boolean)
> Defines whether or not the typing state is sent.
**typing_notice_display** (type: boolean)
> Defines whether or not the typing state is displayed.
**user** (type: map)
> Overrides values for the specified user. See *USER OVERRIDES* for
> details on the format.
**default_room** (type: string)
> The room to show by default instead of a welcome-screen.
## USER OVERRIDES
Overrides are mapped onto matrix User IDs such as _@user:matrix.org_ and are
maps containing the following key value pairs.
**name** (type: string)
> Change the display name of the user.
**color** (type: string)
> Change the color the user is shown as. Possible values are: _black_,
> _blue_, _cyan_, _dark-gray_, _gray_, _green_, _light-blue_,
> _light-cyan_, _light-green_, _light-magenta_, _light-red_,
> _light-yellow_, _magenta_, _none_, _red_, _white_, _yellow_
# STARTUP LAYOUT
Specifies what initial set of tabs and windows to show when starting the
client. Configured as an object under the key *layout*.
**style** (type: string)
> Specifies what window layout to load when starting. Valid values are
> _restore_ to restore the layout from the last time the client was exited,
> _new_ to open a single window (uses the value of _default\_room_ if set), or
> _config_ to open the layout described under _tabs_.
**tabs** (type: array of window objects)
> If **style** is set to _config_, then this value will be used to open a set
> of tabs and windows at startup. Each object can contain either a **window**
> key specifying a username, room identifier or room alias to show, or a
> **split** key specifying an array of window objects.
# DIRECTORIES
Specifies the directories to save data in. Configured as a map under the key
*dirs*.
**cache** (type: string)
> Specifies where to store assets and temporary data in.
**logs** (type: string)
> Specifies where to store log files.
**downloads** (type: string)
> Specifies where to store downloaded files.
# SEE ALSO
*iamb(1)*
Full documentation is available online at \<https://iamb.chat\>
07070100000011000081A400000000000000000000000164A9007B00000991000000000000000000000000000000000000001600000000iamb-0.0.8/flake.lock{
"nodes": {
"flake-utils": {
"locked": {
"lastModified": 1678901627,
"narHash": "sha256-U02riOqrKKzwjsxc/400XnElV+UtPUQWpANPlyazjH0=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "93a2b84fc4b70d9e089d029deacc3583435c2ed6",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"flake-utils_2": {
"locked": {
"lastModified": 1659877975,
"narHash": "sha256-zllb8aq3YO3h8B/U0/J1WBgAL8EX5yWf5pMj3G0NAmc=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "c0e246b9b83f637f4681389ecabcb2681b4f3af0",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1679437018,
"narHash": "sha256-vOuiDPLHSEo/7NkiWtxpHpHgoXoNmrm+wkXZ6a072Fc=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "19cf008bb18e47b6e3b4e16e32a9a4bdd4b45f7e",
"type": "github"
},
"original": {
"owner": "nixos",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"nixpkgs_2": {
"locked": {
"lastModified": 1665296151,
"narHash": "sha256-uOB0oxqxN9K7XGF1hcnY+PQnlQJ+3bP2vCn/+Ru/bbc=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "14ccaaedd95a488dd7ae142757884d8e125b3363",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixpkgs-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"flake-utils": "flake-utils",
"nixpkgs": "nixpkgs",
"rust-overlay": "rust-overlay"
}
},
"rust-overlay": {
"inputs": {
"flake-utils": "flake-utils_2",
"nixpkgs": "nixpkgs_2"
},
"locked": {
"lastModified": 1679624450,
"narHash": "sha256-wiDqUaklmc31E1+wz5sv52sMcWvZKsL1FBeGJCxz628=",
"owner": "oxalica",
"repo": "rust-overlay",
"rev": "afbdcf305fd6f05f708fe76d52f24d37d066c251",
"type": "github"
},
"original": {
"owner": "oxalica",
"repo": "rust-overlay",
"type": "github"
}
}
},
"root": "root",
"version": 7
}
07070100000012000081A400000000000000000000000164A9007B00000544000000000000000000000000000000000000001500000000iamb-0.0.8/flake.nix{
description = "iamb";
nixConfig.bash-prompt = "\[nix-develop\]$ ";
inputs = {
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
flake-utils.url = "github:numtide/flake-utils";
rust-overlay.url = "github:oxalica/rust-overlay";
};
outputs = { self, nixpkgs, flake-utils, rust-overlay, ... }:
flake-utils.lib.eachDefaultSystem (system:
let
# We only need the nightly overlay in the devShell because .rs files are formatted with nightly.
overlays = [ (import rust-overlay) ];
pkgs = import nixpkgs { inherit system overlays; };
rustNightly = pkgs.rust-bin.nightly."2023-03-17".default;
in
with pkgs;
{
packages.default = pkgs.rustPlatform.buildRustPackage {
pname = "iamb";
version = "0.0.7";
src = ./.;
cargoLock.lockFile = ./Cargo.lock;
nativeBuildInputs = [ pkgs.pkgconfig ];
buildInputs = [ pkgs.openssl ] ++ pkgs.lib.optionals pkgs.stdenv.isDarwin
(with pkgs.darwin.apple_sdk.frameworks; [ AppKit Security ]);
};
devShell = mkShell {
buildInputs = [
(rustNightly.override { extensions = [ "rust-src" ]; })
pkg-config
cargo-tarpaulin
rust-analyzer
rustfmt
];
};
});
}
07070100000013000041ED00000000000000000000000264A9007B00000000000000000000000000000000000000000000000F00000000iamb-0.0.8/src07070100000014000081A400000000000000000000000164A9007B00009681000000000000000000000000000000000000001700000000iamb-0.0.8/src/base.rsuse std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::convert::TryFrom;
use std::fmt::{self, Display};
use std::hash::Hash;
use std::str::FromStr;
use std::sync::Arc;
use std::time::{Duration, Instant};
use emojis::Emoji;
use serde::{
de::Error as SerdeError,
de::Visitor,
Deserialize,
Deserializer,
Serialize,
Serializer,
};
use tokio::sync::Mutex as AsyncMutex;
use url::Url;
use matrix_sdk::{
encryption::verification::SasVerification,
room::{Joined, Room as MatrixRoom},
ruma::{
events::{
reaction::ReactionEvent,
room::encrypted::RoomEncryptedEvent,
room::message::{
OriginalRoomMessageEvent,
Relation,
Replacement,
RoomMessageEvent,
RoomMessageEventContent,
},
tag::{TagName, Tags},
MessageLikeEvent,
},
presence::PresenceState,
EventId,
OwnedEventId,
OwnedRoomId,
OwnedUserId,
RoomId,
},
};
use modalkit::{
editing::{
action::{Action, UIError, UIResult},
application::{
ApplicationAction,
ApplicationContentId,
ApplicationError,
ApplicationInfo,
ApplicationStore,
ApplicationWindowId,
},
base::{CommandType, WordStyle},
completion::{complete_path, CompletionMap},
context::EditContext,
cursor::Cursor,
rope::EditRope,
store::Store,
},
env::vim::{
command::{CommandContext, CommandDescription, VimCommand, VimCommandMachine},
keybindings::VimMachine,
VimContext,
},
input::bindings::SequenceStatus,
input::key::TerminalKey,
tui::{
buffer::Buffer,
layout::{Alignment, Rect},
text::{Span, Spans},
widgets::{Paragraph, Widget},
},
};
use crate::{
message::{Message, MessageEvent, MessageKey, MessageTimeStamp, Messages},
worker::Requester,
ApplicationSettings,
};
pub const MATRIX_ID_WORD: WordStyle = WordStyle::CharSet(is_mxid_char);
/// Find the boundaries for a Matrix username, room alias, or room ID.
///
/// Technically "[" and "]" should be here since IPv6 addresses are allowed
/// in the server name, but in practice that should be uncommon, and people
/// can just use `gf` and friends in Visual mode instead.
fn is_mxid_char(c: char) -> bool {
return c >= 'a' && c <= 'z' ||
c >= 'A' && c <= 'Z' ||
c >= '0' && c <= '9' ||
":-./@_#!".contains(c);
}
const ROOM_FETCH_DEBOUNCE: Duration = Duration::from_secs(2);
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum IambInfo {}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum VerifyAction {
Accept,
Cancel,
Confirm,
Mismatch,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum MessageAction {
/// Cance the current reply or edit.
///
/// The [bool] argument indicates whether to skip confirmation for clearing the message bar.
Cancel(bool),
/// Download an attachment to the given path.
///
/// The second argument controls whether to overwrite any already existing file at the
/// destination path, or to open the attachment after downloading.
Download(Option<String>, DownloadFlags),
/// Edit a sent message.
Edit,
/// React to a message with an Emoji.
React(String),
/// Redact a message, with an optional reason.
///
/// The [bool] argument indicates whether to skip confirmation.
Redact(Option<String>, bool),
/// Reply to a message.
Reply,
/// Unreact to a message.
///
/// If no specific Emoji to remove to is specified, then all reactions from the user on the
/// message are removed.
Unreact(Option<String>),
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum CreateRoomType {
/// A direct message room.
Direct(OwnedUserId),
/// A standard chat room.
Room,
/// A Matrix space.
Space,
}
bitflags::bitflags! {
pub struct CreateRoomFlags: u32 {
const NONE = 0b00000000;
/// Make the room public.
const PUBLIC = 0b00000001;
/// Encrypt this room.
const ENCRYPTED = 0b00000010;
}
}
bitflags::bitflags! {
pub struct DownloadFlags: u32 {
const NONE = 0b00000000;
/// Overwrite file if it already exists.
const FORCE = 0b00000001;
/// Open file after downloading.
const OPEN = 0b00000010;
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum RoomField {
Name,
Tag(TagName),
Topic,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum RoomAction {
InviteAccept,
InviteReject,
InviteSend(OwnedUserId),
Leave(bool),
Members(Box<CommandContext<ProgramContext>>),
Set(RoomField, String),
Unset(RoomField),
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum SendAction {
Submit,
Upload(String),
UploadImage(usize, usize, Cow<'static, [u8]>),
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum HomeserverAction {
CreateRoom(Option<String>, CreateRoomType, CreateRoomFlags),
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum IambAction {
Homeserver(HomeserverAction),
Message(MessageAction),
Room(RoomAction),
Send(SendAction),
Verify(VerifyAction, String),
VerifyRequest(String),
ToggleScrollbackFocus,
}
impl From<HomeserverAction> for IambAction {
fn from(act: HomeserverAction) -> Self {
IambAction::Homeserver(act)
}
}
impl From<MessageAction> for IambAction {
fn from(act: MessageAction) -> Self {
IambAction::Message(act)
}
}
impl From<RoomAction> for IambAction {
fn from(act: RoomAction) -> Self {
IambAction::Room(act)
}
}
impl From<SendAction> for IambAction {
fn from(act: SendAction) -> Self {
IambAction::Send(act)
}
}
impl ApplicationAction for IambAction {
fn is_edit_sequence<C: EditContext>(&self, _: &C) -> SequenceStatus {
match self {
IambAction::Homeserver(..) => SequenceStatus::Break,
IambAction::Message(..) => SequenceStatus::Break,
IambAction::Room(..) => SequenceStatus::Break,
IambAction::Send(..) => SequenceStatus::Break,
IambAction::ToggleScrollbackFocus => SequenceStatus::Break,
IambAction::Verify(..) => SequenceStatus::Break,
IambAction::VerifyRequest(..) => SequenceStatus::Break,
}
}
fn is_last_action<C: EditContext>(&self, _: &C) -> SequenceStatus {
match self {
IambAction::Homeserver(..) => SequenceStatus::Atom,
IambAction::Message(..) => SequenceStatus::Atom,
IambAction::Room(..) => SequenceStatus::Atom,
IambAction::Send(..) => SequenceStatus::Atom,
IambAction::ToggleScrollbackFocus => SequenceStatus::Atom,
IambAction::Verify(..) => SequenceStatus::Atom,
IambAction::VerifyRequest(..) => SequenceStatus::Atom,
}
}
fn is_last_selection<C: EditContext>(&self, _: &C) -> SequenceStatus {
match self {
IambAction::Homeserver(..) => SequenceStatus::Ignore,
IambAction::Message(..) => SequenceStatus::Ignore,
IambAction::Room(..) => SequenceStatus::Ignore,
IambAction::Send(..) => SequenceStatus::Ignore,
IambAction::ToggleScrollbackFocus => SequenceStatus::Ignore,
IambAction::Verify(..) => SequenceStatus::Ignore,
IambAction::VerifyRequest(..) => SequenceStatus::Ignore,
}
}
fn is_switchable<C: EditContext>(&self, _: &C) -> bool {
match self {
IambAction::Homeserver(..) => false,
IambAction::Message(..) => false,
IambAction::Room(..) => false,
IambAction::Send(..) => false,
IambAction::ToggleScrollbackFocus => false,
IambAction::Verify(..) => false,
IambAction::VerifyRequest(..) => false,
}
}
}
impl From<RoomAction> for ProgramAction {
fn from(act: RoomAction) -> Self {
IambAction::from(act).into()
}
}
impl From<IambAction> for ProgramAction {
fn from(act: IambAction) -> Self {
Action::Application(act)
}
}
pub type ProgramAction = Action<IambInfo>;
pub type ProgramContext = VimContext<IambInfo>;
pub type Keybindings = VimMachine<TerminalKey, IambInfo>;
pub type ProgramCommand = VimCommand<ProgramContext, IambInfo>;
pub type ProgramCommands = VimCommandMachine<ProgramContext, IambInfo>;
pub type ProgramStore = Store<IambInfo>;
pub type AsyncProgramStore = Arc<AsyncMutex<ProgramStore>>;
pub type IambResult<T> = UIResult<T, IambInfo>;
/// Reaction events for some message.
///
/// The event identifier used as a key here is the ID for the reaction, and not for the message
/// it's reacting to.
pub type MessageReactions = HashMap<OwnedEventId, (String, OwnedUserId)>;
pub type Receipts = HashMap<OwnedEventId, Vec<OwnedUserId>>;
#[derive(thiserror::Error, Debug)]
pub enum IambError {
#[error("Invalid user identifier: {0}")]
InvalidUserId(String),
#[error("Invalid verification user/device pair: {0}")]
InvalidVerificationId(String),
#[error("Cryptographic storage error: {0}")]
CryptoStore(#[from] matrix_sdk::encryption::CryptoStoreError),
#[error("HTTP client error: {0}")]
Http(#[from] matrix_sdk::HttpError),
#[error("Matrix client error: {0}")]
Matrix(#[from] matrix_sdk::Error),
#[error("Matrix client storage error: {0}")]
Store(#[from] matrix_sdk::StoreError),
#[error("Serialization/deserialization error: {0}")]
Serde(#[from] serde_json::Error),
#[error("No download directory configured")]
NoDownloadDir,
#[error("Selected message does not have any attachments")]
NoAttachment,
#[error("No message currently selected")]
NoSelectedMessage,
#[error("Current window is not a room or space")]
NoSelectedRoomOrSpace,
#[error("Current window is not a room")]
NoSelectedRoom,
#[error("You do not have a current invitation to this room")]
NotInvited,
#[error("You need to join the room before you can do that")]
NotJoined,
#[error("Unknown room identifier: {0}")]
UnknownRoom(OwnedRoomId),
#[error("Verification request error: {0}")]
VerificationRequestError(#[from] matrix_sdk::encryption::identities::RequestVerificationError),
#[error("Image error: {0}")]
Image(#[from] image::ImageError),
#[error("Could not use system clipboard data")]
Clipboard,
}
impl From<IambError> for UIError<IambInfo> {
fn from(err: IambError) -> Self {
UIError::Application(err)
}
}
impl ApplicationError for IambError {}
#[derive(Default)]
pub enum RoomFetchStatus {
Done,
HaveMore(String),
#[default]
NotStarted,
}
pub enum EventLocation {
Message(MessageKey),
Reaction(OwnedEventId),
}
impl EventLocation {
fn to_message_key(&self) -> Option<&MessageKey> {
if let EventLocation::Message(key) = self {
Some(key)
} else {
None
}
}
}
#[derive(Default)]
pub struct RoomInfo {
/// The display name for this room.
pub name: Option<String>,
/// The tags placed on this room.
pub tags: Option<Tags>,
/// A map of event IDs to where they are stored in this struct.
pub keys: HashMap<OwnedEventId, EventLocation>,
/// The messages loaded for this room.
pub messages: Messages,
/// A map of read markers to display on different events.
pub receipts: HashMap<OwnedEventId, Vec<OwnedUserId>>,
/// An event ID for where we should indicate we've read up to.
pub read_till: Option<OwnedEventId>,
/// A map of message identifiers to a map of reaction events.
pub reactions: HashMap<OwnedEventId, MessageReactions>,
/// Whether the scrollback for this room is currently being fetched.
pub fetching: bool,
/// Where to continue fetching from when we continue loading scrollback history.
pub fetch_id: RoomFetchStatus,
/// The time that we last fetched scrollback for this room.
pub fetch_last: Option<Instant>,
/// Users currently typing in this room, and when we received notification of them doing so.
pub users_typing: Option<(Instant, Vec<OwnedUserId>)>,
/// The display names for users in this room.
pub display_names: HashMap<OwnedUserId, String>,
}
impl RoomInfo {
pub fn get_reactions(&self, event_id: &EventId) -> Vec<(&str, usize)> {
if let Some(reacts) = self.reactions.get(event_id) {
let mut counts = HashMap::new();
for (key, _) in reacts.values() {
let count = counts.entry(key.as_str()).or_default();
*count += 1;
}
let mut reactions = counts.into_iter().collect::<Vec<_>>();
reactions.sort();
reactions
} else {
vec![]
}
}
pub fn get_message_key(&self, event_id: &EventId) -> Option<&MessageKey> {
self.keys.get(event_id)?.to_message_key()
}
pub fn get_event(&self, event_id: &EventId) -> Option<&Message> {
self.messages.get(self.get_message_key(event_id)?)
}
pub fn insert_reaction(&mut self, react: ReactionEvent) {
match react {
MessageLikeEvent::Original(react) => {
let rel_id = react.content.relates_to.event_id;
let key = react.content.relates_to.key;
let message = self.reactions.entry(rel_id.clone()).or_default();
let event_id = react.event_id;
let user_id = react.sender;
message.insert(event_id.clone(), (key, user_id));
let loc = EventLocation::Reaction(rel_id);
self.keys.insert(event_id, loc);
},
MessageLikeEvent::Redacted(_) => {
return;
},
}
}
pub fn insert_edit(&mut self, msg: Replacement) {
let event_id = msg.event_id;
let new_content = msg.new_content;
let key = if let Some(EventLocation::Message(k)) = self.keys.get(&event_id) {
k
} else {
return;
};
let msg = if let Some(msg) = self.messages.get_mut(key) {
msg
} else {
return;
};
match &mut msg.event {
MessageEvent::Original(orig) => {
orig.content.msgtype = new_content.msgtype;
},
MessageEvent::Local(_, content) => {
content.msgtype = new_content.msgtype;
},
MessageEvent::Redacted(_) |
MessageEvent::EncryptedOriginal(_) |
MessageEvent::EncryptedRedacted(_) => {
return;
},
}
msg.html = msg.event.html();
}
/// Inserts events that couldn't be decrypted into the scrollback.
pub fn insert_encrypted(&mut self, msg: RoomEncryptedEvent) {
let event_id = msg.event_id().to_owned();
let key = (msg.origin_server_ts().into(), event_id.clone());
self.keys.insert(event_id, EventLocation::Message(key.clone()));
self.messages.insert(key, msg.into());
}
pub fn insert_message(&mut self, msg: RoomMessageEvent) {
let event_id = msg.event_id().to_owned();
let key = (msg.origin_server_ts().into(), event_id.clone());
self.keys.insert(event_id.clone(), EventLocation::Message(key.clone()));
self.messages.insert(key, msg.into());
// Remove any echo.
let key = (MessageTimeStamp::LocalEcho, event_id);
let _ = self.messages.remove(&key);
}
pub fn insert(&mut self, msg: RoomMessageEvent) {
match msg {
RoomMessageEvent::Original(OriginalRoomMessageEvent {
content:
RoomMessageEventContent { relates_to: Some(Relation::Replacement(repl)), .. },
..
}) => self.insert_edit(repl),
_ => self.insert_message(msg),
}
}
pub fn recently_fetched(&self) -> bool {
self.fetch_last.map_or(false, |i| i.elapsed() < ROOM_FETCH_DEBOUNCE)
}
fn get_typers(&self) -> &[OwnedUserId] {
if let Some((t, users)) = &self.users_typing {
if t.elapsed() < Duration::from_secs(4) {
return users.as_ref();
} else {
return &[];
}
} else {
return &[];
}
}
fn get_typing_spans<'a>(&'a self, settings: &'a ApplicationSettings) -> Spans<'a> {
let typers = self.get_typers();
let n = typers.len();
match n {
0 => Spans(vec![]),
1 => {
let user = settings.get_user_span(typers[0].as_ref(), self);
Spans(vec![user, Span::from(" is typing...")])
},
2 => {
let user1 = settings.get_user_span(typers[0].as_ref(), self);
let user2 = settings.get_user_span(typers[1].as_ref(), self);
Spans(vec![
user1,
Span::raw(" and "),
user2,
Span::from(" are typing..."),
])
},
n if n < 5 => Spans::from("Several people are typing..."),
_ => Spans::from("Many people are typing..."),
}
}
pub fn set_typing(&mut self, user_ids: Vec<OwnedUserId>) {
self.users_typing = (Instant::now(), user_ids).into();
}
pub fn render_typing(
&mut self,
area: Rect,
buf: &mut Buffer,
settings: &ApplicationSettings,
) -> Rect {
if area.height <= 2 || area.width <= 20 {
return area;
}
if !settings.tunables.typing_notice_display {
return area;
}
let top = Rect::new(area.x, area.y, area.width, area.height - 1);
let bar = Rect::new(area.x, area.y + top.height, area.width, 1);
Paragraph::new(self.get_typing_spans(settings))
.alignment(Alignment::Center)
.render(bar, buf);
return top;
}
}
fn emoji_map() -> CompletionMap<String, &'static Emoji> {
let mut emojis = CompletionMap::default();
for emoji in emojis::iter() {
for shortcode in emoji.shortcodes() {
emojis.insert(shortcode.to_string(), emoji);
}
}
return emojis;
}
#[derive(Default)]
pub struct SyncInfo {
pub spaces: Vec<MatrixRoom>,
pub rooms: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
pub dms: Vec<Arc<(MatrixRoom, Option<Tags>)>>,
}
pub struct ChatStore {
pub cmds: ProgramCommands,
pub worker: Requester,
pub rooms: CompletionMap<OwnedRoomId, RoomInfo>,
pub names: CompletionMap<String, OwnedRoomId>,
pub presences: CompletionMap<OwnedUserId, PresenceState>,
pub verifications: HashMap<String, SasVerification>,
pub settings: ApplicationSettings,
pub need_load: HashSet<OwnedRoomId>,
pub emojis: CompletionMap<String, &'static Emoji>,
pub sync_info: SyncInfo,
}
impl ChatStore {
pub fn new(worker: Requester, settings: ApplicationSettings) -> Self {
ChatStore {
worker,
settings,
cmds: crate::commands::setup_commands(),
emojis: emoji_map(),
names: Default::default(),
rooms: Default::default(),
presences: Default::default(),
verifications: Default::default(),
need_load: Default::default(),
sync_info: Default::default(),
}
}
pub fn get_joined_room(&self, room_id: &RoomId) -> Option<Joined> {
self.worker.client.get_joined_room(room_id)
}
pub fn get_room_title(&self, room_id: &RoomId) -> String {
self.rooms
.get(room_id)
.and_then(|i| i.name.as_ref())
.map(String::from)
.unwrap_or_else(|| "Untitled Matrix Room".to_string())
}
pub async fn set_receipts(
&mut self,
receipts: Vec<(OwnedRoomId, Receipts)>,
) -> Vec<(OwnedRoomId, OwnedEventId)> {
let mut updates = vec![];
for (room_id, receipts) in receipts.into_iter() {
if let Some(info) = self.rooms.get_mut(&room_id) {
info.receipts = receipts;
if let Some(read_till) = info.read_till.take() {
updates.push((room_id, read_till));
}
}
}
return updates;
}
pub fn mark_for_load(&mut self, room_id: OwnedRoomId) {
self.need_load.insert(room_id);
}
pub fn get_room_info(&mut self, room_id: OwnedRoomId) -> &mut RoomInfo {
self.rooms.get_or_default(room_id)
}
pub fn set_room_name(&mut self, room_id: &RoomId, name: &str) {
self.rooms.get_or_default(room_id.to_owned()).name = name.to_string().into();
}
pub fn insert_sas(&mut self, sas: SasVerification) {
let key = format!("{}/{}", sas.other_user_id(), sas.other_device().device_id());
self.verifications.insert(key, sas);
}
}
impl ApplicationStore for ChatStore {}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum IambId {
/// A Matrix room.
Room(OwnedRoomId),
/// The `:rooms` window.
DirectList,
/// The `:members` window for a given Matrix room.
MemberList(OwnedRoomId),
/// The `:rooms` window.
RoomList,
/// The `:spaces` window.
SpaceList,
/// The `:verify` window.
VerifyList,
/// The `:welcome` window.
Welcome,
}
impl Display for IambId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
IambId::Room(room_id) => {
write!(f, "iamb://room/{room_id}")
},
IambId::MemberList(room_id) => {
write!(f, "iamb://members/{room_id}")
},
IambId::DirectList => f.write_str("iamb://dms"),
IambId::RoomList => f.write_str("iamb://rooms"),
IambId::SpaceList => f.write_str("iamb://spaces"),
IambId::VerifyList => f.write_str("iamb://verify"),
IambId::Welcome => f.write_str("iamb://welcome"),
}
}
}
impl ApplicationWindowId for IambId {}
impl Serialize for IambId {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.to_string())
}
}
impl<'de> Deserialize<'de> for IambId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_str(IambIdVisitor)
}
}
struct IambIdVisitor;
impl<'de> Visitor<'de> for IambIdVisitor {
type Value = IambId;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a valid window URL")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: SerdeError,
{
let Ok(url) = Url::parse(value) else {
return Err(E::custom("Invalid iamb window URL"));
};
if url.scheme() != "iamb" {
return Err(E::custom("Invalid iamb window URL"));
}
match url.domain() {
Some("room") => {
let Some(path) = url.path_segments() else {
return Err(E::custom("Invalid members window URL"));
};
let &[room_id] = path.collect::<Vec<_>>().as_slice() else {
return Err(E::custom("Invalid members window URL"));
};
let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
return Err(E::custom("Invalid room identifier"));
};
Ok(IambId::Room(room_id))
},
Some("members") => {
let Some(path) = url.path_segments() else {
return Err(E::custom("Invalid members window URL"));
};
let &[room_id] = path.collect::<Vec<_>>().as_slice() else {
return Err(E::custom("Invalid members window URL"));
};
let Ok(room_id) = OwnedRoomId::try_from(room_id) else {
return Err(E::custom("Invalid room identifier"));
};
Ok(IambId::MemberList(room_id))
},
Some("dms") => {
if url.path() != "" {
return Err(E::custom("iamb://dms takes no path"));
}
Ok(IambId::DirectList)
},
Some("rooms") => {
if url.path() != "" {
return Err(E::custom("iamb://rooms takes no path"));
}
Ok(IambId::RoomList)
},
Some("spaces") => {
if url.path() != "" {
return Err(E::custom("iamb://spaces takes no path"));
}
Ok(IambId::SpaceList)
},
Some("verify") => {
if url.path() != "" {
return Err(E::custom("iamb://verify takes no path"));
}
Ok(IambId::VerifyList)
},
Some("welcome") => {
if url.path() != "" {
return Err(E::custom("iamb://welcome takes no path"));
}
Ok(IambId::Welcome)
},
Some(s) => Err(E::custom(format!("{s:?} is not a valid window"))),
None => Err(E::custom("Invalid iamb window URL")),
}
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum RoomFocus {
Scrollback,
MessageBar,
}
impl RoomFocus {
pub fn is_scrollback(&self) -> bool {
matches!(self, RoomFocus::Scrollback)
}
pub fn is_msgbar(&self) -> bool {
matches!(self, RoomFocus::MessageBar)
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum IambBufferId {
Command(CommandType),
Room(OwnedRoomId, RoomFocus),
DirectList,
MemberList(OwnedRoomId),
RoomList,
SpaceList,
VerifyList,
Welcome,
}
impl IambBufferId {
pub fn to_window(&self) -> Option<IambId> {
match self {
IambBufferId::Command(_) => None,
IambBufferId::Room(room, _) => Some(IambId::Room(room.clone())),
IambBufferId::DirectList => Some(IambId::DirectList),
IambBufferId::MemberList(room) => Some(IambId::MemberList(room.clone())),
IambBufferId::RoomList => Some(IambId::RoomList),
IambBufferId::SpaceList => Some(IambId::SpaceList),
IambBufferId::VerifyList => Some(IambId::VerifyList),
IambBufferId::Welcome => Some(IambId::Welcome),
}
}
}
impl ApplicationContentId for IambBufferId {}
impl ApplicationInfo for IambInfo {
type Error = IambError;
type Store = ChatStore;
type Action = IambAction;
type WindowId = IambId;
type ContentId = IambBufferId;
fn complete(
text: &EditRope,
cursor: &mut Cursor,
content: &IambBufferId,
store: &mut ProgramStore,
) -> Vec<String> {
match content {
IambBufferId::Command(CommandType::Command) => complete_cmdbar(text, cursor, store),
IambBufferId::Command(CommandType::Search) => vec![],
IambBufferId::Room(_, RoomFocus::MessageBar) => complete_msgbar(text, cursor, store),
IambBufferId::Room(_, RoomFocus::Scrollback) => vec![],
IambBufferId::DirectList => vec![],
IambBufferId::MemberList(_) => vec![],
IambBufferId::RoomList => vec![],
IambBufferId::SpaceList => vec![],
IambBufferId::VerifyList => vec![],
IambBufferId::Welcome => vec![],
}
}
fn content_of_command(ct: CommandType) -> IambBufferId {
IambBufferId::Command(ct)
}
}
fn complete_users(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
let id = text
.get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
.unwrap_or_else(EditRope::empty);
let id = Cow::from(&id);
store
.application
.presences
.complete(id.as_ref())
.into_iter()
.map(|i| i.to_string())
.collect()
}
fn complete_msgbar(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
let id = text
.get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
.unwrap_or_else(EditRope::empty);
let id = Cow::from(&id);
match id.chars().next() {
// Complete room aliases.
Some('#') => {
return store.application.names.complete(id.as_ref());
},
// Complete room identifiers.
Some('!') => {
return store
.application
.rooms
.complete(id.as_ref())
.into_iter()
.map(|i| i.to_string())
.collect();
},
// Complete Emoji shortcodes.
Some(':') => {
let list = store.application.emojis.complete(&id[1..]);
let iter = list.into_iter().take(200).map(|s| format!(":{}:", s));
return iter.collect();
},
// Complete usernames for @ and empty strings.
Some('@') | None => {
return store
.application
.presences
.complete(id.as_ref())
.into_iter()
.map(|i| i.to_string())
.collect();
},
// Unknown sigil.
Some(_) => return vec![],
}
}
fn complete_matrix_names(
text: &EditRope,
cursor: &mut Cursor,
store: &ProgramStore,
) -> Vec<String> {
let id = text
.get_prefix_word_mut(cursor, &MATRIX_ID_WORD)
.unwrap_or_else(EditRope::empty);
let id = Cow::from(&id);
let list = store.application.names.complete(id.as_ref());
if !list.is_empty() {
return list;
}
let list = store.application.presences.complete(id.as_ref());
if !list.is_empty() {
return list.into_iter().map(|i| i.to_string()).collect();
}
store
.application
.rooms
.complete(id.as_ref())
.into_iter()
.map(|i| i.to_string())
.collect()
}
fn complete_emoji(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
let sc = text.get_prefix_word_mut(cursor, &WordStyle::Little);
let sc = sc.unwrap_or_else(EditRope::empty);
let sc = Cow::from(&sc);
store.application.emojis.complete(sc.as_ref())
}
fn complete_cmdname(
desc: CommandDescription,
text: &EditRope,
cursor: &mut Cursor,
store: &ProgramStore,
) -> Vec<String> {
// Complete command name and set cursor position.
let _ = text.get_prefix_word_mut(cursor, &WordStyle::Little);
store.application.cmds.complete_name(desc.command.as_str())
}
fn complete_cmdarg(
desc: CommandDescription,
text: &EditRope,
cursor: &mut Cursor,
store: &ProgramStore,
) -> Vec<String> {
let cmd = match store.application.cmds.get(desc.command.as_str()) {
Ok(cmd) => cmd,
Err(_) => return vec![],
};
match cmd.name.as_str() {
"cancel" | "dms" | "edit" | "redact" | "reply" => vec![],
"members" | "rooms" | "spaces" | "welcome" => vec![],
"download" | "open" | "upload" => complete_path(text, cursor),
"react" | "unreact" => complete_emoji(text, cursor, store),
"invite" => complete_users(text, cursor, store),
"join" | "split" | "vsplit" | "tabedit" => complete_matrix_names(text, cursor, store),
"room" => vec![],
"verify" => vec![],
"vertical" | "horizontal" | "aboveleft" | "belowright" | "tab" => {
complete_cmd(desc.arg.text.as_str(), text, cursor, store)
},
_ => vec![],
}
}
fn complete_cmd(
cmd: &str,
text: &EditRope,
cursor: &mut Cursor,
store: &ProgramStore,
) -> Vec<String> {
match CommandDescription::from_str(cmd) {
Ok(desc) => {
if desc.arg.untrimmed.is_empty() {
complete_cmdname(desc, text, cursor, store)
} else {
// Complete command argument.
complete_cmdarg(desc, text, cursor, store)
}
},
// Can't parse command text, so return zero completions.
Err(_) => vec![],
}
}
fn complete_cmdbar(text: &EditRope, cursor: &mut Cursor, store: &ProgramStore) -> Vec<String> {
let eo = text.cursor_to_offset(cursor);
let slice = text.slice(0.into(), eo, false);
let cow = Cow::from(&slice);
complete_cmd(cow.as_ref(), text, cursor, store)
}
#[cfg(test)]
pub mod tests {
use super::*;
use crate::config::user_style_from_color;
use crate::tests::*;
use modalkit::tui::style::Color;
#[test]
fn test_typing_spans() {
let mut info = RoomInfo::default();
let settings = mock_settings();
let users0 = vec![];
let users1 = vec![TEST_USER1.clone()];
let users2 = vec![TEST_USER1.clone(), TEST_USER2.clone()];
let users4 = vec![
TEST_USER1.clone(),
TEST_USER2.clone(),
TEST_USER3.clone(),
TEST_USER4.clone(),
];
let users5 = vec![
TEST_USER1.clone(),
TEST_USER2.clone(),
TEST_USER3.clone(),
TEST_USER4.clone(),
TEST_USER5.clone(),
];
// Nothing set.
assert_eq!(info.users_typing, None);
assert_eq!(info.get_typing_spans(&settings), Spans(vec![]));
// Empty typing list.
info.set_typing(users0);
assert!(info.users_typing.is_some());
assert_eq!(info.get_typing_spans(&settings), Spans(vec![]));
// Single user typing.
info.set_typing(users1);
assert!(info.users_typing.is_some());
assert_eq!(
info.get_typing_spans(&settings),
Spans(vec![
Span::styled("@user1:example.com", user_style("@user1:example.com")),
Span::from(" is typing...")
])
);
// Two users typing.
info.set_typing(users2);
assert!(info.users_typing.is_some());
assert_eq!(
info.get_typing_spans(&settings),
Spans(vec![
Span::styled("@user1:example.com", user_style("@user1:example.com")),
Span::raw(" and "),
Span::styled("@user2:example.com", user_style("@user2:example.com")),
Span::raw(" are typing...")
])
);
// Four users typing.
info.set_typing(users4);
assert!(info.users_typing.is_some());
assert_eq!(info.get_typing_spans(&settings), Spans::from("Several people are typing..."));
// Five users typing.
info.set_typing(users5);
assert!(info.users_typing.is_some());
assert_eq!(info.get_typing_spans(&settings), Spans::from("Many people are typing..."));
// Test that USER5 gets rendered using the configured color and name.
info.set_typing(vec![TEST_USER5.clone()]);
assert!(info.users_typing.is_some());
assert_eq!(
info.get_typing_spans(&settings),
Spans(vec![
Span::styled("USER 5", user_style_from_color(Color::Black)),
Span::from(" is typing...")
])
);
}
#[tokio::test]
async fn test_complete_msgbar() {
let store = mock_store().await;
let text = EditRope::from("going for a walk :walk ");
let mut cursor = Cursor::new(0, 22);
let res = complete_msgbar(&text, &mut cursor, &store);
assert_eq!(res, vec![":walking:", ":walking_man:", ":walking_woman:"]);
assert_eq!(cursor, Cursor::new(0, 17));
let text = EditRope::from("hello @user1 ");
let mut cursor = Cursor::new(0, 12);
let res = complete_msgbar(&text, &mut cursor, &store);
assert_eq!(res, vec!["@user1:example.com"]);
assert_eq!(cursor, Cursor::new(0, 6));
let text = EditRope::from("see #room ");
let mut cursor = Cursor::new(0, 9);
let res = complete_msgbar(&text, &mut cursor, &store);
assert_eq!(res, vec!["#room1:example.com"]);
assert_eq!(cursor, Cursor::new(0, 4));
}
#[tokio::test]
async fn test_complete_cmdbar() {
let store = mock_store().await;
let users = vec![
"@user1:example.com",
"@user2:example.com",
"@user3:example.com",
"@user4:example.com",
"@user5:example.com",
];
let text = EditRope::from("invite ");
let mut cursor = Cursor::new(0, 7);
let id = text
.get_prefix_word_mut(&mut cursor, &MATRIX_ID_WORD)
.unwrap_or_else(EditRope::empty);
assert_eq!(id.to_string(), "");
assert_eq!(cursor, Cursor::new(0, 7));
let text = EditRope::from("invite ");
let mut cursor = Cursor::new(0, 7);
let res = complete_cmdbar(&text, &mut cursor, &store);
assert_eq!(res, users);
let text = EditRope::from("invite ignored");
let mut cursor = Cursor::new(0, 7);
let res = complete_cmdbar(&text, &mut cursor, &store);
assert_eq!(res, users);
let text = EditRope::from("invite @user1ignored");
let mut cursor = Cursor::new(0, 13);
let res = complete_cmdbar(&text, &mut cursor, &store);
assert_eq!(res, vec!["@user1:example.com"]);
let text = EditRope::from("abo hor");
let mut cursor = Cursor::new(0, 7);
let res = complete_cmdbar(&text, &mut cursor, &store);
assert_eq!(res, vec!["horizontal"]);
let text = EditRope::from("abo hor inv");
let mut cursor = Cursor::new(0, 11);
let res = complete_cmdbar(&text, &mut cursor, &store);
assert_eq!(res, vec!["invite"]);
let text = EditRope::from("abo hor invite \n");
let mut cursor = Cursor::new(0, 15);
let res = complete_cmdbar(&text, &mut cursor, &store);
assert_eq!(res, users);
}
}
07070100000015000081A400000000000000000000000164A9007B00007EF3000000000000000000000000000000000000001B00000000iamb-0.0.8/src/commands.rsuse std::convert::TryFrom;
use matrix_sdk::ruma::{events::tag::TagName, OwnedUserId};
use modalkit::{
editing::base::OpenTarget,
env::vim::command::{CommandContext, CommandDescription, OptionType},
input::commands::{CommandError, CommandResult, CommandStep},
input::InputContext,
};
use crate::base::{
CreateRoomFlags,
CreateRoomType,
DownloadFlags,
HomeserverAction,
IambAction,
IambId,
MessageAction,
ProgramCommand,
ProgramCommands,
ProgramContext,
RoomAction,
RoomField,
SendAction,
VerifyAction,
};
type ProgContext = CommandContext<ProgramContext>;
type ProgResult = CommandResult<ProgramCommand>;
/// Convert strings the user types into a tag name.
fn tag_name(name: String) -> Result<TagName, CommandError> {
let tag = match name.as_str() {
"fav" | "favorite" | "favourite" | "m.favourite" => TagName::Favorite,
"low" | "lowpriority" | "low_priority" | "low-priority" | "m.lowpriority" => {
TagName::LowPriority
},
"servernotice" | "server_notice" | "server-notice" | "m.server_notice" => {
TagName::ServerNotice
},
_ => {
if let Ok(tag) = name.parse() {
TagName::User(tag)
} else {
let msg = format!("Invalid user tag name: {name}");
return Err(CommandError::Error(msg));
}
},
};
Ok(tag)
}
fn iamb_invite(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
let args = desc.arg.strings()?;
if args.is_empty() {
return Err(CommandError::InvalidArgument);
}
let ract = match args[0].as_str() {
"accept" => {
if args.len() != 1 {
return Err(CommandError::InvalidArgument);
}
RoomAction::InviteAccept
},
"reject" => {
if args.len() != 1 {
return Err(CommandError::InvalidArgument);
}
RoomAction::InviteReject
},
"send" => {
if args.len() != 2 {
return Err(CommandError::InvalidArgument);
}
if let Ok(user) = OwnedUserId::try_from(args[1].as_str()) {
RoomAction::InviteSend(user)
} else {
let msg = format!("Invalid user identifier: {}", args[1]);
let err = CommandError::Error(msg);
return Err(err);
}
},
_ => {
return Err(CommandError::InvalidArgument);
},
};
let iact = IambAction::from(ract);
let step = CommandStep::Continue(iact.into(), ctx.context.take());
return Ok(step);
}
fn iamb_verify(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
let mut args = desc.arg.strings()?;
match args.len() {
0 => {
let open = ctx.switch(OpenTarget::Application(IambId::VerifyList));
let step = CommandStep::Continue(open, ctx.context.take());
return Ok(step);
},
1 => {
return Result::Err(CommandError::InvalidArgument);
},
2 => {
let act = match args[0].as_str() {
"accept" => VerifyAction::Accept,
"cancel" => VerifyAction::Cancel,
"confirm" => VerifyAction::Confirm,
"mismatch" => VerifyAction::Mismatch,
"request" => {
let iact = IambAction::VerifyRequest(args.remove(1));
let step = CommandStep::Continue(iact.into(), ctx.context.take());
return Ok(step);
},
_ => return Result::Err(CommandError::InvalidArgument),
};
let vact = IambAction::Verify(act, args.remove(1));
let step = CommandStep::Continue(vact.into(), ctx.context.take());
return Ok(step);
},
_ => {
return Result::Err(CommandError::InvalidArgument);
},
}
}
fn iamb_dms(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
if !desc.arg.text.is_empty() {
return Result::Err(CommandError::InvalidArgument);
}
let open = ctx.switch(OpenTarget::Application(IambId::DirectList));
let step = CommandStep::Continue(open, ctx.context.take());
return Ok(step);
}
fn iamb_members(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
if !desc.arg.text.is_empty() {
return Result::Err(CommandError::InvalidArgument);
}
let open = IambAction::Room(RoomAction::Members(ctx.clone().into()));
let step = CommandStep::Continue(open.into(), ctx.context.take());
return Ok(step);
}
fn iamb_leave(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
if !desc.arg.text.is_empty() {
return Result::Err(CommandError::InvalidArgument);
}
let leave = IambAction::Room(RoomAction::Leave(desc.bang));
let step = CommandStep::Continue(leave.into(), ctx.context.take());
return Ok(step);
}
fn iamb_cancel(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
if !desc.arg.text.is_empty() {
return Result::Err(CommandError::InvalidArgument);
}
let mact = IambAction::from(MessageAction::Cancel(desc.bang));
let step = CommandStep::Continue(mact.into(), ctx.context.take());
return Ok(step);
}
fn iamb_edit(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
if !desc.arg.text.is_empty() {
return Result::Err(CommandError::InvalidArgument);
}
let mact = IambAction::from(MessageAction::Edit);
let step = CommandStep::Continue(mact.into(), ctx.context.take());
return Ok(step);
}
fn iamb_react(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
let args = desc.arg.strings()?;
if args.len() != 1 {
return Result::Err(CommandError::InvalidArgument);
}
let k = args[0].as_str();
if let Some(emoji) = emojis::get(k).or_else(|| emojis::get_by_shortcode(k)) {
let mact = IambAction::from(MessageAction::React(emoji.to_string()));
let step = CommandStep::Continue(mact.into(), ctx.context.take());
return Ok(step);
} else {
let msg = format!("Invalid Emoji or shortcode: {k}");
return Result::Err(CommandError::Error(msg));
}
}
fn iamb_unreact(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
let mut args = desc.arg.strings()?;
if args.len() > 1 {
return Result::Err(CommandError::InvalidArgument);
}
let mact = if let Some(k) = args.pop() {
let k = k.as_str();
if let Some(emoji) = emojis::get(k).or_else(|| emojis::get_by_shortcode(k)) {
IambAction::from(MessageAction::Unreact(Some(emoji.to_string())))
} else {
let msg = format!("Invalid Emoji or shortcode: {k}");
return Result::Err(CommandError::Error(msg));
}
} else {
IambAction::from(MessageAction::Unreact(None))
};
let step = CommandStep::Continue(mact.into(), ctx.context.take());
return Ok(step);
}
fn iamb_redact(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
let args = desc.arg.strings()?;
if args.len() > 1 {
return Result::Err(CommandError::InvalidArgument);
}
let reason = args.into_iter().next();
let ract = IambAction::from(MessageAction::Redact(reason, desc.bang));
let step = CommandStep::Continue(ract.into(), ctx.context.take());
return Ok(step);
}
fn iamb_reply(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
if !desc.arg.text.is_empty() {
return Result::Err(CommandError::InvalidArgument);
}
let ract = IambAction::from(MessageAction::Reply);
let step = CommandStep::Continue(ract.into(), ctx.context.take());
return Ok(step);
}
fn iamb_rooms(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
if !desc.arg.text.is_empty() {
return Result::Err(CommandError::InvalidArgument);
}
let open = ctx.switch(OpenTarget::Application(IambId::RoomList));
let step = CommandStep::Continue(open, ctx.context.take());
return Ok(step);
}
fn iamb_spaces(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
if !desc.arg.text.is_empty() {
return Result::Err(CommandError::InvalidArgument);
}
let open = ctx.switch(OpenTarget::Application(IambId::SpaceList));
let step = CommandStep::Continue(open, ctx.context.take());
return Ok(step);
}
fn iamb_welcome(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
if !desc.arg.text.is_empty() {
return Result::Err(CommandError::InvalidArgument);
}
let open = ctx.switch(OpenTarget::Application(IambId::Welcome));
let step = CommandStep::Continue(open, ctx.context.take());
return Ok(step);
}
fn iamb_join(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
let mut args = desc.arg.filenames()?;
if args.len() != 1 {
return Result::Err(CommandError::InvalidArgument);
}
let open = ctx.switch(args.remove(0));
let step = CommandStep::Continue(open, ctx.context.take());
return Ok(step);
}
fn iamb_create(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
let args = desc.arg.options()?;
let mut flags = CreateRoomFlags::NONE;
let mut alias = None;
let mut ct = CreateRoomType::Room;
for arg in args {
match arg {
OptionType::Flag(name, Some(arg)) => {
match name.as_str() {
"alias" => {
if alias.is_some() {
let msg = "Multiple ++alias arguments are not allowed";
let err = CommandError::Error(msg.into());
return Err(err);
} else {
alias = Some(arg);
}
},
_ => return Err(CommandError::InvalidArgument),
}
},
OptionType::Flag(name, None) => {
match name.as_str() {
"public" => flags |= CreateRoomFlags::PUBLIC,
"space" => ct = CreateRoomType::Space,
"enc" | "encrypted" => flags |= CreateRoomFlags::ENCRYPTED,
_ => return Err(CommandError::InvalidArgument),
}
},
OptionType::Positional(_) => {
let msg = ":create doesn't take any positional arguments";
let err = CommandError::Error(msg.into());
return Err(err);
},
}
}
let hact = HomeserverAction::CreateRoom(alias, ct, flags);
let iact = IambAction::from(hact);
let step = CommandStep::Continue(iact.into(), ctx.context.take());
return Ok(step);
}
fn iamb_room(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
let mut args = desc.arg.strings()?;
if args.len() < 2 {
return Result::Err(CommandError::InvalidArgument);
}
let field = args.remove(0);
let action = args.remove(0);
if args.len() > 1 {
return Result::Err(CommandError::InvalidArgument);
}
let act: IambAction = match (field.as_str(), action.as_str(), args.pop()) {
// :room name set <room-name>
("name", "set", Some(s)) => RoomAction::Set(RoomField::Name, s).into(),
("name", "set", None) => return Result::Err(CommandError::InvalidArgument),
// :room name unset
("name", "unset", None) => RoomAction::Unset(RoomField::Name).into(),
("name", "unset", Some(_)) => return Result::Err(CommandError::InvalidArgument),
// :room topic set <topic>
("topic", "set", Some(s)) => RoomAction::Set(RoomField::Topic, s).into(),
("topic", "set", None) => return Result::Err(CommandError::InvalidArgument),
// :room topic unset
("topic", "unset", None) => RoomAction::Unset(RoomField::Topic).into(),
("topic", "unset", Some(_)) => return Result::Err(CommandError::InvalidArgument),
// :room tag set <tag-name>
("tag", "set", Some(s)) => RoomAction::Set(RoomField::Tag(tag_name(s)?), "".into()).into(),
("tag", "set", None) => return Result::Err(CommandError::InvalidArgument),
// :room tag unset <tag-name>
("tag", "unset", Some(s)) => RoomAction::Unset(RoomField::Tag(tag_name(s)?)).into(),
("tag", "unset", None) => return Result::Err(CommandError::InvalidArgument),
_ => return Result::Err(CommandError::InvalidArgument),
};
let step = CommandStep::Continue(act.into(), ctx.context.take());
return Ok(step);
}
fn iamb_upload(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
let mut args = desc.arg.strings()?;
if args.len() != 1 {
return Result::Err(CommandError::InvalidArgument);
}
let sact = SendAction::Upload(args.remove(0));
let iact = IambAction::from(sact);
let step = CommandStep::Continue(iact.into(), ctx.context.take());
return Ok(step);
}
fn iamb_download(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
let mut args = desc.arg.strings()?;
if args.len() > 1 {
return Result::Err(CommandError::InvalidArgument);
}
let mut flags = DownloadFlags::NONE;
if desc.bang {
flags |= DownloadFlags::FORCE;
};
let mact = MessageAction::Download(args.pop(), flags);
let iact = IambAction::from(mact);
let step = CommandStep::Continue(iact.into(), ctx.context.take());
return Ok(step);
}
fn iamb_open(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
let mut args = desc.arg.strings()?;
if args.len() > 1 {
return Result::Err(CommandError::InvalidArgument);
}
let mut flags = DownloadFlags::OPEN;
if desc.bang {
flags |= DownloadFlags::FORCE;
};
let mact = MessageAction::Download(args.pop(), flags);
let iact = IambAction::from(mact);
let step = CommandStep::Continue(iact.into(), ctx.context.take());
return Ok(step);
}
fn add_iamb_commands(cmds: &mut ProgramCommands) {
cmds.add_command(ProgramCommand {
name: "cancel".into(),
aliases: vec![],
f: iamb_cancel,
});
cmds.add_command(ProgramCommand {
name: "create".into(),
aliases: vec![],
f: iamb_create,
});
cmds.add_command(ProgramCommand { name: "dms".into(), aliases: vec![], f: iamb_dms });
cmds.add_command(ProgramCommand {
name: "download".into(),
aliases: vec![],
f: iamb_download,
});
cmds.add_command(ProgramCommand { name: "open".into(), aliases: vec![], f: iamb_open });
cmds.add_command(ProgramCommand { name: "edit".into(), aliases: vec![], f: iamb_edit });
cmds.add_command(ProgramCommand {
name: "invite".into(),
aliases: vec![],
f: iamb_invite,
});
cmds.add_command(ProgramCommand { name: "join".into(), aliases: vec![], f: iamb_join });
cmds.add_command(ProgramCommand {
name: "leave".into(),
aliases: vec![],
f: iamb_leave,
});
cmds.add_command(ProgramCommand {
name: "members".into(),
aliases: vec![],
f: iamb_members,
});
cmds.add_command(ProgramCommand {
name: "react".into(),
aliases: vec![],
f: iamb_react,
});
cmds.add_command(ProgramCommand {
name: "redact".into(),
aliases: vec![],
f: iamb_redact,
});
cmds.add_command(ProgramCommand {
name: "reply".into(),
aliases: vec![],
f: iamb_reply,
});
cmds.add_command(ProgramCommand {
name: "rooms".into(),
aliases: vec![],
f: iamb_rooms,
});
cmds.add_command(ProgramCommand { name: "room".into(), aliases: vec![], f: iamb_room });
cmds.add_command(ProgramCommand {
name: "spaces".into(),
aliases: vec![],
f: iamb_spaces,
});
cmds.add_command(ProgramCommand {
name: "unreact".into(),
aliases: vec![],
f: iamb_unreact,
});
cmds.add_command(ProgramCommand {
name: "upload".into(),
aliases: vec![],
f: iamb_upload,
});
cmds.add_command(ProgramCommand {
name: "verify".into(),
aliases: vec![],
f: iamb_verify,
});
cmds.add_command(ProgramCommand {
name: "welcome".into(),
aliases: vec![],
f: iamb_welcome,
});
}
pub fn setup_commands() -> ProgramCommands {
let mut cmds = ProgramCommands::default();
add_iamb_commands(&mut cmds);
return cmds;
}
#[cfg(test)]
mod tests {
use super::*;
use matrix_sdk::ruma::user_id;
use modalkit::editing::action::WindowAction;
#[test]
fn test_cmd_verify() {
let mut cmds = setup_commands();
let ctx = ProgramContext::default();
let res = cmds.input_cmd(":verify", ctx.clone()).unwrap();
let act = WindowAction::Switch(OpenTarget::Application(IambId::VerifyList));
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd(":verify request @user1:example.com", ctx.clone()).unwrap();
let act = IambAction::VerifyRequest("@user1:example.com".into());
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds
.input_cmd(":verify accept @user1:example.com/FOOBAR", ctx.clone())
.unwrap();
let act = IambAction::Verify(VerifyAction::Accept, "@user1:example.com/FOOBAR".into());
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds
.input_cmd(":verify mismatch @user2:example.com/QUUXBAZ", ctx.clone())
.unwrap();
let act = IambAction::Verify(VerifyAction::Mismatch, "@user2:example.com/QUUXBAZ".into());
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds
.input_cmd(":verify cancel @user3:example.com/MYDEVICE", ctx.clone())
.unwrap();
let act = IambAction::Verify(VerifyAction::Cancel, "@user3:example.com/MYDEVICE".into());
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds
.input_cmd(":verify confirm @user4:example.com/GOODDEV", ctx.clone())
.unwrap();
let act = IambAction::Verify(VerifyAction::Confirm, "@user4:example.com/GOODDEV".into());
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd(":verify confirm", ctx.clone());
assert_eq!(res, Err(CommandError::InvalidArgument));
let res = cmds.input_cmd(":verify cancel @user4:example.com MYDEVICE", ctx.clone());
assert_eq!(res, Err(CommandError::InvalidArgument));
let res = cmds.input_cmd(":verify mismatch a b c d e f", ctx.clone());
assert_eq!(res, Err(CommandError::InvalidArgument));
}
#[test]
fn test_cmd_join() {
let mut cmds = setup_commands();
let ctx = ProgramContext::default();
let res = cmds.input_cmd("join #foobar:example.com", ctx.clone()).unwrap();
let act = WindowAction::Switch(OpenTarget::Name("#foobar:example.com".into()));
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd("join #", ctx.clone()).unwrap();
let act = WindowAction::Switch(OpenTarget::Alternate);
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd("join", ctx.clone());
assert_eq!(res, Err(CommandError::InvalidArgument));
let res = cmds.input_cmd("join foo bar", ctx.clone());
assert_eq!(res, Err(CommandError::InvalidArgument));
}
#[test]
fn test_cmd_room_invalid() {
let mut cmds = setup_commands();
let ctx = ProgramContext::default();
let res = cmds.input_cmd("room", ctx.clone());
assert_eq!(res, Err(CommandError::InvalidArgument));
let res = cmds.input_cmd("room foo", ctx.clone());
assert_eq!(res, Err(CommandError::InvalidArgument));
let res = cmds.input_cmd("room set topic", ctx.clone());
assert_eq!(res, Err(CommandError::InvalidArgument));
}
#[test]
fn test_cmd_room_topic_set() {
let mut cmds = setup_commands();
let ctx = ProgramContext::default();
let res = cmds
.input_cmd("room topic set \"Lots of fun discussion!\"", ctx.clone())
.unwrap();
let act = RoomAction::Set(RoomField::Topic, "Lots of fun discussion!".into());
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds
.input_cmd("room topic set The\\ Discussion\\ Room", ctx.clone())
.unwrap();
let act = RoomAction::Set(RoomField::Topic, "The Discussion Room".into());
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd("room topic set Development", ctx.clone()).unwrap();
let act = RoomAction::Set(RoomField::Topic, "Development".into());
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd("room topic", ctx.clone());
assert_eq!(res, Err(CommandError::InvalidArgument));
let res = cmds.input_cmd("room topic set", ctx.clone());
assert_eq!(res, Err(CommandError::InvalidArgument));
let res = cmds.input_cmd("room topic set A B C", ctx.clone());
assert_eq!(res, Err(CommandError::InvalidArgument));
}
#[test]
fn test_cmd_room_name_invalid() {
let mut cmds = setup_commands();
let ctx = ProgramContext::default();
let res = cmds.input_cmd("room name", ctx.clone());
assert_eq!(res, Err(CommandError::InvalidArgument));
let res = cmds.input_cmd("room name foo", ctx.clone());
assert_eq!(res, Err(CommandError::InvalidArgument));
}
#[test]
fn test_cmd_room_name_set() {
let mut cmds = setup_commands();
let ctx = ProgramContext::default();
let res = cmds.input_cmd("room name set Development", ctx.clone()).unwrap();
let act = RoomAction::Set(RoomField::Name, "Development".into());
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds
.input_cmd("room name set \"Application Development\"", ctx.clone())
.unwrap();
let act = RoomAction::Set(RoomField::Name, "Application Development".into());
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd("room name set", ctx.clone());
assert_eq!(res, Err(CommandError::InvalidArgument));
}
#[test]
fn test_cmd_room_name_unset() {
let mut cmds = setup_commands();
let ctx = ProgramContext::default();
let res = cmds.input_cmd("room name unset", ctx.clone()).unwrap();
let act = RoomAction::Unset(RoomField::Name);
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd("room name unset foo", ctx.clone());
assert_eq!(res, Err(CommandError::InvalidArgument));
}
#[test]
fn test_cmd_room_tag_set() {
let mut cmds = setup_commands();
let ctx = ProgramContext::default();
let res = cmds.input_cmd("room tag set favourite", ctx.clone()).unwrap();
let act = RoomAction::Set(RoomField::Tag(TagName::Favorite), "".into());
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd("room tag set favorite", ctx.clone()).unwrap();
let act = RoomAction::Set(RoomField::Tag(TagName::Favorite), "".into());
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd("room tag set fav", ctx.clone()).unwrap();
let act = RoomAction::Set(RoomField::Tag(TagName::Favorite), "".into());
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd("room tag set low_priority", ctx.clone()).unwrap();
let act = RoomAction::Set(RoomField::Tag(TagName::LowPriority), "".into());
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd("room tag set low-priority", ctx.clone()).unwrap();
let act = RoomAction::Set(RoomField::Tag(TagName::LowPriority), "".into());
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd("room tag set low", ctx.clone()).unwrap();
let act = RoomAction::Set(RoomField::Tag(TagName::LowPriority), "".into());
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd("room tag set servernotice", ctx.clone()).unwrap();
let act = RoomAction::Set(RoomField::Tag(TagName::ServerNotice), "".into());
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd("room tag set server_notice", ctx.clone()).unwrap();
let act = RoomAction::Set(RoomField::Tag(TagName::ServerNotice), "".into());
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd("room tag set server_notice", ctx.clone()).unwrap();
let act = RoomAction::Set(RoomField::Tag(TagName::ServerNotice), "".into());
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd("room tag set u.custom-tag", ctx.clone()).unwrap();
let act = RoomAction::Set(
RoomField::Tag(TagName::User("u.custom-tag".parse().unwrap())),
"".into(),
);
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd("room tag set u.irc", ctx.clone()).unwrap();
let act =
RoomAction::Set(RoomField::Tag(TagName::User("u.irc".parse().unwrap())), "".into());
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd("room tag", ctx.clone());
assert_eq!(res, Err(CommandError::InvalidArgument));
let res = cmds.input_cmd("room tag set", ctx.clone());
assert_eq!(res, Err(CommandError::InvalidArgument));
let res = cmds.input_cmd("room tag set unknown", ctx.clone());
assert_eq!(res, Err(CommandError::Error("Invalid user tag name: unknown".into())));
let res = cmds.input_cmd("room tag set needs-leading-u-dot", ctx.clone());
assert_eq!(
res,
Err(CommandError::Error("Invalid user tag name: needs-leading-u-dot".into()))
);
}
#[test]
fn test_cmd_room_tag_unset() {
let mut cmds = setup_commands();
let ctx = ProgramContext::default();
let res = cmds.input_cmd("room tag unset favourite", ctx.clone()).unwrap();
let act = RoomAction::Unset(RoomField::Tag(TagName::Favorite));
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd("room tag unset favorite", ctx.clone()).unwrap();
let act = RoomAction::Unset(RoomField::Tag(TagName::Favorite));
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd("room tag unset fav", ctx.clone()).unwrap();
let act = RoomAction::Unset(RoomField::Tag(TagName::Favorite));
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd("room tag unset low_priority", ctx.clone()).unwrap();
let act = RoomAction::Unset(RoomField::Tag(TagName::LowPriority));
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd("room tag unset low-priority", ctx.clone()).unwrap();
let act = RoomAction::Unset(RoomField::Tag(TagName::LowPriority));
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd("room tag unset low", ctx.clone()).unwrap();
let act = RoomAction::Unset(RoomField::Tag(TagName::LowPriority));
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd("room tag unset servernotice", ctx.clone()).unwrap();
let act = RoomAction::Unset(RoomField::Tag(TagName::ServerNotice));
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd("room tag unset server_notice", ctx.clone()).unwrap();
let act = RoomAction::Unset(RoomField::Tag(TagName::ServerNotice));
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd("room tag unset server_notice", ctx.clone()).unwrap();
let act = RoomAction::Unset(RoomField::Tag(TagName::ServerNotice));
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd("room tag unset u.custom-tag", ctx.clone()).unwrap();
let act = RoomAction::Unset(RoomField::Tag(TagName::User("u.custom-tag".parse().unwrap())));
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd("room tag unset u.irc", ctx.clone()).unwrap();
let act = RoomAction::Unset(RoomField::Tag(TagName::User("u.irc".parse().unwrap())));
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd("room tag", ctx.clone());
assert_eq!(res, Err(CommandError::InvalidArgument));
let res = cmds.input_cmd("room tag set", ctx.clone());
assert_eq!(res, Err(CommandError::InvalidArgument));
let res = cmds.input_cmd("room tag unset unknown", ctx.clone());
assert_eq!(res, Err(CommandError::Error("Invalid user tag name: unknown".into())));
let res = cmds.input_cmd("room tag unset needs-leading-u-dot", ctx.clone());
assert_eq!(
res,
Err(CommandError::Error("Invalid user tag name: needs-leading-u-dot".into()))
);
}
#[test]
fn test_cmd_invite() {
let mut cmds = setup_commands();
let ctx = ProgramContext::default();
let res = cmds.input_cmd("invite accept", ctx.clone()).unwrap();
let act = IambAction::Room(RoomAction::InviteAccept);
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd("invite reject", ctx.clone()).unwrap();
let act = IambAction::Room(RoomAction::InviteReject);
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd("invite send @user:example.com", ctx.clone()).unwrap();
let act =
IambAction::Room(RoomAction::InviteSend(user_id!("@user:example.com").to_owned()));
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd("invite", ctx.clone());
assert_eq!(res, Err(CommandError::InvalidArgument));
let res = cmds.input_cmd("invite foo", ctx.clone());
assert_eq!(res, Err(CommandError::InvalidArgument));
let res = cmds.input_cmd("invite accept @user:example.com", ctx.clone());
assert_eq!(res, Err(CommandError::InvalidArgument));
let res = cmds.input_cmd("invite reject @user:example.com", ctx.clone());
assert_eq!(res, Err(CommandError::InvalidArgument));
let res = cmds.input_cmd("invite send", ctx.clone());
assert_eq!(res, Err(CommandError::InvalidArgument));
let res = cmds.input_cmd("invite @user:example.com", ctx.clone());
assert_eq!(res, Err(CommandError::InvalidArgument));
}
#[test]
fn test_cmd_redact() {
let mut cmds = setup_commands();
let ctx = ProgramContext::default();
let res = cmds.input_cmd("redact", ctx.clone()).unwrap();
let act = IambAction::Message(MessageAction::Redact(None, false));
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd("redact!", ctx.clone()).unwrap();
let act = IambAction::Message(MessageAction::Redact(None, true));
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd("redact Removed", ctx.clone()).unwrap();
let act = IambAction::Message(MessageAction::Redact(Some("Removed".into()), false));
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd("redact \"Removed\"", ctx.clone()).unwrap();
let act = IambAction::Message(MessageAction::Redact(Some("Removed".into()), false));
assert_eq!(res, vec![(act.into(), ctx.clone())]);
let res = cmds.input_cmd("redact Removed Removed", ctx.clone());
assert_eq!(res, Err(CommandError::InvalidArgument));
}
}
07070100000016000081A400000000000000000000000164A9007B00006077000000000000000000000000000000000000001900000000iamb-0.0.8/src/config.rsuse std::borrow::Cow;
use std::collections::hash_map::DefaultHasher;
use std::collections::HashMap;
use std::fmt;
use std::fs::File;
use std::hash::{Hash, Hasher};
use std::io::BufReader;
use std::path::{Path, PathBuf};
use std::process;
use clap::Parser;
use matrix_sdk::ruma::{OwnedRoomAliasId, OwnedRoomId, OwnedUserId, UserId};
use serde::{de::Error as SerdeError, de::Visitor, Deserialize, Deserializer};
use tracing::Level;
use url::Url;
use modalkit::tui::{
style::{Color, Modifier as StyleModifier, Style},
text::Span,
};
use super::base::{IambId, RoomInfo};
macro_rules! usage {
( $($args: tt)* ) => {
println!($($args)*);
process::exit(2);
}
}
const DEFAULT_REQ_TIMEOUT: u64 = 120;
const COLORS: [Color; 13] = [
Color::Blue,
Color::Cyan,
Color::Green,
Color::LightBlue,
Color::LightGreen,
Color::LightCyan,
Color::LightMagenta,
Color::LightRed,
Color::LightYellow,
Color::Magenta,
Color::Red,
Color::Reset,
Color::Yellow,
];
pub fn user_color(user: &str) -> Color {
let mut hasher = DefaultHasher::new();
user.hash(&mut hasher);
let color = hasher.finish() as usize % COLORS.len();
COLORS[color]
}
pub fn user_style_from_color(color: Color) -> Style {
Style::default().fg(color).add_modifier(StyleModifier::BOLD)
}
fn is_profile_char(c: char) -> bool {
c.is_ascii_alphanumeric() || c == '.' || c == '-'
}
fn validate_profile_name(name: &str) -> bool {
if name.is_empty() {
return false;
}
let mut chars = name.chars();
if !chars.next().map_or(false, |c| c.is_ascii_alphanumeric()) {
return false;
}
name.chars().all(is_profile_char)
}
fn validate_profile_names(names: &HashMap<String, ProfileConfig>) {
for name in names.keys() {
if validate_profile_name(name.as_str()) {
continue;
}
usage!(
"{:?} is not a valid profile name.\n\n\
Profile names can only contain the characters \
a-z, A-Z, and 0-9. Period (.) and hyphen (-) are allowed after the first character.",
name
);
}
}
const VERSION: &str = match option_env!("VERGEN_GIT_SHA") {
None => env!("CARGO_PKG_VERSION"),
Some(_) => concat!(env!("CARGO_PKG_VERSION"), " (", env!("VERGEN_GIT_SHA"), ")"),
};
#[derive(Parser)]
#[clap(version = VERSION, about, long_about = None)]
#[clap(propagate_version = true)]
pub struct Iamb {
#[clap(short = 'P', long, value_parser)]
pub profile: Option<String>,
#[clap(short = 'C', long, value_parser)]
pub config_directory: Option<PathBuf>,
}
#[derive(thiserror::Error, Debug)]
pub enum ConfigError {
#[error("Error reading configuration file: {0}")]
IO(#[from] std::io::Error),
#[error("Error loading configuration file: {0}")]
Invalid(#[from] serde_json::Error),
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LogLevel(pub Level);
pub struct LogLevelVisitor;
impl From<LogLevel> for Level {
fn from(level: LogLevel) -> Level {
level.0
}
}
impl<'de> Visitor<'de> for LogLevelVisitor {
type Value = LogLevel;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a valid log level (e.g. \"warn\" or \"debug\")")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: SerdeError,
{
match value {
"info" => Ok(LogLevel(Level::INFO)),
"debug" => Ok(LogLevel(Level::DEBUG)),
"warn" => Ok(LogLevel(Level::WARN)),
"error" => Ok(LogLevel(Level::ERROR)),
"trace" => Ok(LogLevel(Level::TRACE)),
_ => Err(E::custom("Could not parse log level")),
}
}
}
impl<'de> Deserialize<'de> for LogLevel {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_str(LogLevelVisitor)
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct UserColor(pub Color);
pub struct UserColorVisitor;
impl<'de> Visitor<'de> for UserColorVisitor {
type Value = UserColor;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a valid color")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: SerdeError,
{
match value {
"none" => Ok(UserColor(Color::Reset)),
"red" => Ok(UserColor(Color::Red)),
"black" => Ok(UserColor(Color::Black)),
"green" => Ok(UserColor(Color::Green)),
"yellow" => Ok(UserColor(Color::Yellow)),
"blue" => Ok(UserColor(Color::Blue)),
"magenta" => Ok(UserColor(Color::Magenta)),
"cyan" => Ok(UserColor(Color::Cyan)),
"gray" => Ok(UserColor(Color::Gray)),
"dark-gray" => Ok(UserColor(Color::DarkGray)),
"light-red" => Ok(UserColor(Color::LightRed)),
"light-green" => Ok(UserColor(Color::LightGreen)),
"light-yellow" => Ok(UserColor(Color::LightYellow)),
"light-blue" => Ok(UserColor(Color::LightBlue)),
"light-magenta" => Ok(UserColor(Color::LightMagenta)),
"light-cyan" => Ok(UserColor(Color::LightCyan)),
"white" => Ok(UserColor(Color::White)),
_ => Err(E::custom("Could not parse color")),
}
}
}
impl<'de> Deserialize<'de> for UserColor {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_str(UserColorVisitor)
}
}
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
pub struct UserDisplayTunables {
pub color: Option<UserColor>,
pub name: Option<String>,
}
pub type UserOverrides = HashMap<OwnedUserId, UserDisplayTunables>;
fn merge_users(a: Option<UserOverrides>, b: Option<UserOverrides>) -> Option<UserOverrides> {
match (a, b) {
(Some(a), None) => Some(a),
(None, Some(b)) => Some(b),
(Some(mut a), Some(b)) => {
for (k, v) in b {
a.insert(k, v);
}
Some(a)
},
(None, None) => None,
}
}
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum UserDisplayStyle {
// The Matrix username for the sender (e.g., "@user:example.com").
#[default]
Username,
// The localpart of the Matrix username (e.g., "@user").
LocalPart,
// The display name for the Matrix user, calculated according to the rules from the spec.
//
// This is usually something like "Ada Lovelace" if the user has configured a display name, but
// it can wind up being the Matrix username if there are display name collisions in the room,
// in order to avoid any confusion.
DisplayName,
}
#[derive(Clone)]
pub struct TunableValues {
pub log_level: Level,
pub reaction_display: bool,
pub reaction_shortcode_display: bool,
pub read_receipt_send: bool,
pub read_receipt_display: bool,
pub request_timeout: u64,
pub typing_notice_send: bool,
pub typing_notice_display: bool,
pub users: UserOverrides,
pub username_display: UserDisplayStyle,
pub default_room: Option<String>,
pub open_command: Option<Vec<String>>,
}
#[derive(Clone, Default, Deserialize)]
pub struct Tunables {
pub log_level: Option<LogLevel>,
pub reaction_display: Option<bool>,
pub reaction_shortcode_display: Option<bool>,
pub read_receipt_send: Option<bool>,
pub read_receipt_display: Option<bool>,
pub request_timeout: Option<u64>,
pub typing_notice_send: Option<bool>,
pub typing_notice_display: Option<bool>,
pub users: Option<UserOverrides>,
pub username_display: Option<UserDisplayStyle>,
pub default_room: Option<String>,
pub open_command: Option<Vec<String>>,
}
impl Tunables {
fn merge(self, other: Self) -> Self {
Tunables {
log_level: self.log_level.or(other.log_level),
reaction_display: self.reaction_display.or(other.reaction_display),
reaction_shortcode_display: self
.reaction_shortcode_display
.or(other.reaction_shortcode_display),
read_receipt_send: self.read_receipt_send.or(other.read_receipt_send),
read_receipt_display: self.read_receipt_display.or(other.read_receipt_display),
request_timeout: self.request_timeout.or(other.request_timeout),
typing_notice_send: self.typing_notice_send.or(other.typing_notice_send),
typing_notice_display: self.typing_notice_display.or(other.typing_notice_display),
users: merge_users(self.users, other.users),
username_display: self.username_display.or(other.username_display),
default_room: self.default_room.or(other.default_room),
open_command: self.open_command.or(other.open_command),
}
}
fn values(self) -> TunableValues {
TunableValues {
log_level: self.log_level.map(Level::from).unwrap_or(Level::INFO),
reaction_display: self.reaction_display.unwrap_or(true),
reaction_shortcode_display: self.reaction_shortcode_display.unwrap_or(false),
read_receipt_send: self.read_receipt_send.unwrap_or(true),
read_receipt_display: self.read_receipt_display.unwrap_or(true),
request_timeout: self.request_timeout.unwrap_or(DEFAULT_REQ_TIMEOUT),
typing_notice_send: self.typing_notice_send.unwrap_or(true),
typing_notice_display: self.typing_notice_display.unwrap_or(true),
users: self.users.unwrap_or_default(),
username_display: self.username_display.unwrap_or_default(),
default_room: self.default_room,
open_command: self.open_command,
}
}
}
#[derive(Clone)]
pub struct DirectoryValues {
pub cache: PathBuf,
pub logs: PathBuf,
pub downloads: Option<PathBuf>,
}
#[derive(Clone, Default, Deserialize)]
pub struct Directories {
pub cache: Option<PathBuf>,
pub logs: Option<PathBuf>,
pub downloads: Option<PathBuf>,
}
impl Directories {
fn merge(self, other: Self) -> Self {
Directories {
cache: self.cache.or(other.cache),
logs: self.logs.or(other.logs),
downloads: self.downloads.or(other.downloads),
}
}
fn values(self) -> DirectoryValues {
let cache = self
.cache
.or_else(|| {
let mut dir = dirs::cache_dir()?;
dir.push("iamb");
dir.into()
})
.expect("no dirs.cache value configured!");
let logs = self.logs.unwrap_or_else(|| {
let mut dir = cache.clone();
dir.push("logs");
dir
});
let downloads = self.downloads.or_else(dirs::download_dir);
DirectoryValues { cache, logs, downloads }
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
#[serde(untagged)]
pub enum WindowPath {
AliasId(OwnedRoomAliasId),
RoomId(OwnedRoomId),
UserId(OwnedUserId),
Window(IambId),
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
#[serde(untagged, deny_unknown_fields)]
pub enum WindowLayout {
Window { window: WindowPath },
Split { split: Vec<WindowLayout> },
}
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase", tag = "style")]
pub enum Layout {
/// Restore the layout from the previous session.
#[default]
Restore,
/// Open a single window using the `default_room` value.
New,
/// Open the window layouts described under `tabs`.
Config { tabs: Vec<WindowLayout> },
}
#[derive(Clone, Deserialize)]
pub struct ProfileConfig {
pub user_id: OwnedUserId,
pub url: Url,
pub settings: Option<Tunables>,
pub dirs: Option<Directories>,
pub layout: Option<Layout>,
}
#[derive(Clone, Deserialize)]
pub struct IambConfig {
pub profiles: HashMap<String, ProfileConfig>,
pub default_profile: Option<String>,
pub settings: Option<Tunables>,
pub dirs: Option<Directories>,
pub layout: Option<Layout>,
}
impl IambConfig {
pub fn load(config_json: &Path) -> Result<Self, ConfigError> {
if !config_json.is_file() {
usage!(
"Please create a configuration file at {}\n\n\
For more information try '--help'",
config_json.display(),
);
}
let file = File::open(config_json)?;
let reader = BufReader::new(file);
let config = serde_json::from_reader(reader)?;
Ok(config)
}
}
#[derive(Clone)]
pub struct ApplicationSettings {
pub matrix_dir: PathBuf,
pub layout_json: PathBuf,
pub session_json: PathBuf,
pub profile_name: String,
pub profile: ProfileConfig,
pub tunables: TunableValues,
pub dirs: DirectoryValues,
pub layout: Layout,
}
impl ApplicationSettings {
pub fn load(cli: Iamb) -> Result<Self, Box<dyn std::error::Error>> {
let mut config_dir = cli.config_directory.or_else(dirs::config_dir).unwrap_or_else(|| {
usage!(
"No user configuration directory found;\
please specify one via -C.\n\n
For more information try '--help'"
);
});
config_dir.push("iamb");
let mut config_json = config_dir.clone();
config_json.push("config.json");
let IambConfig {
mut profiles,
default_profile,
dirs,
settings: global,
layout,
} = IambConfig::load(config_json.as_path())?;
validate_profile_names(&profiles);
let (profile_name, mut profile) = if let Some(profile) = cli.profile.or(default_profile) {
profiles.remove_entry(&profile).unwrap_or_else(|| {
usage!(
"No configured profile with the name {:?} in {}",
profile,
config_json.display()
);
})
} else if profiles.len() == 1 {
profiles.into_iter().next().unwrap()
} else {
usage!(
"No profile specified. \
Please use -P or add \"default_profile\" to {}.\n\n\
For more information try '--help'",
config_json.display()
);
};
let layout = profile.layout.take().or(layout).unwrap_or_default();
let tunables = global.unwrap_or_default();
let tunables = profile.settings.take().unwrap_or_default().merge(tunables);
let tunables = tunables.values();
let dirs = dirs.unwrap_or_default();
let dirs = profile.dirs.take().unwrap_or_default().merge(dirs);
let dirs = dirs.values();
// Set up paths that live inside the profile's data directory.
let mut profile_dir = config_dir.clone();
profile_dir.push("profiles");
profile_dir.push(profile_name.as_str());
let mut matrix_dir = profile_dir.clone();
matrix_dir.push("matrix");
let mut session_json = profile_dir;
session_json.push("session.json");
// Set up paths that live inside the profile's cache directory.
let mut cache_dir = dirs.cache.clone();
cache_dir.push("profiles");
cache_dir.push(profile_name.as_str());
let mut layout_json = cache_dir.clone();
layout_json.push("layout.json");
let settings = ApplicationSettings {
matrix_dir,
layout_json,
session_json,
profile_name,
profile,
tunables,
dirs,
layout,
};
Ok(settings)
}
pub fn get_user_char_span<'a>(&self, user_id: &'a UserId) -> Span<'a> {
let (color, c) = self
.tunables
.users
.get(user_id)
.map(|user| {
(
user.color.as_ref().map(|c| c.0),
user.name.as_ref().and_then(|s| s.chars().next()),
)
})
.unwrap_or_default();
let color = color.unwrap_or_else(|| user_color(user_id.as_str()));
let style = user_style_from_color(color);
let c = c.unwrap_or_else(|| user_id.localpart().chars().next().unwrap_or(' '));
Span::styled(String::from(c), style)
}
pub fn get_user_overrides(
&self,
user_id: &UserId,
) -> (Option<Color>, Option<Cow<'static, str>>) {
self.tunables
.users
.get(user_id)
.map(|user| (user.color.as_ref().map(|c| c.0), user.name.clone().map(Cow::Owned)))
.unwrap_or_default()
}
pub fn get_user_style(&self, user_id: &UserId) -> Style {
let color = self
.tunables
.users
.get(user_id)
.and_then(|user| user.color.as_ref().map(|c| c.0))
.unwrap_or_else(|| user_color(user_id.as_str()));
user_style_from_color(color)
}
pub fn get_user_span<'a>(&self, user_id: &'a UserId, info: &'a RoomInfo) -> Span<'a> {
let (color, name) = self.get_user_overrides(user_id);
let color = color.unwrap_or_else(|| user_color(user_id.as_str()));
let style = user_style_from_color(color);
let name = match (name, &self.tunables.username_display) {
(Some(name), _) => name,
(None, UserDisplayStyle::Username) => Cow::Borrowed(user_id.as_str()),
(None, UserDisplayStyle::LocalPart) => Cow::Borrowed(user_id.localpart()),
(None, UserDisplayStyle::DisplayName) => {
if let Some(display) = info.display_names.get(user_id) {
Cow::Borrowed(display.as_str())
} else {
Cow::Borrowed(user_id.as_str())
}
},
};
Span::styled(name, style)
}
}
#[cfg(test)]
mod tests {
use super::*;
use matrix_sdk::ruma::user_id;
use std::convert::TryFrom;
#[test]
fn test_profile_name_invalid() {
assert_eq!(validate_profile_name(""), false);
assert_eq!(validate_profile_name(" "), false);
assert_eq!(validate_profile_name("a b"), false);
assert_eq!(validate_profile_name("foo^bar"), false);
assert_eq!(validate_profile_name("FOO/BAR"), false);
assert_eq!(validate_profile_name("-b-c"), false);
assert_eq!(validate_profile_name("-B-c"), false);
assert_eq!(validate_profile_name(".b-c"), false);
assert_eq!(validate_profile_name(".B-c"), false);
}
#[test]
fn test_profile_name_valid() {
assert_eq!(validate_profile_name("foo"), true);
assert_eq!(validate_profile_name("FOO"), true);
assert_eq!(validate_profile_name("a-b-c"), true);
assert_eq!(validate_profile_name("a-B-c"), true);
assert_eq!(validate_profile_name("a.b-c"), true);
assert_eq!(validate_profile_name("a.B-c"), true);
}
#[test]
fn test_merge_users() {
let a = None;
let b = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
color: Some(UserColor(Color::Red)),
name: Some("Hello".into()),
})]
.into_iter()
.collect::<HashMap<_, _>>();
let c = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
color: Some(UserColor(Color::Green)),
name: Some("World".into()),
})]
.into_iter()
.collect::<HashMap<_, _>>();
let res = merge_users(a.clone(), a.clone());
assert_eq!(res, None);
let res = merge_users(a.clone(), Some(b.clone()));
assert_eq!(res, Some(b.clone()));
let res = merge_users(Some(b.clone()), a.clone());
assert_eq!(res, Some(b.clone()));
let res = merge_users(Some(b.clone()), Some(b.clone()));
assert_eq!(res, Some(b.clone()));
let res = merge_users(Some(b.clone()), Some(c.clone()));
assert_eq!(res, Some(c.clone()));
let res = merge_users(Some(c.clone()), Some(b.clone()));
assert_eq!(res, Some(b.clone()));
}
#[test]
fn test_parse_tunables() {
let res: Tunables = serde_json::from_str("{}").unwrap();
assert_eq!(res.typing_notice_send, None);
assert_eq!(res.typing_notice_display, None);
assert_eq!(res.users, None);
let res: Tunables = serde_json::from_str("{\"typing_notice_send\": true}").unwrap();
assert_eq!(res.typing_notice_send, Some(true));
assert_eq!(res.typing_notice_display, None);
assert_eq!(res.users, None);
let res: Tunables = serde_json::from_str("{\"typing_notice_send\": false}").unwrap();
assert_eq!(res.typing_notice_send, Some(false));
assert_eq!(res.typing_notice_display, None);
assert_eq!(res.users, None);
let res: Tunables = serde_json::from_str("{\"users\": {}}").unwrap();
assert_eq!(res.typing_notice_send, None);
assert_eq!(res.typing_notice_display, None);
assert_eq!(res.users, Some(HashMap::new()));
let res: Tunables = serde_json::from_str(
"{\"users\": {\"@a:b.c\": {\"color\": \"black\", \"name\": \"Tim\"}}}",
)
.unwrap();
assert_eq!(res.typing_notice_send, None);
assert_eq!(res.typing_notice_display, None);
let users = vec![(user_id!("@a:b.c").to_owned(), UserDisplayTunables {
color: Some(UserColor(Color::Black)),
name: Some("Tim".into()),
})];
assert_eq!(res.users, Some(users.into_iter().collect()));
}
#[test]
fn test_parse_tunables_username_display() {
let res: Tunables = serde_json::from_str("{\"username_display\": \"username\"}").unwrap();
assert_eq!(res.username_display, Some(UserDisplayStyle::Username));
let res: Tunables = serde_json::from_str("{\"username_display\": \"localpart\"}").unwrap();
assert_eq!(res.username_display, Some(UserDisplayStyle::LocalPart));
let res: Tunables =
serde_json::from_str("{\"username_display\": \"displayname\"}").unwrap();
assert_eq!(res.username_display, Some(UserDisplayStyle::DisplayName));
}
#[test]
fn test_parse_layout() {
let user = WindowPath::UserId(user_id!("@user:example.com").to_owned());
let alias = WindowPath::AliasId(OwnedRoomAliasId::try_from("#room:example.com").unwrap());
let room = WindowPath::RoomId(OwnedRoomId::try_from("!room:example.com").unwrap());
let dms = WindowPath::Window(IambId::DirectList);
let welcome = WindowPath::Window(IambId::Welcome);
let res: Layout = serde_json::from_str("{\"style\": \"restore\"}").unwrap();
assert_eq!(res, Layout::Restore);
let res: Layout = serde_json::from_str("{\"style\": \"new\"}").unwrap();
assert_eq!(res, Layout::New);
let res: Layout = serde_json::from_str(
"{\"style\": \"config\", \"tabs\": [{\"window\":\"@user:example.com\"}]}",
)
.unwrap();
assert_eq!(res, Layout::Config {
tabs: vec![WindowLayout::Window { window: user.clone() }]
});
let res: Layout = serde_json::from_str(
"{\
\"style\": \"config\",\
\"tabs\": [\
{\"split\":[\
{\"window\":\"@user:example.com\"},\
{\"window\":\"#room:example.com\"}\
]},\
{\"split\":[\
{\"window\":\"!room:example.com\"},\
{\"split\":[\
{\"window\":\"iamb://dms\"},\
{\"window\":\"iamb://welcome\"}\
]}\
]}\
]}",
)
.unwrap();
let split1 = WindowLayout::Split {
split: vec![
WindowLayout::Window { window: user.clone() },
WindowLayout::Window { window: alias },
],
};
let split2 = WindowLayout::Split {
split: vec![WindowLayout::Window { window: dms }, WindowLayout::Window {
window: welcome,
}],
};
let split3 = WindowLayout::Split {
split: vec![WindowLayout::Window { window: room }, split2],
};
let tabs = vec![split1, split3];
assert_eq!(res, Layout::Config { tabs });
}
}
07070100000017000081A400000000000000000000000164A9007B000007E1000000000000000000000000000000000000001E00000000iamb-0.0.8/src/keybindings.rsuse modalkit::{
editing::action::WindowAction,
env::vim::keybindings::{InputStep, VimBindings},
env::vim::VimMode,
input::bindings::{EdgeEvent, EdgeRepeat, InputBindings},
input::key::TerminalKey,
};
use crate::base::{IambAction, IambInfo, Keybindings, MATRIX_ID_WORD};
type IambStep = InputStep<IambInfo>;
pub fn setup_keybindings() -> Keybindings {
let mut ism = Keybindings::empty();
let vim = VimBindings::default()
.submit_on_enter()
.cursor_open(MATRIX_ID_WORD.clone());
vim.setup(&mut ism);
let ctrl_w = EdgeEvent::Key("<C-W>".parse::<TerminalKey>().unwrap());
let ctrl_m = EdgeEvent::Key("<C-M>".parse::<TerminalKey>().unwrap());
let ctrl_z = EdgeEvent::Key("<C-Z>".parse::<TerminalKey>().unwrap());
let key_m_lc = EdgeEvent::Key("m".parse::<TerminalKey>().unwrap());
let key_z_lc = EdgeEvent::Key("z".parse::<TerminalKey>().unwrap());
let cwz = vec![
(EdgeRepeat::Once, ctrl_w.clone()),
(EdgeRepeat::Once, key_z_lc),
];
let cwcz = vec![
(EdgeRepeat::Once, ctrl_w.clone()),
(EdgeRepeat::Once, ctrl_z),
];
let zoom = IambStep::new()
.actions(vec![WindowAction::ZoomToggle.into()])
.goto(VimMode::Normal);
ism.add_mapping(VimMode::Normal, &cwz, &zoom);
ism.add_mapping(VimMode::Visual, &cwz, &zoom);
ism.add_mapping(VimMode::Normal, &cwcz, &zoom);
ism.add_mapping(VimMode::Visual, &cwcz, &zoom);
let cwm = vec![
(EdgeRepeat::Once, ctrl_w.clone()),
(EdgeRepeat::Once, key_m_lc),
];
let cwcm = vec![(EdgeRepeat::Once, ctrl_w), (EdgeRepeat::Once, ctrl_m)];
let stoggle = IambStep::new()
.actions(vec![IambAction::ToggleScrollbackFocus.into()])
.goto(VimMode::Normal);
ism.add_mapping(VimMode::Normal, &cwm, &stoggle);
ism.add_mapping(VimMode::Visual, &cwm, &stoggle);
ism.add_mapping(VimMode::Normal, &cwcm, &stoggle);
ism.add_mapping(VimMode::Visual, &cwcm, &stoggle);
return ism;
}
07070100000018000081A400000000000000000000000164A9007B00005C6F000000000000000000000000000000000000001700000000iamb-0.0.8/src/main.rs#![allow(clippy::manual_range_contains)]
#![allow(clippy::needless_return)]
#![allow(clippy::result_large_err)]
#![allow(clippy::bool_assert_comparison)]
use std::collections::VecDeque;
use std::convert::TryFrom;
use std::fmt::Display;
use std::fs::{create_dir_all, File};
use std::io::{stdout, BufReader, BufWriter, Stdout};
use std::ops::DerefMut;
use std::process;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Duration;
use clap::Parser;
use tokio::sync::Mutex as AsyncMutex;
use tracing_subscriber::FmtSubscriber;
use matrix_sdk::{
config::SyncSettings,
ruma::{
api::client::filter::{FilterDefinition, LazyLoadOptions, RoomEventFilter, RoomFilter},
OwnedUserId,
},
};
use modalkit::crossterm::{
self,
cursor::Show as CursorShow,
event::{
poll,
read,
DisableBracketedPaste,
DisableFocusChange,
EnableBracketedPaste,
EnableFocusChange,
Event,
},
execute,
terminal::{EnterAlternateScreen, LeaveAlternateScreen, SetTitle},
};
use modalkit::tui::{
backend::CrosstermBackend,
layout::Rect,
style::{Color, Style},
text::Span,
widgets::Paragraph,
Terminal,
};
mod base;
mod commands;
mod config;
mod keybindings;
mod message;
mod util;
mod windows;
mod worker;
#[cfg(test)]
mod tests;
use crate::{
base::{
AsyncProgramStore,
ChatStore,
HomeserverAction,
IambAction,
IambError,
IambId,
IambInfo,
IambResult,
ProgramAction,
ProgramContext,
ProgramStore,
},
config::{ApplicationSettings, Iamb},
windows::IambWindow,
worker::{create_room, ClientWorker, LoginStyle, Requester},
};
use modalkit::{
editing::{
action::{
Action,
Commandable,
EditError,
EditInfo,
Editable,
EditorAction,
InfoMessage,
InsertTextAction,
Jumpable,
Promptable,
Scrollable,
TabAction,
TabContainer,
TabCount,
UIError,
WindowAction,
WindowContainer,
},
base::{MoveDir1D, OpenTarget, RepeatType},
context::Resolve,
key::KeyManager,
store::Store,
},
input::{bindings::BindingMachine, dialog::Pager, key::TerminalKey},
widgets::{
cmdbar::CommandBarState,
screen::{FocusList, Screen, ScreenState, TabLayoutDescription},
windows::WindowLayoutDescription,
TerminalCursor,
TerminalExtOps,
Window,
},
};
fn config_tab_to_desc(
layout: config::WindowLayout,
store: &mut ProgramStore,
) -> IambResult<WindowLayoutDescription<IambInfo>> {
let desc = match layout {
config::WindowLayout::Window { window } => {
let ChatStore { names, worker, .. } = &mut store.application;
let window = match window {
config::WindowPath::UserId(user_id) => {
let name = user_id.to_string();
let room_id = worker.join_room(name.clone())?;
names.insert(name, room_id.clone());
IambId::Room(room_id)
},
config::WindowPath::RoomId(room_id) => IambId::Room(room_id),
config::WindowPath::AliasId(alias) => {
let name = alias.to_string();
let room_id = worker.join_room(name.clone())?;
names.insert(name, room_id.clone());
IambId::Room(room_id)
},
config::WindowPath::Window(id) => id,
};
WindowLayoutDescription::Window { window, length: None }
},
config::WindowLayout::Split { split } => {
let children = split
.into_iter()
.map(|child| config_tab_to_desc(child, store))
.collect::<IambResult<Vec<_>>>()?;
WindowLayoutDescription::Split { children, length: None }
},
};
Ok(desc)
}
fn setup_screen(
settings: ApplicationSettings,
store: &mut ProgramStore,
) -> IambResult<ScreenState<IambWindow, IambInfo>> {
let cmd = CommandBarState::new(store);
let dims = crossterm::terminal::size()?;
let area = Rect::new(0, 0, dims.0, dims.1);
match settings.layout {
config::Layout::Restore => {
if let Ok(layout) = std::fs::read(&settings.layout_json) {
let tabs: TabLayoutDescription<IambInfo> =
serde_json::from_slice(&layout).map_err(IambError::from)?;
let tabs = tabs.to_layout(area.into(), store)?;
return Ok(ScreenState::from_list(tabs, cmd));
}
},
config::Layout::New => {},
config::Layout::Config { tabs } => {
let mut list = FocusList::default();
for tab in tabs.into_iter() {
let tab = config_tab_to_desc(tab, store)?;
let tab = tab.to_layout(area.into(), store)?;
list.push(tab);
}
return Ok(ScreenState::from_list(list, cmd));
},
}
let win = settings
.tunables
.default_room
.and_then(|room| IambWindow::find(room, store).ok())
.or_else(|| IambWindow::open(IambId::Welcome, store).ok())
.unwrap();
return Ok(ScreenState::new(win, cmd));
}
struct Application {
/// Terminal backend.
terminal: Terminal<CrosstermBackend<Stdout>>,
/// State for the Matrix client, editing, etc.
store: AsyncProgramStore,
/// UI state (open tabs, command bar, etc.) to use when rendering.
screen: ScreenState<IambWindow, IambInfo>,
/// Handle to communicate synchronously with the Matrix worker task.
worker: Requester,
/// Mapped keybindings.
bindings: KeyManager<TerminalKey, ProgramAction, RepeatType, ProgramContext>,
/// Pending actions to run.
actstack: VecDeque<(ProgramAction, ProgramContext)>,
/// Whether or not the terminal is currently focused.
focused: bool,
/// The tab layout before the last executed [TabAction].
last_layout: Option<TabLayoutDescription<IambInfo>>,
}
impl Application {
pub async fn new(
settings: ApplicationSettings,
store: AsyncProgramStore,
) -> IambResult<Application> {
let mut stdout = stdout();
crossterm::terminal::enable_raw_mode()?;
crossterm::execute!(stdout, EnterAlternateScreen)?;
crossterm::execute!(stdout, EnableBracketedPaste)?;
crossterm::execute!(stdout, EnableFocusChange)?;
let title = format!("iamb ({})", settings.profile.user_id);
crossterm::execute!(stdout, SetTitle(title))?;
let backend = CrosstermBackend::new(stdout);
let terminal = Terminal::new(backend)?;
let bindings = crate::keybindings::setup_keybindings();
let bindings = KeyManager::new(bindings);
let mut locked = store.lock().await;
let screen = setup_screen(settings, locked.deref_mut())?;
let worker = locked.application.worker.clone();
drop(locked);
let actstack = VecDeque::new();
Ok(Application {
store,
worker,
terminal,
bindings,
actstack,
screen,
focused: true,
last_layout: None,
})
}
fn redraw(&mut self, full: bool, store: &mut ProgramStore) -> Result<(), std::io::Error> {
let bindings = &mut self.bindings;
let focused = self.focused;
let sstate = &mut self.screen;
let term = &mut self.terminal;
if full {
term.clear()?;
}
term.draw(|f| {
let area = f.size();
let modestr = bindings.show_mode();
let cursor = bindings.get_cursor_indicator();
let dialogstr = bindings.show_dialog(area.height as usize, area.width as usize);
// Don't show terminal cursor when we show a dialog.
let hide_cursor = !dialogstr.is_empty();
let screen = Screen::new(store)
.show_dialog(dialogstr)
.show_mode(modestr)
.borders(true)
.focus(focused);
f.render_stateful_widget(screen, area, sstate);
if hide_cursor {
return;
}
if let Some((cx, cy)) = sstate.get_term_cursor() {
if let Some(c) = cursor {
let style = Style::default().fg(Color::Green);
let span = Span::styled(c.to_string(), style);
let para = Paragraph::new(span);
let inner = Rect::new(cx, cy, 1, 1);
f.render_widget(para, inner)
}
f.set_cursor(cx, cy);
}
})?;
Ok(())
}
async fn step(&mut self) -> Result<TerminalKey, std::io::Error> {
loop {
self.redraw(false, self.store.clone().lock().await.deref_mut())?;
if !poll(Duration::from_secs(1))? {
// Redraw in case there's new messages to show.
continue;
}
match read()? {
Event::Key(ke) => return Ok(ke.into()),
Event::Mouse(_) => {
// Do nothing for now.
},
Event::FocusGained => {
self.focused = true;
},
Event::FocusLost => {
self.focused = false;
},
Event::Resize(_, _) => {
// We'll redraw for the new size next time step() is called.
},
Event::Paste(s) => {
let act = InsertTextAction::Transcribe(s, MoveDir1D::Previous, 1.into());
let act = EditorAction::from(act);
let ctx = ProgramContext::default();
let mut store = self.store.lock().await;
match self.screen.editor_command(&act, &ctx, store.deref_mut()) {
Ok(None) => {},
Ok(Some(info)) => {
drop(store);
self.handle_info(info);
},
Err(e) => {
self.screen.push_error(e);
},
}
},
}
}
}
fn action_prepend(&mut self, acts: Vec<(ProgramAction, ProgramContext)>) {
let mut acts = VecDeque::from(acts);
acts.append(&mut self.actstack);
self.actstack = acts;
}
fn action_pop(&mut self, keyskip: bool) -> Option<(ProgramAction, ProgramContext)> {
if let res @ Some(_) = self.actstack.pop_front() {
return res;
}
if keyskip {
return None;
} else {
return self.bindings.pop();
}
}
async fn action_run(
&mut self,
action: ProgramAction,
ctx: ProgramContext,
store: &mut ProgramStore,
) -> IambResult<EditInfo> {
let info = match action {
// Do nothing.
Action::NoOp => None,
Action::Editor(act) => {
match self.screen.editor_command(&act, &ctx, store) {
Ok(info) => info,
Err(EditError::WrongBuffer(content)) if act.is_switchable(&ctx) => {
// Switch to the right window.
if let Some(winid) = content.to_window() {
let open = OpenTarget::Application(winid);
let open = WindowAction::Switch(open);
let _ = self.screen.window_command(&open, &ctx, store)?;
// Run command again.
self.screen.editor_command(&act, &ctx, store)?
} else {
return Err(EditError::WrongBuffer(content).into());
}
},
Err(err) => return Err(err.into()),
}
},
// Simple delegations.
Action::Application(act) => self.iamb_run(act, ctx, store).await?,
Action::CommandBar(act) => self.screen.command_bar(&act, &ctx)?,
Action::Macro(act) => self.bindings.macro_command(&act, &ctx, store)?,
Action::Scroll(style) => self.screen.scroll(&style, &ctx, store)?,
Action::ShowInfoMessage(info) => Some(info),
Action::Window(cmd) => self.screen.window_command(&cmd, &ctx, store)?,
Action::Jump(l, dir, count) => {
let count = ctx.resolve(&count);
let _ = self.screen.jump(l, dir, count, &ctx)?;
None
},
Action::Suspend => {
self.terminal.program_suspend()?;
None
},
// UI actions.
Action::Tab(cmd) => {
if let TabAction::Close(_, _) = &cmd {
self.last_layout = self.screen.as_description().into();
}
self.screen.tab_command(&cmd, &ctx, store)?
},
Action::RedrawScreen => {
self.screen.clear_message();
self.redraw(true, store)?;
None
},
// Actions that create more Actions.
Action::Prompt(act) => {
let acts = self.screen.prompt(&act, &ctx, store)?;
self.action_prepend(acts);
None
},
Action::Command(act) => {
let acts = store.application.cmds.command(&act, &ctx)?;
self.action_prepend(acts);
None
},
Action::Repeat(rt) => {
self.bindings.repeat(rt, Some(ctx));
None
},
// Unimplemented.
Action::KeywordLookup => {
// XXX: implement
None
},
_ => {
// XXX: log unhandled actions? print message?
None
},
};
return Ok(info);
}
async fn iamb_run(
&mut self,
action: IambAction,
ctx: ProgramContext,
store: &mut ProgramStore,
) -> IambResult<EditInfo> {
let info = match action {
IambAction::ToggleScrollbackFocus => {
self.screen.current_window_mut()?.focus_toggle();
None
},
IambAction::Homeserver(act) => {
let acts = self.homeserver_command(act, ctx, store).await?;
self.action_prepend(acts);
None
},
IambAction::Message(act) => {
self.screen.current_window_mut()?.message_command(act, ctx, store).await?
},
IambAction::Room(act) => {
let acts = self.screen.current_window_mut()?.room_command(act, ctx, store).await?;
self.action_prepend(acts);
None
},
IambAction::Send(act) => {
self.screen.current_window_mut()?.send_command(act, ctx, store).await?
},
IambAction::Verify(act, user_dev) => {
if let Some(sas) = store.application.verifications.get(&user_dev) {
self.worker.verify(act, sas.clone())?
} else {
return Err(IambError::InvalidVerificationId(user_dev).into());
}
},
IambAction::VerifyRequest(user_id) => {
if let Ok(user_id) = OwnedUserId::try_from(user_id.as_str()) {
self.worker.verify_request(user_id)?
} else {
return Err(IambError::InvalidUserId(user_id).into());
}
},
};
Ok(info)
}
async fn homeserver_command(
&mut self,
action: HomeserverAction,
ctx: ProgramContext,
store: &mut ProgramStore,
) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> {
match action {
HomeserverAction::CreateRoom(alias, vis, flags) => {
let client = &store.application.worker.client;
let room_id = create_room(client, alias.as_deref(), vis, flags).await?;
let room = IambId::Room(room_id);
let target = OpenTarget::Application(room);
let action = WindowAction::Switch(target);
Ok(vec![(action.into(), ctx)])
},
}
}
fn handle_info(&mut self, info: InfoMessage) {
match info {
InfoMessage::Message(info) => {
self.screen.push_info(info);
},
InfoMessage::Pager(text) => {
let pager = Box::new(Pager::new(text, vec![]));
self.bindings.run_dialog(pager);
},
}
}
pub async fn run(&mut self) -> Result<(), std::io::Error> {
self.terminal.clear()?;
let store = self.store.clone();
while self.screen.tabs() != 0 {
let key = self.step().await?;
self.bindings.input_key(key);
let mut locked = store.lock().await;
let mut keyskip = false;
while let Some((action, ctx)) = self.action_pop(keyskip) {
match self.action_run(action, ctx, locked.deref_mut()).await {
Ok(None) => {
// Continue processing.
continue;
},
Ok(Some(info)) => {
self.handle_info(info);
// Continue processing; we'll redraw later.
continue;
},
Err(
UIError::NeedConfirm(dialog) |
UIError::EditingFailure(EditError::NeedConfirm(dialog)),
) => {
self.bindings.run_dialog(dialog);
continue;
},
Err(e) => {
self.screen.push_error(e);
// Skip processing any more keypress Actions until the next key.
keyskip = true;
continue;
},
}
}
}
if let Some(ref layout) = self.last_layout {
let locked = self.store.lock().await;
let path = locked.application.settings.layout_json.as_path();
path.parent().map(create_dir_all).transpose()?;
let file = File::create(path)?;
let writer = BufWriter::new(file);
if let Err(e) = serde_json::to_writer(writer, layout) {
tracing::error!("Failed to save window layout while exiting: {}", e);
}
}
crossterm::terminal::disable_raw_mode()?;
execute!(self.terminal.backend_mut(), LeaveAlternateScreen)?;
self.terminal.show_cursor()?;
return Ok(());
}
}
async fn login(worker: Requester, settings: &ApplicationSettings) -> IambResult<()> {
println!("Logging in for {}...", settings.profile.user_id);
if settings.session_json.is_file() {
let file = File::open(settings.session_json.as_path())?;
let reader = BufReader::new(file);
let session = serde_json::from_reader(reader).map_err(IambError::from)?;
worker.login(LoginStyle::SessionRestore(session))?;
return Ok(());
}
loop {
let password = rpassword::prompt_password("Password: ")?;
match worker.login(LoginStyle::Password(password)) {
Ok(info) => {
if let Some(msg) = info {
println!("{msg}");
}
break;
},
Err(err) => {
println!("Failed to login: {err}");
continue;
},
}
}
// Perform an initial, lazily-loaded sync.
let mut room = RoomEventFilter::default();
room.lazy_load_options = LazyLoadOptions::Enabled { include_redundant_members: false };
let mut room_ev = RoomFilter::default();
room_ev.state = room;
let mut filter = FilterDefinition::default();
filter.room = room_ev;
let settings = SyncSettings::new().filter(filter.into());
worker.client.sync_once(settings).await.map_err(IambError::from)?;
Ok(())
}
fn print_exit<T: Display, N>(v: T) -> N {
println!("{v}");
process::exit(2);
}
async fn run(settings: ApplicationSettings) -> IambResult<()> {
// Set up the async worker thread and global store.
let worker = ClientWorker::spawn(settings.clone()).await;
let store = ChatStore::new(worker.clone(), settings.clone());
let store = Store::new(store);
let store = Arc::new(AsyncMutex::new(store));
worker.init(store.clone());
login(worker, &settings).await.unwrap_or_else(print_exit);
fn restore_tty() {
let _ = crossterm::terminal::disable_raw_mode();
let _ = crossterm::execute!(stdout(), DisableBracketedPaste);
let _ = crossterm::execute!(stdout(), DisableFocusChange);
let _ = crossterm::execute!(stdout(), LeaveAlternateScreen);
let _ = crossterm::execute!(stdout(), CursorShow);
}
// Make sure panics clean up the terminal properly.
let orig_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |panic_info| {
restore_tty();
orig_hook(panic_info);
process::exit(1);
}));
let mut application = Application::new(settings, store).await?;
// We can now run the application.
application.run().await?;
restore_tty();
Ok(())
}
fn main() -> IambResult<()> {
// Parse command-line flags.
let iamb = Iamb::parse();
// Load configuration and set up the Matrix SDK.
let settings = ApplicationSettings::load(iamb).unwrap_or_else(print_exit);
// Set umask on Unix platforms so that tokens, keys, etc. are only readable by the user.
#[cfg(unix)]
unsafe {
libc::umask(0o077);
};
// Set up the tracing subscriber so we can log client messages.
let log_prefix = format!("iamb-log-{}", settings.profile_name);
let log_dir = settings.dirs.logs.as_path();
create_dir_all(settings.matrix_dir.as_path())?;
create_dir_all(log_dir)?;
let appender = tracing_appender::rolling::daily(log_dir, log_prefix);
let (appender, guard) = tracing_appender::non_blocking(appender);
let subscriber = FmtSubscriber::builder()
.with_writer(appender)
.with_max_level(settings.tunables.log_level)
.finish();
tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");
let rt = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.worker_threads(2)
.thread_name_fn(|| {
static ATOMIC_ID: AtomicUsize = AtomicUsize::new(0);
let id = ATOMIC_ID.fetch_add(1, Ordering::SeqCst);
format!("iamb-worker-{id}")
})
.build()
.unwrap();
rt.block_on(async move { run(settings).await })?;
drop(guard);
process::exit(0);
}
07070100000019000041ED00000000000000000000000264A9007B00000000000000000000000000000000000000000000001700000000iamb-0.0.8/src/message0707010000001A000081A400000000000000000000000164A9007B00009BEF000000000000000000000000000000000000001F00000000iamb-0.0.8/src/message/html.rs//! # Rendering for formatted bodies
//!
//! This module contains the code for rendering messages that contained an
//! "org.matrix.custom.html"-formatted body.
//!
//! The Matrix specification recommends limiting rendered tags and attributes to a safe subset of
//! HTML. You can read more in section 11.2.1.1, "m.room.message msgtypes":
//!
//! <https://spec.matrix.org/unstable/client-server-api/#mroommessage-msgtypes>
//!
//! This isn't as important for iamb, since it isn't a browser environment, but we do still map
//! input onto an enum of the safe list of tags to keep it easy to understand and process.
use std::ops::Deref;
use css_color_parser::Color as CssColor;
use markup5ever_rcdom::{Handle, NodeData, RcDom};
use unicode_segmentation::UnicodeSegmentation;
use html5ever::{
driver::{parse_fragment, ParseOpts},
interface::{Attribute, QualName},
local_name,
namespace_url,
ns,
tendril::{StrTendril, TendrilSink},
};
use modalkit::tui::{
layout::Alignment,
style::{Color, Modifier as StyleModifier, Style},
symbols::line,
text::{Span, Spans, Text},
};
use crate::{
message::printer::TextPrinter,
util::{join_cell_text, space_text},
};
struct BulletIterator {
style: ListStyle,
pos: usize,
len: usize,
}
impl BulletIterator {
fn width(&self) -> usize {
match self.style {
ListStyle::Unordered => 2,
ListStyle::Ordered => self.len.to_string().len() + 2,
}
}
}
impl Iterator for BulletIterator {
type Item = String;
fn next(&mut self) -> Option<Self::Item> {
if self.pos == self.len {
return None;
}
self.pos += 1;
let bullet = match self.style {
ListStyle::Unordered => "- ".to_string(),
ListStyle::Ordered => {
let w = self.len.to_string().len();
format!("{: >w$}. ", self.pos, w = w)
},
};
return Some(bullet);
}
}
#[derive(Clone, Copy, Debug)]
pub enum ListStyle {
Ordered,
Unordered,
}
impl ListStyle {
fn bullets(&self, len: usize) -> BulletIterator {
BulletIterator { style: *self, pos: 0, len }
}
}
pub type StyleTreeChildren = Vec<StyleTreeNode>;
pub enum CellType {
Data,
Header,
}
pub struct TableRow {
cells: Vec<(CellType, StyleTreeNode)>,
}
impl TableRow {
fn columns(&self) -> usize {
self.cells.len()
}
}
pub struct TableSection {
rows: Vec<TableRow>,
}
impl TableSection {
fn columns(&self) -> usize {
self.rows.iter().map(TableRow::columns).max().unwrap_or(0)
}
}
pub struct Table {
caption: Option<Box<StyleTreeNode>>,
sections: Vec<TableSection>,
}
impl Table {
fn columns(&self) -> usize {
self.sections.iter().map(TableSection::columns).max().unwrap_or(0)
}
fn to_text(&self, width: usize, style: Style) -> Text {
let mut text = Text::default();
let columns = self.columns();
let cell_total = width.saturating_sub(columns).saturating_sub(1);
let cell_min = cell_total / columns;
let mut cell_slop = cell_total - cell_min * columns;
let cell_widths = (0..columns)
.map(|_| {
let slopped = cell_slop.min(1);
cell_slop -= slopped;
cell_min + slopped
})
.collect::<Vec<_>>();
let mut nrows = 0;
if let Some(caption) = &self.caption {
let subw = width.saturating_sub(6);
let mut printer = TextPrinter::new(subw, style, true).align(Alignment::Center);
caption.print(&mut printer, style);
for mut line in printer.finish().lines {
line.0.insert(0, Span::styled(" ", style));
line.0.push(Span::styled(" ", style));
text.lines.push(line);
}
}
for section in self.sections.iter() {
for row in section.rows.iter() {
let mut ruler = String::new();
for (i, w) in cell_widths.iter().enumerate() {
let cross = match (nrows, i) {
(0, 0) => line::TOP_LEFT,
(0, _) => line::HORIZONTAL_DOWN,
(_, 0) => line::VERTICAL_RIGHT,
(_, _) => line::CROSS,
};
ruler.push_str(cross);
for _ in 0..*w {
ruler.push_str(line::HORIZONTAL);
}
}
if nrows == 0 {
ruler.push_str(line::TOP_RIGHT);
} else {
ruler.push_str(line::VERTICAL_LEFT);
}
text.lines.push(Spans(vec![Span::styled(ruler, style)]));
let cells = cell_widths
.iter()
.enumerate()
.map(|(i, w)| {
let text = if let Some((kind, cell)) = row.cells.get(i) {
let style = match kind {
CellType::Header => style.add_modifier(StyleModifier::BOLD),
CellType::Data => style,
};
cell.to_text(*w, style)
} else {
space_text(*w, style)
};
(text, *w)
})
.collect();
let joined = join_cell_text(cells, Span::styled(line::VERTICAL, style), style);
text.lines.extend(joined.lines);
nrows += 1;
}
}
if nrows > 0 {
let mut ruler = String::new();
for (i, w) in cell_widths.iter().enumerate() {
let cross = if i == 0 {
line::BOTTOM_LEFT
} else {
line::HORIZONTAL_UP
};
ruler.push_str(cross);
for _ in 0..*w {
ruler.push_str(line::HORIZONTAL);
}
}
ruler.push_str(line::BOTTOM_RIGHT);
text.lines.push(Spans(vec![Span::styled(ruler, style)]));
}
text
}
}
pub enum StyleTreeNode {
Blockquote(Box<StyleTreeNode>),
Break,
Code(Box<StyleTreeNode>, Option<String>),
Header(Box<StyleTreeNode>, usize),
Image(Option<String>),
List(StyleTreeChildren, ListStyle),
Paragraph(Box<StyleTreeNode>),
Pre(Box<StyleTreeNode>),
Reply(Box<StyleTreeNode>),
Ruler,
Style(Box<StyleTreeNode>, Style),
Table(Table),
Text(String),
Sequence(StyleTreeChildren),
}
impl StyleTreeNode {
pub fn to_text(&self, width: usize, style: Style) -> Text {
let mut printer = TextPrinter::new(width, style, true);
self.print(&mut printer, style);
printer.finish()
}
pub fn print<'a>(&'a self, printer: &mut TextPrinter<'a>, style: Style) {
let width = printer.width();
match self {
StyleTreeNode::Blockquote(child) => {
let mut subp = printer.sub(4);
child.print(&mut subp, style);
for mut line in subp.finish() {
line.0.insert(0, Span::styled(" ", style));
printer.push_line(line);
}
},
StyleTreeNode::Code(child, _) => {
child.print(printer, style);
},
StyleTreeNode::Header(child, level) => {
let style = style.add_modifier(StyleModifier::BOLD);
for _ in 0..*level {
printer.push_str("#", style);
}
printer.push_str(" ", style);
child.print(printer, style);
},
StyleTreeNode::Image(None) => {},
StyleTreeNode::Image(Some(alt)) => {
printer.commit();
printer.push_str("Image Alt: ", Style::default());
printer.push_str(alt, Style::default());
printer.commit();
},
StyleTreeNode::List(children, lt) => {
let mut bullets = lt.bullets(children.len());
let liw = bullets.width();
for child in children {
let mut subp = printer.sub(liw);
let mut bullet = bullets.next();
child.print(&mut subp, style);
for mut line in subp.finish() {
let leading = if let Some(bullet) = bullet.take() {
Span::styled(bullet, style)
} else {
Span::styled(" ".repeat(liw), style)
};
line.0.insert(0, leading);
printer.push_line(line);
}
}
},
StyleTreeNode::Paragraph(child) => {
printer.push_break();
child.print(printer, style);
printer.commit();
},
StyleTreeNode::Pre(child) => {
let mut subp = printer.sub(2).literal(true);
let subw = subp.width();
child.print(&mut subp, style);
printer.commit();
printer.push_line(
vec![
Span::styled(line::TOP_LEFT, style),
Span::styled(line::HORIZONTAL.repeat(subw), style),
Span::styled(line::TOP_RIGHT, style),
]
.into(),
);
for mut line in subp.finish() {
line.0.insert(0, Span::styled(line::VERTICAL, style));
line.0.push(Span::styled(line::VERTICAL, style));
printer.push_line(line);
}
printer.push_line(
vec![
Span::styled(line::BOTTOM_LEFT, style),
Span::styled(line::HORIZONTAL.repeat(subw), style),
Span::styled(line::BOTTOM_RIGHT, style),
]
.into(),
);
printer.commit();
},
StyleTreeNode::Reply(child) => {
if printer.hide_reply() {
return;
}
printer.push_break();
child.print(printer, style);
printer.commit();
},
StyleTreeNode::Ruler => {
for _ in 0..width {
printer.push_str(line::HORIZONTAL, style);
}
},
StyleTreeNode::Table(table) => {
let text = table.to_text(width, style);
printer.push_text(text);
},
StyleTreeNode::Break => {
printer.push_break();
},
StyleTreeNode::Text(s) => {
printer.push_str(s.as_str(), style);
},
StyleTreeNode::Style(child, patch) => child.print(printer, style.patch(*patch)),
StyleTreeNode::Sequence(children) => {
for child in children {
child.print(printer, style);
}
},
}
}
}
pub struct StyleTree {
children: StyleTreeChildren,
}
impl StyleTree {
pub fn to_text(&self, width: usize, style: Style, hide_reply: bool) -> Text<'_> {
let mut printer = TextPrinter::new(width, style, hide_reply);
for child in self.children.iter() {
child.print(&mut printer, style);
}
printer.finish()
}
}
fn c2c(handles: &[Handle]) -> Vec<StyleTreeNode> {
handles.iter().flat_map(h2t).collect()
}
fn c2t(handles: &[Handle]) -> Box<StyleTreeNode> {
let node = StyleTreeNode::Sequence(c2c(handles));
Box::new(node)
}
fn get_node(hdl: &Handle, want: &str) -> Option<StyleTreeNode> {
let node = hdl.deref();
if let NodeData::Element { name, .. } = &node.data {
if name.local.as_ref() != want {
return None;
}
let c = c2c(&node.children.borrow());
return Some(StyleTreeNode::Sequence(c));
} else {
return None;
}
}
fn li2t(hdl: &Handle) -> Option<StyleTreeNode> {
get_node(hdl, "li")
}
fn table_cell(hdl: &Handle) -> Option<(CellType, StyleTreeNode)> {
if let Some(node) = get_node(hdl, "th") {
return Some((CellType::Header, node));
}
Some((CellType::Data, get_node(hdl, "td")?))
}
fn table_row(hdl: &Handle) -> Option<TableRow> {
let node = hdl.deref();
if let NodeData::Element { name, .. } = &node.data {
if name.local.as_ref() != "tr" {
return None;
}
let cells = table_cells(&node.children.borrow());
return Some(TableRow { cells });
} else {
return None;
}
}
fn table_section(hdl: &Handle) -> Option<TableSection> {
let node = hdl.deref();
if let NodeData::Element { name, .. } = &node.data {
match name.local.as_ref() {
"thead" | "tbody" => {
let rows = table_rows(&node.children.borrow());
Some(TableSection { rows })
},
_ => None,
}
} else {
return None;
}
}
fn table_cells(handles: &[Handle]) -> Vec<(CellType, StyleTreeNode)> {
handles.iter().filter_map(table_cell).collect()
}
fn table_rows(handles: &[Handle]) -> Vec<TableRow> {
handles.iter().filter_map(table_row).collect()
}
fn table_sections(handles: &[Handle]) -> Vec<TableSection> {
handles.iter().filter_map(table_section).collect()
}
fn lic2t(handles: &[Handle]) -> StyleTreeChildren {
handles.iter().filter_map(li2t).collect()
}
fn attrs_to_alt(attrs: &[Attribute]) -> Option<String> {
for attr in attrs {
if attr.name.local.as_ref() != "alt" {
continue;
}
return Some(attr.value.to_string());
}
return None;
}
fn attrs_to_language(attrs: &[Attribute]) -> Option<String> {
for attr in attrs {
if attr.name.local.as_ref() != "class" {
continue;
}
for class in attr.value.as_ref().unicode_words() {
if class.len() > 9 && class.starts_with("language-") {
return Some(class[9..].to_string());
}
}
}
return None;
}
fn attrs_to_style(attrs: &[Attribute]) -> Style {
let mut style = Style::default();
for attr in attrs {
match attr.name.local.as_ref() {
"data-mx-bg-color" => {
if let Ok(rgb) = attr.value.as_ref().parse::<CssColor>() {
let color = Color::Rgb(rgb.r, rgb.g, rgb.b);
style = style.bg(color);
}
},
"data-mx-color" | "color" => {
if let Ok(rgb) = attr.value.as_ref().parse::<CssColor>() {
let color = Color::Rgb(rgb.r, rgb.g, rgb.b);
style = style.fg(color);
}
},
_ => continue,
}
}
return style;
}
fn h2t(hdl: &Handle) -> StyleTreeChildren {
let node = hdl.deref();
let tree = match &node.data {
NodeData::Document => *c2t(node.children.borrow().as_slice()),
NodeData::Text { contents } => StyleTreeNode::Text(contents.borrow().to_string()),
NodeData::Element { name, attrs, .. } => {
match name.local.as_ref() {
// Message that this one replies to.
"mx-reply" => StyleTreeNode::Reply(c2t(&node.children.borrow())),
// Style change
"b" | "strong" => {
let c = c2t(&node.children.borrow());
let s = Style::default().add_modifier(StyleModifier::BOLD);
StyleTreeNode::Style(c, s)
},
"font" => {
let c = c2t(&node.children.borrow());
let s = attrs_to_style(&attrs.borrow());
StyleTreeNode::Style(c, s)
},
"em" | "i" => {
let c = c2t(&node.children.borrow());
let s = Style::default().add_modifier(StyleModifier::ITALIC);
StyleTreeNode::Style(c, s)
},
"span" => {
let c = c2t(&node.children.borrow());
let s = attrs_to_style(&attrs.borrow());
StyleTreeNode::Style(c, s)
},
"del" | "strike" => {
let c = c2t(&node.children.borrow());
let s = Style::default().add_modifier(StyleModifier::CROSSED_OUT);
StyleTreeNode::Style(c, s)
},
"u" => {
let c = c2t(&node.children.borrow());
let s = Style::default().add_modifier(StyleModifier::UNDERLINED);
StyleTreeNode::Style(c, s)
},
// Lists
"ol" => StyleTreeNode::List(lic2t(&node.children.borrow()), ListStyle::Ordered),
"ul" => StyleTreeNode::List(lic2t(&node.children.borrow()), ListStyle::Unordered),
// Headers
"h1" => StyleTreeNode::Header(c2t(&node.children.borrow()), 1),
"h2" => StyleTreeNode::Header(c2t(&node.children.borrow()), 2),
"h3" => StyleTreeNode::Header(c2t(&node.children.borrow()), 3),
"h4" => StyleTreeNode::Header(c2t(&node.children.borrow()), 4),
"h5" => StyleTreeNode::Header(c2t(&node.children.borrow()), 5),
"h6" => StyleTreeNode::Header(c2t(&node.children.borrow()), 6),
// Table
"table" => {
let sections = table_sections(&node.children.borrow());
let caption = node
.children
.borrow()
.iter()
.find_map(|hdl| get_node(hdl, "caption"))
.map(Box::new);
let table = Table { caption, sections };
StyleTreeNode::Table(table)
},
// Code blocks.
"code" => {
let c = c2t(&node.children.borrow());
let l = attrs_to_language(&attrs.borrow());
StyleTreeNode::Code(c, l)
},
// Other text blocks.
"blockquote" => StyleTreeNode::Blockquote(c2t(&node.children.borrow())),
"div" | "p" => StyleTreeNode::Paragraph(c2t(&node.children.borrow())),
"pre" => StyleTreeNode::Pre(c2t(&node.children.borrow())),
// No children.
"hr" => StyleTreeNode::Ruler,
"br" => StyleTreeNode::Break,
"img" => StyleTreeNode::Image(attrs_to_alt(&attrs.borrow())),
// These don't render in any special way.
"a" | "details" | "html" | "summary" | "sub" | "sup" => {
*c2t(&node.children.borrow())
},
_ => return vec![],
}
},
// These don't render as anything.
NodeData::Doctype { .. } => return vec![],
NodeData::Comment { .. } => return vec![],
NodeData::ProcessingInstruction { .. } => return vec![],
};
vec![tree]
}
fn dom_to_style_tree(dom: RcDom) -> StyleTree {
StyleTree { children: h2t(&dom.document) }
}
pub fn parse_matrix_html(s: &str) -> StyleTree {
let dom = parse_fragment(
RcDom::default(),
ParseOpts::default(),
QualName::new(None, ns!(html), local_name!("body")),
vec![],
)
.one(StrTendril::from(s));
dom_to_style_tree(dom)
}
#[cfg(test)]
pub mod tests {
use super::*;
use crate::util::space_span;
use pretty_assertions::assert_eq;
#[test]
fn test_header() {
let bold = Style::default().add_modifier(StyleModifier::BOLD);
let s = "<h1>Header 1</h1>";
let tree = parse_matrix_html(s);
let text = tree.to_text(20, Style::default(), false);
assert_eq!(text.lines, vec![Spans(vec![
Span::styled("#", bold),
Span::styled(" ", bold),
Span::styled("Header", bold),
Span::styled(" ", bold),
Span::styled("1", bold),
space_span(10, Style::default())
])]);
let s = "<h2>Header 2</h2>";
let tree = parse_matrix_html(s);
let text = tree.to_text(20, Style::default(), false);
assert_eq!(text.lines, vec![Spans(vec![
Span::styled("#", bold),
Span::styled("#", bold),
Span::styled(" ", bold),
Span::styled("Header", bold),
Span::styled(" ", bold),
Span::styled("2", bold),
space_span(9, Style::default())
])]);
let s = "<h3>Header 3</h3>";
let tree = parse_matrix_html(s);
let text = tree.to_text(20, Style::default(), false);
assert_eq!(text.lines, vec![Spans(vec![
Span::styled("#", bold),
Span::styled("#", bold),
Span::styled("#", bold),
Span::styled(" ", bold),
Span::styled("Header", bold),
Span::styled(" ", bold),
Span::styled("3", bold),
space_span(8, Style::default())
])]);
let s = "<h4>Header 4</h4>";
let tree = parse_matrix_html(s);
let text = tree.to_text(20, Style::default(), false);
assert_eq!(text.lines, vec![Spans(vec![
Span::styled("#", bold),
Span::styled("#", bold),
Span::styled("#", bold),
Span::styled("#", bold),
Span::styled(" ", bold),
Span::styled("Header", bold),
Span::styled(" ", bold),
Span::styled("4", bold),
space_span(7, Style::default())
])]);
let s = "<h5>Header 5</h5>";
let tree = parse_matrix_html(s);
let text = tree.to_text(20, Style::default(), false);
assert_eq!(text.lines, vec![Spans(vec![
Span::styled("#", bold),
Span::styled("#", bold),
Span::styled("#", bold),
Span::styled("#", bold),
Span::styled("#", bold),
Span::styled(" ", bold),
Span::styled("Header", bold),
Span::styled(" ", bold),
Span::styled("5", bold),
space_span(6, Style::default())
])]);
let s = "<h6>Header 6</h6>";
let tree = parse_matrix_html(s);
let text = tree.to_text(20, Style::default(), false);
assert_eq!(text.lines, vec![Spans(vec![
Span::styled("#", bold),
Span::styled("#", bold),
Span::styled("#", bold),
Span::styled("#", bold),
Span::styled("#", bold),
Span::styled("#", bold),
Span::styled(" ", bold),
Span::styled("Header", bold),
Span::styled(" ", bold),
Span::styled("6", bold),
space_span(5, Style::default())
])]);
}
#[test]
fn test_style() {
let def = Style::default();
let bold = def.add_modifier(StyleModifier::BOLD);
let italic = def.add_modifier(StyleModifier::ITALIC);
let strike = def.add_modifier(StyleModifier::CROSSED_OUT);
let underl = def.add_modifier(StyleModifier::UNDERLINED);
let red = def.fg(Color::Rgb(0xff, 0x00, 0x00));
let s = "<b>Bold!</b>";
let tree = parse_matrix_html(s);
let text = tree.to_text(20, Style::default(), false);
assert_eq!(text.lines, vec![Spans(vec![
Span::styled("Bold", bold),
Span::styled("!", bold),
space_span(15, def)
])]);
let s = "<strong>Bold!</strong>";
let tree = parse_matrix_html(s);
let text = tree.to_text(20, Style::default(), false);
assert_eq!(text.lines, vec![Spans(vec![
Span::styled("Bold", bold),
Span::styled("!", bold),
space_span(15, def)
])]);
let s = "<i>Italic!</i>";
let tree = parse_matrix_html(s);
let text = tree.to_text(20, Style::default(), false);
assert_eq!(text.lines, vec![Spans(vec![
Span::styled("Italic", italic),
Span::styled("!", italic),
space_span(13, def)
])]);
let s = "<em>Italic!</em>";
let tree = parse_matrix_html(s);
let text = tree.to_text(20, Style::default(), false);
assert_eq!(text.lines, vec![Spans(vec![
Span::styled("Italic", italic),
Span::styled("!", italic),
space_span(13, def)
])]);
let s = "<del>Strikethrough!</del>";
let tree = parse_matrix_html(s);
let text = tree.to_text(20, Style::default(), false);
assert_eq!(text.lines, vec![Spans(vec![
Span::styled("Strikethrough", strike),
Span::styled("!", strike),
space_span(6, def)
])]);
let s = "<strike>Strikethrough!</strike>";
let tree = parse_matrix_html(s);
let text = tree.to_text(20, Style::default(), false);
assert_eq!(text.lines, vec![Spans(vec![
Span::styled("Strikethrough", strike),
Span::styled("!", strike),
space_span(6, def)
])]);
let s = "<u>Underline!</u>";
let tree = parse_matrix_html(s);
let text = tree.to_text(20, Style::default(), false);
assert_eq!(text.lines, vec![Spans(vec![
Span::styled("Underline", underl),
Span::styled("!", underl),
space_span(10, def)
])]);
let s = "<font color=\"#ff0000\">Red!</u>";
let tree = parse_matrix_html(s);
let text = tree.to_text(20, Style::default(), false);
assert_eq!(text.lines, vec![Spans(vec![
Span::styled("Red", red),
Span::styled("!", red),
space_span(16, def)
])]);
let s = "<font color=\"red\">Red!</u>";
let tree = parse_matrix_html(s);
let text = tree.to_text(20, Style::default(), false);
assert_eq!(text.lines, vec![Spans(vec![
Span::styled("Red", red),
Span::styled("!", red),
space_span(16, def)
])]);
}
#[test]
fn test_paragraph() {
let s = "<p>Hello world!</p><p>Content</p><p>Goodbye world!</p>";
let tree = parse_matrix_html(s);
let text = tree.to_text(10, Style::default(), false);
assert_eq!(text.lines.len(), 7);
assert_eq!(
text.lines[0],
Spans(vec![Span::raw("Hello"), Span::raw(" "), Span::raw(" ")])
);
assert_eq!(
text.lines[1],
Spans(vec![Span::raw("world"), Span::raw("!"), Span::raw(" ")])
);
assert_eq!(text.lines[2], Spans(vec![Span::raw(" ")]));
assert_eq!(text.lines[3], Spans(vec![Span::raw("Content"), Span::raw(" ")]));
assert_eq!(text.lines[4], Spans(vec![Span::raw(" ")]));
assert_eq!(
text.lines[5],
Spans(vec![Span::raw("Goodbye"), Span::raw(" "), Span::raw(" ")])
);
assert_eq!(
text.lines[6],
Spans(vec![Span::raw("world"), Span::raw("!"), Span::raw(" ")])
);
}
#[test]
fn test_blockquote() {
let s = "<blockquote>Hello world!</blockquote>";
let tree = parse_matrix_html(s);
let text = tree.to_text(10, Style::default(), false);
assert_eq!(text.lines.len(), 2);
assert_eq!(
text.lines[0],
Spans(vec![Span::raw(" "), Span::raw("Hello"), Span::raw(" ")])
);
assert_eq!(
text.lines[1],
Spans(vec![Span::raw(" "), Span::raw("world"), Span::raw("!")])
);
}
#[test]
fn test_list_unordered() {
let s = "<ul><li>List Item 1</li><li>List Item 2</li><li>List Item 3</li></ul>";
let tree = parse_matrix_html(s);
let text = tree.to_text(8, Style::default(), false);
assert_eq!(text.lines.len(), 6);
assert_eq!(
text.lines[0],
Spans(vec![
Span::raw("- "),
Span::raw("List"),
Span::raw(" "),
Span::raw(" ")
])
);
assert_eq!(
text.lines[1],
Spans(vec![
Span::raw(" "),
Span::raw("Item"),
Span::raw(" "),
Span::raw("1")
])
);
assert_eq!(
text.lines[2],
Spans(vec![
Span::raw("- "),
Span::raw("List"),
Span::raw(" "),
Span::raw(" ")
])
);
assert_eq!(
text.lines[3],
Spans(vec![
Span::raw(" "),
Span::raw("Item"),
Span::raw(" "),
Span::raw("2")
])
);
assert_eq!(
text.lines[4],
Spans(vec![
Span::raw("- "),
Span::raw("List"),
Span::raw(" "),
Span::raw(" ")
])
);
assert_eq!(
text.lines[5],
Spans(vec![
Span::raw(" "),
Span::raw("Item"),
Span::raw(" "),
Span::raw("3")
])
);
}
#[test]
fn test_list_ordered() {
let s = "<ol><li>List Item 1</li><li>List Item 2</li><li>List Item 3</li></ol>";
let tree = parse_matrix_html(s);
let text = tree.to_text(9, Style::default(), false);
assert_eq!(text.lines.len(), 6);
assert_eq!(
text.lines[0],
Spans(vec![
Span::raw("1. "),
Span::raw("List"),
Span::raw(" "),
Span::raw(" ")
])
);
assert_eq!(
text.lines[1],
Spans(vec![
Span::raw(" "),
Span::raw("Item"),
Span::raw(" "),
Span::raw("1")
])
);
assert_eq!(
text.lines[2],
Spans(vec![
Span::raw("2. "),
Span::raw("List"),
Span::raw(" "),
Span::raw(" ")
])
);
assert_eq!(
text.lines[3],
Spans(vec![
Span::raw(" "),
Span::raw("Item"),
Span::raw(" "),
Span::raw("2")
])
);
assert_eq!(
text.lines[4],
Spans(vec![
Span::raw("3. "),
Span::raw("List"),
Span::raw(" "),
Span::raw(" ")
])
);
assert_eq!(
text.lines[5],
Spans(vec![
Span::raw(" "),
Span::raw("Item"),
Span::raw(" "),
Span::raw("3")
])
);
}
#[test]
fn test_table() {
let s = "<table>\
<thead>\
<tr><th>Column 1</th><th>Column 2</th><th>Column 3</th></tr>
</thead>\
<tbody>\
<tr><td>a</td><td>b</td><td>c</td></tr>\
<tr><td>a</td><td>b</td><td>c</td></tr>\
<tr><td>a</td><td>b</td><td>c</td></tr>\
</tbody></table>";
let tree = parse_matrix_html(s);
let text = tree.to_text(15, Style::default(), false);
let bold = Style::default().add_modifier(StyleModifier::BOLD);
assert_eq!(text.lines.len(), 11);
// Table header
assert_eq!(text.lines[0].0, vec![Span::raw("┌────┬────┬───┐")]);
assert_eq!(text.lines[1].0, vec![
Span::raw("│"),
Span::styled("Colu", bold),
Span::raw("│"),
Span::styled("Colu", bold),
Span::raw("│"),
Span::styled("Col", bold),
Span::raw("│")
]);
assert_eq!(text.lines[2].0, vec![
Span::raw("│"),
Span::styled("mn", bold),
Span::styled(" ", bold),
Span::styled("1", bold),
Span::raw("│"),
Span::styled("mn", bold),
Span::styled(" ", bold),
Span::styled("2", bold),
Span::raw("│"),
Span::styled("umn", bold),
Span::raw("│")
]);
assert_eq!(text.lines[3].0, vec![
Span::raw("│"),
Span::raw(" "),
Span::raw("│"),
Span::raw(" "),
Span::raw("│"),
Span::styled("3", bold),
Span::styled(" ", bold),
Span::raw("│")
]);
// First row
assert_eq!(text.lines[4].0, vec![Span::raw("├────┼────┼───┤")]);
assert_eq!(text.lines[5].0, vec![
Span::raw("│"),
Span::raw("a"),
Span::raw(" "),
Span::raw("│"),
Span::raw("b"),
Span::raw(" "),
Span::raw("│"),
Span::raw("c"),
Span::raw(" "),
Span::raw("│")
]);
// Second row
assert_eq!(text.lines[6].0, vec![Span::raw("├────┼────┼───┤")]);
assert_eq!(text.lines[7].0, vec![
Span::raw("│"),
Span::raw("a"),
Span::raw(" "),
Span::raw("│"),
Span::raw("b"),
Span::raw(" "),
Span::raw("│"),
Span::raw("c"),
Span::raw(" "),
Span::raw("│")
]);
// Third row
assert_eq!(text.lines[8].0, vec![Span::raw("├────┼────┼───┤")]);
assert_eq!(text.lines[9].0, vec![
Span::raw("│"),
Span::raw("a"),
Span::raw(" "),
Span::raw("│"),
Span::raw("b"),
Span::raw(" "),
Span::raw("│"),
Span::raw("c"),
Span::raw(" "),
Span::raw("│")
]);
// Bottom ruler
assert_eq!(text.lines[10].0, vec![Span::raw("└────┴────┴───┘")]);
}
#[test]
fn test_matrix_reply() {
let s = "<mx-reply>This was replied to</mx-reply>This is the reply";
let tree = parse_matrix_html(s);
let text = tree.to_text(10, Style::default(), false);
assert_eq!(text.lines.len(), 4);
assert_eq!(
text.lines[0],
Spans(vec![
Span::raw("This"),
Span::raw(" "),
Span::raw("was"),
Span::raw(" "),
Span::raw(" ")
])
);
assert_eq!(
text.lines[1],
Spans(vec![Span::raw("replied"), Span::raw(" "), Span::raw("to")])
);
assert_eq!(
text.lines[2],
Spans(vec![
Span::raw("This"),
Span::raw(" "),
Span::raw("is"),
Span::raw(" "),
Span::raw(" ")
])
);
assert_eq!(
text.lines[3],
Spans(vec![
Span::raw("the"),
Span::raw(" "),
Span::raw("reply"),
Span::raw(" ")
])
);
let tree = parse_matrix_html(s);
let text = tree.to_text(10, Style::default(), true);
assert_eq!(text.lines.len(), 2);
assert_eq!(
text.lines[0],
Spans(vec![
Span::raw("This"),
Span::raw(" "),
Span::raw("is"),
Span::raw(" "),
Span::raw(" ")
])
);
assert_eq!(
text.lines[1],
Spans(vec![
Span::raw("the"),
Span::raw(" "),
Span::raw("reply"),
Span::raw(" ")
])
);
}
#[test]
fn test_self_closing() {
let s = "Hello<br>World<br>Goodbye";
let tree = parse_matrix_html(s);
let text = tree.to_text(7, Style::default(), true);
assert_eq!(text.lines.len(), 3);
assert_eq!(text.lines[0], Spans(vec![Span::raw("Hello"), Span::raw(" "),]));
assert_eq!(text.lines[1], Spans(vec![Span::raw("World"), Span::raw(" "),]));
assert_eq!(text.lines[2], Spans(vec![Span::raw("Goodbye")]),);
}
#[test]
fn test_embedded_newline() {
let s = "<p>Hello\nWorld</p>";
let tree = parse_matrix_html(s);
let text = tree.to_text(15, Style::default(), true);
assert_eq!(text.lines.len(), 1);
assert_eq!(
text.lines[0],
Spans(vec![
Span::raw("Hello"),
Span::raw(" "),
Span::raw("World"),
Span::raw(" ")
])
);
}
#[test]
fn test_pre_tag() {
let s = concat!(
"<pre><code class=\"language-rust\">",
"fn hello() -> usize {\n",
" return 5;\n",
"}\n",
"</code></pre>\n"
);
let tree = parse_matrix_html(s);
let text = tree.to_text(25, Style::default(), true);
assert_eq!(text.lines.len(), 5);
assert_eq!(
text.lines[0],
Spans(vec![
Span::raw(line::TOP_LEFT),
Span::raw(line::HORIZONTAL.repeat(23)),
Span::raw(line::TOP_RIGHT)
])
);
assert_eq!(
text.lines[1],
Spans(vec![
Span::raw(line::VERTICAL),
Span::raw("fn"),
Span::raw(" "),
Span::raw("hello"),
Span::raw("("),
Span::raw(")"),
Span::raw(" "),
Span::raw("-"),
Span::raw(">"),
Span::raw(" "),
Span::raw("usize"),
Span::raw(" "),
Span::raw("{"),
Span::raw(" "),
Span::raw(line::VERTICAL)
])
);
assert_eq!(
text.lines[2],
Spans(vec![
Span::raw(line::VERTICAL),
Span::raw(" "),
Span::raw("return"),
Span::raw(" "),
Span::raw("5"),
Span::raw(";"),
Span::raw(" "),
Span::raw(line::VERTICAL)
])
);
assert_eq!(
text.lines[3],
Spans(vec![
Span::raw(line::VERTICAL),
Span::raw("}"),
Span::raw(" ".repeat(22)),
Span::raw(line::VERTICAL)
])
);
assert_eq!(
text.lines[4],
Spans(vec![
Span::raw(line::BOTTOM_LEFT),
Span::raw(line::HORIZONTAL.repeat(23)),
Span::raw(line::BOTTOM_RIGHT)
])
);
}
}
0707010000001B000081A400000000000000000000000164A9007B00008652000000000000000000000000000000000000001E00000000iamb-0.0.8/src/message/mod.rsuse std::borrow::Cow;
use std::cmp::{Ord, Ordering, PartialOrd};
use std::collections::hash_map::DefaultHasher;
use std::collections::BTreeMap;
use std::convert::TryFrom;
use std::hash::{Hash, Hasher};
use std::slice::Iter;
use chrono::{DateTime, Local as LocalTz, NaiveDateTime, TimeZone};
use comrak::{markdown_to_html, ComrakOptions};
use unicode_width::UnicodeWidthStr;
use matrix_sdk::ruma::{
events::{
room::{
encrypted::{
OriginalRoomEncryptedEvent,
RedactedRoomEncryptedEvent,
RoomEncryptedEvent,
},
message::{
FormattedBody,
MessageFormat,
MessageType,
OriginalRoomMessageEvent,
RedactedRoomMessageEvent,
Relation,
RoomMessageEvent,
RoomMessageEventContent,
TextMessageEventContent,
},
redaction::SyncRoomRedactionEvent,
},
AnyMessageLikeEvent,
Redact,
RedactedUnsigned,
},
EventId,
MilliSecondsSinceUnixEpoch,
OwnedEventId,
OwnedUserId,
RoomVersionId,
UInt,
};
use modalkit::tui::{
style::{Modifier as StyleModifier, Style},
symbols::line::THICK_VERTICAL,
text::{Span, Spans, Text},
};
use modalkit::editing::{base::ViewportContext, cursor::Cursor};
use crate::{
base::{IambResult, RoomInfo},
config::ApplicationSettings,
message::html::{parse_matrix_html, StyleTree},
util::{space_span, wrapped_text},
};
mod html;
mod printer;
pub type MessageFetchResult = IambResult<(Option<String>, Vec<AnyMessageLikeEvent>)>;
pub type MessageKey = (MessageTimeStamp, OwnedEventId);
pub type Messages = BTreeMap<MessageKey, Message>;
const fn span_static(s: &'static str) -> Span<'static> {
Span {
content: Cow::Borrowed(s),
style: Style {
fg: None,
bg: None,
add_modifier: StyleModifier::empty(),
sub_modifier: StyleModifier::empty(),
},
}
}
const BOLD_STYLE: Style = Style {
fg: None,
bg: None,
add_modifier: StyleModifier::BOLD,
sub_modifier: StyleModifier::empty(),
};
const USER_GUTTER: usize = 30;
const TIME_GUTTER: usize = 12;
const READ_GUTTER: usize = 5;
const MIN_MSG_LEN: usize = 30;
const USER_GUTTER_EMPTY: &str = " ";
const USER_GUTTER_EMPTY_SPAN: Span<'static> = span_static(USER_GUTTER_EMPTY);
const TIME_GUTTER_EMPTY: &str = " ";
const TIME_GUTTER_EMPTY_SPAN: Span<'static> = span_static(TIME_GUTTER_EMPTY);
fn text_to_message_content(input: String) -> TextMessageEventContent {
let mut options = ComrakOptions::default();
options.extension.shortcodes = true;
options.render.hardbreaks = true;
let html = markdown_to_html(input.as_str(), &options);
TextMessageEventContent::html(input, html)
}
pub fn text_to_message(input: String) -> RoomMessageEventContent {
let msg = MessageType::Text(text_to_message_content(input));
RoomMessageEventContent::new(msg)
}
#[inline]
fn millis_to_datetime(ms: UInt) -> DateTime<LocalTz> {
let time = i64::from(ms) / 1000;
let time = NaiveDateTime::from_timestamp_opt(time, 0).unwrap_or_default();
LocalTz.from_utc_datetime(&time)
}
#[derive(thiserror::Error, Debug)]
pub enum TimeStampIntError {
#[error("Integer conversion error: {0}")]
IntError(#[from] std::num::TryFromIntError),
#[error("UInt conversion error: {0}")]
UIntError(<UInt as TryFrom<u64>>::Error),
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MessageTimeStamp {
OriginServer(UInt),
LocalEcho,
}
impl MessageTimeStamp {
fn as_datetime(&self) -> DateTime<LocalTz> {
match self {
MessageTimeStamp::OriginServer(ms) => millis_to_datetime(*ms),
MessageTimeStamp::LocalEcho => LocalTz::now(),
}
}
fn same_day(&self, other: &Self) -> bool {
let dt1 = self.as_datetime();
let dt2 = other.as_datetime();
dt1.date_naive() == dt2.date_naive()
}
fn show_date(&self) -> Option<Span> {
let time = self.as_datetime().format("%A, %B %d %Y").to_string();
Span::styled(time, BOLD_STYLE).into()
}
fn show_time(&self) -> Option<Span> {
match self {
MessageTimeStamp::OriginServer(ms) => {
let time = millis_to_datetime(*ms).format("%T");
let time = format!(" [{time}]");
Span::raw(time).into()
},
MessageTimeStamp::LocalEcho => None,
}
}
fn is_local_echo(&self) -> bool {
matches!(self, MessageTimeStamp::LocalEcho)
}
pub fn as_millis(&self) -> Option<MilliSecondsSinceUnixEpoch> {
match self {
MessageTimeStamp::OriginServer(ms) => MilliSecondsSinceUnixEpoch(*ms).into(),
MessageTimeStamp::LocalEcho => None,
}
}
}
impl Ord for MessageTimeStamp {
fn cmp(&self, other: &Self) -> Ordering {
match (self, other) {
(MessageTimeStamp::OriginServer(_), MessageTimeStamp::LocalEcho) => Ordering::Less,
(MessageTimeStamp::OriginServer(a), MessageTimeStamp::OriginServer(b)) => a.cmp(b),
(MessageTimeStamp::LocalEcho, MessageTimeStamp::OriginServer(_)) => Ordering::Greater,
(MessageTimeStamp::LocalEcho, MessageTimeStamp::LocalEcho) => Ordering::Equal,
}
}
}
impl PartialOrd for MessageTimeStamp {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.cmp(other).into()
}
}
impl From<UInt> for MessageTimeStamp {
fn from(millis: UInt) -> Self {
MessageTimeStamp::OriginServer(millis)
}
}
impl From<MilliSecondsSinceUnixEpoch> for MessageTimeStamp {
fn from(millis: MilliSecondsSinceUnixEpoch) -> Self {
MessageTimeStamp::OriginServer(millis.0)
}
}
impl TryFrom<&MessageTimeStamp> for usize {
type Error = TimeStampIntError;
fn try_from(ts: &MessageTimeStamp) -> Result<Self, Self::Error> {
let n = match ts {
MessageTimeStamp::LocalEcho => 0,
MessageTimeStamp::OriginServer(u) => usize::try_from(u64::from(*u))?,
};
Ok(n)
}
}
impl TryFrom<usize> for MessageTimeStamp {
type Error = TimeStampIntError;
fn try_from(u: usize) -> Result<Self, Self::Error> {
if u == 0 {
Ok(MessageTimeStamp::LocalEcho)
} else {
let n = u64::try_from(u)?;
let n = UInt::try_from(n).map_err(TimeStampIntError::UIntError)?;
Ok(MessageTimeStamp::from(n))
}
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct MessageCursor {
/// When timestamp is None, the corner is determined by moving backwards from
/// the most recently received message.
pub timestamp: Option<MessageKey>,
/// A row within the [Text] representation of a [Message].
pub text_row: usize,
}
impl MessageCursor {
pub fn new(timestamp: MessageKey, text_row: usize) -> Self {
MessageCursor { timestamp: Some(timestamp), text_row }
}
/// Get a cursor that refers to the most recent message.
pub fn latest() -> Self {
MessageCursor::default()
}
pub fn to_key<'a>(&'a self, info: &'a RoomInfo) -> Option<&'a MessageKey> {
if let Some(ref key) = self.timestamp {
Some(key)
} else {
Some(info.messages.last_key_value()?.0)
}
}
pub fn from_cursor(cursor: &Cursor, info: &RoomInfo) -> Option<Self> {
let ev_hash = u64::try_from(cursor.get_x()).ok()?;
let ev_term = OwnedEventId::try_from("$").ok()?;
let ts_start = MessageTimeStamp::try_from(cursor.get_y()).ok()?;
let start = (ts_start, ev_term);
let mut mc = None;
for ((ts, event_id), _) in info.messages.range(start..) {
let mut hasher = DefaultHasher::new();
event_id.hash(&mut hasher);
if hasher.finish() == ev_hash {
mc = Self::from((*ts, event_id.clone())).into();
break;
}
if mc.is_none() {
mc = Self::from((*ts, event_id.clone())).into();
}
if ts > &ts_start {
break;
}
}
return mc;
}
pub fn to_cursor(&self, info: &RoomInfo) -> Option<Cursor> {
let (ts, event_id) = self.to_key(info)?;
let y: usize = usize::try_from(ts).ok()?;
let mut hasher = DefaultHasher::new();
event_id.hash(&mut hasher);
let x = usize::try_from(hasher.finish()).ok()?;
Cursor::new(y, x).into()
}
}
impl From<Option<MessageKey>> for MessageCursor {
fn from(key: Option<MessageKey>) -> Self {
MessageCursor { timestamp: key, text_row: 0 }
}
}
impl From<MessageKey> for MessageCursor {
fn from(key: MessageKey) -> Self {
MessageCursor { timestamp: Some(key), text_row: 0 }
}
}
impl Ord for MessageCursor {
fn cmp(&self, other: &Self) -> Ordering {
match (&self.timestamp, &other.timestamp) {
(None, None) => self.text_row.cmp(&other.text_row),
(None, Some(_)) => Ordering::Greater,
(Some(_), None) => Ordering::Less,
(Some(st), Some(ot)) => {
let pcmp = st.cmp(ot);
let tcmp = self.text_row.cmp(&other.text_row);
pcmp.then(tcmp)
},
}
}
}
impl PartialOrd for MessageCursor {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.cmp(other).into()
}
}
#[derive(Clone)]
pub enum MessageEvent {
EncryptedOriginal(Box<OriginalRoomEncryptedEvent>),
EncryptedRedacted(Box<RedactedRoomEncryptedEvent>),
Original(Box<OriginalRoomMessageEvent>),
Redacted(Box<RedactedRoomMessageEvent>),
Local(OwnedEventId, Box<RoomMessageEventContent>),
}
impl MessageEvent {
pub fn event_id(&self) -> &EventId {
match self {
MessageEvent::EncryptedOriginal(ev) => ev.event_id.as_ref(),
MessageEvent::EncryptedRedacted(ev) => ev.event_id.as_ref(),
MessageEvent::Original(ev) => ev.event_id.as_ref(),
MessageEvent::Redacted(ev) => ev.event_id.as_ref(),
MessageEvent::Local(event_id, _) => event_id.as_ref(),
}
}
pub fn content(&self) -> Option<&RoomMessageEventContent> {
match self {
MessageEvent::EncryptedOriginal(_) => None,
MessageEvent::Original(ev) => Some(&ev.content),
MessageEvent::EncryptedRedacted(_) => None,
MessageEvent::Redacted(_) => None,
MessageEvent::Local(_, content) => Some(content),
}
}
pub fn is_emote(&self) -> bool {
matches!(
self.content(),
Some(RoomMessageEventContent { msgtype: MessageType::Emote(_), .. })
)
}
pub fn body(&self) -> Cow<'_, str> {
match self {
MessageEvent::EncryptedOriginal(_) => "[Unable to decrypt message]".into(),
MessageEvent::Original(ev) => body_cow_content(&ev.content),
MessageEvent::EncryptedRedacted(ev) => body_cow_reason(&ev.unsigned),
MessageEvent::Redacted(ev) => body_cow_reason(&ev.unsigned),
MessageEvent::Local(_, content) => body_cow_content(content),
}
}
pub fn html(&self) -> Option<StyleTree> {
let content = match self {
MessageEvent::EncryptedOriginal(_) => return None,
MessageEvent::EncryptedRedacted(_) => return None,
MessageEvent::Original(ev) => &ev.content,
MessageEvent::Redacted(_) => return None,
MessageEvent::Local(_, content) => content,
};
if let MessageType::Text(content) = &content.msgtype {
if let Some(FormattedBody { format: MessageFormat::Html, body }) = &content.formatted {
Some(parse_matrix_html(body.as_str()))
} else {
None
}
} else {
None
}
}
fn redact(&mut self, redaction: SyncRoomRedactionEvent, version: &RoomVersionId) {
match self {
MessageEvent::EncryptedOriginal(_) => return,
MessageEvent::EncryptedRedacted(_) => return,
MessageEvent::Redacted(_) => return,
MessageEvent::Local(_, _) => return,
MessageEvent::Original(ev) => {
let redacted = ev.clone().redact(redaction, version);
*self = MessageEvent::Redacted(Box::new(redacted));
},
}
}
}
fn body_cow_content(content: &RoomMessageEventContent) -> Cow<'_, str> {
let s = match &content.msgtype {
MessageType::Text(content) => content.body.as_str(),
MessageType::VerificationRequest(_) => "[Verification Request]",
MessageType::Emote(content) => content.body.as_ref(),
MessageType::Notice(content) => content.body.as_str(),
MessageType::ServerNotice(content) => content.body.as_str(),
MessageType::Audio(content) => {
return Cow::Owned(format!("[Attached Audio: {}]", content.body));
},
MessageType::File(content) => {
return Cow::Owned(format!("[Attached File: {}]", content.body));
},
MessageType::Image(content) => {
return Cow::Owned(format!("[Attached Image: {}]", content.body));
},
MessageType::Video(content) => {
return Cow::Owned(format!("[Attached Video: {}]", content.body));
},
_ => {
return Cow::Owned(format!("[Unknown message type: {:?}]", content.msgtype()));
},
};
Cow::Borrowed(s)
}
fn body_cow_reason(unsigned: &RedactedUnsigned) -> Cow<'_, str> {
let reason = unsigned
.redacted_because
.as_ref()
.and_then(|e| e.as_original())
.and_then(|r| r.content.reason.as_ref());
if let Some(r) = reason {
Cow::Owned(format!("[Redacted: {r:?}]"))
} else {
Cow::Borrowed("[Redacted]")
}
}
enum MessageColumns {
/// Four columns: sender, message, timestamp, read receipts.
Four,
/// Three columns: sender, message, timestamp.
Three,
/// Two columns: sender, message.
Two,
/// One column: message with sender on line before the message.
One,
}
struct MessageFormatter<'a> {
settings: &'a ApplicationSettings,
/// How many columns to print.
cols: MessageColumns,
/// The full, original width.
orig: usize,
/// The width that the message contents need to fill.
fill: usize,
/// The formatted Span for the message sender.
user: Option<Span<'a>>,
/// The time the message was sent.
time: Option<Span<'a>>,
/// The date the message was sent.
date: Option<Span<'a>>,
/// Iterator over the users who have read up to this message.
read: Iter<'a, OwnedUserId>,
}
impl<'a> MessageFormatter<'a> {
fn width(&self) -> usize {
self.fill
}
#[inline]
fn push_spans(&mut self, spans: Spans<'a>, style: Style, text: &mut Text<'a>) {
if let Some(date) = self.date.take() {
let len = date.content.as_ref().len();
let padding = self.orig.saturating_sub(len);
let leading = space_span(padding / 2, Style::default());
let trailing = space_span(padding.saturating_sub(padding / 2), Style::default());
text.lines.push(Spans(vec![leading, date, trailing]));
}
match self.cols {
MessageColumns::Four => {
let settings = self.settings;
let user = self.user.take().unwrap_or(USER_GUTTER_EMPTY_SPAN);
let time = self.time.take().unwrap_or(TIME_GUTTER_EMPTY_SPAN);
let mut line = vec![user];
line.extend(spans.0);
line.push(time);
// Show read receipts.
let user_char =
|user: &'a OwnedUserId| -> Span<'a> { settings.get_user_char_span(user) };
let a = self.read.next().map(user_char).unwrap_or_else(|| Span::raw(" "));
let b = self.read.next().map(user_char).unwrap_or_else(|| Span::raw(" "));
let c = self.read.next().map(user_char).unwrap_or_else(|| Span::raw(" "));
line.push(Span::raw(" "));
line.push(c);
line.push(b);
line.push(a);
line.push(Span::raw(" "));
text.lines.push(Spans(line))
},
MessageColumns::Three => {
let user = self.user.take().unwrap_or(USER_GUTTER_EMPTY_SPAN);
let time = self.time.take().unwrap_or_else(|| Span::from(""));
let mut line = vec![user];
line.extend(spans.0);
line.push(time);
text.lines.push(Spans(line))
},
MessageColumns::Two => {
let user = self.user.take().unwrap_or(USER_GUTTER_EMPTY_SPAN);
let mut line = vec![user];
line.extend(spans.0);
text.lines.push(Spans(line));
},
MessageColumns::One => {
if let Some(user) = self.user.take() {
text.lines.push(Spans(vec![user]));
}
let leading = space_span(2, style);
let mut line = vec![leading];
line.extend(spans.0);
text.lines.push(Spans(line));
},
}
}
fn push_text(&mut self, append: Text<'a>, style: Style, text: &mut Text<'a>) {
for line in append.lines.into_iter() {
self.push_spans(line, style, text);
}
}
}
pub struct Message {
pub event: MessageEvent,
pub sender: OwnedUserId,
pub timestamp: MessageTimeStamp,
pub downloaded: bool,
pub html: Option<StyleTree>,
}
impl Message {
pub fn new(event: MessageEvent, sender: OwnedUserId, timestamp: MessageTimeStamp) -> Self {
let html = event.html();
let downloaded = false;
Message { event, sender, timestamp, downloaded, html }
}
pub fn reply_to(&self) -> Option<OwnedEventId> {
let content = match &self.event {
MessageEvent::EncryptedOriginal(_) => return None,
MessageEvent::EncryptedRedacted(_) => return None,
MessageEvent::Local(_, content) => content,
MessageEvent::Original(ev) => &ev.content,
MessageEvent::Redacted(_) => return None,
};
if let Some(Relation::Reply { in_reply_to }) = &content.relates_to {
Some(in_reply_to.event_id.clone())
} else {
None
}
}
fn get_render_style(&self, selected: bool) -> Style {
let mut style = Style::default();
if selected {
style = style.add_modifier(StyleModifier::REVERSED)
}
if self.timestamp.is_local_echo() {
style = style.add_modifier(StyleModifier::ITALIC);
}
return style;
}
fn get_render_format<'a>(
&'a self,
prev: Option<&Message>,
width: usize,
info: &'a RoomInfo,
settings: &'a ApplicationSettings,
) -> MessageFormatter<'a> {
let orig = width;
let date = match &prev {
Some(prev) if prev.timestamp.same_day(&self.timestamp) => None,
_ => self.timestamp.show_date(),
};
if USER_GUTTER + TIME_GUTTER + READ_GUTTER + MIN_MSG_LEN <= width &&
settings.tunables.read_receipt_display
{
let cols = MessageColumns::Four;
let fill = width - USER_GUTTER - TIME_GUTTER - READ_GUTTER;
let user = self.show_sender(prev, true, info, settings);
let time = self.timestamp.show_time();
let read = match info.receipts.get(self.event.event_id()) {
Some(read) => read.iter(),
None => [].iter(),
};
MessageFormatter { settings, cols, orig, fill, user, date, time, read }
} else if USER_GUTTER + TIME_GUTTER + MIN_MSG_LEN <= width {
let cols = MessageColumns::Three;
let fill = width - USER_GUTTER - TIME_GUTTER;
let user = self.show_sender(prev, true, info, settings);
let time = self.timestamp.show_time();
let read = [].iter();
MessageFormatter { settings, cols, orig, fill, user, date, time, read }
} else if USER_GUTTER + MIN_MSG_LEN <= width {
let cols = MessageColumns::Two;
let fill = width - USER_GUTTER;
let user = self.show_sender(prev, true, info, settings);
let time = None;
let read = [].iter();
MessageFormatter { settings, cols, orig, fill, user, date, time, read }
} else {
let cols = MessageColumns::One;
let fill = width.saturating_sub(2);
let user = self.show_sender(prev, false, info, settings);
let time = None;
let read = [].iter();
MessageFormatter { settings, cols, orig, fill, user, date, time, read }
}
}
pub fn show<'a>(
&'a self,
prev: Option<&Message>,
selected: bool,
vwctx: &ViewportContext<MessageCursor>,
info: &'a RoomInfo,
settings: &'a ApplicationSettings,
) -> Text<'a> {
let width = vwctx.get_width();
let style = self.get_render_style(selected);
let mut fmt = self.get_render_format(prev, width, info, settings);
let mut text = Text { lines: vec![] };
let width = fmt.width();
// Show the message that this one replied to, if any.
let reply = self.reply_to().and_then(|e| info.get_event(&e));
if let Some(r) = &reply {
let w = width.saturating_sub(2);
let mut replied = r.show_msg(w, style, true);
let mut sender = r.sender_span(info, settings);
let sender_width = UnicodeWidthStr::width(sender.content.as_ref());
let trailing = w.saturating_sub(sender_width + 1);
sender.style = sender.style.patch(style);
fmt.push_spans(
Spans(vec![
Span::styled(" ", style),
Span::styled(THICK_VERTICAL, style),
sender,
Span::styled(":", style),
space_span(trailing, style),
]),
style,
&mut text,
);
for line in replied.lines.iter_mut() {
line.0.insert(0, Span::styled(THICK_VERTICAL, style));
line.0.insert(0, Span::styled(" ", style));
}
fmt.push_text(replied, style, &mut text);
}
// Now show the message contents, and the inlined reply if we couldn't find it above.
let msg = self.show_msg(width, style, reply.is_some());
fmt.push_text(msg, style, &mut text);
if text.lines.is_empty() {
// If there was nothing in the body, just show an empty message.
fmt.push_spans(space_span(width, style).into(), style, &mut text);
}
if settings.tunables.reaction_display {
let mut emojis = printer::TextPrinter::new(width, style, false);
let mut reactions = 0;
for (key, count) in info.get_reactions(self.event.event_id()).into_iter() {
if reactions != 0 {
emojis.push_str(" ", style);
}
let name = if settings.tunables.reaction_shortcode_display {
if let Some(emoji) = emojis::get(key) {
if let Some(short) = emoji.shortcode() {
short
} else {
// No ASCII shortcode name to show.
continue;
}
} else if key.chars().all(|c| c.is_ascii_alphanumeric()) {
key
} else {
// Not an Emoji or a printable ASCII string.
continue;
}
} else {
key
};
emojis.push_str("[", style);
emojis.push_str(name, style);
emojis.push_str(" ", style);
emojis.push_span_nobreak(Span::styled(count.to_string(), style));
emojis.push_str("]", style);
reactions += 1;
}
if reactions > 0 {
fmt.push_text(emojis.finish(), style, &mut text);
}
}
return text;
}
pub fn show_msg(&self, width: usize, style: Style, hide_reply: bool) -> Text {
if let Some(html) = &self.html {
html.to_text(width, style, hide_reply)
} else {
let mut msg = self.event.body();
if self.downloaded {
msg.to_mut().push_str(" \u{2705}");
}
wrapped_text(msg, width, style)
}
}
fn sender_span<'a>(
&'a self,
info: &'a RoomInfo,
settings: &'a ApplicationSettings,
) -> Span<'a> {
settings.get_user_span(self.sender.as_ref(), info)
}
fn show_sender<'a>(
&'a self,
prev: Option<&Message>,
align_right: bool,
info: &'a RoomInfo,
settings: &'a ApplicationSettings,
) -> Option<Span<'a>> {
if let Some(prev) = prev {
if self.sender == prev.sender &&
self.timestamp.same_day(&prev.timestamp) &&
!self.event.is_emote()
{
return None;
}
}
let Span { content, style } = self.sender_span(info, settings);
let stop = content.len().min(28);
let s = &content[..stop];
let sender = if align_right {
format!("{: >width$} ", s, width = 28)
} else {
format!("{: <width$} ", s, width = 28)
};
Span::styled(sender, style).into()
}
pub fn redact(&mut self, redaction: SyncRoomRedactionEvent, version: &RoomVersionId) {
self.event.redact(redaction, version);
self.html = None;
}
}
impl From<RoomEncryptedEvent> for Message {
fn from(event: RoomEncryptedEvent) -> Self {
let timestamp = event.origin_server_ts().into();
let user_id = event.sender().to_owned();
let content = match event {
RoomEncryptedEvent::Original(ev) => MessageEvent::EncryptedOriginal(ev.into()),
RoomEncryptedEvent::Redacted(ev) => MessageEvent::EncryptedRedacted(ev.into()),
};
Message::new(content, user_id, timestamp)
}
}
impl From<OriginalRoomMessageEvent> for Message {
fn from(event: OriginalRoomMessageEvent) -> Self {
let timestamp = event.origin_server_ts.into();
let user_id = event.sender.clone();
let content = MessageEvent::Original(event.into());
Message::new(content, user_id, timestamp)
}
}
impl From<RedactedRoomMessageEvent> for Message {
fn from(event: RedactedRoomMessageEvent) -> Self {
let timestamp = event.origin_server_ts.into();
let user_id = event.sender.clone();
let content = MessageEvent::Redacted(event.into());
Message::new(content, user_id, timestamp)
}
}
impl From<RoomMessageEvent> for Message {
fn from(event: RoomMessageEvent) -> Self {
match event {
RoomMessageEvent::Original(ev) => ev.into(),
RoomMessageEvent::Redacted(ev) => ev.into(),
}
}
}
impl ToString for Message {
fn to_string(&self) -> String {
self.event.body().into_owned()
}
}
#[cfg(test)]
pub mod tests {
use super::*;
use crate::tests::*;
#[test]
fn test_mc_cmp() {
let mc1 = MessageCursor::from(MSG1_KEY.clone());
let mc2 = MessageCursor::from(MSG2_KEY.clone());
let mc3 = MessageCursor::from(MSG3_KEY.clone());
let mc4 = MessageCursor::from(MSG4_KEY.clone());
let mc5 = MessageCursor::from(MSG5_KEY.clone());
// Everything is equal to itself.
assert_eq!(mc1.cmp(&mc1), Ordering::Equal);
assert_eq!(mc2.cmp(&mc2), Ordering::Equal);
assert_eq!(mc3.cmp(&mc3), Ordering::Equal);
assert_eq!(mc4.cmp(&mc4), Ordering::Equal);
assert_eq!(mc5.cmp(&mc5), Ordering::Equal);
// Local echo is always greater than an origin server timestamp.
assert_eq!(mc1.cmp(&mc2), Ordering::Greater);
assert_eq!(mc1.cmp(&mc3), Ordering::Greater);
assert_eq!(mc1.cmp(&mc4), Ordering::Greater);
assert_eq!(mc1.cmp(&mc5), Ordering::Greater);
// mc2 is the smallest timestamp.
assert_eq!(mc2.cmp(&mc1), Ordering::Less);
assert_eq!(mc2.cmp(&mc3), Ordering::Less);
assert_eq!(mc2.cmp(&mc4), Ordering::Less);
assert_eq!(mc2.cmp(&mc5), Ordering::Less);
// mc3 should be less than mc4 because of its event ID.
assert_eq!(mc3.cmp(&mc1), Ordering::Less);
assert_eq!(mc3.cmp(&mc2), Ordering::Greater);
assert_eq!(mc3.cmp(&mc4), Ordering::Less);
assert_eq!(mc3.cmp(&mc5), Ordering::Less);
// mc4 should be greater than mc3 because of its event ID.
assert_eq!(mc4.cmp(&mc1), Ordering::Less);
assert_eq!(mc4.cmp(&mc2), Ordering::Greater);
assert_eq!(mc4.cmp(&mc3), Ordering::Greater);
assert_eq!(mc4.cmp(&mc5), Ordering::Less);
// mc5 is the greatest OriginServer timestamp.
assert_eq!(mc5.cmp(&mc1), Ordering::Less);
assert_eq!(mc5.cmp(&mc2), Ordering::Greater);
assert_eq!(mc5.cmp(&mc3), Ordering::Greater);
assert_eq!(mc5.cmp(&mc4), Ordering::Greater);
}
#[test]
fn test_mc_to_key() {
let info = mock_room();
let mc1 = MessageCursor::from(MSG1_KEY.clone());
let mc2 = MessageCursor::from(MSG2_KEY.clone());
let mc3 = MessageCursor::from(MSG3_KEY.clone());
let mc4 = MessageCursor::from(MSG4_KEY.clone());
let mc5 = MessageCursor::from(MSG5_KEY.clone());
let mc6 = MessageCursor::latest();
let k1 = mc1.to_key(&info).unwrap();
let k2 = mc2.to_key(&info).unwrap();
let k3 = mc3.to_key(&info).unwrap();
let k4 = mc4.to_key(&info).unwrap();
let k5 = mc5.to_key(&info).unwrap();
let k6 = mc6.to_key(&info).unwrap();
// These should all be equal to their MSGN_KEYs.
assert_eq!(k1, &MSG1_KEY.clone());
assert_eq!(k2, &MSG2_KEY.clone());
assert_eq!(k3, &MSG3_KEY.clone());
assert_eq!(k4, &MSG4_KEY.clone());
assert_eq!(k5, &MSG5_KEY.clone());
// MessageCursor::latest() turns into the largest key (our local echo message).
assert_eq!(k6, &MSG1_KEY.clone());
// MessageCursor::latest() fails to convert for a room w/o messages.
let info_empty = RoomInfo::default();
assert_eq!(mc6.to_key(&info_empty), None);
}
#[test]
fn test_mc_to_from_cursor() {
let info = mock_room();
let mc1 = MessageCursor::from(MSG1_KEY.clone());
let mc2 = MessageCursor::from(MSG2_KEY.clone());
let mc3 = MessageCursor::from(MSG3_KEY.clone());
let mc4 = MessageCursor::from(MSG4_KEY.clone());
let mc5 = MessageCursor::from(MSG5_KEY.clone());
let mc6 = MessageCursor::latest();
let identity = |mc: &MessageCursor| {
let c = mc.to_cursor(&info).unwrap();
MessageCursor::from_cursor(&c, &info).unwrap()
};
// These should all convert to a Cursor and back to the original value.
assert_eq!(identity(&mc1), mc1);
assert_eq!(identity(&mc2), mc2);
assert_eq!(identity(&mc3), mc3);
assert_eq!(identity(&mc4), mc4);
assert_eq!(identity(&mc5), mc5);
// MessageCursor::latest() should point at the most recent message after conversion.
assert_eq!(identity(&mc6), mc1);
}
#[test]
fn test_markdown_message() {
let input = "**bold**\n";
let content = text_to_message_content(input.into());
assert_eq!(content.body, input);
assert_eq!(content.formatted.unwrap().body, "<p><strong>bold</strong></p>\n");
let input = "*emphasis*\n";
let content = text_to_message_content(input.into());
assert_eq!(content.body, input);
assert_eq!(content.formatted.unwrap().body, "<p><em>emphasis</em></p>\n");
let input = "`code`\n";
let content = text_to_message_content(input.into());
assert_eq!(content.body, input);
assert_eq!(content.formatted.unwrap().body, "<p><code>code</code></p>\n");
let input = "```rust\nconst A: usize = 1;\n```\n";
let content = text_to_message_content(input.into());
assert_eq!(content.body, input);
assert_eq!(
content.formatted.unwrap().body,
"<pre><code class=\"language-rust\">const A: usize = 1;\n</code></pre>\n"
);
let input = ":heart:\n";
let content = text_to_message_content(input.into());
assert_eq!(content.body, input);
assert_eq!(content.formatted.unwrap().body, "<p>\u{2764}\u{FE0F}</p>\n");
let input = "para 1\n\npara 2\n";
let content = text_to_message_content(input.into());
assert_eq!(content.body, input);
assert_eq!(content.formatted.unwrap().body, "<p>para 1</p>\n<p>para 2</p>\n");
let input = "line 1\nline 2\n";
let content = text_to_message_content(input.into());
assert_eq!(content.body, input);
assert_eq!(content.formatted.unwrap().body, "<p>line 1<br />\nline 2</p>\n");
let input = "# Heading\n## Subheading\n\ntext\n";
let content = text_to_message_content(input.into());
assert_eq!(content.body, input);
assert_eq!(
content.formatted.unwrap().body,
"<h1>Heading</h1>\n<h2>Subheading</h2>\n<p>text</p>\n"
);
}
}
0707010000001C000081A400000000000000000000000164A9007B00001809000000000000000000000000000000000000002200000000iamb-0.0.8/src/message/printer.rsuse std::borrow::Cow;
use modalkit::tui::layout::Alignment;
use modalkit::tui::style::Style;
use modalkit::tui::text::{Span, Spans, Text};
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;
use crate::util::{space_span, take_width};
pub struct TextPrinter<'a> {
text: Text<'a>,
width: usize,
base_style: Style,
hide_reply: bool,
alignment: Alignment,
curr_spans: Vec<Span<'a>>,
curr_width: usize,
literal: bool,
}
impl<'a> TextPrinter<'a> {
pub fn new(width: usize, base_style: Style, hide_reply: bool) -> Self {
TextPrinter {
text: Text::default(),
width,
base_style,
hide_reply,
alignment: Alignment::Left,
curr_spans: vec![],
curr_width: 0,
literal: false,
}
}
pub fn align(mut self, alignment: Alignment) -> Self {
self.alignment = alignment;
self
}
pub fn literal(mut self, literal: bool) -> Self {
self.literal = literal;
self
}
pub fn hide_reply(&self) -> bool {
self.hide_reply
}
pub fn width(&self) -> usize {
self.width
}
pub fn sub(&self, indent: usize) -> Self {
TextPrinter {
text: Text::default(),
width: self.width.saturating_sub(indent),
base_style: self.base_style,
hide_reply: self.hide_reply,
alignment: self.alignment,
curr_spans: vec![],
curr_width: 0,
literal: self.literal,
}
}
fn remaining(&self) -> usize {
self.width - self.curr_width
}
pub fn commit(&mut self) {
if self.curr_width > 0 {
self.push_break();
}
}
fn push(&mut self) {
self.curr_width = 0;
self.text.lines.push(Spans(std::mem::take(&mut self.curr_spans)));
}
pub fn push_break(&mut self) {
if self.curr_width == 0 && self.text.lines.is_empty() {
// Disallow leading breaks.
return;
}
let remaining = self.remaining();
if remaining > 0 {
match self.alignment {
Alignment::Left => {
let tspan = space_span(remaining, self.base_style);
self.curr_spans.push(tspan);
},
Alignment::Center => {
let trailing = remaining / 2;
let leading = remaining - trailing;
let tspan = space_span(trailing, self.base_style);
let lspan = space_span(leading, self.base_style);
self.curr_spans.push(tspan);
self.curr_spans.insert(0, lspan);
},
Alignment::Right => {
let lspan = space_span(remaining, self.base_style);
self.curr_spans.insert(0, lspan);
},
}
}
self.push();
}
fn push_str_wrapped<T>(&mut self, s: T, style: Style)
where
T: Into<Cow<'a, str>>,
{
let style = self.base_style.patch(style);
let mut cow = s.into();
loop {
let sw = UnicodeWidthStr::width(cow.as_ref());
if self.curr_width + sw <= self.width {
// The text fits within the current line.
self.curr_spans.push(Span::styled(cow, style));
self.curr_width += sw;
break;
}
// Take a leading portion of the text that fits in the line.
let ((s0, w), s1) = take_width(cow, self.remaining());
cow = s1;
self.curr_spans.push(Span::styled(s0, style));
self.curr_width += w;
self.commit();
}
if self.curr_width == self.width {
// If the last bit fills the full line, start a new one.
self.push();
}
}
pub fn push_span_nobreak(&mut self, span: Span<'a>) {
let sw = UnicodeWidthStr::width(span.content.as_ref());
if self.curr_width + sw > self.width {
// Span doesn't fit on this line, so start a new one.
self.commit();
}
self.curr_spans.push(span);
self.curr_width += sw;
}
pub fn push_str(&mut self, s: &'a str, style: Style) {
let style = self.base_style.patch(style);
if self.width == 0 {
return;
}
for mut word in UnicodeSegmentation::split_word_bounds(s) {
if let "\n" | "\r\n" = word {
if self.literal {
self.commit();
continue;
}
// Render embedded newlines as spaces.
word = " ";
}
if !self.literal && self.curr_width == 0 && word.chars().all(char::is_whitespace) {
// Drop leading whitespace.
continue;
}
let sw = UnicodeWidthStr::width(word);
if sw > self.width {
self.push_str_wrapped(word, style);
continue;
}
if self.curr_width + sw > self.width {
// Word doesn't fit on this line, so start a new one.
self.commit();
if !self.literal && word.chars().all(char::is_whitespace) {
// Drop leading whitespace.
continue;
}
}
let span = Span::styled(word, style);
self.curr_spans.push(span);
self.curr_width += sw;
}
if self.curr_width == self.width {
// If the last bit fills the full line, start a new one.
self.push();
}
}
pub fn push_line(&mut self, spans: Spans<'a>) {
self.commit();
self.text.lines.push(spans);
}
pub fn push_text(&mut self, text: Text<'a>) {
self.commit();
self.text.lines.extend(text.lines);
}
pub fn finish(mut self) -> Text<'a> {
self.commit();
self.text
}
}
0707010000001D000081A400000000000000000000000164A9007B00001DC4000000000000000000000000000000000000001800000000iamb-0.0.8/src/tests.rsuse std::collections::{BTreeMap, HashMap};
use std::path::PathBuf;
use matrix_sdk::ruma::{
event_id,
events::room::message::{OriginalRoomMessageEvent, RoomMessageEventContent},
server_name,
user_id,
EventId,
OwnedEventId,
OwnedRoomId,
OwnedUserId,
RoomId,
UInt,
};
use lazy_static::lazy_static;
use modalkit::tui::style::{Color, Style};
use tokio::sync::mpsc::unbounded_channel;
use tracing::Level;
use url::Url;
use crate::{
base::{ChatStore, EventLocation, ProgramStore, RoomFetchStatus, RoomInfo},
config::{
user_color,
user_style_from_color,
ApplicationSettings,
DirectoryValues,
ProfileConfig,
TunableValues,
UserColor,
UserDisplayStyle,
UserDisplayTunables,
},
message::{
Message,
MessageEvent,
MessageKey,
MessageTimeStamp::{LocalEcho, OriginServer},
Messages,
},
worker::Requester,
};
const TEST_ROOM1_ALIAS: &str = "#room1:example.com";
lazy_static! {
pub static ref TEST_ROOM1_ID: OwnedRoomId = RoomId::new(server_name!("example.com")).to_owned();
pub static ref TEST_USER1: OwnedUserId = user_id!("@user1:example.com").to_owned();
pub static ref TEST_USER2: OwnedUserId = user_id!("@user2:example.com").to_owned();
pub static ref TEST_USER3: OwnedUserId = user_id!("@user3:example.com").to_owned();
pub static ref TEST_USER4: OwnedUserId = user_id!("@user4:example.com").to_owned();
pub static ref TEST_USER5: OwnedUserId = user_id!("@user5:example.com").to_owned();
pub static ref MSG1_EVID: OwnedEventId = EventId::new(server_name!("example.com"));
pub static ref MSG2_EVID: OwnedEventId = EventId::new(server_name!("example.com"));
pub static ref MSG3_EVID: OwnedEventId =
event_id!("$5jRz3KfVhaUzXtVj7k:example.com").to_owned();
pub static ref MSG4_EVID: OwnedEventId =
event_id!("$JP6qFV7WyXk5ZnexM3:example.com").to_owned();
pub static ref MSG5_EVID: OwnedEventId = EventId::new(server_name!("example.com"));
pub static ref MSG1_KEY: MessageKey = (LocalEcho, MSG1_EVID.clone());
pub static ref MSG2_KEY: MessageKey = (OriginServer(UInt::new(1).unwrap()), MSG2_EVID.clone());
pub static ref MSG3_KEY: MessageKey = (OriginServer(UInt::new(2).unwrap()), MSG3_EVID.clone());
pub static ref MSG4_KEY: MessageKey = (OriginServer(UInt::new(2).unwrap()), MSG4_EVID.clone());
pub static ref MSG5_KEY: MessageKey = (OriginServer(UInt::new(8).unwrap()), MSG5_EVID.clone());
}
pub fn user_style(user: &str) -> Style {
user_style_from_color(user_color(user))
}
pub fn mock_room1_message(
content: RoomMessageEventContent,
sender: OwnedUserId,
key: MessageKey,
) -> Message {
let origin_server_ts = key.0.as_millis().unwrap();
let event_id = key.1;
let event = OriginalRoomMessageEvent {
content,
event_id,
sender,
origin_server_ts,
room_id: TEST_ROOM1_ID.clone(),
unsigned: Default::default(),
};
event.into()
}
pub fn mock_message1() -> Message {
let content = RoomMessageEventContent::text_plain("writhe");
let content = MessageEvent::Local(MSG1_EVID.clone(), content.into());
Message::new(content, TEST_USER1.clone(), MSG1_KEY.0)
}
pub fn mock_message2() -> Message {
let content = RoomMessageEventContent::text_plain("helium");
mock_room1_message(content, TEST_USER2.clone(), MSG2_KEY.clone())
}
pub fn mock_message3() -> Message {
let content = RoomMessageEventContent::text_plain("this\nis\na\nmultiline\nmessage");
mock_room1_message(content, TEST_USER2.clone(), MSG3_KEY.clone())
}
pub fn mock_message4() -> Message {
let content = RoomMessageEventContent::text_plain("help");
mock_room1_message(content, TEST_USER1.clone(), MSG4_KEY.clone())
}
pub fn mock_message5() -> Message {
let content = RoomMessageEventContent::text_plain("character");
mock_room1_message(content, TEST_USER2.clone(), MSG4_KEY.clone())
}
pub fn mock_keys() -> HashMap<OwnedEventId, EventLocation> {
let mut keys = HashMap::new();
keys.insert(MSG1_EVID.clone(), EventLocation::Message(MSG1_KEY.clone()));
keys.insert(MSG2_EVID.clone(), EventLocation::Message(MSG2_KEY.clone()));
keys.insert(MSG3_EVID.clone(), EventLocation::Message(MSG3_KEY.clone()));
keys.insert(MSG4_EVID.clone(), EventLocation::Message(MSG4_KEY.clone()));
keys.insert(MSG5_EVID.clone(), EventLocation::Message(MSG5_KEY.clone()));
keys
}
pub fn mock_messages() -> Messages {
let mut messages = BTreeMap::new();
messages.insert(MSG1_KEY.clone(), mock_message1());
messages.insert(MSG2_KEY.clone(), mock_message2());
messages.insert(MSG3_KEY.clone(), mock_message3());
messages.insert(MSG4_KEY.clone(), mock_message4());
messages.insert(MSG5_KEY.clone(), mock_message5());
messages
}
pub fn mock_room() -> RoomInfo {
RoomInfo {
name: Some("Watercooler Discussion".into()),
tags: None,
keys: mock_keys(),
messages: mock_messages(),
receipts: HashMap::new(),
read_till: None,
reactions: HashMap::new(),
fetching: false,
fetch_id: RoomFetchStatus::NotStarted,
fetch_last: None,
users_typing: None,
display_names: HashMap::new(),
}
}
pub fn mock_dirs() -> DirectoryValues {
DirectoryValues {
cache: PathBuf::new(),
logs: PathBuf::new(),
downloads: None,
}
}
pub fn mock_tunables() -> TunableValues {
TunableValues {
default_room: None,
log_level: Level::INFO,
reaction_display: true,
reaction_shortcode_display: false,
read_receipt_send: true,
read_receipt_display: true,
request_timeout: 120,
typing_notice_send: true,
typing_notice_display: true,
users: vec![(TEST_USER5.clone(), UserDisplayTunables {
color: Some(UserColor(Color::Black)),
name: Some("USER 5".into()),
})]
.into_iter()
.collect::<HashMap<_, _>>(),
open_command: None,
username_display: UserDisplayStyle::Username,
}
}
pub fn mock_settings() -> ApplicationSettings {
ApplicationSettings {
matrix_dir: PathBuf::new(),
layout_json: PathBuf::new(),
session_json: PathBuf::new(),
profile_name: "test".into(),
profile: ProfileConfig {
user_id: user_id!("@user:example.com").to_owned(),
url: Url::parse("https://example.com").unwrap(),
settings: None,
dirs: None,
layout: None,
},
tunables: mock_tunables(),
dirs: mock_dirs(),
layout: Default::default(),
}
}
pub async fn mock_store() -> ProgramStore {
let (tx, _) = unbounded_channel();
let homeserver = Url::parse("https://localhost").unwrap();
let client = matrix_sdk::Client::new(homeserver).await.unwrap();
let worker = Requester { tx, client };
let mut store = ChatStore::new(worker, mock_settings());
// Add presence information.
store.presences.get_or_default(TEST_USER1.clone());
store.presences.get_or_default(TEST_USER2.clone());
store.presences.get_or_default(TEST_USER3.clone());
store.presences.get_or_default(TEST_USER4.clone());
store.presences.get_or_default(TEST_USER5.clone());
let room_id = TEST_ROOM1_ID.clone();
let info = mock_room();
store.rooms.insert(room_id.clone(), info);
store.names.insert(TEST_ROOM1_ALIAS.to_string(), room_id);
ProgramStore::new(store)
}
0707010000001E000081A400000000000000000000000164A9007B000015D8000000000000000000000000000000000000001700000000iamb-0.0.8/src/util.rsuse std::borrow::Cow;
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;
use modalkit::tui::style::Style;
use modalkit::tui::text::{Span, Spans, Text};
pub fn split_cow(cow: Cow<'_, str>, idx: usize) -> (Cow<'_, str>, Cow<'_, str>) {
match cow {
Cow::Borrowed(s) => {
let s1 = Cow::Borrowed(&s[idx..]);
let s0 = Cow::Borrowed(&s[..idx]);
(s0, s1)
},
Cow::Owned(mut s) => {
let s1 = Cow::Owned(s.split_off(idx));
let s0 = Cow::Owned(s);
(s0, s1)
},
}
}
pub fn take_width(s: Cow<'_, str>, width: usize) -> ((Cow<'_, str>, usize), Cow<'_, str>) {
// Find where to split the line.
let mut idx = 0;
let mut w = 0;
for (i, g) in UnicodeSegmentation::grapheme_indices(s.as_ref(), true) {
let gw = UnicodeWidthStr::width(g);
idx = i;
if w + gw > width {
break;
}
w += gw;
}
let (s0, s1) = split_cow(s, idx);
((s0, w), s1)
}
pub struct WrappedLinesIterator<'a> {
iter: std::vec::IntoIter<Cow<'a, str>>,
curr: Option<Cow<'a, str>>,
width: usize,
}
impl<'a> WrappedLinesIterator<'a> {
fn new<T>(input: T, width: usize) -> Self
where
T: Into<Cow<'a, str>>,
{
let width = width.max(2);
let cows: Vec<Cow<'a, str>> = match input.into() {
Cow::Borrowed(s) => s.lines().map(Cow::Borrowed).collect(),
Cow::Owned(s) => s.lines().map(ToOwned::to_owned).map(Cow::Owned).collect(),
};
WrappedLinesIterator { iter: cows.into_iter(), curr: None, width }
}
}
impl<'a> Iterator for WrappedLinesIterator<'a> {
type Item = (Cow<'a, str>, usize);
fn next(&mut self) -> Option<Self::Item> {
if self.curr.is_none() {
self.curr = self.iter.next();
}
if let Some(s) = self.curr.take() {
let width = UnicodeWidthStr::width(s.as_ref());
if width <= self.width {
return Some((s, width));
} else {
let (prefix, s1) = take_width(s, self.width);
self.curr = Some(s1);
return Some(prefix);
}
} else {
return None;
}
}
}
pub fn wrap<'a, T>(input: T, width: usize) -> WrappedLinesIterator<'a>
where
T: Into<Cow<'a, str>>,
{
WrappedLinesIterator::new(input, width)
}
pub fn wrapped_text<'a, T>(s: T, width: usize, style: Style) -> Text<'a>
where
T: Into<Cow<'a, str>>,
{
let mut text = Text::default();
for (line, w) in wrap(s, width) {
let space = space_span(width.saturating_sub(w), style);
let spans = Spans(vec![Span::styled(line, style), space]);
text.lines.push(spans);
}
return text;
}
pub fn space(width: usize) -> String {
" ".repeat(width)
}
pub fn space_span(width: usize, style: Style) -> Span<'static> {
Span::styled(space(width), style)
}
pub fn space_text(width: usize, style: Style) -> Text<'static> {
space_span(width, style).into()
}
pub fn join_cell_text<'a>(texts: Vec<(Text<'a>, usize)>, join: Span<'a>, style: Style) -> Text<'a> {
let height = texts.iter().map(|t| t.0.height()).max().unwrap_or(0);
let mut text = Text { lines: vec![Spans(vec![join.clone()]); height] };
for (mut t, w) in texts.into_iter() {
for i in 0..height {
if let Some(spans) = t.lines.get_mut(i) {
text.lines[i].0.append(&mut spans.0);
} else {
text.lines[i].0.push(space_span(w, style));
}
text.lines[i].0.push(join.clone());
}
}
text
}
#[cfg(test)]
pub mod tests {
use super::*;
#[test]
fn test_wrapped_lines_ascii() {
let s = "hello world!\nabcdefghijklmnopqrstuvwxyz\ngoodbye";
let mut iter = wrap(s, 100);
assert_eq!(iter.next(), Some((Cow::Borrowed("hello world!"), 12)));
assert_eq!(iter.next(), Some((Cow::Borrowed("abcdefghijklmnopqrstuvwxyz"), 26)));
assert_eq!(iter.next(), Some((Cow::Borrowed("goodbye"), 7)));
assert_eq!(iter.next(), None);
let mut iter = wrap(s, 5);
assert_eq!(iter.next(), Some((Cow::Borrowed("hello"), 5)));
assert_eq!(iter.next(), Some((Cow::Borrowed(" worl"), 5)));
assert_eq!(iter.next(), Some((Cow::Borrowed("d!"), 2)));
assert_eq!(iter.next(), Some((Cow::Borrowed("abcde"), 5)));
assert_eq!(iter.next(), Some((Cow::Borrowed("fghij"), 5)));
assert_eq!(iter.next(), Some((Cow::Borrowed("klmno"), 5)));
assert_eq!(iter.next(), Some((Cow::Borrowed("pqrst"), 5)));
assert_eq!(iter.next(), Some((Cow::Borrowed("uvwxy"), 5)));
assert_eq!(iter.next(), Some((Cow::Borrowed("z"), 1)));
assert_eq!(iter.next(), Some((Cow::Borrowed("goodb"), 5)));
assert_eq!(iter.next(), Some((Cow::Borrowed("ye"), 2)));
assert_eq!(iter.next(), None);
}
#[test]
fn test_wrapped_lines_unicode() {
let s = "CHICKEN";
let mut iter = wrap(s, 14);
assert_eq!(iter.next(), Some((Cow::Borrowed(s), 14)));
assert_eq!(iter.next(), None);
let mut iter = wrap(s, 5);
assert_eq!(iter.next(), Some((Cow::Borrowed("CH"), 4)));
assert_eq!(iter.next(), Some((Cow::Borrowed("IC"), 4)));
assert_eq!(iter.next(), Some((Cow::Borrowed("KE"), 4)));
assert_eq!(iter.next(), Some((Cow::Borrowed("N"), 2)));
assert_eq!(iter.next(), None);
}
}
0707010000001F000041ED00000000000000000000000264A9007B00000000000000000000000000000000000000000000001700000000iamb-0.0.8/src/windows07070100000020000081A400000000000000000000000164A9007B000088D9000000000000000000000000000000000000001E00000000iamb-0.0.8/src/windows/mod.rsuse std::cmp::{Ord, Ordering, PartialOrd};
use std::ops::Deref;
use std::sync::Arc;
use std::time::{Duration, Instant};
use matrix_sdk::{
encryption::verification::{format_emojis, SasVerification},
room::{Room as MatrixRoom, RoomMember},
ruma::{
events::room::member::MembershipState,
events::tag::{TagName, Tags},
OwnedRoomId,
RoomId,
},
};
use modalkit::tui::{
buffer::Buffer,
layout::{Alignment, Rect},
style::{Modifier as StyleModifier, Style},
text::{Span, Spans, Text},
widgets::StatefulWidget,
};
use modalkit::{
editing::{
action::{
Action,
EditError,
EditInfo,
EditResult,
Editable,
EditorAction,
Jumpable,
PromptAction,
Promptable,
Scrollable,
UIError,
WindowAction,
},
base::{
CloseFlags,
MoveDir1D,
OpenTarget,
PositionList,
ScrollStyle,
ViewportContext,
WordStyle,
WriteFlags,
},
completion::CompletionList,
},
widgets::{
list::{List, ListCursor, ListItem, ListState},
TermOffset,
TerminalCursor,
Window,
WindowOps,
},
};
use crate::base::{
ChatStore,
IambBufferId,
IambError,
IambId,
IambInfo,
IambResult,
MessageAction,
ProgramAction,
ProgramContext,
ProgramStore,
RoomAction,
SendAction,
};
use self::{room::RoomState, welcome::WelcomeState};
pub mod room;
pub mod welcome;
type MatrixRoomInfo = Arc<(MatrixRoom, Option<Tags>)>;
const MEMBER_FETCH_DEBOUNCE: Duration = Duration::from_secs(5);
#[inline]
fn bold_style() -> Style {
Style::default().add_modifier(StyleModifier::BOLD)
}
#[inline]
fn bold_span(s: &str) -> Span {
Span::styled(s, bold_style())
}
#[inline]
fn bold_spans(s: &str) -> Spans {
bold_span(s).into()
}
#[inline]
fn selected_style(selected: bool) -> Style {
if selected {
Style::default().add_modifier(StyleModifier::REVERSED)
} else {
Style::default()
}
}
#[inline]
fn selected_span(s: &str, selected: bool) -> Span {
Span::styled(s, selected_style(selected))
}
#[inline]
fn selected_text(s: &str, selected: bool) -> Text {
Text::from(selected_span(s, selected))
}
fn room_cmp(a: &MatrixRoom, b: &MatrixRoom) -> Ordering {
let ca1 = a.canonical_alias();
let ca2 = b.canonical_alias();
let ord = match (ca1, ca2) {
(None, None) => Ordering::Equal,
(None, Some(_)) => Ordering::Greater,
(Some(_), None) => Ordering::Less,
(Some(ca1), Some(ca2)) => ca1.cmp(&ca2),
};
ord.then_with(|| a.room_id().cmp(b.room_id()))
}
fn tag_cmp(a: &Option<Tags>, b: &Option<Tags>) -> Ordering {
let (fava, lowa) = a
.as_ref()
.map(|tags| {
(tags.contains_key(&TagName::Favorite), tags.contains_key(&TagName::LowPriority))
})
.unwrap_or((false, false));
let (favb, lowb) = b
.as_ref()
.map(|tags| {
(tags.contains_key(&TagName::Favorite), tags.contains_key(&TagName::LowPriority))
})
.unwrap_or((false, false));
// If a has Favorite and b doesn't, it should sort earlier in room list.
let cmpf = favb.cmp(&fava);
// If a has LowPriority and b doesn't, it should sort later in room list.
let cmpl = lowa.cmp(&lowb);
cmpl.then(cmpf)
}
fn append_tags<'a>(tags: &'a Tags, spans: &mut Vec<Span<'a>>, style: Style) {
if tags.is_empty() {
return;
}
spans.push(Span::styled(" (", style));
for (i, tag) in tags.keys().enumerate() {
if i > 0 {
spans.push(Span::styled(", ", style));
}
match tag {
TagName::Favorite => spans.push(Span::styled("Favorite", style)),
TagName::LowPriority => spans.push(Span::styled("Low Priority", style)),
TagName::ServerNotice => spans.push(Span::styled("Server Notice", style)),
TagName::User(tag) => {
spans.push(Span::styled("User Tag: ", style));
spans.push(Span::styled(tag.as_ref(), style));
},
tag => spans.push(Span::styled(format!("{tag:?}"), style)),
}
}
spans.push(Span::styled(")", style));
}
#[inline]
fn room_prompt(
room_id: &RoomId,
act: &PromptAction,
ctx: &ProgramContext,
) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
match act {
PromptAction::Submit => {
let room = IambId::Room(room_id.to_owned());
let open = WindowAction::Switch(OpenTarget::Application(room));
let acts = vec![(open.into(), ctx.clone())];
Ok(acts)
},
PromptAction::Abort(_) => {
let msg = "Cannot abort entry inside a list";
let err = EditError::Failure(msg.into());
Err(err)
},
PromptAction::Recall(..) => {
let msg = "Cannot recall history inside a list";
let err = EditError::Failure(msg.into());
Err(err)
},
_ => Err(EditError::Unimplemented("unknown prompt action".to_string())),
}
}
macro_rules! delegate {
($s: expr, $id: ident => $e: expr) => {
match $s {
IambWindow::Room($id) => $e,
IambWindow::DirectList($id) => $e,
IambWindow::MemberList($id, _, _) => $e,
IambWindow::RoomList($id) => $e,
IambWindow::SpaceList($id) => $e,
IambWindow::VerifyList($id) => $e,
IambWindow::Welcome($id) => $e,
}
};
}
pub enum IambWindow {
DirectList(DirectListState),
MemberList(MemberListState, OwnedRoomId, Option<Instant>),
Room(RoomState),
VerifyList(VerifyListState),
RoomList(RoomListState),
SpaceList(SpaceListState),
Welcome(WelcomeState),
}
impl IambWindow {
pub fn focus_toggle(&mut self) {
if let IambWindow::Room(w) = self {
w.focus_toggle()
} else {
return;
}
}
pub async fn message_command(
&mut self,
act: MessageAction,
ctx: ProgramContext,
store: &mut ProgramStore,
) -> IambResult<EditInfo> {
if let IambWindow::Room(w) = self {
w.message_command(act, ctx, store).await
} else {
return Err(IambError::NoSelectedRoom.into());
}
}
pub async fn room_command(
&mut self,
act: RoomAction,
ctx: ProgramContext,
store: &mut ProgramStore,
) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> {
if let IambWindow::Room(w) = self {
w.room_command(act, ctx, store).await
} else {
return Err(IambError::NoSelectedRoomOrSpace.into());
}
}
pub async fn send_command(
&mut self,
act: SendAction,
ctx: ProgramContext,
store: &mut ProgramStore,
) -> IambResult<EditInfo> {
if let IambWindow::Room(w) = self {
w.send_command(act, ctx, store).await
} else {
return Err(IambError::NoSelectedRoom.into());
}
}
}
pub type DirectListState = ListState<DirectItem, IambInfo>;
pub type MemberListState = ListState<MemberItem, IambInfo>;
pub type RoomListState = ListState<RoomItem, IambInfo>;
pub type SpaceListState = ListState<SpaceItem, IambInfo>;
pub type VerifyListState = ListState<VerifyItem, IambInfo>;
impl From<RoomState> for IambWindow {
fn from(room: RoomState) -> Self {
IambWindow::Room(room)
}
}
impl From<VerifyListState> for IambWindow {
fn from(list: VerifyListState) -> Self {
IambWindow::VerifyList(list)
}
}
impl From<DirectListState> for IambWindow {
fn from(list: DirectListState) -> Self {
IambWindow::DirectList(list)
}
}
impl From<RoomListState> for IambWindow {
fn from(list: RoomListState) -> Self {
IambWindow::RoomList(list)
}
}
impl From<SpaceListState> for IambWindow {
fn from(list: SpaceListState) -> Self {
IambWindow::SpaceList(list)
}
}
impl From<WelcomeState> for IambWindow {
fn from(win: WelcomeState) -> Self {
IambWindow::Welcome(win)
}
}
impl Editable<ProgramContext, ProgramStore, IambInfo> for IambWindow {
fn editor_command(
&mut self,
act: &EditorAction,
ctx: &ProgramContext,
store: &mut ProgramStore,
) -> EditResult<EditInfo, IambInfo> {
delegate!(self, w => w.editor_command(act, ctx, store))
}
}
impl Jumpable<ProgramContext, IambInfo> for IambWindow {
fn jump(
&mut self,
list: PositionList,
dir: MoveDir1D,
count: usize,
ctx: &ProgramContext,
) -> IambResult<usize> {
delegate!(self, w => w.jump(list, dir, count, ctx))
}
}
impl Scrollable<ProgramContext, ProgramStore, IambInfo> for IambWindow {
fn scroll(
&mut self,
style: &ScrollStyle,
ctx: &ProgramContext,
store: &mut ProgramStore,
) -> EditResult<EditInfo, IambInfo> {
delegate!(self, w => w.scroll(style, ctx, store))
}
}
impl Promptable<ProgramContext, ProgramStore, IambInfo> for IambWindow {
fn prompt(
&mut self,
act: &PromptAction,
ctx: &ProgramContext,
store: &mut ProgramStore,
) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
delegate!(self, w => w.prompt(act, ctx, store))
}
}
impl TerminalCursor for IambWindow {
fn get_term_cursor(&self) -> Option<TermOffset> {
delegate!(self, w => w.get_term_cursor())
}
}
impl WindowOps<IambInfo> for IambWindow {
fn draw(&mut self, area: Rect, buf: &mut Buffer, focused: bool, store: &mut ProgramStore) {
match self {
IambWindow::Room(state) => state.draw(area, buf, focused, store),
IambWindow::DirectList(state) => {
let mut items = store
.application
.sync_info
.dms
.clone()
.into_iter()
.map(|room_info| DirectItem::new(room_info, store))
.collect::<Vec<_>>();
items.sort();
state.set(items);
List::new(store)
.empty_message("No direct messages yet!")
.empty_alignment(Alignment::Center)
.focus(focused)
.render(area, buf, state);
},
IambWindow::MemberList(state, room_id, last_fetch) => {
let need_fetch = match last_fetch {
Some(i) => i.elapsed() >= MEMBER_FETCH_DEBOUNCE,
None => true,
};
if need_fetch {
if let Ok(mems) = store.application.worker.members(room_id.clone()) {
let items = mems.into_iter().map(|m| MemberItem::new(m, room_id.clone()));
state.set(items.collect());
*last_fetch = Some(Instant::now());
}
}
List::new(store)
.empty_message("No users here yet!")
.empty_alignment(Alignment::Center)
.focus(focused)
.render(area, buf, state);
},
IambWindow::RoomList(state) => {
let mut items = store
.application
.sync_info
.rooms
.clone()
.into_iter()
.map(|room_info| RoomItem::new(room_info, store))
.collect::<Vec<_>>();
items.sort();
state.set(items);
List::new(store)
.empty_message("You haven't joined any rooms yet")
.empty_alignment(Alignment::Center)
.focus(focused)
.render(area, buf, state);
},
IambWindow::SpaceList(state) => {
let items = store
.application
.sync_info
.spaces
.clone()
.into_iter()
.map(|room| SpaceItem::new(room, store));
state.set(items.collect());
state.draw(area, buf, focused, store);
List::new(store)
.empty_message("You haven't joined any spaces yet")
.empty_alignment(Alignment::Center)
.focus(focused)
.render(area, buf, state);
},
IambWindow::VerifyList(state) => {
let verifications = &store.application.verifications;
let mut items = verifications.iter().map(VerifyItem::from).collect::<Vec<_>>();
// Sort the active verifications towards the top.
items.sort();
state.set(items);
List::new(store)
.empty_message("No in-progress verifications")
.empty_alignment(Alignment::Center)
.focus(focused)
.render(area, buf, state);
},
IambWindow::Welcome(state) => state.draw(area, buf, focused, store),
}
}
fn dup(&self, store: &mut ProgramStore) -> Self {
match self {
IambWindow::Room(w) => w.dup(store).into(),
IambWindow::DirectList(w) => w.dup(store).into(),
IambWindow::MemberList(w, room_id, last_fetch) => {
IambWindow::MemberList(w.dup(store), room_id.clone(), *last_fetch)
},
IambWindow::RoomList(w) => w.dup(store).into(),
IambWindow::SpaceList(w) => w.dup(store).into(),
IambWindow::VerifyList(w) => w.dup(store).into(),
IambWindow::Welcome(w) => w.dup(store).into(),
}
}
fn close(&mut self, flags: CloseFlags, store: &mut ProgramStore) -> bool {
delegate!(self, w => w.close(flags, store))
}
fn write(
&mut self,
path: Option<&str>,
flags: WriteFlags,
store: &mut ProgramStore,
) -> IambResult<EditInfo> {
delegate!(self, w => w.write(path, flags, store))
}
fn get_completions(&self) -> Option<CompletionList> {
delegate!(self, w => w.get_completions())
}
fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
delegate!(self, w => w.get_cursor_word(style))
}
fn get_selected_word(&self) -> Option<String> {
delegate!(self, w => w.get_selected_word())
}
}
impl Window<IambInfo> for IambWindow {
fn id(&self) -> IambId {
match self {
IambWindow::Room(room) => IambId::Room(room.id().to_owned()),
IambWindow::DirectList(_) => IambId::DirectList,
IambWindow::MemberList(_, room_id, _) => IambId::MemberList(room_id.clone()),
IambWindow::RoomList(_) => IambId::RoomList,
IambWindow::SpaceList(_) => IambId::SpaceList,
IambWindow::VerifyList(_) => IambId::VerifyList,
IambWindow::Welcome(_) => IambId::Welcome,
}
}
fn get_tab_title(&self, store: &mut ProgramStore) -> Spans {
match self {
IambWindow::DirectList(_) => bold_spans("Direct Messages"),
IambWindow::RoomList(_) => bold_spans("Rooms"),
IambWindow::SpaceList(_) => bold_spans("Spaces"),
IambWindow::VerifyList(_) => bold_spans("Verifications"),
IambWindow::Welcome(_) => bold_spans("Welcome to iamb"),
IambWindow::Room(w) => {
let title = store.application.get_room_title(w.id());
Spans::from(title)
},
IambWindow::MemberList(state, room_id, _) => {
let title = store.application.get_room_title(room_id.as_ref());
let n = state.len();
let v = vec![
bold_span("Room Members "),
Span::styled(format!("({n}): "), bold_style()),
title.into(),
];
Spans(v)
},
}
}
fn get_win_title(&self, store: &mut ProgramStore) -> Spans {
match self {
IambWindow::DirectList(_) => bold_spans("Direct Messages"),
IambWindow::RoomList(_) => bold_spans("Rooms"),
IambWindow::SpaceList(_) => bold_spans("Spaces"),
IambWindow::VerifyList(_) => bold_spans("Verifications"),
IambWindow::Welcome(_) => bold_spans("Welcome to iamb"),
IambWindow::Room(w) => w.get_title(store),
IambWindow::MemberList(state, room_id, _) => {
let title = store.application.get_room_title(room_id.as_ref());
let n = state.len();
let v = vec![
bold_span("Room Members "),
Span::styled(format!("({n}): "), bold_style()),
title.into(),
];
Spans(v)
},
}
}
fn open(id: IambId, store: &mut ProgramStore) -> IambResult<Self> {
match id {
IambId::Room(room_id) => {
let (room, name, tags) = store.application.worker.get_room(room_id)?;
let room = RoomState::new(room, name, tags, store);
return Ok(room.into());
},
IambId::DirectList => {
let list = DirectListState::new(IambBufferId::DirectList, vec![]);
return Ok(list.into());
},
IambId::MemberList(room_id) => {
let id = IambBufferId::MemberList(room_id.clone());
let list = MemberListState::new(id, vec![]);
let win = IambWindow::MemberList(list, room_id, None);
return Ok(win);
},
IambId::RoomList => {
let list = RoomListState::new(IambBufferId::RoomList, vec![]);
return Ok(list.into());
},
IambId::SpaceList => {
let list = SpaceListState::new(IambBufferId::SpaceList, vec![]);
return Ok(list.into());
},
IambId::VerifyList => {
let list = VerifyListState::new(IambBufferId::VerifyList, vec![]);
return Ok(list.into());
},
IambId::Welcome => {
let win = WelcomeState::new(store);
return Ok(win.into());
},
}
}
fn find(name: String, store: &mut ProgramStore) -> IambResult<Self> {
let ChatStore { names, worker, .. } = &mut store.application;
if let Some(room) = names.get_mut(&name) {
let id = IambId::Room(room.clone());
IambWindow::open(id, store)
} else {
let room_id = worker.join_room(name.clone())?;
names.insert(name, room_id.clone());
let (room, name, tags) = store.application.worker.get_room(room_id)?;
let room = RoomState::new(room, name, tags, store);
Ok(room.into())
}
}
fn posn(index: usize, _: &mut ProgramStore) -> IambResult<Self> {
let msg = format!("Cannot find indexed buffer (index = {index})");
let err = UIError::Unimplemented(msg);
Err(err)
}
fn unnamed(store: &mut ProgramStore) -> IambResult<Self> {
Self::open(IambId::RoomList, store)
}
}
#[derive(Clone)]
pub struct RoomItem {
room_info: MatrixRoomInfo,
name: String,
}
impl RoomItem {
fn new(room_info: MatrixRoomInfo, store: &mut ProgramStore) -> Self {
let room = &room_info.deref().0;
let room_id = room.room_id();
let info = store.application.get_room_info(room_id.to_owned());
let name = info.name.clone().unwrap_or_default();
info.tags = room_info.deref().1.clone();
if let Some(alias) = room.canonical_alias() {
store.application.names.insert(alias.to_string(), room_id.to_owned());
}
RoomItem { room_info, name }
}
#[inline]
fn room(&self) -> &MatrixRoom {
&self.room_info.deref().0
}
#[inline]
fn room_id(&self) -> &RoomId {
self.room().room_id()
}
#[inline]
fn tags(&self) -> &Option<Tags> {
&self.room_info.deref().1
}
}
impl PartialEq for RoomItem {
fn eq(&self, other: &Self) -> bool {
self.room_id() == other.room_id()
}
}
impl Eq for RoomItem {}
impl Ord for RoomItem {
fn cmp(&self, other: &Self) -> Ordering {
tag_cmp(self.tags(), other.tags()).then_with(|| room_cmp(self.room(), other.room()))
}
}
impl PartialOrd for RoomItem {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.cmp(other).into()
}
}
impl ToString for RoomItem {
fn to_string(&self) -> String {
return self.name.clone();
}
}
impl ListItem<IambInfo> for RoomItem {
fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text {
if let Some(tags) = &self.tags() {
let style = selected_style(selected);
let mut spans = vec![Span::styled(self.name.as_str(), style)];
append_tags(tags, &mut spans, style);
Text::from(Spans(spans))
} else {
selected_text(self.name.as_str(), selected)
}
}
fn get_word(&self) -> Option<String> {
self.room_id().to_string().into()
}
}
impl Promptable<ProgramContext, ProgramStore, IambInfo> for RoomItem {
fn prompt(
&mut self,
act: &PromptAction,
ctx: &ProgramContext,
_: &mut ProgramStore,
) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
room_prompt(self.room_id(), act, ctx)
}
}
#[derive(Clone)]
pub struct DirectItem {
room_info: MatrixRoomInfo,
name: String,
}
impl DirectItem {
fn new(room_info: MatrixRoomInfo, store: &mut ProgramStore) -> Self {
let room_id = room_info.deref().0.room_id().to_owned();
let name = store.application.get_room_info(room_id).name.clone().unwrap_or_default();
DirectItem { room_info, name }
}
#[inline]
fn room(&self) -> &MatrixRoom {
&self.room_info.deref().0
}
#[inline]
fn room_id(&self) -> &RoomId {
self.room().room_id()
}
#[inline]
fn tags(&self) -> &Option<Tags> {
&self.room_info.deref().1
}
}
impl ToString for DirectItem {
fn to_string(&self) -> String {
return self.name.clone();
}
}
impl ListItem<IambInfo> for DirectItem {
fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text {
if let Some(tags) = &self.tags() {
let style = selected_style(selected);
let mut spans = vec![Span::styled(self.name.as_str(), style)];
append_tags(tags, &mut spans, style);
Text::from(Spans(spans))
} else {
selected_text(self.name.as_str(), selected)
}
}
fn get_word(&self) -> Option<String> {
self.room_id().to_string().into()
}
}
impl PartialEq for DirectItem {
fn eq(&self, other: &Self) -> bool {
self.room_id() == other.room_id()
}
}
impl Eq for DirectItem {}
impl Ord for DirectItem {
fn cmp(&self, other: &Self) -> Ordering {
tag_cmp(self.tags(), other.tags()).then_with(|| room_cmp(self.room(), other.room()))
}
}
impl PartialOrd for DirectItem {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.cmp(other).into()
}
}
impl Promptable<ProgramContext, ProgramStore, IambInfo> for DirectItem {
fn prompt(
&mut self,
act: &PromptAction,
ctx: &ProgramContext,
_: &mut ProgramStore,
) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
room_prompt(self.room_id(), act, ctx)
}
}
#[derive(Clone)]
pub struct SpaceItem {
room: MatrixRoom,
name: String,
}
impl SpaceItem {
fn new(room: MatrixRoom, store: &mut ProgramStore) -> Self {
let room_id = room.room_id();
let name = store
.application
.get_room_info(room_id.to_owned())
.name
.clone()
.unwrap_or_default();
if let Some(alias) = room.canonical_alias() {
store.application.names.insert(alias.to_string(), room_id.to_owned());
}
SpaceItem { room, name }
}
}
impl PartialEq for SpaceItem {
fn eq(&self, other: &Self) -> bool {
self.room.room_id() == other.room.room_id()
}
}
impl Eq for SpaceItem {}
impl Ord for SpaceItem {
fn cmp(&self, other: &Self) -> Ordering {
room_cmp(&self.room, &other.room)
}
}
impl PartialOrd for SpaceItem {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.cmp(other).into()
}
}
impl ToString for SpaceItem {
fn to_string(&self) -> String {
return self.room.room_id().to_string();
}
}
impl ListItem<IambInfo> for SpaceItem {
fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text {
selected_text(self.name.as_str(), selected)
}
fn get_word(&self) -> Option<String> {
self.room.room_id().to_string().into()
}
}
impl Promptable<ProgramContext, ProgramStore, IambInfo> for SpaceItem {
fn prompt(
&mut self,
act: &PromptAction,
ctx: &ProgramContext,
_: &mut ProgramStore,
) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
room_prompt(self.room.room_id(), act, ctx)
}
}
#[derive(Clone)]
pub struct VerifyItem {
user_dev: String,
sasv1: SasVerification,
}
impl VerifyItem {
fn new(user_dev: String, sasv1: SasVerification) -> Self {
VerifyItem { user_dev, sasv1 }
}
fn show_item(&self) -> String {
let state = if self.sasv1.is_done() {
"done"
} else if self.sasv1.is_cancelled() {
"cancelled"
} else if self.sasv1.emoji().is_some() {
"accepted"
} else {
"not accepted"
};
if self.sasv1.is_self_verification() {
let device = self.sasv1.other_device();
if let Some(display_name) = device.display_name() {
format!("Device verification with {display_name} ({state})")
} else {
format!("Device verification with device {} ({})", device.device_id(), state)
}
} else {
format!("User Verification with {} ({})", self.sasv1.other_user_id(), state)
}
}
}
impl PartialEq for VerifyItem {
fn eq(&self, other: &Self) -> bool {
self.user_dev == other.user_dev
}
}
impl Eq for VerifyItem {}
impl Ord for VerifyItem {
fn cmp(&self, other: &Self) -> Ordering {
fn state_val(sas: &SasVerification) -> usize {
if sas.is_done() {
return 3;
} else if sas.is_cancelled() {
return 2;
} else {
return 1;
}
}
fn device_val(sas: &SasVerification) -> usize {
if sas.is_self_verification() {
return 1;
} else {
return 2;
}
}
let state1 = state_val(&self.sasv1);
let state2 = state_val(&other.sasv1);
let dev1 = device_val(&self.sasv1);
let dev2 = device_val(&other.sasv1);
let scmp = state1.cmp(&state2);
let dcmp = dev1.cmp(&dev2);
scmp.then(dcmp).then_with(|| {
let did1 = self.sasv1.other_device().device_id();
let did2 = other.sasv1.other_device().device_id();
did1.cmp(did2)
})
}
}
impl PartialOrd for VerifyItem {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.cmp(other).into()
}
}
impl From<(&String, &SasVerification)> for VerifyItem {
fn from((user_dev, sasv1): (&String, &SasVerification)) -> Self {
VerifyItem::new(user_dev.clone(), sasv1.clone())
}
}
impl ToString for VerifyItem {
fn to_string(&self) -> String {
if self.sasv1.is_done() {
String::new()
} else if self.sasv1.is_cancelled() {
format!(":verify request {}", self.sasv1.other_user_id())
} else if self.sasv1.emoji().is_some() {
format!(":verify confirm {}", self.user_dev)
} else {
format!(":verify accept {}", self.user_dev)
}
}
}
impl ListItem<IambInfo> for VerifyItem {
fn show(&self, selected: bool, _: &ViewportContext<ListCursor>, _: &mut ProgramStore) -> Text {
let mut lines = vec![];
let bold = Style::default().add_modifier(StyleModifier::BOLD);
let item = Span::styled(self.show_item(), selected_style(selected));
lines.push(Spans::from(item));
if self.sasv1.is_done() {
// Print nothing.
} else if self.sasv1.is_cancelled() {
if let Some(info) = self.sasv1.cancel_info() {
lines.push(Spans::from(format!(" Cancelled: {}", info.reason())));
lines.push(Spans::from(""));
}
lines.push(Spans::from(" You can start a new verification request with:"));
} else if let Some(emoji) = self.sasv1.emoji() {
lines.push(Spans::from(
" Both devices should see the following Emoji sequence:".to_string(),
));
lines.push(Spans::from(""));
for line in format_emojis(emoji).lines() {
lines.push(Spans::from(format!(" {line}")));
}
lines.push(Spans::from(""));
lines.push(Spans::from(" If they don't match, run:"));
lines.push(Spans::from(""));
lines.push(Spans::from(Span::styled(
format!(":verify mismatch {}", self.user_dev),
bold,
)));
lines.push(Spans::from(""));
lines.push(Spans::from(" If everything looks right, you can confirm with:"));
} else {
lines.push(Spans::from(" To accept this request, run:"));
}
let cmd = self.to_string();
if !cmd.is_empty() {
lines.push(Spans::from(""));
lines.push(Spans(vec![Span::from(" "), Span::styled(cmd, bold)]));
lines.push(Spans::from(""));
lines.push(Spans(vec![
Span::from("You can copy the above command with "),
Span::styled("yy", bold),
Span::from(" and then execute it with "),
Span::styled("@\"", bold),
]));
}
Text { lines }
}
fn get_word(&self) -> Option<String> {
None
}
}
impl Promptable<ProgramContext, ProgramStore, IambInfo> for VerifyItem {
fn prompt(
&mut self,
act: &PromptAction,
_: &ProgramContext,
_: &mut ProgramStore,
) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
match act {
PromptAction::Submit => Ok(vec![]),
PromptAction::Abort(_) => {
let msg = "Cannot abort entry inside a list";
let err = EditError::Failure(msg.into());
Err(err)
},
PromptAction::Recall(..) => {
let msg = "Cannot recall history inside a list";
let err = EditError::Failure(msg.into());
Err(err)
},
_ => Err(EditError::Unimplemented("unknown prompt action".to_string())),
}
}
}
#[derive(Clone)]
pub struct MemberItem {
member: RoomMember,
room_id: OwnedRoomId,
}
impl MemberItem {
fn new(member: RoomMember, room_id: OwnedRoomId) -> Self {
Self { member, room_id }
}
}
impl ToString for MemberItem {
fn to_string(&self) -> String {
self.member.user_id().to_string()
}
}
impl ListItem<IambInfo> for MemberItem {
fn show(
&self,
selected: bool,
_: &ViewportContext<ListCursor>,
store: &mut ProgramStore,
) -> Text {
let info = store.application.rooms.get_or_default(self.room_id.clone());
let user_id = self.member.user_id();
let (color, name) = store.application.settings.get_user_overrides(self.member.user_id());
let color = color.unwrap_or_else(|| super::config::user_color(user_id.as_str()));
let mut style = super::config::user_style_from_color(color);
if selected {
style = style.add_modifier(StyleModifier::REVERSED);
}
let mut spans = vec![];
let mut parens = false;
if let Some(name) = name {
spans.push(Span::styled(name, style));
parens = true;
} else if let Some(display) = info.display_names.get(user_id) {
spans.push(Span::styled(display.clone(), style));
parens = true;
}
spans.extend(parens.then_some(Span::styled(" (", style)));
spans.push(Span::styled(user_id.as_str(), style));
spans.extend(parens.then_some(Span::styled(")", style)));
let state = match self.member.membership() {
MembershipState::Ban => Span::raw(" (banned)").into(),
MembershipState::Invite => Span::raw(" (invited)").into(),
MembershipState::Knock => Span::raw(" (wants to join)").into(),
MembershipState::Leave => Span::raw(" (left)").into(),
MembershipState::Join => None,
_ => None,
};
spans.extend(state);
return Spans(spans).into();
}
fn get_word(&self) -> Option<String> {
self.member.user_id().to_string().into()
}
}
impl Promptable<ProgramContext, ProgramStore, IambInfo> for MemberItem {
fn prompt(
&mut self,
act: &PromptAction,
_: &ProgramContext,
_: &mut ProgramStore,
) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
match act {
PromptAction::Submit => Ok(vec![]),
PromptAction::Abort(_) => {
let msg = "Cannot abort entry inside a list";
let err = EditError::Failure(msg.into());
Err(err)
},
PromptAction::Recall(..) => {
let msg = "Cannot recall history inside a list";
let err = EditError::Failure(msg.into());
Err(err)
},
_ => Err(EditError::Unimplemented("unknown prompt action".to_string())),
}
}
}
07070100000021000041ED00000000000000000000000264A9007B00000000000000000000000000000000000000000000001C00000000iamb-0.0.8/src/windows/room07070100000022000081A400000000000000000000000164A9007B00007616000000000000000000000000000000000000002400000000iamb-0.0.8/src/windows/room/chat.rsuse std::borrow::Cow;
use std::ffi::{OsStr, OsString};
use std::fs;
use std::ops::Deref;
use std::path::{Path, PathBuf};
use modalkit::editing::store::RegisterError;
use std::process::Command;
use tokio;
use matrix_sdk::{
attachment::AttachmentConfig,
media::{MediaFormat, MediaRequest},
room::{Joined, Room as MatrixRoom},
ruma::{
events::reaction::{ReactionEventContent, Relation as Reaction},
events::room::message::{
MessageType,
OriginalRoomMessageEvent,
Relation,
Replacement,
RoomMessageEventContent,
TextMessageEventContent,
},
EventId,
OwnedRoomId,
RoomId,
},
};
use modalkit::{
input::dialog::PromptYesNo,
tui::{
buffer::Buffer,
layout::Rect,
text::{Span, Spans},
widgets::{Paragraph, StatefulWidget, Widget},
},
widgets::textbox::{TextBox, TextBoxState},
widgets::TerminalCursor,
widgets::{PromptActions, WindowOps},
};
use modalkit::editing::{
action::{
Action,
EditError,
EditInfo,
EditResult,
Editable,
EditorAction,
InfoMessage,
Jumpable,
PromptAction,
Promptable,
Scrollable,
UIError,
},
base::{CloseFlags, Count, MoveDir1D, PositionList, ScrollStyle, WordStyle, WriteFlags},
completion::CompletionList,
context::Resolve,
history::{self, HistoryList},
rope::EditRope,
};
use crate::base::{
DownloadFlags,
IambAction,
IambBufferId,
IambError,
IambInfo,
IambResult,
MessageAction,
ProgramAction,
ProgramContext,
ProgramStore,
RoomFocus,
RoomInfo,
SendAction,
};
use crate::message::{text_to_message, Message, MessageEvent, MessageKey, MessageTimeStamp};
use crate::worker::Requester;
use super::scrollback::{Scrollback, ScrollbackState};
pub struct ChatState {
room_id: OwnedRoomId,
room: MatrixRoom,
tbox: TextBoxState<IambInfo>,
sent: HistoryList<EditRope>,
sent_scrollback: history::ScrollbackState,
scrollback: ScrollbackState,
focus: RoomFocus,
reply_to: Option<MessageKey>,
editing: Option<MessageKey>,
}
impl ChatState {
pub fn new(room: MatrixRoom, store: &mut ProgramStore) -> Self {
let room_id = room.room_id().to_owned();
let scrollback = ScrollbackState::new(room_id.clone());
let id = IambBufferId::Room(room_id.clone(), RoomFocus::MessageBar);
let ebuf = store.load_buffer(id);
let tbox = TextBoxState::new(ebuf);
ChatState {
room_id,
room,
tbox,
sent: HistoryList::new(EditRope::from(""), 100),
sent_scrollback: history::ScrollbackState::Pending,
scrollback,
focus: RoomFocus::MessageBar,
reply_to: None,
editing: None,
}
}
fn get_joined(&self, worker: &Requester) -> Result<Joined, IambError> {
worker.client.get_joined_room(self.id()).ok_or(IambError::NotJoined)
}
fn get_reply_to<'a>(&self, info: &'a RoomInfo) -> Option<&'a OriginalRoomMessageEvent> {
let key = self.reply_to.as_ref()?;
let msg = info.messages.get(key)?;
if let MessageEvent::Original(ev) = &msg.event {
Some(ev)
} else {
None
}
}
fn reset(&mut self) -> EditRope {
self.reply_to = None;
self.editing = None;
self.tbox.reset()
}
pub fn refresh_room(&mut self, store: &mut ProgramStore) {
if let Some(room) = store.application.worker.client.get_room(self.id()) {
self.room = room;
}
}
pub async fn message_command(
&mut self,
act: MessageAction,
_: ProgramContext,
store: &mut ProgramStore,
) -> IambResult<EditInfo> {
let client = &store.application.worker.client;
let settings = &store.application.settings;
let info = store.application.rooms.get_or_default(self.room_id.clone());
let msg = self
.scrollback
.get_mut(&mut info.messages)
.ok_or(IambError::NoSelectedMessage)?;
match act {
MessageAction::Cancel(skip_confirm) => {
self.reply_to = None;
self.editing = None;
if skip_confirm {
return Ok(None);
}
let msg = "Would you like to clear the message bar?";
let act = PromptAction::Abort(false);
let prompt = PromptYesNo::new(msg, vec![Action::from(act)]);
let prompt = Box::new(prompt);
Err(UIError::NeedConfirm(prompt))
},
MessageAction::Download(filename, flags) => {
if let MessageEvent::Original(ev) = &msg.event {
let media = client.media();
let mut filename = match (filename, &settings.dirs.downloads) {
(Some(f), _) => PathBuf::from(f),
(None, Some(downloads)) => downloads.clone(),
(None, None) => return Err(IambError::NoDownloadDir.into()),
};
let (source, msg_filename) = match &ev.content.msgtype {
MessageType::Audio(c) => (c.source.clone(), c.body.as_str()),
MessageType::File(c) => {
(c.source.clone(), c.filename.as_deref().unwrap_or(c.body.as_str()))
},
MessageType::Image(c) => (c.source.clone(), c.body.as_str()),
MessageType::Video(c) => (c.source.clone(), c.body.as_str()),
_ => {
return Err(IambError::NoAttachment.into());
},
};
if filename.is_dir() {
filename.push(msg_filename);
}
if filename.exists() && !flags.contains(DownloadFlags::FORCE) {
// Find an incrementally suffixed filename, e.g. image-2.jpg -> image-3.jpg
if let Some(stem) = filename.file_stem().and_then(OsStr::to_str) {
let ext = filename.extension();
let mut filename_incr = filename.clone();
for n in 1..=1000 {
if let Some(ext) = ext.and_then(OsStr::to_str) {
filename_incr.set_file_name(format!("{}-{}.{}", stem, n, ext));
} else {
filename_incr.set_file_name(format!("{}-{}", stem, n));
}
if !filename_incr.exists() {
filename = filename_incr;
break;
}
}
}
}
if !filename.exists() || flags.contains(DownloadFlags::FORCE) {
let req = MediaRequest { source, format: MediaFormat::File };
let bytes =
media.get_media_content(&req, true).await.map_err(IambError::from)?;
fs::write(filename.as_path(), bytes.as_slice())?;
msg.downloaded = true;
} else if !flags.contains(DownloadFlags::OPEN) {
let msg = format!(
"The file {} already exists; add ! to end of command to overwrite it.",
filename.display()
);
let err = UIError::Failure(msg);
return Err(err);
}
let info = if flags.contains(DownloadFlags::OPEN) {
let target = filename.clone().into_os_string();
match open_command(
store.application.settings.tunables.open_command.as_ref(),
target,
) {
Ok(_) => {
InfoMessage::from(format!(
"Attachment downloaded to {} and opened",
filename.display()
))
},
Err(err) => {
return Err(err);
},
}
} else {
InfoMessage::from(format!(
"Attachment downloaded to {}",
filename.display()
))
};
return Ok(info.into());
}
Err(IambError::NoAttachment.into())
},
MessageAction::Edit => {
if msg.sender != settings.profile.user_id {
let msg = "Cannot edit messages sent by someone else";
let err = UIError::Failure(msg.into());
return Err(err);
}
let ev = match &msg.event {
MessageEvent::Original(ev) => &ev.content,
MessageEvent::Local(_, ev) => ev.deref(),
_ => {
let msg = "Cannot edit a redacted message";
let err = UIError::Failure(msg.into());
return Err(err);
},
};
let text = match &ev.msgtype {
MessageType::Text(msg) => msg.body.as_str(),
_ => {
let msg = "Cannot edit a non-text message";
let err = UIError::Failure(msg.into());
return Err(err);
},
};
self.tbox.set_text(text);
self.reply_to = msg.reply_to().and_then(|id| info.get_message_key(&id)).cloned();
self.editing = self.scrollback.get_key(info);
self.focus = RoomFocus::MessageBar;
Ok(None)
},
MessageAction::React(emoji) => {
let room = self.get_joined(&store.application.worker)?;
let event_id = match &msg.event {
MessageEvent::EncryptedOriginal(ev) => ev.event_id.clone(),
MessageEvent::EncryptedRedacted(ev) => ev.event_id.clone(),
MessageEvent::Original(ev) => ev.event_id.clone(),
MessageEvent::Local(event_id, _) => event_id.clone(),
MessageEvent::Redacted(_) => {
let msg = "Cannot react to a redacted message";
let err = UIError::Failure(msg.into());
return Err(err);
},
};
let reaction = Reaction::new(event_id, emoji);
let msg = ReactionEventContent::new(reaction);
let _ = room.send(msg, None).await.map_err(IambError::from)?;
Ok(None)
},
MessageAction::Redact(reason, skip_confirm) => {
if !skip_confirm {
let msg = "Are you sure you want to redact this message?";
let act = IambAction::Message(MessageAction::Redact(reason, true));
let prompt = PromptYesNo::new(msg, vec![Action::from(act)]);
let prompt = Box::new(prompt);
return Err(UIError::NeedConfirm(prompt));
}
let room = self.get_joined(&store.application.worker)?;
let event_id = match &msg.event {
MessageEvent::EncryptedOriginal(ev) => ev.event_id.clone(),
MessageEvent::EncryptedRedacted(ev) => ev.event_id.clone(),
MessageEvent::Original(ev) => ev.event_id.clone(),
MessageEvent::Local(event_id, _) => event_id.clone(),
MessageEvent::Redacted(_) => {
let msg = "Cannot redact already redacted message";
let err = UIError::Failure(msg.into());
return Err(err);
},
};
let event_id = event_id.as_ref();
let reason = reason.as_deref();
let _ = room.redact(event_id, reason, None).await.map_err(IambError::from)?;
Ok(None)
},
MessageAction::Reply => {
self.reply_to = self.scrollback.get_key(info);
self.focus = RoomFocus::MessageBar;
Ok(None)
},
MessageAction::Unreact(emoji) => {
let room = self.get_joined(&store.application.worker)?;
let event_id: &EventId = match &msg.event {
MessageEvent::EncryptedOriginal(ev) => ev.event_id.as_ref(),
MessageEvent::EncryptedRedacted(ev) => ev.event_id.as_ref(),
MessageEvent::Original(ev) => ev.event_id.as_ref(),
MessageEvent::Local(event_id, _) => event_id.as_ref(),
MessageEvent::Redacted(_) => {
let msg = "Cannot unreact to a redacted message";
let err = UIError::Failure(msg.into());
return Err(err);
},
};
let reactions = match info.reactions.get(event_id) {
Some(r) => r,
None => return Ok(None),
};
let reactions = reactions.iter().filter_map(|(event_id, (reaction, user_id))| {
if user_id != &settings.profile.user_id {
return None;
}
if let Some(emoji) = &emoji {
if emoji == reaction {
return Some(event_id);
} else {
return None;
}
} else {
return Some(event_id);
}
});
for reaction in reactions {
let _ = room.redact(reaction, None, None).await.map_err(IambError::from)?;
}
Ok(None)
},
}
}
pub async fn send_command(
&mut self,
act: SendAction,
_: ProgramContext,
store: &mut ProgramStore,
) -> IambResult<EditInfo> {
let room = store
.application
.worker
.client
.get_joined_room(self.id())
.ok_or(IambError::NotJoined)?;
let info = store.application.rooms.get_or_default(self.id().to_owned());
let mut show_echo = true;
let (event_id, msg) = match act {
SendAction::Submit => {
let msg = self.tbox.get();
if msg.is_blank() {
return Ok(None);
}
let mut msg = text_to_message(msg.trim_end().to_string());
if let Some((_, event_id)) = &self.editing {
msg.relates_to = Some(Relation::Replacement(Replacement::new(
event_id.clone(),
Box::new(msg.clone()),
)));
show_echo = false;
} else if let Some(m) = self.get_reply_to(info) {
// XXX: Switch to RoomMessageEventContent::reply() once it's stable?
msg = msg.make_reply_to(m);
}
// XXX: second parameter can be a locally unique transaction id.
// Useful for doing retries.
let resp = room.send(msg.clone(), None).await.map_err(IambError::from)?;
let event_id = resp.event_id;
// Reset message bar state now that it's been sent.
self.reset();
(event_id, msg)
},
SendAction::Upload(file) => {
let path = Path::new(file.as_str());
let mime = mime_guess::from_path(path).first_or(mime::APPLICATION_OCTET_STREAM);
let bytes = fs::read(path)?;
let name = path
.file_name()
.map(OsStr::to_string_lossy)
.unwrap_or_else(|| Cow::from("Attachment"));
let config = AttachmentConfig::new();
let resp = room
.send_attachment(name.as_ref(), &mime, bytes.as_ref(), config)
.await
.map_err(IambError::from)?;
// Mock up the local echo message for the scrollback.
let msg = TextMessageEventContent::plain(format!("[Attached File: {name}]"));
let msg = MessageType::Text(msg);
let msg = RoomMessageEventContent::new(msg);
(resp.event_id, msg)
},
SendAction::UploadImage(width, height, bytes) => {
// Convert to png because arboard does not give us the mime type.
let bytes =
image::ImageBuffer::from_raw(width as _, height as _, bytes.into_owned())
.ok_or(IambError::Clipboard)
.and_then(|imagebuf| {
let dynimage = image::DynamicImage::ImageRgba8(imagebuf);
let bytes = Vec::<u8>::new();
let mut buff = std::io::Cursor::new(bytes);
dynimage.write_to(&mut buff, image::ImageOutputFormat::Png)?;
Ok(buff.into_inner())
})
.map_err(IambError::from)?;
let mime = mime::IMAGE_PNG;
let name = "Clipboard.png";
let config = AttachmentConfig::new();
let resp = room
.send_attachment(name.as_ref(), &mime, bytes.as_ref(), config)
.await
.map_err(IambError::from)?;
// Mock up the local echo message for the scrollback.
let msg = TextMessageEventContent::plain(format!("[Attached File: {name}]"));
let msg = MessageType::Text(msg);
let msg = RoomMessageEventContent::new(msg);
(resp.event_id, msg)
},
};
if show_echo {
let user = store.application.settings.profile.user_id.clone();
let key = (MessageTimeStamp::LocalEcho, event_id.clone());
let msg = MessageEvent::Local(event_id, msg.into());
let msg = Message::new(msg, user, MessageTimeStamp::LocalEcho);
info.messages.insert(key, msg);
}
// Jump to the end of the scrollback to show the message.
self.scrollback.goto_latest();
Ok(None)
}
pub fn focus_toggle(&mut self) {
self.focus = match self.focus {
RoomFocus::Scrollback => RoomFocus::MessageBar,
RoomFocus::MessageBar => RoomFocus::Scrollback,
};
}
pub fn room(&self) -> &MatrixRoom {
&self.room
}
pub fn id(&self) -> &RoomId {
&self.room_id
}
pub fn typing_notice(
&self,
act: &EditorAction,
ctx: &ProgramContext,
store: &mut ProgramStore,
) {
if !self.focus.is_msgbar() || act.is_readonly(ctx) {
return;
}
if !store.application.settings.tunables.typing_notice_send {
return;
}
store.application.worker.typing_notice(self.room_id.clone());
}
}
macro_rules! delegate {
($s: expr, $id: ident => $e: expr) => {
match $s.focus {
RoomFocus::Scrollback => {
match $s {
ChatState { scrollback: $id, .. } => $e,
}
},
RoomFocus::MessageBar => {
match $s {
ChatState { tbox: $id, .. } => $e,
}
},
}
};
}
impl WindowOps<IambInfo> for ChatState {
fn draw(&mut self, area: Rect, buf: &mut Buffer, focused: bool, store: &mut ProgramStore) {
Chat::new(store).focus(focused).render(area, buf, self)
}
fn dup(&self, store: &mut ProgramStore) -> Self {
// XXX: I want each WindowSlot to have its own shared buffer, instead of each Room; need to
// find a good way to pass that info here so that it can be part of the content id.
let id = IambBufferId::Room(self.room_id.clone(), RoomFocus::MessageBar);
let ebuf = store.load_buffer(id);
let tbox = TextBoxState::new(ebuf);
ChatState {
room_id: self.room_id.clone(),
room: self.room.clone(),
tbox,
sent: self.sent.clone(),
sent_scrollback: history::ScrollbackState::Pending,
scrollback: self.scrollback.dup(store),
focus: self.focus,
reply_to: None,
editing: None,
}
}
fn close(&mut self, _: CloseFlags, _: &mut ProgramStore) -> bool {
// XXX: what's the right closing behaviour for a room?
// Should write send a message?
true
}
fn write(
&mut self,
_: Option<&str>,
_: WriteFlags,
_: &mut ProgramStore,
) -> IambResult<EditInfo> {
// XXX: what's the right writing behaviour for a room?
// Should write send a message?
Ok(None)
}
fn get_completions(&self) -> Option<CompletionList> {
delegate!(self, w => w.get_completions())
}
fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
delegate!(self, w => w.get_cursor_word(style))
}
fn get_selected_word(&self) -> Option<String> {
delegate!(self, w => w.get_selected_word())
}
}
impl Editable<ProgramContext, ProgramStore, IambInfo> for ChatState {
fn editor_command(
&mut self,
act: &EditorAction,
ctx: &ProgramContext,
store: &mut ProgramStore,
) -> EditResult<EditInfo, IambInfo> {
self.typing_notice(act, ctx, store);
match delegate!(self, w => w.editor_command(act, ctx, store)) {
res @ Ok(_) => res,
Err(EditError::WrongBuffer(IambBufferId::Room(room_id, focus)))
if room_id == self.room_id && act.is_switchable(ctx) =>
{
// Switch focus.
self.focus = focus;
// Run command again.
delegate!(self, w => w.editor_command(act, ctx, store))
},
Err(EditError::Register(RegisterError::ClipboardImage(data))) => {
let msg = "Do you really want to upload the image from your system clipboard?";
let send =
IambAction::Send(SendAction::UploadImage(data.width, data.height, data.bytes));
let prompt = PromptYesNo::new(msg, vec![Action::from(send)]);
let prompt = Box::new(prompt);
Err(EditError::NeedConfirm(prompt))
},
res @ Err(_) => res,
}
}
}
impl TerminalCursor for ChatState {
fn get_term_cursor(&self) -> Option<(u16, u16)> {
delegate!(self, w => w.get_term_cursor())
}
}
impl Jumpable<ProgramContext, IambInfo> for ChatState {
fn jump(
&mut self,
list: PositionList,
dir: MoveDir1D,
count: usize,
ctx: &ProgramContext,
) -> IambResult<usize> {
delegate!(self, w => w.jump(list, dir, count, ctx))
}
}
impl Scrollable<ProgramContext, ProgramStore, IambInfo> for ChatState {
fn scroll(
&mut self,
style: &ScrollStyle,
ctx: &ProgramContext,
store: &mut ProgramStore,
) -> EditResult<EditInfo, IambInfo> {
// Send all scroll commands to the scrollback.
//
// If there's enough message text for scrolling to be necessary,
// navigating with movement keys should be enough to do the job.
self.scrollback.scroll(style, ctx, store)
}
}
impl PromptActions<ProgramContext, ProgramStore, IambInfo> for ChatState {
fn submit(
&mut self,
ctx: &ProgramContext,
_: &mut ProgramStore,
) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
let act = SendAction::Submit;
Ok(vec![(IambAction::from(act).into(), ctx.clone())])
}
fn abort(
&mut self,
empty: bool,
_: &ProgramContext,
_: &mut ProgramStore,
) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
let text = self.tbox.get();
if empty && text.is_blank() {
return Ok(vec![]);
}
let text = self.reset().trim();
if text.is_empty() {
let _ = self.sent.end();
} else {
self.sent.select(text);
}
return Ok(vec![]);
}
fn recall(
&mut self,
dir: &MoveDir1D,
count: &Count,
prefixed: bool,
ctx: &ProgramContext,
_: &mut ProgramStore,
) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
let count = ctx.resolve(count);
let rope = self.tbox.get();
let text = self.sent.recall(&rope, &mut self.sent_scrollback, *dir, prefixed, count);
if let Some(text) = text {
self.tbox.set_text(text);
}
Ok(vec![])
}
}
impl Promptable<ProgramContext, ProgramStore, IambInfo> for ChatState {
fn prompt(
&mut self,
act: &PromptAction,
ctx: &ProgramContext,
store: &mut ProgramStore,
) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
if let RoomFocus::Scrollback = self.focus {
return Ok(vec![]);
}
match act {
PromptAction::Submit => self.submit(ctx, store),
PromptAction::Abort(empty) => self.abort(*empty, ctx, store),
PromptAction::Recall(dir, count, prefixed) => {
self.recall(dir, count, *prefixed, ctx, store)
},
_ => Err(EditError::Unimplemented("unknown prompt action".to_string())),
}
}
}
pub struct Chat<'a> {
store: &'a mut ProgramStore,
focused: bool,
}
impl<'a> Chat<'a> {
pub fn new(store: &'a mut ProgramStore) -> Chat<'a> {
Chat { store, focused: false }
}
pub fn focus(mut self, focused: bool) -> Self {
self.focused = focused;
self
}
}
impl<'a> StatefulWidget for Chat<'a> {
type State = ChatState;
fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
// Determine whether we have a description to show for the message bar.
let desc_spans = match (&state.editing, &state.reply_to) {
(None, None) => None,
(Some(_), None) => Some(Spans::from("Editing message")),
(editing, Some(_)) => {
state.reply_to.as_ref().and_then(|k| {
let room = self.store.application.rooms.get(state.id())?;
let msg = room.messages.get(k)?;
let user =
self.store.application.settings.get_user_span(msg.sender.as_ref(), room);
let prefix = if editing.is_some() {
Span::from("Editing reply to ")
} else {
Span::from("Replying to ")
};
let spans = Spans(vec![prefix, user]);
spans.into()
})
},
};
// Determine the region to show each UI element.
let lines = state.tbox.has_lines(5).max(1) as u16;
let drawh = area.height;
let texth = lines.min(drawh).clamp(1, 5);
let desch = if desc_spans.is_some() {
drawh.saturating_sub(texth).min(1)
} else {
0
};
let scrollh = drawh.saturating_sub(texth).saturating_sub(desch);
let scrollarea = Rect::new(area.x, area.y, area.width, scrollh);
let descarea = Rect::new(area.x, scrollarea.y + scrollh, area.width, desch);
let textarea = Rect::new(area.x, descarea.y + desch, area.width, texth);
// Render the message bar and any description for it.
if let Some(desc_spans) = desc_spans {
Paragraph::new(desc_spans).render(descarea, buf);
}
let prompt = if self.focused { "> " } else { " " };
let tbox = TextBox::new().prompt(prompt);
tbox.render(textarea, buf, &mut state.tbox);
// Render the message scrollback.
let scrollback_focused = state.focus.is_scrollback() && self.focused;
let scrollback = Scrollback::new(self.store)
.focus(scrollback_focused)
.room_focus(self.focused);
scrollback.render(scrollarea, buf, &mut state.scrollback);
}
}
fn open_command(open_command: Option<&Vec<String>>, target: OsString) -> IambResult<()> {
if let Some(mut cmd) = open_command.and_then(cmd) {
cmd.arg(target);
cmd.spawn()?;
return Ok(());
} else {
// open::that may not return until the spawned program closes.
tokio::task::spawn_blocking(move || {
return open::that(target);
});
return Ok(());
}
}
fn cmd(open_command: &Vec<String>) -> Option<Command> {
if let [program, args @ ..] = open_command.as_slice() {
let mut cmd = Command::new(program);
cmd.args(args);
return Some(cmd);
}
None
}
07070100000023000081A400000000000000000000000164A9007B0000369D000000000000000000000000000000000000002300000000iamb-0.0.8/src/windows/room/mod.rsuse matrix_sdk::{
room::{Invited, Room as MatrixRoom},
ruma::{
events::{
room::{name::RoomNameEventContent, topic::RoomTopicEventContent},
tag::{TagInfo, Tags},
},
RoomId,
},
DisplayName,
};
use modalkit::tui::{
buffer::Buffer,
layout::{Alignment, Rect},
style::{Modifier as StyleModifier, Style},
text::{Span, Spans, Text},
widgets::{Paragraph, StatefulWidget, Widget},
};
use modalkit::{
editing::action::{
Action,
EditInfo,
EditResult,
Editable,
EditorAction,
Jumpable,
PromptAction,
Promptable,
Scrollable,
UIError,
},
editing::base::{
Axis,
CloseFlags,
Count,
MoveDir1D,
OpenTarget,
PositionList,
ScrollStyle,
WordStyle,
WriteFlags,
},
editing::completion::CompletionList,
input::dialog::PromptYesNo,
input::InputContext,
widgets::{TermOffset, TerminalCursor, WindowOps},
};
use crate::base::{
IambAction,
IambError,
IambId,
IambInfo,
IambResult,
MessageAction,
ProgramAction,
ProgramContext,
ProgramStore,
RoomAction,
RoomField,
SendAction,
};
use self::chat::ChatState;
use self::space::{Space, SpaceState};
mod chat;
mod scrollback;
mod space;
macro_rules! delegate {
($s: expr, $id: ident => $e: expr) => {
match $s {
RoomState::Chat($id) => $e,
RoomState::Space($id) => $e,
}
};
}
pub enum RoomState {
Chat(ChatState),
Space(SpaceState),
}
impl From<ChatState> for RoomState {
fn from(chat: ChatState) -> Self {
RoomState::Chat(chat)
}
}
impl From<SpaceState> for RoomState {
fn from(space: SpaceState) -> Self {
RoomState::Space(space)
}
}
impl RoomState {
pub fn new(
room: MatrixRoom,
name: DisplayName,
tags: Option<Tags>,
store: &mut ProgramStore,
) -> Self {
let room_id = room.room_id().to_owned();
let info = store.application.get_room_info(room_id);
info.name = name.to_string().into();
info.tags = tags;
if room.is_space() {
SpaceState::new(room).into()
} else {
ChatState::new(room, store).into()
}
}
pub fn refresh_room(&mut self, store: &mut ProgramStore) {
match self {
RoomState::Chat(chat) => chat.refresh_room(store),
RoomState::Space(space) => space.refresh_room(store),
}
}
fn draw_invite(
&self,
invited: Invited,
area: Rect,
buf: &mut Buffer,
store: &mut ProgramStore,
) {
let inviter = store.application.worker.get_inviter(invited.clone());
let name = match invited.canonical_alias() {
Some(alias) => alias.to_string(),
None => format!("{:?}", store.application.get_room_title(self.id())),
};
let mut invited = vec![Span::from(format!("You have been invited to join {name}"))];
if let Ok(Some(inviter)) = &inviter {
let info = store.application.rooms.get_or_default(self.id().to_owned());
invited.push(Span::from(" by "));
invited.push(store.application.settings.get_user_span(inviter.user_id(), info));
}
let l1 = Spans(invited);
let l2 = Spans::from(
"You can run `:invite accept` or `:invite reject` to accept or reject this invitation.",
);
let text = Text { lines: vec![l1, l2] };
Paragraph::new(text).alignment(Alignment::Center).render(area, buf);
return;
}
pub async fn message_command(
&mut self,
act: MessageAction,
ctx: ProgramContext,
store: &mut ProgramStore,
) -> IambResult<EditInfo> {
match self {
RoomState::Chat(chat) => chat.message_command(act, ctx, store).await,
RoomState::Space(_) => Err(IambError::NoSelectedMessage.into()),
}
}
pub async fn send_command(
&mut self,
act: SendAction,
ctx: ProgramContext,
store: &mut ProgramStore,
) -> IambResult<EditInfo> {
match self {
RoomState::Chat(chat) => chat.send_command(act, ctx, store).await,
RoomState::Space(_) => Err(IambError::NoSelectedRoom.into()),
}
}
pub async fn room_command(
&mut self,
act: RoomAction,
_: ProgramContext,
store: &mut ProgramStore,
) -> IambResult<Vec<(Action<IambInfo>, ProgramContext)>> {
match act {
RoomAction::InviteAccept => {
if let Some(room) = store.application.worker.client.get_invited_room(self.id()) {
let details = room.invite_details().await.map_err(IambError::from)?;
let details = details.invitee.event().original_content();
let is_direct = details.and_then(|ev| ev.is_direct).unwrap_or_default();
room.accept_invitation().await.map_err(IambError::from)?;
if is_direct {
room.set_is_direct(true).await.map_err(IambError::from)?;
}
Ok(vec![])
} else {
Err(IambError::NotInvited.into())
}
},
RoomAction::InviteReject => {
if let Some(room) = store.application.worker.client.get_invited_room(self.id()) {
room.reject_invitation().await.map_err(IambError::from)?;
Ok(vec![])
} else {
Err(IambError::NotInvited.into())
}
},
RoomAction::InviteSend(user) => {
if let Some(room) = store.application.worker.client.get_joined_room(self.id()) {
room.invite_user_by_id(user.as_ref()).await.map_err(IambError::from)?;
Ok(vec![])
} else {
Err(IambError::NotJoined.into())
}
},
RoomAction::Leave(skip_confirm) => {
if let Some(room) = store.application.worker.client.get_joined_room(self.id()) {
if skip_confirm {
room.leave().await.map_err(IambError::from)?;
Ok(vec![])
} else {
let msg = "Do you really want to leave this room?";
let leave = IambAction::Room(RoomAction::Leave(true));
let prompt = PromptYesNo::new(msg, vec![Action::from(leave)]);
let prompt = Box::new(prompt);
Err(UIError::NeedConfirm(prompt))
}
} else {
Err(IambError::NotJoined.into())
}
},
RoomAction::Members(mut cmd) => {
let width = Count::Exact(30);
let act =
cmd.default_axis(Axis::Vertical).default_relation(MoveDir1D::Next).window(
OpenTarget::Application(IambId::MemberList(self.id().to_owned())),
width.into(),
);
Ok(vec![(act, cmd.context.take())])
},
RoomAction::Set(field, value) => {
let room = store
.application
.get_joined_room(self.id())
.ok_or(UIError::Application(IambError::NotJoined))?;
match field {
RoomField::Name => {
let ev = RoomNameEventContent::new(value.into());
let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
},
RoomField::Tag(tag) => {
let mut info = TagInfo::new();
info.order = Some(1.0);
let _ = room.set_tag(tag, info).await.map_err(IambError::from)?;
},
RoomField::Topic => {
let ev = RoomTopicEventContent::new(value);
let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
},
}
Ok(vec![])
},
RoomAction::Unset(field) => {
let room = store
.application
.get_joined_room(self.id())
.ok_or(UIError::Application(IambError::NotJoined))?;
match field {
RoomField::Name => {
let ev = RoomNameEventContent::new(None);
let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
},
RoomField::Tag(tag) => {
let _ = room.remove_tag(tag).await.map_err(IambError::from)?;
},
RoomField::Topic => {
let ev = RoomTopicEventContent::new("".into());
let _ = room.send_state_event(ev).await.map_err(IambError::from)?;
},
}
Ok(vec![])
},
}
}
pub fn get_title(&self, store: &mut ProgramStore) -> Spans {
let title = store.application.get_room_title(self.id());
let style = Style::default().add_modifier(StyleModifier::BOLD);
let mut spans = vec![Span::styled(title, style)];
match self.room().topic() {
Some(desc) if !desc.is_empty() => {
spans.push(" (".into());
spans.push(desc.into());
spans.push(")".into());
},
_ => {},
}
Spans(spans)
}
pub fn focus_toggle(&mut self) {
match self {
RoomState::Chat(chat) => chat.focus_toggle(),
RoomState::Space(_) => return,
}
}
pub fn room(&self) -> &MatrixRoom {
match self {
RoomState::Chat(chat) => chat.room(),
RoomState::Space(space) => space.room(),
}
}
pub fn id(&self) -> &RoomId {
match self {
RoomState::Chat(chat) => chat.id(),
RoomState::Space(space) => space.id(),
}
}
}
impl Editable<ProgramContext, ProgramStore, IambInfo> for RoomState {
fn editor_command(
&mut self,
act: &EditorAction,
ctx: &ProgramContext,
store: &mut ProgramStore,
) -> EditResult<EditInfo, IambInfo> {
delegate!(self, w => w.editor_command(act, ctx, store))
}
}
impl Jumpable<ProgramContext, IambInfo> for RoomState {
fn jump(
&mut self,
list: PositionList,
dir: MoveDir1D,
count: usize,
ctx: &ProgramContext,
) -> IambResult<usize> {
delegate!(self, w => w.jump(list, dir, count, ctx))
}
}
impl Scrollable<ProgramContext, ProgramStore, IambInfo> for RoomState {
fn scroll(
&mut self,
style: &ScrollStyle,
ctx: &ProgramContext,
store: &mut ProgramStore,
) -> EditResult<EditInfo, IambInfo> {
delegate!(self, w => w.scroll(style, ctx, store))
}
}
impl Promptable<ProgramContext, ProgramStore, IambInfo> for RoomState {
fn prompt(
&mut self,
act: &PromptAction,
ctx: &ProgramContext,
store: &mut ProgramStore,
) -> EditResult<Vec<(ProgramAction, ProgramContext)>, IambInfo> {
delegate!(self, w => w.prompt(act, ctx, store))
}
}
impl TerminalCursor for RoomState {
fn get_term_cursor(&self) -> Option<TermOffset> {
delegate!(self, w => w.get_term_cursor())
}
}
impl WindowOps<IambInfo> for RoomState {
fn draw(&mut self, area: Rect, buf: &mut Buffer, focused: bool, store: &mut ProgramStore) {
if let MatrixRoom::Invited(_) = self.room() {
self.refresh_room(store);
}
if let MatrixRoom::Invited(invited) = self.room() {
self.draw_invite(invited.clone(), area, buf, store);
}
match self {
RoomState::Chat(chat) => chat.draw(area, buf, focused, store),
RoomState::Space(space) => {
Space::new(store).focus(focused).render(area, buf, space);
},
}
}
fn dup(&self, store: &mut ProgramStore) -> Self {
match self {
RoomState::Chat(chat) => RoomState::Chat(chat.dup(store)),
RoomState::Space(space) => RoomState::Space(space.dup(store)),
}
}
fn close(&mut self, flags: CloseFlags, store: &mut ProgramStore) -> bool {
match self {
RoomState::Chat(chat) => chat.close(flags, store),
RoomState::Space(space) => space.close(flags, store),
}
}
fn write(
&mut self,
path: Option<&str>,
flags: WriteFlags,
store: &mut ProgramStore,
) -> IambResult<EditInfo> {
match self {
RoomState::Chat(chat) => chat.write(path, flags, store),
RoomState::Space(space) => space.write(path, flags, store),
}
}
fn get_completions(&self) -> Option<CompletionList> {
match self {
RoomState::Chat(chat) => chat.get_completions(),
RoomState::Space(space) => space.get_completions(),
}
}
fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
match self {
RoomState::Chat(chat) => chat.get_cursor_word(style),
RoomState::Space(space) => space.get_cursor_word(style),
}
}
fn get_selected_word(&self) -> Option<String> {
match self {
RoomState::Chat(chat) => chat.get_selected_word(),
RoomState::Space(space) => space.get_selected_word(),
}
}
}
07070100000024000081A400000000000000000000000164A9007B0000E17A000000000000000000000000000000000000002A00000000iamb-0.0.8/src/windows/room/scrollback.rsuse std::collections::HashSet;
use regex::Regex;
use matrix_sdk::ruma::OwnedRoomId;
use modalkit::tui::{
buffer::Buffer,
layout::{Alignment, Rect},
style::{Modifier as StyleModifier, Style},
text::{Span, Spans},
widgets::{Paragraph, StatefulWidget, Widget},
};
use modalkit::widgets::{ScrollActions, TerminalCursor, WindowOps};
use modalkit::editing::{
action::{
Action,
CursorAction,
EditAction,
EditError,
EditInfo,
EditResult,
Editable,
EditorAction,
EditorActions,
HistoryAction,
InsertTextAction,
Jumpable,
PromptAction,
Promptable,
Scrollable,
Searchable,
SelectionAction,
UIError,
UIResult,
},
base::{
Axis,
CloseFlags,
CompletionDisplay,
CompletionSelection,
CompletionType,
Count,
EditRange,
EditTarget,
Mark,
MoveDir1D,
MoveDir2D,
MoveDirMod,
MovePosition,
MoveTerminus,
MoveType,
PositionList,
RangeType,
Register,
ScrollSize,
ScrollStyle,
SearchType,
TargetShape,
ViewportContext,
WordStyle,
WriteFlags,
},
completion::CompletionList,
context::{EditContext, Resolve},
cursor::{CursorGroup, CursorState},
history::HistoryList,
rope::EditRope,
store::{RegisterCell, RegisterPutFlags},
};
use crate::{
base::{IambBufferId, IambInfo, IambResult, ProgramContext, ProgramStore, RoomFocus, RoomInfo},
config::ApplicationSettings,
message::{Message, MessageCursor, MessageKey, Messages},
};
fn nth_key_before(pos: MessageKey, n: usize, info: &RoomInfo) -> MessageKey {
let mut end = &pos;
let iter = info.messages.range(..=&pos).rev().enumerate();
for (i, (key, _)) in iter {
end = key;
if i >= n {
break;
}
}
end.clone()
}
fn nth_before(pos: MessageKey, n: usize, info: &RoomInfo) -> MessageCursor {
nth_key_before(pos, n, info).into()
}
fn nth_key_after(pos: MessageKey, n: usize, info: &RoomInfo) -> MessageKey {
let mut end = &pos;
let iter = info.messages.range(&pos..).enumerate();
for (i, (key, _)) in iter {
end = key;
if i >= n {
break;
}
}
end.clone()
}
fn nth_after(pos: MessageKey, n: usize, info: &RoomInfo) -> MessageCursor {
nth_key_after(pos, n, info).into()
}
fn prevmsg<'a>(key: &MessageKey, info: &'a RoomInfo) -> Option<&'a Message> {
info.messages.range(..key).next_back().map(|(_, v)| v)
}
pub struct ScrollbackState {
/// The room identifier.
room_id: OwnedRoomId,
/// The buffer identifier used for saving marks, etc.
id: IambBufferId,
/// The currently selected message in the scrollback.
cursor: MessageCursor,
/// Contextual info about the viewport used during rendering.
viewctx: ViewportContext<MessageCursor>,
/// The jumplist of visited messages.
jumped: HistoryList<MessageCursor>,
/// Whether the full message should be drawn during the next render() call.
///
/// This is used to ensure that ^E/^Y work nicely when the cursor is currently
/// on a multiline message.
show_full_on_redraw: bool,
}
impl ScrollbackState {
pub fn new(room_id: OwnedRoomId) -> ScrollbackState {
let id = IambBufferId::Room(room_id.to_owned(), RoomFocus::Scrollback);
let cursor = MessageCursor::default();
let viewctx = ViewportContext::default();
let jumped = HistoryList::default();
let show_full_on_redraw = false;
ScrollbackState {
room_id,
id,
cursor,
viewctx,
jumped,
show_full_on_redraw,
}
}
pub fn goto_latest(&mut self) {
self.cursor = MessageCursor::latest();
}
/// Set the dimensions and placement within the terminal window for this list.
pub fn set_term_info(&mut self, area: Rect) {
self.viewctx.dimensions = (area.width as usize, area.height as usize);
}
pub fn get_key(&self, info: &mut RoomInfo) -> Option<MessageKey> {
self.cursor
.timestamp
.clone()
.or_else(|| info.messages.last_key_value().map(|kv| kv.0.clone()))
}
pub fn get_mut<'a>(&mut self, messages: &'a mut Messages) -> Option<&'a mut Message> {
if let Some(k) = &self.cursor.timestamp {
messages.get_mut(k)
} else {
messages.last_entry().map(|o| o.into_mut())
}
}
pub fn messages<'a>(
&self,
range: EditRange<MessageCursor>,
info: &'a RoomInfo,
) -> impl Iterator<Item = (&'a MessageKey, &'a Message)> {
let start = range.start.to_key(info);
let end = range.end.to_key(info);
let (start, end) = if let (Some(start), Some(end)) = (start, end) {
(start, end)
} else if let Some((last, _)) = info.messages.last_key_value() {
(last, last)
} else {
return info.messages.range(..);
};
if range.inclusive {
info.messages.range(start..=end)
} else {
info.messages.range(start..end)
}
}
fn scrollview(
&mut self,
idx: MessageKey,
pos: MovePosition,
info: &RoomInfo,
settings: &ApplicationSettings,
) {
let selidx = if let Some(key) = self.cursor.to_key(info) {
key
} else {
return;
};
match pos {
MovePosition::Beginning => {
self.viewctx.corner = idx.into();
},
MovePosition::Middle => {
let mut lines = 0;
let target = self.viewctx.get_height() / 2;
for (key, item) in info.messages.range(..=&idx).rev() {
let sel = selidx == key;
let prev = prevmsg(key, info);
let len = item.show(prev, sel, &self.viewctx, info, settings).lines.len();
if key == &idx {
lines += len / 2;
} else {
lines += len;
}
if lines >= target {
// We've moved back far enough.
self.viewctx.corner.timestamp = key.clone().into();
self.viewctx.corner.text_row = lines - target;
break;
}
}
},
MovePosition::End => {
let mut lines = 0;
let target = self.viewctx.get_height();
for (key, item) in info.messages.range(..=&idx).rev() {
let sel = key == selidx;
let prev = prevmsg(key, info);
let len = item.show(prev, sel, &self.viewctx, info, settings).lines.len();
lines += len;
if lines >= target {
// We've moved back far enough.
self.viewctx.corner.timestamp = key.clone().into();
self.viewctx.corner.text_row = lines - target;
break;
}
}
},
}
}
fn shift_cursor(&mut self, info: &RoomInfo, settings: &ApplicationSettings) {
let last_key = if let Some(k) = info.messages.last_key_value() {
k.0
} else {
return;
};
let corner_key = self.viewctx.corner.timestamp.as_ref().unwrap_or(last_key);
if self.cursor < self.viewctx.corner {
// Cursor is above the viewport; move it inside.
self.cursor = corner_key.clone().into();
}
// Check whether the cursor is below the viewport.
let mut lines = 0;
let cursor_key = self.cursor.timestamp.as_ref().unwrap_or(last_key);
let mut prev = prevmsg(cursor_key, info);
for (idx, item) in info.messages.range(corner_key.clone()..) {
if idx == cursor_key {
// Cursor is already within the viewport.
break;
}
lines += item.show(prev, false, &self.viewctx, info, settings).height().max(1);
if lines >= self.viewctx.get_height() {
// We've reached the end of the viewport; move cursor into it.
self.cursor = idx.clone().into();
break;
}
prev = Some(item);
}
}
fn _range_to(&self, cursor: MessageCursor) -> EditRange<MessageCursor> {
EditRange::inclusive(self.cursor.clone(), cursor, TargetShape::LineWise)
}
fn movement(
&self,
pos: MessageKey,
movement: &MoveType,
count: &Count,
ctx: &ProgramContext,
info: &RoomInfo,
) -> Option<MessageCursor> {
let count = ctx.resolve(count);
match movement {
// These movements don't map meaningfully onto the scrollback history.
MoveType::BufferByteOffset => None,
MoveType::Column(_, _) => None,
MoveType::ItemMatch => None,
MoveType::LineColumnOffset => None,
MoveType::LinePercent => None,
MoveType::LinePos(_) => None,
MoveType::SentenceBegin(_) => None,
MoveType::ScreenFirstWord(_) => None,
MoveType::ScreenLinePos(_) => None,
MoveType::WordBegin(_, _) => None,
MoveType::WordEnd(_, _) => None,
MoveType::BufferLineOffset => None,
MoveType::BufferLinePercent => None,
MoveType::BufferPos(MovePosition::Beginning) => {
let start = info.messages.first_key_value()?.0.clone();
Some(start.into())
},
MoveType::BufferPos(MovePosition::Middle) => None,
MoveType::BufferPos(MovePosition::End) => Some(MessageCursor::latest()),
MoveType::FinalNonBlank(dir) |
MoveType::FirstWord(dir) |
MoveType::Line(dir) |
MoveType::ScreenLine(dir) |
MoveType::ParagraphBegin(dir) |
MoveType::SectionBegin(dir) |
MoveType::SectionEnd(dir) => {
match dir {
MoveDir1D::Previous => nth_before(pos, count, info).into(),
MoveDir1D::Next => nth_after(pos, count, info).into(),
}
},
MoveType::ViewportPos(MovePosition::Beginning) => {
return self.viewctx.corner.timestamp.as_ref().map(|k| k.clone().into());
},
MoveType::ViewportPos(MovePosition::Middle) => {
// XXX: Need to calculate an accurate middle position.
return None;
},
MoveType::ViewportPos(MovePosition::End) => {
// XXX: Need store to calculate an accurate end position.
return None;
},
_ => None,
}
}
fn range_of_movement(
&self,
pos: MessageKey,
movement: &MoveType,
count: &Count,
ctx: &ProgramContext,
info: &RoomInfo,
) -> Option<EditRange<MessageCursor>> {
let other = self.movement(pos.clone(), movement, count, ctx, info)?;
Some(EditRange::inclusive(pos.into(), other, TargetShape::LineWise))
}
fn range(
&self,
pos: MessageKey,
range: &RangeType,
_: bool,
count: &Count,
ctx: &ProgramContext,
info: &RoomInfo,
) -> Option<EditRange<MessageCursor>> {
match range {
RangeType::Bracketed(_, _) => None,
RangeType::Item => None,
RangeType::Quote(_) => None,
RangeType::Word(_) => None,
RangeType::XmlTag => None,
RangeType::Buffer => {
let start = info.messages.first_key_value()?.0.clone();
let end = info.messages.last_key_value()?.0.clone();
Some(EditRange::inclusive(start.into(), end.into(), TargetShape::LineWise))
},
RangeType::Line | RangeType::Paragraph | RangeType::Sentence => {
let count = ctx.resolve(count);
if count == 0 {
return None;
}
let mut end = &pos;
for (i, (key, _)) in info.messages.range(&pos..).enumerate() {
if i >= count {
break;
}
end = key;
}
let end = end.clone().into();
let start = pos.into();
Some(EditRange::inclusive(start, end, TargetShape::LineWise))
},
_ => None,
}
}
fn find_message_next(
&self,
start: MessageKey,
needle: &Regex,
mut count: usize,
info: &RoomInfo,
) -> Option<MessageCursor> {
let mut mc = None;
for (key, msg) in info.messages.range(&start..) {
if count == 0 {
break;
}
if key == &start {
continue;
}
if needle.is_match(msg.event.body().as_ref()) {
mc = MessageCursor::from(key.clone()).into();
count -= 1;
}
}
return mc;
}
fn find_message_prev(
&self,
end: MessageKey,
needle: &Regex,
mut count: usize,
info: &RoomInfo,
need_load: &mut HashSet<OwnedRoomId>,
) -> Option<MessageCursor> {
let mut mc = None;
for (key, msg) in info.messages.range(..&end).rev() {
if count == 0 {
break;
}
if needle.is_match(msg.event.body().as_ref()) {
mc = MessageCursor::from(key.clone()).into();
count -= 1;
}
}
if count > 0 {
need_load.insert(self.room_id.clone());
}
return mc;
}
fn find_message(
&self,
key: MessageKey,
dir: MoveDir1D,
needle: &Regex,
count: usize,
info: &RoomInfo,
need_load: &mut HashSet<OwnedRoomId>,
) -> Option<MessageCursor> {
match dir {
MoveDir1D::Next => self.find_message_next(key, needle, count, info),
MoveDir1D::Previous => self.find_message_prev(key, needle, count, info, need_load),
}
}
}
impl WindowOps<IambInfo> for ScrollbackState {
fn draw(&mut self, area: Rect, buf: &mut Buffer, focused: bool, store: &mut ProgramStore) {
Scrollback::new(store).focus(focused).render(area, buf, self)
}
fn dup(&self, _: &mut ProgramStore) -> Self {
ScrollbackState {
room_id: self.room_id.clone(),
id: self.id.clone(),
cursor: self.cursor.clone(),
viewctx: self.viewctx.clone(),
jumped: self.jumped.clone(),
show_full_on_redraw: false,
}
}
fn close(&mut self, _: CloseFlags, _: &mut ProgramStore) -> bool {
// XXX: what's the right closing behaviour for a room?
// Should write send a message?
true
}
fn write(
&mut self,
_: Option<&str>,
flags: WriteFlags,
_: &mut ProgramStore,
) -> IambResult<EditInfo> {
if flags.contains(WriteFlags::FORCE) {
Ok(None)
} else {
Err(EditError::ReadOnly.into())
}
}
fn get_completions(&self) -> Option<CompletionList> {
None
}
fn get_cursor_word(&self, _: &WordStyle) -> Option<String> {
None
}
fn get_selected_word(&self) -> Option<String> {
None
}
}
impl EditorActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
fn edit(
&mut self,
operation: &EditAction,
motion: &EditTarget,
ctx: &ProgramContext,
store: &mut ProgramStore,
) -> EditResult<EditInfo, IambInfo> {
let info = store.application.rooms.get_or_default(self.room_id.clone());
let key = if let Some(k) = self.cursor.to_key(info) {
k.clone()
} else {
let msg = "No messages to select.";
let err = EditError::Failure(msg.to_string());
return Err(err);
};
match operation {
EditAction::Motion => {
if motion.is_jumping() {
self.jumped.push(self.cursor.clone());
}
let pos = match motion {
EditTarget::CurrentPosition | EditTarget::Selection => {
return Ok(None);
},
EditTarget::Boundary(rt, inc, term, count) => {
self.range(key, rt, *inc, count, ctx, info).map(|r| {
match term {
MoveTerminus::Beginning => r.start,
MoveTerminus::End => r.end,
}
})
},
EditTarget::CharJump(mark) | EditTarget::LineJump(mark) => {
let mark = ctx.resolve(mark);
let cursor = store.cursors.get_mark(self.id.clone(), mark)?;
if let mc @ Some(_) = MessageCursor::from_cursor(&cursor, info) {
mc
} else {
let msg = "Failed to restore mark";
let err = EditError::Failure(msg.into());
return Err(err);
}
},
EditTarget::Motion(mt, count) => self.movement(key, mt, count, ctx, info),
EditTarget::Range(_, _, _) => {
return Err(EditError::Failure("Cannot use ranges in a list".to_string()));
},
EditTarget::Search(SearchType::Char(_), _, _) => {
let msg = "Cannot perform character search in a list";
let err = EditError::Failure(msg.into());
return Err(err);
},
EditTarget::Search(SearchType::Regex, flip, count) => {
let count = ctx.resolve(count);
let dir = ctx.get_search_regex_dir();
let dir = flip.resolve(&dir);
let needle = match ctx.get_search_regex() {
Some(re) => re,
None => {
let lsearch = store.registers.get(&Register::LastSearch)?;
let lsearch = lsearch.value.to_string();
Regex::new(lsearch.as_ref())?
},
};
self.find_message(
key,
dir,
&needle,
count,
info,
&mut store.application.need_load,
)
},
EditTarget::Search(SearchType::Word(_, _), _, _) => {
let msg = "Cannot perform word search in a list";
let err = EditError::Failure(msg.into());
return Err(err);
},
_ => {
let msg = format!("Unknown editing target: {motion:?}");
let err = EditError::Unimplemented(msg);
return Err(err);
},
};
if let Some(pos) = pos {
self.cursor = pos;
}
self.show_full_on_redraw = true;
return Ok(None);
},
EditAction::Yank => {
let range = match motion {
EditTarget::CurrentPosition | EditTarget::Selection => {
Some(self._range_to(key.into()))
},
EditTarget::Boundary(rt, inc, term, count) => {
self.range(key, rt, *inc, count, ctx, info).map(|r| {
self._range_to(match term {
MoveTerminus::Beginning => r.start,
MoveTerminus::End => r.end,
})
})
},
EditTarget::CharJump(mark) | EditTarget::LineJump(mark) => {
let mark = ctx.resolve(mark);
let cursor = store.cursors.get_mark(self.id.clone(), mark)?;
if let Some(c) = MessageCursor::from_cursor(&cursor, info) {
self._range_to(c).into()
} else {
let msg = "Failed to restore mark";
let err = EditError::Failure(msg.into());
return Err(err);
}
},
EditTarget::Motion(mt, count) => {
self.range_of_movement(key, mt, count, ctx, info)
},
EditTarget::Range(rt, inc, count) => {
self.range(key, rt, *inc, count, ctx, info)
},
EditTarget::Search(SearchType::Char(_), _, _) => {
let msg = "Cannot perform character search in a list";
let err = EditError::Failure(msg.into());
return Err(err);
},
EditTarget::Search(SearchType::Regex, flip, count) => {
let count = ctx.resolve(count);
let dir = ctx.get_search_regex_dir();
let dir = flip.resolve(&dir);
let needle = match ctx.get_search_regex() {
Some(re) => re,
None => {
let lsearch = store.registers.get(&Register::LastSearch)?;
let lsearch = lsearch.value.to_string();
Regex::new(lsearch.as_ref())?
},
};
self.find_message(
key,
dir,
&needle,
count,
info,
&mut store.application.need_load,
)
.map(|c| self._range_to(c))
},
EditTarget::Search(SearchType::Word(_, _), _, _) => {
let msg = "Cannot perform word search in a list";
let err = EditError::Failure(msg.into());
return Err(err);
},
_ => {
let msg = format!("Unknown motion: {motion:?}");
let err = EditError::Unimplemented(msg);
return Err(err);
},
};
if let Some(range) = range {
let mut yanked = EditRope::from("");
for (_, msg) in self.messages(range, info) {
yanked += EditRope::from(msg.event.body());
yanked += EditRope::from('\n');
}
let cell = RegisterCell::new(TargetShape::LineWise, yanked);
let register = ctx.get_register().unwrap_or(Register::Unnamed);
let mut flags = RegisterPutFlags::NONE;
if ctx.get_register_append() {
flags |= RegisterPutFlags::APPEND;
}
store.registers.put(®ister, cell, flags)?;
}
return Ok(None);
},
// Everything else is a modifying action.
EditAction::ChangeCase(_) => Err(EditError::ReadOnly),
EditAction::ChangeNumber(_, _) => Err(EditError::ReadOnly),
EditAction::Delete => Err(EditError::ReadOnly),
EditAction::Format => Err(EditError::ReadOnly),
EditAction::Indent(_) => Err(EditError::ReadOnly),
EditAction::Join(_) => Err(EditError::ReadOnly),
EditAction::Replace(_) => Err(EditError::ReadOnly),
}
}
fn mark(
&mut self,
name: Mark,
_: &ProgramContext,
store: &mut ProgramStore,
) -> EditResult<EditInfo, IambInfo> {
let info = store.application.get_room_info(self.room_id.clone());
if let Some(cursor) = self.cursor.to_cursor(info) {
store.cursors.set_mark(self.id.clone(), name, cursor);
Ok(None)
} else {
let msg = "Failed to set mark for message";
let err = EditError::Failure(msg.into());
Err(err)
}
}
fn complete(
&mut self,
_: &CompletionType,
_: &CompletionSelection,
_: &CompletionDisplay,
_: &ProgramContext,
_: &mut ProgramStore,
) -> EditResult<EditInfo, IambInfo> {
Err(EditError::ReadOnly)
}
fn insert_text(
&mut self,
_: &InsertTextAction,
_: &ProgramContext,
_: &mut ProgramStore,
) -> EditResult<EditInfo, IambInfo> {
Err(EditError::ReadOnly)
}
fn selection_command(
&mut self,
_: &SelectionAction,
_: &ProgramContext,
_: &mut ProgramStore,
) -> EditResult<EditInfo, IambInfo> {
Err(EditError::Failure("Cannot perform selection actions in a list".into()))
}
fn history_command(
&mut self,
act: &HistoryAction,
_: &ProgramContext,
_: &mut ProgramStore,
) -> EditResult<EditInfo, IambInfo> {
match act {
HistoryAction::Checkpoint => Ok(None),
HistoryAction::Undo(_) => Err(EditError::Failure("Nothing to undo".into())),
HistoryAction::Redo(_) => Err(EditError::Failure("Nothing to redo".into())),
_ => Err(EditError::Unimplemented(format!("Unknown action: {act:?}"))),
}
}
fn cursor_command(
&mut self,
act: &CursorAction,
ctx: &ProgramContext,
store: &mut ProgramStore,
) -> EditResult<EditInfo, IambInfo> {
let info = store.application.get_room_info(self.room_id.clone());
match act {
CursorAction::Close(_) => Ok(None),
CursorAction::Rotate(_, _) => Ok(None),
CursorAction::Split(_) => Ok(None),
CursorAction::Restore(_) => {
let reg = ctx.get_register().unwrap_or(Register::UnnamedCursorGroup);
// Get saved group.
let ngroup = store.cursors.get_group(self.id.clone(), ®)?;
// Lists don't have groups; override current position.
if self.jumped.current() != &self.cursor {
self.jumped.push(self.cursor.clone());
}
if let Some(mc) = MessageCursor::from_cursor(ngroup.leader.cursor(), info) {
self.cursor = mc;
Ok(None)
} else {
let msg = "Cannot restore position in message history";
let err = EditError::Failure(msg.into());
Err(err)
}
},
CursorAction::Save(_) => {
let reg = ctx.get_register().unwrap_or(Register::UnnamedCursorGroup);
// Lists don't have groups; override any previously saved group.
let cursor = self.cursor.to_cursor(info).ok_or_else(|| {
let msg = "Cannot save position in message history";
EditError::Failure(msg.into())
})?;
let group = CursorGroup {
leader: CursorState::Location(cursor),
members: vec![],
};
store.cursors.set_group(self.id.clone(), reg, group)?;
Ok(None)
},
_ => Err(EditError::Unimplemented(format!("Unknown action: {act:?}"))),
}
}
}
impl Editable<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
fn editor_command(
&mut self,
act: &EditorAction,
ctx: &ProgramContext,
store: &mut ProgramStore,
) -> EditResult<EditInfo, IambInfo> {
match act {
EditorAction::Cursor(act) => self.cursor_command(act, ctx, store),
EditorAction::Edit(ea, et) => self.edit(&ctx.resolve(ea), et, ctx, store),
EditorAction::History(act) => self.history_command(act, ctx, store),
EditorAction::InsertText(act) => self.insert_text(act, ctx, store),
EditorAction::Mark(name) => self.mark(ctx.resolve(name), ctx, store),
EditorAction::Selection(act) => self.selection_command(act, ctx, store),
EditorAction::Complete(_, _, _) => {
let msg = "Nothing to complete in message scrollback";
let err = EditError::Failure(msg.into());
Err(err)
},
_ => Err(EditError::Unimplemented(format!("Unknown action: {act:?}"))),
}
}
}
impl Jumpable<ProgramContext, IambInfo> for ScrollbackState {
fn jump(
&mut self,
list: PositionList,
dir: MoveDir1D,
count: usize,
_: &ProgramContext,
) -> UIResult<usize, IambInfo> {
match list {
PositionList::ChangeList => {
let msg = "No changes to jump to within the list";
let err = UIError::Failure(msg.into());
return Err(err);
},
PositionList::JumpList => {
let (len, pos) = match dir {
MoveDir1D::Previous => {
if self.jumped.future_len() == 0 && *self.jumped.current() != self.cursor {
// Push current position if this is the first jump backwards.
self.jumped.push(self.cursor.clone());
}
let plen = self.jumped.past_len();
let pos = self.jumped.prev(count);
(plen, pos)
},
MoveDir1D::Next => {
let flen = self.jumped.future_len();
let pos = self.jumped.next(count);
(flen, pos)
},
};
if len > 0 {
self.cursor = pos.clone();
}
return Ok(count.saturating_sub(len));
},
}
}
}
impl Promptable<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
fn prompt(
&mut self,
act: &PromptAction,
_: &ProgramContext,
store: &mut ProgramStore,
) -> EditResult<Vec<(Action<IambInfo>, ProgramContext)>, IambInfo> {
let info = store.application.get_room_info(self.room_id.clone());
let _ = if let Some(key) = self.cursor.to_key(info) {
key
} else {
let msg = "No message currently selected";
let err = EditError::Failure(msg.into());
return Err(err);
};
match act {
PromptAction::Submit => {
// XXX: I'm not sure exactly what to do here yet. I think I want this to display a
// pop-over ListState with actions that can then be submitted:
//
// - Create a reply
// - Edit a message
// - Redact a message
// - React to a message
// - Report a message
// - Download an attachment
//
// Each of these should correspond to a command that a user can run. For example,
// running `:reply` when hovering over a message should be equivalent to opening
// the pop-up and selecting "Reply To This Message".
return Ok(vec![]);
},
PromptAction::Abort(..) => {
let msg = "Cannot abort a message.";
let err = EditError::Failure(msg.into());
return Err(err);
},
PromptAction::Recall(..) => {
let msg = "Cannot recall previous messages.";
let err = EditError::Failure(msg.into());
return Err(err);
},
_ => {
let msg = format!("Messages scrollback doesn't support {act:?}");
let err = EditError::Unimplemented(msg);
return Err(err);
},
}
}
}
impl ScrollActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
fn dirscroll(
&mut self,
dir: MoveDir2D,
size: ScrollSize,
count: &Count,
ctx: &ProgramContext,
store: &mut ProgramStore,
) -> EditResult<EditInfo, IambInfo> {
let info = store.application.rooms.get_or_default(self.room_id.clone());
let settings = &store.application.settings;
let mut corner = self.viewctx.corner.clone();
let last_key = if let Some(k) = info.messages.last_key_value() {
k.0
} else {
return Ok(None);
};
let corner_key = corner.timestamp.as_ref().unwrap_or(last_key).clone();
let cursor_key = self.cursor.timestamp.as_ref().unwrap_or(last_key);
let count = ctx.resolve(count);
let height = self.viewctx.get_height();
let mut rows = match size {
ScrollSize::Cell => count,
ScrollSize::HalfPage => count.saturating_mul(height) / 2,
ScrollSize::Page => count.saturating_mul(height),
};
match dir {
MoveDir2D::Up => {
let first_key = info.messages.first_key_value().map(|f| f.0.clone());
for (key, item) in info.messages.range(..=&corner_key).rev() {
let sel = key == cursor_key;
let prev = prevmsg(key, info);
let txt = item.show(prev, sel, &self.viewctx, info, settings);
let len = txt.height().max(1);
let max = len.saturating_sub(1);
if key != &corner_key {
corner.text_row = max;
}
corner.timestamp = key.clone().into();
if rows == 0 {
break;
} else if corner.text_row >= rows {
corner.text_row -= rows;
break;
} else if corner.timestamp == first_key {
corner.text_row = 0;
break;
}
rows -= corner.text_row + 1;
}
},
MoveDir2D::Down => {
let mut prev = prevmsg(&corner_key, info);
for (key, item) in info.messages.range(&corner_key..) {
let sel = key == cursor_key;
let txt = item.show(prev, sel, &self.viewctx, info, settings);
let len = txt.height().max(1);
let max = len.saturating_sub(1);
prev = Some(item);
if key != &corner_key {
corner.text_row = 0;
}
corner.timestamp = key.clone().into();
if rows == 0 {
break;
} else if key == last_key {
corner.text_row = corner.text_row.saturating_add(rows).min(max);
break;
} else if corner.text_row >= max {
rows -= 1;
continue;
} else if corner.text_row + rows <= max {
corner.text_row += rows;
break;
} else {
rows -= len - corner.text_row;
continue;
}
}
},
MoveDir2D::Left | MoveDir2D::Right => {
let msg = "Cannot scroll vertically in message scrollback";
let err = EditError::Failure(msg.into());
return Err(err);
},
}
self.viewctx.corner = corner;
self.shift_cursor(info, settings);
Ok(None)
}
fn cursorpos(
&mut self,
pos: MovePosition,
axis: Axis,
_: &ProgramContext,
store: &mut ProgramStore,
) -> EditResult<EditInfo, IambInfo> {
match axis {
Axis::Horizontal => {
let msg = "Cannot scroll vertically in message scrollback";
let err = EditError::Failure(msg.into());
Err(err)
},
Axis::Vertical => {
let info = store.application.rooms.get_or_default(self.room_id.clone());
let settings = &store.application.settings;
if let Some(key) = self.cursor.to_key(info).cloned() {
self.scrollview(key, pos, info, settings);
}
Ok(None)
},
}
}
fn linepos(
&mut self,
_: MovePosition,
_: &Count,
_: &ProgramContext,
_: &mut ProgramStore,
) -> EditResult<EditInfo, IambInfo> {
let msg = "Cannot scroll in message scrollback using line numbers";
let err = EditError::Failure(msg.into());
Err(err)
}
}
impl Scrollable<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
fn scroll(
&mut self,
style: &ScrollStyle,
ctx: &ProgramContext,
store: &mut ProgramStore,
) -> EditResult<EditInfo, IambInfo> {
match style {
ScrollStyle::Direction2D(dir, size, count) => {
return self.dirscroll(*dir, *size, count, ctx, store);
},
ScrollStyle::CursorPos(pos, axis) => {
return self.cursorpos(*pos, *axis, ctx, store);
},
ScrollStyle::LinePos(pos, count) => {
return self.linepos(*pos, count, ctx, store);
},
}
}
}
impl Searchable<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
fn search(
&mut self,
dir: MoveDirMod,
count: Count,
ctx: &ProgramContext,
store: &mut ProgramStore,
) -> UIResult<EditInfo, IambInfo> {
let search = EditTarget::Search(SearchType::Regex, dir, count);
Ok(self.edit(&EditAction::Motion, &search, ctx, store)?)
}
}
impl TerminalCursor for ScrollbackState {
fn get_term_cursor(&self) -> Option<(u16, u16)> {
None
}
}
fn render_jump_to_recent(area: Rect, buf: &mut Buffer, focused: bool) -> Rect {
if area.height <= 5 || area.width <= 20 {
return area;
}
let top = Rect::new(area.x, area.y, area.width, area.height - 1);
let bar = Rect::new(area.x, area.y + top.height, area.width, 1);
let msg = vec![
Span::raw("Use "),
Span::styled("G", Style::default().add_modifier(StyleModifier::BOLD)),
Span::raw(if focused { "" } else { " in scrollback" }),
Span::raw(" to jump to latest message"),
];
Paragraph::new(Spans::from(msg))
.alignment(Alignment::Center)
.render(bar, buf);
return top;
}
pub struct Scrollback<'a> {
room_focused: bool,
focused: bool,
store: &'a mut ProgramStore,
}
impl<'a> Scrollback<'a> {
pub fn new(store: &'a mut ProgramStore) -> Self {
Scrollback { room_focused: false, focused: false, store }
}
/// Indicate whether the room window is currently focused, regardless of whether the scrollback
/// also is.
pub fn room_focus(mut self, focused: bool) -> Self {
self.room_focused = focused;
self
}
/// Indicate whether the scrollback is currently focused.
pub fn focus(mut self, focused: bool) -> Self {
self.focused = focused;
self
}
}
impl<'a> StatefulWidget for Scrollback<'a> {
type State = ScrollbackState;
fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
let info = self.store.application.rooms.get_or_default(state.room_id.clone());
let settings = &self.store.application.settings;
let area = if state.cursor.timestamp.is_some() {
render_jump_to_recent(area, buf, self.focused)
} else {
info.render_typing(area, buf, &self.store.application.settings)
};
state.set_term_info(area);
let height = state.viewctx.get_height();
if height == 0 {
return;
}
if state.cursor.timestamp < state.viewctx.corner.timestamp {
state.viewctx.corner = state.cursor.clone();
}
let cursor = &state.cursor;
let cursor_key = if let Some(k) = cursor.to_key(info) {
k
} else {
self.store.application.mark_for_load(state.room_id.clone());
return;
};
let corner = &state.viewctx.corner;
let corner_key = if let Some(k) = &corner.timestamp {
k.clone()
} else {
nth_key_before(cursor_key.clone(), height, info)
};
let foc = self.focused || cursor.timestamp.is_some();
let full = std::mem::take(&mut state.show_full_on_redraw) || cursor.timestamp.is_none();
let mut lines = vec![];
let mut sawit = false;
let mut prev = prevmsg(&corner_key, info);
for (key, item) in info.messages.range(&corner_key..) {
let sel = key == cursor_key;
let txt = item.show(prev, foc && sel, &state.viewctx, info, settings);
prev = Some(item);
let incomplete_ok = !full || !sel;
for (row, line) in txt.lines.into_iter().enumerate() {
if sawit && lines.len() >= height && incomplete_ok {
// Check whether we've seen the first line of the
// selected message and can fill the screen.
break;
}
if key == &corner_key && row < corner.text_row {
// Skip rows above the viewport corner.
continue;
}
lines.push((key, row, line));
sawit |= sel;
}
}
if lines.len() > height {
let n = lines.len() - height;
let _ = lines.drain(..n);
}
if let Some(((ts, event_id), row, _)) = lines.first() {
state.viewctx.corner.timestamp = Some((*ts, event_id.clone()));
state.viewctx.corner.text_row = *row;
}
let mut y = area.top();
let x = area.left();
for (_, _, txt) in lines.into_iter() {
let _ = buf.set_spans(x, y, &txt, area.width);
y += 1;
}
if self.room_focused &&
settings.tunables.read_receipt_send &&
state.cursor.timestamp.is_none()
{
// If the cursor is at the last message, then update the read marker.
info.read_till = info.messages.last_key_value().map(|(k, _)| k.1.clone());
}
// Check whether we should load older messages for this room.
let first_key = info.messages.first_key_value().map(|(k, _)| k.clone());
if first_key == state.viewctx.corner.timestamp {
// If the top of the screen is the older message, load more.
self.store.application.mark_for_load(state.room_id.clone());
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tests::*;
#[tokio::test]
async fn test_search_messages() {
let room_id = TEST_ROOM1_ID.clone();
let mut store = mock_store().await;
let mut scrollback = ScrollbackState::new(room_id.clone());
let ctx = ProgramContext::default();
let next = MoveDirMod::Exact(MoveDir1D::Next);
let prev = MoveDirMod::Exact(MoveDir1D::Previous);
// Search through the messages:
//
// MSG2: "helium"
// MSG3: "this\nis\na\nmultiline\nmessage"
// MSG4: "help"
// MSG5: "character"
// MSG1: "writhe"
store.set_last_search("he");
assert_eq!(scrollback.cursor, MessageCursor::latest());
// Search backwards to MSG4.
scrollback.search(prev.clone(), 1.into(), &ctx, &mut store).unwrap();
assert_eq!(scrollback.cursor, MSG4_KEY.clone().into());
// Search backwards to MSG2.
scrollback.search(prev.clone(), 1.into(), &ctx, &mut store).unwrap();
assert_eq!(scrollback.cursor, MSG2_KEY.clone().into());
assert_eq!(store.application.need_load.contains(&room_id), false);
// Can't go any further; need_load now contains the room ID.
scrollback.search(prev.clone(), 1.into(), &ctx, &mut store).unwrap();
assert_eq!(scrollback.cursor, MSG2_KEY.clone().into());
assert_eq!(store.application.need_load.contains(&room_id), true);
// Search forward twice to MSG1.
scrollback.search(next.clone(), 2.into(), &ctx, &mut store).unwrap();
assert_eq!(scrollback.cursor, MSG1_KEY.clone().into());
// Can't go any further.
scrollback.search(next.clone(), 2.into(), &ctx, &mut store).unwrap();
assert_eq!(scrollback.cursor, MSG1_KEY.clone().into());
}
#[tokio::test]
async fn test_movement() {
let mut store = mock_store().await;
let mut scrollback = ScrollbackState::new(TEST_ROOM1_ID.clone());
let ctx = ProgramContext::default();
let prev = |n: usize| EditTarget::Motion(MoveType::Line(MoveDir1D::Previous), n.into());
let next = |n: usize| EditTarget::Motion(MoveType::Line(MoveDir1D::Next), n.into());
assert_eq!(scrollback.cursor, MessageCursor::latest());
scrollback.edit(&EditAction::Motion, &prev(1), &ctx, &mut store).unwrap();
assert_eq!(scrollback.cursor, MSG5_KEY.clone().into());
scrollback.edit(&EditAction::Motion, &prev(2), &ctx, &mut store).unwrap();
assert_eq!(scrollback.cursor, MSG3_KEY.clone().into());
scrollback.edit(&EditAction::Motion, &prev(5), &ctx, &mut store).unwrap();
assert_eq!(scrollback.cursor, MSG2_KEY.clone().into());
scrollback.edit(&EditAction::Motion, &next(1), &ctx, &mut store).unwrap();
assert_eq!(scrollback.cursor, MSG3_KEY.clone().into());
scrollback.edit(&EditAction::Motion, &next(1), &ctx, &mut store).unwrap();
assert_eq!(scrollback.cursor, MSG4_KEY.clone().into());
scrollback.edit(&EditAction::Motion, &next(1), &ctx, &mut store).unwrap();
assert_eq!(scrollback.cursor, MSG5_KEY.clone().into());
scrollback.edit(&EditAction::Motion, &next(1), &ctx, &mut store).unwrap();
assert_eq!(scrollback.cursor, MSG1_KEY.clone().into());
}
#[tokio::test]
async fn test_dirscroll() {
let mut store = mock_store().await;
let mut scrollback = ScrollbackState::new(TEST_ROOM1_ID.clone());
let ctx = ProgramContext::default();
let prev = MoveDir2D::Up;
let next = MoveDir2D::Down;
// Skip rendering typing notices.
store.application.settings.tunables.typing_notice_display = false;
assert_eq!(scrollback.cursor, MessageCursor::latest());
assert_eq!(scrollback.viewctx.dimensions, (0, 0));
assert_eq!(scrollback.viewctx.corner, MessageCursor::latest());
// Set a terminal width of 60, and height of 4, rendering in scrollback as:
//
// |------------------------------------------------------------|
// MSG2: | Wednesday, December 31 1969 |
// | @user2:example.com helium |
// MSG3: | @user2:example.com this |
// | is |
// | a |
// | multiline |
// | message |
// MSG4: | @user1:example.com help |
// MSG5: | @user2:example.com character |
// MSG1: | XXXday, Month NN 20XX |
// | @user1:example.com writhe |
// |------------------------------------------------------------|
let area = Rect::new(0, 0, 60, 4);
let mut buffer = Buffer::empty(area);
scrollback.draw(area, &mut buffer, true, &mut store);
assert_eq!(scrollback.cursor, MessageCursor::latest());
assert_eq!(scrollback.viewctx.dimensions, (60, 4));
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG4_KEY.clone(), 0));
// Scroll up a line at a time until we hit the first message.
scrollback
.dirscroll(prev, ScrollSize::Cell, &1.into(), &ctx, &mut store)
.unwrap();
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG3_KEY.clone(), 4));
scrollback
.dirscroll(prev, ScrollSize::Cell, &1.into(), &ctx, &mut store)
.unwrap();
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG3_KEY.clone(), 3));
scrollback
.dirscroll(prev, ScrollSize::Cell, &1.into(), &ctx, &mut store)
.unwrap();
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG3_KEY.clone(), 2));
scrollback
.dirscroll(prev, ScrollSize::Cell, &1.into(), &ctx, &mut store)
.unwrap();
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG3_KEY.clone(), 1));
scrollback
.dirscroll(prev, ScrollSize::Cell, &1.into(), &ctx, &mut store)
.unwrap();
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG3_KEY.clone(), 0));
scrollback
.dirscroll(prev, ScrollSize::Cell, &1.into(), &ctx, &mut store)
.unwrap();
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG2_KEY.clone(), 1));
scrollback
.dirscroll(prev, ScrollSize::Cell, &1.into(), &ctx, &mut store)
.unwrap();
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG2_KEY.clone(), 0));
// Cannot scroll any further.
scrollback
.dirscroll(prev, ScrollSize::Cell, &1.into(), &ctx, &mut store)
.unwrap();
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG2_KEY.clone(), 0));
// Now scroll back down one line at a time.
scrollback
.dirscroll(next, ScrollSize::Cell, &1.into(), &ctx, &mut store)
.unwrap();
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG2_KEY.clone(), 1));
scrollback
.dirscroll(next, ScrollSize::Cell, &1.into(), &ctx, &mut store)
.unwrap();
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG3_KEY.clone(), 0));
scrollback
.dirscroll(next, ScrollSize::Cell, &1.into(), &ctx, &mut store)
.unwrap();
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG3_KEY.clone(), 1));
scrollback
.dirscroll(next, ScrollSize::Cell, &1.into(), &ctx, &mut store)
.unwrap();
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG3_KEY.clone(), 2));
scrollback
.dirscroll(next, ScrollSize::Cell, &1.into(), &ctx, &mut store)
.unwrap();
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG3_KEY.clone(), 3));
scrollback
.dirscroll(next, ScrollSize::Cell, &1.into(), &ctx, &mut store)
.unwrap();
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG3_KEY.clone(), 4));
scrollback
.dirscroll(next, ScrollSize::Cell, &1.into(), &ctx, &mut store)
.unwrap();
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG4_KEY.clone(), 0));
scrollback
.dirscroll(next, ScrollSize::Cell, &1.into(), &ctx, &mut store)
.unwrap();
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG5_KEY.clone(), 0));
scrollback
.dirscroll(next, ScrollSize::Cell, &1.into(), &ctx, &mut store)
.unwrap();
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG1_KEY.clone(), 0));
scrollback
.dirscroll(next, ScrollSize::Cell, &1.into(), &ctx, &mut store)
.unwrap();
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG1_KEY.clone(), 1));
// Cannot scroll down any further.
scrollback
.dirscroll(next, ScrollSize::Cell, &1.into(), &ctx, &mut store)
.unwrap();
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG1_KEY.clone(), 1));
// Scroll up two Pages (eight lines).
scrollback
.dirscroll(prev, ScrollSize::Page, &2.into(), &ctx, &mut store)
.unwrap();
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG3_KEY.clone(), 0));
// Scroll down two HalfPages (four lines).
scrollback
.dirscroll(next, ScrollSize::HalfPage, &2.into(), &ctx, &mut store)
.unwrap();
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG3_KEY.clone(), 4));
}
#[tokio::test]
async fn test_cursorpos() {
let mut store = mock_store().await;
let mut scrollback = ScrollbackState::new(TEST_ROOM1_ID.clone());
let ctx = ProgramContext::default();
// Skip rendering typing notices.
store.application.settings.tunables.typing_notice_display = false;
// Set a terminal width of 60, and height of 3, rendering in scrollback as:
//
// |------------------------------------------------------------|
// MSG2: | Wednesday, December 31 1969 |
// | @user2:example.com helium |
// MSG3: | @user2:example.com this |
// | is |
// | a |
// | multiline |
// | message |
// MSG4: | @user1:example.com help |
// MSG5: | @user2:example.com character |
// MSG1: | XXXday, Month NN 20XX |
// | @user1:example.com writhe |
// |------------------------------------------------------------|
let area = Rect::new(0, 0, 60, 3);
let mut buffer = Buffer::empty(area);
scrollback.cursor = MSG4_KEY.clone().into();
scrollback.draw(area, &mut buffer, true, &mut store);
assert_eq!(scrollback.cursor, MSG4_KEY.clone().into());
assert_eq!(scrollback.viewctx.dimensions, (60, 3));
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG3_KEY.clone(), 3));
// Scroll so that the cursor is at the top of the screen.
scrollback
.cursorpos(MovePosition::Beginning, Axis::Vertical, &ctx, &mut store)
.unwrap();
assert_eq!(scrollback.cursor, MSG4_KEY.clone().into());
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG4_KEY.clone(), 0));
// Scroll so that the cursor is at the bottom of the screen.
scrollback
.cursorpos(MovePosition::End, Axis::Vertical, &ctx, &mut store)
.unwrap();
assert_eq!(scrollback.cursor, MSG4_KEY.clone().into());
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG3_KEY.clone(), 3));
// Scroll so that the cursor is in the middle of the screen.
scrollback
.cursorpos(MovePosition::Middle, Axis::Vertical, &ctx, &mut store)
.unwrap();
assert_eq!(scrollback.cursor, MSG4_KEY.clone().into());
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG3_KEY.clone(), 4));
}
}
07070100000025000081A400000000000000000000000164A9007B00001076000000000000000000000000000000000000002500000000iamb-0.0.8/src/windows/room/space.rsuse std::ops::{Deref, DerefMut};
use std::time::{Duration, Instant};
use matrix_sdk::{
room::Room as MatrixRoom,
ruma::{OwnedRoomId, RoomId},
};
use modalkit::tui::{
buffer::Buffer,
layout::Rect,
style::{Color, Style},
text::{Span, Spans, Text},
widgets::StatefulWidget,
};
use modalkit::{
widgets::list::{List, ListState},
widgets::{TermOffset, TerminalCursor, WindowOps},
};
use crate::base::{IambBufferId, IambInfo, ProgramStore, RoomFocus};
use crate::windows::RoomItem;
const SPACE_HIERARCHY_DEBOUNCE: Duration = Duration::from_secs(5);
pub struct SpaceState {
room_id: OwnedRoomId,
room: MatrixRoom,
list: ListState<RoomItem, IambInfo>,
last_fetch: Option<Instant>,
}
impl SpaceState {
pub fn new(room: MatrixRoom) -> Self {
let room_id = room.room_id().to_owned();
let content = IambBufferId::Room(room_id.clone(), RoomFocus::Scrollback);
let list = ListState::new(content, vec![]);
let last_fetch = None;
SpaceState { room_id, room, list, last_fetch }
}
pub fn refresh_room(&mut self, store: &mut ProgramStore) {
if let Some(room) = store.application.worker.client.get_room(self.id()) {
self.room = room;
}
}
pub fn room(&self) -> &MatrixRoom {
&self.room
}
pub fn id(&self) -> &RoomId {
&self.room_id
}
pub fn dup(&self, store: &mut ProgramStore) -> Self {
SpaceState {
room_id: self.room_id.clone(),
room: self.room.clone(),
list: self.list.dup(store),
last_fetch: self.last_fetch,
}
}
}
impl TerminalCursor for SpaceState {
fn get_term_cursor(&self) -> Option<TermOffset> {
self.list.get_term_cursor()
}
}
impl Deref for SpaceState {
type Target = ListState<RoomItem, IambInfo>;
fn deref(&self) -> &Self::Target {
&self.list
}
}
impl DerefMut for SpaceState {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.list
}
}
pub struct Space<'a> {
focused: bool,
store: &'a mut ProgramStore,
}
impl<'a> Space<'a> {
pub fn new(store: &'a mut ProgramStore) -> Self {
Space { focused: false, store }
}
pub fn focus(mut self, focused: bool) -> Self {
self.focused = focused;
self
}
}
impl<'a> StatefulWidget for Space<'a> {
type State = SpaceState;
fn render(self, area: Rect, buffer: &mut Buffer, state: &mut Self::State) {
let mut empty_message = None;
let need_fetch = match state.last_fetch {
Some(i) => i.elapsed() >= SPACE_HIERARCHY_DEBOUNCE,
None => true,
};
if need_fetch {
let res = self.store.application.worker.space_members(state.room_id.clone());
match res {
Ok(members) => {
let items = members
.into_iter()
.filter_map(|id| {
let (room, _, tags) =
self.store.application.worker.get_room(id.clone()).ok()?;
let room_info = std::sync::Arc::new((room, tags));
if id != state.room_id {
Some(RoomItem::new(room_info, self.store))
} else {
None
}
})
.collect();
state.list.set(items);
state.last_fetch = Some(Instant::now());
},
Err(e) => {
let lines = vec![
Spans::from("Unable to fetch space room hierarchy:"),
Span::styled(e.to_string(), Style::default().fg(Color::Red)).into(),
];
empty_message = Text { lines }.into();
},
}
}
let mut list = List::new(self.store).focus(self.focused);
if let Some(text) = empty_message {
list = list.empty_message(text);
}
list.render(area, buffer, &mut state.list)
}
}
07070100000026000081A400000000000000000000000164A9007B000006E7000000000000000000000000000000000000002200000000iamb-0.0.8/src/windows/welcome.md# Welcome to iamb!
## Useful Keybindings
- `<Enter>` will send a typed message
- `^V^J` can be used in Insert mode to enter a newline without submitting
- `O`/`o` can be used to insert blank lines before and after the cursor line
- `^Wm` can be used to toggle whether the message bar or scrollback is selected
- `^Wz` can be used to toggle whether the current window takes up the full screen
## Room Commands
- `:dms` will open a list of direct messages
- `:rooms` will open a list of joined rooms
- `:members` will open a list of members for the currently focused room or space
- `:spaces` will open a list of joined spaces
- `:join` can be used to switch to join a new room or start a direct message
- `:split` and `:vsplit` can be used to open rooms in a new window
## Verification Commands
The `:verify` command has several different subcommands for working with
verification requests. When used without any arguments, it will take you to a
list of current verifications, where you can see and compare the Emoji.
The different subcommands are:
- `:verify request USERNAME` will send a verification request to a user
- `:verify confirm USERNAME/DEVICE` will confirm a verification
- `:verify mismatch USERNAME/DEVICE` will cancel a verification where the Emoji don't match
- `:verify cancel USERNAME/DEVICE` will cancel a verification
## Other Useful Commands
- `:welcome` will take you back to this screen
## Additional Configuration
You can customize iamb in your `$CONFIG_DIR/iamb/config.json` file, where
`$CONFIG_DIR` is your system's per-user configuration directory.
You can edit the following values in the file:
- `"default_profile"`, a profile name to use when starting iamb if one wasn't specified
- `"cache"`, a directory for cached iamb
07070100000027000081A400000000000000000000000164A9007B000008A4000000000000000000000000000000000000002200000000iamb-0.0.8/src/windows/welcome.rsuse std::ops::{Deref, DerefMut};
use modalkit::tui::{buffer::Buffer, layout::Rect};
use modalkit::{
widgets::textbox::TextBoxState,
widgets::WindowOps,
widgets::{TermOffset, TerminalCursor},
};
use modalkit::editing::action::EditInfo;
use modalkit::editing::base::{CloseFlags, WordStyle, WriteFlags};
use modalkit::editing::completion::CompletionList;
use crate::base::{IambBufferId, IambInfo, IambResult, ProgramStore};
const WELCOME_TEXT: &str = include_str!("welcome.md");
pub struct WelcomeState {
tbox: TextBoxState<IambInfo>,
}
impl WelcomeState {
pub fn new(store: &mut ProgramStore) -> Self {
let buf = store.buffers.load_str(IambBufferId::Welcome, WELCOME_TEXT);
let mut tbox = TextBoxState::new(buf);
tbox.set_readonly(true);
WelcomeState { tbox }
}
}
impl Deref for WelcomeState {
type Target = TextBoxState<IambInfo>;
fn deref(&self) -> &Self::Target {
return &self.tbox;
}
}
impl DerefMut for WelcomeState {
fn deref_mut(&mut self) -> &mut Self::Target {
return &mut self.tbox;
}
}
impl TerminalCursor for WelcomeState {
fn get_term_cursor(&self) -> Option<TermOffset> {
self.tbox.get_term_cursor()
}
}
impl WindowOps<IambInfo> for WelcomeState {
fn draw(&mut self, area: Rect, buf: &mut Buffer, focused: bool, store: &mut ProgramStore) {
self.tbox.draw(area, buf, focused, store)
}
fn dup(&self, store: &mut ProgramStore) -> Self {
let tbox = self.tbox.dup(store);
WelcomeState { tbox }
}
fn close(&mut self, flags: CloseFlags, store: &mut ProgramStore) -> bool {
self.tbox.close(flags, store)
}
fn write(
&mut self,
path: Option<&str>,
flags: WriteFlags,
store: &mut ProgramStore,
) -> IambResult<EditInfo> {
self.tbox.write(path, flags, store)
}
fn get_completions(&self) -> Option<CompletionList> {
self.tbox.get_completions()
}
fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
self.tbox.get_cursor_word(style)
}
fn get_selected_word(&self) -> Option<String> {
self.tbox.get_selected_word()
}
}
07070100000028000081A400000000000000000000000164A9007B00009E66000000000000000000000000000000000000001900000000iamb-0.0.8/src/worker.rsuse std::collections::HashMap;
use std::convert::TryFrom;
use std::fmt::{Debug, Formatter};
use std::fs::File;
use std::io::BufWriter;
use std::str::FromStr;
use std::sync::mpsc::{sync_channel, Receiver, SyncSender};
use std::sync::Arc;
use std::time::{Duration, Instant};
use futures::{stream::FuturesUnordered, StreamExt};
use gethostname::gethostname;
use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
use tokio::task::JoinHandle;
use tracing::{error, warn};
use matrix_sdk::{
config::{RequestConfig, SyncSettings},
encryption::verification::{SasVerification, Verification},
event_handler::Ctx,
reqwest,
room::{Invited, Messages, MessagesOptions, Room as MatrixRoom, RoomMember},
ruma::{
api::client::{
room::create_room::v3::{CreationContent, Request as CreateRoomRequest, RoomPreset},
room::Visibility,
space::get_hierarchy::v1::Request as SpaceHierarchyRequest,
},
assign,
events::{
key::verification::{
done::{OriginalSyncKeyVerificationDoneEvent, ToDeviceKeyVerificationDoneEvent},
key::{OriginalSyncKeyVerificationKeyEvent, ToDeviceKeyVerificationKeyEvent},
request::ToDeviceKeyVerificationRequestEvent,
start::{OriginalSyncKeyVerificationStartEvent, ToDeviceKeyVerificationStartEvent},
VerificationMethod,
},
presence::PresenceEvent,
reaction::ReactionEventContent,
room::{
encryption::RoomEncryptionEventContent,
member::OriginalSyncRoomMemberEvent,
message::{MessageType, RoomMessageEventContent},
name::RoomNameEventContent,
redaction::{OriginalSyncRoomRedactionEvent, SyncRoomRedactionEvent},
},
tag::Tags,
typing::SyncTypingEvent,
AnyInitialStateEvent,
AnyMessageLikeEvent,
AnyTimelineEvent,
EmptyStateKey,
InitialStateEvent,
SyncMessageLikeEvent,
SyncStateEvent,
},
room::RoomType,
serde::Raw,
EventEncryptionAlgorithm,
OwnedEventId,
OwnedRoomId,
OwnedRoomOrAliasId,
OwnedUserId,
RoomId,
RoomVersionId,
},
Client,
DisplayName,
Session,
};
use modalkit::editing::action::{EditInfo, InfoMessage, UIError};
use crate::{
base::{
AsyncProgramStore,
ChatStore,
CreateRoomFlags,
CreateRoomType,
EventLocation,
IambError,
IambResult,
Receipts,
RoomFetchStatus,
VerifyAction,
},
message::MessageFetchResult,
ApplicationSettings,
};
const IAMB_DEVICE_NAME: &str = "iamb";
const IAMB_USER_AGENT: &str = "iamb";
const MIN_MSG_LOAD: u32 = 50;
fn initial_devname() -> String {
format!("{} on {}", IAMB_DEVICE_NAME, gethostname().to_string_lossy())
}
pub async fn create_room(
client: &Client,
room_alias_name: Option<&str>,
rt: CreateRoomType,
flags: CreateRoomFlags,
) -> IambResult<OwnedRoomId> {
let mut creation_content = None;
let mut initial_state = vec![];
let mut is_direct = false;
let mut preset = None;
let mut invite = vec![];
let visibility = if flags.contains(CreateRoomFlags::PUBLIC) {
Visibility::Public
} else {
Visibility::Private
};
match rt {
CreateRoomType::Direct(user) => {
invite.push(user);
is_direct = true;
preset = Some(RoomPreset::TrustedPrivateChat);
},
CreateRoomType::Space => {
let mut cc = CreationContent::new();
cc.room_type = Some(RoomType::Space);
let raw_cc = Raw::new(&cc).map_err(IambError::from)?;
creation_content = Some(raw_cc);
},
CreateRoomType::Room => {},
}
// Set up encryption.
if flags.contains(CreateRoomFlags::ENCRYPTED) {
// XXX: Once matrix-sdk uses ruma 0.8, then this can skip the cast.
let algo = EventEncryptionAlgorithm::MegolmV1AesSha2;
let content = RoomEncryptionEventContent::new(algo);
let encr = InitialStateEvent { content, state_key: EmptyStateKey };
let encr_raw = Raw::new(&encr).map_err(IambError::from)?;
let encr_raw = encr_raw.cast::<AnyInitialStateEvent>();
initial_state.push(encr_raw);
}
let request = assign!(CreateRoomRequest::new(), {
room_alias_name,
creation_content,
initial_state: initial_state.as_slice(),
invite: invite.as_slice(),
is_direct,
visibility,
preset,
});
let resp = client.create_room(request).await.map_err(IambError::from)?;
if is_direct {
if let Some(room) = client.get_room(&resp.room_id) {
room.set_is_direct(true).await.map_err(IambError::from)?;
} else {
error!(
room_id = resp.room_id.as_str(),
"Couldn't set is_direct for new direct message room"
);
}
}
return Ok(resp.room_id);
}
async fn load_plan(store: &AsyncProgramStore) -> HashMap<OwnedRoomId, Option<String>> {
let mut locked = store.lock().await;
let ChatStore { need_load, rooms, .. } = &mut locked.application;
let mut plan = HashMap::new();
for room_id in std::mem::take(need_load).into_iter() {
let info = rooms.get_or_default(room_id.clone());
if info.recently_fetched() || info.fetching {
need_load.insert(room_id);
continue;
} else {
info.fetch_last = Instant::now().into();
info.fetching = true;
}
let fetch_id = match &info.fetch_id {
RoomFetchStatus::Done => continue,
RoomFetchStatus::HaveMore(fetch_id) => Some(fetch_id.clone()),
RoomFetchStatus::NotStarted => None,
};
plan.insert(room_id, fetch_id);
}
return plan;
}
async fn load_older_one(
client: Client,
room_id: &RoomId,
fetch_id: Option<String>,
limit: u32,
) -> MessageFetchResult {
if let Some(room) = client.get_room(room_id) {
let mut opts = match &fetch_id {
Some(id) => MessagesOptions::backward().from(id.as_str()),
None => MessagesOptions::backward(),
};
opts.limit = limit.into();
let Messages { end, chunk, .. } = room.messages(opts).await.map_err(IambError::from)?;
let msgs = chunk.into_iter().filter_map(|ev| {
match ev.event.deserialize() {
Ok(AnyTimelineEvent::MessageLike(msg)) => Some(msg),
Ok(AnyTimelineEvent::State(_)) => None,
Err(_) => None,
}
});
Ok((end, msgs.collect()))
} else {
Err(IambError::UnknownRoom(room_id.to_owned()).into())
}
}
async fn load_insert(room_id: OwnedRoomId, res: MessageFetchResult, store: AsyncProgramStore) {
let mut locked = store.lock().await;
let ChatStore { need_load, presences, rooms, .. } = &mut locked.application;
let info = rooms.get_or_default(room_id.clone());
info.fetching = false;
match res {
Ok((fetch_id, msgs)) => {
for msg in msgs.into_iter() {
let sender = msg.sender().to_owned();
let _ = presences.get_or_default(sender);
match msg {
AnyMessageLikeEvent::RoomEncrypted(msg) => {
info.insert_encrypted(msg);
},
AnyMessageLikeEvent::RoomMessage(msg) => {
info.insert(msg);
},
AnyMessageLikeEvent::Reaction(ev) => {
info.insert_reaction(ev);
},
_ => continue,
}
}
info.fetch_id = fetch_id.map_or(RoomFetchStatus::Done, RoomFetchStatus::HaveMore);
},
Err(e) => {
warn!(room_id = room_id.as_str(), err = e.to_string(), "Failed to load older messages");
// Wait and try again.
need_load.insert(room_id);
},
}
}
async fn load_older(client: &Client, store: &AsyncProgramStore) -> usize {
let limit = MIN_MSG_LOAD;
// Fetch each room separately, so they don't block each other.
load_plan(store)
.await
.into_iter()
.map(|(room_id, fetch_id)| {
let client = client.clone();
let store = store.clone();
async move {
let res = load_older_one(client, room_id.as_ref(), fetch_id, limit).await;
load_insert(room_id, res, store).await;
}
})
.collect::<FuturesUnordered<_>>()
.count()
.await
}
async fn load_older_forever(client: &Client, store: &AsyncProgramStore) {
// Load older messages every 2 seconds.
let mut interval = tokio::time::interval(Duration::from_secs(2));
loop {
interval.tick().await;
load_older(client, store).await;
}
}
async fn refresh_rooms(client: &Client, store: &AsyncProgramStore) {
let mut names = vec![];
let mut spaces = vec![];
let mut rooms = vec![];
let mut dms = vec![];
for room in client.invited_rooms().into_iter() {
let name = room.display_name().await.unwrap_or(DisplayName::Empty).to_string();
names.push((room.room_id().to_owned(), name));
if room.is_direct() {
let tags = room.tags().await.unwrap_or_default();
dms.push(Arc::new((room.into(), tags)));
} else if room.is_space() {
spaces.push(room.into());
} else {
let tags = room.tags().await.unwrap_or_default();
rooms.push(Arc::new((room.into(), tags)));
}
}
for room in client.joined_rooms().into_iter() {
let name = room.display_name().await.unwrap_or(DisplayName::Empty).to_string();
names.push((room.room_id().to_owned(), name));
if room.is_direct() {
let tags = room.tags().await.unwrap_or_default();
dms.push(Arc::new((room.into(), tags)));
} else if room.is_space() {
spaces.push(room.into());
} else {
let tags = room.tags().await.unwrap_or_default();
rooms.push(Arc::new((room.into(), tags)));
}
}
let mut locked = store.lock().await;
locked.application.sync_info.spaces = spaces;
locked.application.sync_info.rooms = rooms;
locked.application.sync_info.dms = dms;
for (room_id, name) in names {
locked.application.set_room_name(&room_id, &name);
}
}
async fn refresh_rooms_forever(client: &Client, store: &AsyncProgramStore) {
let mut interval = tokio::time::interval(Duration::from_secs(5));
loop {
interval.tick().await;
refresh_rooms(client, store).await;
}
}
async fn refresh_receipts_forever(client: &Client, store: &AsyncProgramStore) {
// Update the displayed read receipts every 5 seconds.
let mut interval = tokio::time::interval(Duration::from_secs(5));
let mut sent = HashMap::<OwnedRoomId, OwnedEventId>::default();
loop {
interval.tick().await;
let receipts = update_receipts(client).await;
let read = store.lock().await.application.set_receipts(receipts).await;
for (room_id, read_till) in read.into_iter() {
if let Some(read_sent) = sent.get(&room_id) {
if read_sent == &read_till {
// Skip unchanged receipts.
continue;
}
}
if let Some(room) = client.get_joined_room(&room_id) {
if room.read_receipt(&read_till).await.is_ok() {
sent.insert(room_id, read_till);
}
}
}
}
}
#[derive(Debug)]
pub enum LoginStyle {
SessionRestore(Session),
Password(String),
}
pub struct ClientResponse<T>(Receiver<T>);
pub struct ClientReply<T>(SyncSender<T>);
impl<T> ClientResponse<T> {
fn recv(self) -> T {
self.0.recv().expect("failed to receive response from client thread")
}
}
impl<T> ClientReply<T> {
fn send(self, t: T) {
self.0.send(t).unwrap();
}
}
fn oneshot<T>() -> (ClientReply<T>, ClientResponse<T>) {
let (tx, rx) = sync_channel(1);
let reply = ClientReply(tx);
let response = ClientResponse(rx);
return (reply, response);
}
async fn update_receipts(client: &Client) -> Vec<(OwnedRoomId, Receipts)> {
let mut rooms = vec![];
for room in client.joined_rooms() {
if let Ok(users) = room.active_members_no_sync().await {
let mut receipts = Receipts::new();
for member in users {
let res = room.user_read_receipt(member.user_id()).await;
if let Ok(Some((event_id, _))) = res {
let user_id = member.user_id().to_owned();
receipts.entry(event_id).or_default().push(user_id);
}
}
rooms.push((room.room_id().to_owned(), receipts));
}
}
return rooms;
}
pub type FetchedRoom = (MatrixRoom, DisplayName, Option<Tags>);
pub enum WorkerTask {
Init(AsyncProgramStore, ClientReply<()>),
Login(LoginStyle, ClientReply<IambResult<EditInfo>>),
GetInviter(Invited, ClientReply<IambResult<Option<RoomMember>>>),
GetRoom(OwnedRoomId, ClientReply<IambResult<FetchedRoom>>),
JoinRoom(String, ClientReply<IambResult<OwnedRoomId>>),
Members(OwnedRoomId, ClientReply<IambResult<Vec<RoomMember>>>),
SpaceMembers(OwnedRoomId, ClientReply<IambResult<Vec<OwnedRoomId>>>),
TypingNotice(OwnedRoomId),
Verify(VerifyAction, SasVerification, ClientReply<IambResult<EditInfo>>),
VerifyRequest(OwnedUserId, ClientReply<IambResult<EditInfo>>),
}
impl Debug for WorkerTask {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
match self {
WorkerTask::Init(_, _) => {
f.debug_tuple("WorkerTask::Init")
.field(&format_args!("_"))
.field(&format_args!("_"))
.finish()
},
WorkerTask::Login(style, _) => {
f.debug_tuple("WorkerTask::Login")
.field(style)
.field(&format_args!("_"))
.finish()
},
WorkerTask::GetInviter(invite, _) => {
f.debug_tuple("WorkerTask::GetInviter").field(invite).finish()
},
WorkerTask::GetRoom(room_id, _) => {
f.debug_tuple("WorkerTask::GetRoom")
.field(room_id)
.field(&format_args!("_"))
.finish()
},
WorkerTask::JoinRoom(s, _) => {
f.debug_tuple("WorkerTask::JoinRoom")
.field(s)
.field(&format_args!("_"))
.finish()
},
WorkerTask::Members(room_id, _) => {
f.debug_tuple("WorkerTask::Members")
.field(room_id)
.field(&format_args!("_"))
.finish()
},
WorkerTask::SpaceMembers(room_id, _) => {
f.debug_tuple("WorkerTask::SpaceMembers")
.field(room_id)
.field(&format_args!("_"))
.finish()
},
WorkerTask::TypingNotice(room_id) => {
f.debug_tuple("WorkerTask::TypingNotice").field(room_id).finish()
},
WorkerTask::Verify(act, sasv1, _) => {
f.debug_tuple("WorkerTask::Verify")
.field(act)
.field(sasv1)
.field(&format_args!("_"))
.finish()
},
WorkerTask::VerifyRequest(user_id, _) => {
f.debug_tuple("WorkerTask::VerifyRequest")
.field(user_id)
.field(&format_args!("_"))
.finish()
},
}
}
}
#[derive(Clone)]
pub struct Requester {
pub client: Client,
pub tx: UnboundedSender<WorkerTask>,
}
impl Requester {
pub fn init(&self, store: AsyncProgramStore) {
let (reply, response) = oneshot();
self.tx.send(WorkerTask::Init(store, reply)).unwrap();
return response.recv();
}
pub fn login(&self, style: LoginStyle) -> IambResult<EditInfo> {
let (reply, response) = oneshot();
self.tx.send(WorkerTask::Login(style, reply)).unwrap();
return response.recv();
}
pub fn get_inviter(&self, invite: Invited) -> IambResult<Option<RoomMember>> {
let (reply, response) = oneshot();
self.tx.send(WorkerTask::GetInviter(invite, reply)).unwrap();
return response.recv();
}
pub fn get_room(&self, room_id: OwnedRoomId) -> IambResult<FetchedRoom> {
let (reply, response) = oneshot();
self.tx.send(WorkerTask::GetRoom(room_id, reply)).unwrap();
return response.recv();
}
pub fn join_room(&self, name: String) -> IambResult<OwnedRoomId> {
let (reply, response) = oneshot();
self.tx.send(WorkerTask::JoinRoom(name, reply)).unwrap();
return response.recv();
}
pub fn members(&self, room_id: OwnedRoomId) -> IambResult<Vec<RoomMember>> {
let (reply, response) = oneshot();
self.tx.send(WorkerTask::Members(room_id, reply)).unwrap();
return response.recv();
}
pub fn space_members(&self, space: OwnedRoomId) -> IambResult<Vec<OwnedRoomId>> {
let (reply, response) = oneshot();
self.tx.send(WorkerTask::SpaceMembers(space, reply)).unwrap();
return response.recv();
}
pub fn typing_notice(&self, room_id: OwnedRoomId) {
self.tx.send(WorkerTask::TypingNotice(room_id)).unwrap();
}
pub fn verify(&self, act: VerifyAction, sas: SasVerification) -> IambResult<EditInfo> {
let (reply, response) = oneshot();
self.tx.send(WorkerTask::Verify(act, sas, reply)).unwrap();
return response.recv();
}
pub fn verify_request(&self, user_id: OwnedUserId) -> IambResult<EditInfo> {
let (reply, response) = oneshot();
self.tx.send(WorkerTask::VerifyRequest(user_id, reply)).unwrap();
return response.recv();
}
}
pub struct ClientWorker {
initialized: bool,
settings: ApplicationSettings,
client: Client,
load_handle: Option<JoinHandle<()>>,
sync_handle: Option<JoinHandle<()>>,
}
impl ClientWorker {
pub async fn spawn(settings: ApplicationSettings) -> Requester {
let (tx, rx) = unbounded_channel();
let account = &settings.profile;
let req_timeout = Duration::from_secs(settings.tunables.request_timeout);
// Set up the HTTP client.
let http = reqwest::Client::builder()
.user_agent(IAMB_USER_AGENT)
.timeout(req_timeout)
.pool_idle_timeout(Duration::from_secs(60))
.pool_max_idle_per_host(10)
.tcp_keepalive(Duration::from_secs(10))
.build()
.unwrap();
let req_config = RequestConfig::new().timeout(req_timeout).retry_timeout(req_timeout);
// Set up the Matrix client for the selected profile.
let client = Client::builder()
.http_client(Arc::new(http))
.homeserver_url(account.url.clone())
.sled_store(settings.matrix_dir.as_path(), None)
.expect("Failed to setup up sled store for Matrix SDK")
.request_config(req_config)
.build()
.await
.expect("Failed to instantiate Matrix client");
let mut worker = ClientWorker {
initialized: false,
settings,
client: client.clone(),
load_handle: None,
sync_handle: None,
};
tokio::spawn(async move {
worker.work(rx).await;
});
return Requester { client, tx };
}
async fn work(&mut self, mut rx: UnboundedReceiver<WorkerTask>) {
loop {
let t = rx.recv().await;
match t {
Some(task) => self.run(task).await,
None => {
break;
},
}
}
if let Some(handle) = self.sync_handle.take() {
handle.abort();
}
}
async fn run(&mut self, task: WorkerTask) {
match task {
WorkerTask::Init(store, reply) => {
assert_eq!(self.initialized, false);
self.init(store).await;
reply.send(());
},
WorkerTask::JoinRoom(room_id, reply) => {
assert!(self.initialized);
reply.send(self.join_room(room_id).await);
},
WorkerTask::GetInviter(invited, reply) => {
assert!(self.initialized);
reply.send(self.get_inviter(invited).await);
},
WorkerTask::GetRoom(room_id, reply) => {
assert!(self.initialized);
reply.send(self.get_room(room_id).await);
},
WorkerTask::Login(style, reply) => {
assert!(self.initialized);
reply.send(self.login_and_sync(style).await);
},
WorkerTask::Members(room_id, reply) => {
assert!(self.initialized);
reply.send(self.members(room_id).await);
},
WorkerTask::SpaceMembers(space, reply) => {
assert!(self.initialized);
reply.send(self.space_members(space).await);
},
WorkerTask::TypingNotice(room_id) => {
assert!(self.initialized);
self.typing_notice(room_id).await;
},
WorkerTask::Verify(act, sas, reply) => {
assert!(self.initialized);
reply.send(self.verify(act, sas).await);
},
WorkerTask::VerifyRequest(user_id, reply) => {
assert!(self.initialized);
reply.send(self.verify_request(user_id).await);
},
}
}
async fn init(&mut self, store: AsyncProgramStore) {
self.client.add_event_handler_context(store.clone());
let _ = self.client.add_event_handler(
|ev: SyncTypingEvent, room: MatrixRoom, store: Ctx<AsyncProgramStore>| {
async move {
let room_id = room.room_id().to_owned();
let mut locked = store.lock().await;
let users = ev
.content
.user_ids
.into_iter()
.filter(|u| u != &locked.application.settings.profile.user_id)
.collect();
locked.application.get_room_info(room_id).set_typing(users);
}
},
);
let _ =
self.client
.add_event_handler(|ev: PresenceEvent, store: Ctx<AsyncProgramStore>| {
async move {
let mut locked = store.lock().await;
locked.application.presences.insert(ev.sender, ev.content.presence);
}
});
let _ = self.client.add_event_handler(
|ev: SyncStateEvent<RoomNameEventContent>,
room: MatrixRoom,
store: Ctx<AsyncProgramStore>| {
async move {
if let SyncStateEvent::Original(ev) = ev {
if let Some(room_name) = ev.content.name {
let room_id = room.room_id().to_owned();
let room_name = Some(room_name.to_string());
let mut locked = store.lock().await;
let mut info = locked.application.rooms.get_or_default(room_id.clone());
info.name = room_name;
}
}
}
},
);
let _ = self.client.add_event_handler(
|ev: SyncMessageLikeEvent<RoomMessageEventContent>,
room: MatrixRoom,
client: Client,
store: Ctx<AsyncProgramStore>| {
async move {
let room_id = room.room_id();
if let Some(msg) = ev.as_original() {
if let MessageType::VerificationRequest(_) = msg.content.msgtype {
if let Some(request) = client
.encryption()
.get_verification_request(ev.sender(), ev.event_id())
.await
{
request.accept().await.expect("Failed to accept request");
}
}
}
let mut locked = store.lock().await;
let sender = ev.sender().to_owned();
let _ = locked.application.presences.get_or_default(sender);
let info = locked.application.get_room_info(room_id.to_owned());
info.insert(ev.into_full_event(room_id.to_owned()));
}
},
);
let _ = self.client.add_event_handler(
|ev: SyncMessageLikeEvent<ReactionEventContent>,
room: MatrixRoom,
store: Ctx<AsyncProgramStore>| {
async move {
let room_id = room.room_id();
let mut locked = store.lock().await;
let sender = ev.sender().to_owned();
let _ = locked.application.presences.get_or_default(sender);
let info = locked.application.get_room_info(room_id.to_owned());
info.insert_reaction(ev.into_full_event(room_id.to_owned()));
}
},
);
let _ = self.client.add_event_handler(
|ev: OriginalSyncRoomRedactionEvent,
room: MatrixRoom,
store: Ctx<AsyncProgramStore>| {
async move {
let room_id = room.room_id();
let room_info = room.clone_info();
let room_version = room_info.room_version().unwrap_or(&RoomVersionId::V1);
let mut locked = store.lock().await;
let info = locked.application.get_room_info(room_id.to_owned());
match info.keys.get(&ev.redacts) {
None => return,
Some(EventLocation::Message(key)) => {
if let Some(msg) = info.messages.get_mut(key) {
let ev = SyncRoomRedactionEvent::Original(ev);
msg.redact(ev, room_version);
}
},
Some(EventLocation::Reaction(event_id)) => {
if let Some(reactions) = info.reactions.get_mut(event_id) {
reactions.remove(&ev.redacts);
}
info.keys.remove(&ev.redacts);
},
}
}
},
);
let _ = self.client.add_event_handler(
|ev: OriginalSyncRoomMemberEvent,
room: MatrixRoom,
client: Client,
store: Ctx<AsyncProgramStore>| {
async move {
let room_id = room.room_id();
let user_id = ev.state_key;
let ambiguous_name =
ev.content.displayname.as_deref().unwrap_or_else(|| user_id.localpart());
let ambiguous = client
.store()
.get_users_with_display_name(room_id, ambiguous_name)
.await
.map(|users| users.len() > 1)
.unwrap_or_default();
let mut locked = store.lock().await;
let info = locked.application.get_room_info(room_id.to_owned());
if ambiguous {
info.display_names.remove(&user_id);
} else if let Some(display) = ev.content.displayname {
info.display_names.insert(user_id, display);
} else {
info.display_names.remove(&user_id);
}
}
},
);
let _ = self.client.add_event_handler(
|ev: OriginalSyncKeyVerificationStartEvent,
client: Client,
store: Ctx<AsyncProgramStore>| {
async move {
let tx_id = ev.content.relates_to.event_id.as_ref();
if let Some(Verification::SasV1(sas)) =
client.encryption().get_verification(&ev.sender, tx_id).await
{
sas.accept().await.unwrap();
store.lock().await.application.insert_sas(sas)
}
}
},
);
let _ = self.client.add_event_handler(
|ev: OriginalSyncKeyVerificationKeyEvent,
client: Client,
store: Ctx<AsyncProgramStore>| {
async move {
let tx_id = ev.content.relates_to.event_id.as_ref();
if let Some(Verification::SasV1(sas)) =
client.encryption().get_verification(&ev.sender, tx_id).await
{
store.lock().await.application.insert_sas(sas);
}
}
},
);
let _ = self.client.add_event_handler(
|ev: OriginalSyncKeyVerificationDoneEvent,
client: Client,
store: Ctx<AsyncProgramStore>| {
async move {
let tx_id = ev.content.relates_to.event_id.as_ref();
if let Some(Verification::SasV1(sas)) =
client.encryption().get_verification(&ev.sender, tx_id).await
{
store.lock().await.application.insert_sas(sas);
}
}
},
);
let _ = self.client.add_event_handler(
|ev: ToDeviceKeyVerificationRequestEvent, client: Client| {
async move {
let request = client
.encryption()
.get_verification_request(&ev.sender, &ev.content.transaction_id)
.await;
if let Some(request) = request {
request.accept().await.unwrap();
}
}
},
);
let _ = self.client.add_event_handler(
|ev: ToDeviceKeyVerificationStartEvent,
client: Client,
store: Ctx<AsyncProgramStore>| {
async move {
let tx_id = ev.content.transaction_id;
if let Some(Verification::SasV1(sas)) =
client.encryption().get_verification(&ev.sender, tx_id.as_ref()).await
{
sas.accept().await.unwrap();
store.lock().await.application.insert_sas(sas);
}
}
},
);
let _ = self.client.add_event_handler(
|ev: ToDeviceKeyVerificationKeyEvent, client: Client, store: Ctx<AsyncProgramStore>| {
async move {
let tx_id = ev.content.transaction_id;
if let Some(Verification::SasV1(sas)) =
client.encryption().get_verification(&ev.sender, tx_id.as_ref()).await
{
store.lock().await.application.insert_sas(sas);
}
}
},
);
let _ = self.client.add_event_handler(
|ev: ToDeviceKeyVerificationDoneEvent,
client: Client,
store: Ctx<AsyncProgramStore>| {
async move {
let tx_id = ev.content.transaction_id;
if let Some(Verification::SasV1(sas)) =
client.encryption().get_verification(&ev.sender, tx_id.as_ref()).await
{
store.lock().await.application.insert_sas(sas);
}
}
},
);
self.load_handle = tokio::spawn({
let client = self.client.clone();
async move {
let load = load_older_forever(&client, &store);
let rcpt = refresh_receipts_forever(&client, &store);
let room = refresh_rooms_forever(&client, &store);
let ((), (), ()) = tokio::join!(load, rcpt, room);
}
})
.into();
self.initialized = true;
}
async fn login_and_sync(&mut self, style: LoginStyle) -> IambResult<EditInfo> {
let client = self.client.clone();
match style {
LoginStyle::SessionRestore(session) => {
client.restore_login(session).await.map_err(IambError::from)?;
},
LoginStyle::Password(password) => {
let resp = client
.login_username(&self.settings.profile.user_id, &password)
.initial_device_display_name(initial_devname().as_str())
.send()
.await
.map_err(IambError::from)?;
let file = File::create(self.settings.session_json.as_path())?;
let writer = BufWriter::new(file);
let session = Session::from(resp);
serde_json::to_writer(writer, &session).map_err(IambError::from)?;
},
}
self.sync_handle = tokio::spawn(async move {
loop {
let settings = SyncSettings::default();
let _ = client.sync(settings).await;
}
})
.into();
Ok(Some(InfoMessage::from("Successfully logged in!")))
}
async fn direct_message(&mut self, user: OwnedUserId) -> IambResult<OwnedRoomId> {
for room in self.client.rooms() {
if !room.is_direct() {
continue;
}
if room.get_member(user.as_ref()).await.map_err(IambError::from)?.is_some() {
return Ok(room.room_id().to_owned());
}
}
let rt = CreateRoomType::Direct(user.clone());
let flags = CreateRoomFlags::ENCRYPTED;
create_room(&self.client, None, rt, flags).await.map_err(|e| {
error!(
user_id = user.as_str(),
err = e.to_string(),
"Failed to create direct message room"
);
let msg = format!("Could not open a room with {user}");
UIError::Failure(msg)
})
}
async fn get_inviter(&mut self, invited: Invited) -> IambResult<Option<RoomMember>> {
let details = invited.invite_details().await.map_err(IambError::from)?;
Ok(details.inviter)
}
async fn get_room(&mut self, room_id: OwnedRoomId) -> IambResult<FetchedRoom> {
if let Some(room) = self.client.get_room(&room_id) {
let name = room.display_name().await.map_err(IambError::from)?;
let tags = room.tags().await.map_err(IambError::from)?;
Ok((room, name, tags))
} else {
Err(IambError::UnknownRoom(room_id).into())
}
}
async fn join_room(&mut self, name: String) -> IambResult<OwnedRoomId> {
if let Ok(alias_id) = OwnedRoomOrAliasId::from_str(name.as_str()) {
match self.client.join_room_by_id_or_alias(&alias_id, &[]).await {
Ok(resp) => Ok(resp.room_id),
Err(e) => {
let msg = e.to_string();
let err = UIError::Failure(msg);
return Err(err);
},
}
} else if let Ok(user) = OwnedUserId::try_from(name.as_str()) {
self.direct_message(user).await
} else {
let msg = format!("{:?} is not a valid room or user name", name.as_str());
let err = UIError::Failure(msg);
return Err(err);
}
}
async fn members(&mut self, room_id: OwnedRoomId) -> IambResult<Vec<RoomMember>> {
if let Some(room) = self.client.get_room(room_id.as_ref()) {
Ok(room.active_members().await.map_err(IambError::from)?)
} else {
Err(IambError::UnknownRoom(room_id).into())
}
}
async fn space_members(&mut self, space: OwnedRoomId) -> IambResult<Vec<OwnedRoomId>> {
let mut req = SpaceHierarchyRequest::new(&space);
req.limit = Some(1000u32.into());
req.max_depth = Some(1u32.into());
let resp = self.client.send(req, None).await.map_err(IambError::from)?;
let rooms = resp.rooms.into_iter().map(|chunk| chunk.room_id).collect();
Ok(rooms)
}
async fn typing_notice(&mut self, room_id: OwnedRoomId) {
if let Some(room) = self.client.get_joined_room(room_id.as_ref()) {
let _ = room.typing_notice(true).await;
}
}
async fn verify(&self, action: VerifyAction, sas: SasVerification) -> IambResult<EditInfo> {
match action {
VerifyAction::Accept => {
sas.accept().await.map_err(IambError::from)?;
Ok(Some(InfoMessage::from("Accepted verification request")))
},
VerifyAction::Confirm => {
if sas.is_done() || sas.is_cancelled() {
let msg = "Can only confirm in-progress verifications!";
let err = UIError::Failure(msg.into());
return Err(err);
}
sas.confirm().await.map_err(IambError::from)?;
Ok(Some(InfoMessage::from("Confirmed verification")))
},
VerifyAction::Cancel => {
if sas.is_done() || sas.is_cancelled() {
let msg = "Can only cancel in-progress verifications!";
let err = UIError::Failure(msg.into());
return Err(err);
}
sas.cancel().await.map_err(IambError::from)?;
Ok(Some(InfoMessage::from("Cancelled verification")))
},
VerifyAction::Mismatch => {
if sas.is_done() || sas.is_cancelled() {
let msg = "Can only cancel in-progress verifications!";
let err = UIError::Failure(msg.into());
return Err(err);
}
sas.mismatch().await.map_err(IambError::from)?;
Ok(Some(InfoMessage::from("Cancelled verification")))
},
}
}
async fn verify_request(&self, user_id: OwnedUserId) -> IambResult<EditInfo> {
let enc = self.client.encryption();
match enc.get_user_identity(user_id.as_ref()).await.map_err(IambError::from)? {
Some(identity) => {
let methods = vec![VerificationMethod::SasV1];
let request = identity.request_verification_with_methods(methods);
let _req = request.await.map_err(IambError::from)?;
let info = format!("Sent verification request to {user_id}");
Ok(Some(InfoMessage::from(info)))
},
None => {
let msg = format!("Could not find identity information for {user_id}");
let err = UIError::Failure(msg);
Err(err)
},
}
}
}
07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!1080 blocks