zed2.rs

  1mod assets;
  2pub mod languages;
  3mod only_instance;
  4mod open_listener;
  5
  6pub use assets::*;
  7use collections::HashMap;
  8use gpui2::{
  9    point, px, AppContext, AsyncAppContext, AsyncWindowContext, Point, Task, TitlebarOptions,
 10    WeakView, WindowBounds, WindowKind, WindowOptions,
 11};
 12pub use only_instance::*;
 13pub use open_listener::*;
 14
 15use anyhow::{Context, Result};
 16use cli::{
 17    ipc::{self, IpcSender},
 18    CliRequest, CliResponse, IpcHandshake,
 19};
 20use futures::{
 21    channel::{mpsc, oneshot},
 22    FutureExt, SinkExt, StreamExt,
 23};
 24use std::{path::Path, sync::Arc, thread, time::Duration};
 25use util::{paths::PathLikeWithPosition, ResultExt};
 26use uuid::Uuid;
 27use workspace2::{AppState, Workspace};
 28
 29pub fn connect_to_cli(
 30    server_name: &str,
 31) -> Result<(mpsc::Receiver<CliRequest>, IpcSender<CliResponse>)> {
 32    let handshake_tx = cli::ipc::IpcSender::<IpcHandshake>::connect(server_name.to_string())
 33        .context("error connecting to cli")?;
 34    let (request_tx, request_rx) = ipc::channel::<CliRequest>()?;
 35    let (response_tx, response_rx) = ipc::channel::<CliResponse>()?;
 36
 37    handshake_tx
 38        .send(IpcHandshake {
 39            requests: request_tx,
 40            responses: response_rx,
 41        })
 42        .context("error sending ipc handshake")?;
 43
 44    let (mut async_request_tx, async_request_rx) =
 45        futures::channel::mpsc::channel::<CliRequest>(16);
 46    thread::spawn(move || {
 47        while let Ok(cli_request) = request_rx.recv() {
 48            if smol::block_on(async_request_tx.send(cli_request)).is_err() {
 49                break;
 50            }
 51        }
 52        Ok::<_, anyhow::Error>(())
 53    });
 54
 55    Ok((async_request_rx, response_tx))
 56}
 57
 58pub async fn handle_cli_connection(
 59    (mut requests, responses): (mpsc::Receiver<CliRequest>, IpcSender<CliResponse>),
 60    app_state: Arc<AppState>,
 61    mut cx: AsyncAppContext,
 62) {
 63    if let Some(request) = requests.next().await {
 64        match request {
 65            CliRequest::Open { paths, wait } => {
 66                let mut caret_positions = HashMap::default();
 67
 68                let paths = if paths.is_empty() {
 69                    todo!()
 70                    //     workspace::last_opened_workspace_paths()
 71                    //         .await
 72                    //         .map(|location| location.paths().to_vec())
 73                    //         .unwrap_or_default()
 74                } else {
 75                    paths
 76                        .into_iter()
 77                        .filter_map(|path_with_position_string| {
 78                            let path_with_position = PathLikeWithPosition::parse_str(
 79                                &path_with_position_string,
 80                                |path_str| {
 81                                    Ok::<_, std::convert::Infallible>(
 82                                        Path::new(path_str).to_path_buf(),
 83                                    )
 84                                },
 85                            )
 86                            .expect("Infallible");
 87                            let path = path_with_position.path_like;
 88                            if let Some(row) = path_with_position.row {
 89                                if path.is_file() {
 90                                    let row = row.saturating_sub(1);
 91                                    let col =
 92                                        path_with_position.column.unwrap_or(0).saturating_sub(1);
 93                                    caret_positions.insert(path.clone(), Point::new(row, col));
 94                                }
 95                            }
 96                            Some(path)
 97                        })
 98                        .collect::<Vec<_>>()
 99                };
100
101                let mut errored = false;
102
103                if let Some(open_paths_task) = cx
104                    .update(|cx| workspace2::open_paths(&paths, &app_state, None, cx))
105                    .log_err()
106                {
107                    match open_paths_task.await {
108                        Ok((workspace, items)) => {
109                            let mut item_release_futures = Vec::new();
110
111                            for (item, path) in items.into_iter().zip(&paths) {
112                                match item {
113                                    Some(Ok(mut item)) => {
114                                        if let Some(point) = caret_positions.remove(path) {
115                                            todo!()
116                                            // if let Some(active_editor) = item.downcast::<Editor>() {
117                                            //     active_editor
118                                            //         .downgrade()
119                                            //         .update(&mut cx, |editor, cx| {
120                                            //             let snapshot =
121                                            //                 editor.snapshot(cx).display_snapshot;
122                                            //             let point = snapshot
123                                            //                 .buffer_snapshot
124                                            //                 .clip_point(point, Bias::Left);
125                                            //             editor.change_selections(
126                                            //                 Some(Autoscroll::center()),
127                                            //                 cx,
128                                            //                 |s| s.select_ranges([point..point]),
129                                            //             );
130                                            //         })
131                                            //         .log_err();
132                                            // }
133                                        }
134
135                                        let released = oneshot::channel();
136                                        cx.update(move |cx| {
137                                            item.on_release(
138                                                cx,
139                                                Box::new(move |_| {
140                                                    let _ = released.0.send(());
141                                                }),
142                                            )
143                                            .detach();
144                                        });
145                                        item_release_futures.push(released.1);
146                                    }
147                                    Some(Err(err)) => {
148                                        responses
149                                            .send(CliResponse::Stderr {
150                                                message: format!(
151                                                    "error opening {:?}: {}",
152                                                    path, err
153                                                ),
154                                            })
155                                            .log_err();
156                                        errored = true;
157                                    }
158                                    None => {}
159                                }
160                            }
161
162                            if wait {
163                                let executor = cx.background_executor().clone();
164                                let wait = async move {
165                                    if paths.is_empty() {
166                                        let (done_tx, done_rx) = oneshot::channel();
167                                        let _subscription =
168                                            workspace.update(&mut cx, move |_, cx| {
169                                                cx.on_release(|_, _| {
170                                                    let _ = done_tx.send(());
171                                                })
172                                            });
173                                        drop(workspace);
174                                        let _ = done_rx.await;
175                                    } else {
176                                        let _ = futures::future::try_join_all(item_release_futures)
177                                            .await;
178                                    };
179                                }
180                                .fuse();
181                                futures::pin_mut!(wait);
182
183                                loop {
184                                    // Repeatedly check if CLI is still open to avoid wasting resources
185                                    // waiting for files or workspaces to close.
186                                    let mut timer = executor.timer(Duration::from_secs(1)).fuse();
187                                    futures::select_biased! {
188                                        _ = wait => break,
189                                        _ = timer => {
190                                            if responses.send(CliResponse::Ping).is_err() {
191                                                break;
192                                            }
193                                        }
194                                    }
195                                }
196                            }
197                        }
198                        Err(error) => {
199                            errored = true;
200                            responses
201                                .send(CliResponse::Stderr {
202                                    message: format!("error opening {:?}: {}", paths, error),
203                                })
204                                .log_err();
205                        }
206                    }
207
208                    responses
209                        .send(CliResponse::Exit {
210                            status: i32::from(errored),
211                        })
212                        .log_err();
213                }
214            }
215        }
216    }
217}
218
219pub fn build_window_options(
220    bounds: Option<WindowBounds>,
221    display_uuid: Option<Uuid>,
222    cx: &mut AppContext,
223) -> WindowOptions {
224    let bounds = bounds.unwrap_or(WindowBounds::Maximized);
225    let display = display_uuid.and_then(|uuid| {
226        cx.displays()
227            .into_iter()
228            .find(|display| display.uuid().ok() == Some(uuid))
229    });
230
231    WindowOptions {
232        bounds,
233        titlebar: Some(TitlebarOptions {
234            title: None,
235            appears_transparent: true,
236            traffic_light_position: Some(point(px(8.), px(8.))),
237        }),
238        center: false,
239        focus: false,
240        show: false,
241        kind: WindowKind::Normal,
242        is_movable: false,
243        display_id: display.map(|display| display.id()),
244    }
245}
246
247pub fn initialize_workspace(
248    workspace_handle: WeakView<Workspace>,
249    was_deserialized: bool,
250    app_state: Arc<AppState>,
251    cx: AsyncWindowContext,
252) -> Task<Result<()>> {
253    cx.spawn(|mut cx| async move {
254        workspace_handle.update(&mut cx, |workspace, cx| {
255            let workspace_handle = cx.view();
256            cx.subscribe(&workspace_handle, {
257                move |workspace, _, event, cx| {
258                    if let workspace2::Event::PaneAdded(pane) = event {
259                        pane.update(cx, |pane, cx| {
260                            // todo!()
261                            // pane.toolbar().update(cx, |toolbar, cx| {
262                            //     let breadcrumbs = cx.add_view(|_| Breadcrumbs::new(workspace));
263                            //     toolbar.add_item(breadcrumbs, cx);
264                            //     let buffer_search_bar = cx.add_view(BufferSearchBar::new);
265                            //     toolbar.add_item(buffer_search_bar.clone(), cx);
266                            //     let quick_action_bar = cx.add_view(|_| {
267                            //         QuickActionBar::new(buffer_search_bar, workspace)
268                            //     });
269                            //     toolbar.add_item(quick_action_bar, cx);
270                            //     let diagnostic_editor_controls =
271                            //         cx.add_view(|_| diagnostics2::ToolbarControls::new());
272                            //     toolbar.add_item(diagnostic_editor_controls, cx);
273                            //     let project_search_bar = cx.add_view(|_| ProjectSearchBar::new());
274                            //     toolbar.add_item(project_search_bar, cx);
275                            //     let submit_feedback_button =
276                            //         cx.add_view(|_| SubmitFeedbackButton::new());
277                            //     toolbar.add_item(submit_feedback_button, cx);
278                            //     let feedback_info_text = cx.add_view(|_| FeedbackInfoText::new());
279                            //     toolbar.add_item(feedback_info_text, cx);
280                            //     let lsp_log_item =
281                            //         cx.add_view(|_| language_tools::LspLogToolbarItemView::new());
282                            //     toolbar.add_item(lsp_log_item, cx);
283                            //     let syntax_tree_item = cx
284                            //         .add_view(|_| language_tools::SyntaxTreeToolbarItemView::new());
285                            //     toolbar.add_item(syntax_tree_item, cx);
286                            // })
287                        });
288                    }
289                }
290            })
291            .detach();
292
293            //     cx.emit(workspace2::Event::PaneAdded(
294            //         workspace.active_pane().clone(),
295            //     ));
296
297            //     let collab_titlebar_item =
298            //         cx.add_view(|cx| CollabTitlebarItem::new(workspace, &workspace_handle, cx));
299            //     workspace.set_titlebar_item(collab_titlebar_item.into_any(), cx);
300
301            //     let copilot =
302            //         cx.add_view(|cx| copilot_button::CopilotButton::new(app_state.fs.clone(), cx));
303            //     let diagnostic_summary =
304            //         cx.add_view(|cx| diagnostics::items::DiagnosticIndicator::new(workspace, cx));
305            //     let activity_indicator = activity_indicator::ActivityIndicator::new(
306            //         workspace,
307            //         app_state.languages.clone(),
308            //         cx,
309            //     );
310            //     let active_buffer_language =
311            //         cx.add_view(|_| language_selector::ActiveBufferLanguage::new(workspace));
312            //     let vim_mode_indicator = cx.add_view(|cx| vim::ModeIndicator::new(cx));
313            //     let feedback_button = cx.add_view(|_| {
314            //         feedback::deploy_feedback_button::DeployFeedbackButton::new(workspace)
315            //     });
316            //     let cursor_position = cx.add_view(|_| editor::items::CursorPosition::new());
317            //     workspace.status_bar().update(cx, |status_bar, cx| {
318            //         status_bar.add_left_item(diagnostic_summary, cx);
319            //         status_bar.add_left_item(activity_indicator, cx);
320
321            //         status_bar.add_right_item(feedback_button, cx);
322            //         status_bar.add_right_item(copilot, cx);
323            //         status_bar.add_right_item(active_buffer_language, cx);
324            //         status_bar.add_right_item(vim_mode_indicator, cx);
325            //         status_bar.add_right_item(cursor_position, cx);
326            //     });
327
328            //     auto_update::notify_of_any_new_update(cx.weak_handle(), cx);
329
330            //     vim::observe_keystrokes(cx);
331
332            //     cx.on_window_should_close(|workspace, cx| {
333            //         if let Some(task) = workspace.close(&Default::default(), cx) {
334            //             task.detach_and_log_err(cx);
335            //         }
336            //         false
337            //     });
338            // })?;
339
340            // let project_panel = ProjectPanel::load(workspace_handle.clone(), cx.clone());
341            // let terminal_panel = TerminalPanel::load(workspace_handle.clone(), cx.clone());
342            // let assistant_panel = AssistantPanel::load(workspace_handle.clone(), cx.clone());
343            // let channels_panel =
344            //     collab_ui::collab_panel::CollabPanel::load(workspace_handle.clone(), cx.clone());
345            // let chat_panel =
346            //     collab_ui::chat_panel::ChatPanel::load(workspace_handle.clone(), cx.clone());
347            // let notification_panel = collab_ui::notification_panel::NotificationPanel::load(
348            //     workspace_handle.clone(),
349            //     cx.clone(),
350            // );
351            // let (
352            //     project_panel,
353            //     terminal_panel,
354            //     assistant_panel,
355            //     channels_panel,
356            //     chat_panel,
357            //     notification_panel,
358            // ) = futures::try_join!(
359            //     project_panel,
360            //     terminal_panel,
361            //     assistant_panel,
362            //     channels_panel,
363            //     chat_panel,
364            //     notification_panel,
365            // )?;
366            // workspace_handle.update(&mut cx, |workspace, cx| {
367            //     let project_panel_position = project_panel.position(cx);
368            //     workspace.add_panel_with_extra_event_handler(
369            //         project_panel,
370            //         cx,
371            //         |workspace, _, event, cx| match event {
372            //             project_panel::Event::NewSearchInDirectory { dir_entry } => {
373            //                 search::ProjectSearchView::new_search_in_directory(workspace, dir_entry, cx)
374            //             }
375            //             project_panel::Event::ActivatePanel => {
376            //                 workspace.focus_panel::<ProjectPanel>(cx);
377            //             }
378            //             _ => {}
379            //         },
380            //     );
381            //     workspace.add_panel(terminal_panel, cx);
382            //     workspace.add_panel(assistant_panel, cx);
383            //     workspace.add_panel(channels_panel, cx);
384            //     workspace.add_panel(chat_panel, cx);
385            //     workspace.add_panel(notification_panel, cx);
386
387            //     if !was_deserialized
388            //         && workspace
389            //             .project()
390            //             .read(cx)
391            //             .visible_worktrees(cx)
392            //             .any(|tree| {
393            //                 tree.read(cx)
394            //                     .root_entry()
395            //                     .map_or(false, |entry| entry.is_dir())
396            //             })
397            //     {
398            //         workspace.toggle_dock(project_panel_position, cx);
399            //     }
400            //     cx.focus_self();
401        })?;
402        Ok(())
403    })
404}