Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6e7f63d79a | ||
|
|
ee693aa503 | ||
|
|
ebcc60cd92 | ||
|
|
0db48bc003 | ||
|
|
880ba30d20 | ||
|
|
d889f9b25d | ||
|
|
0de1b20951 | ||
|
|
338a947b57 | ||
|
|
98ce928f0c | ||
|
|
61cad5dd96 | ||
|
|
a87184214f |
Generated
+202
-173
File diff suppressed because it is too large
Load Diff
+1
-1
@@ -4,7 +4,7 @@ members = ["crates/*"]
|
||||
default-members = ["crates/coop"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.2.9"
|
||||
version = "0.2.11"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24">
|
||||
<path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M17.75 19.25h2.596c1.163 0 2.106-1.001 1.788-2.12-.733-2.573-2.465-4.38-5.134-4.38-.446 0-.866.05-1.26.147M11.25 7a3.25 3.25 0 1 1-6.5 0 3.25 3.25 0 0 1 6.5 0Zm8.5.5a2.75 2.75 0 1 1-5.5 0 2.75 2.75 0 0 1 5.5 0ZM2.08 18.126c.78-3.14 2.78-5.376 5.92-5.376s5.14 2.237 5.918 5.376c.28 1.128-.658 2.124-1.82 2.124H3.901c-1.162 0-2.1-.996-1.82-2.124Z"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 550 B |
@@ -1,4 +1,3 @@
|
||||
use std::collections::HashSet;
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
|
||||
use itertools::Itertools;
|
||||
@@ -7,26 +6,14 @@ use nostr_sdk::prelude::*;
|
||||
pub trait EventUtils {
|
||||
fn uniq_id(&self) -> u64;
|
||||
fn all_pubkeys(&self) -> Vec<PublicKey>;
|
||||
fn compare_pubkeys(&self, other: &[PublicKey]) -> bool;
|
||||
}
|
||||
|
||||
impl EventUtils for Event {
|
||||
fn uniq_id(&self) -> u64 {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
let mut pubkeys: Vec<PublicKey> = vec![];
|
||||
|
||||
// Add all public keys from event
|
||||
pubkeys.push(self.pubkey);
|
||||
pubkeys.extend(self.tags.public_keys().collect::<Vec<_>>());
|
||||
|
||||
// Generate unique hash
|
||||
pubkeys
|
||||
.into_iter()
|
||||
.unique()
|
||||
.sorted()
|
||||
.collect::<Vec<_>>()
|
||||
.hash(&mut hasher);
|
||||
|
||||
let mut pubkeys: Vec<PublicKey> = self.all_pubkeys();
|
||||
pubkeys.sort();
|
||||
pubkeys.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
@@ -34,15 +21,7 @@ impl EventUtils for Event {
|
||||
let mut public_keys: Vec<PublicKey> = self.tags.public_keys().copied().collect();
|
||||
public_keys.push(self.pubkey);
|
||||
|
||||
public_keys
|
||||
}
|
||||
|
||||
fn compare_pubkeys(&self, other: &[PublicKey]) -> bool {
|
||||
let pubkeys = self.all_pubkeys();
|
||||
let a: HashSet<_> = pubkeys.iter().collect();
|
||||
let b: HashSet<_> = other.iter().collect();
|
||||
|
||||
a == b
|
||||
public_keys.into_iter().unique().collect()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,12 +51,4 @@ impl EventUtils for UnsignedEvent {
|
||||
|
||||
public_keys
|
||||
}
|
||||
|
||||
fn compare_pubkeys(&self, other: &[PublicKey]) -> bool {
|
||||
let pubkeys = self.all_pubkeys();
|
||||
let a: HashSet<_> = pubkeys.iter().collect();
|
||||
let b: HashSet<_> = other.iter().collect();
|
||||
|
||||
a == b
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ product-name = "Coop"
|
||||
description = "Chat Freely, Stay Private on Nostr"
|
||||
identifier = "su.reya.coop"
|
||||
category = "SocialNetworking"
|
||||
version = "0.2.9"
|
||||
version = "0.2.11"
|
||||
out-dir = "../../dist"
|
||||
before-packaging-command = "cargo build --release"
|
||||
resources = ["Cargo.toml", "src"]
|
||||
|
||||
@@ -16,8 +16,8 @@ use global::constants::{
|
||||
use global::{app_state, nostr_client, AuthRequest, Notice, SignalKind, UnwrappingStatus};
|
||||
use gpui::prelude::FluentBuilder;
|
||||
use gpui::{
|
||||
deferred, div, px, rems, App, AppContext, AsyncWindowContext, Axis, Context, Entity,
|
||||
InteractiveElement, IntoElement, ParentElement, Render, SharedString,
|
||||
deferred, div, px, rems, App, AppContext, AsyncWindowContext, Axis, ClipboardItem, Context,
|
||||
Entity, InteractiveElement, IntoElement, ParentElement, Render, SharedString,
|
||||
StatefulInteractiveElement, Styled, Subscription, Task, WeakEntity, Window,
|
||||
};
|
||||
use i18n::{shared_t, t};
|
||||
@@ -30,7 +30,7 @@ use signer_proxy::{BrowserSignerProxy, BrowserSignerProxyOptions};
|
||||
use smallvec::{smallvec, SmallVec};
|
||||
use theme::{ActiveTheme, Theme, ThemeMode};
|
||||
use title_bar::TitleBar;
|
||||
use ui::actions::OpenProfile;
|
||||
use ui::actions::{CopyPublicKey, OpenPublicKey};
|
||||
use ui::avatar::Avatar;
|
||||
use ui::button::{Button, ButtonVariants};
|
||||
use ui::dock_area::dock::DockPlacement;
|
||||
@@ -545,7 +545,7 @@ impl ChatSpace {
|
||||
|
||||
// Load all chat rooms
|
||||
registry.update(cx, |this, cx| {
|
||||
this.set_identity(public_key, cx);
|
||||
this.set_signer_pubkey(public_key, cx);
|
||||
this.load_rooms(window, cx);
|
||||
});
|
||||
}
|
||||
@@ -676,7 +676,7 @@ impl ChatSpace {
|
||||
}
|
||||
|
||||
/// Stores an unwrapped event in local database with reference to original
|
||||
async fn set_unwrapped_event(root: EventId, unwrapped: &Event) -> Result<(), Error> {
|
||||
async fn set_unwrapped_event(gift_wrap: EventId, unwrapped: &Event) -> Result<(), Error> {
|
||||
let client = nostr_client();
|
||||
|
||||
// Save unwrapped event
|
||||
@@ -684,7 +684,7 @@ impl ChatSpace {
|
||||
|
||||
// Create a reference event pointing to the unwrapped event
|
||||
let event = EventBuilder::new(Kind::ApplicationSpecificData, "")
|
||||
.tags(vec![Tag::identifier(root), Tag::event(unwrapped.id)])
|
||||
.tags(vec![Tag::identifier(gift_wrap), Tag::event(unwrapped.id)])
|
||||
.sign(&Keys::generate())
|
||||
.await?;
|
||||
|
||||
@@ -744,8 +744,6 @@ impl ChatSpace {
|
||||
match event.created_at >= app_state.init_at {
|
||||
// New message: send a signal to notify the UI
|
||||
true => {
|
||||
// A small delay to prevent UI flickering
|
||||
smol::Timer::after(Duration::from_millis(200)).await;
|
||||
app_state
|
||||
.signal
|
||||
.send(SignalKind::NewMessage((target.id, event)))
|
||||
@@ -1179,7 +1177,7 @@ impl ChatSpace {
|
||||
.detach();
|
||||
}
|
||||
|
||||
fn on_open_profile(&mut self, ev: &OpenProfile, window: &mut Window, cx: &mut Context<Self>) {
|
||||
fn on_open_pubkey(&mut self, ev: &OpenPublicKey, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let public_key = ev.0;
|
||||
let profile = user_profile::init(public_key, window, cx);
|
||||
|
||||
@@ -1197,6 +1195,12 @@ impl ChatSpace {
|
||||
});
|
||||
}
|
||||
|
||||
fn on_copy_pubkey(&mut self, ev: &CopyPublicKey, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let Ok(bech32) = ev.0.to_bech32();
|
||||
cx.write_to_clipboard(ClipboardItem::new_string(bech32));
|
||||
window.push_notification(t!("common.copied"), cx);
|
||||
}
|
||||
|
||||
fn render_proxy_modal(&mut self, window: &mut Window, cx: &mut App) {
|
||||
window.open_modal(cx, |this, _window, _cx| {
|
||||
this.overlay_closable(false)
|
||||
@@ -1477,8 +1481,8 @@ impl Render for ChatSpace {
|
||||
let registry = Registry::read_global(cx);
|
||||
|
||||
// Only render titlebar child elements if user is logged in
|
||||
if registry.identity.is_some() {
|
||||
let profile = registry.identity(cx);
|
||||
if let Some(public_key) = registry.signer_pubkey() {
|
||||
let profile = registry.get_person(&public_key, cx);
|
||||
|
||||
let left_side = self
|
||||
.render_titlebar_left_side(window, cx)
|
||||
@@ -1498,7 +1502,8 @@ impl Render for ChatSpace {
|
||||
.on_action(cx.listener(Self::on_settings))
|
||||
.on_action(cx.listener(Self::on_dark_mode))
|
||||
.on_action(cx.listener(Self::on_sign_out))
|
||||
.on_action(cx.listener(Self::on_open_profile))
|
||||
.on_action(cx.listener(Self::on_open_pubkey))
|
||||
.on_action(cx.listener(Self::on_copy_pubkey))
|
||||
.on_action(cx.listener(Self::on_reload_metadata))
|
||||
.relative()
|
||||
.size_full()
|
||||
|
||||
+119
-151
@@ -1,4 +1,5 @@
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::time::Duration;
|
||||
|
||||
use common::display::{RenderedProfile, RenderedTimestamp};
|
||||
use common::nip96::nip96_upload;
|
||||
@@ -24,8 +25,10 @@ use settings::AppSettings;
|
||||
use smallvec::{smallvec, SmallVec};
|
||||
use smol::fs;
|
||||
use theme::ActiveTheme;
|
||||
use ui::actions::{CopyPublicKey, OpenPublicKey};
|
||||
use ui::avatar::Avatar;
|
||||
use ui::button::{Button, ButtonVariants};
|
||||
use ui::context_menu::ContextMenuExt;
|
||||
use ui::dock_area::panel::{Panel, PanelEvent};
|
||||
use ui::emoji_picker::EmojiPicker;
|
||||
use ui::input::{InputEvent, InputState, TextInput};
|
||||
@@ -61,7 +64,7 @@ pub struct Chat {
|
||||
|
||||
// New Message
|
||||
input: Entity<InputState>,
|
||||
replies_to: Entity<Vec<EventId>>,
|
||||
replies_to: Entity<HashSet<EventId>>,
|
||||
|
||||
// Media Attachment
|
||||
attachments: Entity<Vec<Url>>,
|
||||
@@ -79,7 +82,7 @@ pub struct Chat {
|
||||
impl Chat {
|
||||
pub fn new(room: Entity<Room>, window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||
let attachments = cx.new(|_| vec![]);
|
||||
let replies_to = cx.new(|_| vec![]);
|
||||
let replies_to = cx.new(|_| HashSet::new());
|
||||
|
||||
let relays = cx.new(|_| {
|
||||
let this: HashMap<PublicKey, Vec<RelayUrl>> = HashMap::new();
|
||||
@@ -89,18 +92,15 @@ impl Chat {
|
||||
let input = cx.new(|cx| {
|
||||
InputState::new(window, cx)
|
||||
.placeholder(t!("chat.placeholder"))
|
||||
.multi_line()
|
||||
.prevent_new_line_on_enter()
|
||||
.rows(1)
|
||||
.multi_line()
|
||||
.auto_grow(1, 20)
|
||||
.prevent_new_line_on_enter()
|
||||
.clean_on_escape()
|
||||
});
|
||||
|
||||
let messages = BTreeSet::from([Message::system()]);
|
||||
let list_state = ListState::new(messages.len(), ListAlignment::Bottom, px(1024.));
|
||||
|
||||
let connect_relays = room.read(cx).connect_relays(cx);
|
||||
let connect = room.read(cx).connect(cx);
|
||||
let load_messages = room.read(cx).load_messages(cx);
|
||||
|
||||
let mut subscriptions = smallvec![];
|
||||
@@ -109,43 +109,41 @@ impl Chat {
|
||||
tasks.push(
|
||||
// Load all messages belonging to this room
|
||||
cx.spawn_in(window, async move |this, cx| {
|
||||
match connect_relays.await {
|
||||
Ok(relays) => {
|
||||
this.update(cx, |this, cx| {
|
||||
this.relays.update(cx, |this, cx| {
|
||||
*this = relays;
|
||||
cx.notify();
|
||||
});
|
||||
})
|
||||
.ok();
|
||||
let result = load_messages.await;
|
||||
|
||||
this.update_in(cx, |this, window, cx| {
|
||||
match result {
|
||||
Ok(events) => {
|
||||
this.insert_messages(events, cx);
|
||||
}
|
||||
Err(e) => {
|
||||
cx.update(|window, cx| {
|
||||
window.push_notification(e.to_string(), cx);
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
};
|
||||
})
|
||||
.ok();
|
||||
}),
|
||||
);
|
||||
|
||||
tasks.push(
|
||||
// Load all messages belonging to this room
|
||||
// Get messaging relays for all members
|
||||
cx.spawn_in(window, async move |this, cx| {
|
||||
match load_messages.await {
|
||||
Ok(events) => {
|
||||
this.update(cx, |this, cx| {
|
||||
this.insert_messages(events, cx);
|
||||
})
|
||||
.ok();
|
||||
let result = connect.await;
|
||||
|
||||
this.update_in(cx, |this, _window, cx| {
|
||||
match result {
|
||||
Ok(relays) => {
|
||||
this.relays.update(cx, |this, cx| {
|
||||
this.extend(relays);
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
Err(e) => {
|
||||
cx.update(|window, cx| {
|
||||
window.push_notification(e.to_string(), cx);
|
||||
})
|
||||
.ok();
|
||||
this.insert_warning(e.to_string(), cx);
|
||||
}
|
||||
};
|
||||
})
|
||||
.ok();
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -155,14 +153,8 @@ impl Chat {
|
||||
&input,
|
||||
window,
|
||||
move |this: &mut Self, _input, event, window, cx| {
|
||||
match event {
|
||||
InputEvent::PressEnter { .. } => {
|
||||
if let InputEvent::PressEnter { .. } = event {
|
||||
this.send_message(window, cx);
|
||||
}
|
||||
InputEvent::Change(_) => {
|
||||
// this.mention_popup(text, input, cx);
|
||||
}
|
||||
_ => {}
|
||||
};
|
||||
},
|
||||
),
|
||||
@@ -173,9 +165,21 @@ impl Chat {
|
||||
cx.subscribe_in(&room, window, move |this, _, signal, window, cx| {
|
||||
match signal {
|
||||
RoomSignal::NewMessage((gift_wrap_id, event)) => {
|
||||
if !this.is_sent_by_coop(gift_wrap_id) {
|
||||
this.insert_message(Message::user(event), false, cx);
|
||||
let gift_wrap_id = gift_wrap_id.to_owned();
|
||||
let message = Message::user(event);
|
||||
|
||||
cx.spawn_in(window, async move |this, cx| {
|
||||
let app_state = app_state();
|
||||
let sent_ids = app_state.sent_ids.read().await;
|
||||
|
||||
this.update_in(cx, |this, _window, cx| {
|
||||
if !sent_ids.contains(&gift_wrap_id) {
|
||||
this.insert_message(message, false, cx);
|
||||
}
|
||||
})
|
||||
.ok();
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
RoomSignal::Refresh => {
|
||||
this.load_messages(window, cx);
|
||||
@@ -187,9 +191,12 @@ impl Chat {
|
||||
subscriptions.push(
|
||||
// Observe the messaging relays of the room's members
|
||||
cx.observe_in(&relays, window, |this, entity, _window, cx| {
|
||||
for (public_key, urls) in entity.read(cx).clone().into_iter() {
|
||||
let registry = Registry::global(cx);
|
||||
let relays = entity.read(cx).clone();
|
||||
|
||||
for (public_key, urls) in relays.iter() {
|
||||
if urls.is_empty() {
|
||||
let profile = Registry::read_global(cx).get_person(&public_key, cx);
|
||||
let profile = registry.read(cx).get_person(public_key, cx);
|
||||
let content = t!("chat.nip17_not_found", u = profile.name());
|
||||
|
||||
this.insert_warning(content, cx);
|
||||
@@ -201,7 +208,6 @@ impl Chat {
|
||||
subscriptions.push(
|
||||
// Observe when user close chat panel
|
||||
cx.on_release_in(window, move |this, window, cx| {
|
||||
this.disconnect_relays(cx);
|
||||
this.messages.clear();
|
||||
this.rendered_texts_by_id.clear();
|
||||
this.reports_by_id.clear();
|
||||
@@ -230,20 +236,6 @@ impl Chat {
|
||||
}
|
||||
}
|
||||
|
||||
/// Disconnect all relays when the user closes the chat panel
|
||||
fn disconnect_relays(&mut self, cx: &mut App) {
|
||||
let relays = self.relays.read(cx).clone();
|
||||
|
||||
cx.background_spawn(async move {
|
||||
let client = nostr_client();
|
||||
|
||||
for relay in relays.values().flatten() {
|
||||
client.disconnect_relay(relay).await.ok();
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
/// Load all messages belonging to this room
|
||||
fn load_messages(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let load_messages = self.room.read(cx).load_messages(cx);
|
||||
@@ -251,29 +243,23 @@ impl Chat {
|
||||
self._tasks.push(
|
||||
// Run the task in the background
|
||||
cx.spawn_in(window, async move |this, cx| {
|
||||
match load_messages.await {
|
||||
let result = load_messages.await;
|
||||
|
||||
this.update_in(cx, |this, window, cx| {
|
||||
match result {
|
||||
Ok(events) => {
|
||||
this.update(cx, |this, cx| {
|
||||
this.insert_messages(events, cx);
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
Err(e) => {
|
||||
cx.update(|window, cx| {
|
||||
window.push_notification(e.to_string(), cx);
|
||||
})
|
||||
.ok();
|
||||
window.push_notification(Notification::error(e.to_string()), cx);
|
||||
}
|
||||
};
|
||||
})
|
||||
.ok();
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
fn mention_popup(&mut self, _text: &str, _input: &Entity<InputState>, _cx: &mut Context<Self>) {
|
||||
// TODO: open mention popup at current cursor position
|
||||
}
|
||||
|
||||
/// Get user input content and merged all attachments
|
||||
fn input_content(&self, cx: &Context<Self>) -> String {
|
||||
let mut content = self.input.read(cx).value().trim().to_string();
|
||||
@@ -298,11 +284,6 @@ impl Chat {
|
||||
content
|
||||
}
|
||||
|
||||
/// Check if the event is sent by Coop
|
||||
fn is_sent_by_coop(&self, gift_wrap_id: &EventId) -> bool {
|
||||
app_state().sent_ids.read_blocking().contains(gift_wrap_id)
|
||||
}
|
||||
|
||||
/// Send a message to all members of the chat
|
||||
fn send_message(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
// Get the message which includes all attachments
|
||||
@@ -314,52 +295,56 @@ impl Chat {
|
||||
return;
|
||||
}
|
||||
|
||||
// Temporary disable input
|
||||
// Temporary disable the message input
|
||||
self.input.update(cx, |this, cx| {
|
||||
this.set_loading(true, cx);
|
||||
this.set_disabled(true, cx);
|
||||
this.set_loading(false, cx);
|
||||
this.set_disabled(false, cx);
|
||||
this.set_value("", window, cx);
|
||||
});
|
||||
|
||||
// Get the backup setting
|
||||
let backup = AppSettings::get_backup_messages(cx);
|
||||
|
||||
// Get replies_to if it's present
|
||||
let replies = self.replies_to.read(cx).clone();
|
||||
let replies: Vec<EventId> = self.replies_to.read(cx).iter().copied().collect();
|
||||
|
||||
// Get the current room entity
|
||||
let room = self.room.read(cx);
|
||||
let identity = Registry::read_global(cx).identity(cx).public_key();
|
||||
|
||||
// Create a temporary message for optimistic update
|
||||
let temp_message = room.create_temp_message(identity, &content, replies.as_ref());
|
||||
let temp_id = temp_message.id.unwrap();
|
||||
let rumor = room.create_message(&content, replies.as_ref(), cx);
|
||||
let rumor_id = rumor.id.unwrap();
|
||||
|
||||
// Create a task for sending the message in the background
|
||||
let send_message = room.send_in_background(&content, replies, backup, cx);
|
||||
let send_message = room.send_message(rumor.clone(), backup, cx);
|
||||
|
||||
cx.defer_in(window, |this, window, cx| {
|
||||
// Optimistically update message list
|
||||
this.insert_message(Message::user(temp_message), true, cx);
|
||||
cx.spawn_in(window, async move |this, cx| {
|
||||
cx.background_executor()
|
||||
.timer(Duration::from_millis(100))
|
||||
.await;
|
||||
|
||||
// Remove all replies
|
||||
this.update_in(cx, |this, window, cx| {
|
||||
this.insert_message(Message::user(rumor), true, cx);
|
||||
this.remove_all_replies(cx);
|
||||
|
||||
// remove all attachments
|
||||
this.remove_all_attachments(cx);
|
||||
|
||||
// Reset the input state
|
||||
this.input.update(cx, |this, cx| {
|
||||
this.set_loading(false, cx);
|
||||
this.set_disabled(false, cx);
|
||||
this.set_value("", window, cx);
|
||||
});
|
||||
});
|
||||
})
|
||||
.ok();
|
||||
})
|
||||
.detach();
|
||||
|
||||
// Continue sending the message in the background
|
||||
cx.spawn_in(window, async move |this, cx| {
|
||||
match send_message.await {
|
||||
let result = send_message.await;
|
||||
|
||||
this.update_in(cx, |this, window, cx| {
|
||||
match result {
|
||||
Ok(reports) => {
|
||||
this.update(cx, |this, cx| {
|
||||
this.room.update(cx, |this, cx| {
|
||||
if this.kind != RoomKind::Ongoing {
|
||||
// Update the room kind to ongoing
|
||||
@@ -372,56 +357,47 @@ impl Chat {
|
||||
});
|
||||
|
||||
// Insert the sent reports
|
||||
this.reports_by_id.insert(temp_id, reports);
|
||||
this.reports_by_id.insert(rumor_id, reports);
|
||||
|
||||
cx.notify();
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
Err(e) => {
|
||||
cx.update(|window, cx| {
|
||||
window.push_notification(e.to_string(), cx);
|
||||
}
|
||||
}
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
/// Resend a failed message
|
||||
fn resend_message(&mut self, id: &EventId, window: &mut Window, cx: &mut Context<Self>) {
|
||||
if let Some(reports) = self.reports_by_id.get(id).cloned() {
|
||||
if let Some(message) = self.message(id) {
|
||||
let backup = AppSettings::get_backup_messages(cx);
|
||||
let id_clone = id.to_owned();
|
||||
let message = message.content.to_owned();
|
||||
let task = self.room.read(cx).resend(reports, message, backup, cx);
|
||||
let resend = self.room.read(cx).resend_message(reports, cx);
|
||||
|
||||
cx.spawn_in(window, async move |this, cx| {
|
||||
match task.await {
|
||||
let result = resend.await;
|
||||
|
||||
this.update_in(cx, |this, window, cx| {
|
||||
match result {
|
||||
Ok(reports) => {
|
||||
if !reports.is_empty() {
|
||||
this.update(cx, |this, cx| {
|
||||
this.reports_by_id.entry(id_clone).and_modify(|this| {
|
||||
*this = reports;
|
||||
});
|
||||
cx.notify();
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
cx.update(|window, cx| {
|
||||
window.push_notification(e.to_string(), cx);
|
||||
})
|
||||
.ok();
|
||||
window.push_notification(Notification::error(e.to_string()), cx);
|
||||
}
|
||||
};
|
||||
})
|
||||
.ok();
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Insert a message into the chat panel
|
||||
fn insert_message<E>(&mut self, m: E, scroll: bool, cx: &mut Context<Self>)
|
||||
@@ -439,8 +415,9 @@ impl Chat {
|
||||
item_ix: self.list_state.item_count(),
|
||||
offset_in_item: px(0.0),
|
||||
});
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -448,11 +425,12 @@ impl Chat {
|
||||
fn insert_messages(&mut self, events: Vec<Event>, cx: &mut Context<Self>) {
|
||||
for event in events.into_iter() {
|
||||
let m = Message::user(event);
|
||||
// Bulk inserting messages, so no need to scroll to the latest message
|
||||
self.insert_message(m, false, cx);
|
||||
}
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
/// Insert a warning message into the chat panel
|
||||
fn insert_warning(&mut self, content: impl Into<String>, cx: &mut Context<Self>) {
|
||||
let m = Message::warning(content.into());
|
||||
self.insert_message(m, true, cx);
|
||||
@@ -515,7 +493,7 @@ impl Chat {
|
||||
fn reply_to(&mut self, id: &EventId, cx: &mut Context<Self>) {
|
||||
if let Some(text) = self.message(id) {
|
||||
self.replies_to.update(cx, |this, cx| {
|
||||
this.push(text.id);
|
||||
this.insert(text.id);
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
@@ -523,16 +501,14 @@ impl Chat {
|
||||
|
||||
fn remove_reply(&mut self, id: &EventId, cx: &mut Context<Self>) {
|
||||
self.replies_to.update(cx, |this, cx| {
|
||||
if let Some(ix) = this.iter().position(|this| this == id) {
|
||||
this.remove(ix);
|
||||
this.remove(id);
|
||||
cx.notify();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn remove_all_replies(&mut self, cx: &mut Context<Self>) {
|
||||
self.replies_to.update(cx, |this, cx| {
|
||||
*this = vec![];
|
||||
this.clear();
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
@@ -624,7 +600,7 @@ impl Chat {
|
||||
});
|
||||
}
|
||||
|
||||
fn render_announcement(&mut self, ix: usize, cx: &mut Context<Self>) -> AnyElement {
|
||||
fn render_announcement(&self, ix: usize, cx: &Context<Self>) -> AnyElement {
|
||||
v_flex()
|
||||
.id(ix)
|
||||
.group("")
|
||||
@@ -650,7 +626,7 @@ impl Chat {
|
||||
.into_any_element()
|
||||
}
|
||||
|
||||
fn render_warning(&mut self, ix: usize, content: String, cx: &mut Context<Self>) -> AnyElement {
|
||||
fn render_warning(&self, ix: usize, content: SharedString, cx: &Context<Self>) -> AnyElement {
|
||||
div()
|
||||
.id(ix)
|
||||
.relative()
|
||||
@@ -664,7 +640,7 @@ impl Chat {
|
||||
.text_sm()
|
||||
.text_color(cx.theme().warning_foreground)
|
||||
.child(Avatar::new("brand/system.png").size(rems(2.)))
|
||||
.child(SharedString::from(content)),
|
||||
.child(content),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
@@ -678,23 +654,6 @@ impl Chat {
|
||||
.into_any_element()
|
||||
}
|
||||
|
||||
fn render_message_not_found(&self, ix: usize, cx: &Context<Self>) -> AnyElement {
|
||||
div()
|
||||
.id(ix)
|
||||
.w_full()
|
||||
.py_1()
|
||||
.px_3()
|
||||
.child(
|
||||
h_flex()
|
||||
.gap_1()
|
||||
.text_xs()
|
||||
.text_color(cx.theme().danger_foreground)
|
||||
.child(SharedString::from(ix.to_string()))
|
||||
.child(shared_t!("chat.not_found")),
|
||||
)
|
||||
.into_any_element()
|
||||
}
|
||||
|
||||
fn render_message(
|
||||
&self,
|
||||
ix: usize,
|
||||
@@ -707,6 +666,7 @@ impl Chat {
|
||||
|
||||
let id = message.id;
|
||||
let author = self.profile(&message.author, cx);
|
||||
let public_key = author.public_key();
|
||||
|
||||
let replies = message.replies_to.as_slice();
|
||||
let has_replies = !replies.is_empty();
|
||||
@@ -729,7 +689,18 @@ impl Chat {
|
||||
.flex()
|
||||
.gap_3()
|
||||
.when(!hide_avatar, |this| {
|
||||
this.child(Avatar::new(author.avatar(proxy)).size(rems(2.)))
|
||||
this.child(
|
||||
div()
|
||||
.id(SharedString::from(format!("{ix}-avatar")))
|
||||
.child(Avatar::new(author.avatar(proxy)).size(rems(2.)))
|
||||
.context_menu(move |this, _window, _cx| {
|
||||
let view = Box::new(OpenPublicKey(public_key));
|
||||
let copy = Box::new(CopyPublicKey(public_key));
|
||||
|
||||
this.menu(t!("profile.view"), view)
|
||||
.menu(t!("profile.copy"), copy)
|
||||
}),
|
||||
)
|
||||
})
|
||||
.child(
|
||||
v_flex()
|
||||
@@ -1237,8 +1208,7 @@ impl Chat {
|
||||
weak_view.read_with(cx, |this, cx| this.new_subject(cx))
|
||||
{
|
||||
room.update(cx, |this, cx| {
|
||||
this.subject = Some(subject);
|
||||
cx.notify();
|
||||
this.set_subject(subject, cx);
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
@@ -1332,9 +1302,7 @@ impl Panel for Chat {
|
||||
let label = this.display_name(cx);
|
||||
let url = this.display_image(proxy, cx);
|
||||
|
||||
div()
|
||||
.flex()
|
||||
.items_center()
|
||||
h_flex()
|
||||
.gap_1p5()
|
||||
.child(Avatar::new(url).size(rems(1.25)))
|
||||
.child(label)
|
||||
@@ -1383,13 +1351,13 @@ impl Render for Chat {
|
||||
|
||||
this.render_message(ix, rendered, text, cx)
|
||||
}
|
||||
Message::Warning(content, _) => {
|
||||
this.render_warning(ix, content.to_owned(), cx)
|
||||
Message::Warning(content, _timestamp) => {
|
||||
this.render_warning(ix, SharedString::from(content), cx)
|
||||
}
|
||||
Message::System(_) => this.render_announcement(ix, cx),
|
||||
Message::System(_timestamp) => this.render_announcement(ix, cx),
|
||||
}
|
||||
} else {
|
||||
this.render_message_not_found(ix, cx)
|
||||
this.render_warning(ix, shared_t!("chat.not_found"), cx)
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -19,7 +19,6 @@ use registry::room::Room;
|
||||
use registry::Registry;
|
||||
use settings::AppSettings;
|
||||
use smallvec::{smallvec, SmallVec};
|
||||
use smol::Timer;
|
||||
use theme::ActiveTheme;
|
||||
use ui::avatar::Avatar;
|
||||
use ui::button::{Button, ButtonVariants};
|
||||
@@ -237,7 +236,7 @@ impl Compose {
|
||||
});
|
||||
});
|
||||
} else {
|
||||
self.set_error(Some(t!("compose.contact_existed").into()), cx);
|
||||
self.set_error(t!("compose.contact_existed"), cx);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -283,7 +282,7 @@ impl Compose {
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
this.update(cx, |this, cx| {
|
||||
this.set_error(Some(e.to_string().into()), cx);
|
||||
this.set_error(e.to_string(), cx);
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
@@ -312,47 +311,38 @@ impl Compose {
|
||||
|
||||
fn submit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let registry = Registry::global(cx);
|
||||
let public_keys: Vec<PublicKey> = self.selected(cx);
|
||||
let receivers: Vec<PublicKey> = self.selected(cx);
|
||||
let subject_input = self.title_input.read(cx).value();
|
||||
let subject = (!subject_input.is_empty()).then(|| subject_input.to_string());
|
||||
|
||||
if !self.user_input.read(cx).value().is_empty() {
|
||||
self.add_and_select_contact(window, cx);
|
||||
return;
|
||||
};
|
||||
|
||||
if public_keys.is_empty() {
|
||||
self.set_error(Some(t!("compose.receiver_required").into()), cx);
|
||||
return;
|
||||
};
|
||||
cx.spawn_in(window, async move |this, cx| {
|
||||
let result = Room::new(subject, receivers).await;
|
||||
|
||||
// Convert selected pubkeys into Nostr tags
|
||||
let mut tags: Tags = Tags::from_list(
|
||||
public_keys
|
||||
.iter()
|
||||
.map(|pubkey| Tag::public_key(pubkey.to_owned()))
|
||||
.collect(),
|
||||
);
|
||||
|
||||
// Add subject if it is present
|
||||
if !self.title_input.read(cx).value().is_empty() {
|
||||
tags.push(Tag::custom(
|
||||
TagKind::Subject,
|
||||
vec![self.title_input.read(cx).value().to_string()],
|
||||
));
|
||||
}
|
||||
|
||||
// Create a new room
|
||||
let room = Room::new(public_keys[0], tags, cx);
|
||||
|
||||
// Insert the new room into the registry
|
||||
this.update_in(cx, |this, window, cx| {
|
||||
match result {
|
||||
Ok(room) => {
|
||||
registry.update(cx, |this, cx| {
|
||||
this.push_room(cx.new(|_| room), cx);
|
||||
});
|
||||
|
||||
// Close the current modal
|
||||
window.close_modal(cx);
|
||||
}
|
||||
Err(e) => {
|
||||
this.set_error(e.to_string(), cx);
|
||||
}
|
||||
};
|
||||
})
|
||||
.ok();
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
fn set_error(&mut self, error: impl Into<Option<SharedString>>, cx: &mut Context<Self>) {
|
||||
fn set_error(&mut self, error: impl Into<SharedString>, cx: &mut Context<Self>) {
|
||||
// Unlock the user input
|
||||
self.user_input.update(cx, |this, cx| {
|
||||
this.set_loading(false, cx);
|
||||
@@ -360,15 +350,19 @@ impl Compose {
|
||||
|
||||
// Update error message
|
||||
self.error_message.update(cx, |this, cx| {
|
||||
*this = error.into();
|
||||
*this = Some(error.into());
|
||||
cx.notify();
|
||||
});
|
||||
|
||||
// Dismiss error after 2 seconds
|
||||
cx.spawn(async move |this, cx| {
|
||||
Timer::after(Duration::from_secs(2)).await;
|
||||
cx.background_executor().timer(Duration::from_secs(2)).await;
|
||||
|
||||
this.update(cx, |this, cx| {
|
||||
this.set_error(None, cx);
|
||||
this.error_message.update(cx, |this, cx| {
|
||||
*this = None;
|
||||
cx.notify();
|
||||
});
|
||||
})
|
||||
.ok();
|
||||
})
|
||||
@@ -424,7 +418,7 @@ impl Compose {
|
||||
impl Render for Compose {
|
||||
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let error = self.error_message.read(cx).as_ref();
|
||||
let loading = self.user_input.read(cx).loading(cx);
|
||||
let loading = self.user_input.read(cx).loading;
|
||||
let contacts = self.contacts.read(cx);
|
||||
|
||||
v_flex()
|
||||
|
||||
@@ -6,7 +6,8 @@ use global::nostr_client;
|
||||
use gpui::prelude::FluentBuilder;
|
||||
use gpui::{
|
||||
div, relative, AnyElement, App, AppContext, Context, Entity, EventEmitter, FocusHandle,
|
||||
Focusable, IntoElement, ParentElement, Render, SharedString, Styled, Subscription, Window,
|
||||
Focusable, IntoElement, ParentElement, Render, SharedString, Styled, Subscription, Task,
|
||||
Window,
|
||||
};
|
||||
use i18n::{shared_t, t};
|
||||
use nostr_connect::prelude::*;
|
||||
@@ -292,21 +293,15 @@ impl Login {
|
||||
|
||||
// Handle connection
|
||||
cx.spawn_in(window, async move |this, cx| {
|
||||
let client = nostr_client();
|
||||
|
||||
match signer.bunker_uri().await {
|
||||
Ok(uri) => {
|
||||
this.update(cx, |this, cx| {
|
||||
this.write_uri_to_disk(&uri, cx);
|
||||
this.write_uri_to_disk(signer, uri, cx);
|
||||
})
|
||||
.ok();
|
||||
|
||||
// Set the client's signer with the current nostr connect instance
|
||||
client.set_signer(signer).await;
|
||||
}
|
||||
Err(error) => {
|
||||
cx.update(|window, cx| {
|
||||
this.update(cx, |this, cx| {
|
||||
this.update_in(cx, |this, window, cx| {
|
||||
this.set_error(error.to_string(), window, cx);
|
||||
// Force reset the client keys
|
||||
//
|
||||
@@ -316,46 +311,47 @@ impl Login {
|
||||
});
|
||||
})
|
||||
.ok();
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
|
||||
fn write_uri_to_disk(&mut self, uri: &NostrConnectURI, cx: &mut Context<Self>) {
|
||||
let Some(public_key) = uri.remote_signer_public_key().cloned() else {
|
||||
log::error!("Remote Signer's public key not found");
|
||||
return;
|
||||
};
|
||||
fn write_uri_to_disk(
|
||||
&mut self,
|
||||
signer: NostrConnect,
|
||||
uri: NostrConnectURI,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
let mut uri_without_secret = uri.to_string();
|
||||
|
||||
let mut value = uri.to_string();
|
||||
|
||||
// Clear the secret param if it exists
|
||||
// Clear the secret parameter in the URI if it exists
|
||||
if let Some(secret) = uri.secret() {
|
||||
value = value.replace(secret, "");
|
||||
uri_without_secret = uri_without_secret.replace(secret, "");
|
||||
}
|
||||
|
||||
cx.background_spawn(async move {
|
||||
let task: Task<Result<(), anyhow::Error>> = cx.background_spawn(async move {
|
||||
let client = nostr_client();
|
||||
let keys = Keys::generate();
|
||||
let tags = vec![Tag::identifier(ACCOUNT_IDENTIFIER)];
|
||||
let kind = Kind::ApplicationSpecificData;
|
||||
|
||||
let builder = EventBuilder::new(kind, value)
|
||||
.tags(tags)
|
||||
// Update the client's signer
|
||||
client.set_signer(signer).await;
|
||||
|
||||
let signer = client.signer().await?;
|
||||
let public_key = signer.get_public_key().await?;
|
||||
|
||||
let event = EventBuilder::new(Kind::ApplicationSpecificData, uri_without_secret)
|
||||
.tags(vec![Tag::identifier(ACCOUNT_IDENTIFIER)])
|
||||
.build(public_key)
|
||||
.sign(&keys)
|
||||
.await;
|
||||
.sign(&Keys::generate())
|
||||
.await?;
|
||||
|
||||
if let Ok(event) = builder {
|
||||
if let Err(e) = client.database().save_event(&event).await {
|
||||
log::error!("Failed to save event: {e}");
|
||||
};
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
// Save the event to the database
|
||||
client.database().save_event(&event).await?;
|
||||
|
||||
Ok(())
|
||||
});
|
||||
|
||||
task.detach();
|
||||
}
|
||||
|
||||
pub fn write_keys_to_disk(&self, keys: &Keys, password: String, cx: &mut Context<Self>) {
|
||||
|
||||
@@ -135,7 +135,6 @@ impl Onboarding {
|
||||
self._tasks.push(
|
||||
// Wait for Nostr Connect approval
|
||||
cx.spawn_in(window, async move |this, cx| {
|
||||
let client = nostr_client();
|
||||
let connect = this.read_with(cx, |this, cx| this.nostr_connect.read(cx).clone());
|
||||
|
||||
if let Ok(Some(signer)) = connect {
|
||||
@@ -143,12 +142,9 @@ impl Onboarding {
|
||||
Ok(uri) => {
|
||||
this.update(cx, |this, cx| {
|
||||
this.set_connecting(cx);
|
||||
this.write_uri_to_disk(&uri, cx);
|
||||
this.write_uri_to_disk(signer, uri, cx);
|
||||
})
|
||||
.ok();
|
||||
|
||||
// Set the client's signer with the current nostr connect instance
|
||||
client.set_signer(signer).await;
|
||||
}
|
||||
Err(e) => {
|
||||
this.update_in(cx, |_, window, cx| {
|
||||
@@ -169,38 +165,41 @@ impl Onboarding {
|
||||
ChatSpace::proxy_signer(window, cx);
|
||||
}
|
||||
|
||||
fn write_uri_to_disk(&mut self, uri: &NostrConnectURI, cx: &mut Context<Self>) {
|
||||
let Some(public_key) = uri.remote_signer_public_key().cloned() else {
|
||||
log::error!("Remote Signer's public key not found");
|
||||
return;
|
||||
};
|
||||
fn write_uri_to_disk(
|
||||
&mut self,
|
||||
signer: NostrConnect,
|
||||
uri: NostrConnectURI,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
let mut uri_without_secret = uri.to_string();
|
||||
|
||||
let mut value = uri.to_string();
|
||||
|
||||
// Clear the secret param if it exists
|
||||
// Clear the secret parameter in the URI if it exists
|
||||
if let Some(secret) = uri.secret() {
|
||||
value = value.replace(secret, "");
|
||||
uri_without_secret = uri_without_secret.replace(secret, "");
|
||||
}
|
||||
|
||||
cx.background_spawn(async move {
|
||||
let task: Task<Result<(), anyhow::Error>> = cx.background_spawn(async move {
|
||||
let client = nostr_client();
|
||||
let keys = Keys::generate();
|
||||
let tags = vec![Tag::identifier(ACCOUNT_IDENTIFIER)];
|
||||
let kind = Kind::ApplicationSpecificData;
|
||||
|
||||
let builder = EventBuilder::new(kind, value)
|
||||
.tags(tags)
|
||||
// Update the client's signer
|
||||
client.set_signer(signer).await;
|
||||
|
||||
let signer = client.signer().await?;
|
||||
let public_key = signer.get_public_key().await?;
|
||||
|
||||
let event = EventBuilder::new(Kind::ApplicationSpecificData, uri_without_secret)
|
||||
.tags(vec![Tag::identifier(ACCOUNT_IDENTIFIER)])
|
||||
.build(public_key)
|
||||
.sign(&keys)
|
||||
.await;
|
||||
.sign(&Keys::generate())
|
||||
.await?;
|
||||
|
||||
if let Ok(event) = builder {
|
||||
if let Err(e) = client.database().save_event(&event).await {
|
||||
log::error!("Failed to save event: {e}");
|
||||
};
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
// Save the event to the database
|
||||
client.database().save_event(&event).await?;
|
||||
|
||||
Ok(())
|
||||
});
|
||||
|
||||
task.detach();
|
||||
}
|
||||
|
||||
fn copy_uri(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use common::display::RenderedProfile;
|
||||
use gpui::http_client::Url;
|
||||
use gpui::prelude::FluentBuilder;
|
||||
use gpui::{
|
||||
div, px, relative, rems, App, AppContext, Context, Entity, InteractiveElement, IntoElement,
|
||||
ParentElement, Render, SharedString, StatefulInteractiveElement, Styled, Window,
|
||||
@@ -111,9 +112,6 @@ impl Preferences {
|
||||
|
||||
impl Render for Preferences {
|
||||
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let input_state = self.media_input.downgrade();
|
||||
let profile = Registry::read_global(cx).identity(cx);
|
||||
|
||||
let auto_auth = AppSettings::get_auto_auth(cx);
|
||||
let backup = AppSettings::get_backup_messages(cx);
|
||||
let screening = AppSettings::get_screening(cx);
|
||||
@@ -121,6 +119,9 @@ impl Render for Preferences {
|
||||
let proxy = AppSettings::get_proxy_user_avatars(cx);
|
||||
let hide = AppSettings::get_hide_user_avatars(cx);
|
||||
|
||||
let registry = Registry::read_global(cx);
|
||||
let input_state = self.media_input.downgrade();
|
||||
|
||||
v_flex()
|
||||
.child(
|
||||
v_flex()
|
||||
@@ -133,7 +134,10 @@ impl Render for Preferences {
|
||||
.font_semibold()
|
||||
.child(shared_t!("preferences.account_header")),
|
||||
)
|
||||
.child(
|
||||
.when_some(registry.signer_pubkey(), |this, public_key| {
|
||||
let profile = registry.get_person(&public_key, cx);
|
||||
|
||||
this.child(
|
||||
h_flex()
|
||||
.w_full()
|
||||
.justify_between()
|
||||
@@ -157,7 +161,9 @@ impl Render for Preferences {
|
||||
.text_xs()
|
||||
.text_color(cx.theme().text_muted)
|
||||
.line_height(relative(1.3))
|
||||
.child(shared_t!("preferences.account_btn")),
|
||||
.child(shared_t!(
|
||||
"preferences.account_btn"
|
||||
)),
|
||||
),
|
||||
)
|
||||
.on_click(cx.listener(move |this, _e, window, cx| {
|
||||
@@ -174,7 +180,8 @@ impl Render for Preferences {
|
||||
this.open_relays(window, cx);
|
||||
})),
|
||||
),
|
||||
),
|
||||
)
|
||||
}),
|
||||
)
|
||||
.child(
|
||||
v_flex()
|
||||
@@ -204,7 +211,7 @@ impl Render for Preferences {
|
||||
.on_click(move |_, _window, cx| {
|
||||
if let Some(input) = input_state.upgrade() {
|
||||
let Ok(url) =
|
||||
Url::parse(input.read(cx).value())
|
||||
Url::parse(&input.read(cx).value())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -37,16 +37,18 @@ pub struct Screening {
|
||||
impl Screening {
|
||||
pub fn new(public_key: PublicKey, window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||
let registry = Registry::read_global(cx);
|
||||
let identity = registry.identity(cx).public_key();
|
||||
let profile = registry.get_person(&public_key, cx);
|
||||
|
||||
let mut tasks = smallvec![];
|
||||
|
||||
let contact_check: Task<(bool, Vec<Profile>)> = cx.background_spawn(async move {
|
||||
let contact_check: Task<Result<(bool, Vec<Profile>), Error>> =
|
||||
cx.background_spawn(async move {
|
||||
let client = nostr_client();
|
||||
let signer = client.signer().await?;
|
||||
let signer_pubkey = signer.get_public_key().await?;
|
||||
|
||||
// Check if user is in contact list
|
||||
let contacts = client.database().contacts_public_keys(identity).await;
|
||||
let contacts = client.database().contacts_public_keys(signer_pubkey).await;
|
||||
let followed = contacts.unwrap_or_default().contains(&public_key);
|
||||
|
||||
// Check mutual contacts
|
||||
@@ -54,7 +56,7 @@ impl Screening {
|
||||
let mut mutual_contacts = vec![];
|
||||
|
||||
if let Ok(events) = client.database().query(contact_list).await {
|
||||
for event in events.into_iter().filter(|ev| ev.pubkey != identity) {
|
||||
for event in events.into_iter().filter(|ev| ev.pubkey != signer_pubkey) {
|
||||
if let Ok(metadata) = client.database().metadata(event.pubkey).await {
|
||||
let profile = Profile::new(event.pubkey, metadata.unwrap_or_default());
|
||||
mutual_contacts.push(profile);
|
||||
@@ -62,7 +64,7 @@ impl Screening {
|
||||
}
|
||||
}
|
||||
|
||||
(followed, mutual_contacts)
|
||||
Ok((followed, mutual_contacts))
|
||||
});
|
||||
|
||||
let activity_check = cx.background_spawn(async move {
|
||||
@@ -93,14 +95,14 @@ impl Screening {
|
||||
tasks.push(
|
||||
// Run the contact check in the background
|
||||
cx.spawn_in(window, async move |this, cx| {
|
||||
let (followed, mutual_contacts) = contact_check.await;
|
||||
|
||||
if let Ok((followed, mutual_contacts)) = contact_check.await {
|
||||
this.update(cx, |this, cx| {
|
||||
this.followed = followed;
|
||||
this.mutual_contacts = mutual_contacts;
|
||||
cx.notify();
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -11,7 +11,6 @@ use gpui::{
|
||||
};
|
||||
use i18n::{shared_t, t};
|
||||
use nostr_sdk::prelude::*;
|
||||
use registry::Registry;
|
||||
use smallvec::{smallvec, SmallVec};
|
||||
use theme::ActiveTheme;
|
||||
use ui::button::{Button, ButtonVariants};
|
||||
@@ -70,7 +69,6 @@ pub struct SetupRelay {
|
||||
|
||||
impl SetupRelay {
|
||||
pub fn new(kind: Kind, window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||
let identity = Registry::read_global(cx).identity(cx).public_key();
|
||||
let input = cx.new(|cx| InputState::new(window, cx).placeholder("wss://example.com"));
|
||||
|
||||
let mut subscriptions = smallvec![];
|
||||
@@ -78,7 +76,10 @@ impl SetupRelay {
|
||||
|
||||
let load_relay = cx.background_spawn(async move {
|
||||
let client = nostr_client();
|
||||
let filter = Filter::new().kind(kind).author(identity).limit(1);
|
||||
let signer = client.signer().await?;
|
||||
let public_key = signer.get_public_key().await?;
|
||||
|
||||
let filter = Filter::new().kind(kind).author(public_key).limit(1);
|
||||
|
||||
if let Some(event) = client.database().query(filter).await?.first() {
|
||||
let relays: Vec<RelayUrl> = event
|
||||
|
||||
@@ -11,7 +11,9 @@ use registry::room::RoomKind;
|
||||
use registry::Registry;
|
||||
use settings::AppSettings;
|
||||
use theme::ActiveTheme;
|
||||
use ui::actions::{CopyPublicKey, OpenPublicKey};
|
||||
use ui::avatar::Avatar;
|
||||
use ui::context_menu::ContextMenuExt;
|
||||
use ui::modal::ModalButtonProps;
|
||||
use ui::skeleton::Skeleton;
|
||||
use ui::{h_flex, ContextModal, StyledExt};
|
||||
@@ -166,6 +168,10 @@ impl RenderOnce for RoomListItem {
|
||||
),
|
||||
)
|
||||
.hover(|this| this.bg(cx.theme().elevated_surface_background))
|
||||
.context_menu(move |this, _window, _cx| {
|
||||
this.menu(t!("profile.view"), Box::new(OpenPublicKey(public_key)))
|
||||
.menu(t!("profile.copy"), Box::new(CopyPublicKey(public_key)))
|
||||
})
|
||||
.on_click(move |event, window, cx| {
|
||||
handler(event, window, cx);
|
||||
|
||||
|
||||
@@ -100,12 +100,12 @@ impl Sidebar {
|
||||
|
||||
subscriptions.push(
|
||||
// Subscribe for find input events
|
||||
cx.subscribe_in(&find_input, window, |this, _state, event, window, cx| {
|
||||
cx.subscribe_in(&find_input, window, |this, state, event, window, cx| {
|
||||
match event {
|
||||
InputEvent::PressEnter { .. } => this.search(window, cx),
|
||||
InputEvent::Change(text) => {
|
||||
InputEvent::Change => {
|
||||
// Clear the result when input is empty
|
||||
if text.is_empty() {
|
||||
if state.read(cx).value().is_empty() {
|
||||
this.clear_search_results(window, cx);
|
||||
} else {
|
||||
// Run debounced search
|
||||
@@ -138,7 +138,8 @@ impl Sidebar {
|
||||
}
|
||||
}
|
||||
|
||||
async fn request_metadata(client: &Client, public_key: PublicKey) -> Result<(), Error> {
|
||||
async fn request_metadata(public_key: PublicKey) -> Result<(), Error> {
|
||||
let client = nostr_client();
|
||||
let opts = SubscribeAutoCloseOptions::default().exit_policy(ReqExitPolicy::ExitOnEOSE);
|
||||
let kinds = vec![Kind::Metadata, Kind::ContactList, Kind::RelayList];
|
||||
let filter = Filter::new().author(public_key).kinds(kinds).limit(10);
|
||||
@@ -152,23 +153,21 @@ impl Sidebar {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn create_temp_room(identity: PublicKey, public_key: PublicKey) -> Result<Room, Error> {
|
||||
let client = nostr_client();
|
||||
let keys = Keys::generate();
|
||||
let builder = EventBuilder::private_msg_rumor(public_key, "");
|
||||
let event = builder.build(identity).sign(&keys).await?;
|
||||
|
||||
async fn create_temp_room(receiver: PublicKey) -> Result<Room, Error> {
|
||||
// Request to get user's metadata
|
||||
Self::request_metadata(client, public_key).await?;
|
||||
Self::request_metadata(receiver).await?;
|
||||
|
||||
// Create a temporary room
|
||||
let room = Room::from(&event).current_user(identity);
|
||||
let room = Room::new(None, vec![receiver]).await?;
|
||||
|
||||
Ok(room)
|
||||
}
|
||||
|
||||
async fn nip50(identity: PublicKey, query: &str) -> BTreeSet<Room> {
|
||||
async fn nip50(query: &str) -> Result<BTreeSet<Room>, Error> {
|
||||
let client = nostr_client();
|
||||
let signer = client.signer().await?;
|
||||
let public_key = signer.get_public_key().await?;
|
||||
|
||||
let timeout = Duration::from_secs(2);
|
||||
let mut rooms: BTreeSet<Room> = BTreeSet::new();
|
||||
|
||||
@@ -184,18 +183,18 @@ impl Sidebar {
|
||||
// Process to verify the search results
|
||||
for event in events.into_iter().unique_by(|event| event.pubkey) {
|
||||
// Skip if author is match current user
|
||||
if event.pubkey == identity {
|
||||
if event.pubkey == public_key {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Return a temporary room
|
||||
if let Ok(room) = Self::create_temp_room(identity, event.pubkey).await {
|
||||
if let Ok(room) = Self::create_temp_room(event.pubkey).await {
|
||||
rooms.insert(room);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
rooms
|
||||
Ok(rooms)
|
||||
}
|
||||
|
||||
fn debounced_search(&self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
|
||||
@@ -214,15 +213,11 @@ impl Sidebar {
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
let identity = Registry::read_global(cx).identity(cx).public_key();
|
||||
let query = query.to_owned();
|
||||
let query_cloned = query.clone();
|
||||
|
||||
let task = smol::future::or(
|
||||
Tokio::spawn(cx, async move {
|
||||
let rooms = Self::nip50(identity, &query).await;
|
||||
Some(rooms)
|
||||
}),
|
||||
Tokio::spawn(cx, async move { Self::nip50(&query).await.ok() }),
|
||||
Tokio::spawn(cx, async move {
|
||||
let _ = rx.recv().await.is_ok();
|
||||
None
|
||||
@@ -269,12 +264,11 @@ impl Sidebar {
|
||||
}
|
||||
|
||||
fn search_by_nip05(&mut self, query: &str, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let identity = Registry::read_global(cx).identity(cx).public_key();
|
||||
let address = query.to_owned();
|
||||
|
||||
let task = Tokio::spawn(cx, async move {
|
||||
if let Ok(profile) = common::nip05::nip05_profile(&address).await {
|
||||
Self::create_temp_room(identity, profile.public_key).await
|
||||
Self::create_temp_room(profile.public_key).await
|
||||
} else {
|
||||
Err(anyhow!(t!("sidebar.addr_error")))
|
||||
}
|
||||
@@ -323,10 +317,9 @@ impl Sidebar {
|
||||
return;
|
||||
};
|
||||
|
||||
let identity = Registry::read_global(cx).identity(cx).public_key();
|
||||
let task: Task<Result<Room, Error>> = cx.background_spawn(async move {
|
||||
// Create a gift wrap event to represent as room
|
||||
Self::create_temp_room(identity, public_key).await
|
||||
Self::create_temp_room(public_key).await
|
||||
});
|
||||
|
||||
cx.spawn_in(window, async move |this, cx| {
|
||||
@@ -722,6 +715,7 @@ impl Render for Sidebar {
|
||||
.small()
|
||||
.cleanable()
|
||||
.appearance(true)
|
||||
.text_xs()
|
||||
.suffix(
|
||||
Button::new("find")
|
||||
.icon(IconName::Search)
|
||||
|
||||
@@ -17,7 +17,7 @@ use smallvec::{smallvec, SmallVec};
|
||||
use theme::ActiveTheme;
|
||||
use ui::avatar::Avatar;
|
||||
use ui::button::{Button, ButtonVariants};
|
||||
use ui::{h_flex, v_flex, Disableable, Icon, IconName, Sizable, StyledExt};
|
||||
use ui::{h_flex, v_flex, Icon, IconName, Sizable, StyledExt};
|
||||
|
||||
pub fn init(public_key: PublicKey, window: &mut Window, cx: &mut App) -> Entity<UserProfile> {
|
||||
cx.new(|cx| UserProfile::new(public_key, window, cx))
|
||||
@@ -32,27 +32,24 @@ pub struct UserProfile {
|
||||
}
|
||||
|
||||
impl UserProfile {
|
||||
pub fn new(public_key: PublicKey, window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||
pub fn new(target: PublicKey, window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||
let registry = Registry::read_global(cx);
|
||||
let identity = registry.identity(cx).public_key();
|
||||
let profile = registry.get_person(&public_key, cx);
|
||||
let profile = registry.get_person(&target, cx);
|
||||
|
||||
let mut tasks = smallvec![];
|
||||
|
||||
let check_follow: Task<bool> = cx.background_spawn(async move {
|
||||
let check_follow: Task<Result<bool, Error>> = cx.background_spawn(async move {
|
||||
let client = nostr_client();
|
||||
let filter = Filter::new()
|
||||
.kind(Kind::ContactList)
|
||||
.author(identity)
|
||||
.pubkey(public_key)
|
||||
.limit(1);
|
||||
let signer = client.signer().await?;
|
||||
let public_key = signer.get_public_key().await?;
|
||||
let contact_list = client.database().contacts_public_keys(public_key).await?;
|
||||
|
||||
client.database().count(filter).await.unwrap_or(0) >= 1
|
||||
Ok(contact_list.contains(&target))
|
||||
});
|
||||
|
||||
let verify_nip05 = if let Some(address) = profile.metadata().nip05 {
|
||||
Some(Tokio::spawn(cx, async move {
|
||||
nip05_verify(public_key, &address).await.unwrap_or(false)
|
||||
nip05_verify(target, &address).await.unwrap_or(false)
|
||||
}))
|
||||
} else {
|
||||
None
|
||||
@@ -61,7 +58,7 @@ impl UserProfile {
|
||||
tasks.push(
|
||||
// Load user profile data
|
||||
cx.spawn_in(window, async move |this, cx| {
|
||||
let followed = check_follow.await;
|
||||
let followed = check_follow.await.unwrap_or(false);
|
||||
|
||||
// Update the followed status
|
||||
this.update(cx, |this, cx| {
|
||||
@@ -133,6 +130,7 @@ impl Render for UserProfile {
|
||||
|
||||
v_flex()
|
||||
.gap_4()
|
||||
.text_sm()
|
||||
.child(
|
||||
v_flex()
|
||||
.gap_3()
|
||||
@@ -188,10 +186,8 @@ impl Render for UserProfile {
|
||||
.child(
|
||||
v_flex()
|
||||
.gap_1()
|
||||
.text_sm()
|
||||
.child(
|
||||
div()
|
||||
.block()
|
||||
.text_color(cx.theme().text_muted)
|
||||
.child(SharedString::from("Public Key:")),
|
||||
)
|
||||
@@ -201,12 +197,13 @@ impl Render for UserProfile {
|
||||
.child(
|
||||
div()
|
||||
.p_2()
|
||||
.h_9()
|
||||
.h_7()
|
||||
.rounded_md()
|
||||
.bg(cx.theme().elevated_surface_background)
|
||||
.truncate()
|
||||
.text_ellipsis()
|
||||
.line_clamp(1)
|
||||
.line_height(relative(1.))
|
||||
.child(shared_bech32),
|
||||
)
|
||||
.child(
|
||||
@@ -218,8 +215,8 @@ impl Render for UserProfile {
|
||||
IconName::Copy
|
||||
}
|
||||
})
|
||||
.ghost()
|
||||
.disabled(self.copied)
|
||||
.cta()
|
||||
.ghost_alt()
|
||||
.on_click(cx.listener(move |this, _e, window, cx| {
|
||||
this.copy_pubkey(window, cx);
|
||||
})),
|
||||
@@ -229,7 +226,6 @@ impl Render for UserProfile {
|
||||
.child(
|
||||
v_flex()
|
||||
.gap_1()
|
||||
.text_sm()
|
||||
.child(
|
||||
div()
|
||||
.text_color(cx.theme().text_muted)
|
||||
|
||||
@@ -147,28 +147,40 @@ impl Ingester {
|
||||
/// A simple storage to store all states that using across the application.
|
||||
#[derive(Debug)]
|
||||
pub struct AppState {
|
||||
/// The timestamp when the application was initialized.
|
||||
pub init_at: Timestamp,
|
||||
|
||||
/// The timestamp when the application was last used.
|
||||
pub last_used_at: Option<Timestamp>,
|
||||
|
||||
/// Whether this is the first run of the application.
|
||||
pub is_first_run: AtomicBool,
|
||||
|
||||
/// Subscription ID for listening to gift wrap events from relays.
|
||||
pub gift_wrap_sub_id: SubscriptionId,
|
||||
|
||||
pub gift_wrap_processing: AtomicBool,
|
||||
|
||||
/// Auto-close options for relay subscriptions
|
||||
pub auto_close_opts: Option<SubscribeAutoCloseOptions>,
|
||||
|
||||
pub seen_on_relays: RwLock<HashMap<EventId, HashSet<RelayUrl>>>,
|
||||
/// Whether gift wrap processing is in progress.
|
||||
pub gift_wrap_processing: AtomicBool,
|
||||
|
||||
/// Tracking events sent by Coop in the current session
|
||||
pub sent_ids: RwLock<HashSet<EventId>>,
|
||||
|
||||
/// Tracking events seen on which relays in the current session
|
||||
pub seen_on_relays: RwLock<HashMap<EventId, HashSet<RelayUrl>>>,
|
||||
|
||||
/// Tracking events that have been resent by Coop in the current session
|
||||
pub resent_ids: RwLock<Vec<Output<EventId>>>,
|
||||
|
||||
/// Temporarily store events that need to be resent later
|
||||
pub resend_queue: RwLock<HashMap<EventId, RelayUrl>>,
|
||||
|
||||
/// Signal channel for communication between Nostr and GPUI
|
||||
pub signal: Signal,
|
||||
|
||||
/// Ingester channel for processing public keys
|
||||
pub ingester: Ingester,
|
||||
}
|
||||
|
||||
@@ -196,8 +208,8 @@ impl AppState {
|
||||
gift_wrap_sub_id: SubscriptionId::new("inbox"),
|
||||
gift_wrap_processing: AtomicBool::new(false),
|
||||
auto_close_opts: Some(opts),
|
||||
seen_on_relays: RwLock::new(HashMap::new()),
|
||||
sent_ids: RwLock::new(HashSet::new()),
|
||||
seen_on_relays: RwLock::new(HashMap::new()),
|
||||
resent_ids: RwLock::new(Vec::new()),
|
||||
resend_queue: RwLock::new(HashMap::new()),
|
||||
}
|
||||
@@ -223,7 +235,7 @@ pub fn nostr_client() -> &'static Client {
|
||||
.automatic_authentication(false)
|
||||
.verify_subscriptions(false)
|
||||
.sleep_when_idle(SleepWhenIdle::Enabled {
|
||||
timeout: Duration::from_secs(300),
|
||||
timeout: Duration::from_secs(600),
|
||||
});
|
||||
|
||||
ClientBuilder::default().database(lmdb).opts(opts).build()
|
||||
|
||||
+25
-28
@@ -44,8 +44,8 @@ pub struct Registry {
|
||||
/// Status of the unwrapping process
|
||||
pub unwrapping_status: Entity<UnwrappingStatus>,
|
||||
|
||||
/// Public Key of the current user
|
||||
pub identity: Option<PublicKey>,
|
||||
/// Public key of the currently activated signer
|
||||
signer_pubkey: Option<PublicKey>,
|
||||
|
||||
/// Tasks for asynchronous operations
|
||||
_tasks: SmallVec<[Task<()>; 1]>,
|
||||
@@ -106,21 +106,19 @@ impl Registry {
|
||||
unwrapping_status,
|
||||
rooms: vec![],
|
||||
persons: HashMap::new(),
|
||||
identity: None,
|
||||
signer_pubkey: None,
|
||||
_tasks: tasks,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the identity of the user.
|
||||
///
|
||||
/// WARNING: This method will panic if user is not logged in.
|
||||
pub fn identity(&self, cx: &App) -> Profile {
|
||||
self.get_person(&self.identity.unwrap(), cx)
|
||||
/// Returns the public key of the currently activated signer.
|
||||
pub fn signer_pubkey(&self) -> Option<PublicKey> {
|
||||
self.signer_pubkey
|
||||
}
|
||||
|
||||
/// Sets the identity of the user.
|
||||
pub fn set_identity(&mut self, identity: PublicKey, cx: &mut Context<Self>) {
|
||||
self.identity = Some(identity);
|
||||
/// Update the public key of the currently activated signer.
|
||||
pub fn set_signer_pubkey(&mut self, public_key: PublicKey, cx: &mut Context<Self>) {
|
||||
self.signer_pubkey = Some(public_key);
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
@@ -254,7 +252,7 @@ impl Registry {
|
||||
self.set_unwrapping_status(UnwrappingStatus::default(), cx);
|
||||
|
||||
// Clear the current identity
|
||||
self.identity = None;
|
||||
self.signer_pubkey = None;
|
||||
|
||||
// Clear all current rooms
|
||||
self.rooms.clear();
|
||||
@@ -276,7 +274,7 @@ impl Registry {
|
||||
let contacts = client.database().contacts_public_keys(public_key).await?;
|
||||
|
||||
// Get messages sent by the user
|
||||
let send = Filter::new()
|
||||
let sent = Filter::new()
|
||||
.kind(Kind::PrivateDirectMessage)
|
||||
.author(public_key);
|
||||
|
||||
@@ -285,9 +283,9 @@ impl Registry {
|
||||
.kind(Kind::PrivateDirectMessage)
|
||||
.pubkey(public_key);
|
||||
|
||||
let send_events = client.database().query(send).await?;
|
||||
let sent_events = client.database().query(sent).await?;
|
||||
let recv_events = client.database().query(recv).await?;
|
||||
let events = send_events.merge(recv_events);
|
||||
let events = sent_events.merge(recv_events);
|
||||
|
||||
let mut rooms: HashSet<Room> = HashSet::new();
|
||||
|
||||
@@ -297,12 +295,16 @@ impl Registry {
|
||||
.sorted_by_key(|event| Reverse(event.created_at))
|
||||
.filter(|ev| ev.tags.public_keys().peekable().peek().is_some())
|
||||
{
|
||||
if rooms.iter().any(|room| room.id == event.uniq_id()) {
|
||||
// Parse the room from the nostr event
|
||||
let room = Room::from(&event);
|
||||
|
||||
// Skip if the room is already in the set
|
||||
if rooms.iter().any(|r| r.id == room.id) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Get all public keys from the event's tags
|
||||
let mut public_keys = event.all_pubkeys();
|
||||
let mut public_keys: Vec<PublicKey> = room.members().to_vec();
|
||||
public_keys.retain(|pk| pk != &public_key);
|
||||
|
||||
// Bypass screening flag
|
||||
@@ -323,9 +325,6 @@ impl Registry {
|
||||
// If current user has sent a message at least once, mark as ongoing
|
||||
let is_ongoing = client.database().count(filter).await.unwrap_or(1) >= 1;
|
||||
|
||||
// Create a new room
|
||||
let room = Room::from(&event).current_user(public_key);
|
||||
|
||||
if is_ongoing || bypassed {
|
||||
rooms.insert(room.kind(RoomKind::Ongoing));
|
||||
} else {
|
||||
@@ -419,7 +418,7 @@ impl Registry {
|
||||
/// Updates room ordering based on the most recent messages.
|
||||
pub fn event_to_message(
|
||||
&mut self,
|
||||
gift_wrap_id: EventId,
|
||||
gift_wrap: EventId,
|
||||
event: Event,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
@@ -427,7 +426,7 @@ impl Registry {
|
||||
let id = event.uniq_id();
|
||||
let author = event.pubkey;
|
||||
|
||||
let Some(identity) = self.identity else {
|
||||
let Some(public_key) = self.signer_pubkey else {
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -437,17 +436,17 @@ impl Registry {
|
||||
// Update room
|
||||
room.update(cx, |this, cx| {
|
||||
if is_new_event {
|
||||
this.created_at(event.created_at, cx);
|
||||
this.set_created_at(event.created_at, cx);
|
||||
}
|
||||
|
||||
// Set this room is ongoing if the new message is from current user
|
||||
if author == identity {
|
||||
if author == public_key {
|
||||
this.set_ongoing(cx);
|
||||
}
|
||||
|
||||
// Emit the new message to the room
|
||||
cx.defer_in(window, move |this, _window, cx| {
|
||||
this.emit_message(gift_wrap_id, event, cx);
|
||||
this.emit_message(gift_wrap, event, cx);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -458,10 +457,8 @@ impl Registry {
|
||||
});
|
||||
}
|
||||
} else {
|
||||
let room = Room::from(&event).current_user(identity);
|
||||
|
||||
// Push the new room to the front of the list
|
||||
self.add_room(cx.new(|_| room), cx);
|
||||
self.add_room(cx.new(|_| Room::from(&event)), cx);
|
||||
|
||||
// Notify the UI about the new room
|
||||
cx.defer_in(window, move |_this, _window, cx| {
|
||||
|
||||
@@ -14,27 +14,33 @@ impl Message {
|
||||
Self::User(user.into())
|
||||
}
|
||||
|
||||
pub fn warning(content: String) -> Self {
|
||||
Self::Warning(content, Timestamp::now())
|
||||
pub fn warning(content: impl Into<String>) -> Self {
|
||||
Self::Warning(content.into(), Timestamp::now())
|
||||
}
|
||||
|
||||
pub fn system() -> Self {
|
||||
Self::System(Timestamp::default())
|
||||
}
|
||||
|
||||
fn timestamp(&self) -> &Timestamp {
|
||||
match self {
|
||||
Message::User(msg) => &msg.created_at,
|
||||
Message::Warning(_, ts) => ts,
|
||||
Message::System(ts) => ts,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Ord for Message {
|
||||
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
|
||||
match (self, other) {
|
||||
(Message::User(a), Message::User(b)) => a.cmp(b),
|
||||
(Message::System(a), Message::System(b)) => a.cmp(b),
|
||||
(Message::User(a), Message::System(b)) => a.created_at.cmp(b),
|
||||
(Message::System(a), Message::User(b)) => a.cmp(&b.created_at),
|
||||
(Message::Warning(_, a), Message::Warning(_, b)) => a.cmp(b),
|
||||
(Message::Warning(_, a), Message::User(b)) => a.cmp(&b.created_at),
|
||||
(Message::User(a), Message::Warning(_, b)) => a.created_at.cmp(b),
|
||||
(Message::Warning(_, a), Message::System(b)) => a.cmp(b),
|
||||
(Message::System(a), Message::Warning(_, b)) => a.cmp(b),
|
||||
// System always comes first
|
||||
(Message::System(_), Message::System(_)) => self.timestamp().cmp(other.timestamp()),
|
||||
(Message::System(_), _) => std::cmp::Ordering::Less,
|
||||
(_, Message::System(_)) => std::cmp::Ordering::Greater,
|
||||
|
||||
// For non-system messages, compare by timestamp
|
||||
_ => self.timestamp().cmp(other.timestamp()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -151,20 +157,16 @@ fn extract_reply_ids(inner: &Tags) -> Vec<EventId> {
|
||||
let mut replies_to = vec![];
|
||||
|
||||
for tag in inner.filter(TagKind::e()) {
|
||||
if let Some(content) = tag.content() {
|
||||
if let Ok(id) = EventId::from_hex(content) {
|
||||
if let Some(id) = tag.content().and_then(|id| EventId::parse(id).ok()) {
|
||||
replies_to.push(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for tag in inner.filter(TagKind::q()) {
|
||||
if let Some(content) = tag.content() {
|
||||
if let Ok(id) = EventId::from_hex(content) {
|
||||
if let Some(id) = tag.content().and_then(|id| EventId::parse(id).ok()) {
|
||||
replies_to.push(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
replies_to
|
||||
}
|
||||
|
||||
+281
-229
@@ -3,7 +3,7 @@ use std::collections::{HashMap, HashSet};
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Error;
|
||||
use anyhow::{anyhow, Error};
|
||||
use common::display::RenderedProfile;
|
||||
use common::event::EventUtils;
|
||||
use global::constants::SEND_RETRY;
|
||||
@@ -17,9 +17,9 @@ use crate::Registry;
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SendReport {
|
||||
pub receiver: PublicKey,
|
||||
pub tags: Option<Vec<Tag>>,
|
||||
pub status: Option<Output<EventId>>,
|
||||
pub error: Option<SharedString>,
|
||||
pub on_hold: Option<Event>,
|
||||
pub relays_not_found: bool,
|
||||
}
|
||||
|
||||
@@ -29,13 +29,14 @@ impl SendReport {
|
||||
receiver,
|
||||
status: None,
|
||||
error: None,
|
||||
tags: None,
|
||||
on_hold: None,
|
||||
relays_not_found: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn not_found(mut self) -> Self {
|
||||
self.relays_not_found = true;
|
||||
pub fn status(mut self, output: Output<EventId>) -> Self {
|
||||
self.status = Some(output);
|
||||
self.relays_not_found = false;
|
||||
self
|
||||
}
|
||||
|
||||
@@ -45,14 +46,13 @@ impl SendReport {
|
||||
self
|
||||
}
|
||||
|
||||
pub fn status(mut self, output: Output<EventId>) -> Self {
|
||||
self.status = Some(output);
|
||||
self.relays_not_found = false;
|
||||
pub fn on_hold(mut self, event: Event) -> Self {
|
||||
self.on_hold = Some(event);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn tags(mut self, tags: &Vec<Tag>) -> Self {
|
||||
self.tags = Some(tags.to_owned());
|
||||
pub fn not_found(mut self) -> Self {
|
||||
self.relays_not_found = true;
|
||||
self
|
||||
}
|
||||
|
||||
@@ -88,8 +88,6 @@ pub struct Room {
|
||||
pub created_at: Timestamp,
|
||||
/// Subject of the room
|
||||
pub subject: Option<String>,
|
||||
/// Picture of the room
|
||||
pub picture: Option<String>,
|
||||
/// All members of the room
|
||||
pub members: Vec<PublicKey>,
|
||||
/// Kind
|
||||
@@ -130,32 +128,18 @@ impl From<&Event> for Room {
|
||||
let created_at = val.created_at;
|
||||
|
||||
// Get the members from the event's tags and event's pubkey
|
||||
let members = val
|
||||
.all_pubkeys()
|
||||
.into_iter()
|
||||
.unique()
|
||||
.sorted()
|
||||
.collect_vec();
|
||||
let members = val.all_pubkeys();
|
||||
|
||||
// Get the subject from the event's tags
|
||||
let subject = if let Some(tag) = val.tags.find(TagKind::Subject) {
|
||||
tag.content().map(|s| s.to_owned())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// Get the picture from the event's tags
|
||||
let picture = if let Some(tag) = val.tags.find(TagKind::custom("picture")) {
|
||||
tag.content().map(|s| s.to_owned())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// Get subject from tags
|
||||
let subject = val
|
||||
.tags
|
||||
.find(TagKind::Subject)
|
||||
.and_then(|tag| tag.content().map(|s| s.to_owned()));
|
||||
|
||||
Room {
|
||||
id,
|
||||
created_at,
|
||||
subject,
|
||||
picture,
|
||||
members,
|
||||
kind: RoomKind::default(),
|
||||
}
|
||||
@@ -168,32 +152,18 @@ impl From<&UnsignedEvent> for Room {
|
||||
let created_at = val.created_at;
|
||||
|
||||
// Get the members from the event's tags and event's pubkey
|
||||
let members = val
|
||||
.all_pubkeys()
|
||||
.into_iter()
|
||||
.unique()
|
||||
.sorted()
|
||||
.collect_vec();
|
||||
let members = val.all_pubkeys();
|
||||
|
||||
// Get the subject from the event's tags
|
||||
let subject = if let Some(tag) = val.tags.find(TagKind::Subject) {
|
||||
tag.content().map(|s| s.to_owned())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// Get the picture from the event's tags
|
||||
let picture = if let Some(tag) = val.tags.find(TagKind::custom("picture")) {
|
||||
tag.content().map(|s| s.to_owned())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// Get subject from tags
|
||||
let subject = val
|
||||
.tags
|
||||
.find(TagKind::Subject)
|
||||
.and_then(|tag| tag.content().map(|s| s.to_owned()));
|
||||
|
||||
Room {
|
||||
id,
|
||||
created_at,
|
||||
subject,
|
||||
picture,
|
||||
members,
|
||||
kind: RoomKind::default(),
|
||||
}
|
||||
@@ -201,32 +171,39 @@ impl From<&UnsignedEvent> for Room {
|
||||
}
|
||||
|
||||
impl Room {
|
||||
/// Constructs a new room instance with a given receiver.
|
||||
pub fn new(receiver: PublicKey, tags: Tags, cx: &App) -> Self {
|
||||
let identity = Registry::read_global(cx).identity(cx);
|
||||
/// Constructs a new room instance for a private message with the given receiver and tags.
|
||||
pub async fn new(subject: Option<String>, receivers: Vec<PublicKey>) -> Result<Self, Error> {
|
||||
let client = nostr_client();
|
||||
let signer = client.signer().await?;
|
||||
let public_key = signer.get_public_key().await?;
|
||||
|
||||
let mut event = EventBuilder::private_msg_rumor(receiver, "")
|
||||
if receivers.is_empty() {
|
||||
return Err(anyhow!("You need to add at least one receiver"));
|
||||
};
|
||||
|
||||
// Convert receiver's public keys into tags
|
||||
let mut tags: Tags = Tags::from_list(
|
||||
receivers
|
||||
.iter()
|
||||
.map(|pubkey| Tag::public_key(pubkey.to_owned()))
|
||||
.collect(),
|
||||
);
|
||||
|
||||
// Add subject if it is present
|
||||
if let Some(subject) = subject {
|
||||
tags.push(Tag::from_standardized_without_cell(TagStandard::Subject(
|
||||
subject,
|
||||
)));
|
||||
}
|
||||
|
||||
let mut event = EventBuilder::new(Kind::PrivateDirectMessage, "")
|
||||
.tags(tags)
|
||||
.build(identity.public_key());
|
||||
.build(public_key);
|
||||
|
||||
// Ensure event ID is generated
|
||||
// Generate event ID
|
||||
event.ensure_id();
|
||||
|
||||
Room::from(&event).current_user(identity.public_key())
|
||||
}
|
||||
|
||||
/// Constructs a new room instance from an nostr event.
|
||||
pub fn from(event: impl Into<Room>) -> Self {
|
||||
event.into()
|
||||
}
|
||||
|
||||
/// Call this function to ensure the current user is always at the bottom of the members list
|
||||
pub fn current_user(mut self, public_key: PublicKey) -> Self {
|
||||
let (not_match, matches): (Vec<PublicKey>, Vec<PublicKey>) =
|
||||
self.members.iter().partition(|&key| key != &public_key);
|
||||
self.members = not_match;
|
||||
self.members.extend(matches);
|
||||
self
|
||||
Ok(Room::from(&event))
|
||||
}
|
||||
|
||||
/// Sets the kind of the room and returns the modified room
|
||||
@@ -235,7 +212,7 @@ impl Room {
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the room kind to ongoing
|
||||
/// Sets this room is ongoing conversation
|
||||
pub fn set_ongoing(&mut self, cx: &mut Context<Self>) {
|
||||
if self.kind != RoomKind::Ongoing {
|
||||
self.kind = RoomKind::Ongoing;
|
||||
@@ -243,27 +220,26 @@ impl Room {
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks if the room is a group chat
|
||||
pub fn is_group(&self) -> bool {
|
||||
self.members.len() > 2
|
||||
}
|
||||
|
||||
/// Updates the creation timestamp of the room
|
||||
pub fn created_at(&mut self, created_at: impl Into<Timestamp>, cx: &mut Context<Self>) {
|
||||
pub fn set_created_at(&mut self, created_at: impl Into<Timestamp>, cx: &mut Context<Self>) {
|
||||
self.created_at = created_at.into();
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
/// Updates the subject of the room
|
||||
pub fn subject(&mut self, subject: String, cx: &mut Context<Self>) {
|
||||
pub fn set_subject(&mut self, subject: String, cx: &mut Context<Self>) {
|
||||
self.subject = Some(subject);
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
/// Updates the picture of the room
|
||||
pub fn picture(&mut self, picture: String, cx: &mut Context<Self>) {
|
||||
self.picture = Some(picture);
|
||||
cx.notify();
|
||||
/// Returns the members of the room
|
||||
pub fn members(&self) -> &Vec<PublicKey> {
|
||||
&self.members
|
||||
}
|
||||
|
||||
/// Checks if the room has more than two members (group)
|
||||
pub fn is_group(&self) -> bool {
|
||||
self.members.len() > 2
|
||||
}
|
||||
|
||||
/// Gets the display name for the room
|
||||
@@ -277,33 +253,40 @@ impl Room {
|
||||
|
||||
/// Gets the display image for the room
|
||||
pub fn display_image(&self, proxy: bool, cx: &App) -> SharedUri {
|
||||
if let Some(picture) = self.picture.as_ref() {
|
||||
SharedUri::from(picture)
|
||||
} else if !self.is_group() {
|
||||
self.first_member(cx).avatar(proxy)
|
||||
if !self.is_group() {
|
||||
self.display_member(cx).avatar(proxy)
|
||||
} else {
|
||||
SharedUri::from("brand/group.png")
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the first member of the room.
|
||||
/// Get a single member to represent the room
|
||||
///
|
||||
/// First member is always different from the current user.
|
||||
pub(crate) fn first_member(&self, cx: &App) -> Profile {
|
||||
/// This member is always different from the current user.
|
||||
fn display_member(&self, cx: &App) -> Profile {
|
||||
let registry = Registry::read_global(cx);
|
||||
|
||||
if let Some(public_key) = registry.signer_pubkey() {
|
||||
for member in self.members() {
|
||||
if member != &public_key {
|
||||
return registry.get_person(member, cx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
registry.get_person(&self.members[0], cx)
|
||||
}
|
||||
|
||||
/// Merge the names of the first two members of the room.
|
||||
pub(crate) fn merged_name(&self, cx: &App) -> SharedString {
|
||||
fn merged_name(&self, cx: &App) -> SharedString {
|
||||
let registry = Registry::read_global(cx);
|
||||
|
||||
if self.is_group() {
|
||||
let profiles = self
|
||||
let profiles: Vec<Profile> = self
|
||||
.members
|
||||
.iter()
|
||||
.map(|pk| registry.get_person(pk, cx))
|
||||
.collect::<Vec<_>>();
|
||||
.map(|public_key| registry.get_person(public_key, cx))
|
||||
.collect();
|
||||
|
||||
let mut name = profiles
|
||||
.iter()
|
||||
@@ -318,91 +301,168 @@ impl Room {
|
||||
|
||||
SharedString::from(name)
|
||||
} else {
|
||||
self.first_member(cx).display_name()
|
||||
self.display_member(cx).display_name()
|
||||
}
|
||||
}
|
||||
|
||||
/// Connects to all members' messaging relays
|
||||
pub fn connect_relays(
|
||||
&self,
|
||||
cx: &App,
|
||||
) -> Task<Result<HashMap<PublicKey, Vec<RelayUrl>>, Error>> {
|
||||
/// Connects to all members's messaging relays
|
||||
pub fn connect(&self, cx: &App) -> Task<Result<HashMap<PublicKey, Vec<RelayUrl>>, Error>> {
|
||||
let members = self.members.clone();
|
||||
|
||||
cx.background_spawn(async move {
|
||||
let client = nostr_client();
|
||||
let timeout = Duration::from_secs(3);
|
||||
let mut processed = HashSet::new();
|
||||
let mut relays: HashMap<PublicKey, Vec<RelayUrl>> = HashMap::new();
|
||||
let signer = client.signer().await?;
|
||||
let public_key = signer.get_public_key().await?;
|
||||
|
||||
if let Some((_, members)) = members.split_last() {
|
||||
for member in members.iter() {
|
||||
relays.insert(member.to_owned(), vec![]);
|
||||
let mut relays = HashMap::new();
|
||||
let mut processed = HashSet::new();
|
||||
|
||||
for member in members.into_iter() {
|
||||
if member == public_key {
|
||||
continue;
|
||||
};
|
||||
|
||||
relays.insert(member, vec![]);
|
||||
|
||||
let filter = Filter::new()
|
||||
.kind(Kind::InboxRelays)
|
||||
.author(member.to_owned())
|
||||
.author(member)
|
||||
.limit(1);
|
||||
|
||||
if let Ok(mut stream) = client.stream_events(filter, timeout).await {
|
||||
let mut stream = client
|
||||
.stream_events(filter, Duration::from_secs(10))
|
||||
.await?;
|
||||
|
||||
if let Some(event) = stream.next().await {
|
||||
if processed.insert(event.id) {
|
||||
let urls = nip17::extract_owned_relay_list(event).collect_vec();
|
||||
relays.entry(member.to_owned()).or_default().extend(urls);
|
||||
let public_key = event.pubkey;
|
||||
let urls: Vec<RelayUrl> = nip17::extract_owned_relay_list(event).collect();
|
||||
|
||||
// Check if at least one URL exists
|
||||
if urls.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Connect to relays
|
||||
for url in urls.iter() {
|
||||
client.add_relay(url).await?;
|
||||
client.connect_relay(url).await?;
|
||||
}
|
||||
|
||||
relays.entry(public_key).and_modify(|v| v.extend(urls));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Ok(relays)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn disconnect(&self, relays: Vec<RelayUrl>, cx: &App) -> Task<Result<(), Error>> {
|
||||
cx.background_spawn(async move {
|
||||
let client = nostr_client();
|
||||
|
||||
for relay in relays.into_iter() {
|
||||
client.disconnect_relay(relay).await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Loads all messages for this room from the database
|
||||
pub fn load_messages(&self, cx: &App) -> Task<Result<Vec<Event>, Error>> {
|
||||
let members = self.members.clone();
|
||||
|
||||
cx.background_spawn(async move {
|
||||
let client = nostr_client();
|
||||
let public_key = members[members.len() - 1];
|
||||
let signer = client.signer().await?;
|
||||
let public_key = signer.get_public_key().await?;
|
||||
let sent_ids = app_state()
|
||||
.sent_ids
|
||||
.read()
|
||||
.await
|
||||
.iter()
|
||||
.copied()
|
||||
.collect_vec();
|
||||
|
||||
let sent = Filter::new()
|
||||
// Get seen events from database
|
||||
let filter = Filter::new()
|
||||
.kind(Kind::ApplicationSpecificData)
|
||||
.identifiers(sent_ids);
|
||||
|
||||
let seen_events = client.database().query(filter).await?;
|
||||
|
||||
// Extract seen event IDs
|
||||
let seen_ids: Vec<EventId> = seen_events
|
||||
.into_iter()
|
||||
.filter_map(|event| event.tags.event_ids().next().copied())
|
||||
.collect();
|
||||
|
||||
// Get events that sent by current user
|
||||
let filter = Filter::new()
|
||||
.kind(Kind::PrivateDirectMessage)
|
||||
.author(public_key)
|
||||
.pubkeys(members.clone());
|
||||
|
||||
let recv = Filter::new()
|
||||
let sent_events = client.database().query(filter).await?;
|
||||
|
||||
// Get events that received by current user
|
||||
let filter = Filter::new()
|
||||
.kind(Kind::PrivateDirectMessage)
|
||||
.authors(members)
|
||||
.pubkey(public_key);
|
||||
|
||||
let sent_events = client.database().query(sent).await?;
|
||||
let recv_events = client.database().query(recv).await?;
|
||||
let events: Vec<Event> = sent_events.merge(recv_events).into_iter().collect();
|
||||
let recv_events = client.database().query(filter).await?;
|
||||
|
||||
// Merge events
|
||||
let events: Vec<Event> = sent_events
|
||||
.merge(recv_events)
|
||||
.into_iter()
|
||||
.filter(|event| !seen_ids.contains(&event.id))
|
||||
.collect();
|
||||
|
||||
Ok(events)
|
||||
})
|
||||
}
|
||||
|
||||
/// Creates a temporary message for optimistic updates
|
||||
///
|
||||
/// The event must not been published to relays.
|
||||
pub fn create_temp_message(
|
||||
&self,
|
||||
receiver: PublicKey,
|
||||
content: &str,
|
||||
replies: &[EventId],
|
||||
) -> UnsignedEvent {
|
||||
let builder = EventBuilder::private_msg_rumor(receiver, content);
|
||||
/// Emits a new message signal to the current room
|
||||
pub fn emit_message(&self, gift_wrap_id: EventId, event: Event, cx: &mut Context<Self>) {
|
||||
cx.emit(RoomSignal::NewMessage((gift_wrap_id, Box::new(event))));
|
||||
}
|
||||
|
||||
/// Emits a signal to refresh the current room's messages.
|
||||
pub fn emit_refresh(&mut self, cx: &mut Context<Self>) {
|
||||
cx.emit(RoomSignal::Refresh);
|
||||
}
|
||||
|
||||
/// Create a new message event (unsigned)
|
||||
pub fn create_message(&self, content: &str, replies: &[EventId], cx: &App) -> UnsignedEvent {
|
||||
let public_key = Registry::read_global(cx).signer_pubkey().unwrap();
|
||||
let subject = self.subject.clone();
|
||||
|
||||
let mut tags = vec![];
|
||||
|
||||
// Add event reference if it's present (replying to another event)
|
||||
// Add receivers
|
||||
//
|
||||
// NOTE: current user will be removed from the list of receivers
|
||||
for member in self.members.iter() {
|
||||
tags.push(Tag::public_key(member.to_owned()));
|
||||
}
|
||||
|
||||
// Add subject tag if it's present
|
||||
if let Some(subject) = subject {
|
||||
tags.push(Tag::from_standardized_without_cell(TagStandard::Subject(
|
||||
subject,
|
||||
)));
|
||||
}
|
||||
|
||||
// Add reply/quote tag
|
||||
if replies.len() == 1 {
|
||||
tags.push(Tag::event(replies[0]))
|
||||
} else {
|
||||
for id in replies.iter() {
|
||||
tags.push(Tag::from_standardized(TagStandard::Quote {
|
||||
for id in replies {
|
||||
tags.push(Tag::from_standardized_without_cell(TagStandard::Quote {
|
||||
event_id: id.to_owned(),
|
||||
relay_url: None,
|
||||
public_key: None,
|
||||
@@ -410,26 +470,27 @@ impl Room {
|
||||
}
|
||||
}
|
||||
|
||||
let mut event = builder.tags(tags).build(receiver);
|
||||
// Construct a direct message event
|
||||
//
|
||||
// WARNING: never send this event to relays
|
||||
let mut event = EventBuilder::new(Kind::PrivateDirectMessage, content)
|
||||
.tags(tags)
|
||||
.build(public_key);
|
||||
|
||||
// Ensure event ID is set
|
||||
// Generate event ID
|
||||
event.ensure_id();
|
||||
|
||||
event
|
||||
}
|
||||
|
||||
/// Create a task to sends a message to all members in the background
|
||||
pub fn send_in_background(
|
||||
/// Create a task to send a message to all room members
|
||||
pub fn send_message(
|
||||
&self,
|
||||
content: &str,
|
||||
replies: Vec<EventId>,
|
||||
rumor: UnsignedEvent,
|
||||
backup: bool,
|
||||
cx: &App,
|
||||
) -> Task<Result<Vec<SendReport>, Error>> {
|
||||
let content = content.to_owned();
|
||||
let subject = self.subject.clone();
|
||||
let picture = self.picture.clone();
|
||||
let mut public_keys = self.members.clone();
|
||||
let mut members = self.members.clone();
|
||||
|
||||
cx.background_spawn(async move {
|
||||
let app_state = app_state();
|
||||
@@ -437,57 +498,26 @@ impl Room {
|
||||
let signer = client.signer().await?;
|
||||
let public_key = signer.get_public_key().await?;
|
||||
|
||||
let mut tags: Vec<Tag> = public_keys
|
||||
.iter()
|
||||
.filter_map(|&this| {
|
||||
if this != public_key {
|
||||
Some(Tag::public_key(this))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
// Remove the current user's public key from the list of receivers
|
||||
// Current user will be handled separately
|
||||
members.retain(|&pk| pk != public_key);
|
||||
|
||||
// Add event reference if it's present (replying to another event)
|
||||
if replies.len() == 1 {
|
||||
tags.push(Tag::event(replies[0]))
|
||||
} else {
|
||||
for id in replies.iter() {
|
||||
tags.push(Tag::from_standardized(TagStandard::Quote {
|
||||
event_id: id.to_owned(),
|
||||
relay_url: None,
|
||||
public_key: None,
|
||||
}))
|
||||
}
|
||||
}
|
||||
let mut reports: Vec<SendReport> = vec![];
|
||||
|
||||
// Add subject tag if it's present
|
||||
if let Some(subject) = subject {
|
||||
tags.push(Tag::from_standardized(TagStandard::Subject(
|
||||
subject.to_string(),
|
||||
)));
|
||||
}
|
||||
for receiver in members.into_iter() {
|
||||
let rumor = rumor.clone();
|
||||
let event = EventBuilder::gift_wrap(&signer, &receiver, rumor, vec![]).await?;
|
||||
|
||||
// Add picture tag if it's present
|
||||
if let Some(picture) = picture {
|
||||
tags.push(Tag::custom(TagKind::custom("picture"), vec![picture]));
|
||||
}
|
||||
let Ok(relay_urls) = Self::messaging_relays(receiver).await else {
|
||||
reports.push(SendReport::new(receiver).not_found());
|
||||
continue;
|
||||
};
|
||||
|
||||
// Remove the current public key from the list of receivers
|
||||
public_keys.retain(|&pk| pk != public_key);
|
||||
|
||||
// Stored all send errors
|
||||
let mut reports = vec![];
|
||||
|
||||
for pubkey in public_keys.into_iter() {
|
||||
match client
|
||||
.send_private_msg(pubkey, &content, tags.clone())
|
||||
.await
|
||||
{
|
||||
match client.send_event_to(relay_urls, &event).await {
|
||||
Ok(output) => {
|
||||
let id = output.id().to_owned();
|
||||
let auth_required = output.failed.iter().any(|m| m.1.starts_with("auth-"));
|
||||
let report = SendReport::new(pubkey).status(output).tags(&tags);
|
||||
let report = SendReport::new(receiver).status(output);
|
||||
|
||||
if auth_required {
|
||||
// Wait for authenticated and resent event successfully
|
||||
@@ -496,7 +526,7 @@ impl Room {
|
||||
|
||||
// Check if event was successfully resent
|
||||
if let Some(output) = ids.iter().find(|e| e.id() == &id).cloned() {
|
||||
let output = SendReport::new(pubkey).status(output).tags(&tags);
|
||||
let output = SendReport::new(receiver).status(output);
|
||||
reports.push(output);
|
||||
break;
|
||||
}
|
||||
@@ -514,33 +544,31 @@ impl Room {
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
if let nostr_sdk::client::Error::PrivateMsgRelaysNotFound = e {
|
||||
reports.push(SendReport::new(pubkey).not_found().tags(&tags));
|
||||
} else {
|
||||
reports.push(SendReport::new(pubkey).error(e.to_string()).tags(&tags));
|
||||
}
|
||||
reports.push(SendReport::new(receiver).error(e.to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Construct a gift wrap to back up to current user's owned messaging relays
|
||||
let rumor = rumor.clone();
|
||||
let event = EventBuilder::gift_wrap(&signer, &public_key, rumor, vec![]).await?;
|
||||
|
||||
// Only send a backup message to current user if sent successfully to others
|
||||
if reports.iter().all(|r| r.is_sent_success()) && backup {
|
||||
match client
|
||||
.send_private_msg(public_key, &content, tags.clone())
|
||||
.await
|
||||
{
|
||||
if let Ok(relay_urls) = Self::messaging_relays(public_key).await {
|
||||
match client.send_event_to(relay_urls, &event).await {
|
||||
Ok(output) => {
|
||||
reports.push(SendReport::new(public_key).status(output).tags(&tags));
|
||||
reports.push(SendReport::new(public_key).status(output));
|
||||
}
|
||||
Err(e) => {
|
||||
if let nostr_sdk::client::Error::PrivateMsgRelaysNotFound = e {
|
||||
reports.push(SendReport::new(public_key).not_found());
|
||||
reports.push(SendReport::new(public_key).error(e.to_string()));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
reports
|
||||
.push(SendReport::new(public_key).error(e.to_string()).tags(&tags));
|
||||
}
|
||||
}
|
||||
reports.push(SendReport::new(public_key).not_found());
|
||||
}
|
||||
} else {
|
||||
reports.push(SendReport::new(public_key).on_hold(event));
|
||||
}
|
||||
|
||||
Ok(reports)
|
||||
@@ -548,19 +576,19 @@ impl Room {
|
||||
}
|
||||
|
||||
/// Create a task to resend a failed message
|
||||
pub fn resend(
|
||||
pub fn resend_message(
|
||||
&self,
|
||||
reports: Vec<SendReport>,
|
||||
message: String,
|
||||
backup: bool,
|
||||
cx: &App,
|
||||
) -> Task<Result<Vec<SendReport>, Error>> {
|
||||
cx.background_spawn(async move {
|
||||
let client = nostr_client();
|
||||
let mut resend_reports = vec![];
|
||||
let mut resend_tag = vec![];
|
||||
|
||||
for report in reports.into_iter() {
|
||||
let receiver = report.receiver;
|
||||
|
||||
// Process failed events
|
||||
if let Some(output) = report.status {
|
||||
let id = output.id();
|
||||
let urls: Vec<&RelayUrl> = output.failed.keys().collect();
|
||||
@@ -569,44 +597,68 @@ impl Room {
|
||||
for url in urls.into_iter() {
|
||||
let relay = client.pool().relay(url).await?;
|
||||
let id = relay.send_event(&event).await?;
|
||||
|
||||
let resent: Output<EventId> = Output {
|
||||
val: id,
|
||||
success: HashSet::from([url.to_owned()]),
|
||||
failed: HashMap::new(),
|
||||
};
|
||||
|
||||
resend_reports.push(SendReport::new(report.receiver).status(resent));
|
||||
}
|
||||
|
||||
if let Some(tags) = report.tags {
|
||||
resend_tag.extend(tags);
|
||||
}
|
||||
resend_reports.push(SendReport::new(receiver).status(resent));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Only send a backup message to current user if sent successfully to others
|
||||
if backup && !resend_reports.is_empty() {
|
||||
let signer = client.signer().await?;
|
||||
let public_key = signer.get_public_key().await?;
|
||||
let output = client
|
||||
.send_private_msg(public_key, message, resend_tag)
|
||||
.await?;
|
||||
|
||||
resend_reports.push(SendReport::new(public_key).status(output));
|
||||
// Process the on hold event if it exists
|
||||
if let Some(event) = report.on_hold {
|
||||
if let Ok(relay_urls) = Self::messaging_relays(receiver).await {
|
||||
match client.send_event_to(relay_urls, &event).await {
|
||||
Ok(output) => {
|
||||
resend_reports.push(SendReport::new(receiver).status(output));
|
||||
}
|
||||
Err(e) => {
|
||||
resend_reports.push(SendReport::new(receiver).error(e.to_string()));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
resend_reports.push(SendReport::new(receiver).not_found());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(resend_reports)
|
||||
})
|
||||
}
|
||||
|
||||
/// Emits a new message signal to the current room
|
||||
pub fn emit_message(&self, gift_wrap_id: EventId, event: Event, cx: &mut Context<Self>) {
|
||||
cx.emit(RoomSignal::NewMessage((gift_wrap_id, Box::new(event))));
|
||||
/// Gets messaging relays for public key
|
||||
async fn messaging_relays(public_key: PublicKey) -> Result<Vec<RelayUrl>, Error> {
|
||||
let client = nostr_client();
|
||||
let mut relay_urls = vec![];
|
||||
|
||||
let filter = Filter::new()
|
||||
.kind(Kind::InboxRelays)
|
||||
.author(public_key)
|
||||
.limit(1);
|
||||
|
||||
if let Some(event) = client.database().query(filter).await?.first_owned() {
|
||||
let urls: Vec<RelayUrl> = nip17::extract_owned_relay_list(event).collect();
|
||||
|
||||
// Check if at least one URL exists
|
||||
if urls.is_empty() {
|
||||
return Err(anyhow!("Not found"));
|
||||
}
|
||||
|
||||
/// Emits a signal to refresh the current room's messages.
|
||||
pub fn emit_refresh(&mut self, cx: &mut Context<Self>) {
|
||||
cx.emit(RoomSignal::Refresh);
|
||||
// Connect to relays
|
||||
for url in urls.iter() {
|
||||
client.add_relay(url).await?;
|
||||
client.connect_relay(url).await?;
|
||||
}
|
||||
|
||||
relay_urls.extend(urls.into_iter().take(3).unique());
|
||||
} else {
|
||||
return Err(anyhow!("Not found"));
|
||||
}
|
||||
|
||||
Ok(relay_urls)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,3 +28,6 @@ uuid = "1.10"
|
||||
once_cell = "1.19.0"
|
||||
image = "0.25.1"
|
||||
linkify = "0.10.0"
|
||||
lsp-types = "0.97.0"
|
||||
rope = { git = "https://github.com/zed-industries/zed.git" }
|
||||
sum_tree = { git = "https://github.com/zed-industries/zed.git" }
|
||||
|
||||
@@ -2,10 +2,15 @@ use gpui::{actions, Action};
|
||||
use nostr_sdk::prelude::PublicKey;
|
||||
use serde::Deserialize;
|
||||
|
||||
/// Define a open profile action
|
||||
/// Define a open public key action
|
||||
#[derive(Action, Clone, PartialEq, Eq, Deserialize, Debug)]
|
||||
#[action(namespace = profile, no_json)]
|
||||
pub struct OpenProfile(pub PublicKey);
|
||||
#[action(namespace = pubkey, no_json)]
|
||||
pub struct OpenPublicKey(pub PublicKey);
|
||||
|
||||
/// Define a copy inline public key action
|
||||
#[derive(Action, Clone, PartialEq, Eq, Deserialize, Debug)]
|
||||
#[action(namespace = pubkey, no_json)]
|
||||
pub struct CopyPublicKey(pub PublicKey);
|
||||
|
||||
/// Define a custom confirm action
|
||||
#[derive(Clone, Action, PartialEq, Eq, Deserialize)]
|
||||
|
||||
@@ -22,10 +22,10 @@ pub struct History<I: HistoryItem> {
|
||||
redos: Vec<I>,
|
||||
last_changed_at: Instant,
|
||||
version: usize,
|
||||
pub(crate) ignore: bool,
|
||||
max_undo: usize,
|
||||
group_interval: Option<Duration>,
|
||||
unique: bool,
|
||||
pub ignore: bool,
|
||||
}
|
||||
|
||||
impl<I> History<I>
|
||||
|
||||
@@ -45,6 +45,7 @@ pub enum IconName {
|
||||
Plus,
|
||||
PlusFill,
|
||||
PlusCircleFill,
|
||||
Group,
|
||||
ResizeCorner,
|
||||
Reply,
|
||||
Report,
|
||||
@@ -106,6 +107,7 @@ impl IconName {
|
||||
Self::Plus => "icons/plus.svg",
|
||||
Self::PlusFill => "icons/plus-fill.svg",
|
||||
Self::PlusCircleFill => "icons/plus-circle-fill.svg",
|
||||
Self::Group => "icons/group.svg",
|
||||
Self::ResizeCorner => "icons/resize-corner.svg",
|
||||
Self::Reply => "icons/reply.svg",
|
||||
Self::Report => "icons/report.svg",
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use gpui::{Context, Timer};
|
||||
use gpui::{px, Context, Pixels, Timer};
|
||||
|
||||
static INTERVAL: Duration = Duration::from_millis(500);
|
||||
static PAUSE_DELAY: Duration = Duration::from_millis(300);
|
||||
pub(super) const CURSOR_WIDTH: Pixels = px(1.5);
|
||||
|
||||
/// To manage the Input cursor blinking.
|
||||
///
|
||||
@@ -11,7 +12,7 @@ static PAUSE_DELAY: Duration = Duration::from_millis(300);
|
||||
/// Every loop will notify the view to update the `visible`, and Input will observe this update to touch repaint.
|
||||
///
|
||||
/// The input painter will check if this in visible state, then it will draw the cursor.
|
||||
pub(crate) struct BlinkCursor {
|
||||
pub struct BlinkCursor {
|
||||
visible: bool,
|
||||
paused: bool,
|
||||
epoch: usize,
|
||||
@@ -52,10 +53,8 @@ impl BlinkCursor {
|
||||
|
||||
// Schedule the next blink
|
||||
let epoch = self.next_epoch();
|
||||
|
||||
cx.spawn(async move |this, cx| {
|
||||
Timer::after(INTERVAL).await;
|
||||
|
||||
if let Some(this) = this.upgrade() {
|
||||
this.update(cx, |this, cx| this.blink(epoch, cx)).ok();
|
||||
}
|
||||
@@ -71,11 +70,11 @@ impl BlinkCursor {
|
||||
/// Pause the blinking, and delay 500ms to resume the blinking.
|
||||
pub fn pause(&mut self, cx: &mut Context<Self>) {
|
||||
self.paused = true;
|
||||
self.visible = true;
|
||||
cx.notify();
|
||||
|
||||
// delay 500ms to start the blinking
|
||||
let epoch = self.next_epoch();
|
||||
|
||||
cx.spawn(async move |this, cx| {
|
||||
Timer::after(PAUSE_DELAY).await;
|
||||
|
||||
@@ -90,3 +89,9 @@ impl BlinkCursor {
|
||||
.detach();
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for BlinkCursor {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,28 +1,28 @@
|
||||
use std::fmt::Debug;
|
||||
use std::ops::Range;
|
||||
|
||||
use crate::history::HistoryItem;
|
||||
use crate::input::cursor::Selection;
|
||||
|
||||
#[derive(Debug, PartialEq, Clone)]
|
||||
pub struct Change {
|
||||
pub(crate) old_range: Range<usize>,
|
||||
pub(crate) old_range: Selection,
|
||||
pub(crate) old_text: String,
|
||||
pub(crate) new_range: Range<usize>,
|
||||
pub(crate) new_range: Selection,
|
||||
pub(crate) new_text: String,
|
||||
version: usize,
|
||||
}
|
||||
|
||||
impl Change {
|
||||
pub fn new(
|
||||
old_range: Range<usize>,
|
||||
old_range: impl Into<Selection>,
|
||||
old_text: &str,
|
||||
new_range: Range<usize>,
|
||||
new_range: impl Into<Selection>,
|
||||
new_text: &str,
|
||||
) -> Self {
|
||||
Self {
|
||||
old_range,
|
||||
old_range: old_range.into(),
|
||||
old_text: old_text.to_string(),
|
||||
new_range,
|
||||
new_range: new_range.into(),
|
||||
new_text: new_text.to_string(),
|
||||
version: 0,
|
||||
}
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
use gpui::{App, Styled};
|
||||
use i18n::t;
|
||||
use theme::ActiveTheme;
|
||||
|
||||
use crate::button::{Button, ButtonVariants as _};
|
||||
use crate::{Icon, IconName, Sizable as _};
|
||||
use crate::button::{Button, ButtonVariants};
|
||||
use crate::{Icon, IconName, Sizable};
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn clear_button(cx: &App) -> Button {
|
||||
Button::new("clean")
|
||||
.icon(Icon::new(IconName::CloseCircle))
|
||||
.tooltip(t!("common.clear"))
|
||||
.tooltip("Clear")
|
||||
.small()
|
||||
.text_color(cx.theme().text_muted)
|
||||
.transparent()
|
||||
.text_color(cx.theme().text_muted)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
use std::ops::Range;
|
||||
|
||||
/// A selection in the text, represented by start and end byte indices.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
|
||||
pub struct Selection {
|
||||
pub start: usize,
|
||||
pub end: usize,
|
||||
}
|
||||
|
||||
impl Selection {
|
||||
pub fn new(start: usize, end: usize) -> Self {
|
||||
Self { start, end }
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.end.saturating_sub(self.start)
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.start == self.end
|
||||
}
|
||||
|
||||
/// Clears the selection, setting start and end to 0.
|
||||
pub fn clear(&mut self) {
|
||||
self.start = 0;
|
||||
self.end = 0;
|
||||
}
|
||||
|
||||
/// Checks if the given offset is within the selection range.
|
||||
pub fn contains(&self, offset: usize) -> bool {
|
||||
offset >= self.start && offset < self.end
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Range<usize>> for Selection {
|
||||
fn from(value: Range<usize>) -> Self {
|
||||
Self::new(value.start, value.end)
|
||||
}
|
||||
}
|
||||
impl From<Selection> for Range<usize> {
|
||||
fn from(value: Selection) -> Self {
|
||||
value.start..value.end
|
||||
}
|
||||
}
|
||||
|
||||
pub type Position = lsp_types::Position;
|
||||
+354
-207
@@ -1,29 +1,34 @@
|
||||
use std::{ops::Range, rc::Rc};
|
||||
use std::ops::Range;
|
||||
use std::rc::Rc;
|
||||
|
||||
use gpui::{
|
||||
fill, point, px, relative, size, App, Bounds, Corners, Element, ElementId, ElementInputHandler,
|
||||
Entity, GlobalElementId, IntoElement, LayoutId, MouseButton, MouseMoveEvent, Path, Pixels,
|
||||
Point, SharedString, Size, Style, TextAlign, TextRun, UnderlineStyle, Window, WrappedLine,
|
||||
Entity, GlobalElementId, Half, Hitbox, IntoElement, LayoutId, MouseButton, MouseMoveEvent,
|
||||
Path, Pixels, Point, ShapedLine, SharedString, Size, Style, TextAlign, TextRun, UnderlineStyle,
|
||||
Window,
|
||||
};
|
||||
use rope::Rope;
|
||||
use smallvec::SmallVec;
|
||||
use theme::ActiveTheme;
|
||||
|
||||
use super::{InputState, LastLayout};
|
||||
use super::blink_cursor::CURSOR_WIDTH;
|
||||
use super::rope_ext::RopeExt;
|
||||
use super::state::{InputState, LastLayout};
|
||||
use crate::Root;
|
||||
|
||||
const CURSOR_THICKNESS: Pixels = px(2.);
|
||||
const RIGHT_MARGIN: Pixels = px(5.);
|
||||
const BOTTOM_MARGIN_ROWS: usize = 1;
|
||||
const BOTTOM_MARGIN_ROWS: usize = 3;
|
||||
pub(super) const RIGHT_MARGIN: Pixels = px(10.);
|
||||
pub(super) const LINE_NUMBER_RIGHT_MARGIN: Pixels = px(10.);
|
||||
|
||||
pub(super) struct TextElement {
|
||||
input: Entity<InputState>,
|
||||
pub(crate) state: Entity<InputState>,
|
||||
placeholder: SharedString,
|
||||
}
|
||||
|
||||
impl TextElement {
|
||||
pub(super) fn new(input: Entity<InputState>) -> Self {
|
||||
pub(super) fn new(state: Entity<InputState>) -> Self {
|
||||
Self {
|
||||
input,
|
||||
state,
|
||||
placeholder: SharedString::default(),
|
||||
}
|
||||
}
|
||||
@@ -36,12 +41,12 @@ impl TextElement {
|
||||
|
||||
fn paint_mouse_listeners(&mut self, window: &mut Window, _: &mut App) {
|
||||
window.on_mouse_event({
|
||||
let input = self.input.clone();
|
||||
let state = self.state.clone();
|
||||
|
||||
move |event: &MouseMoveEvent, _, window, cx| {
|
||||
if event.pressed_button == Some(MouseButton::Left) {
|
||||
input.update(cx, |input, cx| {
|
||||
input.on_drag_move(event, window, cx);
|
||||
state.update(cx, |state, cx| {
|
||||
state.on_drag_move(event, window, cx);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -52,33 +57,44 @@ impl TextElement {
|
||||
///
|
||||
/// - cursor bounds
|
||||
/// - scroll offset
|
||||
/// - current line index
|
||||
/// - current row index (No only the visible lines, but all lines)
|
||||
///
|
||||
/// This method also will update for track scroll to cursor.
|
||||
fn layout_cursor(
|
||||
&self,
|
||||
lines: &[WrappedLine],
|
||||
line_height: Pixels,
|
||||
last_layout: &LastLayout,
|
||||
bounds: &mut Bounds<Pixels>,
|
||||
line_number_width: Pixels,
|
||||
window: &mut Window,
|
||||
_: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> (Option<Bounds<Pixels>>, Point<Pixels>, Option<usize>) {
|
||||
let input = self.input.read(cx);
|
||||
let mut selected_range = input.selected_range.clone();
|
||||
if let Some(marked_range) = &input.marked_range {
|
||||
selected_range = marked_range.end..marked_range.end;
|
||||
let state = self.state.read(cx);
|
||||
|
||||
let line_height = last_layout.line_height;
|
||||
let visible_range = &last_layout.visible_range;
|
||||
let lines = &last_layout.lines;
|
||||
let text_wrapper = &state.text_wrapper;
|
||||
let line_number_width = last_layout.line_number_width;
|
||||
|
||||
let mut selected_range = state.selected_range;
|
||||
if let Some(ime_marked_range) = &state.ime_marked_range {
|
||||
selected_range = (ime_marked_range.end..ime_marked_range.end).into();
|
||||
}
|
||||
|
||||
let cursor_offset = input.cursor_offset();
|
||||
let mut current_line_index = None;
|
||||
let mut scroll_offset = input.scroll_handle.offset();
|
||||
let cursor = state.cursor();
|
||||
let mut current_row = None;
|
||||
let mut scroll_offset = state.scroll_handle.offset();
|
||||
let mut cursor_bounds = None;
|
||||
|
||||
// If the input has a fixed height (Otherwise is auto-grow), we need to add a bottom margin to the input.
|
||||
let bottom_margin = if input.is_auto_grow() {
|
||||
px(0.) + line_height
|
||||
let top_bottom_margin = if state.mode.is_auto_grow() {
|
||||
#[allow(clippy::if_same_then_else)]
|
||||
line_height
|
||||
} else if visible_range.len() < BOTTOM_MARGIN_ROWS * 8 {
|
||||
line_height
|
||||
} else {
|
||||
BOTTOM_MARGIN_ROWS * line_height + line_height
|
||||
BOTTOM_MARGIN_ROWS * line_height
|
||||
};
|
||||
|
||||
// The cursor corresponds to the current cursor position in the text no only the line.
|
||||
let mut cursor_pos = None;
|
||||
let mut cursor_start = None;
|
||||
@@ -86,17 +102,26 @@ impl TextElement {
|
||||
|
||||
let mut prev_lines_offset = 0;
|
||||
let mut offset_y = px(0.);
|
||||
for (line_ix, line) in lines.iter().enumerate() {
|
||||
|
||||
for (ix, wrap_line) in text_wrapper.lines.iter().enumerate() {
|
||||
let row = ix;
|
||||
let line_origin = point(px(0.), offset_y);
|
||||
|
||||
// break loop if all cursor positions are found
|
||||
if cursor_pos.is_some() && cursor_start.is_some() && cursor_end.is_some() {
|
||||
break;
|
||||
}
|
||||
|
||||
let line_origin = point(px(0.), offset_y);
|
||||
let in_visible_range = ix >= visible_range.start;
|
||||
if let Some(line) = in_visible_range
|
||||
.then(|| lines.get(ix.saturating_sub(visible_range.start)))
|
||||
.flatten()
|
||||
{
|
||||
// If in visible range lines
|
||||
if cursor_pos.is_none() {
|
||||
let offset = cursor_offset.saturating_sub(prev_lines_offset);
|
||||
let offset = cursor.saturating_sub(prev_lines_offset);
|
||||
if let Some(pos) = line.position_for_index(offset, line_height) {
|
||||
current_line_index = Some(line_ix);
|
||||
current_row = Some(row);
|
||||
cursor_pos = Some(line_origin + pos);
|
||||
}
|
||||
}
|
||||
@@ -114,40 +139,61 @@ impl TextElement {
|
||||
}
|
||||
|
||||
offset_y += line.size(line_height).height;
|
||||
// +1 for skip the last `\n`
|
||||
// +1 for the last `\n`
|
||||
prev_lines_offset += line.len() + 1;
|
||||
} else {
|
||||
// If not in the visible range.
|
||||
|
||||
// Just increase the offset_y and prev_lines_offset.
|
||||
// This will let the scroll_offset to track the cursor position correctly.
|
||||
if prev_lines_offset >= cursor && cursor_pos.is_none() {
|
||||
current_row = Some(row);
|
||||
cursor_pos = Some(line_origin);
|
||||
}
|
||||
if prev_lines_offset >= selected_range.start && cursor_start.is_none() {
|
||||
cursor_start = Some(line_origin);
|
||||
}
|
||||
if prev_lines_offset >= selected_range.end && cursor_end.is_none() {
|
||||
cursor_end = Some(line_origin);
|
||||
}
|
||||
|
||||
offset_y += wrap_line.height(line_height);
|
||||
// +1 for the last `\n`
|
||||
prev_lines_offset += wrap_line.len() + 1;
|
||||
}
|
||||
}
|
||||
|
||||
if let (Some(cursor_pos), Some(cursor_start), Some(cursor_end)) =
|
||||
(cursor_pos, cursor_start, cursor_end)
|
||||
{
|
||||
let cursor_moved = input.last_cursor_offset != Some(cursor_offset);
|
||||
let selection_changed = input.last_selected_range != Some(selected_range.clone());
|
||||
|
||||
if cursor_moved || selection_changed {
|
||||
scroll_offset.x =
|
||||
if scroll_offset.x + cursor_pos.x > (bounds.size.width - RIGHT_MARGIN) {
|
||||
let selection_changed = state.last_selected_range != Some(selected_range);
|
||||
if selection_changed {
|
||||
scroll_offset.x = if scroll_offset.x + cursor_pos.x
|
||||
> (bounds.size.width - line_number_width - RIGHT_MARGIN)
|
||||
{
|
||||
// cursor is out of right
|
||||
bounds.size.width - RIGHT_MARGIN - cursor_pos.x
|
||||
bounds.size.width - line_number_width - RIGHT_MARGIN - cursor_pos.x
|
||||
} else if scroll_offset.x + cursor_pos.x < px(0.) {
|
||||
// cursor is out of left
|
||||
scroll_offset.x - cursor_pos.x
|
||||
} else {
|
||||
scroll_offset.x
|
||||
};
|
||||
scroll_offset.y = if scroll_offset.y + cursor_pos.y + line_height
|
||||
> bounds.size.height - bottom_margin
|
||||
{
|
||||
|
||||
// If we change the scroll_offset.y, GPUI will render and trigger the next run loop.
|
||||
// So, here we just adjust offset by `line_height` for move smooth.
|
||||
scroll_offset.y =
|
||||
if scroll_offset.y + cursor_pos.y > bounds.size.height - top_bottom_margin {
|
||||
// cursor is out of bottom
|
||||
bounds.size.height - bottom_margin - cursor_pos.y
|
||||
} else if scroll_offset.y + cursor_pos.y < px(0.) {
|
||||
scroll_offset.y - line_height
|
||||
} else if scroll_offset.y + cursor_pos.y < top_bottom_margin {
|
||||
// cursor is out of top
|
||||
scroll_offset.y - cursor_pos.y
|
||||
(scroll_offset.y + line_height).min(px(0.))
|
||||
} else {
|
||||
scroll_offset.y
|
||||
};
|
||||
|
||||
if input.selection_reversed {
|
||||
if state.selection_reversed {
|
||||
if scroll_offset.x + cursor_start.x < px(0.) {
|
||||
// selection start is out of left
|
||||
scroll_offset.x = -cursor_start.x;
|
||||
@@ -168,54 +214,55 @@ impl TextElement {
|
||||
}
|
||||
}
|
||||
|
||||
if input.show_cursor(window, cx) {
|
||||
// cursor blink
|
||||
// cursor bounds
|
||||
let cursor_height = line_height;
|
||||
cursor_bounds = Some(Bounds::new(
|
||||
point(
|
||||
bounds.left() + cursor_pos.x + line_number_width + scroll_offset.x,
|
||||
bounds.top() + cursor_pos.y + ((line_height - cursor_height) / 2.),
|
||||
),
|
||||
size(CURSOR_THICKNESS, cursor_height),
|
||||
size(CURSOR_WIDTH, cursor_height),
|
||||
));
|
||||
};
|
||||
}
|
||||
|
||||
if let Some(deferred_scroll_offset) = state.deferred_scroll_offset {
|
||||
scroll_offset = deferred_scroll_offset;
|
||||
}
|
||||
|
||||
bounds.origin += scroll_offset;
|
||||
|
||||
(cursor_bounds, scroll_offset, current_line_index)
|
||||
(cursor_bounds, scroll_offset, current_row)
|
||||
}
|
||||
|
||||
fn layout_selections(
|
||||
&self,
|
||||
lines: &[WrappedLine],
|
||||
line_height: Pixels,
|
||||
/// Layout the match range to a Path.
|
||||
pub(crate) fn layout_match_range(
|
||||
range: Range<usize>,
|
||||
last_layout: &LastLayout,
|
||||
bounds: &mut Bounds<Pixels>,
|
||||
line_number_width: Pixels,
|
||||
_: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Option<Path<Pixels>> {
|
||||
let input = self.input.read(cx);
|
||||
let mut selected_range = input.selected_range.clone();
|
||||
if let Some(marked_range) = &input.marked_range {
|
||||
if !marked_range.is_empty() {
|
||||
selected_range = marked_range.end..marked_range.end;
|
||||
}
|
||||
}
|
||||
if selected_range.is_empty() {
|
||||
if range.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let (start_ix, end_ix) = if selected_range.start < selected_range.end {
|
||||
(selected_range.start, selected_range.end)
|
||||
} else {
|
||||
(selected_range.end, selected_range.start)
|
||||
};
|
||||
if range.start < last_layout.visible_range_offset.start
|
||||
|| range.end > last_layout.visible_range_offset.end
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut prev_lines_offset = 0;
|
||||
let line_height = last_layout.line_height;
|
||||
let visible_top = last_layout.visible_top;
|
||||
let visible_start_offset = last_layout.visible_range_offset.start;
|
||||
let lines = &last_layout.lines;
|
||||
let line_number_width = last_layout.line_number_width;
|
||||
|
||||
let start_ix = range.start;
|
||||
let end_ix = range.end;
|
||||
|
||||
let mut prev_lines_offset = visible_start_offset;
|
||||
let mut offset_y = visible_top;
|
||||
let mut line_corners = vec![];
|
||||
|
||||
let mut offset_y = px(0.);
|
||||
for line in lines.iter() {
|
||||
let line_size = line.size(line_height);
|
||||
let line_wrap_width = line_size.width;
|
||||
@@ -239,7 +286,6 @@ impl TextElement {
|
||||
(end.y / line_height).ceil() as usize - (start.y / line_height).ceil() as usize;
|
||||
|
||||
let mut end_x = end.x;
|
||||
|
||||
if wrapped_lines > 0 {
|
||||
end_x = line_wrap_width;
|
||||
}
|
||||
@@ -322,39 +368,79 @@ impl TextElement {
|
||||
builder.build().ok()
|
||||
}
|
||||
|
||||
fn layout_selections(
|
||||
&self,
|
||||
last_layout: &LastLayout,
|
||||
bounds: &mut Bounds<Pixels>,
|
||||
cx: &mut App,
|
||||
) -> Option<Path<Pixels>> {
|
||||
let state = self.state.read(cx);
|
||||
let mut selected_range = state.selected_range;
|
||||
if let Some(ime_marked_range) = &state.ime_marked_range {
|
||||
if !ime_marked_range.is_empty() {
|
||||
selected_range = (ime_marked_range.end..ime_marked_range.end).into();
|
||||
}
|
||||
}
|
||||
if selected_range.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let (start_ix, end_ix) = if selected_range.start < selected_range.end {
|
||||
(selected_range.start, selected_range.end)
|
||||
} else {
|
||||
(selected_range.end, selected_range.start)
|
||||
};
|
||||
|
||||
let range = start_ix.max(last_layout.visible_range_offset.start)
|
||||
..end_ix.min(last_layout.visible_range_offset.end);
|
||||
|
||||
Self::layout_match_range(range, last_layout, bounds)
|
||||
}
|
||||
|
||||
/// Calculate the visible range of lines in the viewport.
|
||||
///
|
||||
/// The visible range is based on unwrapped lines (Zero based).
|
||||
/// Returns
|
||||
///
|
||||
/// - visible_range: The visible range is based on unwrapped lines (Zero based).
|
||||
/// - visible_top: The top position of the first visible line in the scroll viewport.
|
||||
fn calculate_visible_range(
|
||||
&self,
|
||||
state: &InputState,
|
||||
line_height: Pixels,
|
||||
input_height: Pixels,
|
||||
) -> Range<usize> {
|
||||
if state.is_single_line() {
|
||||
return 0..1;
|
||||
) -> (Range<usize>, Pixels) {
|
||||
// Add extra rows to avoid showing empty space when scroll to bottom.
|
||||
let extra_rows = 1;
|
||||
let mut visible_top = px(0.);
|
||||
if state.mode.is_single_line() {
|
||||
return (0..1, visible_top);
|
||||
}
|
||||
|
||||
let scroll_top = -state.scroll_handle.offset().y;
|
||||
let total_lines = state.text_wrapper.lines.len();
|
||||
let total_lines = state.text_wrapper.len();
|
||||
let scroll_top = if let Some(deferred_scroll_offset) = state.deferred_scroll_offset {
|
||||
deferred_scroll_offset.y
|
||||
} else {
|
||||
state.scroll_handle.offset().y
|
||||
};
|
||||
|
||||
let mut visible_range = 0..total_lines;
|
||||
let mut line_top = px(0.);
|
||||
|
||||
let mut line_bottom = px(0.);
|
||||
for (ix, line) in state.text_wrapper.lines.iter().enumerate() {
|
||||
line_top += line.height(line_height);
|
||||
let wrapped_height = line.height(line_height);
|
||||
line_bottom += wrapped_height;
|
||||
|
||||
if line_top < scroll_top {
|
||||
if line_bottom < -scroll_top {
|
||||
visible_top = line_bottom - wrapped_height;
|
||||
visible_range.start = ix;
|
||||
}
|
||||
|
||||
if line_top > scroll_top + input_height {
|
||||
visible_range.end = (ix + 1).min(total_lines);
|
||||
if line_bottom + scroll_top >= input_height {
|
||||
visible_range.end = (ix + extra_rows).min(total_lines);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
visible_range
|
||||
(visible_range, visible_top)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -362,13 +448,17 @@ pub(super) struct PrepaintState {
|
||||
/// The lines of entire lines.
|
||||
last_layout: LastLayout,
|
||||
/// The lines only contains the visible lines in the viewport, based on `visible_range`.
|
||||
line_numbers: Option<Vec<SmallVec<[WrappedLine; 1]>>>,
|
||||
line_number_width: Pixels,
|
||||
///
|
||||
/// The child is the soft lines.
|
||||
line_numbers: Option<Vec<SmallVec<[ShapedLine; 1]>>>,
|
||||
/// Size of the scrollable area by entire lines.
|
||||
scroll_size: Size<Pixels>,
|
||||
cursor_bounds: Option<Bounds<Pixels>>,
|
||||
cursor_scroll_offset: Point<Pixels>,
|
||||
selection_path: Option<Path<Pixels>>,
|
||||
hover_highlight_path: Option<Path<Pixels>>,
|
||||
search_match_paths: Vec<(Path<Pixels>, bool)>,
|
||||
hover_definition_hitbox: Option<Hitbox>,
|
||||
bounds: Bounds<Pixels>,
|
||||
}
|
||||
|
||||
@@ -380,34 +470,9 @@ impl IntoElement for TextElement {
|
||||
}
|
||||
}
|
||||
|
||||
/// A debug function to print points as SVG path.
|
||||
#[allow(unused)]
|
||||
fn print_points_as_svg_path(line_corners: &Vec<Corners<Point<Pixels>>>, points: &[Point<Pixels>]) {
|
||||
for corners in line_corners {
|
||||
println!(
|
||||
"tl: ({}, {}), tr: ({}, {}), bl: ({}, {}), br: ({}, {})",
|
||||
corners.top_left.x.0 as i32,
|
||||
corners.top_left.y.0 as i32,
|
||||
corners.top_right.x.0 as i32,
|
||||
corners.top_right.y.0 as i32,
|
||||
corners.bottom_left.x.0 as i32,
|
||||
corners.bottom_left.y.0 as i32,
|
||||
corners.bottom_right.x.0 as i32,
|
||||
corners.bottom_right.y.0 as i32,
|
||||
);
|
||||
}
|
||||
|
||||
if !points.is_empty() {
|
||||
println!("M{},{}", points[0].x.0 as i32, points[0].y.0 as i32);
|
||||
for p in points.iter().skip(1) {
|
||||
println!("L{},{}", p.x.0 as i32, p.y.0 as i32);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Element for TextElement {
|
||||
type RequestLayoutState = ();
|
||||
type PrepaintState = PrepaintState;
|
||||
type RequestLayoutState = ();
|
||||
|
||||
fn id(&self) -> Option<ElementId> {
|
||||
None
|
||||
@@ -424,19 +489,20 @@ impl Element for TextElement {
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> (LayoutId, Self::RequestLayoutState) {
|
||||
let input = self.input.read(cx);
|
||||
let state = self.state.read(cx);
|
||||
let line_height = window.line_height();
|
||||
|
||||
let mut style = Style::default();
|
||||
style.size.width = relative(1.).into();
|
||||
if self.input.read(cx).is_multi_line() {
|
||||
if state.mode.is_multi_line() {
|
||||
style.flex_grow = 1.0;
|
||||
if let Some(h) = input.mode.height() {
|
||||
style.size.height = h.into();
|
||||
style.min_size.height = line_height.into();
|
||||
} else {
|
||||
style.size.height = relative(1.).into();
|
||||
style.min_size.height = (input.mode.rows() * line_height).into();
|
||||
if state.mode.is_auto_grow() {
|
||||
// Auto grow to let height match to rows, but not exceed max rows.
|
||||
let rows = state.mode.max_rows().min(state.mode.rows());
|
||||
style.min_size.height = (rows * line_height).into();
|
||||
} else {
|
||||
style.min_size.height = line_height.into();
|
||||
}
|
||||
} else {
|
||||
// For single-line inputs, the minimum height should be the line height
|
||||
@@ -455,11 +521,19 @@ impl Element for TextElement {
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) -> Self::PrepaintState {
|
||||
let state = self.state.read(cx);
|
||||
let line_height = window.line_height();
|
||||
let input = self.input.read(cx);
|
||||
let multi_line = input.is_multi_line();
|
||||
let visible_range = self.calculate_visible_range(input, line_height, bounds.size.height);
|
||||
let text = input.text.clone();
|
||||
|
||||
let (visible_range, visible_top) =
|
||||
self.calculate_visible_range(state, line_height, bounds.size.height);
|
||||
let visible_start_offset = state.text.line_start_offset(visible_range.start);
|
||||
let visible_end_offset = state
|
||||
.text
|
||||
.line_end_offset(visible_range.end.saturating_sub(1));
|
||||
|
||||
let state = self.state.read(cx);
|
||||
let multi_line = state.mode.is_multi_line();
|
||||
let text = state.text.clone();
|
||||
let is_empty = text.is_empty();
|
||||
let placeholder = self.placeholder.clone();
|
||||
let style = window.text_style();
|
||||
@@ -467,9 +541,9 @@ impl Element for TextElement {
|
||||
let mut bounds = bounds;
|
||||
|
||||
let (display_text, text_color) = if is_empty {
|
||||
(placeholder, cx.theme().text_muted)
|
||||
} else if input.masked {
|
||||
("*".repeat(text.chars().count()).into(), cx.theme().text)
|
||||
(Rope::from(placeholder.as_str()), cx.theme().text_muted)
|
||||
} else if state.masked {
|
||||
(Rope::from("*".repeat(text.chars_count())), cx.theme().text)
|
||||
} else {
|
||||
(text.clone(), cx.theme().text)
|
||||
};
|
||||
@@ -500,20 +574,20 @@ impl Element for TextElement {
|
||||
|
||||
let runs = if !is_empty {
|
||||
vec![run]
|
||||
} else if let Some(marked_range) = &input.marked_range {
|
||||
} else if let Some(ime_marked_range) = &state.ime_marked_range {
|
||||
// IME marked text
|
||||
vec![
|
||||
TextRun {
|
||||
len: marked_range.start,
|
||||
len: ime_marked_range.start,
|
||||
..run.clone()
|
||||
},
|
||||
TextRun {
|
||||
len: marked_range.end - marked_range.start,
|
||||
len: ime_marked_range.end - ime_marked_range.start,
|
||||
underline: marked_run.underline,
|
||||
..run.clone()
|
||||
},
|
||||
TextRun {
|
||||
len: display_text.len() - marked_range.end,
|
||||
len: display_text.len() - ime_marked_range.end,
|
||||
..run.clone()
|
||||
},
|
||||
]
|
||||
@@ -524,35 +598,76 @@ impl Element for TextElement {
|
||||
vec![run]
|
||||
};
|
||||
|
||||
let wrap_width = if multi_line {
|
||||
let wrap_width = if multi_line && state.soft_wrap {
|
||||
Some(bounds.size.width - line_number_width - RIGHT_MARGIN)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// NOTE: Here 50 lines about 150µs
|
||||
// let measure = crate::Measure::new("shape_text");
|
||||
let visible_text = display_text
|
||||
.slice_rows(visible_range.start as u32..visible_range.end as u32)
|
||||
.to_string();
|
||||
|
||||
let lines = window
|
||||
.text_system()
|
||||
.shape_text(display_text, font_size, &runs, wrap_width, None)
|
||||
.shape_text(visible_text.into(), font_size, &runs, wrap_width, None)
|
||||
.expect("failed to shape text");
|
||||
// measure.end();
|
||||
|
||||
let total_wrapped_lines = lines
|
||||
.iter()
|
||||
.map(|line| {
|
||||
// +1 is the first line, `wrap_boundaries` is the wrapped lines after the `\n`.
|
||||
1 + line.wrap_boundaries.len()
|
||||
})
|
||||
.sum::<usize>();
|
||||
let mut longest_line_width = wrap_width.unwrap_or(px(0.));
|
||||
if state.mode.is_multi_line() && !state.soft_wrap && lines.len() > 1 {
|
||||
let longtest_line: SharedString = state
|
||||
.text
|
||||
.line(state.text.summary().longest_row as usize)
|
||||
.to_string()
|
||||
.into();
|
||||
longest_line_width = window
|
||||
.text_system()
|
||||
.shape_line(
|
||||
longtest_line.clone(),
|
||||
font_size,
|
||||
&[TextRun {
|
||||
len: longtest_line.len(),
|
||||
font: style.font(),
|
||||
color: gpui::black(),
|
||||
background_color: None,
|
||||
underline: None,
|
||||
strikethrough: None,
|
||||
}],
|
||||
wrap_width,
|
||||
)
|
||||
.width;
|
||||
}
|
||||
|
||||
let max_line_width = lines
|
||||
.iter()
|
||||
.map(|line| line.width())
|
||||
.max()
|
||||
.unwrap_or(bounds.size.width);
|
||||
let total_wrapped_lines = state.text_wrapper.len();
|
||||
let empty_bottom_height = bounds
|
||||
.size
|
||||
.height
|
||||
.half()
|
||||
.max(BOTTOM_MARGIN_ROWS * line_height);
|
||||
let scroll_size = size(
|
||||
max_line_width + line_number_width + RIGHT_MARGIN,
|
||||
(total_wrapped_lines as f32 * line_height).max(bounds.size.height),
|
||||
if longest_line_width + line_number_width + RIGHT_MARGIN > bounds.size.width {
|
||||
longest_line_width + line_number_width + RIGHT_MARGIN
|
||||
} else {
|
||||
longest_line_width
|
||||
},
|
||||
(total_wrapped_lines as f32 * line_height + empty_bottom_height)
|
||||
.max(bounds.size.height),
|
||||
);
|
||||
|
||||
let mut last_layout = LastLayout {
|
||||
visible_range,
|
||||
visible_top,
|
||||
visible_range_offset: visible_start_offset..visible_end_offset,
|
||||
line_height,
|
||||
wrap_width,
|
||||
line_number_width,
|
||||
lines: Rc::new(lines),
|
||||
cursor_bounds: None,
|
||||
};
|
||||
|
||||
// `position_for_index` for example
|
||||
//
|
||||
// #### text
|
||||
@@ -584,37 +699,27 @@ impl Element for TextElement {
|
||||
|
||||
// Calculate the scroll offset to keep the cursor in view
|
||||
|
||||
let (cursor_bounds, cursor_scroll_offset, _) = self.layout_cursor(
|
||||
&lines,
|
||||
line_height,
|
||||
&mut bounds,
|
||||
line_number_width,
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
let (cursor_bounds, cursor_scroll_offset, _) =
|
||||
self.layout_cursor(&last_layout, &mut bounds, window, cx);
|
||||
last_layout.cursor_bounds = cursor_bounds;
|
||||
|
||||
let selection_path = self.layout_selections(
|
||||
&lines,
|
||||
line_height,
|
||||
&mut bounds,
|
||||
line_number_width,
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
let selection_path = self.layout_selections(&last_layout, &mut bounds, cx);
|
||||
let search_match_paths = vec![];
|
||||
let hover_highlight_path = None;
|
||||
let line_numbers = None;
|
||||
let hover_definition_hitbox = None;
|
||||
|
||||
PrepaintState {
|
||||
bounds,
|
||||
last_layout: LastLayout {
|
||||
lines: Rc::new(lines),
|
||||
line_height,
|
||||
visible_range,
|
||||
},
|
||||
last_layout,
|
||||
scroll_size,
|
||||
line_numbers: None,
|
||||
line_number_width,
|
||||
line_numbers,
|
||||
cursor_bounds,
|
||||
cursor_scroll_offset,
|
||||
selection_path,
|
||||
search_match_paths,
|
||||
hover_highlight_path,
|
||||
hover_definition_hitbox,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -628,21 +733,21 @@ impl Element for TextElement {
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
) {
|
||||
let focus_handle = self.input.read(cx).focus_handle.clone();
|
||||
let focus_handle = self.state.read(cx).focus_handle.clone();
|
||||
let show_cursor = self.state.read(cx).show_cursor(window, cx);
|
||||
let focused = focus_handle.is_focused(window);
|
||||
let bounds = prepaint.bounds;
|
||||
let selected_range = self.input.read(cx).selected_range.clone();
|
||||
let visible_range = &prepaint.last_layout.visible_range;
|
||||
let selected_range = self.state.read(cx).selected_range;
|
||||
|
||||
window.handle_input(
|
||||
&focus_handle,
|
||||
ElementInputHandler::new(bounds, self.input.clone()),
|
||||
ElementInputHandler::new(bounds, self.state.clone()),
|
||||
cx,
|
||||
);
|
||||
|
||||
// Set Root focused_input when self is focused
|
||||
if focused {
|
||||
let state = self.input.clone();
|
||||
let state = self.state.clone();
|
||||
if Root::read(window, cx).focused_input.as_ref() != Some(&state) {
|
||||
Root::update(window, cx, |root, _, cx| {
|
||||
root.focused_input = Some(state);
|
||||
@@ -653,7 +758,7 @@ impl Element for TextElement {
|
||||
|
||||
// And reset focused_input when next_frame start
|
||||
window.on_next_frame({
|
||||
let state = self.input.clone();
|
||||
let state = self.state.clone();
|
||||
move |window, cx| {
|
||||
if !focused && Root::read(window, cx).focused_input.as_ref() == Some(&state) {
|
||||
Root::update(window, cx, |root, _, cx| {
|
||||
@@ -668,13 +773,10 @@ impl Element for TextElement {
|
||||
let line_height = window.line_height();
|
||||
let origin = bounds.origin;
|
||||
|
||||
let mut invisible_top_padding = px(0.);
|
||||
for line in prepaint.last_layout.lines.iter().take(visible_range.start) {
|
||||
invisible_top_padding += line.size(line_height).height;
|
||||
}
|
||||
let invisible_top_padding = prepaint.last_layout.visible_top;
|
||||
|
||||
let mut mask_offset_y = px(0.);
|
||||
if self.input.read(cx).masked {
|
||||
if self.state.read(cx).masked {
|
||||
// Move down offset for vertical centering the *****
|
||||
if cfg!(target_os = "macos") {
|
||||
mask_offset_y = px(3.);
|
||||
@@ -683,60 +785,105 @@ impl Element for TextElement {
|
||||
}
|
||||
}
|
||||
|
||||
// Paint active line
|
||||
let mut offset_y = px(0.);
|
||||
if let Some(line_numbers) = prepaint.line_numbers.as_ref() {
|
||||
offset_y += invisible_top_padding;
|
||||
|
||||
// Each item is the normal lines.
|
||||
for lines in line_numbers.iter() {
|
||||
for line in lines {
|
||||
let p = point(origin.x, origin.y + offset_y);
|
||||
let line_size = line.size(line_height);
|
||||
_ = line.paint(p, line_height, TextAlign::Left, None, window, cx);
|
||||
offset_y += line_size.height;
|
||||
}
|
||||
let height = line_height * lines.len() as f32;
|
||||
offset_y += height;
|
||||
}
|
||||
}
|
||||
|
||||
// Paint selections
|
||||
if window.is_window_active() {
|
||||
let secondary_selection = cx.theme().selection;
|
||||
for (path, is_active) in prepaint.search_match_paths.iter() {
|
||||
window.paint_path(path.clone(), secondary_selection);
|
||||
|
||||
if *is_active {
|
||||
window.paint_path(path.clone(), cx.theme().selection);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(path) = prepaint.selection_path.take() {
|
||||
window.paint_path(path, cx.theme().selection);
|
||||
}
|
||||
|
||||
// Paint hover highlight
|
||||
if let Some(path) = prepaint.hover_highlight_path.take() {
|
||||
window.paint_path(path, secondary_selection);
|
||||
}
|
||||
}
|
||||
|
||||
// Paint text
|
||||
let mut offset_y = mask_offset_y + invisible_top_padding;
|
||||
for line in prepaint
|
||||
.last_layout
|
||||
.iter()
|
||||
.skip(visible_range.start)
|
||||
.take(visible_range.len())
|
||||
{
|
||||
let p = point(origin.x + prepaint.line_number_width, origin.y + offset_y);
|
||||
for line in prepaint.last_layout.lines.iter() {
|
||||
let p = point(
|
||||
origin.x + prepaint.last_layout.line_number_width,
|
||||
origin.y + offset_y,
|
||||
);
|
||||
_ = line.paint(p, line_height, TextAlign::Left, None, window, cx);
|
||||
offset_y += line.size(line_height).height;
|
||||
}
|
||||
|
||||
if focused {
|
||||
// Paint blinking cursor
|
||||
if focused && show_cursor {
|
||||
if let Some(mut cursor_bounds) = prepaint.cursor_bounds.take() {
|
||||
cursor_bounds.origin.y += prepaint.cursor_scroll_offset.y;
|
||||
window.paint_quad(fill(cursor_bounds, cx.theme().cursor));
|
||||
}
|
||||
}
|
||||
|
||||
self.input.update(cx, |input, cx| {
|
||||
input.last_layout = Some(prepaint.last_layout.clone());
|
||||
input.last_bounds = Some(bounds);
|
||||
input.last_cursor_offset = Some(input.cursor_offset());
|
||||
input.set_input_bounds(input_bounds, cx);
|
||||
input.last_selected_range = Some(selected_range);
|
||||
input.scroll_size = prepaint.scroll_size;
|
||||
input.line_number_width = prepaint.line_number_width;
|
||||
input
|
||||
// Paint line numbers
|
||||
let mut offset_y = px(0.);
|
||||
if let Some(line_numbers) = prepaint.line_numbers.as_ref() {
|
||||
offset_y += invisible_top_padding;
|
||||
|
||||
// Paint line number background
|
||||
window.paint_quad(fill(
|
||||
Bounds {
|
||||
origin: input_bounds.origin,
|
||||
size: size(
|
||||
prepaint.last_layout.line_number_width - LINE_NUMBER_RIGHT_MARGIN,
|
||||
input_bounds.size.height,
|
||||
),
|
||||
},
|
||||
cx.theme().background,
|
||||
));
|
||||
|
||||
// Each item is the normal lines.
|
||||
for lines in line_numbers.iter() {
|
||||
let p = point(input_bounds.origin.x, origin.y + offset_y);
|
||||
|
||||
for line in lines {
|
||||
_ = line.paint(p, line_height, window, cx);
|
||||
offset_y += line_height;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.state.update(cx, |state, cx| {
|
||||
state.last_layout = Some(prepaint.last_layout.clone());
|
||||
state.last_bounds = Some(bounds);
|
||||
state.last_cursor = Some(state.cursor());
|
||||
state.set_input_bounds(input_bounds, cx);
|
||||
state.last_selected_range = Some(selected_range);
|
||||
state.scroll_size = prepaint.scroll_size;
|
||||
state
|
||||
.scroll_handle
|
||||
.set_offset(prepaint.cursor_scroll_offset);
|
||||
state.deferred_scroll_offset = None;
|
||||
|
||||
cx.notify();
|
||||
});
|
||||
|
||||
if let Some(hitbox) = prepaint.hover_definition_hitbox.as_ref() {
|
||||
window.set_cursor_style(gpui::CursorStyle::PointingHand, hitbox);
|
||||
}
|
||||
|
||||
self.paint_mouse_listeners(window, cx);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ use gpui::SharedString;
|
||||
|
||||
#[derive(Clone, PartialEq, Debug)]
|
||||
pub enum MaskToken {
|
||||
/// 0 Digit, equivalent to `[0]`
|
||||
// Digit0,
|
||||
/// Digit, equivalent to `[0-9]`
|
||||
Digit,
|
||||
/// Letter, equivalent to `[a-zA-Z]`
|
||||
@@ -200,11 +202,25 @@ impl MaskPattern {
|
||||
return false;
|
||||
}
|
||||
|
||||
// check if the integer part is valid
|
||||
if !int_part
|
||||
let sign_positions: Vec<usize> = int_part
|
||||
.chars()
|
||||
.all(|ch| ch.is_ascii_digit() || Some(ch) == *separator)
|
||||
{
|
||||
.enumerate()
|
||||
.filter_map(|(i, ch)| match is_sign(&ch) {
|
||||
true => Some(i),
|
||||
false => None,
|
||||
})
|
||||
.collect();
|
||||
|
||||
// only one sign is valid
|
||||
// sign is only valid at the beginning of the string
|
||||
if sign_positions.len() > 1 || sign_positions.first() > Some(&0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// check if the integer part is valid
|
||||
if !int_part.chars().enumerate().all(|(i, ch)| {
|
||||
ch.is_ascii_digit() || is_sign(&ch) && i == 0 || Some(ch) == *separator
|
||||
}) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -286,7 +302,11 @@ impl MaskPattern {
|
||||
});
|
||||
|
||||
// Reverse the integer part for easier grouping
|
||||
let chars: Vec<char> = int_part.chars().rev().collect();
|
||||
let mut chars: Vec<char> = int_part.chars().rev().collect();
|
||||
|
||||
// Removing the sign from formatting to avoid cases such as: -,123
|
||||
let maybe_signed = chars.iter().position(is_sign).map(|pos| chars.remove(pos));
|
||||
|
||||
let mut result = String::new();
|
||||
for (i, ch) in chars.iter().enumerate() {
|
||||
if i > 0 && i % 3 == 0 {
|
||||
@@ -305,6 +325,13 @@ impl MaskPattern {
|
||||
} else {
|
||||
int_with_sep
|
||||
};
|
||||
|
||||
let final_str = if let Some(sign) = maybe_signed {
|
||||
format!("{sign}{final_str}")
|
||||
} else {
|
||||
final_str
|
||||
};
|
||||
|
||||
return final_str.into();
|
||||
}
|
||||
|
||||
@@ -376,3 +403,8 @@ impl MaskPattern {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn is_sign(ch: &char) -> bool {
|
||||
matches!(ch, '+' | '-')
|
||||
}
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
mod blink_cursor;
|
||||
mod change;
|
||||
mod cursor;
|
||||
mod element;
|
||||
mod mask_pattern;
|
||||
mod mode;
|
||||
mod rope_ext;
|
||||
mod state;
|
||||
mod text_input;
|
||||
mod text_wrapper;
|
||||
|
||||
pub(crate) mod clear_button;
|
||||
|
||||
#[allow(ambiguous_glob_reexports)]
|
||||
pub use state::*;
|
||||
pub use text_input::*;
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
use gpui::SharedString;
|
||||
|
||||
use super::text_wrapper::TextWrapper;
|
||||
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub struct TabSize {
|
||||
/// Default is 2
|
||||
pub tab_size: usize,
|
||||
/// Set true to use `\t` as tab indent, default is false
|
||||
pub hard_tabs: bool,
|
||||
}
|
||||
|
||||
impl Default for TabSize {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
tab_size: 2,
|
||||
hard_tabs: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TabSize {
|
||||
pub(super) fn to_string(self) -> SharedString {
|
||||
if self.hard_tabs {
|
||||
"\t".into()
|
||||
} else {
|
||||
" ".repeat(self.tab_size).into()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
pub enum InputMode {
|
||||
#[default]
|
||||
SingleLine,
|
||||
MultiLine {
|
||||
tab: TabSize,
|
||||
rows: usize,
|
||||
},
|
||||
AutoGrow {
|
||||
rows: usize,
|
||||
min_rows: usize,
|
||||
max_rows: usize,
|
||||
},
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
impl InputMode {
|
||||
#[inline]
|
||||
pub(super) fn is_single_line(&self) -> bool {
|
||||
matches!(self, InputMode::SingleLine)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(super) fn is_auto_grow(&self) -> bool {
|
||||
matches!(self, InputMode::AutoGrow { .. })
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(super) fn is_multi_line(&self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
InputMode::MultiLine { .. } | InputMode::AutoGrow { .. }
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn set_rows(&mut self, new_rows: usize) {
|
||||
match self {
|
||||
InputMode::MultiLine { rows, .. } => {
|
||||
*rows = new_rows;
|
||||
}
|
||||
InputMode::AutoGrow {
|
||||
rows,
|
||||
min_rows,
|
||||
max_rows,
|
||||
} => {
|
||||
*rows = new_rows.clamp(*min_rows, *max_rows);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn update_auto_grow(&mut self, text_wrapper: &TextWrapper) {
|
||||
if self.is_single_line() {
|
||||
return;
|
||||
}
|
||||
|
||||
let wrapped_lines = text_wrapper.len();
|
||||
self.set_rows(wrapped_lines);
|
||||
}
|
||||
|
||||
/// At least 1 row be return.
|
||||
pub(super) fn rows(&self) -> usize {
|
||||
match self {
|
||||
InputMode::MultiLine { rows, .. } => *rows,
|
||||
InputMode::AutoGrow { rows, .. } => *rows,
|
||||
_ => 1,
|
||||
}
|
||||
.max(1)
|
||||
}
|
||||
|
||||
/// At least 1 row be return.
|
||||
#[allow(unused)]
|
||||
pub(super) fn min_rows(&self) -> usize {
|
||||
match self {
|
||||
InputMode::MultiLine { .. } => 1,
|
||||
InputMode::AutoGrow { min_rows, .. } => *min_rows,
|
||||
_ => 1,
|
||||
}
|
||||
.max(1)
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
pub(super) fn max_rows(&self) -> usize {
|
||||
match self {
|
||||
InputMode::MultiLine { .. } => usize::MAX,
|
||||
InputMode::AutoGrow { max_rows, .. } => *max_rows,
|
||||
_ => 1,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(super) fn tab_size(&self) -> Option<&TabSize> {
|
||||
match self {
|
||||
InputMode::MultiLine { tab, .. } => Some(tab),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
use std::ops::Range;
|
||||
|
||||
use rope::{Point, Rope};
|
||||
|
||||
use super::cursor::Position;
|
||||
|
||||
/// An extension trait for `Rope` to provide additional utility methods.
|
||||
pub trait RopeExt {
|
||||
/// Get the line at the given row (0-based) index, including the `\r` at the end, but not `\n`.
|
||||
///
|
||||
/// Return empty rope if the row (0-based) is out of bounds.
|
||||
fn line(&self, row: usize) -> Rope;
|
||||
|
||||
/// Start offset of the line at the given row (0-based) index.
|
||||
fn line_start_offset(&self, row: usize) -> usize;
|
||||
|
||||
/// Line the end offset (including `\n`) of the line at the given row (0-based) index.
|
||||
///
|
||||
/// Return the end of the rope if the row is out of bounds.
|
||||
fn line_end_offset(&self, row: usize) -> usize;
|
||||
|
||||
/// Return the number of lines in the rope.
|
||||
fn lines_len(&self) -> usize;
|
||||
|
||||
/// Return the lines iterator.
|
||||
///
|
||||
/// Each line is including the `\r` at the end, but not `\n`.
|
||||
fn lines(&self) -> RopeLines;
|
||||
|
||||
/// Check is equal to another rope.
|
||||
fn eq(&self, other: &Rope) -> bool;
|
||||
|
||||
/// Total number of characters in the rope.
|
||||
fn chars_count(&self) -> usize;
|
||||
|
||||
/// Get char at the given offset (byte).
|
||||
///
|
||||
/// If the offset is in the middle of a multi-byte character will panic.
|
||||
///
|
||||
/// If the offset is out of bounds, return None.
|
||||
fn char_at(&self, offset: usize) -> Option<char>;
|
||||
|
||||
/// Get the byte offset from the given line, column [`Position`] (0-based).
|
||||
fn position_to_offset(&self, line_col: &Position) -> usize;
|
||||
|
||||
/// Get the line, column [`Position`] (0-based) from the given byte offset.
|
||||
fn offset_to_position(&self, offset: usize) -> Position;
|
||||
|
||||
/// Get the word byte range at the given offset (byte).
|
||||
fn word_range(&self, offset: usize) -> Option<Range<usize>>;
|
||||
|
||||
/// Get word at the given offset (byte).
|
||||
#[allow(dead_code)]
|
||||
fn word_at(&self, offset: usize) -> String;
|
||||
}
|
||||
|
||||
/// An iterator over the lines of a `Rope`.
|
||||
pub struct RopeLines {
|
||||
row: usize,
|
||||
end_row: usize,
|
||||
rope: Rope,
|
||||
}
|
||||
|
||||
impl RopeLines {
|
||||
/// Create a new `RopeLines` iterator.
|
||||
pub fn new(rope: Rope) -> Self {
|
||||
let end_row = rope.lines_len();
|
||||
Self {
|
||||
row: 0,
|
||||
end_row,
|
||||
rope,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Iterator for RopeLines {
|
||||
type Item = Rope;
|
||||
|
||||
#[inline]
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if self.row >= self.end_row {
|
||||
return None;
|
||||
}
|
||||
|
||||
let line = self.rope.line(self.row);
|
||||
self.row += 1;
|
||||
Some(line)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn nth(&mut self, n: usize) -> Option<Self::Item> {
|
||||
self.row = self.row.saturating_add(n);
|
||||
self.next()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
let len = self.end_row - self.row;
|
||||
(len, Some(len))
|
||||
}
|
||||
}
|
||||
|
||||
impl std::iter::ExactSizeIterator for RopeLines {}
|
||||
impl std::iter::FusedIterator for RopeLines {}
|
||||
|
||||
impl RopeExt for Rope {
|
||||
fn line(&self, row: usize) -> Rope {
|
||||
let start = self.line_start_offset(row);
|
||||
let end = start + self.line_len(row as u32) as usize;
|
||||
self.slice(start..end)
|
||||
}
|
||||
|
||||
fn line_start_offset(&self, row: usize) -> usize {
|
||||
let row = row as u32;
|
||||
self.point_to_offset(Point::new(row, 0))
|
||||
}
|
||||
|
||||
fn position_to_offset(&self, pos: &Position) -> usize {
|
||||
let line = self.line(pos.line as usize);
|
||||
self.line_start_offset(pos.line as usize)
|
||||
+ line
|
||||
.chars()
|
||||
.take(pos.character as usize)
|
||||
.map(|c| c.len_utf8())
|
||||
.sum::<usize>()
|
||||
}
|
||||
|
||||
fn offset_to_position(&self, offset: usize) -> Position {
|
||||
let point = self.offset_to_point(offset);
|
||||
let line = self.line(point.row as usize);
|
||||
let column = line.clip_offset(point.column as usize, sum_tree::Bias::Left);
|
||||
let character = line.slice(0..column).chars().count();
|
||||
Position::new(point.row, character as u32)
|
||||
}
|
||||
|
||||
fn line_end_offset(&self, row: usize) -> usize {
|
||||
if row > self.max_point().row as usize {
|
||||
return self.len();
|
||||
}
|
||||
|
||||
self.line_start_offset(row) + self.line_len(row as u32) as usize
|
||||
}
|
||||
|
||||
fn lines_len(&self) -> usize {
|
||||
self.max_point().row as usize + 1
|
||||
}
|
||||
|
||||
fn lines(&self) -> RopeLines {
|
||||
RopeLines::new(self.clone())
|
||||
}
|
||||
|
||||
fn eq(&self, other: &Rope) -> bool {
|
||||
self.summary() == other.summary()
|
||||
}
|
||||
|
||||
fn chars_count(&self) -> usize {
|
||||
self.chars().count()
|
||||
}
|
||||
|
||||
fn char_at(&self, offset: usize) -> Option<char> {
|
||||
if offset > self.len() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let offset = self.clip_offset(offset, sum_tree::Bias::Left);
|
||||
self.slice(offset..self.len()).chars().next()
|
||||
}
|
||||
|
||||
fn word_range(&self, offset: usize) -> Option<Range<usize>> {
|
||||
if offset >= self.len() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let offset = self.clip_offset(offset, sum_tree::Bias::Left);
|
||||
|
||||
let mut left = String::new();
|
||||
for c in self.reversed_chars_at(offset) {
|
||||
if c.is_alphanumeric() || c == '_' {
|
||||
left.insert(0, c);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let start = offset.saturating_sub(left.len());
|
||||
|
||||
let right = self
|
||||
.chars_at(offset)
|
||||
.take_while(|c| c.is_alphanumeric() || *c == '_')
|
||||
.collect::<String>();
|
||||
|
||||
let end = offset + right.len();
|
||||
|
||||
if start == end {
|
||||
None
|
||||
} else {
|
||||
Some(start..end)
|
||||
}
|
||||
}
|
||||
|
||||
fn word_at(&self, offset: usize) -> String {
|
||||
if let Some(range) = self.word_range(offset) {
|
||||
self.slice(range).to_string()
|
||||
} else {
|
||||
String::new()
|
||||
}
|
||||
}
|
||||
}
|
||||
+929
-717
File diff suppressed because it is too large
Load Diff
@@ -6,11 +6,10 @@ use gpui::{
|
||||
};
|
||||
use theme::ActiveTheme;
|
||||
|
||||
use super::InputState;
|
||||
use crate::button::{Button, ButtonVariants as _};
|
||||
use super::clear_button::clear_button;
|
||||
use super::state::{InputState, CONTEXT};
|
||||
use crate::button::{Button, ButtonVariants};
|
||||
use crate::indicator::Indicator;
|
||||
use crate::input::clear_button::clear_button;
|
||||
use crate::scroll::{Scrollbar, ScrollbarAxis};
|
||||
use crate::{h_flex, IconName, Sizable, Size, StyleSized, StyledExt};
|
||||
|
||||
#[derive(IntoElement)]
|
||||
@@ -18,7 +17,6 @@ pub struct TextInput {
|
||||
state: Entity<InputState>,
|
||||
style: StyleRefinement,
|
||||
size: Size,
|
||||
no_gap: bool,
|
||||
prefix: Option<AnyElement>,
|
||||
suffix: Option<AnyElement>,
|
||||
height: Option<DefiniteLength>,
|
||||
@@ -26,6 +24,8 @@ pub struct TextInput {
|
||||
cleanable: bool,
|
||||
mask_toggle: bool,
|
||||
disabled: bool,
|
||||
bordered: bool,
|
||||
focus_bordered: bool,
|
||||
}
|
||||
|
||||
impl Sizable for TextInput {
|
||||
@@ -40,9 +40,8 @@ impl TextInput {
|
||||
pub fn new(state: &Entity<InputState>) -> Self {
|
||||
Self {
|
||||
state: state.clone(),
|
||||
style: StyleRefinement::default(),
|
||||
size: Size::default(),
|
||||
no_gap: false,
|
||||
style: StyleRefinement::default(),
|
||||
prefix: None,
|
||||
suffix: None,
|
||||
height: None,
|
||||
@@ -50,6 +49,8 @@ impl TextInput {
|
||||
cleanable: false,
|
||||
mask_toggle: false,
|
||||
disabled: false,
|
||||
bordered: true,
|
||||
focus_bordered: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,12 +76,24 @@ impl TextInput {
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the appearance of the input field.
|
||||
/// Set the appearance of the input field, if false the input field will no border, background.
|
||||
pub fn appearance(mut self, appearance: bool) -> Self {
|
||||
self.appearance = appearance;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the bordered for the input, default: true
|
||||
pub fn bordered(mut self, bordered: bool) -> Self {
|
||||
self.bordered = bordered;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set focus border for the input, default is true.
|
||||
pub fn focus_bordered(mut self, bordered: bool) -> Self {
|
||||
self.focus_bordered = bordered;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set true to show the clear button when the input field is not empty.
|
||||
pub fn cleanable(mut self) -> Self {
|
||||
self.cleanable = true;
|
||||
@@ -99,15 +112,6 @@ impl TextInput {
|
||||
self
|
||||
}
|
||||
|
||||
/// Set true to not use gap between input and prefix, suffix, and clear button.
|
||||
///
|
||||
/// Default: false
|
||||
#[allow(dead_code)]
|
||||
pub(super) fn no_gap(mut self) -> Self {
|
||||
self.no_gap = true;
|
||||
self
|
||||
}
|
||||
|
||||
fn render_toggle_mask_button(state: Entity<InputState>) -> impl IntoElement {
|
||||
Button::new("toggle-mask")
|
||||
.icon(IconName::Eye)
|
||||
@@ -132,44 +136,51 @@ impl TextInput {
|
||||
}
|
||||
}
|
||||
|
||||
impl Styled for TextInput {
|
||||
fn style(&mut self) -> &mut StyleRefinement {
|
||||
&mut self.style
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderOnce for TextInput {
|
||||
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
|
||||
const LINE_HEIGHT: Rems = Rems(1.25);
|
||||
let font = window.text_style().font();
|
||||
let font_size = window.text_style().font_size.to_pixels(window.rem_size());
|
||||
|
||||
self.state.update(cx, |state, _| {
|
||||
state.mode.set_height(self.height);
|
||||
self.state.update(cx, |state, cx| {
|
||||
state.text_wrapper.set_font(font, font_size, cx);
|
||||
state.disabled = self.disabled;
|
||||
});
|
||||
|
||||
let state = self.state.read(cx);
|
||||
let focused = state.focus_handle.is_focused(window);
|
||||
|
||||
let mut gap_x = match self.size {
|
||||
let gap_x = match self.size {
|
||||
Size::Small => px(4.),
|
||||
Size::Large => px(8.),
|
||||
_ => px(4.),
|
||||
};
|
||||
|
||||
if self.no_gap {
|
||||
gap_x = px(0.);
|
||||
}
|
||||
|
||||
let prefix = self.prefix;
|
||||
let suffix = self.suffix;
|
||||
|
||||
let show_clear_button =
|
||||
self.cleanable && !state.loading && !state.text.is_empty() && state.is_single_line();
|
||||
|
||||
let bg = if state.disabled {
|
||||
cx.theme().surface_background
|
||||
} else {
|
||||
cx.theme().elevated_surface_background
|
||||
};
|
||||
|
||||
let prefix = self.prefix;
|
||||
let suffix = self.suffix;
|
||||
|
||||
let show_clear_button = self.cleanable
|
||||
&& !state.loading
|
||||
&& !state.text.is_empty()
|
||||
&& state.mode.is_single_line();
|
||||
|
||||
let has_suffix = suffix.is_some() || state.loading || self.mask_toggle || show_clear_button;
|
||||
|
||||
div()
|
||||
.id(("input", self.state.entity_id()))
|
||||
.flex()
|
||||
.key_context(crate::input::CONTEXT)
|
||||
.key_context(CONTEXT)
|
||||
.track_focus(&state.focus_handle)
|
||||
.when(!state.disabled, |this| {
|
||||
this.on_action(window.listener_for(&self.state, InputState::backspace))
|
||||
@@ -182,17 +193,31 @@ impl RenderOnce for TextInput {
|
||||
.on_action(window.listener_for(&self.state, InputState::delete_next_word))
|
||||
.on_action(window.listener_for(&self.state, InputState::enter))
|
||||
.on_action(window.listener_for(&self.state, InputState::escape))
|
||||
.on_action(window.listener_for(&self.state, InputState::paste))
|
||||
.on_action(window.listener_for(&self.state, InputState::cut))
|
||||
.on_action(window.listener_for(&self.state, InputState::undo))
|
||||
.on_action(window.listener_for(&self.state, InputState::redo))
|
||||
.when(state.mode.is_multi_line(), |this| {
|
||||
this.on_action(window.listener_for(&self.state, InputState::indent_inline))
|
||||
.on_action(window.listener_for(&self.state, InputState::outdent_inline))
|
||||
.on_action(window.listener_for(&self.state, InputState::indent_block))
|
||||
.on_action(window.listener_for(&self.state, InputState::outdent_block))
|
||||
.on_action(
|
||||
window.listener_for(&self.state, InputState::shift_to_new_line),
|
||||
)
|
||||
})
|
||||
})
|
||||
.on_action(window.listener_for(&self.state, InputState::left))
|
||||
.on_action(window.listener_for(&self.state, InputState::right))
|
||||
.on_action(window.listener_for(&self.state, InputState::select_left))
|
||||
.on_action(window.listener_for(&self.state, InputState::select_right))
|
||||
.when(state.is_multi_line(), |this| {
|
||||
.when(state.mode.is_multi_line(), |this| {
|
||||
this.on_action(window.listener_for(&self.state, InputState::up))
|
||||
.on_action(window.listener_for(&self.state, InputState::down))
|
||||
.on_action(window.listener_for(&self.state, InputState::select_up))
|
||||
.on_action(window.listener_for(&self.state, InputState::select_down))
|
||||
.on_action(window.listener_for(&self.state, InputState::shift_to_new_line))
|
||||
.on_action(window.listener_for(&self.state, InputState::page_up))
|
||||
.on_action(window.listener_for(&self.state, InputState::page_down))
|
||||
})
|
||||
.on_action(window.listener_for(&self.state, InputState::select_all))
|
||||
.on_action(window.listener_for(&self.state, InputState::select_to_start_of_line))
|
||||
@@ -209,54 +234,51 @@ impl RenderOnce for TextInput {
|
||||
.on_action(window.listener_for(&self.state, InputState::select_to_end))
|
||||
.on_action(window.listener_for(&self.state, InputState::show_character_palette))
|
||||
.on_action(window.listener_for(&self.state, InputState::copy))
|
||||
.on_action(window.listener_for(&self.state, InputState::paste))
|
||||
.on_action(window.listener_for(&self.state, InputState::cut))
|
||||
.on_action(window.listener_for(&self.state, InputState::undo))
|
||||
.on_action(window.listener_for(&self.state, InputState::redo))
|
||||
.on_key_down(window.listener_for(&self.state, InputState::on_key_down))
|
||||
.on_mouse_down(
|
||||
MouseButton::Left,
|
||||
window.listener_for(&self.state, InputState::on_mouse_down),
|
||||
)
|
||||
.on_mouse_down(
|
||||
MouseButton::Middle,
|
||||
MouseButton::Right,
|
||||
window.listener_for(&self.state, InputState::on_mouse_down),
|
||||
)
|
||||
.on_mouse_up(
|
||||
MouseButton::Left,
|
||||
window.listener_for(&self.state, InputState::on_mouse_up),
|
||||
)
|
||||
.on_mouse_up(
|
||||
MouseButton::Right,
|
||||
window.listener_for(&self.state, InputState::on_mouse_up),
|
||||
)
|
||||
.on_scroll_wheel(window.listener_for(&self.state, InputState::on_scroll_wheel))
|
||||
.size_full()
|
||||
.line_height(LINE_HEIGHT)
|
||||
.cursor_text()
|
||||
.input_px(self.size)
|
||||
.input_py(self.size)
|
||||
.input_h(self.size)
|
||||
.when(state.is_multi_line(), |this| {
|
||||
.cursor_text()
|
||||
.text_size(font_size)
|
||||
.items_center()
|
||||
.when(state.mode.is_multi_line(), |this| {
|
||||
this.h_auto()
|
||||
.when_some(self.height, |this, height| this.h(height))
|
||||
})
|
||||
.when(self.appearance, |this| {
|
||||
this.bg(bg)
|
||||
.rounded(cx.theme().radius)
|
||||
.when(focused, |this| this.border_color(cx.theme().ring))
|
||||
this.bg(bg).rounded(cx.theme().radius)
|
||||
})
|
||||
.when(prefix.is_none(), |this| this.input_pl(self.size))
|
||||
.input_pr(self.size)
|
||||
.items_center()
|
||||
.gap(gap_x)
|
||||
.refine_style(&self.style)
|
||||
.children(prefix)
|
||||
// TODO: Define height here, and use it in the input element
|
||||
.child(self.state.clone())
|
||||
.child(
|
||||
.when(has_suffix, |this| {
|
||||
this.pr_2().child(
|
||||
h_flex()
|
||||
.id("suffix")
|
||||
.absolute()
|
||||
.gap(gap_x)
|
||||
.when(self.appearance, |this| this.bg(bg))
|
||||
.items_center()
|
||||
.when(suffix.is_none(), |this| this.pr_1())
|
||||
.right_0()
|
||||
.when(state.loading, |this| {
|
||||
this.child(Indicator::new().color(cx.theme().text_muted))
|
||||
})
|
||||
@@ -275,24 +297,6 @@ impl RenderOnce for TextInput {
|
||||
})
|
||||
.children(suffix),
|
||||
)
|
||||
.when(state.is_multi_line(), |this| {
|
||||
if state.last_layout.is_some() {
|
||||
this.relative().child(
|
||||
div()
|
||||
.absolute()
|
||||
.top_0()
|
||||
.left_0()
|
||||
.right(px(1.))
|
||||
.bottom_0()
|
||||
.child(
|
||||
Scrollbar::vertical(&state.scrollbar_state, &state.scroll_handle)
|
||||
.axis(ScrollbarAxis::Vertical),
|
||||
),
|
||||
)
|
||||
} else {
|
||||
this
|
||||
}
|
||||
})
|
||||
.refine_style(&self.style)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,99 +1,215 @@
|
||||
use std::ops::Range;
|
||||
|
||||
use gpui::{App, Font, LineFragment, Pixels, SharedString};
|
||||
use gpui::{App, Font, LineFragment, Pixels};
|
||||
use rope::Rope;
|
||||
|
||||
#[allow(unused)]
|
||||
pub(super) struct LineWrap {
|
||||
/// The number of soft wrapped lines of this line (Not include first line.)
|
||||
pub(super) wrap_lines: usize,
|
||||
/// The range of the line text in the entire text.
|
||||
pub(super) range: Range<usize>,
|
||||
}
|
||||
use super::rope_ext::RopeExt;
|
||||
|
||||
impl LineWrap {
|
||||
pub(super) fn height(&self, line_height: Pixels) -> Pixels {
|
||||
line_height * (self.wrap_lines + 1)
|
||||
}
|
||||
}
|
||||
|
||||
/// Used to prepare the text with soft_wrap to be get lines to displayed in the TextArea
|
||||
/// A line with soft wrapped lines info.
|
||||
#[derive(Clone)]
|
||||
pub(super) struct LineItem {
|
||||
/// The original line text.
|
||||
line: Rope,
|
||||
/// The soft wrapped lines relative byte range (0..line.len) of this line (Include first line).
|
||||
///
|
||||
/// After use lines to calculate the scroll size of the TextArea
|
||||
/// FIXME: Here in somecase, the `line_wrapper.wrap_line` has returned different
|
||||
/// like the `window.text_system().shape_text`. So, this value may not equal
|
||||
/// the actual rendered lines.
|
||||
wrapped_lines: Vec<Range<usize>>,
|
||||
}
|
||||
|
||||
impl LineItem {
|
||||
/// Get the bytes length of this line.
|
||||
#[inline]
|
||||
pub(super) fn len(&self) -> usize {
|
||||
self.line.len()
|
||||
}
|
||||
|
||||
/// Get number of soft wrapped lines of this line (include the first line).
|
||||
#[inline]
|
||||
pub(super) fn lines_len(&self) -> usize {
|
||||
self.wrapped_lines.len()
|
||||
}
|
||||
|
||||
/// Get the height of this line item with given line height.
|
||||
pub(super) fn height(&self, line_height: Pixels) -> Pixels {
|
||||
self.lines_len() as f32 * line_height
|
||||
}
|
||||
}
|
||||
|
||||
/// Used to prepare the text with soft wrap to be get lines to displayed in the Editor.
|
||||
///
|
||||
/// After use lines to calculate the scroll size of the Editor.
|
||||
pub(super) struct TextWrapper {
|
||||
pub(super) text: SharedString,
|
||||
/// The wrapped lines, value is start and end index of the line (by split \n).
|
||||
pub(super) wrapped_lines: Vec<Range<usize>>,
|
||||
/// The lines by split \n
|
||||
pub(super) lines: Vec<LineWrap>,
|
||||
pub(super) font: Font,
|
||||
pub(super) font_size: Pixels,
|
||||
text: Rope,
|
||||
/// Total wrapped lines (Inlucde the first line), value is start and end index of the line.
|
||||
soft_lines: usize,
|
||||
font: Font,
|
||||
font_size: Pixels,
|
||||
/// If is none, it means the text is not wrapped
|
||||
pub(super) wrap_width: Option<Pixels>,
|
||||
wrap_width: Option<Pixels>,
|
||||
/// The lines by split \n
|
||||
pub(super) lines: Vec<LineItem>,
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
impl TextWrapper {
|
||||
pub(super) fn new(font: Font, font_size: Pixels, wrap_width: Option<Pixels>) -> Self {
|
||||
Self {
|
||||
text: SharedString::default(),
|
||||
text: Rope::new(),
|
||||
font,
|
||||
font_size,
|
||||
wrap_width,
|
||||
wrapped_lines: Vec::new(),
|
||||
soft_lines: 0,
|
||||
lines: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(super) fn set_default_text(&mut self, text: &Rope) {
|
||||
self.text = text.clone();
|
||||
}
|
||||
|
||||
/// Get the total number of lines including wrapped lines.
|
||||
#[inline]
|
||||
pub(super) fn len(&self) -> usize {
|
||||
self.soft_lines
|
||||
}
|
||||
|
||||
/// Get the line item by row index.
|
||||
#[inline]
|
||||
pub(super) fn line(&self, row: usize) -> Option<&LineItem> {
|
||||
self.lines.get(row)
|
||||
}
|
||||
|
||||
pub(super) fn set_wrap_width(&mut self, wrap_width: Option<Pixels>, cx: &mut App) {
|
||||
self.wrap_width = wrap_width;
|
||||
self.update(&self.text.clone(), true, cx);
|
||||
}
|
||||
|
||||
pub(super) fn set_font(&mut self, font: Font, font_size: Pixels, cx: &mut App) {
|
||||
self.font = font;
|
||||
self.font_size = font_size;
|
||||
self.update(&self.text.clone(), true, cx);
|
||||
}
|
||||
|
||||
pub(super) fn update(&mut self, text: &SharedString, force: bool, cx: &mut App) {
|
||||
if &self.text == text && !force {
|
||||
if wrap_width == self.wrap_width {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut wrapped_lines = vec![];
|
||||
let mut lines = vec![];
|
||||
let wrap_width = self.wrap_width.unwrap_or(Pixels::MAX);
|
||||
self.wrap_width = wrap_width;
|
||||
self.update_all(&self.text.clone(), true, cx);
|
||||
}
|
||||
|
||||
pub(super) fn set_font(&mut self, font: Font, font_size: Pixels, cx: &mut App) {
|
||||
if self.font.eq(&font) && self.font_size == font_size {
|
||||
return;
|
||||
}
|
||||
|
||||
self.font = font;
|
||||
self.font_size = font_size;
|
||||
self.update_all(&self.text.clone(), true, cx);
|
||||
}
|
||||
|
||||
/// Update the text wrapper and recalculate the wrapped lines.
|
||||
///
|
||||
/// If the `text` is the same as the current text, do nothing.
|
||||
///
|
||||
/// - `changed_text`: The text [`Rope`] that has changed.
|
||||
/// - `range`: The `selected_range` before change.
|
||||
/// - `new_text`: The inserted text.
|
||||
/// - `force`: Whether to force the update, if false, the update will be skipped if the text is the same.
|
||||
/// - `cx`: The application context.
|
||||
pub(super) fn update(
|
||||
&mut self,
|
||||
changed_text: &Rope,
|
||||
range: &Range<usize>,
|
||||
new_text: &Rope,
|
||||
force: bool,
|
||||
cx: &mut App,
|
||||
) {
|
||||
let mut line_wrapper = cx
|
||||
.text_system()
|
||||
.line_wrapper(self.font.clone(), self.font_size);
|
||||
self._update(
|
||||
changed_text,
|
||||
range,
|
||||
new_text,
|
||||
force,
|
||||
&mut |line_str, wrap_width| {
|
||||
line_wrapper
|
||||
.wrap_line(&[LineFragment::text(line_str)], wrap_width)
|
||||
.collect()
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let mut prev_line_ix = 0;
|
||||
for line in text.split('\n') {
|
||||
let mut line_wraps = vec![];
|
||||
fn _update<F>(
|
||||
&mut self,
|
||||
changed_text: &Rope,
|
||||
range: &Range<usize>,
|
||||
new_text: &Rope,
|
||||
force: bool,
|
||||
wrap_line: &mut F,
|
||||
) where
|
||||
F: FnMut(&str, Pixels) -> Vec<gpui::Boundary>,
|
||||
{
|
||||
if self.text.eq(changed_text) && !force {
|
||||
return;
|
||||
}
|
||||
|
||||
// Remove the old changed lines.
|
||||
let start_row = self.text.offset_to_point(range.start).row as usize;
|
||||
let start_row = start_row.min(self.lines.len().saturating_sub(1));
|
||||
let end_row = self.text.offset_to_point(range.end).row as usize;
|
||||
let end_row = end_row.min(self.lines.len().saturating_sub(1));
|
||||
let rows_range = start_row..=end_row;
|
||||
|
||||
// To add the new lines.
|
||||
let new_start_row = changed_text.offset_to_point(range.start).row as usize;
|
||||
let new_start_offset = changed_text.line_start_offset(new_start_row);
|
||||
let new_end_row = changed_text
|
||||
.offset_to_point(range.start + new_text.len())
|
||||
.row as usize;
|
||||
let new_end_offset = changed_text.line_end_offset(new_end_row);
|
||||
let new_range = new_start_offset..new_end_offset;
|
||||
|
||||
let mut new_lines = vec![];
|
||||
|
||||
let wrap_width = self.wrap_width;
|
||||
|
||||
for line in changed_text.slice(new_range).lines() {
|
||||
let line_str = line.to_string();
|
||||
let mut wrapped_lines = vec![];
|
||||
let mut prev_boundary_ix = 0;
|
||||
|
||||
// If wrap_width is Pixels::MAX, skip wrapping to disable word wrap
|
||||
if let Some(wrap_width) = wrap_width {
|
||||
// Here only have wrapped line, if there is no wrap meet, the `line_wraps` result will empty.
|
||||
for boundary in line_wrapper.wrap_line(&[LineFragment::text(line)], wrap_width) {
|
||||
line_wraps.push(prev_boundary_ix..boundary.ix);
|
||||
for boundary in wrap_line(&line_str, wrap_width) {
|
||||
wrapped_lines.push(prev_boundary_ix..boundary.ix);
|
||||
prev_boundary_ix = boundary.ix;
|
||||
}
|
||||
}
|
||||
|
||||
lines.push(LineWrap {
|
||||
wrap_lines: line_wraps.len(),
|
||||
range: prev_line_ix..prev_line_ix + line.len(),
|
||||
});
|
||||
|
||||
wrapped_lines.extend(line_wraps);
|
||||
// Reset of the line
|
||||
if !line[prev_boundary_ix..].is_empty() || prev_boundary_ix == 0 {
|
||||
wrapped_lines.push(prev_line_ix + prev_boundary_ix..prev_line_ix + line.len());
|
||||
if !line_str[prev_boundary_ix..].is_empty() || prev_boundary_ix == 0 {
|
||||
wrapped_lines.push(prev_boundary_ix..line.len());
|
||||
}
|
||||
|
||||
prev_line_ix += line.len() + 1;
|
||||
new_lines.push(LineItem {
|
||||
line: line.clone(),
|
||||
wrapped_lines,
|
||||
});
|
||||
}
|
||||
|
||||
self.text = text.clone();
|
||||
self.wrapped_lines = wrapped_lines;
|
||||
self.lines = lines;
|
||||
// dbg!(&new_lines.len());
|
||||
// dbg!(self.lines.len());
|
||||
if self.lines.is_empty() {
|
||||
self.lines = new_lines;
|
||||
} else {
|
||||
self.lines.splice(rows_range, new_lines);
|
||||
}
|
||||
|
||||
// dbg!(self.lines.len());
|
||||
self.text = changed_text.clone();
|
||||
self.soft_lines = self.lines.iter().map(|l| l.lines_len()).sum();
|
||||
}
|
||||
|
||||
/// Update the text wrapper and recalculate the wrapped lines.
|
||||
///
|
||||
/// If the `text` is the same as the current text, do nothing.
|
||||
pub(crate) fn update_all(&mut self, text: &Rope, force: bool, cx: &mut App) {
|
||||
self.update(text, &(0..text.len()), text, force, cx);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -299,14 +299,16 @@ where
|
||||
|
||||
fn on_query_input_event(
|
||||
&mut self,
|
||||
_: &Entity<InputState>,
|
||||
state: &Entity<InputState>,
|
||||
event: &InputEvent,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
match event {
|
||||
InputEvent::Change(text) => {
|
||||
InputEvent::Change => {
|
||||
let text = state.read(cx).value();
|
||||
let text = text.trim().to_string();
|
||||
|
||||
if Some(&text) == self.last_query.as_ref() {
|
||||
return;
|
||||
}
|
||||
@@ -347,7 +349,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
fn set_querying(&mut self, querying: bool, _: &mut Window, cx: &mut Context<Self>) {
|
||||
fn set_querying(&mut self, querying: bool, _window: &mut Window, cx: &mut Context<Self>) {
|
||||
self.querying = querying;
|
||||
if let Some(input) = &self.query_input {
|
||||
input.update(cx, |input, cx| input.set_loading(querying, cx))
|
||||
|
||||
@@ -13,7 +13,7 @@ use regex::Regex;
|
||||
use registry::Registry;
|
||||
use theme::ActiveTheme;
|
||||
|
||||
use crate::actions::OpenProfile;
|
||||
use crate::actions::OpenPublicKey;
|
||||
|
||||
static URL_REGEX: Lazy<Regex> = Lazy::new(|| {
|
||||
Regex::new(r"^(?:[a-zA-Z]+://)?([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}(:\d+)?(/.*)?$").unwrap()
|
||||
@@ -140,7 +140,7 @@ impl RenderedText {
|
||||
log::error!("Failed to parse public key from: {clean_url}");
|
||||
return;
|
||||
};
|
||||
window.dispatch_action(Box::new(OpenProfile(public_key)), cx);
|
||||
window.dispatch_action(Box::new(OpenPublicKey(public_key)), cx);
|
||||
} else if is_url(token) {
|
||||
if !token.starts_with("http") {
|
||||
cx.open_url(&format!("https://{token}"));
|
||||
|
||||
+3
-3
@@ -272,9 +272,11 @@ profile:
|
||||
unknown:
|
||||
en: "Unknown contact"
|
||||
njump:
|
||||
en: "Open in njump.me"
|
||||
en: "View on njump.me"
|
||||
no_bio:
|
||||
en: "No bio."
|
||||
copy:
|
||||
en: "Copy Public Key"
|
||||
|
||||
preferences:
|
||||
account_header:
|
||||
@@ -329,8 +331,6 @@ compose:
|
||||
en: "Your recently contacts will appear here."
|
||||
contact_existed:
|
||||
en: "Contact already added"
|
||||
receiver_required:
|
||||
en: "You need to add at least 1 receiver"
|
||||
description:
|
||||
en: "Start a conversation with someone using their npub or NIP-05 (like foo@bar.com)."
|
||||
subject_label:
|
||||
|
||||
Executable
+135
@@ -0,0 +1,135 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Script to release a new version of the application
|
||||
# Usage: ./release <new_version>
|
||||
|
||||
set -e # Exit on any error
|
||||
|
||||
if [ $# -ne 1 ]; then
|
||||
echo "Usage: $0 <new_version>"
|
||||
echo "Example: $0 1.0.0"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
NEW_VERSION="$1"
|
||||
WORKSPACE_CARGO="Cargo.toml"
|
||||
CRATE_CARGO="crates/coop/Cargo.toml"
|
||||
|
||||
# Check if both Cargo.toml files exist
|
||||
if [ ! -f "$WORKSPACE_CARGO" ]; then
|
||||
echo "Error: $WORKSPACE_CARGO not found in current directory"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ ! -f "$CRATE_CARGO" ]; then
|
||||
echo "Error: $CRATE_CARGO not found"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Function to update version in a Cargo.toml file
|
||||
update_version() {
|
||||
local file="$1"
|
||||
local backup="${file}.bak"
|
||||
|
||||
# Backup the original file
|
||||
cp "$file" "$backup"
|
||||
|
||||
# Replace the version in Cargo.toml
|
||||
if sed -i.bak -E "s/^version = \"[0-9]+\.[0-9]+\.[0-9]+\"/version = \"$NEW_VERSION\"/" "$file"; then
|
||||
echo "✓ Updated version to $NEW_VERSION in $file"
|
||||
# Remove backup created by sed
|
||||
if [ -f "${file}.bak" ]; then
|
||||
rm "${file}.bak"
|
||||
fi
|
||||
else
|
||||
echo "Error: Failed to update version in $file"
|
||||
# Restore original backup
|
||||
mv "$backup" "$file"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Remove the initial backup file
|
||||
rm -f "$backup"
|
||||
}
|
||||
|
||||
# Update both Cargo.toml files
|
||||
echo "Updating versions..."
|
||||
update_version "$WORKSPACE_CARGO"
|
||||
update_version "$CRATE_CARGO"
|
||||
|
||||
# Check git status before committing
|
||||
echo "Checking git status..."
|
||||
if git status --porcelain | grep -q .; then
|
||||
echo "Current uncommitted changes:"
|
||||
git status --short
|
||||
|
||||
# Ask user if they want to commit all changes or just version files
|
||||
echo ""
|
||||
echo "Do you want to:"
|
||||
echo "1) Commit all current changes (including the version updates)"
|
||||
echo "2) Commit only the version file changes"
|
||||
echo "3) Abort the release"
|
||||
read -p "Enter choice (1/2/3): " choice
|
||||
|
||||
case $choice in
|
||||
1)
|
||||
echo "Committing all changes..."
|
||||
git add .
|
||||
;;
|
||||
2)
|
||||
echo "Committing only version file changes..."
|
||||
git add "$WORKSPACE_CARGO" "$CRATE_CARGO"
|
||||
;;
|
||||
3)
|
||||
echo "Release aborted by user"
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
echo "Invalid choice. Release aborted."
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
else
|
||||
# Only version files were modified, add them specifically
|
||||
echo "Only version files were modified, adding them for commit..."
|
||||
git add "$WORKSPACE_CARGO" "$CRATE_CARGO"
|
||||
fi
|
||||
|
||||
# Commit the changes
|
||||
COMMIT_MSG="chore: release version $NEW_VERSION"
|
||||
|
||||
if git commit -m "$COMMIT_MSG"; then
|
||||
echo "✓ Committed version changes"
|
||||
else
|
||||
echo "Error: Failed to commit version changes"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Push version changes to origin
|
||||
echo "Pushing version changes to origin..."
|
||||
if git push origin master; then
|
||||
echo "✓ Successfully pushed version changes to origin"
|
||||
else
|
||||
echo "Error: Failed to push version changes to origin"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Create git tag
|
||||
TAG_NAME="v$NEW_VERSION"
|
||||
|
||||
if git tag -a "$TAG_NAME" -m "$COMMIT_MSG"; then
|
||||
echo "✓ Created git tag: $TAG_NAME"
|
||||
else
|
||||
echo "Error: Failed to create git tag"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Push tag to origin
|
||||
echo "Pushing tag to origin..."
|
||||
if git push origin "$TAG_NAME"; then
|
||||
echo "✓ Successfully pushed tag to origin"
|
||||
echo "✓ Release $NEW_VERSION completed successfully!"
|
||||
else
|
||||
echo "Error: Failed to push tag to origin"
|
||||
exit 1
|
||||
fi
|
||||
Reference in New Issue
Block a user