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, MainThread, Point, Task,
10 TitlebarOptions, WeakView, WindowBounds, WindowHandle, 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.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 MainThread<AppContext>,
223) -> WindowOptions {
224 let bounds = bounds.unwrap_or(WindowBounds::Maximized);
225 let display = display_uuid.and_then(|uuid| cx.display_for_uuid(uuid));
226
227 WindowOptions {
228 bounds,
229 titlebar: Some(TitlebarOptions {
230 title: None,
231 appears_transparent: true,
232 traffic_light_position: Some(point(px(8.), px(8.))),
233 }),
234 center: false,
235 focus: false,
236 show: false,
237 kind: WindowKind::Normal,
238 is_movable: false,
239 display_id: display.map(|display| display.id()),
240 }
241}
242
243pub fn initialize_workspace(
244 workspace_handle: WeakView<Workspace>,
245 was_deserialized: bool,
246 app_state: Arc<AppState>,
247 cx: AsyncWindowContext,
248) -> Task<Result<()>> {
249 cx.spawn(|mut cx| async move {
250 workspace_handle.update(&mut cx, |workspace, cx| {
251 let workspace_handle = cx.view();
252 cx.subscribe(&workspace_handle, {
253 move |workspace, _, event, cx| {
254 if let workspace2::Event::PaneAdded(pane) = event {
255 pane.update(cx, |pane, cx| {
256 // todo!()
257 // pane.toolbar().update(cx, |toolbar, cx| {
258 // let breadcrumbs = cx.add_view(|_| Breadcrumbs::new(workspace));
259 // toolbar.add_item(breadcrumbs, cx);
260 // let buffer_search_bar = cx.add_view(BufferSearchBar::new);
261 // toolbar.add_item(buffer_search_bar.clone(), cx);
262 // let quick_action_bar = cx.add_view(|_| {
263 // QuickActionBar::new(buffer_search_bar, workspace)
264 // });
265 // toolbar.add_item(quick_action_bar, cx);
266 // let diagnostic_editor_controls =
267 // cx.add_view(|_| diagnostics2::ToolbarControls::new());
268 // toolbar.add_item(diagnostic_editor_controls, cx);
269 // let project_search_bar = cx.add_view(|_| ProjectSearchBar::new());
270 // toolbar.add_item(project_search_bar, cx);
271 // let submit_feedback_button =
272 // cx.add_view(|_| SubmitFeedbackButton::new());
273 // toolbar.add_item(submit_feedback_button, cx);
274 // let feedback_info_text = cx.add_view(|_| FeedbackInfoText::new());
275 // toolbar.add_item(feedback_info_text, cx);
276 // let lsp_log_item =
277 // cx.add_view(|_| language_tools::LspLogToolbarItemView::new());
278 // toolbar.add_item(lsp_log_item, cx);
279 // let syntax_tree_item = cx
280 // .add_view(|_| language_tools::SyntaxTreeToolbarItemView::new());
281 // toolbar.add_item(syntax_tree_item, cx);
282 // })
283 });
284 }
285 }
286 })
287 .detach();
288
289 // cx.emit(workspace2::Event::PaneAdded(
290 // workspace.active_pane().clone(),
291 // ));
292
293 // let collab_titlebar_item =
294 // cx.add_view(|cx| CollabTitlebarItem::new(workspace, &workspace_handle, cx));
295 // workspace.set_titlebar_item(collab_titlebar_item.into_any(), cx);
296
297 // let copilot =
298 // cx.add_view(|cx| copilot_button::CopilotButton::new(app_state.fs.clone(), cx));
299 // let diagnostic_summary =
300 // cx.add_view(|cx| diagnostics::items::DiagnosticIndicator::new(workspace, cx));
301 // let activity_indicator = activity_indicator::ActivityIndicator::new(
302 // workspace,
303 // app_state.languages.clone(),
304 // cx,
305 // );
306 // let active_buffer_language =
307 // cx.add_view(|_| language_selector::ActiveBufferLanguage::new(workspace));
308 // let vim_mode_indicator = cx.add_view(|cx| vim::ModeIndicator::new(cx));
309 // let feedback_button = cx.add_view(|_| {
310 // feedback::deploy_feedback_button::DeployFeedbackButton::new(workspace)
311 // });
312 // let cursor_position = cx.add_view(|_| editor::items::CursorPosition::new());
313 // workspace.status_bar().update(cx, |status_bar, cx| {
314 // status_bar.add_left_item(diagnostic_summary, cx);
315 // status_bar.add_left_item(activity_indicator, cx);
316
317 // status_bar.add_right_item(feedback_button, cx);
318 // status_bar.add_right_item(copilot, cx);
319 // status_bar.add_right_item(active_buffer_language, cx);
320 // status_bar.add_right_item(vim_mode_indicator, cx);
321 // status_bar.add_right_item(cursor_position, cx);
322 // });
323
324 // auto_update::notify_of_any_new_update(cx.weak_handle(), cx);
325
326 // vim::observe_keystrokes(cx);
327
328 // cx.on_window_should_close(|workspace, cx| {
329 // if let Some(task) = workspace.close(&Default::default(), cx) {
330 // task.detach_and_log_err(cx);
331 // }
332 // false
333 // });
334 // })?;
335
336 // let project_panel = ProjectPanel::load(workspace_handle.clone(), cx.clone());
337 // let terminal_panel = TerminalPanel::load(workspace_handle.clone(), cx.clone());
338 // let assistant_panel = AssistantPanel::load(workspace_handle.clone(), cx.clone());
339 // let channels_panel =
340 // collab_ui::collab_panel::CollabPanel::load(workspace_handle.clone(), cx.clone());
341 // let chat_panel =
342 // collab_ui::chat_panel::ChatPanel::load(workspace_handle.clone(), cx.clone());
343 // let notification_panel = collab_ui::notification_panel::NotificationPanel::load(
344 // workspace_handle.clone(),
345 // cx.clone(),
346 // );
347 // let (
348 // project_panel,
349 // terminal_panel,
350 // assistant_panel,
351 // channels_panel,
352 // chat_panel,
353 // notification_panel,
354 // ) = futures::try_join!(
355 // project_panel,
356 // terminal_panel,
357 // assistant_panel,
358 // channels_panel,
359 // chat_panel,
360 // notification_panel,
361 // )?;
362 // workspace_handle.update(&mut cx, |workspace, cx| {
363 // let project_panel_position = project_panel.position(cx);
364 // workspace.add_panel_with_extra_event_handler(
365 // project_panel,
366 // cx,
367 // |workspace, _, event, cx| match event {
368 // project_panel::Event::NewSearchInDirectory { dir_entry } => {
369 // search::ProjectSearchView::new_search_in_directory(workspace, dir_entry, cx)
370 // }
371 // project_panel::Event::ActivatePanel => {
372 // workspace.focus_panel::<ProjectPanel>(cx);
373 // }
374 // _ => {}
375 // },
376 // );
377 // workspace.add_panel(terminal_panel, cx);
378 // workspace.add_panel(assistant_panel, cx);
379 // workspace.add_panel(channels_panel, cx);
380 // workspace.add_panel(chat_panel, cx);
381 // workspace.add_panel(notification_panel, cx);
382
383 // if !was_deserialized
384 // && workspace
385 // .project()
386 // .read(cx)
387 // .visible_worktrees(cx)
388 // .any(|tree| {
389 // tree.read(cx)
390 // .root_entry()
391 // .map_or(false, |entry| entry.is_dir())
392 // })
393 // {
394 // workspace.toggle_dock(project_panel_position, cx);
395 // }
396 // cx.focus_self();
397 })?;
398 Ok(())
399 })
400}