Add static Runnables (#8009)

Part of #7108

This PR includes just the static runnables part. We went with **not**
having a dedicated panel for runnables.
This is just a 1st PR out of N, as we want to start exploring the
dynamic runnables front. Still, all that work is going to happen once
this gets merged.

Release Notes:

- Added initial, static Runnables support to Zed. Such runnables are defined in
`runnables.json` file (accessible via `zed: open runnables` action) and
they can be spawned with `runnables: spawn` action.

---------

Co-authored-by: Kirill Bulatov <kirill@zed.dev>
Co-authored-by: Pitor <pitor@zed.dev>
Co-authored-by: Beniamin <beniamin@zagan.be>
This commit is contained in:
Piotr Osiewicz 2024-02-19 17:41:43 +01:00 committed by GitHub
parent ca251babcd
commit f17d0b5729
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
30 changed files with 1394 additions and 275 deletions

View file

@ -25,6 +25,7 @@ mio-extras = "2.0.6"
ordered-float.workspace = true
procinfo = { git = "https://github.com/zed-industries/wezterm", rev = "5cd757e5f2eb039ed0c6bb6512223e69d5efc64d", default-features = false }
project.workspace = true
runnable.workspace = true
search.workspace = true
serde.workspace = true
serde_derive.workspace = true

View file

@ -1,7 +1,9 @@
use std::{ops::ControlFlow, path::PathBuf, sync::Arc};
use crate::TerminalView;
use collections::{HashMap, HashSet};
use db::kvp::KEY_VALUE_STORE;
use futures::future::join_all;
use gpui::{
actions, AppContext, AsyncWindowContext, Entity, EventEmitter, ExternalPaths, FocusHandle,
FocusableView, IntoElement, ParentElement, Pixels, Render, Styled, Subscription, Task, View,
@ -9,10 +11,14 @@ use gpui::{
};
use itertools::Itertools;
use project::{Fs, ProjectEntryId};
use runnable::RunnableId;
use search::{buffer_search::DivRegistrar, BufferSearchBar};
use serde::{Deserialize, Serialize};
use settings::Settings;
use terminal::terminal_settings::{TerminalDockPosition, TerminalSettings};
use terminal::{
terminal_settings::{TerminalDockPosition, TerminalSettings},
SpawnRunnable,
};
use ui::{h_flex, ButtonCommon, Clickable, IconButton, IconSize, Selectable, Tooltip};
use util::{ResultExt, TryFutureExt};
use workspace::{
@ -49,7 +55,9 @@ pub struct TerminalPanel {
width: Option<Pixels>,
height: Option<Pixels>,
pending_serialization: Task<Option<()>>,
pending_terminals_to_add: usize,
_subscriptions: Vec<Subscription>,
deferred_runnables: HashMap<RunnableId, Task<()>>,
}
impl TerminalPanel {
@ -75,7 +83,7 @@ impl TerminalPanel {
.icon_size(IconSize::Small)
.on_click(move |_, cx| {
terminal_panel
.update(cx, |panel, cx| panel.add_terminal(None, cx))
.update(cx, |panel, cx| panel.add_terminal(None, None, cx))
.log_err();
})
.tooltip(|cx| Tooltip::text("New Terminal", cx)),
@ -157,6 +165,8 @@ impl TerminalPanel {
pending_serialization: Task::ready(None),
width: None,
height: None,
pending_terminals_to_add: 0,
deferred_runnables: HashMap::default(),
_subscriptions: subscriptions,
};
this
@ -201,12 +211,27 @@ impl TerminalPanel {
})
})
} else {
Default::default()
Vec::new()
};
let pane = panel.read(cx).pane.clone();
(panel, pane, items)
})?;
if let Some(workspace) = workspace.upgrade() {
panel
.update(&mut cx, |panel, cx| {
panel._subscriptions.push(cx.subscribe(
&workspace,
|terminal_panel, _, e, cx| {
if let workspace::Event::SpawnRunnable(spawn_in_terminal) = e {
terminal_panel.spawn_runnable(spawn_in_terminal, cx);
};
},
))
})
.ok();
}
let pane = pane.downgrade();
let items = futures::future::join_all(items).await;
pane.update(&mut cx, |pane, cx| {
@ -266,10 +291,97 @@ impl TerminalPanel {
};
this.update(cx, |this, cx| {
this.add_terminal(Some(action.working_directory.clone()), cx)
this.add_terminal(Some(action.working_directory.clone()), None, cx)
})
}
pub fn spawn_runnable(
&mut self,
spawn_in_terminal: &runnable::SpawnInTerminal,
cx: &mut ViewContext<Self>,
) {
let spawn_runnable = SpawnRunnable {
id: spawn_in_terminal.id.clone(),
label: spawn_in_terminal.label.clone(),
command: spawn_in_terminal.command.clone(),
args: spawn_in_terminal.args.clone(),
env: spawn_in_terminal.env.clone(),
};
let working_directory = spawn_in_terminal.cwd.clone();
let allow_concurrent_runs = spawn_in_terminal.allow_concurrent_runs;
let use_new_terminal = spawn_in_terminal.use_new_terminal;
if allow_concurrent_runs && use_new_terminal {
self.spawn_in_new_terminal(spawn_runnable, working_directory, cx);
return;
}
let terminals_for_runnable = self.terminals_for_runnable(&spawn_in_terminal.id, cx);
if terminals_for_runnable.is_empty() {
self.spawn_in_new_terminal(spawn_runnable, working_directory, cx);
return;
}
let (existing_item_index, existing_terminal) = terminals_for_runnable
.last()
.expect("covered no terminals case above")
.clone();
if allow_concurrent_runs {
debug_assert!(
!use_new_terminal,
"Should have handled 'allow_concurrent_runs && use_new_terminal' case above"
);
self.replace_terminal(
working_directory,
spawn_runnable,
existing_item_index,
existing_terminal,
cx,
);
} else {
self.deferred_runnables.insert(
spawn_in_terminal.id.clone(),
cx.spawn(|terminal_panel, mut cx| async move {
wait_for_terminals_tasks(terminals_for_runnable, &mut cx).await;
terminal_panel
.update(&mut cx, |terminal_panel, cx| {
if use_new_terminal {
terminal_panel.spawn_in_new_terminal(
spawn_runnable,
working_directory,
cx,
);
} else {
terminal_panel.replace_terminal(
working_directory,
spawn_runnable,
existing_item_index,
existing_terminal,
cx,
);
}
})
.ok();
}),
);
}
}
fn spawn_in_new_terminal(
&mut self,
spawn_runnable: SpawnRunnable,
working_directory: Option<PathBuf>,
cx: &mut ViewContext<Self>,
) {
self.add_terminal(working_directory, Some(spawn_runnable), cx);
let task_workspace = self.workspace.clone();
cx.spawn(|_, mut cx| async move {
task_workspace
.update(&mut cx, |workspace, cx| workspace.focus_panel::<Self>(cx))
.ok()
})
.detach();
}
///Create a new Terminal in the current working directory or the user's home directory
fn new_terminal(
workspace: &mut Workspace,
@ -280,13 +392,46 @@ impl TerminalPanel {
return;
};
this.update(cx, |this, cx| this.add_terminal(None, cx))
this.update(cx, |this, cx| this.add_terminal(None, None, cx))
}
fn add_terminal(&mut self, working_directory: Option<PathBuf>, cx: &mut ViewContext<Self>) {
fn terminals_for_runnable(
&self,
id: &RunnableId,
cx: &mut AppContext,
) -> Vec<(usize, View<TerminalView>)> {
self.pane
.read(cx)
.items()
.enumerate()
.filter_map(|(index, item)| Some((index, item.act_as::<TerminalView>(cx)?)))
.filter_map(|(index, terminal_view)| {
let runnable_state = terminal_view.read(cx).terminal().read(cx).runnable()?;
if &runnable_state.id == id {
Some((index, terminal_view))
} else {
None
}
})
.collect()
}
fn activate_terminal_view(&self, item_index: usize, cx: &mut WindowContext) {
self.pane.update(cx, |pane, cx| {
pane.activate_item(item_index, true, true, cx)
})
}
fn add_terminal(
&mut self,
working_directory: Option<PathBuf>,
spawn_runnable: Option<SpawnRunnable>,
cx: &mut ViewContext<Self>,
) {
let workspace = self.workspace.clone();
cx.spawn(|this, mut cx| async move {
let pane = this.update(&mut cx, |this, _| this.pane.clone())?;
self.pending_terminals_to_add += 1;
cx.spawn(|terminal_panel, mut cx| async move {
let pane = terminal_panel.update(&mut cx, |this, _| this.pane.clone())?;
workspace.update(&mut cx, |workspace, cx| {
let working_directory = if let Some(working_directory) = working_directory {
Some(working_directory)
@ -299,7 +444,7 @@ impl TerminalPanel {
let window = cx.window_handle();
if let Some(terminal) = workspace.project().update(cx, |project, cx| {
project
.create_terminal(working_directory, window, cx)
.create_terminal(working_directory, spawn_runnable, window, cx)
.log_err()
}) {
let terminal = Box::new(cx.new_view(|cx| {
@ -316,24 +461,44 @@ impl TerminalPanel {
});
}
})?;
this.update(&mut cx, |this, cx| this.serialize(cx))?;
terminal_panel.update(&mut cx, |this, cx| {
this.pending_terminals_to_add = this.pending_terminals_to_add.saturating_sub(1);
this.serialize(cx)
})?;
anyhow::Ok(())
})
.detach_and_log_err(cx);
}
fn serialize(&mut self, cx: &mut ViewContext<Self>) {
let mut items_to_serialize = HashSet::default();
let items = self
.pane
.read(cx)
.items()
.map(|item| item.item_id().as_u64())
.filter_map(|item| {
let terminal_view = item.act_as::<TerminalView>(cx)?;
if terminal_view
.read(cx)
.terminal()
.read(cx)
.runnable()
.is_some()
{
None
} else {
let id = item.item_id().as_u64();
items_to_serialize.insert(id);
Some(id)
}
})
.collect::<Vec<_>>();
let active_item_id = self
.pane
.read(cx)
.active_item()
.map(|item| item.item_id().as_u64());
.map(|item| item.item_id().as_u64())
.filter(|active_id| items_to_serialize.contains(active_id));
let height = self.height;
let width = self.width;
self.pending_serialization = cx.background_executor().spawn(
@ -354,6 +519,47 @@ impl TerminalPanel {
.log_err(),
);
}
fn replace_terminal(
&self,
working_directory: Option<PathBuf>,
spawn_runnable: SpawnRunnable,
terminal_item_index: usize,
terminal_to_replace: View<TerminalView>,
cx: &mut ViewContext<'_, Self>,
) -> Option<()> {
let project = self
.workspace
.update(cx, |workspace, _| workspace.project().clone())
.ok()?;
let window = cx.window_handle();
let new_terminal = project.update(cx, |project, cx| {
project
.create_terminal(working_directory, Some(spawn_runnable), window, cx)
.log_err()
})?;
terminal_to_replace.update(cx, |terminal_to_replace, cx| {
terminal_to_replace.set_terminal(new_terminal, cx);
});
self.activate_terminal_view(terminal_item_index, cx);
Some(())
}
}
async fn wait_for_terminals_tasks(
terminals_for_runnable: Vec<(usize, View<TerminalView>)>,
cx: &mut AsyncWindowContext,
) {
let pending_tasks = terminals_for_runnable.iter().filter_map(|(_, terminal)| {
terminal
.update(cx, |terminal_view, cx| {
terminal_view
.terminal()
.update(cx, |terminal, cx| terminal.wait_for_completed_runnable(cx))
})
.ok()
});
let _: Vec<()> = join_all(pending_tasks).await;
}
fn add_paths_to_terminal(pane: &mut Pane, paths: &[PathBuf], cx: &mut ViewContext<'_, Pane>) {
@ -450,8 +656,8 @@ impl Panel for TerminalPanel {
}
fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
if active && self.pane.read(cx).items_len() == 0 {
self.add_terminal(None, cx)
if active && self.pane.read(cx).items_len() == 0 && self.pending_terminals_to_add == 0 {
self.add_terminal(None, None, cx)
}
}

View file

@ -91,6 +91,7 @@ pub struct TerminalView {
can_navigate_to_selected_word: bool,
workspace_id: WorkspaceId,
_subscriptions: Vec<Subscription>,
_terminal_subscriptions: Vec<Subscription>,
}
impl EventEmitter<Event> for TerminalView {}
@ -118,7 +119,7 @@ impl TerminalView {
let terminal = workspace
.project()
.update(cx, |project, cx| {
project.create_terminal(working_directory, window, cx)
project.create_terminal(working_directory, None, window, cx)
})
.notify_err(workspace, cx);
@ -142,161 +143,7 @@ impl TerminalView {
cx: &mut ViewContext<Self>,
) -> Self {
let workspace_handle = workspace.clone();
cx.observe(&terminal, |_, _, cx| cx.notify()).detach();
cx.subscribe(&terminal, move |this, _, event, cx| match event {
Event::Wakeup => {
cx.notify();
cx.emit(Event::Wakeup);
cx.emit(ItemEvent::UpdateTab);
cx.emit(SearchEvent::MatchesInvalidated);
}
Event::Bell => {
this.has_bell = true;
cx.emit(Event::Wakeup);
}
Event::BlinkChanged => this.blinking_on = !this.blinking_on,
Event::TitleChanged => {
cx.emit(ItemEvent::UpdateTab);
if let Some(foreground_info) = &this.terminal().read(cx).foreground_process_info {
let cwd = foreground_info.cwd.clone();
let item_id = cx.entity_id();
let workspace_id = this.workspace_id;
cx.background_executor()
.spawn(async move {
TERMINAL_DB
.save_working_directory(item_id.as_u64(), workspace_id, cwd)
.await
.log_err();
})
.detach();
}
}
Event::NewNavigationTarget(maybe_navigation_target) => {
this.can_navigate_to_selected_word = match maybe_navigation_target {
Some(MaybeNavigationTarget::Url(_)) => true,
Some(MaybeNavigationTarget::PathLike(path_like_target)) => {
if let Ok(fs) = workspace.update(cx, |workspace, cx| {
workspace.project().read(cx).fs().clone()
}) {
let valid_files_to_open_task = possible_open_targets(
fs,
&workspace,
&path_like_target.terminal_dir,
&path_like_target.maybe_path,
cx,
);
smol::block_on(valid_files_to_open_task).len() > 0
} else {
false
}
}
None => false,
}
}
Event::Open(maybe_navigation_target) => match maybe_navigation_target {
MaybeNavigationTarget::Url(url) => cx.open_url(url),
MaybeNavigationTarget::PathLike(path_like_target) => {
if !this.can_navigate_to_selected_word {
return;
}
let task_workspace = workspace.clone();
let Some(fs) = workspace
.update(cx, |workspace, cx| {
workspace.project().read(cx).fs().clone()
})
.ok()
else {
return;
};
let path_like_target = path_like_target.clone();
cx.spawn(|terminal_view, mut cx| async move {
let valid_files_to_open = terminal_view
.update(&mut cx, |_, cx| {
possible_open_targets(
fs,
&task_workspace,
&path_like_target.terminal_dir,
&path_like_target.maybe_path,
cx,
)
})?
.await;
let paths_to_open = valid_files_to_open
.iter()
.map(|(p, _)| p.path_like.clone())
.collect();
let opened_items = task_workspace
.update(&mut cx, |workspace, cx| {
workspace.open_paths(
paths_to_open,
OpenVisible::OnlyDirectories,
None,
cx,
)
})
.context("workspace update")?
.await;
let mut has_dirs = false;
for ((path, metadata), opened_item) in valid_files_to_open
.into_iter()
.zip(opened_items.into_iter())
{
if metadata.is_dir {
has_dirs = true;
} else if let Some(Ok(opened_item)) = opened_item {
if let Some(row) = path.row {
let col = path.column.unwrap_or(0);
if let Some(active_editor) = opened_item.downcast::<Editor>() {
active_editor
.downgrade()
.update(&mut cx, |editor, cx| {
let snapshot = editor.snapshot(cx).display_snapshot;
let point = snapshot.buffer_snapshot.clip_point(
language::Point::new(
row.saturating_sub(1),
col.saturating_sub(1),
),
Bias::Left,
);
editor.change_selections(
Some(Autoscroll::center()),
cx,
|s| s.select_ranges([point..point]),
);
})
.log_err();
}
}
}
}
if has_dirs {
task_workspace.update(&mut cx, |workspace, cx| {
workspace.project().update(cx, |_, cx| {
cx.emit(project::Event::ActivateProjectPanel);
})
})?;
}
anyhow::Ok(())
})
.detach_and_log_err(cx)
}
},
Event::BreadcrumbsChanged => cx.emit(ItemEvent::UpdateBreadcrumbs),
Event::CloseTerminal => cx.emit(ItemEvent::CloseItem),
Event::SelectionsChanged => cx.emit(SearchEvent::ActiveMatchChanged),
})
.detach();
let terminal_subscriptions = subscribe_for_terminal_events(&terminal, workspace, cx);
let focus_handle = cx.focus_handle();
let focus_in = cx.on_focus_in(&focus_handle, |terminal_view, cx| {
@ -319,6 +166,7 @@ impl TerminalView {
can_navigate_to_selected_word: false,
workspace_id,
_subscriptions: vec![focus_in, focus_out],
_terminal_subscriptions: terminal_subscriptions,
}
}
@ -560,6 +408,178 @@ impl TerminalView {
};
dispatch_context
}
fn set_terminal(&mut self, terminal: Model<Terminal>, cx: &mut ViewContext<'_, TerminalView>) {
self._terminal_subscriptions =
subscribe_for_terminal_events(&terminal, self.workspace.clone(), cx);
self.terminal = terminal;
}
}
fn subscribe_for_terminal_events(
terminal: &Model<Terminal>,
workspace: WeakView<Workspace>,
cx: &mut ViewContext<'_, TerminalView>,
) -> Vec<Subscription> {
let terminal_subscription = cx.observe(terminal, |_, _, cx| cx.notify());
let terminal_events_subscription =
cx.subscribe(terminal, move |this, _, event, cx| match event {
Event::Wakeup => {
cx.notify();
cx.emit(Event::Wakeup);
cx.emit(ItemEvent::UpdateTab);
cx.emit(SearchEvent::MatchesInvalidated);
}
Event::Bell => {
this.has_bell = true;
cx.emit(Event::Wakeup);
}
Event::BlinkChanged => this.blinking_on = !this.blinking_on,
Event::TitleChanged => {
cx.emit(ItemEvent::UpdateTab);
let terminal = this.terminal().read(cx);
if !terminal.runnable().is_some() {
if let Some(foreground_info) = &terminal.foreground_process_info {
let cwd = foreground_info.cwd.clone();
let item_id = cx.entity_id();
let workspace_id = this.workspace_id;
cx.background_executor()
.spawn(async move {
TERMINAL_DB
.save_working_directory(item_id.as_u64(), workspace_id, cwd)
.await
.log_err();
})
.detach();
}
}
}
Event::NewNavigationTarget(maybe_navigation_target) => {
this.can_navigate_to_selected_word = match maybe_navigation_target {
Some(MaybeNavigationTarget::Url(_)) => true,
Some(MaybeNavigationTarget::PathLike(path_like_target)) => {
if let Ok(fs) = workspace.update(cx, |workspace, cx| {
workspace.project().read(cx).fs().clone()
}) {
let valid_files_to_open_task = possible_open_targets(
fs,
&workspace,
&path_like_target.terminal_dir,
&path_like_target.maybe_path,
cx,
);
smol::block_on(valid_files_to_open_task).len() > 0
} else {
false
}
}
None => false,
}
}
Event::Open(maybe_navigation_target) => match maybe_navigation_target {
MaybeNavigationTarget::Url(url) => cx.open_url(url),
MaybeNavigationTarget::PathLike(path_like_target) => {
if !this.can_navigate_to_selected_word {
return;
}
let task_workspace = workspace.clone();
let Some(fs) = workspace
.update(cx, |workspace, cx| {
workspace.project().read(cx).fs().clone()
})
.ok()
else {
return;
};
let path_like_target = path_like_target.clone();
cx.spawn(|terminal_view, mut cx| async move {
let valid_files_to_open = terminal_view
.update(&mut cx, |_, cx| {
possible_open_targets(
fs,
&task_workspace,
&path_like_target.terminal_dir,
&path_like_target.maybe_path,
cx,
)
})?
.await;
let paths_to_open = valid_files_to_open
.iter()
.map(|(p, _)| p.path_like.clone())
.collect();
let opened_items = task_workspace
.update(&mut cx, |workspace, cx| {
workspace.open_paths(
paths_to_open,
OpenVisible::OnlyDirectories,
None,
cx,
)
})
.context("workspace update")?
.await;
let mut has_dirs = false;
for ((path, metadata), opened_item) in valid_files_to_open
.into_iter()
.zip(opened_items.into_iter())
{
if metadata.is_dir {
has_dirs = true;
} else if let Some(Ok(opened_item)) = opened_item {
if let Some(row) = path.row {
let col = path.column.unwrap_or(0);
if let Some(active_editor) = opened_item.downcast::<Editor>() {
active_editor
.downgrade()
.update(&mut cx, |editor, cx| {
let snapshot = editor.snapshot(cx).display_snapshot;
let point = snapshot.buffer_snapshot.clip_point(
language::Point::new(
row.saturating_sub(1),
col.saturating_sub(1),
),
Bias::Left,
);
editor.change_selections(
Some(Autoscroll::center()),
cx,
|s| s.select_ranges([point..point]),
);
})
.log_err();
}
}
}
}
if has_dirs {
task_workspace.update(&mut cx, |workspace, cx| {
workspace.project().update(cx, |_, cx| {
cx.emit(project::Event::ActivateProjectPanel);
})
})?;
}
anyhow::Ok(())
})
.detach_and_log_err(cx)
}
},
Event::BreadcrumbsChanged => cx.emit(ItemEvent::UpdateBreadcrumbs),
Event::CloseTerminal => cx.emit(ItemEvent::CloseItem),
Event::SelectionsChanged => cx.emit(SearchEvent::ActiveMatchChanged),
});
vec![terminal_subscription, terminal_events_subscription]
}
fn possible_open_paths_metadata(
@ -755,10 +775,16 @@ impl Item for TerminalView {
selected: bool,
cx: &WindowContext,
) -> AnyElement {
let title = self.terminal().read(cx).title(true);
let terminal = self.terminal().read(cx);
let title = terminal.title(true);
let icon = if terminal.runnable().is_some() {
IconName::Play
} else {
IconName::Terminal
};
h_flex()
.gap_2()
.child(Icon::new(IconName::Terminal))
.child(Icon::new(icon))
.child(Label::new(title).color(if selected {
Color::Default
} else {
@ -790,8 +816,11 @@ impl Item for TerminalView {
None
}
fn is_dirty(&self, _cx: &gpui::AppContext) -> bool {
self.has_bell()
fn is_dirty(&self, cx: &gpui::AppContext) -> bool {
match self.terminal.read(cx).runnable() {
Some(runnable) => !runnable.completed,
None => self.has_bell(),
}
}
fn has_conflict(&self, _cx: &AppContext) -> bool {
@ -845,7 +874,7 @@ impl Item for TerminalView {
});
let terminal = project.update(&mut cx, |project, cx| {
project.create_terminal(cwd, window, cx)
project.create_terminal(cwd, None, window, cx)
})??;
pane.update(&mut cx, |_, cx| {
cx.new_view(|cx| TerminalView::new(terminal, workspace, workspace_id, cx))
@ -854,14 +883,16 @@ impl Item for TerminalView {
}
fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
cx.background_executor()
.spawn(TERMINAL_DB.update_workspace_id(
workspace.database_id(),
self.workspace_id,
cx.entity_id().as_u64(),
))
.detach();
self.workspace_id = workspace.database_id();
if !self.terminal().read(cx).runnable().is_some() {
cx.background_executor()
.spawn(TERMINAL_DB.update_workspace_id(
workspace.database_id(),
self.workspace_id,
cx.entity_id().as_u64(),
))
.detach();
self.workspace_id = workspace.database_id();
}
}
fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {