Use ipc_channel crate to communicate between cli and app

Nathan Sobo and Max Brunsfeld created

We still aren't handling CLI requests in the app, but this lays the foundation for bi-directional communication.

Co-Authored-By: Max Brunsfeld <maxbrunsfeld@gmail.com>

Change summary

Cargo.lock                               |  1 
crates/cli/Cargo.toml                    |  8 ++
crates/cli/src/cli.rs                    | 21 +++++++
crates/cli/src/main.rs                   | 74 ++++++++++++-------------
crates/gpui/src/app.rs                   | 20 +++++-
crates/gpui/src/platform.rs              |  1 
crates/gpui/src/platform/mac/platform.rs | 23 ++++---
crates/gpui/src/platform/test.rs         |  2 
crates/zed/Cargo.toml                    |  1 
crates/zed/src/main.rs                   | 35 +++++++++++
10 files changed, 134 insertions(+), 52 deletions(-)

Detailed changes

Cargo.lock 🔗

@@ -6344,6 +6344,7 @@ dependencies = [
  "async-trait",
  "breadcrumbs",
  "chat_panel",
+ "cli",
  "client",
  "clock",
  "collections",

crates/cli/Cargo.toml 🔗

@@ -3,6 +3,14 @@ name = "cli"
 version = "0.1.0"
 edition = "2021"
 
+[lib]
+path = "src/cli.rs"
+doctest = false
+
+[[bin]]
+name = "cli"
+path = "src/main.rs"
+
 [dependencies]
 anyhow = "1.0"
 core-foundation = "0.9"

crates/cli/src/cli.rs 🔗

@@ -0,0 +1,21 @@
+pub use ipc_channel::ipc;
+use serde::{Deserialize, Serialize};
+use std::path::PathBuf;
+
+#[derive(Serialize, Deserialize)]
+pub struct IpcHandshake {
+    pub requests: ipc::IpcSender<CliRequest>,
+    pub responses: ipc::IpcReceiver<CliResponse>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub enum CliRequest {
+    Open { paths: Vec<PathBuf>, wait: bool },
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub enum CliResponse {
+    Stdout { message: String },
+    Stderr { message: String },
+    Exit { status: i32 },
+}

crates/cli/src/main.rs 🔗

@@ -1,14 +1,14 @@
 use anyhow::{anyhow, Result};
 use clap::Parser;
+use cli::{CliRequest, CliResponse, IpcHandshake};
 use core_foundation::{
     array::{CFArray, CFIndex},
     string::kCFStringEncodingUTF8,
     url::{CFURLCreateWithBytes, CFURL},
 };
 use core_services::{kLSLaunchDefaults, LSLaunchURLSpec, LSOpenFromURLSpec, TCFType};
-use ipc_channel::ipc::IpcOneShotServer;
-use serde::{Deserialize, Serialize};
-use std::{path::PathBuf, process, ptr};
+use ipc_channel::ipc::{IpcOneShotServer, IpcReceiver, IpcSender};
+use std::{fs, path::PathBuf, ptr};
 
 #[derive(Parser)]
 #[clap(name = "zed")]
@@ -21,61 +21,55 @@ struct Args {
     paths: Vec<PathBuf>,
 }
 
-#[derive(Serialize, Deserialize)]
-struct OpenResult {
-    exit_status: i32,
-    stdout_message: Option<String>,
-    stderr_message: Option<String>,
-}
-
 fn main() -> Result<()> {
     let args = Args::parse();
 
-    let (server, server_name) = IpcOneShotServer::<OpenResult>::new()?;
     let app_path = locate_app()?;
-    launch_app(app_path, args.paths, server_name)?;
+    let (tx, rx) = launch_app(app_path)?;
 
-    let (_, result) = server.accept()?;
-    if let Some(message) = result.stdout_message {
-        println!("{}", message);
-    }
-    if let Some(message) = result.stderr_message {
-        eprintln!("{}", message);
+    tx.send(CliRequest::Open {
+        paths: args
+            .paths
+            .into_iter()
+            .map(|path| fs::canonicalize(path).map_err(|error| anyhow!(error)))
+            .collect::<Result<Vec<PathBuf>>>()?,
+        wait: false,
+    })?;
+
+    while let Ok(response) = rx.recv() {
+        match response {
+            CliResponse::Stdout { message } => println!("{message}"),
+            CliResponse::Stderr { message } => eprintln!("{message}"),
+            CliResponse::Exit { status } => std::process::exit(status),
+        }
     }
 
-    process::exit(result.exit_status)
+    Ok(())
 }
 
 fn locate_app() -> Result<PathBuf> {
-    Ok("/Applications/Zed.app".into())
+    Ok("/Users/nathan/src/zed/target/debug/bundle/osx/Zed.app".into())
+    // Ok("/Applications/Zed.app".into())
 }
 
-fn launch_app(app_path: PathBuf, paths_to_open: Vec<PathBuf>, server_name: String) -> Result<()> {
+fn launch_app(app_path: PathBuf) -> Result<(IpcSender<CliRequest>, IpcReceiver<CliResponse>)> {
+    let (server, server_name) = IpcOneShotServer::<IpcHandshake>::new()?;
+
     let status = unsafe {
         let app_url =
             CFURL::from_path(&app_path, true).ok_or_else(|| anyhow!("invalid app path"))?;
-        let mut urls_to_open = paths_to_open
-            .into_iter()
-            .map(|path| {
-                CFURL::from_path(&path, true).ok_or_else(|| anyhow!("{:?} is invalid", path))
-            })
-            .collect::<Result<Vec<_>>>()?;
 
-        let server_url = format!("zed_cli_response://{server_name}");
-        urls_to_open.push(CFURL::wrap_under_create_rule(CFURLCreateWithBytes(
+        let url = format!("zed-cli://{server_name}");
+        let url_to_open = CFURL::wrap_under_create_rule(CFURLCreateWithBytes(
             ptr::null(),
-            server_url.as_ptr(),
-            server_url.len() as CFIndex,
+            url.as_ptr(),
+            url.len() as CFIndex,
             kCFStringEncodingUTF8,
             ptr::null(),
-        )));
+        ));
+
+        let urls_to_open = CFArray::from_copyable(&[url_to_open.as_concrete_TypeRef()]);
 
-        let urls_to_open = CFArray::from_copyable(
-            &urls_to_open
-                .iter()
-                .map(|url| url.as_concrete_TypeRef())
-                .collect::<Vec<_>>(),
-        );
         LSOpenFromURLSpec(
             &LSLaunchURLSpec {
                 appURL: app_url.as_concrete_TypeRef(),
@@ -87,8 +81,10 @@ fn launch_app(app_path: PathBuf, paths_to_open: Vec<PathBuf>, server_name: Strin
             ptr::null_mut(),
         )
     };
+
     if status == 0 {
-        Ok(())
+        let (_, handshake) = server.accept()?;
+        Ok((handshake.requests, handshake.responses))
     } else {
         Err(anyhow!("cannot start {:?}", app_path))
     }

crates/gpui/src/app.rs 🔗

@@ -248,7 +248,7 @@ impl App {
         self
     }
 
-    pub fn on_quit<F>(self, mut callback: F) -> Self
+    pub fn on_quit<F>(&mut self, mut callback: F) -> &mut Self
     where
         F: 'static + FnMut(&mut MutableAppContext),
     {
@@ -260,7 +260,7 @@ impl App {
         self
     }
 
-    pub fn on_event<F>(self, mut callback: F) -> Self
+    pub fn on_event<F>(&mut self, mut callback: F) -> &mut Self
     where
         F: 'static + FnMut(Event, &mut MutableAppContext) -> bool,
     {
@@ -274,7 +274,7 @@ impl App {
         self
     }
 
-    pub fn on_open_files<F>(self, mut callback: F) -> Self
+    pub fn on_open_files<F>(&mut self, mut callback: F) -> &mut Self
     where
         F: 'static + FnMut(Vec<PathBuf>, &mut MutableAppContext),
     {
@@ -288,6 +288,20 @@ impl App {
         self
     }
 
+    pub fn on_open_urls<F>(&mut self, mut callback: F) -> &mut Self
+    where
+        F: 'static + FnMut(Vec<String>, &mut MutableAppContext),
+    {
+        let cx = self.0.clone();
+        self.0
+            .borrow_mut()
+            .foreground_platform
+            .on_open_urls(Box::new(move |paths| {
+                callback(paths, &mut *cx.borrow_mut())
+            }));
+        self
+    }
+
     pub fn run<F>(self, on_finish_launching: F)
     where
         F: 'static + FnOnce(&mut MutableAppContext),

crates/gpui/src/platform.rs 🔗

@@ -64,6 +64,7 @@ pub(crate) trait ForegroundPlatform {
     fn on_quit(&self, callback: Box<dyn FnMut()>);
     fn on_event(&self, callback: Box<dyn FnMut(Event) -> bool>);
     fn on_open_files(&self, callback: Box<dyn FnMut(Vec<PathBuf>)>);
+    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>);
     fn run(&self, on_finish_launching: Box<dyn FnOnce() -> ()>);
 
     fn on_menu_command(&self, callback: Box<dyn FnMut(&dyn Action)>);

crates/gpui/src/platform/mac/platform.rs 🔗

@@ -113,6 +113,7 @@ pub struct MacForegroundPlatformState {
     event: Option<Box<dyn FnMut(crate::Event) -> bool>>,
     menu_command: Option<Box<dyn FnMut(&dyn Action)>>,
     open_files: Option<Box<dyn FnMut(Vec<PathBuf>)>>,
+    open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
     finish_launching: Option<Box<dyn FnOnce() -> ()>>,
     menu_actions: Vec<Box<dyn Action>>,
 }
@@ -218,6 +219,10 @@ impl platform::ForegroundPlatform for MacForegroundPlatform {
         self.0.borrow_mut().open_files = Some(callback);
     }
 
+    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
+        self.0.borrow_mut().open_urls = Some(callback);
+    }
+
     fn run(&self, on_finish_launching: Box<dyn FnOnce() -> ()>) {
         self.0.borrow_mut().finish_launching = Some(on_finish_launching);
 
@@ -706,16 +711,16 @@ extern "C" fn open_files(this: &mut Object, _: Sel, _: id, paths: id) {
     }
 }
 
-extern "C" fn open_urls(this: &mut Object, _: Sel, _: id, paths: id) {
-    let paths = unsafe {
-        (0..paths.count())
+extern "C" fn open_urls(this: &mut Object, _: Sel, _: id, urls: id) {
+    let urls = unsafe {
+        (0..urls.count())
             .into_iter()
             .filter_map(|i| {
-                let path = paths.objectAtIndex(i);
+                let path = urls.objectAtIndex(i);
                 match dbg!(
                     CStr::from_ptr(path.absoluteString().UTF8String() as *mut c_char).to_str()
                 ) {
-                    Ok(string) => Some(PathBuf::from(string)),
+                    Ok(string) => Some(string.to_string()),
                     Err(err) => {
                         log::error!("error converting path to string: {}", err);
                         None
@@ -724,10 +729,10 @@ extern "C" fn open_urls(this: &mut Object, _: Sel, _: id, paths: id) {
             })
             .collect::<Vec<_>>()
     };
-    // let platform = unsafe { get_foreground_platform(this) };
-    // if let Some(callback) = platform.0.borrow_mut().open_files.as_mut() {
-    //     callback(paths);
-    // }
+    let platform = unsafe { get_foreground_platform(this) };
+    if let Some(callback) = platform.0.borrow_mut().open_urls.as_mut() {
+        callback(urls);
+    }
 }
 
 extern "C" fn handle_menu_item(this: &mut Object, _: Sel, item: id) {

crates/gpui/src/platform/test.rs 🔗

@@ -68,6 +68,8 @@ impl super::ForegroundPlatform for ForegroundPlatform {
 
     fn on_open_files(&self, _: Box<dyn FnMut(Vec<std::path::PathBuf>)>) {}
 
+    fn on_open_urls(&self, _: Box<dyn FnMut(Vec<String>)>) {}
+
     fn run(&self, _on_finish_launching: Box<dyn FnOnce() -> ()>) {
         unimplemented!()
     }

crates/zed/Cargo.toml 🔗

@@ -32,6 +32,7 @@ test-support = [
 assets = { path = "../assets" }
 breadcrumbs = { path = "../breadcrumbs" }
 chat_panel = { path = "../chat_panel" }
+cli = { path = "../cli" }
 collections = { path = "../collections" }
 command_palette = { path = "../command_palette" }
 client = { path = "../client" }

crates/zed/src/main.rs 🔗

@@ -3,6 +3,7 @@
 
 use anyhow::{anyhow, Context, Result};
 use assets::Assets;
+use cli::{ipc, CliRequest, CliResponse, IpcHandshake};
 use client::{self, http, ChannelList, UserStore};
 use fs::OpenOptions;
 use futures::{channel::oneshot, StreamExt};
@@ -26,7 +27,7 @@ use zed::{
 fn main() {
     init_logger();
 
-    let app = gpui::App::new(Assets).unwrap();
+    let mut app = gpui::App::new(Assets).unwrap();
     load_embedded_fonts(&app);
 
     let fs = Arc::new(RealFs);
@@ -87,6 +88,12 @@ fn main() {
         })
     };
 
+    app.on_open_urls(|urls, _| {
+        if let Some(server_name) = urls.first().and_then(|url| url.strip_prefix("zed-cli://")) {
+            connect_to_cli(server_name).log_err();
+        }
+    });
+
     app.run(move |cx| {
         let http = http::client();
         let client = client::Client::new(http.clone());
@@ -292,3 +299,29 @@ fn load_config_files(
         .detach();
     rx
 }
+
+fn connect_to_cli(server_name: &str) -> Result<()> {
+    let handshake_tx = cli::ipc::IpcSender::<IpcHandshake>::connect(server_name.to_string())
+        .context("error connecting to cli")?;
+    let (request_tx, request_rx) = ipc::channel::<CliRequest>()?;
+    let (response_tx, response_rx) = ipc::channel::<CliResponse>()?;
+
+    handshake_tx
+        .send(IpcHandshake {
+            requests: request_tx,
+            responses: response_rx,
+        })
+        .context("error sending ipc handshake")?;
+
+    std::thread::spawn(move || {
+        while let Ok(cli_request) = request_rx.recv() {
+            log::info!("{cli_request:?}");
+            response_tx.send(CliResponse::Stdout {
+                message: "Hi, CLI!".into(),
+            })?;
+            response_tx.send(CliResponse::Exit { status: 0 })?;
+        }
+        Ok::<_, anyhow::Error>(())
+    });
+    Ok(())
+}