Commit 4f2261e66f

4f2261e66f41580d2add92234fc9f3d68eb669be

parent: 8966644f6e

Unregistered key

Ulyssa <git@ulyssa.dev> · 2023-01-24 01:08 UTC

Support sending and displaying formatted messages (#10)

Layout: unified · split

Cargo.lock +234 −40
@@ -124,9 +124,9 @@ dependencies = [
124124
125125[[package]]
126126name = "async-trait"
127version = "0.1.61"
127version = "0.1.63"
128128source = "registry+https://github.com/rust-lang/crates.io-index"
129checksum = "705339e0e4a9690e2908d2b3d049d85682cf19fbd5782494498fbf7003a6a282"
129checksum = "eff18d764974428cf3a9328e23fc5c986f5fbed46e6cd4cdf42544df5d297ec1"
130130dependencies = [
131131 "proc-macro2",
132132 "quote",
@@ -229,9 +229,9 @@ dependencies = [
229229
230230[[package]]
231231name = "bumpalo"
232version = "3.11.1"
232version = "3.12.0"
233233source = "registry+https://github.com/rust-lang/crates.io-index"
234checksum = "572f695136211188308f16ad2ca5c851a712c464060ae6974944458eb83880ba"
234checksum = "0d261e256854913907f67ed06efbc3338dfe6179796deefc1ff763fc1aee5535"
235235
236236[[package]]
237237name = "byteorder"
@@ -333,9 +333,9 @@ dependencies = [
333333
334334[[package]]
335335name = "clap"
336version = "4.1.0"
336version = "4.1.2"
337337source = "registry+https://github.com/rust-lang/crates.io-index"
338checksum = "aa91278560fc226a5d9d736cc21e485ff9aad47d26b8ffe1f54cba868b684b9f"
338checksum = "0e638668a62aced2c9fb72b5135a33b4a500485ccf2a0e402e09aa04ab2fc115"
339339dependencies = [
340340 "bitflags",
341341 "clap_derive",
@@ -487,6 +487,15 @@ dependencies = [
487487 "typenum",
488488]
489489
490[[package]]
491name = "css-color-parser"
492version = "0.1.2"
493source = "registry+https://github.com/rust-lang/crates.io-index"
494checksum = "9ccb6ce7ef97e6dc6e575e51b596c9889a5cc88a307b5ef177d215c61fd7581d"
495dependencies = [
496 "lazy_static 0.1.16",
497]
498
490499[[package]]
491500name = "ctr"
492501version = "0.9.2"
@@ -512,9 +521,9 @@ dependencies = [
512521
513522[[package]]
514523name = "cxx"
515version = "1.0.86"
524version = "1.0.87"
516525source = "registry+https://github.com/rust-lang/crates.io-index"
517checksum = "51d1075c37807dcf850c379432f0df05ba52cc30f279c5cfc43cc221ce7f8579"
526checksum = "b61a7545f753a88bcbe0a70de1fcc0221e10bfc752f576754fa91e663db1622e"
518527dependencies = [
519528 "cc",
520529 "cxxbridge-flags",
@@ -524,9 +533,9 @@ dependencies = [
524533
525534[[package]]
526535name = "cxx-build"
527version = "1.0.86"
536version = "1.0.87"
528537source = "registry+https://github.com/rust-lang/crates.io-index"
529checksum = "5044281f61b27bc598f2f6647d480aed48d2bf52d6eb0b627d84c0361b17aa70"
538checksum = "f464457d494b5ed6905c63b0c4704842aba319084a0a3561cdc1359536b53200"
530539dependencies = [
531540 "cc",
532541 "codespan-reporting",
@@ -539,15 +548,15 @@ dependencies = [
539548
540549[[package]]
541550name = "cxxbridge-flags"
542version = "1.0.86"
551version = "1.0.87"
543552source = "registry+https://github.com/rust-lang/crates.io-index"
544checksum = "61b50bc93ba22c27b0d31128d2d130a0a6b3d267ae27ef7e4fae2167dfe8781c"
553checksum = "43c7119ce3a3701ed81aca8410b9acf6fc399d2629d057b87e2efa4e63a3aaea"
545554
546555[[package]]
547556name = "cxxbridge-macro"
548version = "1.0.86"
557version = "1.0.87"
549558source = "registry+https://github.com/rust-lang/crates.io-index"
550checksum = "39e61fda7e62115119469c7b3591fd913ecca96fb766cfd3f2e2502ab7bc87a5"
559checksum = "65e07508b90551e610910fa648a1878991d367064997a596135b86df30daf07e"
551560dependencies = [
552561 "proc-macro2",
553562 "quote",
@@ -714,9 +723,9 @@ dependencies = [
714723
715724[[package]]
716725name = "ed25519"
717version = "1.5.2"
726version = "1.5.3"
718727source = "registry+https://github.com/rust-lang/crates.io-index"
719checksum = "1e9c280362032ea4203659fc489832d0204ef09f247a0506f170dafcac08c369"
728checksum = "91cff35c70bba8a626e3185d8cd48cc11b5437e1a5bcd15b9b5fa3c64b6dfee7"
720729dependencies = [
721730 "serde",
722731 "signature",
@@ -819,6 +828,16 @@ version = "1.2.0"
819828source = "registry+https://github.com/rust-lang/crates.io-index"
820829checksum = "2022715d62ab30faffd124d40b76f4134a550a87792276512b18d63272333394"
821830
831[[package]]
832name = "futf"
833version = "0.1.5"
834source = "registry+https://github.com/rust-lang/crates.io-index"
835checksum = "df420e2e84819663797d1ec6544b13c5be84629e7bb00dc960d6917db2987843"
836dependencies = [
837 "mac",
838 "new_debug_unreachable",
839]
840
822841[[package]]
823842name = "futures"
824843version = "0.3.25"
@@ -1052,6 +1071,20 @@ dependencies = [
10521071 "digest 0.10.6",
10531072]
10541073
1074[[package]]
1075name = "html5ever"
1076version = "0.26.0"
1077source = "registry+https://github.com/rust-lang/crates.io-index"
1078checksum = "bea68cab48b8459f17cf1c944c67ddc572d272d9f2b274140f223ecb1da4a3b7"
1079dependencies = [
1080 "log",
1081 "mac",
1082 "markup5ever",
1083 "proc-macro2",
1084 "quote",
1085 "syn",
1086]
1087
10551088[[package]]
10561089name = "http"
10571090version = "0.2.8"
@@ -1129,10 +1162,12 @@ version = "0.0.3"
11291162dependencies = [
11301163 "chrono",
11311164 "clap",
1165 "css-color-parser",
11321166 "dirs",
1133 "futures",
11341167 "gethostname",
1135 "lazy_static",
1168 "html5ever",
1169 "lazy_static 1.4.0",
1170 "markup5ever_rcdom",
11361171 "matrix-sdk",
11371172 "mime",
11381173 "mime_guess",
@@ -1141,7 +1176,6 @@ dependencies = [
11411176 "rpassword",
11421177 "serde",
11431178 "serde_json",
1144 "sled",
11451179 "thiserror",
11461180 "tokio",
11471181 "tracing",
@@ -1318,6 +1352,12 @@ dependencies = [
13181352 "serde",
13191353]
13201354
1355[[package]]
1356name = "lazy_static"
1357version = "0.1.16"
1358source = "registry+https://github.com/rust-lang/crates.io-index"
1359checksum = "cf186d1a8aa5f5bee5fd662bc9c1b949e0259e1bcc379d1f006847b0080c7417"
1360
13211361[[package]]
13221362name = "lazy_static"
13231363version = "1.4.0"
@@ -1373,12 +1413,44 @@ dependencies = [
13731413 "hashbrown",
13741414]
13751415
1416[[package]]
1417name = "mac"
1418version = "0.1.1"
1419source = "registry+https://github.com/rust-lang/crates.io-index"
1420checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4"
1421
13761422[[package]]
13771423name = "maplit"
13781424version = "1.0.2"
13791425source = "registry+https://github.com/rust-lang/crates.io-index"
13801426checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d"
13811427
1428[[package]]
1429name = "markup5ever"
1430version = "0.11.0"
1431source = "registry+https://github.com/rust-lang/crates.io-index"
1432checksum = "7a2629bb1404f3d34c2e921f21fd34ba00b206124c81f65c50b43b6aaefeb016"
1433dependencies = [
1434 "log",
1435 "phf",
1436 "phf_codegen",
1437 "string_cache",
1438 "string_cache_codegen",
1439 "tendril",
1440]
1441
1442[[package]]
1443name = "markup5ever_rcdom"
1444version = "0.2.0"
1445source = "registry+https://github.com/rust-lang/crates.io-index"
1446checksum = "b9521dd6750f8e80ee6c53d65e2e4656d7de37064f3a7a5d2d11d05df93839c2"
1447dependencies = [
1448 "html5ever",
1449 "markup5ever",
1450 "tendril",
1451 "xml5ever",
1452]
1453
13821454[[package]]
13831455name = "matrix-sdk"
13841456version = "0.6.2"
@@ -1609,9 +1681,9 @@ dependencies = [
16091681
16101682[[package]]
16111683name = "modalkit"
1612version = "0.0.9"
1684version = "0.0.10"
16131685source = "registry+https://github.com/rust-lang/crates.io-index"
1614checksum = "28a676fc7ab6a9fd329ff82d9d291370aafcf904ac3ff9f72397f64529cb1b2d"
1686checksum = "4f57d0d53c9f3d8cad2508351f88656e4185cbb8b95d0c738b314fc8167bc90f"
16151687dependencies = [
16161688 "anymap2",
16171689 "bitflags",
@@ -1626,11 +1698,17 @@ dependencies = [
16261698 "tui",
16271699]
16281700
1701[[package]]
1702name = "new_debug_unreachable"
1703version = "1.0.4"
1704source = "registry+https://github.com/rust-lang/crates.io-index"
1705checksum = "e4a24736216ec316047a1fc4252e27dabb04218aa4a3f37c6e7ddbf1f9782b54"
1706
16291707[[package]]
16301708name = "nom"
1631version = "7.1.2"
1709version = "7.1.3"
16321710source = "registry+https://github.com/rust-lang/crates.io-index"
1633checksum = "e5507769c4919c998e69e49c839d9dc6e693ede4cc4290d6ad8b41d4f09c548c"
1711checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
16341712dependencies = [
16351713 "memchr",
16361714 "minimal-lexical",
@@ -1782,6 +1860,44 @@ version = "2.2.0"
17821860source = "registry+https://github.com/rust-lang/crates.io-index"
17831861checksum = "478c572c3d73181ff3c2539045f6eb99e5491218eae919370993b890cdbdd98e"
17841862
1863[[package]]
1864name = "phf"
1865version = "0.10.1"
1866source = "registry+https://github.com/rust-lang/crates.io-index"
1867checksum = "fabbf1ead8a5bcbc20f5f8b939ee3f5b0f6f281b6ad3468b84656b658b455259"
1868dependencies = [
1869 "phf_shared",
1870]
1871
1872[[package]]
1873name = "phf_codegen"
1874version = "0.10.0"
1875source = "registry+https://github.com/rust-lang/crates.io-index"
1876checksum = "4fb1c3a8bc4dd4e5cfce29b44ffc14bedd2ee294559a294e2a4d4c9e9a6a13cd"
1877dependencies = [
1878 "phf_generator",
1879 "phf_shared",
1880]
1881
1882[[package]]
1883name = "phf_generator"
1884version = "0.10.0"
1885source = "registry+https://github.com/rust-lang/crates.io-index"
1886checksum = "5d5285893bb5eb82e6aaf5d59ee909a06a16737a8970984dd7746ba9283498d6"
1887dependencies = [
1888 "phf_shared",
1889 "rand 0.8.5",
1890]
1891
1892[[package]]
1893name = "phf_shared"
1894version = "0.10.0"
1895source = "registry+https://github.com/rust-lang/crates.io-index"
1896checksum = "b6796ad771acdc0123d2a88dc428b5e38ef24456743ddb1744ed628f9815c096"
1897dependencies = [
1898 "siphasher",
1899]
1900
17851901[[package]]
17861902name = "pin-project"
17871903version = "1.0.12"
@@ -1841,6 +1957,12 @@ version = "0.2.17"
18411957source = "registry+https://github.com/rust-lang/crates.io-index"
18421958checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de"
18431959
1960[[package]]
1961name = "precomputed-hash"
1962version = "0.1.1"
1963source = "registry+https://github.com/rust-lang/crates.io-index"
1964checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
1965
18441966[[package]]
18451967name = "proc-macro-crate"
18461968version = "1.2.1"
@@ -1878,9 +2000,9 @@ dependencies = [
18782000
18792001[[package]]
18802002name = "proc-macro2"
1881version = "1.0.49"
2003version = "1.0.50"
18822004source = "registry+https://github.com/rust-lang/crates.io-index"
1883checksum = "57a8eca9f9c4ffde41714334dee777596264c7825420f521abc92b5b5deb63a5"
2005checksum = "6ef7d57beacfaf2d8aee5937dab7b7f28de3cb8b1828479bb5de2a7106f2bae2"
18842006dependencies = [
18852007 "unicode-ident",
18862008]
@@ -1908,6 +2030,17 @@ dependencies = [
19082030 "syn",
19092031]
19102032
2033[[package]]
2034name = "pulldown-cmark"
2035version = "0.9.2"
2036source = "registry+https://github.com/rust-lang/crates.io-index"
2037checksum = "2d9cc634bc78768157b5cbfe988ffcd1dcba95cd2b2f03a88316c08c6d00ed63"
2038dependencies = [
2039 "bitflags",
2040 "memchr",
2041 "unicase",
2042]
2043
19112044[[package]]
19122045name = "quote"
19132046version = "1.0.23"
@@ -2027,11 +2160,11 @@ checksum = "456c603be3e8d448b072f410900c09faf164fbce2d480456f50eea6e25f9c848"
20272160
20282161[[package]]
20292162name = "reqwest"
2030version = "0.11.13"
2163version = "0.11.14"
20312164source = "registry+https://github.com/rust-lang/crates.io-index"
2032checksum = "68cc60575865c7831548863cc02356512e3f1dc2f3f82cb837d7fc4cc8f3c97c"
2165checksum = "21eed90ec8570952d53b772ecf8f206aa1ec9a3d76b2521c56c42973f2d91ee9"
20332166dependencies = [
2034 "base64 0.13.1",
2167 "base64 0.21.0",
20352168 "bytes",
20362169 "encoding_rs",
20372170 "futures-core",
@@ -2158,6 +2291,7 @@ dependencies = [
21582291 "js_int",
21592292 "js_option",
21602293 "percent-encoding",
2294 "pulldown-cmark",
21612295 "rand 0.8.5",
21622296 "regex",
21632297 "ruma-identifiers-validation",
@@ -2220,9 +2354,9 @@ dependencies = [
22202354
22212355[[package]]
22222356name = "rustix"
2223version = "0.36.6"
2357version = "0.36.7"
22242358source = "registry+https://github.com/rust-lang/crates.io-index"
2225checksum = "4feacf7db682c6c329c4ede12649cd36ecab0f3be5b7d74e6a20304725db4549"
2359checksum = "d4fdebc4b395b7fbb9ab11e462e20ed9051e7b16e42d24042c776eca0ac81b03"
22262360dependencies = [
22272361 "bitflags",
22282362 "errno",
@@ -2369,7 +2503,7 @@ version = "0.1.4"
23692503source = "registry+https://github.com/rust-lang/crates.io-index"
23702504checksum = "900fba806f70c630b0a382d0d825e17a0f19fcd059a2ade1ff237bcddf446b31"
23712505dependencies = [
2372 "lazy_static",
2506 "lazy_static 1.4.0",
23732507]
23742508
23752509[[package]]
@@ -2408,6 +2542,12 @@ version = "1.6.4"
24082542source = "registry+https://github.com/rust-lang/crates.io-index"
24092543checksum = "74233d3b3b2f6d4b006dc19dee745e73e2a6bfb6f93607cd3b02bd5b00797d7c"
24102544
2545[[package]]
2546name = "siphasher"
2547version = "0.3.10"
2548source = "registry+https://github.com/rust-lang/crates.io-index"
2549checksum = "7bd3e3206899af3f8b12af284fafc038cc1dc2b41d1b89dd17297221c5d225de"
2550
24112551[[package]]
24122552name = "slab"
24132553version = "0.4.7"
@@ -2470,6 +2610,32 @@ version = "0.4.1"
24702610source = "registry+https://github.com/rust-lang/crates.io-index"
24712611checksum = "5f026164926842ec52deb1938fae44f83dfdb82d0a5b0270c5bd5935ab74d6dd"
24722612
2613[[package]]
2614name = "string_cache"
2615version = "0.8.4"
2616source = "registry+https://github.com/rust-lang/crates.io-index"
2617checksum = "213494b7a2b503146286049378ce02b482200519accc31872ee8be91fa820a08"
2618dependencies = [
2619 "new_debug_unreachable",
2620 "once_cell",
2621 "parking_lot 0.12.1",
2622 "phf_shared",
2623 "precomputed-hash",
2624 "serde",
2625]
2626
2627[[package]]
2628name = "string_cache_codegen"
2629version = "0.5.2"
2630source = "registry+https://github.com/rust-lang/crates.io-index"
2631checksum = "6bb30289b722be4ff74a408c3cc27edeaad656e06cb1fe8fa9231fa59c728988"
2632dependencies = [
2633 "phf_generator",
2634 "phf_shared",
2635 "proc-macro2",
2636 "quote",
2637]
2638
24732639[[package]]
24742640name = "strsim"
24752641version = "0.10.0"
@@ -2505,11 +2671,22 @@ dependencies = [
25052671 "unicode-xid",
25062672]
25072673
2674[[package]]
2675name = "tendril"
2676version = "0.4.3"
2677source = "registry+https://github.com/rust-lang/crates.io-index"
2678checksum = "d24a120c5fc464a3458240ee02c299ebcb9d67b5249c8848b09d639dca8d7bb0"
2679dependencies = [
2680 "futf",
2681 "mac",
2682 "utf-8",
2683]
2684
25082685[[package]]
25092686name = "termcolor"
2510version = "1.1.3"
2687version = "1.2.0"
25112688source = "registry+https://github.com/rust-lang/crates.io-index"
2512checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755"
2689checksum = "be55cf8942feac5c765c2c993422806843c9a9a45d4d5c407ad6dd2ea95eb9b6"
25132690dependencies = [
25142691 "winapi-util",
25152692]
@@ -2598,9 +2775,9 @@ checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c"
25982775
25992776[[package]]
26002777name = "tokio"
2601version = "1.24.1"
2778version = "1.24.2"
26022779source = "registry+https://github.com/rust-lang/crates.io-index"
2603checksum = "1d9f76183f91ecfb55e1d7d5602bd1d979e38a3a522fe900241cf195624d67ae"
2780checksum = "597a12a59981d9e3c38d216785b0c37399f6e415e8d0712047620f189371b0bb"
26042781dependencies = [
26052782 "autocfg",
26062783 "bytes",
@@ -2652,9 +2829,9 @@ dependencies = [
26522829
26532830[[package]]
26542831name = "toml"
2655version = "0.5.10"
2832version = "0.5.11"
26562833source = "registry+https://github.com/rust-lang/crates.io-index"
2657checksum = "1333c76748e868a4d9d1017b5ab53171dfd095f70c712fdb4653a406547f598f"
2834checksum = "f4f7f0dd8d50a853a531c426359045b1998f04219d88799810762cd4ad314234"
26582835dependencies = [
26592836 "serde",
26602837]
@@ -2715,7 +2892,7 @@ version = "0.1.3"
27152892source = "registry+https://github.com/rust-lang/crates.io-index"
27162893checksum = "78ddad33d2d10b1ed7eb9d1f518a5674713876e97e5bb9b7345a7984fbb4f922"
27172894dependencies = [
2718 "lazy_static",
2895 "lazy_static 1.4.0",
27192896 "log",
27202897 "tracing-core",
27212898]
@@ -2770,9 +2947,9 @@ dependencies = [
27702947
27712948[[package]]
27722949name = "unicode-bidi"
2773version = "0.3.8"
2950version = "0.3.10"
27742951source = "registry+https://github.com/rust-lang/crates.io-index"
2775checksum = "099b7128301d285f79ddd55b9a83d5e6b9e97c92e0ea0daebee7263e932de992"
2952checksum = "d54675592c1dbefd78cbd98db9bacd89886e1ca50692a0692baefffdeb92dd58"
27762953
27772954[[package]]
27782955name = "unicode-ident"
@@ -2835,6 +3012,12 @@ dependencies = [
28353012 "serde",
28363013]
28373014
3015[[package]]
3016name = "utf-8"
3017version = "0.7.6"
3018source = "registry+https://github.com/rust-lang/crates.io-index"
3019checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"
3020
28383021[[package]]
28393022name = "uuid"
28403023version = "0.8.2"
@@ -3167,6 +3350,17 @@ dependencies = [
31673350 "zeroize",
31683351]
31693352
3353[[package]]
3354name = "xml5ever"
3355version = "0.17.0"
3356source = "registry+https://github.com/rust-lang/crates.io-index"
3357checksum = "4034e1d05af98b51ad7214527730626f019682d797ba38b51689212118d8e650"
3358dependencies = [
3359 "log",
3360 "mac",
3361 "markup5ever",
3362]
3363
31703364[[package]]
31713365name = "zeroize"
31723366version = "1.3.0"
Cargo.toml +16 −5
@@ -10,25 +10,24 @@ description = "A Matrix chat client that uses Vim keybindings"
1010license = "Apache-2.0"
1111exclude = [".github", "CONTRIBUTING.md"]
1212keywords = ["matrix", "chat", "tui", "vim"]
13categories = ["command-line-utilities"]
1314rust-version = "1.66"
1415
1516[dependencies]
1617chrono = "0.4"
1718clap = {version = "4.0", features = ["derive"]}
19css-color-parser = "0.1.2"
1820dirs = "4.0.0"
19futures = "0.3.21"
2021gethostname = "0.4.1"
21matrix-sdk = {version = "0.6", default-features = false, features = ["e2e-encryption", "sled", "rustls-tls"]}
22html5ever = "0.26.0"
23markup5ever_rcdom = "0.2.0"
2224mime = "^0.3.16"
2325mime_guess = "^2.0.4"
24modalkit = "0.0.9"
2526regex = "^1.5"
2627rpassword = "^7.2"
2728serde = "^1.0"
2829serde_json = "^1.0"
29sled = "0.34"
3030thiserror = "^1.0.37"
31tokio = {version = "1.24.1", features = ["macros", "net", "rt-multi-thread", "sync", "time"]}
3231tracing = "~0.1.36"
3332tracing-appender = "~0.2.2"
3433tracing-subscriber = "0.3.16"
@@ -36,5 +35,17 @@ unicode-segmentation = "^1.7"
3635unicode-width = "0.1.10"
3736url = {version = "^2.2.2", features = ["serde"]}
3837
38[dependencies.modalkit]
39version = "0.0.10"
40
41[dependencies.matrix-sdk]
42version = "0.6"
43default-features = false
44features = ["e2e-encryption", "markdown", "sled", "rustls-tls"]
45
46[dependencies.tokio]
47version = "1.24.1"
48features = ["macros", "net", "rt-multi-thread", "sync", "time"]
49
3950[dev-dependencies]
4051lazy_static = "1.4.0"
README.md +3 −3
@@ -21,7 +21,7 @@ website, [iamb.chat].
2121Install Rust and Cargo, and then run:
2222
2323```
24cargo install iamb
24cargo install --locked iamb
2525```
2626
2727## Configuration
@@ -66,9 +66,9 @@ two other TUI clients and Element Web:
6666| Attachment uploading | ✔️ | ❌ | ✔️ | ✔️ |
6767| Attachment downloading | ✔️ | ✔️ | ✔️ | ✔️ |
6868| Send stickers | ❌ | ❌ | ❌ | ✔️ |
69| Send formatted messages (markdown) | ❌ ([#10]) | ✔️ | ✔️ | ✔️ |
69| Send formatted messages (markdown) | ✔️ | ✔️ | ✔️ | ✔️ |
7070| Rich Text Editor for formatted messages | ❌ | ❌ | ❌ | ✔️ |
71| Display formatted messages | ❌ ([#10]) | ✔️ | ✔️ | ✔️ |
71| Display formatted messages | ✔️ | ✔️ | ✔️ | ✔️ |
7272| Redacting | ✔️ | ✔️ | ✔️ | ✔️ |
7373| Multiple Matrix Accounts | ✔️ | ❌ | ✔️ | ❌ |
7474| New user registration | ❌ | ❌ | ❌ | ✔️ |
src/base.rs +1 −1
@@ -59,7 +59,7 @@ use crate::{
5959 ApplicationSettings,
6060};
6161
62const ROOM_FETCH_DEBOUNCE: Duration = Duration::from_secs(3);
62const ROOM_FETCH_DEBOUNCE: Duration = Duration::from_secs(2);
6363
6464#[derive(Clone, Debug, Eq, PartialEq)]
6565pub enum IambInfo {}
src/main.rs +12 −2
@@ -42,6 +42,7 @@ mod commands;
4242mod config;
4343mod keybindings;
4444mod message;
45mod util;
4546mod windows;
4647mod worker;
4748
@@ -99,6 +100,14 @@ use modalkit::{
99100 },
100101};
101102
103const MIN_MSG_LOAD: u32 = 50;
104
105fn msg_load_req(area: Rect) -> u32 {
106 let n = area.height as u32;
107
108 n.max(MIN_MSG_LOAD)
109}
110
102111struct Application {
103112 store: AsyncProgramStore,
104113 worker: Requester,
@@ -176,7 +185,7 @@ impl Application {
176185 f.set_cursor(cx, cy);
177186 }
178187
179 store.application.load_older(area.height as u32);
188 store.application.load_older(msg_load_req(area));
180189 })?;
181190
182191 Ok(())
@@ -186,7 +195,8 @@ impl Application {
186195 loop {
187196 self.redraw(false, self.store.clone().lock().await.deref_mut())?;
188197
189 if !poll(Duration::from_millis(500))? {
198 if !poll(Duration::from_secs(1))? {
199 // Redraw in case there's new messages to show.
190200 continue;
191201 }
192202
src/message/html.rs added +942
@@ -0,0 +1,942 @@
1//! # Rendering for formatted bodies
2//!
3//! This module contains the code for rendering messages that contained an
4//! "org.matrix.custom.html"-formatted body.
5//!
6//! The Matrix specification recommends limiting rendered tags and attributes to a safe subset of
7//! HTML. You can read more in section 11.2.1.1, "m.room.message msgtypes":
8//!
9//! https://spec.matrix.org/unstable/client-server-api/#mroommessage-msgtypes
10//!
11//! This isn't as important for iamb, since it isn't a browser environment, but we do still map
12//! input onto an enum of the safe list of tags to keep it easy to understand and process.
13use std::ops::Deref;
14
15use css_color_parser::Color as CssColor;
16use markup5ever_rcdom::{Handle, NodeData, RcDom};
17use unicode_segmentation::UnicodeSegmentation;
18
19use html5ever::{
20 driver::{parse_fragment, ParseOpts},
21 interface::{Attribute, QualName},
22 local_name,
23 namespace_url,
24 ns,
25 tendril::{StrTendril, TendrilSink},
26};
27
28use modalkit::tui::{
29 layout::Alignment,
30 style::{Color, Modifier as StyleModifier, Style},
31 symbols::line,
32 text::{Span, Spans, Text},
33};
34
35use crate::{
36 message::printer::TextPrinter,
37 util::{join_cell_text, space_text},
38};
39
40struct BulletIterator {
41 style: ListStyle,
42 pos: usize,
43 len: usize,
44}
45
46impl BulletIterator {
47 fn width(&self) -> usize {
48 match self.style {
49 ListStyle::Unordered => 2,
50 ListStyle::Ordered => self.len.to_string().len() + 2,
51 }
52 }
53}
54
55impl Iterator for BulletIterator {
56 type Item = String;
57
58 fn next(&mut self) -> Option<Self::Item> {
59 if self.pos == self.len {
60 return None;
61 }
62
63 self.pos += 1;
64
65 let bullet = match self.style {
66 ListStyle::Unordered => "- ".to_string(),
67 ListStyle::Ordered => {
68 let w = self.len.to_string().len();
69 format!("{: >w$}. ", self.pos, w = w)
70 },
71 };
72
73 return Some(bullet);
74 }
75}
76
77#[derive(Clone, Copy, Debug)]
78pub enum ListStyle {
79 Ordered,
80 Unordered,
81}
82
83impl ListStyle {
84 fn bullets(&self, len: usize) -> BulletIterator {
85 BulletIterator { style: *self, pos: 0, len }
86 }
87}
88
89pub type StyleTreeChildren = Vec<StyleTreeNode>;
90
91pub enum CellType {
92 Data,
93 Header,
94}
95
96pub struct TableRow {
97 cells: Vec<(CellType, StyleTreeNode)>,
98}
99
100impl TableRow {
101 fn columns(&self) -> usize {
102 self.cells.len()
103 }
104}
105
106pub struct TableSection {
107 rows: Vec<TableRow>,
108}
109
110impl TableSection {
111 fn columns(&self) -> usize {
112 self.rows.iter().map(TableRow::columns).max().unwrap_or(0)
113 }
114}
115
116pub struct Table {
117 caption: Option<Box<StyleTreeNode>>,
118 sections: Vec<TableSection>,
119}
120
121impl Table {
122 fn columns(&self) -> usize {
123 self.sections.iter().map(TableSection::columns).max().unwrap_or(0)
124 }
125
126 fn to_text(&self, width: usize, style: Style) -> Text {
127 let mut text = Text::default();
128 let columns = self.columns();
129 let cell_total = width.saturating_sub(columns).saturating_sub(1);
130 let cell_min = cell_total / columns;
131 let mut cell_slop = cell_total - cell_min * columns;
132 let cell_widths = (0..columns)
133 .into_iter()
134 .map(|_| {
135 let slopped = cell_slop.min(1);
136 cell_slop -= slopped;
137 cell_min + slopped
138 })
139 .collect::<Vec<_>>();
140
141 let mut nrows = 0;
142
143 if let Some(caption) = &self.caption {
144 let subw = width.saturating_sub(6);
145 let mut printer = TextPrinter::new(subw, style, true).align(Alignment::Center);
146 caption.print(&mut printer, style);
147
148 for mut line in printer.finish().lines {
149 line.0.insert(0, Span::styled(" ", style));
150 line.0.push(Span::styled(" ", style));
151 text.lines.push(line);
152 }
153 }
154
155 for section in self.sections.iter() {
156 for row in section.rows.iter() {
157 let mut ruler = String::new();
158
159 for (i, w) in cell_widths.iter().enumerate() {
160 let cross = match (nrows, i) {
161 (0, 0) => line::TOP_LEFT,
162 (0, _) => line::HORIZONTAL_DOWN,
163 (_, 0) => line::VERTICAL_RIGHT,
164 (_, _) => line::CROSS,
165 };
166
167 ruler.push_str(cross);
168
169 for _ in 0..*w {
170 ruler.push_str(line::HORIZONTAL);
171 }
172 }
173
174 if nrows == 0 {
175 ruler.push_str(line::TOP_RIGHT);
176 } else {
177 ruler.push_str(line::VERTICAL_LEFT);
178 }
179
180 text.lines.push(Spans(vec![Span::styled(ruler, style)]));
181
182 let cells = cell_widths
183 .iter()
184 .enumerate()
185 .map(|(i, w)| {
186 let text = if let Some((kind, cell)) = row.cells.get(i) {
187 let style = match kind {
188 CellType::Header => style.add_modifier(StyleModifier::BOLD),
189 CellType::Data => style,
190 };
191
192 cell.to_text(*w, style)
193 } else {
194 space_text(*w, style)
195 };
196
197 (text, *w)
198 })
199 .collect();
200
201 let joined = join_cell_text(cells, Span::styled(line::VERTICAL, style));
202 text.lines.extend(joined.lines);
203
204 nrows += 1;
205 }
206 }
207
208 if nrows > 0 {
209 let mut ruler = String::new();
210
211 for (i, w) in cell_widths.iter().enumerate() {
212 let cross = if i == 0 {
213 line::BOTTOM_LEFT
214 } else {
215 line::HORIZONTAL_UP
216 };
217
218 ruler.push_str(cross);
219
220 for _ in 0..*w {
221 ruler.push_str(line::HORIZONTAL);
222 }
223 }
224
225 ruler.push_str(line::BOTTOM_RIGHT);
226 text.lines.push(Spans(vec![Span::styled(ruler, style)]));
227 }
228
229 text
230 }
231}
232
233pub enum StyleTreeNode {
234 Blockquote(Box<StyleTreeNode>),
235 Break,
236 Code(Box<StyleTreeNode>, Option<String>),
237 Header(Box<StyleTreeNode>, usize),
238 Image(Option<String>),
239 List(StyleTreeChildren, ListStyle),
240 Paragraph(Box<StyleTreeNode>),
241 Reply(Box<StyleTreeNode>),
242 Ruler,
243 Style(Box<StyleTreeNode>, Style),
244 Table(Table),
245 Text(String),
246 Sequence(StyleTreeChildren),
247}
248
249impl StyleTreeNode {
250 pub fn to_text(&self, width: usize, style: Style) -> Text {
251 let mut printer = TextPrinter::new(width, style, true);
252 self.print(&mut printer, style);
253 printer.finish()
254 }
255
256 pub fn print<'a>(&'a self, printer: &mut TextPrinter<'a>, style: Style) {
257 let width = printer.width();
258
259 match self {
260 StyleTreeNode::Blockquote(child) => {
261 let mut subp = printer.sub(4);
262 child.print(&mut subp, style);
263
264 for mut line in subp.finish() {
265 line.0.insert(0, Span::styled(" ", style));
266 printer.push_line(line);
267 }
268 },
269 StyleTreeNode::Code(child, _) => {
270 child.print(printer, style);
271 },
272 StyleTreeNode::Header(child, level) => {
273 let style = style.add_modifier(StyleModifier::BOLD);
274 let mut hashes = "#".repeat(*level);
275 hashes.push(' ');
276
277 printer.push_str(hashes, style);
278 child.print(printer, style);
279 },
280 StyleTreeNode::Image(None) => {},
281 StyleTreeNode::Image(Some(alt)) => {
282 printer.commit();
283 printer.push_str("Image Alt: ", Style::default());
284 printer.push_str(alt, Style::default());
285 printer.commit();
286 },
287 StyleTreeNode::List(children, lt) => {
288 let mut bullets = lt.bullets(children.len());
289 let liw = bullets.width();
290
291 for child in children {
292 let mut subp = printer.sub(liw);
293 let mut bullet = bullets.next();
294 child.print(&mut subp, style);
295
296 for mut line in subp.finish() {
297 let leading = if let Some(bullet) = bullet.take() {
298 Span::styled(bullet, style)
299 } else {
300 Span::styled(" ".repeat(liw), style)
301 };
302
303 line.0.insert(0, leading);
304 printer.push_line(line);
305 }
306 }
307 },
308 StyleTreeNode::Paragraph(child) => {
309 printer.push_break();
310 child.print(printer, style);
311 printer.commit();
312 },
313 StyleTreeNode::Reply(child) => {
314 if printer.hide_reply() {
315 return;
316 }
317
318 printer.push_break();
319 child.print(printer, style);
320 printer.commit();
321 },
322 StyleTreeNode::Ruler => {
323 printer.push_str(line::HORIZONTAL.repeat(width), style);
324 },
325 StyleTreeNode::Table(table) => {
326 let text = table.to_text(width, style);
327 printer.push_text(text);
328 },
329 StyleTreeNode::Break => {
330 printer.push_break();
331 },
332 StyleTreeNode::Text(s) => {
333 printer.push_str(s.as_str(), style);
334 },
335
336 StyleTreeNode::Style(child, patch) => child.print(printer, style.patch(*patch)),
337 StyleTreeNode::Sequence(children) => {
338 for child in children {
339 child.print(printer, style);
340 }
341 },
342 }
343 }
344}
345
346pub struct StyleTree {
347 children: StyleTreeChildren,
348}
349
350impl StyleTree {
351 pub fn to_text(&self, width: usize, style: Style, hide_reply: bool) -> Text<'_> {
352 let mut printer = TextPrinter::new(width, style, hide_reply);
353
354 for child in self.children.iter() {
355 child.print(&mut printer, style);
356 }
357
358 printer.finish()
359 }
360}
361
362fn c2c(handles: &[Handle]) -> Vec<StyleTreeNode> {
363 handles.iter().flat_map(h2t).collect()
364}
365
366fn c2t(handles: &[Handle]) -> Box<StyleTreeNode> {
367 let node = StyleTreeNode::Sequence(c2c(handles));
368
369 Box::new(node)
370}
371
372fn get_node(hdl: &Handle, want: &str) -> Option<StyleTreeNode> {
373 let node = hdl.deref();
374
375 if let NodeData::Element { name, .. } = &node.data {
376 if name.local.as_ref() != want {
377 return None;
378 }
379
380 let c = c2c(&node.children.borrow());
381 return Some(StyleTreeNode::Sequence(c));
382 } else {
383 return None;
384 }
385}
386
387fn li2t(hdl: &Handle) -> Option<StyleTreeNode> {
388 get_node(hdl, "li")
389}
390
391fn table_cell(hdl: &Handle) -> Option<(CellType, StyleTreeNode)> {
392 if let Some(node) = get_node(hdl, "th") {
393 return Some((CellType::Header, node));
394 }
395
396 Some((CellType::Data, get_node(hdl, "td")?))
397}
398
399fn table_row(hdl: &Handle) -> Option<TableRow> {
400 let node = hdl.deref();
401
402 if let NodeData::Element { name, .. } = &node.data {
403 if name.local.as_ref() != "tr" {
404 return None;
405 }
406
407 let cells = table_cells(&node.children.borrow());
408 return Some(TableRow { cells });
409 } else {
410 return None;
411 }
412}
413
414fn table_section(hdl: &Handle) -> Option<TableSection> {
415 let node = hdl.deref();
416
417 if let NodeData::Element { name, .. } = &node.data {
418 match name.local.as_ref() {
419 "thead" | "tbody" => {
420 let rows = table_rows(&node.children.borrow());
421
422 Some(TableSection { rows })
423 },
424 _ => None,
425 }
426 } else {
427 return None;
428 }
429}
430
431fn table_cells(handles: &[Handle]) -> Vec<(CellType, StyleTreeNode)> {
432 handles.iter().filter_map(table_cell).collect()
433}
434
435fn table_rows(handles: &[Handle]) -> Vec<TableRow> {
436 handles.iter().filter_map(table_row).collect()
437}
438
439fn table_sections(handles: &[Handle]) -> Vec<TableSection> {
440 handles.iter().filter_map(table_section).collect()
441}
442
443fn lic2t(handles: &[Handle]) -> StyleTreeChildren {
444 handles.iter().filter_map(li2t).collect()
445}
446
447fn attrs_to_alt(attrs: &[Attribute]) -> Option<String> {
448 for attr in attrs {
449 if attr.name.local.as_ref() != "alt" {
450 continue;
451 }
452
453 return Some(attr.value.to_string());
454 }
455
456 return None;
457}
458
459fn attrs_to_language(attrs: &[Attribute]) -> Option<String> {
460 for attr in attrs {
461 if attr.name.local.as_ref() != "class" {
462 continue;
463 }
464
465 for class in attr.value.as_ref().unicode_words() {
466 if class.len() > 9 && class.starts_with("language-") {
467 return Some(class[9..].to_string());
468 }
469 }
470 }
471
472 return None;
473}
474
475fn attrs_to_style(attrs: &[Attribute]) -> Style {
476 let mut style = Style::default();
477
478 for attr in attrs {
479 match attr.name.local.as_ref() {
480 "data-mx-bg-color" => {
481 if let Ok(rgb) = attr.value.as_ref().parse::<CssColor>() {
482 let color = Color::Rgb(rgb.r, rgb.g, rgb.b);
483 style = style.bg(color);
484 }
485 },
486 "data-mx-color" | "color" => {
487 if let Ok(rgb) = attr.value.as_ref().parse::<CssColor>() {
488 let color = Color::Rgb(rgb.r, rgb.g, rgb.b);
489 style = style.fg(color);
490 }
491 },
492 _ => continue,
493 }
494 }
495
496 return style;
497}
498
499fn h2t(hdl: &Handle) -> StyleTreeChildren {
500 let node = hdl.deref();
501
502 let tree = match &node.data {
503 NodeData::Document => *c2t(node.children.borrow().as_slice()),
504 NodeData::Text { contents } => StyleTreeNode::Text(contents.borrow().to_string()),
505 NodeData::Element { name, attrs, .. } => {
506 match name.local.as_ref() {
507 // Message that this one replies to.
508 "mx-reply" => StyleTreeNode::Reply(c2t(&node.children.borrow())),
509
510 // Style change
511 "b" | "strong" => {
512 let c = c2t(&node.children.borrow());
513 let s = Style::default().add_modifier(StyleModifier::BOLD);
514
515 StyleTreeNode::Style(c, s)
516 },
517 "font" => {
518 let c = c2t(&node.children.borrow());
519 let s = attrs_to_style(&attrs.borrow());
520
521 StyleTreeNode::Style(c, s)
522 },
523 "em" | "i" => {
524 let c = c2t(&node.children.borrow());
525 let s = Style::default().add_modifier(StyleModifier::ITALIC);
526
527 StyleTreeNode::Style(c, s)
528 },
529 "span" => {
530 let c = c2t(&node.children.borrow());
531 let s = attrs_to_style(&attrs.borrow());
532
533 StyleTreeNode::Style(c, s)
534 },
535 "del" | "strike" => {
536 let c = c2t(&node.children.borrow());
537 let s = Style::default().add_modifier(StyleModifier::CROSSED_OUT);
538
539 StyleTreeNode::Style(c, s)
540 },
541 "u" => {
542 let c = c2t(&node.children.borrow());
543 let s = Style::default().add_modifier(StyleModifier::UNDERLINED);
544
545 StyleTreeNode::Style(c, s)
546 },
547
548 // Lists
549 "ol" => StyleTreeNode::List(lic2t(&node.children.borrow()), ListStyle::Ordered),
550 "ul" => StyleTreeNode::List(lic2t(&node.children.borrow()), ListStyle::Unordered),
551
552 // Headers
553 "h1" => StyleTreeNode::Header(c2t(&node.children.borrow()), 1),
554 "h2" => StyleTreeNode::Header(c2t(&node.children.borrow()), 2),
555 "h3" => StyleTreeNode::Header(c2t(&node.children.borrow()), 3),
556 "h4" => StyleTreeNode::Header(c2t(&node.children.borrow()), 4),
557 "h5" => StyleTreeNode::Header(c2t(&node.children.borrow()), 5),
558 "h6" => StyleTreeNode::Header(c2t(&node.children.borrow()), 6),
559
560 // Table
561 "table" => {
562 let sections = table_sections(&node.children.borrow());
563 let caption = node
564 .children
565 .borrow()
566 .iter()
567 .find_map(|hdl| get_node(hdl, "caption"))
568 .map(Box::new);
569 let table = Table { caption, sections };
570
571 StyleTreeNode::Table(table)
572 },
573
574 // Code blocks.
575 "code" => {
576 let c = c2t(&node.children.borrow());
577 let l = attrs_to_language(&attrs.borrow());
578
579 StyleTreeNode::Code(c, l)
580 },
581
582 // Other text blocks.
583 "blockquote" => StyleTreeNode::Blockquote(c2t(&node.children.borrow())),
584 "div" | "p" => StyleTreeNode::Paragraph(c2t(&node.children.borrow())),
585
586 // No children.
587 "hr" => StyleTreeNode::Ruler,
588 "br" => StyleTreeNode::Break,
589
590 "img" => StyleTreeNode::Image(attrs_to_alt(&attrs.borrow())),
591
592 // These don't render in any special way.
593 "a" | "details" | "html" | "pre" | "summary" | "sub" | "sup" => {
594 *c2t(&node.children.borrow())
595 },
596
597 _ => return vec![],
598 }
599 },
600
601 // These don't render as anything.
602 NodeData::Doctype { .. } => return vec![],
603 NodeData::Comment { .. } => return vec![],
604 NodeData::ProcessingInstruction { .. } => return vec![],
605 };
606
607 vec![tree]
608}
609
610fn dom_to_style_tree(dom: RcDom) -> StyleTree {
611 StyleTree { children: h2t(&dom.document) }
612}
613
614pub fn parse_matrix_html(s: &str) -> StyleTree {
615 let dom = parse_fragment(
616 RcDom::default(),
617 ParseOpts::default(),
618 QualName::new(None, ns!(), local_name!("div")),
619 vec![],
620 )
621 .one(StrTendril::from(s));
622
623 dom_to_style_tree(dom)
624}
625
626#[cfg(test)]
627pub mod tests {
628 use super::*;
629 use crate::util::space_span;
630
631 #[test]
632 fn test_header() {
633 let bold = Style::default().add_modifier(StyleModifier::BOLD);
634
635 let s = "<h1>Header 1</h1>";
636 let tree = parse_matrix_html(s);
637 let text = tree.to_text(20, Style::default(), false);
638 assert_eq!(text.lines, vec![Spans(vec![
639 Span::styled("# ", bold),
640 Span::styled("Header 1", bold),
641 space_span(10, Style::default())
642 ])]);
643
644 let s = "<h2>Header 2</h2>";
645 let tree = parse_matrix_html(s);
646 let text = tree.to_text(20, Style::default(), false);
647 assert_eq!(text.lines, vec![Spans(vec![
648 Span::styled("## ", bold),
649 Span::styled("Header 2", bold),
650 space_span(9, Style::default())
651 ])]);
652
653 let s = "<h3>Header 3</h3>";
654 let tree = parse_matrix_html(s);
655 let text = tree.to_text(20, Style::default(), false);
656 assert_eq!(text.lines, vec![Spans(vec![
657 Span::styled("### ", bold),
658 Span::styled("Header 3", bold),
659 space_span(8, Style::default())
660 ])]);
661
662 let s = "<h4>Header 4</h4>";
663 let tree = parse_matrix_html(s);
664 let text = tree.to_text(20, Style::default(), false);
665 assert_eq!(text.lines, vec![Spans(vec![
666 Span::styled("#### ", bold),
667 Span::styled("Header 4", bold),
668 space_span(7, Style::default())
669 ])]);
670
671 let s = "<h5>Header 5</h5>";
672 let tree = parse_matrix_html(s);
673 let text = tree.to_text(20, Style::default(), false);
674 assert_eq!(text.lines, vec![Spans(vec![
675 Span::styled("##### ", bold),
676 Span::styled("Header 5", bold),
677 space_span(6, Style::default())
678 ])]);
679
680 let s = "<h6>Header 6</h6>";
681 let tree = parse_matrix_html(s);
682 let text = tree.to_text(20, Style::default(), false);
683 assert_eq!(text.lines, vec![Spans(vec![
684 Span::styled("###### ", bold),
685 Span::styled("Header 6", bold),
686 space_span(5, Style::default())
687 ])]);
688 }
689
690 #[test]
691 fn test_style() {
692 let def = Style::default();
693 let bold = def.add_modifier(StyleModifier::BOLD);
694 let italic = def.add_modifier(StyleModifier::ITALIC);
695 let strike = def.add_modifier(StyleModifier::CROSSED_OUT);
696 let underl = def.add_modifier(StyleModifier::UNDERLINED);
697 let red = def.fg(Color::Rgb(0xff, 0x00, 0x00));
698
699 let s = "<b>Bold!</b>";
700 let tree = parse_matrix_html(s);
701 let text = tree.to_text(20, Style::default(), false);
702 assert_eq!(text.lines, vec![Spans(vec![
703 Span::styled("Bold!", bold),
704 space_span(15, def)
705 ])]);
706
707 let s = "<strong>Bold!</strong>";
708 let tree = parse_matrix_html(s);
709 let text = tree.to_text(20, Style::default(), false);
710 assert_eq!(text.lines, vec![Spans(vec![
711 Span::styled("Bold!", bold),
712 space_span(15, def)
713 ])]);
714
715 let s = "<i>Italic!</i>";
716 let tree = parse_matrix_html(s);
717 let text = tree.to_text(20, Style::default(), false);
718 assert_eq!(text.lines, vec![Spans(vec![
719 Span::styled("Italic!", italic),
720 space_span(13, def)
721 ])]);
722
723 let s = "<em>Italic!</em>";
724 let tree = parse_matrix_html(s);
725 let text = tree.to_text(20, Style::default(), false);
726 assert_eq!(text.lines, vec![Spans(vec![
727 Span::styled("Italic!", italic),
728 space_span(13, def)
729 ])]);
730
731 let s = "<del>Strikethrough!</del>";
732 let tree = parse_matrix_html(s);
733 let text = tree.to_text(20, Style::default(), false);
734 assert_eq!(text.lines, vec![Spans(vec![
735 Span::styled("Strikethrough!", strike),
736 space_span(6, def)
737 ])]);
738
739 let s = "<strike>Strikethrough!</strike>";
740 let tree = parse_matrix_html(s);
741 let text = tree.to_text(20, Style::default(), false);
742 assert_eq!(text.lines, vec![Spans(vec![
743 Span::styled("Strikethrough!", strike),
744 space_span(6, def)
745 ])]);
746
747 let s = "<u>Underline!</u>";
748 let tree = parse_matrix_html(s);
749 let text = tree.to_text(20, Style::default(), false);
750 assert_eq!(text.lines, vec![Spans(vec![
751 Span::styled("Underline!", underl),
752 space_span(10, def)
753 ])]);
754
755 let s = "<font color=\"#ff0000\">Red!</u>";
756 let tree = parse_matrix_html(s);
757 let text = tree.to_text(20, Style::default(), false);
758 assert_eq!(text.lines, vec![Spans(vec![Span::styled("Red!", red), space_span(16, def)])]);
759
760 let s = "<font color=\"red\">Red!</u>";
761 let tree = parse_matrix_html(s);
762 let text = tree.to_text(20, Style::default(), false);
763 assert_eq!(text.lines, vec![Spans(vec![Span::styled("Red!", red), space_span(16, def)])]);
764 }
765
766 #[test]
767 fn test_paragraph() {
768 let s = "<p>Hello world!</p><p>Content</p><p>Goodbye world!</p>";
769 let tree = parse_matrix_html(s);
770 let text = tree.to_text(10, Style::default(), false);
771 assert_eq!(text.lines.len(), 7);
772 assert_eq!(text.lines[0], Spans(vec![Span::raw("Hello worl")]));
773 assert_eq!(text.lines[1], Spans(vec![Span::raw("d!"), Span::raw(" ")]));
774 assert_eq!(text.lines[2], Spans(vec![Span::raw(" ")]));
775 assert_eq!(text.lines[3], Spans(vec![Span::raw("Content"), Span::raw(" ")]));
776 assert_eq!(text.lines[4], Spans(vec![Span::raw(" ")]));
777 assert_eq!(text.lines[5], Spans(vec![Span::raw("Goodbye wo")]));
778 assert_eq!(text.lines[6], Spans(vec![Span::raw("rld!"), Span::raw(" ")]));
779 }
780
781 #[test]
782 fn test_blockquote() {
783 let s = "<blockquote>Hello world!</blockquote>";
784 let tree = parse_matrix_html(s);
785 let text = tree.to_text(10, Style::default(), false);
786 assert_eq!(text.lines.len(), 2);
787 assert_eq!(text.lines[0], Spans(vec![Span::raw(" "), Span::raw("Hello ")]));
788 assert_eq!(text.lines[1], Spans(vec![Span::raw(" "), Span::raw("world!")]));
789 }
790
791 #[test]
792 fn test_list_unordered() {
793 let s = "<ul><li>List Item 1</li><li>List Item 2</li><li>List Item 3</li></ul>";
794 let tree = parse_matrix_html(s);
795 let text = tree.to_text(8, Style::default(), false);
796 assert_eq!(text.lines.len(), 6);
797 assert_eq!(text.lines[0], Spans(vec![Span::raw("- "), Span::raw("List I")]));
798 assert_eq!(text.lines[1], Spans(vec![Span::raw(" "), Span::raw("tem 1"), Span::raw(" ")]));
799 assert_eq!(text.lines[2], Spans(vec![Span::raw("- "), Span::raw("List I")]));
800 assert_eq!(text.lines[3], Spans(vec![Span::raw(" "), Span::raw("tem 2"), Span::raw(" ")]));
801 assert_eq!(text.lines[4], Spans(vec![Span::raw("- "), Span::raw("List I")]));
802 assert_eq!(text.lines[5], Spans(vec![Span::raw(" "), Span::raw("tem 3"), Span::raw(" ")]));
803 }
804
805 #[test]
806 fn test_list_ordered() {
807 let s = "<ol><li>List Item 1</li><li>List Item 2</li><li>List Item 3</li></ol>";
808 let tree = parse_matrix_html(s);
809 let text = tree.to_text(9, Style::default(), false);
810 assert_eq!(text.lines.len(), 6);
811 assert_eq!(text.lines[0], Spans(vec![Span::raw("1. "), Span::raw("List I")]));
812 assert_eq!(
813 text.lines[1],
814 Spans(vec![Span::raw(" "), Span::raw("tem 1"), Span::raw(" ")])
815 );
816 assert_eq!(text.lines[2], Spans(vec![Span::raw("2. "), Span::raw("List I")]));
817 assert_eq!(
818 text.lines[3],
819 Spans(vec![Span::raw(" "), Span::raw("tem 2"), Span::raw(" ")])
820 );
821 assert_eq!(text.lines[4], Spans(vec![Span::raw("3. "), Span::raw("List I")]));
822 assert_eq!(
823 text.lines[5],
824 Spans(vec![Span::raw(" "), Span::raw("tem 3"), Span::raw(" ")])
825 );
826 }
827
828 #[test]
829 fn test_table() {
830 let s = "<table>\
831 <thead>\
832 <tr><th>Column 1</th><th>Column 2</th><th>Column 3</th></tr>
833 </thead>\
834 <tbody>\
835 <tr><td>a</td><td>b</td><td>c</td></tr>\
836 <tr><td>a</td><td>b</td><td>c</td></tr>\
837 <tr><td>a</td><td>b</td><td>c</td></tr>\
838 </tbody></table>";
839 let tree = parse_matrix_html(s);
840 let text = tree.to_text(15, Style::default(), false);
841 let bold = Style::default().add_modifier(StyleModifier::BOLD);
842 assert_eq!(text.lines.len(), 11);
843
844 // Table header
845 assert_eq!(text.lines[0].0, vec![Span::raw("┌────┬────┬───┐")]);
846 assert_eq!(text.lines[1].0, vec![
847 Span::raw("│"),
848 Span::styled("Colu", bold),
849 Span::raw("│"),
850 Span::styled("Colu", bold),
851 Span::raw("│"),
852 Span::styled("Col", bold),
853 Span::raw("│")
854 ]);
855 assert_eq!(text.lines[2].0, vec![
856 Span::raw("│"),
857 Span::styled("mn 1", bold),
858 Span::raw("│"),
859 Span::styled("mn 2", bold),
860 Span::raw("│"),
861 Span::styled("umn", bold),
862 Span::raw("│")
863 ]);
864 assert_eq!(text.lines[3].0, vec![
865 Span::raw("│"),
866 Span::raw(" "),
867 Span::raw("│"),
868 Span::raw(" "),
869 Span::raw("│"),
870 Span::styled(" 3", bold),
871 Span::styled(" ", bold),
872 Span::raw("│")
873 ]);
874
875 // First row
876 assert_eq!(text.lines[4].0, vec![Span::raw("├────┼────┼───┤")]);
877 assert_eq!(text.lines[5].0, vec![
878 Span::raw("│"),
879 Span::raw("a"),
880 Span::raw(" "),
881 Span::raw("│"),
882 Span::raw("b"),
883 Span::raw(" "),
884 Span::raw("│"),
885 Span::raw("c"),
886 Span::raw(" "),
887 Span::raw("│")
888 ]);
889
890 // Second row
891 assert_eq!(text.lines[6].0, vec![Span::raw("├────┼────┼───┤")]);
892 assert_eq!(text.lines[7].0, vec![
893 Span::raw("│"),
894 Span::raw("a"),
895 Span::raw(" "),
896 Span::raw("│"),
897 Span::raw("b"),
898 Span::raw(" "),
899 Span::raw("│"),
900 Span::raw("c"),
901 Span::raw(" "),
902 Span::raw("│")
903 ]);
904
905 // Third row
906 assert_eq!(text.lines[8].0, vec![Span::raw("├────┼────┼───┤")]);
907 assert_eq!(text.lines[9].0, vec![
908 Span::raw("│"),
909 Span::raw("a"),
910 Span::raw(" "),
911 Span::raw("│"),
912 Span::raw("b"),
913 Span::raw(" "),
914 Span::raw("│"),
915 Span::raw("c"),
916 Span::raw(" "),
917 Span::raw("│")
918 ]);
919
920 // Bottom ruler
921 assert_eq!(text.lines[10].0, vec![Span::raw("└────┴────┴───┘")]);
922 }
923
924 #[test]
925 fn test_matrix_reply() {
926 let s = "<mx-reply>This was replied to</mx-reply>This is the reply";
927
928 let tree = parse_matrix_html(s);
929 let text = tree.to_text(10, Style::default(), false);
930 assert_eq!(text.lines.len(), 4);
931 assert_eq!(text.lines[0], Spans(vec![Span::raw("This was r")]));
932 assert_eq!(text.lines[1], Spans(vec![Span::raw("eplied to"), Span::raw(" ")]));
933 assert_eq!(text.lines[2], Spans(vec![Span::raw("This is th")]));
934 assert_eq!(text.lines[3], Spans(vec![Span::raw("e reply"), Span::raw(" ")]));
935
936 let tree = parse_matrix_html(s);
937 let text = tree.to_text(10, Style::default(), true);
938 assert_eq!(text.lines.len(), 2);
939 assert_eq!(text.lines[0], Spans(vec![Span::raw("This is th")]));
940 assert_eq!(text.lines[1], Spans(vec![Span::raw("e reply"), Span::raw(" ")]));
941 }
942}
src/message.rs → src/message/mod.rs renamed +199 −167
@@ -4,19 +4,20 @@ use std::collections::hash_map::DefaultHasher;
44use std::collections::BTreeMap;
55use std::convert::TryFrom;
66use std::hash::{Hash, Hasher};
7use std::str::Lines;
87
98use chrono::{DateTime, NaiveDateTime, Utc};
10use unicode_segmentation::UnicodeSegmentation;
119use unicode_width::UnicodeWidthStr;
1210
1311use matrix_sdk::ruma::{
1412 events::{
1513 room::{
1614 message::{
15 FormattedBody,
16 MessageFormat,
1717 MessageType,
1818 OriginalRoomMessageEvent,
1919 RedactedRoomMessageEvent,
20 Relation,
2021 RoomMessageEvent,
2122 RoomMessageEventContent,
2223 },
@@ -33,6 +34,7 @@ use matrix_sdk::ruma::{
3334
3435use modalkit::tui::{
3536 style::{Modifier as StyleModifier, Style},
37 symbols::line::THICK_VERTICAL,
3638 text::{Span, Spans, Text},
3739};
3840
@@ -41,8 +43,13 @@ use modalkit::editing::{base::ViewportContext, cursor::Cursor};
4143use crate::{
4244 base::{IambResult, RoomInfo},
4345 config::ApplicationSettings,
46 message::html::{parse_matrix_html, StyleTree},
47 util::{space_span, wrapped_text},
4448};
4549
50mod html;
51mod printer;
52
4653pub type MessageFetchResult = IambResult<(Option<String>, Vec<RoomMessageEvent>)>;
4754pub type MessageKey = (MessageTimeStamp, OwnedEventId);
4855pub type Messages = BTreeMap<MessageKey, Message>;
@@ -62,65 +69,6 @@ const USER_GUTTER_EMPTY_SPAN: Span<'static> = Span {
6269 },
6370};
6471
65struct WrappedLinesIterator<'a> {
66 iter: Lines<'a>,
67 curr: Option<&'a str>,
68 width: usize,
69}
70
71impl<'a> WrappedLinesIterator<'a> {
72 fn new(input: &'a str, width: usize) -> Self {
73 WrappedLinesIterator { iter: input.lines(), curr: None, width }
74 }
75}
76
77impl<'a> Iterator for WrappedLinesIterator<'a> {
78 type Item = (&'a str, usize);
79
80 fn next(&mut self) -> Option<Self::Item> {
81 if self.curr.is_none() {
82 self.curr = self.iter.next();
83 }
84
85 if let Some(s) = self.curr.take() {
86 let width = UnicodeWidthStr::width(s);
87
88 if width <= self.width {
89 return Some((s, width));
90 } else {
91 // Find where to split the line.
92 let mut width = 0;
93 let mut idx = 0;
94
95 for (i, g) in UnicodeSegmentation::grapheme_indices(s, true) {
96 let gw = UnicodeWidthStr::width(g);
97 idx = i;
98
99 if width + gw > self.width {
100 break;
101 }
102
103 width += gw;
104 }
105
106 self.curr = Some(&s[idx..]);
107
108 return Some((&s[..idx], width));
109 }
110 } else {
111 return None;
112 }
113 }
114}
115
116fn wrap(input: &str, width: usize) -> WrappedLinesIterator<'_> {
117 WrappedLinesIterator::new(input, width)
118}
119
120fn space(width: usize) -> String {
121 " ".repeat(width)
122}
123
12472#[derive(thiserror::Error, Debug)]
12573pub enum TimeStampIntError {
12674 #[error("Integer conversion error: {0}")]
@@ -327,9 +275,9 @@ pub enum MessageEvent {
327275}
328276
329277impl MessageEvent {
330 pub fn show(&self) -> Cow<'_, str> {
278 pub fn body(&self) -> Cow<'_, str> {
331279 match self {
332 MessageEvent::Original(ev) => show_room_content(&ev.content),
280 MessageEvent::Original(ev) => body_cow_content(&ev.content),
333281 MessageEvent::Redacted(ev) => {
334282 let reason = ev
335283 .unsigned
@@ -344,7 +292,25 @@ impl MessageEvent {
344292 Cow::Borrowed("[Redacted]")
345293 }
346294 },
347 MessageEvent::Local(content) => show_room_content(content),
295 MessageEvent::Local(content) => body_cow_content(content),
296 }
297 }
298
299 pub fn html(&self) -> Option<StyleTree> {
300 let content = match self {
301 MessageEvent::Original(ev) => &ev.content,
302 MessageEvent::Redacted(_) => return None,
303 MessageEvent::Local(content) => content,
304 };
305
306 if let MessageType::Text(content) = &content.msgtype {
307 if let Some(FormattedBody { format: MessageFormat::Html, body }) = &content.formatted {
308 Some(parse_matrix_html(body.as_str()))
309 } else {
310 None
311 }
312 } else {
313 None
348314 }
349315 }
350316
@@ -360,18 +326,14 @@ impl MessageEvent {
360326 }
361327}
362328
363fn show_room_content(content: &RoomMessageEventContent) -> Cow<'_, str> {
329fn body_cow_content(content: &RoomMessageEventContent) -> Cow<'_, str> {
364330 let s = match &content.msgtype {
365 MessageType::Text(content) => content.body.as_ref(),
331 MessageType::Text(content) => content.body.as_str(),
332 MessageType::VerificationRequest(_) => "[Verification Request]",
366333 MessageType::Emote(content) => content.body.as_ref(),
367334 MessageType::Notice(content) => content.body.as_str(),
368335 MessageType::ServerNotice(content) => content.body.as_str(),
369336
370 MessageType::VerificationRequest(_) => {
371 // XXX: implement
372
373 return Cow::Owned("[verification request]".into());
374 },
375337 MessageType::Audio(content) => {
376338 return Cow::Owned(format!("[Attached Audio: {}]", content.body));
377339 },
@@ -392,37 +354,93 @@ fn show_room_content(content: &RoomMessageEventContent) -> Cow<'_, str> {
392354 Cow::Borrowed(s)
393355}
394356
395#[derive(Clone)]
357enum MessageColumns<'a> {
358 Three(usize, Option<Span<'a>>, Option<Span<'a>>),
359 Two(usize, Option<Span<'a>>),
360 One(usize, Option<Span<'a>>),
361}
362
363impl<'a> MessageColumns<'a> {
364 fn width(&self) -> usize {
365 match self {
366 MessageColumns::Three(fill, _, _) => *fill,
367 MessageColumns::Two(fill, _) => *fill,
368 MessageColumns::One(fill, _) => *fill,
369 }
370 }
371
372 #[inline]
373 fn push_spans(&mut self, spans: Spans<'a>, style: Style, text: &mut Text<'a>) {
374 match self {
375 MessageColumns::Three(_, user, time) => {
376 let user = user.take().unwrap_or(USER_GUTTER_EMPTY_SPAN);
377 let time = time.take().unwrap_or_else(|| Span::from(""));
378
379 let mut line = vec![user];
380 line.extend(spans.0);
381 line.push(time);
382
383 text.lines.push(Spans(line))
384 },
385 MessageColumns::Two(_, opt) => {
386 let user = opt.take().unwrap_or(USER_GUTTER_EMPTY_SPAN);
387 let mut line = vec![user];
388 line.extend(spans.0);
389
390 text.lines.push(Spans(line));
391 },
392 MessageColumns::One(_, opt) => {
393 if let Some(user) = opt.take() {
394 text.lines.push(Spans(vec![user]));
395 }
396
397 let leading = space_span(2, style);
398 let mut line = vec![leading];
399 line.extend(spans.0);
400
401 text.lines.push(Spans(line));
402 },
403 }
404 }
405
406 fn push_text(&mut self, append: Text<'a>, style: Style, text: &mut Text<'a>) {
407 for line in append.lines.into_iter() {
408 self.push_spans(line, style, text);
409 }
410 }
411}
412
396413pub struct Message {
397414 pub event: MessageEvent,
398415 pub sender: OwnedUserId,
399416 pub timestamp: MessageTimeStamp,
400417 pub downloaded: bool,
418 pub html: Option<StyleTree>,
401419}
402420
403421impl Message {
404422 pub fn new(event: MessageEvent, sender: OwnedUserId, timestamp: MessageTimeStamp) -> Self {
405 Message { event, sender, timestamp, downloaded: false }
423 let html = event.html();
424 let downloaded = false;
425
426 Message { event, sender, timestamp, downloaded, html }
406427 }
407428
408 pub fn show(
409 &self,
410 prev: Option<&Message>,
411 selected: bool,
412 vwctx: &ViewportContext<MessageCursor>,
413 settings: &ApplicationSettings,
414 ) -> Text {
415 let width = vwctx.get_width();
416 let mut msg = self.event.show();
429 pub fn reply_to(&self) -> Option<OwnedEventId> {
430 let content = match &self.event {
431 MessageEvent::Local(content) => content,
432 MessageEvent::Original(ev) => &ev.content,
433 MessageEvent::Redacted(_) => return None,
434 };
417435
418 if self.downloaded {
419 msg.to_mut().push_str(" \u{2705}");
436 if let Some(Relation::Reply { in_reply_to }) = &content.relates_to {
437 Some(in_reply_to.event_id.clone())
438 } else {
439 None
420440 }
441 }
421442
422 let msg = msg.as_ref();
423
424 let mut lines = vec![];
425
443 fn get_render_style(&self, selected: bool) -> Style {
426444 let mut style = Style::default();
427445
428446 if selected {
@@ -433,54 +451,109 @@ impl Message {
433451 style = style.add_modifier(StyleModifier::ITALIC);
434452 }
435453
454 return style;
455 }
456
457 fn get_render_format(
458 &self,
459 prev: Option<&Message>,
460 width: usize,
461 settings: &ApplicationSettings,
462 ) -> MessageColumns {
436463 if USER_GUTTER + TIME_GUTTER + MIN_MSG_LEN <= width {
437464 let lw = width - USER_GUTTER - TIME_GUTTER;
465 let user = self.show_sender(prev, true, settings);
466 let time = self.timestamp.show();
438467
439 for (i, (line, w)) in wrap(msg, lw).enumerate() {
440 let line = Span::styled(line.to_string(), style);
441 let trailing = Span::styled(space(lw.saturating_sub(w)), style);
468 MessageColumns::Three(lw, user, time)
469 } else if USER_GUTTER + MIN_MSG_LEN <= width {
470 let lw = width - USER_GUTTER;
471 let user = self.show_sender(prev, true, settings);
442472
443 if i == 0 {
444 let user = self.show_sender(prev, true, settings);
473 MessageColumns::Two(lw, user)
474 } else {
475 let lw = width.saturating_sub(2);
476 let user = self.show_sender(prev, false, settings);
445477
446 if let Some(time) = self.timestamp.show() {
447 lines.push(Spans(vec![user, line, trailing, time]))
448 } else {
449 lines.push(Spans(vec![user, line, trailing]))
450 }
451 } else {
452 let space = USER_GUTTER_EMPTY_SPAN;
478 MessageColumns::One(lw, user)
479 }
480 }
453481
454 lines.push(Spans(vec![space, line, trailing]))
455 }
482 pub fn show<'a>(
483 &'a self,
484 prev: Option<&Message>,
485 selected: bool,
486 vwctx: &ViewportContext<MessageCursor>,
487 info: &'a RoomInfo,
488 settings: &ApplicationSettings,
489 ) -> Text<'a> {
490 let width = vwctx.get_width();
491
492 let style = self.get_render_style(selected);
493 let mut fmt = self.get_render_format(prev, width, settings);
494 let mut text = Text { lines: vec![] };
495 let width = fmt.width();
496
497 // Show the message that this one replied to, if any.
498 let reply = self.reply_to().and_then(|e| info.get_event(&e));
499
500 if let Some(r) = &reply {
501 let w = width.saturating_sub(2);
502 let mut replied = r.show_msg(w, style, true);
503 let mut sender = r.sender_span(settings);
504 let sender_width = UnicodeWidthStr::width(sender.content.as_ref());
505 let trailing = w.saturating_sub(sender_width + 1);
506
507 sender.style = sender.style.patch(style);
508
509 fmt.push_spans(
510 Spans(vec![
511 Span::styled(" ", style),
512 Span::styled(THICK_VERTICAL, style),
513 sender,
514 Span::styled(":", style),
515 space_span(trailing, style),
516 ]),
517 style,
518 &mut text,
519 );
520
521 for line in replied.lines.iter_mut() {
522 line.0.insert(0, Span::styled(THICK_VERTICAL, style));
523 line.0.insert(0, Span::styled(" ", style));
456524 }
457 } else if USER_GUTTER + MIN_MSG_LEN <= width {
458 let lw = width - USER_GUTTER;
459525
460 for (i, (line, w)) in wrap(msg, lw).enumerate() {
461 let line = Span::styled(line.to_string(), style);
462 let trailing = Span::styled(space(lw.saturating_sub(w)), style);
526 fmt.push_text(replied, style, &mut text);
527 }
463528
464 let prefix = if i == 0 {
465 self.show_sender(prev, true, settings)
466 } else {
467 USER_GUTTER_EMPTY_SPAN
468 };
529 // Now show the message contents, and the inlined reply if we couldn't find it above.
530 let msg = self.show_msg(width, style, reply.is_some());
531 fmt.push_text(msg, style, &mut text);
469532
470 lines.push(Spans(vec![prefix, line, trailing]))
471 }
472 } else {
473 lines.push(Spans::from(self.show_sender(prev, false, settings)));
533 if text.lines.is_empty() {
534 // If there was nothing in the body, just show an empty message.
535 fmt.push_spans(space_span(width, style).into(), style, &mut text);
536 }
474537
475 for (line, _) in wrap(msg, width.saturating_sub(2)) {
476 let line = format!(" {}", line);
477 let line = Span::styled(line, style);
538 return text;
539 }
540
541 pub fn show_msg(&self, width: usize, style: Style, hide_reply: bool) -> Text {
542 if let Some(html) = &self.html {
543 html.to_text(width, style, hide_reply)
544 } else {
545 let mut msg = self.event.body();
478546
479 lines.push(Spans(vec![line]))
547 if self.downloaded {
548 msg.to_mut().push_str(" \u{2705}");
480549 }
550
551 wrapped_text(msg, width, style)
481552 }
553 }
482554
483 return Text { lines };
555 fn sender_span(&self, settings: &ApplicationSettings) -> Span {
556 settings.get_user_span(self.sender.as_ref())
484557 }
485558
486559 fn show_sender(
@@ -488,11 +561,11 @@ impl Message {
488561 prev: Option<&Message>,
489562 align_right: bool,
490563 settings: &ApplicationSettings,
491 ) -> Span {
564 ) -> Option<Span> {
492565 let user = if matches!(prev, Some(prev) if self.sender == prev.sender) {
493 USER_GUTTER_EMPTY_SPAN
566 return None;
494567 } else {
495 settings.get_user_span(self.sender.as_ref())
568 self.sender_span(settings)
496569 };
497570
498571 let Span { content, style } = user;
@@ -505,7 +578,7 @@ impl Message {
505578 format!("{: <width$} ", s, width = 28)
506579 };
507580
508 Span::styled(sender, style)
581 Span::styled(sender, style).into()
509582 }
510583}
511584
@@ -540,7 +613,7 @@ impl From<RoomMessageEvent> for Message {
540613
541614impl ToString for Message {
542615 fn to_string(&self) -> String {
543 self.event.show().into_owned()
616 self.event.body().into_owned()
544617 }
545618}
546619
@@ -549,47 +622,6 @@ pub mod tests {
549622 use super::*;
550623 use crate::tests::*;
551624
552 #[test]
553 fn test_wrapped_lines_ascii() {
554 let s = "hello world!\nabcdefghijklmnopqrstuvwxyz\ngoodbye";
555
556 let mut iter = wrap(s, 100);
557 assert_eq!(iter.next(), Some(("hello world!", 12)));
558 assert_eq!(iter.next(), Some(("abcdefghijklmnopqrstuvwxyz", 26)));
559 assert_eq!(iter.next(), Some(("goodbye", 7)));
560 assert_eq!(iter.next(), None);
561
562 let mut iter = wrap(s, 5);
563 assert_eq!(iter.next(), Some(("hello", 5)));
564 assert_eq!(iter.next(), Some((" worl", 5)));
565 assert_eq!(iter.next(), Some(("d!", 2)));
566 assert_eq!(iter.next(), Some(("abcde", 5)));
567 assert_eq!(iter.next(), Some(("fghij", 5)));
568 assert_eq!(iter.next(), Some(("klmno", 5)));
569 assert_eq!(iter.next(), Some(("pqrst", 5)));
570 assert_eq!(iter.next(), Some(("uvwxy", 5)));
571 assert_eq!(iter.next(), Some(("z", 1)));
572 assert_eq!(iter.next(), Some(("goodb", 5)));
573 assert_eq!(iter.next(), Some(("ye", 2)));
574 assert_eq!(iter.next(), None);
575 }
576
577 #[test]
578 fn test_wrapped_lines_unicode() {
579 let s = "CHICKEN";
580
581 let mut iter = wrap(s, 14);
582 assert_eq!(iter.next(), Some((s, 14)));
583 assert_eq!(iter.next(), None);
584
585 let mut iter = wrap(s, 5);
586 assert_eq!(iter.next(), Some(("CH", 4)));
587 assert_eq!(iter.next(), Some(("IC", 4)));
588 assert_eq!(iter.next(), Some(("KE", 4)));
589 assert_eq!(iter.next(), Some(("N", 2)));
590 assert_eq!(iter.next(), None);
591 }
592
593625 #[test]
594626 fn test_mc_cmp() {
595627 let mc1 = MessageCursor::from(MSG1_KEY.clone());
src/message/printer.rs added +157
@@ -0,0 +1,157 @@
1use std::borrow::Cow;
2
3use modalkit::tui::layout::Alignment;
4use modalkit::tui::style::Style;
5use modalkit::tui::text::{Span, Spans, Text};
6use unicode_width::UnicodeWidthStr;
7
8use crate::util::{space_span, take_width};
9
10pub struct TextPrinter<'a> {
11 text: Text<'a>,
12 width: usize,
13 base_style: Style,
14 hide_reply: bool,
15
16 alignment: Alignment,
17 curr_spans: Vec<Span<'a>>,
18 curr_width: usize,
19}
20
21impl<'a> TextPrinter<'a> {
22 pub fn new(width: usize, base_style: Style, hide_reply: bool) -> Self {
23 TextPrinter {
24 text: Text::default(),
25 width,
26 base_style,
27 hide_reply,
28
29 alignment: Alignment::Left,
30 curr_spans: vec![],
31 curr_width: 0,
32 }
33 }
34
35 pub fn align(mut self, alignment: Alignment) -> Self {
36 self.alignment = alignment;
37 self
38 }
39
40 pub fn hide_reply(&self) -> bool {
41 self.hide_reply
42 }
43
44 pub fn width(&self) -> usize {
45 self.width
46 }
47
48 pub fn sub(&self, indent: usize) -> Self {
49 TextPrinter {
50 text: Text::default(),
51 width: self.width.saturating_sub(indent),
52 base_style: self.base_style,
53 hide_reply: self.hide_reply,
54
55 alignment: self.alignment,
56 curr_spans: vec![],
57 curr_width: 0,
58 }
59 }
60
61 fn remaining(&self) -> usize {
62 self.width - self.curr_width
63 }
64
65 pub fn commit(&mut self) {
66 if self.curr_width > 0 {
67 self.push_break();
68 }
69 }
70
71 fn push(&mut self) {
72 self.curr_width = 0;
73 self.text.lines.push(Spans(std::mem::take(&mut self.curr_spans)));
74 }
75
76 pub fn push_break(&mut self) {
77 if self.curr_width == 0 && self.text.lines.is_empty() {
78 // Disallow leading breaks.
79 return;
80 }
81
82 let remaining = self.remaining();
83
84 if remaining > 0 {
85 match self.alignment {
86 Alignment::Left => {
87 let tspan = space_span(remaining, self.base_style);
88 self.curr_spans.push(tspan);
89 },
90 Alignment::Center => {
91 let trailing = remaining / 2;
92 let leading = remaining - trailing;
93
94 let tspan = space_span(trailing, self.base_style);
95 let lspan = space_span(leading, self.base_style);
96
97 self.curr_spans.push(tspan);
98 self.curr_spans.insert(0, lspan);
99 },
100 Alignment::Right => {
101 let lspan = space_span(remaining, self.base_style);
102 self.curr_spans.insert(0, lspan);
103 },
104 }
105 }
106
107 self.push();
108 }
109
110 pub fn push_str<T>(&mut self, s: T, style: Style)
111 where
112 T: Into<Cow<'a, str>>,
113 {
114 let style = self.base_style.patch(style);
115 let mut cow = s.into();
116
117 loop {
118 let sw = UnicodeWidthStr::width(cow.as_ref());
119
120 if self.curr_width + sw <= self.width {
121 // The text fits within the current line.
122 self.curr_spans.push(Span::styled(cow, style));
123 self.curr_width += sw;
124 break;
125 }
126
127 // Take a leading portion of the text that fits in the line.
128 let ((s0, w), s1) = take_width(cow, self.remaining());
129 cow = s1;
130
131 self.curr_spans.push(Span::styled(s0, style));
132 self.curr_width += w;
133
134 self.commit();
135 }
136
137 if self.curr_width == self.width {
138 // If the last bit fills the full line, start a new one.
139 self.push();
140 }
141 }
142
143 pub fn push_line(&mut self, spans: Spans<'a>) {
144 self.commit();
145 self.text.lines.push(spans);
146 }
147
148 pub fn push_text(&mut self, text: Text<'a>) {
149 self.commit();
150 self.text.lines.extend(text.lines);
151 }
152
153 pub fn finish(mut self) -> Text<'a> {
154 self.commit();
155 self.text
156 }
157}
src/util.rs added +191
@@ -0,0 +1,191 @@
1use std::borrow::Cow;
2
3use unicode_segmentation::UnicodeSegmentation;
4use unicode_width::UnicodeWidthStr;
5
6use modalkit::tui::style::Style;
7use modalkit::tui::text::{Span, Spans, Text};
8
9pub fn split_cow(cow: Cow<'_, str>, idx: usize) -> (Cow<'_, str>, Cow<'_, str>) {
10 match cow {
11 Cow::Borrowed(s) => {
12 let s1 = Cow::Borrowed(&s[idx..]);
13 let s0 = Cow::Borrowed(&s[..idx]);
14
15 (s0, s1)
16 },
17 Cow::Owned(mut s) => {
18 let s1 = Cow::Owned(s.split_off(idx));
19 let s0 = Cow::Owned(s);
20
21 (s0, s1)
22 },
23 }
24}
25
26pub fn take_width(s: Cow<'_, str>, width: usize) -> ((Cow<'_, str>, usize), Cow<'_, str>) {
27 // Find where to split the line.
28 let mut idx = 0;
29 let mut w = 0;
30
31 for (i, g) in UnicodeSegmentation::grapheme_indices(s.as_ref(), true) {
32 let gw = UnicodeWidthStr::width(g);
33 idx = i;
34
35 if w + gw > width {
36 break;
37 }
38
39 w += gw;
40 }
41
42 let (s0, s1) = split_cow(s, idx);
43
44 ((s0, w), s1)
45}
46
47pub struct WrappedLinesIterator<'a> {
48 iter: std::vec::IntoIter<Cow<'a, str>>,
49 curr: Option<Cow<'a, str>>,
50 width: usize,
51}
52
53impl<'a> WrappedLinesIterator<'a> {
54 fn new<T>(input: T, width: usize) -> Self
55 where
56 T: Into<Cow<'a, str>>,
57 {
58 let width = width.max(2);
59
60 let cows: Vec<Cow<'a, str>> = match input.into() {
61 Cow::Borrowed(s) => s.lines().map(Cow::Borrowed).collect(),
62 Cow::Owned(s) => s.lines().map(ToOwned::to_owned).map(Cow::Owned).collect(),
63 };
64
65 WrappedLinesIterator { iter: cows.into_iter(), curr: None, width }
66 }
67}
68
69impl<'a> Iterator for WrappedLinesIterator<'a> {
70 type Item = (Cow<'a, str>, usize);
71
72 fn next(&mut self) -> Option<Self::Item> {
73 if self.curr.is_none() {
74 self.curr = self.iter.next();
75 }
76
77 if let Some(s) = self.curr.take() {
78 let width = UnicodeWidthStr::width(s.as_ref());
79
80 if width <= self.width {
81 return Some((s, width));
82 } else {
83 let (prefix, s1) = take_width(s, self.width);
84 self.curr = Some(s1);
85 return Some(prefix);
86 }
87 } else {
88 return None;
89 }
90 }
91}
92
93pub fn wrap<'a, T>(input: T, width: usize) -> WrappedLinesIterator<'a>
94where
95 T: Into<Cow<'a, str>>,
96{
97 WrappedLinesIterator::new(input, width)
98}
99
100pub fn wrapped_text<'a, T>(s: T, width: usize, style: Style) -> Text<'a>
101where
102 T: Into<Cow<'a, str>>,
103{
104 let mut text = Text::default();
105
106 for (line, w) in wrap(s, width) {
107 let space = space_span(width.saturating_sub(w), style);
108 let spans = Spans(vec![Span::styled(line, style), space]);
109
110 text.lines.push(spans);
111 }
112
113 return text;
114}
115
116pub fn space(width: usize) -> String {
117 " ".repeat(width)
118}
119
120pub fn space_span(width: usize, style: Style) -> Span<'static> {
121 Span::styled(space(width), style)
122}
123
124pub fn space_text(width: usize, style: Style) -> Text<'static> {
125 space_span(width, style).into()
126}
127
128pub fn join_cell_text<'a>(texts: Vec<(Text<'a>, usize)>, join: Span<'a>) -> Text<'a> {
129 let height = texts.iter().map(|t| t.0.height()).max().unwrap_or(0);
130 let mut text = Text { lines: vec![Spans(vec![join.clone()]); height] };
131
132 for (mut t, w) in texts.into_iter() {
133 for i in 0..height {
134 if let Some(spans) = t.lines.get_mut(i) {
135 text.lines[i].0.append(&mut spans.0);
136 } else {
137 text.lines[i].0.push(space_span(w, Style::default()));
138 }
139
140 text.lines[i].0.push(join.clone());
141 }
142 }
143
144 text
145}
146
147#[cfg(test)]
148pub mod tests {
149 use super::*;
150
151 #[test]
152 fn test_wrapped_lines_ascii() {
153 let s = "hello world!\nabcdefghijklmnopqrstuvwxyz\ngoodbye";
154
155 let mut iter = wrap(s, 100);
156 assert_eq!(iter.next(), Some((Cow::Borrowed("hello world!"), 12)));
157 assert_eq!(iter.next(), Some((Cow::Borrowed("abcdefghijklmnopqrstuvwxyz"), 26)));
158 assert_eq!(iter.next(), Some((Cow::Borrowed("goodbye"), 7)));
159 assert_eq!(iter.next(), None);
160
161 let mut iter = wrap(s, 5);
162 assert_eq!(iter.next(), Some((Cow::Borrowed("hello"), 5)));
163 assert_eq!(iter.next(), Some((Cow::Borrowed(" worl"), 5)));
164 assert_eq!(iter.next(), Some((Cow::Borrowed("d!"), 2)));
165 assert_eq!(iter.next(), Some((Cow::Borrowed("abcde"), 5)));
166 assert_eq!(iter.next(), Some((Cow::Borrowed("fghij"), 5)));
167 assert_eq!(iter.next(), Some((Cow::Borrowed("klmno"), 5)));
168 assert_eq!(iter.next(), Some((Cow::Borrowed("pqrst"), 5)));
169 assert_eq!(iter.next(), Some((Cow::Borrowed("uvwxy"), 5)));
170 assert_eq!(iter.next(), Some((Cow::Borrowed("z"), 1)));
171 assert_eq!(iter.next(), Some((Cow::Borrowed("goodb"), 5)));
172 assert_eq!(iter.next(), Some((Cow::Borrowed("ye"), 2)));
173 assert_eq!(iter.next(), None);
174 }
175
176 #[test]
177 fn test_wrapped_lines_unicode() {
178 let s = "CHICKEN";
179
180 let mut iter = wrap(s, 14);
181 assert_eq!(iter.next(), Some((Cow::Borrowed(s), 14)));
182 assert_eq!(iter.next(), None);
183
184 let mut iter = wrap(s, 5);
185 assert_eq!(iter.next(), Some((Cow::Borrowed("CH"), 4)));
186 assert_eq!(iter.next(), Some((Cow::Borrowed("IC"), 4)));
187 assert_eq!(iter.next(), Some((Cow::Borrowed("KE"), 4)));
188 assert_eq!(iter.next(), Some((Cow::Borrowed("N"), 2)));
189 assert_eq!(iter.next(), None);
190 }
191}
src/windows/room/chat.rs +1 −1
@@ -324,7 +324,7 @@ impl ChatState {
324324 return Ok(None);
325325 }
326326
327 let msg = TextMessageEventContent::plain(msg);
327 let msg = TextMessageEventContent::markdown(msg);
328328 let msg = MessageType::Text(msg);
329329
330330 let mut msg = RoomMessageEventContent::new(msg);
src/windows/room/scrollback.rs +9 −9
@@ -214,7 +214,7 @@ impl ScrollbackState {
214214
215215 for (key, item) in info.messages.range(..=&idx).rev() {
216216 let sel = selidx == key;
217 let len = item.show(None, sel, &self.viewctx, settings).lines.len();
217 let len = item.show(None, sel, &self.viewctx, info, settings).lines.len();
218218
219219 if key == &idx {
220220 lines += len / 2;
@@ -236,7 +236,7 @@ impl ScrollbackState {
236236
237237 for (key, item) in info.messages.range(..=&idx).rev() {
238238 let sel = key == selidx;
239 let len = item.show(None, sel, &self.viewctx, settings).lines.len();
239 let len = item.show(None, sel, &self.viewctx, info, settings).lines.len();
240240
241241 lines += len;
242242
@@ -276,7 +276,7 @@ impl ScrollbackState {
276276 break;
277277 }
278278
279 lines += item.show(None, false, &self.viewctx, settings).height().max(1);
279 lines += item.show(None, false, &self.viewctx, info, settings).height().max(1);
280280
281281 if lines >= self.viewctx.get_height() {
282282 // We've reached the end of the viewport; move cursor into it.
@@ -431,7 +431,7 @@ impl ScrollbackState {
431431 continue;
432432 }
433433
434 if needle.is_match(msg.event.show().as_ref()) {
434 if needle.is_match(msg.event.body().as_ref()) {
435435 mc = MessageCursor::from(key.clone()).into();
436436 count -= 1;
437437 }
@@ -455,7 +455,7 @@ impl ScrollbackState {
455455 break;
456456 }
457457
458 if needle.is_match(msg.event.show().as_ref()) {
458 if needle.is_match(msg.event.body().as_ref()) {
459459 mc = MessageCursor::from(key.clone()).into();
460460 count -= 1;
461461 }
@@ -704,7 +704,7 @@ impl EditorActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
704704 let mut yanked = EditRope::from("");
705705
706706 for (_, msg) in self.messages(range, info) {
707 yanked += EditRope::from(msg.event.show().into_owned());
707 yanked += EditRope::from(msg.event.body());
708708 yanked += EditRope::from('\n');
709709 }
710710
@@ -1009,7 +1009,7 @@ impl ScrollActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
10091009
10101010 for (key, item) in info.messages.range(..=&corner_key).rev() {
10111011 let sel = key == cursor_key;
1012 let txt = item.show(None, sel, &self.viewctx, settings);
1012 let txt = item.show(None, sel, &self.viewctx, info, settings);
10131013 let len = txt.height().max(1);
10141014 let max = len.saturating_sub(1);
10151015
@@ -1035,7 +1035,7 @@ impl ScrollActions<ProgramContext, ProgramStore, IambInfo> for ScrollbackState {
10351035 MoveDir2D::Down => {
10361036 for (key, item) in info.messages.range(&corner_key..) {
10371037 let sel = key == cursor_key;
1038 let txt = item.show(None, sel, &self.viewctx, settings);
1038 let txt = item.show(None, sel, &self.viewctx, info, settings);
10391039 let len = txt.height().max(1);
10401040 let max = len.saturating_sub(1);
10411041
@@ -1218,7 +1218,7 @@ impl<'a> StatefulWidget for Scrollback<'a> {
12181218
12191219 for (key, item) in info.messages.range(&corner_key..) {
12201220 let sel = key == cursor_key;
1221 let txt = item.show(prev, foc && sel, &state.viewctx, settings);
1221 let txt = item.show(prev, foc && sel, &state.viewctx, info, settings);
12221222
12231223 prev = Some(item);
12241224