Compare commits
15 Commits
7b27a7e864
...
v1.0.0-bet
| Author | SHA1 | Date | |
|---|---|---|---|
| 2e451aae12 | |||
| cdfcfdd782 | |||
| 9817dd29a6 | |||
| f066cb8223 | |||
| 6d60726f27 | |||
| 80186a79e5 | |||
|
|
cffcb4711d | ||
|
|
44484d9992 | ||
|
|
15ac8d6775 | ||
|
|
6f0cefed33 | ||
|
|
c239e351b8 | ||
|
|
9ff18aae35 | ||
|
|
6fef2ae1c6 | ||
|
|
c2a723faa8 | ||
|
|
6b872527ad |
10
.github/workflows/release.yml
vendored
@@ -45,7 +45,7 @@ jobs:
|
|||||||
# Windows and macOS builds using cargo-packager
|
# Windows and macOS builds using cargo-packager
|
||||||
- name: Build with cargo-packager (Windows/macOS)
|
- name: Build with cargo-packager (Windows/macOS)
|
||||||
if: runner.os != 'Linux'
|
if: runner.os != 'Linux'
|
||||||
working-directory: crates/coop
|
working-directory: desktop
|
||||||
run: |
|
run: |
|
||||||
cargo install cargo-packager --locked
|
cargo install cargo-packager --locked
|
||||||
cargo packager --release
|
cargo packager --release
|
||||||
@@ -154,13 +154,13 @@ jobs:
|
|||||||
|
|
||||||
- name: Create draft release
|
- name: Create draft release
|
||||||
id: create_release
|
id: create_release
|
||||||
uses: softprops/action-gh-release@v2
|
uses: akkuman/gitea-release-action@v1
|
||||||
with:
|
with:
|
||||||
tag_name: ${{ steps.version.outputs.tag }}
|
server_url: "https://git.reya.su/"
|
||||||
name: ${{ steps.version.outputs.tag }}
|
repository: "reya/coop"
|
||||||
|
token: ${{ secrets.GITEA_TOKEN }}
|
||||||
draft: true
|
draft: true
|
||||||
prerelease: false
|
prerelease: false
|
||||||
generate_release_notes: true
|
|
||||||
files: |
|
files: |
|
||||||
artifacts/**/*
|
artifacts/**/*
|
||||||
|
|
||||||
|
|||||||
814
Cargo.lock
generated
@@ -1,10 +1,10 @@
|
|||||||
[workspace]
|
[workspace]
|
||||||
resolver = "2"
|
resolver = "2"
|
||||||
members = ["crates/*"]
|
members = ["crates/*", "desktop", "web"]
|
||||||
default-members = ["crates/coop"]
|
default-members = ["desktop"]
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "1.0.0-beta2"
|
version = "1.0.0-beta4"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
publish = false
|
publish = false
|
||||||
|
|
||||||
@@ -15,13 +15,11 @@ gpui_platform = { git = "https://github.com/zed-industries/zed", features = ["fo
|
|||||||
gpui_linux = { git = "https://github.com/zed-industries/zed" }
|
gpui_linux = { git = "https://github.com/zed-industries/zed" }
|
||||||
gpui_windows = { git = "https://github.com/zed-industries/zed" }
|
gpui_windows = { git = "https://github.com/zed-industries/zed" }
|
||||||
gpui_macos = { git = "https://github.com/zed-industries/zed" }
|
gpui_macos = { git = "https://github.com/zed-industries/zed" }
|
||||||
gpui_web = { git = "https://github.com/zed-industries/zed" }
|
|
||||||
gpui_tokio = { git = "https://github.com/zed-industries/zed" }
|
gpui_tokio = { git = "https://github.com/zed-industries/zed" }
|
||||||
reqwest_client = { git = "https://github.com/zed-industries/zed" }
|
reqwest_client = { git = "https://github.com/zed-industries/zed" }
|
||||||
|
|
||||||
# Nostr
|
# Nostr
|
||||||
nostr-lmdb = { git = "https://github.com/rust-nostr/nostr" }
|
nostr-lmdb = { 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-memory = { git = "https://github.com/rust-nostr/nostr" }
|
nostr-gossip-memory = { git = "https://github.com/rust-nostr/nostr" }
|
||||||
@@ -44,6 +42,7 @@ smallvec = "1.14.0"
|
|||||||
smol = "2"
|
smol = "2"
|
||||||
tracing = "0.1.40"
|
tracing = "0.1.40"
|
||||||
webbrowser = "1.0.4"
|
webbrowser = "1.0.4"
|
||||||
|
tracing-subscriber = { version = "0.3.18", features = ["fmt", "env-filter"] }
|
||||||
|
|
||||||
[profile.release]
|
[profile.release]
|
||||||
strip = true
|
strip = true
|
||||||
|
|||||||
16
README.md
@@ -1,12 +1,12 @@
|
|||||||

|

|
||||||
|
|
||||||
<p>
|
<p>
|
||||||
<a href="https://github.com/lumehq/coop/actions/workflows/rust.yml">
|
<a href="https://github.com/reyakov/coop/actions/workflows/rust.yml">
|
||||||
<img alt="Actions" src="https://github.com/lumehq/coop/actions/workflows/rust.yml/badge.svg">
|
<img alt="Actions" src="https://github.com/reyakov/coop/actions/workflows/rust.yml/badge.svg">
|
||||||
</a>
|
</a>
|
||||||
<img alt="GitHub repo size" src="https://img.shields.io/github/repo-size/lumehq/coop">
|
<img alt="GitHub repo size" src="https://img.shields.io/github/repo-size/reyakov/coop">
|
||||||
<img alt="GitHub issues" src="https://img.shields.io/github/issues-raw/lumehq/coop">
|
<img alt="GitHub issues" src="https://img.shields.io/github/issues-raw/reyakov/coop">
|
||||||
<img alt="GitHub pull requests" src="https://img.shields.io/github/issues-pr/lumehq/coop">
|
<img alt="GitHub pull requests" src="https://img.shields.io/github/issues-pr/reyakov/coop">
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
Coop is a simple, fast, and reliable nostr client for secure messaging across all platforms.
|
Coop is a simple, fast, and reliable nostr client for secure messaging across all platforms.
|
||||||
@@ -36,7 +36,7 @@ To install Coop, follow these steps:
|
|||||||
|
|
||||||
1. **Download the Latest Release**:
|
1. **Download the Latest Release**:
|
||||||
|
|
||||||
- Visit the [Coop Releases page on GitHub](https://github.com/lumehq/coop/releases).
|
- Visit the [Coop Releases page on GitHub](https://github.com/reyakov/coop/releases).
|
||||||
- Download the package that matches your operating system (Windows, macOS, or Linux).
|
- Download the package that matches your operating system (Windows, macOS, or Linux).
|
||||||
|
|
||||||
2. **Install**:
|
2. **Install**:
|
||||||
@@ -65,7 +65,7 @@ Coop is built using Rust and GPUI. All Nostr related stuffs handled by [Rust Nos
|
|||||||
1. Clone the repository:
|
1. Clone the repository:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone https://github.com/lumehq/coop.git
|
git clone https://github.com/reyakov/coop.git
|
||||||
cd coop
|
cd coop
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -118,7 +118,7 @@ For more information, see the [Contributing](#contributing) section.
|
|||||||
- [Rust Nostr](https://github.com/rust-nostr/nostr/)
|
- [Rust Nostr](https://github.com/rust-nostr/nostr/)
|
||||||
- [GPUI](https://www.gpui.rs/)
|
- [GPUI](https://www.gpui.rs/)
|
||||||
- [GPUI Components](https://github.com/longbridge/gpui-component/)
|
- [GPUI Components](https://github.com/longbridge/gpui-component/)
|
||||||
- [Coop Issue Tracker](https://github.com/lumehq/coop/issues/)
|
- [Coop Issue Tracker](https://github.com/reyakov/coop/issues/)
|
||||||
|
|
||||||
### License
|
### License
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,8 @@ use std::sync::atomic::{AtomicBool, Ordering};
|
|||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use anyhow::{Context as AnyhowContext, Error, anyhow};
|
use anyhow::{Context as AnyhowContext, Error, anyhow};
|
||||||
use common::EventUtils;
|
use common::EventExt;
|
||||||
|
use device::{DeviceEvent, DeviceRegistry};
|
||||||
use fuzzy_matcher::FuzzyMatcher;
|
use fuzzy_matcher::FuzzyMatcher;
|
||||||
use fuzzy_matcher::skim::SkimMatcherV2;
|
use fuzzy_matcher::skim::SkimMatcherV2;
|
||||||
use gpui::{
|
use gpui::{
|
||||||
@@ -41,8 +42,6 @@ pub enum ChatEvent {
|
|||||||
CloseRoom(u64),
|
CloseRoom(u64),
|
||||||
/// An event to notify UI about a new chat request
|
/// An event to notify UI about a new chat request
|
||||||
Ping,
|
Ping,
|
||||||
/// An event to notify UI that the chat registry has subscribed to messaging relays
|
|
||||||
Subscribed,
|
|
||||||
/// An error occurred
|
/// An error occurred
|
||||||
Error(SharedString),
|
Error(SharedString),
|
||||||
}
|
}
|
||||||
@@ -81,6 +80,9 @@ type GiftWrapId = EventId;
|
|||||||
/// Chat Registry
|
/// Chat Registry
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct ChatRegistry {
|
pub struct ChatRegistry {
|
||||||
|
/// Whether the chat registry is currently initializing.
|
||||||
|
pub initializing: bool,
|
||||||
|
|
||||||
/// Chat rooms
|
/// Chat rooms
|
||||||
rooms: Vec<Entity<Room>>,
|
rooms: Vec<Entity<Room>>,
|
||||||
|
|
||||||
@@ -106,7 +108,7 @@ pub struct ChatRegistry {
|
|||||||
tasks: SmallVec<[Task<Result<(), Error>>; 2]>,
|
tasks: SmallVec<[Task<Result<(), Error>>; 2]>,
|
||||||
|
|
||||||
/// Subscriptions
|
/// Subscriptions
|
||||||
_subscriptions: SmallVec<[Subscription; 1]>,
|
_subscriptions: SmallVec<[Subscription; 2]>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EventEmitter<ChatEvent> for ChatRegistry {}
|
impl EventEmitter<ChatEvent> for ChatRegistry {}
|
||||||
@@ -125,22 +127,48 @@ impl ChatRegistry {
|
|||||||
/// Create a new chat registry instance
|
/// Create a new chat registry instance
|
||||||
fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
|
fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
|
let device = DeviceRegistry::global(cx);
|
||||||
|
|
||||||
let (tx, rx) = flume::unbounded::<Signal>();
|
let (tx, rx) = flume::unbounded::<Signal>();
|
||||||
let mut subscriptions = smallvec![];
|
let mut subscriptions = smallvec![];
|
||||||
|
|
||||||
subscriptions.push(
|
subscriptions.push(
|
||||||
// Subscribe to the signer event
|
// Subscribe to the signer event
|
||||||
cx.subscribe(&nostr, |this, _state, event, cx| {
|
cx.subscribe_in(&nostr, window, |this, state, event, window, cx| {
|
||||||
match event {
|
if event == &StateEvent::SignerSet {
|
||||||
StateEvent::SignerSet => {
|
|
||||||
this.reset(cx);
|
this.reset(cx);
|
||||||
this.get_rooms(cx);
|
|
||||||
}
|
|
||||||
StateEvent::RelayConnected => {
|
|
||||||
this.get_contact_list(cx);
|
this.get_contact_list(cx);
|
||||||
this.get_messages(cx)
|
this.get_rooms(cx);
|
||||||
|
|
||||||
|
let signer = state.read(cx).signer();
|
||||||
|
cx.spawn_in(window, async move |this, cx| {
|
||||||
|
let user_signer = signer.get().await;
|
||||||
|
this.update(cx, |this, cx| {
|
||||||
|
this.get_messages(user_signer, cx);
|
||||||
|
})
|
||||||
|
.ok();
|
||||||
|
})
|
||||||
|
.detach();
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
subscriptions.push(
|
||||||
|
// Subscribe to the device event
|
||||||
|
cx.subscribe_in(&device, window, |_this, _s, event, window, cx| {
|
||||||
|
if event == &DeviceEvent::Set {
|
||||||
|
let nostr = NostrRegistry::global(cx);
|
||||||
|
let signer = nostr.read(cx).signer();
|
||||||
|
|
||||||
|
cx.spawn_in(window, async move |this, cx| {
|
||||||
|
if let Some(device_signer) = signer.get_encryption_signer().await {
|
||||||
|
this.update(cx, |this, cx| {
|
||||||
|
this.get_messages(device_signer, cx);
|
||||||
|
})
|
||||||
|
.ok();
|
||||||
}
|
}
|
||||||
_ => {}
|
})
|
||||||
|
.detach();
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -153,6 +181,7 @@ impl ChatRegistry {
|
|||||||
});
|
});
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
|
initializing: true,
|
||||||
rooms: vec![],
|
rooms: vec![],
|
||||||
trashes: cx.new(|_| BTreeSet::default()),
|
trashes: cx.new(|_| BTreeSet::default()),
|
||||||
seens: Arc::new(RwLock::new(HashMap::default())),
|
seens: Arc::new(RwLock::new(HashMap::default())),
|
||||||
@@ -224,6 +253,13 @@ impl ChatRegistry {
|
|||||||
event_map.insert(rumor.id.unwrap(), (event.id, dekey));
|
event_map.insert(rumor.id.unwrap(), (event.id, dekey));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if rumor.kind != Kind::PrivateDirectMessage
|
||||||
|
|| rumor.kind != Kind::Custom(15)
|
||||||
|
{
|
||||||
|
log::info!("Rumor is not releated to NIP17");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
// Check if the rumor has a recipient
|
// Check if the rumor has a recipient
|
||||||
if rumor.tags.is_empty() {
|
if rumor.tags.is_empty() {
|
||||||
let signal =
|
let signal =
|
||||||
@@ -306,7 +342,7 @@ impl ChatRegistry {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Get contact list from relays
|
/// Get contact list from relays
|
||||||
pub fn get_contact_list(&mut self, cx: &mut Context<Self>) {
|
fn get_contact_list(&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();
|
||||||
@@ -336,15 +372,18 @@ impl ChatRegistry {
|
|||||||
self.tasks.push(task);
|
self.tasks.push(task);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get all messages for current user
|
/// Get all messages for the provided signer
|
||||||
pub fn get_messages(&mut self, cx: &mut Context<Self>) {
|
fn get_messages<T>(&mut self, signer: T, cx: &mut Context<Self>)
|
||||||
let task = self.subscribe(cx);
|
where
|
||||||
|
T: NostrSigner + 'static,
|
||||||
|
{
|
||||||
|
let task = self.subscribe_gift_wrap_events(signer, cx);
|
||||||
|
|
||||||
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(_) => {
|
||||||
this.update(cx, |_this, cx| {
|
this.update(cx, |this, cx| {
|
||||||
cx.emit(ChatEvent::Subscribed);
|
this.set_initializing(false, cx);
|
||||||
})?;
|
})?;
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
@@ -365,6 +404,7 @@ impl ChatRegistry {
|
|||||||
|
|
||||||
cx.background_spawn(async move {
|
cx.background_spawn(async move {
|
||||||
let public_key = signer.get_public_key().await?;
|
let public_key = signer.get_public_key().await?;
|
||||||
|
let id = SubscriptionId::new("inbox-relay");
|
||||||
|
|
||||||
// Construct filter for inbox relays
|
// Construct filter for inbox relays
|
||||||
let filter = Filter::new()
|
let filter = Filter::new()
|
||||||
@@ -375,12 +415,12 @@ impl ChatRegistry {
|
|||||||
// Stream events from user's write relays
|
// Stream events from user's write relays
|
||||||
let mut stream = client
|
let mut stream = client
|
||||||
.stream_events(filter)
|
.stream_events(filter)
|
||||||
|
.with_id(id)
|
||||||
.timeout(Duration::from_secs(TIMEOUT))
|
.timeout(Duration::from_secs(TIMEOUT))
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
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);
|
||||||
}
|
}
|
||||||
@@ -390,18 +430,20 @@ impl ChatRegistry {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Continuously get gift wrap events for the current user in their messaging relays
|
/// Continuously get gift wrap events for the signer
|
||||||
fn subscribe(&self, cx: &App) -> Task<Result<(), Error>> {
|
fn subscribe_gift_wrap_events<T>(&self, signer: T, cx: &App) -> Task<Result<(), Error>>
|
||||||
|
where
|
||||||
|
T: NostrSigner + 'static,
|
||||||
|
{
|
||||||
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 urls = self.get_messaging_relays(cx);
|
let urls = self.get_messaging_relays(cx);
|
||||||
|
|
||||||
cx.background_spawn(async move {
|
cx.background_spawn(async move {
|
||||||
let urls = urls.await?;
|
let urls = urls.await?;
|
||||||
let public_key = signer.get_public_key().await?;
|
let public_key = signer.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(USER_GIFTWRAP);
|
let id = SubscriptionId::new(format!("{}-msg", public_key.to_hex()));
|
||||||
|
|
||||||
// Ensure relay connections
|
// Ensure relay connections
|
||||||
for url in urls.iter() {
|
for url in urls.iter() {
|
||||||
@@ -425,6 +467,37 @@ impl ChatRegistry {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Refresh the chat registry, fetching messages and contact list from relays.
|
||||||
|
pub fn refresh(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||||
|
self.reset(cx);
|
||||||
|
self.get_contact_list(cx);
|
||||||
|
self.get_rooms(cx);
|
||||||
|
|
||||||
|
let nostr = NostrRegistry::global(cx);
|
||||||
|
let signer = nostr.read(cx).signer();
|
||||||
|
|
||||||
|
cx.spawn_in(window, async move |this, cx| {
|
||||||
|
let user_signer = signer.get().await;
|
||||||
|
let device_signer = signer.get_encryption_signer().await;
|
||||||
|
|
||||||
|
this.update(cx, |this, cx| {
|
||||||
|
this.get_messages(user_signer, cx);
|
||||||
|
|
||||||
|
if let Some(device_signer) = device_signer {
|
||||||
|
this.get_messages(device_signer, cx);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.ok();
|
||||||
|
})
|
||||||
|
.detach();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set the initializing status of the chat registry
|
||||||
|
fn set_initializing(&mut self, initializing: bool, cx: &mut Context<Self>) {
|
||||||
|
self.initializing = initializing;
|
||||||
|
cx.notify();
|
||||||
|
}
|
||||||
|
|
||||||
/// Get the loading status of the chat registry
|
/// Get the loading status of the chat registry
|
||||||
pub fn loading(&self) -> bool {
|
pub fn loading(&self) -> bool {
|
||||||
self.tracking_flag.load(Ordering::Acquire)
|
self.tracking_flag.load(Ordering::Acquire)
|
||||||
@@ -577,6 +650,7 @@ impl ChatRegistry {
|
|||||||
|
|
||||||
/// Reset the registry.
|
/// Reset the registry.
|
||||||
pub fn reset(&mut self, cx: &mut Context<Self>) {
|
pub fn reset(&mut self, cx: &mut Context<Self>) {
|
||||||
|
self.initializing = true;
|
||||||
self.rooms.clear();
|
self.rooms.clear();
|
||||||
self.trashes.update(cx, |this, cx| {
|
self.trashes.update(cx, |this, cx| {
|
||||||
this.clear();
|
this.clear();
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
use std::hash::Hash;
|
use std::hash::Hash;
|
||||||
use std::ops::Range;
|
use std::ops::Range;
|
||||||
|
|
||||||
use common::{EventUtils, NostrParser};
|
use common::{EventExt, NostrParser, extract_and_remove_media_urls};
|
||||||
use gpui::SharedString;
|
use gpui::{SharedString, SharedUri};
|
||||||
use nostr_sdk::prelude::*;
|
use nostr_sdk::prelude::*;
|
||||||
|
|
||||||
/// New message.
|
/// New message.
|
||||||
@@ -132,6 +132,8 @@ pub struct RenderedMessage {
|
|||||||
pub author: PublicKey,
|
pub author: PublicKey,
|
||||||
/// The content/text of the message
|
/// The content/text of the message
|
||||||
pub content: String,
|
pub content: String,
|
||||||
|
/// List of media URLs in the message
|
||||||
|
pub media: Vec<SharedUri>,
|
||||||
/// Message created time as unix timestamp
|
/// Message created time as unix timestamp
|
||||||
pub created_at: Timestamp,
|
pub created_at: Timestamp,
|
||||||
/// List of mentioned public keys in the message
|
/// List of mentioned public keys in the message
|
||||||
@@ -144,11 +146,13 @@ impl From<&Event> for RenderedMessage {
|
|||||||
fn from(val: &Event) -> Self {
|
fn from(val: &Event) -> Self {
|
||||||
let mentions = extract_mentions(&val.content);
|
let mentions = extract_mentions(&val.content);
|
||||||
let replies_to = extract_reply_ids(&val.tags);
|
let replies_to = extract_reply_ids(&val.tags);
|
||||||
|
let (media, string) = extract_and_remove_media_urls(&val.content);
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
id: val.id,
|
id: val.id,
|
||||||
author: val.pubkey,
|
author: val.pubkey,
|
||||||
content: val.content.clone(),
|
content: string,
|
||||||
|
media,
|
||||||
created_at: val.created_at,
|
created_at: val.created_at,
|
||||||
mentions,
|
mentions,
|
||||||
replies_to,
|
replies_to,
|
||||||
@@ -160,12 +164,14 @@ impl From<&UnsignedEvent> for RenderedMessage {
|
|||||||
fn from(val: &UnsignedEvent) -> Self {
|
fn from(val: &UnsignedEvent) -> Self {
|
||||||
let mentions = extract_mentions(&val.content);
|
let mentions = extract_mentions(&val.content);
|
||||||
let replies_to = extract_reply_ids(&val.tags);
|
let replies_to = extract_reply_ids(&val.tags);
|
||||||
|
let (media, string) = extract_and_remove_media_urls(&val.content);
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
// Event ID must be known
|
// Event ID must be known
|
||||||
id: val.id.unwrap(),
|
id: val.id.unwrap(),
|
||||||
author: val.pubkey,
|
author: val.pubkey,
|
||||||
content: val.content.clone(),
|
content: string,
|
||||||
|
media,
|
||||||
created_at: val.created_at,
|
created_at: val.created_at,
|
||||||
mentions,
|
mentions,
|
||||||
replies_to,
|
replies_to,
|
||||||
@@ -177,12 +183,14 @@ impl From<&NewMessage> for RenderedMessage {
|
|||||||
fn from(val: &NewMessage) -> Self {
|
fn from(val: &NewMessage) -> Self {
|
||||||
let mentions = extract_mentions(&val.rumor.content);
|
let mentions = extract_mentions(&val.rumor.content);
|
||||||
let replies_to = extract_reply_ids(&val.rumor.tags);
|
let replies_to = extract_reply_ids(&val.rumor.tags);
|
||||||
|
let (media, string) = extract_and_remove_media_urls(&val.rumor.content);
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
// Event ID must be known
|
// Event ID must be known
|
||||||
id: val.rumor.id.unwrap(),
|
id: val.rumor.id.unwrap(),
|
||||||
author: val.rumor.pubkey,
|
author: val.rumor.pubkey,
|
||||||
content: val.rumor.content.clone(),
|
content: string,
|
||||||
|
media,
|
||||||
created_at: val.rumor.created_at,
|
created_at: val.rumor.created_at,
|
||||||
mentions,
|
mentions,
|
||||||
replies_to,
|
replies_to,
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ use std::hash::{Hash, Hasher};
|
|||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use anyhow::{Error, anyhow};
|
use anyhow::{Error, anyhow};
|
||||||
use common::EventUtils;
|
use common::EventExt;
|
||||||
use gpui::{App, AppContext, Context, EventEmitter, SharedString, Task};
|
use gpui::{App, AppContext, Context, EventEmitter, SharedString, Task};
|
||||||
use itertools::Itertools;
|
use itertools::Itertools;
|
||||||
use nostr_sdk::prelude::*;
|
use nostr_sdk::prelude::*;
|
||||||
@@ -400,6 +400,10 @@ impl Room {
|
|||||||
.await?
|
.await?
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter_map(|event| UnsignedEvent::from_json(&event.content).ok())
|
.filter_map(|event| UnsignedEvent::from_json(&event.content).ok())
|
||||||
|
.filter(|event| {
|
||||||
|
// Only process private direct messages and file messages
|
||||||
|
event.kind == Kind::PrivateDirectMessage || event.kind == Kind::Custom(15)
|
||||||
|
})
|
||||||
.sorted_by_key(|message| message.created_at)
|
.sorted_by_key(|message| message.created_at)
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
@@ -598,7 +602,8 @@ async fn send_gift_wrap<T>(
|
|||||||
where
|
where
|
||||||
T: NostrSigner + 'static,
|
T: NostrSigner + 'static,
|
||||||
{
|
{
|
||||||
let mut extra_tags = vec![];
|
let k_tag = Tag::custom(TagKind::k(), vec!["14"]);
|
||||||
|
let mut extra_tags = vec![k_tag];
|
||||||
|
|
||||||
// Determine the receiver public key based on the config
|
// Determine the receiver public key based on the config
|
||||||
let receiver = match config {
|
let receiver = match config {
|
||||||
|
|||||||
@@ -4,14 +4,14 @@ use std::sync::Arc;
|
|||||||
pub use actions::*;
|
pub use actions::*;
|
||||||
use anyhow::{Context as AnyhowContext, Error};
|
use anyhow::{Context as AnyhowContext, Error};
|
||||||
use chat::{ChatRegistry, Message, RenderedMessage, Room, RoomEvent, SendReport, SendStatus};
|
use chat::{ChatRegistry, Message, RenderedMessage, Room, RoomEvent, SendReport, SendStatus};
|
||||||
use common::RenderedTimestamp;
|
use common::{TimestampExt, coop_cache};
|
||||||
use gpui::prelude::FluentBuilder;
|
use gpui::prelude::FluentBuilder;
|
||||||
use gpui::{
|
use gpui::{
|
||||||
AnyElement, App, AppContext, ClipboardItem, Context, Entity, EventEmitter, FocusHandle,
|
AnyElement, App, AppContext, ClipboardItem, Context, Entity, EventEmitter, FocusHandle,
|
||||||
Focusable, InteractiveElement, IntoElement, ListAlignment, ListOffset, ListState, MouseButton,
|
Focusable, InteractiveElement, IntoElement, ListAlignment, ListOffset, ListState, MouseButton,
|
||||||
ObjectFit, ParentElement, PathPromptOptions, Render, SharedString, StatefulInteractiveElement,
|
ObjectFit, ParentElement, PathPromptOptions, Render, SharedString, SharedUri,
|
||||||
Styled, StyledImage, Subscription, Task, WeakEntity, Window, deferred, div, img, list, px, red,
|
StatefulInteractiveElement, Styled, StyledImage, Subscription, Task, WeakEntity, Window,
|
||||||
relative, svg, white,
|
deferred, div, img, list, px, red, relative, svg, white,
|
||||||
};
|
};
|
||||||
use itertools::Itertools;
|
use itertools::Itertools;
|
||||||
use nostr_sdk::prelude::*;
|
use nostr_sdk::prelude::*;
|
||||||
@@ -914,7 +914,8 @@ impl ChatPanel {
|
|||||||
.when(has_replies, |this| {
|
.when(has_replies, |this| {
|
||||||
this.children(self.render_message_replies(replies, cx))
|
this.children(self.render_message_replies(replies, cx))
|
||||||
})
|
})
|
||||||
.child(rendered_text),
|
.child(rendered_text)
|
||||||
|
.child(self.render_media(&message.media, cx)),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
.child(
|
.child(
|
||||||
@@ -941,6 +942,55 @@ impl ChatPanel {
|
|||||||
.into_any_element()
|
.into_any_element()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn render_media(&self, media: &[SharedUri], cx: &Context<Self>) -> impl IntoElement {
|
||||||
|
// No media: return empty div
|
||||||
|
if media.is_empty() {
|
||||||
|
return div();
|
||||||
|
};
|
||||||
|
|
||||||
|
// Single media item: render full-width image
|
||||||
|
if media.len() == 1 {
|
||||||
|
return div().child(
|
||||||
|
img(media[0].clone())
|
||||||
|
.border_1()
|
||||||
|
.border_color(cx.theme().border_variant)
|
||||||
|
.h(px(250.))
|
||||||
|
.object_fit(ObjectFit::Cover)
|
||||||
|
.rounded(cx.theme().radius),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Multiple media items: render in a row
|
||||||
|
div()
|
||||||
|
.w_full()
|
||||||
|
.flex_1()
|
||||||
|
.flex()
|
||||||
|
.flex_row()
|
||||||
|
.flex_wrap()
|
||||||
|
.gap_2()
|
||||||
|
.children({
|
||||||
|
let mut items = vec![];
|
||||||
|
|
||||||
|
for (ix, item) in media.iter().enumerate() {
|
||||||
|
items.push(
|
||||||
|
div()
|
||||||
|
.id(format!("media-{ix}"))
|
||||||
|
.flex_grow_0()
|
||||||
|
.flex_shrink_0()
|
||||||
|
.child(
|
||||||
|
img(item.clone())
|
||||||
|
.h_32()
|
||||||
|
.border_1()
|
||||||
|
.border_color(cx.theme().border_variant)
|
||||||
|
.rounded(cx.theme().radius),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
items
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
fn render_message_replies(
|
fn render_message_replies(
|
||||||
&self,
|
&self,
|
||||||
replies: &[EventId],
|
replies: &[EventId],
|
||||||
@@ -1371,7 +1421,7 @@ impl ChatPanel {
|
|||||||
.icon(IconName::Emoji)
|
.icon(IconName::Emoji)
|
||||||
.ghost()
|
.ghost()
|
||||||
.large()
|
.large()
|
||||||
.dropdown_menu_with_anchor(gpui::Corner::BottomLeft, move |this, _window, _cx| {
|
.dropdown_menu_with_anchor(gpui::Anchor::BottomLeft, move |this, _window, _cx| {
|
||||||
this.horizontal()
|
this.horizontal()
|
||||||
.menu("👍", Box::new(Command::Insert("👍")))
|
.menu("👍", Box::new(Command::Insert("👍")))
|
||||||
.menu("👎", Box::new(Command::Insert("👎")))
|
.menu("👎", Box::new(Command::Insert("👎")))
|
||||||
@@ -1435,6 +1485,7 @@ impl Focusable for ChatPanel {
|
|||||||
impl Render for ChatPanel {
|
impl Render for ChatPanel {
|
||||||
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 {
|
||||||
v_flex()
|
v_flex()
|
||||||
|
.image_cache(coop_cache(self.id.clone(), 100))
|
||||||
.on_action(cx.listener(Self::on_command))
|
.on_action(cx.listener(Self::on_command))
|
||||||
.size_full()
|
.size_full()
|
||||||
.when(*self.subject_bar.read(cx), |this| {
|
.when(*self.subject_bar.read(cx), |this| {
|
||||||
|
|||||||
@@ -69,6 +69,7 @@ impl RenderedText {
|
|||||||
|
|
||||||
pub fn element(&self, id: ElementId, window: &Window, cx: &App) -> AnyElement {
|
pub fn element(&self, id: ElementId, window: &Window, cx: &App) -> AnyElement {
|
||||||
let code_background = cx.theme().elevated_surface_background;
|
let code_background = cx.theme().elevated_surface_background;
|
||||||
|
let color = cx.theme().text_accent;
|
||||||
|
|
||||||
InteractiveText::new(
|
InteractiveText::new(
|
||||||
id,
|
id,
|
||||||
@@ -100,6 +101,7 @@ impl RenderedText {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
Highlight::Mention => HighlightStyle {
|
Highlight::Mention => HighlightStyle {
|
||||||
|
color: Some(color),
|
||||||
underline: Some(UnderlineStyle {
|
underline: Some(UnderlineStyle {
|
||||||
thickness: 1.0.into(),
|
thickness: 1.0.into(),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
|
|||||||
@@ -20,3 +20,4 @@ log.workspace = true
|
|||||||
dirs = "5.0"
|
dirs = "5.0"
|
||||||
qrcode = "0.14.1"
|
qrcode = "0.14.1"
|
||||||
bech32 = "0.11.1"
|
bech32 = "0.11.1"
|
||||||
|
regex = "1.10"
|
||||||
|
|||||||
135
crates/common/src/caching.rs
Normal file
@@ -0,0 +1,135 @@
|
|||||||
|
use std::collections::{HashMap, VecDeque};
|
||||||
|
use std::mem::take;
|
||||||
|
|
||||||
|
use futures::FutureExt;
|
||||||
|
use gpui::{
|
||||||
|
App, AppContext, Asset, AssetLogger, ElementId, Entity, ImageAssetLoader, ImageCache,
|
||||||
|
ImageCacheItem, ImageCacheProvider, ImageSource, Resource, hash,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub fn coop_cache(id: impl Into<ElementId>, max_items: usize) -> CoopImageCacheProvider {
|
||||||
|
CoopImageCacheProvider {
|
||||||
|
id: id.into(),
|
||||||
|
max_items,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct CoopImageCacheProvider {
|
||||||
|
id: ElementId,
|
||||||
|
max_items: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ImageCacheProvider for CoopImageCacheProvider {
|
||||||
|
fn provide(&mut self, window: &mut gpui::Window, cx: &mut App) -> gpui::AnyImageCache {
|
||||||
|
window
|
||||||
|
.with_global_id(self.id.clone(), |id, window| {
|
||||||
|
window.with_element_state(id, |cache, _| {
|
||||||
|
let cache = cache.unwrap_or_else(|| CoopImageCache::new(self.max_items, cx));
|
||||||
|
(cache.clone(), cache)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.into()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct CoopImageCache {
|
||||||
|
max_items: usize,
|
||||||
|
usage_list: VecDeque<u64>,
|
||||||
|
cache: HashMap<u64, (ImageCacheItem, Resource)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CoopImageCache {
|
||||||
|
pub fn new(max_items: usize, cx: &mut App) -> Entity<Self> {
|
||||||
|
cx.new(|cx| {
|
||||||
|
log::info!("Creating CoopImageCache");
|
||||||
|
cx.on_release(|this: &mut Self, cx| {
|
||||||
|
for (ix, (mut image, resource)) in take(&mut this.cache) {
|
||||||
|
if let Some(Ok(image)) = image.get() {
|
||||||
|
log::info!("Dropping image {ix}");
|
||||||
|
cx.drop_image(image, None);
|
||||||
|
}
|
||||||
|
ImageSource::Resource(resource).remove_asset(cx);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.detach();
|
||||||
|
|
||||||
|
CoopImageCache {
|
||||||
|
max_items,
|
||||||
|
usage_list: VecDeque::with_capacity(max_items),
|
||||||
|
cache: HashMap::with_capacity(max_items),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ImageCache for CoopImageCache {
|
||||||
|
fn load(
|
||||||
|
&mut self,
|
||||||
|
resource: &Resource,
|
||||||
|
window: &mut gpui::Window,
|
||||||
|
cx: &mut gpui::App,
|
||||||
|
) -> Option<Result<std::sync::Arc<gpui::RenderImage>, gpui::ImageCacheError>> {
|
||||||
|
let hash = hash(resource);
|
||||||
|
|
||||||
|
if let Some(item) = self.cache.get_mut(&hash) {
|
||||||
|
let current_idx = self
|
||||||
|
.usage_list
|
||||||
|
.iter()
|
||||||
|
.position(|item| *item == hash)
|
||||||
|
.expect("cache has an item usage_list doesn't");
|
||||||
|
|
||||||
|
self.usage_list.remove(current_idx);
|
||||||
|
self.usage_list.push_front(hash);
|
||||||
|
|
||||||
|
return item.0.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
let load_future = AssetLogger::<ImageAssetLoader>::load(resource.clone(), cx);
|
||||||
|
let task = cx.background_executor().spawn(load_future).shared();
|
||||||
|
|
||||||
|
if self.usage_list.len() >= self.max_items {
|
||||||
|
log::info!("Image cache is full, evicting oldest item");
|
||||||
|
|
||||||
|
if let Some(oldest) = self.usage_list.pop_back() {
|
||||||
|
let mut image = self
|
||||||
|
.cache
|
||||||
|
.remove(&oldest)
|
||||||
|
.expect("usage_list has an item cache doesn't");
|
||||||
|
|
||||||
|
if let Some(Ok(image)) = image.0.get() {
|
||||||
|
log::info!("requesting image to be dropped");
|
||||||
|
cx.drop_image(image, Some(window));
|
||||||
|
}
|
||||||
|
|
||||||
|
ImageSource::Resource(image.1).remove_asset(cx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
self.cache.insert(
|
||||||
|
hash,
|
||||||
|
(
|
||||||
|
gpui::ImageCacheItem::Loading(task.clone()),
|
||||||
|
resource.clone(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
self.usage_list.push_front(hash);
|
||||||
|
|
||||||
|
let entity = window.current_view();
|
||||||
|
|
||||||
|
window
|
||||||
|
.spawn(cx, async move |cx| {
|
||||||
|
let result = task.await;
|
||||||
|
|
||||||
|
if let Err(err) = result {
|
||||||
|
log::error!("error loading image into cache: {:?}", err);
|
||||||
|
}
|
||||||
|
|
||||||
|
cx.on_next_frame(move |_, cx| {
|
||||||
|
cx.notify(entity);
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.detach();
|
||||||
|
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,10 @@
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use anyhow::{Error, anyhow};
|
|
||||||
use chrono::{Local, TimeZone};
|
use chrono::{Local, TimeZone};
|
||||||
use gpui::{Image, ImageFormat, SharedString};
|
use gpui::{Image, ImageFormat, SharedString};
|
||||||
use nostr_sdk::prelude::*;
|
use nostr_sdk::prelude::*;
|
||||||
use qrcode::render::svg;
|
|
||||||
use qrcode::QrCode;
|
use qrcode::QrCode;
|
||||||
|
use qrcode::render::svg;
|
||||||
|
|
||||||
const NOW: &str = "now";
|
const NOW: &str = "now";
|
||||||
const SECONDS_IN_MINUTE: i64 = 60;
|
const SECONDS_IN_MINUTE: i64 = 60;
|
||||||
@@ -13,12 +12,12 @@ const MINUTES_IN_HOUR: i64 = 60;
|
|||||||
const HOURS_IN_DAY: i64 = 24;
|
const HOURS_IN_DAY: i64 = 24;
|
||||||
const DAYS_IN_MONTH: i64 = 30;
|
const DAYS_IN_MONTH: i64 = 30;
|
||||||
|
|
||||||
pub trait RenderedTimestamp {
|
pub trait TimestampExt {
|
||||||
fn to_human_time(&self) -> SharedString;
|
fn to_human_time(&self) -> SharedString;
|
||||||
fn to_ago(&self) -> SharedString;
|
fn to_ago(&self) -> SharedString;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RenderedTimestamp for Timestamp {
|
impl TimestampExt for Timestamp {
|
||||||
fn to_human_time(&self) -> SharedString {
|
fn to_human_time(&self) -> SharedString {
|
||||||
let input_time = match Local.timestamp_opt(self.as_secs() as i64, 0) {
|
let input_time = match Local.timestamp_opt(self.as_secs() as i64, 0) {
|
||||||
chrono::LocalResult::Single(time) => time,
|
chrono::LocalResult::Single(time) => time,
|
||||||
@@ -61,23 +60,11 @@ impl RenderedTimestamp for Timestamp {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait TextUtils {
|
pub trait StringExt {
|
||||||
fn to_public_key(&self) -> Result<PublicKey, Error>;
|
|
||||||
fn to_qr(&self) -> Option<Arc<Image>>;
|
fn to_qr(&self) -> Option<Arc<Image>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: AsRef<str>> TextUtils for T {
|
impl<T: AsRef<str>> StringExt for T {
|
||||||
fn to_public_key(&self) -> Result<PublicKey, Error> {
|
|
||||||
let s = self.as_ref();
|
|
||||||
if s.starts_with("nprofile1") {
|
|
||||||
Ok(Nip19Profile::from_bech32(s)?.public_key)
|
|
||||||
} else if s.starts_with("npub1") {
|
|
||||||
Ok(PublicKey::parse(s)?)
|
|
||||||
} else {
|
|
||||||
Err(anyhow!("Invalid public key"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn to_qr(&self) -> Option<Arc<Image>> {
|
fn to_qr(&self) -> Option<Arc<Image>> {
|
||||||
let s = self.as_ref();
|
let s = self.as_ref();
|
||||||
let code = QrCode::new(s).unwrap();
|
let code = QrCode::new(s).unwrap();
|
||||||
|
|||||||
@@ -3,12 +3,12 @@ use std::hash::{DefaultHasher, Hash, Hasher};
|
|||||||
use itertools::Itertools;
|
use itertools::Itertools;
|
||||||
use nostr_sdk::prelude::*;
|
use nostr_sdk::prelude::*;
|
||||||
|
|
||||||
pub trait EventUtils {
|
pub trait EventExt {
|
||||||
fn uniq_id(&self) -> u64;
|
fn uniq_id(&self) -> u64;
|
||||||
fn extract_public_keys(&self) -> Vec<PublicKey>;
|
fn extract_public_keys(&self) -> Vec<PublicKey>;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EventUtils for Event {
|
impl EventExt for Event {
|
||||||
fn uniq_id(&self) -> u64 {
|
fn uniq_id(&self) -> u64 {
|
||||||
let mut hasher = DefaultHasher::new();
|
let mut hasher = DefaultHasher::new();
|
||||||
let mut pubkeys: Vec<PublicKey> = self.extract_public_keys();
|
let mut pubkeys: Vec<PublicKey> = self.extract_public_keys();
|
||||||
@@ -25,7 +25,7 @@ impl EventUtils for Event {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EventUtils for UnsignedEvent {
|
impl EventExt for UnsignedEvent {
|
||||||
fn uniq_id(&self) -> u64 {
|
fn uniq_id(&self) -> u64 {
|
||||||
let mut hasher = DefaultHasher::new();
|
let mut hasher = DefaultHasher::new();
|
||||||
let mut pubkeys: Vec<PublicKey> = vec![];
|
let mut pubkeys: Vec<PublicKey> = vec![];
|
||||||
|
|||||||
@@ -1,13 +1,17 @@
|
|||||||
|
pub use caching::*;
|
||||||
pub use debounced_delay::*;
|
pub use debounced_delay::*;
|
||||||
pub use display::*;
|
pub use display::*;
|
||||||
pub use event::*;
|
pub use event::*;
|
||||||
|
pub use media_extractor::*;
|
||||||
pub use parser::*;
|
pub use parser::*;
|
||||||
pub use paths::*;
|
pub use paths::*;
|
||||||
pub use range::*;
|
pub use range::*;
|
||||||
|
|
||||||
|
mod caching;
|
||||||
mod debounced_delay;
|
mod debounced_delay;
|
||||||
mod display;
|
mod display;
|
||||||
mod event;
|
mod event;
|
||||||
|
mod media_extractor;
|
||||||
mod parser;
|
mod parser;
|
||||||
mod paths;
|
mod paths;
|
||||||
mod range;
|
mod range;
|
||||||
|
|||||||
117
crates/common/src/media_extractor.rs
Normal file
@@ -0,0 +1,117 @@
|
|||||||
|
use gpui::SharedUri;
|
||||||
|
use regex::Regex;
|
||||||
|
|
||||||
|
/// Extracts media URLs from a string and returns both the extracted URLs
|
||||||
|
/// and the string with media URLs removed
|
||||||
|
pub struct MediaExtractor {
|
||||||
|
image_regex: Regex,
|
||||||
|
video_regex: Regex,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MediaExtractor {
|
||||||
|
/// Creates a new MediaExtractor with compiled regex patterns
|
||||||
|
pub fn new() -> Self {
|
||||||
|
MediaExtractor {
|
||||||
|
// Match common image extensions
|
||||||
|
image_regex: Regex::new(
|
||||||
|
r#"(?i)\bhttps?://[^\s<>"']+\.(?:jpg|jpeg|png|gif|bmp|webp|svg|ico)(?:\?[^\s<>"']*)?\b"#,
|
||||||
|
).unwrap(),
|
||||||
|
// Match common video extensions
|
||||||
|
video_regex: Regex::new(
|
||||||
|
r#"(?i)\bhttps?://[^\s<>"']+\.(?:mp4|mov|avi|mkv|webm|flv|wmv|m4v|3gp)(?:\?[^\s<>"']*)?\b"#,
|
||||||
|
).unwrap(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Extracts all media URLs from a string
|
||||||
|
pub fn extract_media_urls(&self, text: &str) -> Vec<SharedUri> {
|
||||||
|
let mut urls = Vec::new();
|
||||||
|
|
||||||
|
// Extract image URLs
|
||||||
|
for capture in self.image_regex.find_iter(text) {
|
||||||
|
urls.push(capture.as_str().to_string().into());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract video URLs
|
||||||
|
// for capture in self.video_regex.find_iter(text) {
|
||||||
|
// urls.push(capture.as_str().to_string().into());
|
||||||
|
// }
|
||||||
|
|
||||||
|
urls
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Removes all media URLs from a string and returns the cleaned text
|
||||||
|
pub fn remove_media_urls(&self, text: &str) -> String {
|
||||||
|
let mut result = text.to_string();
|
||||||
|
|
||||||
|
// Remove image URLs
|
||||||
|
result = self.image_regex.replace_all(&result, "").to_string();
|
||||||
|
|
||||||
|
// Remove video URLs
|
||||||
|
// result = self.video_regex.replace_all(&result, "").to_string();
|
||||||
|
|
||||||
|
// Clean up extra whitespace that might result from removal
|
||||||
|
self.cleanup_text(&result)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Extracts media URLs and removes them from the string, returning both
|
||||||
|
pub fn extract_and_remove(&self, text: &str) -> (Vec<SharedUri>, String) {
|
||||||
|
let urls = self.extract_media_urls(text);
|
||||||
|
let cleaned_text = self.remove_media_urls(text);
|
||||||
|
(urls, cleaned_text)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Helper function to clean up text after URL removal
|
||||||
|
fn cleanup_text(&self, text: &str) -> String {
|
||||||
|
let text = text.trim();
|
||||||
|
|
||||||
|
// Remove multiple consecutive spaces
|
||||||
|
let re = Regex::new(r"\s+").unwrap();
|
||||||
|
re.replace_all(text, " ").trim().to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Validates if a URL is a valid media URL
|
||||||
|
pub fn is_media_url(&self, url: &str) -> bool {
|
||||||
|
self.image_regex.is_match(url) || self.video_regex.is_match(url)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Categorizes extracted URLs into images and videos
|
||||||
|
pub fn categorize_urls(&self, urls: &[SharedUri]) -> (Vec<SharedUri>, Vec<SharedUri>) {
|
||||||
|
let mut images = Vec::new();
|
||||||
|
let mut videos = Vec::new();
|
||||||
|
|
||||||
|
for url in urls {
|
||||||
|
if self.image_regex.is_match(url) {
|
||||||
|
images.push(url.clone());
|
||||||
|
} else if self.video_regex.is_match(url) {
|
||||||
|
videos.push(url.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
(images, videos)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for MediaExtractor {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Convenience function for one-time extraction and removal
|
||||||
|
pub fn extract_and_remove_media_urls(text: &str) -> (Vec<SharedUri>, String) {
|
||||||
|
let extractor = MediaExtractor::new();
|
||||||
|
extractor.extract_and_remove(text)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Convenience function for just extracting media URLs
|
||||||
|
pub fn extract_media_urls(text: &str) -> Vec<SharedUri> {
|
||||||
|
let extractor = MediaExtractor::new();
|
||||||
|
extractor.extract_media_urls(text)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Convenience function for just removing media URLs
|
||||||
|
pub fn remove_media_urls(text: &str) -> String {
|
||||||
|
let extractor = MediaExtractor::new();
|
||||||
|
extractor.remove_media_urls(text)
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
use std::cell::Cell;
|
use std::cell::Cell;
|
||||||
use std::collections::{HashMap, HashSet};
|
use std::collections::HashSet;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
@@ -11,12 +11,12 @@ use gpui::{
|
|||||||
};
|
};
|
||||||
use nostr_sdk::prelude::*;
|
use nostr_sdk::prelude::*;
|
||||||
use person::PersonRegistry;
|
use person::PersonRegistry;
|
||||||
use state::{Announcement, DEVICE_GIFTWRAP, NostrRegistry, StateEvent, TIMEOUT, app_name};
|
use state::{Announcement, CLIENT_NAME, NostrRegistry, StateEvent, TIMEOUT};
|
||||||
use theme::ActiveTheme;
|
use theme::ActiveTheme;
|
||||||
use ui::avatar::Avatar;
|
use ui::avatar::Avatar;
|
||||||
use ui::button::{Button, ButtonVariants};
|
use ui::button::Button;
|
||||||
use ui::notification::Notification;
|
use ui::notification::{Notification, NotificationKind};
|
||||||
use ui::{Disableable, IconName, Sizable, StyledExt, WindowExtension, h_flex, v_flex};
|
use ui::{Disableable, 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. \
|
||||||
@@ -39,10 +39,6 @@ pub enum DeviceEvent {
|
|||||||
Requesting,
|
Requesting,
|
||||||
/// The device is creating a new encryption key
|
/// The device is creating a new encryption key
|
||||||
Creating,
|
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),
|
||||||
}
|
}
|
||||||
@@ -54,24 +50,6 @@ impl DeviceEvent {
|
|||||||
{
|
{
|
||||||
Self::Error(error.into())
|
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
|
||||||
@@ -79,14 +57,11 @@ impl DeviceEvent {
|
|||||||
/// 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 {
|
||||||
/// Whether the registry is currently subscribing to gift wrap events
|
/// Whether the registry is currently initializing
|
||||||
pub subscribing: bool,
|
pub initializing: 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
|
/// Whether there is a pending request for encryption key approval
|
||||||
pub has_pending_request: bool,
|
pub pending_request: bool,
|
||||||
|
|
||||||
/// Async tasks
|
/// Async tasks
|
||||||
tasks: Vec<Task<Result<(), Error>>>,
|
tasks: Vec<Task<Result<(), Error>>>,
|
||||||
@@ -112,17 +87,11 @@ impl DeviceRegistry {
|
|||||||
fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
|
fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
|
|
||||||
// Get announcement when signer is set
|
// Subscribe to nostr state events
|
||||||
let subscription = cx.subscribe_in(&nostr, window, |this, _e, event, _window, cx| {
|
let subscription = cx.subscribe_in(&nostr, window, |this, _e, event, _window, cx| {
|
||||||
match event {
|
if event == &StateEvent::SignerSet {
|
||||||
StateEvent::SignerSet => {
|
this.set_initializing(true, cx);
|
||||||
this.set_subscribing(false, cx);
|
|
||||||
this.set_requesting(false, cx);
|
|
||||||
}
|
|
||||||
StateEvent::RelayConnected => {
|
|
||||||
this.get_announcement(cx);
|
this.get_announcement(cx);
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -131,9 +100,8 @@ impl DeviceRegistry {
|
|||||||
});
|
});
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
subscribing: false,
|
initializing: true,
|
||||||
requesting: false,
|
pending_request: false,
|
||||||
has_pending_request: false,
|
|
||||||
tasks: vec![],
|
tasks: vec![],
|
||||||
_subscription: Some(subscription),
|
_subscription: Some(subscription),
|
||||||
}
|
}
|
||||||
@@ -198,21 +166,15 @@ impl DeviceRegistry {
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set whether the registry is currently subscribing to gift wrap events
|
/// Set whether the registry is currently initializing
|
||||||
fn set_subscribing(&mut self, subscribing: bool, cx: &mut Context<Self>) {
|
fn set_initializing(&mut self, initializing: bool, cx: &mut Context<Self>) {
|
||||||
self.subscribing = subscribing;
|
self.initializing = initializing;
|
||||||
cx.notify();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Set whether the registry is waiting for encryption key approval from other devices
|
|
||||||
fn set_requesting(&mut self, requesting: bool, cx: &mut Context<Self>) {
|
|
||||||
self.requesting = requesting;
|
|
||||||
cx.notify();
|
cx.notify();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set whether there is a pending request for encryption key approval
|
/// Set whether there is a pending request for encryption key approval
|
||||||
fn set_has_pending_request(&mut self, pending: bool, cx: &mut Context<Self>) {
|
fn set_pending_request(&mut self, pending: bool, cx: &mut Context<Self>) {
|
||||||
self.has_pending_request = pending;
|
self.pending_request = pending;
|
||||||
cx.notify();
|
cx.notify();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -229,76 +191,14 @@ impl DeviceRegistry {
|
|||||||
|
|
||||||
// Update state
|
// Update state
|
||||||
this.update(cx, |this, cx| {
|
this.update(cx, |this, cx| {
|
||||||
|
this.set_initializing(false, cx);
|
||||||
cx.emit(DeviceEvent::Set);
|
cx.emit(DeviceEvent::Set);
|
||||||
this.get_messages(cx);
|
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get all messages for encryption keys
|
|
||||||
fn get_messages(&mut self, cx: &mut Context<Self>) {
|
|
||||||
let task = self.subscribe_to_giftwrap_events(cx);
|
|
||||||
|
|
||||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
|
||||||
if let Err(e) = task.await {
|
|
||||||
this.update(cx, |_this, cx| {
|
|
||||||
cx.emit(DeviceEvent::not_subscribe(e.to_string()));
|
|
||||||
})?;
|
|
||||||
} else {
|
|
||||||
this.update(cx, |this, cx| {
|
|
||||||
this.set_subscribing(true, cx);
|
|
||||||
})?;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Continuously get gift wrap events for the current user in their messaging relays
|
|
||||||
fn subscribe_to_giftwrap_events(&self, cx: &App) -> Task<Result<(), Error>> {
|
|
||||||
let persons = PersonRegistry::global(cx);
|
|
||||||
let nostr = NostrRegistry::global(cx);
|
|
||||||
let client = nostr.read(cx).client();
|
|
||||||
let signer = nostr.read(cx).signer();
|
|
||||||
|
|
||||||
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 {
|
|
||||||
let encryption = signer.get_encryption_signer().await.context("not found")?;
|
|
||||||
let public_key = encryption.get_public_key().await?;
|
|
||||||
|
|
||||||
let filter = Filter::new().kind(Kind::GiftWrap).pubkey(public_key);
|
|
||||||
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
|
|
||||||
let target: HashMap<RelayUrl, Filter> = relays
|
|
||||||
.into_iter()
|
|
||||||
.map(|relay| (relay, filter.clone()))
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
// Subscribe
|
|
||||||
client.subscribe(target).with_id(id).await?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Backup the encryption's secret key to a file
|
/// Backup the encryption's secret key to a file
|
||||||
pub fn backup(&self, path: PathBuf, cx: &App) -> Task<Result<(), Error>> {
|
pub fn backup(&self, path: PathBuf, cx: &App) -> Task<Result<(), Error>> {
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
@@ -401,7 +301,7 @@ impl DeviceRegistry {
|
|||||||
// Construct an announcement event
|
// Construct an announcement event
|
||||||
let builder = EventBuilder::new(Kind::Custom(10044), "").tags(vec![
|
let 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(CLIENT_NAME),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// Sign the event with user's signer
|
// Sign the event with user's signer
|
||||||
@@ -431,30 +331,27 @@ impl DeviceRegistry {
|
|||||||
|
|
||||||
// Get encryption key from the database and compare with the announcement
|
// 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 {
|
let keys = get_keys(&client).await?;
|
||||||
|
|
||||||
|
// Compare the public key from the announcement with the one from the database
|
||||||
if keys.public_key() != device_pubkey {
|
if keys.public_key() != device_pubkey {
|
||||||
return Err(anyhow!("Encryption Key doesn't match the announcement"));
|
return Err(anyhow!("Encryption Key doesn't match the announcement"));
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok(keys)
|
Ok(keys)
|
||||||
} else {
|
|
||||||
Err(anyhow!("Encryption Key not found. Please create a new key"))
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
self.tasks.push(cx.spawn(async move |this, cx| {
|
||||||
match task.await {
|
if let Ok(keys) = task.await {
|
||||||
Ok(keys) => {
|
|
||||||
this.update(cx, |this, cx| {
|
this.update(cx, |this, cx| {
|
||||||
this.set_signer(keys, cx);
|
this.set_signer(keys, cx);
|
||||||
this.wait_for_request(cx);
|
this.wait_for_request(cx);
|
||||||
})?;
|
})?;
|
||||||
}
|
} else {
|
||||||
Err(e) => {
|
this.update(cx, |this, cx| {
|
||||||
this.update(cx, |_this, cx| {
|
this.request(cx);
|
||||||
cx.emit(DeviceEvent::not_set(e.to_string()));
|
|
||||||
})?;
|
})?;
|
||||||
}
|
}
|
||||||
};
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
@@ -467,21 +364,16 @@ impl DeviceRegistry {
|
|||||||
|
|
||||||
self.tasks.push(cx.background_spawn(async move {
|
self.tasks.push(cx.background_spawn(async move {
|
||||||
let public_key = signer.get_public_key().await?;
|
let public_key = signer.get_public_key().await?;
|
||||||
|
let id = SubscriptionId::new("dekey-requests");
|
||||||
|
|
||||||
// Construct a filter for encryption key requests
|
// Construct a filter for encryption 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());
|
||||||
|
|
||||||
// Construct a filter for the last encryption key request
|
|
||||||
let last = Filter::new()
|
|
||||||
.kind(Kind::Custom(4454))
|
|
||||||
.author(public_key)
|
|
||||||
.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(vec![now, last]).await?;
|
client.subscribe(vec![filter]).with_id(id).await?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}));
|
}));
|
||||||
@@ -514,7 +406,7 @@ impl DeviceRegistry {
|
|||||||
// Construct an event for device key request
|
// Construct an event for device key request
|
||||||
let builder = EventBuilder::new(Kind::Custom(4454), "").tags(vec![
|
let builder = EventBuilder::new(Kind::Custom(4454), "").tags(vec![
|
||||||
Tag::custom(TagKind::custom("P"), vec![app_pubkey]),
|
Tag::custom(TagKind::custom("P"), vec![app_pubkey]),
|
||||||
Tag::client(app_name()),
|
Tag::client(CLIENT_NAME),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// Sign the event with user's signer
|
// Sign the event with user's signer
|
||||||
@@ -537,7 +429,7 @@ impl DeviceRegistry {
|
|||||||
}
|
}
|
||||||
Ok(None) => {
|
Ok(None) => {
|
||||||
this.update(cx, |this, cx| {
|
this.update(cx, |this, cx| {
|
||||||
this.set_requesting(true, cx);
|
this.set_initializing(false, cx);
|
||||||
this.wait_for_approval(cx);
|
this.wait_for_approval(cx);
|
||||||
|
|
||||||
cx.emit(DeviceEvent::Requesting);
|
cx.emit(DeviceEvent::Requesting);
|
||||||
@@ -602,12 +494,11 @@ 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.set_requesting(false, cx);
|
|
||||||
})?;
|
})?;
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
this.update(cx, |_this, cx| {
|
this.update(cx, |_this, cx| {
|
||||||
cx.emit(DeviceEvent::not_set(e.to_string()));
|
cx.emit(DeviceEvent::error(e.to_string()));
|
||||||
})?;
|
})?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -683,10 +574,10 @@ 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>) {
|
||||||
// Ignore if there is already a pending request
|
// Ignore if there is already a pending request
|
||||||
if self.has_pending_request {
|
if self.pending_request {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
self.set_has_pending_request(true, cx);
|
self.set_pending_request(true, cx);
|
||||||
|
|
||||||
// Show notification
|
// Show notification
|
||||||
let notification = self.notification(event, cx);
|
let notification = self.notification(event, cx);
|
||||||
@@ -706,8 +597,8 @@ impl DeviceRegistry {
|
|||||||
Notification::new()
|
Notification::new()
|
||||||
.type_id::<DeviceNotification>(key)
|
.type_id::<DeviceNotification>(key)
|
||||||
.autohide(false)
|
.autohide(false)
|
||||||
.icon(IconName::UserKey)
|
.with_kind(NotificationKind::Info)
|
||||||
.title(SharedString::from("New request"))
|
.title("Encryption Key Request")
|
||||||
.content(move |_this, _window, cx| {
|
.content(move |_this, _window, cx| {
|
||||||
v_flex()
|
v_flex()
|
||||||
.gap_2()
|
.gap_2()
|
||||||
@@ -730,7 +621,7 @@ impl DeviceRegistry {
|
|||||||
.font_semibold()
|
.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("From:")),
|
||||||
)
|
)
|
||||||
.child(
|
.child(
|
||||||
div()
|
div()
|
||||||
@@ -777,8 +668,6 @@ impl DeviceRegistry {
|
|||||||
|
|
||||||
Button::new("approve")
|
Button::new("approve")
|
||||||
.label("Approve")
|
.label("Approve")
|
||||||
.small()
|
|
||||||
.primary()
|
|
||||||
.loading(loading.get())
|
.loading(loading.get())
|
||||||
.disabled(loading.get())
|
.disabled(loading.get())
|
||||||
.on_click({
|
.on_click({
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ use std::rc::Rc;
|
|||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use anyhow::{Error, anyhow};
|
use anyhow::{Error, anyhow};
|
||||||
use common::EventUtils;
|
use common::EventExt;
|
||||||
use gpui::{App, AppContext, Context, Entity, Global, Task, Window};
|
use gpui::{App, AppContext, Context, Entity, Global, Task, Window};
|
||||||
use nostr_sdk::prelude::*;
|
use nostr_sdk::prelude::*;
|
||||||
use smallvec::{SmallVec, smallvec};
|
use smallvec::{SmallVec, smallvec};
|
||||||
|
|||||||
@@ -15,9 +15,9 @@ use settings::{AppSettings, AuthMode};
|
|||||||
use smallvec::{SmallVec, smallvec};
|
use smallvec::{SmallVec, smallvec};
|
||||||
use state::NostrRegistry;
|
use state::NostrRegistry;
|
||||||
use theme::ActiveTheme;
|
use theme::ActiveTheme;
|
||||||
use ui::button::{Button, ButtonVariants};
|
use ui::button::Button;
|
||||||
use ui::notification::Notification;
|
use ui::notification::{Notification, NotificationKind};
|
||||||
use ui::{Disableable, IconName, Sizable, StyledExt, WindowExtension, v_flex};
|
use ui::{Disableable, 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.";
|
||||||
@@ -327,8 +327,8 @@ impl RelayAuth {
|
|||||||
Notification::new()
|
Notification::new()
|
||||||
.type_id::<AuthNotification>(challenge)
|
.type_id::<AuthNotification>(challenge)
|
||||||
.autohide(false)
|
.autohide(false)
|
||||||
.icon(IconName::Warning)
|
.with_kind(NotificationKind::Info)
|
||||||
.title(SharedString::from("Authentication Required"))
|
.title("Authentication Required")
|
||||||
.content(move |_this, _window, cx| {
|
.content(move |_this, _window, cx| {
|
||||||
v_flex()
|
v_flex()
|
||||||
.gap_2()
|
.gap_2()
|
||||||
@@ -344,7 +344,6 @@ 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)
|
.text_color(cx.theme().text)
|
||||||
.child(url.clone()),
|
.child(url.clone()),
|
||||||
@@ -357,8 +356,6 @@ impl RelayAuth {
|
|||||||
|
|
||||||
Button::new("approve")
|
Button::new("approve")
|
||||||
.label("Approve")
|
.label("Approve")
|
||||||
.small()
|
|
||||||
.primary()
|
|
||||||
.loading(loading.get())
|
.loading(loading.get())
|
||||||
.disabled(loading.get())
|
.disabled(loading.get())
|
||||||
.on_click({
|
.on_click({
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ common = { path = "../common" }
|
|||||||
nostr.workspace = true
|
nostr.workspace = true
|
||||||
nostr-sdk.workspace = true
|
nostr-sdk.workspace = true
|
||||||
nostr-lmdb.workspace = true
|
nostr-lmdb.workspace = true
|
||||||
nostr-memory.workspace = true
|
|
||||||
nostr-gossip-memory.workspace = true
|
nostr-gossip-memory.workspace = true
|
||||||
nostr-connect.workspace = true
|
nostr-connect.workspace = true
|
||||||
nostr-blossom.workspace = true
|
nostr-blossom.workspace = true
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
use std::sync::OnceLock;
|
|
||||||
|
|
||||||
/// Client name (Application name)
|
/// Client name (Application name)
|
||||||
pub const CLIENT_NAME: &str = "Coop";
|
pub const CLIENT_NAME: &str = "Coop";
|
||||||
|
|
||||||
@@ -15,6 +13,9 @@ pub const KEYRING: &str = "Coop Safe Storage";
|
|||||||
/// Default timeout for subscription
|
/// Default timeout for subscription
|
||||||
pub const TIMEOUT: u64 = 2;
|
pub const TIMEOUT: u64 = 2;
|
||||||
|
|
||||||
|
/// Default image cache size
|
||||||
|
pub const IMAGE_CACHE_SIZE: usize = 20;
|
||||||
|
|
||||||
/// Default delay for searching
|
/// Default delay for searching
|
||||||
pub const FIND_DELAY: u64 = 600;
|
pub const FIND_DELAY: u64 = 600;
|
||||||
|
|
||||||
@@ -48,15 +49,3 @@ pub const BOOTSTRAP_RELAYS: [&str; 3] = [
|
|||||||
"wss://relay.primal.net",
|
"wss://relay.primal.net",
|
||||||
"wss://user.kindpag.es",
|
"wss://user.kindpag.es",
|
||||||
];
|
];
|
||||||
|
|
||||||
static APP_NAME: OnceLock<String> = OnceLock::new();
|
|
||||||
|
|
||||||
/// Get the app name
|
|
||||||
pub fn app_name() -> &'static String {
|
|
||||||
APP_NAME.get_or_init(|| {
|
|
||||||
let devicename = whoami::devicename();
|
|
||||||
let platform = whoami::platform();
|
|
||||||
|
|
||||||
format!("{CLIENT_NAME} on {platform} ({devicename})")
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
use std::path::PathBuf;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
@@ -8,7 +9,6 @@ use gpui::{App, AppContext, Context, Entity, EventEmitter, Global, SharedString,
|
|||||||
use nostr_connect::prelude::*;
|
use nostr_connect::prelude::*;
|
||||||
use nostr_gossip_memory::prelude::*;
|
use nostr_gossip_memory::prelude::*;
|
||||||
use nostr_lmdb::prelude::*;
|
use nostr_lmdb::prelude::*;
|
||||||
use nostr_memory::prelude::*;
|
|
||||||
use nostr_sdk::prelude::*;
|
use nostr_sdk::prelude::*;
|
||||||
|
|
||||||
mod blossom;
|
mod blossom;
|
||||||
@@ -44,18 +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
|
/// Creating the signer
|
||||||
FetchingRelayList,
|
Creating,
|
||||||
/// User has not set up NIP-65 relays
|
/// Show the identity dialog
|
||||||
RelayNotConfigured,
|
Show,
|
||||||
/// Connected to NIP-65 relays
|
|
||||||
RelayConnected,
|
|
||||||
/// A new signer has been set
|
/// A new signer has been set
|
||||||
SignerSet,
|
SignerSet,
|
||||||
/// An error occurred
|
/// An error occurred
|
||||||
@@ -80,16 +76,19 @@ pub struct NostrRegistry {
|
|||||||
/// Nostr signer
|
/// Nostr signer
|
||||||
signer: Arc<CoopSigner>,
|
signer: Arc<CoopSigner>,
|
||||||
|
|
||||||
/// Local public keys
|
/// All local stored identities
|
||||||
npubs: Entity<Vec<PublicKey>>,
|
npubs: Entity<Vec<PublicKey>>,
|
||||||
|
|
||||||
/// App keys
|
/// Keys directory
|
||||||
|
key_dir: PathBuf,
|
||||||
|
|
||||||
|
/// Master app keys used for various operations.
|
||||||
///
|
///
|
||||||
/// Used for Nostr Connect and NIP-4e operations
|
/// Example: Nostr Connect and NIP-4e operations
|
||||||
app_keys: Keys,
|
app_keys: Keys,
|
||||||
|
|
||||||
/// Tasks for asynchronous operations
|
/// Tasks for asynchronous operations
|
||||||
tasks: Vec<Task<()>>,
|
tasks: Vec<Task<Result<(), Error>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EventEmitter<StateEvent> for NostrRegistry {}
|
impl EventEmitter<StateEvent> for NostrRegistry {}
|
||||||
@@ -107,55 +106,63 @@ impl NostrRegistry {
|
|||||||
|
|
||||||
/// Create a new nostr instance
|
/// Create a new nostr instance
|
||||||
fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
|
fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||||
|
let key_dir = config_dir().join("keys");
|
||||||
|
let app_keys = get_or_init_app_keys(cx).unwrap_or(Keys::generate());
|
||||||
|
|
||||||
// Construct the nostr signer
|
// Construct the nostr signer
|
||||||
let app_keys = get_or_init_app_keys().unwrap_or(Keys::generate());
|
|
||||||
let signer = Arc::new(CoopSigner::new(app_keys.clone()));
|
let signer = Arc::new(CoopSigner::new(app_keys.clone()));
|
||||||
|
|
||||||
// Construct the nostr npubs entity
|
// Get all local stored npubs
|
||||||
let npubs = cx.new(|_| vec![]);
|
let npubs = cx.new(|_| match Self::discover(&key_dir) {
|
||||||
|
Ok(npubs) => npubs,
|
||||||
// Construct the nostr client builder
|
Err(e) => {
|
||||||
let mut builder = ClientBuilder::default()
|
log::error!("Failed to discover npubs: {e}");
|
||||||
.signer(signer.clone())
|
vec![]
|
||||||
.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)
|
|
||||||
.verify_subscriptions(false)
|
|
||||||
.connect_timeout(Duration::from_secs(10))
|
|
||||||
.sleep_when_idle(SleepWhenIdle::Enabled {
|
|
||||||
timeout: Duration::from_secs(600),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Add database if not in debug mode
|
|
||||||
if !cfg!(debug_assertions) {
|
|
||||||
// Construct the nostr lmdb instance
|
// Construct the nostr lmdb instance
|
||||||
let lmdb = cx.foreground_executor().block_on(async move {
|
let lmdb = cx.foreground_executor().block_on(async move {
|
||||||
NostrLmdb::open(config_dir().join("nostr"))
|
NostrLmdb::open(config_dir().join("nostr"))
|
||||||
.await
|
.await
|
||||||
.expect("Failed to initialize database")
|
.expect("Failed to initialize database")
|
||||||
});
|
});
|
||||||
builder = builder.database(lmdb);
|
|
||||||
} else {
|
|
||||||
builder = builder.database(MemoryDatabase::unbounded())
|
|
||||||
}
|
|
||||||
|
|
||||||
// Build the nostr client
|
// Construct the nostr client
|
||||||
let client = builder.build();
|
let client = ClientBuilder::default()
|
||||||
|
.signer(signer.clone())
|
||||||
|
.database(lmdb)
|
||||||
|
.gossip(NostrGossipMemory::unbounded())
|
||||||
|
.gossip_config(
|
||||||
|
GossipConfig::default()
|
||||||
|
.sync_initial_timeout(Duration::from_millis(100))
|
||||||
|
.sync_idle_timeout(Duration::from_millis(100))
|
||||||
|
.no_background_refresh(),
|
||||||
|
)
|
||||||
|
.automatic_authentication(false)
|
||||||
|
.connect_timeout(Duration::from_secs(10))
|
||||||
|
.sleep_when_idle(SleepWhenIdle::Enabled {
|
||||||
|
timeout: Duration::from_secs(600),
|
||||||
|
})
|
||||||
|
.build();
|
||||||
|
|
||||||
// Run at the end of current cycle
|
// Run at the end of current cycle
|
||||||
cx.defer_in(window, |this, _window, cx| {
|
cx.defer_in(window, |this, _window, cx| {
|
||||||
this.connect(cx);
|
this.connect(cx);
|
||||||
|
// Create an identity if none exists
|
||||||
|
if this.npubs.read(cx).is_empty() {
|
||||||
|
this.create_identity(cx);
|
||||||
|
} else {
|
||||||
|
// Show the identity dialog
|
||||||
|
cx.emit(StateEvent::Show);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
client,
|
client,
|
||||||
signer,
|
signer,
|
||||||
npubs,
|
npubs,
|
||||||
|
key_dir,
|
||||||
app_keys,
|
app_keys,
|
||||||
tasks: vec![],
|
tasks: vec![],
|
||||||
}
|
}
|
||||||
@@ -181,6 +188,33 @@ impl NostrRegistry {
|
|||||||
self.app_keys.clone()
|
self.app_keys.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Discover all npubs in the keys directory
|
||||||
|
fn discover(dir: &PathBuf) -> Result<Vec<PublicKey>, Error> {
|
||||||
|
// Ensure keys directory exists
|
||||||
|
std::fs::create_dir_all(dir)?;
|
||||||
|
|
||||||
|
let files = std::fs::read_dir(dir)?;
|
||||||
|
let mut entries = Vec::new();
|
||||||
|
let mut npubs: Vec<PublicKey> = Vec::new();
|
||||||
|
|
||||||
|
for file in files.flatten() {
|
||||||
|
let metadata = file.metadata()?;
|
||||||
|
let modified_time = metadata.modified()?;
|
||||||
|
let name = file.file_name().into_string().unwrap().replace(".npub", "");
|
||||||
|
entries.push((modified_time, name));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sort by modification time (most recent first)
|
||||||
|
entries.sort_by(|a, b| b.0.cmp(&a.0));
|
||||||
|
|
||||||
|
for (_, name) in entries {
|
||||||
|
let public_key = PublicKey::parse(&name)?;
|
||||||
|
npubs.push(public_key);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(npubs)
|
||||||
|
}
|
||||||
|
|
||||||
/// Connect to the bootstrapping relays
|
/// Connect to the bootstrapping relays
|
||||||
fn connect(&mut self, cx: &mut Context<Self>) {
|
fn connect(&mut self, cx: &mut Context<Self>) {
|
||||||
let client = self.client();
|
let client = self.client();
|
||||||
@@ -219,105 +253,143 @@ impl NostrRegistry {
|
|||||||
// Emit connecting event
|
// Emit connecting event
|
||||||
cx.emit(StateEvent::Connecting);
|
cx.emit(StateEvent::Connecting);
|
||||||
|
|
||||||
self.tasks
|
|
||||||
.push(cx.spawn(async move |this, cx| match task.await {
|
|
||||||
Ok(_) => {
|
|
||||||
this.update(cx, |this, cx| {
|
|
||||||
cx.emit(StateEvent::Connected);
|
|
||||||
this.get_npubs(cx);
|
|
||||||
})
|
|
||||||
.ok();
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
this.update(cx, |_this, cx| {
|
|
||||||
cx.emit(StateEvent::error(e.to_string()));
|
|
||||||
})
|
|
||||||
.ok();
|
|
||||||
}
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get all used npubs
|
|
||||||
fn get_npubs(&mut self, cx: &mut Context<Self>) {
|
|
||||||
let npubs = self.npubs.downgrade();
|
|
||||||
|
|
||||||
let task: Task<Result<Vec<PublicKey>, Error>> = cx.background_spawn(async move {
|
|
||||||
let dir = config_dir().join("keys");
|
|
||||||
// Ensure keys directory exists
|
|
||||||
smol::fs::create_dir_all(&dir).await?;
|
|
||||||
|
|
||||||
let mut files = smol::fs::read_dir(&dir).await?;
|
|
||||||
let mut entries = Vec::new();
|
|
||||||
|
|
||||||
while let Some(Ok(entry)) = files.next().await {
|
|
||||||
let metadata = entry.metadata().await?;
|
|
||||||
let modified_time = metadata.modified()?;
|
|
||||||
let name = entry
|
|
||||||
.file_name()
|
|
||||||
.into_string()
|
|
||||||
.unwrap()
|
|
||||||
.replace(".npub", "");
|
|
||||||
|
|
||||||
entries.push((modified_time, name));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sort by modification time (most recent first)
|
|
||||||
entries.sort_by(|a, b| b.0.cmp(&a.0));
|
|
||||||
|
|
||||||
let mut npubs = Vec::new();
|
|
||||||
|
|
||||||
for (_, name) in entries {
|
|
||||||
let public_key = PublicKey::parse(&name)?;
|
|
||||||
npubs.push(public_key);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(npubs)
|
|
||||||
});
|
|
||||||
|
|
||||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
self.tasks.push(cx.spawn(async move |this, cx| {
|
||||||
match task.await {
|
if let Err(e) = task.await {
|
||||||
Ok(public_keys) => match public_keys.is_empty() {
|
|
||||||
true => {
|
|
||||||
this.update(cx, |this, cx| {
|
|
||||||
this.create_identity(cx);
|
|
||||||
})
|
|
||||||
.ok();
|
|
||||||
}
|
|
||||||
false => {
|
|
||||||
// TODO: auto login
|
|
||||||
npubs
|
|
||||||
.update(cx, |this, cx| {
|
|
||||||
this.extend(public_keys);
|
|
||||||
cx.notify();
|
|
||||||
})
|
|
||||||
.ok();
|
|
||||||
}
|
|
||||||
},
|
|
||||||
Err(e) => {
|
|
||||||
this.update(cx, |_this, cx| {
|
this.update(cx, |_this, cx| {
|
||||||
cx.emit(StateEvent::error(e.to_string()));
|
cx.emit(StateEvent::error(e.to_string()));
|
||||||
})
|
})?;
|
||||||
.ok();
|
} else {
|
||||||
}
|
this.update(cx, |_this, cx| {
|
||||||
|
cx.emit(StateEvent::Connected);
|
||||||
|
})?;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Get the secret for a given npub.
|
||||||
|
pub fn get_secret(
|
||||||
|
&self,
|
||||||
|
public_key: PublicKey,
|
||||||
|
cx: &App,
|
||||||
|
) -> Task<Result<Arc<dyn NostrSigner>, Error>> {
|
||||||
|
let npub = public_key.to_bech32().unwrap();
|
||||||
|
let key_path = self.key_dir.join(format!("{}.npub", npub));
|
||||||
|
let app_keys = self.app_keys.clone();
|
||||||
|
|
||||||
|
if let Ok(payload) = std::fs::read_to_string(key_path) {
|
||||||
|
if !payload.is_empty() {
|
||||||
|
cx.background_spawn(async move {
|
||||||
|
let decrypted = app_keys.nip44_decrypt(&public_key, &payload).await?;
|
||||||
|
let secret = SecretKey::parse(&decrypted)?;
|
||||||
|
let keys = Keys::new(secret);
|
||||||
|
|
||||||
|
Ok(keys.into_nostr_signer())
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
self.get_secret_keyring(&npub, cx)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
self.get_secret_keyring(&npub, cx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the secret for a given npub in the OS credentials store.
|
||||||
|
#[deprecated = "Use get_secret instead"]
|
||||||
|
fn get_secret_keyring(
|
||||||
|
&self,
|
||||||
|
user: &str,
|
||||||
|
cx: &App,
|
||||||
|
) -> Task<Result<Arc<dyn NostrSigner>, Error>> {
|
||||||
|
let read = cx.read_credentials(user);
|
||||||
|
let app_keys = self.app_keys.clone();
|
||||||
|
|
||||||
|
cx.background_spawn(async move {
|
||||||
|
let (_, secret) = read
|
||||||
|
.await
|
||||||
|
.map_err(|_| anyhow!("Failed to get signer. Please re-import the secret key"))?
|
||||||
|
.ok_or_else(|| anyhow!("Failed to get signer. Please re-import the secret key"))?;
|
||||||
|
|
||||||
|
// Try to parse as a direct secret key first
|
||||||
|
if let Ok(secret_key) = SecretKey::from_slice(&secret) {
|
||||||
|
return Ok(Keys::new(secret_key).into_nostr_signer());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert the secret into string
|
||||||
|
let sec = String::from_utf8(secret)
|
||||||
|
.map_err(|_| anyhow!("Failed to parse secret as UTF-8"))?;
|
||||||
|
|
||||||
|
// Try to parse as a NIP-46 URI
|
||||||
|
let uri =
|
||||||
|
NostrConnectUri::parse(&sec).map_err(|_| anyhow!("Failed to parse NIP-46 URI"))?;
|
||||||
|
|
||||||
|
let timeout = Duration::from_secs(NOSTR_CONNECT_TIMEOUT);
|
||||||
|
let mut nip46 = NostrConnect::new(uri, app_keys, timeout, None)?;
|
||||||
|
|
||||||
|
// Set the auth URL handler
|
||||||
|
nip46.auth_url_handler(CoopAuthUrlHandler);
|
||||||
|
|
||||||
|
Ok(nip46.into_nostr_signer())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Add a new npub to the keys directory
|
||||||
|
fn write_secret(
|
||||||
|
&self,
|
||||||
|
public_key: PublicKey,
|
||||||
|
secret: String,
|
||||||
|
cx: &App,
|
||||||
|
) -> Task<Result<(), Error>> {
|
||||||
|
let npub = public_key.to_bech32().unwrap();
|
||||||
|
let key_path = self.key_dir.join(format!("{}.npub", npub));
|
||||||
|
let app_keys = self.app_keys.clone();
|
||||||
|
|
||||||
|
cx.background_spawn(async move {
|
||||||
|
// If the secret starts with "bunker://" (nostr connect), use it directly; otherwise, encrypt it
|
||||||
|
let content = if secret.starts_with("bunker://") {
|
||||||
|
secret
|
||||||
|
} else {
|
||||||
|
app_keys.nip44_encrypt(&public_key, &secret).await?
|
||||||
|
};
|
||||||
|
|
||||||
|
// Write the encrypted secret to the keys directory
|
||||||
|
smol::fs::write(key_path, &content).await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove a secret
|
||||||
|
pub fn remove_secret(&mut self, public_key: &PublicKey, cx: &mut Context<Self>) {
|
||||||
|
let public_key = public_key.to_owned();
|
||||||
|
let npub = public_key.to_bech32().unwrap();
|
||||||
|
|
||||||
|
let keys_dir = config_dir().join("keys");
|
||||||
|
let key_path = keys_dir.join(format!("{}.npub", npub));
|
||||||
|
|
||||||
|
// Remove the secret file from the keys directory
|
||||||
|
std::fs::remove_file(key_path).ok();
|
||||||
|
|
||||||
|
self.npubs.update(cx, |this, cx| {
|
||||||
|
this.retain(|k| k != &public_key);
|
||||||
|
cx.notify();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/// Create a new identity
|
/// Create a new identity
|
||||||
fn create_identity(&mut self, cx: &mut Context<Self>) {
|
pub fn create_identity(&mut self, cx: &mut Context<Self>) {
|
||||||
let client = self.client();
|
let client = self.client();
|
||||||
let keys = Keys::generate();
|
let keys = Keys::generate();
|
||||||
let async_keys = keys.clone();
|
let async_keys = keys.clone();
|
||||||
|
|
||||||
let username = keys.public_key().to_bech32().unwrap();
|
|
||||||
let secret = keys.secret_key().to_secret_bytes();
|
|
||||||
|
|
||||||
// Create a write credential task
|
|
||||||
let write_credential = cx.write_credentials(&username, &username, &secret);
|
|
||||||
|
|
||||||
// Emit creating event
|
// Emit creating event
|
||||||
cx.emit(StateEvent::Creating);
|
cx.emit(StateEvent::Creating);
|
||||||
|
|
||||||
|
// Create the write secret task
|
||||||
|
let write_secret =
|
||||||
|
self.write_secret(keys.public_key(), keys.secret_key().to_secret_hex(), cx);
|
||||||
|
|
||||||
// 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();
|
||||||
@@ -362,14 +434,10 @@ impl NostrRegistry {
|
|||||||
let event = EventBuilder::nip17_relay_list(relays).sign(&signer).await?;
|
let event = EventBuilder::nip17_relay_list(relays).sign(&signer).await?;
|
||||||
|
|
||||||
// Publish messaging relay list event
|
// Publish messaging relay list event
|
||||||
client
|
client.send_event(&event).to_nip65().await?;
|
||||||
.send_event(&event)
|
|
||||||
.to_nip65()
|
|
||||||
.ack_policy(AckPolicy::none())
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
// Write user's credentials to the system keyring
|
// Write user's credentials to the system keyring
|
||||||
write_credential.await?;
|
write_secret.await?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
});
|
});
|
||||||
@@ -379,58 +447,19 @@ impl NostrRegistry {
|
|||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
this.update(cx, |this, cx| {
|
this.update(cx, |this, cx| {
|
||||||
this.set_signer(keys, cx);
|
this.set_signer(keys, cx);
|
||||||
})
|
})?;
|
||||||
.ok();
|
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
this.update(cx, |_this, cx| {
|
this.update(cx, |_this, cx| {
|
||||||
cx.emit(StateEvent::error(e.to_string()));
|
cx.emit(StateEvent::error(e.to_string()));
|
||||||
})
|
})?;
|
||||||
.ok();
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
Ok(())
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the signer in keyring by username
|
|
||||||
pub fn get_signer(
|
|
||||||
&self,
|
|
||||||
public_key: &PublicKey,
|
|
||||||
cx: &App,
|
|
||||||
) -> Task<Result<Arc<dyn NostrSigner>, Error>> {
|
|
||||||
let username = public_key.to_bech32().unwrap();
|
|
||||||
let app_keys = self.app_keys.clone();
|
|
||||||
let read_credential = cx.read_credentials(&username);
|
|
||||||
|
|
||||||
cx.spawn(async move |_cx| {
|
|
||||||
let (_, secret) = read_credential
|
|
||||||
.await
|
|
||||||
.map_err(|_| anyhow!("Failed to get signer. Please re-import the secret key"))?
|
|
||||||
.ok_or_else(|| anyhow!("Failed to get signer. Please re-import the secret key"))?;
|
|
||||||
|
|
||||||
// Try to parse as a direct secret key first
|
|
||||||
if let Ok(secret_key) = SecretKey::from_slice(&secret) {
|
|
||||||
return Ok(Keys::new(secret_key).into_nostr_signer());
|
|
||||||
}
|
|
||||||
|
|
||||||
// Convert the secret into string
|
|
||||||
let sec = String::from_utf8(secret)
|
|
||||||
.map_err(|_| anyhow!("Failed to parse secret as UTF-8"))?;
|
|
||||||
|
|
||||||
// Try to parse as a NIP-46 URI
|
|
||||||
let uri =
|
|
||||||
NostrConnectUri::parse(&sec).map_err(|_| anyhow!("Failed to parse NIP-46 URI"))?;
|
|
||||||
|
|
||||||
let timeout = Duration::from_secs(NOSTR_CONNECT_TIMEOUT);
|
|
||||||
let mut nip46 = NostrConnect::new(uri, app_keys, timeout, None)?;
|
|
||||||
|
|
||||||
// Set the auth URL handler
|
|
||||||
nip46.auth_url_handler(CoopAuthUrlHandler);
|
|
||||||
|
|
||||||
Ok(nip46.into_nostr_signer())
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Set the signer for the nostr client and verify the public key
|
/// Set the signer for the nostr client and verify the public key
|
||||||
pub fn set_signer<T>(&mut self, new: T, cx: &mut Context<Self>)
|
pub fn set_signer<T>(&mut self, new: T, cx: &mut Context<Self>)
|
||||||
where
|
where
|
||||||
@@ -449,15 +478,6 @@ impl NostrRegistry {
|
|||||||
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?;
|
||||||
|
|
||||||
let npub = public_key.to_bech32().unwrap();
|
|
||||||
let keys_dir = config_dir().join("keys");
|
|
||||||
|
|
||||||
// Ensure keys directory exists
|
|
||||||
smol::fs::create_dir_all(&keys_dir).await?;
|
|
||||||
|
|
||||||
let key_path = keys_dir.join(format!("{}.npub", npub));
|
|
||||||
smol::fs::write(key_path, "").await?;
|
|
||||||
|
|
||||||
log::info!("Signer's public key: {}", public_key);
|
log::info!("Signer's public key: {}", public_key);
|
||||||
Ok(public_key)
|
Ok(public_key)
|
||||||
});
|
});
|
||||||
@@ -465,9 +485,7 @@ impl NostrRegistry {
|
|||||||
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(public_key) => {
|
Ok(public_key) => {
|
||||||
// Update states
|
|
||||||
this.update(cx, |this, cx| {
|
this.update(cx, |this, cx| {
|
||||||
this.ensure_relay_list(&public_key, cx);
|
|
||||||
// Add public key to npubs if not already present
|
// Add public key to npubs if not already present
|
||||||
this.npubs.update(cx, |this, cx| {
|
this.npubs.update(cx, |this, cx| {
|
||||||
if !this.contains(&public_key) {
|
if !this.contains(&public_key) {
|
||||||
@@ -475,65 +493,43 @@ impl NostrRegistry {
|
|||||||
cx.notify();
|
cx.notify();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Emit signer changed event
|
// Emit signer changed event
|
||||||
cx.emit(StateEvent::SignerSet);
|
cx.emit(StateEvent::SignerSet);
|
||||||
})
|
})?;
|
||||||
.ok();
|
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
this.update(cx, |_this, cx| {
|
this.update(cx, |_this, cx| {
|
||||||
cx.emit(StateEvent::error(e.to_string()));
|
cx.emit(StateEvent::error(e.to_string()));
|
||||||
})
|
})?;
|
||||||
.ok();
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Remove a signer from the keyring
|
Ok(())
|
||||||
pub fn remove_signer(&mut self, public_key: &PublicKey, cx: &mut Context<Self>) {
|
|
||||||
let public_key = public_key.to_owned();
|
|
||||||
let npub = public_key.to_bech32().unwrap();
|
|
||||||
let keys_dir = config_dir().join("keys");
|
|
||||||
|
|
||||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
|
||||||
let key_path = keys_dir.join(format!("{}.npub", npub));
|
|
||||||
smol::fs::remove_file(key_path).await.ok();
|
|
||||||
|
|
||||||
this.update(cx, |this, cx| {
|
|
||||||
this.npubs().update(cx, |this, cx| {
|
|
||||||
this.retain(|k| k != &public_key);
|
|
||||||
cx.notify();
|
|
||||||
});
|
|
||||||
})
|
|
||||||
.ok();
|
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Add a key signer to keyring
|
/// Add a key signer to keyring
|
||||||
pub fn add_key_signer(&mut self, keys: &Keys, cx: &mut Context<Self>) {
|
pub fn add_key_signer(&mut self, keys: &Keys, cx: &mut Context<Self>) {
|
||||||
let keys = keys.clone();
|
let keys = keys.clone();
|
||||||
let username = keys.public_key().to_bech32().unwrap();
|
let write_secret =
|
||||||
let secret = keys.secret_key().to_secret_bytes();
|
self.write_secret(keys.public_key(), keys.secret_key().to_secret_hex(), cx);
|
||||||
|
|
||||||
// Write the credential to the keyring
|
|
||||||
let write_credential = cx.write_credentials(&username, "keys", &secret);
|
|
||||||
|
|
||||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
self.tasks.push(cx.spawn(async move |this, cx| {
|
||||||
match write_credential.await {
|
match write_secret.await {
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
this.update(cx, |this, cx| {
|
this.update(cx, |this, cx| {
|
||||||
this.set_signer(keys, cx);
|
this.set_signer(keys, cx);
|
||||||
})
|
})?;
|
||||||
.ok();
|
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
this.update(cx, |_this, cx| {
|
this.update(cx, |_this, cx| {
|
||||||
cx.emit(StateEvent::error(e.to_string()));
|
cx.emit(StateEvent::error(e.to_string()));
|
||||||
})
|
})?;
|
||||||
.ok();
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
Ok(())
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -554,154 +550,35 @@ impl NostrRegistry {
|
|||||||
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((public_key, uri)) => {
|
Ok((public_key, uri)) => {
|
||||||
let username = public_key.to_bech32().unwrap();
|
// Create the write secret task
|
||||||
let write_credential = this
|
let write_secret = this.read_with(cx, |this, cx| {
|
||||||
.read_with(cx, |_this, cx| {
|
this.write_secret(public_key, uri.to_string(), cx)
|
||||||
cx.write_credentials(
|
})?;
|
||||||
&username,
|
|
||||||
"nostrconnect",
|
|
||||||
uri.to_string().as_bytes(),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
match write_credential.await {
|
match write_secret.await {
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
this.update(cx, |this, cx| {
|
this.update(cx, |this, cx| {
|
||||||
this.set_signer(nip46, cx);
|
this.set_signer(nip46, cx);
|
||||||
})
|
})?;
|
||||||
.ok();
|
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
this.update(cx, |_this, cx| {
|
this.update(cx, |_this, cx| {
|
||||||
cx.emit(StateEvent::error(e.to_string()));
|
cx.emit(StateEvent::error(e.to_string()));
|
||||||
})
|
})?;
|
||||||
.ok();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
this.update(cx, |_this, cx| {
|
this.update(cx, |_this, cx| {
|
||||||
cx.emit(StateEvent::error(e.to_string()));
|
cx.emit(StateEvent::error(e.to_string()));
|
||||||
})
|
})?;
|
||||||
.ok();
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 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>) {
|
|
||||||
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(())
|
Ok(())
|
||||||
});
|
|
||||||
|
|
||||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
|
||||||
match task.await {
|
|
||||||
Ok(_) => {
|
|
||||||
this.update(cx, |_this, cx| {
|
|
||||||
cx.emit(StateEvent::RelayConnected);
|
|
||||||
})
|
|
||||||
.ok();
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
this.update(cx, |_this, cx| {
|
|
||||||
cx.emit(StateEvent::RelayNotConfigured);
|
|
||||||
cx.emit(StateEvent::error(e.to_string()));
|
|
||||||
})
|
|
||||||
.ok();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get an event with the given author and kind.
|
|
||||||
pub fn get_event(
|
|
||||||
&self,
|
|
||||||
author: &PublicKey,
|
|
||||||
kind: Kind,
|
|
||||||
cx: &App,
|
|
||||||
) -> Task<Result<Event, Error>> {
|
|
||||||
let client = self.client();
|
|
||||||
let public_key = *author;
|
|
||||||
|
|
||||||
cx.background_spawn(async move {
|
|
||||||
let filter = Filter::new().kind(kind).author(public_key).limit(1);
|
|
||||||
let mut stream = client
|
|
||||||
.stream_events(filter)
|
|
||||||
.timeout(Duration::from_millis(800))
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
while let Some((_url, res)) = stream.next().await {
|
|
||||||
if let Ok(event) = res {
|
|
||||||
return Ok(event);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Err(anyhow!("No event found"))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get the public key of a NIP-05 address
|
/// Get the public key of a NIP-05 address
|
||||||
pub fn get_address(&self, addr: Nip05Address, cx: &App) -> Task<Result<PublicKey, Error>> {
|
pub fn get_address(&self, addr: Nip05Address, cx: &App) -> Task<Result<PublicKey, Error>> {
|
||||||
let client = self.client();
|
let client = self.client();
|
||||||
@@ -857,29 +734,33 @@ impl NostrRegistry {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get or create a new app keys
|
/// Get or create new app keys
|
||||||
fn get_or_init_app_keys() -> Result<Keys, Error> {
|
fn get_or_init_app_keys(cx: &App) -> Result<Keys, Error> {
|
||||||
let dir = config_dir().join(".app_keys");
|
let read = cx.read_credentials(CLIENT_NAME);
|
||||||
|
let stored_keys: Option<Keys> = cx.foreground_executor().block_on(async move {
|
||||||
let content = match std::fs::read(&dir) {
|
if let Ok(Some((_, secret))) = read.await {
|
||||||
Ok(content) => content,
|
SecretKey::from_slice(&secret).map(Keys::new).ok()
|
||||||
Err(_) => {
|
} else {
|
||||||
// Generate new keys if file doesn't exist
|
None
|
||||||
let keys = Keys::generate();
|
|
||||||
let secret_key = keys.secret_key();
|
|
||||||
|
|
||||||
// Create directory and write secret key
|
|
||||||
std::fs::create_dir_all(dir.parent().unwrap())?;
|
|
||||||
std::fs::write(&dir, secret_key.to_secret_bytes())?;
|
|
||||||
|
|
||||||
return Ok(keys);
|
|
||||||
}
|
}
|
||||||
};
|
});
|
||||||
|
|
||||||
let secret_key = SecretKey::from_slice(&content)?;
|
if let Some(keys) = stored_keys {
|
||||||
let keys = Keys::new(secret_key);
|
Ok(keys)
|
||||||
|
} else {
|
||||||
|
let keys = Keys::generate();
|
||||||
|
let user = keys.public_key().to_hex();
|
||||||
|
let secret = keys.secret_key().to_secret_bytes();
|
||||||
|
let write = cx.write_credentials(CLIENT_NAME, &user, &secret);
|
||||||
|
|
||||||
|
cx.foreground_executor().block_on(async move {
|
||||||
|
if let Err(e) = write.await {
|
||||||
|
log::error!("Keyring not available or panic: {e}")
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
Ok(keys)
|
Ok(keys)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn default_relay_list() -> Vec<(RelayUrl, Option<RelayMetadata>)> {
|
fn default_relay_list() -> Vec<(RelayUrl, Option<RelayMetadata>)> {
|
||||||
@@ -911,7 +792,7 @@ fn default_messaging_relays() -> Vec<RelayUrl> {
|
|||||||
vec![
|
vec![
|
||||||
RelayUrl::parse("wss://nos.lol").unwrap(),
|
RelayUrl::parse("wss://nos.lol").unwrap(),
|
||||||
RelayUrl::parse("wss://nip17.com").unwrap(),
|
RelayUrl::parse("wss://nip17.com").unwrap(),
|
||||||
RelayUrl::parse("wss://relay.0xchat.com").unwrap(),
|
RelayUrl::parse("wss://auth.nostr1.com").unwrap(),
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ impl CoopSigner {
|
|||||||
/// Get public key
|
/// Get public key
|
||||||
///
|
///
|
||||||
/// Ensure to call this method after the signer has been initialized.
|
/// Ensure to call this method after the signer has been initialized.
|
||||||
/// Otherwise, this method will panic.
|
/// Otherwise, it will panic.
|
||||||
pub fn public_key(&self) -> Option<PublicKey> {
|
pub fn public_key(&self) -> Option<PublicKey> {
|
||||||
*self.signer_pkey.read_blocking()
|
*self.signer_pkey.read_blocking()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use std::fmt::{self, Debug, Display, Formatter};
|
use std::fmt::{self, Debug, Display, Formatter};
|
||||||
|
|
||||||
use gpui::{AbsoluteLength, Axis, Corner, Length, Pixels};
|
use gpui::{AbsoluteLength, Axis, Length, Pixels};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
/// A enum for defining the placement of the element.
|
/// A enum for defining the placement of the element.
|
||||||
@@ -49,141 +49,6 @@ impl Placement {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The anchor position of an element.
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
|
||||||
pub enum Anchor {
|
|
||||||
#[default]
|
|
||||||
#[serde(rename = "top-left")]
|
|
||||||
TopLeft,
|
|
||||||
#[serde(rename = "top-center")]
|
|
||||||
TopCenter,
|
|
||||||
#[serde(rename = "top-right")]
|
|
||||||
TopRight,
|
|
||||||
#[serde(rename = "bottom-left")]
|
|
||||||
BottomLeft,
|
|
||||||
#[serde(rename = "bottom-center")]
|
|
||||||
BottomCenter,
|
|
||||||
#[serde(rename = "bottom-right")]
|
|
||||||
BottomRight,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Display for Anchor {
|
|
||||||
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
|
||||||
match self {
|
|
||||||
Anchor::TopLeft => write!(f, "TopLeft"),
|
|
||||||
Anchor::TopCenter => write!(f, "TopCenter"),
|
|
||||||
Anchor::TopRight => write!(f, "TopRight"),
|
|
||||||
Anchor::BottomLeft => write!(f, "BottomLeft"),
|
|
||||||
Anchor::BottomCenter => write!(f, "BottomCenter"),
|
|
||||||
Anchor::BottomRight => write!(f, "BottomRight"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Anchor {
|
|
||||||
/// Returns true if the anchor is at the top.
|
|
||||||
#[inline]
|
|
||||||
pub fn is_top(&self) -> bool {
|
|
||||||
matches!(self, Self::TopLeft | Self::TopCenter | Self::TopRight)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns true if the anchor is at the bottom.
|
|
||||||
#[inline]
|
|
||||||
pub fn is_bottom(&self) -> bool {
|
|
||||||
matches!(
|
|
||||||
self,
|
|
||||||
Self::BottomLeft | Self::BottomCenter | Self::BottomRight
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns true if the anchor is at the left.
|
|
||||||
#[inline]
|
|
||||||
pub fn is_left(&self) -> bool {
|
|
||||||
matches!(self, Self::TopLeft | Self::BottomLeft)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns true if the anchor is at the right.
|
|
||||||
#[inline]
|
|
||||||
pub fn is_right(&self) -> bool {
|
|
||||||
matches!(self, Self::TopRight | Self::BottomRight)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns true if the anchor is at the center.
|
|
||||||
#[inline]
|
|
||||||
pub fn is_center(&self) -> bool {
|
|
||||||
matches!(self, Self::TopCenter | Self::BottomCenter)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Swaps the vertical position of the anchor.
|
|
||||||
pub fn swap_vertical(&self) -> Self {
|
|
||||||
match self {
|
|
||||||
Anchor::TopLeft => Anchor::BottomLeft,
|
|
||||||
Anchor::TopCenter => Anchor::BottomCenter,
|
|
||||||
Anchor::TopRight => Anchor::BottomRight,
|
|
||||||
Anchor::BottomLeft => Anchor::TopLeft,
|
|
||||||
Anchor::BottomCenter => Anchor::TopCenter,
|
|
||||||
Anchor::BottomRight => Anchor::TopRight,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Swaps the horizontal position of the anchor.
|
|
||||||
pub fn swap_horizontal(&self) -> Self {
|
|
||||||
match self {
|
|
||||||
Anchor::TopLeft => Anchor::TopRight,
|
|
||||||
Anchor::TopCenter => Anchor::TopCenter,
|
|
||||||
Anchor::TopRight => Anchor::TopLeft,
|
|
||||||
Anchor::BottomLeft => Anchor::BottomRight,
|
|
||||||
Anchor::BottomCenter => Anchor::BottomCenter,
|
|
||||||
Anchor::BottomRight => Anchor::BottomLeft,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn other_side_corner_along(&self, axis: Axis) -> Anchor {
|
|
||||||
match axis {
|
|
||||||
Axis::Vertical => match self {
|
|
||||||
Self::TopLeft => Self::BottomLeft,
|
|
||||||
Self::TopCenter => Self::BottomCenter,
|
|
||||||
Self::TopRight => Self::BottomRight,
|
|
||||||
Self::BottomLeft => Self::TopLeft,
|
|
||||||
Self::BottomCenter => Self::TopCenter,
|
|
||||||
Self::BottomRight => Self::TopRight,
|
|
||||||
},
|
|
||||||
Axis::Horizontal => match self {
|
|
||||||
Self::TopLeft => Self::TopRight,
|
|
||||||
Self::TopCenter => Self::TopCenter,
|
|
||||||
Self::TopRight => Self::TopLeft,
|
|
||||||
Self::BottomLeft => Self::BottomRight,
|
|
||||||
Self::BottomCenter => Self::BottomCenter,
|
|
||||||
Self::BottomRight => Self::BottomLeft,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<Corner> for Anchor {
|
|
||||||
fn from(corner: Corner) -> Self {
|
|
||||||
match corner {
|
|
||||||
Corner::TopLeft => Anchor::TopLeft,
|
|
||||||
Corner::TopRight => Anchor::TopRight,
|
|
||||||
Corner::BottomLeft => Anchor::BottomLeft,
|
|
||||||
Corner::BottomRight => Anchor::BottomRight,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<Anchor> for Corner {
|
|
||||||
fn from(anchor: Anchor) -> Self {
|
|
||||||
match anchor {
|
|
||||||
Anchor::TopLeft => Corner::TopLeft,
|
|
||||||
Anchor::TopRight => Corner::TopRight,
|
|
||||||
Anchor::BottomLeft => Corner::BottomLeft,
|
|
||||||
Anchor::BottomRight => Corner::BottomRight,
|
|
||||||
Anchor::TopCenter => Corner::TopLeft,
|
|
||||||
Anchor::BottomCenter => Corner::BottomLeft,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A enum for defining the side of the element.
|
/// A enum for defining the side of the element.
|
||||||
///
|
///
|
||||||
/// See also: [`Placement`] if you need to define the 4 edges.
|
/// See also: [`Placement`] if you need to define the 4 edges.
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
use gpui::{Pixels, px};
|
use gpui::{Anchor, Pixels, px};
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
use crate::{Anchor, Edges, TITLEBAR_HEIGHT};
|
use crate::{Edges, TITLEBAR_HEIGHT};
|
||||||
|
|
||||||
/// The settings for notifications.
|
/// The settings for notifications.
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct NotificationSettings {
|
pub struct NotificationSettings {
|
||||||
/// The placement of the notification, default: [`Anchor::TopRight`]
|
/// The placement of the notification, default: [`Anchor::TopRight`]
|
||||||
pub placement: Anchor,
|
pub placement: Anchor,
|
||||||
|
|||||||
@@ -1,332 +0,0 @@
|
|||||||
//! This is a fork of gpui's anchored element that adds support for offsetting
|
|
||||||
//! https://github.com/zed-industries/zed/blob/b06f4088a3565c5e30663106ff79c1ced645d87a/crates/gpui/src/elements/anchored.rs
|
|
||||||
use gpui::{
|
|
||||||
AnyElement, App, Axis, Bounds, Display, Edges, Element, GlobalElementId, Half,
|
|
||||||
InspectorElementId, IntoElement, LayoutId, ParentElement, Pixels, Point, Position, Size, Style,
|
|
||||||
Window, point, px,
|
|
||||||
};
|
|
||||||
use smallvec::SmallVec;
|
|
||||||
use theme::Anchor;
|
|
||||||
|
|
||||||
/// The state that the anchored element element uses to track its children.
|
|
||||||
pub struct AnchoredState {
|
|
||||||
child_layout_ids: SmallVec<[LayoutId; 4]>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An anchored element that can be used to display UI that
|
|
||||||
/// will avoid overflowing the window bounds.
|
|
||||||
pub(crate) struct Anchored {
|
|
||||||
children: SmallVec<[AnyElement; 2]>,
|
|
||||||
anchor_corner: Anchor,
|
|
||||||
fit_mode: AnchoredFitMode,
|
|
||||||
anchor_position: Option<Point<Pixels>>,
|
|
||||||
position_mode: AnchoredPositionMode,
|
|
||||||
offset: Option<Point<Pixels>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// anchored gives you an element that will avoid overflowing the window bounds.
|
|
||||||
/// Its children should have no margin to avoid measurement issues.
|
|
||||||
pub(crate) fn anchored() -> Anchored {
|
|
||||||
Anchored {
|
|
||||||
children: SmallVec::new(),
|
|
||||||
anchor_corner: Anchor::TopLeft,
|
|
||||||
fit_mode: AnchoredFitMode::SwitchAnchor,
|
|
||||||
anchor_position: None,
|
|
||||||
position_mode: AnchoredPositionMode::Window,
|
|
||||||
offset: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[allow(dead_code)]
|
|
||||||
impl Anchored {
|
|
||||||
/// Sets which corner of the anchored element should be anchored to the current position.
|
|
||||||
pub fn anchor(mut self, anchor: Anchor) -> Self {
|
|
||||||
self.anchor_corner = anchor;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Sets the position in window coordinates
|
|
||||||
/// (otherwise the location the anchored element is rendered is used)
|
|
||||||
pub fn position(mut self, anchor: Point<Pixels>) -> Self {
|
|
||||||
self.anchor_position = Some(anchor);
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Offset the final position by this amount.
|
|
||||||
/// Useful when you want to anchor to an element but offset from it, such as in PopoverMenu.
|
|
||||||
pub fn offset(mut self, offset: Point<Pixels>) -> Self {
|
|
||||||
self.offset = Some(offset);
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Sets the position mode for this anchored element. Local will have this
|
|
||||||
/// interpret its [`Anchored::position`] as relative to the parent element.
|
|
||||||
/// While Window will have it interpret the position as relative to the window.
|
|
||||||
pub fn position_mode(mut self, mode: AnchoredPositionMode) -> Self {
|
|
||||||
self.position_mode = mode;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Snap to window edge instead of switching anchor corner when an overflow would occur.
|
|
||||||
pub fn snap_to_window(mut self) -> Self {
|
|
||||||
self.fit_mode = AnchoredFitMode::SnapToWindow;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Snap to window edge and leave some margins.
|
|
||||||
pub fn snap_to_window_with_margin(mut self, edges: impl Into<Edges<Pixels>>) -> Self {
|
|
||||||
self.fit_mode = AnchoredFitMode::SnapToWindowWithMargin(edges.into());
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ParentElement for Anchored {
|
|
||||||
fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
|
|
||||||
self.children.extend(elements)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Element for Anchored {
|
|
||||||
type PrepaintState = ();
|
|
||||||
type RequestLayoutState = AnchoredState;
|
|
||||||
|
|
||||||
fn id(&self) -> Option<gpui::ElementId> {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
fn request_layout(
|
|
||||||
&mut self,
|
|
||||||
_id: Option<&GlobalElementId>,
|
|
||||||
_inspector_id: Option<&InspectorElementId>,
|
|
||||||
window: &mut Window,
|
|
||||||
cx: &mut App,
|
|
||||||
) -> (gpui::LayoutId, Self::RequestLayoutState) {
|
|
||||||
let child_layout_ids = self
|
|
||||||
.children
|
|
||||||
.iter_mut()
|
|
||||||
.map(|child| child.request_layout(window, cx))
|
|
||||||
.collect::<SmallVec<_>>();
|
|
||||||
|
|
||||||
let anchored_style = Style {
|
|
||||||
position: Position::Absolute,
|
|
||||||
display: Display::Flex,
|
|
||||||
..Style::default()
|
|
||||||
};
|
|
||||||
|
|
||||||
let layout_id = window.request_layout(anchored_style, child_layout_ids.iter().copied(), cx);
|
|
||||||
|
|
||||||
(layout_id, AnchoredState { child_layout_ids })
|
|
||||||
}
|
|
||||||
|
|
||||||
fn prepaint(
|
|
||||||
&mut self,
|
|
||||||
_id: Option<&GlobalElementId>,
|
|
||||||
_inspector_id: Option<&InspectorElementId>,
|
|
||||||
bounds: Bounds<Pixels>,
|
|
||||||
request_layout: &mut Self::RequestLayoutState,
|
|
||||||
window: &mut Window,
|
|
||||||
cx: &mut App,
|
|
||||||
) {
|
|
||||||
if request_layout.child_layout_ids.is_empty() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut child_min = point(Pixels::MAX, Pixels::MAX);
|
|
||||||
let mut child_max = Point::default();
|
|
||||||
for child_layout_id in &request_layout.child_layout_ids {
|
|
||||||
let child_bounds = window.layout_bounds(*child_layout_id);
|
|
||||||
child_min = child_min.min(&child_bounds.origin);
|
|
||||||
child_max = child_max.max(&child_bounds.bottom_right());
|
|
||||||
}
|
|
||||||
let size: Size<Pixels> = (child_max - child_min).into();
|
|
||||||
|
|
||||||
let (origin, mut desired) = self.position_mode.get_position_and_bounds(
|
|
||||||
self.anchor_position,
|
|
||||||
self.anchor_corner,
|
|
||||||
size,
|
|
||||||
bounds,
|
|
||||||
self.offset,
|
|
||||||
);
|
|
||||||
|
|
||||||
let limits = Bounds {
|
|
||||||
origin: Point::default(),
|
|
||||||
size: window.viewport_size(),
|
|
||||||
};
|
|
||||||
|
|
||||||
if self.fit_mode == AnchoredFitMode::SwitchAnchor {
|
|
||||||
let mut anchor_corner = self.anchor_corner;
|
|
||||||
|
|
||||||
if desired.left() < limits.left() || desired.right() > limits.right() {
|
|
||||||
let switched = Bounds::from_corner_and_size(
|
|
||||||
anchor_corner
|
|
||||||
.other_side_corner_along(Axis::Horizontal)
|
|
||||||
.into(),
|
|
||||||
origin,
|
|
||||||
size,
|
|
||||||
);
|
|
||||||
if !(switched.left() < limits.left() || switched.right() > limits.right()) {
|
|
||||||
anchor_corner = anchor_corner.other_side_corner_along(Axis::Horizontal);
|
|
||||||
desired = switched
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if desired.top() < limits.top() || desired.bottom() > limits.bottom() {
|
|
||||||
let switched = Bounds::from_corner_and_size(
|
|
||||||
anchor_corner.other_side_corner_along(Axis::Vertical).into(),
|
|
||||||
origin,
|
|
||||||
size,
|
|
||||||
);
|
|
||||||
if !(switched.top() < limits.top() || switched.bottom() > limits.bottom()) {
|
|
||||||
desired = switched;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let client_inset = window.client_inset().unwrap_or(px(0.));
|
|
||||||
let edges = match self.fit_mode {
|
|
||||||
AnchoredFitMode::SnapToWindowWithMargin(edges) => edges,
|
|
||||||
_ => Edges::default(),
|
|
||||||
}
|
|
||||||
.map(|edge| *edge + client_inset);
|
|
||||||
|
|
||||||
// Snap the horizontal edges of the anchored element to the horizontal edges of the window if
|
|
||||||
// its horizontal bounds overflow, aligning to the left if it is wider than the limits.
|
|
||||||
if desired.right() > limits.right() {
|
|
||||||
desired.origin.x -= desired.right() - limits.right() + edges.right;
|
|
||||||
}
|
|
||||||
if desired.left() < limits.left() {
|
|
||||||
desired.origin.x = limits.origin.x + edges.left;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Snap the vertical edges of the anchored element to the vertical edges of the window if
|
|
||||||
// its vertical bounds overflow, aligning to the top if it is taller than the limits.
|
|
||||||
if desired.bottom() > limits.bottom() {
|
|
||||||
desired.origin.y -= desired.bottom() - limits.bottom() + edges.bottom;
|
|
||||||
}
|
|
||||||
if desired.top() < limits.top() {
|
|
||||||
desired.origin.y = limits.origin.y + edges.top;
|
|
||||||
}
|
|
||||||
|
|
||||||
let offset = desired.origin - bounds.origin;
|
|
||||||
let offset = point(offset.x.round(), offset.y.round());
|
|
||||||
|
|
||||||
window.with_element_offset(offset, |window| {
|
|
||||||
for child in &mut self.children {
|
|
||||||
child.prepaint(window, cx);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn paint(
|
|
||||||
&mut self,
|
|
||||||
_id: Option<&GlobalElementId>,
|
|
||||||
_inspector_id: Option<&InspectorElementId>,
|
|
||||||
_bounds: Bounds<Pixels>,
|
|
||||||
_request_layout: &mut Self::RequestLayoutState,
|
|
||||||
_prepaint: &mut Self::PrepaintState,
|
|
||||||
window: &mut Window,
|
|
||||||
cx: &mut App,
|
|
||||||
) {
|
|
||||||
for child in &mut self.children {
|
|
||||||
child.paint(window, cx);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl IntoElement for Anchored {
|
|
||||||
type Element = Self;
|
|
||||||
|
|
||||||
fn into_element(self) -> Self::Element {
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Which algorithm to use when fitting the anchored element to be inside the window.
|
|
||||||
#[allow(dead_code)]
|
|
||||||
#[derive(Copy, Clone, PartialEq)]
|
|
||||||
pub enum AnchoredFitMode {
|
|
||||||
/// Snap the anchored element to the window edge.
|
|
||||||
SnapToWindow,
|
|
||||||
/// Snap to window edge and leave some margins.
|
|
||||||
SnapToWindowWithMargin(Edges<Pixels>),
|
|
||||||
/// Switch which corner anchor this anchored element is attached to.
|
|
||||||
SwitchAnchor,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Which algorithm to use when positioning the anchored element.
|
|
||||||
#[allow(dead_code)]
|
|
||||||
#[derive(Copy, Clone, PartialEq)]
|
|
||||||
pub enum AnchoredPositionMode {
|
|
||||||
/// Position the anchored element relative to the window.
|
|
||||||
Window,
|
|
||||||
/// Position the anchored element relative to its parent.
|
|
||||||
Local,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AnchoredPositionMode {
|
|
||||||
fn get_position_and_bounds(
|
|
||||||
&self,
|
|
||||||
anchor_position: Option<Point<Pixels>>,
|
|
||||||
anchor_corner: Anchor,
|
|
||||||
size: Size<Pixels>,
|
|
||||||
bounds: Bounds<Pixels>,
|
|
||||||
offset: Option<Point<Pixels>>,
|
|
||||||
) -> (Point<Pixels>, Bounds<Pixels>) {
|
|
||||||
let offset = offset.unwrap_or_default();
|
|
||||||
|
|
||||||
match self {
|
|
||||||
AnchoredPositionMode::Window => {
|
|
||||||
let anchor_position = anchor_position.unwrap_or(bounds.origin);
|
|
||||||
let bounds =
|
|
||||||
Self::from_corner_and_size(anchor_corner, anchor_position + offset, size);
|
|
||||||
(anchor_position, bounds)
|
|
||||||
}
|
|
||||||
AnchoredPositionMode::Local => {
|
|
||||||
let anchor_position = anchor_position.unwrap_or_default();
|
|
||||||
let bounds = Self::from_corner_and_size(
|
|
||||||
anchor_corner,
|
|
||||||
bounds.origin + anchor_position + offset,
|
|
||||||
size,
|
|
||||||
);
|
|
||||||
(anchor_position, bounds)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Ref https://github.com/zed-industries/zed/blob/b06f4088a3565c5e30663106ff79c1ced645d87a/crates/gpui/src/geometry.rs#L863
|
|
||||||
fn from_corner_and_size(
|
|
||||||
anchor: Anchor,
|
|
||||||
origin: Point<Pixels>,
|
|
||||||
size: Size<Pixels>,
|
|
||||||
) -> Bounds<Pixels> {
|
|
||||||
let origin = match anchor {
|
|
||||||
Anchor::TopLeft => origin,
|
|
||||||
Anchor::TopCenter => Point {
|
|
||||||
x: origin.x - size.width.half(),
|
|
||||||
y: origin.y,
|
|
||||||
},
|
|
||||||
Anchor::TopRight => Point {
|
|
||||||
x: origin.x - size.width,
|
|
||||||
y: origin.y,
|
|
||||||
},
|
|
||||||
Anchor::BottomLeft => Point {
|
|
||||||
x: origin.x,
|
|
||||||
y: origin.y - size.height,
|
|
||||||
},
|
|
||||||
Anchor::BottomCenter => Point {
|
|
||||||
x: origin.x - size.width.half(),
|
|
||||||
y: origin.y - size.height,
|
|
||||||
},
|
|
||||||
Anchor::BottomRight => Point {
|
|
||||||
x: origin.x - size.width,
|
|
||||||
y: origin.y - size.height,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
Bounds { origin, size }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -2,7 +2,7 @@ use std::sync::Arc;
|
|||||||
|
|
||||||
use gpui::prelude::FluentBuilder;
|
use gpui::prelude::FluentBuilder;
|
||||||
use gpui::{
|
use gpui::{
|
||||||
App, AppContext, Context, Corner, DefiniteLength, DismissEvent, DragMoveEvent, Empty, Entity,
|
Anchor, App, AppContext, Context, DefiniteLength, DismissEvent, DragMoveEvent, Empty, Entity,
|
||||||
EventEmitter, FocusHandle, Focusable, InteractiveElement as _, IntoElement, MouseButton,
|
EventEmitter, FocusHandle, Focusable, InteractiveElement as _, IntoElement, MouseButton,
|
||||||
ParentElement, Pixels, Render, ScrollHandle, SharedString, StatefulInteractiveElement, Styled,
|
ParentElement, Pixels, Render, ScrollHandle, SharedString, StatefulInteractiveElement, Styled,
|
||||||
WeakEntity, Window, div, px, rems,
|
WeakEntity, Window, div, px, rems,
|
||||||
@@ -460,7 +460,7 @@ impl TabPanel {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.anchor(Corner::TopRight),
|
.anchor(Anchor::TopRight),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
pub use anchored::*;
|
|
||||||
pub use element_ext::ElementExt;
|
pub use element_ext::ElementExt;
|
||||||
pub use event::InteractiveElementExt;
|
pub use event::InteractiveElementExt;
|
||||||
pub use focusable::FocusableCycle;
|
pub use focusable::FocusableCycle;
|
||||||
@@ -34,7 +33,6 @@ pub mod switch;
|
|||||||
pub mod tab;
|
pub mod tab;
|
||||||
pub mod tooltip;
|
pub mod tooltip;
|
||||||
|
|
||||||
mod anchored;
|
|
||||||
mod element_ext;
|
mod element_ext;
|
||||||
mod event;
|
mod event;
|
||||||
mod focusable;
|
mod focusable;
|
||||||
|
|||||||
@@ -1,14 +1,15 @@
|
|||||||
use gpui::prelude::FluentBuilder;
|
use gpui::prelude::FluentBuilder;
|
||||||
use gpui::{
|
use gpui::{
|
||||||
anchored, deferred, div, px, App, AppContext as _, ClickEvent, Context, DismissEvent, Entity,
|
App, AppContext as _, ClickEvent, Context, DismissEvent, Entity, Focusable,
|
||||||
Focusable, InteractiveElement as _, IntoElement, KeyBinding, MouseButton, OwnedMenu,
|
InteractiveElement as _, IntoElement, KeyBinding, MouseButton, OwnedMenu, ParentElement,
|
||||||
ParentElement, Render, SharedString, StatefulInteractiveElement, Styled, Subscription, Window,
|
Render, SharedString, StatefulInteractiveElement, Styled, Subscription, Window, anchored,
|
||||||
|
deferred, div, px,
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::actions::{Cancel, SelectLeft, SelectRight};
|
use crate::actions::{Cancel, SelectLeft, SelectRight};
|
||||||
use crate::button::{Button, ButtonVariants};
|
use crate::button::{Button, ButtonVariants};
|
||||||
use crate::menu::PopupMenu;
|
use crate::menu::PopupMenu;
|
||||||
use crate::{h_flex, Selectable, Sizable};
|
use crate::{Selectable, Sizable, h_flex};
|
||||||
|
|
||||||
const CONTEXT: &str = "AppMenuBar";
|
const CONTEXT: &str = "AppMenuBar";
|
||||||
|
|
||||||
@@ -241,7 +242,7 @@ impl Render for AppMenu {
|
|||||||
.when(is_selected, |this| {
|
.when(is_selected, |this| {
|
||||||
this.child(deferred(
|
this.child(deferred(
|
||||||
anchored()
|
anchored()
|
||||||
.anchor(gpui::Corner::TopLeft)
|
.anchor(gpui::Anchor::TopLeft)
|
||||||
.snap_to_window_with_margin(px(8.))
|
.snap_to_window_with_margin(px(8.))
|
||||||
.child(
|
.child(
|
||||||
div()
|
div()
|
||||||
|
|||||||
@@ -3,10 +3,10 @@ use std::rc::Rc;
|
|||||||
|
|
||||||
use gpui::prelude::FluentBuilder;
|
use gpui::prelude::FluentBuilder;
|
||||||
use gpui::{
|
use gpui::{
|
||||||
anchored, deferred, div, px, AnyElement, App, Context, Corner, DismissEvent, Element,
|
Anchor, AnyElement, App, Context, DismissEvent, Element, ElementId, Entity, Focusable,
|
||||||
ElementId, Entity, Focusable, GlobalElementId, Hitbox, HitboxBehavior, InspectorElementId,
|
GlobalElementId, Hitbox, HitboxBehavior, InspectorElementId, InteractiveElement, IntoElement,
|
||||||
InteractiveElement, IntoElement, MouseButton, MouseDownEvent, ParentElement, Pixels, Point,
|
MouseButton, MouseDownEvent, ParentElement, Pixels, Point, StyleRefinement, Styled,
|
||||||
StyleRefinement, Styled, Subscription, Window,
|
Subscription, Window, anchored, deferred, div, px,
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::menu::PopupMenu;
|
use crate::menu::PopupMenu;
|
||||||
@@ -41,7 +41,7 @@ pub struct ContextMenu<E: ParentElement + Styled + Sized> {
|
|||||||
menu: Option<Rc<dyn Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu>>,
|
menu: Option<Rc<dyn Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu>>,
|
||||||
// This is not in use, just for style refinement forwarding.
|
// This is not in use, just for style refinement forwarding.
|
||||||
_ignore_style: StyleRefinement,
|
_ignore_style: StyleRefinement,
|
||||||
anchor: Corner,
|
anchor: Anchor,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<E: ParentElement + Styled> ContextMenu<E> {
|
impl<E: ParentElement + Styled> ContextMenu<E> {
|
||||||
@@ -51,7 +51,7 @@ impl<E: ParentElement + Styled> ContextMenu<E> {
|
|||||||
id: id.into(),
|
id: id.into(),
|
||||||
element: Some(element),
|
element: Some(element),
|
||||||
menu: None,
|
menu: None,
|
||||||
anchor: Corner::TopLeft,
|
anchor: Anchor::TopLeft,
|
||||||
_ignore_style: StyleRefinement::default(),
|
_ignore_style: StyleRefinement::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
|
||||||
use gpui::{
|
use gpui::{
|
||||||
Context, Corner, DismissEvent, ElementId, Entity, Focusable, InteractiveElement, IntoElement,
|
Anchor, Context, DismissEvent, ElementId, Entity, Focusable, InteractiveElement, IntoElement,
|
||||||
RenderOnce, SharedString, StyleRefinement, Styled, Window,
|
RenderOnce, SharedString, StyleRefinement, Styled, Window,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -18,13 +18,13 @@ pub trait DropdownMenu: Styled + Selectable + InteractiveElement + IntoElement +
|
|||||||
self,
|
self,
|
||||||
f: impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static,
|
f: impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static,
|
||||||
) -> DropdownMenuPopover<Self> {
|
) -> DropdownMenuPopover<Self> {
|
||||||
self.dropdown_menu_with_anchor(Corner::TopLeft, f)
|
self.dropdown_menu_with_anchor(Anchor::TopLeft, f)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create a dropdown menu with the given items, anchored to the given corner
|
/// Create a dropdown menu with the given items, anchored to the given corner
|
||||||
fn dropdown_menu_with_anchor(
|
fn dropdown_menu_with_anchor(
|
||||||
mut self,
|
mut self,
|
||||||
anchor: impl Into<Corner>,
|
anchor: impl Into<Anchor>,
|
||||||
f: impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static,
|
f: impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static,
|
||||||
) -> DropdownMenuPopover<Self> {
|
) -> DropdownMenuPopover<Self> {
|
||||||
let style = self.style().clone();
|
let style = self.style().clone();
|
||||||
@@ -42,7 +42,7 @@ impl DropdownMenu for Avatar {}
|
|||||||
pub struct DropdownMenuPopover<T: Selectable + IntoElement + 'static> {
|
pub struct DropdownMenuPopover<T: Selectable + IntoElement + 'static> {
|
||||||
id: ElementId,
|
id: ElementId,
|
||||||
style: StyleRefinement,
|
style: StyleRefinement,
|
||||||
anchor: Corner,
|
anchor: Anchor,
|
||||||
trigger: T,
|
trigger: T,
|
||||||
#[allow(clippy::type_complexity)]
|
#[allow(clippy::type_complexity)]
|
||||||
builder: Rc<dyn Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu>,
|
builder: Rc<dyn Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu>,
|
||||||
@@ -54,7 +54,7 @@ where
|
|||||||
{
|
{
|
||||||
fn new(
|
fn new(
|
||||||
id: ElementId,
|
id: ElementId,
|
||||||
anchor: impl Into<Corner>,
|
anchor: impl Into<Anchor>,
|
||||||
trigger: T,
|
trigger: T,
|
||||||
builder: impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static,
|
builder: impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
@@ -68,7 +68,7 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Set the anchor corner for the dropdown menu popover.
|
/// Set the anchor corner for the dropdown menu popover.
|
||||||
pub fn anchor(mut self, anchor: impl Into<Corner>) -> Self {
|
pub fn anchor(mut self, anchor: impl Into<Anchor>) -> Self {
|
||||||
self.anchor = anchor.into();
|
self.anchor = anchor.into();
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ use std::rc::Rc;
|
|||||||
|
|
||||||
use gpui::prelude::FluentBuilder;
|
use gpui::prelude::FluentBuilder;
|
||||||
use gpui::{
|
use gpui::{
|
||||||
Action, AnyElement, App, AppContext, Axis, Bounds, ClickEvent, Context, Corner, DismissEvent,
|
Action, Anchor, AnyElement, App, AppContext, Axis, Bounds, ClickEvent, Context, DismissEvent,
|
||||||
Edges, Entity, EventEmitter, FocusHandle, Focusable, Half, InteractiveElement, IntoElement,
|
Edges, Entity, EventEmitter, FocusHandle, Focusable, Half, InteractiveElement, IntoElement,
|
||||||
KeyBinding, MouseDownEvent, OwnedMenuItem, ParentElement, Pixels, Point, Render, ScrollHandle,
|
KeyBinding, MouseDownEvent, OwnedMenuItem, ParentElement, Pixels, Point, Render, ScrollHandle,
|
||||||
SharedString, StatefulInteractiveElement, Styled, Subscription, WeakEntity, Window, anchored,
|
SharedString, StatefulInteractiveElement, Styled, Subscription, WeakEntity, Window, anchored,
|
||||||
@@ -299,7 +299,7 @@ pub struct PopupMenu {
|
|||||||
scroll_handle: ScrollHandle,
|
scroll_handle: ScrollHandle,
|
||||||
|
|
||||||
/// This will update on render
|
/// This will update on render
|
||||||
submenu_anchor: (Corner, Pixels),
|
submenu_anchor: (Anchor, Pixels),
|
||||||
|
|
||||||
_subscriptions: Vec<Subscription>,
|
_subscriptions: Vec<Subscription>,
|
||||||
}
|
}
|
||||||
@@ -322,7 +322,7 @@ impl PopupMenu {
|
|||||||
scroll_handle: ScrollHandle::default(),
|
scroll_handle: ScrollHandle::default(),
|
||||||
external_link_icon: true,
|
external_link_icon: true,
|
||||||
size: Size::default(),
|
size: Size::default(),
|
||||||
submenu_anchor: (Corner::TopLeft, Pixels::ZERO),
|
submenu_anchor: (Anchor::TopLeft, Pixels::ZERO),
|
||||||
_subscriptions: vec![],
|
_subscriptions: vec![],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -840,7 +840,7 @@ impl PopupMenu {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
|
fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
|
||||||
let handled = if matches!(self.submenu_anchor.0, Corner::TopLeft | Corner::BottomLeft) {
|
let handled = if matches!(self.submenu_anchor.0, Anchor::TopLeft | Anchor::BottomLeft) {
|
||||||
self._unselect_submenu(window, cx)
|
self._unselect_submenu(window, cx)
|
||||||
} else {
|
} else {
|
||||||
self._select_submenu(window, cx)
|
self._select_submenu(window, cx)
|
||||||
@@ -861,7 +861,7 @@ impl PopupMenu {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
|
fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
|
||||||
let handled = if matches!(self.submenu_anchor.0, Corner::TopLeft | Corner::BottomLeft) {
|
let handled = if matches!(self.submenu_anchor.0, Anchor::TopLeft | Anchor::BottomLeft) {
|
||||||
self._select_submenu(window, cx)
|
self._select_submenu(window, cx)
|
||||||
} else {
|
} else {
|
||||||
self._unselect_submenu(window, cx)
|
self._unselect_submenu(window, cx)
|
||||||
@@ -930,8 +930,9 @@ impl PopupMenu {
|
|||||||
};
|
};
|
||||||
|
|
||||||
match parent.read(cx).submenu_anchor.0 {
|
match parent.read(cx).submenu_anchor.0 {
|
||||||
Corner::TopLeft | Corner::BottomLeft => Side::Left,
|
Anchor::TopLeft | Anchor::BottomLeft => Side::Left,
|
||||||
Corner::TopRight | Corner::BottomRight => Side::Right,
|
Anchor::TopRight | Anchor::BottomRight => Side::Right,
|
||||||
|
_ => Side::Left,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1041,14 +1042,14 @@ impl PopupMenu {
|
|||||||
let bounds = self.bounds;
|
let bounds = self.bounds;
|
||||||
let max_width = self.max_width();
|
let max_width = self.max_width();
|
||||||
let (anchor, left) = if max_width + bounds.origin.x > window.bounds().size.width {
|
let (anchor, left) = if max_width + bounds.origin.x > window.bounds().size.width {
|
||||||
(Corner::TopRight, -px(16.))
|
(Anchor::TopRight, -px(16.))
|
||||||
} else {
|
} else {
|
||||||
(Corner::TopLeft, bounds.size.width - px(8.))
|
(Anchor::TopLeft, bounds.size.width - px(8.))
|
||||||
};
|
};
|
||||||
|
|
||||||
let is_bottom_pos = bounds.origin.y + bounds.size.height > window.bounds().size.height;
|
let is_bottom_pos = bounds.origin.y + bounds.size.height > window.bounds().size.height;
|
||||||
self.submenu_anchor = if is_bottom_pos {
|
self.submenu_anchor = if is_bottom_pos {
|
||||||
(anchor.other_side_corner_along(gpui::Axis::Vertical), left)
|
(anchor.other_side_along(gpui::Axis::Vertical), left)
|
||||||
} else {
|
} else {
|
||||||
(anchor, left)
|
(anchor, left)
|
||||||
};
|
};
|
||||||
@@ -1230,7 +1231,7 @@ impl PopupMenu {
|
|||||||
this.child({
|
this.child({
|
||||||
let (anchor, left) = self.submenu_anchor;
|
let (anchor, left) = self.submenu_anchor;
|
||||||
let is_bottom_pos =
|
let is_bottom_pos =
|
||||||
matches!(anchor, Corner::BottomLeft | Corner::BottomRight);
|
matches!(anchor, Anchor::BottomLeft | Anchor::BottomRight);
|
||||||
anchored()
|
anchored()
|
||||||
.anchor(anchor)
|
.anchor(anchor)
|
||||||
.child(
|
.child(
|
||||||
|
|||||||
@@ -5,12 +5,12 @@ use std::time::Duration;
|
|||||||
|
|
||||||
use gpui::prelude::FluentBuilder;
|
use gpui::prelude::FluentBuilder;
|
||||||
use gpui::{
|
use gpui::{
|
||||||
Animation, AnimationExt, AnyElement, App, AppContext, ClickEvent, Context, DismissEvent,
|
Anchor, Animation, AnimationExt, AnyElement, App, AppContext, ClickEvent, Context,
|
||||||
ElementId, Entity, EventEmitter, InteractiveElement as _, IntoElement, ParentElement as _,
|
DismissEvent, ElementId, Entity, EventEmitter, InteractiveElement as _, IntoElement,
|
||||||
Render, SharedString, StatefulInteractiveElement, StyleRefinement, Styled, Subscription,
|
ParentElement as _, Render, SharedString, StatefulInteractiveElement, StyleRefinement, Styled,
|
||||||
Window, div, px, relative,
|
Subscription, Window, div, px, relative,
|
||||||
};
|
};
|
||||||
use theme::{ActiveTheme, Anchor};
|
use theme::ActiveTheme;
|
||||||
|
|
||||||
use crate::animation::cubic_bezier;
|
use crate::animation::cubic_bezier;
|
||||||
use crate::button::{Button, ButtonVariants as _};
|
use crate::button::{Button, ButtonVariants as _};
|
||||||
@@ -288,6 +288,7 @@ impl Styled for Notification {
|
|||||||
&mut self.style
|
&mut self.style
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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 content = self
|
let content = self
|
||||||
@@ -295,10 +296,13 @@ impl Render for Notification {
|
|||||||
.clone()
|
.clone()
|
||||||
.map(|builder| builder(self, window, cx));
|
.map(|builder| builder(self, window, cx));
|
||||||
|
|
||||||
let action = self
|
let action = self.action_builder.clone().map(|builder| {
|
||||||
.action_builder
|
builder(self, window, cx)
|
||||||
.clone()
|
.xsmall()
|
||||||
.map(|builder| builder(self, window, cx).small().mr_3p5());
|
.primary()
|
||||||
|
.px_3()
|
||||||
|
.font_semibold()
|
||||||
|
});
|
||||||
|
|
||||||
let icon = match self.kind {
|
let icon = match self.kind {
|
||||||
None => self.icon.clone(),
|
None => self.icon.clone(),
|
||||||
@@ -360,14 +364,8 @@ impl Render for Notification {
|
|||||||
})
|
})
|
||||||
.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(
|
this.gap_2()
|
||||||
h_flex()
|
.child(h_flex().w_full().flex_1().justify_end().child(action))
|
||||||
.w_full()
|
|
||||||
.flex_1()
|
|
||||||
.gap_1()
|
|
||||||
.justify_end()
|
|
||||||
.child(action),
|
|
||||||
)
|
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.child(
|
.child(
|
||||||
@@ -426,12 +424,17 @@ impl Render for Notification {
|
|||||||
let y_offset = px(0.) + delta * px(45.);
|
let y_offset = px(0.) + delta * px(45.);
|
||||||
that.top(px(0.) + y_offset)
|
that.top(px(0.) + y_offset)
|
||||||
}
|
}
|
||||||
|
_ => that,
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
let opacity = delta;
|
let opacity = delta;
|
||||||
let y_offset = match placement {
|
let y_offset = match placement {
|
||||||
placement if placement.is_top() => px(-45.) + delta * px(45.),
|
Anchor::TopLeft | Anchor::TopRight | Anchor::TopCenter => {
|
||||||
placement if placement.is_bottom() => px(45.) - delta * px(45.),
|
px(-45.) + delta * px(45.)
|
||||||
|
}
|
||||||
|
Anchor::BottomLeft | Anchor::BottomRight | Anchor::BottomCenter => {
|
||||||
|
px(45.) - delta * px(45.)
|
||||||
|
}
|
||||||
_ => px(0.),
|
_ => px(0.),
|
||||||
};
|
};
|
||||||
this.top(px(0.) + y_offset)
|
this.top(px(0.) + y_offset)
|
||||||
|
|||||||
@@ -2,15 +2,14 @@ use std::rc::Rc;
|
|||||||
|
|
||||||
use gpui::prelude::FluentBuilder as _;
|
use gpui::prelude::FluentBuilder as _;
|
||||||
use gpui::{
|
use gpui::{
|
||||||
AnyElement, App, Bounds, Context, Deferred, DismissEvent, Div, ElementId, EventEmitter,
|
Anchor, AnyElement, App, Bounds, Context, Deferred, DismissEvent, Div, ElementId, EventEmitter,
|
||||||
FocusHandle, Focusable, Half, InteractiveElement as _, IntoElement, KeyBinding, MouseButton,
|
FocusHandle, Focusable, InteractiveElement as _, IntoElement, KeyBinding, MouseButton,
|
||||||
ParentElement, Pixels, Point, Render, RenderOnce, Stateful, StyleRefinement, Styled,
|
ParentElement, Pixels, Point, Render, RenderOnce, Stateful, StyleRefinement, Styled,
|
||||||
Subscription, Window, deferred, div, px,
|
Subscription, Window, anchored, deferred, div, px,
|
||||||
};
|
};
|
||||||
use theme::Anchor;
|
|
||||||
|
|
||||||
use crate::actions::Cancel;
|
use crate::actions::Cancel;
|
||||||
use crate::{ElementExt, Selectable, StyledExt as _, anchored, v_flex};
|
use crate::{ElementExt, Selectable, StyledExt as _, v_flex};
|
||||||
|
|
||||||
const CONTEXT: &str = "Popover";
|
const CONTEXT: &str = "Popover";
|
||||||
|
|
||||||
@@ -175,18 +174,25 @@ impl Popover {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
fn resolved_corner(anchor: Anchor, trigger_bounds: Bounds<Pixels>) -> Point<Pixels> {
|
pub(crate) fn resolved_corner(anchor: Anchor, trigger_bounds: Bounds<Pixels>) -> Point<Pixels> {
|
||||||
let offset = if anchor.is_center() {
|
match anchor {
|
||||||
gpui::point(trigger_bounds.size.width.half(), px(0.))
|
Anchor::TopLeft => trigger_bounds.origin,
|
||||||
} else {
|
Anchor::TopCenter => trigger_bounds.top_center(),
|
||||||
Point::default()
|
Anchor::TopRight => trigger_bounds.top_right(),
|
||||||
};
|
Anchor::BottomLeft => Point {
|
||||||
|
x: trigger_bounds.origin.x,
|
||||||
trigger_bounds.corner(anchor.swap_vertical().into())
|
y: trigger_bounds.origin.y - trigger_bounds.size.height,
|
||||||
+ offset
|
},
|
||||||
+ Point {
|
Anchor::BottomCenter => Point {
|
||||||
x: px(0.),
|
x: trigger_bounds.top_center().x,
|
||||||
y: -trigger_bounds.size.height,
|
y: trigger_bounds.origin.y - trigger_bounds.size.height,
|
||||||
|
},
|
||||||
|
Anchor::BottomRight => Point {
|
||||||
|
x: trigger_bounds.top_right().x,
|
||||||
|
y: trigger_bounds.origin.y - trigger_bounds.size.height,
|
||||||
|
},
|
||||||
|
// Fallback for LeftCenter/RightCenter – adjust as needed.
|
||||||
|
_ => trigger_bounds.origin,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -330,6 +336,7 @@ impl Popover {
|
|||||||
.map(|this| match anchor {
|
.map(|this| match anchor {
|
||||||
Anchor::TopLeft | Anchor::TopCenter | Anchor::TopRight => this.top_1(),
|
Anchor::TopLeft | Anchor::TopCenter | Anchor::TopRight => this.top_1(),
|
||||||
Anchor::BottomLeft | Anchor::BottomCenter | Anchor::BottomRight => this.bottom_1(),
|
Anchor::BottomLeft | Anchor::BottomCenter | Anchor::BottomRight => this.bottom_1(),
|
||||||
|
Anchor::LeftCenter | Anchor::RightCenter => this.top_1(), // Fallback for centered
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ use std::rc::Rc;
|
|||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
use gpui::{
|
use gpui::{
|
||||||
App, Axis, BorderStyle, Bounds, ContentMask, Corner, CursorStyle, Edges, Element, ElementId,
|
Anchor, App, Axis, BorderStyle, Bounds, ContentMask, CursorStyle, Edges, Element, ElementId,
|
||||||
GlobalElementId, Hitbox, HitboxBehavior, Hsla, InspectorElementId, IntoElement, IsZero,
|
GlobalElementId, Hitbox, HitboxBehavior, Hsla, InspectorElementId, IntoElement, IsZero,
|
||||||
LayoutId, ListState, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PaintQuad, Pixels, Point,
|
LayoutId, ListState, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PaintQuad, Pixels, Point,
|
||||||
Position, ScrollHandle, ScrollWheelEvent, Size, Style, UniformListScrollHandle, Window, fill,
|
Position, ScrollHandle, ScrollWheelEvent, Size, Style, UniformListScrollHandle, Window, fill,
|
||||||
@@ -648,14 +648,14 @@ impl Element for Scrollbar {
|
|||||||
// The clickable area of the thumb
|
// The clickable area of the thumb
|
||||||
let thumb_length = thumb_end - thumb_start - inset * 2;
|
let thumb_length = thumb_end - thumb_start - inset * 2;
|
||||||
let thumb_bounds = if is_vertical {
|
let thumb_bounds = if is_vertical {
|
||||||
Bounds::from_corner_and_size(
|
Bounds::from_anchor_and_size(
|
||||||
Corner::TopRight,
|
Anchor::TopRight,
|
||||||
bounds.top_right() + point(-inset, inset + thumb_start),
|
bounds.top_right() + point(-inset, inset + thumb_start),
|
||||||
size(WIDTH, thumb_length),
|
size(WIDTH, thumb_length),
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
Bounds::from_corner_and_size(
|
Bounds::from_anchor_and_size(
|
||||||
Corner::BottomLeft,
|
Anchor::BottomLeft,
|
||||||
bounds.bottom_left() + point(inset + thumb_start, -inset),
|
bounds.bottom_left() + point(inset + thumb_start, -inset),
|
||||||
size(thumb_length, WIDTH),
|
size(thumb_length, WIDTH),
|
||||||
)
|
)
|
||||||
@@ -663,14 +663,14 @@ impl Element for Scrollbar {
|
|||||||
|
|
||||||
// The actual render area of the thumb
|
// The actual render area of the thumb
|
||||||
let thumb_fill_bounds = if is_vertical {
|
let thumb_fill_bounds = if is_vertical {
|
||||||
Bounds::from_corner_and_size(
|
Bounds::from_anchor_and_size(
|
||||||
Corner::TopRight,
|
Anchor::TopRight,
|
||||||
bounds.top_right() + point(-inset, inset + thumb_start),
|
bounds.top_right() + point(-inset, inset + thumb_start),
|
||||||
size(thumb_width, thumb_length),
|
size(thumb_width, thumb_length),
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
Bounds::from_corner_and_size(
|
Bounds::from_anchor_and_size(
|
||||||
Corner::BottomLeft,
|
Anchor::BottomLeft,
|
||||||
bounds.bottom_left() + point(inset + thumb_start, -inset),
|
bounds.bottom_left() + point(inset + thumb_start, -inset),
|
||||||
size(thumb_length, thumb_width),
|
size(thumb_length, thumb_width),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ use std::rc::Rc;
|
|||||||
|
|
||||||
use gpui::prelude::FluentBuilder as _;
|
use gpui::prelude::FluentBuilder as _;
|
||||||
use gpui::{
|
use gpui::{
|
||||||
AnyElement, App, Corner, Div, Edges, ElementId, InteractiveElement, IntoElement, ParentElement,
|
Anchor, AnyElement, App, Div, Edges, ElementId, InteractiveElement, IntoElement, ParentElement,
|
||||||
RenderOnce, ScrollHandle, Stateful, StatefulInteractiveElement as _, StyleRefinement, Styled,
|
RenderOnce, ScrollHandle, Stateful, StatefulInteractiveElement as _, StyleRefinement, Styled,
|
||||||
Window, div, px,
|
Window, div, px,
|
||||||
};
|
};
|
||||||
@@ -282,7 +282,7 @@ impl RenderOnce for TabBar {
|
|||||||
|
|
||||||
this
|
this
|
||||||
})
|
})
|
||||||
.anchor(Corner::TopRight),
|
.anchor(Anchor::TopRight),
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
.when_some(self.suffix, |this, suffix| this.child(suffix))
|
.when_some(self.suffix, |this, suffix| this.child(suffix))
|
||||||
|
|||||||
@@ -14,8 +14,8 @@ 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-beta2"
|
version = "1.0.0-beta4"
|
||||||
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"]
|
||||||
icons = [
|
icons = [
|
||||||
@@ -27,19 +27,19 @@ icons = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
assets = { path = "../assets" }
|
assets = { path = "../crates/assets" }
|
||||||
ui = { path = "../ui" }
|
ui = { path = "../crates/ui" }
|
||||||
title_bar = { path = "../title_bar" }
|
title_bar = { path = "../crates/title_bar" }
|
||||||
theme = { path = "../theme" }
|
theme = { path = "../crates/theme" }
|
||||||
common = { path = "../common" }
|
common = { path = "../crates/common" }
|
||||||
state = { path = "../state" }
|
state = { path = "../crates/state" }
|
||||||
device = { path = "../device" }
|
device = { path = "../crates/device" }
|
||||||
chat = { path = "../chat" }
|
chat = { path = "../crates/chat" }
|
||||||
chat_ui = { path = "../chat_ui" }
|
chat_ui = { path = "../crates/chat_ui" }
|
||||||
settings = { path = "../settings" }
|
settings = { path = "../crates/settings" }
|
||||||
auto_update = { path = "../auto_update" }
|
auto_update = { path = "../crates/auto_update" }
|
||||||
person = { path = "../person" }
|
person = { path = "../crates/person" }
|
||||||
relay_auth = { path = "../relay_auth" }
|
relay_auth = { path = "../crates/relay_auth" }
|
||||||
|
|
||||||
gpui.workspace = true
|
gpui.workspace = true
|
||||||
gpui_platform.workspace = true
|
gpui_platform.workspace = true
|
||||||
@@ -62,9 +62,9 @@ smol.workspace = true
|
|||||||
futures.workspace = true
|
futures.workspace = true
|
||||||
oneshot.workspace = true
|
oneshot.workspace = true
|
||||||
webbrowser.workspace = true
|
webbrowser.workspace = true
|
||||||
|
tracing-subscriber.workspace = true
|
||||||
|
|
||||||
indexset = "0.12.3"
|
indexset = "0.12.3"
|
||||||
tracing-subscriber = { version = "0.3.18", features = ["fmt", "env-filter"] }
|
|
||||||
|
|
||||||
[target.'cfg(target_os = "macos")'.dependencies]
|
[target.'cfg(target_os = "macos")'.dependencies]
|
||||||
# Temporary workaround https://github.com/zed-industries/zed/issues/47168
|
# Temporary workaround https://github.com/zed-industries/zed/issues/47168
|
||||||
|
Before Width: | Height: | Size: 8.4 KiB After Width: | Height: | Size: 8.4 KiB |
|
Before Width: | Height: | Size: 22 KiB After Width: | Height: | Size: 22 KiB |
|
Before Width: | Height: | Size: 1.6 KiB After Width: | Height: | Size: 1.6 KiB |
@@ -50,7 +50,7 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"type": "dir",
|
"type": "dir",
|
||||||
"path": "./crates/coop/resources"
|
"path": "./desktop/resources"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
Before Width: | Height: | Size: 30 KiB After Width: | Height: | Size: 30 KiB |
|
Before Width: | Height: | Size: 70 KiB After Width: | Height: | Size: 70 KiB |
|
Before Width: | Height: | Size: 120 KiB After Width: | Height: | Size: 120 KiB |
@@ -91,7 +91,7 @@ impl AccountSelector {
|
|||||||
|
|
||||||
fn login(&mut self, public_key: PublicKey, window: &mut Window, cx: &mut Context<Self>) {
|
fn login(&mut self, public_key: PublicKey, window: &mut Window, cx: &mut Context<Self>) {
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let task = nostr.read(cx).get_signer(&public_key, cx);
|
let task = nostr.read(cx).get_secret(public_key, cx);
|
||||||
|
|
||||||
// Mark the public key as being logged in
|
// Mark the public key as being logged in
|
||||||
self.set_logging_in(public_key, cx);
|
self.set_logging_in(public_key, cx);
|
||||||
@@ -117,7 +117,7 @@ impl AccountSelector {
|
|||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
|
|
||||||
nostr.update(cx, |this, cx| {
|
nostr.update(cx, |this, cx| {
|
||||||
this.remove_signer(&public_key, cx);
|
this.remove_secret(&public_key, cx);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use common::TextUtils;
|
use common::StringExt;
|
||||||
use gpui::prelude::FluentBuilder;
|
use gpui::prelude::FluentBuilder;
|
||||||
use gpui::{
|
use gpui::{
|
||||||
AppContext, Context, Entity, Image, IntoElement, ParentElement, Render, SharedString, Styled,
|
AppContext, Context, Entity, Image, IntoElement, ParentElement, Render, SharedString, Styled,
|
||||||
@@ -2,21 +2,21 @@ use std::collections::HashMap;
|
|||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use anyhow::{Context as AnyhowContext, Error};
|
use anyhow::{Context as AnyhowContext, Error};
|
||||||
use common::RenderedTimestamp;
|
use common::TimestampExt;
|
||||||
use gpui::prelude::FluentBuilder;
|
use gpui::prelude::FluentBuilder;
|
||||||
use gpui::{
|
use gpui::{
|
||||||
div, px, relative, uniform_list, App, AppContext, Context, Div, Entity, InteractiveElement,
|
App, AppContext, Context, Div, Entity, InteractiveElement, IntoElement, ParentElement, Render,
|
||||||
IntoElement, ParentElement, Render, SharedString, Styled, Subscription, Task, Window,
|
SharedString, Styled, Subscription, Task, Window, div, px, relative, uniform_list,
|
||||||
};
|
};
|
||||||
use nostr_sdk::prelude::*;
|
use nostr_sdk::prelude::*;
|
||||||
use person::{shorten_pubkey, Person, PersonRegistry};
|
use person::{Person, PersonRegistry, shorten_pubkey};
|
||||||
use smallvec::{smallvec, SmallVec};
|
use smallvec::{SmallVec, smallvec};
|
||||||
use state::{NostrAddress, NostrRegistry, BOOTSTRAP_RELAYS, TIMEOUT};
|
use state::{BOOTSTRAP_RELAYS, NostrAddress, NostrRegistry, TIMEOUT};
|
||||||
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::indicator::Indicator;
|
use ui::indicator::Indicator;
|
||||||
use ui::{h_flex, v_flex, Icon, IconName, Sizable, StyledExt, WindowExtension};
|
use ui::{Icon, IconName, Sizable, StyledExt, WindowExtension, h_flex, v_flex};
|
||||||
|
|
||||||
pub fn init(public_key: PublicKey, window: &mut Window, cx: &mut App) -> Entity<Screening> {
|
pub fn init(public_key: PublicKey, window: &mut Window, cx: &mut App) -> Entity<Screening> {
|
||||||
cx.new(|cx| Screening::new(public_key, window, cx))
|
cx.new(|cx| Screening::new(public_key, window, cx))
|
||||||
@@ -92,14 +92,14 @@ fn main() {
|
|||||||
// Initialize relay auth registry
|
// Initialize relay auth registry
|
||||||
relay_auth::init(window, cx);
|
relay_auth::init(window, cx);
|
||||||
|
|
||||||
// Initialize app registry
|
|
||||||
chat::init(window, cx);
|
|
||||||
|
|
||||||
// Initialize device signer
|
// Initialize device signer
|
||||||
//
|
//
|
||||||
// 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
|
||||||
device::init(window, cx);
|
device::init(window, cx);
|
||||||
|
|
||||||
|
// Initialize app registry
|
||||||
|
chat::init(window, cx);
|
||||||
|
|
||||||
// Initialize auto update
|
// Initialize auto update
|
||||||
auto_update::init(window, cx);
|
auto_update::init(window, cx);
|
||||||
|
|
||||||
@@ -4,18 +4,18 @@ use std::time::Duration;
|
|||||||
|
|
||||||
use anyhow::{Context as AnyhowContext, Error};
|
use anyhow::{Context as AnyhowContext, Error};
|
||||||
use chat::{ChatEvent, ChatRegistry, Room, RoomKind};
|
use chat::{ChatEvent, ChatRegistry, Room, RoomKind};
|
||||||
use common::{DebouncedDelay, RenderedTimestamp};
|
use common::{DebouncedDelay, TimestampExt, coop_cache};
|
||||||
use entry::RoomEntry;
|
use entry::RoomEntry;
|
||||||
use gpui::prelude::FluentBuilder;
|
use gpui::prelude::FluentBuilder;
|
||||||
use gpui::{
|
use gpui::{
|
||||||
App, AppContext, Context, Entity, EventEmitter, FocusHandle, Focusable, IntoElement,
|
App, AppContext, Context, Entity, EventEmitter, FocusHandle, Focusable, IntoElement,
|
||||||
ParentElement, Render, RetainAllImageCache, SharedString, Styled, Subscription, Task,
|
ParentElement, Render, SharedString, Styled, Subscription, Task, UniformListScrollHandle,
|
||||||
UniformListScrollHandle, Window, div, uniform_list,
|
Window, div, uniform_list,
|
||||||
};
|
};
|
||||||
use nostr_sdk::prelude::*;
|
use nostr_sdk::prelude::*;
|
||||||
use person::PersonRegistry;
|
use person::PersonRegistry;
|
||||||
use smallvec::{SmallVec, smallvec};
|
use smallvec::{SmallVec, smallvec};
|
||||||
use state::{FIND_DELAY, NostrRegistry};
|
use state::{FIND_DELAY, IMAGE_CACHE_SIZE, NostrRegistry};
|
||||||
use theme::{ActiveTheme, SIDEBAR_WIDTH, TABBAR_HEIGHT};
|
use theme::{ActiveTheme, SIDEBAR_WIDTH, TABBAR_HEIGHT};
|
||||||
use ui::button::{Button, ButtonVariants};
|
use ui::button::{Button, ButtonVariants};
|
||||||
use ui::dock::{Panel, PanelEvent};
|
use ui::dock::{Panel, PanelEvent};
|
||||||
@@ -39,9 +39,6 @@ pub struct Sidebar {
|
|||||||
focus_handle: FocusHandle,
|
focus_handle: FocusHandle,
|
||||||
scroll_handle: UniformListScrollHandle,
|
scroll_handle: UniformListScrollHandle,
|
||||||
|
|
||||||
/// Image cache
|
|
||||||
image_cache: Entity<RetainAllImageCache>,
|
|
||||||
|
|
||||||
/// Find input state
|
/// Find input state
|
||||||
find_input: Entity<InputState>,
|
find_input: Entity<InputState>,
|
||||||
|
|
||||||
@@ -141,7 +138,6 @@ impl Sidebar {
|
|||||||
name: "Sidebar".into(),
|
name: "Sidebar".into(),
|
||||||
focus_handle: cx.focus_handle(),
|
focus_handle: cx.focus_handle(),
|
||||||
scroll_handle: UniformListScrollHandle::new(),
|
scroll_handle: UniformListScrollHandle::new(),
|
||||||
image_cache: RetainAllImageCache::new(cx),
|
|
||||||
find_input,
|
find_input,
|
||||||
find_debouncer: DebouncedDelay::new(),
|
find_debouncer: DebouncedDelay::new(),
|
||||||
find_results,
|
find_results,
|
||||||
@@ -507,7 +503,7 @@ impl Render for Sidebar {
|
|||||||
};
|
};
|
||||||
|
|
||||||
v_flex()
|
v_flex()
|
||||||
.image_cache(self.image_cache.clone())
|
.image_cache(coop_cache("sidebar", IMAGE_CACHE_SIZE))
|
||||||
.size_full()
|
.size_full()
|
||||||
.gap_2()
|
.gap_2()
|
||||||
.child(
|
.child(
|
||||||
@@ -1,22 +1,20 @@
|
|||||||
use std::cell::Cell;
|
|
||||||
use std::rc::Rc;
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use ::settings::AppSettings;
|
use ::settings::AppSettings;
|
||||||
use chat::{ChatEvent, ChatRegistry};
|
use chat::{ChatEvent, ChatRegistry};
|
||||||
use common::download_dir;
|
use common::{CoopImageCache, 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, StatefulInteractiveElement, Styled, Subscription, Window, div, px,
|
Render, SharedString, StatefulInteractiveElement, Styled, Subscription, Window, div,
|
||||||
relative,
|
image_cache, px, relative,
|
||||||
};
|
};
|
||||||
use nostr_sdk::prelude::*;
|
use nostr_sdk::prelude::*;
|
||||||
use person::PersonRegistry;
|
use person::{PersonRegistry, shorten_pubkey};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use smallvec::{SmallVec, smallvec};
|
use smallvec::{SmallVec, smallvec};
|
||||||
use state::{NostrRegistry, StateEvent};
|
use state::{IMAGE_CACHE_SIZE, NostrRegistry, StateEvent};
|
||||||
use theme::{ActiveTheme, SIDEBAR_WIDTH, Theme, ThemeRegistry};
|
use theme::{ActiveTheme, SIDEBAR_WIDTH, Theme, ThemeRegistry};
|
||||||
use title_bar::TitleBar;
|
use title_bar::TitleBar;
|
||||||
use ui::avatar::Avatar;
|
use ui::avatar::Avatar;
|
||||||
@@ -24,7 +22,7 @@ use ui::button::{Button, ButtonVariants};
|
|||||||
use ui::dock::{ClosePanel, DockArea, DockItem, DockPlacement, PanelView};
|
use ui::dock::{ClosePanel, DockArea, DockItem, DockPlacement, PanelView};
|
||||||
use ui::menu::{DropdownMenu, PopupMenuItem};
|
use ui::menu::{DropdownMenu, PopupMenuItem};
|
||||||
use ui::notification::{Notification, NotificationKind};
|
use ui::notification::{Notification, NotificationKind};
|
||||||
use ui::{Disableable, Icon, IconName, Root, Sizable, WindowExtension, h_flex, v_flex};
|
use ui::{Icon, IconName, Root, Sizable, WindowExtension, h_flex, v_flex};
|
||||||
|
|
||||||
use crate::dialogs::restore::RestoreEncryption;
|
use crate::dialogs::restore::RestoreEncryption;
|
||||||
use crate::dialogs::{accounts, settings};
|
use crate::dialogs::{accounts, settings};
|
||||||
@@ -51,7 +49,6 @@ enum Command {
|
|||||||
ToggleTheme,
|
ToggleTheme,
|
||||||
ToggleAccount,
|
ToggleAccount,
|
||||||
|
|
||||||
RefreshRelayList,
|
|
||||||
RefreshMessagingRelays,
|
RefreshMessagingRelays,
|
||||||
BackupEncryption,
|
BackupEncryption,
|
||||||
ImportEncryption,
|
ImportEncryption,
|
||||||
@@ -73,14 +70,11 @@ pub struct Workspace {
|
|||||||
/// App's Dock Area
|
/// App's Dock Area
|
||||||
dock: Entity<DockArea>,
|
dock: Entity<DockArea>,
|
||||||
|
|
||||||
/// Whether a user's relay list is connected
|
/// App's Image Cache
|
||||||
relay_connected: bool,
|
image_cache: Entity<CoopImageCache>,
|
||||||
|
|
||||||
/// Whether the inbox is connected
|
|
||||||
inbox_connected: bool,
|
|
||||||
|
|
||||||
/// Event subscriptions
|
/// Event subscriptions
|
||||||
_subscriptions: SmallVec<[Subscription; 6]>,
|
_subscriptions: SmallVec<[Subscription; 5]>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Workspace {
|
impl Workspace {
|
||||||
@@ -88,10 +82,10 @@ impl Workspace {
|
|||||||
let chat = ChatRegistry::global(cx);
|
let chat = ChatRegistry::global(cx);
|
||||||
let device = DeviceRegistry::global(cx);
|
let device = DeviceRegistry::global(cx);
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let npubs = nostr.read(cx).npubs();
|
|
||||||
|
|
||||||
let titlebar = cx.new(|_| TitleBar::new());
|
let titlebar = cx.new(|_| TitleBar::new());
|
||||||
let dock = cx.new(|cx| DockArea::new(window, cx));
|
let dock = cx.new(|cx| DockArea::new(window, cx));
|
||||||
|
let image_cache = CoopImageCache::new(IMAGE_CACHE_SIZE, cx);
|
||||||
|
|
||||||
let mut subscriptions = smallvec![];
|
let mut subscriptions = smallvec![];
|
||||||
|
|
||||||
@@ -102,15 +96,6 @@ impl Workspace {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
subscriptions.push(
|
|
||||||
// Observe the npubs entity
|
|
||||||
cx.observe_in(&npubs, window, move |this, npubs, window, cx| {
|
|
||||||
if !npubs.read(cx).is_empty() {
|
|
||||||
this.account_selector(window, cx);
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
subscriptions.push(
|
subscriptions.push(
|
||||||
// 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| {
|
||||||
@@ -141,28 +126,14 @@ impl Workspace {
|
|||||||
|
|
||||||
window.push_notification(note, cx);
|
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);
|
|
||||||
}
|
|
||||||
StateEvent::RelayNotConfigured => {
|
|
||||||
this.relay_warning(window, cx);
|
|
||||||
}
|
|
||||||
StateEvent::RelayConnected => {
|
|
||||||
window.clear_notification::<RelayNotifcation>(cx);
|
|
||||||
this.set_relay_connected(true, cx);
|
|
||||||
}
|
|
||||||
StateEvent::SignerSet => {
|
StateEvent::SignerSet => {
|
||||||
this.set_center_layout(window, cx);
|
this.set_center_layout(window, cx);
|
||||||
this.set_relay_connected(false, cx);
|
|
||||||
this.set_inbox_connected(false, cx);
|
|
||||||
// Clear the signer notification
|
// Clear the signer notification
|
||||||
window.clear_notification::<SignerNotifcation>(cx);
|
window.clear_notification::<SignerNotifcation>(cx);
|
||||||
}
|
}
|
||||||
|
StateEvent::Show => {
|
||||||
|
this.account_selector(window, cx);
|
||||||
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
@@ -174,10 +145,11 @@ impl Workspace {
|
|||||||
match event {
|
match event {
|
||||||
DeviceEvent::Requesting => {
|
DeviceEvent::Requesting => {
|
||||||
const MSG: &str =
|
const MSG: &str =
|
||||||
"Please open the other client and approve the encryption key request";
|
"Coop has sent a request for an encryption key. Please open the other client then approve the request.";
|
||||||
|
|
||||||
let note = Notification::new()
|
let note = Notification::new()
|
||||||
.id::<DeviceNotifcation>()
|
.id::<DeviceNotifcation>()
|
||||||
|
.autohide(false)
|
||||||
.title("Wait for approval")
|
.title("Wait for approval")
|
||||||
.message(MSG)
|
.message(MSG)
|
||||||
.with_kind(NotificationKind::Info);
|
.with_kind(NotificationKind::Info);
|
||||||
@@ -187,6 +159,7 @@ impl Workspace {
|
|||||||
DeviceEvent::Creating => {
|
DeviceEvent::Creating => {
|
||||||
let note = Notification::new()
|
let note = Notification::new()
|
||||||
.id::<DeviceNotifcation>()
|
.id::<DeviceNotifcation>()
|
||||||
|
.autohide(false)
|
||||||
.message("Creating encryption key")
|
.message("Creating encryption key")
|
||||||
.with_kind(NotificationKind::Info);
|
.with_kind(NotificationKind::Info);
|
||||||
|
|
||||||
@@ -200,26 +173,6 @@ impl Workspace {
|
|||||||
|
|
||||||
window.push_notification(note, cx);
|
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);
|
||||||
}
|
}
|
||||||
@@ -255,9 +208,6 @@ impl Workspace {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
ChatEvent::Subscribed => {
|
|
||||||
this.set_inbox_connected(true, cx);
|
|
||||||
}
|
|
||||||
ChatEvent::Error(error) => {
|
ChatEvent::Error(error) => {
|
||||||
window.push_notification(Notification::error(error).autohide(false), cx);
|
window.push_notification(Notification::error(error).autohide(false), cx);
|
||||||
}
|
}
|
||||||
@@ -285,8 +235,7 @@ impl Workspace {
|
|||||||
Self {
|
Self {
|
||||||
titlebar,
|
titlebar,
|
||||||
dock,
|
dock,
|
||||||
relay_connected: false,
|
image_cache,
|
||||||
inbox_connected: false,
|
|
||||||
_subscriptions: subscriptions,
|
_subscriptions: subscriptions,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -318,18 +267,6 @@ impl Workspace {
|
|||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set whether the relay list is connected
|
|
||||||
fn set_relay_connected(&mut self, connected: bool, cx: &mut Context<Self>) {
|
|
||||||
self.relay_connected = connected;
|
|
||||||
cx.notify();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Set whether the inbox is connected
|
|
||||||
fn set_inbox_connected(&mut self, connected: bool, cx: &mut Context<Self>) {
|
|
||||||
self.inbox_connected = connected;
|
|
||||||
cx.notify();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Set the dock layout
|
/// Set the dock layout
|
||||||
fn set_layout(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
fn set_layout(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||||
let left = DockItem::panel(Arc::new(sidebar::init(window, cx)));
|
let left = DockItem::panel(Arc::new(sidebar::init(window, cx)));
|
||||||
@@ -414,8 +351,9 @@ impl Workspace {
|
|||||||
}
|
}
|
||||||
Command::RefreshMessagingRelays => {
|
Command::RefreshMessagingRelays => {
|
||||||
let chat = ChatRegistry::global(cx);
|
let chat = ChatRegistry::global(cx);
|
||||||
|
// Trigger a refresh of the chat registry
|
||||||
chat.update(cx, |this, cx| {
|
chat.update(cx, |this, cx| {
|
||||||
this.get_messages(cx);
|
this.refresh(window, cx);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
Command::ShowRelayList => {
|
Command::ShowRelayList => {
|
||||||
@@ -428,16 +366,6 @@ impl Workspace {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
Command::RefreshRelayList => {
|
|
||||||
let nostr = NostrRegistry::global(cx);
|
|
||||||
let signer = nostr.read(cx).signer();
|
|
||||||
|
|
||||||
if let Some(public_key) = signer.public_key() {
|
|
||||||
nostr.update(cx, |this, cx| {
|
|
||||||
this.ensure_relay_list(&public_key, cx);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Command::RefreshEncryption => {
|
Command::RefreshEncryption => {
|
||||||
let device = DeviceRegistry::global(cx);
|
let device = DeviceRegistry::global(cx);
|
||||||
device.update(cx, |this, cx| {
|
device.update(cx, |this, cx| {
|
||||||
@@ -630,55 +558,6 @@ impl Workspace {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn relay_warning(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
|
||||||
const BODY: &str = "Coop cannot found your gossip relay list. \
|
|
||||||
Maybe you haven't set it yet or relay not responsed";
|
|
||||||
|
|
||||||
let nostr = NostrRegistry::global(cx);
|
|
||||||
let signer = nostr.read(cx).signer();
|
|
||||||
|
|
||||||
let Some(public_key) = signer.public_key() else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
|
|
||||||
let entity = nostr.downgrade();
|
|
||||||
let loading = Rc::new(Cell::new(false));
|
|
||||||
|
|
||||||
let note = Notification::new()
|
|
||||||
.autohide(false)
|
|
||||||
.id::<RelayNotifcation>()
|
|
||||||
.icon(IconName::Relay)
|
|
||||||
.title("Gossip Relays are required")
|
|
||||||
.message(BODY)
|
|
||||||
.action(move |_this, _window, _cx| {
|
|
||||||
let entity = entity.clone();
|
|
||||||
let public_key = public_key.to_owned();
|
|
||||||
|
|
||||||
Button::new("retry")
|
|
||||||
.label("Retry")
|
|
||||||
.small()
|
|
||||||
.primary()
|
|
||||||
.loading(loading.get())
|
|
||||||
.disabled(loading.get())
|
|
||||||
.on_click({
|
|
||||||
let loading = Rc::clone(&loading);
|
|
||||||
|
|
||||||
move |_ev, _window, cx| {
|
|
||||||
// Set loading state to true
|
|
||||||
loading.set(true);
|
|
||||||
// Retry
|
|
||||||
entity
|
|
||||||
.update(cx, |this, cx| {
|
|
||||||
this.ensure_relay_list(&public_key, cx);
|
|
||||||
})
|
|
||||||
.ok();
|
|
||||||
}
|
|
||||||
})
|
|
||||||
});
|
|
||||||
|
|
||||||
window.push_notification(note, cx);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn titlebar_left(&mut self, 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();
|
||||||
@@ -759,19 +638,24 @@ impl Workspace {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn titlebar_right(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
|
fn titlebar_right(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
|
||||||
let relay_connected = self.relay_connected;
|
let chat = ChatRegistry::global(cx);
|
||||||
let inbox_connected = self.inbox_connected;
|
let initializing = chat.read(cx).initializing;
|
||||||
|
let trash_messages = chat.read(cx).count_trash_messages(cx);
|
||||||
|
|
||||||
|
let device = DeviceRegistry::global(cx);
|
||||||
|
let device_initializing = device.read(cx).initializing;
|
||||||
|
|
||||||
let nostr = NostrRegistry::global(cx);
|
let nostr = NostrRegistry::global(cx);
|
||||||
let signer = nostr.read(cx).signer();
|
let signer = nostr.read(cx).signer();
|
||||||
|
|
||||||
let trashes = ChatRegistry::global(cx);
|
|
||||||
let trash_messages = trashes.read(cx).count_trash_messages(cx);
|
|
||||||
|
|
||||||
let Some(public_key) = signer.public_key() else {
|
let Some(public_key) = signer.public_key() else {
|
||||||
return div();
|
return div();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let persons = PersonRegistry::global(cx);
|
||||||
|
let profile = persons.read(cx).get(&public_key, cx);
|
||||||
|
let announcement = profile.announcement();
|
||||||
|
|
||||||
h_flex()
|
h_flex()
|
||||||
.when(!cx.theme().platform.is_mac(), |this| this.pr_2())
|
.when(!cx.theme().platform.is_mac(), |this| this.pr_2())
|
||||||
.gap_2()
|
.gap_2()
|
||||||
@@ -813,53 +697,42 @@ impl Workspace {
|
|||||||
.tooltip("Decoupled encryption key")
|
.tooltip("Decoupled encryption key")
|
||||||
.small()
|
.small()
|
||||||
.ghost()
|
.ghost()
|
||||||
.dropdown_menu(move |this, _window, cx| {
|
.loading(device_initializing)
|
||||||
let device = DeviceRegistry::global(cx);
|
.when(device_initializing, |this| {
|
||||||
let subscribing = device.read(cx).subscribing;
|
this.label("Dekey")
|
||||||
let requesting = device.read(cx).requesting;
|
.xsmall()
|
||||||
|
.tooltip("Loading decoupled encryption key...")
|
||||||
|
})
|
||||||
|
.dropdown_menu(move |this, _window, _cx| {
|
||||||
this.min_w(px(260.))
|
this.min_w(px(260.))
|
||||||
.label("Encryption Key")
|
.label("Encryption Key")
|
||||||
.when(requesting, |this| {
|
.when_some(announcement.as_ref(), |this, announcement| {
|
||||||
|
let name = announcement.client_name();
|
||||||
|
let pkey = shorten_pubkey(announcement.public_key(), 8);
|
||||||
|
|
||||||
this.item(PopupMenuItem::element(move |_window, cx| {
|
this.item(PopupMenuItem::element(move |_window, cx| {
|
||||||
h_flex()
|
h_flex()
|
||||||
.px_1()
|
.gap_1()
|
||||||
.w_full()
|
|
||||||
.gap_2()
|
|
||||||
.text_sm()
|
.text_sm()
|
||||||
.child(
|
.child(
|
||||||
div()
|
Icon::new(IconName::Device)
|
||||||
.size_1p5()
|
.small()
|
||||||
.rounded_full()
|
.text_color(cx.theme().icon_muted),
|
||||||
.bg(cx.theme().icon_accent),
|
|
||||||
)
|
)
|
||||||
.child(SharedString::from("Waiting for approval..."))
|
.child(name.clone())
|
||||||
}))
|
}))
|
||||||
})
|
|
||||||
.item(PopupMenuItem::element(move |_window, cx| {
|
.item(PopupMenuItem::element(move |_window, cx| {
|
||||||
h_flex()
|
h_flex()
|
||||||
.px_1()
|
.gap_1()
|
||||||
.w_full()
|
|
||||||
.gap_2()
|
|
||||||
.text_sm()
|
.text_sm()
|
||||||
.when(!subscribing, |this| {
|
.child(
|
||||||
this.text_color(cx.theme().text_muted)
|
Icon::new(IconName::UserKey)
|
||||||
})
|
.small()
|
||||||
.child(div().size_1p5().rounded_full().map(|this| {
|
.text_color(cx.theme().icon_muted),
|
||||||
if subscribing {
|
)
|
||||||
this.bg(cx.theme().icon_accent)
|
.child(SharedString::from(pkey.clone()))
|
||||||
} else {
|
|
||||||
this.bg(cx.theme().icon_muted)
|
|
||||||
}
|
|
||||||
}))
|
}))
|
||||||
.map(|this| {
|
|
||||||
if subscribing {
|
|
||||||
this.child("Listening for messages")
|
|
||||||
} else {
|
|
||||||
this.child("Idle")
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
}))
|
|
||||||
.separator()
|
.separator()
|
||||||
.menu_with_icon(
|
.menu_with_icon(
|
||||||
"Backup",
|
"Backup",
|
||||||
@@ -889,17 +762,13 @@ impl Workspace {
|
|||||||
.icon(IconName::Inbox)
|
.icon(IconName::Inbox)
|
||||||
.small()
|
.small()
|
||||||
.ghost()
|
.ghost()
|
||||||
.loading(!inbox_connected)
|
.loading(initializing)
|
||||||
.disabled(!inbox_connected)
|
.when(initializing, |this| {
|
||||||
.when(!inbox_connected, |this| {
|
this.label("Inbox")
|
||||||
this.tooltip("Connecting to the user's messaging relays...")
|
.xsmall()
|
||||||
|
.tooltip("Getting inbox messages...")
|
||||||
})
|
})
|
||||||
.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 profile = persons.read(cx).get(&public_key, cx);
|
|
||||||
|
|
||||||
let urls: Vec<(SharedString, SharedString)> = profile
|
let urls: Vec<(SharedString, SharedString)> = profile
|
||||||
.messaging_relays()
|
.messaging_relays()
|
||||||
.iter()
|
.iter()
|
||||||
@@ -950,38 +819,17 @@ impl Workspace {
|
|||||||
Box::new(Command::RefreshMessagingRelays),
|
Box::new(Command::RefreshMessagingRelays),
|
||||||
)
|
)
|
||||||
.menu_with_icon(
|
.menu_with_icon(
|
||||||
"Update relays",
|
"Manage gossip relays",
|
||||||
|
IconName::Relay,
|
||||||
|
Box::new(Command::ShowRelayList),
|
||||||
|
)
|
||||||
|
.menu_with_icon(
|
||||||
|
"Manage messaging relays",
|
||||||
IconName::Settings,
|
IconName::Settings,
|
||||||
Box::new(Command::ShowMessaging),
|
Box::new(Command::ShowMessaging),
|
||||||
)
|
)
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.child(
|
|
||||||
Button::new("relay-list")
|
|
||||||
.icon(IconName::Relay)
|
|
||||||
.small()
|
|
||||||
.ghost()
|
|
||||||
.loading(!relay_connected)
|
|
||||||
.disabled(!relay_connected)
|
|
||||||
.when(!relay_connected, |this| {
|
|
||||||
this.tooltip("Connecting to the user's relay list...")
|
|
||||||
})
|
|
||||||
.when(relay_connected, |this| this.indicator())
|
|
||||||
.dropdown_menu(move |this, _window, _cx| {
|
|
||||||
this.label("User's Relay List")
|
|
||||||
.separator()
|
|
||||||
.menu_with_icon(
|
|
||||||
"Reload",
|
|
||||||
IconName::Refresh,
|
|
||||||
Box::new(Command::RefreshRelayList),
|
|
||||||
)
|
|
||||||
.menu_with_icon(
|
|
||||||
"Update",
|
|
||||||
IconName::Settings,
|
|
||||||
Box::new(Command::ShowRelayList),
|
|
||||||
)
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1005,13 +853,17 @@ impl Render for Workspace {
|
|||||||
.relative()
|
.relative()
|
||||||
.size_full()
|
.size_full()
|
||||||
.child(
|
.child(
|
||||||
v_flex()
|
image_cache(self.image_cache.clone())
|
||||||
.relative()
|
.relative()
|
||||||
|
.size_full()
|
||||||
|
.child(
|
||||||
|
v_flex()
|
||||||
.size_full()
|
.size_full()
|
||||||
// Title Bar
|
// Title Bar
|
||||||
.child(self.titlebar.clone())
|
.child(self.titlebar.clone())
|
||||||
// Dock
|
// Dock
|
||||||
.child(self.dock.clone()),
|
.child(self.dock.clone()),
|
||||||
|
),
|
||||||
)
|
)
|
||||||
// Notifications
|
// Notifications
|
||||||
.children(notification_layer)
|
.children(notification_layer)
|
||||||
@@ -8,5 +8,7 @@ targets = [
|
|||||||
"x86_64-unknown-linux-gnu",
|
"x86_64-unknown-linux-gnu",
|
||||||
"x86_64-pc-windows-msvc",
|
"x86_64-pc-windows-msvc",
|
||||||
"aarch64-pc-windows-msvc",
|
"aarch64-pc-windows-msvc",
|
||||||
|
"aarch64-apple-ios",
|
||||||
|
"aarch64-linux-android",
|
||||||
"wasm32-unknown-unknown"
|
"wasm32-unknown-unknown"
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -98,9 +98,9 @@ cp $(find_libs) "${coop_dir}/lib"
|
|||||||
|
|
||||||
# Icons
|
# Icons
|
||||||
mkdir -p "${coop_dir}/share/icons/hicolor/512x512/apps"
|
mkdir -p "${coop_dir}/share/icons/hicolor/512x512/apps"
|
||||||
cp "crates/coop/resources/icon.png" "${coop_dir}/share/icons/hicolor/512x512/apps/coop.png"
|
cp "desktop/resources/icon.png" "${coop_dir}/share/icons/hicolor/512x512/apps/coop.png"
|
||||||
mkdir -p "${coop_dir}/share/icons/hicolor/1024x1024/apps"
|
mkdir -p "${coop_dir}/share/icons/hicolor/1024x1024/apps"
|
||||||
cp "crates/coop/resources/icon@2x.png" "${coop_dir}/share/icons/hicolor/1024x1024/apps/coop.png"
|
cp "desktop/resources/icon@2x.png" "${coop_dir}/share/icons/hicolor/1024x1024/apps/coop.png"
|
||||||
|
|
||||||
# .desktop
|
# .desktop
|
||||||
export DO_STARTUP_NOTIFY="true"
|
export DO_STARTUP_NOTIFY="true"
|
||||||
@@ -110,7 +110,7 @@ export APP_ARGS="%U"
|
|||||||
export APP_NAME="Coop"
|
export APP_NAME="Coop"
|
||||||
|
|
||||||
mkdir -p "${coop_dir}/share/applications"
|
mkdir -p "${coop_dir}/share/applications"
|
||||||
envsubst < "crates/coop/resources/coop.desktop.in" > "${coop_dir}/share/applications/coop.desktop"
|
envsubst < "desktop/resources/coop.desktop.in" > "${coop_dir}/share/applications/coop.desktop"
|
||||||
|
|
||||||
# Create archive out of everything that's in the temp directory
|
# Create archive out of everything that's in the temp directory
|
||||||
arch=$(uname -m)
|
arch=$(uname -m)
|
||||||
|
|||||||
@@ -21,11 +21,11 @@ export DO_STARTUP_NOTIFY="true"
|
|||||||
export APP_NAME="Coop"
|
export APP_NAME="Coop"
|
||||||
export APP_ICON="\${SNAP}/meta/gui/coop.png"
|
export APP_ICON="\${SNAP}/meta/gui/coop.png"
|
||||||
export APP_ARGS="%U"
|
export APP_ARGS="%U"
|
||||||
envsubst < "crates/coop/resources/coop.desktop.in" > "snap/gui/coop.desktop"
|
envsubst < "desktop/resources/coop.desktop.in" > "snap/gui/coop.desktop"
|
||||||
cp "crates/coop/resources/icon.png" "snap/gui/coop.png"
|
cp "desktop/resources/icon.png" "snap/gui/coop.png"
|
||||||
|
|
||||||
# Generate snapcraft.yaml with version and architecture
|
# Generate snapcraft.yaml with version and architecture
|
||||||
RELEASE_VERSION="$1" ARCH_SUFFIX="$ARCH_SUFFIX" envsubst < crates/coop/resources/snap/snapcraft.yaml.in > snap/snapcraft.yaml
|
RELEASE_VERSION="$1" ARCH_SUFFIX="$ARCH_SUFFIX" envsubst < desktop/resources/snap/snapcraft.yaml.in > snap/snapcraft.yaml
|
||||||
|
|
||||||
# Clean previous builds
|
# Clean previous builds
|
||||||
snapcraft clean
|
snapcraft clean
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ export ICON_FILE="icon"
|
|||||||
export CHANNEL="stable"
|
export CHANNEL="stable"
|
||||||
|
|
||||||
# Generate manifest
|
# Generate manifest
|
||||||
envsubst < "crates/coop/resources/flatpak/manifest-template.json" > "$APP_ID.json"
|
envsubst < "desktop/resources/flatpak/manifest-template.json" > "$APP_ID.json"
|
||||||
|
|
||||||
# Build Flatpak
|
# Build Flatpak
|
||||||
flatpak-builder --user --install --force-clean build "$APP_ID.json"
|
flatpak-builder --user --install --force-clean build "$APP_ID.json"
|
||||||
|
|||||||
@@ -93,7 +93,7 @@ echo " Created flathub/release-info.xml"
|
|||||||
# Step 4: Generate the metainfo file with release info
|
# Step 4: Generate the metainfo file with release info
|
||||||
echo "[4/5] Generating metainfo.xml..."
|
echo "[4/5] Generating metainfo.xml..."
|
||||||
export APP_ID APP_NAME BRANDING_LIGHT BRANDING_DARK
|
export APP_ID APP_NAME BRANDING_LIGHT BRANDING_DARK
|
||||||
cat crates/coop/resources/flatpak/coop.metainfo.xml.in | \
|
cat desktop/resources/flatpak/coop.metainfo.xml.in | \
|
||||||
sed -e "/@release_info@/r flathub/release-info.xml" -e '/@release_info@/d' \
|
sed -e "/@release_info@/r flathub/release-info.xml" -e '/@release_info@/d' \
|
||||||
> flathub/${APP_ID}.metainfo.xml
|
> flathub/${APP_ID}.metainfo.xml
|
||||||
echo " Created flathub/${APP_ID}.metainfo.xml"
|
echo " Created flathub/${APP_ID}.metainfo.xml"
|
||||||
@@ -153,8 +153,8 @@ modules:
|
|||||||
- install -Dm755 target/release/coop /app/bin/coop
|
- install -Dm755 target/release/coop /app/bin/coop
|
||||||
|
|
||||||
# Install icons
|
# Install icons
|
||||||
- install -Dm644 crates/coop/resources/icon.png /app/share/icons/hicolor/512x512/apps/su.reya.coop.png
|
- install -Dm644 desktop/resources/icon.png /app/share/icons/hicolor/512x512/apps/su.reya.coop.png
|
||||||
- install -Dm644 crates/coop/resources/icon@2x.png /app/share/icons/hicolor/1024x1024/apps/su.reya.coop.png
|
- install -Dm644 desktop/resources/icon@2x.png /app/share/icons/hicolor/1024x1024/apps/su.reya.coop.png
|
||||||
|
|
||||||
# Install desktop file
|
# Install desktop file
|
||||||
- |
|
- |
|
||||||
@@ -164,7 +164,7 @@ modules:
|
|||||||
export APP_CLI="coop"
|
export APP_CLI="coop"
|
||||||
export APP_ARGS="%U"
|
export APP_ARGS="%U"
|
||||||
export DO_STARTUP_NOTIFY="true"
|
export DO_STARTUP_NOTIFY="true"
|
||||||
envsubst < crates/coop/resources/coop.desktop.in > coop.desktop
|
envsubst < desktop/resources/coop.desktop.in > coop.desktop
|
||||||
install -Dm644 coop.desktop /app/share/applications/su.reya.coop.desktop
|
install -Dm644 coop.desktop /app/share/applications/su.reya.coop.desktop
|
||||||
|
|
||||||
# Install metainfo (use pre-generated one with release info)
|
# Install metainfo (use pre-generated one with release info)
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ fi
|
|||||||
|
|
||||||
NEW_VERSION="$1"
|
NEW_VERSION="$1"
|
||||||
WORKSPACE_CARGO="Cargo.toml"
|
WORKSPACE_CARGO="Cargo.toml"
|
||||||
CRATE_CARGO="crates/coop/Cargo.toml"
|
CRATE_CARGO="desktop/Cargo.toml"
|
||||||
|
|
||||||
# Check if both Cargo.toml files exist
|
# Check if both Cargo.toml files exist
|
||||||
if [ ! -f "$WORKSPACE_CARGO" ]; then
|
if [ ! -f "$WORKSPACE_CARGO" ]; then
|
||||||
|
|||||||
@@ -5,22 +5,21 @@ edition.workspace = true
|
|||||||
publish.workspace = true
|
publish.workspace = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
assets = { path = "../assets" }
|
assets = { path = "../crates/assets" }
|
||||||
ui = { path = "../ui" }
|
ui = { path = "../crates/ui" }
|
||||||
theme = { path = "../theme" }
|
theme = { path = "../crates/theme" }
|
||||||
common = { path = "../common" }
|
common = { path = "../crates/common" }
|
||||||
state = { path = "../state" }
|
state = { path = "../crates/state" }
|
||||||
device = { path = "../device" }
|
device = { path = "../crates/device" }
|
||||||
chat = { path = "../chat" }
|
chat = { path = "../crates/chat" }
|
||||||
chat_ui = { path = "../chat_ui" }
|
settings = { path = "../crates/settings" }
|
||||||
settings = { path = "../settings" }
|
person = { path = "../crates/person" }
|
||||||
person = { path = "../person" }
|
relay_auth = { path = "../crates/relay_auth" }
|
||||||
relay_auth = { path = "../relay_auth" }
|
|
||||||
|
|
||||||
gpui.workspace = true
|
gpui.workspace = true
|
||||||
gpui_web.workspace = true
|
|
||||||
gpui_platform.workspace = true
|
gpui_platform.workspace = true
|
||||||
gpui_tokio.workspace = true
|
gpui_tokio.workspace = true
|
||||||
|
gpui_web = { git = "https://github.com/zed-industries/zed" }
|
||||||
|
|
||||||
nostr-connect.workspace = true
|
nostr-connect.workspace = true
|
||||||
nostr-sdk.workspace = true
|
nostr-sdk.workspace = true
|
||||||
@@ -35,8 +34,8 @@ smol.workspace = true
|
|||||||
futures.workspace = true
|
futures.workspace = true
|
||||||
oneshot.workspace = true
|
oneshot.workspace = true
|
||||||
webbrowser.workspace = true
|
webbrowser.workspace = true
|
||||||
|
tracing-subscriber.workspace = true
|
||||||
|
|
||||||
tracing-subscriber = { version = "0.3.18", features = ["fmt", "env-filter"] }
|
|
||||||
console_error_panic_hook = "0.1"
|
console_error_panic_hook = "0.1"
|
||||||
tracing-wasm = "0.2"
|
tracing-wasm = "0.2"
|
||||||
console_log = "1.0"
|
console_log = "1.0"
|
||||||