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

@ -62,7 +62,7 @@ jobs:
runs-on: runs-on:
- self-hosted - self-hosted
- bundle - bundle
if: ${{ github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v') || contains(github.event.pull_request.labels.*.name, 'run-build-dmg') }} if: ${{ startsWith(github.ref, 'refs/tags/v') || contains(github.event.pull_request.labels.*.name, 'run-build-dmg') }}
needs: tests needs: tests
env: env:
MACOS_CERTIFICATE: ${{ secrets.MACOS_CERTIFICATE }} MACOS_CERTIFICATE: ${{ secrets.MACOS_CERTIFICATE }}

1
Cargo.lock generated
View file

@ -2118,6 +2118,7 @@ dependencies = [
"settings2", "settings2",
"smol", "smol",
"theme2", "theme2",
"ui2",
"util", "util",
] ]

View file

@ -23,11 +23,13 @@ pub type HashMap<K, V> = std::collections::HashMap<K, V>;
#[cfg(not(feature = "test-support"))] #[cfg(not(feature = "test-support"))]
pub type HashSet<T> = std::collections::HashSet<T>; pub type HashSet<T> = std::collections::HashSet<T>;
use std::any::TypeId;
pub use std::collections::*; pub use std::collections::*;
// NEW TYPES // NEW TYPES
#[derive(Default)] #[derive(Default)]
pub struct CommandPaletteFilter { 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| { let filtered = cx.read(|cx| {
if cx.has_global::<CommandPaletteFilter>() { if cx.has_global::<CommandPaletteFilter>() {
let filter = cx.global::<CommandPaletteFilter>(); let filter = cx.global::<CommandPaletteFilter>();
filter.filtered_namespaces.contains(action.namespace()) filter.hidden_namespaces.contains(action.namespace())
} else { } else {
false false
} }
@ -430,7 +430,7 @@ mod tests {
// Add namespace filter, and redeploy the palette // Add namespace filter, and redeploy the palette
cx.update(|cx| { cx.update(|cx| {
cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| { 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| { .filter_map(|action| {
let name = gpui::remove_the_2(action.name()); let name = gpui::remove_the_2(action.name());
let namespace = name.split("::").next().unwrap_or("malformed 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; return None;
} }
@ -433,7 +436,7 @@ mod tests {
cx.update(|cx| { cx.update(|cx| {
cx.set_global(CommandPaletteFilter::default()); cx.set_global(CommandPaletteFilter::default());
cx.update_global::<CommandPaletteFilter, _>(|filter, _| { 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| { cx.update_default_global::<collections::CommandPaletteFilter, _, _>(move |filter, _cx| {
match status { match status {
Status::Disabled => { Status::Disabled => {
filter.filtered_namespaces.insert(COPILOT_NAMESPACE); filter.hidden_namespaces.insert(COPILOT_NAMESPACE);
filter.filtered_namespaces.insert(COPILOT_AUTH_NAMESPACE); filter.hidden_namespaces.insert(COPILOT_AUTH_NAMESPACE);
} }
Status::Authorized => { Status::Authorized => {
filter.filtered_namespaces.remove(COPILOT_NAMESPACE); filter.hidden_namespaces.remove(COPILOT_NAMESPACE);
filter.filtered_namespaces.remove(COPILOT_AUTH_NAMESPACE); filter.hidden_namespaces.remove(COPILOT_AUTH_NAMESPACE);
} }
_ => { _ => {
filter.filtered_namespaces.insert(COPILOT_NAMESPACE); filter.hidden_namespaces.insert(COPILOT_NAMESPACE);
filter.filtered_namespaces.remove(COPILOT_AUTH_NAMESPACE); filter.hidden_namespaces.remove(COPILOT_AUTH_NAMESPACE);
} }
} }
}); });

View file

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

View file

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

View file

@ -1,376 +1,213 @@
// TODO add logging in use crate::{request::PromptUserDeviceFlow, Copilot, Status};
// use crate::{request::PromptUserDeviceFlow, Copilot, Status}; use gpui::{
// use gpui::{ div, size, AppContext, Bounds, ClipboardItem, Div, Element, GlobalPixels, InteractiveElement,
// elements::*, IntoElement, ParentElement, Point, Render, Stateful, Styled, ViewContext, VisualContext,
// geometry::rect::RectF, WindowBounds, WindowHandle, WindowKind, WindowOptions,
// platform::{WindowBounds, WindowKind, WindowOptions}, };
// AnyElement, AnyViewHandle, AppContext, ClipboardItem, Element, Entity, View, ViewContext, use theme::ActiveTheme;
// WindowHandle, use ui::{h_stack, v_stack, Button, Clickable, Color, Icon, IconElement, Label};
// };
// use theme::ui::modal;
// #[derive(PartialEq, Eq, Debug, Clone)] const COPILOT_SIGN_UP_URL: &'static str = "https://github.com/features/copilot";
// struct CopyUserCode;
// #[derive(PartialEq, Eq, Debug, Clone)] pub fn init(cx: &mut AppContext) {
// struct OpenGithub; 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) { fn create_copilot_auth_window(
// if let Some(copilot) = Copilot::global(cx) { cx: &mut AppContext,
// let mut verification_window: Option<WindowHandle<CopilotCodeVerification>> = None; status: &Status,
// cx.observe(&copilot, move |copilot, cx| { ) -> WindowHandle<CopilotCodeVerification> {
// let status = copilot.read(cx).status(); 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 { pub struct CopilotCodeVerification {
// crate::Status::SigningIn { prompt } => { status: Status,
// if let Some(window) = verification_window.as_mut() { connect_clicked: bool,
// 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();
// }
// }
// fn create_copilot_auth_window( impl CopilotCodeVerification {
// cx: &mut AppContext, pub fn new(status: Status) -> Self {
// status: &Status, Self {
// ) -> WindowHandle<CopilotCodeVerification> { status,
// let window_size = theme::current(cx).copilot.modal.dimensions(); connect_clicked: false,
// 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())
// })
// }
// pub struct CopilotCodeVerification { pub fn set_status(&mut self, status: Status, cx: &mut ViewContext<Self>) {
// status: Status, self.status = status;
// connect_clicked: bool, cx.notify();
// } }
// impl CopilotCodeVerification { fn render_device_code(
// pub fn new(status: Status) -> Self { data: &PromptUserDeviceFlow,
// Self { cx: &mut ViewContext<Self>,
// status, ) -> impl IntoElement {
// connect_clicked: false, 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>) { fn render_prompting_modal(
// self.status = status; connect_clicked: bool,
// cx.notify(); 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( fn render_unauthorized_modal() -> impl Element {
// data: &PromptUserDeviceFlow, v_stack()
// style: &theme::Copilot, .child(Label::new(
// cx: &mut ViewContext<Self>, "Enable Copilot by connecting your existing license.",
// ) -> impl IntoAnyElement<Self> { ))
// let copied = cx .child(
// .read_from_clipboard() Label::new("You must have an active Copilot license to use it in Zed.")
// .map(|item| item.text() == &data.user_code) .color(Color::Warning),
// .unwrap_or(false); )
.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| { fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
// Flex::row() let prompt = match &self.status {
// .with_child( Status::SigningIn {
// Label::new(data.user_code.clone(), device_code_style.text.clone()) prompt: Some(prompt),
// .aligned() } => Self::render_prompting_modal(self.connect_clicked, &prompt, cx).into_any_element(),
// .contained() Status::Unauthorized => {
// .with_style(device_code_style.left_container) self.connect_clicked = false;
// .constrained() Self::render_unauthorized_modal().into_any_element()
// .with_width(device_code_style.left), }
// ) Status::Authorized => {
// .with_child( self.connect_clicked = false;
// Label::new( Self::render_enabled_modal().into_any_element()
// if copied { "Copied!" } else { "Copy" }, }
// device_code_style.cta.style_for(state).text.clone(), _ => div().into_any_element(),
// ) };
// .aligned() div()
// .contained() .id("copilot code verification")
// .with_style(*device_code_style.right_container.style_for(state)) .flex()
// .constrained() .flex_col()
// .with_width(device_code_style.right), .size_full()
// ) .items_center()
// .contained() .p_10()
// .with_style(device_code_style.cta.style_for(state).container) .bg(cx.theme().colors().element_background)
// }) .child(ui::Label::new("Connect Copilot to Zed"))
// .on_click(gpui::platform::MouseButton::Left, { .child(IconElement::new(Icon::ZedXCopilot))
// let user_code = data.user_code.clone(); .child(prompt)
// 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()
// }
// }

View file

@ -2803,7 +2803,10 @@ impl Element for EditorElement {
let focus_handle = editor.focus_handle(cx); let focus_handle = editor.focus_handle(cx);
let dispatch_context = self.editor.read(cx).dispatch_context(cx); let dispatch_context = self.editor.read(cx).dispatch_context(cx);
cx.with_key_dispatch(dispatch_context, Some(focus_handle.clone()), |_, cx| { cx.with_key_dispatch(
Some(dispatch_context),
Some(focus_handle.clone()),
|_, cx| {
self.register_actions(cx); self.register_actions(cx);
self.register_key_listeners(cx); self.register_key_listeners(cx);
@ -2813,9 +2816,16 @@ impl Element for EditorElement {
// Paint mouse listeners at z-index 0 so any elements we paint on top of the editor // Paint mouse listeners at z-index 0 so any elements we paint on top of the editor
// take precedence. // take precedence.
cx.with_z_index(0, |cx| { cx.with_z_index(0, |cx| {
self.paint_mouse_listeners(bounds, gutter_bounds, text_bounds, &layout, cx); self.paint_mouse_listeners(
bounds,
gutter_bounds,
text_bounds,
&layout,
cx,
);
}); });
let input_handler = ElementInputHandler::new(bounds, self.editor.clone(), cx); let input_handler =
ElementInputHandler::new(bounds, self.editor.clone(), cx);
cx.handle_input(&focus_handle, input_handler); cx.handle_input(&focus_handle, input_handler);
self.paint_background(gutter_bounds, text_bounds, &layout, cx); self.paint_background(gutter_bounds, text_bounds, &layout, cx);
@ -2831,7 +2841,8 @@ impl Element for EditorElement {
} }
}); });
}); });
}) },
)
} }
} }

View file

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

View file

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

View file

@ -61,7 +61,7 @@ impl DispatchTree {
self.keystroke_matchers.clear(); 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 parent = self.node_stack.last().copied();
let node_id = DispatchNodeId(self.nodes.len()); let node_id = DispatchNodeId(self.nodes.len());
self.nodes.push(DispatchNode { self.nodes.push(DispatchNode {
@ -69,7 +69,7 @@ impl DispatchTree {
..Default::default() ..Default::default()
}); });
self.node_stack.push(node_id); self.node_stack.push(node_id);
if !context.is_empty() { if let Some(context) = context {
self.active_node().context = context.clone(); self.active_node().context = context.clone();
self.context_stack.push(context); self.context_stack.push(context);
} }
@ -148,10 +148,9 @@ impl DispatchTree {
false 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(); let mut actions = Vec::new();
if let Some(node) = self.focusable_node_ids.get(&target) { for node_id in self.dispatch_path(target) {
for node_id in self.dispatch_path(*node) {
let node = &self.nodes[node_id.0]; let node = &self.nodes[node_id.0];
for DispatchActionListener { action_type, .. } in &node.action_listeners { for DispatchActionListener { action_type, .. } in &node.action_listeners {
// Intentionally silence these errors without logging. // Intentionally silence these errors without logging.
@ -159,7 +158,6 @@ impl DispatchTree {
actions.extend(self.action_registry.build_action_type(action_type).ok()); actions.extend(self.action_registry.build_action_type(action_type).ok());
} }
} }
}
actions actions
} }
@ -236,6 +234,11 @@ impl DispatchTree {
self.focusable_node_ids.get(&target).copied() 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 { fn active_node_id(&self) -> DispatchNodeId {
*self.node_stack.last().unwrap() *self.node_stack.last().unwrap()
} }

View file

@ -453,20 +453,22 @@ impl<'a> WindowContext<'a> {
} }
pub fn dispatch_action(&mut self, action: Box<dyn Action>) { pub fn dispatch_action(&mut self, action: Box<dyn Action>) {
if let Some(focus_handle) = self.focused() { let focus_handle = self.focused();
self.defer(move |cx| { self.defer(move |cx| {
if let Some(node_id) = cx let node_id = focus_handle
.window .and_then(|handle| {
cx.window
.current_frame .current_frame
.dispatch_tree .dispatch_tree
.focusable_node_id(focus_handle.id) .focusable_node_id(handle.id)
{ })
.unwrap_or_else(|| cx.window.current_frame.dispatch_tree.root_node_id());
cx.propagate_event = true; cx.propagate_event = true;
cx.dispatch_action_on_node(node_id, action); 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 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
/// that are currently on the stack to be returned to the app. /// that are currently on the stack to be returned to the app.
@ -1154,8 +1156,19 @@ impl<'a> WindowContext<'a> {
self.start_frame(); self.start_frame();
self.with_z_index(0, |cx| { self.with_z_index(0, |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); let available_space = cx.window.viewport_size.map(Into::into);
root_view.draw(Point::zero(), available_space, cx); root_view.draw(Point::zero(), available_space, cx);
})
}); });
if let Some(active_drag) = self.app.active_drag.take() { if let Some(active_drag) = self.app.active_drag.take() {
@ -1338,12 +1351,17 @@ impl<'a> WindowContext<'a> {
} }
fn dispatch_key_event(&mut self, event: &dyn Any) { fn dispatch_key_event(&mut self, event: &dyn Any) {
if let Some(node_id) = self.window.focus.and_then(|focus_id| { let node_id = self
.window
.focus
.and_then(|focus_id| {
self.window self.window
.current_frame .current_frame
.dispatch_tree .dispatch_tree
.focusable_node_id(focus_id) .focusable_node_id(focus_id)
}) { })
.unwrap_or_else(|| self.window.current_frame.dispatch_tree.root_node_id());
let dispatch_path = self let dispatch_path = self
.window .window
.current_frame .current_frame
@ -1407,7 +1425,6 @@ impl<'a> WindowContext<'a> {
} }
} }
} }
}
fn dispatch_action_on_node(&mut self, node_id: DispatchNodeId, action: Box<dyn Action>) { fn dispatch_action_on_node(&mut self, node_id: DispatchNodeId, action: Box<dyn Action>) {
let dispatch_path = self let dispatch_path = self
@ -1490,14 +1507,21 @@ impl<'a> WindowContext<'a> {
} }
pub fn available_actions(&self) -> Vec<Box<dyn Action>> { pub fn available_actions(&self) -> Vec<Box<dyn Action>> {
if let Some(focus_id) = self.window.focus { let node_id = self
.window
.focus
.and_then(|focus_id| {
self.window self.window
.current_frame .current_frame
.dispatch_tree .dispatch_tree
.available_actions(focus_id) .focusable_node_id(focus_id)
} else { })
Vec::new() .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> { pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
@ -1553,7 +1577,7 @@ impl<'a> WindowContext<'a> {
//========== ELEMENT RELATED FUNCTIONS =========== //========== ELEMENT RELATED FUNCTIONS ===========
pub fn with_key_dispatch<R>( pub fn with_key_dispatch<R>(
&mut self, &mut self,
context: KeyContext, context: Option<KeyContext>,
focus_handle: Option<FocusHandle>, focus_handle: Option<FocusHandle>,
f: impl FnOnce(Option<FocusHandle>, &mut Self) -> R, f: impl FnOnce(Option<FocusHandle>, &mut Self) -> R,
) -> R { ) -> R {

View file

@ -92,6 +92,7 @@ pub enum Icon {
Shift, Shift,
Option, Option,
Return, Return,
ZedXCopilot,
} }
impl Icon { impl Icon {
@ -120,6 +121,7 @@ impl Icon {
Icon::Close => "icons/x.svg", Icon::Close => "icons/x.svg",
Icon::Collab => "icons/user_group_16.svg", Icon::Collab => "icons/user_group_16.svg",
Icon::Copilot => "icons/copilot.svg", Icon::Copilot => "icons/copilot.svg",
Icon::CopilotInit => "icons/copilot_init.svg", Icon::CopilotInit => "icons/copilot_init.svg",
Icon::CopilotError => "icons/copilot_error.svg", Icon::CopilotError => "icons/copilot_error.svg",
Icon::CopilotDisabled => "icons/copilot_disabled.svg", Icon::CopilotDisabled => "icons/copilot_disabled.svg",
@ -166,6 +168,7 @@ impl Icon {
Icon::Shift => "icons/shift.svg", Icon::Shift => "icons/shift.svg",
Icon::Option => "icons/option.svg", Icon::Option => "icons/option.svg",
Icon::Return => "icons/return.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 // will be initialized as disabled by default, so we filter its commands
// out when starting up. // out when starting up.
cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| { 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| { cx.update_global(|vim: &mut Vim, cx: &mut AppContext| {
vim.set_enabled(settings::get::<VimModeSetting>(cx).0, cx) vim.set_enabled(settings::get::<VimModeSetting>(cx).0, cx)
@ -477,9 +477,9 @@ impl Vim {
cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| { cx.update_default_global::<CommandPaletteFilter, _, _>(|filter, _| {
if self.enabled { if self.enabled {
filter.filtered_namespaces.remove("vim"); filter.hidden_namespaces.remove("vim");
} else { } else {
filter.filtered_namespaces.insert("vim"); filter.hidden_namespaces.insert("vim");
} }
}); });