Compare commits
30 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a2590b6bbb | ||
|
|
725ebb9fd6 | ||
|
|
ca395097e1 | ||
|
|
e98d58a8cc | ||
|
|
e6cdd02f22 | ||
|
|
0bc4ff07b0 | ||
|
|
14fe916d94 | ||
|
|
db35581d07 | ||
|
|
7c1c62897a | ||
|
|
61897ea6f2 | ||
|
|
6a0722795a | ||
|
|
f3bbc6ad9f | ||
|
|
2dd8c0fddf | ||
|
|
a786369b14 | ||
|
|
066f60ad32 | ||
|
|
10b142c071 | ||
|
|
ac6ff63d25 | ||
|
|
54a0e76823 | ||
|
|
93eff79f79 | ||
|
|
11625262f1 | ||
|
|
0ed1d53946 | ||
|
|
e3be8c16cb | ||
|
|
4c5c57e26c | ||
|
|
8eef8787cc | ||
|
|
c9c547acc1 | ||
|
|
3629f15e0d | ||
|
|
fd72cf5c4e | ||
|
|
1d93461183 | ||
|
|
a1574c6b8d | ||
|
|
e8205df21d |
6
.github/workflows/ci.yml
vendored
6
.github/workflows/ci.yml
vendored
@@ -13,7 +13,7 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout code
|
- name: Checkout code
|
||||||
uses: actions/checkout@v1
|
uses: actions/checkout@v3
|
||||||
with:
|
with:
|
||||||
submodules: true
|
submodules: true
|
||||||
- name: Install Rust
|
- name: Install Rust
|
||||||
@@ -35,7 +35,7 @@ jobs:
|
|||||||
runs-on: ${{ matrix.platform }}
|
runs-on: ${{ matrix.platform }}
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout code
|
- name: Checkout code
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v3
|
||||||
with:
|
with:
|
||||||
submodules: true
|
submodules: true
|
||||||
- name: Install Rust
|
- name: Install Rust
|
||||||
@@ -45,7 +45,7 @@ jobs:
|
|||||||
override: true
|
override: true
|
||||||
components: rustfmt, clippy
|
components: rustfmt, clippy
|
||||||
- name: Cache cargo registry
|
- name: Cache cargo registry
|
||||||
uses: actions/cache@v1
|
uses: actions/cache@v3
|
||||||
with:
|
with:
|
||||||
path: ~/.cargo/registry
|
path: ~/.cargo/registry
|
||||||
key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }}
|
key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }}
|
||||||
|
|||||||
397
Cargo.lock
generated
397
Cargo.lock
generated
@@ -2,6 +2,12 @@
|
|||||||
# It is not intended for manual editing.
|
# It is not intended for manual editing.
|
||||||
version = 3
|
version = 3
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "adler"
|
||||||
|
version = "1.0.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "aead"
|
name = "aead"
|
||||||
version = "0.4.3"
|
version = "0.4.3"
|
||||||
@@ -64,6 +70,26 @@ version = "0.13.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "d301b3b94cb4b2f23d7917810addbbaff90738e0ca2be692bd027e70d7e0330c"
|
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]]
|
[[package]]
|
||||||
name = "arrayref"
|
name = "arrayref"
|
||||||
version = "0.3.6"
|
version = "0.3.6"
|
||||||
@@ -200,6 +226,12 @@ dependencies = [
|
|||||||
"digest 0.10.6",
|
"digest 0.10.6",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "block"
|
||||||
|
version = "0.1.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "block-buffer"
|
name = "block-buffer"
|
||||||
version = "0.9.0"
|
version = "0.9.0"
|
||||||
@@ -233,6 +265,12 @@ version = "3.12.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "0d261e256854913907f67ed06efbc3338dfe6179796deefc1ff763fc1aee5535"
|
checksum = "0d261e256854913907f67ed06efbc3338dfe6179796deefc1ff763fc1aee5535"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "bytemuck"
|
||||||
|
version = "1.13.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c041d3eab048880cb0b86b256447da3f18859a163c3b8d8893f4e6368abe6393"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "byteorder"
|
name = "byteorder"
|
||||||
version = "1.4.3"
|
version = "1.4.3"
|
||||||
@@ -368,6 +406,17 @@ dependencies = [
|
|||||||
"os_str_bytes",
|
"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]]
|
[[package]]
|
||||||
name = "codespan-reporting"
|
name = "codespan-reporting"
|
||||||
version = "0.11.1"
|
version = "0.11.1"
|
||||||
@@ -378,6 +427,12 @@ dependencies = [
|
|||||||
"unicode-width",
|
"unicode-width",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "color_quant"
|
||||||
|
version = "1.1.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "const-oid"
|
name = "const-oid"
|
||||||
version = "0.7.1"
|
version = "0.7.1"
|
||||||
@@ -396,12 +451,47 @@ version = "0.4.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e"
|
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]]
|
[[package]]
|
||||||
name = "core-foundation-sys"
|
name = "core-foundation-sys"
|
||||||
version = "0.8.3"
|
version = "0.8.3"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "5827cebf4670468b8772dd191856768aedcb1b0278a04f989f7766351917b9dc"
|
checksum = "5827cebf4670468b8772dd191856768aedcb1b0278a04f989f7766351917b9dc"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "core-graphics"
|
||||||
|
version = "0.22.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "2581bbab3b8ffc6fcbd550bf46c355135d16e9ff2a6ea032ad6b9bf1d7efe4fb"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags",
|
||||||
|
"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",
|
||||||
|
"core-foundation",
|
||||||
|
"foreign-types",
|
||||||
|
"libc",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cpufeatures"
|
name = "cpufeatures"
|
||||||
version = "0.2.5"
|
version = "0.2.5"
|
||||||
@@ -439,7 +529,7 @@ dependencies = [
|
|||||||
"autocfg",
|
"autocfg",
|
||||||
"cfg-if",
|
"cfg-if",
|
||||||
"crossbeam-utils",
|
"crossbeam-utils",
|
||||||
"memoffset",
|
"memoffset 0.7.1",
|
||||||
"scopeguard",
|
"scopeguard",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -752,6 +842,15 @@ version = "1.8.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "90e5c1c8368803113bf0c9584fc495a58b86dc8a29edbf8fe877d21d9507e797"
|
checksum = "90e5c1c8368803113bf0c9584fc495a58b86dc8a29edbf8fe877d21d9507e797"
|
||||||
|
|
||||||
|
[[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]]
|
[[package]]
|
||||||
name = "encoding_rs"
|
name = "encoding_rs"
|
||||||
version = "0.8.31"
|
version = "0.8.31"
|
||||||
@@ -761,6 +860,12 @@ dependencies = [
|
|||||||
"cfg-if",
|
"cfg-if",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "endian-type"
|
||||||
|
version = "0.1.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c34f04666d835ff5d62e058c3995147c06f42fe86ff053337632bca83e42702d"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "errno"
|
name = "errno"
|
||||||
version = "0.2.8"
|
version = "0.2.8"
|
||||||
@@ -782,6 +887,16 @@ dependencies = [
|
|||||||
"libc",
|
"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]]
|
[[package]]
|
||||||
name = "event-listener"
|
name = "event-listener"
|
||||||
version = "2.5.3"
|
version = "2.5.3"
|
||||||
@@ -797,12 +912,37 @@ dependencies = [
|
|||||||
"instant",
|
"instant",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "flate2"
|
||||||
|
version = "1.0.25"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a8a2db397cb1c8772f31494cb8917e48cd1e64f0fa7efac59fbd741a0a8ce841"
|
||||||
|
dependencies = [
|
||||||
|
"crc32fast",
|
||||||
|
"miniz_oxide",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "fnv"
|
name = "fnv"
|
||||||
version = "1.0.7"
|
version = "1.0.7"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
|
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]]
|
[[package]]
|
||||||
name = "form_urlencoded"
|
name = "form_urlencoded"
|
||||||
version = "1.1.0"
|
version = "1.1.0"
|
||||||
@@ -974,6 +1114,16 @@ dependencies = [
|
|||||||
"version_check",
|
"version_check",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "gethostname"
|
||||||
|
version = "0.2.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c1ebd34e35c46e00bb73e81363248d627782724609fe1b6396f553f68fe3862e"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
"winapi",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "gethostname"
|
name = "gethostname"
|
||||||
version = "0.4.1"
|
version = "0.4.1"
|
||||||
@@ -1158,13 +1308,15 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "iamb"
|
name = "iamb"
|
||||||
version = "0.0.4"
|
version = "0.0.7"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"bitflags",
|
||||||
"chrono",
|
"chrono",
|
||||||
"clap",
|
"clap",
|
||||||
"css-color-parser",
|
"css-color-parser",
|
||||||
"dirs",
|
"dirs",
|
||||||
"gethostname",
|
"emojis",
|
||||||
|
"gethostname 0.4.1",
|
||||||
"html5ever",
|
"html5ever",
|
||||||
"lazy_static 1.4.0",
|
"lazy_static 1.4.0",
|
||||||
"markup5ever_rcdom",
|
"markup5ever_rcdom",
|
||||||
@@ -1172,6 +1324,7 @@ dependencies = [
|
|||||||
"mime",
|
"mime",
|
||||||
"mime_guess",
|
"mime_guess",
|
||||||
"modalkit",
|
"modalkit",
|
||||||
|
"open",
|
||||||
"regex",
|
"regex",
|
||||||
"rpassword",
|
"rpassword",
|
||||||
"serde",
|
"serde",
|
||||||
@@ -1226,6 +1379,21 @@ dependencies = [
|
|||||||
"unicode-normalization",
|
"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",
|
||||||
|
"num-rational",
|
||||||
|
"num-traits",
|
||||||
|
"png",
|
||||||
|
"tiff",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "indexed_db_futures"
|
name = "indexed_db_futures"
|
||||||
version = "0.2.3"
|
version = "0.2.3"
|
||||||
@@ -1325,6 +1493,12 @@ version = "1.0.5"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "fad582f4b9e86b6caa621cabeb0963332d92eea04729ab12892c2533951e6440"
|
checksum = "fad582f4b9e86b6caa621cabeb0963332d92eea04729ab12892c2533951e6440"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "jpeg-decoder"
|
||||||
|
version = "0.3.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "bc0000e42512c92e31c2252315bda326620a4e034105e900c98ec492fa077b3e"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "js-sys"
|
name = "js-sys"
|
||||||
version = "0.3.60"
|
version = "0.3.60"
|
||||||
@@ -1419,6 +1593,15 @@ version = "0.1.1"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4"
|
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]]
|
[[package]]
|
||||||
name = "maplit"
|
name = "maplit"
|
||||||
version = "1.0.2"
|
version = "1.0.2"
|
||||||
@@ -1432,7 +1615,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "7a2629bb1404f3d34c2e921f21fd34ba00b206124c81f65c50b43b6aaefeb016"
|
checksum = "7a2629bb1404f3d34c2e921f21fd34ba00b206124c81f65c50b43b6aaefeb016"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"log",
|
"log",
|
||||||
"phf",
|
"phf 0.10.1",
|
||||||
"phf_codegen",
|
"phf_codegen",
|
||||||
"string_cache",
|
"string_cache",
|
||||||
"string_cache_codegen",
|
"string_cache_codegen",
|
||||||
@@ -1636,6 +1819,15 @@ version = "2.5.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d"
|
checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "memoffset"
|
||||||
|
version = "0.6.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce"
|
||||||
|
dependencies = [
|
||||||
|
"autocfg",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "memoffset"
|
name = "memoffset"
|
||||||
version = "0.7.1"
|
version = "0.7.1"
|
||||||
@@ -1667,6 +1859,15 @@ version = "0.2.1"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
|
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]]
|
[[package]]
|
||||||
name = "mio"
|
name = "mio"
|
||||||
version = "0.8.5"
|
version = "0.8.5"
|
||||||
@@ -1681,21 +1882,24 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "modalkit"
|
name = "modalkit"
|
||||||
version = "0.0.10"
|
version = "0.0.14"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "4f57d0d53c9f3d8cad2508351f88656e4185cbb8b95d0c738b314fc8167bc90f"
|
checksum = "5c48c7d7e6d764a09435b43a7e4d342ba2d2e026626ca773b16a5ba34b90b933"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anymap2",
|
"anymap2",
|
||||||
|
"arboard",
|
||||||
"bitflags",
|
"bitflags",
|
||||||
"crossterm",
|
"crossterm",
|
||||||
"derive_more",
|
"derive_more",
|
||||||
"intervaltree",
|
"intervaltree",
|
||||||
"libc",
|
"libc",
|
||||||
"nom",
|
"nom",
|
||||||
|
"radix_trie",
|
||||||
"regex",
|
"regex",
|
||||||
"ropey",
|
"ropey",
|
||||||
"thiserror",
|
"thiserror",
|
||||||
"tui",
|
"tui",
|
||||||
|
"unicode-segmentation",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1704,6 +1908,27 @@ version = "1.0.4"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "e4a24736216ec316047a1fc4252e27dabb04218aa4a3f37c6e7ddbf1f9782b54"
|
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",
|
||||||
|
"cfg-if",
|
||||||
|
"libc",
|
||||||
|
"memoffset 0.6.5",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "nom"
|
name = "nom"
|
||||||
version = "7.1.3"
|
version = "7.1.3"
|
||||||
@@ -1734,6 +1959,17 @@ dependencies = [
|
|||||||
"num-traits",
|
"num-traits",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "num-rational"
|
||||||
|
version = "0.4.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0638a1c9d0a3c0914158145bc76cff373a75a627e6ecbfb71cbe6f453a5a19b0"
|
||||||
|
dependencies = [
|
||||||
|
"autocfg",
|
||||||
|
"num-integer",
|
||||||
|
"num-traits",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "num-traits"
|
name = "num-traits"
|
||||||
version = "0.2.15"
|
version = "0.2.15"
|
||||||
@@ -1753,6 +1989,35 @@ dependencies = [
|
|||||||
"libc",
|
"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]]
|
[[package]]
|
||||||
name = "once_cell"
|
name = "once_cell"
|
||||||
version = "1.17.0"
|
version = "1.17.0"
|
||||||
@@ -1765,6 +2030,16 @@ version = "0.3.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5"
|
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",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "os_str_bytes"
|
name = "os_str_bytes"
|
||||||
version = "6.4.1"
|
version = "6.4.1"
|
||||||
@@ -1842,6 +2117,12 @@ dependencies = [
|
|||||||
"subtle",
|
"subtle",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "pathdiff"
|
||||||
|
version = "0.2.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8835116a5c179084a830efb3adc117ab007512b535bc1a21c991d3b32a6b44dd"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pbkdf2"
|
name = "pbkdf2"
|
||||||
version = "0.11.0"
|
version = "0.11.0"
|
||||||
@@ -1866,7 +2147,16 @@ version = "0.10.1"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "fabbf1ead8a5bcbc20f5f8b939ee3f5b0f6f281b6ad3468b84656b658b455259"
|
checksum = "fabbf1ead8a5bcbc20f5f8b939ee3f5b0f6f281b6ad3468b84656b658b455259"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"phf_shared",
|
"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]]
|
[[package]]
|
||||||
@@ -1876,7 +2166,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "4fb1c3a8bc4dd4e5cfce29b44ffc14bedd2ee294559a294e2a4d4c9e9a6a13cd"
|
checksum = "4fb1c3a8bc4dd4e5cfce29b44ffc14bedd2ee294559a294e2a4d4c9e9a6a13cd"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"phf_generator",
|
"phf_generator",
|
||||||
"phf_shared",
|
"phf_shared 0.10.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1885,7 +2175,7 @@ version = "0.10.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "5d5285893bb5eb82e6aaf5d59ee909a06a16737a8970984dd7746ba9283498d6"
|
checksum = "5d5285893bb5eb82e6aaf5d59ee909a06a16737a8970984dd7746ba9283498d6"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"phf_shared",
|
"phf_shared 0.10.0",
|
||||||
"rand 0.8.5",
|
"rand 0.8.5",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -1898,6 +2188,15 @@ dependencies = [
|
|||||||
"siphasher",
|
"siphasher",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "phf_shared"
|
||||||
|
version = "0.11.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e1fb5f6f826b772a8d4c0394209441e7d37cbbb967ae9c7e0e8134365c9ee676"
|
||||||
|
dependencies = [
|
||||||
|
"siphasher",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pin-project"
|
name = "pin-project"
|
||||||
version = "1.0.12"
|
version = "1.0.12"
|
||||||
@@ -1940,6 +2239,18 @@ dependencies = [
|
|||||||
"spki",
|
"spki",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "png"
|
||||||
|
version = "0.17.7"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "5d708eaf860a19b19ce538740d2b4bdeeb8337fa53f7738455e706623ad5c638"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags",
|
||||||
|
"crc32fast",
|
||||||
|
"flate2",
|
||||||
|
"miniz_oxide",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "poly1305"
|
name = "poly1305"
|
||||||
version = "0.7.2"
|
version = "0.7.2"
|
||||||
@@ -2050,6 +2361,16 @@ dependencies = [
|
|||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[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]]
|
[[package]]
|
||||||
name = "rand"
|
name = "rand"
|
||||||
version = "0.7.3"
|
version = "0.7.3"
|
||||||
@@ -2604,6 +2925,12 @@ dependencies = [
|
|||||||
"der",
|
"der",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "str-buf"
|
||||||
|
version = "1.0.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9e08d8363704e6c71fc928674353e6b7c23dcea9d82d7012c8faf2a3a025f8d0"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "str_indices"
|
name = "str_indices"
|
||||||
version = "0.4.1"
|
version = "0.4.1"
|
||||||
@@ -2619,7 +2946,7 @@ dependencies = [
|
|||||||
"new_debug_unreachable",
|
"new_debug_unreachable",
|
||||||
"once_cell",
|
"once_cell",
|
||||||
"parking_lot 0.12.1",
|
"parking_lot 0.12.1",
|
||||||
"phf_shared",
|
"phf_shared 0.10.0",
|
||||||
"precomputed-hash",
|
"precomputed-hash",
|
||||||
"serde",
|
"serde",
|
||||||
]
|
]
|
||||||
@@ -2631,7 +2958,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "6bb30289b722be4ff74a408c3cc27edeaad656e06cb1fe8fa9231fa59c728988"
|
checksum = "6bb30289b722be4ff74a408c3cc27edeaad656e06cb1fe8fa9231fa59c728988"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"phf_generator",
|
"phf_generator",
|
||||||
"phf_shared",
|
"phf_shared 0.10.0",
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
]
|
]
|
||||||
@@ -2720,6 +3047,17 @@ dependencies = [
|
|||||||
"once_cell",
|
"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]]
|
[[package]]
|
||||||
name = "time"
|
name = "time"
|
||||||
version = "0.1.45"
|
version = "0.1.45"
|
||||||
@@ -3220,6 +3558,12 @@ dependencies = [
|
|||||||
"webpki",
|
"webpki",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "weezl"
|
||||||
|
version = "0.1.7"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9193164d4de03a926d909d3bc7c30543cecb35400c02114792c2cae20d5e2dbb"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "wildmatch"
|
name = "wildmatch"
|
||||||
version = "2.1.1"
|
version = "2.1.1"
|
||||||
@@ -3251,6 +3595,15 @@ dependencies = [
|
|||||||
"winapi",
|
"winapi",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "winapi-wsapoll"
|
||||||
|
version = "0.1.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "44c17110f57155602a80dca10be03852116403c9ff3cd25b079d666f2aa3df6e"
|
||||||
|
dependencies = [
|
||||||
|
"winapi",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "winapi-x86_64-pc-windows-gnu"
|
name = "winapi-x86_64-pc-windows-gnu"
|
||||||
version = "0.4.0"
|
version = "0.4.0"
|
||||||
@@ -3338,6 +3691,28 @@ dependencies = [
|
|||||||
"winapi",
|
"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]]
|
[[package]]
|
||||||
name = "x25519-dalek"
|
name = "x25519-dalek"
|
||||||
version = "1.2.0"
|
version = "1.2.0"
|
||||||
|
|||||||
11
Cargo.toml
11
Cargo.toml
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "iamb"
|
name = "iamb"
|
||||||
version = "0.0.4"
|
version = "0.0.7"
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
authors = ["Ulyssa <git@ulyssa.dev>"]
|
authors = ["Ulyssa <git@ulyssa.dev>"]
|
||||||
repository = "https://github.com/ulyssa/iamb"
|
repository = "https://github.com/ulyssa/iamb"
|
||||||
@@ -14,15 +14,18 @@ categories = ["command-line-utilities"]
|
|||||||
rust-version = "1.66"
|
rust-version = "1.66"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
bitflags = "1.3.2"
|
||||||
chrono = "0.4"
|
chrono = "0.4"
|
||||||
clap = {version = "4.0", features = ["derive"]}
|
clap = {version = "4.0", features = ["derive"]}
|
||||||
css-color-parser = "0.1.2"
|
css-color-parser = "0.1.2"
|
||||||
dirs = "4.0.0"
|
dirs = "4.0.0"
|
||||||
|
emojis = "~0.5.2"
|
||||||
gethostname = "0.4.1"
|
gethostname = "0.4.1"
|
||||||
html5ever = "0.26.0"
|
html5ever = "0.26.0"
|
||||||
markup5ever_rcdom = "0.2.0"
|
markup5ever_rcdom = "0.2.0"
|
||||||
mime = "^0.3.16"
|
mime = "^0.3.16"
|
||||||
mime_guess = "^2.0.4"
|
mime_guess = "^2.0.4"
|
||||||
|
open = "3.2.0"
|
||||||
regex = "^1.5"
|
regex = "^1.5"
|
||||||
rpassword = "^7.2"
|
rpassword = "^7.2"
|
||||||
serde = "^1.0"
|
serde = "^1.0"
|
||||||
@@ -36,7 +39,7 @@ unicode-width = "0.1.10"
|
|||||||
url = {version = "^2.2.2", features = ["serde"]}
|
url = {version = "^2.2.2", features = ["serde"]}
|
||||||
|
|
||||||
[dependencies.modalkit]
|
[dependencies.modalkit]
|
||||||
version = "0.0.10"
|
version = "0.0.14"
|
||||||
|
|
||||||
[dependencies.matrix-sdk]
|
[dependencies.matrix-sdk]
|
||||||
version = "0.6"
|
version = "0.6"
|
||||||
@@ -49,3 +52,7 @@ features = ["macros", "net", "rt-multi-thread", "sync", "time"]
|
|||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
lazy_static = "1.4.0"
|
lazy_static = "1.4.0"
|
||||||
|
|
||||||
|
[profile.release]
|
||||||
|
lto = true
|
||||||
|
incremental = false
|
||||||
|
|||||||
36
README.md
36
README.md
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
[](https://github.com/ulyssa/iamb/actions?query=workflow%3ACI+)
|
[](https://github.com/ulyssa/iamb/actions?query=workflow%3ACI+)
|
||||||
[](https://crates.io/crates/iamb)
|
[](https://crates.io/crates/iamb)
|
||||||
|
[](https://matrix.to/#/#iamb:0x.badd.cafe)
|
||||||
[](https://crates.io/crates/iamb)
|
[](https://crates.io/crates/iamb)
|
||||||
|
|
||||||
## About
|
## About
|
||||||
@@ -11,6 +12,8 @@
|
|||||||
This project is a work-in-progress, and there's still a lot to be implemented,
|
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.
|
but much of the basic client functionality is already present.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
|
|
||||||
You can find documentation for installing, configuring, and using iamb on its
|
You can find documentation for installing, configuring, and using iamb on its
|
||||||
@@ -24,6 +27,22 @@ Install Rust and Cargo, and then run:
|
|||||||
cargo install --locked iamb
|
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 is available in the Arch User Repositories (AUR). To install it simply run with your favorite AUR helper:
|
||||||
|
|
||||||
|
```
|
||||||
|
paru iamb-git
|
||||||
|
```
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
|
|
||||||
You can create a basic configuration in `$CONFIG_DIR/iamb/config.json` that looks like:
|
You can create a basic configuration in `$CONFIG_DIR/iamb/config.json` that looks like:
|
||||||
@@ -73,9 +92,9 @@ two other TUI clients and Element Web:
|
|||||||
| Multiple Matrix Accounts | ✔️ | ❌ | ✔️ | ❌ |
|
| Multiple Matrix Accounts | ✔️ | ❌ | ✔️ | ❌ |
|
||||||
| New user registration | ❌ | ❌ | ❌ | ✔️ |
|
| New user registration | ❌ | ❌ | ❌ | ✔️ |
|
||||||
| VOIP | ❌ | ❌ | ❌ | ✔️ |
|
| VOIP | ❌ | ❌ | ❌ | ✔️ |
|
||||||
| Reactions | ❌ ([#2]) | ✔️ | ❌ | ✔️ |
|
| Reactions | ✔️ | ✔️ | ❌ | ✔️ |
|
||||||
| Message editing | ✔️ | ✔️ | ❌ | ✔️ |
|
| Message editing | ✔️ | ✔️ | ❌ | ✔️ |
|
||||||
| Room upgrades | ❌ | ✔️ | ❌ | ✔️ |
|
| Room upgrades | ❌ ([#41]) | ✔️ | ❌ | ✔️ |
|
||||||
| Localisations | ❌ | 1 | ❌ | 44 |
|
| Localisations | ❌ | 1 | ❌ | 44 |
|
||||||
| SSO Support | ❌ | ✔️ | ✔️ | ✔️ |
|
| SSO Support | ❌ | ✔️ | ✔️ | ✔️ |
|
||||||
|
|
||||||
@@ -88,18 +107,7 @@ iamb is released under the [Apache License, Version 2.0].
|
|||||||
[iamb.chat]: https://iamb.chat
|
[iamb.chat]: https://iamb.chat
|
||||||
[gomuks]: https://github.com/tulir/gomuks
|
[gomuks]: https://github.com/tulir/gomuks
|
||||||
[weechat-matrix]: https://github.com/poljar/weechat-matrix
|
[weechat-matrix]: https://github.com/poljar/weechat-matrix
|
||||||
[#2]: https://github.com/ulyssa/iamb/issues/2
|
|
||||||
[#3]: https://github.com/ulyssa/iamb/issues/3
|
|
||||||
[#4]: https://github.com/ulyssa/iamb/issues/4
|
|
||||||
[#5]: https://github.com/ulyssa/iamb/issues/5
|
|
||||||
[#6]: https://github.com/ulyssa/iamb/issues/6
|
|
||||||
[#7]: https://github.com/ulyssa/iamb/issues/7
|
|
||||||
[#8]: https://github.com/ulyssa/iamb/issues/8
|
[#8]: https://github.com/ulyssa/iamb/issues/8
|
||||||
[#9]: https://github.com/ulyssa/iamb/issues/9
|
|
||||||
[#10]: https://github.com/ulyssa/iamb/issues/10
|
|
||||||
[#11]: https://github.com/ulyssa/iamb/issues/11
|
|
||||||
[#12]: https://github.com/ulyssa/iamb/issues/12
|
|
||||||
[#13]: https://github.com/ulyssa/iamb/issues/13
|
|
||||||
[#14]: https://github.com/ulyssa/iamb/issues/14
|
[#14]: https://github.com/ulyssa/iamb/issues/14
|
||||||
[#15]: https://github.com/ulyssa/iamb/issues/15
|
|
||||||
[#16]: https://github.com/ulyssa/iamb/issues/16
|
[#16]: https://github.com/ulyssa/iamb/issues/16
|
||||||
|
[#41]: https://github.com/ulyssa/iamb/issues/41
|
||||||
|
|||||||
459
src/base.rs
459
src/base.rs
@@ -1,23 +1,31 @@
|
|||||||
|
use std::borrow::Cow;
|
||||||
use std::collections::{HashMap, HashSet};
|
use std::collections::{HashMap, HashSet};
|
||||||
use std::hash::Hash;
|
use std::hash::Hash;
|
||||||
|
use std::str::FromStr;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use emojis::Emoji;
|
||||||
use tokio::sync::Mutex as AsyncMutex;
|
use tokio::sync::Mutex as AsyncMutex;
|
||||||
use tracing::warn;
|
|
||||||
|
|
||||||
use matrix_sdk::{
|
use matrix_sdk::{
|
||||||
encryption::verification::SasVerification,
|
encryption::verification::SasVerification,
|
||||||
room::Joined,
|
room::Joined,
|
||||||
ruma::{
|
ruma::{
|
||||||
events::room::message::{
|
events::{
|
||||||
OriginalRoomMessageEvent,
|
reaction::ReactionEvent,
|
||||||
Relation,
|
room::encrypted::RoomEncryptedEvent,
|
||||||
Replacement,
|
room::message::{
|
||||||
RoomMessageEvent,
|
OriginalRoomMessageEvent,
|
||||||
RoomMessageEventContent,
|
Relation,
|
||||||
|
Replacement,
|
||||||
|
RoomMessageEvent,
|
||||||
|
RoomMessageEventContent,
|
||||||
|
},
|
||||||
|
tag::{TagName, Tags},
|
||||||
|
MessageLikeEvent,
|
||||||
},
|
},
|
||||||
events::tag::{TagName, Tags},
|
presence::PresenceState,
|
||||||
EventId,
|
EventId,
|
||||||
OwnedEventId,
|
OwnedEventId,
|
||||||
OwnedRoomId,
|
OwnedRoomId,
|
||||||
@@ -37,11 +45,15 @@ use modalkit::{
|
|||||||
ApplicationStore,
|
ApplicationStore,
|
||||||
ApplicationWindowId,
|
ApplicationWindowId,
|
||||||
},
|
},
|
||||||
|
base::{CommandType, WordStyle},
|
||||||
|
completion::{complete_path, CompletionMap},
|
||||||
context::EditContext,
|
context::EditContext,
|
||||||
|
cursor::Cursor,
|
||||||
|
rope::EditRope,
|
||||||
store::Store,
|
store::Store,
|
||||||
},
|
},
|
||||||
env::vim::{
|
env::vim::{
|
||||||
command::{CommandContext, VimCommand, VimCommandMachine},
|
command::{CommandContext, CommandDescription, VimCommand, VimCommandMachine},
|
||||||
keybindings::VimMachine,
|
keybindings::VimMachine,
|
||||||
VimContext,
|
VimContext,
|
||||||
},
|
},
|
||||||
@@ -61,6 +73,20 @@ use crate::{
|
|||||||
ApplicationSettings,
|
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);
|
const ROOM_FETCH_DEBOUNCE: Duration = Duration::from_secs(2);
|
||||||
|
|
||||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||||
@@ -81,18 +107,63 @@ pub enum MessageAction {
|
|||||||
|
|
||||||
/// Download an attachment to the given path.
|
/// Download an attachment to the given path.
|
||||||
///
|
///
|
||||||
/// The [bool] argument controls whether to overwrite any already existing file at the
|
/// The second argument controls whether to overwrite any already existing file at the
|
||||||
/// destination path.
|
/// destination path, or to open the attachment after downloading.
|
||||||
Download(Option<String>, bool),
|
Download(Option<String>, DownloadFlags),
|
||||||
|
|
||||||
/// Edit a sent message.
|
/// Edit a sent message.
|
||||||
Edit,
|
Edit,
|
||||||
|
|
||||||
/// Redact a message.
|
/// React to a message with an Emoji.
|
||||||
|
React(String),
|
||||||
|
|
||||||
|
/// Redact a message, with an optional reason.
|
||||||
Redact(Option<String>),
|
Redact(Option<String>),
|
||||||
|
|
||||||
/// Reply to a message.
|
/// Reply to a message.
|
||||||
Reply,
|
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)]
|
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||||
@@ -118,8 +189,14 @@ pub enum SendAction {
|
|||||||
Upload(String),
|
Upload(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||||
|
pub enum HomeserverAction {
|
||||||
|
CreateRoom(Option<String>, CreateRoomType, CreateRoomFlags),
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||||
pub enum IambAction {
|
pub enum IambAction {
|
||||||
|
Homeserver(HomeserverAction),
|
||||||
Message(MessageAction),
|
Message(MessageAction),
|
||||||
Room(RoomAction),
|
Room(RoomAction),
|
||||||
Send(SendAction),
|
Send(SendAction),
|
||||||
@@ -128,6 +205,12 @@ pub enum IambAction {
|
|||||||
ToggleScrollbackFocus,
|
ToggleScrollbackFocus,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl From<HomeserverAction> for IambAction {
|
||||||
|
fn from(act: HomeserverAction) -> Self {
|
||||||
|
IambAction::Homeserver(act)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl From<MessageAction> for IambAction {
|
impl From<MessageAction> for IambAction {
|
||||||
fn from(act: MessageAction) -> Self {
|
fn from(act: MessageAction) -> Self {
|
||||||
IambAction::Message(act)
|
IambAction::Message(act)
|
||||||
@@ -149,6 +232,7 @@ impl From<SendAction> for IambAction {
|
|||||||
impl ApplicationAction for IambAction {
|
impl ApplicationAction for IambAction {
|
||||||
fn is_edit_sequence<C: EditContext>(&self, _: &C) -> SequenceStatus {
|
fn is_edit_sequence<C: EditContext>(&self, _: &C) -> SequenceStatus {
|
||||||
match self {
|
match self {
|
||||||
|
IambAction::Homeserver(..) => SequenceStatus::Break,
|
||||||
IambAction::Message(..) => SequenceStatus::Break,
|
IambAction::Message(..) => SequenceStatus::Break,
|
||||||
IambAction::Room(..) => SequenceStatus::Break,
|
IambAction::Room(..) => SequenceStatus::Break,
|
||||||
IambAction::Send(..) => SequenceStatus::Break,
|
IambAction::Send(..) => SequenceStatus::Break,
|
||||||
@@ -160,6 +244,7 @@ impl ApplicationAction for IambAction {
|
|||||||
|
|
||||||
fn is_last_action<C: EditContext>(&self, _: &C) -> SequenceStatus {
|
fn is_last_action<C: EditContext>(&self, _: &C) -> SequenceStatus {
|
||||||
match self {
|
match self {
|
||||||
|
IambAction::Homeserver(..) => SequenceStatus::Atom,
|
||||||
IambAction::Message(..) => SequenceStatus::Atom,
|
IambAction::Message(..) => SequenceStatus::Atom,
|
||||||
IambAction::Room(..) => SequenceStatus::Atom,
|
IambAction::Room(..) => SequenceStatus::Atom,
|
||||||
IambAction::Send(..) => SequenceStatus::Atom,
|
IambAction::Send(..) => SequenceStatus::Atom,
|
||||||
@@ -171,6 +256,7 @@ impl ApplicationAction for IambAction {
|
|||||||
|
|
||||||
fn is_last_selection<C: EditContext>(&self, _: &C) -> SequenceStatus {
|
fn is_last_selection<C: EditContext>(&self, _: &C) -> SequenceStatus {
|
||||||
match self {
|
match self {
|
||||||
|
IambAction::Homeserver(..) => SequenceStatus::Ignore,
|
||||||
IambAction::Message(..) => SequenceStatus::Ignore,
|
IambAction::Message(..) => SequenceStatus::Ignore,
|
||||||
IambAction::Room(..) => SequenceStatus::Ignore,
|
IambAction::Room(..) => SequenceStatus::Ignore,
|
||||||
IambAction::Send(..) => SequenceStatus::Ignore,
|
IambAction::Send(..) => SequenceStatus::Ignore,
|
||||||
@@ -182,6 +268,7 @@ impl ApplicationAction for IambAction {
|
|||||||
|
|
||||||
fn is_switchable<C: EditContext>(&self, _: &C) -> bool {
|
fn is_switchable<C: EditContext>(&self, _: &C) -> bool {
|
||||||
match self {
|
match self {
|
||||||
|
IambAction::Homeserver(..) => false,
|
||||||
IambAction::Message(..) => false,
|
IambAction::Message(..) => false,
|
||||||
IambAction::Room(..) => false,
|
IambAction::Room(..) => false,
|
||||||
IambAction::Send(..) => false,
|
IambAction::Send(..) => false,
|
||||||
@@ -214,6 +301,12 @@ pub type AsyncProgramStore = Arc<AsyncMutex<ProgramStore>>;
|
|||||||
|
|
||||||
pub type IambResult<T> = UIResult<T, IambInfo>;
|
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>>;
|
pub type Receipts = HashMap<OwnedEventId, Vec<OwnedUserId>>;
|
||||||
|
|
||||||
#[derive(thiserror::Error, Debug)]
|
#[derive(thiserror::Error, Debug)]
|
||||||
@@ -280,32 +373,106 @@ pub enum RoomFetchStatus {
|
|||||||
NotStarted,
|
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)]
|
#[derive(Default)]
|
||||||
pub struct RoomInfo {
|
pub struct RoomInfo {
|
||||||
|
/// The display name for this room.
|
||||||
pub name: Option<String>,
|
pub name: Option<String>,
|
||||||
|
|
||||||
|
/// The tags placed on this room.
|
||||||
pub tags: Option<Tags>,
|
pub tags: Option<Tags>,
|
||||||
|
|
||||||
pub keys: HashMap<OwnedEventId, MessageKey>,
|
/// 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,
|
pub messages: Messages,
|
||||||
|
|
||||||
|
/// A map of read markers to display on different events.
|
||||||
pub receipts: HashMap<OwnedEventId, Vec<OwnedUserId>>,
|
pub receipts: HashMap<OwnedEventId, Vec<OwnedUserId>>,
|
||||||
|
|
||||||
|
/// An event ID for where we should indicate we've read up to.
|
||||||
pub read_till: Option<OwnedEventId>,
|
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,
|
pub fetch_id: RoomFetchStatus,
|
||||||
|
|
||||||
|
/// The time that we last fetched scrollback for this room.
|
||||||
pub fetch_last: Option<Instant>,
|
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>)>,
|
pub users_typing: Option<(Instant, Vec<OwnedUserId>)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RoomInfo {
|
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_event(&self, event_id: &EventId) -> Option<&Message> {
|
pub fn get_event(&self, event_id: &EventId) -> Option<&Message> {
|
||||||
self.messages.get(self.keys.get(event_id)?)
|
self.messages.get(self.keys.get(event_id)?.to_message_key()?)
|
||||||
|
}
|
||||||
|
|
||||||
|
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) {
|
pub fn insert_edit(&mut self, msg: Replacement) {
|
||||||
let event_id = msg.event_id;
|
let event_id = msg.event_id;
|
||||||
let new_content = msg.new_content;
|
let new_content = msg.new_content;
|
||||||
|
|
||||||
let key = if let Some(k) = self.keys.get(&event_id) {
|
let key = if let Some(EventLocation::Message(k)) = self.keys.get(&event_id) {
|
||||||
k
|
k
|
||||||
} else {
|
} else {
|
||||||
return;
|
return;
|
||||||
@@ -324,17 +491,30 @@ impl RoomInfo {
|
|||||||
MessageEvent::Local(_, content) => {
|
MessageEvent::Local(_, content) => {
|
||||||
*content = new_content;
|
*content = new_content;
|
||||||
},
|
},
|
||||||
MessageEvent::Redacted(_) => {
|
MessageEvent::Redacted(_) |
|
||||||
|
MessageEvent::EncryptedOriginal(_) |
|
||||||
|
MessageEvent::EncryptedRedacted(_) => {
|
||||||
return;
|
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) {
|
pub fn insert_message(&mut self, msg: RoomMessageEvent) {
|
||||||
let event_id = msg.event_id().to_owned();
|
let event_id = msg.event_id().to_owned();
|
||||||
let key = (msg.origin_server_ts().into(), event_id.clone());
|
let key = (msg.origin_server_ts().into(), event_id.clone());
|
||||||
|
|
||||||
self.keys.insert(event_id.clone(), key.clone());
|
self.keys.insert(event_id.clone(), EventLocation::Message(key.clone()));
|
||||||
self.messages.insert(key, msg.into());
|
self.messages.insert(key, msg.into());
|
||||||
|
|
||||||
// Remove any echo.
|
// Remove any echo.
|
||||||
@@ -353,7 +533,7 @@ impl RoomInfo {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn recently_fetched(&self) -> bool {
|
pub fn recently_fetched(&self) -> bool {
|
||||||
self.fetch_last.map_or(false, |i| i.elapsed() < ROOM_FETCH_DEBOUNCE)
|
self.fetch_last.map_or(false, |i| i.elapsed() < ROOM_FETCH_DEBOUNCE)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -425,13 +605,28 @@ impl RoomInfo {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
pub struct ChatStore {
|
pub struct ChatStore {
|
||||||
|
pub cmds: ProgramCommands,
|
||||||
pub worker: Requester,
|
pub worker: Requester,
|
||||||
pub rooms: HashMap<OwnedRoomId, RoomInfo>,
|
pub rooms: CompletionMap<OwnedRoomId, RoomInfo>,
|
||||||
pub names: HashMap<String, OwnedRoomId>,
|
pub names: CompletionMap<String, OwnedRoomId>,
|
||||||
|
pub presences: CompletionMap<OwnedUserId, PresenceState>,
|
||||||
pub verifications: HashMap<String, SasVerification>,
|
pub verifications: HashMap<String, SasVerification>,
|
||||||
pub settings: ApplicationSettings,
|
pub settings: ApplicationSettings,
|
||||||
pub need_load: HashSet<OwnedRoomId>,
|
pub need_load: HashSet<OwnedRoomId>,
|
||||||
|
pub emojis: CompletionMap<String, &'static Emoji>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ChatStore {
|
impl ChatStore {
|
||||||
@@ -440,10 +635,13 @@ impl ChatStore {
|
|||||||
worker,
|
worker,
|
||||||
settings,
|
settings,
|
||||||
|
|
||||||
|
cmds: crate::commands::setup_commands(),
|
||||||
names: Default::default(),
|
names: Default::default(),
|
||||||
rooms: Default::default(),
|
rooms: Default::default(),
|
||||||
|
presences: Default::default(),
|
||||||
verifications: Default::default(),
|
verifications: Default::default(),
|
||||||
need_load: Default::default(),
|
need_load: Default::default(),
|
||||||
|
emojis: emoji_map(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -483,56 +681,12 @@ impl ChatStore {
|
|||||||
self.need_load.insert(room_id);
|
self.need_load.insert(room_id);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn load_older(&mut self, limit: u32) {
|
|
||||||
let ChatStore { need_load, rooms, worker, .. } = self;
|
|
||||||
|
|
||||||
for room_id in std::mem::take(need_load).into_iter() {
|
|
||||||
let info = rooms.entry(room_id.clone()).or_default();
|
|
||||||
|
|
||||||
if info.recently_fetched() {
|
|
||||||
need_load.insert(room_id);
|
|
||||||
continue;
|
|
||||||
} else {
|
|
||||||
info.fetch_last = Instant::now().into();
|
|
||||||
}
|
|
||||||
|
|
||||||
let fetch_id = match &info.fetch_id {
|
|
||||||
RoomFetchStatus::Done => continue,
|
|
||||||
RoomFetchStatus::HaveMore(fetch_id) => Some(fetch_id.clone()),
|
|
||||||
RoomFetchStatus::NotStarted => None,
|
|
||||||
};
|
|
||||||
|
|
||||||
let res = worker.load_older(room_id.clone(), fetch_id, limit);
|
|
||||||
|
|
||||||
match res {
|
|
||||||
Ok((fetch_id, msgs)) => {
|
|
||||||
for msg in msgs.into_iter() {
|
|
||||||
info.insert(msg);
|
|
||||||
}
|
|
||||||
|
|
||||||
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);
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_room_info(&mut self, room_id: OwnedRoomId) -> &mut RoomInfo {
|
pub fn get_room_info(&mut self, room_id: OwnedRoomId) -> &mut RoomInfo {
|
||||||
self.rooms.entry(room_id).or_default()
|
self.rooms.get_or_default(room_id)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn set_room_name(&mut self, room_id: &RoomId, name: &str) {
|
pub fn set_room_name(&mut self, room_id: &RoomId, name: &str) {
|
||||||
self.rooms.entry(room_id.to_owned()).or_default().name = name.to_string().into();
|
self.rooms.get_or_default(room_id.to_owned()).name = name.to_string().into();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn insert_sas(&mut self, sas: SasVerification) {
|
pub fn insert_sas(&mut self, sas: SasVerification) {
|
||||||
@@ -575,7 +729,7 @@ impl RoomFocus {
|
|||||||
|
|
||||||
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
|
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
|
||||||
pub enum IambBufferId {
|
pub enum IambBufferId {
|
||||||
Command,
|
Command(CommandType),
|
||||||
Room(OwnedRoomId, RoomFocus),
|
Room(OwnedRoomId, RoomFocus),
|
||||||
DirectList,
|
DirectList,
|
||||||
MemberList(OwnedRoomId),
|
MemberList(OwnedRoomId),
|
||||||
@@ -588,7 +742,7 @@ pub enum IambBufferId {
|
|||||||
impl IambBufferId {
|
impl IambBufferId {
|
||||||
pub fn to_window(&self) -> Option<IambId> {
|
pub fn to_window(&self) -> Option<IambId> {
|
||||||
match self {
|
match self {
|
||||||
IambBufferId::Command => None,
|
IambBufferId::Command(_) => None,
|
||||||
IambBufferId::Room(room, _) => Some(IambId::Room(room.clone())),
|
IambBufferId::Room(room, _) => Some(IambId::Room(room.clone())),
|
||||||
IambBufferId::DirectList => Some(IambId::DirectList),
|
IambBufferId::DirectList => Some(IambId::DirectList),
|
||||||
IambBufferId::MemberList(room) => Some(IambId::MemberList(room.clone())),
|
IambBufferId::MemberList(room) => Some(IambId::MemberList(room.clone())),
|
||||||
@@ -608,6 +762,133 @@ impl ApplicationInfo for IambInfo {
|
|||||||
type Action = IambAction;
|
type Action = IambAction;
|
||||||
type WindowId = IambId;
|
type WindowId = IambId;
|
||||||
type ContentId = IambBufferId;
|
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_matrix_names(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_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_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" => complete_matrix_names(text, cursor, store),
|
||||||
|
"room" => vec![],
|
||||||
|
"verify" => vec![],
|
||||||
|
_ => panic!("unknown command {}", cmd.name.as_str()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
|
||||||
|
match CommandDescription::from_str(cow.as_ref()) {
|
||||||
|
Ok(desc) => {
|
||||||
|
if desc.arg.untrimmed.is_empty() {
|
||||||
|
// 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())
|
||||||
|
} else {
|
||||||
|
// Complete command argument.
|
||||||
|
complete_cmdarg(desc, text, cursor, store)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
// Can't parse command text, so return zero completions.
|
||||||
|
Err(_) => vec![],
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@@ -693,4 +974,44 @@ pub mod tests {
|
|||||||
])
|
])
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_complete_cmdbar() {
|
||||||
|
let store = mock_store().await;
|
||||||
|
|
||||||
|
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, vec![
|
||||||
|
"@user1:example.com",
|
||||||
|
"@user2:example.com",
|
||||||
|
"@user3:example.com",
|
||||||
|
"@user4:example.com",
|
||||||
|
"@user5:example.com"
|
||||||
|
]);
|
||||||
|
|
||||||
|
let text = EditRope::from("invite ignored");
|
||||||
|
let mut cursor = Cursor::new(0, 7);
|
||||||
|
let res = complete_cmdbar(&text, &mut cursor, &store);
|
||||||
|
assert_eq!(res, vec![
|
||||||
|
"@user1:example.com",
|
||||||
|
"@user2:example.com",
|
||||||
|
"@user3:example.com",
|
||||||
|
"@user4:example.com",
|
||||||
|
"@user5:example.com"
|
||||||
|
]);
|
||||||
|
|
||||||
|
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"]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
224
src/commands.rs
224
src/commands.rs
@@ -4,12 +4,16 @@ use matrix_sdk::ruma::{events::tag::TagName, OwnedUserId};
|
|||||||
|
|
||||||
use modalkit::{
|
use modalkit::{
|
||||||
editing::base::OpenTarget,
|
editing::base::OpenTarget,
|
||||||
env::vim::command::{CommandContext, CommandDescription},
|
env::vim::command::{CommandContext, CommandDescription, OptionType},
|
||||||
input::commands::{CommandError, CommandResult, CommandStep},
|
input::commands::{CommandError, CommandResult, CommandStep},
|
||||||
input::InputContext,
|
input::InputContext,
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::base::{
|
use crate::base::{
|
||||||
|
CreateRoomFlags,
|
||||||
|
CreateRoomType,
|
||||||
|
DownloadFlags,
|
||||||
|
HomeserverAction,
|
||||||
IambAction,
|
IambAction,
|
||||||
IambId,
|
IambId,
|
||||||
MessageAction,
|
MessageAction,
|
||||||
@@ -39,7 +43,7 @@ fn tag_name(name: String) -> Result<TagName, CommandError> {
|
|||||||
if let Ok(tag) = name.parse() {
|
if let Ok(tag) = name.parse() {
|
||||||
TagName::User(tag)
|
TagName::User(tag)
|
||||||
} else {
|
} else {
|
||||||
let msg = format!("Invalid user tag name: {}", name);
|
let msg = format!("Invalid user tag name: {name}");
|
||||||
|
|
||||||
return Err(CommandError::Error(msg));
|
return Err(CommandError::Error(msg));
|
||||||
}
|
}
|
||||||
@@ -162,8 +166,8 @@ fn iamb_cancel(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
|
|||||||
return Result::Err(CommandError::InvalidArgument);
|
return Result::Err(CommandError::InvalidArgument);
|
||||||
}
|
}
|
||||||
|
|
||||||
let ract = IambAction::from(MessageAction::Cancel);
|
let mact = IambAction::from(MessageAction::Cancel);
|
||||||
let step = CommandStep::Continue(ract.into(), ctx.context.take());
|
let step = CommandStep::Continue(mact.into(), ctx.context.take());
|
||||||
|
|
||||||
return Ok(step);
|
return Ok(step);
|
||||||
}
|
}
|
||||||
@@ -173,8 +177,55 @@ fn iamb_edit(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
|
|||||||
return Result::Err(CommandError::InvalidArgument);
|
return Result::Err(CommandError::InvalidArgument);
|
||||||
}
|
}
|
||||||
|
|
||||||
let ract = IambAction::from(MessageAction::Edit);
|
let mact = IambAction::from(MessageAction::Edit);
|
||||||
let step = CommandStep::Continue(ract.into(), ctx.context.take());
|
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);
|
return Ok(step);
|
||||||
}
|
}
|
||||||
@@ -249,6 +300,53 @@ fn iamb_join(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
|
|||||||
return Ok(step);
|
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 {
|
fn iamb_room(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult {
|
||||||
let mut args = desc.arg.strings()?;
|
let mut args = desc.arg.strings()?;
|
||||||
|
|
||||||
@@ -317,7 +415,29 @@ fn iamb_download(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult
|
|||||||
return Result::Err(CommandError::InvalidArgument);
|
return Result::Err(CommandError::InvalidArgument);
|
||||||
}
|
}
|
||||||
|
|
||||||
let mact = MessageAction::Download(args.pop(), desc.bang);
|
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 iact = IambAction::from(mact);
|
||||||
let step = CommandStep::Continue(iact.into(), ctx.context.take());
|
let step = CommandStep::Continue(iact.into(), ctx.context.take());
|
||||||
|
|
||||||
@@ -325,21 +445,81 @@ fn iamb_download(desc: CommandDescription, ctx: &mut ProgContext) -> ProgResult
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn add_iamb_commands(cmds: &mut ProgramCommands) {
|
fn add_iamb_commands(cmds: &mut ProgramCommands) {
|
||||||
cmds.add_command(ProgramCommand { names: vec!["cancel".into()], f: iamb_cancel });
|
cmds.add_command(ProgramCommand {
|
||||||
cmds.add_command(ProgramCommand { names: vec!["dms".into()], f: iamb_dms });
|
name: "cancel".into(),
|
||||||
cmds.add_command(ProgramCommand { names: vec!["download".into()], f: iamb_download });
|
aliases: vec![],
|
||||||
cmds.add_command(ProgramCommand { names: vec!["edit".into()], f: iamb_edit });
|
f: iamb_cancel,
|
||||||
cmds.add_command(ProgramCommand { names: vec!["invite".into()], f: iamb_invite });
|
});
|
||||||
cmds.add_command(ProgramCommand { names: vec!["join".into()], f: iamb_join });
|
cmds.add_command(ProgramCommand {
|
||||||
cmds.add_command(ProgramCommand { names: vec!["members".into()], f: iamb_members });
|
name: "create".into(),
|
||||||
cmds.add_command(ProgramCommand { names: vec!["redact".into()], f: iamb_redact });
|
aliases: vec![],
|
||||||
cmds.add_command(ProgramCommand { names: vec!["reply".into()], f: iamb_reply });
|
f: iamb_create,
|
||||||
cmds.add_command(ProgramCommand { names: vec!["rooms".into()], f: iamb_rooms });
|
});
|
||||||
cmds.add_command(ProgramCommand { names: vec!["room".into()], f: iamb_room });
|
cmds.add_command(ProgramCommand { name: "dms".into(), aliases: vec![], f: iamb_dms });
|
||||||
cmds.add_command(ProgramCommand { names: vec!["spaces".into()], f: iamb_spaces });
|
cmds.add_command(ProgramCommand {
|
||||||
cmds.add_command(ProgramCommand { names: vec!["upload".into()], f: iamb_upload });
|
name: "download".into(),
|
||||||
cmds.add_command(ProgramCommand { names: vec!["verify".into()], f: iamb_verify });
|
aliases: vec![],
|
||||||
cmds.add_command(ProgramCommand { names: vec!["welcome".into()], f: iamb_welcome });
|
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: "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 {
|
pub fn setup_commands() -> ProgramCommands {
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ use std::process;
|
|||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use matrix_sdk::ruma::{OwnedUserId, UserId};
|
use matrix_sdk::ruma::{OwnedUserId, UserId};
|
||||||
use serde::{de::Error as SerdeError, de::Visitor, Deserialize, Deserializer};
|
use serde::{de::Error as SerdeError, de::Visitor, Deserialize, Deserializer};
|
||||||
|
use tracing::Level;
|
||||||
use url::Url;
|
use url::Url;
|
||||||
|
|
||||||
use modalkit::tui::{
|
use modalkit::tui::{
|
||||||
@@ -25,6 +26,8 @@ macro_rules! usage {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const DEFAULT_REQ_TIMEOUT: u64 = 120;
|
||||||
|
|
||||||
const COLORS: [Color; 13] = [
|
const COLORS: [Color; 13] = [
|
||||||
Color::Blue,
|
Color::Blue,
|
||||||
Color::Cyan,
|
Color::Cyan,
|
||||||
@@ -106,6 +109,47 @@ pub enum ConfigError {
|
|||||||
Invalid(#[from] serde_json::Error),
|
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)]
|
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||||
pub struct UserColor(pub Color);
|
pub struct UserColor(pub Color);
|
||||||
pub struct UserColorVisitor;
|
pub struct UserColorVisitor;
|
||||||
@@ -178,8 +222,12 @@ fn merge_users(a: Option<UserOverrides>, b: Option<UserOverrides>) -> Option<Use
|
|||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct TunableValues {
|
pub struct TunableValues {
|
||||||
|
pub log_level: Level,
|
||||||
|
pub reaction_display: bool,
|
||||||
|
pub reaction_shortcode_display: bool,
|
||||||
pub read_receipt_send: bool,
|
pub read_receipt_send: bool,
|
||||||
pub read_receipt_display: bool,
|
pub read_receipt_display: bool,
|
||||||
|
pub request_timeout: u64,
|
||||||
pub typing_notice_send: bool,
|
pub typing_notice_send: bool,
|
||||||
pub typing_notice_display: bool,
|
pub typing_notice_display: bool,
|
||||||
pub users: UserOverrides,
|
pub users: UserOverrides,
|
||||||
@@ -188,8 +236,12 @@ pub struct TunableValues {
|
|||||||
|
|
||||||
#[derive(Clone, Default, Deserialize)]
|
#[derive(Clone, Default, Deserialize)]
|
||||||
pub struct Tunables {
|
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_send: Option<bool>,
|
||||||
pub read_receipt_display: Option<bool>,
|
pub read_receipt_display: Option<bool>,
|
||||||
|
pub request_timeout: Option<u64>,
|
||||||
pub typing_notice_send: Option<bool>,
|
pub typing_notice_send: Option<bool>,
|
||||||
pub typing_notice_display: Option<bool>,
|
pub typing_notice_display: Option<bool>,
|
||||||
pub users: Option<UserOverrides>,
|
pub users: Option<UserOverrides>,
|
||||||
@@ -199,8 +251,14 @@ pub struct Tunables {
|
|||||||
impl Tunables {
|
impl Tunables {
|
||||||
fn merge(self, other: Self) -> Self {
|
fn merge(self, other: Self) -> Self {
|
||||||
Tunables {
|
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_send: self.read_receipt_send.or(other.read_receipt_send),
|
||||||
read_receipt_display: self.read_receipt_display.or(other.read_receipt_display),
|
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_send: self.typing_notice_send.or(other.typing_notice_send),
|
||||||
typing_notice_display: self.typing_notice_display.or(other.typing_notice_display),
|
typing_notice_display: self.typing_notice_display.or(other.typing_notice_display),
|
||||||
users: merge_users(self.users, other.users),
|
users: merge_users(self.users, other.users),
|
||||||
@@ -210,8 +268,12 @@ impl Tunables {
|
|||||||
|
|
||||||
fn values(self) -> TunableValues {
|
fn values(self) -> TunableValues {
|
||||||
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_send: self.read_receipt_send.unwrap_or(true),
|
||||||
read_receipt_display: self.read_receipt_display.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_send: self.typing_notice_send.unwrap_or(true),
|
||||||
typing_notice_display: self.typing_notice_display.unwrap_or(true),
|
typing_notice_display: self.typing_notice_display.unwrap_or(true),
|
||||||
users: self.users.unwrap_or_default(),
|
users: self.users.unwrap_or_default(),
|
||||||
|
|||||||
@@ -1,32 +1,21 @@
|
|||||||
use modalkit::{
|
use modalkit::{
|
||||||
editing::action::WindowAction,
|
editing::action::WindowAction,
|
||||||
editing::base::WordStyle,
|
|
||||||
env::vim::keybindings::{InputStep, VimBindings},
|
env::vim::keybindings::{InputStep, VimBindings},
|
||||||
env::vim::VimMode,
|
env::vim::VimMode,
|
||||||
input::bindings::{EdgeEvent, EdgeRepeat, InputBindings},
|
input::bindings::{EdgeEvent, EdgeRepeat, InputBindings},
|
||||||
input::key::TerminalKey,
|
input::key::TerminalKey,
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::base::{IambAction, Keybindings};
|
use crate::base::{IambAction, IambInfo, Keybindings, MATRIX_ID_WORD};
|
||||||
|
|
||||||
/// Find the boundaries for a Matrix username, room alias, or room ID.
|
type IambStep = InputStep<IambInfo>;
|
||||||
///
|
|
||||||
/// 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);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn setup_keybindings() -> Keybindings {
|
pub fn setup_keybindings() -> Keybindings {
|
||||||
let mut ism = Keybindings::empty();
|
let mut ism = Keybindings::empty();
|
||||||
|
|
||||||
let vim = VimBindings::default()
|
let vim = VimBindings::default()
|
||||||
.submit_on_enter()
|
.submit_on_enter()
|
||||||
.cursor_open(WordStyle::CharSet(is_mxid_char));
|
.cursor_open(MATRIX_ID_WORD.clone());
|
||||||
|
|
||||||
vim.setup(&mut ism);
|
vim.setup(&mut ism);
|
||||||
|
|
||||||
@@ -44,19 +33,27 @@ pub fn setup_keybindings() -> Keybindings {
|
|||||||
(EdgeRepeat::Once, ctrl_w.clone()),
|
(EdgeRepeat::Once, ctrl_w.clone()),
|
||||||
(EdgeRepeat::Once, ctrl_z),
|
(EdgeRepeat::Once, ctrl_z),
|
||||||
];
|
];
|
||||||
let zoom = InputStep::new().actions(vec![WindowAction::ZoomToggle.into()]);
|
let zoom = IambStep::new()
|
||||||
|
.actions(vec![WindowAction::ZoomToggle.into()])
|
||||||
|
.goto(VimMode::Normal);
|
||||||
|
|
||||||
ism.add_mapping(VimMode::Normal, &cwz, &zoom);
|
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::Normal, &cwcz, &zoom);
|
||||||
|
ism.add_mapping(VimMode::Visual, &cwcz, &zoom);
|
||||||
|
|
||||||
let cwm = vec![
|
let cwm = vec![
|
||||||
(EdgeRepeat::Once, ctrl_w.clone()),
|
(EdgeRepeat::Once, ctrl_w.clone()),
|
||||||
(EdgeRepeat::Once, key_m_lc),
|
(EdgeRepeat::Once, key_m_lc),
|
||||||
];
|
];
|
||||||
let cwcm = vec![(EdgeRepeat::Once, ctrl_w), (EdgeRepeat::Once, ctrl_m)];
|
let cwcm = vec![(EdgeRepeat::Once, ctrl_w), (EdgeRepeat::Once, ctrl_m)];
|
||||||
let stoggle = InputStep::new().actions(vec![IambAction::ToggleScrollbackFocus.into()]);
|
let stoggle = IambStep::new()
|
||||||
|
.actions(vec![IambAction::ToggleScrollbackFocus.into()])
|
||||||
|
.goto(VimMode::Normal);
|
||||||
ism.add_mapping(VimMode::Normal, &cwm, &stoggle);
|
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::Normal, &cwcm, &stoggle);
|
||||||
|
ism.add_mapping(VimMode::Visual, &cwcm, &stoggle);
|
||||||
|
|
||||||
return ism;
|
return ism;
|
||||||
}
|
}
|
||||||
|
|||||||
83
src/main.rs
83
src/main.rs
@@ -15,7 +15,6 @@ use std::time::Duration;
|
|||||||
|
|
||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use tokio::sync::Mutex as AsyncMutex;
|
use tokio::sync::Mutex as AsyncMutex;
|
||||||
use tracing::{self, Level};
|
|
||||||
use tracing_subscriber::FmtSubscriber;
|
use tracing_subscriber::FmtSubscriber;
|
||||||
|
|
||||||
use matrix_sdk::ruma::OwnedUserId;
|
use matrix_sdk::ruma::OwnedUserId;
|
||||||
@@ -23,7 +22,7 @@ use matrix_sdk::ruma::OwnedUserId;
|
|||||||
use modalkit::crossterm::{
|
use modalkit::crossterm::{
|
||||||
self,
|
self,
|
||||||
cursor::Show as CursorShow,
|
cursor::Show as CursorShow,
|
||||||
event::{poll, read, Event},
|
event::{poll, read, DisableBracketedPaste, EnableBracketedPaste, Event},
|
||||||
execute,
|
execute,
|
||||||
terminal::{EnterAlternateScreen, LeaveAlternateScreen, SetTitle},
|
terminal::{EnterAlternateScreen, LeaveAlternateScreen, SetTitle},
|
||||||
};
|
};
|
||||||
@@ -53,20 +52,19 @@ use crate::{
|
|||||||
base::{
|
base::{
|
||||||
AsyncProgramStore,
|
AsyncProgramStore,
|
||||||
ChatStore,
|
ChatStore,
|
||||||
|
HomeserverAction,
|
||||||
IambAction,
|
IambAction,
|
||||||
IambBufferId,
|
|
||||||
IambError,
|
IambError,
|
||||||
IambId,
|
IambId,
|
||||||
IambInfo,
|
IambInfo,
|
||||||
IambResult,
|
IambResult,
|
||||||
ProgramAction,
|
ProgramAction,
|
||||||
ProgramCommands,
|
|
||||||
ProgramContext,
|
ProgramContext,
|
||||||
ProgramStore,
|
ProgramStore,
|
||||||
},
|
},
|
||||||
config::{ApplicationSettings, Iamb},
|
config::{ApplicationSettings, Iamb},
|
||||||
windows::IambWindow,
|
windows::IambWindow,
|
||||||
worker::{ClientWorker, LoginStyle, Requester},
|
worker::{create_room, ClientWorker, LoginStyle, Requester},
|
||||||
};
|
};
|
||||||
|
|
||||||
use modalkit::{
|
use modalkit::{
|
||||||
@@ -77,6 +75,8 @@ use modalkit::{
|
|||||||
EditError,
|
EditError,
|
||||||
EditInfo,
|
EditInfo,
|
||||||
Editable,
|
Editable,
|
||||||
|
EditorAction,
|
||||||
|
InsertTextAction,
|
||||||
Jumpable,
|
Jumpable,
|
||||||
Promptable,
|
Promptable,
|
||||||
Scrollable,
|
Scrollable,
|
||||||
@@ -85,7 +85,7 @@ use modalkit::{
|
|||||||
WindowAction,
|
WindowAction,
|
||||||
WindowContainer,
|
WindowContainer,
|
||||||
},
|
},
|
||||||
base::{OpenTarget, RepeatType},
|
base::{MoveDir1D, OpenTarget, RepeatType},
|
||||||
context::Resolve,
|
context::Resolve,
|
||||||
key::KeyManager,
|
key::KeyManager,
|
||||||
store::Store,
|
store::Store,
|
||||||
@@ -100,21 +100,12 @@ use modalkit::{
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const MIN_MSG_LOAD: u32 = 50;
|
|
||||||
|
|
||||||
fn msg_load_req(area: Rect) -> u32 {
|
|
||||||
let n = area.height as u32;
|
|
||||||
|
|
||||||
n.max(MIN_MSG_LOAD)
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Application {
|
struct Application {
|
||||||
store: AsyncProgramStore,
|
store: AsyncProgramStore,
|
||||||
worker: Requester,
|
worker: Requester,
|
||||||
terminal: Terminal<CrosstermBackend<Stdout>>,
|
terminal: Terminal<CrosstermBackend<Stdout>>,
|
||||||
bindings: KeyManager<TerminalKey, ProgramAction, RepeatType, ProgramContext>,
|
bindings: KeyManager<TerminalKey, ProgramAction, RepeatType, ProgramContext>,
|
||||||
actstack: VecDeque<(ProgramAction, ProgramContext)>,
|
actstack: VecDeque<(ProgramAction, ProgramContext)>,
|
||||||
cmds: ProgramCommands,
|
|
||||||
screen: ScreenState<IambWindow, IambInfo>,
|
screen: ScreenState<IambWindow, IambInfo>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -126,6 +117,7 @@ impl Application {
|
|||||||
let mut stdout = stdout();
|
let mut stdout = stdout();
|
||||||
crossterm::terminal::enable_raw_mode()?;
|
crossterm::terminal::enable_raw_mode()?;
|
||||||
crossterm::execute!(stdout, EnterAlternateScreen)?;
|
crossterm::execute!(stdout, EnterAlternateScreen)?;
|
||||||
|
crossterm::execute!(stdout, EnableBracketedPaste)?;
|
||||||
|
|
||||||
let title = format!("iamb ({})", settings.profile.user_id);
|
let title = format!("iamb ({})", settings.profile.user_id);
|
||||||
crossterm::execute!(stdout, SetTitle(title))?;
|
crossterm::execute!(stdout, SetTitle(title))?;
|
||||||
@@ -135,7 +127,6 @@ impl Application {
|
|||||||
|
|
||||||
let bindings = crate::keybindings::setup_keybindings();
|
let bindings = crate::keybindings::setup_keybindings();
|
||||||
let bindings = KeyManager::new(bindings);
|
let bindings = KeyManager::new(bindings);
|
||||||
let cmds = crate::commands::setup_commands();
|
|
||||||
|
|
||||||
let mut locked = store.lock().await;
|
let mut locked = store.lock().await;
|
||||||
|
|
||||||
@@ -146,7 +137,7 @@ impl Application {
|
|||||||
.or_else(|| IambWindow::open(IambId::Welcome, locked.deref_mut()).ok())
|
.or_else(|| IambWindow::open(IambId::Welcome, locked.deref_mut()).ok())
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
let cmd = CommandBarState::new(IambBufferId::Command, locked.deref_mut());
|
let cmd = CommandBarState::new(locked.deref_mut());
|
||||||
let screen = ScreenState::new(win, cmd);
|
let screen = ScreenState::new(win, cmd);
|
||||||
|
|
||||||
let worker = locked.application.worker.clone();
|
let worker = locked.application.worker.clone();
|
||||||
@@ -160,7 +151,6 @@ impl Application {
|
|||||||
terminal,
|
terminal,
|
||||||
bindings,
|
bindings,
|
||||||
actstack,
|
actstack,
|
||||||
cmds,
|
|
||||||
screen,
|
screen,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -191,8 +181,6 @@ impl Application {
|
|||||||
}
|
}
|
||||||
f.set_cursor(cx, cy);
|
f.set_cursor(cx, cy);
|
||||||
}
|
}
|
||||||
|
|
||||||
store.application.load_older(msg_load_req(area));
|
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -218,8 +206,21 @@ impl Application {
|
|||||||
Event::Resize(_, _) => {
|
Event::Resize(_, _) => {
|
||||||
// We'll redraw for the new size next time step() is called.
|
// We'll redraw for the new size next time step() is called.
|
||||||
},
|
},
|
||||||
Event::Paste(_) => {
|
Event::Paste(s) => {
|
||||||
// Do nothing for now.
|
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)) => {
|
||||||
|
self.screen.push_info(info);
|
||||||
|
},
|
||||||
|
Err(e) => {
|
||||||
|
self.screen.push_error(e);
|
||||||
|
},
|
||||||
|
}
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -305,7 +306,7 @@ impl Application {
|
|||||||
None
|
None
|
||||||
},
|
},
|
||||||
Action::Command(act) => {
|
Action::Command(act) => {
|
||||||
let acts = self.cmds.command(&act, &ctx)?;
|
let acts = store.application.cmds.command(&act, &ctx)?;
|
||||||
self.action_prepend(acts);
|
self.action_prepend(acts);
|
||||||
|
|
||||||
None
|
None
|
||||||
@@ -344,6 +345,12 @@ impl Application {
|
|||||||
None
|
None
|
||||||
},
|
},
|
||||||
|
|
||||||
|
IambAction::Homeserver(act) => {
|
||||||
|
let acts = self.homeserver_command(act, ctx, store).await?;
|
||||||
|
self.action_prepend(acts);
|
||||||
|
|
||||||
|
None
|
||||||
|
},
|
||||||
IambAction::Message(act) => {
|
IambAction::Message(act) => {
|
||||||
self.screen.current_window_mut()?.message_command(act, ctx, store).await?
|
self.screen.current_window_mut()?.message_command(act, ctx, store).await?
|
||||||
},
|
},
|
||||||
@@ -376,6 +383,25 @@ impl Application {
|
|||||||
Ok(info)
|
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)])
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn run(&mut self) -> Result<(), std::io::Error> {
|
pub async fn run(&mut self) -> Result<(), std::io::Error> {
|
||||||
self.terminal.clear()?;
|
self.terminal.clear()?;
|
||||||
|
|
||||||
@@ -439,13 +465,13 @@ async fn login(worker: Requester, settings: &ApplicationSettings) -> IambResult<
|
|||||||
match worker.login(LoginStyle::Password(password)) {
|
match worker.login(LoginStyle::Password(password)) {
|
||||||
Ok(info) => {
|
Ok(info) => {
|
||||||
if let Some(msg) = info {
|
if let Some(msg) = info {
|
||||||
println!("{}", msg);
|
println!("{msg}");
|
||||||
}
|
}
|
||||||
|
|
||||||
break;
|
break;
|
||||||
},
|
},
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
println!("Failed to login: {}", err);
|
println!("Failed to login: {err}");
|
||||||
continue;
|
continue;
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -455,7 +481,7 @@ async fn login(worker: Requester, settings: &ApplicationSettings) -> IambResult<
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn print_exit<T: Display, N>(v: T) -> N {
|
fn print_exit<T: Display, N>(v: T) -> N {
|
||||||
println!("{}", v);
|
println!("{v}");
|
||||||
process::exit(2);
|
process::exit(2);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -473,6 +499,7 @@ async fn run(settings: ApplicationSettings) -> IambResult<()> {
|
|||||||
let orig_hook = std::panic::take_hook();
|
let orig_hook = std::panic::take_hook();
|
||||||
std::panic::set_hook(Box::new(move |panic_info| {
|
std::panic::set_hook(Box::new(move |panic_info| {
|
||||||
let _ = crossterm::terminal::disable_raw_mode();
|
let _ = crossterm::terminal::disable_raw_mode();
|
||||||
|
let _ = crossterm::execute!(stdout(), DisableBracketedPaste);
|
||||||
let _ = crossterm::execute!(stdout(), LeaveAlternateScreen);
|
let _ = crossterm::execute!(stdout(), LeaveAlternateScreen);
|
||||||
let _ = crossterm::execute!(stdout(), CursorShow);
|
let _ = crossterm::execute!(stdout(), CursorShow);
|
||||||
orig_hook(panic_info);
|
orig_hook(panic_info);
|
||||||
@@ -506,7 +533,7 @@ fn main() -> IambResult<()> {
|
|||||||
|
|
||||||
let subscriber = FmtSubscriber::builder()
|
let subscriber = FmtSubscriber::builder()
|
||||||
.with_writer(appender)
|
.with_writer(appender)
|
||||||
.with_max_level(Level::TRACE)
|
.with_max_level(settings.tunables.log_level)
|
||||||
.finish();
|
.finish();
|
||||||
tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");
|
tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");
|
||||||
|
|
||||||
@@ -515,7 +542,7 @@ fn main() -> IambResult<()> {
|
|||||||
.thread_name_fn(|| {
|
.thread_name_fn(|| {
|
||||||
static ATOMIC_ID: AtomicUsize = AtomicUsize::new(0);
|
static ATOMIC_ID: AtomicUsize = AtomicUsize::new(0);
|
||||||
let id = ATOMIC_ID.fetch_add(1, Ordering::SeqCst);
|
let id = ATOMIC_ID.fetch_add(1, Ordering::SeqCst);
|
||||||
format!("iamb-worker-{}", id)
|
format!("iamb-worker-{id}")
|
||||||
})
|
})
|
||||||
.build()
|
.build()
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
//! The Matrix specification recommends limiting rendered tags and attributes to a safe subset of
|
//! 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":
|
//! 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
|
//! <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
|
//! 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.
|
//! input onto an enum of the safe list of tags to keep it easy to understand and process.
|
||||||
@@ -271,10 +271,12 @@ impl StyleTreeNode {
|
|||||||
},
|
},
|
||||||
StyleTreeNode::Header(child, level) => {
|
StyleTreeNode::Header(child, level) => {
|
||||||
let style = style.add_modifier(StyleModifier::BOLD);
|
let style = style.add_modifier(StyleModifier::BOLD);
|
||||||
let mut hashes = "#".repeat(*level);
|
|
||||||
hashes.push(' ');
|
|
||||||
|
|
||||||
printer.push_str(hashes, style);
|
for _ in 0..*level {
|
||||||
|
printer.push_str("#", style);
|
||||||
|
}
|
||||||
|
|
||||||
|
printer.push_str(" ", style);
|
||||||
child.print(printer, style);
|
child.print(printer, style);
|
||||||
},
|
},
|
||||||
StyleTreeNode::Image(None) => {},
|
StyleTreeNode::Image(None) => {},
|
||||||
@@ -320,7 +322,9 @@ impl StyleTreeNode {
|
|||||||
printer.commit();
|
printer.commit();
|
||||||
},
|
},
|
||||||
StyleTreeNode::Ruler => {
|
StyleTreeNode::Ruler => {
|
||||||
printer.push_str(line::HORIZONTAL.repeat(width), style);
|
for _ in 0..width {
|
||||||
|
printer.push_str(line::HORIZONTAL, style);
|
||||||
|
}
|
||||||
},
|
},
|
||||||
StyleTreeNode::Table(table) => {
|
StyleTreeNode::Table(table) => {
|
||||||
let text = table.to_text(width, style);
|
let text = table.to_text(width, style);
|
||||||
@@ -615,7 +619,7 @@ pub fn parse_matrix_html(s: &str) -> StyleTree {
|
|||||||
let dom = parse_fragment(
|
let dom = parse_fragment(
|
||||||
RcDom::default(),
|
RcDom::default(),
|
||||||
ParseOpts::default(),
|
ParseOpts::default(),
|
||||||
QualName::new(None, ns!(), local_name!("div")),
|
QualName::new(None, ns!(html), local_name!("body")),
|
||||||
vec![],
|
vec![],
|
||||||
)
|
)
|
||||||
.one(StrTendril::from(s));
|
.one(StrTendril::from(s));
|
||||||
@@ -636,8 +640,11 @@ pub mod tests {
|
|||||||
let tree = parse_matrix_html(s);
|
let tree = parse_matrix_html(s);
|
||||||
let text = tree.to_text(20, Style::default(), false);
|
let text = tree.to_text(20, Style::default(), false);
|
||||||
assert_eq!(text.lines, vec![Spans(vec![
|
assert_eq!(text.lines, vec![Spans(vec![
|
||||||
Span::styled("# ", bold),
|
Span::styled("#", bold),
|
||||||
Span::styled("Header 1", bold),
|
Span::styled(" ", bold),
|
||||||
|
Span::styled("Header", bold),
|
||||||
|
Span::styled(" ", bold),
|
||||||
|
Span::styled("1", bold),
|
||||||
space_span(10, Style::default())
|
space_span(10, Style::default())
|
||||||
])]);
|
])]);
|
||||||
|
|
||||||
@@ -645,8 +652,12 @@ pub mod tests {
|
|||||||
let tree = parse_matrix_html(s);
|
let tree = parse_matrix_html(s);
|
||||||
let text = tree.to_text(20, Style::default(), false);
|
let text = tree.to_text(20, Style::default(), false);
|
||||||
assert_eq!(text.lines, vec![Spans(vec![
|
assert_eq!(text.lines, vec![Spans(vec![
|
||||||
Span::styled("## ", bold),
|
Span::styled("#", bold),
|
||||||
Span::styled("Header 2", bold),
|
Span::styled("#", bold),
|
||||||
|
Span::styled(" ", bold),
|
||||||
|
Span::styled("Header", bold),
|
||||||
|
Span::styled(" ", bold),
|
||||||
|
Span::styled("2", bold),
|
||||||
space_span(9, Style::default())
|
space_span(9, Style::default())
|
||||||
])]);
|
])]);
|
||||||
|
|
||||||
@@ -654,8 +665,13 @@ pub mod tests {
|
|||||||
let tree = parse_matrix_html(s);
|
let tree = parse_matrix_html(s);
|
||||||
let text = tree.to_text(20, Style::default(), false);
|
let text = tree.to_text(20, Style::default(), false);
|
||||||
assert_eq!(text.lines, vec![Spans(vec![
|
assert_eq!(text.lines, vec![Spans(vec![
|
||||||
Span::styled("### ", bold),
|
Span::styled("#", bold),
|
||||||
Span::styled("Header 3", 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())
|
space_span(8, Style::default())
|
||||||
])]);
|
])]);
|
||||||
|
|
||||||
@@ -663,8 +679,14 @@ pub mod tests {
|
|||||||
let tree = parse_matrix_html(s);
|
let tree = parse_matrix_html(s);
|
||||||
let text = tree.to_text(20, Style::default(), false);
|
let text = tree.to_text(20, Style::default(), false);
|
||||||
assert_eq!(text.lines, vec![Spans(vec![
|
assert_eq!(text.lines, vec![Spans(vec![
|
||||||
Span::styled("#### ", bold),
|
Span::styled("#", bold),
|
||||||
Span::styled("Header 4", 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())
|
space_span(7, Style::default())
|
||||||
])]);
|
])]);
|
||||||
|
|
||||||
@@ -672,8 +694,15 @@ pub mod tests {
|
|||||||
let tree = parse_matrix_html(s);
|
let tree = parse_matrix_html(s);
|
||||||
let text = tree.to_text(20, Style::default(), false);
|
let text = tree.to_text(20, Style::default(), false);
|
||||||
assert_eq!(text.lines, vec![Spans(vec![
|
assert_eq!(text.lines, vec![Spans(vec![
|
||||||
Span::styled("##### ", bold),
|
Span::styled("#", bold),
|
||||||
Span::styled("Header 5", 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())
|
space_span(6, Style::default())
|
||||||
])]);
|
])]);
|
||||||
|
|
||||||
@@ -681,8 +710,16 @@ pub mod tests {
|
|||||||
let tree = parse_matrix_html(s);
|
let tree = parse_matrix_html(s);
|
||||||
let text = tree.to_text(20, Style::default(), false);
|
let text = tree.to_text(20, Style::default(), false);
|
||||||
assert_eq!(text.lines, vec![Spans(vec![
|
assert_eq!(text.lines, vec![Spans(vec![
|
||||||
Span::styled("###### ", bold),
|
Span::styled("#", bold),
|
||||||
Span::styled("Header 6", 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())
|
space_span(5, Style::default())
|
||||||
])]);
|
])]);
|
||||||
}
|
}
|
||||||
@@ -700,7 +737,8 @@ pub mod tests {
|
|||||||
let tree = parse_matrix_html(s);
|
let tree = parse_matrix_html(s);
|
||||||
let text = tree.to_text(20, Style::default(), false);
|
let text = tree.to_text(20, Style::default(), false);
|
||||||
assert_eq!(text.lines, vec![Spans(vec![
|
assert_eq!(text.lines, vec![Spans(vec![
|
||||||
Span::styled("Bold!", bold),
|
Span::styled("Bold", bold),
|
||||||
|
Span::styled("!", bold),
|
||||||
space_span(15, def)
|
space_span(15, def)
|
||||||
])]);
|
])]);
|
||||||
|
|
||||||
@@ -708,7 +746,8 @@ pub mod tests {
|
|||||||
let tree = parse_matrix_html(s);
|
let tree = parse_matrix_html(s);
|
||||||
let text = tree.to_text(20, Style::default(), false);
|
let text = tree.to_text(20, Style::default(), false);
|
||||||
assert_eq!(text.lines, vec![Spans(vec![
|
assert_eq!(text.lines, vec![Spans(vec![
|
||||||
Span::styled("Bold!", bold),
|
Span::styled("Bold", bold),
|
||||||
|
Span::styled("!", bold),
|
||||||
space_span(15, def)
|
space_span(15, def)
|
||||||
])]);
|
])]);
|
||||||
|
|
||||||
@@ -716,7 +755,8 @@ pub mod tests {
|
|||||||
let tree = parse_matrix_html(s);
|
let tree = parse_matrix_html(s);
|
||||||
let text = tree.to_text(20, Style::default(), false);
|
let text = tree.to_text(20, Style::default(), false);
|
||||||
assert_eq!(text.lines, vec![Spans(vec![
|
assert_eq!(text.lines, vec![Spans(vec![
|
||||||
Span::styled("Italic!", italic),
|
Span::styled("Italic", italic),
|
||||||
|
Span::styled("!", italic),
|
||||||
space_span(13, def)
|
space_span(13, def)
|
||||||
])]);
|
])]);
|
||||||
|
|
||||||
@@ -724,7 +764,8 @@ pub mod tests {
|
|||||||
let tree = parse_matrix_html(s);
|
let tree = parse_matrix_html(s);
|
||||||
let text = tree.to_text(20, Style::default(), false);
|
let text = tree.to_text(20, Style::default(), false);
|
||||||
assert_eq!(text.lines, vec![Spans(vec![
|
assert_eq!(text.lines, vec![Spans(vec![
|
||||||
Span::styled("Italic!", italic),
|
Span::styled("Italic", italic),
|
||||||
|
Span::styled("!", italic),
|
||||||
space_span(13, def)
|
space_span(13, def)
|
||||||
])]);
|
])]);
|
||||||
|
|
||||||
@@ -732,7 +773,8 @@ pub mod tests {
|
|||||||
let tree = parse_matrix_html(s);
|
let tree = parse_matrix_html(s);
|
||||||
let text = tree.to_text(20, Style::default(), false);
|
let text = tree.to_text(20, Style::default(), false);
|
||||||
assert_eq!(text.lines, vec![Spans(vec![
|
assert_eq!(text.lines, vec![Spans(vec![
|
||||||
Span::styled("Strikethrough!", strike),
|
Span::styled("Strikethrough", strike),
|
||||||
|
Span::styled("!", strike),
|
||||||
space_span(6, def)
|
space_span(6, def)
|
||||||
])]);
|
])]);
|
||||||
|
|
||||||
@@ -740,7 +782,8 @@ pub mod tests {
|
|||||||
let tree = parse_matrix_html(s);
|
let tree = parse_matrix_html(s);
|
||||||
let text = tree.to_text(20, Style::default(), false);
|
let text = tree.to_text(20, Style::default(), false);
|
||||||
assert_eq!(text.lines, vec![Spans(vec![
|
assert_eq!(text.lines, vec![Spans(vec![
|
||||||
Span::styled("Strikethrough!", strike),
|
Span::styled("Strikethrough", strike),
|
||||||
|
Span::styled("!", strike),
|
||||||
space_span(6, def)
|
space_span(6, def)
|
||||||
])]);
|
])]);
|
||||||
|
|
||||||
@@ -748,19 +791,28 @@ pub mod tests {
|
|||||||
let tree = parse_matrix_html(s);
|
let tree = parse_matrix_html(s);
|
||||||
let text = tree.to_text(20, Style::default(), false);
|
let text = tree.to_text(20, Style::default(), false);
|
||||||
assert_eq!(text.lines, vec![Spans(vec![
|
assert_eq!(text.lines, vec![Spans(vec![
|
||||||
Span::styled("Underline!", underl),
|
Span::styled("Underline", underl),
|
||||||
|
Span::styled("!", underl),
|
||||||
space_span(10, def)
|
space_span(10, def)
|
||||||
])]);
|
])]);
|
||||||
|
|
||||||
let s = "<font color=\"#ff0000\">Red!</u>";
|
let s = "<font color=\"#ff0000\">Red!</u>";
|
||||||
let tree = parse_matrix_html(s);
|
let tree = parse_matrix_html(s);
|
||||||
let text = tree.to_text(20, Style::default(), false);
|
let text = tree.to_text(20, Style::default(), false);
|
||||||
assert_eq!(text.lines, vec![Spans(vec![Span::styled("Red!", red), space_span(16, def)])]);
|
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 s = "<font color=\"red\">Red!</u>";
|
||||||
let tree = parse_matrix_html(s);
|
let tree = parse_matrix_html(s);
|
||||||
let text = tree.to_text(20, Style::default(), false);
|
let text = tree.to_text(20, Style::default(), false);
|
||||||
assert_eq!(text.lines, vec![Spans(vec![Span::styled("Red!", red), space_span(16, def)])]);
|
assert_eq!(text.lines, vec![Spans(vec![
|
||||||
|
Span::styled("Red", red),
|
||||||
|
Span::styled("!", red),
|
||||||
|
space_span(16, def)
|
||||||
|
])]);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -769,13 +821,25 @@ pub mod tests {
|
|||||||
let tree = parse_matrix_html(s);
|
let tree = parse_matrix_html(s);
|
||||||
let text = tree.to_text(10, Style::default(), false);
|
let text = tree.to_text(10, Style::default(), false);
|
||||||
assert_eq!(text.lines.len(), 7);
|
assert_eq!(text.lines.len(), 7);
|
||||||
assert_eq!(text.lines[0], Spans(vec![Span::raw("Hello worl")]));
|
assert_eq!(
|
||||||
assert_eq!(text.lines[1], Spans(vec![Span::raw("d!"), Span::raw(" ")]));
|
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[2], Spans(vec![Span::raw(" ")]));
|
||||||
assert_eq!(text.lines[3], Spans(vec![Span::raw("Content"), 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[4], Spans(vec![Span::raw(" ")]));
|
||||||
assert_eq!(text.lines[5], Spans(vec![Span::raw("Goodbye wo")]));
|
assert_eq!(
|
||||||
assert_eq!(text.lines[6], Spans(vec![Span::raw("rld!"), Span::raw(" ")]));
|
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]
|
#[test]
|
||||||
@@ -784,8 +848,14 @@ pub mod tests {
|
|||||||
let tree = parse_matrix_html(s);
|
let tree = parse_matrix_html(s);
|
||||||
let text = tree.to_text(10, Style::default(), false);
|
let text = tree.to_text(10, Style::default(), false);
|
||||||
assert_eq!(text.lines.len(), 2);
|
assert_eq!(text.lines.len(), 2);
|
||||||
assert_eq!(text.lines[0], Spans(vec![Span::raw(" "), Span::raw("Hello ")]));
|
assert_eq!(
|
||||||
assert_eq!(text.lines[1], Spans(vec![Span::raw(" "), Span::raw("world!")]));
|
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]
|
#[test]
|
||||||
@@ -794,12 +864,60 @@ pub mod tests {
|
|||||||
let tree = parse_matrix_html(s);
|
let tree = parse_matrix_html(s);
|
||||||
let text = tree.to_text(8, Style::default(), false);
|
let text = tree.to_text(8, Style::default(), false);
|
||||||
assert_eq!(text.lines.len(), 6);
|
assert_eq!(text.lines.len(), 6);
|
||||||
assert_eq!(text.lines[0], Spans(vec![Span::raw("- "), Span::raw("List I")]));
|
assert_eq!(
|
||||||
assert_eq!(text.lines[1], Spans(vec![Span::raw(" "), Span::raw("tem 1"), Span::raw(" ")]));
|
text.lines[0],
|
||||||
assert_eq!(text.lines[2], Spans(vec![Span::raw("- "), Span::raw("List I")]));
|
Spans(vec![
|
||||||
assert_eq!(text.lines[3], Spans(vec![Span::raw(" "), Span::raw("tem 2"), Span::raw(" ")]));
|
Span::raw("- "),
|
||||||
assert_eq!(text.lines[4], Spans(vec![Span::raw("- "), Span::raw("List I")]));
|
Span::raw("List"),
|
||||||
assert_eq!(text.lines[5], Spans(vec![Span::raw(" "), Span::raw("tem 3"), Span::raw(" ")]));
|
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]
|
#[test]
|
||||||
@@ -808,20 +926,59 @@ pub mod tests {
|
|||||||
let tree = parse_matrix_html(s);
|
let tree = parse_matrix_html(s);
|
||||||
let text = tree.to_text(9, Style::default(), false);
|
let text = tree.to_text(9, Style::default(), false);
|
||||||
assert_eq!(text.lines.len(), 6);
|
assert_eq!(text.lines.len(), 6);
|
||||||
assert_eq!(text.lines[0], Spans(vec![Span::raw("1. "), Span::raw("List I")]));
|
assert_eq!(
|
||||||
|
text.lines[0],
|
||||||
|
Spans(vec![
|
||||||
|
Span::raw("1. "),
|
||||||
|
Span::raw("List"),
|
||||||
|
Span::raw(" "),
|
||||||
|
Span::raw(" ")
|
||||||
|
])
|
||||||
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
text.lines[1],
|
text.lines[1],
|
||||||
Spans(vec![Span::raw(" "), Span::raw("tem 1"), Span::raw(" ")])
|
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[2], Spans(vec![Span::raw("2. "), Span::raw("List I")]));
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
text.lines[3],
|
text.lines[3],
|
||||||
Spans(vec![Span::raw(" "), Span::raw("tem 2"), Span::raw(" ")])
|
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[4], Spans(vec![Span::raw("3. "), Span::raw("List I")]));
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
text.lines[5],
|
text.lines[5],
|
||||||
Spans(vec![Span::raw(" "), Span::raw("tem 3"), Span::raw(" ")])
|
Spans(vec![
|
||||||
|
Span::raw(" "),
|
||||||
|
Span::raw("Item"),
|
||||||
|
Span::raw(" "),
|
||||||
|
Span::raw("3")
|
||||||
|
])
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -854,9 +1011,13 @@ pub mod tests {
|
|||||||
]);
|
]);
|
||||||
assert_eq!(text.lines[2].0, vec![
|
assert_eq!(text.lines[2].0, vec![
|
||||||
Span::raw("│"),
|
Span::raw("│"),
|
||||||
Span::styled("mn 1", bold),
|
Span::styled("mn", bold),
|
||||||
|
Span::styled(" ", bold),
|
||||||
|
Span::styled("1", bold),
|
||||||
Span::raw("│"),
|
Span::raw("│"),
|
||||||
Span::styled("mn 2", bold),
|
Span::styled("mn", bold),
|
||||||
|
Span::styled(" ", bold),
|
||||||
|
Span::styled("2", bold),
|
||||||
Span::raw("│"),
|
Span::raw("│"),
|
||||||
Span::styled("umn", bold),
|
Span::styled("umn", bold),
|
||||||
Span::raw("│")
|
Span::raw("│")
|
||||||
@@ -867,7 +1028,8 @@ pub mod tests {
|
|||||||
Span::raw("│"),
|
Span::raw("│"),
|
||||||
Span::raw(" "),
|
Span::raw(" "),
|
||||||
Span::raw("│"),
|
Span::raw("│"),
|
||||||
Span::styled(" 3", bold),
|
Span::styled(" ", bold),
|
||||||
|
Span::styled("3", bold),
|
||||||
Span::styled(" ", bold),
|
Span::styled(" ", bold),
|
||||||
Span::raw("│")
|
Span::raw("│")
|
||||||
]);
|
]);
|
||||||
@@ -928,15 +1090,72 @@ pub mod tests {
|
|||||||
let tree = parse_matrix_html(s);
|
let tree = parse_matrix_html(s);
|
||||||
let text = tree.to_text(10, Style::default(), false);
|
let text = tree.to_text(10, Style::default(), false);
|
||||||
assert_eq!(text.lines.len(), 4);
|
assert_eq!(text.lines.len(), 4);
|
||||||
assert_eq!(text.lines[0], Spans(vec![Span::raw("This was r")]));
|
assert_eq!(
|
||||||
assert_eq!(text.lines[1], Spans(vec![Span::raw("eplied to"), Span::raw(" ")]));
|
text.lines[0],
|
||||||
assert_eq!(text.lines[2], Spans(vec![Span::raw("This is th")]));
|
Spans(vec![
|
||||||
assert_eq!(text.lines[3], Spans(vec![Span::raw("e reply"), Span::raw(" ")]));
|
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 tree = parse_matrix_html(s);
|
||||||
let text = tree.to_text(10, Style::default(), true);
|
let text = tree.to_text(10, Style::default(), true);
|
||||||
assert_eq!(text.lines.len(), 2);
|
assert_eq!(text.lines.len(), 2);
|
||||||
assert_eq!(text.lines[0], Spans(vec![Span::raw("This is th")]));
|
assert_eq!(
|
||||||
assert_eq!(text.lines[1], Spans(vec![Span::raw("e reply"), Span::raw(" ")]));
|
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")]),);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,12 +6,17 @@ use std::convert::TryFrom;
|
|||||||
use std::hash::{Hash, Hasher};
|
use std::hash::{Hash, Hasher};
|
||||||
use std::slice::Iter;
|
use std::slice::Iter;
|
||||||
|
|
||||||
use chrono::{DateTime, NaiveDateTime, Utc};
|
use chrono::{DateTime, Local as LocalTz, NaiveDateTime, TimeZone};
|
||||||
use unicode_width::UnicodeWidthStr;
|
use unicode_width::UnicodeWidthStr;
|
||||||
|
|
||||||
use matrix_sdk::ruma::{
|
use matrix_sdk::ruma::{
|
||||||
events::{
|
events::{
|
||||||
room::{
|
room::{
|
||||||
|
encrypted::{
|
||||||
|
OriginalRoomEncryptedEvent,
|
||||||
|
RedactedRoomEncryptedEvent,
|
||||||
|
RoomEncryptedEvent,
|
||||||
|
},
|
||||||
message::{
|
message::{
|
||||||
FormattedBody,
|
FormattedBody,
|
||||||
MessageFormat,
|
MessageFormat,
|
||||||
@@ -24,7 +29,9 @@ use matrix_sdk::ruma::{
|
|||||||
},
|
},
|
||||||
redaction::SyncRoomRedactionEvent,
|
redaction::SyncRoomRedactionEvent,
|
||||||
},
|
},
|
||||||
|
AnyMessageLikeEvent,
|
||||||
Redact,
|
Redact,
|
||||||
|
RedactedUnsigned,
|
||||||
},
|
},
|
||||||
EventId,
|
EventId,
|
||||||
MilliSecondsSinceUnixEpoch,
|
MilliSecondsSinceUnixEpoch,
|
||||||
@@ -52,7 +59,7 @@ use crate::{
|
|||||||
mod html;
|
mod html;
|
||||||
mod printer;
|
mod printer;
|
||||||
|
|
||||||
pub type MessageFetchResult = IambResult<(Option<String>, Vec<RoomMessageEvent>)>;
|
pub type MessageFetchResult = IambResult<(Option<String>, Vec<AnyMessageLikeEvent>)>;
|
||||||
pub type MessageKey = (MessageTimeStamp, OwnedEventId);
|
pub type MessageKey = (MessageTimeStamp, OwnedEventId);
|
||||||
pub type Messages = BTreeMap<MessageKey, Message>;
|
pub type Messages = BTreeMap<MessageKey, Message>;
|
||||||
|
|
||||||
@@ -68,6 +75,13 @@ const fn span_static(s: &'static str) -> Span<'static> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const BOLD_STYLE: Style = Style {
|
||||||
|
fg: None,
|
||||||
|
bg: None,
|
||||||
|
add_modifier: StyleModifier::BOLD,
|
||||||
|
sub_modifier: StyleModifier::empty(),
|
||||||
|
};
|
||||||
|
|
||||||
const USER_GUTTER: usize = 30;
|
const USER_GUTTER: usize = 30;
|
||||||
const TIME_GUTTER: usize = 12;
|
const TIME_GUTTER: usize = 12;
|
||||||
const READ_GUTTER: usize = 5;
|
const READ_GUTTER: usize = 5;
|
||||||
@@ -79,6 +93,14 @@ const USER_GUTTER_EMPTY_SPAN: Span<'static> = span_static(USER_GUTTER_EMPTY);
|
|||||||
const TIME_GUTTER_EMPTY: &str = " ";
|
const TIME_GUTTER_EMPTY: &str = " ";
|
||||||
const TIME_GUTTER_EMPTY_SPAN: Span<'static> = span_static(TIME_GUTTER_EMPTY);
|
const TIME_GUTTER_EMPTY_SPAN: Span<'static> = span_static(TIME_GUTTER_EMPTY);
|
||||||
|
|
||||||
|
#[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)]
|
#[derive(thiserror::Error, Debug)]
|
||||||
pub enum TimeStampIntError {
|
pub enum TimeStampIntError {
|
||||||
#[error("Integer conversion error: {0}")]
|
#[error("Integer conversion error: {0}")]
|
||||||
@@ -95,14 +117,31 @@ pub enum MessageTimeStamp {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl MessageTimeStamp {
|
impl MessageTimeStamp {
|
||||||
fn show(&self) -> Option<Span> {
|
fn as_datetime(&self) -> DateTime<LocalTz> {
|
||||||
match self {
|
match self {
|
||||||
MessageTimeStamp::OriginServer(ts) => {
|
MessageTimeStamp::OriginServer(ms) => millis_to_datetime(*ms),
|
||||||
let time = i64::from(*ts) / 1000;
|
MessageTimeStamp::LocalEcho => LocalTz::now(),
|
||||||
let time = NaiveDateTime::from_timestamp_opt(time, 0)?;
|
}
|
||||||
let time = DateTime::<Utc>::from_utc(time, Utc);
|
}
|
||||||
let time = time.format("%T");
|
|
||||||
let time = format!(" [{}]", time);
|
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()
|
Span::raw(time).into()
|
||||||
},
|
},
|
||||||
@@ -139,6 +178,12 @@ impl PartialOrd for MessageTimeStamp {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl From<UInt> for MessageTimeStamp {
|
||||||
|
fn from(millis: UInt) -> Self {
|
||||||
|
MessageTimeStamp::OriginServer(millis)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl From<MilliSecondsSinceUnixEpoch> for MessageTimeStamp {
|
impl From<MilliSecondsSinceUnixEpoch> for MessageTimeStamp {
|
||||||
fn from(millis: MilliSecondsSinceUnixEpoch) -> Self {
|
fn from(millis: MilliSecondsSinceUnixEpoch) -> Self {
|
||||||
MessageTimeStamp::OriginServer(millis.0)
|
MessageTimeStamp::OriginServer(millis.0)
|
||||||
@@ -168,7 +213,7 @@ impl TryFrom<usize> for MessageTimeStamp {
|
|||||||
let n = u64::try_from(u)?;
|
let n = u64::try_from(u)?;
|
||||||
let n = UInt::try_from(n).map_err(TimeStampIntError::UIntError)?;
|
let n = UInt::try_from(n).map_err(TimeStampIntError::UIntError)?;
|
||||||
|
|
||||||
Ok(MessageTimeStamp::OriginServer(n))
|
Ok(MessageTimeStamp::from(n))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -279,6 +324,8 @@ impl PartialOrd for MessageCursor {
|
|||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub enum MessageEvent {
|
pub enum MessageEvent {
|
||||||
|
EncryptedOriginal(Box<OriginalRoomEncryptedEvent>),
|
||||||
|
EncryptedRedacted(Box<RedactedRoomEncryptedEvent>),
|
||||||
Original(Box<OriginalRoomMessageEvent>),
|
Original(Box<OriginalRoomMessageEvent>),
|
||||||
Redacted(Box<RedactedRoomMessageEvent>),
|
Redacted(Box<RedactedRoomMessageEvent>),
|
||||||
Local(OwnedEventId, Box<RoomMessageEventContent>),
|
Local(OwnedEventId, Box<RoomMessageEventContent>),
|
||||||
@@ -287,35 +334,45 @@ pub enum MessageEvent {
|
|||||||
impl MessageEvent {
|
impl MessageEvent {
|
||||||
pub fn event_id(&self) -> &EventId {
|
pub fn event_id(&self) -> &EventId {
|
||||||
match self {
|
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::Original(ev) => ev.event_id.as_ref(),
|
||||||
MessageEvent::Redacted(ev) => ev.event_id.as_ref(),
|
MessageEvent::Redacted(ev) => ev.event_id.as_ref(),
|
||||||
MessageEvent::Local(event_id, _) => 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> {
|
pub fn body(&self) -> Cow<'_, str> {
|
||||||
match self {
|
match self {
|
||||||
|
MessageEvent::EncryptedOriginal(_) => "[Unable to decrypt message]".into(),
|
||||||
MessageEvent::Original(ev) => body_cow_content(&ev.content),
|
MessageEvent::Original(ev) => body_cow_content(&ev.content),
|
||||||
MessageEvent::Redacted(ev) => {
|
MessageEvent::EncryptedRedacted(ev) => body_cow_reason(&ev.unsigned),
|
||||||
let reason = ev
|
MessageEvent::Redacted(ev) => body_cow_reason(&ev.unsigned),
|
||||||
.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]")
|
|
||||||
}
|
|
||||||
},
|
|
||||||
MessageEvent::Local(_, content) => body_cow_content(content),
|
MessageEvent::Local(_, content) => body_cow_content(content),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn html(&self) -> Option<StyleTree> {
|
pub fn html(&self) -> Option<StyleTree> {
|
||||||
let content = match self {
|
let content = match self {
|
||||||
|
MessageEvent::EncryptedOriginal(_) => return None,
|
||||||
|
MessageEvent::EncryptedRedacted(_) => return None,
|
||||||
MessageEvent::Original(ev) => &ev.content,
|
MessageEvent::Original(ev) => &ev.content,
|
||||||
MessageEvent::Redacted(_) => return None,
|
MessageEvent::Redacted(_) => return None,
|
||||||
MessageEvent::Local(_, content) => content,
|
MessageEvent::Local(_, content) => content,
|
||||||
@@ -332,8 +389,10 @@ impl MessageEvent {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn redact(&mut self, redaction: SyncRoomRedactionEvent, version: &RoomVersionId) {
|
fn redact(&mut self, redaction: SyncRoomRedactionEvent, version: &RoomVersionId) {
|
||||||
match self {
|
match self {
|
||||||
|
MessageEvent::EncryptedOriginal(_) => return,
|
||||||
|
MessageEvent::EncryptedRedacted(_) => return,
|
||||||
MessageEvent::Redacted(_) => return,
|
MessageEvent::Redacted(_) => return,
|
||||||
MessageEvent::Local(_, _) => return,
|
MessageEvent::Local(_, _) => return,
|
||||||
MessageEvent::Original(ev) => {
|
MessageEvent::Original(ev) => {
|
||||||
@@ -372,6 +431,20 @@ fn body_cow_content(content: &RoomMessageEventContent) -> Cow<'_, str> {
|
|||||||
Cow::Borrowed(s)
|
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 {
|
enum MessageColumns {
|
||||||
/// Four columns: sender, message, timestamp, read receipts.
|
/// Four columns: sender, message, timestamp, read receipts.
|
||||||
Four,
|
Four,
|
||||||
@@ -388,10 +461,26 @@ enum MessageColumns {
|
|||||||
|
|
||||||
struct MessageFormatter<'a> {
|
struct MessageFormatter<'a> {
|
||||||
settings: &'a ApplicationSettings,
|
settings: &'a ApplicationSettings,
|
||||||
|
|
||||||
|
/// How many columns to print.
|
||||||
cols: MessageColumns,
|
cols: MessageColumns,
|
||||||
|
|
||||||
|
/// The full, original width.
|
||||||
|
orig: usize,
|
||||||
|
|
||||||
|
/// The width that the message contents need to fill.
|
||||||
fill: usize,
|
fill: usize,
|
||||||
|
|
||||||
|
/// The formatted Span for the message sender.
|
||||||
user: Option<Span<'a>>,
|
user: Option<Span<'a>>,
|
||||||
|
|
||||||
|
/// The time the message was sent.
|
||||||
time: Option<Span<'a>>,
|
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>,
|
read: Iter<'a, OwnedUserId>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -402,6 +491,15 @@ impl<'a> MessageFormatter<'a> {
|
|||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn push_spans(&mut self, spans: Spans<'a>, style: Style, text: &mut Text<'a>) {
|
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 {
|
match self.cols {
|
||||||
MessageColumns::Four => {
|
MessageColumns::Four => {
|
||||||
let settings = self.settings;
|
let settings = self.settings;
|
||||||
@@ -484,6 +582,8 @@ impl Message {
|
|||||||
|
|
||||||
pub fn reply_to(&self) -> Option<OwnedEventId> {
|
pub fn reply_to(&self) -> Option<OwnedEventId> {
|
||||||
let content = match &self.event {
|
let content = match &self.event {
|
||||||
|
MessageEvent::EncryptedOriginal(_) => return None,
|
||||||
|
MessageEvent::EncryptedRedacted(_) => return None,
|
||||||
MessageEvent::Local(_, content) => content,
|
MessageEvent::Local(_, content) => content,
|
||||||
MessageEvent::Original(ev) => &ev.content,
|
MessageEvent::Original(ev) => &ev.content,
|
||||||
MessageEvent::Redacted(_) => return None,
|
MessageEvent::Redacted(_) => return None,
|
||||||
@@ -517,27 +617,33 @@ impl Message {
|
|||||||
info: &'a RoomInfo,
|
info: &'a RoomInfo,
|
||||||
settings: &'a ApplicationSettings,
|
settings: &'a ApplicationSettings,
|
||||||
) -> MessageFormatter<'a> {
|
) -> 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 &&
|
if USER_GUTTER + TIME_GUTTER + READ_GUTTER + MIN_MSG_LEN <= width &&
|
||||||
settings.tunables.read_receipt_display
|
settings.tunables.read_receipt_display
|
||||||
{
|
{
|
||||||
let cols = MessageColumns::Four;
|
let cols = MessageColumns::Four;
|
||||||
let fill = width - USER_GUTTER - TIME_GUTTER - READ_GUTTER;
|
let fill = width - USER_GUTTER - TIME_GUTTER - READ_GUTTER;
|
||||||
let user = self.show_sender(prev, true, settings);
|
let user = self.show_sender(prev, true, settings);
|
||||||
let time = self.timestamp.show();
|
let time = self.timestamp.show_time();
|
||||||
let read = match info.receipts.get(self.event.event_id()) {
|
let read = match info.receipts.get(self.event.event_id()) {
|
||||||
Some(read) => read.iter(),
|
Some(read) => read.iter(),
|
||||||
None => [].iter(),
|
None => [].iter(),
|
||||||
};
|
};
|
||||||
|
|
||||||
MessageFormatter { settings, cols, fill, user, time, read }
|
MessageFormatter { settings, cols, orig, fill, user, date, time, read }
|
||||||
} else if USER_GUTTER + TIME_GUTTER + MIN_MSG_LEN <= width {
|
} else if USER_GUTTER + TIME_GUTTER + MIN_MSG_LEN <= width {
|
||||||
let cols = MessageColumns::Three;
|
let cols = MessageColumns::Three;
|
||||||
let fill = width - USER_GUTTER - TIME_GUTTER;
|
let fill = width - USER_GUTTER - TIME_GUTTER;
|
||||||
let user = self.show_sender(prev, true, settings);
|
let user = self.show_sender(prev, true, settings);
|
||||||
let time = self.timestamp.show();
|
let time = self.timestamp.show_time();
|
||||||
let read = [].iter();
|
let read = [].iter();
|
||||||
|
|
||||||
MessageFormatter { settings, cols, fill, user, time, read }
|
MessageFormatter { settings, cols, orig, fill, user, date, time, read }
|
||||||
} else if USER_GUTTER + MIN_MSG_LEN <= width {
|
} else if USER_GUTTER + MIN_MSG_LEN <= width {
|
||||||
let cols = MessageColumns::Two;
|
let cols = MessageColumns::Two;
|
||||||
let fill = width - USER_GUTTER;
|
let fill = width - USER_GUTTER;
|
||||||
@@ -545,7 +651,7 @@ impl Message {
|
|||||||
let time = None;
|
let time = None;
|
||||||
let read = [].iter();
|
let read = [].iter();
|
||||||
|
|
||||||
MessageFormatter { settings, cols, fill, user, time, read }
|
MessageFormatter { settings, cols, orig, fill, user, date, time, read }
|
||||||
} else {
|
} else {
|
||||||
let cols = MessageColumns::One;
|
let cols = MessageColumns::One;
|
||||||
let fill = width.saturating_sub(2);
|
let fill = width.saturating_sub(2);
|
||||||
@@ -553,7 +659,7 @@ impl Message {
|
|||||||
let time = None;
|
let time = None;
|
||||||
let read = [].iter();
|
let read = [].iter();
|
||||||
|
|
||||||
MessageFormatter { settings, cols, fill, user, time, read }
|
MessageFormatter { settings, cols, orig, fill, user, date, time, read }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -613,6 +719,47 @@ impl Message {
|
|||||||
fmt.push_spans(space_span(width, style).into(), style, &mut text);
|
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;
|
return text;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -640,13 +787,16 @@ impl Message {
|
|||||||
align_right: bool,
|
align_right: bool,
|
||||||
settings: &ApplicationSettings,
|
settings: &ApplicationSettings,
|
||||||
) -> Option<Span> {
|
) -> Option<Span> {
|
||||||
let user = if matches!(prev, Some(prev) if self.sender == prev.sender) {
|
if let Some(prev) = prev {
|
||||||
return None;
|
if self.sender == prev.sender &&
|
||||||
} else {
|
self.timestamp.same_day(&prev.timestamp) &&
|
||||||
self.sender_span(settings)
|
!self.event.is_emote()
|
||||||
};
|
{
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let Span { content, style } = user;
|
let Span { content, style } = self.sender_span(settings);
|
||||||
let stop = content.len().min(28);
|
let stop = content.len().min(28);
|
||||||
let s = &content[..stop];
|
let s = &content[..stop];
|
||||||
|
|
||||||
@@ -658,6 +808,24 @@ impl Message {
|
|||||||
|
|
||||||
Span::styled(sender, style).into()
|
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 {
|
impl From<OriginalRoomMessageEvent> for Message {
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ use std::borrow::Cow;
|
|||||||
use modalkit::tui::layout::Alignment;
|
use modalkit::tui::layout::Alignment;
|
||||||
use modalkit::tui::style::Style;
|
use modalkit::tui::style::Style;
|
||||||
use modalkit::tui::text::{Span, Spans, Text};
|
use modalkit::tui::text::{Span, Spans, Text};
|
||||||
|
use unicode_segmentation::UnicodeSegmentation;
|
||||||
use unicode_width::UnicodeWidthStr;
|
use unicode_width::UnicodeWidthStr;
|
||||||
|
|
||||||
use crate::util::{space_span, take_width};
|
use crate::util::{space_span, take_width};
|
||||||
@@ -107,7 +108,7 @@ impl<'a> TextPrinter<'a> {
|
|||||||
self.push();
|
self.push();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn push_str<T>(&mut self, s: T, style: Style)
|
fn push_str_wrapped<T>(&mut self, s: T, style: Style)
|
||||||
where
|
where
|
||||||
T: Into<Cow<'a, str>>,
|
T: Into<Cow<'a, str>>,
|
||||||
{
|
{
|
||||||
@@ -140,6 +141,55 @@ impl<'a> TextPrinter<'a> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
|
||||||
|
for word in UnicodeSegmentation::split_word_bounds(s) {
|
||||||
|
if self.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 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>) {
|
pub fn push_line(&mut self, spans: Spans<'a>) {
|
||||||
self.commit();
|
self.commit();
|
||||||
self.text.lines.push(spans);
|
self.text.lines.push(spans);
|
||||||
|
|||||||
29
src/tests.rs
29
src/tests.rs
@@ -17,10 +17,11 @@ use matrix_sdk::ruma::{
|
|||||||
use lazy_static::lazy_static;
|
use lazy_static::lazy_static;
|
||||||
use modalkit::tui::style::{Color, Style};
|
use modalkit::tui::style::{Color, Style};
|
||||||
use tokio::sync::mpsc::unbounded_channel;
|
use tokio::sync::mpsc::unbounded_channel;
|
||||||
|
use tracing::Level;
|
||||||
use url::Url;
|
use url::Url;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
base::{ChatStore, ProgramStore, RoomFetchStatus, RoomInfo},
|
base::{ChatStore, EventLocation, ProgramStore, RoomFetchStatus, RoomInfo},
|
||||||
config::{
|
config::{
|
||||||
user_color,
|
user_color,
|
||||||
user_style_from_color,
|
user_style_from_color,
|
||||||
@@ -117,14 +118,14 @@ pub fn mock_message5() -> Message {
|
|||||||
mock_room1_message(content, TEST_USER2.clone(), MSG4_KEY.clone())
|
mock_room1_message(content, TEST_USER2.clone(), MSG4_KEY.clone())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn mock_keys() -> HashMap<OwnedEventId, MessageKey> {
|
pub fn mock_keys() -> HashMap<OwnedEventId, EventLocation> {
|
||||||
let mut keys = HashMap::new();
|
let mut keys = HashMap::new();
|
||||||
|
|
||||||
keys.insert(MSG1_EVID.clone(), MSG1_KEY.clone());
|
keys.insert(MSG1_EVID.clone(), EventLocation::Message(MSG1_KEY.clone()));
|
||||||
keys.insert(MSG2_EVID.clone(), MSG2_KEY.clone());
|
keys.insert(MSG2_EVID.clone(), EventLocation::Message(MSG2_KEY.clone()));
|
||||||
keys.insert(MSG3_EVID.clone(), MSG3_KEY.clone());
|
keys.insert(MSG3_EVID.clone(), EventLocation::Message(MSG3_KEY.clone()));
|
||||||
keys.insert(MSG4_EVID.clone(), MSG4_KEY.clone());
|
keys.insert(MSG4_EVID.clone(), EventLocation::Message(MSG4_KEY.clone()));
|
||||||
keys.insert(MSG5_EVID.clone(), MSG5_KEY.clone());
|
keys.insert(MSG5_EVID.clone(), EventLocation::Message(MSG5_KEY.clone()));
|
||||||
|
|
||||||
keys
|
keys
|
||||||
}
|
}
|
||||||
@@ -151,7 +152,9 @@ pub fn mock_room() -> RoomInfo {
|
|||||||
|
|
||||||
receipts: HashMap::new(),
|
receipts: HashMap::new(),
|
||||||
read_till: None,
|
read_till: None,
|
||||||
|
reactions: HashMap::new(),
|
||||||
|
|
||||||
|
fetching: false,
|
||||||
fetch_id: RoomFetchStatus::NotStarted,
|
fetch_id: RoomFetchStatus::NotStarted,
|
||||||
fetch_last: None,
|
fetch_last: None,
|
||||||
users_typing: None,
|
users_typing: None,
|
||||||
@@ -169,8 +172,12 @@ pub fn mock_dirs() -> DirectoryValues {
|
|||||||
pub fn mock_tunables() -> TunableValues {
|
pub fn mock_tunables() -> TunableValues {
|
||||||
TunableValues {
|
TunableValues {
|
||||||
default_room: None,
|
default_room: None,
|
||||||
|
log_level: Level::INFO,
|
||||||
|
reaction_display: true,
|
||||||
|
reaction_shortcode_display: false,
|
||||||
read_receipt_send: true,
|
read_receipt_send: true,
|
||||||
read_receipt_display: true,
|
read_receipt_display: true,
|
||||||
|
request_timeout: 120,
|
||||||
typing_notice_send: true,
|
typing_notice_send: true,
|
||||||
typing_notice_display: true,
|
typing_notice_display: true,
|
||||||
users: vec![(TEST_USER5.clone(), UserDisplayTunables {
|
users: vec![(TEST_USER5.clone(), UserDisplayTunables {
|
||||||
@@ -205,6 +212,14 @@ pub async fn mock_store() -> ProgramStore {
|
|||||||
let worker = Requester { tx, client };
|
let worker = Requester { tx, client };
|
||||||
|
|
||||||
let mut store = ChatStore::new(worker, mock_settings());
|
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 room_id = TEST_ROOM1_ID.clone();
|
||||||
let info = mock_room();
|
let info = mock_room();
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use std::cmp::{Ord, Ordering, PartialOrd};
|
use std::cmp::{Ord, Ordering, PartialOrd};
|
||||||
use std::collections::hash_map::Entry;
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
use matrix_sdk::{
|
use matrix_sdk::{
|
||||||
encryption::verification::{format_emojis, SasVerification},
|
encryption::verification::{format_emojis, SasVerification},
|
||||||
@@ -45,7 +45,9 @@ use modalkit::{
|
|||||||
ScrollStyle,
|
ScrollStyle,
|
||||||
ViewportContext,
|
ViewportContext,
|
||||||
WordStyle,
|
WordStyle,
|
||||||
|
WriteFlags,
|
||||||
},
|
},
|
||||||
|
completion::CompletionList,
|
||||||
},
|
},
|
||||||
widgets::{
|
widgets::{
|
||||||
list::{List, ListCursor, ListItem, ListState},
|
list::{List, ListCursor, ListItem, ListState},
|
||||||
@@ -76,6 +78,8 @@ use self::{room::RoomState, welcome::WelcomeState};
|
|||||||
pub mod room;
|
pub mod room;
|
||||||
pub mod welcome;
|
pub mod welcome;
|
||||||
|
|
||||||
|
const MEMBER_FETCH_DEBOUNCE: Duration = Duration::from_secs(5);
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn bold_style() -> Style {
|
fn bold_style() -> Style {
|
||||||
Style::default().add_modifier(StyleModifier::BOLD)
|
Style::default().add_modifier(StyleModifier::BOLD)
|
||||||
@@ -168,7 +172,7 @@ fn append_tags<'a>(tags: &'a Tags, spans: &mut Vec<Span<'a>>, style: Style) {
|
|||||||
spans.push(Span::styled("User Tag: ", style));
|
spans.push(Span::styled("User Tag: ", style));
|
||||||
spans.push(Span::styled(tag.as_ref(), style));
|
spans.push(Span::styled(tag.as_ref(), style));
|
||||||
},
|
},
|
||||||
tag => spans.push(Span::styled(format!("{:?}", tag), style)),
|
tag => spans.push(Span::styled(format!("{tag:?}"), style)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -210,7 +214,7 @@ macro_rules! delegate {
|
|||||||
match $s {
|
match $s {
|
||||||
IambWindow::Room($id) => $e,
|
IambWindow::Room($id) => $e,
|
||||||
IambWindow::DirectList($id) => $e,
|
IambWindow::DirectList($id) => $e,
|
||||||
IambWindow::MemberList($id, _) => $e,
|
IambWindow::MemberList($id, _, _) => $e,
|
||||||
IambWindow::RoomList($id) => $e,
|
IambWindow::RoomList($id) => $e,
|
||||||
IambWindow::SpaceList($id) => $e,
|
IambWindow::SpaceList($id) => $e,
|
||||||
IambWindow::VerifyList($id) => $e,
|
IambWindow::VerifyList($id) => $e,
|
||||||
@@ -221,7 +225,7 @@ macro_rules! delegate {
|
|||||||
|
|
||||||
pub enum IambWindow {
|
pub enum IambWindow {
|
||||||
DirectList(DirectListState),
|
DirectList(DirectListState),
|
||||||
MemberList(MemberListState, OwnedRoomId),
|
MemberList(MemberListState, OwnedRoomId, Option<Instant>),
|
||||||
Room(RoomState),
|
Room(RoomState),
|
||||||
VerifyList(VerifyListState),
|
VerifyList(VerifyListState),
|
||||||
RoomList(RoomListState),
|
RoomList(RoomListState),
|
||||||
@@ -391,10 +395,18 @@ impl WindowOps<IambInfo> for IambWindow {
|
|||||||
.focus(focused)
|
.focus(focused)
|
||||||
.render(area, buf, state);
|
.render(area, buf, state);
|
||||||
},
|
},
|
||||||
IambWindow::MemberList(state, room_id) => {
|
IambWindow::MemberList(state, room_id, last_fetch) => {
|
||||||
if let Ok(mems) = store.application.worker.members(room_id.clone()) {
|
let need_fetch = match last_fetch {
|
||||||
let items = mems.into_iter().map(MemberItem::new);
|
Some(i) => i.elapsed() >= MEMBER_FETCH_DEBOUNCE,
|
||||||
state.set(items.collect());
|
None => true,
|
||||||
|
};
|
||||||
|
|
||||||
|
if need_fetch {
|
||||||
|
if let Ok(mems) = store.application.worker.members(room_id.clone()) {
|
||||||
|
let items = mems.into_iter().map(MemberItem::new);
|
||||||
|
state.set(items.collect());
|
||||||
|
*last_fetch = Some(Instant::now());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
List::new(store)
|
List::new(store)
|
||||||
@@ -455,8 +467,8 @@ impl WindowOps<IambInfo> for IambWindow {
|
|||||||
match self {
|
match self {
|
||||||
IambWindow::Room(w) => w.dup(store).into(),
|
IambWindow::Room(w) => w.dup(store).into(),
|
||||||
IambWindow::DirectList(w) => w.dup(store).into(),
|
IambWindow::DirectList(w) => w.dup(store).into(),
|
||||||
IambWindow::MemberList(w, room_id) => {
|
IambWindow::MemberList(w, room_id, last_fetch) => {
|
||||||
IambWindow::MemberList(w.dup(store), room_id.clone())
|
IambWindow::MemberList(w.dup(store), room_id.clone(), *last_fetch)
|
||||||
},
|
},
|
||||||
IambWindow::RoomList(w) => w.dup(store).into(),
|
IambWindow::RoomList(w) => w.dup(store).into(),
|
||||||
IambWindow::SpaceList(w) => w.dup(store).into(),
|
IambWindow::SpaceList(w) => w.dup(store).into(),
|
||||||
@@ -469,6 +481,19 @@ impl WindowOps<IambInfo> for IambWindow {
|
|||||||
delegate!(self, w => w.close(flags, store))
|
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> {
|
fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
|
||||||
delegate!(self, w => w.get_cursor_word(style))
|
delegate!(self, w => w.get_cursor_word(style))
|
||||||
}
|
}
|
||||||
@@ -483,7 +508,7 @@ impl Window<IambInfo> for IambWindow {
|
|||||||
match self {
|
match self {
|
||||||
IambWindow::Room(room) => IambId::Room(room.id().to_owned()),
|
IambWindow::Room(room) => IambId::Room(room.id().to_owned()),
|
||||||
IambWindow::DirectList(_) => IambId::DirectList,
|
IambWindow::DirectList(_) => IambId::DirectList,
|
||||||
IambWindow::MemberList(_, room_id) => IambId::MemberList(room_id.clone()),
|
IambWindow::MemberList(_, room_id, _) => IambId::MemberList(room_id.clone()),
|
||||||
IambWindow::RoomList(_) => IambId::RoomList,
|
IambWindow::RoomList(_) => IambId::RoomList,
|
||||||
IambWindow::SpaceList(_) => IambId::SpaceList,
|
IambWindow::SpaceList(_) => IambId::SpaceList,
|
||||||
IambWindow::VerifyList(_) => IambId::VerifyList,
|
IambWindow::VerifyList(_) => IambId::VerifyList,
|
||||||
@@ -504,7 +529,7 @@ impl Window<IambInfo> for IambWindow {
|
|||||||
|
|
||||||
Spans::from(title)
|
Spans::from(title)
|
||||||
},
|
},
|
||||||
IambWindow::MemberList(_, room_id) => {
|
IambWindow::MemberList(_, room_id, _) => {
|
||||||
let title = store.application.get_room_title(room_id.as_ref());
|
let title = store.application.get_room_title(room_id.as_ref());
|
||||||
|
|
||||||
Spans(vec![bold_span("Room Members: "), title.into()])
|
Spans(vec![bold_span("Room Members: "), title.into()])
|
||||||
@@ -521,7 +546,7 @@ impl Window<IambInfo> for IambWindow {
|
|||||||
IambWindow::Welcome(_) => bold_spans("Welcome to iamb"),
|
IambWindow::Welcome(_) => bold_spans("Welcome to iamb"),
|
||||||
|
|
||||||
IambWindow::Room(w) => w.get_title(store),
|
IambWindow::Room(w) => w.get_title(store),
|
||||||
IambWindow::MemberList(_, room_id) => {
|
IambWindow::MemberList(_, room_id, _) => {
|
||||||
let title = store.application.get_room_title(room_id.as_ref());
|
let title = store.application.get_room_title(room_id.as_ref());
|
||||||
|
|
||||||
Spans(vec![bold_span("Room Members: "), title.into()])
|
Spans(vec![bold_span("Room Members: "), title.into()])
|
||||||
@@ -545,7 +570,7 @@ impl Window<IambInfo> for IambWindow {
|
|||||||
IambId::MemberList(room_id) => {
|
IambId::MemberList(room_id) => {
|
||||||
let id = IambBufferId::MemberList(room_id.clone());
|
let id = IambBufferId::MemberList(room_id.clone());
|
||||||
let list = MemberListState::new(id, vec![]);
|
let list = MemberListState::new(id, vec![]);
|
||||||
let win = IambWindow::MemberList(list, room_id);
|
let win = IambWindow::MemberList(list, room_id, None);
|
||||||
|
|
||||||
return Ok(win);
|
return Ok(win);
|
||||||
},
|
},
|
||||||
@@ -575,26 +600,23 @@ impl Window<IambInfo> for IambWindow {
|
|||||||
fn find(name: String, store: &mut ProgramStore) -> IambResult<Self> {
|
fn find(name: String, store: &mut ProgramStore) -> IambResult<Self> {
|
||||||
let ChatStore { names, worker, .. } = &mut store.application;
|
let ChatStore { names, worker, .. } = &mut store.application;
|
||||||
|
|
||||||
match names.entry(name) {
|
if let Some(room) = names.get_mut(&name) {
|
||||||
Entry::Vacant(v) => {
|
let id = IambId::Room(room.clone());
|
||||||
let room_id = worker.join_room(v.key().to_string())?;
|
|
||||||
v.insert(room_id.clone());
|
|
||||||
|
|
||||||
let (room, name, tags) = store.application.worker.get_room(room_id)?;
|
IambWindow::open(id, store)
|
||||||
let room = RoomState::new(room, name, tags, store);
|
} else {
|
||||||
|
let room_id = worker.join_room(name.clone())?;
|
||||||
|
names.insert(name, room_id.clone());
|
||||||
|
|
||||||
Ok(room.into())
|
let (room, name, tags) = store.application.worker.get_room(room_id)?;
|
||||||
},
|
let room = RoomState::new(room, name, tags, store);
|
||||||
Entry::Occupied(o) => {
|
|
||||||
let id = IambId::Room(o.get().clone());
|
|
||||||
|
|
||||||
IambWindow::open(id, store)
|
Ok(room.into())
|
||||||
},
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn posn(index: usize, _: &mut ProgramStore) -> IambResult<Self> {
|
fn posn(index: usize, _: &mut ProgramStore) -> IambResult<Self> {
|
||||||
let msg = format!("Cannot find indexed buffer (index = {})", index);
|
let msg = format!("Cannot find indexed buffer (index = {index})");
|
||||||
let err = UIError::Unimplemented(msg);
|
let err = UIError::Unimplemented(msg);
|
||||||
|
|
||||||
Err(err)
|
Err(err)
|
||||||
@@ -620,11 +642,16 @@ impl RoomItem {
|
|||||||
store: &mut ProgramStore,
|
store: &mut ProgramStore,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
let name = name.to_string();
|
let name = name.to_string();
|
||||||
|
let room_id = room.room_id();
|
||||||
|
|
||||||
let info = store.application.get_room_info(room.room_id().to_owned());
|
let info = store.application.get_room_info(room_id.to_owned());
|
||||||
info.name = name.clone().into();
|
info.name = name.clone().into();
|
||||||
info.tags = tags.clone();
|
info.tags = tags.clone();
|
||||||
|
|
||||||
|
if let Some(alias) = room.canonical_alias() {
|
||||||
|
store.application.names.insert(alias.to_string(), room_id.to_owned());
|
||||||
|
}
|
||||||
|
|
||||||
RoomItem { room, tags, name }
|
RoomItem { room, tags, name }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -772,8 +799,13 @@ pub struct SpaceItem {
|
|||||||
impl SpaceItem {
|
impl SpaceItem {
|
||||||
fn new(room: MatrixRoom, name: DisplayName, store: &mut ProgramStore) -> Self {
|
fn new(room: MatrixRoom, name: DisplayName, store: &mut ProgramStore) -> Self {
|
||||||
let name = name.to_string();
|
let name = name.to_string();
|
||||||
|
let room_id = room.room_id();
|
||||||
|
|
||||||
store.application.set_room_name(room.room_id(), name.as_str());
|
store.application.set_room_name(room_id, name.as_str());
|
||||||
|
|
||||||
|
if let Some(alias) = room.canonical_alias() {
|
||||||
|
store.application.names.insert(alias.to_string(), room_id.to_owned());
|
||||||
|
}
|
||||||
|
|
||||||
SpaceItem { room, name }
|
SpaceItem { room, name }
|
||||||
}
|
}
|
||||||
@@ -852,7 +884,7 @@ impl VerifyItem {
|
|||||||
let device = self.sasv1.other_device();
|
let device = self.sasv1.other_device();
|
||||||
|
|
||||||
if let Some(display_name) = device.display_name() {
|
if let Some(display_name) = device.display_name() {
|
||||||
format!("Device verification with {} ({})", display_name, state)
|
format!("Device verification with {display_name} ({state})")
|
||||||
} else {
|
} else {
|
||||||
format!("Device verification with device {} ({})", device.device_id(), state)
|
format!("Device verification with device {} ({})", device.device_id(), state)
|
||||||
}
|
}
|
||||||
@@ -958,7 +990,7 @@ impl ListItem<IambInfo> for VerifyItem {
|
|||||||
lines.push(Spans::from(""));
|
lines.push(Spans::from(""));
|
||||||
|
|
||||||
for line in format_emojis(emoji).lines() {
|
for line in format_emojis(emoji).lines() {
|
||||||
lines.push(Spans::from(format!(" {}", line)));
|
lines.push(Spans::from(format!(" {line}")));
|
||||||
}
|
}
|
||||||
|
|
||||||
lines.push(Spans::from(""));
|
lines.push(Spans::from(""));
|
||||||
|
|||||||
@@ -4,11 +4,14 @@ use std::fs;
|
|||||||
use std::ops::Deref;
|
use std::ops::Deref;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use tokio;
|
||||||
|
|
||||||
use matrix_sdk::{
|
use matrix_sdk::{
|
||||||
attachment::AttachmentConfig,
|
attachment::AttachmentConfig,
|
||||||
media::{MediaFormat, MediaRequest},
|
media::{MediaFormat, MediaRequest},
|
||||||
room::Room as MatrixRoom,
|
room::{Joined, Room as MatrixRoom},
|
||||||
ruma::{
|
ruma::{
|
||||||
|
events::reaction::{ReactionEventContent, Relation as Reaction},
|
||||||
events::room::message::{
|
events::room::message::{
|
||||||
MessageType,
|
MessageType,
|
||||||
OriginalRoomMessageEvent,
|
OriginalRoomMessageEvent,
|
||||||
@@ -17,6 +20,7 @@ use matrix_sdk::{
|
|||||||
RoomMessageEventContent,
|
RoomMessageEventContent,
|
||||||
TextMessageEventContent,
|
TextMessageEventContent,
|
||||||
},
|
},
|
||||||
|
EventId,
|
||||||
OwnedRoomId,
|
OwnedRoomId,
|
||||||
RoomId,
|
RoomId,
|
||||||
},
|
},
|
||||||
@@ -48,13 +52,15 @@ use modalkit::editing::{
|
|||||||
Scrollable,
|
Scrollable,
|
||||||
UIError,
|
UIError,
|
||||||
},
|
},
|
||||||
base::{CloseFlags, Count, MoveDir1D, PositionList, ScrollStyle, WordStyle},
|
base::{CloseFlags, Count, MoveDir1D, PositionList, ScrollStyle, WordStyle, WriteFlags},
|
||||||
|
completion::CompletionList,
|
||||||
context::Resolve,
|
context::Resolve,
|
||||||
history::{self, HistoryList},
|
history::{self, HistoryList},
|
||||||
rope::EditRope,
|
rope::EditRope,
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::base::{
|
use crate::base::{
|
||||||
|
DownloadFlags,
|
||||||
IambAction,
|
IambAction,
|
||||||
IambBufferId,
|
IambBufferId,
|
||||||
IambError,
|
IambError,
|
||||||
@@ -70,6 +76,7 @@ use crate::base::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use crate::message::{Message, MessageEvent, MessageKey, MessageTimeStamp};
|
use crate::message::{Message, MessageEvent, MessageKey, MessageTimeStamp};
|
||||||
|
use crate::worker::Requester;
|
||||||
|
|
||||||
use super::scrollback::{Scrollback, ScrollbackState};
|
use super::scrollback::{Scrollback, ScrollbackState};
|
||||||
|
|
||||||
@@ -112,6 +119,10 @@ impl ChatState {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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> {
|
fn get_reply_to<'a>(&self, info: &'a RoomInfo) -> Option<&'a OriginalRoomMessageEvent> {
|
||||||
let key = self.reply_to.as_ref()?;
|
let key = self.reply_to.as_ref()?;
|
||||||
let msg = info.messages.get(key)?;
|
let msg = info.messages.get(key)?;
|
||||||
@@ -144,9 +155,12 @@ impl ChatState {
|
|||||||
let client = &store.application.worker.client;
|
let client = &store.application.worker.client;
|
||||||
|
|
||||||
let settings = &store.application.settings;
|
let settings = &store.application.settings;
|
||||||
let info = store.application.rooms.entry(self.room_id.clone()).or_default();
|
let info = store.application.rooms.get_or_default(self.room_id.clone());
|
||||||
|
|
||||||
let msg = self.scrollback.get_mut(info).ok_or(IambError::NoSelectedMessage)?;
|
let msg = self
|
||||||
|
.scrollback
|
||||||
|
.get_mut(&mut info.messages)
|
||||||
|
.ok_or(IambError::NoSelectedMessage)?;
|
||||||
|
|
||||||
match act {
|
match act {
|
||||||
MessageAction::Cancel => {
|
MessageAction::Cancel => {
|
||||||
@@ -155,7 +169,7 @@ impl ChatState {
|
|||||||
|
|
||||||
Ok(None)
|
Ok(None)
|
||||||
},
|
},
|
||||||
MessageAction::Download(filename, force) => {
|
MessageAction::Download(filename, flags) => {
|
||||||
if let MessageEvent::Original(ev) = &msg.event {
|
if let MessageEvent::Original(ev) = &msg.event {
|
||||||
let media = client.media();
|
let media = client.media();
|
||||||
|
|
||||||
@@ -202,9 +216,18 @@ impl ChatState {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
if !force && filename.exists() {
|
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!(
|
let msg = format!(
|
||||||
"The file {} already exists; use :download! to overwrite it.",
|
"The file {} already exists; add ! to end of command to overwrite it.",
|
||||||
filename.display()
|
filename.display()
|
||||||
);
|
);
|
||||||
let err = UIError::Failure(msg);
|
let err = UIError::Failure(msg);
|
||||||
@@ -212,19 +235,21 @@ impl ChatState {
|
|||||||
return Err(err);
|
return Err(err);
|
||||||
}
|
}
|
||||||
|
|
||||||
let req = MediaRequest { source, format: MediaFormat::File };
|
let info = if flags.contains(DownloadFlags::OPEN) {
|
||||||
|
// open::that may not return until the spawned program closes.
|
||||||
|
let target = filename.clone().into_os_string();
|
||||||
|
tokio::task::spawn_blocking(move || open::that(target));
|
||||||
|
|
||||||
let bytes =
|
InfoMessage::from(format!(
|
||||||
media.get_media_content(&req, true).await.map_err(IambError::from)?;
|
"Attachment downloaded to {} and opened",
|
||||||
|
filename.display()
|
||||||
fs::write(filename.as_path(), bytes.as_slice())?;
|
))
|
||||||
|
} else {
|
||||||
msg.downloaded = true;
|
InfoMessage::from(format!(
|
||||||
|
"Attachment downloaded to {}",
|
||||||
let info = InfoMessage::from(format!(
|
filename.display()
|
||||||
"Attachment downloaded to {}",
|
))
|
||||||
filename.display()
|
};
|
||||||
));
|
|
||||||
|
|
||||||
return Ok(info.into());
|
return Ok(info.into());
|
||||||
}
|
}
|
||||||
@@ -266,19 +291,36 @@ impl ChatState {
|
|||||||
|
|
||||||
Ok(None)
|
Ok(None)
|
||||||
},
|
},
|
||||||
MessageAction::Redact(reason) => {
|
MessageAction::React(emoji) => {
|
||||||
let room = store
|
let room = self.get_joined(&store.application.worker)?;
|
||||||
.application
|
|
||||||
.worker
|
|
||||||
.client
|
|
||||||
.get_joined_room(self.id())
|
|
||||||
.ok_or(IambError::NotJoined)?;
|
|
||||||
|
|
||||||
let event_id = match &msg.event {
|
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::Original(ev) => ev.event_id.clone(),
|
||||||
MessageEvent::Local(event_id, _) => event_id.clone(),
|
MessageEvent::Local(event_id, _) => event_id.clone(),
|
||||||
MessageEvent::Redacted(_) => {
|
MessageEvent::Redacted(_) => {
|
||||||
let msg = "";
|
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) => {
|
||||||
|
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());
|
let err = UIError::Failure(msg.into());
|
||||||
|
|
||||||
return Err(err);
|
return Err(err);
|
||||||
@@ -295,6 +337,48 @@ impl ChatState {
|
|||||||
self.reply_to = self.scrollback.get_key(info);
|
self.reply_to = self.scrollback.get_key(info);
|
||||||
self.focus = RoomFocus::MessageBar;
|
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)
|
Ok(None)
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -312,18 +396,18 @@ impl ChatState {
|
|||||||
.client
|
.client
|
||||||
.get_joined_room(self.id())
|
.get_joined_room(self.id())
|
||||||
.ok_or(IambError::NotJoined)?;
|
.ok_or(IambError::NotJoined)?;
|
||||||
let info = store.application.rooms.entry(self.id().to_owned()).or_default();
|
let info = store.application.rooms.get_or_default(self.id().to_owned());
|
||||||
let mut show_echo = true;
|
let mut show_echo = true;
|
||||||
|
|
||||||
let (event_id, msg) = match act {
|
let (event_id, msg) = match act {
|
||||||
SendAction::Submit => {
|
SendAction::Submit => {
|
||||||
let msg = self.tbox.get_text();
|
let msg = self.tbox.get();
|
||||||
|
|
||||||
if msg.is_empty() {
|
if msg.is_blank() {
|
||||||
return Ok(None);
|
return Ok(None);
|
||||||
}
|
}
|
||||||
|
|
||||||
let msg = TextMessageEventContent::markdown(msg);
|
let msg = TextMessageEventContent::markdown(msg.to_string());
|
||||||
let msg = MessageType::Text(msg);
|
let msg = MessageType::Text(msg);
|
||||||
|
|
||||||
let mut msg = RoomMessageEventContent::new(msg);
|
let mut msg = RoomMessageEventContent::new(msg);
|
||||||
@@ -367,7 +451,7 @@ impl ChatState {
|
|||||||
.map_err(IambError::from)?;
|
.map_err(IambError::from)?;
|
||||||
|
|
||||||
// Mock up the local echo message for the scrollback.
|
// Mock up the local echo message for the scrollback.
|
||||||
let msg = TextMessageEventContent::plain(format!("[Attached File: {}]", name));
|
let msg = TextMessageEventContent::plain(format!("[Attached File: {name}]"));
|
||||||
let msg = MessageType::Text(msg);
|
let msg = MessageType::Text(msg);
|
||||||
let msg = RoomMessageEventContent::new(msg);
|
let msg = RoomMessageEventContent::new(msg);
|
||||||
|
|
||||||
@@ -473,6 +557,21 @@ impl WindowOps<IambInfo> for ChatState {
|
|||||||
true
|
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> {
|
fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
|
||||||
delegate!(self, w => w.get_cursor_word(style))
|
delegate!(self, w => w.get_cursor_word(style))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -40,7 +40,9 @@ use modalkit::{
|
|||||||
PositionList,
|
PositionList,
|
||||||
ScrollStyle,
|
ScrollStyle,
|
||||||
WordStyle,
|
WordStyle,
|
||||||
|
WriteFlags,
|
||||||
},
|
},
|
||||||
|
editing::completion::CompletionList,
|
||||||
input::InputContext,
|
input::InputContext,
|
||||||
widgets::{TermOffset, TerminalCursor, WindowOps},
|
widgets::{TermOffset, TerminalCursor, WindowOps},
|
||||||
};
|
};
|
||||||
@@ -132,10 +134,7 @@ impl RoomState {
|
|||||||
None => format!("{:?}", store.application.get_room_title(self.id())),
|
None => format!("{:?}", store.application.get_room_title(self.id())),
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut invited = vec![Span::from(format!(
|
let mut invited = vec![Span::from(format!("You have been invited to join {name}"))];
|
||||||
"You have been invited to join {}",
|
|
||||||
name
|
|
||||||
))];
|
|
||||||
|
|
||||||
if let Ok(Some(inviter)) = &inviter {
|
if let Ok(Some(inviter)) = &inviter {
|
||||||
invited.push(Span::from(" by "));
|
invited.push(Span::from(" by "));
|
||||||
@@ -186,8 +185,16 @@ impl RoomState {
|
|||||||
match act {
|
match act {
|
||||||
RoomAction::InviteAccept => {
|
RoomAction::InviteAccept => {
|
||||||
if let Some(room) = store.application.worker.client.get_invited_room(self.id()) {
|
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)?;
|
room.accept_invitation().await.map_err(IambError::from)?;
|
||||||
|
|
||||||
|
if is_direct {
|
||||||
|
room.set_is_direct(true).await.map_err(IambError::from)?;
|
||||||
|
}
|
||||||
|
|
||||||
Ok(vec![])
|
Ok(vec![])
|
||||||
} else {
|
} else {
|
||||||
Err(IambError::NotInvited.into())
|
Err(IambError::NotInvited.into())
|
||||||
@@ -386,10 +393,30 @@ impl WindowOps<IambInfo> for RoomState {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn close(&mut self, _: CloseFlags, _: &mut ProgramStore) -> bool {
|
fn close(&mut self, flags: CloseFlags, store: &mut ProgramStore) -> bool {
|
||||||
// XXX: what's the right closing behaviour for a room?
|
match self {
|
||||||
// Should write send a message?
|
RoomState::Chat(chat) => chat.close(flags, store),
|
||||||
true
|
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> {
|
fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
|
||||||
|
|||||||
@@ -32,6 +32,9 @@ use modalkit::editing::{
|
|||||||
base::{
|
base::{
|
||||||
Axis,
|
Axis,
|
||||||
CloseFlags,
|
CloseFlags,
|
||||||
|
CompletionDisplay,
|
||||||
|
CompletionSelection,
|
||||||
|
CompletionType,
|
||||||
Count,
|
Count,
|
||||||
EditRange,
|
EditRange,
|
||||||
EditTarget,
|
EditTarget,
|
||||||
@@ -51,7 +54,9 @@ use modalkit::editing::{
|
|||||||
TargetShape,
|
TargetShape,
|
||||||
ViewportContext,
|
ViewportContext,
|
||||||
WordStyle,
|
WordStyle,
|
||||||
|
WriteFlags,
|
||||||
},
|
},
|
||||||
|
completion::CompletionList,
|
||||||
context::{EditContext, Resolve},
|
context::{EditContext, Resolve},
|
||||||
cursor::{CursorGroup, CursorState},
|
cursor::{CursorGroup, CursorState},
|
||||||
history::HistoryList,
|
history::HistoryList,
|
||||||
@@ -60,9 +65,9 @@ use modalkit::editing::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
base::{IambBufferId, IambInfo, ProgramContext, ProgramStore, RoomFocus, RoomInfo},
|
base::{IambBufferId, IambInfo, IambResult, ProgramContext, ProgramStore, RoomFocus, RoomInfo},
|
||||||
config::ApplicationSettings,
|
config::ApplicationSettings,
|
||||||
message::{Message, MessageCursor, MessageKey},
|
message::{Message, MessageCursor, MessageKey, Messages},
|
||||||
};
|
};
|
||||||
|
|
||||||
fn nth_key_before(pos: MessageKey, n: usize, info: &RoomInfo) -> MessageKey {
|
fn nth_key_before(pos: MessageKey, n: usize, info: &RoomInfo) -> MessageKey {
|
||||||
@@ -103,6 +108,10 @@ fn nth_after(pos: MessageKey, n: usize, info: &RoomInfo) -> MessageCursor {
|
|||||||
nth_key_after(pos, n, info).into()
|
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 {
|
pub struct ScrollbackState {
|
||||||
/// The room identifier.
|
/// The room identifier.
|
||||||
room_id: OwnedRoomId,
|
room_id: OwnedRoomId,
|
||||||
@@ -160,11 +169,11 @@ impl ScrollbackState {
|
|||||||
.or_else(|| info.messages.last_key_value().map(|kv| kv.0.clone()))
|
.or_else(|| info.messages.last_key_value().map(|kv| kv.0.clone()))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_mut<'a>(&mut self, info: &'a mut RoomInfo) -> Option<&'a mut Message> {
|
pub fn get_mut<'a>(&mut self, messages: &'a mut Messages) -> Option<&'a mut Message> {
|
||||||
if let Some(k) = &self.cursor.timestamp {
|
if let Some(k) = &self.cursor.timestamp {
|
||||||
info.messages.get_mut(k)
|
messages.get_mut(k)
|
||||||
} else {
|
} else {
|
||||||
info.messages.last_entry().map(|o| o.into_mut())
|
messages.last_entry().map(|o| o.into_mut())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -214,7 +223,8 @@ impl ScrollbackState {
|
|||||||
|
|
||||||
for (key, item) in info.messages.range(..=&idx).rev() {
|
for (key, item) in info.messages.range(..=&idx).rev() {
|
||||||
let sel = selidx == key;
|
let sel = selidx == key;
|
||||||
let len = item.show(None, sel, &self.viewctx, info, settings).lines.len();
|
let prev = prevmsg(key, info);
|
||||||
|
let len = item.show(prev, sel, &self.viewctx, info, settings).lines.len();
|
||||||
|
|
||||||
if key == &idx {
|
if key == &idx {
|
||||||
lines += len / 2;
|
lines += len / 2;
|
||||||
@@ -236,7 +246,8 @@ impl ScrollbackState {
|
|||||||
|
|
||||||
for (key, item) in info.messages.range(..=&idx).rev() {
|
for (key, item) in info.messages.range(..=&idx).rev() {
|
||||||
let sel = key == selidx;
|
let sel = key == selidx;
|
||||||
let len = item.show(None, sel, &self.viewctx, info, settings).lines.len();
|
let prev = prevmsg(key, info);
|
||||||
|
let len = item.show(prev, sel, &self.viewctx, info, settings).lines.len();
|
||||||
|
|
||||||
lines += len;
|
lines += len;
|
||||||
|
|
||||||
@@ -269,6 +280,7 @@ impl ScrollbackState {
|
|||||||
let mut lines = 0;
|
let mut lines = 0;
|
||||||
|
|
||||||
let cursor_key = self.cursor.timestamp.as_ref().unwrap_or(last_key);
|
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()..) {
|
for (idx, item) in info.messages.range(corner_key.clone()..) {
|
||||||
if idx == cursor_key {
|
if idx == cursor_key {
|
||||||
@@ -276,13 +288,15 @@ impl ScrollbackState {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
lines += item.show(None, false, &self.viewctx, info, settings).height().max(1);
|
lines += item.show(prev, false, &self.viewctx, info, settings).height().max(1);
|
||||||
|
|
||||||
if lines >= self.viewctx.get_height() {
|
if lines >= self.viewctx.get_height() {
|
||||||
// We've reached the end of the viewport; move cursor into it.
|
// We've reached the end of the viewport; move cursor into it.
|
||||||
self.cursor = idx.clone().into();
|
self.cursor = idx.clone().into();
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
prev = Some(item);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -506,6 +520,23 @@ impl WindowOps<IambInfo> for ScrollbackState {
|
|||||||
true
|
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> {
|
fn get_cursor_word(&self, _: &WordStyle) -> Option<String> {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
@@ -523,7 +554,7 @@ impl EditorActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
|
|||||||
ctx: &ProgramContext,
|
ctx: &ProgramContext,
|
||||||
store: &mut ProgramStore,
|
store: &mut ProgramStore,
|
||||||
) -> EditResult<EditInfo, IambInfo> {
|
) -> EditResult<EditInfo, IambInfo> {
|
||||||
let info = store.application.rooms.entry(self.room_id.clone()).or_default();
|
let info = store.application.rooms.get_or_default(self.room_id.clone());
|
||||||
let key = if let Some(k) = self.cursor.to_key(info) {
|
let key = if let Some(k) = self.cursor.to_key(info) {
|
||||||
k.clone()
|
k.clone()
|
||||||
} else {
|
} else {
|
||||||
@@ -582,7 +613,7 @@ impl EditorActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
|
|||||||
let needle = match ctx.get_search_regex() {
|
let needle = match ctx.get_search_regex() {
|
||||||
Some(re) => re,
|
Some(re) => re,
|
||||||
None => {
|
None => {
|
||||||
let lsearch = store.registers.get(&Register::LastSearch);
|
let lsearch = store.registers.get(&Register::LastSearch)?;
|
||||||
let lsearch = lsearch.value.to_string();
|
let lsearch = lsearch.value.to_string();
|
||||||
|
|
||||||
Regex::new(lsearch.as_ref())?
|
Regex::new(lsearch.as_ref())?
|
||||||
@@ -606,7 +637,7 @@ impl EditorActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
|
|||||||
},
|
},
|
||||||
|
|
||||||
_ => {
|
_ => {
|
||||||
let msg = format!("Unknown editing target: {:?}", motion);
|
let msg = format!("Unknown editing target: {motion:?}");
|
||||||
let err = EditError::Unimplemented(msg);
|
let err = EditError::Unimplemented(msg);
|
||||||
|
|
||||||
return Err(err);
|
return Err(err);
|
||||||
@@ -668,7 +699,7 @@ impl EditorActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
|
|||||||
let needle = match ctx.get_search_regex() {
|
let needle = match ctx.get_search_regex() {
|
||||||
Some(re) => re,
|
Some(re) => re,
|
||||||
None => {
|
None => {
|
||||||
let lsearch = store.registers.get(&Register::LastSearch);
|
let lsearch = store.registers.get(&Register::LastSearch)?;
|
||||||
let lsearch = lsearch.value.to_string();
|
let lsearch = lsearch.value.to_string();
|
||||||
|
|
||||||
Regex::new(lsearch.as_ref())?
|
Regex::new(lsearch.as_ref())?
|
||||||
@@ -693,7 +724,7 @@ impl EditorActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
|
|||||||
},
|
},
|
||||||
|
|
||||||
_ => {
|
_ => {
|
||||||
let msg = format!("Unknown motion: {:?}", motion);
|
let msg = format!("Unknown motion: {motion:?}");
|
||||||
let err = EditError::Unimplemented(msg);
|
let err = EditError::Unimplemented(msg);
|
||||||
|
|
||||||
return Err(err);
|
return Err(err);
|
||||||
@@ -716,7 +747,7 @@ impl EditorActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
|
|||||||
flags |= RegisterPutFlags::APPEND;
|
flags |= RegisterPutFlags::APPEND;
|
||||||
}
|
}
|
||||||
|
|
||||||
store.registers.put(®ister, cell, flags);
|
store.registers.put(®ister, cell, flags)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
return Ok(None);
|
return Ok(None);
|
||||||
@@ -724,7 +755,7 @@ impl EditorActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
|
|||||||
|
|
||||||
// Everything else is a modifying action.
|
// Everything else is a modifying action.
|
||||||
EditAction::ChangeCase(_) => Err(EditError::ReadOnly),
|
EditAction::ChangeCase(_) => Err(EditError::ReadOnly),
|
||||||
EditAction::ChangeNumber(_) => Err(EditError::ReadOnly),
|
EditAction::ChangeNumber(_, _) => Err(EditError::ReadOnly),
|
||||||
EditAction::Delete => Err(EditError::ReadOnly),
|
EditAction::Delete => Err(EditError::ReadOnly),
|
||||||
EditAction::Format => Err(EditError::ReadOnly),
|
EditAction::Format => Err(EditError::ReadOnly),
|
||||||
EditAction::Indent(_) => Err(EditError::ReadOnly),
|
EditAction::Indent(_) => Err(EditError::ReadOnly),
|
||||||
@@ -753,6 +784,17 @@ impl EditorActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn complete(
|
||||||
|
&mut self,
|
||||||
|
_: &CompletionType,
|
||||||
|
_: &CompletionSelection,
|
||||||
|
_: &CompletionDisplay,
|
||||||
|
_: &ProgramContext,
|
||||||
|
_: &mut ProgramStore,
|
||||||
|
) -> EditResult<EditInfo, IambInfo> {
|
||||||
|
Err(EditError::ReadOnly)
|
||||||
|
}
|
||||||
|
|
||||||
fn insert_text(
|
fn insert_text(
|
||||||
&mut self,
|
&mut self,
|
||||||
_: &InsertTextAction,
|
_: &InsertTextAction,
|
||||||
@@ -781,7 +823,7 @@ impl EditorActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
|
|||||||
HistoryAction::Checkpoint => Ok(None),
|
HistoryAction::Checkpoint => Ok(None),
|
||||||
HistoryAction::Undo(_) => Err(EditError::Failure("Nothing to undo".into())),
|
HistoryAction::Undo(_) => Err(EditError::Failure("Nothing to undo".into())),
|
||||||
HistoryAction::Redo(_) => Err(EditError::Failure("Nothing to redo".into())),
|
HistoryAction::Redo(_) => Err(EditError::Failure("Nothing to redo".into())),
|
||||||
_ => Err(EditError::Unimplemented(format!("Unknown action: {:?}", act))),
|
_ => Err(EditError::Unimplemented(format!("Unknown action: {act:?}"))),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -838,7 +880,7 @@ impl EditorActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
|
|||||||
|
|
||||||
Ok(None)
|
Ok(None)
|
||||||
},
|
},
|
||||||
_ => Err(EditError::Unimplemented(format!("Unknown action: {:?}", act))),
|
_ => Err(EditError::Unimplemented(format!("Unknown action: {act:?}"))),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -858,14 +900,14 @@ impl Editable<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
|
|||||||
EditorAction::Mark(name) => self.mark(ctx.resolve(name), ctx, store),
|
EditorAction::Mark(name) => self.mark(ctx.resolve(name), ctx, store),
|
||||||
EditorAction::Selection(act) => self.selection_command(act, ctx, store),
|
EditorAction::Selection(act) => self.selection_command(act, ctx, store),
|
||||||
|
|
||||||
EditorAction::Complete(_, _) => {
|
EditorAction::Complete(_, _, _) => {
|
||||||
let msg = "";
|
let msg = "Nothing to complete in message scrollback";
|
||||||
let err = EditError::Unimplemented(msg.into());
|
let err = EditError::Failure(msg.into());
|
||||||
|
|
||||||
Err(err)
|
Err(err)
|
||||||
},
|
},
|
||||||
|
|
||||||
_ => Err(EditError::Unimplemented(format!("Unknown action: {:?}", act))),
|
_ => Err(EditError::Unimplemented(format!("Unknown action: {act:?}"))),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -964,7 +1006,7 @@ impl Promptable<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
|
|||||||
return Err(err);
|
return Err(err);
|
||||||
},
|
},
|
||||||
_ => {
|
_ => {
|
||||||
let msg = format!("Messages scrollback doesn't support {:?}", act);
|
let msg = format!("Messages scrollback doesn't support {act:?}");
|
||||||
let err = EditError::Unimplemented(msg);
|
let err = EditError::Unimplemented(msg);
|
||||||
|
|
||||||
return Err(err);
|
return Err(err);
|
||||||
@@ -982,7 +1024,7 @@ impl ScrollActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
|
|||||||
ctx: &ProgramContext,
|
ctx: &ProgramContext,
|
||||||
store: &mut ProgramStore,
|
store: &mut ProgramStore,
|
||||||
) -> EditResult<EditInfo, IambInfo> {
|
) -> EditResult<EditInfo, IambInfo> {
|
||||||
let info = store.application.rooms.entry(self.room_id.clone()).or_default();
|
let info = store.application.rooms.get_or_default(self.room_id.clone());
|
||||||
let settings = &store.application.settings;
|
let settings = &store.application.settings;
|
||||||
let mut corner = self.viewctx.corner.clone();
|
let mut corner = self.viewctx.corner.clone();
|
||||||
|
|
||||||
@@ -1009,7 +1051,8 @@ impl ScrollActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
|
|||||||
|
|
||||||
for (key, item) in info.messages.range(..=&corner_key).rev() {
|
for (key, item) in info.messages.range(..=&corner_key).rev() {
|
||||||
let sel = key == cursor_key;
|
let sel = key == cursor_key;
|
||||||
let txt = item.show(None, sel, &self.viewctx, info, settings);
|
let prev = prevmsg(key, info);
|
||||||
|
let txt = item.show(prev, sel, &self.viewctx, info, settings);
|
||||||
let len = txt.height().max(1);
|
let len = txt.height().max(1);
|
||||||
let max = len.saturating_sub(1);
|
let max = len.saturating_sub(1);
|
||||||
|
|
||||||
@@ -1033,12 +1076,16 @@ impl ScrollActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
MoveDir2D::Down => {
|
MoveDir2D::Down => {
|
||||||
|
let mut prev = prevmsg(&corner_key, info);
|
||||||
|
|
||||||
for (key, item) in info.messages.range(&corner_key..) {
|
for (key, item) in info.messages.range(&corner_key..) {
|
||||||
let sel = key == cursor_key;
|
let sel = key == cursor_key;
|
||||||
let txt = item.show(None, sel, &self.viewctx, info, settings);
|
let txt = item.show(prev, sel, &self.viewctx, info, settings);
|
||||||
let len = txt.height().max(1);
|
let len = txt.height().max(1);
|
||||||
let max = len.saturating_sub(1);
|
let max = len.saturating_sub(1);
|
||||||
|
|
||||||
|
prev = Some(item);
|
||||||
|
|
||||||
if key != &corner_key {
|
if key != &corner_key {
|
||||||
corner.text_row = 0;
|
corner.text_row = 0;
|
||||||
}
|
}
|
||||||
@@ -1091,7 +1138,7 @@ impl ScrollActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
|
|||||||
Err(err)
|
Err(err)
|
||||||
},
|
},
|
||||||
Axis::Vertical => {
|
Axis::Vertical => {
|
||||||
let info = store.application.rooms.entry(self.room_id.clone()).or_default();
|
let info = store.application.rooms.get_or_default(self.room_id.clone());
|
||||||
let settings = &store.application.settings;
|
let settings = &store.application.settings;
|
||||||
|
|
||||||
if let Some(key) = self.cursor.to_key(info).cloned() {
|
if let Some(key) = self.cursor.to_key(info).cloned() {
|
||||||
@@ -1179,7 +1226,7 @@ impl<'a> StatefulWidget for Scrollback<'a> {
|
|||||||
type State = ScrollbackState;
|
type State = ScrollbackState;
|
||||||
|
|
||||||
fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
|
fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
|
||||||
let info = self.store.application.rooms.entry(state.room_id.clone()).or_default();
|
let info = self.store.application.rooms.get_or_default(state.room_id.clone());
|
||||||
let settings = &self.store.application.settings;
|
let settings = &self.store.application.settings;
|
||||||
let area = info.render_typing(area, buf, &self.store.application.settings);
|
let area = info.render_typing(area, buf, &self.store.application.settings);
|
||||||
|
|
||||||
@@ -1214,7 +1261,7 @@ impl<'a> StatefulWidget for Scrollback<'a> {
|
|||||||
let full = std::mem::take(&mut state.show_full_on_redraw) || cursor.timestamp.is_none();
|
let full = std::mem::take(&mut state.show_full_on_redraw) || cursor.timestamp.is_none();
|
||||||
let mut lines = vec![];
|
let mut lines = vec![];
|
||||||
let mut sawit = false;
|
let mut sawit = false;
|
||||||
let mut prev = None;
|
let mut prev = prevmsg(&corner_key, info);
|
||||||
|
|
||||||
for (key, item) in info.messages.range(&corner_key..) {
|
for (key, item) in info.messages.range(&corner_key..) {
|
||||||
let sel = key == cursor_key;
|
let sel = key == cursor_key;
|
||||||
@@ -1373,10 +1420,11 @@ mod tests {
|
|||||||
assert_eq!(scrollback.viewctx.dimensions, (0, 0));
|
assert_eq!(scrollback.viewctx.dimensions, (0, 0));
|
||||||
assert_eq!(scrollback.viewctx.corner, MessageCursor::latest());
|
assert_eq!(scrollback.viewctx.corner, MessageCursor::latest());
|
||||||
|
|
||||||
// Set a terminal width of 60, and height of 3, rendering in scrollback as:
|
// Set a terminal width of 60, and height of 4, rendering in scrollback as:
|
||||||
//
|
//
|
||||||
// |------------------------------------------------------------|
|
// |------------------------------------------------------------|
|
||||||
// MSG2: | @user2:example.com helium |
|
// MSG2: | Wednesday, December 31 1969 |
|
||||||
|
// | @user2:example.com helium |
|
||||||
// MSG3: | @user2:example.com this |
|
// MSG3: | @user2:example.com this |
|
||||||
// | is |
|
// | is |
|
||||||
// | a |
|
// | a |
|
||||||
@@ -1384,14 +1432,15 @@ mod tests {
|
|||||||
// | message |
|
// | message |
|
||||||
// MSG4: | @user1:example.com help |
|
// MSG4: | @user1:example.com help |
|
||||||
// MSG5: | @user2:example.com character |
|
// MSG5: | @user2:example.com character |
|
||||||
// MSG1: | @user1:example.com writhe |
|
// MSG1: | XXXday, Month NN 20XX |
|
||||||
|
// | @user1:example.com writhe |
|
||||||
// |------------------------------------------------------------|
|
// |------------------------------------------------------------|
|
||||||
let area = Rect::new(0, 0, 60, 3);
|
let area = Rect::new(0, 0, 60, 4);
|
||||||
let mut buffer = Buffer::empty(area);
|
let mut buffer = Buffer::empty(area);
|
||||||
scrollback.draw(area, &mut buffer, true, &mut store);
|
scrollback.draw(area, &mut buffer, true, &mut store);
|
||||||
|
|
||||||
assert_eq!(scrollback.cursor, MessageCursor::latest());
|
assert_eq!(scrollback.cursor, MessageCursor::latest());
|
||||||
assert_eq!(scrollback.viewctx.dimensions, (60, 3));
|
assert_eq!(scrollback.viewctx.dimensions, (60, 4));
|
||||||
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG4_KEY.clone(), 0));
|
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG4_KEY.clone(), 0));
|
||||||
|
|
||||||
// Scroll up a line at a time until we hit the first message.
|
// Scroll up a line at a time until we hit the first message.
|
||||||
@@ -1420,6 +1469,11 @@ mod tests {
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG3_KEY.clone(), 0));
|
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
|
scrollback
|
||||||
.dirscroll(prev, ScrollSize::Cell, &1.into(), &ctx, &mut store)
|
.dirscroll(prev, ScrollSize::Cell, &1.into(), &ctx, &mut store)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -1432,6 +1486,11 @@ mod tests {
|
|||||||
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG2_KEY.clone(), 0));
|
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG2_KEY.clone(), 0));
|
||||||
|
|
||||||
// Now scroll back down one line at a time.
|
// 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
|
scrollback
|
||||||
.dirscroll(next, ScrollSize::Cell, &1.into(), &ctx, &mut store)
|
.dirscroll(next, ScrollSize::Cell, &1.into(), &ctx, &mut store)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -1472,19 +1531,24 @@ mod tests {
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG1_KEY.clone(), 0));
|
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.
|
// Cannot scroll down any further.
|
||||||
scrollback
|
scrollback
|
||||||
.dirscroll(next, ScrollSize::Cell, &1.into(), &ctx, &mut store)
|
.dirscroll(next, ScrollSize::Cell, &1.into(), &ctx, &mut store)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG1_KEY.clone(), 0));
|
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG1_KEY.clone(), 1));
|
||||||
|
|
||||||
// Scroll up two Pages (six lines).
|
// Scroll up two Pages (eight lines).
|
||||||
scrollback
|
scrollback
|
||||||
.dirscroll(prev, ScrollSize::Page, &2.into(), &ctx, &mut store)
|
.dirscroll(prev, ScrollSize::Page, &2.into(), &ctx, &mut store)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG3_KEY.clone(), 1));
|
assert_eq!(scrollback.viewctx.corner, MessageCursor::new(MSG3_KEY.clone(), 0));
|
||||||
|
|
||||||
// Scroll down two HalfPages (three lines).
|
// Scroll down two HalfPages (four lines).
|
||||||
scrollback
|
scrollback
|
||||||
.dirscroll(next, ScrollSize::HalfPage, &2.into(), &ctx, &mut store)
|
.dirscroll(next, ScrollSize::HalfPage, &2.into(), &ctx, &mut store)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -1503,7 +1567,8 @@ mod tests {
|
|||||||
// Set a terminal width of 60, and height of 3, rendering in scrollback as:
|
// Set a terminal width of 60, and height of 3, rendering in scrollback as:
|
||||||
//
|
//
|
||||||
// |------------------------------------------------------------|
|
// |------------------------------------------------------------|
|
||||||
// MSG2: | @user2:example.com helium |
|
// MSG2: | Wednesday, December 31 1969 |
|
||||||
|
// | @user2:example.com helium |
|
||||||
// MSG3: | @user2:example.com this |
|
// MSG3: | @user2:example.com this |
|
||||||
// | is |
|
// | is |
|
||||||
// | a |
|
// | a |
|
||||||
@@ -1511,7 +1576,8 @@ mod tests {
|
|||||||
// | message |
|
// | message |
|
||||||
// MSG4: | @user1:example.com help |
|
// MSG4: | @user1:example.com help |
|
||||||
// MSG5: | @user2:example.com character |
|
// MSG5: | @user2:example.com character |
|
||||||
// MSG1: | @user1:example.com writhe |
|
// MSG1: | XXXday, Month NN 20XX |
|
||||||
|
// | @user1:example.com writhe |
|
||||||
// |------------------------------------------------------------|
|
// |------------------------------------------------------------|
|
||||||
let area = Rect::new(0, 0, 60, 3);
|
let area = Rect::new(0, 0, 60, 3);
|
||||||
let mut buffer = Buffer::empty(area);
|
let mut buffer = Buffer::empty(area);
|
||||||
|
|||||||
@@ -8,9 +8,11 @@ use modalkit::{
|
|||||||
widgets::{TermOffset, TerminalCursor},
|
widgets::{TermOffset, TerminalCursor},
|
||||||
};
|
};
|
||||||
|
|
||||||
use modalkit::editing::base::{CloseFlags, WordStyle};
|
use modalkit::editing::action::EditInfo;
|
||||||
|
use modalkit::editing::base::{CloseFlags, WordStyle, WriteFlags};
|
||||||
|
use modalkit::editing::completion::CompletionList;
|
||||||
|
|
||||||
use crate::base::{IambBufferId, IambInfo, ProgramStore};
|
use crate::base::{IambBufferId, IambInfo, IambResult, ProgramStore};
|
||||||
|
|
||||||
const WELCOME_TEXT: &str = include_str!("welcome.md");
|
const WELCOME_TEXT: &str = include_str!("welcome.md");
|
||||||
|
|
||||||
@@ -63,6 +65,19 @@ impl WindowOps<IambInfo> for WelcomeState {
|
|||||||
self.tbox.close(flags, store)
|
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> {
|
fn get_cursor_word(&self, style: &WordStyle) -> Option<String> {
|
||||||
self.tbox.get_cursor_word(style)
|
self.tbox.get_cursor_word(style)
|
||||||
}
|
}
|
||||||
|
|||||||
438
src/worker.rs
438
src/worker.rs
@@ -1,3 +1,4 @@
|
|||||||
|
use std::collections::HashMap;
|
||||||
use std::convert::TryFrom;
|
use std::convert::TryFrom;
|
||||||
use std::fmt::{Debug, Formatter};
|
use std::fmt::{Debug, Formatter};
|
||||||
use std::fs::File;
|
use std::fs::File;
|
||||||
@@ -5,25 +6,27 @@ use std::io::BufWriter;
|
|||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
use std::sync::mpsc::{sync_channel, Receiver, SyncSender};
|
use std::sync::mpsc::{sync_channel, Receiver, SyncSender};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::Duration;
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
use gethostname::gethostname;
|
use gethostname::gethostname;
|
||||||
use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
|
use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
|
||||||
use tokio::task::JoinHandle;
|
use tokio::task::JoinHandle;
|
||||||
use tracing::error;
|
use tracing::{error, warn};
|
||||||
|
|
||||||
use matrix_sdk::{
|
use matrix_sdk::{
|
||||||
config::{RequestConfig, StoreConfig, SyncSettings},
|
config::{RequestConfig, SyncSettings},
|
||||||
encryption::verification::{SasVerification, Verification},
|
encryption::verification::{SasVerification, Verification},
|
||||||
event_handler::Ctx,
|
event_handler::Ctx,
|
||||||
reqwest,
|
reqwest,
|
||||||
room::{Invited, Messages, MessagesOptions, Room as MatrixRoom, RoomMember},
|
room::{Invited, Messages, MessagesOptions, Room as MatrixRoom, RoomMember},
|
||||||
ruma::{
|
ruma::{
|
||||||
api::client::{
|
api::client::{
|
||||||
room::create_room::v3::{Request as CreateRoomRequest, RoomPreset},
|
filter::{FilterDefinition, LazyLoadOptions, RoomEventFilter, RoomFilter},
|
||||||
|
room::create_room::v3::{CreationContent, Request as CreateRoomRequest, RoomPreset},
|
||||||
room::Visibility,
|
room::Visibility,
|
||||||
space::get_hierarchy::v1::Request as SpaceHierarchyRequest,
|
space::get_hierarchy::v1::Request as SpaceHierarchyRequest,
|
||||||
},
|
},
|
||||||
|
assign,
|
||||||
events::{
|
events::{
|
||||||
key::verification::{
|
key::verification::{
|
||||||
done::{OriginalSyncKeyVerificationDoneEvent, ToDeviceKeyVerificationDoneEvent},
|
done::{OriginalSyncKeyVerificationDoneEvent, ToDeviceKeyVerificationDoneEvent},
|
||||||
@@ -32,21 +35,31 @@ use matrix_sdk::{
|
|||||||
start::{OriginalSyncKeyVerificationStartEvent, ToDeviceKeyVerificationStartEvent},
|
start::{OriginalSyncKeyVerificationStartEvent, ToDeviceKeyVerificationStartEvent},
|
||||||
VerificationMethod,
|
VerificationMethod,
|
||||||
},
|
},
|
||||||
|
presence::PresenceEvent,
|
||||||
|
reaction::ReactionEventContent,
|
||||||
room::{
|
room::{
|
||||||
|
encryption::RoomEncryptionEventContent,
|
||||||
message::{MessageType, RoomMessageEventContent},
|
message::{MessageType, RoomMessageEventContent},
|
||||||
name::RoomNameEventContent,
|
name::RoomNameEventContent,
|
||||||
redaction::{OriginalSyncRoomRedactionEvent, SyncRoomRedactionEvent},
|
redaction::{OriginalSyncRoomRedactionEvent, SyncRoomRedactionEvent},
|
||||||
},
|
},
|
||||||
tag::Tags,
|
tag::Tags,
|
||||||
typing::SyncTypingEvent,
|
typing::SyncTypingEvent,
|
||||||
|
AnyInitialStateEvent,
|
||||||
AnyMessageLikeEvent,
|
AnyMessageLikeEvent,
|
||||||
AnyTimelineEvent,
|
AnyTimelineEvent,
|
||||||
|
EmptyStateKey,
|
||||||
|
InitialStateEvent,
|
||||||
SyncMessageLikeEvent,
|
SyncMessageLikeEvent,
|
||||||
SyncStateEvent,
|
SyncStateEvent,
|
||||||
},
|
},
|
||||||
|
room::RoomType,
|
||||||
|
serde::Raw,
|
||||||
|
EventEncryptionAlgorithm,
|
||||||
OwnedRoomId,
|
OwnedRoomId,
|
||||||
OwnedRoomOrAliasId,
|
OwnedRoomOrAliasId,
|
||||||
OwnedUserId,
|
OwnedUserId,
|
||||||
|
RoomId,
|
||||||
RoomVersionId,
|
RoomVersionId,
|
||||||
},
|
},
|
||||||
Client,
|
Client,
|
||||||
@@ -57,19 +70,211 @@ use matrix_sdk::{
|
|||||||
use modalkit::editing::action::{EditInfo, InfoMessage, UIError};
|
use modalkit::editing::action::{EditInfo, InfoMessage, UIError};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
base::{AsyncProgramStore, IambError, IambResult, Receipts, VerifyAction},
|
base::{
|
||||||
|
AsyncProgramStore,
|
||||||
|
ChatStore,
|
||||||
|
CreateRoomFlags,
|
||||||
|
CreateRoomType,
|
||||||
|
EventLocation,
|
||||||
|
IambError,
|
||||||
|
IambResult,
|
||||||
|
Receipts,
|
||||||
|
RoomFetchStatus,
|
||||||
|
VerifyAction,
|
||||||
|
},
|
||||||
message::MessageFetchResult,
|
message::MessageFetchResult,
|
||||||
ApplicationSettings,
|
ApplicationSettings,
|
||||||
};
|
};
|
||||||
|
|
||||||
const IAMB_DEVICE_NAME: &str = "iamb";
|
const IAMB_DEVICE_NAME: &str = "iamb";
|
||||||
const IAMB_USER_AGENT: &str = "iamb";
|
const IAMB_USER_AGENT: &str = "iamb";
|
||||||
const REQ_TIMEOUT: Duration = Duration::from_secs(60);
|
const MIN_MSG_LOAD: u32 = 50;
|
||||||
|
|
||||||
fn initial_devname() -> String {
|
fn initial_devname() -> String {
|
||||||
format!("{} on {}", IAMB_DEVICE_NAME, gethostname().to_string_lossy())
|
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) {
|
||||||
|
let limit = MIN_MSG_LOAD;
|
||||||
|
let plan = load_plan(store).await;
|
||||||
|
|
||||||
|
// Fetch each room separately, so they don't block each other.
|
||||||
|
for (room_id, fetch_id) in plan.into_iter() {
|
||||||
|
let client = client.clone();
|
||||||
|
let store = store.clone();
|
||||||
|
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let res = load_older_one(client, room_id.as_ref(), fetch_id, limit).await;
|
||||||
|
load_insert(room_id, res, store).await;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum LoginStyle {
|
pub enum LoginStyle {
|
||||||
SessionRestore(Session),
|
SessionRestore(Session),
|
||||||
@@ -128,7 +333,6 @@ pub enum WorkerTask {
|
|||||||
ActiveRooms(ClientReply<Vec<FetchedRoom>>),
|
ActiveRooms(ClientReply<Vec<FetchedRoom>>),
|
||||||
DirectMessages(ClientReply<Vec<FetchedRoom>>),
|
DirectMessages(ClientReply<Vec<FetchedRoom>>),
|
||||||
Init(AsyncProgramStore, ClientReply<()>),
|
Init(AsyncProgramStore, ClientReply<()>),
|
||||||
LoadOlder(OwnedRoomId, Option<String>, u32, ClientReply<MessageFetchResult>),
|
|
||||||
Login(LoginStyle, ClientReply<IambResult<EditInfo>>),
|
Login(LoginStyle, ClientReply<IambResult<EditInfo>>),
|
||||||
GetInviter(Invited, ClientReply<IambResult<Option<RoomMember>>>),
|
GetInviter(Invited, ClientReply<IambResult<Option<RoomMember>>>),
|
||||||
GetRoom(OwnedRoomId, ClientReply<IambResult<FetchedRoom>>),
|
GetRoom(OwnedRoomId, ClientReply<IambResult<FetchedRoom>>),
|
||||||
@@ -158,14 +362,6 @@ impl Debug for WorkerTask {
|
|||||||
.field(&format_args!("_"))
|
.field(&format_args!("_"))
|
||||||
.finish()
|
.finish()
|
||||||
},
|
},
|
||||||
WorkerTask::LoadOlder(room_id, from, n, _) => {
|
|
||||||
f.debug_tuple("WorkerTask::LoadOlder")
|
|
||||||
.field(room_id)
|
|
||||||
.field(from)
|
|
||||||
.field(n)
|
|
||||||
.field(&format_args!("_"))
|
|
||||||
.finish()
|
|
||||||
},
|
|
||||||
WorkerTask::Login(style, _) => {
|
WorkerTask::Login(style, _) => {
|
||||||
f.debug_tuple("WorkerTask::Login")
|
f.debug_tuple("WorkerTask::Login")
|
||||||
.field(style)
|
.field(style)
|
||||||
@@ -237,21 +433,6 @@ impl Requester {
|
|||||||
return response.recv();
|
return response.recv();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn load_older(
|
|
||||||
&self,
|
|
||||||
room_id: OwnedRoomId,
|
|
||||||
fetch_id: Option<String>,
|
|
||||||
limit: u32,
|
|
||||||
) -> MessageFetchResult {
|
|
||||||
let (reply, response) = oneshot();
|
|
||||||
|
|
||||||
self.tx
|
|
||||||
.send(WorkerTask::LoadOlder(room_id, fetch_id, limit, reply))
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
return response.recv();
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn login(&self, style: LoginStyle) -> IambResult<EditInfo> {
|
pub fn login(&self, style: LoginStyle) -> IambResult<EditInfo> {
|
||||||
let (reply, response) = oneshot();
|
let (reply, response) = oneshot();
|
||||||
|
|
||||||
@@ -349,6 +530,8 @@ pub struct ClientWorker {
|
|||||||
initialized: bool,
|
initialized: bool,
|
||||||
settings: ApplicationSettings,
|
settings: ApplicationSettings,
|
||||||
client: Client,
|
client: Client,
|
||||||
|
load_handle: Option<JoinHandle<()>>,
|
||||||
|
rcpt_handle: Option<JoinHandle<()>>,
|
||||||
sync_handle: Option<JoinHandle<()>>,
|
sync_handle: Option<JoinHandle<()>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -357,28 +540,27 @@ impl ClientWorker {
|
|||||||
let (tx, rx) = unbounded_channel();
|
let (tx, rx) = unbounded_channel();
|
||||||
let account = &settings.profile;
|
let account = &settings.profile;
|
||||||
|
|
||||||
// Set up a custom client that only uses HTTP/1.
|
let req_timeout = Duration::from_secs(settings.tunables.request_timeout);
|
||||||
//
|
|
||||||
// During my testing, I kept stumbling across something weird with sync and HTTP/2 that
|
// Set up the HTTP client.
|
||||||
// will need to be revisited in the future.
|
|
||||||
let http = reqwest::Client::builder()
|
let http = reqwest::Client::builder()
|
||||||
.user_agent(IAMB_USER_AGENT)
|
.user_agent(IAMB_USER_AGENT)
|
||||||
.timeout(Duration::from_secs(30))
|
.timeout(req_timeout)
|
||||||
.pool_idle_timeout(Duration::from_secs(60))
|
.pool_idle_timeout(Duration::from_secs(60))
|
||||||
.pool_max_idle_per_host(10)
|
.pool_max_idle_per_host(10)
|
||||||
.tcp_keepalive(Duration::from_secs(10))
|
.tcp_keepalive(Duration::from_secs(10))
|
||||||
.http1_only()
|
|
||||||
.build()
|
.build()
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
|
let req_config = RequestConfig::new().timeout(req_timeout).retry_timeout(req_timeout);
|
||||||
|
|
||||||
// Set up the Matrix client for the selected profile.
|
// Set up the Matrix client for the selected profile.
|
||||||
let client = Client::builder()
|
let client = Client::builder()
|
||||||
.http_client(Arc::new(http))
|
.http_client(Arc::new(http))
|
||||||
.homeserver_url(account.url.clone())
|
.homeserver_url(account.url.clone())
|
||||||
.store_config(StoreConfig::default())
|
|
||||||
.sled_store(settings.matrix_dir.as_path(), None)
|
.sled_store(settings.matrix_dir.as_path(), None)
|
||||||
.expect("Failed to setup up sled store for Matrix SDK")
|
.expect("Failed to setup up sled store for Matrix SDK")
|
||||||
.request_config(RequestConfig::new().timeout(REQ_TIMEOUT).retry_timeout(REQ_TIMEOUT))
|
.request_config(req_config)
|
||||||
.build()
|
.build()
|
||||||
.await
|
.await
|
||||||
.expect("Failed to instantiate Matrix client");
|
.expect("Failed to instantiate Matrix client");
|
||||||
@@ -387,10 +569,12 @@ impl ClientWorker {
|
|||||||
initialized: false,
|
initialized: false,
|
||||||
settings,
|
settings,
|
||||||
client: client.clone(),
|
client: client.clone(),
|
||||||
|
load_handle: None,
|
||||||
|
rcpt_handle: None,
|
||||||
sync_handle: None,
|
sync_handle: None,
|
||||||
};
|
};
|
||||||
|
|
||||||
let _ = tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
worker.work(rx).await;
|
worker.work(rx).await;
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -412,6 +596,10 @@ impl ClientWorker {
|
|||||||
if let Some(handle) = self.sync_handle.take() {
|
if let Some(handle) = self.sync_handle.take() {
|
||||||
handle.abort();
|
handle.abort();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if let Some(handle) = self.rcpt_handle.take() {
|
||||||
|
handle.abort();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn run(&mut self, task: WorkerTask) {
|
async fn run(&mut self, task: WorkerTask) {
|
||||||
@@ -441,10 +629,6 @@ impl ClientWorker {
|
|||||||
assert!(self.initialized);
|
assert!(self.initialized);
|
||||||
reply.send(self.active_rooms().await);
|
reply.send(self.active_rooms().await);
|
||||||
},
|
},
|
||||||
WorkerTask::LoadOlder(room_id, fetch_id, limit, reply) => {
|
|
||||||
assert!(self.initialized);
|
|
||||||
reply.send(self.load_older(room_id, fetch_id, limit).await);
|
|
||||||
},
|
|
||||||
WorkerTask::Login(style, reply) => {
|
WorkerTask::Login(style, reply) => {
|
||||||
assert!(self.initialized);
|
assert!(self.initialized);
|
||||||
reply.send(self.login_and_sync(style).await);
|
reply.send(self.login_and_sync(style).await);
|
||||||
@@ -497,6 +681,15 @@ impl ClientWorker {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
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(
|
let _ = self.client.add_event_handler(
|
||||||
|ev: SyncStateEvent<RoomNameEventContent>,
|
|ev: SyncStateEvent<RoomNameEventContent>,
|
||||||
room: MatrixRoom,
|
room: MatrixRoom,
|
||||||
@@ -507,8 +700,7 @@ impl ClientWorker {
|
|||||||
let room_id = room.room_id().to_owned();
|
let room_id = room.room_id().to_owned();
|
||||||
let room_name = Some(room_name.to_string());
|
let room_name = Some(room_name.to_string());
|
||||||
let mut locked = store.lock().await;
|
let mut locked = store.lock().await;
|
||||||
let mut info =
|
let mut info = locked.application.rooms.get_or_default(room_id.clone());
|
||||||
locked.application.rooms.entry(room_id.to_owned()).or_default();
|
|
||||||
info.name = room_name;
|
info.name = room_name;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -523,8 +715,6 @@ impl ClientWorker {
|
|||||||
store: Ctx<AsyncProgramStore>| {
|
store: Ctx<AsyncProgramStore>| {
|
||||||
async move {
|
async move {
|
||||||
let room_id = room.room_id();
|
let room_id = room.room_id();
|
||||||
let room_name = room.display_name().await.ok();
|
|
||||||
let room_name = room_name.as_ref().map(ToString::to_string);
|
|
||||||
|
|
||||||
if let Some(msg) = ev.as_original() {
|
if let Some(msg) = ev.as_original() {
|
||||||
if let MessageType::VerificationRequest(_) = msg.content.msgtype {
|
if let MessageType::VerificationRequest(_) = msg.content.msgtype {
|
||||||
@@ -539,13 +729,34 @@ impl ClientWorker {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let mut locked = store.lock().await;
|
let mut locked = store.lock().await;
|
||||||
let mut info = locked.application.get_room_info(room_id.to_owned());
|
|
||||||
info.name = room_name;
|
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()));
|
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(
|
let _ = self.client.add_event_handler(
|
||||||
|ev: OriginalSyncRoomRedactionEvent,
|
|ev: OriginalSyncRoomRedactionEvent,
|
||||||
room: MatrixRoom,
|
room: MatrixRoom,
|
||||||
@@ -558,15 +769,21 @@ impl ClientWorker {
|
|||||||
let mut locked = store.lock().await;
|
let mut locked = store.lock().await;
|
||||||
let info = locked.application.get_room_info(room_id.to_owned());
|
let info = locked.application.get_room_info(room_id.to_owned());
|
||||||
|
|
||||||
let key = if let Some(k) = info.keys.get(&ev.redacts) {
|
match info.keys.get(&ev.redacts) {
|
||||||
k
|
None => return,
|
||||||
} else {
|
Some(EventLocation::Message(key)) => {
|
||||||
return;
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
if let Some(msg) = info.messages.get_mut(key) {
|
info.keys.remove(&ev.redacts);
|
||||||
let ev = SyncRoomRedactionEvent::Original(ev);
|
},
|
||||||
msg.event.redact(ev, room_version);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -684,18 +901,37 @@ impl ClientWorker {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
let client = self.client.clone();
|
self.rcpt_handle = tokio::spawn({
|
||||||
let _ = tokio::spawn(async move {
|
let store = store.clone();
|
||||||
// Update the displayed read receipts ever 5 seconds.
|
let client = self.client.clone();
|
||||||
let mut interval = tokio::time::interval(Duration::from_secs(5));
|
|
||||||
|
|
||||||
loop {
|
async move {
|
||||||
interval.tick().await;
|
// Update the displayed read receipts every 5 seconds.
|
||||||
|
let mut interval = tokio::time::interval(Duration::from_secs(5));
|
||||||
|
|
||||||
let receipts = update_receipts(&client).await;
|
loop {
|
||||||
store.lock().await.application.set_receipts(receipts).await;
|
interval.tick().await;
|
||||||
|
|
||||||
|
let receipts = update_receipts(&client).await;
|
||||||
|
store.lock().await.application.set_receipts(receipts).await;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
|
.into();
|
||||||
|
|
||||||
|
self.load_handle = tokio::spawn({
|
||||||
|
let client = self.client.clone();
|
||||||
|
|
||||||
|
async move {
|
||||||
|
// 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.into();
|
||||||
|
|
||||||
self.initialized = true;
|
self.initialized = true;
|
||||||
}
|
}
|
||||||
@@ -731,10 +967,19 @@ impl ClientWorker {
|
|||||||
|
|
||||||
self.sync_handle = Some(handle);
|
self.sync_handle = Some(handle);
|
||||||
|
|
||||||
self.client
|
// Perform an initial, lazily-loaded sync.
|
||||||
.sync_once(SyncSettings::default())
|
let mut room = RoomEventFilter::default();
|
||||||
.await
|
room.lazy_load_options = LazyLoadOptions::Enabled { include_redundant_members: false };
|
||||||
.map_err(IambError::from)?;
|
|
||||||
|
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());
|
||||||
|
|
||||||
|
self.client.sync_once(settings).await.map_err(IambError::from)?;
|
||||||
|
|
||||||
Ok(Some(InfoMessage::from("Successfully logged in!")))
|
Ok(Some(InfoMessage::from("Successfully logged in!")))
|
||||||
}
|
}
|
||||||
@@ -746,15 +991,11 @@ impl ClientWorker {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut request = CreateRoomRequest::new();
|
let rt = CreateRoomType::Direct(user.clone());
|
||||||
let invite = [user.clone()];
|
let flags = CreateRoomFlags::ENCRYPTED;
|
||||||
request.is_direct = true;
|
|
||||||
request.invite = &invite;
|
|
||||||
request.visibility = Visibility::Private;
|
|
||||||
request.preset = Some(RoomPreset::PrivateChat);
|
|
||||||
|
|
||||||
match self.client.create_room(request).await {
|
match create_room(&self.client, None, rt, flags).await {
|
||||||
Ok(resp) => self.get_room(resp.room_id).await,
|
Ok(room_id) => self.get_room(room_id).await,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
error!(
|
error!(
|
||||||
user_id = user.as_str(),
|
user_id = user.as_str(),
|
||||||
@@ -762,7 +1003,7 @@ impl ClientWorker {
|
|||||||
"Failed to create direct message room"
|
"Failed to create direct message room"
|
||||||
);
|
);
|
||||||
|
|
||||||
let msg = format!("Could not open a room with {}", user);
|
let msg = format!("Could not open a room with {user}");
|
||||||
let err = UIError::Failure(msg);
|
let err = UIError::Failure(msg);
|
||||||
|
|
||||||
Err(err)
|
Err(err)
|
||||||
@@ -866,41 +1107,6 @@ impl ClientWorker {
|
|||||||
return rooms;
|
return rooms;
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn load_older(
|
|
||||||
&mut self,
|
|
||||||
room_id: OwnedRoomId,
|
|
||||||
fetch_id: Option<String>,
|
|
||||||
limit: u32,
|
|
||||||
) -> MessageFetchResult {
|
|
||||||
if let Some(room) = self.client.get_room(room_id.as_ref()) {
|
|
||||||
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)) => {
|
|
||||||
if let AnyMessageLikeEvent::RoomMessage(msg) = msg {
|
|
||||||
Some(msg)
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
},
|
|
||||||
Ok(AnyTimelineEvent::State(_)) => None,
|
|
||||||
Err(_) => None,
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
Ok((end, msgs.collect()))
|
|
||||||
} else {
|
|
||||||
Err(IambError::UnknownRoom(room_id).into())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn members(&mut self, room_id: OwnedRoomId) -> IambResult<Vec<RoomMember>> {
|
async fn members(&mut self, room_id: OwnedRoomId) -> IambResult<Vec<RoomMember>> {
|
||||||
if let Some(room) = self.client.get_room(room_id.as_ref()) {
|
if let Some(room) = self.client.get_room(room_id.as_ref()) {
|
||||||
Ok(room.active_members().await.map_err(IambError::from)?)
|
Ok(room.active_members().await.map_err(IambError::from)?)
|
||||||
@@ -1007,12 +1213,12 @@ impl ClientWorker {
|
|||||||
let methods = vec![VerificationMethod::SasV1];
|
let methods = vec![VerificationMethod::SasV1];
|
||||||
let request = identity.request_verification_with_methods(methods);
|
let request = identity.request_verification_with_methods(methods);
|
||||||
let _req = request.await.map_err(IambError::from)?;
|
let _req = request.await.map_err(IambError::from)?;
|
||||||
let info = format!("Sent verification request to {}", user_id);
|
let info = format!("Sent verification request to {user_id}");
|
||||||
|
|
||||||
Ok(InfoMessage::from(info).into())
|
Ok(InfoMessage::from(info).into())
|
||||||
},
|
},
|
||||||
None => {
|
None => {
|
||||||
let msg = format!("Could not find identity information for {}", user_id);
|
let msg = format!("Could not find identity information for {user_id}");
|
||||||
let err = UIError::Failure(msg);
|
let err = UIError::Failure(msg);
|
||||||
|
|
||||||
Err(err)
|
Err(err)
|
||||||
|
|||||||
Reference in New Issue
Block a user