R4.12: answer the token before paths, one deadline per caller, hand-overs via the main window

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
ZacharyZhang-NYandClaude Opus 5.5 committed 2026-10-14 19:30:13 -04:00
1 parent 5bf2056281
commit 78a285d124
8 files changed
+363 -124

No files matched your search

+115 -40
View File
@@ -1,71 +1,84 @@
//! Files handed to the app: arguments, Finder, second copies.
use std::{io, path::PathBuf};
use std::{io, path::PathBuf, time::Duration};
use ely_platform::instance::Door;
use futures::{StreamExt, channel::mpsc};
use gpui::{App, Application, Global};
use gpui::{AnyWindowHandle, App, Application, Global};
/// A request to the running app.
pub(crate) enum Ask {
Open(PathBuf),
/// A second copy started: come to the front.
Raise,
}
/// How long a hand-over waits for the window.
const TAKING: Duration = Duration::from_secs(5);
struct Asked(Option<mpsc::UnboundedReceiver<Ask>>);
struct Asked(Option<mpsc::UnboundedReceiver<PathBuf>>);
impl Global for Asked {}
/// A second copy's files; `taken` answers once they are queued.
pub(crate) struct Hand {
files: Vec<PathBuf>,
taken: std::sync::mpsc::Sender<()>,
}
/// What the system and other copies hand the running app.
pub(crate) struct Handed {
asked: mpsc::UnboundedReceiver<PathBuf>,
hands: Hands,
}
/// Second copies' hand-overs, for the main window.
pub(crate) struct Hands {
hands: mpsc::UnboundedReceiver<Hand>,
queue: mpsc::UnboundedSender<PathBuf>,
}
/// Launch arguments, relative to where the app was started.
pub(crate) fn launch_args() -> io::Result<Vec<PathBuf>> {
std::env::args_os().skip(1).map(std::path::absolute).collect()
}
/// Queues `files`, then files the system or copies ask for.
pub(crate) fn listen(application: &Application, files: Vec<PathBuf>, door: Door) -> io::Result<mpsc::UnboundedReceiver<Ask>> {
let (sender, asked) = mpsc::unbounded();
pub(crate) fn listen(application: &Application, files: Vec<PathBuf>, door: Door) -> io::Result<Handed> {
let (queue, asked) = mpsc::unbounded();
for path in files {
sender.unbounded_send(Ask::Open(path)).ok();
queue.unbounded_send(path).ok();
}
let handed = sender.clone();
let (sender, hands) = mpsc::unbounded();
door.serve(move |files| {
for path in files {
handed.unbounded_send(Ask::Open(path)).ok();
}
handed.unbounded_send(Ask::Raise).ok();
let (taken, took) = std::sync::mpsc::channel();
sender.unbounded_send(Hand { files, taken }).is_ok() && took.recv_timeout(TAKING).is_ok()
})?;
let system = queue.clone();
application.on_open_urls(move |urls| {
for url in urls {
match file_path(&url) {
Some(path) => {
log::info!("run: the system asks to open a file");
sender.unbounded_send(Ask::Open(path)).ok();
system.unbounded_send(path).ok();
}
None => log::warn!("run: not a file URL, ignored"),
}
}
});
Ok(asked)
Ok(Handed { asked, hands: Hands { hands, queue } })
}
pub(crate) fn keep(asked: mpsc::UnboundedReceiver<Ask>, cx: &mut App) {
cx.set_global(Asked(Some(asked)));
/// Keeps the files for `on_open`; the hand-overs go to `home`.
pub(crate) fn keep(handed: Handed, cx: &mut App) -> Hands {
cx.set_global(Asked(Some(handed.asked)));
handed.hands
}
/// No files asked at launch, for tests.
#[cfg(any(test, feature = "test-support"))]
pub fn install_no_launch_files(cx: &mut App) {
keep(mpsc::unbounded().1, cx);
cx.set_global(Asked(Some(mpsc::unbounded().1)));
}
/// Files asked before the app started: arguments and Finder's.
pub fn launch_files(cx: &mut App) -> Vec<PathBuf> {
let asked = cx.global_mut::<Asked>().0.as_mut();
let asked = asked.expect("launch_files comes before on_open");
let pending = std::iter::from_fn(|| asked.try_recv().ok());
// The window opens in front anyway.
pending.filter_map(|ask| if let Ask::Open(path) = ask { Some(path) } else { None }).collect()
std::iter::from_fn(|| asked.try_recv().ok()).collect()
}
/// Hands each file asked from now on to `open`.
@@ -76,26 +89,34 @@ pub fn on_open(cx: &mut App, mut open: impl FnMut(PathBuf, &mut App) + 'static)
.take()
.expect("on_open runs once per app");
cx.spawn(async move |cx| {
while let Some(ask) = asked.next().await {
cx.update(|cx| match ask {
Ask::Open(path) => open(path, cx),
Ask::Raise => raise(cx),
});
while let Some(path) = asked.next().await {
cx.update(|cx| open(path, cx));
}
})
.detach();
}
/// Brings the main window, the first opened, to the front.
fn raise(cx: &mut App) {
cx.activate(true);
let Some(window) = cx.windows().into_iter().next() else {
log::warn!("run: no window to bring to the front");
return;
};
if let Err(error) = window.update(cx, |_, window, _| window.activate_window()) {
log::warn!("run: the window could not come to the front: {error}");
}
/// Brings `main` forward for each hand-over, then queues its files.
pub(crate) fn home(hands: Hands, main: AnyWindowHandle, cx: &mut App) {
let Hands { mut hands, queue } = hands;
cx.spawn(async move |cx| {
while let Some(hand) = hands.next().await {
let raised = cx.update(|cx| {
cx.activate(true);
main.update(cx, |_, window, _| window.activate_window())
});
// No answer: the other copy says the files went untaken.
if let Err(error) = raised {
log::warn!("run: the main window is gone, so a hand-over is refused: {error}");
continue;
}
for path in hand.files {
queue.unbounded_send(path).ok();
}
hand.taken.send(()).ok();
}
})
.detach();
}
/// A `file://` URL's path, percent escapes decoded.
@@ -143,3 +164,57 @@ mod tests {
assert_eq!(file_path("file:///a/%4"), None);
}
}
#[cfg(test)]
mod home_tests {
use super::*;
use gpui::{Context, IntoElement, Render, TestAppContext, Window};
struct Blank;
impl Render for Blank {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
gpui::div()
}
}
/// `home` on `main`; returns its hand-over and file queues.
fn homed(main: AnyWindowHandle, cx: &mut TestAppContext) -> (mpsc::UnboundedSender<Hand>, mpsc::UnboundedReceiver<PathBuf>) {
let (sender, hands) = mpsc::unbounded();
let (queue, asked) = mpsc::unbounded();
cx.update(|cx| home(Hands { hands, queue }, main, cx));
(sender, asked)
}
fn handed(sender: &mpsc::UnboundedSender<Hand>) -> std::sync::mpsc::Receiver<()> {
let (taken, took) = std::sync::mpsc::channel();
sender.unbounded_send(Hand { files: vec![PathBuf::from("x.md")], taken }).expect("sent");
took
}
#[gpui::test]
fn a_hand_over_raises_the_main_window_then_queues(cx: &mut TestAppContext) {
let main: AnyWindowHandle = cx.add_window(|_, _| Blank).into();
let _settings = cx.add_window(|_, _| Blank);
let (sender, mut asked) = homed(main, cx);
assert_ne!(cx.update(|cx| cx.active_window()), Some(main), "another window is in front");
let took = handed(&sender);
cx.run_until_parked();
assert_eq!(cx.update(|cx| cx.active_window()), Some(main));
assert_eq!(asked.try_recv().ok(), Some(PathBuf::from("x.md")));
assert!(took.try_recv().is_ok(), "the other copy hears it was taken");
}
#[gpui::test]
fn a_hand_over_without_the_main_window_is_refused(cx: &mut TestAppContext) {
let main: AnyWindowHandle = cx.add_window(|_, _| Blank).into();
let _settings = cx.add_window(|_, _| Blank);
let (sender, mut asked) = homed(main, cx);
main.update(cx, |_, window, _| window.remove_window()).expect("closed");
cx.run_until_parked();
let took = handed(&sender);
cx.run_until_parked();
assert!(took.try_recv().is_err(), "no answer, so the other copy reports it");
assert!(asked.try_recv().is_err(), "nothing queued for a gone window");
}
}
+12 -8
View File
@@ -36,10 +36,10 @@ pub fn run<V: Render>(
startup::no_window_restore();
let smoke = Smoke::from_env();
let application = gpui_platform::application().with_assets(Assets);
let asked = crate::opening::listen(&application, files, door).unwrap_or_else(|error| startup::fail(app, &format!("the door for other copies did not open: {error}")));
let handed = crate::opening::listen(&application, files, door).unwrap_or_else(|error| startup::fail(app, &format!("the door for other copies did not open: {error}")));
application.run(move |cx: &mut App| {
crate::opening::keep(asked, cx);
open(app, smoke, root, cx)
let hands = crate::opening::keep(handed, cx);
open(app, smoke, root, hands, cx)
});
}
@@ -72,6 +72,7 @@ fn open<V: Render>(
app: AppId,
smoke: Smoke,
root: impl FnOnce(AppId, &mut Window, &mut App) -> Entity<V> + 'static,
hands: crate::opening::Hands,
cx: &mut App,
) {
if let Err(error) = ely_gpui_component::init(cx) {
@@ -109,11 +110,14 @@ fn open<V: Render>(
crate::settings::follow_frame(app, window, cx);
root(app, window, cx)
});
if let Err(error) = opened {
startup::fail(app, &format!("the window did not open: {error:#}"));
}
cx.on_window_closed(|cx, _| {
if cx.windows().is_empty() {
let main: gpui::AnyWindowHandle = match opened {
Ok(window) => window.into(),
Err(error) => startup::fail(app, &format!("the window did not open: {error:#}")),
};
crate::opening::home(hands, main, cx);
// Settings alone would hold the lock yet open nothing.
cx.on_window_closed(move |cx, closed| {
if closed == main.window_id() {
cx.quit();
}
})