Fix esc in command palette

Also: add editor.register_action
This commit is contained in:
Conrad Irwin 2023-11-27 14:32:06 -07:00
parent 4f885252ab
commit 107c3d7f67
8 changed files with 140 additions and 56 deletions

View File

@ -40,11 +40,12 @@ use fuzzy::{StringMatch, StringMatchCandidate};
use git::diff_hunk_to_display; use git::diff_hunk_to_display;
use gpui::{ use gpui::{
actions, div, point, prelude::*, px, relative, rems, size, uniform_list, Action, AnyElement, actions, div, point, prelude::*, px, relative, rems, size, uniform_list, Action, AnyElement,
AppContext, AsyncWindowContext, BackgroundExecutor, Bounds, ClipboardItem, Context, ElementId, AppContext, AsyncWindowContext, BackgroundExecutor, Bounds, ClipboardItem, Context,
EventEmitter, FocusHandle, FocusableView, FontFeatures, FontStyle, FontWeight, HighlightStyle, DispatchPhase, Div, ElementId, EventEmitter, FocusHandle, FocusableView, FontFeatures,
Hsla, InputHandler, InteractiveText, KeyContext, Model, MouseButton, ParentElement, Pixels, FontStyle, FontWeight, HighlightStyle, Hsla, InputHandler, InteractiveText, KeyContext, Model,
Render, RenderOnce, SharedString, Styled, StyledText, Subscription, Task, TextRun, TextStyle, MouseButton, ParentElement, Pixels, Render, RenderOnce, SharedString, Styled, StyledText,
UniformListScrollHandle, View, ViewContext, VisualContext, WeakView, WhiteSpace, WindowContext, Subscription, Task, TextRun, TextStyle, UniformListScrollHandle, View, ViewContext,
VisualContext, WeakView, WhiteSpace, WindowContext,
}; };
use highlight_matching_bracket::refresh_matching_bracket_highlights; use highlight_matching_bracket::refresh_matching_bracket_highlights;
use hover_popover::{hide_hover, HoverState}; use hover_popover::{hide_hover, HoverState};
@ -103,7 +104,7 @@ use util::{post_inc, RangeExt, ResultExt, TryFutureExt};
use workspace::{ use workspace::{
item::{ItemEvent, ItemHandle}, item::{ItemEvent, ItemHandle},
searchable::SearchEvent, searchable::SearchEvent,
ItemNavHistory, SplitDirection, ViewId, Workspace, ItemNavHistory, Pane, SplitDirection, ViewId, Workspace,
}; };
const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500); const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
@ -662,6 +663,7 @@ pub struct Editor {
pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>, pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
gutter_width: Pixels, gutter_width: Pixels,
style: Option<EditorStyle>, style: Option<EditorStyle>,
editor_actions: Vec<Box<dyn Fn(&mut ViewContext<Self>)>>,
} }
pub struct EditorSnapshot { pub struct EditorSnapshot {
@ -1890,6 +1892,7 @@ impl Editor {
pixel_position_of_newest_cursor: None, pixel_position_of_newest_cursor: None,
gutter_width: Default::default(), gutter_width: Default::default(),
style: None, style: None,
editor_actions: Default::default(),
_subscriptions: vec![ _subscriptions: vec![
cx.observe(&buffer, Self::on_buffer_changed), cx.observe(&buffer, Self::on_buffer_changed),
cx.subscribe(&buffer, Self::on_buffer_event), cx.subscribe(&buffer, Self::on_buffer_event),
@ -2021,10 +2024,14 @@ impl Editor {
&self.buffer &self.buffer
} }
fn workspace(&self) -> Option<View<Workspace>> { pub fn workspace(&self) -> Option<View<Workspace>> {
self.workspace.as_ref()?.0.upgrade() self.workspace.as_ref()?.0.upgrade()
} }
pub fn pane(&self, cx: &AppContext) -> Option<View<Pane>> {
self.workspace()?.read(cx).pane_for(&self.handle.upgrade()?)
}
pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> { pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
self.buffer().read(cx).title(cx) self.buffer().read(cx).title(cx)
} }
@ -9181,6 +9188,26 @@ impl Editor {
cx.emit(EditorEvent::Blurred); cx.emit(EditorEvent::Blurred);
cx.notify(); cx.notify();
} }
pub fn register_action<A: Action>(
&mut self,
listener: impl Fn(&A, &mut WindowContext) + 'static,
) -> &mut Self {
let listener = Arc::new(listener);
self.editor_actions.push(Box::new(move |cx| {
let view = cx.view().clone();
let cx = cx.window_context();
let listener = listener.clone();
cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
let action = action.downcast_ref().unwrap();
if phase == DispatchPhase::Bubble {
listener(action, cx)
}
})
}));
self
}
} }
pub trait CollaborationHub { pub trait CollaborationHub {

View File

@ -128,6 +128,11 @@ impl EditorElement {
fn register_actions(&self, cx: &mut WindowContext) { fn register_actions(&self, cx: &mut WindowContext) {
let view = &self.editor; let view = &self.editor;
self.editor.update(cx, |editor, cx| {
for action in editor.editor_actions.iter() {
(action)(cx)
}
});
register_action(view, cx, Editor::move_left); register_action(view, cx, Editor::move_left);
register_action(view, cx, Editor::move_right); register_action(view, cx, Editor::move_right);
register_action(view, cx, Editor::move_down); register_action(view, cx, Editor::move_down);
@ -4068,7 +4073,7 @@ fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
// } // }
// } // }
fn register_action<T: Action>( pub fn register_action<T: Action>(
view: &View<Editor>, view: &View<Editor>,
cx: &mut WindowContext, cx: &mut WindowContext,
listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static, listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,

View File

@ -8,7 +8,6 @@ use text::{Bias, Point};
use theme::ActiveTheme; use theme::ActiveTheme;
use ui::{h_stack, v_stack, Color, Label, StyledExt}; use ui::{h_stack, v_stack, Color, Label, StyledExt};
use util::paths::FILE_ROW_COLUMN_DELIMITER; use util::paths::FILE_ROW_COLUMN_DELIMITER;
use workspace::Workspace;
actions!(Toggle); actions!(Toggle);
@ -26,22 +25,24 @@ pub struct GoToLine {
impl FocusableView for GoToLine { impl FocusableView for GoToLine {
fn focus_handle(&self, cx: &AppContext) -> FocusHandle { fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
self.active_editor.focus_handle(cx) self.line_editor.focus_handle(cx)
} }
} }
impl EventEmitter<DismissEvent> for GoToLine {} impl EventEmitter<DismissEvent> for GoToLine {}
impl GoToLine { impl GoToLine {
fn register(workspace: &mut Workspace, _: &mut ViewContext<Workspace>) { fn register(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
workspace.register_action(|workspace, _: &Toggle, cx| { let handle = cx.view().downgrade();
let Some(editor) = workspace editor.register_action(move |_: &Toggle, cx| {
.active_item(cx) let Some(editor) = handle.upgrade() else {
.and_then(|active_item| active_item.downcast::<Editor>())
else {
return; return;
}; };
let Some(workspace) = editor.read(cx).workspace() else {
workspace.toggle_modal(cx, move |cx| GoToLine::new(editor, cx)); return;
};
workspace.update(cx, |workspace, cx| {
workspace.toggle_modal(cx, move |cx| GoToLine::new(editor, cx));
})
}); });
} }

View File

@ -114,6 +114,7 @@ impl<D: PickerDelegate> Picker<D> {
} }
fn cancel(&mut self, _: &menu::Cancel, cx: &mut ViewContext<Self>) { fn cancel(&mut self, _: &menu::Cancel, cx: &mut ViewContext<Self>) {
dbg!("canceling!");
self.delegate.dismissed(cx); self.delegate.dismissed(cx);
} }

View File

@ -644,6 +644,7 @@ impl ProjectPanel {
} }
fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) { fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
dbg!("odd");
self.edit_state = None; self.edit_state = None;
self.update_visible_entries(None, cx); self.update_visible_entries(None, cx);
cx.focus(&self.focus_handle); cx.focus(&self.focus_handle);

View File

@ -7,12 +7,12 @@ use crate::{
ToggleCaseSensitive, ToggleReplace, ToggleWholeWord, ToggleCaseSensitive, ToggleReplace, ToggleWholeWord,
}; };
use collections::HashMap; use collections::HashMap;
use editor::Editor; use editor::{Editor, EditorMode};
use futures::channel::oneshot; use futures::channel::oneshot;
use gpui::{ use gpui::{
actions, div, red, Action, AppContext, Div, EventEmitter, InteractiveElement as _, IntoElement, actions, div, red, Action, AppContext, Div, EventEmitter, InteractiveElement as _, IntoElement,
ParentElement as _, Render, Styled, Subscription, Task, View, ViewContext, VisualContext as _, ParentElement as _, Render, Styled, Subscription, Task, View, ViewContext, VisualContext as _,
WindowContext, WeakView, WindowContext,
}; };
use project::search::SearchQuery; use project::search::SearchQuery;
use serde::Deserialize; use serde::Deserialize;
@ -23,7 +23,7 @@ use util::ResultExt;
use workspace::{ use workspace::{
item::ItemHandle, item::ItemHandle,
searchable::{Direction, SearchEvent, SearchableItemHandle, WeakSearchableItemHandle}, searchable::{Direction, SearchEvent, SearchableItemHandle, WeakSearchableItemHandle},
ToolbarItemLocation, ToolbarItemView, Workspace, ToolbarItemLocation, ToolbarItemView,
}; };
#[derive(PartialEq, Clone, Deserialize, Default, Action)] #[derive(PartialEq, Clone, Deserialize, Default, Action)]
@ -38,7 +38,7 @@ pub enum Event {
} }
pub fn init(cx: &mut AppContext) { pub fn init(cx: &mut AppContext) {
cx.observe_new_views(|workspace: &mut Workspace, _| BufferSearchBar::register(workspace)) cx.observe_new_views(|editor: &mut Editor, cx| BufferSearchBar::register(editor, cx))
.detach(); .detach();
} }
@ -187,6 +187,7 @@ impl Render for BufferSearchBar {
}) })
.on_action(cx.listener(Self::previous_history_query)) .on_action(cx.listener(Self::previous_history_query))
.on_action(cx.listener(Self::next_history_query)) .on_action(cx.listener(Self::next_history_query))
.on_action(cx.listener(Self::dismiss))
.w_full() .w_full()
.p_1() .p_1()
.child( .child(
@ -294,9 +295,19 @@ impl ToolbarItemView for BufferSearchBar {
} }
impl BufferSearchBar { impl BufferSearchBar {
pub fn register(workspace: &mut Workspace) { pub fn register(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
workspace.register_action(|workspace, a: &Deploy, cx| { if editor.mode() != EditorMode::Full {
workspace.active_pane().update(cx, |this, cx| { return;
};
let handle = cx.view().downgrade();
editor.register_action(move |a: &Deploy, cx| {
let Some(pane) = handle.upgrade().and_then(|editor| editor.read(cx).pane(cx)) else {
return;
};
pane.update(cx, |this, cx| {
this.toolbar().update(cx, |this, cx| { this.toolbar().update(cx, |this, cx| {
if let Some(search_bar) = this.item_of_type::<BufferSearchBar>() { if let Some(search_bar) = this.item_of_type::<BufferSearchBar>() {
search_bar.update(cx, |this, cx| { search_bar.update(cx, |this, cx| {
@ -316,11 +327,16 @@ impl BufferSearchBar {
}); });
}); });
fn register_action<A: Action>( fn register_action<A: Action>(
workspace: &mut Workspace, editor: &mut Editor,
handle: WeakView<Editor>,
update: fn(&mut BufferSearchBar, &A, &mut ViewContext<BufferSearchBar>), update: fn(&mut BufferSearchBar, &A, &mut ViewContext<BufferSearchBar>),
) { ) {
workspace.register_action(move |workspace, action: &A, cx| { editor.register_action(move |action: &A, cx| {
workspace.active_pane().update(cx, move |this, cx| { let Some(pane) = handle.upgrade().and_then(|editor| editor.read(cx).pane(cx))
else {
return;
};
pane.update(cx, move |this, cx| {
this.toolbar().update(cx, move |this, cx| { this.toolbar().update(cx, move |this, cx| {
if let Some(search_bar) = this.item_of_type::<BufferSearchBar>() { if let Some(search_bar) = this.item_of_type::<BufferSearchBar>() {
search_bar.update(cx, move |this, cx| update(this, action, cx)); search_bar.update(cx, move |this, cx| update(this, action, cx));
@ -331,49 +347,76 @@ impl BufferSearchBar {
}); });
} }
register_action(workspace, |this, action: &ToggleCaseSensitive, cx| { let handle = cx.view().downgrade();
if this.supported_options().case { register_action(
this.toggle_case_sensitive(action, cx); editor,
} handle.clone(),
}); |this, action: &ToggleCaseSensitive, cx| {
register_action(workspace, |this, action: &ToggleWholeWord, cx| { if this.supported_options().case {
if this.supported_options().word { this.toggle_case_sensitive(action, cx);
this.toggle_whole_word(action, cx); }
} },
}); );
register_action(workspace, |this, action: &ToggleReplace, cx| { register_action(
if this.supported_options().replacement { editor,
this.toggle_replace(action, cx); handle.clone(),
} |this, action: &ToggleWholeWord, cx| {
}); if this.supported_options().word {
register_action(workspace, |this, _: &ActivateRegexMode, cx| { this.toggle_whole_word(action, cx);
}
},
);
register_action(
editor,
handle.clone(),
|this, action: &ToggleReplace, cx| {
if this.supported_options().replacement {
this.toggle_replace(action, cx);
}
},
);
register_action(editor, handle.clone(), |this, _: &ActivateRegexMode, cx| {
if this.supported_options().regex { if this.supported_options().regex {
this.activate_search_mode(SearchMode::Regex, cx); this.activate_search_mode(SearchMode::Regex, cx);
} }
}); });
register_action(workspace, |this, _: &ActivateTextMode, cx| { register_action(editor, handle.clone(), |this, _: &ActivateTextMode, cx| {
this.activate_search_mode(SearchMode::Text, cx); this.activate_search_mode(SearchMode::Text, cx);
}); });
register_action(workspace, |this, action: &CycleMode, cx| { register_action(editor, handle.clone(), |this, action: &CycleMode, cx| {
if this.supported_options().regex { if this.supported_options().regex {
// If regex is not supported then search has just one mode (text) - in that case there's no point in supporting // If regex is not supported then search has just one mode (text) - in that case there's no point in supporting
// cycling. // cycling.
this.cycle_mode(action, cx) this.cycle_mode(action, cx)
} }
}); });
register_action(workspace, |this, action: &SelectNextMatch, cx| { register_action(
this.select_next_match(action, cx); editor,
}); handle.clone(),
register_action(workspace, |this, action: &SelectPrevMatch, cx| { |this, action: &SelectNextMatch, cx| {
this.select_prev_match(action, cx); this.select_next_match(action, cx);
}); },
register_action(workspace, |this, action: &SelectAllMatches, cx| { );
this.select_all_matches(action, cx); register_action(
}); editor,
register_action(workspace, |this, _: &editor::Cancel, cx| { handle.clone(),
|this, action: &SelectPrevMatch, cx| {
this.select_prev_match(action, cx);
},
);
register_action(
editor,
handle.clone(),
|this, action: &SelectAllMatches, cx| {
this.select_all_matches(action, cx);
},
);
register_action(editor, handle.clone(), |this, _: &editor::Cancel, cx| {
if !this.dismissed { if !this.dismissed {
this.dismiss(&Dismiss, cx); this.dismiss(&Dismiss, cx);
return;
} }
cx.propagate();
}); });
} }
pub fn new(cx: &mut ViewContext<Self>) -> Self { pub fn new(cx: &mut ViewContext<Self>) -> Self {

View File

@ -46,6 +46,7 @@ impl ModalLayer {
previous_focus_handle: cx.focused(), previous_focus_handle: cx.focused(),
focus_handle: cx.focus_handle(), focus_handle: cx.focus_handle(),
}); });
dbg!("focusing");
cx.focus_view(&new_modal); cx.focus_view(&new_modal);
cx.notify(); cx.notify();
} }

View File

@ -2342,6 +2342,11 @@ impl Workspace {
&self.active_pane &self.active_pane
} }
pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<View<Pane>> {
let weak_pane = self.panes_by_item.get(&handle.item_id())?;
weak_pane.upgrade()
}
fn collaborator_left(&mut self, peer_id: PeerId, cx: &mut ViewContext<Self>) { fn collaborator_left(&mut self, peer_id: PeerId, cx: &mut ViewContext<Self>) {
self.follower_states.retain(|_, state| { self.follower_states.retain(|_, state| {
if state.leader_id == peer_id { if state.leader_id == peer_id {