Merge branch 'main' into update-pickers

This commit is contained in:
Nate Butler 2023-12-06 10:48:50 -05:00
commit 3b8c566f31
17 changed files with 667 additions and 762 deletions

View file

@ -23,11 +23,13 @@ pub type HashMap<K, V> = std::collections::HashMap<K, V>;
#[cfg(not(feature = "test-support"))]
pub type HashSet<T> = std::collections::HashSet<T>;
use std::any::TypeId;
pub use std::collections::*;
// NEW TYPES
#[derive(Default)]
pub struct CommandPaletteFilter {
pub filtered_namespaces: HashSet<&'static str>,
pub hidden_namespaces: HashSet<&'static str>,
pub hidden_action_types: HashSet<TypeId>,
}

View file

@ -109,7 +109,7 @@ impl PickerDelegate for CommandPaletteDelegate {
let filtered = cx.read(|cx| {
if cx.has_global::<CommandPaletteFilter>() {
let filter = cx.global::<CommandPaletteFilter>();
filter.filtered_namespaces.contains(action.namespace())
filter.hidden_namespaces.contains(action.namespace())
} else {
false
}
@ -430,7 +430,7 @@ mod tests {
// Add namespace filter, and redeploy the palette
cx.update(|cx| {
cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| {
filter.filtered_namespaces.insert("editor");
filter.hidden_namespaces.insert("editor");
})
});

View file

@ -49,7 +49,10 @@ impl CommandPalette {
.filter_map(|action| {
let name = gpui::remove_the_2(action.name());
let namespace = name.split("::").next().unwrap_or("malformed action name");
if filter.is_some_and(|f| f.filtered_namespaces.contains(namespace)) {
if filter.is_some_and(|f| {
f.hidden_namespaces.contains(namespace)
|| f.hidden_action_types.contains(&action.type_id())
}) {
return None;
}
@ -433,7 +436,7 @@ mod tests {
cx.update(|cx| {
cx.set_global(CommandPaletteFilter::default());
cx.update_global::<CommandPaletteFilter, _>(|filter, _| {
filter.filtered_namespaces.insert("editor");
filter.hidden_namespaces.insert("editor");
})
});

View file

@ -58,16 +58,16 @@ pub fn init(
cx.update_default_global::<collections::CommandPaletteFilter, _, _>(move |filter, _cx| {
match status {
Status::Disabled => {
filter.filtered_namespaces.insert(COPILOT_NAMESPACE);
filter.filtered_namespaces.insert(COPILOT_AUTH_NAMESPACE);
filter.hidden_namespaces.insert(COPILOT_NAMESPACE);
filter.hidden_namespaces.insert(COPILOT_AUTH_NAMESPACE);
}
Status::Authorized => {
filter.filtered_namespaces.remove(COPILOT_NAMESPACE);
filter.filtered_namespaces.remove(COPILOT_AUTH_NAMESPACE);
filter.hidden_namespaces.remove(COPILOT_NAMESPACE);
filter.hidden_namespaces.remove(COPILOT_AUTH_NAMESPACE);
}
_ => {
filter.filtered_namespaces.insert(COPILOT_NAMESPACE);
filter.filtered_namespaces.remove(COPILOT_AUTH_NAMESPACE);
filter.hidden_namespaces.insert(COPILOT_NAMESPACE);
filter.hidden_namespaces.remove(COPILOT_AUTH_NAMESPACE);
}
}
});

View file

@ -28,6 +28,7 @@ theme = { package = "theme2", path = "../theme2" }
lsp = { package = "lsp2", path = "../lsp2" }
node_runtime = { path = "../node_runtime"}
util = { path = "../util" }
ui = { package = "ui2", path = "../ui2" }
async-compression = { version = "0.3", features = ["gzip", "futures-bufread"] }
async-tar = "0.4.2"
anyhow.workspace = true

View file

@ -22,6 +22,7 @@ use request::StatusNotification;
use settings::SettingsStore;
use smol::{fs, io::BufReader, stream::StreamExt};
use std::{
any::TypeId,
ffi::OsString,
mem,
ops::Range,
@ -32,13 +33,14 @@ use util::{
fs::remove_matching, github::latest_github_release, http::HttpClient, paths, ResultExt,
};
// todo!()
// const COPILOT_AUTH_NAMESPACE: &'static str = "copilot_auth";
actions!(SignIn, SignOut);
// todo!()
// const COPILOT_NAMESPACE: &'static str = "copilot";
actions!(Suggest, NextSuggestion, PreviousSuggestion, Reinstall);
actions!(
Suggest,
NextSuggestion,
PreviousSuggestion,
Reinstall,
SignIn,
SignOut
);
pub fn init(
new_server_id: LanguageServerId,
@ -51,52 +53,70 @@ pub fn init(
move |cx| Copilot::start(new_server_id, http, node_runtime, cx)
});
cx.set_global(copilot.clone());
cx.observe(&copilot, |handle, cx| {
let copilot_action_types = [
TypeId::of::<Suggest>(),
TypeId::of::<NextSuggestion>(),
TypeId::of::<PreviousSuggestion>(),
TypeId::of::<Reinstall>(),
];
let copilot_auth_action_types = [TypeId::of::<SignOut>()];
let copilot_no_auth_action_types = [TypeId::of::<SignIn>()];
let status = handle.read(cx).status();
let filter = cx.default_global::<collections::CommandPaletteFilter>();
// TODO
// cx.observe(&copilot, |handle, cx| {
// let status = handle.read(cx).status();
// cx.update_default_global::<collections::CommandPaletteFilter, _, _>(move |filter, _cx| {
// match status {
// Status::Disabled => {
// filter.filtered_namespaces.insert(COPILOT_NAMESPACE);
// filter.filtered_namespaces.insert(COPILOT_AUTH_NAMESPACE);
// }
// Status::Authorized => {
// filter.filtered_namespaces.remove(COPILOT_NAMESPACE);
// filter.filtered_namespaces.remove(COPILOT_AUTH_NAMESPACE);
// }
// _ => {
// filter.filtered_namespaces.insert(COPILOT_NAMESPACE);
// filter.filtered_namespaces.remove(COPILOT_AUTH_NAMESPACE);
// }
// }
// });
// })
// .detach();
match status {
Status::Disabled => {
filter.hidden_action_types.extend(copilot_action_types);
filter.hidden_action_types.extend(copilot_auth_action_types);
filter
.hidden_action_types
.extend(copilot_no_auth_action_types);
}
Status::Authorized => {
filter
.hidden_action_types
.extend(copilot_no_auth_action_types);
for type_id in copilot_action_types
.iter()
.chain(&copilot_auth_action_types)
{
filter.hidden_action_types.remove(type_id);
}
}
_ => {
filter.hidden_action_types.extend(copilot_action_types);
filter.hidden_action_types.extend(copilot_auth_action_types);
for type_id in &copilot_no_auth_action_types {
filter.hidden_action_types.remove(type_id);
}
}
}
})
.detach();
// sign_in::init(cx);
// cx.add_global_action(|_: &SignIn, cx| {
// if let Some(copilot) = Copilot::global(cx) {
// copilot
// .update(cx, |copilot, cx| copilot.sign_in(cx))
// .detach_and_log_err(cx);
// }
// });
// cx.add_global_action(|_: &SignOut, cx| {
// if let Some(copilot) = Copilot::global(cx) {
// copilot
// .update(cx, |copilot, cx| copilot.sign_out(cx))
// .detach_and_log_err(cx);
// }
// });
// cx.add_global_action(|_: &Reinstall, cx| {
// if let Some(copilot) = Copilot::global(cx) {
// copilot
// .update(cx, |copilot, cx| copilot.reinstall(cx))
// .detach();
// }
// });
sign_in::init(cx);
cx.on_action(|_: &SignIn, cx| {
if let Some(copilot) = Copilot::global(cx) {
copilot
.update(cx, |copilot, cx| copilot.sign_in(cx))
.detach_and_log_err(cx);
}
});
cx.on_action(|_: &SignOut, cx| {
if let Some(copilot) = Copilot::global(cx) {
copilot
.update(cx, |copilot, cx| copilot.sign_out(cx))
.detach_and_log_err(cx);
}
});
cx.on_action(|_: &Reinstall, cx| {
if let Some(copilot) = Copilot::global(cx) {
copilot
.update(cx, |copilot, cx| copilot.reinstall(cx))
.detach();
}
});
}
enum CopilotServer {

View file

@ -1,376 +1,213 @@
// TODO add logging in
// use crate::{request::PromptUserDeviceFlow, Copilot, Status};
// use gpui::{
// elements::*,
// geometry::rect::RectF,
// platform::{WindowBounds, WindowKind, WindowOptions},
// AnyElement, AnyViewHandle, AppContext, ClipboardItem, Element, Entity, View, ViewContext,
// WindowHandle,
// };
// use theme::ui::modal;
use crate::{request::PromptUserDeviceFlow, Copilot, Status};
use gpui::{
div, size, AppContext, Bounds, ClipboardItem, Div, Element, GlobalPixels, InteractiveElement,
IntoElement, ParentElement, Point, Render, Stateful, Styled, ViewContext, VisualContext,
WindowBounds, WindowHandle, WindowKind, WindowOptions,
};
use theme::ActiveTheme;
use ui::{h_stack, v_stack, Button, Clickable, Color, Icon, IconElement, Label};
// #[derive(PartialEq, Eq, Debug, Clone)]
// struct CopyUserCode;
const COPILOT_SIGN_UP_URL: &'static str = "https://github.com/features/copilot";
// #[derive(PartialEq, Eq, Debug, Clone)]
// struct OpenGithub;
pub fn init(cx: &mut AppContext) {
if let Some(copilot) = Copilot::global(cx) {
let mut verification_window: Option<WindowHandle<CopilotCodeVerification>> = None;
cx.observe(&copilot, move |copilot, cx| {
let status = copilot.read(cx).status();
// const COPILOT_SIGN_UP_URL: &'static str = "https://github.com/features/copilot";
match &status {
crate::Status::SigningIn { prompt } => {
if let Some(window) = verification_window.as_mut() {
let updated = window
.update(cx, |verification, cx| {
verification.set_status(status.clone(), cx);
cx.activate_window();
})
.is_ok();
if !updated {
verification_window = Some(create_copilot_auth_window(cx, &status));
}
} else if let Some(_prompt) = prompt {
verification_window = Some(create_copilot_auth_window(cx, &status));
}
}
Status::Authorized | Status::Unauthorized => {
if let Some(window) = verification_window.as_ref() {
window
.update(cx, |verification, cx| {
verification.set_status(status, cx);
cx.activate(true);
cx.activate_window();
})
.ok();
}
}
_ => {
if let Some(code_verification) = verification_window.take() {
code_verification
.update(cx, |_, cx| cx.remove_window())
.ok();
}
}
}
})
.detach();
}
}
// pub fn init(cx: &mut AppContext) {
// if let Some(copilot) = Copilot::global(cx) {
// let mut verification_window: Option<WindowHandle<CopilotCodeVerification>> = None;
// cx.observe(&copilot, move |copilot, cx| {
// let status = copilot.read(cx).status();
fn create_copilot_auth_window(
cx: &mut AppContext,
status: &Status,
) -> WindowHandle<CopilotCodeVerification> {
let window_size = size(GlobalPixels::from(280.), GlobalPixels::from(280.));
let window_options = WindowOptions {
bounds: WindowBounds::Fixed(Bounds::new(Point::default(), window_size)),
titlebar: None,
center: true,
focus: true,
show: true,
kind: WindowKind::PopUp,
is_movable: true,
display_id: None,
};
let window = cx.open_window(window_options, |cx| {
cx.build_view(|_| CopilotCodeVerification::new(status.clone()))
});
window
}
// match &status {
// crate::Status::SigningIn { prompt } => {
// if let Some(window) = verification_window.as_mut() {
// let updated = window
// .root(cx)
// .map(|root| {
// root.update(cx, |verification, cx| {
// verification.set_status(status.clone(), cx);
// cx.activate_window();
// })
// })
// .is_some();
// if !updated {
// verification_window = Some(create_copilot_auth_window(cx, &status));
// }
// } else if let Some(_prompt) = prompt {
// verification_window = Some(create_copilot_auth_window(cx, &status));
// }
// }
// Status::Authorized | Status::Unauthorized => {
// if let Some(window) = verification_window.as_ref() {
// if let Some(verification) = window.root(cx) {
// verification.update(cx, |verification, cx| {
// verification.set_status(status, cx);
// cx.platform().activate(true);
// cx.activate_window();
// });
// }
// }
// }
// _ => {
// if let Some(code_verification) = verification_window.take() {
// code_verification.update(cx, |cx| cx.remove_window());
// }
// }
// }
// })
// .detach();
// }
// }
pub struct CopilotCodeVerification {
status: Status,
connect_clicked: bool,
}
// fn create_copilot_auth_window(
// cx: &mut AppContext,
// status: &Status,
// ) -> WindowHandle<CopilotCodeVerification> {
// let window_size = theme::current(cx).copilot.modal.dimensions();
// let window_options = WindowOptions {
// bounds: WindowBounds::Fixed(RectF::new(Default::default(), window_size)),
// titlebar: None,
// center: true,
// focus: true,
// show: true,
// kind: WindowKind::Normal,
// is_movable: true,
// screen: None,
// };
// cx.add_window(window_options, |_cx| {
// CopilotCodeVerification::new(status.clone())
// })
// }
impl CopilotCodeVerification {
pub fn new(status: Status) -> Self {
Self {
status,
connect_clicked: false,
}
}
// pub struct CopilotCodeVerification {
// status: Status,
// connect_clicked: bool,
// }
pub fn set_status(&mut self, status: Status, cx: &mut ViewContext<Self>) {
self.status = status;
cx.notify();
}
// impl CopilotCodeVerification {
// pub fn new(status: Status) -> Self {
// Self {
// status,
// connect_clicked: false,
// }
// }
fn render_device_code(
data: &PromptUserDeviceFlow,
cx: &mut ViewContext<Self>,
) -> impl IntoElement {
let copied = cx
.read_from_clipboard()
.map(|item| item.text() == &data.user_code)
.unwrap_or(false);
h_stack()
.cursor_pointer()
.justify_between()
.on_mouse_down(gpui::MouseButton::Left, {
let user_code = data.user_code.clone();
move |_, cx| {
cx.write_to_clipboard(ClipboardItem::new(user_code.clone()));
cx.notify();
}
})
.child(Label::new(data.user_code.clone()))
.child(div())
.child(Label::new(if copied { "Copied!" } else { "Copy" }))
}
// pub fn set_status(&mut self, status: Status, cx: &mut ViewContext<Self>) {
// self.status = status;
// cx.notify();
// }
fn render_prompting_modal(
connect_clicked: bool,
data: &PromptUserDeviceFlow,
cx: &mut ViewContext<Self>,
) -> impl Element {
let connect_button_label = if connect_clicked {
"Waiting for connection..."
} else {
"Connect to Github"
};
v_stack()
.flex_1()
.items_center()
.justify_between()
.w_full()
.child(Label::new(
"Enable Copilot by connecting your existing license",
))
.child(Self::render_device_code(data, cx))
.child(
Label::new("Paste this code into GitHub after clicking the button below.")
.size(ui::LabelSize::Small),
)
.child(
Button::new("connect-button", connect_button_label).on_click({
let verification_uri = data.verification_uri.clone();
cx.listener(move |this, _, cx| {
cx.open_url(&verification_uri);
this.connect_clicked = true;
})
}),
)
}
fn render_enabled_modal() -> impl Element {
v_stack()
.child(Label::new("Copilot Enabled!"))
.child(Label::new(
"You can update your settings or sign out from the Copilot menu in the status bar.",
))
.child(
Button::new("copilot-enabled-done-button", "Done")
.on_click(|_, cx| cx.remove_window()),
)
}
// fn render_device_code(
// data: &PromptUserDeviceFlow,
// style: &theme::Copilot,
// cx: &mut ViewContext<Self>,
// ) -> impl IntoAnyElement<Self> {
// let copied = cx
// .read_from_clipboard()
// .map(|item| item.text() == &data.user_code)
// .unwrap_or(false);
fn render_unauthorized_modal() -> impl Element {
v_stack()
.child(Label::new(
"Enable Copilot by connecting your existing license.",
))
.child(
Label::new("You must have an active Copilot license to use it in Zed.")
.color(Color::Warning),
)
.child(
Button::new("copilot-subscribe-button", "Subscibe on Github").on_click(|_, cx| {
cx.remove_window();
cx.open_url(COPILOT_SIGN_UP_URL)
}),
)
}
}
// let device_code_style = &style.auth.prompting.device_code;
impl Render for CopilotCodeVerification {
type Element = Stateful<Div>;
// MouseEventHandler::new::<Self, _>(0, cx, |state, _cx| {
// Flex::row()
// .with_child(
// Label::new(data.user_code.clone(), device_code_style.text.clone())
// .aligned()
// .contained()
// .with_style(device_code_style.left_container)
// .constrained()
// .with_width(device_code_style.left),
// )
// .with_child(
// Label::new(
// if copied { "Copied!" } else { "Copy" },
// device_code_style.cta.style_for(state).text.clone(),
// )
// .aligned()
// .contained()
// .with_style(*device_code_style.right_container.style_for(state))
// .constrained()
// .with_width(device_code_style.right),
// )
// .contained()
// .with_style(device_code_style.cta.style_for(state).container)
// })
// .on_click(gpui::platform::MouseButton::Left, {
// let user_code = data.user_code.clone();
// move |_, _, cx| {
// cx.platform()
// .write_to_clipboard(ClipboardItem::new(user_code.clone()));
// cx.notify();
// }
// })
// .with_cursor_style(gpui::platform::CursorStyle::PointingHand)
// }
// fn render_prompting_modal(
// connect_clicked: bool,
// data: &PromptUserDeviceFlow,
// style: &theme::Copilot,
// cx: &mut ViewContext<Self>,
// ) -> AnyElement<Self> {
// enum ConnectButton {}
// Flex::column()
// .with_child(
// Flex::column()
// .with_children([
// Label::new(
// "Enable Copilot by connecting",
// style.auth.prompting.subheading.text.clone(),
// )
// .aligned(),
// Label::new(
// "your existing license.",
// style.auth.prompting.subheading.text.clone(),
// )
// .aligned(),
// ])
// .align_children_center()
// .contained()
// .with_style(style.auth.prompting.subheading.container),
// )
// .with_child(Self::render_device_code(data, &style, cx))
// .with_child(
// Flex::column()
// .with_children([
// Label::new(
// "Paste this code into GitHub after",
// style.auth.prompting.hint.text.clone(),
// )
// .aligned(),
// Label::new(
// "clicking the button below.",
// style.auth.prompting.hint.text.clone(),
// )
// .aligned(),
// ])
// .align_children_center()
// .contained()
// .with_style(style.auth.prompting.hint.container.clone()),
// )
// .with_child(theme::ui::cta_button::<ConnectButton, _, _, _>(
// if connect_clicked {
// "Waiting for connection..."
// } else {
// "Connect to GitHub"
// },
// style.auth.content_width,
// &style.auth.cta_button,
// cx,
// {
// let verification_uri = data.verification_uri.clone();
// move |_, verification, cx| {
// cx.platform().open_url(&verification_uri);
// verification.connect_clicked = true;
// }
// },
// ))
// .align_children_center()
// .into_any()
// }
// fn render_enabled_modal(
// style: &theme::Copilot,
// cx: &mut ViewContext<Self>,
// ) -> AnyElement<Self> {
// enum DoneButton {}
// let enabled_style = &style.auth.authorized;
// Flex::column()
// .with_child(
// Label::new("Copilot Enabled!", enabled_style.subheading.text.clone())
// .contained()
// .with_style(enabled_style.subheading.container)
// .aligned(),
// )
// .with_child(
// Flex::column()
// .with_children([
// Label::new(
// "You can update your settings or",
// enabled_style.hint.text.clone(),
// )
// .aligned(),
// Label::new(
// "sign out from the Copilot menu in",
// enabled_style.hint.text.clone(),
// )
// .aligned(),
// Label::new("the status bar.", enabled_style.hint.text.clone()).aligned(),
// ])
// .align_children_center()
// .contained()
// .with_style(enabled_style.hint.container),
// )
// .with_child(theme::ui::cta_button::<DoneButton, _, _, _>(
// "Done",
// style.auth.content_width,
// &style.auth.cta_button,
// cx,
// |_, _, cx| cx.remove_window(),
// ))
// .align_children_center()
// .into_any()
// }
// fn render_unauthorized_modal(
// style: &theme::Copilot,
// cx: &mut ViewContext<Self>,
// ) -> AnyElement<Self> {
// let unauthorized_style = &style.auth.not_authorized;
// Flex::column()
// .with_child(
// Flex::column()
// .with_children([
// Label::new(
// "Enable Copilot by connecting",
// unauthorized_style.subheading.text.clone(),
// )
// .aligned(),
// Label::new(
// "your existing license.",
// unauthorized_style.subheading.text.clone(),
// )
// .aligned(),
// ])
// .align_children_center()
// .contained()
// .with_style(unauthorized_style.subheading.container),
// )
// .with_child(
// Flex::column()
// .with_children([
// Label::new(
// "You must have an active copilot",
// unauthorized_style.warning.text.clone(),
// )
// .aligned(),
// Label::new(
// "license to use it in Zed.",
// unauthorized_style.warning.text.clone(),
// )
// .aligned(),
// ])
// .align_children_center()
// .contained()
// .with_style(unauthorized_style.warning.container),
// )
// .with_child(theme::ui::cta_button::<Self, _, _, _>(
// "Subscribe on GitHub",
// style.auth.content_width,
// &style.auth.cta_button,
// cx,
// |_, _, cx| {
// cx.remove_window();
// cx.platform().open_url(COPILOT_SIGN_UP_URL)
// },
// ))
// .align_children_center()
// .into_any()
// }
// }
// impl Entity for CopilotCodeVerification {
// type Event = ();
// }
// impl View for CopilotCodeVerification {
// fn ui_name() -> &'static str {
// "CopilotCodeVerification"
// }
// fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
// cx.notify()
// }
// fn focus_out(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
// cx.notify()
// }
// fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
// enum ConnectModal {}
// let style = theme::current(cx).clone();
// modal::<ConnectModal, _, _, _, _>(
// "Connect Copilot to Zed",
// &style.copilot.modal,
// cx,
// |cx| {
// Flex::column()
// .with_children([
// theme::ui::icon(&style.copilot.auth.header).into_any(),
// match &self.status {
// Status::SigningIn {
// prompt: Some(prompt),
// } => Self::render_prompting_modal(
// self.connect_clicked,
// &prompt,
// &style.copilot,
// cx,
// ),
// Status::Unauthorized => {
// self.connect_clicked = false;
// Self::render_unauthorized_modal(&style.copilot, cx)
// }
// Status::Authorized => {
// self.connect_clicked = false;
// Self::render_enabled_modal(&style.copilot, cx)
// }
// _ => Empty::new().into_any(),
// },
// ])
// .align_children_center()
// },
// )
// .into_any()
// }
// }
fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
let prompt = match &self.status {
Status::SigningIn {
prompt: Some(prompt),
} => Self::render_prompting_modal(self.connect_clicked, &prompt, cx).into_any_element(),
Status::Unauthorized => {
self.connect_clicked = false;
Self::render_unauthorized_modal().into_any_element()
}
Status::Authorized => {
self.connect_clicked = false;
Self::render_enabled_modal().into_any_element()
}
_ => div().into_any_element(),
};
div()
.id("copilot code verification")
.flex()
.flex_col()
.size_full()
.items_center()
.p_10()
.bg(cx.theme().colors().element_background)
.child(ui::Label::new("Connect Copilot to Zed"))
.child(IconElement::new(Icon::ZedXCopilot))
.child(prompt)
}
}

View file

@ -2803,35 +2803,46 @@ impl Element for EditorElement {
let focus_handle = editor.focus_handle(cx);
let dispatch_context = self.editor.read(cx).dispatch_context(cx);
cx.with_key_dispatch(dispatch_context, Some(focus_handle.clone()), |_, cx| {
self.register_actions(cx);
self.register_key_listeners(cx);
cx.with_key_dispatch(
Some(dispatch_context),
Some(focus_handle.clone()),
|_, cx| {
self.register_actions(cx);
self.register_key_listeners(cx);
// We call with_z_index to establish a new stacking context.
cx.with_z_index(0, |cx| {
cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
// Paint mouse listeners at z-index 0 so any elements we paint on top of the editor
// take precedence.
cx.with_z_index(0, |cx| {
self.paint_mouse_listeners(bounds, gutter_bounds, text_bounds, &layout, cx);
// We call with_z_index to establish a new stacking context.
cx.with_z_index(0, |cx| {
cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
// Paint mouse listeners at z-index 0 so any elements we paint on top of the editor
// take precedence.
cx.with_z_index(0, |cx| {
self.paint_mouse_listeners(
bounds,
gutter_bounds,
text_bounds,
&layout,
cx,
);
});
let input_handler =
ElementInputHandler::new(bounds, self.editor.clone(), cx);
cx.handle_input(&focus_handle, input_handler);
self.paint_background(gutter_bounds, text_bounds, &layout, cx);
if layout.gutter_size.width > Pixels::ZERO {
self.paint_gutter(gutter_bounds, &mut layout, cx);
}
self.paint_text(text_bounds, &mut layout, cx);
if !layout.blocks.is_empty() {
cx.with_element_id(Some("editor_blocks"), |cx| {
self.paint_blocks(bounds, &mut layout, cx);
})
}
});
let input_handler = ElementInputHandler::new(bounds, self.editor.clone(), cx);
cx.handle_input(&focus_handle, input_handler);
self.paint_background(gutter_bounds, text_bounds, &layout, cx);
if layout.gutter_size.width > Pixels::ZERO {
self.paint_gutter(gutter_bounds, &mut layout, cx);
}
self.paint_text(text_bounds, &mut layout, cx);
if !layout.blocks.is_empty() {
cx.with_element_id(Some("editor_blocks"), |cx| {
self.paint_blocks(bounds, &mut layout, cx);
})
}
});
});
})
},
)
}
}

View file

@ -201,7 +201,7 @@ pub struct AppContext {
pub(crate) windows: SlotMap<WindowId, Option<Window>>,
pub(crate) keymap: Arc<Mutex<Keymap>>,
pub(crate) global_action_listeners:
HashMap<TypeId, Vec<Box<dyn Fn(&dyn Action, DispatchPhase, &mut Self)>>>,
HashMap<TypeId, Vec<Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Self)>>>,
pending_effects: VecDeque<Effect>,
pub(crate) pending_notifications: HashSet<EntityId>,
pub(crate) pending_global_notifications: HashSet<TypeId>,
@ -962,9 +962,9 @@ impl AppContext {
self.global_action_listeners
.entry(TypeId::of::<A>())
.or_default()
.push(Box::new(move |action, phase, cx| {
.push(Rc::new(move |action, phase, cx| {
if phase == DispatchPhase::Bubble {
let action = action.as_any().downcast_ref().unwrap();
let action = action.downcast_ref().unwrap();
listener(action, cx)
}
}));

View file

@ -55,7 +55,7 @@ pub trait InteractiveElement: Sized + Element {
E: Debug,
{
if let Some(key_context) = key_context.try_into().log_err() {
self.interactivity().key_context = key_context;
self.interactivity().key_context = Some(key_context);
}
self
}
@ -722,7 +722,7 @@ impl DivState {
pub struct Interactivity {
pub element_id: Option<ElementId>,
pub key_context: KeyContext,
pub key_context: Option<KeyContext>,
pub focusable: bool,
pub tracked_focus_handle: Option<FocusHandle>,
pub scroll_handle: Option<ScrollHandle>,
@ -1238,7 +1238,7 @@ impl Default for Interactivity {
fn default() -> Self {
Self {
element_id: None,
key_context: KeyContext::default(),
key_context: None,
focusable: false,
tracked_focus_handle: None,
scroll_handle: None,

View file

@ -61,7 +61,7 @@ impl DispatchTree {
self.keystroke_matchers.clear();
}
pub fn push_node(&mut self, context: KeyContext) {
pub fn push_node(&mut self, context: Option<KeyContext>) {
let parent = self.node_stack.last().copied();
let node_id = DispatchNodeId(self.nodes.len());
self.nodes.push(DispatchNode {
@ -69,7 +69,7 @@ impl DispatchTree {
..Default::default()
});
self.node_stack.push(node_id);
if !context.is_empty() {
if let Some(context) = context {
self.active_node().context = context.clone();
self.context_stack.push(context);
}
@ -148,16 +148,14 @@ impl DispatchTree {
false
}
pub fn available_actions(&self, target: FocusId) -> Vec<Box<dyn Action>> {
pub fn available_actions(&self, target: DispatchNodeId) -> Vec<Box<dyn Action>> {
let mut actions = Vec::new();
if let Some(node) = self.focusable_node_ids.get(&target) {
for node_id in self.dispatch_path(*node) {
let node = &self.nodes[node_id.0];
for DispatchActionListener { action_type, .. } in &node.action_listeners {
// Intentionally silence these errors without logging.
// If an action cannot be built by default, it's not available.
actions.extend(self.action_registry.build_action_type(action_type).ok());
}
for node_id in self.dispatch_path(target) {
let node = &self.nodes[node_id.0];
for DispatchActionListener { action_type, .. } in &node.action_listeners {
// Intentionally silence these errors without logging.
// If an action cannot be built by default, it's not available.
actions.extend(self.action_registry.build_action_type(action_type).ok());
}
}
actions
@ -236,6 +234,11 @@ impl DispatchTree {
self.focusable_node_ids.get(&target).copied()
}
pub fn root_node_id(&self) -> DispatchNodeId {
debug_assert!(!self.nodes.is_empty());
DispatchNodeId(0)
}
fn active_node_id(&self) -> DispatchNodeId {
*self.node_stack.last().unwrap()
}

View file

@ -453,19 +453,21 @@ impl<'a> WindowContext<'a> {
}
pub fn dispatch_action(&mut self, action: Box<dyn Action>) {
if let Some(focus_handle) = self.focused() {
self.defer(move |cx| {
if let Some(node_id) = cx
.window
.current_frame
.dispatch_tree
.focusable_node_id(focus_handle.id)
{
cx.propagate_event = true;
cx.dispatch_action_on_node(node_id, action);
}
})
}
let focus_handle = self.focused();
self.defer(move |cx| {
let node_id = focus_handle
.and_then(|handle| {
cx.window
.current_frame
.dispatch_tree
.focusable_node_id(handle.id)
})
.unwrap_or_else(|| cx.window.current_frame.dispatch_tree.root_node_id());
cx.propagate_event = true;
cx.dispatch_action_on_node(node_id, action);
})
}
/// Schedules the given function to be run at the end of the current effect cycle, allowing entities
@ -1154,8 +1156,19 @@ impl<'a> WindowContext<'a> {
self.start_frame();
self.with_z_index(0, |cx| {
let available_space = cx.window.viewport_size.map(Into::into);
root_view.draw(Point::zero(), available_space, cx);
cx.with_key_dispatch(Some(KeyContext::default()), None, |_, cx| {
for (action_type, action_listeners) in &cx.app.global_action_listeners {
for action_listener in action_listeners.iter().cloned() {
cx.window.current_frame.dispatch_tree.on_action(
*action_type,
Rc::new(move |action, phase, cx| action_listener(action, phase, cx)),
)
}
}
let available_space = cx.window.viewport_size.map(Into::into);
root_view.draw(Point::zero(), available_space, cx);
})
});
if let Some(active_drag) = self.app.active_drag.take() {
@ -1338,75 +1351,79 @@ impl<'a> WindowContext<'a> {
}
fn dispatch_key_event(&mut self, event: &dyn Any) {
if let Some(node_id) = self.window.focus.and_then(|focus_id| {
self.window
.current_frame
.dispatch_tree
.focusable_node_id(focus_id)
}) {
let dispatch_path = self
.window
.current_frame
.dispatch_tree
.dispatch_path(node_id);
let node_id = self
.window
.focus
.and_then(|focus_id| {
self.window
.current_frame
.dispatch_tree
.focusable_node_id(focus_id)
})
.unwrap_or_else(|| self.window.current_frame.dispatch_tree.root_node_id());
let mut actions: Vec<Box<dyn Action>> = Vec::new();
let dispatch_path = self
.window
.current_frame
.dispatch_tree
.dispatch_path(node_id);
// Capture phase
let mut context_stack: SmallVec<[KeyContext; 16]> = SmallVec::new();
self.propagate_event = true;
let mut actions: Vec<Box<dyn Action>> = Vec::new();
for node_id in &dispatch_path {
let node = self.window.current_frame.dispatch_tree.node(*node_id);
// Capture phase
let mut context_stack: SmallVec<[KeyContext; 16]> = SmallVec::new();
self.propagate_event = true;
if !node.context.is_empty() {
context_stack.push(node.context.clone());
}
for node_id in &dispatch_path {
let node = self.window.current_frame.dispatch_tree.node(*node_id);
for key_listener in node.key_listeners.clone() {
key_listener(event, DispatchPhase::Capture, self);
if !self.propagate_event {
return;
}
}
if !node.context.is_empty() {
context_stack.push(node.context.clone());
}
// Bubble phase
for node_id in dispatch_path.iter().rev() {
// Handle low level key events
let node = self.window.current_frame.dispatch_tree.node(*node_id);
for key_listener in node.key_listeners.clone() {
key_listener(event, DispatchPhase::Bubble, self);
if !self.propagate_event {
return;
}
}
// Match keystrokes
let node = self.window.current_frame.dispatch_tree.node(*node_id);
if !node.context.is_empty() {
if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
if let Some(found) = self
.window
.current_frame
.dispatch_tree
.dispatch_key(&key_down_event.keystroke, &context_stack)
{
actions.push(found.boxed_clone())
}
}
context_stack.pop();
}
}
for action in actions {
self.dispatch_action_on_node(node_id, action);
for key_listener in node.key_listeners.clone() {
key_listener(event, DispatchPhase::Capture, self);
if !self.propagate_event {
return;
}
}
}
// Bubble phase
for node_id in dispatch_path.iter().rev() {
// Handle low level key events
let node = self.window.current_frame.dispatch_tree.node(*node_id);
for key_listener in node.key_listeners.clone() {
key_listener(event, DispatchPhase::Bubble, self);
if !self.propagate_event {
return;
}
}
// Match keystrokes
let node = self.window.current_frame.dispatch_tree.node(*node_id);
if !node.context.is_empty() {
if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
if let Some(found) = self
.window
.current_frame
.dispatch_tree
.dispatch_key(&key_down_event.keystroke, &context_stack)
{
actions.push(found.boxed_clone())
}
}
context_stack.pop();
}
}
for action in actions {
self.dispatch_action_on_node(node_id, action);
if !self.propagate_event {
return;
}
}
}
fn dispatch_action_on_node(&mut self, node_id: DispatchNodeId, action: Box<dyn Action>) {
@ -1490,14 +1507,21 @@ impl<'a> WindowContext<'a> {
}
pub fn available_actions(&self) -> Vec<Box<dyn Action>> {
if let Some(focus_id) = self.window.focus {
self.window
.current_frame
.dispatch_tree
.available_actions(focus_id)
} else {
Vec::new()
}
let node_id = self
.window
.focus
.and_then(|focus_id| {
self.window
.current_frame
.dispatch_tree
.focusable_node_id(focus_id)
})
.unwrap_or_else(|| self.window.current_frame.dispatch_tree.root_node_id());
self.window
.current_frame
.dispatch_tree
.available_actions(node_id)
}
pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
@ -1553,7 +1577,7 @@ impl<'a> WindowContext<'a> {
//========== ELEMENT RELATED FUNCTIONS ===========
pub fn with_key_dispatch<R>(
&mut self,
context: KeyContext,
context: Option<KeyContext>,
focus_handle: Option<FocusHandle>,
f: impl FnOnce(Option<FocusHandle>, &mut Self) -> R,
) -> R {

View file

@ -92,6 +92,7 @@ pub enum Icon {
Shift,
Option,
Return,
ZedXCopilot,
}
impl Icon {
@ -120,6 +121,7 @@ impl Icon {
Icon::Close => "icons/x.svg",
Icon::Collab => "icons/user_group_16.svg",
Icon::Copilot => "icons/copilot.svg",
Icon::CopilotInit => "icons/copilot_init.svg",
Icon::CopilotError => "icons/copilot_error.svg",
Icon::CopilotDisabled => "icons/copilot_disabled.svg",
@ -166,6 +168,7 @@ impl Icon {
Icon::Shift => "icons/shift.svg",
Icon::Option => "icons/option.svg",
Icon::Return => "icons/return.svg",
Icon::ZedXCopilot => "icons/zed_x_copilot.svg",
}
}
}

View file

@ -101,7 +101,7 @@ pub fn init(cx: &mut AppContext) {
// will be initialized as disabled by default, so we filter its commands
// out when starting up.
cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| {
filter.filtered_namespaces.insert("vim");
filter.hidden_namespaces.insert("vim");
});
cx.update_global(|vim: &mut Vim, cx: &mut AppContext| {
vim.set_enabled(settings::get::<VimModeSetting>(cx).0, cx)
@ -477,9 +477,9 @@ impl Vim {
cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| {
if self.enabled {
filter.filtered_namespaces.remove("vim");
filter.hidden_namespaces.remove("vim");
} else {
filter.filtered_namespaces.insert("vim");
filter.hidden_namespaces.insert("vim");
}
});