mirror of
https://github.com/zed-industries/zed.git
synced 2024-11-07 20:39:04 +03:00
Use ipc_channel crate to communicate between cli and app
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>
This commit is contained in:
parent
01eb2dce24
commit
75f0326e54
1
Cargo.lock
generated
1
Cargo.lock
generated
@ -6344,6 +6344,7 @@ dependencies = [
|
|||||||
"async-trait",
|
"async-trait",
|
||||||
"breadcrumbs",
|
"breadcrumbs",
|
||||||
"chat_panel",
|
"chat_panel",
|
||||||
|
"cli",
|
||||||
"client",
|
"client",
|
||||||
"clock",
|
"clock",
|
||||||
"collections",
|
"collections",
|
||||||
|
@ -3,6 +3,14 @@ name = "cli"
|
|||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
|
[lib]
|
||||||
|
path = "src/cli.rs"
|
||||||
|
doctest = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "cli"
|
||||||
|
path = "src/main.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
anyhow = "1.0"
|
anyhow = "1.0"
|
||||||
core-foundation = "0.9"
|
core-foundation = "0.9"
|
||||||
|
21
crates/cli/src/cli.rs
Normal file
21
crates/cli/src/cli.rs
Normal file
@ -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 },
|
||||||
|
}
|
@ -1,14 +1,14 @@
|
|||||||
use anyhow::{anyhow, Result};
|
use anyhow::{anyhow, Result};
|
||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
|
use cli::{CliRequest, CliResponse, IpcHandshake};
|
||||||
use core_foundation::{
|
use core_foundation::{
|
||||||
array::{CFArray, CFIndex},
|
array::{CFArray, CFIndex},
|
||||||
string::kCFStringEncodingUTF8,
|
string::kCFStringEncodingUTF8,
|
||||||
url::{CFURLCreateWithBytes, CFURL},
|
url::{CFURLCreateWithBytes, CFURL},
|
||||||
};
|
};
|
||||||
use core_services::{kLSLaunchDefaults, LSLaunchURLSpec, LSOpenFromURLSpec, TCFType};
|
use core_services::{kLSLaunchDefaults, LSLaunchURLSpec, LSOpenFromURLSpec, TCFType};
|
||||||
use ipc_channel::ipc::IpcOneShotServer;
|
use ipc_channel::ipc::{IpcOneShotServer, IpcReceiver, IpcSender};
|
||||||
use serde::{Deserialize, Serialize};
|
use std::{fs, path::PathBuf, ptr};
|
||||||
use std::{path::PathBuf, process, ptr};
|
|
||||||
|
|
||||||
#[derive(Parser)]
|
#[derive(Parser)]
|
||||||
#[clap(name = "zed")]
|
#[clap(name = "zed")]
|
||||||
@ -21,61 +21,55 @@ struct Args {
|
|||||||
paths: Vec<PathBuf>,
|
paths: Vec<PathBuf>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize)]
|
|
||||||
struct OpenResult {
|
|
||||||
exit_status: i32,
|
|
||||||
stdout_message: Option<String>,
|
|
||||||
stderr_message: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() -> Result<()> {
|
fn main() -> Result<()> {
|
||||||
let args = Args::parse();
|
let args = Args::parse();
|
||||||
|
|
||||||
let (server, server_name) = IpcOneShotServer::<OpenResult>::new()?;
|
|
||||||
let app_path = locate_app()?;
|
let app_path = locate_app()?;
|
||||||
launch_app(app_path, args.paths, server_name)?;
|
let (tx, rx) = launch_app(app_path)?;
|
||||||
|
|
||||||
let (_, result) = server.accept()?;
|
tx.send(CliRequest::Open {
|
||||||
if let Some(message) = result.stdout_message {
|
paths: args
|
||||||
println!("{}", message);
|
.paths
|
||||||
}
|
.into_iter()
|
||||||
if let Some(message) = result.stderr_message {
|
.map(|path| fs::canonicalize(path).map_err(|error| anyhow!(error)))
|
||||||
eprintln!("{}", message);
|
.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> {
|
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 status = unsafe {
|
||||||
let app_url =
|
let app_url =
|
||||||
CFURL::from_path(&app_path, true).ok_or_else(|| anyhow!("invalid app path"))?;
|
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}");
|
let url = format!("zed-cli://{server_name}");
|
||||||
urls_to_open.push(CFURL::wrap_under_create_rule(CFURLCreateWithBytes(
|
let url_to_open = CFURL::wrap_under_create_rule(CFURLCreateWithBytes(
|
||||||
ptr::null(),
|
ptr::null(),
|
||||||
server_url.as_ptr(),
|
url.as_ptr(),
|
||||||
server_url.len() as CFIndex,
|
url.len() as CFIndex,
|
||||||
kCFStringEncodingUTF8,
|
kCFStringEncodingUTF8,
|
||||||
ptr::null(),
|
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(
|
LSOpenFromURLSpec(
|
||||||
&LSLaunchURLSpec {
|
&LSLaunchURLSpec {
|
||||||
appURL: app_url.as_concrete_TypeRef(),
|
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(),
|
ptr::null_mut(),
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
|
|
||||||
if status == 0 {
|
if status == 0 {
|
||||||
Ok(())
|
let (_, handshake) = server.accept()?;
|
||||||
|
Ok((handshake.requests, handshake.responses))
|
||||||
} else {
|
} else {
|
||||||
Err(anyhow!("cannot start {:?}", app_path))
|
Err(anyhow!("cannot start {:?}", app_path))
|
||||||
}
|
}
|
||||||
|
@ -248,7 +248,7 @@ impl App {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn on_quit<F>(self, mut callback: F) -> Self
|
pub fn on_quit<F>(&mut self, mut callback: F) -> &mut Self
|
||||||
where
|
where
|
||||||
F: 'static + FnMut(&mut MutableAppContext),
|
F: 'static + FnMut(&mut MutableAppContext),
|
||||||
{
|
{
|
||||||
@ -260,7 +260,7 @@ impl App {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn on_event<F>(self, mut callback: F) -> Self
|
pub fn on_event<F>(&mut self, mut callback: F) -> &mut Self
|
||||||
where
|
where
|
||||||
F: 'static + FnMut(Event, &mut MutableAppContext) -> bool,
|
F: 'static + FnMut(Event, &mut MutableAppContext) -> bool,
|
||||||
{
|
{
|
||||||
@ -274,7 +274,7 @@ impl App {
|
|||||||
self
|
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
|
where
|
||||||
F: 'static + FnMut(Vec<PathBuf>, &mut MutableAppContext),
|
F: 'static + FnMut(Vec<PathBuf>, &mut MutableAppContext),
|
||||||
{
|
{
|
||||||
@ -288,6 +288,20 @@ impl App {
|
|||||||
self
|
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)
|
pub fn run<F>(self, on_finish_launching: F)
|
||||||
where
|
where
|
||||||
F: 'static + FnOnce(&mut MutableAppContext),
|
F: 'static + FnOnce(&mut MutableAppContext),
|
||||||
|
@ -64,6 +64,7 @@ pub(crate) trait ForegroundPlatform {
|
|||||||
fn on_quit(&self, callback: Box<dyn FnMut()>);
|
fn on_quit(&self, callback: Box<dyn FnMut()>);
|
||||||
fn on_event(&self, callback: Box<dyn FnMut(Event) -> bool>);
|
fn on_event(&self, callback: Box<dyn FnMut(Event) -> bool>);
|
||||||
fn on_open_files(&self, callback: Box<dyn FnMut(Vec<PathBuf>)>);
|
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 run(&self, on_finish_launching: Box<dyn FnOnce() -> ()>);
|
||||||
|
|
||||||
fn on_menu_command(&self, callback: Box<dyn FnMut(&dyn Action)>);
|
fn on_menu_command(&self, callback: Box<dyn FnMut(&dyn Action)>);
|
||||||
|
@ -113,6 +113,7 @@ pub struct MacForegroundPlatformState {
|
|||||||
event: Option<Box<dyn FnMut(crate::Event) -> bool>>,
|
event: Option<Box<dyn FnMut(crate::Event) -> bool>>,
|
||||||
menu_command: Option<Box<dyn FnMut(&dyn Action)>>,
|
menu_command: Option<Box<dyn FnMut(&dyn Action)>>,
|
||||||
open_files: Option<Box<dyn FnMut(Vec<PathBuf>)>>,
|
open_files: Option<Box<dyn FnMut(Vec<PathBuf>)>>,
|
||||||
|
open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
|
||||||
finish_launching: Option<Box<dyn FnOnce() -> ()>>,
|
finish_launching: Option<Box<dyn FnOnce() -> ()>>,
|
||||||
menu_actions: Vec<Box<dyn Action>>,
|
menu_actions: Vec<Box<dyn Action>>,
|
||||||
}
|
}
|
||||||
@ -218,6 +219,10 @@ impl platform::ForegroundPlatform for MacForegroundPlatform {
|
|||||||
self.0.borrow_mut().open_files = Some(callback);
|
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() -> ()>) {
|
fn run(&self, on_finish_launching: Box<dyn FnOnce() -> ()>) {
|
||||||
self.0.borrow_mut().finish_launching = Some(on_finish_launching);
|
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) {
|
extern "C" fn open_urls(this: &mut Object, _: Sel, _: id, urls: id) {
|
||||||
let paths = unsafe {
|
let urls = unsafe {
|
||||||
(0..paths.count())
|
(0..urls.count())
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter_map(|i| {
|
.filter_map(|i| {
|
||||||
let path = paths.objectAtIndex(i);
|
let path = urls.objectAtIndex(i);
|
||||||
match dbg!(
|
match dbg!(
|
||||||
CStr::from_ptr(path.absoluteString().UTF8String() as *mut c_char).to_str()
|
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) => {
|
Err(err) => {
|
||||||
log::error!("error converting path to string: {}", err);
|
log::error!("error converting path to string: {}", err);
|
||||||
None
|
None
|
||||||
@ -724,10 +729,10 @@ extern "C" fn open_urls(this: &mut Object, _: Sel, _: id, paths: id) {
|
|||||||
})
|
})
|
||||||
.collect::<Vec<_>>()
|
.collect::<Vec<_>>()
|
||||||
};
|
};
|
||||||
// let platform = unsafe { get_foreground_platform(this) };
|
let platform = unsafe { get_foreground_platform(this) };
|
||||||
// if let Some(callback) = platform.0.borrow_mut().open_files.as_mut() {
|
if let Some(callback) = platform.0.borrow_mut().open_urls.as_mut() {
|
||||||
// callback(paths);
|
callback(urls);
|
||||||
// }
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extern "C" fn handle_menu_item(this: &mut Object, _: Sel, item: id) {
|
extern "C" fn handle_menu_item(this: &mut Object, _: Sel, item: id) {
|
||||||
|
@ -68,6 +68,8 @@ impl super::ForegroundPlatform for ForegroundPlatform {
|
|||||||
|
|
||||||
fn on_open_files(&self, _: Box<dyn FnMut(Vec<std::path::PathBuf>)>) {}
|
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() -> ()>) {
|
fn run(&self, _on_finish_launching: Box<dyn FnOnce() -> ()>) {
|
||||||
unimplemented!()
|
unimplemented!()
|
||||||
}
|
}
|
||||||
|
@ -32,6 +32,7 @@ test-support = [
|
|||||||
assets = { path = "../assets" }
|
assets = { path = "../assets" }
|
||||||
breadcrumbs = { path = "../breadcrumbs" }
|
breadcrumbs = { path = "../breadcrumbs" }
|
||||||
chat_panel = { path = "../chat_panel" }
|
chat_panel = { path = "../chat_panel" }
|
||||||
|
cli = { path = "../cli" }
|
||||||
collections = { path = "../collections" }
|
collections = { path = "../collections" }
|
||||||
command_palette = { path = "../command_palette" }
|
command_palette = { path = "../command_palette" }
|
||||||
client = { path = "../client" }
|
client = { path = "../client" }
|
||||||
|
@ -3,6 +3,7 @@
|
|||||||
|
|
||||||
use anyhow::{anyhow, Context, Result};
|
use anyhow::{anyhow, Context, Result};
|
||||||
use assets::Assets;
|
use assets::Assets;
|
||||||
|
use cli::{ipc, CliRequest, CliResponse, IpcHandshake};
|
||||||
use client::{self, http, ChannelList, UserStore};
|
use client::{self, http, ChannelList, UserStore};
|
||||||
use fs::OpenOptions;
|
use fs::OpenOptions;
|
||||||
use futures::{channel::oneshot, StreamExt};
|
use futures::{channel::oneshot, StreamExt};
|
||||||
@ -26,7 +27,7 @@ use zed::{
|
|||||||
fn main() {
|
fn main() {
|
||||||
init_logger();
|
init_logger();
|
||||||
|
|
||||||
let app = gpui::App::new(Assets).unwrap();
|
let mut app = gpui::App::new(Assets).unwrap();
|
||||||
load_embedded_fonts(&app);
|
load_embedded_fonts(&app);
|
||||||
|
|
||||||
let fs = Arc::new(RealFs);
|
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| {
|
app.run(move |cx| {
|
||||||
let http = http::client();
|
let http = http::client();
|
||||||
let client = client::Client::new(http.clone());
|
let client = client::Client::new(http.clone());
|
||||||
@ -292,3 +299,29 @@ fn load_config_files(
|
|||||||
.detach();
|
.detach();
|
||||||
rx
|
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(())
|
||||||
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user