5 Commits

Author SHA1 Message Date
b41de00c95 chore: release version 1.0.0-beta2 2026-03-18 15:22:04 +07:00
94cbb4aa0e chore: fix some gossip and nip4e bugs (#23)
Reviewed-on: #23
Co-authored-by: Ren Amamiya <reya@lume.nu>
Co-committed-by: Ren Amamiya <reya@lume.nu>
2026-03-18 08:21:39 +00:00
40e7ca368b feat: add backup/restore for NIP-4e encryption key (#22)
Reviewed-on: #22
Co-authored-by: Ren Amamiya <reya@lume.nu>
Co-committed-by: Ren Amamiya <reya@lume.nu>
2026-03-17 07:42:25 +00:00
b91697defc feat: add relay tracking for gift wrap events (#21)
Reviewed-on: #21
Co-authored-by: Ren Amamiya <reya@lume.nu>
Co-committed-by: Ren Amamiya <reya@lume.nu>
2026-03-14 08:18:19 +00:00
1d57a2deab chore: bump edition from 2021 to 2024 2026-03-13 09:13:04 +07:00
33 changed files with 1296 additions and 898 deletions

228
Cargo.lock generated
View File

@@ -117,9 +117,9 @@ dependencies = [
[[package]] [[package]]
name = "anstyle" name = "anstyle"
version = "1.0.13" version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78" checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
[[package]] [[package]]
name = "anstyle-parse" name = "anstyle-parse"
@@ -220,9 +220,9 @@ dependencies = [
[[package]] [[package]]
name = "ashpd" name = "ashpd"
version = "0.13.5" version = "0.13.7"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b09507a218cf6eb4ab0659883e54880cea3984e3dbaa4989b6cda3f8f8a97a5" checksum = "313dc617cf7b7e5d58021f999756898e60bdddd64eab2bc2f67909659e3ce5f9"
dependencies = [ dependencies = [
"enumflags2", "enumflags2",
"futures-channel", "futures-channel",
@@ -238,7 +238,7 @@ dependencies = [
[[package]] [[package]]
name = "assets" name = "assets"
version = "1.0.0-beta" version = "1.0.0-beta2"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"gpui", "gpui",
@@ -535,7 +535,7 @@ checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
[[package]] [[package]]
name = "auto_update" name = "auto_update"
version = "1.0.0-beta" version = "1.0.0-beta2"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"common", "common",
@@ -914,9 +914,9 @@ dependencies = [
[[package]] [[package]]
name = "cc" name = "cc"
version = "1.2.56" version = "1.2.57"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aebf35691d1bfb0ac386a69bac2fde4dd276fb618cf8bf4f5318fe285e821bb2" checksum = "7a0dd1ca384932ff3641c8718a02769f1698e7563dc6974ffd03346116310423"
dependencies = [ dependencies = [
"find-msvc-tools", "find-msvc-tools",
"jobserver", "jobserver",
@@ -986,7 +986,7 @@ dependencies = [
[[package]] [[package]]
name = "chat" name = "chat"
version = "1.0.0-beta" version = "1.0.0-beta2"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"common", "common",
@@ -1009,7 +1009,7 @@ dependencies = [
[[package]] [[package]]
name = "chat_ui" name = "chat_ui"
version = "1.0.0-beta" version = "1.0.0-beta2"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"chat", "chat",
@@ -1200,7 +1200,7 @@ dependencies = [
[[package]] [[package]]
name = "collections" name = "collections"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#7b9afc8c454607222eaf751bbc38159ececc1f7a" source = "git+https://github.com/zed-industries/zed#cbc39669b414c2601f86ece9faffe164a33b5ad7"
dependencies = [ dependencies = [
"indexmap", "indexmap",
"rustc-hash 2.1.1", "rustc-hash 2.1.1",
@@ -1214,9 +1214,9 @@ checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
[[package]] [[package]]
name = "colorchoice" name = "colorchoice"
version = "1.0.4" 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 = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
[[package]] [[package]]
name = "combine" name = "combine"
@@ -1240,7 +1240,7 @@ dependencies = [
[[package]] [[package]]
name = "common" name = "common"
version = "1.0.0-beta" version = "1.0.0-beta2"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"bech32", "bech32",
@@ -1325,7 +1325,7 @@ dependencies = [
[[package]] [[package]]
name = "coop" name = "coop"
version = "1.0.0-beta" version = "1.0.0-beta2"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"assets", "assets",
@@ -1659,7 +1659,7 @@ dependencies = [
[[package]] [[package]]
name = "derive_refineable" name = "derive_refineable"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#7b9afc8c454607222eaf751bbc38159ececc1f7a" source = "git+https://github.com/zed-industries/zed#cbc39669b414c2601f86ece9faffe164a33b5ad7"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@@ -1668,7 +1668,7 @@ dependencies = [
[[package]] [[package]]
name = "device" name = "device"
version = "1.0.0-beta" version = "1.0.0-beta2"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"common", "common",
@@ -1857,9 +1857,9 @@ checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
[[package]] [[package]]
name = "embed-resource" name = "embed-resource"
version = "3.0.6" version = "3.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55a075fc573c64510038d7ee9abc7990635863992f83ebc52c8b433b8411a02e" checksum = "47ec73ddcf6b7f23173d5c3c5a32b5507dc0a734de7730aa14abc5d5e296bb5f"
dependencies = [ dependencies = [
"cc", "cc",
"memchr", "memchr",
@@ -1949,7 +1949,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [ dependencies = [
"libc", "libc",
"windows-sys 0.61.2", "windows-sys 0.59.0",
] ]
[[package]] [[package]]
@@ -2013,18 +2013,6 @@ dependencies = [
"zune-inflate", "zune-inflate",
] ]
[[package]]
name = "fallible-iterator"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
[[package]]
name = "fallible-streaming-iterator"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"
[[package]] [[package]]
name = "fastrand" name = "fastrand"
version = "1.9.0" version = "1.9.0"
@@ -2650,7 +2638,7 @@ dependencies = [
[[package]] [[package]]
name = "gpui" name = "gpui"
version = "0.2.2" version = "0.2.2"
source = "git+https://github.com/zed-industries/zed#7b9afc8c454607222eaf751bbc38159ececc1f7a" source = "git+https://github.com/zed-industries/zed#cbc39669b414c2601f86ece9faffe164a33b5ad7"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"async-channel 2.5.0", "async-channel 2.5.0",
@@ -2729,7 +2717,7 @@ dependencies = [
[[package]] [[package]]
name = "gpui_linux" name = "gpui_linux"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#7b9afc8c454607222eaf751bbc38159ececc1f7a" source = "git+https://github.com/zed-industries/zed#cbc39669b414c2601f86ece9faffe164a33b5ad7"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"as-raw-xcb-connection", "as-raw-xcb-connection",
@@ -2777,7 +2765,7 @@ dependencies = [
[[package]] [[package]]
name = "gpui_macos" name = "gpui_macos"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#7b9afc8c454607222eaf751bbc38159ececc1f7a" source = "git+https://github.com/zed-industries/zed#cbc39669b414c2601f86ece9faffe164a33b5ad7"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"async-task", "async-task",
@@ -2819,7 +2807,7 @@ dependencies = [
[[package]] [[package]]
name = "gpui_macros" name = "gpui_macros"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#7b9afc8c454607222eaf751bbc38159ececc1f7a" source = "git+https://github.com/zed-industries/zed#cbc39669b414c2601f86ece9faffe164a33b5ad7"
dependencies = [ dependencies = [
"heck 0.5.0", "heck 0.5.0",
"proc-macro2", "proc-macro2",
@@ -2830,7 +2818,7 @@ dependencies = [
[[package]] [[package]]
name = "gpui_platform" name = "gpui_platform"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#7b9afc8c454607222eaf751bbc38159ececc1f7a" source = "git+https://github.com/zed-industries/zed#cbc39669b414c2601f86ece9faffe164a33b5ad7"
dependencies = [ dependencies = [
"console_error_panic_hook", "console_error_panic_hook",
"gpui", "gpui",
@@ -2843,7 +2831,7 @@ dependencies = [
[[package]] [[package]]
name = "gpui_tokio" name = "gpui_tokio"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#7b9afc8c454607222eaf751bbc38159ececc1f7a" source = "git+https://github.com/zed-industries/zed#cbc39669b414c2601f86ece9faffe164a33b5ad7"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"gpui", "gpui",
@@ -2854,7 +2842,7 @@ dependencies = [
[[package]] [[package]]
name = "gpui_util" name = "gpui_util"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#7b9afc8c454607222eaf751bbc38159ececc1f7a" source = "git+https://github.com/zed-industries/zed#cbc39669b414c2601f86ece9faffe164a33b5ad7"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"log", "log",
@@ -2863,7 +2851,7 @@ dependencies = [
[[package]] [[package]]
name = "gpui_web" name = "gpui_web"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#7b9afc8c454607222eaf751bbc38159ececc1f7a" source = "git+https://github.com/zed-industries/zed#cbc39669b414c2601f86ece9faffe164a33b5ad7"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"console_error_panic_hook", "console_error_panic_hook",
@@ -2887,7 +2875,7 @@ dependencies = [
[[package]] [[package]]
name = "gpui_wgpu" name = "gpui_wgpu"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#7b9afc8c454607222eaf751bbc38159ececc1f7a" source = "git+https://github.com/zed-industries/zed#cbc39669b414c2601f86ece9faffe164a33b5ad7"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"bytemuck", "bytemuck",
@@ -2915,7 +2903,7 @@ dependencies = [
[[package]] [[package]]
name = "gpui_windows" name = "gpui_windows"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#7b9afc8c454607222eaf751bbc38159ececc1f7a" source = "git+https://github.com/zed-industries/zed#cbc39669b414c2601f86ece9faffe164a33b5ad7"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"collections", "collections",
@@ -3158,7 +3146,7 @@ dependencies = [
[[package]] [[package]]
name = "http_client" name = "http_client"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#7b9afc8c454607222eaf751bbc38159ececc1f7a" source = "git+https://github.com/zed-industries/zed#cbc39669b414c2601f86ece9faffe164a33b5ad7"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"async-compression", "async-compression",
@@ -3183,7 +3171,7 @@ dependencies = [
[[package]] [[package]]
name = "http_client_tls" name = "http_client_tls"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#7b9afc8c454607222eaf751bbc38159ececc1f7a" source = "git+https://github.com/zed-industries/zed#cbc39669b414c2601f86ece9faffe164a33b5ad7"
dependencies = [ dependencies = [
"rustls", "rustls",
"rustls-platform-verifier", "rustls-platform-verifier",
@@ -3778,17 +3766,6 @@ dependencies = [
"redox_syscall 0.7.3", "redox_syscall 0.7.3",
] ]
[[package]]
name = "libsqlite3-sys"
version = "0.36.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95b4103cffefa72eb8428cb6b47d6627161e51c2739fc5e3b734584157bc642a"
dependencies = [
"cc",
"pkg-config",
"vcpkg",
]
[[package]] [[package]]
name = "linebender_resource_handle" name = "linebender_resource_handle"
version = "0.1.1" version = "0.1.1"
@@ -4023,7 +4000,7 @@ dependencies = [
[[package]] [[package]]
name = "media" name = "media"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#7b9afc8c454607222eaf751bbc38159ececc1f7a" source = "git+https://github.com/zed-industries/zed#cbc39669b414c2601f86ece9faffe164a33b5ad7"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"bindgen", "bindgen",
@@ -4274,7 +4251,7 @@ checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8"
[[package]] [[package]]
name = "nostr" name = "nostr"
version = "0.44.1" version = "0.44.1"
source = "git+https://github.com/rust-nostr/nostr#493b230aa7308fba416989ae63625da4132cf496" source = "git+https://github.com/rust-nostr/nostr#fb0ee1d9366b05c553a0af48d813a38a7df3eb53"
dependencies = [ dependencies = [
"aes", "aes",
"base64", "base64",
@@ -4298,7 +4275,7 @@ dependencies = [
[[package]] [[package]]
name = "nostr-blossom" name = "nostr-blossom"
version = "0.44.0" version = "0.44.0"
source = "git+https://github.com/rust-nostr/nostr#493b230aa7308fba416989ae63625da4132cf496" source = "git+https://github.com/rust-nostr/nostr#fb0ee1d9366b05c553a0af48d813a38a7df3eb53"
dependencies = [ dependencies = [
"base64", "base64",
"nostr", "nostr",
@@ -4309,7 +4286,7 @@ dependencies = [
[[package]] [[package]]
name = "nostr-connect" name = "nostr-connect"
version = "0.44.0" version = "0.44.0"
source = "git+https://github.com/rust-nostr/nostr#493b230aa7308fba416989ae63625da4132cf496" source = "git+https://github.com/rust-nostr/nostr#fb0ee1d9366b05c553a0af48d813a38a7df3eb53"
dependencies = [ dependencies = [
"async-utility", "async-utility",
"futures-core", "futures-core",
@@ -4322,7 +4299,7 @@ dependencies = [
[[package]] [[package]]
name = "nostr-database" name = "nostr-database"
version = "0.44.0" version = "0.44.0"
source = "git+https://github.com/rust-nostr/nostr#493b230aa7308fba416989ae63625da4132cf496" source = "git+https://github.com/rust-nostr/nostr#fb0ee1d9366b05c553a0af48d813a38a7df3eb53"
dependencies = [ dependencies = [
"btreecap", "btreecap",
"flatbuffers", "flatbuffers",
@@ -4332,27 +4309,27 @@ dependencies = [
[[package]] [[package]]
name = "nostr-gossip" name = "nostr-gossip"
version = "0.44.0" version = "0.44.0"
source = "git+https://github.com/rust-nostr/nostr#493b230aa7308fba416989ae63625da4132cf496" source = "git+https://github.com/rust-nostr/nostr#fb0ee1d9366b05c553a0af48d813a38a7df3eb53"
dependencies = [ dependencies = [
"nostr", "nostr",
] ]
[[package]] [[package]]
name = "nostr-gossip-sqlite" name = "nostr-gossip-memory"
version = "0.44.0" version = "0.44.0"
source = "git+https://github.com/rust-nostr/nostr#493b230aa7308fba416989ae63625da4132cf496" source = "git+https://github.com/rust-nostr/nostr#fb0ee1d9366b05c553a0af48d813a38a7df3eb53"
dependencies = [ dependencies = [
"async-utility", "indexmap",
"lru",
"nostr", "nostr",
"nostr-gossip", "nostr-gossip",
"rusqlite",
"tokio", "tokio",
] ]
[[package]] [[package]]
name = "nostr-lmdb" name = "nostr-lmdb"
version = "0.44.0" version = "0.44.0"
source = "git+https://github.com/rust-nostr/nostr#493b230aa7308fba416989ae63625da4132cf496" source = "git+https://github.com/rust-nostr/nostr#fb0ee1d9366b05c553a0af48d813a38a7df3eb53"
dependencies = [ dependencies = [
"async-utility", "async-utility",
"flume 0.12.0", "flume 0.12.0",
@@ -4366,7 +4343,7 @@ dependencies = [
[[package]] [[package]]
name = "nostr-memory" name = "nostr-memory"
version = "0.44.0" version = "0.44.0"
source = "git+https://github.com/rust-nostr/nostr#493b230aa7308fba416989ae63625da4132cf496" source = "git+https://github.com/rust-nostr/nostr#fb0ee1d9366b05c553a0af48d813a38a7df3eb53"
dependencies = [ dependencies = [
"btreecap", "btreecap",
"nostr", "nostr",
@@ -4377,7 +4354,7 @@ dependencies = [
[[package]] [[package]]
name = "nostr-sdk" name = "nostr-sdk"
version = "0.44.1" version = "0.44.1"
source = "git+https://github.com/rust-nostr/nostr#493b230aa7308fba416989ae63625da4132cf496" source = "git+https://github.com/rust-nostr/nostr#fb0ee1d9366b05c553a0af48d813a38a7df3eb53"
dependencies = [ dependencies = [
"async-utility", "async-utility",
"async-wsocket", "async-wsocket",
@@ -4409,7 +4386,7 @@ version = "0.50.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
dependencies = [ dependencies = [
"windows-sys 0.61.2", "windows-sys 0.59.0",
] ]
[[package]] [[package]]
@@ -4814,7 +4791,7 @@ checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]] [[package]]
name = "perf" name = "perf"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#7b9afc8c454607222eaf751bbc38159ececc1f7a" source = "git+https://github.com/zed-industries/zed#cbc39669b414c2601f86ece9faffe164a33b5ad7"
dependencies = [ dependencies = [
"collections", "collections",
"serde", "serde",
@@ -4823,7 +4800,7 @@ dependencies = [
[[package]] [[package]]
name = "person" name = "person"
version = "1.0.0-beta" version = "1.0.0-beta2"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"common", "common",
@@ -5025,9 +5002,9 @@ checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49"
[[package]] [[package]]
name = "portable-atomic-util" name = "portable-atomic-util"
version = "0.2.5" version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a9db96d7fa8782dd8c15ce32ffe8680bbd1e978a43bf51a34d39483540495f5" checksum = "091397be61a01d4be58e7841595bd4bfedb15f1cd54977d79b8271e94ed799a3"
dependencies = [ dependencies = [
"portable-atomic", "portable-atomic",
] ]
@@ -5271,7 +5248,7 @@ dependencies = [
"once_cell", "once_cell",
"socket2", "socket2",
"tracing", "tracing",
"windows-sys 0.60.2", "windows-sys 0.59.0",
] ]
[[package]] [[package]]
@@ -5524,7 +5501,7 @@ dependencies = [
[[package]] [[package]]
name = "refineable" name = "refineable"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#7b9afc8c454607222eaf751bbc38159ececc1f7a" source = "git+https://github.com/zed-industries/zed#cbc39669b414c2601f86ece9faffe164a33b5ad7"
dependencies = [ dependencies = [
"derive_refineable", "derive_refineable",
] ]
@@ -5560,7 +5537,7 @@ checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
[[package]] [[package]]
name = "relay_auth" name = "relay_auth"
version = "1.0.0-beta" version = "1.0.0-beta2"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"common", "common",
@@ -5623,7 +5600,7 @@ dependencies = [
[[package]] [[package]]
name = "reqwest_client" name = "reqwest_client"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#7b9afc8c454607222eaf751bbc38159ececc1f7a" source = "git+https://github.com/zed-industries/zed#cbc39669b414c2601f86ece9faffe164a33b5ad7"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"bytes", "bytes",
@@ -5678,7 +5655,7 @@ dependencies = [
[[package]] [[package]]
name = "rope" name = "rope"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#7b9afc8c454607222eaf751bbc38159ececc1f7a" source = "git+https://github.com/zed-industries/zed#cbc39669b414c2601f86ece9faffe164a33b5ad7"
dependencies = [ dependencies = [
"arrayvec", "arrayvec",
"log", "log",
@@ -5696,30 +5673,6 @@ version = "0.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"
[[package]]
name = "rsqlite-vfs"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a8a1f2315036ef6b1fbacd1972e8ee7688030b0a2121edfc2a6550febd41574d"
dependencies = [
"hashbrown 0.16.1",
"thiserror 2.0.18",
]
[[package]]
name = "rusqlite"
version = "0.38.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1c93dd1c9683b438c392c492109cb702b8090b2bfc8fed6f6e4eb4523f17af3"
dependencies = [
"bitflags 2.11.0",
"fallible-iterator",
"fallible-streaming-iterator",
"libsqlite3-sys",
"smallvec",
"sqlite-wasm-rs",
]
[[package]] [[package]]
name = "rust-embed" name = "rust-embed"
version = "8.11.0" version = "8.11.0"
@@ -5815,7 +5768,7 @@ dependencies = [
"errno", "errno",
"libc", "libc",
"linux-raw-sys 0.12.1", "linux-raw-sys 0.12.1",
"windows-sys 0.61.2", "windows-sys 0.59.0",
] ]
[[package]] [[package]]
@@ -5964,7 +5917,7 @@ dependencies = [
[[package]] [[package]]
name = "scheduler" name = "scheduler"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#7b9afc8c454607222eaf751bbc38159ececc1f7a" source = "git+https://github.com/zed-industries/zed#cbc39669b414c2601f86ece9faffe164a33b5ad7"
dependencies = [ dependencies = [
"async-task", "async-task",
"backtrace", "backtrace",
@@ -6243,7 +6196,7 @@ dependencies = [
[[package]] [[package]]
name = "settings" name = "settings"
version = "1.0.0-beta" version = "1.0.0-beta2"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"common", "common",
@@ -6458,18 +6411,6 @@ dependencies = [
"bitflags 2.11.0", "bitflags 2.11.0",
] ]
[[package]]
name = "sqlite-wasm-rs"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f4206ed3a67690b9c29b77d728f6acc3ce78f16bf846d83c94f76400320181b"
dependencies = [
"cc",
"js-sys",
"rsqlite-vfs",
"wasm-bindgen",
]
[[package]] [[package]]
name = "stable_deref_trait" name = "stable_deref_trait"
version = "1.2.1" version = "1.2.1"
@@ -6512,7 +6453,7 @@ dependencies = [
[[package]] [[package]]
name = "state" name = "state"
version = "1.0.0-beta" version = "1.0.0-beta2"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"common", "common",
@@ -6524,7 +6465,7 @@ dependencies = [
"nostr", "nostr",
"nostr-blossom", "nostr-blossom",
"nostr-connect", "nostr-connect",
"nostr-gossip-sqlite", "nostr-gossip-memory",
"nostr-lmdb", "nostr-lmdb",
"nostr-memory", "nostr-memory",
"nostr-sdk", "nostr-sdk",
@@ -6588,7 +6529,7 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]] [[package]]
name = "sum_tree" name = "sum_tree"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#7b9afc8c454607222eaf751bbc38159ececc1f7a" source = "git+https://github.com/zed-industries/zed#cbc39669b414c2601f86ece9faffe164a33b5ad7"
dependencies = [ dependencies = [
"arrayvec", "arrayvec",
"log", "log",
@@ -6826,7 +6767,7 @@ dependencies = [
"getrandom 0.4.2", "getrandom 0.4.2",
"once_cell", "once_cell",
"rustix 1.1.4", "rustix 1.1.4",
"windows-sys 0.61.2", "windows-sys 0.59.0",
] ]
[[package]] [[package]]
@@ -6851,7 +6792,7 @@ dependencies = [
[[package]] [[package]]
name = "theme" name = "theme"
version = "1.0.0-beta" version = "1.0.0-beta2"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"gpui", "gpui",
@@ -6973,9 +6914,9 @@ dependencies = [
[[package]] [[package]]
name = "tinyvec" name = "tinyvec"
version = "1.10.0" version = "1.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bfa5fdc3bce6191a1dbc8c02d5c8bffcf557bafa17c124c5264a458f1b0613fa" checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3"
dependencies = [ dependencies = [
"tinyvec_macros", "tinyvec_macros",
] ]
@@ -6988,7 +6929,7 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]] [[package]]
name = "title_bar" name = "title_bar"
version = "1.0.0-beta" version = "1.0.0-beta2"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"common", "common",
@@ -7284,9 +7225,9 @@ dependencies = [
[[package]] [[package]]
name = "tracing-subscriber" name = "tracing-subscriber"
version = "0.3.22" version = "0.3.23"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f30143827ddab0d256fd843b7a66d164e9f271cfa0dde49142c5ca0ca291f1e" checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319"
dependencies = [ dependencies = [
"matchers", "matchers",
"nu-ansi-term", "nu-ansi-term",
@@ -7348,9 +7289,9 @@ checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb"
[[package]] [[package]]
name = "uds_windows" name = "uds_windows"
version = "1.2.0" version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "51b70b87d15e91f553711b40df3048faf27a7a04e01e0ddc0cf9309f0af7c2ca" checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"
dependencies = [ dependencies = [
"memoffset", "memoffset",
"tempfile", "tempfile",
@@ -7359,7 +7300,7 @@ dependencies = [
[[package]] [[package]]
name = "ui" name = "ui"
version = "1.0.0-beta" version = "1.0.0-beta2"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"common", "common",
@@ -7550,7 +7491,7 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]] [[package]]
name = "util" name = "util"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#7b9afc8c454607222eaf751bbc38159ececc1f7a" source = "git+https://github.com/zed-industries/zed#cbc39669b414c2601f86ece9faffe164a33b5ad7"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"async-fs", "async-fs",
@@ -7589,7 +7530,7 @@ dependencies = [
[[package]] [[package]]
name = "util_macros" name = "util_macros"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#7b9afc8c454607222eaf751bbc38159ececc1f7a" source = "git+https://github.com/zed-industries/zed#cbc39669b414c2601f86ece9faffe164a33b5ad7"
dependencies = [ dependencies = [
"perf", "perf",
"quote", "quote",
@@ -7662,12 +7603,6 @@ dependencies = [
"sval_serde", "sval_serde",
] ]
[[package]]
name = "vcpkg"
version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
[[package]] [[package]]
name = "version_check" name = "version_check"
version = "0.9.5" version = "0.9.5"
@@ -8231,7 +8166,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [ dependencies = [
"windows-sys 0.61.2", "windows-sys 0.48.0",
] ]
[[package]] [[package]]
@@ -8554,15 +8489,6 @@ dependencies = [
"windows-targets 0.52.6", "windows-targets 0.52.6",
] ]
[[package]]
name = "windows-sys"
version = "0.60.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"
dependencies = [
"windows-targets 0.53.5",
]
[[package]] [[package]]
name = "windows-sys" name = "windows-sys"
version = "0.61.2" version = "0.61.2"
@@ -9391,7 +9317,7 @@ dependencies = [
[[package]] [[package]]
name = "zlog" name = "zlog"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#7b9afc8c454607222eaf751bbc38159ececc1f7a" source = "git+https://github.com/zed-industries/zed#cbc39669b414c2601f86ece9faffe164a33b5ad7"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"chrono", "chrono",
@@ -9408,7 +9334,7 @@ checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
[[package]] [[package]]
name = "ztracing" name = "ztracing"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#7b9afc8c454607222eaf751bbc38159ececc1f7a" source = "git+https://github.com/zed-industries/zed#cbc39669b414c2601f86ece9faffe164a33b5ad7"
dependencies = [ dependencies = [
"tracing", "tracing",
"tracing-subscriber", "tracing-subscriber",
@@ -9419,7 +9345,7 @@ dependencies = [
[[package]] [[package]]
name = "ztracing_macro" name = "ztracing_macro"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/zed-industries/zed#7b9afc8c454607222eaf751bbc38159ececc1f7a" source = "git+https://github.com/zed-industries/zed#cbc39669b414c2601f86ece9faffe164a33b5ad7"
[[package]] [[package]]
name = "zune-core" name = "zune-core"

View File

@@ -4,8 +4,8 @@ members = ["crates/*"]
default-members = ["crates/coop"] default-members = ["crates/coop"]
[workspace.package] [workspace.package]
version = "1.0.0-beta1" version = "1.0.0-beta2"
edition = "2021" edition = "2024"
publish = false publish = false
[workspace.dependencies] [workspace.dependencies]
@@ -23,7 +23,7 @@ nostr-lmdb = { git = "https://github.com/rust-nostr/nostr" }
nostr-memory = { git = "https://github.com/rust-nostr/nostr" } nostr-memory = { git = "https://github.com/rust-nostr/nostr" }
nostr-connect = { git = "https://github.com/rust-nostr/nostr" } nostr-connect = { git = "https://github.com/rust-nostr/nostr" }
nostr-blossom = { git = "https://github.com/rust-nostr/nostr" } nostr-blossom = { git = "https://github.com/rust-nostr/nostr" }
nostr-gossip-sqlite = { git = "https://github.com/rust-nostr/nostr" } nostr-gossip-memory = { git = "https://github.com/rust-nostr/nostr" }
nostr-sdk = { git = "https://github.com/rust-nostr/nostr" } nostr-sdk = { git = "https://github.com/rust-nostr/nostr" }
nostr = { git = "https://github.com/rust-nostr/nostr", features = [ "nip96", "nip59", "nip49", "nip44" ] } nostr = { git = "https://github.com/rust-nostr/nostr", features = [ "nip96", "nip59", "nip49", "nip44" ] }

View File

@@ -15,7 +15,8 @@ use gpui::{
}; };
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;
use smallvec::{SmallVec, smallvec}; use smallvec::{SmallVec, smallvec};
use state::{DEVICE_GIFTWRAP, NostrRegistry, StateEvent, TIMEOUT, USER_GIFTWRAP}; use smol::lock::RwLock;
use state::{CoopSigner, DEVICE_GIFTWRAP, NostrRegistry, StateEvent, TIMEOUT, USER_GIFTWRAP};
mod message; mod message;
mod room; mod room;
@@ -60,9 +61,12 @@ enum Signal {
/// Chat Registry /// Chat Registry
#[derive(Debug)] #[derive(Debug)]
pub struct ChatRegistry { pub struct ChatRegistry {
/// Collection of all chat rooms /// Chat rooms
rooms: Vec<Entity<Room>>, rooms: Vec<Entity<Room>>,
/// Tracking events seen on which relays in the current session
seens: Arc<RwLock<HashMap<EventId, HashSet<RelayUrl>>>>,
/// Tracking the status of unwrapping gift wrap events. /// Tracking the status of unwrapping gift wrap events.
tracking_flag: Arc<AtomicBool>, tracking_flag: Arc<AtomicBool>,
@@ -101,12 +105,17 @@ impl ChatRegistry {
subscriptions.push( subscriptions.push(
// Subscribe to the signer event // Subscribe to the signer event
cx.subscribe(&nostr, |this, _state, event, cx| { cx.subscribe(&nostr, |this, _state, event, cx| {
if let StateEvent::SignerSet = event { match event {
this.reset(cx); StateEvent::SignerSet => {
this.get_rooms(cx); this.reset(cx);
this.get_contact_list(cx); this.get_rooms(cx);
this.get_messages(cx) }
} StateEvent::RelayConnected => {
this.get_contact_list(cx);
this.get_messages(cx)
}
_ => {}
};
}), }),
); );
@@ -119,6 +128,7 @@ impl ChatRegistry {
Self { Self {
rooms: vec![], rooms: vec![],
seens: Arc::new(RwLock::new(HashMap::default())),
tracking_flag: Arc::new(AtomicBool::new(false)), tracking_flag: Arc::new(AtomicBool::new(false)),
signal_rx: rx, signal_rx: rx,
signal_tx: tx, signal_tx: tx,
@@ -133,6 +143,7 @@ impl ChatRegistry {
let client = nostr.read(cx).client(); let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer(); let signer = nostr.read(cx).signer();
let status = self.tracking_flag.clone(); let status = self.tracking_flag.clone();
let seens = self.seens.clone();
let initialized_at = Timestamp::now(); let initialized_at = Timestamp::now();
let sub_id1 = SubscriptionId::new(DEVICE_GIFTWRAP); let sub_id1 = SubscriptionId::new(DEVICE_GIFTWRAP);
@@ -143,52 +154,52 @@ impl ChatRegistry {
let rx = self.signal_rx.clone(); let rx = self.signal_rx.clone();
self.tasks.push(cx.background_spawn(async move { self.tasks.push(cx.background_spawn(async move {
let device_signer = signer.get_encryption_signer().await;
let mut notifications = client.notifications(); let mut notifications = client.notifications();
let mut processed_events = HashSet::new(); let mut processed_events = HashSet::new();
while let Some(notification) = notifications.next().await { while let Some(notification) = notifications.next().await {
let ClientNotification::Message { message, .. } = notification else { let ClientNotification::Message { message, relay_url } = notification else {
// Skip non-message notifications // Skip non-message notifications
continue; continue;
}; };
match message { match message {
RelayMessage::Event { event, .. } => { RelayMessage::Event { event, .. } => {
// Keep track of which relays have seen this event
{
let mut seens = seens.write().await;
seens.entry(event.id).or_default().insert(relay_url);
}
// De-duplicate events by their ID
if !processed_events.insert(event.id) { if !processed_events.insert(event.id) {
// Skip if the event has already been processed
continue; continue;
} }
// Skip non-gift wrap events
if event.kind != Kind::GiftWrap { if event.kind != Kind::GiftWrap {
// Skip non-gift wrap events
continue; continue;
} }
// Extract the rumor from the gift wrap event // Extract the rumor from the gift wrap event
match extract_rumor(&client, &device_signer, event.as_ref()).await { match extract_rumor(&client, &signer, event.as_ref()).await {
Ok(rumor) => { Ok(rumor) => {
if rumor.tags.is_empty() { if rumor.tags.is_empty() {
let error: SharedString = let error: SharedString = "No room for message".into();
"Message doesn't belong to any rooms".into();
tx.send_async(Signal::Error(error)).await?; tx.send_async(Signal::Error(error)).await?;
} }
match rumor.created_at >= initialized_at { if rumor.created_at >= initialized_at {
true => { let new_message = NewMessage::new(event.id, rumor);
let new_message = NewMessage::new(event.id, rumor); let signal = Signal::Message(new_message);
let signal = Signal::Message(new_message);
tx.send_async(signal).await?; tx.send_async(signal).await?;
} } else {
false => { status.store(true, Ordering::Release);
status.store(true, Ordering::Release);
}
} }
} }
Err(e) => { Err(e) => {
let error: SharedString = let error: SharedString = format!("Failed to unwrap: {e}").into();
format!("Failed to unwrap the gift wrap event: {e}").into();
tx.send_async(Signal::Error(error)).await?; tx.send_async(Signal::Error(error)).await?;
} }
} }
@@ -325,6 +336,7 @@ impl ChatRegistry {
while let Some((_url, res)) = stream.next().await { while let Some((_url, res)) = stream.next().await {
if let Ok(event) = res { if let Ok(event) = res {
log::debug!("Got event: {:?}", event);
let urls: Vec<RelayUrl> = nip17::extract_owned_relay_list(event).collect(); let urls: Vec<RelayUrl> = nip17::extract_owned_relay_list(event).collect();
return Ok(urls); return Ok(urls);
} }
@@ -399,6 +411,24 @@ impl ChatRegistry {
.count() .count()
} }
/// Count the number of messages seen by a given relay.
pub fn count_messages(&self, relay_url: &RelayUrl) -> usize {
self.seens
.read_blocking()
.values()
.filter(|seen| seen.contains(relay_url))
.count()
}
/// Get the relays that have seen a given message.
pub fn seen_on(&self, id: &EventId) -> HashSet<RelayUrl> {
self.seens
.read_blocking()
.get(id)
.cloned()
.unwrap_or_default()
}
/// Add a new room to the start of list. /// Add a new room to the start of list.
pub fn add_room<I>(&mut self, room: I, cx: &mut Context<Self>) pub fn add_room<I>(&mut self, room: I, cx: &mut Context<Self>)
where where
@@ -570,10 +600,10 @@ impl ChatRegistry {
// Process each event and group by room hash // Process each event and group by room hash
for raw in events.into_iter() { for raw in events.into_iter() {
if let Ok(rumor) = UnsignedEvent::from_json(&raw.content) { if let Ok(rumor) = UnsignedEvent::from_json(&raw.content)
if rumor.tags.public_keys().peekable().peek().is_some() { && rumor.tags.public_keys().peekable().peek().is_some()
grouped.entry(rumor.uniq_id()).or_default().push(rumor); {
} grouped.entry(rumor.uniq_id()).or_default().push(rumor);
} }
} }
@@ -619,12 +649,11 @@ impl ChatRegistry {
match self.rooms.iter().find(|e| e.read(cx).id == message.room) { match self.rooms.iter().find(|e| e.read(cx).id == message.room) {
Some(room) => { Some(room) => {
room.update(cx, |this, cx| { room.update(cx, |this, cx| {
if this.kind == RoomKind::Request { if this.kind == RoomKind::Request
if let Some(public_key) = signer.public_key() { && let Some(public_key) = signer.public_key()
if message.rumor.pubkey == public_key { && message.rumor.pubkey == public_key
this.set_ongoing(cx); {
} this.set_ongoing(cx);
}
} }
this.push_message(message, cx); this.push_message(message, cx);
}); });
@@ -652,7 +681,7 @@ impl ChatRegistry {
/// Unwraps a gift-wrapped event and processes its contents. /// Unwraps a gift-wrapped event and processes its contents.
async fn extract_rumor( async fn extract_rumor(
client: &Client, client: &Client,
device_signer: &Option<Arc<dyn NostrSigner>>, signer: &Arc<CoopSigner>,
gift_wrap: &Event, gift_wrap: &Event,
) -> Result<UnsignedEvent, Error> { ) -> Result<UnsignedEvent, Error> {
// Try to get cached rumor first // Try to get cached rumor first
@@ -661,7 +690,7 @@ async fn extract_rumor(
} }
// Try to unwrap with the available signer // Try to unwrap with the available signer
let unwrapped = try_unwrap(client, device_signer, gift_wrap).await?; let unwrapped = try_unwrap(signer, gift_wrap).await?;
let mut rumor = unwrapped.rumor; let mut rumor = unwrapped.rumor;
// Generate event id for the rumor if it doesn't have one // Generate event id for the rumor if it doesn't have one
@@ -676,30 +705,27 @@ async fn extract_rumor(
} }
/// Helper method to try unwrapping with different signers /// Helper method to try unwrapping with different signers
async fn try_unwrap( async fn try_unwrap(signer: &Arc<CoopSigner>, gift_wrap: &Event) -> Result<UnwrappedGift, Error> {
client: &Client,
device_signer: &Option<Arc<dyn NostrSigner>>,
gift_wrap: &Event,
) -> Result<UnwrappedGift, Error> {
// Try with the device signer first // Try with the device signer first
if let Some(signer) = device_signer { if let Some(signer) = signer.get_encryption_signer().await {
if let Ok(unwrapped) = try_unwrap_with(gift_wrap, signer).await { log::info!("trying with encryption key");
if let Ok(unwrapped) = try_unwrap_with(gift_wrap, &signer).await {
return Ok(unwrapped); return Ok(unwrapped);
}; }
}; }
// Try with the user's signer // Fallback to the user's signer
let user_signer = client.signer().context("Signer not found")?; let user_signer = signer.get().await;
let unwrapped = try_unwrap_with(gift_wrap, user_signer).await?; let unwrapped = try_unwrap_with(gift_wrap, &user_signer).await?;
Ok(unwrapped) Ok(unwrapped)
} }
/// Attempts to unwrap a gift wrap event with a given signer. /// Attempts to unwrap a gift wrap event with a given signer.
async fn try_unwrap_with( async fn try_unwrap_with<T>(gift_wrap: &Event, signer: &T) -> Result<UnwrappedGift, Error>
gift_wrap: &Event, where
signer: &Arc<dyn NostrSigner>, T: NostrSigner + 'static,
) -> Result<UnwrappedGift, Error> { {
// Get the sealed event // Get the sealed event
let seal = signer let seal = signer
.nip44_decrypt(&gift_wrap.pubkey, &gift_wrap.content) .nip44_decrypt(&gift_wrap.pubkey, &gift_wrap.content)

View File

@@ -2,7 +2,7 @@ use std::cmp::Ordering;
use std::hash::{Hash, Hasher}; use std::hash::{Hash, Hasher};
use std::time::Duration; use std::time::Duration;
use anyhow::Error; use anyhow::{Error, anyhow};
use common::EventUtils; use common::EventUtils;
use gpui::{App, AppContext, Context, EventEmitter, SharedString, Task}; use gpui::{App, AppContext, Context, EventEmitter, SharedString, Task};
use itertools::Itertools; use itertools::Itertools;
@@ -354,17 +354,7 @@ impl Room {
pub fn connect(&self, cx: &App) -> Task<Result<(), Error>> { pub fn connect(&self, cx: &App) -> Task<Result<(), Error>> {
let nostr = NostrRegistry::global(cx); let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client(); let client = nostr.read(cx).client();
let members = self.members();
let signer = nostr.read(cx).signer();
let sender = signer.public_key();
// Get all members, excluding the sender
let members: Vec<PublicKey> = self
.members
.iter()
.filter(|public_key| Some(**public_key) != sender)
.copied()
.collect();
cx.background_spawn(async move { cx.background_spawn(async move {
let opts = SubscribeAutoCloseOptions::default() let opts = SubscribeAutoCloseOptions::default()
@@ -515,45 +505,46 @@ impl Room {
// Handle encryption signer requirements // Handle encryption signer requirements
if signer_kind.encryption() { if signer_kind.encryption() {
// Receiver didn't set up a decoupled encryption key
if announcement.is_none() { if announcement.is_none() {
reports.push(SendReport::new(public_key).error(NO_DEKEY)); reports.push(SendReport::new(public_key).error(NO_DEKEY));
continue; continue;
} }
// Sender didn't set up a decoupled encryption key
if encryption_signer.is_none() { if encryption_signer.is_none() {
reports.push(SendReport::new(sender.public_key()).error(USER_NO_DEKEY)); reports.push(SendReport::new(sender.public_key()).error(USER_NO_DEKEY));
continue; continue;
} }
} }
// Determine receiver and signer // Determine the signer to use
let (receiver, signer) = match signer_kind { let signer = match signer_kind {
SignerKind::Auto => { SignerKind::Auto => {
if let Some(announcement) = announcement { if announcement.is_some()
if let Some(enc_signer) = encryption_signer.as_ref() { && let Some(encryption_signer) = encryption_signer.clone()
(announcement.public_key(), enc_signer.clone()) {
} else { // Safe to unwrap due to earlier checks
(member.public_key(), user_signer.clone()) encryption_signer
}
} else { } else {
(member.public_key(), user_signer.clone()) user_signer.clone()
} }
} }
SignerKind::Encryption => { SignerKind::Encryption => {
// Safe to unwrap due to earlier checks // Safe to unwrap due to earlier checks
( encryption_signer.as_ref().unwrap().clone()
announcement.unwrap().public_key(),
encryption_signer.as_ref().unwrap().clone(),
)
} }
SignerKind::User => (member.public_key(), user_signer.clone()), SignerKind::User => user_signer.clone(),
}; };
match send_gift_wrap(&client, &signer, &receiver, &rumor, public_key).await { // Send the gift wrap event and collect the report
Ok((report, _)) => { match send_gift_wrap(&client, &signer, &member, &rumor, signer_kind).await {
Ok(report) => {
reports.push(report); reports.push(report);
sents += 1; sents += 1;
} }
Err(report) => { Err(error) => {
let report = SendReport::new(public_key).error(error.to_string());
reports.push(report); reports.push(report);
} }
} }
@@ -562,11 +553,32 @@ impl Room {
// Send backup to current user if needed // Send backup to current user if needed
if backup && sents >= 1 { if backup && sents >= 1 {
let public_key = sender.public_key(); let public_key = sender.public_key();
let signer = encryption_signer.as_ref().unwrap_or(&user_signer);
match send_gift_wrap(&client, signer, &public_key, &rumor, public_key).await { // Determine the signer to use
Ok((report, _)) => reports.push(report), let signer = match signer_kind {
Err(report) => reports.push(report), SignerKind::Auto => {
if sender.announcement().is_some()
&& let Some(encryption_signer) = encryption_signer.clone()
{
// Safe to unwrap due to earlier checks
encryption_signer
} else {
user_signer.clone()
}
}
SignerKind::Encryption => {
// Safe to unwrap due to earlier checks
encryption_signer.as_ref().unwrap().clone()
}
SignerKind::User => user_signer.clone(),
};
match send_gift_wrap(&client, &signer, &sender, &rumor, signer_kind).await {
Ok(report) => reports.push(report),
Err(error) => {
let report = SendReport::new(public_key).error(error.to_string());
reports.push(report);
}
} }
} }
@@ -579,30 +591,50 @@ impl Room {
async fn send_gift_wrap<T>( async fn send_gift_wrap<T>(
client: &Client, client: &Client,
signer: &T, signer: &T,
receiver: &PublicKey, receiver: &Person,
rumor: &UnsignedEvent, rumor: &UnsignedEvent,
public_key: PublicKey, config: &SignerKind,
) -> Result<(SendReport, bool), SendReport> ) -> Result<SendReport, Error>
where where
T: NostrSigner + 'static, T: NostrSigner + 'static,
{ {
match EventBuilder::gift_wrap(signer, receiver, rumor.clone(), []).await { let mut extra_tags = vec![];
Ok(event) => {
match client // Determine the receiver public key based on the config
.send_event(&event) let receiver = match config {
.to_nip17() SignerKind::Auto => {
.ack_policy(AckPolicy::none()) if let Some(announcement) = receiver.announcement().as_ref() {
.await extra_tags.push(Tag::public_key(receiver.public_key()));
{ announcement.public_key()
Ok(output) => Ok(( } else {
SendReport::new(public_key) receiver.public_key()
.gift_wrap_id(event.id)
.output(output),
true,
)),
Err(e) => Err(SendReport::new(public_key).error(e.to_string())),
} }
} }
Err(e) => Err(SendReport::new(public_key).error(e.to_string())), SignerKind::Encryption => {
} if let Some(announcement) = receiver.announcement().as_ref() {
extra_tags.push(Tag::public_key(receiver.public_key()));
announcement.public_key()
} else {
return Err(anyhow!("User has no encryption announcement"));
}
}
SignerKind::User => receiver.public_key(),
};
// Construct the gift wrap event
let event = EventBuilder::gift_wrap(signer, &receiver, rumor.clone(), extra_tags).await?;
// Send the gift wrap event and collect the report
let report = client
.send_event(&event)
.to_nip17()
.ack_policy(AckPolicy::none())
.await
.map(|output| {
SendReport::new(receiver)
.gift_wrap_id(event.id)
.output(output)
})?;
Ok(report)
} }

View File

@@ -10,7 +10,6 @@ pub enum Command {
ChangeSubject(String), ChangeSubject(String),
ChangeSigner(SignerKind), ChangeSigner(SignerKind),
ToggleBackup, ToggleBackup,
Subject,
Copy(PublicKey), Copy(PublicKey),
Relays(PublicKey), Relays(PublicKey),
Njump(PublicKey), Njump(PublicKey),

View File

@@ -154,6 +154,7 @@ impl ChatPanel {
// Define all functions that will run after the current cycle // Define all functions that will run after the current cycle
cx.defer_in(window, |this, window, cx| { cx.defer_in(window, |this, window, cx| {
this.connect(cx);
this.handle_notifications(cx); this.handle_notifications(cx);
this.subscribe_room_events(window, cx); this.subscribe_room_events(window, cx);
this.get_messages(window, cx); this.get_messages(window, cx);
@@ -179,6 +180,14 @@ impl ChatPanel {
} }
} }
/// Get messaging relays and announcement for each member
fn connect(&mut self, cx: &mut Context<Self>) {
if let Some(room) = self.room.upgrade() {
let task = room.read(cx).connect(cx);
self.tasks.push(task);
}
}
/// Handle nostr notifications /// Handle nostr notifications
fn handle_notifications(&mut self, cx: &mut Context<Self>) { fn handle_notifications(&mut self, cx: &mut Context<Self>) {
let nostr = NostrRegistry::global(cx); let nostr = NostrRegistry::global(cx);
@@ -247,11 +256,13 @@ impl ChatPanel {
})); }));
} }
/// Subscribe to room events
fn subscribe_room_events(&mut self, window: &mut Window, cx: &mut Context<Self>) { fn subscribe_room_events(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if let Some(room) = self.room.upgrade() { if let Some(room) = self.room.upgrade() {
self.subscriptions.push( self.subscriptions.push(cx.subscribe_in(
// Subscribe to room events &room,
cx.subscribe_in(&room, window, move |this, _room, event, window, cx| { window,
move |this, _room, event, window, cx| {
match event { match event {
RoomEvent::Incoming(message) => { RoomEvent::Incoming(message) => {
this.insert_message(message, false, cx); this.insert_message(message, false, cx);
@@ -260,8 +271,8 @@ impl ChatPanel {
this.get_messages(window, cx); this.get_messages(window, cx);
} }
}; };
}), },
); ));
} }
} }
@@ -368,9 +379,13 @@ impl ChatPanel {
/// Send message in the background and wait for the response /// Send message in the background and wait for the response
fn send_and_wait(&mut self, rumor: UnsignedEvent, window: &mut Window, cx: &mut Context<Self>) { fn send_and_wait(&mut self, rumor: UnsignedEvent, window: &mut Window, cx: &mut Context<Self>) {
let sent_ids = self.sent_ids.clone(); let sent_ids = self.sent_ids.clone();
// This can't fail, because we already ensured that the ID is set // This can't fail, because we already ensured that the ID is set
let id = rumor.id.unwrap(); let id = rumor.id.unwrap();
// Add empty reports
self.insert_reports(id, vec![], cx);
// Upgrade room reference // Upgrade room reference
let Some(room) = self.room.upgrade() else { let Some(room) = self.room.upgrade() else {
return; return;
@@ -419,7 +434,7 @@ impl ChatPanel {
/// Insert reports /// Insert reports
fn insert_reports(&mut self, id: EventId, reports: Vec<SendReport>, cx: &mut Context<Self>) { fn insert_reports(&mut self, id: EventId, reports: Vec<SendReport>, cx: &mut Context<Self>) {
self.reports_by_id.update(cx, |this, cx| { self.reports_by_id.update(cx, |this, cx| {
this.insert(id, reports); this.entry(id).or_default().extend(reports);
cx.notify(); cx.notify();
}); });
} }
@@ -454,14 +469,6 @@ impl ChatPanel {
} }
} }
/// Check if a message is pending
fn sent_pending(&self, id: &EventId, cx: &App) -> bool {
self.reports_by_id
.read(cx)
.get(id)
.is_some_and(|reports| reports.iter().all(|r| r.pending()))
}
/// Check if a message has any reports /// Check if a message has any reports
fn has_reports(&self, id: &EventId, cx: &App) -> bool { fn has_reports(&self, id: &EventId, cx: &App) -> bool {
self.reports_by_id.read(cx).get(id).is_some() self.reports_by_id.read(cx).get(id).is_some()
@@ -475,10 +482,10 @@ impl ChatPanel {
/// Get a message by its ID /// Get a message by its ID
fn message(&self, id: &EventId) -> Option<&RenderedMessage> { fn message(&self, id: &EventId) -> Option<&RenderedMessage> {
self.messages.iter().find_map(|msg| { self.messages.iter().find_map(|msg| {
if let Message::User(rendered) = msg { if let Message::User(rendered) = msg
if &rendered.id == id { && &rendered.id == id
return Some(rendered); {
} return Some(rendered);
} }
None None
}) })
@@ -645,9 +652,6 @@ impl ChatPanel {
); );
} }
} }
Command::Subject => {
self.open_subject(window, cx);
}
Command::Copy(public_key) => { Command::Copy(public_key) => {
self.copy_author(public_key, cx); self.copy_author(public_key, cx);
} }
@@ -660,47 +664,6 @@ impl ChatPanel {
} }
} }
fn open_subject(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let subject_input = self.subject_input.clone();
window.open_modal(cx, move |this, _window, cx| {
let subject = subject_input.read(cx).value();
this.title("Change subject")
.show_close(true)
.confirm()
.child(
v_flex()
.gap_2()
.child(
v_flex()
.gap_1p5()
.child(
div()
.text_sm()
.text_color(cx.theme().text_muted)
.child(SharedString::from("Subject:")),
)
.child(TextInput::new(&subject_input).small()),
)
.child(
div()
.italic()
.text_xs()
.text_color(cx.theme().text_placeholder)
.child(SharedString::from(
"Subject will be updated when you send a new message.",
)),
),
)
.on_ok(move |_ev, window, cx| {
window
.dispatch_action(Box::new(Command::ChangeSubject(subject.to_string())), cx);
true
})
});
}
fn open_relays(&mut self, public_key: &PublicKey, window: &mut Window, cx: &mut Context<Self>) { fn open_relays(&mut self, public_key: &PublicKey, window: &mut Window, cx: &mut Context<Self>) {
let profile = self.profile(public_key, cx); let profile = self.profile(public_key, cx);
@@ -835,8 +798,6 @@ impl ChatPanel {
let replies = message.replies_to.as_slice(); let replies = message.replies_to.as_slice();
let has_replies = !replies.is_empty(); let has_replies = !replies.is_empty();
let sent_pending = self.sent_pending(&id, cx);
let has_reports = self.has_reports(&id, cx); let has_reports = self.has_reports(&id, cx);
// Hide avatar setting // Hide avatar setting
@@ -884,9 +845,6 @@ impl ChatPanel {
.child(author.name()), .child(author.name()),
) )
.child(message.created_at.to_human_time()) .child(message.created_at.to_human_time())
.when(sent_pending, |this| {
this.child(SharedString::from("• Sending..."))
})
.when(has_reports, |this| { .when(has_reports, |this| {
this.child(deferred(self.render_sent_reports(&id, cx))) this.child(deferred(self.render_sent_reports(&id, cx)))
}), }),
@@ -970,20 +928,26 @@ impl ChatPanel {
fn render_sent_reports(&self, id: &EventId, cx: &App) -> impl IntoElement { fn render_sent_reports(&self, id: &EventId, cx: &App) -> impl IntoElement {
let reports = self.sent_reports(id, cx); let reports = self.sent_reports(id, cx);
let pending = reports
.as_ref()
.is_some_and(|reports| reports.is_empty() || reports.iter().any(|r| r.pending()));
let success = reports let success = reports
.as_ref() .as_ref()
.is_some_and(|reports| reports.iter().any(|r| r.success())); .is_some_and(|reports| !reports.is_empty() && reports.iter().any(|r| r.success()));
let failed = reports let failed = reports
.as_ref() .as_ref()
.is_some_and(|reports| reports.iter().all(|r| r.failed())); .is_some_and(|reports| !reports.is_empty() && reports.iter().all(|r| r.failed()));
let label = if success { let label = if success {
SharedString::from("• Sent") SharedString::from("• Sent")
} else if failed { } else if failed {
SharedString::from("Failed") SharedString::from("Error")
} else { } else if pending {
SharedString::from("• Sending...") SharedString::from("• Sending...")
} else {
SharedString::from("• Unknown")
}; };
div() div()
@@ -991,22 +955,24 @@ impl ChatPanel {
.child(label) .child(label)
.when(failed, |this| this.text_color(cx.theme().text_danger)) .when(failed, |this| this.text_color(cx.theme().text_danger))
.when_some(reports, |this, reports| { .when_some(reports, |this, reports| {
this.on_click(move |_e, window, cx| { this.when(!pending, |this| {
let reports = reports.clone(); this.on_click(move |_e, window, cx| {
let reports = reports.clone();
window.open_modal(cx, move |this, _window, cx| { window.open_modal(cx, move |this, _window, cx| {
this.title(SharedString::from("Sent Reports")) this.title(SharedString::from("Sent Reports"))
.show_close(true) .show_close(true)
.child(v_flex().gap_4().children({ .child(v_flex().gap_4().children({
let mut items = Vec::with_capacity(reports.len()); let mut items = Vec::with_capacity(reports.len());
for report in reports.iter() { for report in reports.iter() {
items.push(Self::render_report(report, cx)) items.push(Self::render_report(report, cx))
} }
items items
})) }))
}); });
})
}) })
}) })
} }

View File

@@ -7,6 +7,13 @@ pub fn home_dir() -> &'static PathBuf {
HOME_DIR.get_or_init(|| dirs::home_dir().expect("failed to determine home directory")) HOME_DIR.get_or_init(|| dirs::home_dir().expect("failed to determine home directory"))
} }
/// Returns the path to the user's download directory.
pub fn download_dir() -> &'static PathBuf {
static DOWNLOAD_DIR: OnceLock<PathBuf> = OnceLock::new();
DOWNLOAD_DIR
.get_or_init(|| dirs::download_dir().expect("failed to determine download directory"))
}
/// Returns the path to the configuration directory used by Coop. /// Returns the path to the configuration directory used by Coop.
pub fn config_dir() -> &'static PathBuf { pub fn config_dir() -> &'static PathBuf {
static CONFIG_DIR: OnceLock<PathBuf> = OnceLock::new(); static CONFIG_DIR: OnceLock<PathBuf> = OnceLock::new();
@@ -56,9 +63,3 @@ pub fn support_dir() -> &'static PathBuf {
config_dir().clone() config_dir().clone()
}) })
} }
/// Returns the path to the `nostr` file.
pub fn nostr_file() -> &'static PathBuf {
static NOSTR_FILE: OnceLock<PathBuf> = OnceLock::new();
NOSTR_FILE.get_or_init(|| support_dir().join("nostr-db"))
}

View File

@@ -14,7 +14,7 @@ product-name = "Coop"
description = "Chat Freely, Stay Private on Nostr" description = "Chat Freely, Stay Private on Nostr"
identifier = "su.reya.coop" identifier = "su.reya.coop"
category = "SocialNetworking" category = "SocialNetworking"
version = "1.0.0-beta1" version = "1.0.0-beta2"
out-dir = "../../dist" out-dir = "../../dist"
before-packaging-command = "cargo build --release" before-packaging-command = "cargo build --release"
resources = ["Cargo.toml", "src"] resources = ["Cargo.toml", "src"]

View File

@@ -242,7 +242,6 @@ impl Render for ImportKey {
fn render(&mut self, _window: &mut gpui::Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, _window: &mut gpui::Window, cx: &mut Context<Self>) -> impl IntoElement {
v_flex() v_flex()
.size_full() .size_full()
.p_4()
.gap_2() .gap_2()
.text_sm() .text_sm()
.child( .child(

View File

@@ -1,6 +1,6 @@
pub mod accounts; pub mod accounts;
pub mod connect;
pub mod import;
pub mod restore;
pub mod screening; pub mod screening;
pub mod settings; pub mod settings;
mod connect;
mod import;

View File

@@ -0,0 +1,130 @@
use std::time::Duration;
use anyhow::Error;
use device::DeviceRegistry;
use gpui::prelude::FluentBuilder;
use gpui::{
AppContext, Context, Entity, IntoElement, ParentElement, Render, SharedString, Styled,
Subscription, Task, Window, div,
};
use nostr_connect::prelude::*;
use theme::ActiveTheme;
use ui::button::{Button, ButtonVariants};
use ui::input::{InputEvent, InputState, TextInput};
use ui::{WindowExtension, v_flex};
#[derive(Debug)]
pub struct RestoreEncryption {
/// Secret key input
key_input: Entity<InputState>,
/// Error message
error: Entity<Option<SharedString>>,
/// Async tasks
tasks: Vec<Task<Result<(), Error>>>,
/// Event subscription
_subscription: Option<Subscription>,
}
impl RestoreEncryption {
pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
let key_input = cx.new(|cx| InputState::new(window, cx).masked(true));
let error = cx.new(|_| None);
let subscription =
cx.subscribe_in(&key_input, window, |this, _input, event, window, cx| {
if let InputEvent::PressEnter { .. } = event {
this.restore(window, cx);
};
});
Self {
key_input,
error,
tasks: vec![],
_subscription: Some(subscription),
}
}
fn restore(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let device = DeviceRegistry::global(cx);
let content = self.key_input.read(cx).value();
if !content.is_empty() {
self.set_error("Secret Key cannot be empty.", cx);
}
let Ok(secret) = SecretKey::parse(&content) else {
self.set_error("Secret Key is invalid.", cx);
return;
};
device.update(cx, |this, cx| {
this.set_announcement(Keys::new(secret), cx);
});
// Close the current modal
window.close_modal(cx);
}
fn set_error<S>(&mut self, message: S, cx: &mut Context<Self>)
where
S: Into<SharedString>,
{
// Update error message
self.error.update(cx, |this, cx| {
*this = Some(message.into());
cx.notify();
});
// Clear the error message after 3 secs
self.tasks.push(cx.spawn(async move |this, cx| {
cx.background_executor().timer(Duration::from_secs(3)).await;
this.update(cx, |this, cx| {
this.error.update(cx, |this, cx| {
*this = None;
cx.notify();
});
})?;
Ok(())
}));
}
}
impl Render for RestoreEncryption {
fn render(&mut self, _window: &mut gpui::Window, cx: &mut Context<Self>) -> impl IntoElement {
v_flex()
.size_full()
.gap_2()
.text_sm()
.child(
v_flex()
.gap_1()
.text_sm()
.text_color(cx.theme().text_muted)
.child("Secret Key")
.child(TextInput::new(&self.key_input)),
)
.child(
Button::new("restore")
.label("Restore")
.primary()
.on_click(cx.listener(move |this, _, window, cx| {
this.restore(window, cx);
})),
)
.when_some(self.error.read(cx).as_ref(), |this, error| {
this.child(
div()
.text_xs()
.text_center()
.text_color(cx.theme().text_danger)
.child(error.clone()),
)
})
}
}

View File

@@ -148,26 +148,27 @@ impl RenderOnce for RoomEntry {
this.on_click(move |event, window, cx| { this.on_click(move |event, window, cx| {
handler(event, window, cx); handler(event, window, cx);
if let Some(public_key) = public_key { if let Some(public_key) = public_key
if self.kind != Some(RoomKind::Ongoing) && screening { && self.kind != Some(RoomKind::Ongoing)
let screening = screening::init(public_key, window, cx); && screening
{
let screening = screening::init(public_key, window, cx);
window.open_modal(cx, move |this, _window, _cx| { window.open_modal(cx, move |this, _window, _cx| {
this.confirm() this.confirm()
.child(screening.clone()) .child(screening.clone())
.button_props( .button_props(
ModalButtonProps::default() ModalButtonProps::default()
.cancel_text("Ignore") .cancel_text("Ignore")
.ok_text("Response"), .ok_text("Response"),
) )
.on_cancel(move |_event, window, cx| { .on_cancel(move |_event, window, cx| {
window.dispatch_action(Box::new(ClosePanel), cx); window.dispatch_action(Box::new(ClosePanel), cx);
// Prevent closing the modal on click // Prevent closing the modal on click
// modal will be automatically closed after closing panel // modal will be automatically closed after closing panel
false false
}) })
}); });
}
} }
}) })
}) })

View File

@@ -366,7 +366,11 @@ impl Sidebar {
self.new_requests = false; self.new_requests = false;
} }
fn render_list_items(&self, range: Range<usize>, cx: &Context<Self>) -> Vec<impl IntoElement> { fn render_list_items(
&self,
range: Range<usize>,
cx: &Context<Self>,
) -> Vec<impl IntoElement + use<>> {
let chat = ChatRegistry::global(cx); let chat = ChatRegistry::global(cx);
let rooms = chat.read(cx).rooms(self.filter.read(cx), cx); let rooms = chat.read(cx).rooms(self.filter.read(cx), cx);
@@ -398,7 +402,11 @@ impl Sidebar {
} }
/// Render the contact list /// Render the contact list
fn render_results(&self, range: Range<usize>, cx: &Context<Self>) -> Vec<impl IntoElement> { fn render_results(
&self,
range: Range<usize>,
cx: &Context<Self>,
) -> Vec<impl IntoElement + use<>> {
let persons = PersonRegistry::global(cx); let persons = PersonRegistry::global(cx);
// Get the contact list // Get the contact list
@@ -431,7 +439,11 @@ impl Sidebar {
} }
/// Render the contact list /// Render the contact list
fn render_contacts(&self, range: Range<usize>, cx: &Context<Self>) -> Vec<impl IntoElement> { fn render_contacts(
&self,
range: Range<usize>,
cx: &Context<Self>,
) -> Vec<impl IntoElement + use<>> {
let persons = PersonRegistry::global(cx); let persons = PersonRegistry::global(cx);
// Get the contact list // Get the contact list
@@ -641,7 +653,7 @@ impl Render for Sidebar {
uniform_list( uniform_list(
"rooms", "rooms",
results.len(), results.len(),
cx.processor(|this, range, _window, cx| { cx.processor(move |this, range, _window, cx| {
this.render_results(range, cx) this.render_results(range, cx)
}), }),
) )
@@ -668,7 +680,7 @@ impl Render for Sidebar {
uniform_list( uniform_list(
"contacts", "contacts",
contacts.len(), contacts.len(),
cx.processor(move |this, range, _window, cx| { cx.processor(|this, range, _window, cx| {
this.render_contacts(range, cx) this.render_contacts(range, cx)
}), }),
) )

View File

@@ -4,12 +4,14 @@ use std::sync::Arc;
use ::settings::AppSettings; use ::settings::AppSettings;
use chat::{ChatEvent, ChatRegistry}; use chat::{ChatEvent, ChatRegistry};
use common::download_dir;
use device::{DeviceEvent, DeviceRegistry}; use device::{DeviceEvent, DeviceRegistry};
use gpui::prelude::FluentBuilder; use gpui::prelude::FluentBuilder;
use gpui::{ use gpui::{
Action, App, AppContext, Axis, Context, Entity, InteractiveElement, IntoElement, ParentElement, Action, App, AppContext, Axis, Context, Entity, InteractiveElement, IntoElement, ParentElement,
Render, SharedString, Styled, Subscription, Window, div, px, Render, SharedString, Styled, Subscription, Window, div, px,
}; };
use nostr_sdk::prelude::*;
use person::PersonRegistry; use person::PersonRegistry;
use serde::Deserialize; use serde::Deserialize;
use smallvec::{SmallVec, smallvec}; use smallvec::{SmallVec, smallvec};
@@ -23,13 +25,14 @@ use ui::menu::{DropdownMenu, PopupMenuItem};
use ui::notification::{Notification, NotificationKind}; use ui::notification::{Notification, NotificationKind};
use ui::{Disableable, IconName, Root, Sizable, WindowExtension, h_flex, v_flex}; use ui::{Disableable, IconName, Root, Sizable, WindowExtension, h_flex, v_flex};
use crate::dialogs::restore::RestoreEncryption;
use crate::dialogs::{accounts, settings}; use crate::dialogs::{accounts, settings};
use crate::panels::{backup, contact_list, greeter, messaging_relays, profile, relay_list}; use crate::panels::{backup, contact_list, greeter, messaging_relays, profile, relay_list};
use crate::sidebar; use crate::sidebar;
const PREPARE_MSG: &str = "Coop is preparing a new identity for you. This may take a moment...";
const ENC_MSG: &str = "Encryption Key is a special key that used to encrypt and decrypt your messages. \ const ENC_MSG: &str = "Encryption Key is a special key that used to encrypt and decrypt your messages. \
Your identity is completely decoupled from all encryption processes to protect your privacy."; Your identity is completely decoupled from all encryption processes to protect your privacy.";
const ENC_WARN: &str = "By resetting your encryption key, you will lose access to \ const ENC_WARN: &str = "By resetting your encryption key, you will lose access to \
all your encrypted messages before. This action cannot be undone."; all your encrypted messages before. This action cannot be undone.";
@@ -37,6 +40,8 @@ pub fn init(window: &mut Window, cx: &mut App) -> Entity<Workspace> {
cx.new(|cx| Workspace::new(window, cx)) cx.new(|cx| Workspace::new(window, cx))
} }
struct DeviceNotifcation;
struct SignerNotifcation;
struct RelayNotifcation; struct RelayNotifcation;
#[derive(Action, Clone, PartialEq, Eq, Deserialize)] #[derive(Action, Clone, PartialEq, Eq, Deserialize)]
@@ -45,9 +50,11 @@ enum Command {
ToggleTheme, ToggleTheme,
ToggleAccount, ToggleAccount,
RefreshEncryption,
RefreshRelayList, RefreshRelayList,
RefreshMessagingRelays, RefreshMessagingRelays,
BackupEncryption,
ImportEncryption,
RefreshEncryption,
ResetEncryption, ResetEncryption,
ShowRelayList, ShowRelayList,
@@ -107,26 +114,42 @@ impl Workspace {
// Subscribe to the signer events // Subscribe to the signer events
cx.subscribe_in(&nostr, window, move |this, _state, event, window, cx| { cx.subscribe_in(&nostr, window, move |this, _state, event, window, cx| {
match event { match event {
StateEvent::Creating => {
let note = Notification::new()
.id::<SignerNotifcation>()
.title("Preparing a new identity")
.message(PREPARE_MSG)
.autohide(false)
.with_kind(NotificationKind::Info);
window.push_notification(note, cx);
}
StateEvent::Connecting => { StateEvent::Connecting => {
let note = Notification::new() let note = Notification::new()
.id::<RelayNotifcation>() .id::<RelayNotifcation>()
.message("Connecting to the bootstrap relay...") .message("Connecting to the bootstrap relays...")
.with_kind(NotificationKind::Info) .with_kind(NotificationKind::Info);
.icon(IconName::Relay);
window.push_notification(note, cx); window.push_notification(note, cx);
} }
StateEvent::Connected => { StateEvent::Connected => {
let note = Notification::new() let note = Notification::new()
.id::<RelayNotifcation>() .id::<RelayNotifcation>()
.message("Connected to the bootstrap relay") .message("Connected to the bootstrap relays")
.with_kind(NotificationKind::Success) .with_kind(NotificationKind::Success);
.icon(IconName::Relay);
window.push_notification(note, cx);
}
StateEvent::FetchingRelayList => {
let note = Notification::new()
.id::<RelayNotifcation>()
.message("Getting relay list...")
.with_kind(NotificationKind::Info);
window.push_notification(note, cx); window.push_notification(note, cx);
} }
StateEvent::RelayNotConfigured => { StateEvent::RelayNotConfigured => {
this.relay_notification(window, cx); this.relay_warning(window, cx);
} }
StateEvent::RelayConnected => { StateEvent::RelayConnected => {
window.clear_notification::<RelayNotifcation>(cx); window.clear_notification::<RelayNotifcation>(cx);
@@ -136,6 +159,8 @@ impl Workspace {
this.set_center_layout(window, cx); this.set_center_layout(window, cx);
this.set_relay_connected(false, cx); this.set_relay_connected(false, cx);
this.set_inbox_connected(false, cx); this.set_inbox_connected(false, cx);
// Clear the signer notification
window.clear_notification::<SignerNotifcation>(cx);
} }
_ => {} _ => {}
}; };
@@ -144,13 +169,55 @@ impl Workspace {
subscriptions.push( subscriptions.push(
// Observe all events emitted by the device registry // Observe all events emitted by the device registry
cx.subscribe_in(&device, window, |_this, _device, ev, window, cx| { cx.subscribe_in(&device, window, |_this, _device, event, window, cx| {
match ev { match event {
DeviceEvent::Requesting => {
const MSG: &str =
"Please open the other client and approve the encryption key request";
let note = Notification::new()
.id::<DeviceNotifcation>()
.title("Wait for approval")
.message(MSG)
.with_kind(NotificationKind::Info);
window.push_notification(note, cx);
}
DeviceEvent::Creating => {
let note = Notification::new()
.id::<DeviceNotifcation>()
.message("Creating encryption key")
.with_kind(NotificationKind::Info);
window.push_notification(note, cx);
}
DeviceEvent::Set => { DeviceEvent::Set => {
window.push_notification( let note = Notification::new()
Notification::success("Encryption Key has been set"), .id::<DeviceNotifcation>()
cx, .message("Encryption Key has been set")
); .with_kind(NotificationKind::Success);
window.push_notification(note, cx);
}
DeviceEvent::NotSet { reason } => {
let note = Notification::new()
.id::<DeviceNotifcation>()
.title("Cannot setup the encryption key")
.message(reason)
.autohide(false)
.with_kind(NotificationKind::Error);
window.push_notification(note, cx);
}
DeviceEvent::NotSubscribe { reason } => {
let note = Notification::new()
.id::<DeviceNotifcation>()
.title("Cannot getting messages")
.message(reason)
.autohide(false)
.with_kind(NotificationKind::Error);
window.push_notification(note, cx);
} }
DeviceEvent::Error(error) => { DeviceEvent::Error(error) => {
window.push_notification(Notification::error(error).autohide(false), cx); window.push_notification(Notification::error(error).autohide(false), cx);
@@ -228,14 +295,14 @@ impl Workspace {
where where
P: PanelView, P: PanelView,
{ {
if let Some(root) = window.root::<Root>().flatten() { if let Some(root) = window.root::<Root>().flatten()
if let Ok(workspace) = root.read(cx).view().clone().downcast::<Self>() { && let Ok(workspace) = root.read(cx).view().clone().downcast::<Self>()
workspace.update(cx, |this, cx| { {
this.dock.update(cx, |this, cx| { workspace.update(cx, |this, cx| {
this.add_panel(Arc::new(panel), placement, window, cx); this.dock.update(cx, |this, cx| {
}); this.add_panel(Arc::new(panel), placement, window, cx);
}); });
} });
} }
} }
@@ -385,14 +452,57 @@ impl Workspace {
Command::ToggleAccount => { Command::ToggleAccount => {
self.account_selector(window, cx); self.account_selector(window, cx);
} }
Command::BackupEncryption => {
let device = DeviceRegistry::global(cx).downgrade();
let save_dialog = cx.prompt_for_new_path(download_dir(), Some("encryption.txt"));
cx.spawn_in(window, async move |_this, cx| {
// Get the output path from the save dialog
let output_path = match save_dialog.await {
Ok(Ok(Some(path))) => path,
Ok(Ok(None)) | Err(_) => return Ok(()),
Ok(Err(error)) => {
cx.update(|window, cx| {
let message = format!("Failed to pick save location: {error:#}");
let note = Notification::error(message).autohide(false);
window.push_notification(note, cx);
})?;
return Ok(());
}
};
// Get the backup task
let backup =
device.read_with(cx, |this, cx| this.backup(output_path.clone(), cx))?;
// Run the backup task
backup.await?;
// Open the backup file with the system's default application
cx.update(|_window, cx| {
cx.open_with_system(output_path.as_path());
})?;
Ok::<_, anyhow::Error>(())
})
.detach();
}
Command::ImportEncryption => {
self.import_encryption(window, cx);
}
} }
} }
fn confirm_reset_encryption(&mut self, window: &mut Window, cx: &mut Context<Self>) { fn confirm_reset_encryption(&mut self, window: &mut Window, cx: &mut Context<Self>) {
window.open_modal(cx, |this, _window, cx| { let device = DeviceRegistry::global(cx);
let ent = device.downgrade();
window.open_modal(cx, move |this, _window, cx| {
let ent = ent.clone();
this.confirm() this.confirm()
.show_close(true) .show_close(true)
.title("Reset Encryption Keys") .title("Reset Encryption Key")
.child( .child(
v_flex() v_flex()
.gap_1() .gap_1()
@@ -401,43 +511,31 @@ impl Workspace {
.child( .child(
div() div()
.italic() .italic()
.text_color(cx.theme().warning_active) .text_color(cx.theme().text_danger)
.child(SharedString::from(ENC_WARN)), .child(SharedString::from(ENC_WARN)),
), ),
) )
.on_ok(move |_ev, window, cx| { .on_ok(move |_ev, _window, cx| {
let device = DeviceRegistry::global(cx); ent.update(cx, |this, cx| {
let task = device.read(cx).create_encryption(cx); this.set_announcement(Keys::generate(), cx);
})
window .ok();
.spawn(cx, async move |cx| { // true to close modal
let result = task.await; true
cx.update(|window, cx| match result {
Ok(keys) => {
device.update(cx, |this, cx| {
this.set_signer(keys, cx);
this.listen_request(cx);
});
window.close_modal(cx);
}
Err(e) => {
window.push_notification(
Notification::error(e.to_string()).autohide(false),
cx,
);
}
})
.ok();
})
.detach();
// false to keep modal open
false
}) })
}); });
} }
fn import_encryption(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let restore = cx.new(|cx| RestoreEncryption::new(window, cx));
window.open_modal(cx, move |this, _window, _cx| {
this.width(px(520.))
.title("Restore Encryption")
.child(restore.clone())
});
}
fn account_selector(&mut self, window: &mut Window, cx: &mut Context<Self>) { fn account_selector(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let accounts = accounts::init(window, cx); let accounts = accounts::init(window, cx);
@@ -447,7 +545,6 @@ impl Workspace {
.show_close(false) .show_close(false)
.keyboard(false) .keyboard(false)
.overlay_closable(false) .overlay_closable(false)
.pb_2()
.child(accounts.clone()) .child(accounts.clone())
}); });
} }
@@ -460,7 +557,6 @@ impl Workspace {
this.width(px(520.)) this.width(px(520.))
.show_close(true) .show_close(true)
.title("Select theme") .title("Select theme")
.pb_2()
.child(v_flex().gap_2().w_full().children({ .child(v_flex().gap_2().w_full().children({
let mut items = vec![]; let mut items = vec![];
@@ -533,7 +629,7 @@ impl Workspace {
}); });
} }
fn relay_notification(&mut self, window: &mut Window, cx: &mut Context<Self>) { fn relay_warning(&mut self, window: &mut Window, cx: &mut Context<Self>) {
const BODY: &str = "Coop cannot found your gossip relay list. \ const BODY: &str = "Coop cannot found your gossip relay list. \
Maybe you haven't set it yet or relay not responsed"; Maybe you haven't set it yet or relay not responsed";
@@ -582,7 +678,7 @@ impl Workspace {
window.push_notification(note, cx); window.push_notification(note, cx);
} }
fn titlebar_left(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn titlebar_left(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
let nostr = NostrRegistry::global(cx); let nostr = NostrRegistry::global(cx);
let signer = nostr.read(cx).signer(); let signer = nostr.read(cx).signer();
let current_user = signer.public_key(); let current_user = signer.public_key();
@@ -661,7 +757,7 @@ impl Workspace {
}) })
} }
fn titlebar_right(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn titlebar_right(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
let relay_connected = self.relay_connected; let relay_connected = self.relay_connected;
let inbox_connected = self.inbox_connected; let inbox_connected = self.inbox_connected;
@@ -683,27 +779,63 @@ impl Workspace {
.ghost() .ghost()
.dropdown_menu(move |this, _window, cx| { .dropdown_menu(move |this, _window, cx| {
let device = DeviceRegistry::global(cx); let device = DeviceRegistry::global(cx);
let state = device.read(cx).state(); let subscribing = device.read(cx).subscribing;
let requesting = device.read(cx).requesting;
this.min_w(px(260.)) this.min_w(px(260.))
.label("Encryption Key")
.when(requesting, |this| {
this.item(PopupMenuItem::element(move |_window, cx| {
h_flex()
.px_1()
.w_full()
.gap_2()
.text_sm()
.child(
div()
.size_1p5()
.rounded_full()
.bg(cx.theme().icon_accent),
)
.child(SharedString::from("Waiting for approval..."))
}))
})
.item(PopupMenuItem::element(move |_window, cx| { .item(PopupMenuItem::element(move |_window, cx| {
h_flex() h_flex()
.px_1() .px_1()
.w_full() .w_full()
.gap_2() .gap_2()
.text_sm() .text_sm()
.child( .when(!subscribing, |this| {
div() this.text_color(cx.theme().text_muted)
.size_1p5() })
.rounded_full() .child(div().size_1p5().rounded_full().map(|this| {
.when(state.set(), |this| this.bg(gpui::green())) if subscribing {
.when(state.requesting(), |this| { this.bg(cx.theme().icon_accent)
this.bg(cx.theme().icon_accent) } else {
}), this.bg(cx.theme().icon_muted)
) }
.child(SharedString::from(state.to_string())) }))
.map(|this| {
if subscribing {
this.child("Listening for messages")
} else {
this.child("Idle")
}
})
})) }))
.separator() .separator()
.menu_with_icon(
"Backup",
IconName::Shield,
Box::new(Command::BackupEncryption),
)
.menu_with_icon(
"Restore from secret key",
IconName::Usb,
Box::new(Command::ImportEncryption),
)
.separator()
.menu_with_icon( .menu_with_icon(
"Reload", "Reload",
IconName::Refresh, IconName::Refresh,
@@ -724,32 +856,53 @@ impl Workspace {
.loading(!inbox_connected) .loading(!inbox_connected)
.disabled(!inbox_connected) .disabled(!inbox_connected)
.when(!inbox_connected, |this| { .when(!inbox_connected, |this| {
this.tooltip("Connecting to user's messaging relays...") this.tooltip("Connecting to the user's messaging relays...")
}) })
.when(inbox_connected, |this| this.indicator()) .when(inbox_connected, |this| this.indicator())
.dropdown_menu(move |this, _window, cx| { .dropdown_menu(move |this, _window, cx| {
let chat = ChatRegistry::global(cx);
let persons = PersonRegistry::global(cx); let persons = PersonRegistry::global(cx);
let profile = persons.read(cx).get(&public_key, cx); let profile = persons.read(cx).get(&public_key, cx);
let urls: Vec<SharedString> = profile let urls: Vec<(SharedString, SharedString)> = profile
.messaging_relays() .messaging_relays()
.iter() .iter()
.map(|url| SharedString::from(url.to_string())) .map(|url| {
(
SharedString::from(url.to_string()),
chat.read(cx).count_messages(url).to_string().into(),
)
})
.collect(); .collect();
// Header // Header
let menu = this.min_w(px(260.)).label("Messaging Relays"); let menu = this.min_w(px(260.)).label("Messaging Relays");
// Content // Content
let menu = urls.into_iter().fold(menu, |this, url| { let menu = urls.into_iter().fold(menu, |this, (url, count)| {
this.item(PopupMenuItem::element(move |_window, _cx| { this.item(PopupMenuItem::element(move |_window, cx| {
h_flex() h_flex()
.px_1() .px_1()
.w_full() .w_full()
.gap_2()
.text_sm() .text_sm()
.child(div().size_1p5().rounded_full().bg(gpui::green())) .justify_between()
.child(url.clone()) .child(
h_flex()
.gap_2()
.child(
div()
.size_1p5()
.rounded_full()
.bg(cx.theme().icon_accent),
)
.child(url.clone()),
)
.child(
div()
.text_xs()
.text_color(cx.theme().text_muted)
.child(count.clone()),
)
})) }))
}); });
@@ -775,7 +928,7 @@ impl Workspace {
.loading(!relay_connected) .loading(!relay_connected)
.disabled(!relay_connected) .disabled(!relay_connected)
.when(!relay_connected, |this| { .when(!relay_connected, |this| {
this.tooltip("Connecting to user's relay list...") this.tooltip("Connecting to the user's relay list...")
}) })
.when(relay_connected, |this| this.indicator()) .when(relay_connected, |this| this.indicator())
.dropdown_menu(move |this, _window, _cx| { .dropdown_menu(move |this, _window, _cx| {
@@ -802,8 +955,8 @@ impl Render for Workspace {
let notification_layer = Root::render_notification_layer(window, cx); let notification_layer = Root::render_notification_layer(window, cx);
// Titlebar elements // Titlebar elements
let left = self.titlebar_left(window, cx).into_any_element(); let left = self.titlebar_left(cx).into_any_element();
let right = self.titlebar_right(window, cx).into_any_element(); let right = self.titlebar_right(cx).into_any_element();
// Update title bar children // Update title bar children
self.titlebar.update(cx, |this, _cx| { self.titlebar.update(cx, |this, _cx| {

View File

@@ -1,21 +1,22 @@
use std::cell::Cell; use std::cell::Cell;
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::rc::Rc; use std::rc::Rc;
use std::time::Duration; use std::time::Duration;
use anyhow::{Context as AnyhowContext, Error, anyhow}; use anyhow::{Context as AnyhowContext, Error, anyhow};
use gpui::{ use gpui::{
App, AppContext, Context, Entity, EventEmitter, Global, IntoElement, ParentElement, App, AppContext, Context, Entity, EventEmitter, Global, IntoElement, ParentElement,
SharedString, Styled, Task, Window, div, relative, SharedString, Styled, Subscription, Task, Window, div, relative,
}; };
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;
use person::PersonRegistry; use person::PersonRegistry;
use state::{Announcement, DEVICE_GIFTWRAP, DeviceState, NostrRegistry, TIMEOUT, app_name}; use state::{Announcement, DEVICE_GIFTWRAP, NostrRegistry, StateEvent, TIMEOUT, app_name};
use theme::ActiveTheme; use theme::ActiveTheme;
use ui::avatar::Avatar; use ui::avatar::Avatar;
use ui::button::{Button, ButtonVariants}; use ui::button::{Button, ButtonVariants};
use ui::notification::Notification; use ui::notification::Notification;
use ui::{Disableable, IconName, Sizable, WindowExtension, h_flex, v_flex}; use ui::{Disableable, IconName, Sizable, StyledExt, WindowExtension, h_flex, v_flex};
const IDENTIFIER: &str = "coop:device"; const IDENTIFIER: &str = "coop:device";
const MSG: &str = "You've requested an encryption key from another device. \ const MSG: &str = "You've requested an encryption key from another device. \
@@ -34,20 +35,64 @@ impl Global for GlobalDeviceRegistry {}
pub enum DeviceEvent { pub enum DeviceEvent {
/// A new encryption signer has been set /// A new encryption signer has been set
Set, Set,
/// The device is requesting an encryption key
Requesting,
/// The device is creating a new encryption key
Creating,
/// Encryption key is not set
NotSet { reason: SharedString },
/// An event to notify that Coop isn't subscribed to gift wrap events
NotSubscribe { reason: SharedString },
/// An error occurred /// An error occurred
Error(SharedString), Error(SharedString),
} }
impl DeviceEvent {
pub fn error<T>(error: T) -> Self
where
T: Into<SharedString>,
{
Self::Error(error.into())
}
pub fn not_subscribe<T>(reason: T) -> Self
where
T: Into<SharedString>,
{
Self::NotSubscribe {
reason: reason.into(),
}
}
pub fn not_set<T>(reason: T) -> Self
where
T: Into<SharedString>,
{
Self::NotSet {
reason: reason.into(),
}
}
}
/// Device Registry /// Device Registry
/// ///
/// NIP-4e: https://github.com/nostr-protocol/nips/blob/per-device-keys/4e.md /// NIP-4e: https://github.com/nostr-protocol/nips/blob/per-device-keys/4e.md
#[derive(Debug)] #[derive(Debug)]
pub struct DeviceRegistry { pub struct DeviceRegistry {
/// Device state /// Whether the registry is currently subscribing to gift wrap events
state: DeviceState, pub subscribing: bool,
/// Whether the registry is waiting for encryption key approval from other devices
pub requesting: bool,
/// Whether there is a pending request for encryption key approval
pub has_pending_request: bool,
/// Async tasks /// Async tasks
tasks: Vec<Task<Result<(), Error>>>, tasks: Vec<Task<Result<(), Error>>>,
/// Event subscription
_subscription: Option<Subscription>,
} }
impl EventEmitter<DeviceEvent> for DeviceRegistry {} impl EventEmitter<DeviceEvent> for DeviceRegistry {}
@@ -65,16 +110,32 @@ impl DeviceRegistry {
/// Create a new device registry instance /// Create a new device registry instance
fn new(window: &mut Window, cx: &mut Context<Self>) -> Self { fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
let state = DeviceState::default(); let nostr = NostrRegistry::global(cx);
// Get announcement when signer is set
let subscription = cx.subscribe_in(&nostr, window, |this, _e, event, _window, cx| {
match event {
StateEvent::SignerSet => {
this.set_subscribing(false, cx);
this.set_requesting(false, cx);
}
StateEvent::RelayConnected => {
this.get_announcement(cx);
}
_ => {}
};
});
cx.defer_in(window, |this, window, cx| { cx.defer_in(window, |this, window, cx| {
this.handle_notifications(window, cx); this.handle_notifications(window, cx);
this.get_announcement(cx);
}); });
Self { Self {
state, subscribing: false,
requesting: false,
has_pending_request: false,
tasks: vec![], tasks: vec![],
_subscription: Some(subscription),
} }
} }
@@ -120,13 +181,13 @@ impl DeviceRegistry {
self.tasks.push(cx.spawn_in(window, async move |this, cx| { self.tasks.push(cx.spawn_in(window, async move |this, cx| {
while let Ok(event) = rx.recv_async().await { while let Ok(event) = rx.recv_async().await {
match event.kind { match event.kind {
// New request event // New request event from other device
Kind::Custom(4454) => { Kind::Custom(4454) => {
this.update_in(cx, |this, window, cx| { this.update_in(cx, |this, window, cx| {
this.ask_for_approval(event, window, cx); this.ask_for_approval(event, window, cx);
})?; })?;
} }
// New response event // New response event from the master device
Kind::Custom(4455) => { Kind::Custom(4455) => {
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
this.extract_encryption(event, cx); this.extract_encryption(event, cx);
@@ -135,24 +196,30 @@ impl DeviceRegistry {
_ => {} _ => {}
} }
} }
Ok(()) Ok(())
})); }));
} }
/// Get the device state /// Set whether the registry is currently subscribing to gift wrap events
pub fn state(&self) -> DeviceState { fn set_subscribing(&mut self, subscribing: bool, cx: &mut Context<Self>) {
self.state.clone() self.subscribing = subscribing;
cx.notify();
} }
/// Set the device state /// Set whether the registry is waiting for encryption key approval from other devices
fn set_state(&mut self, state: DeviceState, cx: &mut Context<Self>) { fn set_requesting(&mut self, requesting: bool, cx: &mut Context<Self>) {
self.state = state; self.requesting = requesting;
cx.notify();
}
/// Set whether there is a pending request for encryption key approval
fn set_has_pending_request(&mut self, pending: bool, cx: &mut Context<Self>) {
self.has_pending_request = pending;
cx.notify(); cx.notify();
} }
/// Set the decoupled encryption key for the current user /// Set the decoupled encryption key for the current user
pub fn set_signer<S>(&mut self, new: S, cx: &mut Context<Self>) fn set_signer<S>(&mut self, new: S, cx: &mut Context<Self>)
where where
S: NostrSigner + 'static, S: NostrSigner + 'static,
{ {
@@ -164,7 +231,7 @@ impl DeviceRegistry {
// Update state // Update state
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
this.set_state(DeviceState::Set, cx); cx.emit(DeviceEvent::Set);
this.get_messages(cx); this.get_messages(cx);
})?; })?;
@@ -172,12 +239,6 @@ impl DeviceRegistry {
})); }));
} }
/// Reset the device state
fn reset(&mut self, cx: &mut Context<Self>) {
self.state = DeviceState::Idle;
cx.notify();
}
/// Get all messages for encryption keys /// Get all messages for encryption keys
fn get_messages(&mut self, cx: &mut Context<Self>) { fn get_messages(&mut self, cx: &mut Context<Self>) {
let task = self.subscribe_to_giftwrap_events(cx); let task = self.subscribe_to_giftwrap_events(cx);
@@ -185,59 +246,50 @@ impl DeviceRegistry {
self.tasks.push(cx.spawn(async move |this, cx| { self.tasks.push(cx.spawn(async move |this, cx| {
if let Err(e) = task.await { if let Err(e) = task.await {
this.update(cx, |_this, cx| { this.update(cx, |_this, cx| {
cx.emit(DeviceEvent::Error(SharedString::from(e.to_string()))); cx.emit(DeviceEvent::not_subscribe(e.to_string()));
})?;
} else {
this.update(cx, |this, cx| {
this.set_subscribing(true, cx);
})?; })?;
} }
Ok(()) Ok(())
})); }));
} }
/// Get the messaging relays for the current user
fn get_user_messaging_relays(&self, cx: &App) -> Task<Result<Vec<RelayUrl>, Error>> {
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer();
cx.background_spawn(async move {
let public_key = signer.get_public_key().await?;
let filter = Filter::new()
.kind(Kind::InboxRelays)
.author(public_key)
.limit(1);
if let Some(event) = client.database().query(filter).await?.first_owned() {
// Extract relay URLs from the event
let urls: Vec<RelayUrl> = nip17::extract_owned_relay_list(event).collect();
// Ensure all relays are connected
for url in urls.iter() {
client.add_relay(url).and_connect().await?;
}
Ok(urls)
} else {
Err(anyhow!("Relays not found"))
}
})
}
/// Continuously get gift wrap events for the current user in their messaging relays /// Continuously get gift wrap events for the current user in their messaging relays
fn subscribe_to_giftwrap_events(&self, cx: &App) -> Task<Result<(), Error>> { fn subscribe_to_giftwrap_events(&self, cx: &App) -> Task<Result<(), Error>> {
let persons = PersonRegistry::global(cx);
let nostr = NostrRegistry::global(cx); let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client(); let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer(); let signer = nostr.read(cx).signer();
let urls = self.get_user_messaging_relays(cx);
let Some(user) = signer.public_key() else {
return Task::ready(Err(anyhow!("User not found")));
};
let profile = persons.read(cx).get(&user, cx);
let relays = profile.messaging_relays().clone();
cx.background_spawn(async move { cx.background_spawn(async move {
let urls = urls.await?;
let encryption = signer.get_encryption_signer().await.context("not found")?; let encryption = signer.get_encryption_signer().await.context("not found")?;
let public_key = encryption.get_public_key().await?; let public_key = encryption.get_public_key().await?;
let filter = Filter::new().kind(Kind::GiftWrap).pubkey(public_key); let filter = Filter::new().kind(Kind::GiftWrap).pubkey(public_key);
let id = SubscriptionId::new(DEVICE_GIFTWRAP); let id = SubscriptionId::new(DEVICE_GIFTWRAP);
// Ensure user has relays configured
if relays.is_empty() {
return Err(anyhow!("No messaging relays found"));
}
// Ensure relays are connected
for url in relays.iter() {
client.add_relay(url).and_connect().await?;
}
// Construct target for subscription // Construct target for subscription
let target: HashMap<RelayUrl, Filter> = urls let target: HashMap<RelayUrl, Filter> = relays
.into_iter() .into_iter()
.map(|relay| (relay, filter.clone())) .map(|relay| (relay, filter.clone()))
.collect(); .collect();
@@ -249,14 +301,26 @@ impl DeviceRegistry {
}) })
} }
/// Backup the encryption's secret key to a file
pub fn backup(&self, path: PathBuf, cx: &App) -> Task<Result<(), Error>> {
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
cx.background_spawn(async move {
let keys = get_keys(&client).await?;
let content = keys.secret_key().to_bech32()?;
smol::fs::write(path, &content).await?;
Ok(())
})
}
/// Get device announcement for current user /// Get device announcement for current user
pub fn get_announcement(&mut self, cx: &mut Context<Self>) { pub fn get_announcement(&mut self, cx: &mut Context<Self>) {
let nostr = NostrRegistry::global(cx); let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client(); let client = nostr.read(cx).client();
// Reset state before fetching announcement
self.reset(cx);
let task: Task<Result<Event, Error>> = cx.background_spawn(async move { let task: Task<Result<Event, Error>> = cx.background_spawn(async move {
let signer = client.signer().context("Signer not found")?; let signer = client.signer().context("Signer not found")?;
let public_key = signer.get_public_key().await?; let public_key = signer.get_public_key().await?;
@@ -285,13 +349,15 @@ impl DeviceRegistry {
self.tasks.push(cx.spawn(async move |this, cx| { self.tasks.push(cx.spawn(async move |this, cx| {
match task.await { match task.await {
Ok(event) => { Ok(event) => {
// Set encryption key from the announcement event
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
this.new_signer(&event, cx); this.set_encryption(&event, cx);
})?; })?;
} }
Err(_) => { Err(_) => {
// User has no announcement, create a new one
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
this.announce(cx); this.set_announcement(Keys::generate(), cx);
})?; })?;
} }
} }
@@ -300,26 +366,55 @@ impl DeviceRegistry {
})); }));
} }
/// Create new encryption keys /// Create a new device signer and announce it to user's relay list
pub fn create_encryption(&self, cx: &App) -> Task<Result<Keys, Error>> { pub fn set_announcement(&mut self, keys: Keys, cx: &mut Context<Self>) {
let task = self.create_encryption(keys, cx);
// Notify that we're creating a new encryption key
cx.emit(DeviceEvent::Creating);
self.tasks.push(cx.spawn(async move |this, cx| {
match task.await {
Ok(keys) => {
this.update(cx, |this, cx| {
this.set_signer(keys, cx);
this.wait_for_request(cx);
})?;
}
Err(e) => {
this.update(cx, |_this, cx| {
cx.emit(DeviceEvent::error(e.to_string()));
})?;
}
}
Ok(())
}));
}
/// Create new encryption key and announce it to user's relay list
fn create_encryption(&self, keys: Keys, cx: &App) -> Task<Result<Keys, Error>> {
let nostr = NostrRegistry::global(cx); let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client(); let client = nostr.read(cx).client();
let keys = Keys::generate();
let secret = keys.secret_key().to_secret_hex(); let secret = keys.secret_key().to_secret_hex();
let n = keys.public_key(); let n = keys.public_key();
cx.background_spawn(async move { cx.background_spawn(async move {
// Construct an announcement event // Construct an announcement event
let event = client let builder = EventBuilder::new(Kind::Custom(10044), "").tags(vec![
.sign_event_builder(EventBuilder::new(Kind::Custom(10044), "").tags(vec![ Tag::custom(TagKind::custom("n"), vec![n]),
Tag::custom(TagKind::custom("n"), vec![n]), Tag::client(app_name()),
Tag::client(app_name()), ]);
]))
.await?; // Sign the event with user's signer
let event = client.sign_event_builder(builder).await?;
// Publish announcement // Publish announcement
client.send_event(&event).to_nip65().await?; client
.send_event(&event)
.to_nip65()
.ack_policy(AckPolicy::none())
.await?;
// Save device keys to the database // Save device keys to the database
set_keys(&client, &secret).await?; set_keys(&client, &secret).await?;
@@ -328,40 +423,23 @@ impl DeviceRegistry {
}) })
} }
/// Create a new device signer and announce it /// Set encryption key from the announcement event
fn announce(&mut self, cx: &mut Context<Self>) { fn set_encryption(&mut self, event: &Event, cx: &mut Context<Self>) {
let task = self.create_encryption(cx);
self.tasks.push(cx.spawn(async move |this, cx| {
let keys = task.await?;
// Update signer
this.update(cx, |this, cx| {
this.set_signer(keys, cx);
this.listen_request(cx);
})?;
Ok(())
}));
}
/// Initialize device signer (decoupled encryption key) for the current user
pub fn new_signer(&mut self, event: &Event, cx: &mut Context<Self>) {
let nostr = NostrRegistry::global(cx); let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client(); let client = nostr.read(cx).client();
let announcement = Announcement::from(event); let announcement = Announcement::from(event);
let device_pubkey = announcement.public_key(); let device_pubkey = announcement.public_key();
// Get encryption key from the database and compare with the announcement
let task: Task<Result<Keys, Error>> = cx.background_spawn(async move { let task: Task<Result<Keys, Error>> = cx.background_spawn(async move {
if let Ok(keys) = get_keys(&client).await { if let Ok(keys) = get_keys(&client).await {
if keys.public_key() != device_pubkey { if keys.public_key() != device_pubkey {
return Err(anyhow!("Key mismatch")); return Err(anyhow!("Encryption Key doesn't match the announcement"));
}; };
Ok(keys) Ok(keys)
} else { } else {
Err(anyhow!("Key not found")) Err(anyhow!("Encryption Key not found. Please create a new key"))
} }
}); });
@@ -370,74 +448,49 @@ impl DeviceRegistry {
Ok(keys) => { Ok(keys) => {
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
this.set_signer(keys, cx); this.set_signer(keys, cx);
this.listen_request(cx); this.wait_for_request(cx);
})?; })?;
} }
Err(e) => { Err(e) => {
log::warn!("Failed to initialize device signer: {e}"); this.update(cx, |_this, cx| {
this.update(cx, |this, cx| { cx.emit(DeviceEvent::not_set(e.to_string()));
this.request(cx);
this.listen_approval(cx);
})?; })?;
} }
}; };
Ok(()) Ok(())
})); }));
} }
/// Listen for device key requests on user's write relays /// Wait for encryption key requests from now on
pub fn listen_request(&mut self, cx: &mut Context<Self>) { fn wait_for_request(&mut self, cx: &mut Context<Self>) {
let nostr = NostrRegistry::global(cx); let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client(); let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer(); let signer = nostr.read(cx).signer();
let Some(public_key) = signer.public_key() else { self.tasks.push(cx.background_spawn(async move {
return; let public_key = signer.get_public_key().await?;
};
let task: Task<Result<(), Error>> = cx.background_spawn(async move { // Construct a filter for encryption key requests
// Construct a filter for device key requests let now = Filter::new()
let filter = Filter::new()
.kind(Kind::Custom(4454)) .kind(Kind::Custom(4454))
.author(public_key) .author(public_key)
.since(Timestamp::now()); .since(Timestamp::now());
// Subscribe to the device key requests on user's write relays // Construct a filter for the last encryption key request
client.subscribe(filter).await?; let last = Filter::new()
.kind(Kind::Custom(4454))
Ok(())
});
task.detach();
}
/// Listen for device key approvals on user's write relays
fn listen_approval(&mut self, cx: &mut Context<Self>) {
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer();
let Some(public_key) = signer.public_key() else {
return;
};
self.tasks.push(cx.background_spawn(async move {
// Construct a filter for device key requests
let filter = Filter::new()
.kind(Kind::Custom(4455))
.author(public_key) .author(public_key)
.since(Timestamp::now()); .limit(1);
// Subscribe to the device key requests on user's write relays // Subscribe to the device key requests on user's write relays
client.subscribe(filter).await?; client.subscribe(vec![now, last]).await?;
Ok(()) Ok(())
})); }));
} }
/// Request encryption keys from other device /// Request encryption keys from other device
fn request(&mut self, cx: &mut Context<Self>) { pub fn request(&mut self, cx: &mut Context<Self>) {
let nostr = NostrRegistry::global(cx); let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client(); let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer(); let signer = nostr.read(cx).signer();
@@ -445,9 +498,10 @@ impl DeviceRegistry {
let app_keys = nostr.read(cx).keys(); let app_keys = nostr.read(cx).keys();
let app_pubkey = app_keys.public_key(); let app_pubkey = app_keys.public_key();
let task: Task<Result<Option<Keys>, Error>> = cx.background_spawn(async move { let task: Task<Result<Option<Event>, Error>> = cx.background_spawn(async move {
let public_key = signer.get_public_key().await?; let public_key = signer.get_public_key().await?;
// Construct a filter to get the latest approval event
let filter = Filter::new() let filter = Filter::new()
.kind(Kind::Custom(4455)) .kind(Kind::Custom(4455))
.author(public_key) .author(public_key)
@@ -455,30 +509,18 @@ impl DeviceRegistry {
.limit(1); .limit(1);
match client.database().query(filter).await?.first_owned() { match client.database().query(filter).await?.first_owned() {
Some(event) => { // Found an approval event
let root_device = event Some(event) => Ok(Some(event)),
.tags // No approval event found, construct a request event
.find(TagKind::custom("P"))
.and_then(|tag| tag.content())
.and_then(|content| PublicKey::parse(content).ok())
.context("Invalid event's tags")?;
let payload = event.content.as_str();
let decrypted = app_keys.nip44_decrypt(&root_device, payload).await?;
let secret = SecretKey::from_hex(&decrypted)?;
let keys = Keys::new(secret);
Ok(Some(keys))
}
None => { None => {
// Construct an event for device key request // Construct an event for device key request
let event = client let builder = EventBuilder::new(Kind::Custom(4454), "").tags(vec![
.sign_event_builder(EventBuilder::new(Kind::Custom(4454), "").tags(vec![ Tag::custom(TagKind::custom("P"), vec![app_pubkey]),
Tag::client(app_name()), Tag::client(app_name()),
Tag::custom(TagKind::custom("P"), vec![app_pubkey]), ]);
]))
.await?; // Sign the event with user's signer
let event = client.sign_event_builder(builder).await?;
// Send the event to write relays // Send the event to write relays
client.send_event(&event).to_nip65().await?; client.send_event(&event).to_nip65().await?;
@@ -490,32 +532,58 @@ impl DeviceRegistry {
self.tasks.push(cx.spawn(async move |this, cx| { self.tasks.push(cx.spawn(async move |this, cx| {
match task.await { match task.await {
Ok(Some(keys)) => { Ok(Some(event)) => {
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
this.set_signer(keys, cx); this.extract_encryption(event, cx);
})?; })?;
} }
Ok(None) => { Ok(None) => {
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
this.set_state(DeviceState::Requesting, cx); this.set_requesting(true, cx);
this.wait_for_approval(cx);
cx.emit(DeviceEvent::Requesting);
})?; })?;
} }
Err(e) => { Err(e) => {
log::error!("Failed to request the encryption key: {e}"); this.update(cx, |_this, cx| {
cx.emit(DeviceEvent::error(e.to_string()));
})?;
} }
}; };
Ok(())
}));
}
/// Wait for encryption key approvals
fn wait_for_approval(&mut self, cx: &mut Context<Self>) {
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer();
self.tasks.push(cx.background_spawn(async move {
let public_key = signer.get_public_key().await?;
// Construct a filter for device key requests
let filter = Filter::new()
.kind(Kind::Custom(4455))
.author(public_key)
.since(Timestamp::now());
// Subscribe to the device key requests on user's write relays
client.subscribe(filter).await?;
Ok(()) Ok(())
})); }));
} }
/// Parse the response event for device keys from other devices /// Parse the approval event to get encryption key then set it
fn extract_encryption(&mut self, event: Event, cx: &mut Context<Self>) { fn extract_encryption(&mut self, event: Event, cx: &mut Context<Self>) {
let nostr = NostrRegistry::global(cx); let nostr = NostrRegistry::global(cx);
let app_keys = nostr.read(cx).keys(); let app_keys = nostr.read(cx).keys();
let task: Task<Result<Keys, Error>> = cx.background_spawn(async move { let task: Task<Result<Keys, Error>> = cx.background_spawn(async move {
let root_device = event let master = event
.tags .tags
.find(TagKind::custom("P")) .find(TagKind::custom("P"))
.and_then(|tag| tag.content()) .and_then(|tag| tag.content())
@@ -523,7 +591,7 @@ impl DeviceRegistry {
.context("Invalid event's tags")?; .context("Invalid event's tags")?;
let payload = event.content.as_str(); let payload = event.content.as_str();
let decrypted = app_keys.nip44_decrypt(&root_device, payload).await?; let decrypted = app_keys.nip44_decrypt(&master, payload).await?;
let secret = SecretKey::from_hex(&decrypted)?; let secret = SecretKey::from_hex(&decrypted)?;
let keys = Keys::new(secret); let keys = Keys::new(secret);
@@ -532,13 +600,19 @@ impl DeviceRegistry {
}); });
self.tasks.push(cx.spawn(async move |this, cx| { self.tasks.push(cx.spawn(async move |this, cx| {
let keys = task.await?; match task.await {
Ok(keys) => {
// Update signer this.update(cx, |this, cx| {
this.update(cx, |this, cx| { this.set_signer(keys, cx);
this.set_signer(keys, cx); this.set_requesting(false, cx);
})?; })?;
}
Err(e) => {
this.update(cx, |_this, cx| {
cx.emit(DeviceEvent::not_set(e.to_string()));
})?;
}
}
Ok(()) Ok(())
})); }));
} }
@@ -547,7 +621,6 @@ impl DeviceRegistry {
fn approve(&mut self, event: &Event, window: &mut Window, cx: &mut Context<Self>) { fn approve(&mut self, event: &Event, window: &mut Window, cx: &mut Context<Self>) {
let nostr = NostrRegistry::global(cx); let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client(); let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer();
// Get user's write relays // Get user's write relays
let event = event.clone(); let event = event.clone();
@@ -567,14 +640,14 @@ impl DeviceRegistry {
.context("Target is not a valid public key")?; .context("Target is not a valid public key")?;
// Encrypt the device keys with the user's signer // Encrypt the device keys with the user's signer
let payload = signer.nip44_encrypt(&target, &secret).await?; let payload = keys.nip44_encrypt(&target, &secret).await?;
// Construct the response event // Construct the response event
// //
// P tag: the current device's public key // P tag: the current device's public key
// p tag: the requester's public key // p tag: the requester's public key
let builder = EventBuilder::new(Kind::Custom(4455), payload).tags(vec![ let builder = EventBuilder::new(Kind::Custom(4455), payload).tags(vec![
Tag::custom(TagKind::custom("P"), vec![keys.public_key()]), Tag::custom(TagKind::custom("P"), vec![keys.public_key().to_hex()]),
Tag::public_key(target), Tag::public_key(target),
]); ]);
@@ -611,15 +684,15 @@ impl DeviceRegistry {
/// Handle encryption request /// Handle encryption request
fn ask_for_approval(&mut self, event: Event, window: &mut Window, cx: &mut Context<Self>) { fn ask_for_approval(&mut self, event: Event, window: &mut Window, cx: &mut Context<Self>) {
let notification = self.notification(event, cx); // Ignore if there is already a pending request
if self.has_pending_request {
return;
}
self.set_has_pending_request(true, cx);
cx.spawn_in(window, async move |_this, cx| { // Show notification
cx.update(|window, cx| { let notification = self.notification(event, cx);
window.push_notification(notification, cx); window.push_notification(notification, cx);
})
.ok();
})
.detach();
} }
/// Build a notification for the encryption request. /// Build a notification for the encryption request.
@@ -656,13 +729,14 @@ impl DeviceRegistry {
.text_sm() .text_sm()
.child( .child(
div() div()
.font_semibold()
.text_xs() .text_xs()
.text_color(cx.theme().text_muted) .text_color(cx.theme().text_muted)
.child(SharedString::from("Requester:")), .child(SharedString::from("Requester:")),
) )
.child( .child(
div() div()
.h_7() .h_8()
.w_full() .w_full()
.px_2() .px_2()
.rounded(cx.theme().radius) .rounded(cx.theme().radius)
@@ -681,13 +755,14 @@ impl DeviceRegistry {
.text_sm() .text_sm()
.child( .child(
div() div()
.font_semibold()
.text_xs() .text_xs()
.text_color(cx.theme().text_muted) .text_color(cx.theme().text_muted)
.child(SharedString::from("Client:")), .child(SharedString::from("Client:")),
) )
.child( .child(
div() div()
.h_7() .h_8()
.w_full() .w_full()
.px_2() .px_2()
.rounded(cx.theme().radius) .rounded(cx.theme().radius)
@@ -728,10 +803,10 @@ struct DeviceNotification;
/// Verify the author of an event /// Verify the author of an event
async fn verify_author(client: &Client, event: &Event) -> bool { async fn verify_author(client: &Client, event: &Event) -> bool {
if let Some(signer) = client.signer() { if let Some(signer) = client.signer()
if let Ok(public_key) = signer.get_public_key().await { && let Ok(public_key) = signer.get_public_key().await
return public_key == event.pubkey; {
} return public_key == event.pubkey;
} }
false false
} }

View File

@@ -123,16 +123,16 @@ impl Person {
/// Get profile name /// Get profile name
pub fn name(&self) -> SharedString { pub fn name(&self) -> SharedString {
if let Some(display_name) = self.metadata().display_name.as_ref() { if let Some(display_name) = self.metadata().display_name.as_ref()
if !display_name.is_empty() { && !display_name.is_empty()
return SharedString::from(display_name); {
} return SharedString::from(display_name);
} }
if let Some(name) = self.metadata().name.as_ref() { if let Some(name) = self.metadata().name.as_ref()
if !name.is_empty() { && !name.is_empty()
return SharedString::from(name); {
} return SharedString::from(name);
} }
SharedString::from(shorten_pubkey(self.public_key(), 4)) SharedString::from(shorten_pubkey(self.public_key(), 4))

View File

@@ -17,7 +17,7 @@ use state::NostrRegistry;
use theme::ActiveTheme; use theme::ActiveTheme;
use ui::button::{Button, ButtonVariants}; use ui::button::{Button, ButtonVariants};
use ui::notification::Notification; use ui::notification::Notification;
use ui::{Disableable, IconName, Sizable, WindowExtension, v_flex}; use ui::{Disableable, IconName, Sizable, StyledExt, WindowExtension, v_flex};
const AUTH_MESSAGE: &str = const AUTH_MESSAGE: &str =
"Approve the authentication request to allow Coop to continue sending or receiving events."; "Approve the authentication request to allow Coop to continue sending or receiving events.";
@@ -344,8 +344,9 @@ impl RelayAuth {
.px_1p5() .px_1p5()
.rounded_sm() .rounded_sm()
.text_xs() .text_xs()
.font_semibold()
.bg(cx.theme().elevated_surface_background) .bg(cx.theme().elevated_surface_background)
.text_color(cx.theme().text_accent) .text_color(cx.theme().text)
.child(url.clone()), .child(url.clone()),
) )
.into_any_element() .into_any_element()

View File

@@ -11,7 +11,7 @@ nostr.workspace = true
nostr-sdk.workspace = true nostr-sdk.workspace = true
nostr-lmdb.workspace = true nostr-lmdb.workspace = true
nostr-memory.workspace = true nostr-memory.workspace = true
nostr-gossip-sqlite.workspace = true nostr-gossip-memory.workspace = true
nostr-connect.workspace = true nostr-connect.workspace = true
nostr-blossom.workspace = true nostr-blossom.workspace = true

View File

@@ -36,14 +36,16 @@ pub const NOSTR_CONNECT_RELAY: &str = "wss://relay.nip46.com";
/// Default vertex relays /// Default vertex relays
pub const WOT_RELAYS: [&str; 1] = ["wss://relay.vertexlab.io"]; pub const WOT_RELAYS: [&str; 1] = ["wss://relay.vertexlab.io"];
/// Default search relays
pub const INDEXER_RELAYS: [&str; 1] = ["wss://indexer.coracle.social"];
/// Default search relays /// Default search relays
pub const SEARCH_RELAYS: [&str; 2] = ["wss://antiprimal.net", "wss://search.nos.today"]; pub const SEARCH_RELAYS: [&str; 2] = ["wss://antiprimal.net", "wss://search.nos.today"];
/// Default bootstrap relays /// Default bootstrap relays
pub const BOOTSTRAP_RELAYS: [&str; 4] = [ pub const BOOTSTRAP_RELAYS: [&str; 3] = [
"wss://relay.damus.io", "wss://relay.damus.io",
"wss://relay.primal.net", "wss://relay.primal.net",
"wss://indexer.coracle.social",
"wss://user.kindpag.es", "wss://user.kindpag.es",
]; ];

View File

@@ -1,40 +1,6 @@
use std::fmt::Display;
use gpui::SharedString; use gpui::SharedString;
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum DeviceState {
#[default]
Idle,
Requesting,
Set,
}
impl Display for DeviceState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
DeviceState::Idle => write!(f, "Idle"),
DeviceState::Requesting => write!(f, "Wait for approval"),
DeviceState::Set => write!(f, "Encryption Key is ready"),
}
}
}
impl DeviceState {
pub fn idle(&self) -> bool {
matches!(self, DeviceState::Idle)
}
pub fn requesting(&self) -> bool {
matches!(self, DeviceState::Requesting)
}
pub fn set(&self) -> bool {
matches!(self, DeviceState::Set)
}
}
/// Announcement /// Announcement
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Announcement { pub struct Announcement {

View File

@@ -6,7 +6,7 @@ use anyhow::{Context as AnyhowContext, Error, anyhow};
use common::config_dir; use common::config_dir;
use gpui::{App, AppContext, Context, Entity, EventEmitter, Global, SharedString, Task, Window}; use gpui::{App, AppContext, Context, Entity, EventEmitter, Global, SharedString, Task, Window};
use nostr_connect::prelude::*; use nostr_connect::prelude::*;
use nostr_gossip_sqlite::prelude::*; use nostr_gossip_memory::prelude::*;
use nostr_lmdb::prelude::*; use nostr_lmdb::prelude::*;
use nostr_memory::prelude::*; use nostr_memory::prelude::*;
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;
@@ -44,10 +44,14 @@ impl Global for GlobalNostrRegistry {}
/// Signer event. /// Signer event.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum StateEvent { pub enum StateEvent {
/// Creating the signer
Creating,
/// Connecting to the bootstrapping relay /// Connecting to the bootstrapping relay
Connecting, Connecting,
/// Connected to the bootstrapping relay /// Connected to the bootstrapping relay
Connected, Connected,
/// Fetching the relay list
FetchingRelayList,
/// User has not set up NIP-65 relays /// User has not set up NIP-65 relays
RelayNotConfigured, RelayNotConfigured,
/// Connected to NIP-65 relays /// Connected to NIP-65 relays
@@ -58,6 +62,15 @@ pub enum StateEvent {
Error(SharedString), Error(SharedString),
} }
impl StateEvent {
pub fn error<T>(error: T) -> Self
where
T: Into<SharedString>,
{
Self::Error(error.into())
}
}
/// Nostr Registry /// Nostr Registry
#[derive(Debug)] #[derive(Debug)]
pub struct NostrRegistry { pub struct NostrRegistry {
@@ -101,20 +114,19 @@ impl NostrRegistry {
// Construct the nostr npubs entity // Construct the nostr npubs entity
let npubs = cx.new(|_| vec![]); let npubs = cx.new(|_| vec![]);
// Construct the nostr gossip instance
let gossip = cx.foreground_executor().block_on(async move {
NostrGossipSqlite::open(config_dir().join("gossip"))
.await
.expect("Failed to initialize gossip instance")
});
// Construct the nostr client builder // Construct the nostr client builder
let mut builder = ClientBuilder::default() let mut builder = ClientBuilder::default()
.signer(signer.clone()) .signer(signer.clone())
.gossip(gossip) .gossip(NostrGossipMemory::unbounded())
.gossip_config(
GossipConfig::default()
.no_background_refresh()
.sync_idle_timeout(Duration::from_secs(TIMEOUT))
.sync_initial_timeout(Duration::from_millis(600)),
)
.automatic_authentication(false) .automatic_authentication(false)
.verify_subscriptions(false) .verify_subscriptions(false)
.connect_timeout(Duration::from_secs(TIMEOUT)) .connect_timeout(Duration::from_secs(10))
.sleep_when_idle(SleepWhenIdle::Enabled { .sleep_when_idle(SleepWhenIdle::Enabled {
timeout: Duration::from_secs(600), timeout: Duration::from_secs(600),
}); });
@@ -176,7 +188,18 @@ impl NostrRegistry {
let task: Task<Result<(), Error>> = cx.background_spawn(async move { let task: Task<Result<(), Error>> = cx.background_spawn(async move {
// Add search relay to the relay pool // Add search relay to the relay pool
for url in SEARCH_RELAYS.into_iter() { for url in SEARCH_RELAYS.into_iter() {
client.add_relay(url).await?; client
.add_relay(url)
.capabilities(RelayCapabilities::READ)
.await?;
}
// Add indexer relay to the relay pool
for url in INDEXER_RELAYS.into_iter() {
client
.add_relay(url)
.capabilities(RelayCapabilities::DISCOVERY)
.await?;
} }
// Add bootstrap relay to the relay pool // Add bootstrap relay to the relay pool
@@ -185,7 +208,10 @@ impl NostrRegistry {
} }
// Connect to all added relays // Connect to all added relays
client.connect().await; client
.connect()
.and_wait(Duration::from_secs(TIMEOUT))
.await;
Ok(()) Ok(())
}); });
@@ -204,7 +230,7 @@ impl NostrRegistry {
} }
Err(e) => { Err(e) => {
this.update(cx, |_this, cx| { this.update(cx, |_this, cx| {
cx.emit(StateEvent::Error(SharedString::from(e.to_string()))); cx.emit(StateEvent::error(e.to_string()));
}) })
.ok(); .ok();
} }
@@ -269,7 +295,7 @@ impl NostrRegistry {
}, },
Err(e) => { Err(e) => {
this.update(cx, |_this, cx| { this.update(cx, |_this, cx| {
cx.emit(StateEvent::Error(SharedString::from(e.to_string()))); cx.emit(StateEvent::error(e.to_string()));
}) })
.ok(); .ok();
} }
@@ -289,6 +315,9 @@ impl NostrRegistry {
// Create a write credential task // Create a write credential task
let write_credential = cx.write_credentials(&username, &username, &secret); let write_credential = cx.write_credentials(&username, &username, &secret);
// Emit creating event
cx.emit(StateEvent::Creating);
// Run async tasks in background // Run async tasks in background
let task: Task<Result<(), Error>> = cx.background_spawn(async move { let task: Task<Result<(), Error>> = cx.background_spawn(async move {
let signer = async_keys.into_nostr_signer(); let signer = async_keys.into_nostr_signer();
@@ -301,7 +330,7 @@ impl NostrRegistry {
client client
.send_event(&event) .send_event(&event)
.to(BOOTSTRAP_RELAYS) .to(BOOTSTRAP_RELAYS)
.ok_timeout(Duration::from_secs(TIMEOUT)) .ack_policy(AckPolicy::none())
.await?; .await?;
// Construct the default metadata // Construct the default metadata
@@ -355,7 +384,7 @@ impl NostrRegistry {
} }
Err(e) => { Err(e) => {
this.update(cx, |_this, cx| { this.update(cx, |_this, cx| {
cx.emit(StateEvent::Error(SharedString::from(e.to_string()))); cx.emit(StateEvent::error(e.to_string()));
}) })
.ok(); .ok();
} }
@@ -453,7 +482,7 @@ impl NostrRegistry {
} }
Err(e) => { Err(e) => {
this.update(cx, |_this, cx| { this.update(cx, |_this, cx| {
cx.emit(StateEvent::Error(SharedString::from(e.to_string()))); cx.emit(StateEvent::error(e.to_string()));
}) })
.ok(); .ok();
} }
@@ -500,7 +529,7 @@ impl NostrRegistry {
} }
Err(e) => { Err(e) => {
this.update(cx, |_this, cx| { this.update(cx, |_this, cx| {
cx.emit(StateEvent::Error(SharedString::from(e.to_string()))); cx.emit(StateEvent::error(e.to_string()));
}) })
.ok(); .ok();
} }
@@ -545,7 +574,7 @@ impl NostrRegistry {
} }
Err(e) => { Err(e) => {
this.update(cx, |_this, cx| { this.update(cx, |_this, cx| {
cx.emit(StateEvent::Error(SharedString::from(e.to_string()))); cx.emit(StateEvent::error(e.to_string()));
}) })
.ok(); .ok();
} }
@@ -553,7 +582,7 @@ impl NostrRegistry {
} }
Err(e) => { Err(e) => {
this.update(cx, |_this, cx| { this.update(cx, |_this, cx| {
cx.emit(StateEvent::Error(SharedString::from(e.to_string()))); cx.emit(StateEvent::error(e.to_string()));
}) })
.ok(); .ok();
} }
@@ -561,9 +590,72 @@ impl NostrRegistry {
})); }));
} }
/// Ensure the relay list is fetched for the given public key
pub fn ensure_relay_list(&mut self, public_key: &PublicKey, cx: &mut Context<Self>) { pub fn ensure_relay_list(&mut self, public_key: &PublicKey, cx: &mut Context<Self>) {
let task = self.get_event(public_key, Kind::RelayList, cx); let task = self.get_event(public_key, Kind::RelayList, cx);
// Emit a fetching event before starting the task
cx.emit(StateEvent::FetchingRelayList);
self.tasks.push(cx.spawn(async move |this, cx| {
match task.await {
Ok(event) => {
this.update(cx, |this, cx| {
this.ensure_connection(&event, cx);
})
.ok();
}
Err(e) => {
this.update(cx, |_this, cx| {
cx.emit(StateEvent::RelayNotConfigured);
cx.emit(StateEvent::error(e.to_string()));
})
.ok();
}
};
}));
}
/// Ensure that the user is connected to the relay specified in the NIP-65 event.
pub fn ensure_connection(&mut self, event: &Event, cx: &mut Context<Self>) {
let client = self.client();
// Extract the relay list from the event
let relays: Vec<(RelayUrl, Option<RelayMetadata>)> = nip65::extract_relay_list(event)
.map(|(url, metadata)| (url.to_owned(), metadata.to_owned()))
.collect();
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
for (url, metadata) in relays.into_iter() {
match metadata {
Some(RelayMetadata::Read) => {
client
.add_relay(url)
.capabilities(RelayCapabilities::READ)
.connect_timeout(Duration::from_secs(TIMEOUT))
.and_connect()
.await?;
}
Some(RelayMetadata::Write) => {
client
.add_relay(url)
.capabilities(RelayCapabilities::WRITE)
.connect_timeout(Duration::from_secs(TIMEOUT))
.and_connect()
.await?;
}
None => {
client
.add_relay(url)
.capabilities(RelayCapabilities::NONE)
.connect_timeout(Duration::from_secs(TIMEOUT))
.and_connect()
.await?;
}
}
}
Ok(())
});
self.tasks.push(cx.spawn(async move |this, cx| { self.tasks.push(cx.spawn(async move |this, cx| {
match task.await { match task.await {
Ok(_) => { Ok(_) => {
@@ -575,7 +667,7 @@ impl NostrRegistry {
Err(e) => { Err(e) => {
this.update(cx, |_this, cx| { this.update(cx, |_this, cx| {
cx.emit(StateEvent::RelayNotConfigured); cx.emit(StateEvent::RelayNotConfigured);
cx.emit(StateEvent::Error(SharedString::from(e.to_string()))); cx.emit(StateEvent::error(e.to_string()));
}) })
.ok(); .ok();
} }
@@ -657,11 +749,11 @@ impl NostrRegistry {
let mut results: Vec<PublicKey> = Vec::with_capacity(FIND_LIMIT); let mut results: Vec<PublicKey> = Vec::with_capacity(FIND_LIMIT);
// Return early if the query is a valid NIP-05 address // Return early if the query is a valid NIP-05 address
if let Some(task) = address_task { if let Some(task) = address_task
if let Ok(public_key) = task.await { && let Ok(public_key) = task.await
results.push(public_key); {
return Ok(results); results.push(public_key);
} return Ok(results);
} }
// Return early if the query is a valid public key // Return early if the query is a valid public key

View File

@@ -271,22 +271,22 @@ impl Dock {
let mut right_dock_size = px(0.0); let mut right_dock_size = px(0.0);
// Get the size of the left dock if it's open and not the current dock // Get the size of the left dock if it's open and not the current dock
if let Some(left_dock) = &dock_area.left_dock { if let Some(left_dock) = &dock_area.left_dock
if left_dock.entity_id() != cx.entity().entity_id() { && left_dock.entity_id() != cx.entity().entity_id()
let left_dock_read = left_dock.read(cx); {
if left_dock_read.is_open() { let left_dock_read = left_dock.read(cx);
left_dock_size = left_dock_read.size; if left_dock_read.is_open() {
} left_dock_size = left_dock_read.size;
} }
} }
// Get the size of the right dock if it's open and not the current dock // Get the size of the right dock if it's open and not the current dock
if let Some(right_dock) = &dock_area.right_dock { if let Some(right_dock) = &dock_area.right_dock
if right_dock.entity_id() != cx.entity().entity_id() { && right_dock.entity_id() != cx.entity().entity_id()
let right_dock_read = right_dock.read(cx); {
if right_dock_read.is_open() { let right_dock_read = right_dock.read(cx);
right_dock_size = right_dock_read.size; if right_dock_read.is_open() {
} right_dock_size = right_dock_read.size;
} }
} }

View File

@@ -70,10 +70,10 @@ impl StackPanel {
return false; return false;
} }
if let Some(parent) = &self.parent { if let Some(parent) = &self.parent
if let Some(parent) = parent.upgrade() { && let Some(parent) = parent.upgrade()
return parent.read(cx).is_last_panel(cx); {
} return parent.read(cx).is_last_panel(cx);
} }
true true
@@ -297,12 +297,11 @@ impl StackPanel {
/// Find the first top left in the stack. /// Find the first top left in the stack.
pub fn left_top_tab_panel(&self, check_parent: bool, cx: &App) -> Option<Entity<TabPanel>> { pub fn left_top_tab_panel(&self, check_parent: bool, cx: &App) -> Option<Entity<TabPanel>> {
if check_parent { if check_parent
if let Some(parent) = self.parent.as_ref().and_then(|parent| parent.upgrade()) { && let Some(parent) = self.parent.as_ref().and_then(|parent| parent.upgrade())
if let Some(panel) = parent.read(cx).left_top_tab_panel(true, cx) { && let Some(panel) = parent.read(cx).left_top_tab_panel(true, cx)
return Some(panel); {
} return Some(panel);
}
} }
let first_panel = self.panels.first(); let first_panel = self.panels.first();
@@ -321,12 +320,11 @@ impl StackPanel {
/// Find the first top right in the stack. /// Find the first top right in the stack.
pub fn right_top_tab_panel(&self, check_parent: bool, cx: &App) -> Option<Entity<TabPanel>> { pub fn right_top_tab_panel(&self, check_parent: bool, cx: &App) -> Option<Entity<TabPanel>> {
if check_parent { if check_parent
if let Some(parent) = self.parent.as_ref().and_then(|parent| parent.upgrade()) { && let Some(parent) = self.parent.as_ref().and_then(|parent| parent.upgrade())
if let Some(panel) = parent.read(cx).right_top_tab_panel(true, cx) { && let Some(panel) = parent.read(cx).right_top_tab_panel(true, cx)
return Some(panel); {
} return Some(panel);
}
} }
let panel = if self.axis.is_vertical() { let panel = if self.axis.is_vertical() {

View File

@@ -232,14 +232,13 @@ impl TabPanel {
.any(|p| p.panel_id(cx) == panel.panel_id(cx)) .any(|p| p.panel_id(cx) == panel.panel_id(cx))
{ {
// Set the active panel to the matched panel // Set the active panel to the matched panel
if active { if active
if let Some(ix) = self && let Some(ix) = self
.panels .panels
.iter() .iter()
.position(|p| p.panel_id(cx) == panel.panel_id(cx)) .position(|p| p.panel_id(cx) == panel.panel_id(cx))
{ {
self.set_active_ix(ix, window, cx); self.set_active_ix(ix, window, cx);
}
} }
return; return;
@@ -372,12 +371,11 @@ impl TabPanel {
/// Return true if self or parent only have last panel. /// Return true if self or parent only have last panel.
fn is_last_panel(&self, cx: &App) -> bool { fn is_last_panel(&self, cx: &App) -> bool {
if let Some(parent) = &self.stack_panel { if let Some(parent) = &self.stack_panel
if let Some(stack_panel) = parent.upgrade() { && let Some(stack_panel) = parent.upgrade()
if !stack_panel.read(cx).is_last_panel(cx) { && !stack_panel.read(cx).is_last_panel(cx)
return false; {
} return false;
}
} }
self.panels.len() <= 1 self.panels.len() <= 1
@@ -1103,10 +1101,10 @@ impl TabPanel {
window: &mut Window, window: &mut Window,
cx: &mut Context<Self>, cx: &mut Context<Self>,
) { ) {
if self.panels.len() > 1 { if self.panels.len() > 1
if let Some(panel) = self.active_panel(cx) { && let Some(panel) = self.active_panel(cx)
self.remove_panel(&panel, window, cx); {
} self.remove_panel(&panel, window, cx);
} }
} }
} }

View File

@@ -2,10 +2,10 @@ use std::ops::Range;
use std::rc::Rc; use std::rc::Rc;
use gpui::{ use gpui::{
fill, point, px, relative, size, App, Bounds, Corners, Element, ElementId, ElementInputHandler, App, Bounds, Corners, Element, ElementId, ElementInputHandler, Entity, GlobalElementId, Hitbox,
Entity, GlobalElementId, Hitbox, IntoElement, LayoutId, MouseButton, MouseMoveEvent, Path, IntoElement, LayoutId, MouseButton, MouseMoveEvent, Path, Pixels, Point, ShapedLine,
Pixels, Point, ShapedLine, SharedString, Size, Style, TextAlign, TextRun, UnderlineStyle, SharedString, Size, Style, TextAlign, TextRun, UnderlineStyle, Window, fill, point, px,
Window, relative, size,
}; };
use rope::Rope; use rope::Rope;
use smallvec::SmallVec; use smallvec::SmallVec;
@@ -348,10 +348,10 @@ impl TextElement {
let mut rev_line_corners = line_corners.iter().rev().peekable(); let mut rev_line_corners = line_corners.iter().rev().peekable();
while let Some(corners) = rev_line_corners.next() { while let Some(corners) = rev_line_corners.next() {
points.push(corners.top_left); points.push(corners.top_left);
if let Some(next) = rev_line_corners.peek() { if let Some(next) = rev_line_corners.peek()
if next.top_left.x > corners.top_left.x { && next.top_left.x > corners.top_left.x
points.push(point(next.top_left.x, corners.top_left.y)); {
} points.push(point(next.top_left.x, corners.top_left.y));
} }
} }
@@ -376,10 +376,10 @@ impl TextElement {
) -> Option<Path<Pixels>> { ) -> Option<Path<Pixels>> {
let state = self.state.read(cx); let state = self.state.read(cx);
let mut selected_range = state.selected_range; let mut selected_range = state.selected_range;
if let Some(ime_marked_range) = &state.ime_marked_range { if let Some(ime_marked_range) = &state.ime_marked_range
if !ime_marked_range.is_empty() { && !ime_marked_range.is_empty()
selected_range = (ime_marked_range.end..ime_marked_range.end).into(); {
} selected_range = (ime_marked_range.end..ime_marked_range.end).into();
} }
if selected_range.is_empty() { if selected_range.is_empty() {
return None; return None;
@@ -830,11 +830,12 @@ impl Element for TextElement {
} }
// Paint blinking cursor // Paint blinking cursor
if focused && show_cursor { if focused
if let Some(mut cursor_bounds) = prepaint.cursor_bounds.take() { && show_cursor
cursor_bounds.origin.y += prepaint.cursor_scroll_offset.y; && let Some(mut cursor_bounds) = prepaint.cursor_bounds.take()
window.paint_quad(fill(cursor_bounds, cx.theme().cursor)); {
} cursor_bounds.origin.y += prepaint.cursor_scroll_offset.y;
window.paint_quad(fill(cursor_bounds, cx.theme().cursor));
} }
// Paint line numbers // Paint line numbers

View File

@@ -225,13 +225,12 @@ impl MaskPattern {
} }
// check if the fraction part is valid // check if the fraction part is valid
if let Some(frac) = frac_part { if let Some(frac) = frac_part
if !frac && !frac
.chars() .chars()
.all(|ch| ch.is_ascii_digit() || Some(ch) == *separator) .all(|ch| ch.is_ascii_digit() || Some(ch) == *separator)
{ {
return false; return false;
}
} }
true true
@@ -255,10 +254,10 @@ impl MaskPattern {
if token.is_sep() { if token.is_sep() {
// If next token is match, it's valid // If next token is match, it's valid
if let Some(next_token) = tokens.get(pos + 1) { if let Some(next_token) = tokens.get(pos + 1)
if next_token.is_match(ch) { && next_token.is_match(ch)
return true; {
} return true;
} }
} }
} }

View File

@@ -4,11 +4,11 @@ use std::time::Duration;
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
actions, div, point, px, Action, App, AppContext, Bounds, ClipboardItem, Context, Entity, Action, App, AppContext, Bounds, ClipboardItem, Context, Entity, EntityInputHandler,
EntityInputHandler, EventEmitter, FocusHandle, Focusable, InteractiveElement as _, IntoElement, EventEmitter, FocusHandle, Focusable, InteractiveElement as _, IntoElement, KeyBinding,
KeyBinding, KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement as _,
ParentElement as _, Pixels, Point, Render, ScrollHandle, ScrollWheelEvent, SharedString, Pixels, Point, Render, ScrollHandle, ScrollWheelEvent, SharedString, Styled as _, Subscription,
Styled as _, Subscription, UTF16Selection, Window, WrappedLine, UTF16Selection, Window, WrappedLine, actions, div, point, px,
}; };
use lsp_types::Position; use lsp_types::Position;
use rope::{OffsetUtf16, Rope}; use rope::{OffsetUtf16, Rope};
@@ -25,9 +25,9 @@ use super::mask_pattern::MaskPattern;
use super::mode::{InputMode, TabSize}; use super::mode::{InputMode, TabSize};
use super::rope_ext::RopeExt; use super::rope_ext::RopeExt;
use super::text_wrapper::{LineItem, TextWrapper}; use super::text_wrapper::{LineItem, TextWrapper};
use crate::Root;
use crate::history::History; use crate::history::History;
use crate::input::element::RIGHT_MARGIN; use crate::input::element::RIGHT_MARGIN;
use crate::Root;
#[derive(Action, Clone, PartialEq, Eq, Deserialize)] #[derive(Action, Clone, PartialEq, Eq, Deserialize)]
#[action(namespace = input, no_json)] #[action(namespace = input, no_json)]
@@ -521,16 +521,16 @@ impl InputState {
let new_row = new_row as usize; let new_row = new_row as usize;
if new_row >= last_layout.visible_range.start { if new_row >= last_layout.visible_range.start {
let visible_row = new_row.saturating_sub(last_layout.visible_range.start); let visible_row = new_row.saturating_sub(last_layout.visible_range.start);
if let Some(line) = last_layout.lines.get(visible_row) { if let Some(line) = last_layout.lines.get(visible_row)
if let Ok(x) = line.closest_index_for_position( && let Ok(x) = line.closest_index_for_position(
Point { Point {
x: preferred_x, x: preferred_x,
y: px(0.), y: px(0.),
}, },
last_layout.line_height, last_layout.line_height,
) { )
new_offset = line_start_offset + x; {
} new_offset = line_start_offset + x;
} }
} }
} }
@@ -1355,10 +1355,10 @@ impl InputState {
) { ) {
// If there have IME marked range and is empty (Means pressed Esc to abort IME typing) // If there have IME marked range and is empty (Means pressed Esc to abort IME typing)
// Clear the marked range. // Clear the marked range.
if let Some(ime_marked_range) = &self.ime_marked_range { if let Some(ime_marked_range) = &self.ime_marked_range
if ime_marked_range.is_empty() { && ime_marked_range.is_empty()
self.ime_marked_range = None; {
} self.ime_marked_range = None;
} }
self.selecting = true; self.selecting = true;
@@ -1842,23 +1842,21 @@ impl InputState {
fn previous_boundary(&self, offset: usize) -> usize { fn previous_boundary(&self, offset: usize) -> usize {
let mut offset = self.text.clip_offset(offset.saturating_sub(1), Bias::Left); let mut offset = self.text.clip_offset(offset.saturating_sub(1), Bias::Left);
if let Some(ch) = self.text.char_at(offset) { if let Some(ch) = self.text.char_at(offset)
if ch == '\r' { && ch == '\r'
offset -= 1; {
} offset -= 1;
} }
offset offset
} }
fn next_boundary(&self, offset: usize) -> usize { fn next_boundary(&self, offset: usize) -> usize {
let mut offset = self.text.clip_offset(offset + 1, Bias::Right); let mut offset = self.text.clip_offset(offset + 1, Bias::Right);
if let Some(ch) = self.text.char_at(offset) { if let Some(ch) = self.text.char_at(offset)
if ch == '\r' { && ch == '\r'
offset += 1; {
} offset += 1;
} }
offset offset
} }
@@ -1927,10 +1925,10 @@ impl InputState {
return true; return true;
} }
if let Some(validate) = &self.validate { if let Some(validate) = &self.validate
if !validate(new_text, cx) { && !validate(new_text, cx)
return false; {
} return false;
} }
if !self.mask_pattern.is_valid(new_text) { if !self.mask_pattern.is_valid(new_text) {
@@ -1979,19 +1977,19 @@ impl InputState {
self.input_bounds = new_bounds; self.input_bounds = new_bounds;
// Update text_wrapper wrap_width if changed. // Update text_wrapper wrap_width if changed.
if let Some(last_layout) = self.last_layout.as_ref() { if let Some(last_layout) = self.last_layout.as_ref()
if wrap_width_changed { && wrap_width_changed
let wrap_width = if !self.soft_wrap { {
// None to disable wrapping (will use Pixels::MAX) let wrap_width = if !self.soft_wrap {
None // None to disable wrapping (will use Pixels::MAX)
} else { None
last_layout.wrap_width } else {
}; last_layout.wrap_width
};
self.text_wrapper.set_wrap_width(wrap_width, cx); self.text_wrapper.set_wrap_width(wrap_width, cx);
self.mode.update_auto_grow(&self.text_wrapper); self.mode.update_auto_grow(&self.text_wrapper);
cx.notify(); cx.notify();
}
} }
} }
@@ -2209,20 +2207,18 @@ impl EntityInputHandler for InputState {
break; break;
} }
if start_origin.is_none() { if start_origin.is_none()
if let Some(p) = && let Some(p) =
line.position_for_index(range.start.saturating_sub(index_offset), line_height) line.position_for_index(range.start.saturating_sub(index_offset), line_height)
{ {
start_origin = Some(p + point(px(0.), y_offset)); start_origin = Some(p + point(px(0.), y_offset));
}
} }
if end_origin.is_none() { if end_origin.is_none()
if let Some(p) = && let Some(p) =
line.position_for_index(range.end.saturating_sub(index_offset), line_height) line.position_for_index(range.end.saturating_sub(index_offset), line_height)
{ {
end_origin = Some(p + point(px(0.), y_offset)); end_origin = Some(p + point(px(0.), y_offset));
}
} }
index_offset += line.len() + 1; index_offset += line.len() + 1;

View File

@@ -3,21 +3,21 @@ use std::time::Duration;
use gpui::prelude::FluentBuilder; use gpui::prelude::FluentBuilder;
use gpui::{ use gpui::{
div, px, size, uniform_list, App, AppContext, AvailableSpace, ClickEvent, Context, App, AppContext, AvailableSpace, ClickEvent, Context, DefiniteLength, EdgesRefinement, Entity,
DefiniteLength, EdgesRefinement, Entity, EventEmitter, FocusHandle, Focusable, EventEmitter, FocusHandle, Focusable, InteractiveElement, IntoElement, KeyBinding, Length,
InteractiveElement, IntoElement, KeyBinding, Length, ListSizingBehavior, MouseButton, ListSizingBehavior, MouseButton, ParentElement, Render, RenderOnce, ScrollStrategy,
ParentElement, Render, RenderOnce, ScrollStrategy, SharedString, StatefulInteractiveElement, SharedString, StatefulInteractiveElement, StyleRefinement, Styled, Subscription, Task,
StyleRefinement, Styled, Subscription, Task, UniformListScrollHandle, Window, UniformListScrollHandle, Window, div, px, size, uniform_list,
}; };
use smol::Timer; use smol::Timer;
use theme::ActiveTheme; use theme::ActiveTheme;
use crate::actions::{Cancel, Confirm, SelectDown, SelectUp}; use crate::actions::{Cancel, Confirm, SelectDown, SelectUp};
use crate::input::{InputEvent, InputState, TextInput}; use crate::input::{InputEvent, InputState, TextInput};
use crate::list::cache::{MeasuredEntrySize, RowEntry, RowsCache};
use crate::list::ListDelegate; use crate::list::ListDelegate;
use crate::list::cache::{MeasuredEntrySize, RowEntry, RowsCache};
use crate::scroll::{Scrollbar, ScrollbarHandle}; use crate::scroll::{Scrollbar, ScrollbarHandle};
use crate::{v_flex, Icon, IconName, IndexPath, Selectable, Sizable, Size, StyledExt}; use crate::{Icon, IconName, IndexPath, Selectable, Sizable, Size, StyledExt, v_flex};
pub(crate) fn init(cx: &mut App) { pub(crate) fn init(cx: &mut App) {
let context: Option<&str> = Some("List"); let context: Option<&str> = Some("List");
@@ -578,10 +578,10 @@ where
self.prepare_items_if_needed(window, cx); self.prepare_items_if_needed(window, cx);
// Scroll to the selected item if it is set. // Scroll to the selected item if it is set.
if let Some((ix, strategy)) = self.deferred_scroll_to_index.take() { if let Some((ix, strategy)) = self.deferred_scroll_to_index.take()
if let Some(item_ix) = self.rows_cache.position_of(&ix) { && let Some(item_ix) = self.rows_cache.position_of(&ix)
self.scroll_handle.scroll_to_item(item_ix, strategy); {
} self.scroll_handle.scroll_to_item(item_ix, strategy);
} }
let loading = self.delegate().loading(cx); let loading = self.delegate().loading(cx);

View File

@@ -719,13 +719,13 @@ impl PopupMenu {
} }
pub(crate) fn active_submenu(&self) -> Option<Entity<PopupMenu>> { pub(crate) fn active_submenu(&self) -> Option<Entity<PopupMenu>> {
if let Some(ix) = self.selected_index { if let Some(ix) = self.selected_index
if let Some(item) = self.menu_items.get(ix) { && let Some(item) = self.menu_items.get(ix)
return match item { {
PopupMenuItem::Submenu { menu, .. } => Some(menu.clone()), return match item {
_ => None, PopupMenuItem::Submenu { menu, .. } => Some(menu.clone()),
}; _ => None,
} };
} }
None None
@@ -965,12 +965,11 @@ impl PopupMenu {
cx: &mut Context<Self>, cx: &mut Context<Self>,
) { ) {
// Do not dismiss, if click inside the parent menu // Do not dismiss, if click inside the parent menu
if let Some(parent) = self.parent_menu.as_ref() { if let Some(parent) = self.parent_menu.as_ref()
if let Some(parent) = parent.upgrade() { && let Some(parent) = parent.upgrade()
if parent.read(cx).bounds.contains(position) { && parent.read(cx).bounds.contains(position)
return; {
} return;
}
} }
self.dismiss(&Cancel, window, cx); self.dismiss(&Cancel, window, cx);

View File

@@ -296,10 +296,10 @@ impl RenderOnce for Modal {
let on_close = on_close.clone(); let on_close = on_close.clone();
move |_, window, cx| { move |_, window, cx| {
if let Some(on_ok) = &on_ok { if let Some(on_ok) = &on_ok
if !on_ok(&ClickEvent::default(), window, cx) { && !on_ok(&ClickEvent::default(), window, cx)
return; {
} return;
} }
on_close(&ClickEvent::default(), window, cx); on_close(&ClickEvent::default(), window, cx);

View File

@@ -14,7 +14,7 @@ use theme::{ActiveTheme, Anchor};
use crate::animation::cubic_bezier; use crate::animation::cubic_bezier;
use crate::button::{Button, ButtonVariants as _}; use crate::button::{Button, ButtonVariants as _};
use crate::{Icon, IconName, Sizable as _, StyledExt, h_flex, v_flex}; use crate::{Icon, IconName, Sizable as _, Size, StyledExt, h_flex, v_flex};
#[derive(Debug, Clone, Copy, Default)] #[derive(Debug, Clone, Copy, Default)]
pub enum NotificationKind { pub enum NotificationKind {
@@ -28,12 +28,18 @@ pub enum NotificationKind {
impl NotificationKind { impl NotificationKind {
fn icon(&self, cx: &App) -> Icon { fn icon(&self, cx: &App) -> Icon {
match self { match self {
Self::Info => Icon::new(IconName::Info).text_color(cx.theme().icon), Self::Info => Icon::new(IconName::Info)
Self::Success => Icon::new(IconName::CheckCircle).text_color(cx.theme().icon_accent), .with_size(Size::Medium)
Self::Warning => Icon::new(IconName::Warning).text_color(cx.theme().text_warning), .text_color(cx.theme().icon),
Self::Error => { Self::Success => Icon::new(IconName::CheckCircle)
Icon::new(IconName::CloseCircle).text_color(cx.theme().danger_foreground) .with_size(Size::Medium)
} .text_color(cx.theme().icon_accent),
Self::Warning => Icon::new(IconName::Warning)
.with_size(Size::Medium)
.text_color(cx.theme().text_warning),
Self::Error => Icon::new(IconName::CloseCircle)
.with_size(Size::Medium)
.text_color(cx.theme().danger_foreground),
} }
} }
} }
@@ -284,9 +290,6 @@ impl Styled for Notification {
} }
impl Render for Notification { impl Render for Notification {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let closing = self.closing;
let placement = cx.theme().notification.placement;
let content = self let content = self
.content_builder .content_builder
.clone() .clone()
@@ -312,6 +315,11 @@ impl Render for Notification {
_ => cx.theme().text, _ => cx.theme().text,
}; };
let closing = self.closing;
let has_title = self.title.is_some();
let only_message = !has_title && content.is_none() && action.is_none();
let placement = cx.theme().notification.placement;
h_flex() h_flex()
.id("notification") .id("notification")
.group("") .group("")
@@ -328,23 +336,38 @@ impl Render for Notification {
.gap_2() .gap_2()
.justify_start() .justify_start()
.items_start() .items_start()
.when(only_message, |this| this.items_center())
.refine_style(&self.style) .refine_style(&self.style)
.when_some(icon, |this, icon| { .when_some(icon, |this, icon| {
this.child(div().flex_shrink_0().child(icon)) this.child(div().flex_shrink_0().size_5().child(icon))
}) })
.child( .child(
v_flex() v_flex()
.flex_1() .flex_1()
.gap_1()
.overflow_hidden() .overflow_hidden()
.when_some(self.title.clone(), |this, title| { .when_some(self.title.clone(), |this, title| {
this.child(div().text_sm().font_semibold().child(title)) this.child(h_flex().h_5().text_sm().font_semibold().child(title))
}) })
.when_some(self.message.clone(), |this, message| { .when_some(self.message.clone(), |this, message| {
this.child(div().text_sm().line_height(relative(1.25)).child(message)) this.child(
div()
.text_sm()
.when(has_title, |this| this.text_color(cx.theme().text_muted))
.line_height(relative(1.3))
.child(message),
)
}) })
.when_some(content, |this, content| this.child(content)) .when_some(content, |this, content| this.child(content))
.when_some(action, |this, action| { .when_some(action, |this, action| {
this.child(h_flex().flex_1().gap_1().justify_end().child(action)) this.child(
h_flex()
.w_full()
.flex_1()
.gap_1()
.justify_end()
.child(action),
)
}), }),
) )
.child( .child(

View File

@@ -1,7 +1,7 @@
use std::ops::Range; use std::ops::Range;
use gpui::{ use gpui::{
px, Along, App, Axis, Bounds, Context, ElementId, EventEmitter, IsZero, Pixels, Window, Along, App, Axis, Bounds, Context, ElementId, EventEmitter, IsZero, Pixels, Window, px,
}; };
mod panel; mod panel;
@@ -142,10 +142,10 @@ impl ResizableState {
pub(crate) fn remove_panel(&mut self, panel_ix: usize, cx: &mut Context<Self>) { pub(crate) fn remove_panel(&mut self, panel_ix: usize, cx: &mut Context<Self>) {
self.panels.remove(panel_ix); self.panels.remove(panel_ix);
self.sizes.remove(panel_ix); self.sizes.remove(panel_ix);
if let Some(resizing_panel_ix) = self.resizing_panel_ix { if let Some(resizing_panel_ix) = self.resizing_panel_ix
if resizing_panel_ix > panel_ix { && resizing_panel_ix > panel_ix
self.resizing_panel_ix = Some(resizing_panel_ix - 1); {
} self.resizing_panel_ix = Some(resizing_panel_ix - 1);
} }
self.adjust_to_container_size(cx); self.adjust_to_container_size(cx);
} }

View File

@@ -92,7 +92,7 @@ impl Root {
pub fn render_notification_layer( pub fn render_notification_layer(
window: &mut Window, window: &mut Window,
cx: &mut App, cx: &mut App,
) -> Option<impl IntoElement> { ) -> Option<impl IntoElement + use<>> {
let root = window.root::<Root>()??; let root = window.root::<Root>()??;
Some( Some(
@@ -105,7 +105,10 @@ impl Root {
} }
/// Render the modal layer. /// Render the modal layer.
pub fn render_modal_layer(window: &mut Window, cx: &mut App) -> Option<impl IntoElement> { pub fn render_modal_layer(
window: &mut Window,
cx: &mut App,
) -> Option<impl IntoElement + use<>> {
let root = window.root::<Root>()??; let root = window.root::<Root>()??;
let active_modals = root.read(cx).active_modals.clone(); let active_modals = root.read(cx).active_modals.clone();
@@ -139,10 +142,10 @@ impl Root {
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
if let Some(ix) = show_overlay_ix { if let Some(ix) = show_overlay_ix
if let Some(modal) = modals.get_mut(ix) { && let Some(modal) = modals.get_mut(ix)
modal.overlay_visible = true; {
} modal.overlay_visible = true;
} }
Some(div().children(modals)) Some(div().children(modals))