1348 lines · 56.4 KB · Rust
RawDownload
use anyhow::Result;use collections::{HashMap, HashSet};use editor::{CompletionProvider, SelectionEffects};use editor::{CurrentLineHighlight, Editor, EditorElement, EditorEvent, EditorStyle, actions::Tab};use gpui::{    Action, App, Bounds, Entity, EventEmitter, Focusable, PromptLevel, Subscription, Task,    TextStyle, TitlebarOptions, WindowBounds, WindowHandle, WindowOptions, actions, point, size,    transparent_black,};use language::{Buffer, LanguageRegistry, language_settings::SoftWrap};use language_model::{    ConfiguredModel, LanguageModelRegistry, LanguageModelRequest, LanguageModelRequestMessage, Role,};use picker::{Picker, PickerDelegate};use release_channel::ReleaseChannel;use rope::Rope;use settings::Settings;use std::rc::Rc;use std::sync::Arc;use std::sync::atomic::AtomicBool;use std::time::Duration;use theme::ThemeSettings;use title_bar::platform_title_bar::PlatformTitleBar;use ui::{    Context, IconButtonShape, KeyBinding, ListItem, ListItemSpacing, ParentElement, Render,    SharedString, Styled, Tooltip, Window, div, prelude::*,};use util::{ResultExt, TryFutureExt};use workspace::{Workspace, client_side_decorations};use zed_actions::assistant::InlineAssist; use prompt_store::*; pub fn init(cx: &mut App) {    prompt_store::init(cx);} actions!(    rules_library,    [        /// Creates a new rule in the rules library.        NewRule,        /// Deletes the selected rule.        DeleteRule,        /// Duplicates the selected rule.        DuplicateRule,        /// Toggles whether the selected rule is a default rule.        ToggleDefaultRule    ]); const BUILT_IN_TOOLTIP_TEXT: &'static str = concat!(    "This rule supports special functionality.\n",    "It's read-only, but you can remove it from your default rules."); pub trait InlineAssistDelegate {    fn assist(        &self,        prompt_editor: &Entity<Editor>,        initial_prompt: Option<String>,        window: &mut Window,        cx: &mut Context<RulesLibrary>,    );     /// Returns whether the Agent panel was focused.    fn focus_agent_panel(        &self,        workspace: &mut Workspace,        window: &mut Window,        cx: &mut Context<Workspace>,    ) -> bool;} /// This function opens a new rules library window if one doesn't exist already./// If one exists, it brings it to the foreground.////// Note that, when opening a new window, this waits for the PromptStore to be/// initialized. If it was initialized successfully, it returns a window handle/// to a rules library.pub fn open_rules_library(    language_registry: Arc<LanguageRegistry>,    inline_assist_delegate: Box<dyn InlineAssistDelegate>,    make_completion_provider: Rc<dyn Fn() -> Rc<dyn CompletionProvider>>,    prompt_to_select: Option<PromptId>,    cx: &mut App,) -> Task<Result<WindowHandle<RulesLibrary>>> {    let store = PromptStore::global(cx);    cx.spawn(async move |cx| {        // We query windows in spawn so that all windows have been returned to GPUI        let existing_window = cx            .update(|cx| {                let existing_window = cx                    .windows()                    .into_iter()                    .find_map(|window| window.downcast::<RulesLibrary>());                if let Some(existing_window) = existing_window {                    existing_window                        .update(cx, |rules_library, window, cx| {                            if let Some(prompt_to_select) = prompt_to_select {                                rules_library.load_rule(prompt_to_select, true, window, cx);                            }                            window.activate_window()                        })                        .ok();                     Some(existing_window)                } else {                    None                }            })            .ok()            .flatten();         if let Some(existing_window) = existing_window {            return Ok(existing_window);        }         let store = store.await?;        cx.update(|cx| {            let app_id = ReleaseChannel::global(cx).app_id();            let bounds = Bounds::centered(None, size(px(1024.0), px(768.0)), cx);            let window_decorations = match std::env::var("ZED_WINDOW_DECORATIONS") {                Ok(val) if val == "server" => gpui::WindowDecorations::Server,                Ok(val) if val == "client" => gpui::WindowDecorations::Client,                _ => gpui::WindowDecorations::Client,            };            cx.open_window(                WindowOptions {                    titlebar: Some(TitlebarOptions {                        title: Some("Rules Library".into()),                        appears_transparent: true,                        traffic_light_position: Some(point(px(9.0), px(9.0))),                    }),                    app_id: Some(app_id.to_owned()),                    window_bounds: Some(WindowBounds::Windowed(bounds)),                    window_background: cx.theme().window_background_appearance(),                    window_decorations: Some(window_decorations),                    ..Default::default()                },                |window, cx| {                    cx.new(|cx| {                        RulesLibrary::new(                            store,                            language_registry,                            inline_assist_delegate,                            make_completion_provider,                            prompt_to_select,                            window,                            cx,                        )                    })                },            )        })?    })} pub struct RulesLibrary {    title_bar: Option<Entity<PlatformTitleBar>>,    store: Entity<PromptStore>,    language_registry: Arc<LanguageRegistry>,    rule_editors: HashMap<PromptId, RuleEditor>,    active_rule_id: Option<PromptId>,    picker: Entity<Picker<RulePickerDelegate>>,    pending_load: Task<()>,    inline_assist_delegate: Box<dyn InlineAssistDelegate>,    make_completion_provider: Rc<dyn Fn() -> Rc<dyn CompletionProvider>>,    _subscriptions: Vec<Subscription>,} struct RuleEditor {    title_editor: Entity<Editor>,    body_editor: Entity<Editor>,    token_count: Option<u64>,    pending_token_count: Task<Option<()>>,    next_title_and_body_to_save: Option<(String, Rope)>,    pending_save: Option<Task<Option<()>>>,    _subscriptions: Vec<Subscription>,} struct RulePickerDelegate {    store: Entity<PromptStore>,    selected_index: usize,    matches: Vec<PromptMetadata>,} enum RulePickerEvent {    Selected { prompt_id: PromptId },    Confirmed { prompt_id: PromptId },    Deleted { prompt_id: PromptId },    ToggledDefault { prompt_id: PromptId },} impl EventEmitter<RulePickerEvent> for Picker<RulePickerDelegate> {} impl PickerDelegate for RulePickerDelegate {    type ListItem = ListItem;     fn match_count(&self) -> usize {        self.matches.len()    }     fn no_matches_text(&self, _window: &mut Window, cx: &mut App) -> Option<SharedString> {        let text = if self.store.read(cx).prompt_count() == 0 {            "No rules.".into()        } else {            "No rules found matching your search.".into()        };        Some(text)    }     fn selected_index(&self) -> usize {        self.selected_index    }     fn set_selected_index(&mut self, ix: usize, _: &mut Window, cx: &mut Context<Picker<Self>>) {        self.selected_index = ix;        if let Some(prompt) = self.matches.get(self.selected_index) {            cx.emit(RulePickerEvent::Selected {                prompt_id: prompt.id,            });        }    }     fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {        "Search...".into()    }     fn update_matches(        &mut self,        query: String,        window: &mut Window,        cx: &mut Context<Picker<Self>>,    ) -> Task<()> {        let cancellation_flag = Arc::new(AtomicBool::default());        let search = self.store.read(cx).search(query, cancellation_flag, cx);        let prev_prompt_id = self.matches.get(self.selected_index).map(|mat| mat.id);        cx.spawn_in(window, async move |this, cx| {            let (matches, selected_index) = cx                .background_spawn(async move {                    let matches = search.await;                     let selected_index = prev_prompt_id                        .and_then(|prev_prompt_id| {                            matches.iter().position(|entry| entry.id == prev_prompt_id)                        })                        .unwrap_or(0);                    (matches, selected_index)                })                .await;             this.update_in(cx, |this, window, cx| {                this.delegate.matches = matches;                this.delegate.set_selected_index(selected_index, window, cx);                cx.notify();            })            .ok();        })    }     fn confirm(&mut self, _secondary: bool, _: &mut Window, cx: &mut Context<Picker<Self>>) {        if let Some(prompt) = self.matches.get(self.selected_index) {            cx.emit(RulePickerEvent::Confirmed {                prompt_id: prompt.id,            });        }    }     fn dismissed(&mut self, _window: &mut Window, _cx: &mut Context<Picker<Self>>) {}     fn render_match(        &self,        ix: usize,        selected: bool,        _: &mut Window,        cx: &mut Context<Picker<Self>>,    ) -> Option<Self::ListItem> {        let rule = self.matches.get(ix)?;        let default = rule.default;        let prompt_id = rule.id;         let element = ListItem::new(ix)            .inset(true)            .spacing(ListItemSpacing::Sparse)            .toggle_state(selected)            .child(                h_flex()                    .h_5()                    .line_height(relative(1.))                    .child(Label::new(rule.title.clone().unwrap_or("Untitled".into()))),            )            .end_slot::<IconButton>(default.then(|| {                IconButton::new("toggle-default-rule", IconName::StarFilled)                    .toggle_state(true)                    .icon_color(Color::Accent)                    .icon_size(IconSize::Small)                    .shape(IconButtonShape::Square)                    .tooltip(Tooltip::text("Remove from Default Rules"))                    .on_click(cx.listener(move |_, _, _, cx| {                        cx.emit(RulePickerEvent::ToggledDefault { prompt_id })                    }))            }))            .end_hover_slot(                h_flex()                    .gap_1()                    .child(if prompt_id.is_built_in() {                        div()                            .id("built-in-rule")                            .child(Icon::new(IconName::FileLock).color(Color::Muted))                            .tooltip(move |window, cx| {                                Tooltip::with_meta(                                    "Built-in rule",                                    None,                                    BUILT_IN_TOOLTIP_TEXT,                                    window,                                    cx,                                )                            })                            .into_any()                    } else {                        IconButton::new("delete-rule", IconName::TrashAlt)                            .icon_color(Color::Muted)                            .icon_size(IconSize::Small)                            .shape(IconButtonShape::Square)                            .tooltip(Tooltip::text("Delete Rule"))                            .on_click(cx.listener(move |_, _, _, cx| {                                cx.emit(RulePickerEvent::Deleted { prompt_id })                            }))                            .into_any_element()                    })                    .child(                        IconButton::new("toggle-default-rule", IconName::Star)                            .toggle_state(default)                            .selected_icon(IconName::StarFilled)                            .icon_color(if default { Color::Accent } else { Color::Muted })                            .icon_size(IconSize::Small)                            .shape(IconButtonShape::Square)                            .map(|this| {                                if default {                                    this.tooltip(Tooltip::text("Remove from Default Rules"))                                } else {                                    this.tooltip(move |window, cx| {                                        Tooltip::with_meta(                                            "Add to Default Rules",                                            None,                                            "Always included in every thread.",                                            window,                                            cx,                                        )                                    })                                }                            })                            .on_click(cx.listener(move |_, _, _, cx| {                                cx.emit(RulePickerEvent::ToggledDefault { prompt_id })                            })),                    ),            );        Some(element)    }     fn render_editor(        &self,        editor: &Entity<Editor>,        _: &mut Window,        cx: &mut Context<Picker<Self>>,    ) -> Div {        h_flex()            .bg(cx.theme().colors().editor_background)            .rounded_sm()            .overflow_hidden()            .flex_none()            .py_1()            .px_2()            .mx_1()            .child(editor.clone())    }} impl RulesLibrary {    fn new(        store: Entity<PromptStore>,        language_registry: Arc<LanguageRegistry>,        inline_assist_delegate: Box<dyn InlineAssistDelegate>,        make_completion_provider: Rc<dyn Fn() -> Rc<dyn CompletionProvider>>,        rule_to_select: Option<PromptId>,        window: &mut Window,        cx: &mut Context<Self>,    ) -> Self {        let (selected_index, matches) = if let Some(rule_to_select) = rule_to_select {            let matches = store.read(cx).all_prompt_metadata();            let selected_index = matches                .iter()                .enumerate()                .find(|(_, metadata)| metadata.id == rule_to_select)                .map_or(0, |(ix, _)| ix);            (selected_index, matches)        } else {            (0, vec![])        };         let delegate = RulePickerDelegate {            store: store.clone(),            selected_index,            matches,        };         let picker = cx.new(|cx| {            let picker = Picker::uniform_list(delegate, window, cx)                .modal(false)                .max_height(None);            picker.focus(window, cx);            picker        });        Self {            title_bar: if !cfg!(target_os = "macos") {                Some(cx.new(|_| PlatformTitleBar::new("rules-library-title-bar")))            } else {                None            },            store: store.clone(),            language_registry,            rule_editors: HashMap::default(),            active_rule_id: None,            pending_load: Task::ready(()),            inline_assist_delegate,            make_completion_provider,            _subscriptions: vec![cx.subscribe_in(&picker, window, Self::handle_picker_event)],            picker,        }    }     fn handle_picker_event(        &mut self,        _: &Entity<Picker<RulePickerDelegate>>,        event: &RulePickerEvent,        window: &mut Window,        cx: &mut Context<Self>,    ) {        match event {            RulePickerEvent::Selected { prompt_id } => {                self.load_rule(*prompt_id, false, window, cx);            }            RulePickerEvent::Confirmed { prompt_id } => {                self.load_rule(*prompt_id, true, window, cx);            }            RulePickerEvent::ToggledDefault { prompt_id } => {                self.toggle_default_for_rule(*prompt_id, window, cx);            }            RulePickerEvent::Deleted { prompt_id } => {                self.delete_rule(*prompt_id, window, cx);            }        }    }     pub fn new_rule(&mut self, window: &mut Window, cx: &mut Context<Self>) {        // If we already have an untitled rule, use that instead        // of creating a new one.        if let Some(metadata) = self.store.read(cx).first() {            if metadata.title.is_none() {                self.load_rule(metadata.id, true, window, cx);                return;            }        }         let prompt_id = PromptId::new();        let save = self.store.update(cx, |store, cx| {            store.save(prompt_id, None, false, "".into(), cx)        });        self.picker            .update(cx, |picker, cx| picker.refresh(window, cx));        cx.spawn_in(window, async move |this, cx| {            save.await?;            this.update_in(cx, |this, window, cx| {                this.load_rule(prompt_id, true, window, cx)            })        })        .detach_and_log_err(cx);    }     pub fn save_rule(&mut self, prompt_id: PromptId, window: &mut Window, cx: &mut Context<Self>) {        const SAVE_THROTTLE: Duration = Duration::from_millis(500);         if prompt_id.is_built_in() {            return;        }         let rule_metadata = self.store.read(cx).metadata(prompt_id).unwrap();        let rule_editor = self.rule_editors.get_mut(&prompt_id).unwrap();        let title = rule_editor.title_editor.read(cx).text(cx);        let body = rule_editor.body_editor.update(cx, |editor, cx| {            editor                .buffer()                .read(cx)                .as_singleton()                .unwrap()                .read(cx)                .as_rope()                .clone()        });

Lines 1–500 of 1348.