//! Manages tracking of open files and window controllers. //! //! GTK is single-threaded, so thread-local storage is safe here. use std::cell::RefCell; use std::path::PathBuf; use relm4::component::Controller; use relm4::gtk; use crate::AppModel; use crate::actions::Action; thread_local! { /// Keeps window controllers alive for the lifetime of each window. static WINDOW_CONTROLLERS: RefCell>> = const { RefCell::new(Vec::new()) }; /// Tracks which files are currently open to prevent duplicate windows. static OPEN_FILES: RefCell> = const { RefCell::new(Vec::new()) }; /// Stores senders for all windows (including main window) to enable broadcasting. static WINDOW_SENDERS: RefCell>> = const { RefCell::new(Vec::new()) }; } /// Stores a window controller to keep it alive. pub fn store_controller(controller: Controller) { WINDOW_CONTROLLERS.with_borrow_mut(|controllers| { controllers.push(controller); }); } /// Returns the window that has the given file open, if any. pub fn find_window_for_file(path: &PathBuf) -> Option { OPEN_FILES.with_borrow(|files| { files .iter() .find(|(file_path, _)| file_path == path) .map(|(_, window)| window.clone()) }) } /// Registers a file as being open in the given window. pub fn register_file(path: &PathBuf, window: >k::Window) { OPEN_FILES.with_borrow_mut(|files| { if !files.iter().any(|(file_path, _)| file_path == path) { files.push((path.clone(), window.clone())); } }); } /// Unregisters a file when its window is closed. pub fn unregister_file(path: &PathBuf) { OPEN_FILES.with_borrow_mut(|files| { files.retain(|(file_path, _)| file_path != path); }); } /// Registers a window's sender for broadcasting. pub fn register_sender(sender: relm4::Sender) { WINDOW_SENDERS.with_borrow_mut(|senders| { senders.push(sender); }); } /// Broadcasts a message to all windows via their registered senders. pub fn broadcast_to_all_windows(message: Action) { WINDOW_SENDERS.with_borrow(|senders| { for sender in senders { sender.emit(message.clone()); } }); }