//! Tab transfer between windows of one workspace. //! //! An offer holds a tab's state, including unsaved text, in memory only. It never goes to disk. //! 1. The source window offers the tab and puts the offer ID in the drag data or the new window URL. //! 2. The receiving window takes the offer. A take checks the workspace root and the expiry. //! 3. The receiving window finishes the offer. If it accepted the tab, the host sends //! `tab-transfer-accepted` to the source window only, and the source closes its tab. //! A refused offer becomes available again. The source tab stays open until it receives the event. use std::collections::HashMap; use std::sync::Mutex; use std::time::{Duration, Instant}; use serde::Serialize; use tauri::{AppHandle, Emitter, State, Window}; use crate::error::{Error, Result}; /// An offer expires after this time if no window took it. pub const EXPIRY: Duration = Duration::from_secs(120); /// A taken offer that the receiver never finished is removed after this time. const TAKEN_EXPIRY: Duration = Duration::from_secs(240); /// A text buffer holds the text and its saved copy, and an image tab holds a data URL. pub const MAX_PAYLOAD_BYTES: usize = 64 * 1024 * 1024; const MAX_OFFERS: usize = 32; pub const ACCEPTED_EVENT: &str = "tab-transfer-accepted"; pub const EXPIRED: &str = "This tab transfer expired. Drag the tab again."; pub const OTHER_WORKSPACE: &str = "Move tabs only between windows of the same workspace."; struct Offer { source: String, root: String, payload: String, created: Instant, taker: Option, } #[derive(Serialize, Clone, Debug, PartialEq)] pub struct Accepted { pub id: String, } #[derive(Default)] pub struct TabTransferState(Mutex>); fn check_id(id: &str) -> Result<()> { uuid::Uuid::parse_str(id).map(|_| ()).map_err(|_| Error::new("Invalid tab transfer.")) } fn prune(offers: &mut HashMap, now: Instant) { offers.retain(|_, offer| { let age = now.saturating_duration_since(offer.created); if offer.taker.is_some() { age < TAKEN_EXPIRY } else { age < EXPIRY } }); } impl TabTransferState { /// Keep a tab offer from `source`. The source window creates the ID, because a drag needs its data at once. pub fn offer(&self, id: &str, source: &str, root: &str, payload: String, now: Instant) -> Result<()> { check_id(id)?; if payload.len() > MAX_PAYLOAD_BYTES { return Err(Error::new("This tab is too large to move to another window. Save it, then open the file in the other window.")); } serde_json::from_str::(&payload).map_err(|_| Error::new("Invalid tab transfer."))?; let mut offers = self.0.lock()?; prune(&mut offers, now); if offers.contains_key(id) { return Err(Error::new("Invalid tab transfer.")); } if offers.len() >= MAX_OFFERS { // Remove the oldest open offer. Its source tab stays open. if let Some(oldest) = offers.iter().filter(|(_, offer)| offer.taker.is_none()) .min_by_key(|(_, offer)| offer.created).map(|(key, _)| key.clone()) { offers.remove(&oldest); } else { return Err(Error::new("Too many tab transfers are in progress. Try again.")); } } offers.insert(id.into(), Offer { source: source.into(), root: root.into(), payload, created: now, taker: None }); Ok(()) } /// Give the offer to `taker` once. A different workspace leaves the offer for another window. pub fn take(&self, id: &str, taker: &str, root: &str, now: Instant) -> Result { check_id(id)?; let mut offers = self.0.lock()?; prune(&mut offers, now); let offer = offers.get_mut(id).filter(|offer| offer.taker.is_none()).ok_or_else(|| Error::new(EXPIRED))?; if offer.root != root { return Err(Error::new(OTHER_WORKSPACE)); } offer.taker = Some(taker.into()); Ok(offer.payload.clone()) } /// End the take of `taker`. Return the source window to acknowledge when the taker accepted the tab. /// A refused offer stays available for another window until it expires. pub fn finish(&self, id: &str, taker: &str, accepted: bool) -> Result> { check_id(id)?; let mut offers = self.0.lock()?; let Some(offer) = offers.get_mut(id).filter(|offer| offer.taker.as_deref() == Some(taker)) else { return Err(Error::new(EXPIRED)); }; if !accepted { offer.taker = None; return Ok(None); } Ok(offers.remove(id).map(|offer| offer.source)) } /// Withdraw an open offer of `source`. A taken offer stays until its receiver finishes it. pub fn cancel(&self, id: &str, source: &str) -> Result<()> { check_id(id)?; let mut offers = self.0.lock()?; if offers.get(id).is_some_and(|offer| offer.source == source && offer.taker.is_none()) { offers.remove(id); } Ok(()) } /// Remove the offers of a closed window, and release the offers that it took. pub fn release_window(&self, label: &str) { let Ok(mut offers) = self.0.lock() else { return }; offers.retain(|_, offer| offer.source != label); for offer in offers.values_mut() { if offer.taker.as_deref() == Some(label) { offer.taker = None; } } } } #[tauri::command] pub async fn tab_transfer_offer(window: Window, state: State<'_, TabTransferState>, id: String, root: String, payload: String) -> Result { state.offer(&id, window.label(), &root, payload, Instant::now())?; Ok(id) } #[tauri::command] pub async fn tab_transfer_take(window: Window, state: State<'_, TabTransferState>, id: String, root: String) -> Result { state.take(&id, window.label(), &root, Instant::now()) } #[tauri::command] pub async fn tab_transfer_finish(app: AppHandle, window: Window, state: State<'_, TabTransferState>, id: String, accepted: bool) -> Result<()> { if let Some(source) = state.finish(&id, window.label(), accepted)? { // Only the source window closes its tab. app.emit_to(source.as_str(), ACCEPTED_EVENT, Accepted { id })?; } Ok(()) } #[tauri::command] pub async fn tab_transfer_cancel(window: Window, state: State<'_, TabTransferState>, id: String) -> Result<()> { state.cancel(&id, window.label()) } #[cfg(test)] mod tests { use super::*; const ID: &str = "00000000-0000-4000-8000-000000000001"; const ROOT: &str = "C:\\workspace"; fn offered(now: Instant) -> TabTransferState { let state = TabTransferState::default(); state.offer(ID, "main", ROOT, r#"{"buffer":{"contents":"unsaved"}}"#.into(), now).unwrap(); state } #[test] fn an_offer_is_taken_once() { let now = Instant::now(); let state = offered(now); assert_eq!(state.take(ID, "workspace-2", ROOT, now).unwrap(), r#"{"buffer":{"contents":"unsaved"}}"#); assert_eq!(state.take(ID, "workspace-3", ROOT, now).unwrap_err().to_string(), EXPIRED); assert_eq!(state.finish(ID, "workspace-2", true).unwrap().as_deref(), Some("main")); assert_eq!(state.take(ID, "workspace-2", ROOT, now).unwrap_err().to_string(), EXPIRED); assert_eq!(state.finish(ID, "workspace-2", true).unwrap_err().to_string(), EXPIRED); } #[test] fn an_offer_expires_after_two_minutes() { let now = Instant::now(); let state = offered(now); assert!(state.take(ID, "workspace-2", ROOT, now + EXPIRY - Duration::from_secs(1)).is_ok()); assert_eq!(state.finish(ID, "workspace-2", false).unwrap(), None); assert_eq!(state.take(ID, "workspace-2", ROOT, now + EXPIRY).unwrap_err().to_string(), EXPIRED); // A taken offer survives the expiry until its receiver finishes it. let state = offered(now); state.take(ID, "workspace-2", ROOT, now).unwrap(); state.offer("00000000-0000-4000-8000-000000000002", "main", ROOT, "{}".into(), now + EXPIRY).unwrap(); assert_eq!(state.finish(ID, "workspace-2", true).unwrap().as_deref(), Some("main")); } #[test] fn a_different_workspace_cannot_take_the_offer_and_leaves_it_open() { let now = Instant::now(); let state = offered(now); assert_eq!(state.take(ID, "workspace-2", "C:\\other", now).unwrap_err().to_string(), OTHER_WORKSPACE); assert!(state.take(ID, "workspace-3", ROOT, now).is_ok()); } #[test] fn only_the_taker_finishes_and_only_acceptance_acknowledges_the_source() { let now = Instant::now(); let state = offered(now); state.take(ID, "workspace-2", ROOT, now).unwrap(); assert_eq!(state.finish(ID, "workspace-3", true).unwrap_err().to_string(), EXPIRED); // A refusal sends nothing, and another window can take the offer. assert_eq!(state.finish(ID, "workspace-2", false).unwrap(), None); state.take(ID, "workspace-3", ROOT, now).unwrap(); // The acknowledgement goes to the source window, not to the taker. assert_eq!(state.finish(ID, "workspace-3", true).unwrap().as_deref(), Some("main")); } #[test] fn offers_check_the_id_the_size_and_json() { let now = Instant::now(); let state = TabTransferState::default(); assert!(state.offer("not-a-uuid", "main", ROOT, "{}".into(), now).is_err()); assert!(state.offer(ID, "main", ROOT, "{".into(), now).is_err()); let large = format!("\"{}\"", "x".repeat(MAX_PAYLOAD_BYTES)); assert!(state.offer(ID, "main", ROOT, large, now).unwrap_err().to_string().contains("too large")); state.offer(ID, "main", ROOT, "{}".into(), now).unwrap(); assert!(state.offer(ID, "main", ROOT, "{}".into(), now).is_err(), "An ID is used once"); assert!(state.take("../x", "workspace-2", ROOT, now).is_err()); } #[test] fn the_oldest_open_offer_makes_room_for_a_new_one() { let now = Instant::now(); let state = TabTransferState::default(); let ids: Vec = (0..=MAX_OFFERS).map(|index| format!("00000000-0000-4000-8000-{index:012}")).collect(); for (index, id) in ids.iter().enumerate() { state.offer(id, "main", ROOT, "{}".into(), now + Duration::from_millis(index as u64)).unwrap(); } assert_eq!(state.take(&ids[0], "workspace-2", ROOT, now).unwrap_err().to_string(), EXPIRED); assert!(state.take(&ids[MAX_OFFERS], "workspace-2", ROOT, now).is_ok()); } #[test] fn the_source_cancels_only_its_open_offers() { let now = Instant::now(); let state = offered(now); state.cancel(ID, "workspace-2").unwrap(); assert!(state.take(ID, "workspace-2", ROOT, now).is_ok()); state.cancel(ID, "main").unwrap(); assert_eq!(state.finish(ID, "workspace-2", true).unwrap().as_deref(), Some("main"), "A taken offer stays until it finishes"); let state = offered(now); state.cancel(ID, "main").unwrap(); assert_eq!(state.take(ID, "workspace-2", ROOT, now).unwrap_err().to_string(), EXPIRED); } #[test] fn closing_a_window_removes_its_offers_and_releases_its_takes() { let now = Instant::now(); let state = offered(now); state.take(ID, "workspace-2", ROOT, now).unwrap(); state.release_window("workspace-2"); assert!(state.take(ID, "workspace-3", ROOT, now).is_ok()); state.release_window("main"); assert_eq!(state.finish(ID, "workspace-3", true).unwrap_err().to_string(), EXPIRED); } #[test] fn the_acknowledgement_names_the_offer() { assert_eq!(serde_json::to_value(Accepted { id: ID.into() }).unwrap(), serde_json::json!({ "id": ID })); } }