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:
1 parent
5bf2056281
commit
78a285d124
8 files changed
+363
-124
No files matched your search
@@ -53,6 +53,11 @@ pub fn check_reply(asked: u64, got: u64) -> io::Result<()> {
|
||||
|
||||
/// Reads (tag, id, payload); None at a clean stream end.
|
||||
pub fn read_frame(input: &mut impl Read) -> io::Result<Option<(u8, u64, Vec<u8>)>> {
|
||||
read_capped(input, MAX_FRAME)
|
||||
}
|
||||
|
||||
/// As `read_frame`, refusing payloads over `cap` before allocating.
|
||||
pub fn read_capped(input: &mut impl Read, cap: usize) -> io::Result<Option<(u8, u64, Vec<u8>)>> {
|
||||
let mut len = [0u8; 4];
|
||||
// Only a stream ending between frames ends cleanly.
|
||||
let mut got = 0;
|
||||
@@ -66,10 +71,10 @@ pub fn read_frame(input: &mut impl Read) -> io::Result<Option<(u8, u64, Vec<u8>)
|
||||
}
|
||||
}
|
||||
let len = u32::from_le_bytes(len) as usize;
|
||||
if len > MAX_FRAME {
|
||||
if len > cap {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"frame over the cap",
|
||||
format!("a {len} byte frame is over the {cap} byte cap"),
|
||||
));
|
||||
}
|
||||
let mut tag = [0u8; 1];
|
||||
|
||||
@@ -161,7 +161,8 @@ mod tests {
|
||||
panic!("the first copy did not hold");
|
||||
};
|
||||
let (sender, heard) = std::sync::mpsc::channel();
|
||||
door.serve(move |files| sender.send(files).expect("heard")).expect("served");
|
||||
let sender = std::sync::Mutex::new(sender);
|
||||
door.serve(move |files| sender.lock().expect("a sender").send(files).is_ok()).expect("served");
|
||||
println!("HELD");
|
||||
let files = heard.recv_timeout(std::time::Duration::from_secs(20)).expect("a hand-over");
|
||||
println!("GOT {}", files[0].display());
|
||||
|
||||
@@ -3,9 +3,10 @@
|
||||
use std::{
|
||||
ffi::OsString,
|
||||
fs,
|
||||
io::{self, Write},
|
||||
io::{self, Read, Write},
|
||||
net::{Ipv4Addr, SocketAddr, TcpListener, TcpStream},
|
||||
path::{Path, PathBuf},
|
||||
sync::Arc,
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
@@ -15,8 +16,13 @@ const TOKEN: u8 = 1;
|
||||
const PATH: u8 = 2;
|
||||
const DONE: u8 = 3;
|
||||
const REFUSED: u8 = 4;
|
||||
/// How long a stalled caller may hold the door.
|
||||
const OPEN: u8 = 5;
|
||||
/// How long one caller may take, start to end.
|
||||
const PATIENCE: Duration = Duration::from_secs(5);
|
||||
/// The largest frame before the token is shown.
|
||||
const SHOWN: usize = 64;
|
||||
/// The largest path frame: a whole Windows path.
|
||||
const LONGEST: usize = 128 * 1024;
|
||||
|
||||
/// The running copy's listener; its token keeps others out.
|
||||
pub struct Door {
|
||||
@@ -39,46 +45,93 @@ impl Door {
|
||||
Ok(Door { listener, token })
|
||||
}
|
||||
|
||||
/// Hands each caller's files to `deliver`, on its own thread.
|
||||
pub fn serve(self, deliver: impl Fn(Vec<PathBuf>) + Send + 'static) -> io::Result<()> {
|
||||
/// Hands each caller's files to `deliver`; false means not taken.
|
||||
pub fn serve(
|
||||
self,
|
||||
deliver: impl Fn(Vec<PathBuf>) -> bool + Send + Sync + 'static,
|
||||
) -> io::Result<()> {
|
||||
let deliver = Arc::new(deliver);
|
||||
thread::Builder::new()
|
||||
.name("instance door".into())
|
||||
.spawn(move || {
|
||||
for stream in self.listener.incoming() {
|
||||
if let Err(error) = stream.and_then(|stream| self.answer(stream, &deliver)) {
|
||||
log::warn!("instance: a hand-over failed: {error}");
|
||||
let (token, deliver) = (self.token, deliver.clone());
|
||||
// A stalled caller must not hold up the next.
|
||||
let answered = stream.and_then(|stream| {
|
||||
thread::Builder::new()
|
||||
.name("instance caller".into())
|
||||
.spawn(move || {
|
||||
if let Err(error) = answer(&stream, &token, &*deliver) {
|
||||
log::warn!("instance: a hand-over failed: {error}");
|
||||
}
|
||||
})
|
||||
.map(drop)
|
||||
});
|
||||
if let Err(error) = answered {
|
||||
log::warn!("instance: a caller was not answered: {error}");
|
||||
}
|
||||
}
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn answer(&self, mut stream: TcpStream, deliver: &impl Fn(Vec<PathBuf>)) -> io::Result<()> {
|
||||
stream.set_read_timeout(Some(PATIENCE))?;
|
||||
let (tag, token) = next(&mut stream)?;
|
||||
if tag != TOKEN || !same(&token, &self.token) {
|
||||
ely_ipc::write_frame(&mut stream, REFUSED, 0, &[])?;
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
"a caller without the token",
|
||||
));
|
||||
}
|
||||
let mut files = Vec::new();
|
||||
loop {
|
||||
match next(&mut stream)? {
|
||||
(PATH, bytes) => files.push(path(bytes)?),
|
||||
(DONE, _) => break,
|
||||
(tag, _) => {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!("frame {tag} is not a hand-over's"),
|
||||
));
|
||||
}
|
||||
fn answer(
|
||||
stream: &TcpStream,
|
||||
token: &[u8],
|
||||
deliver: &dyn Fn(Vec<PathBuf>) -> bool,
|
||||
) -> io::Result<()> {
|
||||
let mut timed = Timed {
|
||||
stream,
|
||||
until: Instant::now() + PATIENCE,
|
||||
};
|
||||
let (tag, shown) = next(&mut timed, SHOWN)?;
|
||||
if tag != TOKEN || !same(&shown, token) {
|
||||
ely_ipc::write_frame(&mut &*stream, REFUSED, 0, &[])?;
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
"a caller without the token",
|
||||
));
|
||||
}
|
||||
ely_ipc::write_frame(&mut &*stream, OPEN, 0, &[])?;
|
||||
let mut files = Vec::new();
|
||||
loop {
|
||||
match next(&mut timed, LONGEST)? {
|
||||
(PATH, bytes) => files.push(path(bytes)?),
|
||||
(DONE, _) => break,
|
||||
(tag, _) => {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!("frame {tag} is not a hand-over's"),
|
||||
));
|
||||
}
|
||||
}
|
||||
log::info!("instance: another copy handed over {} files", files.len());
|
||||
deliver(files);
|
||||
ely_ipc::write_frame(&mut stream, DONE, 0, &[])
|
||||
}
|
||||
log::info!("instance: another copy handed over {} files", files.len());
|
||||
// No receipt: the caller reports the files untaken.
|
||||
if !deliver(files) {
|
||||
return Err(io::Error::other("the app is quitting and took no files"));
|
||||
}
|
||||
ely_ipc::write_frame(&mut &*stream, DONE, 0, &[])
|
||||
}
|
||||
|
||||
/// A stream whose reads all end by one deadline.
|
||||
struct Timed<'a> {
|
||||
stream: &'a TcpStream,
|
||||
until: Instant,
|
||||
}
|
||||
|
||||
impl Read for Timed<'_> {
|
||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||
let left = self.until.saturating_duration_since(Instant::now());
|
||||
if left.is_zero() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::TimedOut,
|
||||
"a caller held the door too long",
|
||||
));
|
||||
}
|
||||
self.stream.set_read_timeout(Some(left))?;
|
||||
(&mut &*self.stream).read(buf)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,18 +139,17 @@ impl Door {
|
||||
pub(super) fn hand(dir: &Path, files: &[PathBuf], wait: Duration) -> io::Result<()> {
|
||||
let deadline = Instant::now() + wait;
|
||||
loop {
|
||||
match knock(dir) {
|
||||
Ok((stream, token)) => match give(stream, &token, files)? {
|
||||
true => return Ok(()),
|
||||
// An old door file; the new one is coming.
|
||||
false if Instant::now() < deadline => {}
|
||||
false => {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
"it refused the door's token",
|
||||
));
|
||||
}
|
||||
},
|
||||
// Nothing handed yet, so every failure here may retry.
|
||||
match knock(dir).and_then(|(stream, token)| Ok((admit(&stream, &token)?, stream))) {
|
||||
Ok((true, stream)) => return give(&stream, files),
|
||||
// An old door file; the new one is coming.
|
||||
Ok((false, _)) if Instant::now() < deadline => {}
|
||||
Ok((false, _)) => {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
"it refused the door's token",
|
||||
));
|
||||
}
|
||||
Err(_) if Instant::now() < deadline => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
@@ -121,30 +173,44 @@ fn knock(dir: &Path) -> io::Result<(TcpStream, Vec<u8>)> {
|
||||
let token = words.next().and_then(unhex).ok_or_else(bad)?;
|
||||
let stream =
|
||||
TcpStream::connect_timeout(&SocketAddr::from((Ipv4Addr::LOCALHOST, port)), PATIENCE)?;
|
||||
stream.set_read_timeout(Some(PATIENCE))?;
|
||||
lend_foreground(pid);
|
||||
Ok((stream, token))
|
||||
}
|
||||
|
||||
/// Sends the files; false when the door refuses the token.
|
||||
fn give(mut stream: TcpStream, token: &[u8], files: &[PathBuf]) -> io::Result<bool> {
|
||||
stream.set_read_timeout(Some(PATIENCE))?;
|
||||
ely_ipc::write_frame(&mut stream, TOKEN, 0, token)?;
|
||||
for file in files {
|
||||
ely_ipc::write_frame(&mut stream, PATH, 0, &bytes(file))?;
|
||||
}
|
||||
ely_ipc::write_frame(&mut stream, DONE, 0, &[])?;
|
||||
match next(&mut stream)? {
|
||||
(DONE, _) => Ok(true),
|
||||
/// Shows the token; false when the door refuses it.
|
||||
fn admit(stream: &TcpStream, token: &[u8]) -> io::Result<bool> {
|
||||
ely_ipc::write_frame(&mut &*stream, TOKEN, 0, token)?;
|
||||
match next(&mut &*stream, SHOWN)? {
|
||||
(OPEN, _) => Ok(true),
|
||||
(REFUSED, _) => Ok(false),
|
||||
(tag, _) => Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!("it answered frame {tag}"),
|
||||
)),
|
||||
(tag, _) => Err(unexpected(tag)),
|
||||
}
|
||||
}
|
||||
|
||||
fn next(stream: &mut TcpStream) -> io::Result<(u8, Vec<u8>)> {
|
||||
match ely_ipc::read_frame(stream)? {
|
||||
/// Sends the files once admitted; never retried.
|
||||
fn give(stream: &TcpStream, files: &[PathBuf]) -> io::Result<()> {
|
||||
for file in files {
|
||||
ely_ipc::write_frame(&mut &*stream, PATH, 0, &bytes(file))?;
|
||||
}
|
||||
ely_ipc::write_frame(&mut &*stream, DONE, 0, &[])?;
|
||||
// The app may answer after the door's own wait.
|
||||
stream.set_read_timeout(Some(PATIENCE * 2))?;
|
||||
match next(&mut &*stream, SHOWN)? {
|
||||
(DONE, _) => Ok(()),
|
||||
(tag, _) => Err(unexpected(tag)),
|
||||
}
|
||||
}
|
||||
|
||||
fn unexpected(tag: u8) -> io::Error {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!("it answered frame {tag}"),
|
||||
)
|
||||
}
|
||||
|
||||
fn next(stream: &mut impl Read, cap: usize) -> io::Result<(u8, Vec<u8>)> {
|
||||
match ely_ipc::read_capped(stream, cap)? {
|
||||
Some((tag, _, payload)) => Ok((tag, payload)),
|
||||
None => Err(io::Error::new(
|
||||
io::ErrorKind::UnexpectedEof,
|
||||
@@ -226,12 +292,22 @@ mod tests {
|
||||
|
||||
fn opened(dir: &Path) -> std::sync::mpsc::Receiver<Vec<PathBuf>> {
|
||||
let (sender, heard) = std::sync::mpsc::channel();
|
||||
let sender = std::sync::Mutex::new(sender);
|
||||
let door = Door::open(dir).expect("a door");
|
||||
door.serve(move |files| sender.send(files).expect("heard"))
|
||||
door.serve(move |files| sender.lock().expect("a sender").send(files).is_ok())
|
||||
.expect("served");
|
||||
heard
|
||||
}
|
||||
|
||||
/// Writes a door file whose token is wrong.
|
||||
fn forge(dir: &Path) -> String {
|
||||
let door = dir.join(FILE);
|
||||
let text = fs::read_to_string(&door).expect("the door");
|
||||
let (head, _) = text.rsplit_once(' ').expect("a token");
|
||||
fs::write(&door, format!("{head} {}\n", hex(&[7; 32]))).expect("a forged door");
|
||||
text
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hand_over_brings_every_path_whole() {
|
||||
let dir = tempfile::tempdir().expect("a temp dir");
|
||||
@@ -248,22 +324,91 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_wrong_token_hands_nothing_over() {
|
||||
for _ in 0..12 {
|
||||
let dir = tempfile::tempdir().expect("a temp dir");
|
||||
let heard = opened(dir.path());
|
||||
forge(dir.path());
|
||||
let refused = hand(
|
||||
dir.path(),
|
||||
&[PathBuf::from("x.md")],
|
||||
Duration::from_millis(300),
|
||||
);
|
||||
assert_eq!(
|
||||
refused.map_err(|error| error.kind()),
|
||||
Err(io::ErrorKind::PermissionDenied)
|
||||
);
|
||||
assert!(heard.try_recv().is_err(), "nothing reached the copy");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_old_door_file_is_waited_out() {
|
||||
for _ in 0..5 {
|
||||
let dir = tempfile::tempdir().expect("a temp dir");
|
||||
let heard = opened(dir.path());
|
||||
let real = forge(dir.path());
|
||||
let door = dir.path().join(FILE);
|
||||
let fixer = thread::spawn(move || {
|
||||
thread::sleep(Duration::from_millis(100));
|
||||
fs::write(door, real).expect("the real door");
|
||||
});
|
||||
let files = vec![PathBuf::from("x.md")];
|
||||
hand(dir.path(), &files, Duration::from_secs(3))
|
||||
.expect("handed once the door is right");
|
||||
fixer.join().expect("fixed");
|
||||
assert_eq!(heard.recv_timeout(Duration::from_secs(2)), Ok(files));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dripping_caller_neither_blocks_nor_stays() {
|
||||
let dir = tempfile::tempdir().expect("a temp dir");
|
||||
let heard = opened(dir.path());
|
||||
let door = dir.path().join(FILE);
|
||||
let text = fs::read_to_string(&door).expect("the door");
|
||||
let (head, _) = text.rsplit_once(' ').expect("a token");
|
||||
fs::write(&door, format!("{head} {}\n", hex(&[7; 32]))).expect("a forged door");
|
||||
let refused = hand(
|
||||
dir.path(),
|
||||
&[PathBuf::from("x.md")],
|
||||
Duration::from_millis(300),
|
||||
let text = fs::read_to_string(dir.path().join(FILE)).expect("the door");
|
||||
let port: u16 = text
|
||||
.split_whitespace()
|
||||
.next()
|
||||
.and_then(|word| word.parse().ok())
|
||||
.expect("a port");
|
||||
let mut drip = TcpStream::connect((Ipv4Addr::LOCALHOST, port)).expect("connected");
|
||||
let started = Instant::now();
|
||||
let dripper = thread::spawn(move || {
|
||||
// A token frame's header, a byte at a time.
|
||||
for byte in [32u8, 0, 0, 0, TOKEN, 0, 0, 0, 0, 0, 0, 0, 0]
|
||||
.into_iter()
|
||||
.chain([0; 32])
|
||||
{
|
||||
if drip.write_all(&[byte]).is_err() {
|
||||
return;
|
||||
}
|
||||
thread::sleep(Duration::from_millis(300));
|
||||
}
|
||||
});
|
||||
let files = vec![PathBuf::from("x.md")];
|
||||
hand(dir.path(), &files, Duration::from_secs(2)).expect("handed past the drip");
|
||||
assert_eq!(heard.recv_timeout(Duration::from_secs(2)), Ok(files));
|
||||
dripper.join().expect("dripped");
|
||||
let held = started.elapsed();
|
||||
assert!(
|
||||
held < PATIENCE + Duration::from_secs(2),
|
||||
"the drip was cut at the deadline, not after {held:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
refused.map_err(|error| error.kind()),
|
||||
Err(io::ErrorKind::PermissionDenied)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_the_app_did_not_take_are_reported() {
|
||||
let dir = tempfile::tempdir().expect("a temp dir");
|
||||
Door::open(dir.path())
|
||||
.expect("a door")
|
||||
.serve(|_| false)
|
||||
.expect("served");
|
||||
let started = Instant::now();
|
||||
let untaken = hand(dir.path(), &[PathBuf::from("x.md")], Duration::from_secs(3));
|
||||
assert!(untaken.is_err(), "untaken files are no success");
|
||||
assert!(
|
||||
started.elapsed() < Duration::from_secs(1),
|
||||
"sent paths are not sent again"
|
||||
);
|
||||
assert!(heard.try_recv().is_err(), "nothing reached the copy");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+115
-40
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
})
|
||||
|
||||
Reference in new issue
Block a user