//! Application state on the UI thread, wired to the engine: setup, the //! event loop glue and the state the screens share. //! //! The screens' logic is elsewhere: servers and the channel tree in //! `servers/`, chat in `chat/`, streams in `streams/`, the people, the bell //! and the search in `social/`, the settings page in `settings_page/` and //! `appearance.rs`, the settings pages in `settings_pages/`, the Stream //! Studio in `studio/`, what the screens show and what a move or an event //! does in the `voelin-ui-vm` crate (`vm`), callbacks in `bind/`, //! development switches in `dev/`. use std::cell::RefCell; use std::path::{Path, PathBuf}; use std::rc::Rc; use std::sync::Arc; use std::time::Duration; use anyhow::{Context, Result}; use slint::{ComponentHandle, ModelRc, VecModel}; use tokio::runtime::Runtime; use tracing::warn; use voelin_core::media::decoder_preference; use voelin_core::settings::{ AUDIO, CRASH_REPORTS, IDENTITY_IMPORT, STREAM_DECODER_BACKEND, STREAM_HARDWARE_DECODING, Settings, }; use voelin_core::{AudioSettings, Command, Engine, Event, History}; use voelin_platform::crash; use voelin_store::{Bookmark, MemorySecrets, Secrets, Store}; use crate::bind::rows::Rows; use crate::hotkey::GlobalPtt; use crate::settings::{CLIENT_PLAYBACK, ClientPlaybackMap, UI, UiSettings, appearance_keys}; use crate::streams::Share; use crate::video::{Decoder, Video}; use crate::vm; slint::include_modules!(); /// The settings service on the client database: the UI's keys registered, /// then a config file (`VOELIN_CONFIG`, else `/config.toml` if it /// exists), `VOELIN_SETTING_*` variables and `overrides` below the stored /// values. Without the database the settings live in memory. fn open_settings(dir: &Path, overrides: &[String]) -> Settings { let prefs = Settings::open(&dir.join("client.db")).unwrap_or_else(|e| { warn!(%e, "settings are not stored this time"); Settings::in_memory() }); prefs.register(&UI); prefs.register(&CLIENT_PLAYBACK); for key in appearance_keys() { prefs.register(key); } for key in crate::settings::page_keys() { prefs.register(key); } prefs.register(&crate::vm::studio::logic::STUDIO_UI); let config = std::env::var_os("VOELIN_CONFIG") .map(PathBuf::from) .or_else(|| Some(dir.join("config.toml")).filter(|p| p.exists())); let mut errors = match config.map(|path| prefs.load_config_file(&path)) { Some(Ok(errors)) => errors, Some(Err(e)) => vec![e], None => Vec::new(), }; errors.extend(prefs.apply_env(std::env::vars())); errors.extend(prefs.apply_overrides(overrides.iter().map(String::as_str))); for e in errors { warn!(%e, "setting ignored"); } prefs } /// Secrets in the OS keyring, or in memory when there is none (headless /// Linux without a Secret Service). #[cfg(not(target_os = "android"))] struct FallbackSecrets { keyring: voelin_store::KeyringSecrets, memory: MemorySecrets, } /// The secrets store when [`RunOptions::secrets`] is not given: the OS /// keyring on desktop, memory elsewhere. fn default_secrets() -> Box { #[cfg(not(target_os = "android"))] return Box::new(FallbackSecrets { keyring: voelin_store::KeyringSecrets::new("voelin"), memory: MemorySecrets::default(), }); #[cfg(target_os = "android")] return Box::new(MemorySecrets::default()); } #[cfg(not(target_os = "android"))] impl Secrets for FallbackSecrets { fn get(&self, key: &str) -> voelin_store::Result> { match self.memory.get(key)? { Some(v) => Ok(Some(v)), None => Ok(self.keyring.get(key).unwrap_or(None)), } } fn set(&self, key: &str, value: &str) -> voelin_store::Result<()> { if let Err(error) = self.keyring.set(key, value) { warn!(%error, "keyring unavailable, keeping the secret for this session only"); return self.memory.set(key, value); } Ok(()) } fn delete(&self, key: &str) -> voelin_store::Result<()> { let _ = self.keyring.delete(key); self.memory.delete(key) } } /// The lines of a chat as the chat view shows them. pub(crate) type ChatRows = Rows; impl vm::state::Lines for ChatRows { fn push(&mut self, line: vm::bridge::ChatLine) { Rows::push(self, line); } } /// A chat of a session (see `voelin_ui_vm::state`). pub(crate) type Tab = vm::state::Tab; /// What we know about one server session. pub(crate) type SessionView = vm::state::SessionView; /// What the screens share, apart from the window and the engine. pub(crate) type AppState = vm::state::AppState; /// The models the Bridge shows, created once and updated row by row /// ([`Rows::sync`]). pub(crate) struct Models { pub servers: Rows, pub tree: Rows, pub members: Rows, pub server_members: Rows, /// The chat strip: the current session's tabs without its private chats. pub tabs: Rows, /// Which of the session's tabs each of `tabs` is ([`crate::vm::chat::strip`]). pub strip: RefCell>, pub streams: Rows, pub viewers: Rows, pub pins: Rows, pub topics: Rows, pub topic_messages: Rows, /// The quality choices of the watched stream. pub qualities: Rows>, /// Shown when there is no chat. pub no_chat: Rows, /// Home, friends, messages, the bell, the search, events. pub social: crate::social::SocialModels, /// Settings pages. pub layers: Rows, pub audio_sources: Rows, pub identities: Rows, pub gateway_config: Rows, pub gateway_perms: Rows, pub all_settings: Rows, } impl Models { fn new(bridge: &Bridge) -> Self { let models = Self { servers: Rows::default(), tree: Rows::default(), members: Rows::default(), server_members: Rows::default(), tabs: Rows::default(), strip: RefCell::new(vec![0]), streams: Rows::default(), viewers: Rows::default(), pins: Rows::default(), topics: Rows::default(), topic_messages: Rows::default(), qualities: Rows::default(), no_chat: Rows::default(), social: crate::social::SocialModels::new(bridge), layers: Rows::default(), audio_sources: Rows::default(), identities: Rows::default(), gateway_config: Rows::default(), gateway_perms: Rows::default(), all_settings: Rows::default(), }; models.attach(bridge); models } /// Show the models in `bridge`: the main window's, and the viewer's own /// window's (its player reads the stream's qualities). pub(crate) fn attach(&self, bridge: &Bridge) { bridge.set_servers(self.servers.model()); bridge.set_tree(self.tree.model()); bridge.set_members(self.members.model()); bridge.set_server_members(self.server_members.model()); bridge.set_tabs(self.tabs.model()); bridge.set_streams(self.streams.model()); bridge.set_share_viewers(self.viewers.model()); bridge.set_pins(self.pins.model()); bridge.set_topics(self.topics.model()); bridge.set_topic_messages(self.topic_messages.model()); bridge.set_viewer_qualities(self.qualities.model()); bridge.set_messages(self.no_chat.model()); bridge.set_layers(self.layers.model()); bridge.set_audio_sources(self.audio_sources.model()); bridge.set_identities(self.identities.model()); bridge.set_gateway_config(self.gateway_config.model()); bridge.set_gateway_perms(self.gateway_perms.model()); bridge.set_all_settings(self.all_settings.model()); } } pub(crate) struct App { pub ui: slint::Weak, pub store: Store, pub secrets: Box, pub engine: Engine, pub identity: tsclientlib::Identity, /// The data the screens share (`voelin_ui_vm::state`). pub state: AppState, pub models: Models, /// The settings service (shared with the engine); `state.settings`, /// `state.audio` and `state.playback` are working copies of its keys. pub prefs: Settings, pub ptt: GlobalPtt, pub video: Video, /// The capture of our stream (`state.share` has the rest of it). pub share: Option, /// The decoder of the stream in the viewer (`state.watch` has the rest). pub decoder: Option, /// `VOELIN_DEMO_STREAM`: the viewer shows a local test stream. pub demo: bool, /// `VOELIN_DEMO_UI`: sample servers, channels and chat (dev/). pub demo_ui: bool, /// `VOELIN_AUTOSHARE=test-pattern`: share the test pattern once streams work. pub autoshare: bool, /// `VOELIN_OPEN=client`: open the volume dialog of the first other client. pub open_client_pending: bool, /// The notices are in the About page's model. pub notices_loaded: bool, /// Home, friends, messages, the bell and the search. pub social: crate::social::Social, /// The settings pages of the new design. pub pages: crate::settings_pages::Pages, /// The Stream Studio (studio/). pub studio: crate::studio::StudioState, /// The stream's own window (popout.rs). pub popout: crate::popout::Popout, } thread_local! { // It is `const`; clippy for Android targets does not see that through // the macro's expansion there. #[allow(clippy::missing_const_for_thread_local)] static APP: RefCell> = const { RefCell::new(None) }; } pub(crate) fn with_app(f: impl FnOnce(&mut App) -> R) -> Option { APP.with(|app| app.borrow_mut().as_mut().map(f)) } /// Run `f` on the app from another thread, on the UI thread. pub(crate) fn later(f: impl FnOnce(&mut App) + Send + 'static) { let _ = slint::invoke_from_event_loop(move || { with_app(f); }); } /// Start options for [`run`]. #[derive(Default)] pub struct RunOptions { /// Where the client database lives. Default: `VOELIN_DATA_DIR`, else /// `/voelin`. Mobile platforms pass their app storage directory. pub data_dir: Option, /// Where passwords are kept. Default: the OS keyring, in memory when it /// is unavailable. pub secrets: Option>, /// An engine the caller keeps running across windows (Android: voice /// goes on in a service while the activity is recreated). Default: an /// engine that stops with the window. pub engine: Option, /// Setting overrides as `key=value` (e.g. `--set` on the command line); /// values set in the app take precedence. pub setting_overrides: Vec, } impl std::fmt::Debug for RunOptions { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("RunOptions") .field("data_dir", &self.data_dir) .field("secrets", &self.secrets.is_some()) .field("engine", &self.engine.is_some()) .field("setting_overrides", &self.setting_overrides) .finish() } } /// An engine owned by the caller of [`run`]. pub struct HostedEngine { pub engine: Engine, /// The runtime the engine runs on; the window's tasks run there too. pub runtime: tokio::runtime::Handle, /// The engine's events for this window: first events that rebuild the /// current state of every session, then new ones. The window stops /// reading when it closes. pub events: tokio::sync::mpsc::UnboundedReceiver, } impl HostedEngine { /// A new engine on `runtime`, all of whose events go to the window. fn start(runtime: &Runtime) -> Self { let engine = runtime.block_on(async { Engine::start() }); let (tx, events) = tokio::sync::mpsc::unbounded_channel(); let mut rx = engine.subscribe(); runtime.spawn(async move { loop { match rx.recv().await { Ok(event) => { if tx.send(event).is_err() { break; } } Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue, Err(_) => break, } } }); Self { engine, runtime: runtime.handle().clone(), events } } } /// Run the app on the current thread until the window closes. The Slint /// platform must be set up before (the default backend on desktop). pub fn run(options: RunOptions) -> Result<()> { // Crash reports: the hook first, recording once the setting is known. crash::set_app_version(env!("CARGO_PKG_VERSION")); crash::install(crash::default_dir(), false); let (own_runtime, hosted) = match options.engine { Some(hosted) => (None, hosted), None => { let runtime = Runtime::new()?; let hosted = HostedEngine::start(&runtime); (Some(runtime), hosted) } }; let HostedEngine { engine, runtime, mut events } = hosted; // VOELIN_DATA_DIR isolates the database; the other development // switches are in dev/. // A host that names the data directory (Android) has no platform cache // directory either: avatars and icons go next to the database. if let Some(dir) = &options.data_dir { engine.send(Command::AttachCache(dir.join("images"))); } let dir: PathBuf = match (options.data_dir, std::env::var_os("VOELIN_DATA_DIR")) { (Some(dir), _) => dir, (None, Some(dir)) => dir.into(), (None, None) => dirs::data_dir().unwrap_or_else(|| ".".into()).join("voelin"), }; let store = Store::open(&dir.join("client.db")).context("failed to open the client database")?; // Chat history and contacts live in the client database; without this // the engine would keep them for this run only. match History::open(&dir.join("client.db")) { Ok(history) => engine.send(Command::AttachHistory(history)), Err(e) => warn!(%e, "chat history is not stored this time"), } let prefs = open_settings(&dir, &options.setting_overrides); let switches = crate::dev::Switches::from_env(); // New identities of the official TeamSpeak clients, on every start (not // with the sample data of VOELIN_DEMO_UI); the client's default // identity becomes ours while we have none the user chose. let imported = if prefs.get(&IDENTITY_IMPORT) && !switches.demo_ui { voelin_core::ts::identity::import_new(&store, &voelin_core::ts::identity::discover()) .unwrap_or_else(|e| { warn!(%e, "could not import TeamSpeak identities"); Default::default() }) } else { Default::default() }; let identity = match store.default_identity()? { Some(entry) => store.identity(entry.id)?, None => { // Creating an identity takes a moment (security level 8). let identity = tsclientlib::Identity::create(); let origin = voelin_store::IdentityOrigin::Created; store.add_identity(vm::servers::logic::CREATED_IDENTITY, &identity, origin)?; identity } }; engine.send(Command::AttachSettings(prefs.clone())); let mut settings: UiSettings = (*prefs.get_arc(&UI)).clone(); settings.crash_reports = prefs.get(&CRASH_REPORTS); crash::set_enabled(settings.crash_reports); crash::test_crash_if_requested(); let audio: AudioSettings = prefs.get(&AUDIO); let playback: ClientPlaybackMap = prefs.get(&CLIENT_PLAYBACK); engine.send(Command::SetAudioSettings(Box::new(audio.clone()))); let ui = MainWindow::new()?; let bridge = ui.global::(); bridge.set_app_name(voelin_platform::APP_NAME.into()); bridge.set_app_version(env!("CARGO_PKG_VERSION").into()); bridge.set_desktop(cfg!(not(target_os = "android"))); #[cfg(not(target_os = "android"))] watch_focus(&ui); let models = Models::new(&bridge); // Wayland and X11 find the desktop file (and icon) by this id. #[cfg(not(target_os = "android"))] if let Err(e) = slint::set_xdg_app_id(voelin_platform::APP_ID) { warn!("cannot set the app id: {e}"); } let bookmarks = store.bookmarks()?; let ptt = GlobalPtt::start( &runtime, |status| later(move |app| app.set_ptt_status(status)), |on| later(move |app| app.command(|session| Command::SetTransmitting { session, on })), ); if settings.global_ptt { ptt.set(Some(settings.ptt_key.clone())); } let mut video = Video::new(&dir, settings.openh264); video.set_decoder_preference(decoder_preference(&prefs)); let app = App { ui: ui.as_weak(), store, // The sample data of VOELIN_DEMO_UI never reaches the system keyring. secrets: options.secrets.unwrap_or_else(|| { if switches.demo_ui { Box::new(MemorySecrets::default()) } else { default_secrets() } }), engine: engine.clone(), identity, state: AppState::new(bookmarks, settings, audio, playback), models, prefs, ptt, video, share: None, decoder: None, demo: switches.demo_stream, demo_ui: switches.demo_ui, autoshare: switches.autoshare, open_client_pending: switches.open_client, notices_loaded: false, social: Default::default(), pages: Default::default(), studio: Default::default(), popout: Default::default(), }; APP.with(|a| *a.borrow_mut() = Some(app)); crate::bind::wire(&ui); // The studio's and the stream's windows close with the main window, // so the app ends. ui.window().on_close_requested(|| { with_app(App::close_windows); slint::CloseRequestResponse::HideWindow }); with_app(|app| { app.apply_appearance(); app.load_own_uids(); app.apply_srtp(); app.refresh_all(); app.refresh_settings_flags(); app.refresh_transmit(); app.refresh_crash_notice(); app.load_recent_chats(); app.refresh_people(); app.refresh_home(); app.refresh_notices(); app.refresh_pages(); if app.demo { app.start_demo(); } if let Some(text) = vm::servers::logic::imported_status(&imported) { app.set_status(text); } }); // Engine events -> UI thread, until the event loop is gone. runtime.spawn(async move { while let Some(event) = events.recv().await { let posted = slint::invoke_from_event_loop(move || { with_app(|app| app.handle_event(event)); }); if posted.is_err() { break; } } }); // Once a second: stream statistics, stored settings. let ticker = slint::Timer::default(); ticker.start(slint::TimerMode::Repeated, Duration::from_secs(1), || { with_app(|app| app.tick()); }); let _dev = crate::dev::start(&ui, &switches); // What the platform asked for before the window ran. crate::inbox::take(); ui.run()?; // With our own engine, leave servers properly, so no ghost client stays // behind until it times out. A hosted engine keeps its sessions. let own = own_runtime.is_some(); let open = with_app(|app| { app.save_audio(); if let Err(e) = app.prefs.flush() { warn!(%e, "could not store settings"); } let ids: Vec = app.state.sessions.keys().copied().collect(); for id in ids { app.save_reads(id); } app.state.watch = None; app.decoder = None; app.state.share = None; app.share = None; if own && !app.demo_ui { for id in app.state.sessions.keys() { app.engine.send(Command::CloseSession { session: *id as u64 }); } } own && !app.state.sessions.is_empty() && !app.demo_ui }); APP.with(|a| a.borrow_mut().take()); if let Some(runtime) = own_runtime { if open == Some(true) { runtime.block_on(async { tokio::time::sleep(Duration::from_millis(500)).await }); } runtime.shutdown_timeout(Duration::from_secs(2)); } Ok(()) } /// Tell the app when the window gains or loses the focus: messages are read /// only while it has it. (winit's focus events; without them, as on /// Android, the window counts as focused.) #[cfg(not(target_os = "android"))] fn watch_focus(ui: &MainWindow) { use slint::winit_030::{EventResult, WinitWindowAccessor, winit::event::WindowEvent}; ui.window().on_winit_window_event(|_, event| { if let WindowEvent::Focused(focused) = *event { later(move |app| app.window_focused(focused)); } EventResult::Propagate }); } /// Open a file or folder with the desktop's default application. pub(crate) fn open_path(path: &Path) -> std::io::Result<()> { open_target(path.as_os_str()) } /// Open a file, folder or address with the desktop's handler. Success is that /// the opener started: explorer's exit code means nothing (1 on success), and /// xdg-open may wait until the browser closes. pub(crate) fn open_target(target: &std::ffi::OsStr) -> std::io::Result<()> { let mut child = desktop_opener(target).spawn()?; // Reap it without blocking the UI. std::thread::spawn(move || child.wait()); Ok(()) } /// Build an argument-based desktop opener; never pass a target through a shell. pub(crate) fn desktop_opener(target: &std::ffi::OsStr) -> std::process::Command { #[cfg(windows)] let mut command = std::process::Command::new("explorer"); #[cfg(target_os = "macos")] let mut command = std::process::Command::new("open"); #[cfg(not(any(windows, target_os = "macos")))] let mut command = std::process::Command::new("xdg-open"); command.arg(target); command } pub(crate) fn model(items: Vec) -> ModelRc { ModelRc::from(Rc::new(VecModel::from(items))) } impl App { pub fn view_mut(&mut self) -> Option<&mut SessionView> { let id = self.state.current?; Some(self.state.sessions.entry(id).or_default()) } pub fn view(&self) -> Option<&SessionView> { self.state.current.and_then(|id| self.state.sessions.get(&id)) } pub fn bookmark(&self, id: i64) -> Option<&Bookmark> { self.state.bookmarks.iter().find(|b| b.id == id) } /// Send a command for the current session. Not for the sample /// sessions of VOELIN_DEMO_UI: the engine would open them for real. pub fn command(&self, f: impl FnOnce(u64) -> Command) { if let Some(id) = self.state.current.filter(|_| !self.demo_ui) { self.engine.send(f(id as u64)); } } pub fn set_status(&mut self, text: impl Into) { self.state.status = text.into(); if let Some(ui) = self.ui.upgrade() { ui.global::().set_status_text(self.state.status.clone().into()); } } /// Open a page on the web in the browser. Pages open through here, so /// a platform without a desktop opener (Android) can open them its own /// way. pub(crate) fn open_url(&self, url: &str) -> std::io::Result<()> { open_target(std::ffi::OsStr::new(url)) } /// Nav.copy put text on the clipboard: one toast says so. pub fn copied(&mut self) { let text = self.state.copy_note.take().unwrap_or_else(|| "Copied".to_owned()); self.set_status(text); } pub fn store_settings(&self) { if let Err(e) = self.prefs.set(&UI, self.state.settings.clone()) { warn!(%e, "could not store settings"); } } /// A setting changed, maybe elsewhere (a command, another window): take /// the values the window keeps copies of. The engine applies audio /// settings itself. pub(crate) fn setting_changed(&mut self, key: &str) { if key == AUDIO.name() && !self.state.audio_dirty { self.state.audio = self.prefs.get(&AUDIO); // The voice controls follow the transmit mode. self.refresh_transmit(); } else if key == CRASH_REPORTS.name() { let enabled = self.prefs.get(&CRASH_REPORTS); if enabled != self.state.settings.crash_reports { self.state.settings.crash_reports = enabled; crash::set_enabled(enabled); self.refresh_settings_flags(); } } else if key == CLIENT_PLAYBACK.name() { self.state.playback = self.prefs.get(&CLIENT_PLAYBACK); } else if appearance_keys().iter().any(|k| k.name() == key) { self.apply_appearance(); } else if key == voelin_core::settings::STREAM_AUDIO_SOURCES.name() { // A running share mixes the new sources (streams/bind.rs). self.share_audio_changed(); } else if key == STREAM_HARDWARE_DECODING.name() || key == STREAM_DECODER_BACKEND.name() { self.video.set_decoder_preference(decoder_preference(&self.prefs)); } self.page_setting_changed(key); } /// Once a second. fn tick(&mut self) { self.tick_streams(); self.tick_pages(); if self.state.audio_dirty { self.save_audio(); } } pub fn refresh_all(&mut self) { self.refresh_servers(); self.refresh_toolbar(); self.refresh_tree(); self.refresh_chat(); self.refresh_streams(); } } #[cfg(test)] mod tests { use voelin_model::ChatTarget; use super::*; #[test] fn channel_unread_ignores_private_tabs() { let mut view = SessionView::default(); view.tabs.push(Tab::new(ChatTarget::Channel(1), "Lobby".into())); view.tabs.push(Tab::new(ChatTarget::Private("a".into()), "@Nova".into())); for (tab, unread) in view.tabs.iter_mut().zip([1, 2, 4]) { tab.unread = unread; } assert_eq!(view.channel_unread(), 3); assert_eq!(view.private_unread(), 4); } /// Closing a tab keeps the current chat, or selects the strip's next /// one (never a private chat). #[test] fn closing_a_tab_keeps_the_current_chat() { let mut view = SessionView::default(); for target in [ ChatTarget::Channel(1), ChatTarget::Channel(2), ChatTarget::Private("a".into()), ChatTarget::Channel(3), ] { view.tabs.push(Tab::new(target, String::new())); } let current = |v: &SessionView| v.tabs[v.current_tab].target.clone(); view.set_current_tab(2); view.remove_tab(1); assert_eq!(current(&view), ChatTarget::Channel(2)); // [Server, 2, @a, 3]: the next tab of the strip, past the private chat. view.remove_tab(1); assert_eq!(current(&view), ChatTarget::Channel(3)); assert_eq!(view.channel_tab, ChatTarget::Channel(3)); // The last one: the strip's last, the server chat. view.remove_tab(2); assert_eq!(current(&view), ChatTarget::Server); } /// A private chat is current only on the Direct Messages page: leaving /// it goes back to the strip's last chat. #[test] fn leaving_a_private_chat_restores_the_strip_tab() { let mut view = SessionView::default(); view.tabs.push(Tab::new(ChatTarget::Channel(1), "Lobby".into())); view.tabs.push(Tab::new(ChatTarget::Private("a".into()), "@Nova".into())); view.set_current_tab(1); assert!(!view.leave_private()); view.set_current_tab(2); assert_eq!(view.channel_tab, ChatTarget::Channel(1)); assert!(view.leave_private()); assert_eq!(view.current_tab, 1); // The strip's chat was closed meanwhile: the server chat. view.set_current_tab(2); view.tabs.remove(1); view.current_tab = 1; assert!(view.leave_private()); assert_eq!(view.current_tab, 0); } /// A channel's chat focused while a private chat is current (voice /// connecting on the Direct Messages page) waits for the page to be /// left: the conversation and its composer stay the private chat's. #[test] fn a_strip_chat_does_not_replace_a_current_private_chat() { let mut view = SessionView::default(); view.tabs.push(Tab::new(ChatTarget::Channel(1), "Lobby".into())); view.tabs.push(Tab::new(ChatTarget::Private("a".into()), "@Nova".into())); view.tabs.push(Tab::new(ChatTarget::Private("b".into()), "@Ivy".into())); view.focus_tab(2); assert_eq!(view.current_tab, 2); view.focus_tab(1); assert_eq!((view.current_tab, &view.channel_tab), (2, &ChatTarget::Channel(1))); // Another private chat does. view.focus_tab(3); assert_eq!(view.current_tab, 3); assert!(view.leave_private()); assert_eq!(view.current_tab, 1); // Without a private chat current, any chat. view.focus_tab(0); assert_eq!((view.current_tab, &view.channel_tab), (0, &ChatTarget::Server)); view.focus_tab(9); assert_eq!(view.current_tab, 0); } }