Async terminal construction

This commit is contained in:
Lukas Wirth 2025-08-18 20:01:40 +02:00
parent 87863b369f
commit 985df3736e
6 changed files with 206 additions and 95 deletions

View file

@ -1,9 +1,8 @@
use crate::Project;
use anyhow::Result; use anyhow::Result;
use collections::HashMap; use collections::HashMap;
use gpui::{App, AppContext as _, Context, Entity, WeakEntity}; use gpui::{App, AppContext as _, Context, Entity, Task, WeakEntity};
use itertools::Itertools; use itertools::Itertools as _;
use language::LanguageName;
use remote::{SshInfo, ssh_session::SshArgs}; use remote::{SshInfo, ssh_session::SshArgs};
use settings::{Settings, SettingsLocation}; use settings::{Settings, SettingsLocation};
use smol::channel::bounded; use smol::channel::bounded;
@ -16,7 +15,12 @@ use task::{Shell, ShellBuilder, SpawnInTerminal};
use terminal::{ use terminal::{
TaskState, TaskStatus, Terminal, TerminalBuilder, terminal_settings::TerminalSettings, TaskState, TaskStatus, Terminal, TerminalBuilder, terminal_settings::TerminalSettings,
}; };
use util::paths::{PathStyle, RemotePathBuf}; use util::{
maybe,
paths::{PathStyle, RemotePathBuf},
};
use crate::{Project, ProjectPath};
pub struct Terminals { pub struct Terminals {
pub(crate) local_handles: Vec<WeakEntity<terminal::Terminal>>, pub(crate) local_handles: Vec<WeakEntity<terminal::Terminal>>,
@ -239,7 +243,8 @@ impl Project {
&mut self, &mut self,
cwd: Option<PathBuf>, cwd: Option<PathBuf>,
cx: &mut Context<Self>, cx: &mut Context<Self>,
) -> Result<Entity<Terminal>> { project_path_context: Option<ProjectPath>,
) -> Task<Result<Entity<Terminal>>> {
let path = cwd.map(|p| Arc::from(&*p)); let path = cwd.map(|p| Arc::from(&*p));
let this = &mut *self; let this = &mut *self;
let ssh_details = this.ssh_details(cx); let ssh_details = this.ssh_details(cx);
@ -305,23 +310,66 @@ impl Project {
None => (None, settings.shell), None => (None, settings.shell),
} }
}; };
TerminalBuilder::new( let toolchain =
local_path.map(|path| path.to_path_buf()), project_path_context.map(|p| self.active_toolchain(p, LanguageName::new("Python"), cx));
spawn_task, cx.spawn(async move |project, cx| {
shell, let toolchain = maybe!(async {
env, let toolchain = toolchain?.await?;
settings.cursor_shape.unwrap_or_default(),
settings.alternate_scroll, Some(())
settings.max_scroll_history_lines, })
is_ssh_terminal, .await;
cx.entity_id().as_u64(), project.update(cx, move |this, cx| {
None, TerminalBuilder::new(
cx, local_path.map(|path| path.to_path_buf()),
) spawn_task,
.map(|builder| { shell,
env,
settings.cursor_shape.unwrap_or_default(),
settings.alternate_scroll,
settings.max_scroll_history_lines,
is_ssh_terminal,
cx.entity_id().as_u64(),
None,
cx,
)
.map(|builder| {
let terminal_handle = cx.new(|cx| builder.subscribe(cx));
this.terminals
.local_handles
.push(terminal_handle.downgrade());
let id = terminal_handle.entity_id();
cx.observe_release(&terminal_handle, move |project, _terminal, cx| {
let handles = &mut project.terminals.local_handles;
if let Some(index) = handles
.iter()
.position(|terminal| terminal.entity_id() == id)
{
handles.remove(index);
cx.notify();
}
})
.detach();
terminal_handle
})
})?
})
}
pub fn clone_terminal(
&mut self,
terminal: &Entity<Terminal>,
cx: &mut Context<'_, Project>,
cwd: impl FnOnce() -> Option<PathBuf>,
) -> Result<Entity<Terminal>> {
terminal.read(cx).clone_builder(cx, cwd).map(|builder| {
let terminal_handle = cx.new(|cx| builder.subscribe(cx)); let terminal_handle = cx.new(|cx| builder.subscribe(cx));
this.terminals self.terminals
.local_handles .local_handles
.push(terminal_handle.downgrade()); .push(terminal_handle.downgrade());

View file

@ -427,13 +427,10 @@ impl TerminalBuilder {
.clone() .clone()
.or_else(|| Some(home_dir().to_path_buf())), .or_else(|| Some(home_dir().to_path_buf())),
drain_on_exit: true, drain_on_exit: true,
env: env.into_iter().collect(), env: env.clone().into_iter().collect(),
} }
}; };
// Setup Alacritty's env, which modifies the current process's environment
alacritty_terminal::tty::setup_env();
let default_cursor_style = AlacCursorStyle::from(cursor_shape); let default_cursor_style = AlacCursorStyle::from(cursor_shape);
let scrolling_history = if task.is_some() { let scrolling_history = if task.is_some() {
// Tasks like `cargo build --all` may produce a lot of output, ergo allow maximum scrolling. // Tasks like `cargo build --all` may produce a lot of output, ergo allow maximum scrolling.
@ -520,6 +517,14 @@ impl TerminalBuilder {
last_hyperlink_search_position: None, last_hyperlink_search_position: None,
#[cfg(windows)] #[cfg(windows)]
shell_program, shell_program,
template: CopyTemplate {
shell,
env,
cursor_shape,
alternate_scroll,
max_scroll_history_lines,
window_id,
},
}; };
Ok(TerminalBuilder { Ok(TerminalBuilder {
@ -704,6 +709,16 @@ pub struct Terminal {
last_hyperlink_search_position: Option<Point<Pixels>>, last_hyperlink_search_position: Option<Point<Pixels>>,
#[cfg(windows)] #[cfg(windows)]
shell_program: Option<String>, shell_program: Option<String>,
template: CopyTemplate,
}
struct CopyTemplate {
shell: Shell,
env: HashMap<String, String>,
cursor_shape: CursorShape,
alternate_scroll: AlternateScroll,
max_scroll_history_lines: Option<usize>,
window_id: u64,
} }
pub struct TaskState { pub struct TaskState {
@ -1949,6 +1964,27 @@ impl Terminal {
pub fn vi_mode_enabled(&self) -> bool { pub fn vi_mode_enabled(&self) -> bool {
self.vi_mode_enabled self.vi_mode_enabled
} }
pub fn clone_builder(
&self,
cx: &App,
cwd: impl FnOnce() -> Option<PathBuf>,
) -> Result<TerminalBuilder> {
let working_directory = self.working_directory().or_else(cwd);
TerminalBuilder::new(
working_directory,
None,
self.template.shell.clone(),
self.template.env.clone(),
self.template.cursor_shape,
self.template.alternate_scroll,
self.template.max_scroll_history_lines,
self.is_ssh_terminal,
self.template.window_id,
None,
cx,
)
}
} }
// Helper function to convert a grid row to a string // Helper function to convert a grid row to a string

View file

@ -5,7 +5,7 @@ use futures::{StreamExt as _, stream::FuturesUnordered};
use gpui::{AppContext as _, AsyncWindowContext, Axis, Entity, Task, WeakEntity}; use gpui::{AppContext as _, AsyncWindowContext, Axis, Entity, Task, WeakEntity};
use project::Project; use project::Project;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf}; use std::path::PathBuf;
use ui::{App, Context, Pixels, Window}; use ui::{App, Context, Pixels, Window};
use util::ResultExt as _; use util::ResultExt as _;
@ -243,10 +243,7 @@ async fn deserialize_pane_group(
.ok() .ok()
.flatten(); .flatten();
let terminal = project.update(cx, |project, cx| { let terminal = project.update(cx, |project, cx| {
project.create_terminal_shell( project.create_terminal_shell(working_directory, cx, None)
working_directory.as_deref().map(Path::to_path_buf),
cx,
)
}); });
Some(Some(terminal)) Some(Some(terminal))
} else { } else {
@ -256,7 +253,7 @@ async fn deserialize_pane_group(
.ok() .ok()
.flatten()?; .flatten()?;
if let Some(terminal) = terminal { if let Some(terminal) = terminal {
let terminal = terminal.ok()?; let terminal = terminal.await.ok()?;
pane.update_in(cx, |pane, window, cx| { pane.update_in(cx, |pane, window, cx| {
let terminal_view = Box::new(cx.new(|cx| { let terminal_view = Box::new(cx.new(|cx| {
TerminalView::new( TerminalView::new(

View file

@ -376,14 +376,19 @@ impl TerminalPanel {
} }
self.serialize(cx); self.serialize(cx);
} }
pane::Event::Split(direction) => { &pane::Event::Split(direction) => {
let Some(new_pane) = self.new_pane_with_cloned_active_terminal(window, cx) else { let fut = self.new_pane_with_cloned_active_terminal(window, cx);
return;
};
let pane = pane.clone(); let pane = pane.clone();
let direction = *direction; cx.spawn_in(window, async move |panel, cx| {
self.center.split(&pane, &new_pane, direction).log_err(); let Some(new_pane) = fut.await else {
window.focus(&new_pane.focus_handle(cx)); return;
};
_ = panel.update_in(cx, |panel, window, cx| {
panel.center.split(&pane, &new_pane, direction).log_err();
window.focus(&new_pane.focus_handle(cx));
});
})
.detach();
} }
pane::Event::Focus => { pane::Event::Focus => {
self.active_pane = pane.clone(); self.active_pane = pane.clone();
@ -400,14 +405,16 @@ impl TerminalPanel {
&mut self, &mut self,
window: &mut Window, window: &mut Window,
cx: &mut Context<Self>, cx: &mut Context<Self>,
) -> Option<Entity<Pane>> { ) -> Task<Option<Entity<Pane>>> {
let workspace = self.workspace.upgrade()?; let Some(workspace) = self.workspace.upgrade() else {
return Task::ready(None);
};
let workspace = workspace.read(cx); let workspace = workspace.read(cx);
let database_id = workspace.database_id(); let database_id = workspace.database_id();
let weak_workspace = self.workspace.clone(); let weak_workspace = self.workspace.clone();
let project = workspace.project().clone(); let project = workspace.project().clone();
let working_directory = self let active_pane = &self.active_pane;
.active_pane let working_directory = active_pane
.read(cx) .read(cx)
.active_item() .active_item()
.and_then(|item| item.downcast::<TerminalView>()) .and_then(|item| item.downcast::<TerminalView>())
@ -418,35 +425,38 @@ impl TerminalPanel {
.or_else(|| default_working_directory(workspace, cx)) .or_else(|| default_working_directory(workspace, cx))
}) })
.unwrap_or(None); .unwrap_or(None);
let terminal = project let is_zoomed = active_pane.read(cx).is_zoomed();
.update(cx, |project, cx| { cx.spawn_in(window, async move |panel, cx| {
project.create_terminal_shell(working_directory, cx) let terminal = project
}) .update(cx, |project, cx| {
.ok()?; project.create_terminal_shell(working_directory, cx, None)
})
.ok()?
.await
.ok()?;
let terminal_view = Box::new(cx.new(|cx| { panel
TerminalView::new( .update_in(cx, move |terminal_panel, window, cx| {
terminal.clone(), let terminal_view = Box::new(cx.new(|cx| {
weak_workspace.clone(), TerminalView::new(
database_id, terminal.clone(),
project.downgrade(), weak_workspace.clone(),
window, database_id,
cx, project.downgrade(),
) window,
})); cx,
let pane = new_terminal_pane( )
weak_workspace, }));
project, let pane = new_terminal_pane(weak_workspace, project, is_zoomed, window, cx);
self.active_pane.read(cx).is_zoomed(), terminal_panel.apply_tab_bar_buttons(&pane, cx);
window, pane.update(cx, |pane, cx| {
cx, pane.add_item(terminal_view, true, true, None, window, cx);
); });
self.apply_tab_bar_buttons(&pane, cx); Some(pane)
pane.update(cx, |pane, cx| { })
pane.add_item(terminal_view, true, true, None, window, cx); .ok()
}); .flatten()
})
Some(pane)
} }
pub fn open_terminal( pub fn open_terminal(
@ -561,7 +571,7 @@ impl TerminalPanel {
.workspace .workspace
.update(cx, |workspace, cx| { .update(cx, |workspace, cx| {
Self::add_center_terminal(workspace, window, cx, |project, cx| { Self::add_center_terminal(workspace, window, cx, |project, cx| {
project.create_terminal_task(spawn_task, cx) Task::ready(project.create_terminal_task(spawn_task, cx))
}) })
}) })
.unwrap_or_else(|e| Task::ready(Err(e))), .unwrap_or_else(|e| Task::ready(Err(e))),
@ -651,7 +661,10 @@ impl TerminalPanel {
workspace: &mut Workspace, workspace: &mut Workspace,
window: &mut Window, window: &mut Window,
cx: &mut Context<Workspace>, cx: &mut Context<Workspace>,
create_terminal: impl FnOnce(&mut Project, &mut Context<Project>) -> Result<Entity<Terminal>> create_terminal: impl FnOnce(
&mut Project,
&mut Context<Project>,
) -> Task<Result<Entity<Terminal>>>
+ 'static, + 'static,
) -> Task<Result<WeakEntity<Terminal>>> { ) -> Task<Result<WeakEntity<Terminal>>> {
if !is_enabled_in_workspace(workspace, cx) { if !is_enabled_in_workspace(workspace, cx) {
@ -661,7 +674,7 @@ impl TerminalPanel {
} }
let project = workspace.project().downgrade(); let project = workspace.project().downgrade();
cx.spawn_in(window, async move |workspace, cx| { cx.spawn_in(window, async move |workspace, cx| {
let terminal = project.update(cx, create_terminal)??; let terminal = project.update(cx, create_terminal)?.await?;
workspace.update_in(cx, |workspace, window, cx| { workspace.update_in(cx, |workspace, window, cx| {
let terminal_view = cx.new(|cx| { let terminal_view = cx.new(|cx| {
@ -755,8 +768,11 @@ impl TerminalPanel {
terminal_panel.active_pane.clone() terminal_panel.active_pane.clone()
})?; })?;
let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?; let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
let terminal = let terminal = project
project.update(cx, |project, cx| project.create_terminal_shell(cwd, cx))??; .update(cx, |project, cx| {
project.create_terminal_shell(cwd, cx, None)
})?
.await?;
let result = workspace.update_in(cx, |workspace, window, cx| { let result = workspace.update_in(cx, |workspace, window, cx| {
let terminal_view = Box::new(cx.new(|cx| { let terminal_view = Box::new(cx.new(|cx| {
TerminalView::new( TerminalView::new(
@ -1291,18 +1307,29 @@ impl Render for TerminalPanel {
let panes = terminal_panel.center.panes(); let panes = terminal_panel.center.panes();
if let Some(&pane) = panes.get(action.0) { if let Some(&pane) = panes.get(action.0) {
window.focus(&pane.read(cx).focus_handle(cx)); window.focus(&pane.read(cx).focus_handle(cx));
} else if let Some(new_pane) = } else {
terminal_panel.new_pane_with_cloned_active_terminal(window, cx) let future =
{ terminal_panel.new_pane_with_cloned_active_terminal(window, cx);
terminal_panel cx.spawn_in(window, async move |terminal_panel, cx| {
.center if let Some(new_pane) = future.await {
.split( _ = terminal_panel.update_in(
&terminal_panel.active_pane, cx,
&new_pane, |terminal_panel, window, cx| {
SplitDirection::Right, terminal_panel
) .center
.log_err(); .split(
window.focus(&new_pane.focus_handle(cx)); &terminal_panel.active_pane,
&new_pane,
SplitDirection::Right,
)
.log_err();
let new_pane = new_pane.read(cx);
window.focus(&new_pane.focus_handle(cx));
},
);
}
})
.detach();
} }
}), }),
) )

View file

@ -408,6 +408,7 @@ mod tests {
.update(cx, |project: &mut Project, cx| { .update(cx, |project: &mut Project, cx| {
project.create_terminal_shell(None, cx, None) project.create_terminal_shell(None, cx, None)
}) })
.await
.expect("Failed to create a terminal"); .expect("Failed to create a terminal");
let workspace_a = workspace.clone(); let workspace_a = workspace.clone();

View file

@ -205,7 +205,7 @@ impl TerminalView {
) { ) {
let working_directory = default_working_directory(workspace, cx); let working_directory = default_working_directory(workspace, cx);
TerminalPanel::add_center_terminal(workspace, window, cx, |project, cx| { TerminalPanel::add_center_terminal(workspace, window, cx, |project, cx| {
project.create_terminal_shell(working_directory, cx) project.create_terminal_shell(working_directory, cx, None)
}) })
.detach_and_log_err(cx); .detach_and_log_err(cx);
} }
@ -1330,11 +1330,10 @@ impl Item for TerminalView {
let terminal = self let terminal = self
.project .project
.update(cx, |project, cx| { .update(cx, |project, cx| {
let terminal = self.terminal().read(cx); let cwd = project
let working_directory = terminal .active_project_directory(cx)
.working_directory() .map(|it| it.to_path_buf());
.or_else(|| Some(project.active_project_directory(cx)?.to_path_buf())); project.clone_terminal(self.terminal(), cx, || cwd)
project.create_terminal_shell(working_directory, cx)
}) })
.ok()? .ok()?
.log_err()?; .log_err()?;
@ -1489,8 +1488,11 @@ impl SerializableItem for TerminalView {
.ok() .ok()
.flatten(); .flatten();
let terminal = let terminal = project
project.update(cx, |project, cx| project.create_terminal_shell(cwd, cx))??; .update(cx, |project, cx| {
project.create_terminal_shell(cwd, cx, None)
})?
.await?;
cx.update(|window, cx| { cx.update(|window, cx| {
cx.new(|cx| { cx.new(|cx| {
TerminalView::new( TerminalView::new(