Compare commits

...
Sign in to create a new pull request.

7 commits

Author SHA1 Message Date
Lukas Wirth
333354024d Load python venv for tasks 2025-08-25 15:02:25 +02:00
Lukas Wirth
d2f2142127 Setup activation scripts in python toolchain 2025-08-25 08:56:58 +02:00
Lukas Wirth
c9eb9a9e41 Populate project path context on shell creation 2025-08-25 08:56:58 +02:00
Lukas Wirth
8e11e6a03e Add activation script support for terminals/toolchains 2025-08-25 08:56:58 +02:00
Lukas Wirth
7b3d73d6fd fetch ssh shell 2025-08-25 08:56:58 +02:00
Lukas Wirth
b2ba2de7b4 Async terminal construction 2025-08-25 08:56:58 +02:00
Lukas Wirth
0ce4dbb641 Split terminal API into shell and task 2025-08-25 08:56:58 +02:00
20 changed files with 899 additions and 722 deletions

1
Cargo.lock generated
View file

@ -9269,6 +9269,7 @@ dependencies = [
"snippet_provider",
"task",
"tempfile",
"terminal",
"text",
"theme",
"toml 0.8.20",

View file

@ -2,7 +2,7 @@ use agent_client_protocol as acp;
use anyhow::Result;
use futures::{FutureExt as _, future::Shared};
use gpui::{App, AppContext, Entity, SharedString, Task};
use project::{Project, terminals::TerminalKind};
use project::Project;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::{
@ -144,15 +144,22 @@ impl AgentTool for TerminalTool {
let terminal = self
.project
.update(cx, |project, cx| {
project.create_terminal(
TerminalKind::Task(task::SpawnInTerminal {
project.create_terminal_task(
task::SpawnInTerminal {
command: Some(program),
args,
cwd: working_dir.clone(),
env,
..Default::default()
}),
},
cx,
project
.active_entry()
.and_then(|entry_id| project.worktree_id_for_entry(entry_id, cx))
.map(|worktree_id| project::ProjectPath {
worktree_id,
path: Arc::from(Path::new("")),
}),
)
})?
.await?;

View file

@ -15,7 +15,7 @@ use language::LineEnding;
use language_model::{LanguageModel, LanguageModelRequest, LanguageModelToolSchemaFormat};
use markdown::{Markdown, MarkdownElement, MarkdownStyle};
use portable_pty::{CommandBuilder, PtySize, native_pty_system};
use project::{Project, terminals::TerminalKind};
use project::Project;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use settings::Settings;
@ -213,18 +213,24 @@ impl Tool for TerminalTool {
async move |cx| {
let program = program.await;
let env = env.await;
project
.update(cx, |project, cx| {
project.create_terminal(
TerminalKind::Task(task::SpawnInTerminal {
project.create_terminal_task(
task::SpawnInTerminal {
command: Some(program),
args,
cwd,
env,
..Default::default()
}),
},
cx,
project
.active_entry()
.and_then(|entry_id| project.worktree_id_for_entry(entry_id, cx))
.map(|worktree_id| project::ProjectPath {
worktree_id,
path: Arc::from(Path::new("")),
}),
)
})?
.await

View file

@ -36,7 +36,6 @@ use module_list::ModuleList;
use project::{
DebugScenarioContext, Project, WorktreeId,
debugger::session::{self, Session, SessionEvent, SessionStateEvent, ThreadId, ThreadStatus},
terminals::TerminalKind,
};
use rpc::proto::ViewId;
use serde_json::Value;
@ -1016,12 +1015,18 @@ impl RunningState {
};
let terminal = project
.update(cx, |project, cx| {
project.create_terminal(
TerminalKind::Task(task_with_shell.clone()),
project.create_terminal_task(
task_with_shell.clone(),
cx,
project
.active_entry()
.and_then(|entry_id| project.worktree_id_for_entry(entry_id, cx))
.map(|worktree_id| project::ProjectPath {
worktree_id,
path: Arc::from(std::path::Path::new("")),
}),
)
})?
.await?;
})?.await?;
let terminal_view = cx.new_window_entity(|window, cx| {
TerminalView::new(
@ -1165,7 +1170,7 @@ impl RunningState {
.filter(|title| !title.is_empty())
.or_else(|| command.clone())
.unwrap_or_else(|| "Debug terminal".to_string());
let kind = TerminalKind::Task(task::SpawnInTerminal {
let kind = task::SpawnInTerminal {
id: task::TaskId("debug".to_string()),
full_label: title.clone(),
label: title.clone(),
@ -1183,12 +1188,24 @@ impl RunningState {
show_summary: false,
show_command: false,
show_rerun: false,
});
};
let workspace = self.workspace.clone();
let weak_project = project.downgrade();
let terminal_task = project.update(cx, |project, cx| project.create_terminal(kind, cx));
let terminal_task = project.update(cx, |project, cx| {
project.create_terminal_task(
kind,
cx,
project
.active_entry()
.and_then(|entry_id| project.worktree_id_for_entry(entry_id, cx))
.map(|worktree_id| project::ProjectPath {
worktree_id,
path: Arc::from(std::path::Path::new("")),
}),
)
});
let terminal_task = cx.spawn_in(window, async move |_, cx| {
let terminal = terminal_task.await?;

View file

@ -10,14 +10,15 @@ use std::{
};
use async_trait::async_trait;
use collections::HashMap;
use collections::{FxHashMap, HashMap};
use gpui::{AsyncApp, SharedString};
use settings::WorktreeId;
use task::ShellKind;
use crate::{LanguageName, ManifestName};
/// Represents a single toolchain.
#[derive(Clone, Debug, Eq)]
#[derive(Clone, Eq, Debug)]
pub struct Toolchain {
/// User-facing label
pub name: SharedString,
@ -25,24 +26,44 @@ pub struct Toolchain {
pub language_name: LanguageName,
/// Full toolchain data (including language-specific details)
pub as_json: serde_json::Value,
/// shell -> script
pub activation_script: FxHashMap<ShellKind, String>,
// Option<String>
// sh activate -c "user shell -l"
// check if this work with powershell
}
impl std::hash::Hash for Toolchain {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.name.hash(state);
self.path.hash(state);
self.language_name.hash(state);
let Self {
name,
path,
language_name,
as_json: _,
activation_script: _,
} = self;
name.hash(state);
path.hash(state);
language_name.hash(state);
}
}
impl PartialEq for Toolchain {
fn eq(&self, other: &Self) -> bool {
let Self {
name,
path,
language_name,
as_json: _,
activation_script: startup_script,
} = self;
// Do not use as_json for comparisons; it shouldn't impact equality, as it's not user-surfaced.
// Thus, there could be multiple entries that look the same in the UI.
(&self.name, &self.path, &self.language_name).eq(&(
(name, path, language_name, startup_script).eq(&(
&other.name,
&other.path,
&other.language_name,
&other.activation_script,
))
}
}
@ -82,7 +103,7 @@ pub trait LocalLanguageToolchainStore: Send + Sync + 'static {
) -> Option<Toolchain>;
}
#[async_trait(?Send )]
#[async_trait(?Send)]
impl<T: LocalLanguageToolchainStore> LanguageToolchainStore for T {
async fn active_toolchain(
self: Arc<Self>,

View file

@ -71,6 +71,7 @@ settings.workspace = true
smol.workspace = true
snippet_provider.workspace = true
task.workspace = true
terminal.workspace = true
tempfile.workspace = true
toml.workspace = true
tree-sitter = { workspace = true, optional = true }

View file

@ -2,6 +2,7 @@ use anyhow::{Context as _, ensure};
use anyhow::{Result, anyhow};
use async_trait::async_trait;
use collections::HashMap;
use futures::AsyncBufReadExt;
use gpui::{App, Task};
use gpui::{AsyncApp, SharedString};
use language::Toolchain;
@ -30,12 +31,10 @@ use std::{
borrow::Cow,
ffi::OsString,
fmt::Write,
fs,
io::{self, BufRead},
path::{Path, PathBuf},
sync::Arc,
};
use task::{TaskTemplate, TaskTemplates, VariableName};
use task::{ShellKind, TaskTemplate, TaskTemplates, VariableName};
use util::ResultExt;
pub(crate) struct PyprojectTomlManifestProvider;
@ -741,14 +740,16 @@ fn env_priority(kind: Option<PythonEnvironmentKind>) -> usize {
/// Return the name of environment declared in <worktree-root/.venv.
///
/// https://virtualfish.readthedocs.io/en/latest/plugins.html#auto-activation-auto-activation
fn get_worktree_venv_declaration(worktree_root: &Path) -> Option<String> {
fs::File::open(worktree_root.join(".venv"))
.and_then(|file| {
let mut venv_name = String::new();
io::BufReader::new(file).read_line(&mut venv_name)?;
Ok(venv_name.trim().to_string())
})
.ok()
async fn get_worktree_venv_declaration(worktree_root: &Path) -> Option<String> {
let file = async_fs::File::open(worktree_root.join(".venv"))
.await
.ok()?;
let mut venv_name = String::new();
smol::io::BufReader::new(file)
.read_line(&mut venv_name)
.await
.ok()?;
Some(venv_name.trim().to_string())
}
#[async_trait]
@ -791,7 +792,7 @@ impl ToolchainLister for PythonToolchainProvider {
.map_or(Vec::new(), |mut guard| std::mem::take(&mut guard));
let wr = worktree_root;
let wr_venv = get_worktree_venv_declaration(&wr);
let wr_venv = get_worktree_venv_declaration(&wr).await;
// Sort detected environments by:
// environment name matching activation file (<workdir>/.venv)
// environment project dir matching worktree_root
@ -856,7 +857,7 @@ impl ToolchainLister for PythonToolchainProvider {
.into_iter()
.filter_map(|toolchain| {
let mut name = String::from("Python");
if let Some(ref version) = toolchain.version {
if let Some(version) = &toolchain.version {
_ = write!(name, " {version}");
}
@ -872,12 +873,50 @@ impl ToolchainLister for PythonToolchainProvider {
if let Some(nk) = name_and_kind {
_ = write!(name, " {nk}");
}
Some(Toolchain {
name: name.into(),
path: toolchain.executable.as_ref()?.to_str()?.to_owned().into(),
language_name: LanguageName::new("Python"),
as_json: serde_json::to_value(toolchain).ok()?,
as_json: serde_json::to_value(toolchain.clone()).ok()?,
activation_script: match (toolchain.kind, toolchain.prefix) {
(Some(PythonEnvironmentKind::Venv), Some(prefix)) => [
(
ShellKind::Fish,
"source",
prefix.join(BINARY_DIR).join("activate.fish"),
),
(
ShellKind::Powershell,
".",
prefix.join(BINARY_DIR).join("activate.ps1"),
),
(
ShellKind::Nushell,
"overlay use",
prefix.join(BINARY_DIR).join("activate.nu"),
),
(
ShellKind::Posix,
".",
prefix.join(BINARY_DIR).join("activate"),
),
(
ShellKind::Cmd,
".",
prefix.join(BINARY_DIR).join("activate.bat"),
),
(
ShellKind::Csh,
".",
prefix.join(BINARY_DIR).join("activate.csh"),
),
]
.into_iter()
.filter(|(_, _, path)| path.exists() && path.is_file())
.map(|(kind, cmd, path)| (kind, format!("{cmd} {}", path.display())))
.collect(),
_ => Default::default(),
},
})
})
.collect();

View file

@ -292,8 +292,8 @@ impl DapStore {
.map(|command| (command, &binary.arguments)),
binary.cwd.as_deref(),
binary.envs,
None,
path_style,
None,
);
Ok(DebugAdapterBinary {

View file

@ -9204,6 +9204,7 @@ fn python_lang(fs: Arc<FakeFs>) -> Arc<Language> {
path: venv_path.to_string_lossy().into_owned().into(),
language_name: LanguageName(SharedString::new_static("Python")),
as_json: serde_json::Value::Null,
activation_script: Default::default(),
})
}
}

File diff suppressed because it is too large Load diff

View file

@ -20,6 +20,7 @@ use rpc::{
proto::{self, FromProto, ToProto},
};
use settings::WorktreeId;
use task::ShellKind;
use util::ResultExt as _;
use crate::{
@ -138,6 +139,11 @@ impl ToolchainStore {
// Do we need to convert path to native string?
path: PathBuf::from(toolchain.path).to_proto().into(),
as_json: serde_json::Value::from_str(&toolchain.raw_json)?,
activation_script: toolchain
.activation_script
.into_iter()
.map(|(k, v)| (ShellKind::new(&k), v))
.collect(),
language_name,
};
let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
@ -178,6 +184,11 @@ impl ToolchainStore {
name: toolchain.name.into(),
path: path.to_proto(),
raw_json: toolchain.as_json.to_string(),
activation_script: toolchain
.activation_script
.into_iter()
.map(|(k, v)| (k.to_string(), v))
.collect(),
}
}),
})
@ -221,6 +232,11 @@ impl ToolchainStore {
name: toolchain.name.to_string(),
path: path.to_proto(),
raw_json: toolchain.as_json.to_string(),
activation_script: toolchain
.activation_script
.into_iter()
.map(|(k, v)| (k.to_string(), v))
.collect(),
}
})
.collect::<Vec<_>>();
@ -449,6 +465,11 @@ impl RemoteToolchainStore {
name: toolchain.name.into(),
path: path.to_proto(),
raw_json: toolchain.as_json.to_string(),
activation_script: toolchain
.activation_script
.into_iter()
.map(|(k, v)| (k.to_string(), v))
.collect(),
}),
path: Some(project_path.path.to_string_lossy().into_owned()),
})
@ -501,6 +522,11 @@ impl RemoteToolchainStore {
.to_string()
.into(),
as_json: serde_json::Value::from_str(&toolchain.raw_json).ok()?,
activation_script: toolchain
.activation_script
.into_iter()
.map(|(k, v)| (ShellKind::new(&k), v))
.collect(),
})
})
.collect();
@ -557,6 +583,11 @@ impl RemoteToolchainStore {
.to_string()
.into(),
as_json: serde_json::Value::from_str(&toolchain.raw_json).ok()?,
activation_script: toolchain
.activation_script
.into_iter()
.map(|(k, v)| (ShellKind::new(&k), v))
.collect(),
})
})
})

View file

@ -12,6 +12,7 @@ message Toolchain {
string name = 1;
string path = 2;
string raw_json = 3;
map<string, string> activation_script = 4;
}
message ToolchainGroup {

View file

@ -1,3 +1,7 @@
use std::fmt;
use util::get_system_shell;
use crate::Shell;
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
@ -11,9 +15,22 @@ pub enum ShellKind {
Cmd,
}
impl fmt::Display for ShellKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ShellKind::Posix => write!(f, "sh"),
ShellKind::Csh => write!(f, "csh"),
ShellKind::Fish => write!(f, "fish"),
ShellKind::Powershell => write!(f, "powershell"),
ShellKind::Nushell => write!(f, "nu"),
ShellKind::Cmd => write!(f, "cmd"),
}
}
}
impl ShellKind {
pub fn system() -> Self {
Self::new(&system_shell())
Self::new(&get_system_shell())
}
pub fn new(program: &str) -> Self {
@ -22,12 +39,12 @@ impl ShellKind {
#[cfg(not(windows))]
let (_, program) = program.rsplit_once('/').unwrap_or(("", program));
if program == "powershell"
|| program == "powershell.exe"
|| program.ends_with("powershell.exe")
|| program == "pwsh"
|| program == "pwsh.exe"
|| program.ends_with("pwsh.exe")
{
ShellKind::Powershell
} else if program == "cmd" || program == "cmd.exe" {
} else if program == "cmd" || program.ends_with("cmd.exe") {
ShellKind::Cmd
} else if program == "nu" {
ShellKind::Nushell
@ -178,18 +195,6 @@ impl ShellKind {
}
}
fn system_shell() -> String {
if cfg!(target_os = "windows") {
// `alacritty_terminal` uses this as default on Windows. See:
// https://github.com/alacritty/alacritty/blob/0d4ab7bca43213d96ddfe40048fc0f922543c6f8/alacritty_terminal/src/tty/windows/mod.rs#L130
// We could use `util::get_windows_system_shell()` here, but we are running tasks here, so leave it to `powershell.exe`
// should be okay.
"powershell.exe".to_string()
} else {
std::env::var("SHELL").unwrap_or("/bin/sh".to_string())
}
}
/// ShellBuilder is used to turn a user-requested task into a
/// program that can be executed by the shell.
pub struct ShellBuilder {
@ -206,7 +211,7 @@ impl ShellBuilder {
let (program, args) = match shell {
Shell::System => match remote_system_shell {
Some(remote_shell) => (remote_shell.to_string(), Vec::new()),
None => (system_shell(), Vec::new()),
None => (get_system_shell(), Vec::new()),
},
Shell::Program(shell) => (shell.clone(), Vec::new()),
Shell::WithArguments { program, args, .. } => (program.clone(), args.clone()),

View file

@ -344,7 +344,6 @@ pub struct TerminalBuilder {
impl TerminalBuilder {
pub fn new(
working_directory: Option<PathBuf>,
python_venv_directory: Option<PathBuf>,
task: Option<TaskState>,
shell: Shell,
mut env: HashMap<String, String>,
@ -353,8 +352,9 @@ impl TerminalBuilder {
max_scroll_history_lines: Option<usize>,
is_ssh_terminal: bool,
window_id: u64,
completion_tx: Sender<Option<ExitStatus>>,
completion_tx: Option<Sender<Option<ExitStatus>>>,
cx: &App,
startup_script: Option<String>,
) -> Result<TerminalBuilder> {
// If the parent environment doesn't have a locale set
// (As is the case when launched from a .app on MacOS),
@ -428,13 +428,10 @@ impl TerminalBuilder {
.clone()
.or_else(|| Some(home_dir().to_path_buf())),
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 scrolling_history = if task.is_some() {
// Tasks like `cargo build --all` may produce a lot of output, ergo allow maximum scrolling.
@ -517,11 +514,19 @@ impl TerminalBuilder {
hyperlink_regex_searches: RegexSearches::new(),
vi_mode_enabled: false,
is_ssh_terminal,
python_venv_directory,
last_mouse_move_time: Instant::now(),
last_hyperlink_search_position: None,
#[cfg(windows)]
shell_program,
startup_script,
template: CopyTemplate {
shell,
env,
cursor_shape,
alternate_scroll,
max_scroll_history_lines,
window_id,
},
};
Ok(TerminalBuilder {
@ -683,7 +688,7 @@ pub enum SelectionPhase {
pub struct Terminal {
pty_tx: Notifier,
completion_tx: Sender<Option<ExitStatus>>,
completion_tx: Option<Sender<Option<ExitStatus>>>,
term: Arc<FairMutex<Term<ZedListener>>>,
term_config: Config,
events: VecDeque<InternalEvent>,
@ -695,7 +700,6 @@ pub struct Terminal {
pub breadcrumb_text: String,
pub pty_info: PtyProcessInfo,
title_override: Option<SharedString>,
pub python_venv_directory: Option<PathBuf>,
scroll_px: Pixels,
next_link_id: usize,
selection_phase: SelectionPhase,
@ -707,6 +711,17 @@ pub struct Terminal {
last_hyperlink_search_position: Option<Point<Pixels>>,
#[cfg(windows)]
shell_program: Option<String>,
template: CopyTemplate,
startup_script: Option<String>,
}
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 {
@ -1895,7 +1910,9 @@ impl Terminal {
}
});
self.completion_tx.try_send(e).ok();
if let Some(tx) = &self.completion_tx {
tx.try_send(e).ok();
}
let task = match &mut self.task {
Some(task) => task,
None => {
@ -1950,6 +1967,28 @@ impl Terminal {
pub fn vi_mode_enabled(&self) -> bool {
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,
self.startup_script.clone(),
)
}
}
// Helper function to convert a grid row to a string
@ -2164,7 +2203,6 @@ mod tests {
let (completion_tx, completion_rx) = smol::channel::unbounded();
let terminal = cx.new(|cx| {
TerminalBuilder::new(
None,
None,
None,
task::Shell::WithArguments {
@ -2178,8 +2216,9 @@ mod tests {
None,
false,
0,
completion_tx,
Some(completion_tx),
cx,
None,
)
.unwrap()
.subscribe(cx)

View file

@ -95,6 +95,7 @@ pub enum VenvSettings {
/// to the current working directory. We recommend overriding this
/// in your project's settings, rather than globally.
activate_script: Option<ActivateScript>,
// deprecate but use
venv_name: Option<String>,
directories: Option<Vec<PathBuf>>,
},

View file

@ -3,9 +3,12 @@ use async_recursion::async_recursion;
use collections::HashSet;
use futures::{StreamExt as _, stream::FuturesUnordered};
use gpui::{AppContext as _, AsyncWindowContext, Axis, Entity, Task, WeakEntity};
use project::{Project, terminals::TerminalKind};
use project::{Project, ProjectPath};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::{
path::{Path, PathBuf},
sync::Arc,
};
use ui::{App, Context, Pixels, Window};
use util::ResultExt as _;
@ -242,11 +245,20 @@ async fn deserialize_pane_group(
.update(cx, |workspace, cx| default_working_directory(workspace, cx))
.ok()
.flatten();
let kind = TerminalKind::Shell(
working_directory.as_deref().map(Path::to_path_buf),
);
let terminal =
project.update(cx, |project, cx| project.create_terminal(kind, cx));
let p = workspace
.update(cx, |workspace, cx| {
let worktree = workspace.worktrees(cx).next()?.read(cx);
worktree.root_dir()?;
Some(ProjectPath {
worktree_id: worktree.id(),
path: Arc::from(Path::new("")),
})
})
.ok()
.flatten();
let terminal = project.update(cx, |project, cx| {
project.create_terminal_shell(working_directory, cx, p)
});
Some(Some(terminal))
} else {
Some(None)

View file

@ -1,4 +1,11 @@
use std::{cmp, ops::ControlFlow, path::PathBuf, process::ExitStatus, sync::Arc, time::Duration};
use std::{
cmp,
ops::ControlFlow,
path::{Path, PathBuf},
process::ExitStatus,
sync::Arc,
time::Duration,
};
use crate::{
TerminalView, default_working_directory,
@ -16,7 +23,7 @@ use gpui::{
Task, WeakEntity, Window, actions,
};
use itertools::Itertools;
use project::{Fs, Project, ProjectEntryId, terminals::TerminalKind};
use project::{Fs, Project, ProjectEntryId};
use search::{BufferSearchBar, buffer_search::DivRegistrar};
use settings::Settings;
use task::{RevealStrategy, RevealTarget, ShellBuilder, SpawnInTerminal, TaskId};
@ -376,14 +383,19 @@ impl TerminalPanel {
}
self.serialize(cx);
}
pane::Event::Split(direction) => {
let Some(new_pane) = self.new_pane_with_cloned_active_terminal(window, cx) else {
return;
};
&pane::Event::Split(direction) => {
let fut = self.new_pane_with_cloned_active_terminal(window, cx);
let pane = pane.clone();
let direction = *direction;
self.center.split(&pane, &new_pane, direction).log_err();
window.focus(&new_pane.focus_handle(cx));
cx.spawn_in(window, async move |panel, cx| {
let Some(new_pane) = fut.await else {
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 => {
self.active_pane = pane.clone();
@ -400,57 +412,72 @@ impl TerminalPanel {
&mut self,
window: &mut Window,
cx: &mut Context<Self>,
) -> Option<Entity<Pane>> {
let workspace = self.workspace.upgrade()?;
) -> Task<Option<Entity<Pane>>> {
let Some(workspace) = self.workspace.upgrade() else {
return Task::ready(None);
};
let workspace = workspace.read(cx);
let database_id = workspace.database_id();
let weak_workspace = self.workspace.clone();
let project = workspace.project().clone();
let (working_directory, python_venv_directory) = self
.active_pane
let active_pane = &self.active_pane;
let terminal_view = active_pane
.read(cx)
.active_item()
.and_then(|item| item.downcast::<TerminalView>())
.map(|terminal_view| {
let terminal = terminal_view.read(cx).terminal().read(cx);
(
terminal
.working_directory()
.or_else(|| default_working_directory(workspace, cx)),
terminal.python_venv_directory.clone(),
)
})
.unwrap_or((None, None));
let kind = TerminalKind::Shell(working_directory);
let terminal = project
.update(cx, |project, cx| {
project.create_terminal_with_venv(kind, python_venv_directory, cx)
})
.ok()?;
let terminal_view = Box::new(cx.new(|cx| {
TerminalView::new(
terminal.clone(),
weak_workspace.clone(),
database_id,
project.downgrade(),
window,
cx,
)
}));
let pane = new_terminal_pane(
weak_workspace,
project,
self.active_pane.read(cx).is_zoomed(),
window,
cx,
);
self.apply_tab_bar_buttons(&pane, cx);
pane.update(cx, |pane, cx| {
pane.add_item(terminal_view, true, true, None, window, cx);
.and_then(|item| item.downcast::<TerminalView>());
let working_directory = terminal_view.as_ref().and_then(|terminal_view| {
let terminal = terminal_view.read(cx).terminal().read(cx);
terminal
.working_directory()
.or_else(|| default_working_directory(workspace, cx))
});
let is_zoomed = active_pane.read(cx).is_zoomed();
cx.spawn_in(window, async move |panel, cx| {
let terminal = project
.update(cx, |project, cx| match terminal_view {
Some(view) => Task::ready(project.clone_terminal(
&view.read(cx).terminal.clone(),
cx,
|| working_directory,
)),
None => project.create_terminal_shell(
working_directory,
cx,
project
.active_entry()
.and_then(|entry_id| project.worktree_id_for_entry(entry_id, cx))
.map(|worktree_id| project::ProjectPath {
worktree_id,
path: Arc::from(Path::new("")),
}),
),
})
.ok()?
.await
.ok()?;
Some(pane)
panel
.update_in(cx, move |terminal_panel, window, cx| {
let terminal_view = Box::new(cx.new(|cx| {
TerminalView::new(
terminal.clone(),
weak_workspace.clone(),
database_id,
project.downgrade(),
window,
cx,
)
}));
let pane = new_terminal_pane(weak_workspace, project, is_zoomed, window, cx);
terminal_panel.apply_tab_bar_buttons(&pane, cx);
pane.update(cx, |pane, cx| {
pane.add_item(terminal_view, true, true, None, window, cx);
});
Some(pane)
})
.ok()
.flatten()
})
}
pub fn open_terminal(
@ -465,8 +492,8 @@ impl TerminalPanel {
terminal_panel
.update(cx, |panel, cx| {
panel.add_terminal(
TerminalKind::Shell(Some(action.working_directory.clone())),
panel.add_terminal_shell(
Some(action.working_directory.clone()),
RevealStrategy::Always,
window,
cx,
@ -560,15 +587,26 @@ impl TerminalPanel {
) -> Task<Result<WeakEntity<Terminal>>> {
let reveal = spawn_task.reveal;
let reveal_target = spawn_task.reveal_target;
let kind = TerminalKind::Task(spawn_task);
match reveal_target {
RevealTarget::Center => self
.workspace
.update(cx, |workspace, cx| {
Self::add_center_terminal(workspace, kind, window, cx)
Self::add_center_terminal(workspace, window, cx, |project, cx| {
project.create_terminal_task(
spawn_task,
cx,
project
.active_entry()
.and_then(|entry_id| project.worktree_id_for_entry(entry_id, cx))
.map(|worktree_id| project::ProjectPath {
worktree_id,
path: Arc::from(Path::new("")),
}),
)
})
})
.unwrap_or_else(|e| Task::ready(Err(e))),
RevealTarget::Dock => self.add_terminal(kind, reveal, window, cx),
RevealTarget::Dock => self.add_terminal_task(spawn_task, reveal, window, cx),
}
}
@ -583,11 +621,14 @@ impl TerminalPanel {
return;
};
let kind = TerminalKind::Shell(default_working_directory(workspace, cx));
terminal_panel
.update(cx, |this, cx| {
this.add_terminal(kind, RevealStrategy::Always, window, cx)
this.add_terminal_shell(
default_working_directory(workspace, cx),
RevealStrategy::Always,
window,
cx,
)
})
.detach_and_log_err(cx);
}
@ -649,9 +690,13 @@ impl TerminalPanel {
pub fn add_center_terminal(
workspace: &mut Workspace,
kind: TerminalKind,
window: &mut Window,
cx: &mut Context<Workspace>,
create_terminal: impl FnOnce(
&mut Project,
&mut Context<Project>,
) -> Task<Result<Entity<Terminal>>>
+ 'static,
) -> Task<Result<WeakEntity<Terminal>>> {
if !is_enabled_in_workspace(workspace, cx) {
return Task::ready(Err(anyhow!(
@ -660,9 +705,7 @@ impl TerminalPanel {
}
let project = workspace.project().downgrade();
cx.spawn_in(window, async move |workspace, cx| {
let terminal = project
.update(cx, |project, cx| project.create_terminal(kind, cx))?
.await?;
let terminal = project.update(cx, create_terminal)?.await?;
workspace.update_in(cx, |workspace, window, cx| {
let terminal_view = cx.new(|cx| {
@ -681,9 +724,9 @@ impl TerminalPanel {
})
}
pub fn add_terminal(
pub fn add_terminal_task(
&mut self,
kind: TerminalKind,
task: SpawnInTerminal,
reveal_strategy: RevealStrategy,
window: &mut Window,
cx: &mut Context<Self>,
@ -699,7 +742,90 @@ impl TerminalPanel {
})?;
let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
let terminal = project
.update(cx, |project, cx| project.create_terminal(kind, cx))?
.update(cx, |project, cx| {
project.create_terminal_task(
task,
cx,
project
.active_entry()
.and_then(|entry_id| project.worktree_id_for_entry(entry_id, cx))
.map(|worktree_id| project::ProjectPath {
worktree_id,
path: Arc::from(Path::new("")),
}),
)
})?
.await?;
let result = workspace.update_in(cx, |workspace, window, cx| {
let terminal_view = Box::new(cx.new(|cx| {
TerminalView::new(
terminal.clone(),
workspace.weak_handle(),
workspace.database_id(),
workspace.project().downgrade(),
window,
cx,
)
}));
match reveal_strategy {
RevealStrategy::Always => {
workspace.focus_panel::<Self>(window, cx);
}
RevealStrategy::NoFocus => {
workspace.open_panel::<Self>(window, cx);
}
RevealStrategy::Never => {}
}
pane.update(cx, |pane, cx| {
let focus = pane.has_focus(window, cx)
|| matches!(reveal_strategy, RevealStrategy::Always);
pane.add_item(terminal_view, true, focus, None, window, cx);
});
Ok(terminal.downgrade())
})?;
terminal_panel.update(cx, |terminal_panel, cx| {
terminal_panel.pending_terminals_to_add =
terminal_panel.pending_terminals_to_add.saturating_sub(1);
terminal_panel.serialize(cx)
})?;
result
})
}
pub fn add_terminal_shell(
&mut self,
cwd: Option<PathBuf>,
reveal_strategy: RevealStrategy,
window: &mut Window,
cx: &mut Context<Self>,
) -> Task<Result<WeakEntity<Terminal>>> {
let workspace = self.workspace.clone();
cx.spawn_in(window, async move |terminal_panel, cx| {
if workspace.update(cx, |workspace, cx| !is_enabled_in_workspace(workspace, cx))? {
anyhow::bail!("terminal not yet supported for remote projects");
}
let pane = terminal_panel.update(cx, |terminal_panel, _| {
terminal_panel.pending_terminals_to_add += 1;
terminal_panel.active_pane.clone()
})?;
let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
let terminal = project
.update(cx, |project, cx| {
project.create_terminal_shell(
cwd,
cx,
project
.active_entry()
.and_then(|entry_id| project.worktree_id_for_entry(entry_id, cx))
.map(|worktree_id| project::ProjectPath {
worktree_id,
path: Arc::from(Path::new("")),
}),
)
})?
.await?;
let result = workspace.update_in(cx, |workspace, window, cx| {
let terminal_view = Box::new(cx.new(|cx| {
@ -808,7 +934,17 @@ impl TerminalPanel {
})??;
let new_terminal = project
.update(cx, |project, cx| {
project.create_terminal(TerminalKind::Task(spawn_task), cx)
project.create_terminal_task(
spawn_task,
cx,
project
.active_entry()
.and_then(|entry_id| project.worktree_id_for_entry(entry_id, cx))
.map(|worktree_id| project::ProjectPath {
worktree_id,
path: Arc::from(Path::new("")),
}),
)
})?
.await?;
terminal_to_replace.update_in(cx, |terminal_to_replace, window, cx| {
@ -1237,18 +1373,29 @@ impl Render for TerminalPanel {
let panes = terminal_panel.center.panes();
if let Some(&pane) = panes.get(action.0) {
window.focus(&pane.read(cx).focus_handle(cx));
} else if let Some(new_pane) =
terminal_panel.new_pane_with_cloned_active_terminal(window, cx)
{
terminal_panel
.center
.split(
&terminal_panel.active_pane,
&new_pane,
SplitDirection::Right,
)
.log_err();
window.focus(&new_pane.focus_handle(cx));
} else {
let future =
terminal_panel.new_pane_with_cloned_active_terminal(window, cx);
cx.spawn_in(window, async move |terminal_panel, cx| {
if let Some(new_pane) = future.await {
_ = terminal_panel.update_in(
cx,
|terminal_panel, window, cx| {
terminal_panel
.center
.split(
&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();
}
}),
)
@ -1384,13 +1531,14 @@ impl Panel for TerminalPanel {
return;
}
cx.defer_in(window, |this, window, cx| {
let Ok(kind) = this.workspace.update(cx, |workspace, cx| {
TerminalKind::Shell(default_working_directory(workspace, cx))
}) else {
let Ok(kind) = this
.workspace
.update(cx, |workspace, cx| default_working_directory(workspace, cx))
else {
return;
};
this.add_terminal(kind, RevealStrategy::Always, window, cx)
this.add_terminal_shell(kind, RevealStrategy::Always, window, cx)
.detach_and_log_err(cx)
})
}

View file

@ -364,7 +364,7 @@ fn possibly_open_target(
mod tests {
use super::*;
use gpui::TestAppContext;
use project::{Project, terminals::TerminalKind};
use project::Project;
use serde_json::json;
use std::path::{Path, PathBuf};
use terminal::{HoveredWord, alacritty_terminal::index::Point as AlacPoint};
@ -405,8 +405,8 @@ mod tests {
app_cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
let terminal = project
.update(cx, |project, cx| {
project.create_terminal(TerminalKind::Shell(None), cx)
.update(cx, |project: &mut Project, cx| {
project.create_terminal_shell(None, cx, None)
})
.await
.expect("Failed to create a terminal");

View file

@ -15,7 +15,7 @@ use gpui::{
deferred, div,
};
use persistence::TERMINAL_DB;
use project::{Project, search::SearchQuery, terminals::TerminalKind};
use project::{Project, ProjectPath, search::SearchQuery};
use schemars::JsonSchema;
use task::TaskId;
use terminal::{
@ -204,12 +204,19 @@ impl TerminalView {
cx: &mut Context<Workspace>,
) {
let working_directory = default_working_directory(workspace, cx);
TerminalPanel::add_center_terminal(
workspace,
TerminalKind::Shell(working_directory),
window,
cx,
)
TerminalPanel::add_center_terminal(workspace, window, cx, |project, cx| {
project.create_terminal_shell(
working_directory,
cx,
project
.active_entry()
.and_then(|entry_id| project.worktree_id_for_entry(entry_id, cx))
.map(|worktree_id| project::ProjectPath {
worktree_id,
path: Arc::from(Path::new("")),
}),
)
})
.detach_and_log_err(cx);
}
@ -1333,16 +1340,10 @@ impl Item for TerminalView {
let terminal = self
.project
.update(cx, |project, cx| {
let terminal = self.terminal().read(cx);
let working_directory = terminal
.working_directory()
.or_else(|| Some(project.active_project_directory(cx)?.to_path_buf()));
let python_venv_directory = terminal.python_venv_directory.clone();
project.create_terminal_with_venv(
TerminalKind::Shell(working_directory),
python_venv_directory,
cx,
)
let cwd = project
.active_project_directory(cx)
.map(|it| it.to_path_buf());
project.clone_terminal(self.terminal(), cx, || cwd)
})
.ok()?
.log_err()?;
@ -1497,10 +1498,19 @@ impl SerializableItem for TerminalView {
.ok()
.flatten();
let p = workspace
.update(cx, |workspace, cx| {
let worktree = workspace.worktrees(cx).next()?.read(cx);
worktree.root_dir()?;
Some(ProjectPath {
worktree_id: worktree.id(),
path: Arc::from(Path::new("")),
})
})
.ok()
.flatten();
let terminal = project
.update(cx, |project, cx| {
project.create_terminal(TerminalKind::Shell(cwd), cx)
})?
.update(cx, |project, cx| project.create_terminal_shell(cwd, cx, p))?
.await?;
cx.update(|window, cx| {
cx.new(|cx| {

View file

@ -1403,7 +1403,8 @@ impl WorkspaceDb {
name: name.into(),
path: path.into(),
language_name,
as_json: serde_json::Value::from_str(&raw_json).ok()?
as_json: serde_json::Value::from_str(&raw_json).ok()?,
activation_script: Default::default(),
})))
})
.await
@ -1423,11 +1424,13 @@ impl WorkspaceDb {
let toolchain: Vec<(String, String, u64, String, String, String)> =
select(workspace_id)?;
// todo look into re-serializing these if we fix up
Ok(toolchain.into_iter().filter_map(|(name, path, worktree_id, relative_worktree_path, language_name, raw_json)| Some((Toolchain {
name: name.into(),
path: path.into(),
language_name: LanguageName::new(&language_name),
as_json: serde_json::Value::from_str(&raw_json).ok()?
as_json: serde_json::Value::from_str(&raw_json).ok()?,
activation_script: Default::default(),
}, WorktreeId::from_proto(worktree_id), Arc::from(relative_worktree_path.as_ref())))).collect())
})
.await