BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-state / src / app_state.rs

app_state.rs

app_state.rs 49.3 KiB Download Raw
1use std::collections::{HashMap, HashSet};
2use std::sync::Arc;
3use std::time::Instant;
4
5use chatsvc::TypingEvent;
6use chrono::{DateTime, Utc};
7use gpui_kit::*;
8use store::{ChatRecord, Sidebar, Store};
9use teams_core::{
10 ChatApp, ChatSection, ChatSectionSettings, CoreEvent, ImageRef, PinnedMessage, PresenceStatus,
11 ScheduledDraft,
12};
13
14use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};
15use crate::call::{ActiveCall, CallLauncher, CallMedia, MissedCall, Rings};
16use crate::card_state::{CardState, TaskDialogState};
17use crate::data::{self, Directory};
18use crate::forward_selection::ForwardSelection;
19use crate::image_view_gallery::ViewerRequest;
20use crate::local_previews::{LocalPreview, load_local_previews};
21use crate::message_actions::{ForwardSource, SavedSet};
22use crate::notice::Notice;
23use crate::notify::LateArrivals;
24use crate::profile_state::{ProfileCache, ProfileRequest};
25use crate::translation::TranslationState;
26use crate::typing::TypingState;
27use calling::meeting::LiveMeeting;
28
29const COLLAPSED_META_KEY: &str = "ui.collapsed_sections";
30const RECENT_MESSAGES_FOR_TYPING: usize = 5;
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum QuickView {
34 Mentions,
35 Drafts,
36 Saved,
37}
38
39impl QuickView {
40 pub fn title(self) -> &'static str {
41 match self {
42 QuickView::Mentions => "Mentions",
43 QuickView::Drafts => "Drafts",
44 QuickView::Saved => "Saved",
45 }
46 }
47
48 pub fn empty_text(self) -> &'static str {
49 match self {
50 QuickView::Mentions => "No mentions yet. When someone @mentions you, it shows up here.",
51 QuickView::Drafts => "No drafts. Messages you start and do not send show up here.",
52 QuickView::Saved => "No saved messages. Use Save message in the ... menu of a message.",
53 }
54 }
55}
56
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub enum Selection {
59 Chat(String),
60 Channel(String),
61}
62
63impl Selection {
64 pub fn conversation_id(&self) -> &str {
65 match self {
66 Selection::Chat(id) | Selection::Channel(id) => id,
67 }
68 }
69}
70
71pub enum AppEvent {
72 Sidebar,
73 Activity,
74 Selection,
75 Messages(String),
76 Images(Vec<String>),
77 Jump,
78 Status,
79 Directory,
80 Cards(String),
81 TaskDialog,
82 Typing,
83 LocalPreviews,
84 Outbox(String),
85 Scheduled,
86 Pins(String),
87 Saved,
88 CallHistory,
89 Translation,
90 Forward,
91 ForwardSelection,
92 ImageViewer,
93 StatusMessage,
94 Settings(crate::settings_section::SettingsSection),
95 Profile,
96 Call,
97 Ring,
98 LiveMeeting,
99 MissedCall(MissedCall),
100 MeetingReminder,
101 MeetingChime,
102 CallTone(chatsvc::sounds::CallTone),
103 SoundSettings,
104 ChatSettings,
105 FollowedStatus {
106 user_id: String,
107 text: &'static str,
108 },
109}
110
111#[derive(Debug, Clone, Copy, Default)]
112pub struct Mode {
113 pub demo: bool,
114 pub read_only: bool,
115 pub demo_sync: Option<std::time::Duration>,
116}
117
118pub struct AppState {
119 pub store: Arc<Store>,
120 pub engine: Option<Arc<Engine>>,
121 pub sidebar: Sidebar,
122 pub favorite_ids: Vec<String>,
123 pub selection: Option<Selection>,
124 pub late_arrivals: LateArrivals,
125 pub acked_urgent: std::collections::HashSet<String>,
126 pub new_chat: bool,
127 pub new_chat_people: Vec<store::MemberRecord>,
128 pub connection: ConnectionState,
129 pub live: LiveState,
130 pub last_sync: Option<DateTime<Utc>>,
131 pub mode: Mode,
132 pub directory: Directory,
133 pub collapsed: HashSet<String>,
134 pub expanded_lists: HashSet<String>,
135 pub start_on_channels: bool,
136 pub pending_jump: Option<(String, String)>,
137 pub cards: CardState,
138 pub task_dialog: Option<TaskDialogState>,
139 pub bot_apps: HashMap<String, Vec<ChatApp>>,
140 pub bot_apps_pending: HashSet<String>,
141 pub notice: Option<Notice>,
142 pub connection_banner: crate::connection_banner::BannerTiming,
143 pub live_retry: Option<Arc<tokio::sync::Notify>>,
144 pub notice_count: u64,
145 pub followed_presence: Vec<crate::presence_follow::FollowedPerson>,
146 pub followed_changes: Vec<(String, &'static str)>,
147 pub keep_unread: Option<String>,
148 pub restorable_deletes: crate::restorable_deletes::RestorableDeletes,
149 pub typing: TypingState,
150 typing_timer_running: bool,
151 pub local_previews: HashMap<String, LocalPreview>,
152 pub quick_view: Option<QuickView>,
153 pub scheduled: Vec<ScheduledDraft>,
154 pub scheduled_polling: bool,
155 pub saved: SavedSet,
156 pub call_history: Vec<teams_core::CallLogEntry>,
157 pub calendar_events: Vec<chatsvc::CalendarEvent>,
158 pub calendar_nudge: Option<tokio::sync::mpsc::UnboundedSender<()>>,
159 pub calls_list: crate::call::CallsList,
160 pub speed_dial: Vec<crate::call::SpeedDialEntry>,
161 pub pins: HashMap<String, Vec<PinnedMessage>>,
162 pub post_follows: crate::post_follow::PostFollows,
163 pub forward_request: Option<ForwardSource>,
164 pub forward_selection: Option<ForwardSelection>,
165 pub image_viewer_request: Option<ViewerRequest>,
166 pub own_status: PresenceStatus,
167 pub notifications_paused_until: Option<chrono::DateTime<chrono::Utc>>,
168 pub own_email: String,
169 pub own_time_zone: Option<String>,
170 pub own_time_zone_requested: bool,
171 pub status_menu_open: bool,
172 pub status_message_request: bool,
173 pub profiles: ProfileCache,
174 pub profile_request: Option<ProfileRequest>,
175 pub call: Option<ActiveCall>,
176 pub held_call: Option<ActiveCall>,
177 pub call_end: Option<crate::call::end_screen::CallEndScreen>,
178 pub call_media: Option<Entity<CallMedia>>,
179 pub call_launcher: Option<Arc<CallLauncher>>,
180 pub call_count: u64,
181 pub call_share_sound: bool,
182 pub recording_policy: teams_core::RecordingPolicy,
183 pub allow_priority_messages: bool,
184 pub account_sounds: Option<chatsvc::sound_settings::SoundSettings>,
185 pub chat_settings: teams_core::ChatSettingsDocument,
186 pub markdown_mode: bool,
187 pub actions_on_right_click: bool,
188 pub web_calls: bool,
189 pub own_engine_next_call: bool,
190 pub demo_chat_desktop: HashMap<String, teams_core::DesktopNotifications>,
191 pub own_tenant: Option<String>,
192 pub call_share_motion: bool,
193 pub call_share_standout: bool,
194 pub call_report_enabled: bool,
195 pub call_strip_width: f32,
196 pub call_view: crate::call::ViewSettings,
197 pub call_background: crate::call::BackgroundPick,
198 pub call_camera: calling::DeviceChoice,
199 pub call_input: calling::DeviceChoice,
200 pub call_output: calling::DeviceChoice,
201 pub call_mic: calling::MicSettings,
202 pub call_effects: calling::CameraEffects,
203 pub meet_now_pending: bool,
204 pub prejoin: Option<crate::call::PendingJoin>,
205 pub prejoin_count: u64,
206 pub join_options: crate::call::JoinOptions,
207 pub rsvp_send_response: bool,
208 pub meeting_toasts: crate::call::MeetingToasts,
209 pub demo_meetings: Vec<chatsvc::CalendarEvent>,
210 pub calendar_week: crate::call::week::CalendarWeek,
211 pub call_backgrounds: crate::call::BackgroundLibrary,
212 pub transfer_picker: Option<AnyView>,
213 pub transcript_panel: Option<AnyView>,
214 pub rings: Rings,
215 pub live_meetings: HashMap<String, LiveMeeting>,
216 pub live_refreshing: HashSet<String>,
217 pub translation: TranslationState,
218 pub section_changes: crate::section_actions::SectionChanges,
219}
220
221pub struct AppHandle(pub Entity<AppState>);
222
223impl Global for AppHandle {}
224
225impl EventEmitter<AppEvent> for AppState {}
226
227pub fn selection_for(sidebar: &Sidebar, conversation_id: &str) -> Option<Selection> {
228 if sidebar.chats.iter().any(|chat| chat.id == conversation_id) {
229 return Some(Selection::Chat(conversation_id.to_owned()));
230 }
231 sidebar
232 .teams
233 .iter()
234 .flat_map(|team| team.channels.iter())
235 .any(|channel| channel.id == conversation_id)
236 .then(|| Selection::Channel(conversation_id.to_owned()))
237}
238
239pub fn chat_title(chat: &ChatRecord) -> String {
240 chat.display_title()
241}
242
243pub fn selection_title(sidebar: &Sidebar, selection: &Selection) -> String {
244 match selection {
245 Selection::Chat(id) => sidebar
246 .chats
247 .iter()
248 .find(|chat| &chat.id == id)
249 .map(chat_title)
250 .unwrap_or_else(|| "Chat".to_owned()),
251 Selection::Channel(id) => sidebar
252 .teams
253 .iter()
254 .find_map(|team| {
255 team.channels
256 .iter()
257 .find(|channel| &channel.id == id)
258 .map(|channel| format!("{} / {}", team.team.name, channel.name))
259 })
260 .unwrap_or_else(|| "Channel".to_owned()),
261 }
262}
263
264impl AppState {
265 pub fn new(store: Arc<Store>, mode: Mode) -> Self {
266 let sidebar = store.sidebar().unwrap_or_default();
267 let speed_dial = crate::call::speed_dial::load(&store);
268 let notifications_paused_until = crate::notify::pause::load(&store);
269 let chat_settings = teams_core::stored_chat_settings(&store);
270 let markdown_mode = crate::chat_settings_actions::stored_markdown_mode(&store);
271 let actions_on_right_click =
272 crate::chat_settings_actions::stored_actions_on_right_click(&store);
273 let web_calls = crate::call::web_call::stored_web_calls(&store);
274 let mut state = AppState {
275 store,
276 engine: None,
277 sidebar,
278 favorite_ids: Vec::new(),
279 selection: None,
280 late_arrivals: LateArrivals::default(),
281 acked_urgent: Default::default(),
282 new_chat: false,
283 new_chat_people: Vec::new(),
284 connection: if mode.demo {
285 ConnectionState::Online
286 } else {
287 ConnectionState::Connecting
288 },
289 live: LiveState::Off,
290 last_sync: None,
291 mode,
292 directory: Directory::default(),
293 collapsed: HashSet::new(),
294 expanded_lists: HashSet::new(),
295 start_on_channels: false,
296 pending_jump: None,
297 cards: CardState::default(),
298 task_dialog: None,
299 bot_apps: HashMap::new(),
300 bot_apps_pending: HashSet::new(),
301 notice: None,
302 connection_banner: Default::default(),
303 live_retry: None,
304 notice_count: 0,
305 followed_presence: Vec::new(),
306 followed_changes: Vec::new(),
307 keep_unread: None,
308 restorable_deletes: Default::default(),
309 typing: TypingState::default(),
310 typing_timer_running: false,
311 local_previews: HashMap::new(),
312 quick_view: None,
313 scheduled: Vec::new(),
314 scheduled_polling: false,
315 saved: SavedSet::default(),
316 call_history: Vec::new(),
317 calendar_events: Vec::new(),
318 calendar_nudge: None,
319 calls_list: crate::call::CallsList::default(),
320 speed_dial,
321 pins: HashMap::new(),
322 post_follows: Default::default(),
323 forward_request: None,
324 forward_selection: None,
325 image_viewer_request: None,
326 own_status: PresenceStatus::default(),
327 notifications_paused_until,
328 own_email: String::new(),
329 own_time_zone: None,
330 own_time_zone_requested: false,
331 status_menu_open: false,
332 status_message_request: false,
333 profiles: ProfileCache::new(),
334 profile_request: None,
335 call: None,
336 call_end: None,
337 held_call: None,
338 call_media: None,
339 call_launcher: None,
340 call_count: 0,
341 call_share_sound: false,
342 recording_policy: teams_core::RecordingPolicy::default(),
343 allow_priority_messages: true,
344 account_sounds: None,
345 chat_settings,
346 markdown_mode,
347 actions_on_right_click,
348 web_calls,
349 own_engine_next_call: false,
350 demo_chat_desktop: HashMap::new(),
351 own_tenant: None,
352 call_share_motion: false,
353 call_share_standout: false,
354 call_report_enabled: true,
355 call_strip_width: crate::call::STRIP_DEFAULT_WIDTH,
356 call_view: crate::call::ViewSettings::default(),
357 call_background: crate::call::BackgroundPick::None,
358 call_camera: calling::DeviceChoice::SystemDefault,
359 call_input: calling::DeviceChoice::SystemDefault,
360 call_output: calling::DeviceChoice::SystemDefault,
361 call_mic: calling::MicSettings::default(),
362 call_effects: calling::CameraEffects::default(),
363 meet_now_pending: false,
364 prejoin: None,
365 prejoin_count: 0,
366 join_options: crate::call::JoinOptions::default(),
367 rsvp_send_response: true,
368 meeting_toasts: crate::call::MeetingToasts::default(),
369 demo_meetings: Vec::new(),
370 calendar_week: crate::call::week::CalendarWeek::default(),
371 call_backgrounds: if mode.demo {
372 crate::call::demo_library()
373 } else {
374 crate::call::BackgroundLibrary::new(crate::call::default_cache_directory())
375 },
376 transfer_picker: None,
377 transcript_panel: None,
378 rings: Rings::default(),
379 live_meetings: HashMap::new(),
380 live_refreshing: HashSet::new(),
381 translation: TranslationState::default(),
382 section_changes: crate::section_actions::SectionChanges::default(),
383 };
384 state.local_previews = load_local_previews(&state.store);
385 state.followed_presence = crate::presence_follow::load_followed(&state.store);
386 state.collapsed = state.load_collapsed();
387 state.call_share_sound = crate::call::load_share_sound(&state.store);
388 state.call_share_motion = crate::call::load_flag(&state.store, crate::call::SHARE_MOTION_META_KEY);
389 state.call_share_standout = crate::call::load_flag(&state.store, crate::call::SHARE_STANDOUT_META_KEY);
390 state.call_report_enabled = crate::call::load_report_enabled(&state.store);
391 state.call_strip_width = crate::call::load_strip_width(&state.store);
392 state.call_view = crate::call::ViewSettings::load(&state.store);
393 state.call_background = crate::call::load_background(&state.store);
394 state.call_camera = crate::call::load_camera(&state.store);
395 state.call_input = crate::call::load_input(&state.store);
396 state.call_output = crate::call::load_output(&state.store);
397 crate::call::apply_sound_output(&state.call_output);
398 state.call_mic = crate::call::load_mic(&state.store);
399 state.call_effects = crate::call::load_camera_effects(&state.store);
400 state.join_options = crate::call::load_join_options(&state.store);
401 state.call_backgrounds.customs = crate::call::load_custom_backgrounds(&state.store);
402 state.load_cached_translation_settings();
403 if !mode.demo {
404 state.directory.load_cached_presence(&state.store);
405 state.reload_directory();
406 }
407 state
408 }
409
410 fn load_collapsed(&self) -> HashSet<String> {
411 self.store
412 .meta(COLLAPSED_META_KEY)
413 .ok()
414 .flatten()
415 .map(|value| {
416 value
417 .lines()
418 .map(str::to_owned)
419 .filter(|id| !id.is_empty())
420 .collect()
421 })
422 .unwrap_or_default()
423 }
424
425 pub fn toggle_collapsed(&mut self, section_id: &str, cx: &mut Context<Self>) {
426 if data::is_pending_folder(section_id) {
427 return;
428 }
429 let now_collapsed = self.collapsed.insert(section_id.to_owned());
430 if !now_collapsed {
431 self.collapsed.remove(section_id);
432 }
433 self.save_collapsed();
434 self.sync_folder_expanded(section_id, !now_collapsed);
435 cx.emit(AppEvent::Sidebar);
436 cx.notify();
437 }
438
439 pub fn collapse_sections(&mut self, section_ids: &[String], cx: &mut Context<Self>) {
440 let newly_collapsed: Vec<String> = section_ids
441 .iter()
442 .filter(|id| !data::is_pending_folder(id) && !self.collapsed.contains(*id))
443 .cloned()
444 .collect();
445 if newly_collapsed.is_empty() {
446 return;
447 }
448 for id in &newly_collapsed {
449 self.collapsed.insert(id.clone());
450 self.sync_folder_expanded(id, false);
451 }
452 self.save_collapsed();
453 cx.emit(AppEvent::Sidebar);
454 cx.notify();
455 }
456
457 pub fn mark_all_chats_read(&mut self, cx: &mut Context<Self>) {
458 let unread: Vec<String> = self
459 .sidebar
460 .chats
461 .iter()
462 .filter(|chat| chat.unread)
463 .map(|chat| chat.id.clone())
464 .collect();
465 for conversation_id in unread {
466 self.mark_chat_read(&conversation_id, cx);
467 }
468 }
469
470 pub fn older_chats(&self) -> (bool, bool) {
471 self.engine.as_ref().map_or((false, false), |engine| {
472 (engine.has_older_chats(), engine.is_loading_older_chats())
473 })
474 }
475
476 pub fn request_older_chats(&self) {
477 let Some(engine) = self.engine.clone() else {
478 return;
479 };
480 if !engine.has_older_chats() || engine.is_loading_older_chats() {
481 return;
482 }
483 drop(crate::runtime::spawn(async move {
484 if let Err(error) = engine.load_older_chats().await {
485 crate::diagnostics::record(format!("sync: older chats not loaded: {error}"));
486 }
487 }));
488 }
489
490 pub fn toggle_list_expanded(&mut self, section_id: &str, cx: &mut Context<Self>) {
491 if !self.expanded_lists.remove(section_id) {
492 self.expanded_lists.insert(section_id.to_owned());
493 }
494 cx.emit(AppEvent::Sidebar);
495 cx.notify();
496 }
497
498 fn save_collapsed(&self) {
499 let mut ids: Vec<&str> = self.collapsed.iter().map(String::as_str).collect();
500 ids.sort_unstable();
501 let _ = self.store.set_meta(COLLAPSED_META_KEY, &ids.join("\n"));
502 }
503
504 fn sync_folder_expanded(&mut self, folder_id: &str, expanded: bool) {
505 let Some(folder) = self
506 .directory
507 .folders
508 .iter_mut()
509 .find(|folder| folder.id == folder_id && folder.expanded.is_some())
510 else {
511 return;
512 };
513 folder.expanded = Some(expanded);
514 let _ = self.store.set_folder_expanded(folder_id, expanded);
515 if let Some(engine) = self.engine.clone().filter(|_| !self.mode.read_only) {
516 let folder_id = folder_id.to_owned();
517 drop(crate::runtime::spawn(async move {
518 engine.set_folder_expanded(&folder_id, expanded).await
519 }));
520 }
521 }
522
523 fn adopt_folder_expanded(&mut self) {
524 let snapshot = self.collapsed.clone();
525 for folder in &self.directory.folders {
526 match folder.expanded {
527 Some(true) => {
528 self.collapsed.remove(&folder.id);
529 }
530 Some(false) => {
531 self.collapsed.insert(folder.id.clone());
532 }
533 None => {}
534 }
535 }
536 if self.collapsed != snapshot {
537 self.save_collapsed();
538 }
539 }
540
541 pub fn set_chat_section(
542 &mut self,
543 section: ChatSection,
544 enabled: bool,
545 cx: &mut Context<Self>,
546 ) {
547 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
548 return;
549 };
550 let previous = self.directory.section_settings;
551 let mut updated = previous;
552 updated.set(section, enabled);
553 self.apply_section_settings(updated, cx);
554 let Some(engine) = engine_or_demo else {
555 return;
556 };
557 self.run_chat_action(
558 "Chat list setting",
559 async move { engine.set_section_enabled(section, enabled).await },
560 move |state, cx| state.apply_section_settings(previous, cx),
561 |_, _| {},
562 cx,
563 );
564 }
565
566 pub fn set_skin_tone(&mut self, tone: u8, cx: &mut Context<Self>) {
567 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
568 return;
569 };
570 let previous = teams_core::skin_tone(&self.store);
571 let _ = teams_core::store_account_skin_tone(&self.store, tone);
572 let Some(engine) = engine_or_demo else {
573 return;
574 };
575 self.run_chat_action(
576 "Skin tone",
577 async move { engine.set_skin_tone(tone).await },
578 move |state, _| {
579 let _ = teams_core::store_account_skin_tone(&state.store, previous);
580 },
581 |_, _| {},
582 cx,
583 );
584 }
585
586 fn apply_section_settings(&mut self, settings: ChatSectionSettings, cx: &mut Context<Self>) {
587 self.directory.section_settings = settings;
588 let _ = teams_core::store_section_settings(&self.store, &settings);
589 cx.emit(AppEvent::Sidebar);
590 cx.notify();
591 }
592
593 pub fn reload_directory(&mut self) {
594 self.directory.me = data::me(&self.store);
595 self.own_email = self
596 .store
597 .meta("me_email")
598 .ok()
599 .flatten()
600 .unwrap_or_default();
601 self.directory.folders = data::folders(&self.store, &self.favorite_ids);
602 self.reapply_section_changes();
603 self.directory.section_settings = teams_core::stored_section_settings(&self.store);
604 self.adopt_folder_expanded();
605 self.directory.pinned_channels = data::pinned_channels(&self.store);
606 if self.directory.pinned_channels.is_empty() {
607 let known: HashSet<&str> = self
608 .sidebar
609 .teams
610 .iter()
611 .flat_map(|team| team.channels.iter().map(|channel| channel.id.as_str()))
612 .collect();
613 self.directory.pinned_channels = self
614 .favorite_ids
615 .iter()
616 .filter(|id| known.contains(id.as_str()))
617 .cloned()
618 .collect();
619 }
620 self.resolve_pending_avatars();
621 self.sync_presence();
622 self.directory.unread_counts = match &self.engine {
623 Some(engine) => data::unread_counts(engine, &self.sidebar.chats),
624 None => Default::default(),
625 };
626 self.directory.unread_importance = match &self.engine {
627 Some(engine) => data::unread_importance(engine, &self.sidebar.chats),
628 None => Default::default(),
629 };
630 }
631
632 pub fn request_avatars(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) {
633 let wanted = self.directory.missing_avatars(user_ids);
634 if wanted.is_empty() {
635 return;
636 }
637 let mut changed = false;
638 let mut uncached = Vec::new();
639 for user_id in wanted {
640 match data::cached_avatar(&self.store, &user_id) {
641 Some(cached) => {
642 self.directory.set_avatar(&user_id, cached);
643 changed = true;
644 }
645 None => uncached.push(user_id),
646 }
647 }
648 if let Some(engine) = self.engine.clone().filter(|_| !uncached.is_empty()) {
649 self.directory.mark_avatars_pending(&uncached);
650 let done = data::fetch_avatars(&engine, uncached);
651 self.on_done(done, cx, |state, cx| {
652 state.resolve_pending_avatars();
653 cx.emit(AppEvent::Directory);
654 cx.notify();
655 });
656 changed = true;
657 }
658 if changed {
659 cx.emit(AppEvent::Directory);
660 cx.notify();
661 }
662 }
663
664 pub fn request_images(&mut self, images: Vec<ImageRef>, cx: &mut Context<Self>) {
665 let Some(engine) = self.engine.clone() else {
666 return;
667 };
668 let wanted = self
669 .directory
670 .images_to_request(images.iter().map(|image| image.url.clone()));
671 let mut changed = false;
672 for image in images
673 .into_iter()
674 .filter(|image| wanted.contains(&image.url))
675 {
676 match engine.image_path(&image) {
677 Some(path) => {
678 self.directory.set_image(&image.url, &path);
679 changed = true;
680 }
681 None => {
682 let done = data::fetch_image(&engine, image.clone());
683 cx.spawn(async move |this, cx| {
684 let failure = match done.await {
685 Ok(Ok(())) => None,
686 Ok(Err(error)) => Some(error),
687 Err(_) => Some("cancelled".to_owned()),
688 };
689 if let Some(failure) = failure {
690 let host = image.url.split("://").nth(1).and_then(|rest| rest.split('/').next()).unwrap_or_default();
691 log::warn!("image from {host} not loaded: {failure}");
692 this.update(cx, |state, cx| {
693 state.directory.mark_image_failed(&image.url);
694 cx.notify();
695 })
696 .ok();
697 }
698 })
699 .detach();
700 }
701 }
702 }
703 if changed {
704 cx.emit(AppEvent::Images(wanted));
705 cx.notify();
706 }
707 }
708
709 pub fn jump_to_message(
710 &mut self,
711 selection: Selection,
712 message_id: String,
713 cx: &mut Context<Self>,
714 ) {
715 self.pending_jump = Some((selection.conversation_id().to_owned(), message_id));
716 if self.selection.as_ref() == Some(&selection) {
717 cx.emit(AppEvent::Jump);
718 } else {
719 self.select(selection, cx);
720 }
721 }
722
723 fn on_done(
724 &self,
725 done: data::Done,
726 cx: &mut Context<Self>,
727 then: impl FnOnce(&mut Self, &mut Context<Self>) + 'static,
728 ) {
729 cx.spawn(async move |this, cx| {
730 let _ = done.await;
731 this.update(cx, |state, cx| then(state, cx)).ok();
732 })
733 .detach();
734 }
735
736 fn resolve_pending_avatars(&mut self) {
737 for user_id in self.directory.pending_avatars() {
738 if let Some(cached) = data::cached_avatar(&self.store, &user_id) {
739 self.directory.set_avatar(&user_id, cached);
740 }
741 }
742 }
743
744 fn sync_presence(&mut self) -> Vec<String> {
745 let Some(engine) = self.engine.clone() else {
746 return Vec::new();
747 };
748 self.directory
749 .requested_presence_ids()
750 .into_iter()
751 .filter(|user_id| {
752 let Some(kind) = data::presence_kind(&engine, user_id) else {
753 return false;
754 };
755 let activity_changed = self
756 .directory
757 .set_activity(user_id, data::presence_activity(&engine, user_id));
758 let previous = self.directory.presence_of(user_id);
759 let changed = self.directory.set_presence(user_id, kind);
760 if changed {
761 self.note_followed_change(user_id, previous, kind);
762 }
763 changed || activity_changed
764 })
765 .collect()
766 }
767
768 pub fn request_presence(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) {
769 let now = Instant::now();
770 let pushed = self.live == LiveState::Live;
771 let wanted = self.directory.stale_presence(user_ids, now, pushed);
772 if wanted.is_empty() {
773 return;
774 }
775 self.directory.mark_presence_pending(&wanted);
776 if let Some(engine) = self.engine.clone() {
777 self.directory.mark_presence_requested(&wanted, now);
778 drop(data::watch_presence(&engine, wanted.clone()));
779 let done = data::refresh_presence(&engine, wanted.clone());
780 self.on_done(done, cx, move |state, cx| {
781 state.sync_presence();
782 state.announce_followed_changes(cx);
783 state.directory.save_presence(&state.store, &wanted);
784 state.directory.settle_presence(&wanted);
785 cx.emit(AppEvent::Directory);
786 cx.notify();
787 });
788 }
789 }
790
791 pub fn move_chat(
792 &mut self,
793 conversation_id: &str,
794 folder_id: Option<&str>,
795 cx: &mut Context<Self>,
796 ) {
797 self.place_chat(conversation_id, folder_id, None, cx);
798 }
799
800 pub fn drop_chat_on(
801 &mut self,
802 conversation_id: &str,
803 target_conversation_id: &str,
804 folder_id: &str,
805 cx: &mut Context<Self>,
806 ) {
807 if conversation_id == target_conversation_id {
808 return;
809 }
810 let Some(slot) = self.directory.slot_of(folder_id, target_conversation_id) else {
811 return;
812 };
813 self.place_chat(conversation_id, Some(folder_id), Some(slot), cx);
814 }
815
816 pub fn place_chat(
817 &mut self,
818 conversation_id: &str,
819 folder_id: Option<&str>,
820 index: Option<usize>,
821 cx: &mut Context<Self>,
822 ) {
823 if self.mode.read_only {
824 return;
825 }
826 let previous_folder = self
827 .directory
828 .folder_of(conversation_id)
829 .map(|folder| folder.id.clone());
830 self.directory.place(conversation_id, folder_id, index);
831 if let Some(engine) = self.engine.clone() {
832 let previous = previous_folder.clone();
833 let done = match (folder_id, previous.as_deref()) {
834 (Some(folder_id), _) => Some(data::move_to_folder(
835 &engine,
836 conversation_id,
837 folder_id,
838 index,
839 )),
840 (None, Some(previous)) => {
841 Some(data::remove_from_folder(&engine, conversation_id, previous))
842 }
843 (None, None) => None,
844 };
845 if let Some(done) = done {
846 self.on_done(done, cx, |state, cx| {
847 state.reload_directory();
848 cx.emit(AppEvent::Sidebar);
849 cx.notify();
850 });
851 }
852 }
853 cx.emit(AppEvent::Sidebar);
854 cx.notify();
855 }
856
857 pub fn mark_chat_read(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
858 if self.keeps_unread(conversation_id) {
859 self.keep_unread = None;
860 }
861 if self.mode.demo {
862 if let Some(chat) = self
863 .sidebar
864 .chats
865 .iter()
866 .find(|chat| chat.id == conversation_id)
867 {
868 let mut read = chat.clone();
869 read.unread = false;
870 let _ = self.store.upsert_chats(&[read]);
871 self.reload_sidebar(cx);
872 }
873 return;
874 }
875 if self.mode.read_only {
876 return;
877 }
878 if let Some(engine) = self.engine.clone() {
879 let _ = self
880 .store
881 .mark_chat_read(conversation_id, chrono::Utc::now());
882 self.reload_sidebar(cx);
883 let conversation_id = conversation_id.to_owned();
884 drop(crate::runtime::spawn(async move {
885 engine.mark_read(&conversation_id).await
886 }));
887 }
888 }
889
890 pub fn mark_channel_read(&mut self, channel_id: &str, cx: &mut Context<Self>) {
891 if self.mode.read_only {
892 return;
893 }
894 let _ = self.store.mark_channel_read(channel_id);
895 self.reload_sidebar(cx);
896 if self.mode.demo {
897 return;
898 }
899 if let Some(engine) = self.engine.clone() {
900 let channel_id = channel_id.to_owned();
901 drop(crate::runtime::spawn(async move {
902 engine.mark_read(&channel_id).await
903 }));
904 }
905 }
906
907 pub fn mark_all_channels_read(&mut self, cx: &mut Context<Self>) {
908 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
909 return;
910 };
911 let previous_unread: Vec<store::ChannelReadState> = self
912 .sidebar
913 .teams
914 .iter()
915 .flat_map(|team| team.channels.iter())
916 .map(|channel| store::ChannelReadState {
917 channel_id: channel.id.clone(),
918 unread: channel.unread,
919 last_message_at: None,
920 read_until: None,
921 })
922 .collect();
923 let previous_mentions: Vec<(String, store::ChannelMentions)> = self
924 .sidebar
925 .teams
926 .iter()
927 .flat_map(|team| team.mentions.iter())
928 .map(|(channel_id, mentions)| (channel_id.clone(), *mentions))
929 .collect();
930 let _ = self.store.mark_all_channels_read();
931 self.reload_sidebar(cx);
932 let Some(engine) = engine_or_demo else {
933 return;
934 };
935 self.run_chat_action(
936 "Mark all as read",
937 async move { engine.mark_all_channels_read().await },
938 move |state, cx| {
939 let _ = state.store.apply_channel_read_states(&previous_unread);
940 let _ = state.store.replace_channel_mentions(&previous_mentions);
941 state.reload_sidebar(cx);
942 },
943 |_, _| {},
944 cx,
945 );
946 }
947
948 pub fn open_quick_view(&mut self, view: QuickView, cx: &mut Context<Self>) {
949 self.show_call(false, cx);
950 self.cancel_prejoin(cx);
951 self.new_chat = false;
952 self.quick_view = Some(view);
953 if view == QuickView::Saved {
954 self.refresh_saved(cx);
955 }
956 cx.emit(AppEvent::Sidebar);
957 cx.notify();
958 }
959
960 pub fn close_quick_view(&mut self, cx: &mut Context<Self>) {
961 if self.quick_view.take().is_some() {
962 cx.emit(AppEvent::Sidebar);
963 cx.notify();
964 }
965 }
966
967 pub fn start_new_chat(&mut self, cx: &mut Context<Self>) {
968 self.quick_view = None;
969 self.new_chat = true;
970 self.show_call(false, cx);
971 cx.emit(AppEvent::Selection);
972 cx.notify();
973 }
974
975 pub fn close_new_chat(&mut self, cx: &mut Context<Self>) {
976 if !self.new_chat {
977 return;
978 }
979 self.new_chat = false;
980 cx.emit(AppEvent::Selection);
981 cx.notify();
982 }
983
984 pub fn select(&mut self, selection: Selection, cx: &mut Context<Self>) {
985 self.show_call(false, cx);
986 self.cancel_prejoin(cx);
987 self.call_end = None;
988 let was_drafting = std::mem::take(&mut self.new_chat);
989 let left_quick_view = self.quick_view.take().is_some();
990 if !was_drafting && self.selection.as_ref() == Some(&selection) {
991 if left_quick_view {
992 cx.emit(AppEvent::Sidebar);
993 cx.notify();
994 }
995 return;
996 }
997 let conversation_id = selection.conversation_id().to_owned();
998 self.selection = Some(selection);
999 self.keep_unread = None;
1000 self.forward_selection = None;
1001 cx.emit(AppEvent::Selection);
1002 cx.notify();
1003 self.refresh_live_meeting(&conversation_id, cx);
1004 self.refresh_language_stamps(&conversation_id, cx);
1005 }
1006
1007 fn apply_typing(&mut self, event: TypingEvent, cx: &mut Context<Self>) {
1008 let is_me = self
1009 .directory
1010 .me
1011 .as_ref()
1012 .is_some_and(|me| me.user_id == event.user_id);
1013 if is_me {
1014 return;
1015 }
1016 if event.active {
1017 let display_name = match event.display_name.trim() {
1018 "" => crate::people::resolve_names(self, std::slice::from_ref(&event.user_id))
1019 .remove(&event.user_id)
1020 .unwrap_or_default(),
1021 _ => event.display_name.clone(),
1022 };
1023 self.typing.start(
1024 &event.conversation_id,
1025 &event.user_id,
1026 &display_name,
1027 Instant::now(),
1028 event.received_at,
1029 );
1030 self.request_avatars(vec![event.user_id.clone()], cx);
1031 self.schedule_typing_expiry(cx);
1032 } else {
1033 self.typing.clear(&event.conversation_id, &event.user_id);
1034 }
1035 cx.emit(AppEvent::Typing);
1036 cx.notify();
1037 }
1038
1039 fn clear_typists_who_sent(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
1040 if !self.typing.is_active(conversation_id) {
1041 return;
1042 }
1043 let Ok(recent) = self
1044 .store
1045 .messages(conversation_id, None, RECENT_MESSAGES_FOR_TYPING)
1046 else {
1047 return;
1048 };
1049 let mut changed = false;
1050 for message in recent {
1051 if let Some(sender_id) = message.sender_id.as_deref() {
1052 changed |= self
1053 .typing
1054 .message_from(conversation_id, sender_id, message.created_at);
1055 }
1056 }
1057 if changed {
1058 cx.emit(AppEvent::Typing);
1059 cx.notify();
1060 }
1061 }
1062
1063 fn schedule_typing_expiry(&mut self, cx: &mut Context<Self>) {
1064 if self.typing_timer_running {
1065 return;
1066 }
1067 self.typing_timer_running = true;
1068 cx.spawn(async move |this, cx| {
1069 loop {
1070 let next = this.update(cx, |state, _| {
1071 let next = state.typing.next_expiry();
1072 state.typing_timer_running = next.is_some();
1073 next
1074 });
1075 let Ok(Some(next)) = next else { return };
1076 cx.background_executor()
1077 .timer(next.saturating_duration_since(Instant::now()))
1078 .await;
1079 let alive = this.update(cx, |state, cx| {
1080 if state.typing.expire(Instant::now()) {
1081 cx.emit(AppEvent::Typing);
1082 cx.notify();
1083 }
1084 });
1085 if alive.is_err() {
1086 return;
1087 }
1088 }
1089 })
1090 .detach();
1091 }
1092
1093 pub fn reload_sidebar(&mut self, cx: &mut Context<Self>) {
1094 if let Ok(sidebar) = self.store.sidebar() {
1095 self.sidebar = sidebar;
1096 self.apply_bot_titles();
1097 }
1098 self.calls_list.invalidate();
1099 if !self.mode.demo {
1100 self.reload_directory();
1101 self.load_own_time_zone(cx);
1102 }
1103 cx.emit(AppEvent::Sidebar);
1104 cx.notify();
1105 }
1106
1107 pub fn apply(&mut self, event: BackendEvent, cx: &mut Context<Self>) {
1108 match event {
1109 BackendEvent::Connection(connection) => {
1110 self.connection = connection;
1111 self.refresh_connection_banner(cx);
1112 cx.emit(AppEvent::Status);
1113 }
1114 BackendEvent::LiveRetry(retry) => self.live_retry = Some(retry),
1115 BackendEvent::Calls(launcher) => {
1116 launcher.set_default_camera(self.call_camera.clone());
1117 self.call_launcher = Some(launcher);
1118 self.load_own_time_zone(cx);
1119 }
1120 BackendEvent::Calendar(events) => self.apply_calendar(events, cx),
1121 BackendEvent::CalendarNudge(nudge) => self.calendar_nudge = Some(nudge),
1122 BackendEvent::Ring(event) => self.on_engine_event(event, cx),
1123 BackendEvent::ThreadChanged(conversation_id) => {
1124 self.on_thread_changed(&conversation_id, cx)
1125 }
1126 BackendEvent::Engine(engine) => {
1127 crate::agent_api::engine_ready(engine.clone(), cx);
1128 self.engine = Some(engine);
1129 self.resend_outbox(cx);
1130 self.refresh_scheduled(cx);
1131 self.refresh_translation_settings(cx);
1132 self.refresh_recording_policy(cx);
1133 self.refresh_messaging_policy(cx);
1134 self.refresh_sound_settings(cx);
1135 self.refresh_chat_settings(cx);
1136 let waiting = self.directory.waiting_presence_ids();
1137 self.request_presence(waiting, cx);
1138 self.watch_followed_presence(cx);
1139 self.refresh_own_status(cx);
1140 cx.emit(AppEvent::Status);
1141 }
1142 BackendEvent::Core(CoreEvent::SidebarChanged) => self.reload_sidebar_after_sync(cx),
1143 BackendEvent::Core(CoreEvent::ActivityChanged) => cx.emit(AppEvent::Activity),
1144 BackendEvent::Core(
1145 CoreEvent::MessagesChanged { conversation_id }
1146 | CoreEvent::ReceiptsChanged { conversation_id },
1147 ) => {
1148 self.clear_typists_who_sent(&conversation_id, cx);
1149 self.refresh_language_stamps(&conversation_id, cx);
1150 cx.emit(AppEvent::Messages(conversation_id));
1151 }
1152 BackendEvent::Core(CoreEvent::MessagesStoredLate {
1153 conversation_id,
1154 message_ids,
1155 }) => self.late_arrivals.insert(&conversation_id, message_ids),
1156 BackendEvent::Core(CoreEvent::PinsChanged { conversation_id }) => {
1157 self.refresh_pins(&conversation_id, cx);
1158 }
1159 BackendEvent::Core(CoreEvent::ImagesChanged { keys }) => {
1160 if let Some(engine) = &self.engine {
1161 for key in &keys {
1162 let image = ImageRef {
1163 id: String::new(),
1164 url: key.clone(),
1165 width: None,
1166 height: None,
1167 alt: None,
1168 };
1169 if let Some(path) = engine.image_path(&image) {
1170 self.directory.set_image(key, &path);
1171 }
1172 }
1173 }
1174 cx.emit(AppEvent::Images(keys));
1175 }
1176 BackendEvent::Core(CoreEvent::PresenceChanged) => {
1177 let changed = self.sync_presence();
1178 self.announce_followed_changes(cx);
1179 self.directory.save_presence(&self.store, &changed);
1180 cx.emit(AppEvent::Directory);
1181 cx.notify();
1182 }
1183 BackendEvent::Core(CoreEvent::PresenceStatusChanged(status)) => {
1184 self.apply_own_status(status, cx);
1185 self.reload_directory();
1186 }
1187 BackendEvent::Core(_) => {
1188 if !self.mode.demo {
1189 self.reload_directory();
1190 }
1191 cx.emit(AppEvent::Directory);
1192 }
1193 BackendEvent::Typing(event) => self.apply_typing(event, cx),
1194 BackendEvent::Live(live) => {
1195 self.live = live;
1196 self.refresh_connection_banner(cx);
1197 cx.emit(AppEvent::Status);
1198 }
1199 BackendEvent::Favorites(ids) => {
1200 self.favorite_ids = ids;
1201 if !self.mode.demo {
1202 self.reload_directory();
1203 }
1204 cx.emit(AppEvent::Sidebar);
1205 }
1206 BackendEvent::Synced(time) => {
1207 if self.last_sync.is_none() {
1208 self.refresh_saved(cx);
1209 }
1210 self.last_sync = Some(time);
1211 cx.emit(AppEvent::Status);
1212 }
1213 }
1214 cx.notify();
1215 }
1216}
1217
1218#[cfg(test)]
1219mod tests {
1220 use std::sync::Arc;
1221
1222 use chatsvc::TypingEvent;
1223 use chrono::{Duration, Utc};
1224 use gpui_kit::{AppContext as _, TestAppContext};
1225 use store::{
1226 ChannelRecord, ChatRecord, MemberRecord, MessageRecord, SidebarTeam, Store, TeamRecord,
1227 };
1228 use teams_core::CoreEvent;
1229
1230 use super::{AppState, Mode, Selection, chat_title, selection_for, selection_title};
1231 use crate::backend::BackendEvent;
1232 use crate::data::Person;
1233 use store::Sidebar;
1234
1235 fn chat(id: &str, title: &str, unread: bool) -> ChatRecord {
1236 ChatRecord {
1237 id: id.into(),
1238 kind: "group".into(),
1239 title: title.into(),
1240 member_summary: "Member".into(),
1241 last_message_at: None,
1242 last_read_at: None,
1243 unread,
1244 ..Default::default()
1245 }
1246 }
1247
1248 #[test]
1249 fn selection_kind_follows_sidebar() {
1250 assert_eq!(
1251 selection_for(&sidebar(), "c1"),
1252 Some(Selection::Chat("c1".into()))
1253 );
1254 assert_eq!(
1255 selection_for(&sidebar(), "ch"),
1256 Some(Selection::Channel("ch".into()))
1257 );
1258 assert_eq!(selection_for(&sidebar(), "x"), None);
1259 }
1260
1261 fn sidebar() -> Sidebar {
1262 Sidebar {
1263 chats: vec![chat("c1", "First", true), chat("c2", "", false)],
1264 teams: vec![SidebarTeam {
1265 rights: Default::default(),
1266 team: TeamRecord {
1267 id: "t".into(),
1268 name: "Team".into(),
1269 },
1270 channels: vec![ChannelRecord {
1271 id: "ch".into(),
1272 team_id: "t".into(),
1273 name: "General".into(),
1274 membership_type: None,
1275 last_message_at: None,
1276 unread: false,
1277 }],
1278 hidden: false,
1279 hidden_channel_ids: Vec::new(),
1280 notifications: Default::default(),
1281 mentions: Default::default(),
1282 }],
1283 }
1284 }
1285
1286 #[test]
1287 fn empty_chat_title_falls_back_to_members() {
1288 assert_eq!(chat_title(&sidebar().chats[1]), "Member");
1289 }
1290
1291 #[test]
1292 fn selection_titles() {
1293 assert_eq!(
1294 selection_title(&sidebar(), &Selection::Channel("ch".into())),
1295 "Team / General"
1296 );
1297 assert_eq!(
1298 selection_title(&sidebar(), &Selection::Chat("c1".into())),
1299 "First"
1300 );
1301 }
1302
1303 fn typing_event(user_id: &str, active: bool) -> BackendEvent {
1304 BackendEvent::Typing(TypingEvent {
1305 conversation_id: "c1".into(),
1306 user_id: user_id.into(),
1307 display_name: format!("Name {user_id}"),
1308 active,
1309 received_at: Utc::now(),
1310 })
1311 }
1312
1313 #[gpui_kit::test]
1314 fn toggle_collapsed_ignores_pending_sections(cx: &mut TestAppContext) {
1315 cx.update(gpui_kit::init);
1316 let store = Arc::new(Store::open_in_memory().unwrap());
1317 let app = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1318 cx.update(|cx| {
1319 app.update(cx, |state, cx| {
1320 state.toggle_collapsed("pending-section:1", cx);
1321 assert!(state.collapsed.is_empty());
1322 })
1323 });
1324 }
1325
1326 #[gpui_kit::test]
1327 fn typing_events_track_other_users_and_ignore_me(cx: &mut TestAppContext) {
1328 cx.update(gpui_kit::init);
1329 let store = Arc::new(Store::open_in_memory().unwrap());
1330 let app = cx.update(|cx| {
1331 cx.new(|_| {
1332 let mut state = AppState::new(store.clone(), Mode::default());
1333 state.directory.me = Some(Person {
1334 user_id: "me".into(),
1335 display_name: "Me".into(),
1336 });
1337 state
1338 })
1339 });
1340 let names = |cx: &mut TestAppContext| cx.update(|cx| app.read(cx).typing.names("c1"));
1341 cx.update(|cx| {
1342 app.update(cx, |state, cx| {
1343 state.apply(typing_event("me", true), cx);
1344 state.apply(typing_event("ada", true), cx);
1345 })
1346 });
1347 assert_eq!(names(cx), vec!["Name ada".to_owned()]);
1348
1349 let message = MessageRecord {
1350 conversation_id: "c1".into(),
1351 message_id: "m1".into(),
1352 sender_id: Some("ada".into()),
1353 created_at: Utc::now() + Duration::seconds(1),
1354 ..Default::default()
1355 };
1356 store.upsert_messages(&[message]).unwrap();
1357 cx.update(|cx| {
1358 app.update(cx, |state, cx| {
1359 state.apply(
1360 BackendEvent::Core(CoreEvent::MessagesChanged {
1361 conversation_id: "c1".into(),
1362 }),
1363 cx,
1364 )
1365 })
1366 });
1367 assert!(names(cx).is_empty());
1368
1369 cx.update(|cx| {
1370 app.update(cx, |state, cx| {
1371 state.apply(typing_event("ada", true), cx);
1372 state.apply(typing_event("ada", false), cx);
1373 })
1374 });
1375 assert!(names(cx).is_empty());
1376 }
1377
1378 #[gpui_kit::test]
1379 fn typing_without_a_display_name_uses_the_chat_member_name(cx: &mut TestAppContext) {
1380 cx.update(gpui_kit::init);
1381 let store = Arc::new(Store::open_in_memory().unwrap());
1382 let app = cx.update(|cx| {
1383 cx.new(|_| {
1384 let mut state = AppState::new(store.clone(), Mode::default());
1385 let mut member_chat = chat("c1", "First", false);
1386 member_chat.members = vec![MemberRecord {
1387 user_id: Some("ada".into()),
1388 display_name: "Ada Lovelace".into(),
1389 }];
1390 state.sidebar.chats = vec![member_chat];
1391 state
1392 })
1393 });
1394 cx.update(|cx| {
1395 app.update(cx, |state, cx| {
1396 state.apply(
1397 BackendEvent::Typing(TypingEvent {
1398 conversation_id: "c1".into(),
1399 user_id: "ada".into(),
1400 display_name: String::new(),
1401 active: true,
1402 received_at: Utc::now(),
1403 }),
1404 cx,
1405 )
1406 })
1407 });
1408 assert_eq!(
1409 cx.update(|cx| app.read(cx).typing.names("c1")),
1410 vec!["Ada Lovelace".to_owned()]
1411 );
1412 }
1413}