Merge branch 'main' into search2

This commit is contained in:
Piotr Osiewicz 2023-11-17 13:22:30 +01:00
commit dca2dc7b6b
88 changed files with 2880 additions and 1797 deletions

32
Cargo.lock generated
View File

@ -3797,6 +3797,7 @@ dependencies = [
"image", "image",
"itertools 0.10.5", "itertools 0.10.5",
"lazy_static", "lazy_static",
"linkme",
"log", "log",
"media", "media",
"metal", "metal",
@ -4815,6 +4816,26 @@ version = "0.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f"
[[package]]
name = "linkme"
version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91ed2ee9464ff9707af8e9ad834cffa4802f072caad90639c583dd3c62e6e608"
dependencies = [
"linkme-impl",
]
[[package]]
name = "linkme-impl"
version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba125974b109d512fccbc6c0244e7580143e460895dfd6ea7f8bbb692fd94396"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.37",
]
[[package]] [[package]]
name = "linux-raw-sys" name = "linux-raw-sys"
version = "0.0.42" version = "0.0.42"
@ -8831,6 +8852,17 @@ dependencies = [
"util", "util",
] ]
[[package]]
name = "storybook3"
version = "0.1.0"
dependencies = [
"anyhow",
"gpui2",
"settings2",
"theme2",
"ui2",
]
[[package]] [[package]]
name = "stringprep" name = "stringprep"
version = "0.1.4" version = "0.1.4"

View File

@ -96,6 +96,7 @@ members = [
"crates/sqlez_macros", "crates/sqlez_macros",
"crates/rich_text", "crates/rich_text",
"crates/storybook2", "crates/storybook2",
"crates/storybook3",
"crates/sum_tree", "crates/sum_tree",
"crates/terminal", "crates/terminal",
"crates/terminal2", "crates/terminal2",

View File

@ -35,6 +35,15 @@
// "custom": 2 // "custom": 2
// }, // },
"buffer_line_height": "comfortable", "buffer_line_height": "comfortable",
// The name of a font to use for rendering text in the UI
"ui_font_family": "Zed Mono",
// The OpenType features to enable for text in the UI
"ui_font_features": {
// Disable ligatures:
"calt": false
},
// The default font size for text in the UI
"ui_font_size": 14,
// The factor to grow the active pane by. Defaults to 1.0 // The factor to grow the active pane by. Defaults to 1.0
// which gives the same size as all other panes. // which gives the same size as all other panes.
"active_pane_magnification": 1.0, "active_pane_magnification": 1.0,

View File

@ -224,7 +224,7 @@ impl TestServer {
}); });
cx.update(|cx| { cx.update(|cx| {
theme::init(cx); theme::init(theme::LoadThemes::JustBase, cx);
Project::init(&client, cx); Project::init(&client, cx);
client::init(&client, cx); client::init(&client, cx);
language::init(cx); language::init(cx);

View File

@ -684,6 +684,7 @@ impl CollabPanel {
if let Some(serialized_panel) = serialized_panel { if let Some(serialized_panel) = serialized_panel {
panel.update(cx, |panel, cx| { panel.update(cx, |panel, cx| {
panel.width = serialized_panel.width; panel.width = serialized_panel.width;
//todo!(collapsed_channels)
// panel.collapsed_channels = serialized_panel // panel.collapsed_channels = serialized_panel
// .collapsed_channels // .collapsed_channels
// .unwrap_or_else(|| Vec::new()); // .unwrap_or_else(|| Vec::new());

View File

@ -31,9 +31,9 @@ use std::sync::Arc;
use call::ActiveCall; use call::ActiveCall;
use client::{Client, UserStore}; use client::{Client, UserStore};
use gpui::{ use gpui::{
div, rems, AppContext, Component, Div, InteractiveComponent, Model, ParentComponent, Render, div, px, rems, AppContext, Component, Div, InteractiveComponent, Model, ParentComponent,
Stateful, StatefulInteractiveComponent, Styled, Subscription, ViewContext, VisualContext, Render, Stateful, StatefulInteractiveComponent, Styled, Subscription, ViewContext,
WeakView, WindowBounds, VisualContext, WeakView, WindowBounds,
}; };
use project::Project; use project::Project;
use theme::ActiveTheme; use theme::ActiveTheme;
@ -88,12 +88,17 @@ impl Render for CollabTitlebarItem {
h_stack() h_stack()
.id("titlebar") .id("titlebar")
.justify_between() .justify_between()
.when(
!matches!(cx.window_bounds(), WindowBounds::Fullscreen),
|s| s.pl_20(),
)
.w_full() .w_full()
.h(rems(1.75)) .h(rems(1.75))
// Set a non-scaling min-height here to ensure the titlebar is
// always at least the height of the traffic lights.
.min_h(px(32.))
.when(
!matches!(cx.window_bounds(), WindowBounds::Fullscreen),
// Use pixels here instead of a rem-based size because the macOS traffic
// lights are a static size, and don't scale with the rest of the UI.
|s| s.pl(px(68.)),
)
.bg(cx.theme().colors().title_bar_background) .bg(cx.theme().colors().title_bar_background)
.on_click(|_, event, cx| { .on_click(|_, event, cx| {
if event.up.click_count == 2 { if event.up.click_count == 2 {
@ -102,6 +107,7 @@ impl Render for CollabTitlebarItem {
}) })
.child( .child(
h_stack() h_stack()
.gap_1()
// TODO - Add player menu // TODO - Add player menu
.child( .child(
div() div()
@ -130,14 +136,12 @@ impl Render for CollabTitlebarItem {
.color(Some(TextColor::Muted)), .color(Some(TextColor::Muted)),
) )
.tooltip(move |_, cx| { .tooltip(move |_, cx| {
// todo!() Replace with real action.
#[gpui::action]
struct NoAction {}
cx.build_view(|_| { cx.build_view(|_| {
Tooltip::new("Recent Branches") Tooltip::new("Recent Branches")
.key_binding(KeyBinding::new(gpui::KeyBinding::new( .key_binding(KeyBinding::new(gpui::KeyBinding::new(
"cmd-b", "cmd-b",
NoAction {}, // todo!() Replace with real action.
gpui::NoAction,
None, None,
))) )))
.meta("Only local branches shown") .meta("Only local branches shown")

View File

@ -1,9 +1,8 @@
use collections::{CommandPaletteFilter, HashMap}; use collections::{CommandPaletteFilter, HashMap};
use fuzzy::{StringMatch, StringMatchCandidate}; use fuzzy::{StringMatch, StringMatchCandidate};
use gpui::{ use gpui::{
actions, div, prelude::*, Action, AppContext, Component, Div, EventEmitter, FocusHandle, actions, div, prelude::*, Action, AppContext, Component, Dismiss, Div, FocusHandle, Keystroke,
Keystroke, ParentComponent, Render, Styled, View, ViewContext, VisualContext, WeakView, ManagedView, ParentComponent, Render, Styled, View, ViewContext, VisualContext, WeakView,
WindowContext,
}; };
use picker::{Picker, PickerDelegate}; use picker::{Picker, PickerDelegate};
use std::{ use std::{
@ -16,7 +15,7 @@ use util::{
channel::{parse_zed_link, ReleaseChannel, RELEASE_CHANNEL}, channel::{parse_zed_link, ReleaseChannel, RELEASE_CHANNEL},
ResultExt, ResultExt,
}; };
use workspace::{Modal, ModalEvent, Workspace}; use workspace::Workspace;
use zed_actions::OpenZedURL; use zed_actions::OpenZedURL;
actions!(Toggle); actions!(Toggle);
@ -47,7 +46,7 @@ impl CommandPalette {
.available_actions() .available_actions()
.into_iter() .into_iter()
.filter_map(|action| { .filter_map(|action| {
let name = 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.filtered_namespaces.contains(namespace)) {
return None; return None;
@ -69,10 +68,9 @@ impl CommandPalette {
} }
} }
impl EventEmitter<ModalEvent> for CommandPalette {} impl ManagedView for CommandPalette {
impl Modal for CommandPalette { fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
fn focus(&self, cx: &mut WindowContext) { self.picker.focus_handle(cx)
self.picker.update(cx, |picker, cx| picker.focus(cx));
} }
} }
@ -267,7 +265,7 @@ impl PickerDelegate for CommandPaletteDelegate {
fn dismissed(&mut self, cx: &mut ViewContext<Picker<Self>>) { fn dismissed(&mut self, cx: &mut ViewContext<Picker<Self>>) {
self.command_palette self.command_palette
.update(cx, |_, cx| cx.emit(ModalEvent::Dismissed)) .update(cx, |_, cx| cx.emit(Dismiss))
.log_err(); .log_err();
} }
@ -456,7 +454,7 @@ mod tests {
fn init_test(cx: &mut TestAppContext) -> Arc<AppState> { fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
cx.update(|cx| { cx.update(|cx| {
let app_state = AppState::test(cx); let app_state = AppState::test(cx);
theme::init(cx); theme::init(theme::LoadThemes::JustBase, cx);
language::init(cx); language::init(cx);
editor::init(cx); editor::init(cx);
workspace::init(app_state.clone(), cx); workspace::init(app_state.clone(), cx);

View File

@ -1051,17 +1051,15 @@ mod tests {
); );
// Ensure updates to the file are reflected in the LSP. // Ensure updates to the file are reflected in the LSP.
buffer_1 buffer_1.update(cx, |buffer, cx| {
.update(cx, |buffer, cx| { buffer.file_updated(
buffer.file_updated( Arc::new(File {
Arc::new(File { abs_path: "/root/child/buffer-1".into(),
abs_path: "/root/child/buffer-1".into(), path: Path::new("child/buffer-1").into(),
path: Path::new("child/buffer-1").into(), }),
}), cx,
cx, )
) });
})
.await;
assert_eq!( assert_eq!(
lsp.receive_notification::<lsp::notification::DidCloseTextDocument>() lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
.await, .await,

View File

@ -13,7 +13,8 @@ pub use block_map::{BlockMap, BlockPoint};
use collections::{BTreeMap, HashMap, HashSet}; use collections::{BTreeMap, HashMap, HashSet};
use fold_map::FoldMap; use fold_map::FoldMap;
use gpui::{ use gpui::{
Font, FontId, HighlightStyle, Hsla, Line, Model, ModelContext, Pixels, TextRun, UnderlineStyle, Font, FontId, HighlightStyle, Hsla, LineLayout, Model, ModelContext, Pixels, ShapedLine,
TextRun, UnderlineStyle, WrappedLine,
}; };
use inlay_map::InlayMap; use inlay_map::InlayMap;
use language::{ use language::{
@ -561,7 +562,7 @@ impl DisplaySnapshot {
}) })
} }
pub fn lay_out_line_for_row( pub fn layout_row(
&self, &self,
display_row: u32, display_row: u32,
TextLayoutDetails { TextLayoutDetails {
@ -569,7 +570,7 @@ impl DisplaySnapshot {
editor_style, editor_style,
rem_size, rem_size,
}: &TextLayoutDetails, }: &TextLayoutDetails,
) -> Line { ) -> Arc<LineLayout> {
let mut runs = Vec::new(); let mut runs = Vec::new();
let mut line = String::new(); let mut line = String::new();
@ -598,29 +599,27 @@ impl DisplaySnapshot {
let font_size = editor_style.text.font_size.to_pixels(*rem_size); let font_size = editor_style.text.font_size.to_pixels(*rem_size);
text_system text_system
.layout_text(&line, font_size, &runs, None) .layout_line(&line, font_size, &runs)
.unwrap() .expect("we expect the font to be loaded because it's rendered by the editor")
.pop()
.unwrap()
} }
pub fn x_for_point( pub fn x_for_display_point(
&self, &self,
display_point: DisplayPoint, display_point: DisplayPoint,
text_layout_details: &TextLayoutDetails, text_layout_details: &TextLayoutDetails,
) -> Pixels { ) -> Pixels {
let layout_line = self.lay_out_line_for_row(display_point.row(), text_layout_details); let line = self.layout_row(display_point.row(), text_layout_details);
layout_line.x_for_index(display_point.column() as usize) line.x_for_index(display_point.column() as usize)
} }
pub fn column_for_x( pub fn display_column_for_x(
&self, &self,
display_row: u32, display_row: u32,
x_coordinate: Pixels, x: Pixels,
text_layout_details: &TextLayoutDetails, details: &TextLayoutDetails,
) -> u32 { ) -> u32 {
let layout_line = self.lay_out_line_for_row(display_row, text_layout_details); let layout_line = self.layout_row(display_row, details);
layout_line.closest_index_for_x(x_coordinate) as u32 layout_line.closest_index_for_x(x) as u32
} }
pub fn chars_at( pub fn chars_at(

View File

@ -1891,6 +1891,6 @@ mod tests {
fn init_test(cx: &mut AppContext) { fn init_test(cx: &mut AppContext) {
let store = SettingsStore::test(cx); let store = SettingsStore::test(cx);
cx.set_global(store); cx.set_global(store);
theme::init(cx); theme::init(theme::LoadThemes::JustBase, cx);
} }
} }

View File

@ -39,7 +39,7 @@ use futures::FutureExt;
use fuzzy::{StringMatch, StringMatchCandidate}; use fuzzy::{StringMatch, StringMatchCandidate};
use git::diff_hunk_to_display; use git::diff_hunk_to_display;
use gpui::{ use gpui::{
action, actions, div, point, prelude::*, px, relative, rems, size, uniform_list, AnyElement, actions, div, point, prelude::*, px, relative, rems, size, uniform_list, Action, AnyElement,
AppContext, AsyncWindowContext, BackgroundExecutor, Bounds, ClipboardItem, Component, Context, AppContext, AsyncWindowContext, BackgroundExecutor, Bounds, ClipboardItem, Component, Context,
EventEmitter, FocusHandle, FocusableView, FontFeatures, FontStyle, FontWeight, HighlightStyle, EventEmitter, FocusHandle, FocusableView, FontFeatures, FontStyle, FontWeight, HighlightStyle,
Hsla, InputHandler, KeyContext, Model, MouseButton, ParentComponent, Pixels, Render, Styled, Hsla, InputHandler, KeyContext, Model, MouseButton, ParentComponent, Pixels, Render, Styled,
@ -180,78 +180,78 @@ pub const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
// // .with_soft_wrap(true) // // .with_soft_wrap(true)
// } // }
#[action] #[derive(PartialEq, Clone, Deserialize, Default, Action)]
pub struct SelectNext { pub struct SelectNext {
#[serde(default)] #[serde(default)]
pub replace_newest: bool, pub replace_newest: bool,
} }
#[action] #[derive(PartialEq, Clone, Deserialize, Default, Action)]
pub struct SelectPrevious { pub struct SelectPrevious {
#[serde(default)] #[serde(default)]
pub replace_newest: bool, pub replace_newest: bool,
} }
#[action] #[derive(PartialEq, Clone, Deserialize, Default, Action)]
pub struct SelectAllMatches { pub struct SelectAllMatches {
#[serde(default)] #[serde(default)]
pub replace_newest: bool, pub replace_newest: bool,
} }
#[action] #[derive(PartialEq, Clone, Deserialize, Default, Action)]
pub struct SelectToBeginningOfLine { pub struct SelectToBeginningOfLine {
#[serde(default)] #[serde(default)]
stop_at_soft_wraps: bool, stop_at_soft_wraps: bool,
} }
#[action] #[derive(PartialEq, Clone, Deserialize, Default, Action)]
pub struct MovePageUp { pub struct MovePageUp {
#[serde(default)] #[serde(default)]
center_cursor: bool, center_cursor: bool,
} }
#[action] #[derive(PartialEq, Clone, Deserialize, Default, Action)]
pub struct MovePageDown { pub struct MovePageDown {
#[serde(default)] #[serde(default)]
center_cursor: bool, center_cursor: bool,
} }
#[action] #[derive(PartialEq, Clone, Deserialize, Default, Action)]
pub struct SelectToEndOfLine { pub struct SelectToEndOfLine {
#[serde(default)] #[serde(default)]
stop_at_soft_wraps: bool, stop_at_soft_wraps: bool,
} }
#[action] #[derive(PartialEq, Clone, Deserialize, Default, Action)]
pub struct ToggleCodeActions { pub struct ToggleCodeActions {
#[serde(default)] #[serde(default)]
pub deployed_from_indicator: bool, pub deployed_from_indicator: bool,
} }
#[action] #[derive(PartialEq, Clone, Deserialize, Default, Action)]
pub struct ConfirmCompletion { pub struct ConfirmCompletion {
#[serde(default)] #[serde(default)]
pub item_ix: Option<usize>, pub item_ix: Option<usize>,
} }
#[action] #[derive(PartialEq, Clone, Deserialize, Default, Action)]
pub struct ConfirmCodeAction { pub struct ConfirmCodeAction {
#[serde(default)] #[serde(default)]
pub item_ix: Option<usize>, pub item_ix: Option<usize>,
} }
#[action] #[derive(PartialEq, Clone, Deserialize, Default, Action)]
pub struct ToggleComments { pub struct ToggleComments {
#[serde(default)] #[serde(default)]
pub advance_downwards: bool, pub advance_downwards: bool,
} }
#[action] #[derive(PartialEq, Clone, Deserialize, Default, Action)]
pub struct FoldAt { pub struct FoldAt {
pub buffer_row: u32, pub buffer_row: u32,
} }
#[action] #[derive(PartialEq, Clone, Deserialize, Default, Action)]
pub struct UnfoldAt { pub struct UnfoldAt {
pub buffer_row: u32, pub buffer_row: u32,
} }
@ -5445,7 +5445,9 @@ impl Editor {
*head.column_mut() += 1; *head.column_mut() += 1;
head = display_map.clip_point(head, Bias::Right); head = display_map.clip_point(head, Bias::Right);
let goal = SelectionGoal::HorizontalPosition( let goal = SelectionGoal::HorizontalPosition(
display_map.x_for_point(head, &text_layout_details).into(), display_map
.x_for_display_point(head, &text_layout_details)
.into(),
); );
selection.collapse_to(head, goal); selection.collapse_to(head, goal);
@ -6391,8 +6393,8 @@ impl Editor {
let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone(); let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
let range = oldest_selection.display_range(&display_map).sorted(); let range = oldest_selection.display_range(&display_map).sorted();
let start_x = display_map.x_for_point(range.start, &text_layout_details); let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
let end_x = display_map.x_for_point(range.end, &text_layout_details); let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
let positions = start_x.min(end_x)..start_x.max(end_x); let positions = start_x.min(end_x)..start_x.max(end_x);
selections.clear(); selections.clear();
@ -6431,15 +6433,16 @@ impl Editor {
let range = selection.display_range(&display_map).sorted(); let range = selection.display_range(&display_map).sorted();
debug_assert_eq!(range.start.row(), range.end.row()); debug_assert_eq!(range.start.row(), range.end.row());
let mut row = range.start.row(); let mut row = range.start.row();
let positions = if let SelectionGoal::HorizontalRange { start, end } = let positions =
selection.goal if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
{ px(start)..px(end)
px(start)..px(end) } else {
} else { let start_x =
let start_x = display_map.x_for_point(range.start, &text_layout_details); display_map.x_for_display_point(range.start, &text_layout_details);
let end_x = display_map.x_for_point(range.end, &text_layout_details); let end_x =
start_x.min(end_x)..start_x.max(end_x) display_map.x_for_display_point(range.end, &text_layout_details);
}; start_x.min(end_x)..start_x.max(end_x)
};
while row != end_row { while row != end_row {
if above { if above {
@ -6992,7 +6995,7 @@ impl Editor {
let display_point = point.to_display_point(display_snapshot); let display_point = point.to_display_point(display_snapshot);
let goal = SelectionGoal::HorizontalPosition( let goal = SelectionGoal::HorizontalPosition(
display_snapshot display_snapshot
.x_for_point(display_point, &text_layout_details) .x_for_display_point(display_point, &text_layout_details)
.into(), .into(),
); );
(display_point, goal) (display_point, goal)
@ -9379,18 +9382,16 @@ impl Render for Editor {
fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element { fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
let settings = ThemeSettings::get_global(cx); let settings = ThemeSettings::get_global(cx);
let text_style = match self.mode { let text_style = match self.mode {
EditorMode::SingleLine => { EditorMode::SingleLine => TextStyle {
TextStyle { color: cx.theme().colors().text,
color: cx.theme().colors().text, font_family: settings.ui_font.family.clone(),
font_family: settings.ui_font.family.clone(), // todo!() font_features: settings.ui_font.features,
font_features: settings.ui_font.features, font_size: rems(0.875).into(),
font_size: rems(0.875).into(), font_weight: FontWeight::NORMAL,
font_weight: FontWeight::NORMAL, font_style: FontStyle::Normal,
font_style: FontStyle::Normal, line_height: relative(1.).into(),
line_height: relative(1.3).into(), // TODO relative(settings.buffer_line_height.value()), underline: None,
underline: None, },
}
}
EditorMode::AutoHeight { max_lines } => todo!(), EditorMode::AutoHeight { max_lines } => todo!(),
@ -9761,7 +9762,8 @@ impl InputHandler for Editor {
let scroll_left = scroll_position.x * em_width; let scroll_left = scroll_position.x * em_width;
let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot); let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
let x = snapshot.x_for_point(start, &text_layout_details) - scroll_left + self.gutter_width; let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
+ self.gutter_width;
let y = line_height * (start.row() as f32 - scroll_position.y); let y = line_height * (start.row() as f32 - scroll_position.y);
Some(Bounds { Some(Bounds {

View File

@ -8277,7 +8277,7 @@ pub(crate) fn init_test(cx: &mut TestAppContext, f: fn(&mut AllLanguageSettingsC
cx.update(|cx| { cx.update(|cx| {
let store = SettingsStore::test(cx); let store = SettingsStore::test(cx);
cx.set_global(store); cx.set_global(store);
theme::init(cx); theme::init(theme::LoadThemes::JustBase, cx);
client::init_settings(cx); client::init_settings(cx);
language::init(cx); language::init(cx);
Project::init_settings(cx); Project::init_settings(cx);

View File

@ -20,10 +20,10 @@ use collections::{BTreeMap, HashMap};
use gpui::{ use gpui::{
div, point, px, relative, size, transparent_black, Action, AnyElement, AvailableSpace, div, point, px, relative, size, transparent_black, Action, AnyElement, AvailableSpace,
BorrowWindow, Bounds, Component, ContentMask, Corners, DispatchPhase, Edges, Element, BorrowWindow, Bounds, Component, ContentMask, Corners, DispatchPhase, Edges, Element,
ElementId, ElementInputHandler, Entity, EntityId, Hsla, InteractiveComponent, Line, ElementId, ElementInputHandler, Entity, EntityId, Hsla, InteractiveComponent, LineLayout,
MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentComponent, Pixels, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentComponent, Pixels,
ScrollWheelEvent, Size, StatefulInteractiveComponent, Style, Styled, TextRun, TextStyle, View, ScrollWheelEvent, ShapedLine, SharedString, Size, StatefulInteractiveComponent, Style, Styled,
ViewContext, WindowContext, TextRun, TextStyle, View, ViewContext, WindowContext, WrappedLine,
}; };
use itertools::Itertools; use itertools::Itertools;
use language::language_settings::ShowWhitespaceSetting; use language::language_settings::ShowWhitespaceSetting;
@ -476,7 +476,7 @@ impl EditorElement {
Self::paint_diff_hunks(bounds, layout, cx); Self::paint_diff_hunks(bounds, layout, cx);
} }
for (ix, line) in layout.line_number_layouts.iter().enumerate() { for (ix, line) in layout.line_numbers.iter().enumerate() {
if let Some(line) = line { if let Some(line) = line {
let line_origin = bounds.origin let line_origin = bounds.origin
+ point( + point(
@ -775,21 +775,21 @@ impl EditorElement {
.chars_at(cursor_position) .chars_at(cursor_position)
.next() .next()
.and_then(|(character, _)| { .and_then(|(character, _)| {
let text = character.to_string(); let text = SharedString::from(character.to_string());
let len = text.len();
cx.text_system() cx.text_system()
.layout_text( .shape_line(
&text, text,
cursor_row_layout.font_size, cursor_row_layout.font_size,
&[TextRun { &[TextRun {
len: text.len(), len,
font: self.style.text.font(), font: self.style.text.font(),
color: self.style.background, color: self.style.background,
background_color: None,
underline: None, underline: None,
}], }],
None,
) )
.unwrap() .log_err()
.pop()
}) })
} else { } else {
None None
@ -1244,20 +1244,20 @@ impl EditorElement {
let font_size = style.text.font_size.to_pixels(cx.rem_size()); let font_size = style.text.font_size.to_pixels(cx.rem_size());
let layout = cx let layout = cx
.text_system() .text_system()
.layout_text( .shape_line(
" ".repeat(column).as_str(), SharedString::from(" ".repeat(column)),
font_size, font_size,
&[TextRun { &[TextRun {
len: column, len: column,
font: style.text.font(), font: style.text.font(),
color: Hsla::default(), color: Hsla::default(),
background_color: None,
underline: None, underline: None,
}], }],
None,
) )
.unwrap(); .unwrap();
layout[0].width layout.width
} }
fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &ViewContext<Editor>) -> Pixels { fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &ViewContext<Editor>) -> Pixels {
@ -1338,7 +1338,7 @@ impl EditorElement {
relative_rows relative_rows
} }
fn layout_line_numbers( fn shape_line_numbers(
&self, &self,
rows: Range<u32>, rows: Range<u32>,
active_rows: &BTreeMap<u32, bool>, active_rows: &BTreeMap<u32, bool>,
@ -1347,12 +1347,12 @@ impl EditorElement {
snapshot: &EditorSnapshot, snapshot: &EditorSnapshot,
cx: &ViewContext<Editor>, cx: &ViewContext<Editor>,
) -> ( ) -> (
Vec<Option<gpui::Line>>, Vec<Option<ShapedLine>>,
Vec<Option<(FoldStatus, BufferRow, bool)>>, Vec<Option<(FoldStatus, BufferRow, bool)>>,
) { ) {
let font_size = self.style.text.font_size.to_pixels(cx.rem_size()); let font_size = self.style.text.font_size.to_pixels(cx.rem_size());
let include_line_numbers = snapshot.mode == EditorMode::Full; let include_line_numbers = snapshot.mode == EditorMode::Full;
let mut line_number_layouts = Vec::with_capacity(rows.len()); let mut shaped_line_numbers = Vec::with_capacity(rows.len());
let mut fold_statuses = Vec::with_capacity(rows.len()); let mut fold_statuses = Vec::with_capacity(rows.len());
let mut line_number = String::new(); let mut line_number = String::new();
let is_relative = EditorSettings::get_global(cx).relative_line_numbers; let is_relative = EditorSettings::get_global(cx).relative_line_numbers;
@ -1387,15 +1387,14 @@ impl EditorElement {
len: line_number.len(), len: line_number.len(),
font: self.style.text.font(), font: self.style.text.font(),
color, color,
background_color: None,
underline: None, underline: None,
}; };
let layout = cx let shaped_line = cx
.text_system() .text_system()
.layout_text(&line_number, font_size, &[run], None) .shape_line(line_number.clone().into(), font_size, &[run])
.unwrap()
.pop()
.unwrap(); .unwrap();
line_number_layouts.push(Some(layout)); shaped_line_numbers.push(Some(shaped_line));
fold_statuses.push( fold_statuses.push(
is_singleton is_singleton
.then(|| { .then(|| {
@ -1408,17 +1407,17 @@ impl EditorElement {
} }
} else { } else {
fold_statuses.push(None); fold_statuses.push(None);
line_number_layouts.push(None); shaped_line_numbers.push(None);
} }
} }
(line_number_layouts, fold_statuses) (shaped_line_numbers, fold_statuses)
} }
fn layout_lines( fn layout_lines(
&mut self, &mut self,
rows: Range<u32>, rows: Range<u32>,
line_number_layouts: &[Option<Line>], line_number_layouts: &[Option<ShapedLine>],
snapshot: &EditorSnapshot, snapshot: &EditorSnapshot,
cx: &ViewContext<Editor>, cx: &ViewContext<Editor>,
) -> Vec<LineWithInvisibles> { ) -> Vec<LineWithInvisibles> {
@ -1439,18 +1438,17 @@ impl EditorElement {
.chain(iter::repeat("")) .chain(iter::repeat(""))
.take(rows.len()); .take(rows.len());
placeholder_lines placeholder_lines
.map(|line| { .filter_map(move |line| {
let run = TextRun { let run = TextRun {
len: line.len(), len: line.len(),
font: self.style.text.font(), font: self.style.text.font(),
color: placeholder_color, color: placeholder_color,
background_color: None,
underline: Default::default(), underline: Default::default(),
}; };
cx.text_system() cx.text_system()
.layout_text(line, font_size, &[run], None) .shape_line(line.to_string().into(), font_size, &[run])
.unwrap() .log_err()
.pop()
.unwrap()
}) })
.map(|line| LineWithInvisibles { .map(|line| LineWithInvisibles {
line, line,
@ -1726,7 +1724,7 @@ impl EditorElement {
.head .head
}); });
let (line_number_layouts, fold_statuses) = self.layout_line_numbers( let (line_numbers, fold_statuses) = self.shape_line_numbers(
start_row..end_row, start_row..end_row,
&active_rows, &active_rows,
head_for_relative, head_for_relative,
@ -1740,8 +1738,7 @@ impl EditorElement {
let scrollbar_row_range = scroll_position.y..(scroll_position.y + height_in_lines); let scrollbar_row_range = scroll_position.y..(scroll_position.y + height_in_lines);
let mut max_visible_line_width = Pixels::ZERO; let mut max_visible_line_width = Pixels::ZERO;
let line_layouts = let line_layouts = self.layout_lines(start_row..end_row, &line_numbers, &snapshot, cx);
self.layout_lines(start_row..end_row, &line_number_layouts, &snapshot, cx);
for line_with_invisibles in &line_layouts { for line_with_invisibles in &line_layouts {
if line_with_invisibles.line.width > max_visible_line_width { if line_with_invisibles.line.width > max_visible_line_width {
max_visible_line_width = line_with_invisibles.line.width; max_visible_line_width = line_with_invisibles.line.width;
@ -1879,35 +1876,31 @@ impl EditorElement {
let invisible_symbol_font_size = font_size / 2.; let invisible_symbol_font_size = font_size / 2.;
let tab_invisible = cx let tab_invisible = cx
.text_system() .text_system()
.layout_text( .shape_line(
"", "".into(),
invisible_symbol_font_size, invisible_symbol_font_size,
&[TextRun { &[TextRun {
len: "".len(), len: "".len(),
font: self.style.text.font(), font: self.style.text.font(),
color: cx.theme().colors().editor_invisible, color: cx.theme().colors().editor_invisible,
background_color: None,
underline: None, underline: None,
}], }],
None,
) )
.unwrap()
.pop()
.unwrap(); .unwrap();
let space_invisible = cx let space_invisible = cx
.text_system() .text_system()
.layout_text( .shape_line(
"", "".into(),
invisible_symbol_font_size, invisible_symbol_font_size,
&[TextRun { &[TextRun {
len: "".len(), len: "".len(),
font: self.style.text.font(), font: self.style.text.font(),
color: cx.theme().colors().editor_invisible, color: cx.theme().colors().editor_invisible,
background_color: None,
underline: None, underline: None,
}], }],
None,
) )
.unwrap()
.pop()
.unwrap(); .unwrap();
LayoutState { LayoutState {
@ -1939,7 +1932,7 @@ impl EditorElement {
active_rows, active_rows,
highlighted_rows, highlighted_rows,
highlighted_ranges, highlighted_ranges,
line_number_layouts, line_numbers,
display_hunks, display_hunks,
blocks, blocks,
selections, selections,
@ -2201,7 +2194,7 @@ impl EditorElement {
#[derive(Debug)] #[derive(Debug)]
pub struct LineWithInvisibles { pub struct LineWithInvisibles {
pub line: Line, pub line: ShapedLine,
invisibles: Vec<Invisible>, invisibles: Vec<Invisible>,
} }
@ -2211,7 +2204,7 @@ impl LineWithInvisibles {
text_style: &TextStyle, text_style: &TextStyle,
max_line_len: usize, max_line_len: usize,
max_line_count: usize, max_line_count: usize,
line_number_layouts: &[Option<Line>], line_number_layouts: &[Option<ShapedLine>],
editor_mode: EditorMode, editor_mode: EditorMode,
cx: &WindowContext, cx: &WindowContext,
) -> Vec<Self> { ) -> Vec<Self> {
@ -2231,11 +2224,12 @@ impl LineWithInvisibles {
}]) { }]) {
for (ix, mut line_chunk) in highlighted_chunk.chunk.split('\n').enumerate() { for (ix, mut line_chunk) in highlighted_chunk.chunk.split('\n').enumerate() {
if ix > 0 { if ix > 0 {
let layout = cx let shaped_line = cx
.text_system() .text_system()
.layout_text(&line, font_size, &styles, None); .shape_line(line.clone().into(), font_size, &styles)
.unwrap();
layouts.push(Self { layouts.push(Self {
line: layout.unwrap().pop().unwrap(), line: shaped_line,
invisibles: invisibles.drain(..).collect(), invisibles: invisibles.drain(..).collect(),
}); });
@ -2269,6 +2263,7 @@ impl LineWithInvisibles {
len: line_chunk.len(), len: line_chunk.len(),
font: text_style.font(), font: text_style.font(),
color: text_style.color, color: text_style.color,
background_color: None,
underline: text_style.underline, underline: text_style.underline,
}); });
@ -3089,7 +3084,7 @@ pub struct LayoutState {
visible_display_row_range: Range<u32>, visible_display_row_range: Range<u32>,
active_rows: BTreeMap<u32, bool>, active_rows: BTreeMap<u32, bool>,
highlighted_rows: Option<Range<u32>>, highlighted_rows: Option<Range<u32>>,
line_number_layouts: Vec<Option<gpui::Line>>, line_numbers: Vec<Option<ShapedLine>>,
display_hunks: Vec<DisplayDiffHunk>, display_hunks: Vec<DisplayDiffHunk>,
blocks: Vec<BlockLayout>, blocks: Vec<BlockLayout>,
highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>, highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
@ -3102,8 +3097,8 @@ pub struct LayoutState {
code_actions_indicator: Option<CodeActionsIndicator>, code_actions_indicator: Option<CodeActionsIndicator>,
// hover_popovers: Option<(DisplayPoint, Vec<AnyElement<Editor>>)>, // hover_popovers: Option<(DisplayPoint, Vec<AnyElement<Editor>>)>,
fold_indicators: Vec<Option<AnyElement<Editor>>>, fold_indicators: Vec<Option<AnyElement<Editor>>>,
tab_invisible: Line, tab_invisible: ShapedLine,
space_invisible: Line, space_invisible: ShapedLine,
} }
struct CodeActionsIndicator { struct CodeActionsIndicator {
@ -3203,7 +3198,7 @@ fn layout_line(
snapshot: &EditorSnapshot, snapshot: &EditorSnapshot,
style: &EditorStyle, style: &EditorStyle,
cx: &WindowContext, cx: &WindowContext,
) -> Result<Line> { ) -> Result<ShapedLine> {
let mut line = snapshot.line(row); let mut line = snapshot.line(row);
if line.len() > MAX_LINE_LEN { if line.len() > MAX_LINE_LEN {
@ -3215,21 +3210,17 @@ fn layout_line(
line.truncate(len); line.truncate(len);
} }
Ok(cx cx.text_system().shape_line(
.text_system() line.into(),
.layout_text( style.text.font_size.to_pixels(cx.rem_size()),
&line, &[TextRun {
style.text.font_size.to_pixels(cx.rem_size()), len: snapshot.line_len(row) as usize,
&[TextRun { font: style.text.font(),
len: snapshot.line_len(row) as usize, color: Hsla::default(),
font: style.text.font(), background_color: None,
color: Hsla::default(), underline: None,
underline: None, }],
}], )
None,
)?
.pop()
.unwrap())
} }
#[derive(Debug)] #[derive(Debug)]
@ -3239,7 +3230,7 @@ pub struct Cursor {
line_height: Pixels, line_height: Pixels,
color: Hsla, color: Hsla,
shape: CursorShape, shape: CursorShape,
block_text: Option<Line>, block_text: Option<ShapedLine>,
} }
impl Cursor { impl Cursor {
@ -3249,7 +3240,7 @@ impl Cursor {
line_height: Pixels, line_height: Pixels,
color: Hsla, color: Hsla,
shape: CursorShape, shape: CursorShape,
block_text: Option<Line>, block_text: Option<ShapedLine>,
) -> Cursor { ) -> Cursor {
Cursor { Cursor {
origin, origin,

View File

@ -3179,7 +3179,7 @@ all hints should be invalidated and requeried for all of its visible excerpts"
cx.update(|cx| { cx.update(|cx| {
let settings_store = SettingsStore::test(cx); let settings_store = SettingsStore::test(cx);
cx.set_global(settings_store); cx.set_global(settings_store);
theme::init(cx); theme::init(theme::LoadThemes::JustBase, cx);
client::init_settings(cx); client::init_settings(cx);
language::init(cx); language::init(cx);
Project::init_settings(cx); Project::init_settings(cx);

View File

@ -797,7 +797,7 @@ impl Item for Editor {
fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) { fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
let workspace_id = workspace.database_id(); let workspace_id = workspace.database_id();
let item_id = cx.view().entity_id().as_u64() as ItemId; let item_id = cx.view().item_id().as_u64() as ItemId;
self.workspace = Some((workspace.weak_handle(), workspace.database_id())); self.workspace = Some((workspace.weak_handle(), workspace.database_id()));
fn serialize( fn serialize(
@ -828,7 +828,7 @@ impl Item for Editor {
serialize( serialize(
buffer, buffer,
*workspace_id, *workspace_id,
cx.view().entity_id().as_u64() as ItemId, cx.view().item_id().as_u64() as ItemId,
cx, cx,
); );
} }

View File

@ -98,7 +98,7 @@ pub fn up_by_rows(
SelectionGoal::HorizontalPosition(x) => x.into(), // todo!("Can the fields in SelectionGoal by Pixels? We should extract a geometry crate and depend on that.") SelectionGoal::HorizontalPosition(x) => x.into(), // todo!("Can the fields in SelectionGoal by Pixels? We should extract a geometry crate and depend on that.")
SelectionGoal::WrappedHorizontalPosition((_, x)) => x.into(), SelectionGoal::WrappedHorizontalPosition((_, x)) => x.into(),
SelectionGoal::HorizontalRange { end, .. } => end.into(), SelectionGoal::HorizontalRange { end, .. } => end.into(),
_ => map.x_for_point(start, text_layout_details), _ => map.x_for_display_point(start, text_layout_details),
}; };
let prev_row = start.row().saturating_sub(row_count); let prev_row = start.row().saturating_sub(row_count);
@ -107,7 +107,7 @@ pub fn up_by_rows(
Bias::Left, Bias::Left,
); );
if point.row() < start.row() { if point.row() < start.row() {
*point.column_mut() = map.column_for_x(point.row(), goal_x, text_layout_details) *point.column_mut() = map.display_column_for_x(point.row(), goal_x, text_layout_details)
} else if preserve_column_at_start { } else if preserve_column_at_start {
return (start, goal); return (start, goal);
} else { } else {
@ -137,18 +137,18 @@ pub fn down_by_rows(
SelectionGoal::HorizontalPosition(x) => x.into(), SelectionGoal::HorizontalPosition(x) => x.into(),
SelectionGoal::WrappedHorizontalPosition((_, x)) => x.into(), SelectionGoal::WrappedHorizontalPosition((_, x)) => x.into(),
SelectionGoal::HorizontalRange { end, .. } => end.into(), SelectionGoal::HorizontalRange { end, .. } => end.into(),
_ => map.x_for_point(start, text_layout_details), _ => map.x_for_display_point(start, text_layout_details),
}; };
let new_row = start.row() + row_count; let new_row = start.row() + row_count;
let mut point = map.clip_point(DisplayPoint::new(new_row, 0), Bias::Right); let mut point = map.clip_point(DisplayPoint::new(new_row, 0), Bias::Right);
if point.row() > start.row() { if point.row() > start.row() {
*point.column_mut() = map.column_for_x(point.row(), goal_x, text_layout_details) *point.column_mut() = map.display_column_for_x(point.row(), goal_x, text_layout_details)
} else if preserve_column_at_end { } else if preserve_column_at_end {
return (start, goal); return (start, goal);
} else { } else {
point = map.max_point(); point = map.max_point();
goal_x = map.x_for_point(point, text_layout_details) goal_x = map.x_for_display_point(point, text_layout_details)
} }
let mut clipped_point = map.clip_point(point, Bias::Right); let mut clipped_point = map.clip_point(point, Bias::Right);

View File

@ -313,14 +313,14 @@ impl SelectionsCollection {
let is_empty = positions.start == positions.end; let is_empty = positions.start == positions.end;
let line_len = display_map.line_len(row); let line_len = display_map.line_len(row);
let layed_out_line = display_map.lay_out_line_for_row(row, &text_layout_details); let line = display_map.layout_row(row, &text_layout_details);
dbg!("****START COL****"); dbg!("****START COL****");
let start_col = layed_out_line.closest_index_for_x(positions.start) as u32; let start_col = line.closest_index_for_x(positions.start) as u32;
if start_col < line_len || (is_empty && positions.start == layed_out_line.width) { if start_col < line_len || (is_empty && positions.start == line.width) {
let start = DisplayPoint::new(row, start_col); let start = DisplayPoint::new(row, start_col);
dbg!("****END COL****"); dbg!("****END COL****");
let end_col = layed_out_line.closest_index_for_x(positions.end) as u32; let end_col = line.closest_index_for_x(positions.end) as u32;
let end = DisplayPoint::new(row, end_col); let end = DisplayPoint::new(row, end_col);
dbg!(start_col, end_col); dbg!(start_col, end_col);

View File

@ -2,9 +2,9 @@ use collections::HashMap;
use editor::{scroll::autoscroll::Autoscroll, Bias, Editor}; use editor::{scroll::autoscroll::Autoscroll, Bias, Editor};
use fuzzy::{CharBag, PathMatch, PathMatchCandidate}; use fuzzy::{CharBag, PathMatch, PathMatchCandidate};
use gpui::{ use gpui::{
actions, div, AppContext, Component, Div, EventEmitter, InteractiveComponent, Model, actions, div, AppContext, Component, Dismiss, Div, FocusHandle, InteractiveComponent,
ParentComponent, Render, Styled, Task, View, ViewContext, VisualContext, WeakView, ManagedView, Model, ParentComponent, Render, Styled, Task, View, ViewContext, VisualContext,
WindowContext, WeakView,
}; };
use picker::{Picker, PickerDelegate}; use picker::{Picker, PickerDelegate};
use project::{PathMatchCandidateSet, Project, ProjectPath, WorktreeId}; use project::{PathMatchCandidateSet, Project, ProjectPath, WorktreeId};
@ -19,7 +19,7 @@ use text::Point;
use theme::ActiveTheme; use theme::ActiveTheme;
use ui::{v_stack, HighlightedLabel, StyledExt}; use ui::{v_stack, HighlightedLabel, StyledExt};
use util::{paths::PathLikeWithPosition, post_inc, ResultExt}; use util::{paths::PathLikeWithPosition, post_inc, ResultExt};
use workspace::{Modal, ModalEvent, Workspace}; use workspace::Workspace;
actions!(Toggle); actions!(Toggle);
@ -111,10 +111,9 @@ impl FileFinder {
} }
} }
impl EventEmitter<ModalEvent> for FileFinder {} impl ManagedView for FileFinder {
impl Modal for FileFinder { fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
fn focus(&self, cx: &mut WindowContext) { self.picker.focus_handle(cx)
self.picker.update(cx, |picker, cx| picker.focus(cx))
} }
} }
impl Render for FileFinder { impl Render for FileFinder {
@ -689,9 +688,7 @@ impl PickerDelegate for FileFinderDelegate {
.log_err(); .log_err();
} }
} }
finder finder.update(&mut cx, |_, cx| cx.emit(Dismiss)).ok()?;
.update(&mut cx, |_, cx| cx.emit(ModalEvent::Dismissed))
.ok()?;
Some(()) Some(())
}) })
@ -702,7 +699,7 @@ impl PickerDelegate for FileFinderDelegate {
fn dismissed(&mut self, cx: &mut ViewContext<Picker<FileFinderDelegate>>) { fn dismissed(&mut self, cx: &mut ViewContext<Picker<FileFinderDelegate>>) {
self.file_finder self.file_finder
.update(cx, |_, cx| cx.emit(ModalEvent::Dismissed)) .update(cx, |_, cx| cx.emit(Dismiss))
.log_err(); .log_err();
} }
@ -1763,7 +1760,7 @@ mod tests {
fn init_test(cx: &mut TestAppContext) -> Arc<AppState> { fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
cx.update(|cx| { cx.update(|cx| {
let state = AppState::test(cx); let state = AppState::test(cx);
theme::init(cx); theme::init(theme::LoadThemes::JustBase, cx);
language::init(cx); language::init(cx);
super::init(cx); super::init(cx);
editor::init(cx); editor::init(cx);

View File

@ -1,13 +1,13 @@
use editor::{display_map::ToDisplayPoint, scroll::autoscroll::Autoscroll, Editor}; use editor::{display_map::ToDisplayPoint, scroll::autoscroll::Autoscroll, Editor};
use gpui::{ use gpui::{
actions, div, prelude::*, AppContext, Div, EventEmitter, ParentComponent, Render, SharedString, actions, div, prelude::*, AppContext, Dismiss, Div, FocusHandle, ManagedView, ParentComponent,
Styled, Subscription, View, ViewContext, VisualContext, WindowContext, Render, SharedString, Styled, Subscription, View, ViewContext, VisualContext, WindowContext,
}; };
use text::{Bias, Point}; use text::{Bias, Point};
use theme::ActiveTheme; use theme::ActiveTheme;
use ui::{h_stack, v_stack, Label, StyledExt, TextColor}; use ui::{h_stack, v_stack, Label, StyledExt, TextColor};
use util::paths::FILE_ROW_COLUMN_DELIMITER; use util::paths::FILE_ROW_COLUMN_DELIMITER;
use workspace::{Modal, ModalEvent, Workspace}; use workspace::Workspace;
actions!(Toggle); actions!(Toggle);
@ -23,10 +23,9 @@ pub struct GoToLine {
_subscriptions: Vec<Subscription>, _subscriptions: Vec<Subscription>,
} }
impl EventEmitter<ModalEvent> for GoToLine {} impl ManagedView for GoToLine {
impl Modal for GoToLine { fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
fn focus(&self, cx: &mut WindowContext) { self.line_editor.focus_handle(cx)
self.line_editor.update(cx, |editor, cx| editor.focus(cx))
} }
} }
@ -88,7 +87,7 @@ impl GoToLine {
) { ) {
match event { match event {
// todo!() this isn't working... // todo!() this isn't working...
editor::Event::Blurred => cx.emit(ModalEvent::Dismissed), editor::Event::Blurred => cx.emit(Dismiss),
editor::Event::BufferEdited { .. } => self.highlight_current_line(cx), editor::Event::BufferEdited { .. } => self.highlight_current_line(cx),
_ => {} _ => {}
} }
@ -123,7 +122,7 @@ impl GoToLine {
} }
fn cancel(&mut self, _: &menu::Cancel, cx: &mut ViewContext<Self>) { fn cancel(&mut self, _: &menu::Cancel, cx: &mut ViewContext<Self>) {
cx.emit(ModalEvent::Dismissed); cx.emit(Dismiss);
} }
fn confirm(&mut self, _: &menu::Confirm, cx: &mut ViewContext<Self>) { fn confirm(&mut self, _: &menu::Confirm, cx: &mut ViewContext<Self>) {
@ -140,7 +139,7 @@ impl GoToLine {
self.prev_scroll_position.take(); self.prev_scroll_position.take();
} }
cx.emit(ModalEvent::Dismissed); cx.emit(Dismiss);
} }
} }

View File

@ -22,6 +22,7 @@ sqlez = { path = "../sqlez" }
async-task = "4.0.3" async-task = "4.0.3"
backtrace = { version = "0.3", optional = true } backtrace = { version = "0.3", optional = true }
ctor.workspace = true ctor.workspace = true
linkme = "0.3"
derive_more.workspace = true derive_more.workspace = true
dhat = { version = "0.3", optional = true } dhat = { version = "0.3", optional = true }
env_logger = { version = "0.9", optional = true } env_logger = { version = "0.9", optional = true }

View File

@ -1,10 +1,12 @@
use crate::SharedString; use crate::SharedString;
use anyhow::{anyhow, Context, Result}; use anyhow::{anyhow, Context, Result};
use collections::HashMap; use collections::HashMap;
use lazy_static::lazy_static; pub use no_action::NoAction;
use parking_lot::{MappedRwLockReadGuard, RwLock, RwLockReadGuard}; use serde_json::json;
use serde::Deserialize; use std::{
use std::any::{type_name, Any, TypeId}; any::{Any, TypeId},
ops::Deref,
};
/// Actions are used to implement keyboard-driven UI. /// Actions are used to implement keyboard-driven UI.
/// When you declare an action, you can bind keys to the action in the keymap and /// When you declare an action, you can bind keys to the action in the keymap and
@ -15,24 +17,16 @@ use std::any::{type_name, Any, TypeId};
/// ```rust /// ```rust
/// actions!(MoveUp, MoveDown, MoveLeft, MoveRight, Newline); /// actions!(MoveUp, MoveDown, MoveLeft, MoveRight, Newline);
/// ``` /// ```
/// More complex data types can also be actions. If you annotate your type with the `#[action]` proc macro, /// More complex data types can also be actions. If you annotate your type with the action derive macro
/// it will automatically /// it will be implemented and registered automatically.
/// ``` /// ```
/// #[action] /// #[derive(Clone, PartialEq, serde_derive::Deserialize, Action)]
/// pub struct SelectNext { /// pub struct SelectNext {
/// pub replace_newest: bool, /// pub replace_newest: bool,
/// } /// }
/// ///
/// Any type A that satisfies the following bounds is automatically an action: /// If you want to control the behavior of the action trait manually, you can use the lower-level `#[register_action]`
/// /// macro, which only generates the code needed to register your action before `main`.
/// ```
/// A: for<'a> Deserialize<'a> + PartialEq + Clone + Default + std::fmt::Debug + 'static,
/// ```
///
/// The `#[action]` annotation will derive these implementations for your struct automatically. If you
/// want to control them manually, you can use the lower-level `#[register_action]` macro, which only
/// generates the code needed to register your action before `main`. Then you'll need to implement all
/// the traits manually.
/// ///
/// ``` /// ```
/// #[gpui::register_action] /// #[gpui::register_action]
@ -41,77 +35,29 @@ use std::any::{type_name, Any, TypeId};
/// pub content: SharedString, /// pub content: SharedString,
/// } /// }
/// ///
/// impl std::default::Default for Paste { /// impl gpui::Action for Paste {
/// fn default() -> Self { /// ///...
/// Self {
/// content: SharedString::from("🍝"),
/// }
/// }
/// } /// }
/// ``` /// ```
pub trait Action: std::fmt::Debug + 'static { pub trait Action: 'static {
fn qualified_name() -> SharedString
where
Self: Sized;
fn build(value: Option<serde_json::Value>) -> Result<Box<dyn Action>>
where
Self: Sized;
fn is_registered() -> bool
where
Self: Sized;
fn partial_eq(&self, action: &dyn Action) -> bool;
fn boxed_clone(&self) -> Box<dyn Action>; fn boxed_clone(&self) -> Box<dyn Action>;
fn as_any(&self) -> &dyn Any; fn as_any(&self) -> &dyn Any;
fn partial_eq(&self, action: &dyn Action) -> bool;
fn name(&self) -> &str;
fn debug_name() -> &'static str
where
Self: Sized;
fn build(value: serde_json::Value) -> Result<Box<dyn Action>>
where
Self: Sized;
} }
// Types become actions by satisfying a list of trait bounds. impl std::fmt::Debug for dyn Action {
impl<A> Action for A fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
where f.debug_struct("dyn Action")
A: for<'a> Deserialize<'a> + PartialEq + Default + Clone + std::fmt::Debug + 'static, .field("type_name", &self.name())
{ .finish()
fn qualified_name() -> SharedString {
let name = type_name::<A>();
let mut separator_matches = name.rmatch_indices("::");
separator_matches.next().unwrap();
let name_start_ix = separator_matches.next().map_or(0, |(ix, _)| ix + 2);
// todo!() remove the 2 replacement when migration is done
name[name_start_ix..].replace("2::", "::").into()
}
fn build(params: Option<serde_json::Value>) -> Result<Box<dyn Action>>
where
Self: Sized,
{
let action = if let Some(params) = params {
serde_json::from_value(params).context("failed to deserialize action")?
} else {
Self::default()
};
Ok(Box::new(action))
}
fn is_registered() -> bool {
ACTION_REGISTRY
.read()
.names_by_type_id
.get(&TypeId::of::<A>())
.is_some()
}
fn partial_eq(&self, action: &dyn Action) -> bool {
action
.as_any()
.downcast_ref::<Self>()
.map_or(false, |a| self == a)
}
fn boxed_clone(&self) -> Box<dyn Action> {
Box::new(self.clone())
}
fn as_any(&self) -> &dyn Any {
self
} }
} }
@ -119,69 +65,93 @@ impl dyn Action {
pub fn type_id(&self) -> TypeId { pub fn type_id(&self) -> TypeId {
self.as_any().type_id() self.as_any().type_id()
} }
pub fn name(&self) -> SharedString {
ACTION_REGISTRY
.read()
.names_by_type_id
.get(&self.type_id())
.expect("type is not a registered action")
.clone()
}
} }
type ActionBuilder = fn(json: Option<serde_json::Value>) -> anyhow::Result<Box<dyn Action>>; type ActionBuilder = fn(json: serde_json::Value) -> anyhow::Result<Box<dyn Action>>;
lazy_static! { pub(crate) struct ActionRegistry {
static ref ACTION_REGISTRY: RwLock<ActionRegistry> = RwLock::default();
}
#[derive(Default)]
struct ActionRegistry {
builders_by_name: HashMap<SharedString, ActionBuilder>, builders_by_name: HashMap<SharedString, ActionBuilder>,
names_by_type_id: HashMap<TypeId, SharedString>, names_by_type_id: HashMap<TypeId, SharedString>,
all_names: Vec<SharedString>, // So we can return a static slice. all_names: Vec<SharedString>, // So we can return a static slice.
} }
/// Register an action type to allow it to be referenced in keymaps. impl Default for ActionRegistry {
pub fn register_action<A: Action>() { fn default() -> Self {
let name = A::qualified_name(); let mut this = ActionRegistry {
let mut lock = ACTION_REGISTRY.write(); builders_by_name: Default::default(),
lock.builders_by_name.insert(name.clone(), A::build); names_by_type_id: Default::default(),
lock.names_by_type_id all_names: Default::default(),
.insert(TypeId::of::<A>(), name.clone()); };
lock.all_names.push(name);
this.load_actions();
this
}
} }
/// Construct an action based on its name and optional JSON parameters sourced from the keymap. /// This type must be public so that our macros can build it in other crates.
pub fn build_action_from_type(type_id: &TypeId) -> Result<Box<dyn Action>> { /// But this is an implementation detail and should not be used directly.
let lock = ACTION_REGISTRY.read(); #[doc(hidden)]
let name = lock pub type MacroActionBuilder = fn() -> ActionData;
.names_by_type_id
.get(type_id)
.ok_or_else(|| anyhow!("no action type registered for {:?}", type_id))?
.clone();
drop(lock);
build_action(&name, None) /// This type must be public so that our macros can build it in other crates.
/// But this is an implementation detail and should not be used directly.
#[doc(hidden)]
pub struct ActionData {
pub name: &'static str,
pub type_id: TypeId,
pub build: ActionBuilder,
} }
/// Construct an action based on its name and optional JSON parameters sourced from the keymap. /// This constant must be public to be accessible from other crates.
pub fn build_action(name: &str, params: Option<serde_json::Value>) -> Result<Box<dyn Action>> { /// But it's existence is an implementation detail and should not be used directly.
let lock = ACTION_REGISTRY.read(); #[doc(hidden)]
#[linkme::distributed_slice]
pub static __GPUI_ACTIONS: [MacroActionBuilder];
let build_action = lock impl ActionRegistry {
.builders_by_name /// Load all registered actions into the registry.
.get(name) pub(crate) fn load_actions(&mut self) {
.ok_or_else(|| anyhow!("no action type registered for {}", name))?; for builder in __GPUI_ACTIONS {
(build_action)(params) let action = builder();
} //todo(remove)
let name: SharedString = remove_the_2(action.name).into();
self.builders_by_name.insert(name.clone(), action.build);
self.names_by_type_id.insert(action.type_id, name.clone());
self.all_names.push(name);
}
}
pub fn all_action_names() -> MappedRwLockReadGuard<'static, [SharedString]> { /// Construct an action based on its name and optional JSON parameters sourced from the keymap.
let lock = ACTION_REGISTRY.read(); pub fn build_action_type(&self, type_id: &TypeId) -> Result<Box<dyn Action>> {
RwLockReadGuard::map(lock, |registry: &ActionRegistry| { let name = self
registry.all_names.as_slice() .names_by_type_id
}) .get(type_id)
.ok_or_else(|| anyhow!("no action type registered for {:?}", type_id))?
.clone();
self.build_action(&name, None)
}
/// Construct an action based on its name and optional JSON parameters sourced from the keymap.
pub fn build_action(
&self,
name: &str,
params: Option<serde_json::Value>,
) -> Result<Box<dyn Action>> {
//todo(remove)
let name = remove_the_2(name);
let build_action = self
.builders_by_name
.get(name.deref())
.ok_or_else(|| anyhow!("no action type registered for {}", name))?;
(build_action)(params.unwrap_or_else(|| json!({})))
.with_context(|| format!("Attempting to build action {}", name))
}
pub fn all_action_names(&self) -> &[SharedString] {
self.all_names.as_slice()
}
} }
/// Defines unit structs that can be used as actions. /// Defines unit structs that can be used as actions.
@ -191,7 +161,7 @@ macro_rules! actions {
() => {}; () => {};
( $name:ident ) => { ( $name:ident ) => {
#[gpui::action] #[derive(::std::cmp::PartialEq, ::std::clone::Clone, ::std::default::Default, gpui::serde_derive::Deserialize, gpui::Action)]
pub struct $name; pub struct $name;
}; };
@ -200,3 +170,20 @@ macro_rules! actions {
actions!($($rest)*); actions!($($rest)*);
}; };
} }
//todo!(remove)
pub fn remove_the_2(action_name: &str) -> String {
let mut separator_matches = action_name.rmatch_indices("::");
separator_matches.next().unwrap();
let name_start_ix = separator_matches.next().map_or(0, |(ix, _)| ix + 2);
// todo!() remove the 2 replacement when migration is done
action_name[name_start_ix..]
.replace("2::", "::")
.to_string()
}
mod no_action {
use crate as gpui;
actions!(NoAction);
}

View File

@ -14,12 +14,13 @@ use smallvec::SmallVec;
pub use test_context::*; pub use test_context::*;
use crate::{ use crate::{
current_platform, image_cache::ImageCache, Action, AnyBox, AnyView, AnyWindowHandle, current_platform, image_cache::ImageCache, Action, ActionRegistry, AnyBox, AnyView,
AppMetadata, AssetSource, BackgroundExecutor, ClipboardItem, Context, DispatchPhase, DisplayId, AnyWindowHandle, AppMetadata, AssetSource, BackgroundExecutor, ClipboardItem, Context,
Entity, EventEmitter, FocusEvent, FocusHandle, FocusId, ForegroundExecutor, KeyBinding, Keymap, DispatchPhase, DisplayId, Entity, EventEmitter, FocusEvent, FocusHandle, FocusId,
LayoutId, PathPromptOptions, Pixels, Platform, PlatformDisplay, Point, Render, SubscriberSet, ForegroundExecutor, KeyBinding, Keymap, LayoutId, PathPromptOptions, Pixels, Platform,
Subscription, SvgRenderer, Task, TextStyle, TextStyleRefinement, TextSystem, View, ViewContext, PlatformDisplay, Point, Render, SharedString, SubscriberSet, Subscription, SvgRenderer, Task,
Window, WindowContext, WindowHandle, WindowId, TextStyle, TextStyleRefinement, TextSystem, View, ViewContext, Window, WindowContext,
WindowHandle, WindowId,
}; };
use anyhow::{anyhow, Result}; use anyhow::{anyhow, Result};
use collections::{HashMap, HashSet, VecDeque}; use collections::{HashMap, HashSet, VecDeque};
@ -182,6 +183,7 @@ pub struct AppContext {
text_system: Arc<TextSystem>, text_system: Arc<TextSystem>,
flushing_effects: bool, flushing_effects: bool,
pending_updates: usize, pending_updates: usize,
pub(crate) actions: Rc<ActionRegistry>,
pub(crate) active_drag: Option<AnyDrag>, pub(crate) active_drag: Option<AnyDrag>,
pub(crate) active_tooltip: Option<AnyTooltip>, pub(crate) active_tooltip: Option<AnyTooltip>,
pub(crate) next_frame_callbacks: HashMap<DisplayId, Vec<FrameCallback>>, pub(crate) next_frame_callbacks: HashMap<DisplayId, Vec<FrameCallback>>,
@ -240,6 +242,7 @@ impl AppContext {
platform: platform.clone(), platform: platform.clone(),
app_metadata, app_metadata,
text_system, text_system,
actions: Rc::new(ActionRegistry::default()),
flushing_effects: false, flushing_effects: false,
pending_updates: 0, pending_updates: 0,
active_drag: None, active_drag: None,
@ -964,6 +967,18 @@ impl AppContext {
pub fn propagate(&mut self) { pub fn propagate(&mut self) {
self.propagate_event = true; self.propagate_event = true;
} }
pub fn build_action(
&self,
name: &str,
data: Option<serde_json::Value>,
) -> Result<Box<dyn Action>> {
self.actions.build_action(name, data)
}
pub fn all_action_names(&self) -> &[SharedString] {
self.actions.all_action_names()
}
} }
impl Context for AppContext { impl Context for AppContext {

View File

@ -182,6 +182,10 @@ pub struct AsyncWindowContext {
} }
impl AsyncWindowContext { impl AsyncWindowContext {
pub fn window_handle(&self) -> AnyWindowHandle {
self.window
}
pub(crate) fn new(app: AsyncAppContext, window: AnyWindowHandle) -> Self { pub(crate) fn new(app: AsyncAppContext, window: AnyWindowHandle) -> Self {
Self { app, window } Self { app, window }
} }

View File

@ -370,10 +370,19 @@ impl<T: Send> Model<T> {
}) })
}); });
cx.executor().run_until_parked(); // Run other tasks until the event is emitted.
rx.try_next() loop {
.expect("no event received") match rx.try_next() {
.expect("model was dropped") Ok(Some(event)) => return event,
Ok(None) => panic!("model was dropped"),
Err(_) => {
if !cx.executor().tick() {
break;
}
}
}
}
panic!("no event received")
} }
} }

View File

@ -13,7 +13,7 @@ pub trait Element<V: 'static> {
fn layout( fn layout(
&mut self, &mut self,
view_state: &mut V, view_state: &mut V,
previous_element_state: Option<Self::ElementState>, element_state: Option<Self::ElementState>,
cx: &mut ViewContext<V>, cx: &mut ViewContext<V>,
) -> (LayoutId, Self::ElementState); ) -> (LayoutId, Self::ElementState);

View File

@ -237,11 +237,11 @@ pub trait InteractiveComponent<V: 'static>: Sized + Element<V> {
// //
// if we are relying on this side-effect still, removing the debug_assert! // if we are relying on this side-effect still, removing the debug_assert!
// likely breaks the command_palette tests. // likely breaks the command_palette tests.
debug_assert!( // debug_assert!(
A::is_registered(), // A::is_registered(),
"{:?} is not registered as an action", // "{:?} is not registered as an action",
A::qualified_name() // A::qualified_name()
); // );
self.interactivity().action_listeners.push(( self.interactivity().action_listeners.push((
TypeId::of::<A>(), TypeId::of::<A>(),
Box::new(move |view, action, phase, cx| { Box::new(move |view, action, phase, cx| {
@ -960,11 +960,11 @@ where
cx.background_executor().timer(TOOLTIP_DELAY).await; cx.background_executor().timer(TOOLTIP_DELAY).await;
view.update(&mut cx, move |view_state, cx| { view.update(&mut cx, move |view_state, cx| {
active_tooltip.borrow_mut().replace(ActiveTooltip { active_tooltip.borrow_mut().replace(ActiveTooltip {
waiting: None,
tooltip: Some(AnyTooltip { tooltip: Some(AnyTooltip {
view: tooltip_builder(view_state, cx), view: tooltip_builder(view_state, cx),
cursor_offset: cx.mouse_position(), cursor_offset: cx.mouse_position(),
}), }),
_task: None,
}); });
cx.notify(); cx.notify();
}) })
@ -972,12 +972,17 @@ where
} }
}); });
active_tooltip.borrow_mut().replace(ActiveTooltip { active_tooltip.borrow_mut().replace(ActiveTooltip {
waiting: Some(task),
tooltip: None, tooltip: None,
_task: Some(task),
}); });
} }
}); });
let active_tooltip = element_state.active_tooltip.clone();
cx.on_mouse_event(move |_, _: &MouseDownEvent, _, _| {
active_tooltip.borrow_mut().take();
});
if let Some(active_tooltip) = element_state.active_tooltip.borrow().as_ref() { if let Some(active_tooltip) = element_state.active_tooltip.borrow().as_ref() {
if active_tooltip.tooltip.is_some() { if active_tooltip.tooltip.is_some() {
cx.active_tooltip = active_tooltip.tooltip.clone() cx.active_tooltip = active_tooltip.tooltip.clone()
@ -1207,9 +1212,8 @@ pub struct InteractiveElementState {
} }
pub struct ActiveTooltip { pub struct ActiveTooltip {
#[allow(unused)] // used to drop the task
waiting: Option<Task<()>>,
tooltip: Option<AnyTooltip>, tooltip: Option<AnyTooltip>,
_task: Option<Task<()>>,
} }
/// Whether or not the element or a group that contains it is clicked by the mouse. /// Whether or not the element or a group that contains it is clicked by the mouse.

View File

@ -1,8 +1,9 @@
use smallvec::SmallVec; use smallvec::SmallVec;
use taffy::style::{Display, Position};
use crate::{ use crate::{
point, AnyElement, BorrowWindow, Bounds, Element, LayoutId, ParentComponent, Pixels, Point, point, AnyElement, BorrowWindow, Bounds, Component, Element, LayoutId, ParentComponent, Pixels,
Size, Style, Point, Size, Style,
}; };
pub struct OverlayState { pub struct OverlayState {
@ -14,7 +15,7 @@ pub struct Overlay<V> {
anchor_corner: AnchorCorner, anchor_corner: AnchorCorner,
fit_mode: OverlayFitMode, fit_mode: OverlayFitMode,
// todo!(); // todo!();
// anchor_position: Option<Vector2F>, anchor_position: Option<Point<Pixels>>,
// position_mode: OverlayPositionMode, // position_mode: OverlayPositionMode,
} }
@ -25,6 +26,7 @@ pub fn overlay<V: 'static>() -> Overlay<V> {
children: SmallVec::new(), children: SmallVec::new(),
anchor_corner: AnchorCorner::TopLeft, anchor_corner: AnchorCorner::TopLeft,
fit_mode: OverlayFitMode::SwitchAnchor, fit_mode: OverlayFitMode::SwitchAnchor,
anchor_position: None,
} }
} }
@ -35,6 +37,13 @@ impl<V> Overlay<V> {
self self
} }
/// Sets the position in window co-ordinates
/// (otherwise the location the overlay is rendered is used)
pub fn position(mut self, anchor: Point<Pixels>) -> Self {
self.anchor_position = Some(anchor);
self
}
/// Snap to window edge instead of switching anchor corner when an overflow would occur. /// Snap to window edge instead of switching anchor corner when an overflow would occur.
pub fn snap_to_window(mut self) -> Self { pub fn snap_to_window(mut self) -> Self {
self.fit_mode = OverlayFitMode::SnapToWindow; self.fit_mode = OverlayFitMode::SnapToWindow;
@ -48,6 +57,12 @@ impl<V: 'static> ParentComponent<V> for Overlay<V> {
} }
} }
impl<V: 'static> Component<V> for Overlay<V> {
fn render(self) -> AnyElement<V> {
AnyElement::new(self)
}
}
impl<V: 'static> Element<V> for Overlay<V> { impl<V: 'static> Element<V> for Overlay<V> {
type ElementState = OverlayState; type ElementState = OverlayState;
@ -66,7 +81,12 @@ impl<V: 'static> Element<V> for Overlay<V> {
.iter_mut() .iter_mut()
.map(|child| child.layout(view_state, cx)) .map(|child| child.layout(view_state, cx))
.collect::<SmallVec<_>>(); .collect::<SmallVec<_>>();
let layout_id = cx.request_layout(&Style::default(), child_layout_ids.iter().copied());
let mut overlay_style = Style::default();
overlay_style.position = Position::Absolute;
overlay_style.display = Display::Flex;
let layout_id = cx.request_layout(&overlay_style, child_layout_ids.iter().copied());
(layout_id, OverlayState { child_layout_ids }) (layout_id, OverlayState { child_layout_ids })
} }
@ -90,7 +110,7 @@ impl<V: 'static> Element<V> for Overlay<V> {
child_max = child_max.max(&child_bounds.lower_right()); child_max = child_max.max(&child_bounds.lower_right());
} }
let size: Size<Pixels> = (child_max - child_min).into(); let size: Size<Pixels> = (child_max - child_min).into();
let origin = bounds.origin; let origin = self.anchor_position.unwrap_or(bounds.origin);
let mut desired = self.anchor_corner.get_bounds(origin, size); let mut desired = self.anchor_corner.get_bounds(origin, size);
let limits = Bounds { let limits = Bounds {
@ -184,6 +204,15 @@ impl AnchorCorner {
Bounds { origin, size } Bounds { origin, size }
} }
pub fn corner(&self, bounds: Bounds<Pixels>) -> Point<Pixels> {
match self {
Self::TopLeft => bounds.origin,
Self::TopRight => bounds.upper_right(),
Self::BottomLeft => bounds.lower_left(),
Self::BottomRight => bounds.lower_right(),
}
}
fn switch_axis(self, axis: Axis) -> Self { fn switch_axis(self, axis: Axis) -> Self {
match axis { match axis {
Axis::Vertical => match self { Axis::Vertical => match self {

View File

@ -1,76 +1,39 @@
use crate::{ use crate::{
AnyElement, BorrowWindow, Bounds, Component, Element, LayoutId, Line, Pixels, SharedString, AnyElement, BorrowWindow, Bounds, Component, Element, ElementId, LayoutId, Pixels,
Size, TextRun, ViewContext, SharedString, Size, TextRun, ViewContext, WrappedLine,
}; };
use parking_lot::Mutex; use parking_lot::{Mutex, MutexGuard};
use smallvec::SmallVec; use smallvec::SmallVec;
use std::{marker::PhantomData, sync::Arc}; use std::{cell::Cell, rc::Rc, sync::Arc};
use util::ResultExt; use util::ResultExt;
impl<V: 'static> Component<V> for SharedString { pub struct Text {
fn render(self) -> AnyElement<V> {
Text {
text: self,
runs: None,
state_type: PhantomData,
}
.render()
}
}
impl<V: 'static> Component<V> for &'static str {
fn render(self) -> AnyElement<V> {
Text {
text: self.into(),
runs: None,
state_type: PhantomData,
}
.render()
}
}
// TODO: Figure out how to pass `String` to `child` without this.
// This impl doesn't exist in the `gpui2` crate.
impl<V: 'static> Component<V> for String {
fn render(self) -> AnyElement<V> {
Text {
text: self.into(),
runs: None,
state_type: PhantomData,
}
.render()
}
}
pub struct Text<V> {
text: SharedString, text: SharedString,
runs: Option<Vec<TextRun>>, runs: Option<Vec<TextRun>>,
state_type: PhantomData<V>,
} }
impl<V: 'static> Text<V> { impl Text {
/// styled renders text that has different runs of different styles. /// Renders text with runs of different styles.
/// callers are responsible for setting the correct style for each run. ///
//// /// Callers are responsible for setting the correct style for each run.
/// For uniform text you can usually just pass a string as a child, and /// For text with a uniform style, you can usually avoid calling this constructor
/// cx.text_style() will be used automatically. /// and just pass text directly.
pub fn styled(text: SharedString, runs: Vec<TextRun>) -> Self { pub fn styled(text: SharedString, runs: Vec<TextRun>) -> Self {
Text { Text {
text, text,
runs: Some(runs), runs: Some(runs),
state_type: Default::default(),
} }
} }
} }
impl<V: 'static> Component<V> for Text<V> { impl<V: 'static> Component<V> for Text {
fn render(self) -> AnyElement<V> { fn render(self) -> AnyElement<V> {
AnyElement::new(self) AnyElement::new(self)
} }
} }
impl<V: 'static> Element<V> for Text<V> { impl<V: 'static> Element<V> for Text {
type ElementState = Arc<Mutex<Option<TextElementState>>>; type ElementState = TextState;
fn element_id(&self) -> Option<crate::ElementId> { fn element_id(&self) -> Option<crate::ElementId> {
None None
@ -103,7 +66,7 @@ impl<V: 'static> Element<V> for Text<V> {
let element_state = element_state.clone(); let element_state = element_state.clone();
move |known_dimensions, _| { move |known_dimensions, _| {
let Some(lines) = text_system let Some(lines) = text_system
.layout_text( .shape_text(
&text, &text,
font_size, font_size,
&runs[..], &runs[..],
@ -111,30 +74,23 @@ impl<V: 'static> Element<V> for Text<V> {
) )
.log_err() .log_err()
else { else {
element_state.lock().replace(TextElementState { element_state.lock().replace(TextStateInner {
lines: Default::default(), lines: Default::default(),
line_height, line_height,
}); });
return Size::default(); return Size::default();
}; };
let line_count = lines let mut size: Size<Pixels> = Size::default();
.iter() for line in &lines {
.map(|line| line.wrap_count() + 1) let line_size = line.size(line_height);
.sum::<usize>(); size.height += line_size.height;
let size = Size { size.width = size.width.max(line_size.width);
width: lines }
.iter()
.map(|line| line.layout.width)
.max()
.unwrap()
.ceil(),
height: line_height * line_count,
};
element_state element_state
.lock() .lock()
.replace(TextElementState { lines, line_height }); .replace(TextStateInner { lines, line_height });
size size
} }
@ -165,7 +121,104 @@ impl<V: 'static> Element<V> for Text<V> {
} }
} }
pub struct TextElementState { #[derive(Default, Clone)]
lines: SmallVec<[Line; 1]>, pub struct TextState(Arc<Mutex<Option<TextStateInner>>>);
impl TextState {
fn lock(&self) -> MutexGuard<Option<TextStateInner>> {
self.0.lock()
}
}
struct TextStateInner {
lines: SmallVec<[WrappedLine; 1]>,
line_height: Pixels, line_height: Pixels,
} }
struct InteractiveText {
id: ElementId,
text: Text,
}
struct InteractiveTextState {
text_state: TextState,
clicked_range_ixs: Rc<Cell<SmallVec<[usize; 1]>>>,
}
impl<V: 'static> Element<V> for InteractiveText {
type ElementState = InteractiveTextState;
fn element_id(&self) -> Option<ElementId> {
Some(self.id.clone())
}
fn layout(
&mut self,
view_state: &mut V,
element_state: Option<Self::ElementState>,
cx: &mut ViewContext<V>,
) -> (LayoutId, Self::ElementState) {
if let Some(InteractiveTextState {
text_state,
clicked_range_ixs,
}) = element_state
{
let (layout_id, text_state) = self.text.layout(view_state, Some(text_state), cx);
let element_state = InteractiveTextState {
text_state,
clicked_range_ixs,
};
(layout_id, element_state)
} else {
let (layout_id, text_state) = self.text.layout(view_state, None, cx);
let element_state = InteractiveTextState {
text_state,
clicked_range_ixs: Rc::default(),
};
(layout_id, element_state)
}
}
fn paint(
&mut self,
bounds: Bounds<Pixels>,
view_state: &mut V,
element_state: &mut Self::ElementState,
cx: &mut ViewContext<V>,
) {
self.text
.paint(bounds, view_state, &mut element_state.text_state, cx)
}
}
impl<V: 'static> Component<V> for SharedString {
fn render(self) -> AnyElement<V> {
Text {
text: self,
runs: None,
}
.render()
}
}
impl<V: 'static> Component<V> for &'static str {
fn render(self) -> AnyElement<V> {
Text {
text: self.into(),
runs: None,
}
.render()
}
}
// TODO: Figure out how to pass `String` to `child` without this.
// This impl doesn't exist in the `gpui2` crate.
impl<V: 'static> Component<V> for String {
fn render(self) -> AnyElement<V> {
Text {
text: self.into(),
runs: None,
}
.render()
}
}

View File

@ -5,10 +5,11 @@ use std::{
fmt::Debug, fmt::Debug,
marker::PhantomData, marker::PhantomData,
mem, mem,
num::NonZeroUsize,
pin::Pin, pin::Pin,
rc::Rc, rc::Rc,
sync::{ sync::{
atomic::{AtomicBool, Ordering::SeqCst}, atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
Arc, Arc,
}, },
task::{Context, Poll}, task::{Context, Poll},
@ -71,30 +72,57 @@ impl<T> Future for Task<T> {
} }
} }
} }
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct TaskLabel(NonZeroUsize);
impl TaskLabel {
pub fn new() -> Self {
static NEXT_TASK_LABEL: AtomicUsize = AtomicUsize::new(1);
Self(NEXT_TASK_LABEL.fetch_add(1, SeqCst).try_into().unwrap())
}
}
type AnyLocalFuture<R> = Pin<Box<dyn 'static + Future<Output = R>>>; type AnyLocalFuture<R> = Pin<Box<dyn 'static + Future<Output = R>>>;
type AnyFuture<R> = Pin<Box<dyn 'static + Send + Future<Output = R>>>; type AnyFuture<R> = Pin<Box<dyn 'static + Send + Future<Output = R>>>;
impl BackgroundExecutor { impl BackgroundExecutor {
pub fn new(dispatcher: Arc<dyn PlatformDispatcher>) -> Self { pub fn new(dispatcher: Arc<dyn PlatformDispatcher>) -> Self {
Self { dispatcher } Self { dispatcher }
} }
/// Enqueues the given closure to be run on any thread. The closure returns /// Enqueues the given future to be run to completion on a background thread.
/// a future which will be run to completion on any available thread.
pub fn spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R> pub fn spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
where where
R: Send + 'static, R: Send + 'static,
{ {
self.spawn_internal::<R>(Box::pin(future), None)
}
/// Enqueues the given future to be run to completion on a background thread.
/// The given label can be used to control the priority of the task in tests.
pub fn spawn_labeled<R>(
&self,
label: TaskLabel,
future: impl Future<Output = R> + Send + 'static,
) -> Task<R>
where
R: Send + 'static,
{
self.spawn_internal::<R>(Box::pin(future), Some(label))
}
fn spawn_internal<R: Send + 'static>(
&self,
future: AnyFuture<R>,
label: Option<TaskLabel>,
) -> Task<R> {
let dispatcher = self.dispatcher.clone(); let dispatcher = self.dispatcher.clone();
fn inner<R: Send + 'static>( let (runnable, task) =
dispatcher: Arc<dyn PlatformDispatcher>, async_task::spawn(future, move |runnable| dispatcher.dispatch(runnable, label));
future: AnyFuture<R>, runnable.schedule();
) -> Task<R> { Task::Spawned(task)
let (runnable, task) =
async_task::spawn(future, move |runnable| dispatcher.dispatch(runnable));
runnable.schedule();
Task::Spawned(task)
}
inner::<R>(dispatcher, Box::pin(future))
} }
#[cfg(any(test, feature = "test-support"))] #[cfg(any(test, feature = "test-support"))]
@ -130,7 +158,7 @@ impl BackgroundExecutor {
match future.as_mut().poll(&mut cx) { match future.as_mut().poll(&mut cx) {
Poll::Ready(result) => return result, Poll::Ready(result) => return result,
Poll::Pending => { Poll::Pending => {
if !self.dispatcher.poll(background_only) { if !self.dispatcher.tick(background_only) {
if awoken.swap(false, SeqCst) { if awoken.swap(false, SeqCst) {
continue; continue;
} }
@ -216,11 +244,21 @@ impl BackgroundExecutor {
self.dispatcher.as_test().unwrap().simulate_random_delay() self.dispatcher.as_test().unwrap().simulate_random_delay()
} }
#[cfg(any(test, feature = "test-support"))]
pub fn deprioritize(&self, task_label: TaskLabel) {
self.dispatcher.as_test().unwrap().deprioritize(task_label)
}
#[cfg(any(test, feature = "test-support"))] #[cfg(any(test, feature = "test-support"))]
pub fn advance_clock(&self, duration: Duration) { pub fn advance_clock(&self, duration: Duration) {
self.dispatcher.as_test().unwrap().advance_clock(duration) self.dispatcher.as_test().unwrap().advance_clock(duration)
} }
#[cfg(any(test, feature = "test-support"))]
pub fn tick(&self) -> bool {
self.dispatcher.as_test().unwrap().tick(false)
}
#[cfg(any(test, feature = "test-support"))] #[cfg(any(test, feature = "test-support"))]
pub fn run_until_parked(&self) { pub fn run_until_parked(&self) {
self.dispatcher.as_test().unwrap().run_until_parked() self.dispatcher.as_test().unwrap().run_until_parked()

View File

@ -343,7 +343,7 @@ where
impl<T> Bounds<T> impl<T> Bounds<T>
where where
T: Clone + Debug + PartialOrd + Add<T, Output = T> + Sub<Output = T> + Default, T: Clone + Debug + PartialOrd + Add<T, Output = T> + Sub<Output = T> + Default + Half,
{ {
pub fn intersects(&self, other: &Bounds<T>) -> bool { pub fn intersects(&self, other: &Bounds<T>) -> bool {
let my_lower_right = self.lower_right(); let my_lower_right = self.lower_right();
@ -362,6 +362,13 @@ where
self.size.width = self.size.width.clone() + double_amount.clone(); self.size.width = self.size.width.clone() + double_amount.clone();
self.size.height = self.size.height.clone() + double_amount; self.size.height = self.size.height.clone() + double_amount;
} }
pub fn center(&self) -> Point<T> {
Point {
x: self.origin.x.clone() + self.size.width.clone().half(),
y: self.origin.y.clone() + self.size.height.clone().half(),
}
}
} }
impl<T: Clone + Default + Debug + PartialOrd + Add<T, Output = T> + Sub<Output = T>> Bounds<T> { impl<T: Clone + Default + Debug + PartialOrd + Add<T, Output = T> + Sub<Output = T>> Bounds<T> {
@ -1211,6 +1218,46 @@ impl From<()> for Length {
} }
} }
pub trait Half {
fn half(&self) -> Self;
}
impl Half for f32 {
fn half(&self) -> Self {
self / 2.
}
}
impl Half for DevicePixels {
fn half(&self) -> Self {
Self(self.0 / 2)
}
}
impl Half for ScaledPixels {
fn half(&self) -> Self {
Self(self.0 / 2.)
}
}
impl Half for Pixels {
fn half(&self) -> Self {
Self(self.0 / 2.)
}
}
impl Half for Rems {
fn half(&self) -> Self {
Self(self.0 / 2.)
}
}
impl Half for GlobalPixels {
fn half(&self) -> Self {
Self(self.0 / 2.)
}
}
pub trait IsZero { pub trait IsZero {
fn is_zero(&self) -> bool; fn is_zero(&self) -> bool;
} }

View File

@ -49,11 +49,13 @@ pub use input::*;
pub use interactive::*; pub use interactive::*;
pub use key_dispatch::*; pub use key_dispatch::*;
pub use keymap::*; pub use keymap::*;
pub use linkme;
pub use platform::*; pub use platform::*;
use private::Sealed; use private::Sealed;
pub use refineable::*; pub use refineable::*;
pub use scene::*; pub use scene::*;
pub use serde; pub use serde;
pub use serde_derive;
pub use serde_json; pub use serde_json;
pub use smallvec; pub use smallvec;
pub use smol::Timer; pub use smol::Timer;

View File

@ -1,6 +1,6 @@
use crate::{ use crate::{
build_action_from_type, Action, DispatchPhase, FocusId, KeyBinding, KeyContext, KeyMatch, Action, ActionRegistry, DispatchPhase, FocusId, KeyBinding, KeyContext, KeyMatch, Keymap,
Keymap, Keystroke, KeystrokeMatcher, WindowContext, Keystroke, KeystrokeMatcher, WindowContext,
}; };
use collections::HashMap; use collections::HashMap;
use parking_lot::Mutex; use parking_lot::Mutex;
@ -10,7 +10,6 @@ use std::{
rc::Rc, rc::Rc,
sync::Arc, sync::Arc,
}; };
use util::ResultExt;
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)] #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub struct DispatchNodeId(usize); pub struct DispatchNodeId(usize);
@ -22,6 +21,7 @@ pub(crate) struct DispatchTree {
focusable_node_ids: HashMap<FocusId, DispatchNodeId>, focusable_node_ids: HashMap<FocusId, DispatchNodeId>,
keystroke_matchers: HashMap<SmallVec<[KeyContext; 4]>, KeystrokeMatcher>, keystroke_matchers: HashMap<SmallVec<[KeyContext; 4]>, KeystrokeMatcher>,
keymap: Arc<Mutex<Keymap>>, keymap: Arc<Mutex<Keymap>>,
action_registry: Rc<ActionRegistry>,
} }
#[derive(Default)] #[derive(Default)]
@ -41,7 +41,7 @@ pub(crate) struct DispatchActionListener {
} }
impl DispatchTree { impl DispatchTree {
pub fn new(keymap: Arc<Mutex<Keymap>>) -> Self { pub fn new(keymap: Arc<Mutex<Keymap>>, action_registry: Rc<ActionRegistry>) -> Self {
Self { Self {
node_stack: Vec::new(), node_stack: Vec::new(),
context_stack: Vec::new(), context_stack: Vec::new(),
@ -49,6 +49,7 @@ impl DispatchTree {
focusable_node_ids: HashMap::default(), focusable_node_ids: HashMap::default(),
keystroke_matchers: HashMap::default(), keystroke_matchers: HashMap::default(),
keymap, keymap,
action_registry,
} }
} }
@ -153,7 +154,9 @@ impl DispatchTree {
for node_id in self.dispatch_path(*node) { 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 {
actions.extend(build_action_from_type(action_type).log_err()); // 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());
} }
} }
} }

View File

@ -1,7 +1,10 @@
use crate::{KeyBinding, KeyBindingContextPredicate, Keystroke}; use crate::{KeyBinding, KeyBindingContextPredicate, Keystroke, NoAction};
use collections::HashSet; use collections::HashSet;
use smallvec::SmallVec; use smallvec::SmallVec;
use std::{any::TypeId, collections::HashMap}; use std::{
any::{Any, TypeId},
collections::HashMap,
};
#[derive(Copy, Clone, Eq, PartialEq, Default)] #[derive(Copy, Clone, Eq, PartialEq, Default)]
pub struct KeymapVersion(usize); pub struct KeymapVersion(usize);
@ -37,20 +40,19 @@ impl Keymap {
} }
pub fn add_bindings<T: IntoIterator<Item = KeyBinding>>(&mut self, bindings: T) { pub fn add_bindings<T: IntoIterator<Item = KeyBinding>>(&mut self, bindings: T) {
// todo!("no action") let no_action_id = &(NoAction {}).type_id();
// let no_action_id = (NoAction {}).id();
let mut new_bindings = Vec::new(); let mut new_bindings = Vec::new();
let has_new_disabled_keystrokes = false; let mut has_new_disabled_keystrokes = false;
for binding in bindings { for binding in bindings {
// if binding.action().id() == no_action_id { if binding.action.type_id() == *no_action_id {
// has_new_disabled_keystrokes |= self has_new_disabled_keystrokes |= self
// .disabled_keystrokes .disabled_keystrokes
// .entry(binding.keystrokes) .entry(binding.keystrokes)
// .or_default() .or_default()
// .insert(binding.context_predicate); .insert(binding.context_predicate);
// } else { } else {
new_bindings.push(binding); new_bindings.push(binding);
// } }
} }
if has_new_disabled_keystrokes { if has_new_disabled_keystrokes {

View File

@ -8,7 +8,7 @@ use crate::{
point, size, AnyWindowHandle, BackgroundExecutor, Bounds, DevicePixels, Font, FontId, point, size, AnyWindowHandle, BackgroundExecutor, Bounds, DevicePixels, Font, FontId,
FontMetrics, FontRun, ForegroundExecutor, GlobalPixels, GlyphId, InputEvent, LineLayout, FontMetrics, FontRun, ForegroundExecutor, GlobalPixels, GlyphId, InputEvent, LineLayout,
Pixels, Point, RenderGlyphParams, RenderImageParams, RenderSvgParams, Result, Scene, Pixels, Point, RenderGlyphParams, RenderImageParams, RenderSvgParams, Result, Scene,
SharedString, Size, SharedString, Size, TaskLabel,
}; };
use anyhow::{anyhow, bail}; use anyhow::{anyhow, bail};
use async_task::Runnable; use async_task::Runnable;
@ -162,10 +162,10 @@ pub(crate) trait PlatformWindow {
pub trait PlatformDispatcher: Send + Sync { pub trait PlatformDispatcher: Send + Sync {
fn is_main_thread(&self) -> bool; fn is_main_thread(&self) -> bool;
fn dispatch(&self, runnable: Runnable); fn dispatch(&self, runnable: Runnable, label: Option<TaskLabel>);
fn dispatch_on_main_thread(&self, runnable: Runnable); fn dispatch_on_main_thread(&self, runnable: Runnable);
fn dispatch_after(&self, duration: Duration, runnable: Runnable); fn dispatch_after(&self, duration: Duration, runnable: Runnable);
fn poll(&self, background_only: bool) -> bool; fn tick(&self, background_only: bool) -> bool;
fn park(&self); fn park(&self);
fn unparker(&self) -> Unparker; fn unparker(&self) -> Unparker;

View File

@ -2,7 +2,7 @@
#![allow(non_camel_case_types)] #![allow(non_camel_case_types)]
#![allow(non_snake_case)] #![allow(non_snake_case)]
use crate::PlatformDispatcher; use crate::{PlatformDispatcher, TaskLabel};
use async_task::Runnable; use async_task::Runnable;
use objc::{ use objc::{
class, msg_send, class, msg_send,
@ -37,7 +37,7 @@ impl PlatformDispatcher for MacDispatcher {
is_main_thread == YES is_main_thread == YES
} }
fn dispatch(&self, runnable: Runnable) { fn dispatch(&self, runnable: Runnable, _: Option<TaskLabel>) {
unsafe { unsafe {
dispatch_async_f( dispatch_async_f(
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT.try_into().unwrap(), 0), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT.try_into().unwrap(), 0),
@ -71,7 +71,7 @@ impl PlatformDispatcher for MacDispatcher {
} }
} }
fn poll(&self, _background_only: bool) -> bool { fn tick(&self, _background_only: bool) -> bool {
false false
} }

View File

@ -343,10 +343,10 @@ impl MacTextSystemState {
// Construct the attributed string, converting UTF8 ranges to UTF16 ranges. // Construct the attributed string, converting UTF8 ranges to UTF16 ranges.
let mut string = CFMutableAttributedString::new(); let mut string = CFMutableAttributedString::new();
{ {
string.replace_str(&CFString::new(text), CFRange::init(0, 0)); string.replace_str(&CFString::new(text.as_ref()), CFRange::init(0, 0));
let utf16_line_len = string.char_len() as usize; let utf16_line_len = string.char_len() as usize;
let mut ix_converter = StringIndexConverter::new(text); let mut ix_converter = StringIndexConverter::new(text.as_ref());
for run in font_runs { for run in font_runs {
let utf8_end = ix_converter.utf8_ix + run.len; let utf8_end = ix_converter.utf8_ix + run.len;
let utf16_start = ix_converter.utf16_ix; let utf16_start = ix_converter.utf16_ix;
@ -390,7 +390,7 @@ impl MacTextSystemState {
}; };
let font_id = self.id_for_native_font(font); let font_id = self.id_for_native_font(font);
let mut ix_converter = StringIndexConverter::new(text); let mut ix_converter = StringIndexConverter::new(text.as_ref());
let mut glyphs = SmallVec::new(); let mut glyphs = SmallVec::new();
for ((glyph_id, position), glyph_utf16_ix) in run for ((glyph_id, position), glyph_utf16_ix) in run
.glyphs() .glyphs()
@ -413,11 +413,11 @@ impl MacTextSystemState {
let typographic_bounds = line.get_typographic_bounds(); let typographic_bounds = line.get_typographic_bounds();
LineLayout { LineLayout {
runs,
font_size,
width: typographic_bounds.width.into(), width: typographic_bounds.width.into(),
ascent: typographic_bounds.ascent.into(), ascent: typographic_bounds.ascent.into(),
descent: typographic_bounds.descent.into(), descent: typographic_bounds.descent.into(),
runs,
font_size,
len: text.len(), len: text.len(),
} }
} }

View File

@ -1141,7 +1141,7 @@ extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
let event = unsafe { InputEvent::from_native(native_event, Some(window_height)) }; let event = unsafe { InputEvent::from_native(native_event, Some(window_height)) };
if let Some(mut event) = event { if let Some(mut event) = event {
let synthesized_second_event = match &mut event { match &mut event {
InputEvent::MouseDown( InputEvent::MouseDown(
event @ MouseDownEvent { event @ MouseDownEvent {
button: MouseButton::Left, button: MouseButton::Left,
@ -1149,6 +1149,7 @@ extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
.. ..
}, },
) => { ) => {
// On mac, a ctrl-left click should be handled as a right click.
*event = MouseDownEvent { *event = MouseDownEvent {
button: MouseButton::Right, button: MouseButton::Right,
modifiers: Modifiers { modifiers: Modifiers {
@ -1158,26 +1159,30 @@ extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
click_count: 1, click_count: 1,
..*event ..*event
}; };
Some(InputEvent::MouseDown(MouseDownEvent {
button: MouseButton::Right,
..*event
}))
} }
// Because we map a ctrl-left_down to a right_down -> right_up let's ignore // Because we map a ctrl-left_down to a right_down -> right_up let's ignore
// the ctrl-left_up to avoid having a mismatch in button down/up events if the // the ctrl-left_up to avoid having a mismatch in button down/up events if the
// user is still holding ctrl when releasing the left mouse button // user is still holding ctrl when releasing the left mouse button
InputEvent::MouseUp(MouseUpEvent { InputEvent::MouseUp(
button: MouseButton::Left, event @ MouseUpEvent {
modifiers: Modifiers { control: true, .. }, button: MouseButton::Left,
.. modifiers: Modifiers { control: true, .. },
}) => { ..
lock.synthetic_drag_counter += 1; },
return; ) => {
*event = MouseUpEvent {
button: MouseButton::Right,
modifiers: Modifiers {
control: false,
..event.modifiers
},
click_count: 1,
..*event
};
} }
_ => None, _ => {}
}; };
match &event { match &event {
@ -1227,9 +1232,6 @@ extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
if let Some(mut callback) = lock.event_callback.take() { if let Some(mut callback) = lock.event_callback.take() {
drop(lock); drop(lock);
callback(event); callback(event);
if let Some(event) = synthesized_second_event {
callback(event);
}
window_state.lock().event_callback = Some(callback); window_state.lock().event_callback = Some(callback);
} }
} }

View File

@ -1,7 +1,7 @@
use crate::PlatformDispatcher; use crate::{PlatformDispatcher, TaskLabel};
use async_task::Runnable; use async_task::Runnable;
use backtrace::Backtrace; use backtrace::Backtrace;
use collections::{HashMap, VecDeque}; use collections::{HashMap, HashSet, VecDeque};
use parking::{Parker, Unparker}; use parking::{Parker, Unparker};
use parking_lot::Mutex; use parking_lot::Mutex;
use rand::prelude::*; use rand::prelude::*;
@ -28,12 +28,14 @@ struct TestDispatcherState {
random: StdRng, random: StdRng,
foreground: HashMap<TestDispatcherId, VecDeque<Runnable>>, foreground: HashMap<TestDispatcherId, VecDeque<Runnable>>,
background: Vec<Runnable>, background: Vec<Runnable>,
deprioritized_background: Vec<Runnable>,
delayed: Vec<(Duration, Runnable)>, delayed: Vec<(Duration, Runnable)>,
time: Duration, time: Duration,
is_main_thread: bool, is_main_thread: bool,
next_id: TestDispatcherId, next_id: TestDispatcherId,
allow_parking: bool, allow_parking: bool,
waiting_backtrace: Option<Backtrace>, waiting_backtrace: Option<Backtrace>,
deprioritized_task_labels: HashSet<TaskLabel>,
} }
impl TestDispatcher { impl TestDispatcher {
@ -43,12 +45,14 @@ impl TestDispatcher {
random, random,
foreground: HashMap::default(), foreground: HashMap::default(),
background: Vec::new(), background: Vec::new(),
deprioritized_background: Vec::new(),
delayed: Vec::new(), delayed: Vec::new(),
time: Duration::ZERO, time: Duration::ZERO,
is_main_thread: true, is_main_thread: true,
next_id: TestDispatcherId(1), next_id: TestDispatcherId(1),
allow_parking: false, allow_parking: false,
waiting_backtrace: None, waiting_backtrace: None,
deprioritized_task_labels: Default::default(),
}; };
TestDispatcher { TestDispatcher {
@ -101,8 +105,15 @@ impl TestDispatcher {
} }
} }
pub fn deprioritize(&self, task_label: TaskLabel) {
self.state
.lock()
.deprioritized_task_labels
.insert(task_label);
}
pub fn run_until_parked(&self) { pub fn run_until_parked(&self) {
while self.poll(false) {} while self.tick(false) {}
} }
pub fn parking_allowed(&self) -> bool { pub fn parking_allowed(&self) -> bool {
@ -150,8 +161,17 @@ impl PlatformDispatcher for TestDispatcher {
self.state.lock().is_main_thread self.state.lock().is_main_thread
} }
fn dispatch(&self, runnable: Runnable) { fn dispatch(&self, runnable: Runnable, label: Option<TaskLabel>) {
self.state.lock().background.push(runnable); {
let mut state = self.state.lock();
if label.map_or(false, |label| {
state.deprioritized_task_labels.contains(&label)
}) {
state.deprioritized_background.push(runnable);
} else {
state.background.push(runnable);
}
}
self.unparker.unpark(); self.unparker.unpark();
} }
@ -174,7 +194,7 @@ impl PlatformDispatcher for TestDispatcher {
state.delayed.insert(ix, (next_time, runnable)); state.delayed.insert(ix, (next_time, runnable));
} }
fn poll(&self, background_only: bool) -> bool { fn tick(&self, background_only: bool) -> bool {
let mut state = self.state.lock(); let mut state = self.state.lock();
while let Some((deadline, _)) = state.delayed.first() { while let Some((deadline, _)) = state.delayed.first() {
@ -196,34 +216,41 @@ impl PlatformDispatcher for TestDispatcher {
}; };
let background_len = state.background.len(); let background_len = state.background.len();
let runnable;
let main_thread;
if foreground_len == 0 && background_len == 0 { if foreground_len == 0 && background_len == 0 {
return false; let deprioritized_background_len = state.deprioritized_background.len();
} if deprioritized_background_len == 0 {
return false;
let main_thread = state.random.gen_ratio( }
foreground_len as u32, let ix = state.random.gen_range(0..deprioritized_background_len);
(foreground_len + background_len) as u32, main_thread = false;
); runnable = state.deprioritized_background.swap_remove(ix);
let was_main_thread = state.is_main_thread;
state.is_main_thread = main_thread;
let runnable = if main_thread {
let state = &mut *state;
let runnables = state
.foreground
.values_mut()
.filter(|runnables| !runnables.is_empty())
.choose(&mut state.random)
.unwrap();
runnables.pop_front().unwrap()
} else { } else {
let ix = state.random.gen_range(0..background_len); main_thread = state.random.gen_ratio(
state.background.swap_remove(ix) foreground_len as u32,
(foreground_len + background_len) as u32,
);
if main_thread {
let state = &mut *state;
runnable = state
.foreground
.values_mut()
.filter(|runnables| !runnables.is_empty())
.choose(&mut state.random)
.unwrap()
.pop_front()
.unwrap();
} else {
let ix = state.random.gen_range(0..background_len);
runnable = state.background.swap_remove(ix);
};
}; };
let was_main_thread = state.is_main_thread;
state.is_main_thread = main_thread;
drop(state); drop(state);
runnable.run(); runnable.run();
self.state.lock().is_main_thread = was_main_thread; self.state.lock().is_main_thread = was_main_thread;
true true

View File

@ -203,6 +203,7 @@ impl TextStyle {
style: self.font_style, style: self.font_style,
}, },
color: self.color, color: self.color,
background_color: None,
underline: self.underline.clone(), underline: self.underline.clone(),
} }
} }

View File

@ -3,20 +3,20 @@ mod line;
mod line_layout; mod line_layout;
mod line_wrapper; mod line_wrapper;
use anyhow::anyhow;
pub use font_features::*; pub use font_features::*;
pub use line::*; pub use line::*;
pub use line_layout::*; pub use line_layout::*;
pub use line_wrapper::*; pub use line_wrapper::*;
use smallvec::SmallVec;
use crate::{ use crate::{
px, Bounds, DevicePixels, Hsla, Pixels, PlatformTextSystem, Point, Result, SharedString, Size, px, Bounds, DevicePixels, Hsla, Pixels, PlatformTextSystem, Point, Result, SharedString, Size,
UnderlineStyle, UnderlineStyle,
}; };
use anyhow::anyhow;
use collections::HashMap; use collections::HashMap;
use core::fmt; use core::fmt;
use parking_lot::{Mutex, RwLock, RwLockUpgradableReadGuard}; use parking_lot::{Mutex, RwLock, RwLockUpgradableReadGuard};
use smallvec::SmallVec;
use std::{ use std::{
cmp, cmp,
fmt::{Debug, Display, Formatter}, fmt::{Debug, Display, Formatter},
@ -151,13 +151,79 @@ impl TextSystem {
} }
} }
pub fn layout_text( pub fn layout_line(
&self, &self,
text: &str, text: &str,
font_size: Pixels, font_size: Pixels,
runs: &[TextRun], runs: &[TextRun],
) -> Result<Arc<LineLayout>> {
let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
for run in runs.iter() {
let font_id = self.font_id(&run.font)?;
if let Some(last_run) = font_runs.last_mut() {
if last_run.font_id == font_id {
last_run.len += run.len;
continue;
}
}
font_runs.push(FontRun {
len: run.len,
font_id,
});
}
let layout = self
.line_layout_cache
.layout_line(&text, font_size, &font_runs);
font_runs.clear();
self.font_runs_pool.lock().push(font_runs);
Ok(layout)
}
pub fn shape_line(
&self,
text: SharedString,
font_size: Pixels,
runs: &[TextRun],
) -> Result<ShapedLine> {
debug_assert!(
text.find('\n').is_none(),
"text argument should not contain newlines"
);
let mut decoration_runs = SmallVec::<[DecorationRun; 32]>::new();
for run in runs {
if let Some(last_run) = decoration_runs.last_mut() {
if last_run.color == run.color && last_run.underline == run.underline {
last_run.len += run.len as u32;
continue;
}
}
decoration_runs.push(DecorationRun {
len: run.len as u32,
color: run.color,
underline: run.underline.clone(),
});
}
let layout = self.layout_line(text.as_ref(), font_size, runs)?;
Ok(ShapedLine {
layout,
text,
decoration_runs,
})
}
pub fn shape_text(
&self,
text: &str, // todo!("pass a SharedString and preserve it when passed a single line?")
font_size: Pixels,
runs: &[TextRun],
wrap_width: Option<Pixels>, wrap_width: Option<Pixels>,
) -> Result<SmallVec<[Line; 1]>> { ) -> Result<SmallVec<[WrappedLine; 1]>> {
let mut runs = runs.iter().cloned().peekable(); let mut runs = runs.iter().cloned().peekable();
let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default(); let mut font_runs = self.font_runs_pool.lock().pop().unwrap_or_default();
@ -210,10 +276,11 @@ impl TextSystem {
let layout = self let layout = self
.line_layout_cache .line_layout_cache
.layout_line(&line_text, font_size, &font_runs, wrap_width); .layout_wrapped_line(&line_text, font_size, &font_runs, wrap_width);
lines.push(Line { lines.push(WrappedLine {
layout, layout,
decorations: decoration_runs, decoration_runs,
text: SharedString::from(line_text),
}); });
line_start = line_end + 1; // Skip `\n` character. line_start = line_end + 1; // Skip `\n` character.
@ -384,6 +451,7 @@ pub struct TextRun {
pub len: usize, pub len: usize,
pub font: Font, pub font: Font,
pub color: Hsla, pub color: Hsla,
pub background_color: Option<Hsla>,
pub underline: Option<UnderlineStyle>, pub underline: Option<UnderlineStyle>,
} }

View File

@ -1,5 +1,5 @@
use crate::{ use crate::{
black, point, px, size, BorrowWindow, Bounds, Hsla, Pixels, Point, Result, Size, black, point, px, BorrowWindow, Bounds, Hsla, LineLayout, Pixels, Point, Result, SharedString,
UnderlineStyle, WindowContext, WrapBoundary, WrappedLineLayout, UnderlineStyle, WindowContext, WrapBoundary, WrappedLineLayout,
}; };
use derive_more::{Deref, DerefMut}; use derive_more::{Deref, DerefMut};
@ -14,23 +14,17 @@ pub struct DecorationRun {
} }
#[derive(Clone, Default, Debug, Deref, DerefMut)] #[derive(Clone, Default, Debug, Deref, DerefMut)]
pub struct Line { pub struct ShapedLine {
#[deref] #[deref]
#[deref_mut] #[deref_mut]
pub(crate) layout: Arc<WrappedLineLayout>, pub(crate) layout: Arc<LineLayout>,
pub(crate) decorations: SmallVec<[DecorationRun; 32]>, pub text: SharedString,
pub(crate) decoration_runs: SmallVec<[DecorationRun; 32]>,
} }
impl Line { impl ShapedLine {
pub fn size(&self, line_height: Pixels) -> Size<Pixels> { pub fn len(&self) -> usize {
size( self.layout.len
self.layout.width,
line_height * (self.layout.wrap_boundaries.len() + 1),
)
}
pub fn wrap_count(&self) -> usize {
self.layout.wrap_boundaries.len()
} }
pub fn paint( pub fn paint(
@ -39,75 +33,84 @@ impl Line {
line_height: Pixels, line_height: Pixels,
cx: &mut WindowContext, cx: &mut WindowContext,
) -> Result<()> { ) -> Result<()> {
let padding_top = paint_line(
(line_height - self.layout.layout.ascent - self.layout.layout.descent) / 2.; origin,
let baseline_offset = point(px(0.), padding_top + self.layout.layout.ascent); &self.layout,
line_height,
&self.decoration_runs,
None,
&[],
cx,
)?;
let mut style_runs = self.decorations.iter(); Ok(())
let mut wraps = self.layout.wrap_boundaries.iter().peekable(); }
let mut run_end = 0; }
let mut color = black();
let mut current_underline: Option<(Point<Pixels>, UnderlineStyle)> = None;
let text_system = cx.text_system().clone();
let mut glyph_origin = origin; #[derive(Clone, Default, Debug, Deref, DerefMut)]
let mut prev_glyph_position = Point::default(); pub struct WrappedLine {
for (run_ix, run) in self.layout.layout.runs.iter().enumerate() { #[deref]
let max_glyph_size = text_system #[deref_mut]
.bounding_box(run.font_id, self.layout.layout.font_size)? pub(crate) layout: Arc<WrappedLineLayout>,
.size; pub text: SharedString,
pub(crate) decoration_runs: SmallVec<[DecorationRun; 32]>,
}
for (glyph_ix, glyph) in run.glyphs.iter().enumerate() { impl WrappedLine {
glyph_origin.x += glyph.position.x - prev_glyph_position.x; pub fn len(&self) -> usize {
self.layout.len()
}
if wraps.peek() == Some(&&WrapBoundary { run_ix, glyph_ix }) { pub fn paint(
wraps.next(); &self,
if let Some((underline_origin, underline_style)) = current_underline.take() { origin: Point<Pixels>,
cx.paint_underline( line_height: Pixels,
underline_origin, cx: &mut WindowContext,
glyph_origin.x - underline_origin.x, ) -> Result<()> {
&underline_style, paint_line(
)?; origin,
} &self.layout.unwrapped_layout,
line_height,
&self.decoration_runs,
self.wrap_width,
&self.wrap_boundaries,
cx,
)?;
glyph_origin.x = origin.x; Ok(())
glyph_origin.y += line_height; }
} }
prev_glyph_position = glyph.position;
let mut finished_underline: Option<(Point<Pixels>, UnderlineStyle)> = None; fn paint_line(
if glyph.index >= run_end { origin: Point<Pixels>,
if let Some(style_run) = style_runs.next() { layout: &LineLayout,
if let Some((_, underline_style)) = &mut current_underline { line_height: Pixels,
if style_run.underline.as_ref() != Some(underline_style) { decoration_runs: &[DecorationRun],
finished_underline = current_underline.take(); wrap_width: Option<Pixels>,
} wrap_boundaries: &[WrapBoundary],
} cx: &mut WindowContext<'_>,
if let Some(run_underline) = style_run.underline.as_ref() { ) -> Result<()> {
current_underline.get_or_insert(( let padding_top = (line_height - layout.ascent - layout.descent) / 2.;
point( let baseline_offset = point(px(0.), padding_top + layout.ascent);
glyph_origin.x, let mut decoration_runs = decoration_runs.iter();
origin.y let mut wraps = wrap_boundaries.iter().peekable();
+ baseline_offset.y let mut run_end = 0;
+ (self.layout.layout.descent * 0.618), let mut color = black();
), let mut current_underline: Option<(Point<Pixels>, UnderlineStyle)> = None;
UnderlineStyle { let text_system = cx.text_system().clone();
color: Some(run_underline.color.unwrap_or(style_run.color)), let mut glyph_origin = origin;
thickness: run_underline.thickness, let mut prev_glyph_position = Point::default();
wavy: run_underline.wavy, for (run_ix, run) in layout.runs.iter().enumerate() {
}, let max_glyph_size = text_system
)); .bounding_box(run.font_id, layout.font_size)?
} .size;
run_end += style_run.len as usize; for (glyph_ix, glyph) in run.glyphs.iter().enumerate() {
color = style_run.color; glyph_origin.x += glyph.position.x - prev_glyph_position.x;
} else {
run_end = self.layout.text.len();
finished_underline = current_underline.take();
}
}
if let Some((underline_origin, underline_style)) = finished_underline { if wraps.peek() == Some(&&WrapBoundary { run_ix, glyph_ix }) {
wraps.next();
if let Some((underline_origin, underline_style)) = current_underline.take() {
cx.paint_underline( cx.paint_underline(
underline_origin, underline_origin,
glyph_origin.x - underline_origin.x, glyph_origin.x - underline_origin.x,
@ -115,42 +118,84 @@ impl Line {
)?; )?;
} }
let max_glyph_bounds = Bounds { glyph_origin.x = origin.x;
origin: glyph_origin, glyph_origin.y += line_height;
size: max_glyph_size, }
}; prev_glyph_position = glyph.position;
let content_mask = cx.content_mask(); let mut finished_underline: Option<(Point<Pixels>, UnderlineStyle)> = None;
if max_glyph_bounds.intersects(&content_mask.bounds) { if glyph.index >= run_end {
if glyph.is_emoji { if let Some(style_run) = decoration_runs.next() {
cx.paint_emoji( if let Some((_, underline_style)) = &mut current_underline {
glyph_origin + baseline_offset, if style_run.underline.as_ref() != Some(underline_style) {
run.font_id, finished_underline = current_underline.take();
glyph.id, }
self.layout.layout.font_size,
)?;
} else {
cx.paint_glyph(
glyph_origin + baseline_offset,
run.font_id,
glyph.id,
self.layout.layout.font_size,
color,
)?;
} }
if let Some(run_underline) = style_run.underline.as_ref() {
current_underline.get_or_insert((
point(
glyph_origin.x,
origin.y + baseline_offset.y + (layout.descent * 0.618),
),
UnderlineStyle {
color: Some(run_underline.color.unwrap_or(style_run.color)),
thickness: run_underline.thickness,
wavy: run_underline.wavy,
},
));
}
run_end += style_run.len as usize;
color = style_run.color;
} else {
run_end = layout.len;
finished_underline = current_underline.take();
}
}
if let Some((underline_origin, underline_style)) = finished_underline {
cx.paint_underline(
underline_origin,
glyph_origin.x - underline_origin.x,
&underline_style,
)?;
}
let max_glyph_bounds = Bounds {
origin: glyph_origin,
size: max_glyph_size,
};
let content_mask = cx.content_mask();
if max_glyph_bounds.intersects(&content_mask.bounds) {
if glyph.is_emoji {
cx.paint_emoji(
glyph_origin + baseline_offset,
run.font_id,
glyph.id,
layout.font_size,
)?;
} else {
cx.paint_glyph(
glyph_origin + baseline_offset,
run.font_id,
glyph.id,
layout.font_size,
color,
)?;
} }
} }
} }
if let Some((underline_start, underline_style)) = current_underline.take() {
let line_end_x = origin.x + self.layout.layout.width;
cx.paint_underline(
underline_start,
line_end_x - underline_start.x,
&underline_style,
)?;
}
Ok(())
} }
if let Some((underline_start, underline_style)) = current_underline.take() {
let line_end_x = origin.x + wrap_width.unwrap_or(Pixels::MAX).min(layout.width);
cx.paint_underline(
underline_start,
line_end_x - underline_start.x,
&underline_style,
)?;
}
Ok(())
} }

View File

@ -1,5 +1,4 @@
use crate::{px, FontId, GlyphId, Pixels, PlatformTextSystem, Point, SharedString}; use crate::{px, FontId, GlyphId, Pixels, PlatformTextSystem, Point, Size};
use derive_more::{Deref, DerefMut};
use parking_lot::{Mutex, RwLock, RwLockUpgradableReadGuard}; use parking_lot::{Mutex, RwLock, RwLockUpgradableReadGuard};
use smallvec::SmallVec; use smallvec::SmallVec;
use std::{ use std::{
@ -149,13 +148,11 @@ impl LineLayout {
} }
} }
#[derive(Deref, DerefMut, Default, Debug)] #[derive(Default, Debug)]
pub struct WrappedLineLayout { pub struct WrappedLineLayout {
#[deref] pub unwrapped_layout: Arc<LineLayout>,
#[deref_mut]
pub layout: LineLayout,
pub text: SharedString,
pub wrap_boundaries: SmallVec<[WrapBoundary; 1]>, pub wrap_boundaries: SmallVec<[WrapBoundary; 1]>,
pub wrap_width: Option<Pixels>,
} }
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
@ -164,31 +161,74 @@ pub struct WrapBoundary {
pub glyph_ix: usize, pub glyph_ix: usize,
} }
impl WrappedLineLayout {
pub fn len(&self) -> usize {
self.unwrapped_layout.len
}
pub fn width(&self) -> Pixels {
self.wrap_width
.unwrap_or(Pixels::MAX)
.min(self.unwrapped_layout.width)
}
pub fn size(&self, line_height: Pixels) -> Size<Pixels> {
Size {
width: self.width(),
height: line_height * (self.wrap_boundaries.len() + 1),
}
}
pub fn ascent(&self) -> Pixels {
self.unwrapped_layout.ascent
}
pub fn descent(&self) -> Pixels {
self.unwrapped_layout.descent
}
pub fn wrap_boundaries(&self) -> &[WrapBoundary] {
&self.wrap_boundaries
}
pub fn font_size(&self) -> Pixels {
self.unwrapped_layout.font_size
}
pub fn runs(&self) -> &[ShapedRun] {
&self.unwrapped_layout.runs
}
}
pub(crate) struct LineLayoutCache { pub(crate) struct LineLayoutCache {
prev_frame: Mutex<HashMap<CacheKey, Arc<WrappedLineLayout>>>, previous_frame: Mutex<HashMap<CacheKey, Arc<LineLayout>>>,
curr_frame: RwLock<HashMap<CacheKey, Arc<WrappedLineLayout>>>, current_frame: RwLock<HashMap<CacheKey, Arc<LineLayout>>>,
previous_frame_wrapped: Mutex<HashMap<CacheKey, Arc<WrappedLineLayout>>>,
current_frame_wrapped: RwLock<HashMap<CacheKey, Arc<WrappedLineLayout>>>,
platform_text_system: Arc<dyn PlatformTextSystem>, platform_text_system: Arc<dyn PlatformTextSystem>,
} }
impl LineLayoutCache { impl LineLayoutCache {
pub fn new(platform_text_system: Arc<dyn PlatformTextSystem>) -> Self { pub fn new(platform_text_system: Arc<dyn PlatformTextSystem>) -> Self {
Self { Self {
prev_frame: Mutex::new(HashMap::new()), previous_frame: Mutex::default(),
curr_frame: RwLock::new(HashMap::new()), current_frame: RwLock::default(),
previous_frame_wrapped: Mutex::default(),
current_frame_wrapped: RwLock::default(),
platform_text_system, platform_text_system,
} }
} }
pub fn start_frame(&self) { pub fn start_frame(&self) {
let mut prev_frame = self.prev_frame.lock(); let mut prev_frame = self.previous_frame.lock();
let mut curr_frame = self.curr_frame.write(); let mut curr_frame = self.current_frame.write();
std::mem::swap(&mut *prev_frame, &mut *curr_frame); std::mem::swap(&mut *prev_frame, &mut *curr_frame);
curr_frame.clear(); curr_frame.clear();
} }
pub fn layout_line( pub fn layout_wrapped_line(
&self, &self,
text: &SharedString, text: &str,
font_size: Pixels, font_size: Pixels,
runs: &[FontRun], runs: &[FontRun],
wrap_width: Option<Pixels>, wrap_width: Option<Pixels>,
@ -199,34 +239,66 @@ impl LineLayoutCache {
runs, runs,
wrap_width, wrap_width,
} as &dyn AsCacheKeyRef; } as &dyn AsCacheKeyRef;
let curr_frame = self.curr_frame.upgradable_read();
if let Some(layout) = curr_frame.get(key) { let current_frame = self.current_frame_wrapped.upgradable_read();
if let Some(layout) = current_frame.get(key) {
return layout.clone(); return layout.clone();
} }
let mut curr_frame = RwLockUpgradableReadGuard::upgrade(curr_frame); let mut current_frame = RwLockUpgradableReadGuard::upgrade(current_frame);
if let Some((key, layout)) = self.prev_frame.lock().remove_entry(key) { if let Some((key, layout)) = self.previous_frame_wrapped.lock().remove_entry(key) {
curr_frame.insert(key, layout.clone()); current_frame.insert(key, layout.clone());
layout layout
} else { } else {
let layout = self.platform_text_system.layout_line(text, font_size, runs); let unwrapped_layout = self.layout_line(text, font_size, runs);
let wrap_boundaries = wrap_width let wrap_boundaries = if let Some(wrap_width) = wrap_width {
.map(|wrap_width| layout.compute_wrap_boundaries(text.as_ref(), wrap_width)) unwrapped_layout.compute_wrap_boundaries(text.as_ref(), wrap_width)
.unwrap_or_default(); } else {
let wrapped_line = Arc::new(WrappedLineLayout { SmallVec::new()
layout, };
text: text.clone(), let layout = Arc::new(WrappedLineLayout {
unwrapped_layout,
wrap_boundaries, wrap_boundaries,
wrap_width,
}); });
let key = CacheKey { let key = CacheKey {
text: text.clone(), text: text.into(),
font_size, font_size,
runs: SmallVec::from(runs), runs: SmallVec::from(runs),
wrap_width, wrap_width,
}; };
curr_frame.insert(key, wrapped_line.clone()); current_frame.insert(key, layout.clone());
wrapped_line layout
}
}
pub fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> Arc<LineLayout> {
let key = &CacheKeyRef {
text,
font_size,
runs,
wrap_width: None,
} as &dyn AsCacheKeyRef;
let current_frame = self.current_frame.upgradable_read();
if let Some(layout) = current_frame.get(key) {
return layout.clone();
}
let mut current_frame = RwLockUpgradableReadGuard::upgrade(current_frame);
if let Some((key, layout)) = self.previous_frame.lock().remove_entry(key) {
current_frame.insert(key, layout.clone());
layout
} else {
let layout = Arc::new(self.platform_text_system.layout_line(text, font_size, runs));
let key = CacheKey {
text: text.into(),
font_size,
runs: SmallVec::from(runs),
wrap_width: None,
};
current_frame.insert(key, layout.clone());
layout
} }
} }
} }
@ -243,7 +315,7 @@ trait AsCacheKeyRef {
#[derive(Eq)] #[derive(Eq)]
struct CacheKey { struct CacheKey {
text: SharedString, text: String,
font_size: Pixels, font_size: Pixels,
runs: SmallVec<[FontRun; 1]>, runs: SmallVec<[FontRun; 1]>,
wrap_width: Option<Pixels>, wrap_width: Option<Pixels>,

View File

@ -185,10 +185,27 @@ impl Drop for FocusHandle {
} }
} }
/// FocusableView allows users of your view to easily
/// focus it (using cx.focus_view(view))
pub trait FocusableView: Render { pub trait FocusableView: Render {
fn focus_handle(&self, cx: &AppContext) -> FocusHandle; fn focus_handle(&self, cx: &AppContext) -> FocusHandle;
} }
/// ManagedView is a view (like a Modal, Popover, Menu, etc.)
/// where the lifecycle of the view is handled by another view.
pub trait ManagedView: Render {
fn focus_handle(&self, cx: &AppContext) -> FocusHandle;
}
pub struct Dismiss;
impl<T: ManagedView> EventEmitter<Dismiss> for T {}
impl<T: ManagedView> FocusableView for T {
fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
self.focus_handle(cx)
}
}
// Holds the state for a specific window. // Holds the state for a specific window.
pub struct Window { pub struct Window {
pub(crate) handle: AnyWindowHandle, pub(crate) handle: AnyWindowHandle,
@ -311,8 +328,8 @@ impl Window {
layout_engine: TaffyLayoutEngine::new(), layout_engine: TaffyLayoutEngine::new(),
root_view: None, root_view: None,
element_id_stack: GlobalElementId::default(), element_id_stack: GlobalElementId::default(),
previous_frame: Frame::new(DispatchTree::new(cx.keymap.clone())), previous_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
current_frame: Frame::new(DispatchTree::new(cx.keymap.clone())), current_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
focus_handles: Arc::new(RwLock::new(SlotMap::with_key())), focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
focus_listeners: SubscriberSet::new(), focus_listeners: SubscriberSet::new(),
default_prevented: true, default_prevented: true,
@ -574,6 +591,7 @@ impl<'a> WindowContext<'a> {
result result
} }
#[must_use]
/// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
/// layout is being requested, along with the layout ids of any children. This method is called during /// layout is being requested, along with the layout ids of any children. This method is called during
/// calls to the `Element::layout` trait method and enables any element to participate in layout. /// calls to the `Element::layout` trait method and enables any element to participate in layout.
@ -1150,6 +1168,14 @@ impl<'a> WindowContext<'a> {
self.window.mouse_position = mouse_move.position; self.window.mouse_position = mouse_move.position;
InputEvent::MouseMove(mouse_move) InputEvent::MouseMove(mouse_move)
} }
InputEvent::MouseDown(mouse_down) => {
self.window.mouse_position = mouse_down.position;
InputEvent::MouseDown(mouse_down)
}
InputEvent::MouseUp(mouse_up) => {
self.window.mouse_position = mouse_up.position;
InputEvent::MouseUp(mouse_up)
}
// Translate dragging and dropping of external files from the operating system // Translate dragging and dropping of external files from the operating system
// to internal drag and drop events. // to internal drag and drop events.
InputEvent::FileDrop(file_drop) => match file_drop { InputEvent::FileDrop(file_drop) => match file_drop {

View File

@ -0,0 +1,45 @@
use serde_derive::Deserialize;
#[test]
fn test_derive() {
use gpui2 as gpui;
#[derive(PartialEq, Clone, Deserialize, gpui2_macros::Action)]
struct AnotherTestAction;
#[gpui2_macros::register_action]
#[derive(PartialEq, Clone, gpui::serde_derive::Deserialize)]
struct RegisterableAction {}
impl gpui::Action for RegisterableAction {
fn boxed_clone(&self) -> Box<dyn gpui::Action> {
todo!()
}
fn as_any(&self) -> &dyn std::any::Any {
todo!()
}
fn partial_eq(&self, _action: &dyn gpui::Action) -> bool {
todo!()
}
fn name(&self) -> &str {
todo!()
}
fn debug_name() -> &'static str
where
Self: Sized,
{
todo!()
}
fn build(_value: serde_json::Value) -> anyhow::Result<Box<dyn gpui::Action>>
where
Self: Sized,
{
todo!()
}
}
}

View File

@ -9,6 +9,6 @@ path = "src/gpui2_macros.rs"
proc-macro = true proc-macro = true
[dependencies] [dependencies]
syn = "1.0.72" syn = { version = "1.0.72", features = ["full"] }
quote = "1.0.9" quote = "1.0.9"
proc-macro2 = "1.0.66" proc-macro2 = "1.0.66"

View File

@ -15,48 +15,81 @@
use proc_macro::TokenStream; use proc_macro::TokenStream;
use quote::quote; use quote::quote;
use syn::{parse_macro_input, DeriveInput}; use syn::{parse_macro_input, DeriveInput, Error};
use crate::register_action::register_action;
pub fn action(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
pub fn action(_attr: TokenStream, item: TokenStream) -> TokenStream {
let input = parse_macro_input!(item as DeriveInput);
let name = &input.ident; let name = &input.ident;
let attrs = input
.attrs
.into_iter()
.filter(|attr| !attr.path.is_ident("action"))
.collect::<Vec<_>>();
let attributes = quote! { if input.generics.lt_token.is_some() {
#[gpui::register_action] return Error::new(name.span(), "Actions must be a concrete type")
#[derive(gpui::serde::Deserialize, std::cmp::PartialEq, std::clone::Clone, std::default::Default, std::fmt::Debug)] .into_compile_error()
#(#attrs)* .into();
}
let is_unit_struct = match input.data {
syn::Data::Struct(struct_data) => struct_data.fields.is_empty(),
syn::Data::Enum(_) => false,
syn::Data::Union(_) => false,
}; };
let visibility = input.vis;
let output = match input.data { let build_impl = if is_unit_struct {
syn::Data::Struct(ref struct_data) => match &struct_data.fields { quote! {
syn::Fields::Named(_) | syn::Fields::Unnamed(_) => { Ok(std::boxed::Box::new(Self {}))
let fields = &struct_data.fields; }
quote! { } else {
#attributes quote! {
#visibility struct #name #fields Ok(std::boxed::Box::new(gpui::serde_json::from_value::<Self>(value)?))
} }
};
let register_action = register_action(&name);
let output = quote! {
const _: fn() = || {
fn assert_impl<T: ?Sized + for<'a> gpui::serde::Deserialize<'a> + ::std::cmp::PartialEq + ::std::clone::Clone>() {}
assert_impl::<#name>();
};
impl gpui::Action for #name {
fn name(&self) -> &'static str
{
::std::any::type_name::<#name>()
} }
syn::Fields::Unit => {
quote! { fn debug_name() -> &'static str
#attributes where
#visibility struct #name; Self: ::std::marker::Sized
} {
::std::any::type_name::<#name>()
} }
},
syn::Data::Enum(ref enum_data) => { fn build(value: gpui::serde_json::Value) -> gpui::Result<::std::boxed::Box<dyn gpui::Action>>
let variants = &enum_data.variants; where
quote! { Self: ::std::marker::Sized {
#attributes #build_impl
#visibility enum #name { #variants } }
fn partial_eq(&self, action: &dyn gpui::Action) -> bool {
action
.as_any()
.downcast_ref::<Self>()
.map_or(false, |a| self == a)
}
fn boxed_clone(&self) -> std::boxed::Box<dyn gpui::Action> {
::std::boxed::Box::new(self.clone())
}
fn as_any(&self) -> &dyn ::std::any::Any {
self
} }
} }
_ => panic!("Expected a struct or an enum."),
#register_action
}; };
TokenStream::from(output) TokenStream::from(output)

View File

@ -11,14 +11,14 @@ pub fn style_helpers(args: TokenStream) -> TokenStream {
style_helpers::style_helpers(args) style_helpers::style_helpers(args)
} }
#[proc_macro_attribute] #[proc_macro_derive(Action)]
pub fn action(attr: TokenStream, item: TokenStream) -> TokenStream { pub fn action(input: TokenStream) -> TokenStream {
action::action(attr, item) action::action(input)
} }
#[proc_macro_attribute] #[proc_macro_attribute]
pub fn register_action(attr: TokenStream, item: TokenStream) -> TokenStream { pub fn register_action(attr: TokenStream, item: TokenStream) -> TokenStream {
register_action::register_action(attr, item) register_action::register_action_macro(attr, item)
} }
#[proc_macro_derive(Component, attributes(component))] #[proc_macro_derive(Component, attributes(component))]

View File

@ -12,22 +12,76 @@
// gpui2::register_action_builder::<Foo>() // gpui2::register_action_builder::<Foo>()
// } // }
use proc_macro::TokenStream; use proc_macro::TokenStream;
use proc_macro2::Ident;
use quote::{format_ident, quote}; use quote::{format_ident, quote};
use syn::{parse_macro_input, DeriveInput}; use syn::{parse_macro_input, DeriveInput, Error};
pub fn register_action(_attr: TokenStream, item: TokenStream) -> TokenStream { pub fn register_action_macro(_attr: TokenStream, item: TokenStream) -> TokenStream {
let input = parse_macro_input!(item as DeriveInput); let input = parse_macro_input!(item as DeriveInput);
let type_name = &input.ident; let registration = register_action(&input.ident);
let ctor_fn_name = format_ident!("register_{}_builder", type_name.to_string().to_lowercase());
let expanded = quote! { let has_action_derive = input
.attrs
.iter()
.find(|attr| {
(|| {
let meta = attr.parse_meta().ok()?;
meta.path().is_ident("derive").then(|| match meta {
syn::Meta::Path(_) => None,
syn::Meta::NameValue(_) => None,
syn::Meta::List(list) => list
.nested
.iter()
.find(|list| match list {
syn::NestedMeta::Meta(meta) => meta.path().is_ident("Action"),
syn::NestedMeta::Lit(_) => false,
})
.map(|_| true),
})?
})()
.unwrap_or(false)
})
.is_some();
if has_action_derive {
return Error::new(
input.ident.span(),
"The Action derive macro has already registered this action",
)
.into_compile_error()
.into();
}
TokenStream::from(quote! {
#input #input
#[allow(non_snake_case)]
#[gpui::ctor]
fn #ctor_fn_name() {
gpui::register_action::<#type_name>()
}
};
TokenStream::from(expanded) #registration
})
}
pub(crate) fn register_action(type_name: &Ident) -> proc_macro2::TokenStream {
let static_slice_name =
format_ident!("__GPUI_ACTIONS_{}", type_name.to_string().to_uppercase());
let action_builder_fn_name = format_ident!(
"__gpui_actions_builder_{}",
type_name.to_string().to_lowercase()
);
quote! {
#[doc(hidden)]
#[gpui::linkme::distributed_slice(gpui::__GPUI_ACTIONS)]
#[linkme(crate = gpui::linkme)]
static #static_slice_name: gpui::MacroActionBuilder = #action_builder_fn_name;
/// This is an auto generated function, do not use.
#[doc(hidden)]
fn #action_builder_fn_name() -> gpui::ActionData {
gpui::ActionData {
name: ::std::any::type_name::<#type_name>(),
type_id: ::std::any::TypeId::of::<#type_name>(),
build: <#type_name as gpui::Action>::build,
}
}
}
} }

View File

@ -17,7 +17,7 @@ use crate::{
}; };
use anyhow::{anyhow, Result}; use anyhow::{anyhow, Result};
pub use clock::ReplicaId; pub use clock::ReplicaId;
use futures::FutureExt as _; use futures::channel::oneshot;
use gpui::{fonts::HighlightStyle, AppContext, Entity, ModelContext, Task}; use gpui::{fonts::HighlightStyle, AppContext, Entity, ModelContext, Task};
use lsp::LanguageServerId; use lsp::LanguageServerId;
use parking_lot::Mutex; use parking_lot::Mutex;
@ -45,7 +45,7 @@ pub use text::{Buffer as TextBuffer, BufferSnapshot as TextBufferSnapshot, *};
use theme::SyntaxTheme; use theme::SyntaxTheme;
#[cfg(any(test, feature = "test-support"))] #[cfg(any(test, feature = "test-support"))]
use util::RandomCharIter; use util::RandomCharIter;
use util::{RangeExt, TryFutureExt as _}; use util::RangeExt;
#[cfg(any(test, feature = "test-support"))] #[cfg(any(test, feature = "test-support"))]
pub use {tree_sitter_rust, tree_sitter_typescript}; pub use {tree_sitter_rust, tree_sitter_typescript};
@ -62,6 +62,7 @@ pub struct Buffer {
saved_mtime: SystemTime, saved_mtime: SystemTime,
transaction_depth: usize, transaction_depth: usize,
was_dirty_before_starting_transaction: Option<bool>, was_dirty_before_starting_transaction: Option<bool>,
reload_task: Option<Task<Result<()>>>,
language: Option<Arc<Language>>, language: Option<Arc<Language>>,
autoindent_requests: Vec<Arc<AutoindentRequest>>, autoindent_requests: Vec<Arc<AutoindentRequest>>,
pending_autoindent: Option<Task<()>>, pending_autoindent: Option<Task<()>>,
@ -509,6 +510,7 @@ impl Buffer {
saved_mtime, saved_mtime,
saved_version: buffer.version(), saved_version: buffer.version(),
saved_version_fingerprint: buffer.as_rope().fingerprint(), saved_version_fingerprint: buffer.as_rope().fingerprint(),
reload_task: None,
transaction_depth: 0, transaction_depth: 0,
was_dirty_before_starting_transaction: None, was_dirty_before_starting_transaction: None,
text: buffer, text: buffer,
@ -608,37 +610,52 @@ impl Buffer {
cx.notify(); cx.notify();
} }
pub fn reload(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<Option<Transaction>>> { pub fn reload(
cx.spawn(|this, mut cx| async move { &mut self,
if let Some((new_mtime, new_text)) = this.read_with(&cx, |this, cx| { cx: &mut ModelContext<Self>,
) -> oneshot::Receiver<Option<Transaction>> {
let (tx, rx) = futures::channel::oneshot::channel();
let prev_version = self.text.version();
self.reload_task = Some(cx.spawn(|this, mut cx| async move {
let Some((new_mtime, new_text)) = this.update(&mut cx, |this, cx| {
let file = this.file.as_ref()?.as_local()?; let file = this.file.as_ref()?.as_local()?;
Some((file.mtime(), file.load(cx))) Some((file.mtime(), file.load(cx)))
}) { }) else {
let new_text = new_text.await?; return Ok(());
let diff = this };
.read_with(&cx, |this, cx| this.diff(new_text, cx))
.await; let new_text = new_text.await?;
this.update(&mut cx, |this, cx| { let diff = this
if this.version() == diff.base_version { .update(&mut cx, |this, cx| this.diff(new_text.clone(), cx))
this.finalize_last_transaction(); .await;
this.apply_diff(diff, cx); this.update(&mut cx, |this, cx| {
if let Some(transaction) = this.finalize_last_transaction().cloned() { if this.version() == diff.base_version {
this.did_reload( this.finalize_last_transaction();
this.version(), this.apply_diff(diff, cx);
this.as_rope().fingerprint(), tx.send(this.finalize_last_transaction().cloned()).ok();
this.line_ending(),
new_mtime, this.did_reload(
cx, this.version(),
); this.as_rope().fingerprint(),
return Ok(Some(transaction)); this.line_ending(),
} new_mtime,
} cx,
Ok(None) );
}) } else {
} else { this.did_reload(
Ok(None) prev_version,
} Rope::text_fingerprint(&new_text),
}) this.line_ending(),
this.saved_mtime,
cx,
);
}
this.reload_task.take();
});
Ok(())
}));
rx
} }
pub fn did_reload( pub fn did_reload(
@ -667,13 +684,8 @@ impl Buffer {
cx.notify(); cx.notify();
} }
pub fn file_updated( pub fn file_updated(&mut self, new_file: Arc<dyn File>, cx: &mut ModelContext<Self>) {
&mut self,
new_file: Arc<dyn File>,
cx: &mut ModelContext<Self>,
) -> Task<()> {
let mut file_changed = false; let mut file_changed = false;
let mut task = Task::ready(());
if let Some(old_file) = self.file.as_ref() { if let Some(old_file) = self.file.as_ref() {
if new_file.path() != old_file.path() { if new_file.path() != old_file.path() {
@ -693,8 +705,7 @@ impl Buffer {
file_changed = true; file_changed = true;
if !self.is_dirty() { if !self.is_dirty() {
let reload = self.reload(cx).log_err().map(drop); self.reload(cx).close();
task = cx.foreground().spawn(reload);
} }
} }
} }
@ -708,7 +719,6 @@ impl Buffer {
cx.emit(Event::FileHandleChanged); cx.emit(Event::FileHandleChanged);
cx.notify(); cx.notify();
} }
task
} }
pub fn diff_base(&self) -> Option<&str> { pub fn diff_base(&self) -> Option<&str> {

View File

@ -16,8 +16,9 @@ use crate::{
}; };
use anyhow::{anyhow, Result}; use anyhow::{anyhow, Result};
pub use clock::ReplicaId; pub use clock::ReplicaId;
use futures::FutureExt as _; use futures::channel::oneshot;
use gpui::{AppContext, EventEmitter, HighlightStyle, ModelContext, Task}; use gpui::{AppContext, EventEmitter, HighlightStyle, ModelContext, Task, TaskLabel};
use lazy_static::lazy_static;
use lsp::LanguageServerId; use lsp::LanguageServerId;
use parking_lot::Mutex; use parking_lot::Mutex;
use similar::{ChangeTag, TextDiff}; use similar::{ChangeTag, TextDiff};
@ -44,23 +45,33 @@ pub use text::{Buffer as TextBuffer, BufferSnapshot as TextBufferSnapshot, *};
use theme::SyntaxTheme; use theme::SyntaxTheme;
#[cfg(any(test, feature = "test-support"))] #[cfg(any(test, feature = "test-support"))]
use util::RandomCharIter; use util::RandomCharIter;
use util::{RangeExt, TryFutureExt as _}; use util::RangeExt;
#[cfg(any(test, feature = "test-support"))] #[cfg(any(test, feature = "test-support"))]
pub use {tree_sitter_rust, tree_sitter_typescript}; pub use {tree_sitter_rust, tree_sitter_typescript};
pub use lsp::DiagnosticSeverity; pub use lsp::DiagnosticSeverity;
lazy_static! {
pub static ref BUFFER_DIFF_TASK: TaskLabel = TaskLabel::new();
}
pub struct Buffer { pub struct Buffer {
text: TextBuffer, text: TextBuffer,
diff_base: Option<String>, diff_base: Option<String>,
git_diff: git::diff::BufferDiff, git_diff: git::diff::BufferDiff,
file: Option<Arc<dyn File>>, file: Option<Arc<dyn File>>,
saved_version: clock::Global, /// The mtime of the file when this buffer was last loaded from
saved_version_fingerprint: RopeFingerprint, /// or saved to disk.
saved_mtime: SystemTime, saved_mtime: SystemTime,
/// The version vector when this buffer was last loaded from
/// or saved to disk.
saved_version: clock::Global,
/// A hash of the current contents of the buffer's file.
file_fingerprint: RopeFingerprint,
transaction_depth: usize, transaction_depth: usize,
was_dirty_before_starting_transaction: Option<bool>, was_dirty_before_starting_transaction: Option<bool>,
reload_task: Option<Task<Result<()>>>,
language: Option<Arc<Language>>, language: Option<Arc<Language>>,
autoindent_requests: Vec<Arc<AutoindentRequest>>, autoindent_requests: Vec<Arc<AutoindentRequest>>,
pending_autoindent: Option<Task<()>>, pending_autoindent: Option<Task<()>>,
@ -380,8 +391,7 @@ impl Buffer {
.ok_or_else(|| anyhow!("missing line_ending"))?, .ok_or_else(|| anyhow!("missing line_ending"))?,
)); ));
this.saved_version = proto::deserialize_version(&message.saved_version); this.saved_version = proto::deserialize_version(&message.saved_version);
this.saved_version_fingerprint = this.file_fingerprint = proto::deserialize_fingerprint(&message.saved_version_fingerprint)?;
proto::deserialize_fingerprint(&message.saved_version_fingerprint)?;
this.saved_mtime = message this.saved_mtime = message
.saved_mtime .saved_mtime
.ok_or_else(|| anyhow!("invalid saved_mtime"))? .ok_or_else(|| anyhow!("invalid saved_mtime"))?
@ -397,7 +407,7 @@ impl Buffer {
diff_base: self.diff_base.as_ref().map(|h| h.to_string()), diff_base: self.diff_base.as_ref().map(|h| h.to_string()),
line_ending: proto::serialize_line_ending(self.line_ending()) as i32, line_ending: proto::serialize_line_ending(self.line_ending()) as i32,
saved_version: proto::serialize_version(&self.saved_version), saved_version: proto::serialize_version(&self.saved_version),
saved_version_fingerprint: proto::serialize_fingerprint(self.saved_version_fingerprint), saved_version_fingerprint: proto::serialize_fingerprint(self.file_fingerprint),
saved_mtime: Some(self.saved_mtime.into()), saved_mtime: Some(self.saved_mtime.into()),
} }
} }
@ -467,7 +477,8 @@ impl Buffer {
Self { Self {
saved_mtime, saved_mtime,
saved_version: buffer.version(), saved_version: buffer.version(),
saved_version_fingerprint: buffer.as_rope().fingerprint(), file_fingerprint: buffer.as_rope().fingerprint(),
reload_task: None,
transaction_depth: 0, transaction_depth: 0,
was_dirty_before_starting_transaction: None, was_dirty_before_starting_transaction: None,
text: buffer, text: buffer,
@ -533,7 +544,7 @@ impl Buffer {
} }
pub fn saved_version_fingerprint(&self) -> RopeFingerprint { pub fn saved_version_fingerprint(&self) -> RopeFingerprint {
self.saved_version_fingerprint self.file_fingerprint
} }
pub fn saved_mtime(&self) -> SystemTime { pub fn saved_mtime(&self) -> SystemTime {
@ -561,43 +572,58 @@ impl Buffer {
cx: &mut ModelContext<Self>, cx: &mut ModelContext<Self>,
) { ) {
self.saved_version = version; self.saved_version = version;
self.saved_version_fingerprint = fingerprint; self.file_fingerprint = fingerprint;
self.saved_mtime = mtime; self.saved_mtime = mtime;
cx.emit(Event::Saved); cx.emit(Event::Saved);
cx.notify(); cx.notify();
} }
pub fn reload(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<Option<Transaction>>> { pub fn reload(
cx.spawn(|this, mut cx| async move { &mut self,
if let Some((new_mtime, new_text)) = this.update(&mut cx, |this, cx| { cx: &mut ModelContext<Self>,
) -> oneshot::Receiver<Option<Transaction>> {
let (tx, rx) = futures::channel::oneshot::channel();
let prev_version = self.text.version();
self.reload_task = Some(cx.spawn(|this, mut cx| async move {
let Some((new_mtime, new_text)) = this.update(&mut cx, |this, cx| {
let file = this.file.as_ref()?.as_local()?; let file = this.file.as_ref()?.as_local()?;
Some((file.mtime(), file.load(cx))) Some((file.mtime(), file.load(cx)))
})? { })?
let new_text = new_text.await?; else {
let diff = this return Ok(());
.update(&mut cx, |this, cx| this.diff(new_text, cx))? };
.await;
this.update(&mut cx, |this, cx| { let new_text = new_text.await?;
if this.version() == diff.base_version { let diff = this
this.finalize_last_transaction(); .update(&mut cx, |this, cx| this.diff(new_text.clone(), cx))?
this.apply_diff(diff, cx); .await;
if let Some(transaction) = this.finalize_last_transaction().cloned() { this.update(&mut cx, |this, cx| {
this.did_reload( if this.version() == diff.base_version {
this.version(), this.finalize_last_transaction();
this.as_rope().fingerprint(), this.apply_diff(diff, cx);
this.line_ending(), tx.send(this.finalize_last_transaction().cloned()).ok();
new_mtime,
cx, this.did_reload(
); this.version(),
return Some(transaction); this.as_rope().fingerprint(),
} this.line_ending(),
} new_mtime,
None cx,
}) );
} else { } else {
Ok(None) this.did_reload(
} prev_version,
}) Rope::text_fingerprint(&new_text),
this.line_ending(),
this.saved_mtime,
cx,
);
}
this.reload_task.take();
})
}));
rx
} }
pub fn did_reload( pub fn did_reload(
@ -609,14 +635,14 @@ impl Buffer {
cx: &mut ModelContext<Self>, cx: &mut ModelContext<Self>,
) { ) {
self.saved_version = version; self.saved_version = version;
self.saved_version_fingerprint = fingerprint; self.file_fingerprint = fingerprint;
self.text.set_line_ending(line_ending); self.text.set_line_ending(line_ending);
self.saved_mtime = mtime; self.saved_mtime = mtime;
if let Some(file) = self.file.as_ref().and_then(|f| f.as_local()) { if let Some(file) = self.file.as_ref().and_then(|f| f.as_local()) {
file.buffer_reloaded( file.buffer_reloaded(
self.remote_id(), self.remote_id(),
&self.saved_version, &self.saved_version,
self.saved_version_fingerprint, self.file_fingerprint,
self.line_ending(), self.line_ending(),
self.saved_mtime, self.saved_mtime,
cx, cx,
@ -626,13 +652,8 @@ impl Buffer {
cx.notify(); cx.notify();
} }
pub fn file_updated( pub fn file_updated(&mut self, new_file: Arc<dyn File>, cx: &mut ModelContext<Self>) {
&mut self,
new_file: Arc<dyn File>,
cx: &mut ModelContext<Self>,
) -> Task<()> {
let mut file_changed = false; let mut file_changed = false;
let mut task = Task::ready(());
if let Some(old_file) = self.file.as_ref() { if let Some(old_file) = self.file.as_ref() {
if new_file.path() != old_file.path() { if new_file.path() != old_file.path() {
@ -652,8 +673,7 @@ impl Buffer {
file_changed = true; file_changed = true;
if !self.is_dirty() { if !self.is_dirty() {
let reload = self.reload(cx).log_err().map(drop); self.reload(cx).close();
task = cx.background_executor().spawn(reload);
} }
} }
} }
@ -667,7 +687,6 @@ impl Buffer {
cx.emit(Event::FileHandleChanged); cx.emit(Event::FileHandleChanged);
cx.notify(); cx.notify();
} }
task
} }
pub fn diff_base(&self) -> Option<&str> { pub fn diff_base(&self) -> Option<&str> {
@ -1118,36 +1137,72 @@ impl Buffer {
pub fn diff(&self, mut new_text: String, cx: &AppContext) -> Task<Diff> { pub fn diff(&self, mut new_text: String, cx: &AppContext) -> Task<Diff> {
let old_text = self.as_rope().clone(); let old_text = self.as_rope().clone();
let base_version = self.version(); let base_version = self.version();
cx.background_executor().spawn(async move { cx.background_executor()
let old_text = old_text.to_string(); .spawn_labeled(*BUFFER_DIFF_TASK, async move {
let line_ending = LineEnding::detect(&new_text); let old_text = old_text.to_string();
LineEnding::normalize(&mut new_text); let line_ending = LineEnding::detect(&new_text);
let diff = TextDiff::from_chars(old_text.as_str(), new_text.as_str()); LineEnding::normalize(&mut new_text);
let mut edits = Vec::new();
let mut offset = 0; let diff = TextDiff::from_chars(old_text.as_str(), new_text.as_str());
let empty: Arc<str> = "".into(); let empty: Arc<str> = "".into();
for change in diff.iter_all_changes() {
let value = change.value(); let mut edits = Vec::new();
let end_offset = offset + value.len(); let mut old_offset = 0;
match change.tag() { let mut new_offset = 0;
ChangeTag::Equal => { let mut last_edit: Option<(Range<usize>, Range<usize>)> = None;
offset = end_offset; for change in diff.iter_all_changes().map(Some).chain([None]) {
if let Some(change) = &change {
let len = change.value().len();
match change.tag() {
ChangeTag::Equal => {
old_offset += len;
new_offset += len;
}
ChangeTag::Delete => {
let old_end_offset = old_offset + len;
if let Some((last_old_range, _)) = &mut last_edit {
last_old_range.end = old_end_offset;
} else {
last_edit =
Some((old_offset..old_end_offset, new_offset..new_offset));
}
old_offset = old_end_offset;
}
ChangeTag::Insert => {
let new_end_offset = new_offset + len;
if let Some((_, last_new_range)) = &mut last_edit {
last_new_range.end = new_end_offset;
} else {
last_edit =
Some((old_offset..old_offset, new_offset..new_end_offset));
}
new_offset = new_end_offset;
}
}
} }
ChangeTag::Delete => {
edits.push((offset..end_offset, empty.clone())); if let Some((old_range, new_range)) = &last_edit {
offset = end_offset; if old_offset > old_range.end
} || new_offset > new_range.end
ChangeTag::Insert => { || change.is_none()
edits.push((offset..offset, value.into())); {
let text = if new_range.is_empty() {
empty.clone()
} else {
new_text[new_range.clone()].into()
};
edits.push((old_range.clone(), text));
last_edit.take();
}
} }
} }
}
Diff { Diff {
base_version, base_version,
line_ending, line_ending,
edits, edits,
} }
}) })
} }
/// Spawn a background task that searches the buffer for any whitespace /// Spawn a background task that searches the buffer for any whitespace
@ -1231,12 +1286,12 @@ impl Buffer {
} }
pub fn is_dirty(&self) -> bool { pub fn is_dirty(&self) -> bool {
self.saved_version_fingerprint != self.as_rope().fingerprint() self.file_fingerprint != self.as_rope().fingerprint()
|| self.file.as_ref().map_or(false, |file| file.is_deleted()) || self.file.as_ref().map_or(false, |file| file.is_deleted())
} }
pub fn has_conflict(&self) -> bool { pub fn has_conflict(&self) -> bool {
self.saved_version_fingerprint != self.as_rope().fingerprint() self.file_fingerprint != self.as_rope().fingerprint()
&& self && self
.file .file
.as_ref() .as_ref()

View File

@ -10,7 +10,7 @@ path = "src/live_kit_client2.rs"
doctest = false doctest = false
[[example]] [[example]]
name = "test_app" name = "test_app2"
[features] [features]
test-support = [ test-support = [

View File

@ -1,7 +1,7 @@
use std::{sync::Arc, time::Duration}; use std::{sync::Arc, time::Duration};
use futures::StreamExt; use futures::StreamExt;
use gpui::KeyBinding; use gpui::{Action, KeyBinding};
use live_kit_client2::{ use live_kit_client2::{
LocalAudioTrack, LocalVideoTrack, RemoteAudioTrackUpdate, RemoteVideoTrackUpdate, Room, LocalAudioTrack, LocalVideoTrack, RemoteAudioTrackUpdate, RemoteVideoTrackUpdate, Room,
}; };
@ -10,7 +10,7 @@ use log::LevelFilter;
use serde_derive::Deserialize; use serde_derive::Deserialize;
use simplelog::SimpleLogger; use simplelog::SimpleLogger;
#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default)] #[derive(Deserialize, Debug, Clone, Copy, PartialEq, Action)]
struct Quit; struct Quit;
fn main() { fn main() {

View File

@ -1,7 +1,7 @@
use editor::Editor; use editor::Editor;
use gpui::{ use gpui::{
div, prelude::*, uniform_list, Component, Div, MouseButton, Render, Task, div, prelude::*, uniform_list, AppContext, Component, Div, FocusHandle, FocusableView,
UniformListScrollHandle, View, ViewContext, WindowContext, MouseButton, Render, Task, UniformListScrollHandle, View, ViewContext, WindowContext,
}; };
use std::{cmp, sync::Arc}; use std::{cmp, sync::Arc};
use ui::{prelude::*, v_stack, Divider, Label, TextColor}; use ui::{prelude::*, v_stack, Divider, Label, TextColor};
@ -35,6 +35,12 @@ pub trait PickerDelegate: Sized + 'static {
) -> Self::ListItem; ) -> Self::ListItem;
} }
impl<D: PickerDelegate> FocusableView for Picker<D> {
fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
self.editor.focus_handle(cx)
}
}
impl<D: PickerDelegate> Picker<D> { impl<D: PickerDelegate> Picker<D> {
pub fn new(delegate: D, cx: &mut ViewContext<Self>) -> Self { pub fn new(delegate: D, cx: &mut ViewContext<Self>) -> Self {
let editor = cx.build_view(|cx| { let editor = cx.build_view(|cx| {

View File

@ -6190,7 +6190,7 @@ impl Project {
.log_err(); .log_err();
} }
buffer.file_updated(Arc::new(new_file), cx).detach(); buffer.file_updated(Arc::new(new_file), cx);
} }
} }
}); });
@ -7182,7 +7182,7 @@ impl Project {
.ok_or_else(|| anyhow!("no such worktree"))?; .ok_or_else(|| anyhow!("no such worktree"))?;
let file = File::from_proto(file, worktree, cx)?; let file = File::from_proto(file, worktree, cx)?;
buffer.update(cx, |buffer, cx| { buffer.update(cx, |buffer, cx| {
buffer.file_updated(Arc::new(file), cx).detach(); buffer.file_updated(Arc::new(file), cx);
}); });
this.detect_language_for_buffer(&buffer, cx); this.detect_language_for_buffer(&buffer, cx);
} }

View File

@ -959,7 +959,7 @@ impl LocalWorktree {
buffer_handle.update(&mut cx, |buffer, cx| { buffer_handle.update(&mut cx, |buffer, cx| {
if has_changed_file { if has_changed_file {
buffer.file_updated(new_file, cx).detach(); buffer.file_updated(new_file, cx);
} }
}); });
} }

View File

@ -6262,7 +6262,7 @@ impl Project {
.log_err(); .log_err();
} }
buffer.file_updated(Arc::new(new_file), cx).detach(); buffer.file_updated(Arc::new(new_file), cx);
} }
} }
}); });
@ -7256,7 +7256,7 @@ impl Project {
.ok_or_else(|| anyhow!("no such worktree"))?; .ok_or_else(|| anyhow!("no such worktree"))?;
let file = File::from_proto(file, worktree, cx)?; let file = File::from_proto(file, worktree, cx)?;
buffer.update(cx, |buffer, cx| { buffer.update(cx, |buffer, cx| {
buffer.file_updated(Arc::new(file), cx).detach(); buffer.file_updated(Arc::new(file), cx);
}); });
this.detect_language_for_buffer(&buffer, cx); this.detect_language_for_buffer(&buffer, cx);
} }

View File

@ -2587,6 +2587,73 @@ async fn test_save_file(cx: &mut gpui::TestAppContext) {
assert_eq!(new_text, buffer.update(cx, |buffer, _| buffer.text())); assert_eq!(new_text, buffer.update(cx, |buffer, _| buffer.text()));
} }
#[gpui::test(iterations = 30)]
async fn test_file_changes_multiple_times_on_disk(cx: &mut gpui::TestAppContext) {
init_test(cx);
let fs = FakeFs::new(cx.executor().clone());
fs.insert_tree(
"/dir",
json!({
"file1": "the original contents",
}),
)
.await;
let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
let worktree = project.read_with(cx, |project, _| project.worktrees().next().unwrap());
let buffer = project
.update(cx, |p, cx| p.open_local_buffer("/dir/file1", cx))
.await
.unwrap();
// Simulate buffer diffs being slow, so that they don't complete before
// the next file change occurs.
cx.executor().deprioritize(*language::BUFFER_DIFF_TASK);
// Change the buffer's file on disk, and then wait for the file change
// to be detected by the worktree, so that the buffer starts reloading.
fs.save(
"/dir/file1".as_ref(),
&"the first contents".into(),
Default::default(),
)
.await
.unwrap();
worktree.next_event(cx);
// Change the buffer's file again. Depending on the random seed, the
// previous file change may still be in progress.
fs.save(
"/dir/file1".as_ref(),
&"the second contents".into(),
Default::default(),
)
.await
.unwrap();
worktree.next_event(cx);
cx.executor().run_until_parked();
let on_disk_text = fs.load(Path::new("/dir/file1")).await.unwrap();
buffer.read_with(cx, |buffer, _| {
let buffer_text = buffer.text();
if buffer_text == on_disk_text {
assert!(
!buffer.is_dirty() && !buffer.has_conflict(),
"buffer shouldn't be dirty. text: {buffer_text:?}, disk text: {on_disk_text:?}",
);
}
// If the file change occurred while the buffer was processing the first
// change, the buffer will be in a conflicting state.
else {
assert!(
buffer.is_dirty() && buffer.has_conflict(),
"buffer should report that it has a conflict. text: {buffer_text:?}, disk text: {on_disk_text:?}"
);
}
});
}
#[gpui::test] #[gpui::test]
async fn test_save_in_single_file_worktree(cx: &mut gpui::TestAppContext) { async fn test_save_in_single_file_worktree(cx: &mut gpui::TestAppContext) {
init_test(cx); init_test(cx);

View File

@ -276,6 +276,7 @@ struct ShareState {
_maintain_remote_snapshot: Task<Option<()>>, _maintain_remote_snapshot: Task<Option<()>>,
} }
#[derive(Clone)]
pub enum Event { pub enum Event {
UpdatedEntries(UpdatedEntriesSet), UpdatedEntries(UpdatedEntriesSet),
UpdatedGitRepositories(UpdatedGitRepositoriesSet), UpdatedGitRepositories(UpdatedGitRepositoriesSet),
@ -961,7 +962,7 @@ impl LocalWorktree {
buffer_handle.update(&mut cx, |buffer, cx| { buffer_handle.update(&mut cx, |buffer, cx| {
if has_changed_file { if has_changed_file {
buffer.file_updated(new_file, cx).detach(); buffer.file_updated(new_file, cx);
} }
})?; })?;
} }

View File

@ -1579,7 +1579,7 @@ mod tests {
path::{Path, PathBuf}, path::{Path, PathBuf},
sync::atomic::{self, AtomicUsize}, sync::atomic::{self, AtomicUsize},
}; };
use workspace::{pane, AppState}; use workspace::AppState;
#[gpui::test] #[gpui::test]
async fn test_visible_list(cx: &mut gpui::TestAppContext) { async fn test_visible_list(cx: &mut gpui::TestAppContext) {
@ -2785,7 +2785,7 @@ mod tests {
let settings_store = SettingsStore::test(cx); let settings_store = SettingsStore::test(cx);
cx.set_global(settings_store); cx.set_global(settings_store);
init_settings(cx); init_settings(cx);
theme::init(cx); theme::init(theme::LoadThemes::JustBase, cx);
language::init(cx); language::init(cx);
editor::init_settings(cx); editor::init_settings(cx);
crate::init((), cx); crate::init((), cx);
@ -2798,11 +2798,10 @@ mod tests {
fn init_test_with_editor(cx: &mut TestAppContext) { fn init_test_with_editor(cx: &mut TestAppContext) {
cx.update(|cx| { cx.update(|cx| {
let app_state = AppState::test(cx); let app_state = AppState::test(cx);
theme::init(cx); theme::init(theme::LoadThemes::JustBase, cx);
init_settings(cx); init_settings(cx);
language::init(cx); language::init(cx);
editor::init(cx); editor::init(cx);
pane::init(cx);
crate::init((), cx); crate::init((), cx);
workspace::init(app_state.clone(), cx); workspace::init(app_state.clone(), cx);
Project::init_settings(cx); Project::init_settings(cx);

View File

@ -41,6 +41,10 @@ impl Rope {
Self::default() Self::default()
} }
pub fn text_fingerprint(text: &str) -> RopeFingerprint {
bromberg_sl2::hash_strict(text.as_bytes())
}
pub fn append(&mut self, rope: Rope) { pub fn append(&mut self, rope: Rope) {
let mut chunks = rope.chunks.cursor::<()>(); let mut chunks = rope.chunks.cursor::<()>();
chunks.next(&()); chunks.next(&());
@ -931,7 +935,7 @@ impl<'a> From<&'a str> for ChunkSummary {
fn from(text: &'a str) -> Self { fn from(text: &'a str) -> Self {
Self { Self {
text: TextSummary::from(text), text: TextSummary::from(text),
fingerprint: bromberg_sl2::hash_strict(text.as_bytes()), fingerprint: Rope::text_fingerprint(text),
} }
} }
} }

View File

@ -41,6 +41,10 @@ impl Rope {
Self::default() Self::default()
} }
pub fn text_fingerprint(text: &str) -> RopeFingerprint {
bromberg_sl2::hash_strict(text.as_bytes())
}
pub fn append(&mut self, rope: Rope) { pub fn append(&mut self, rope: Rope) {
let mut chunks = rope.chunks.cursor::<()>(); let mut chunks = rope.chunks.cursor::<()>();
chunks.next(&()); chunks.next(&());
@ -931,7 +935,7 @@ impl<'a> From<&'a str> for ChunkSummary {
fn from(text: &'a str) -> Self { fn from(text: &'a str) -> Self {
Self { Self {
text: TextSummary::from(text), text: TextSummary::from(text),
fingerprint: bromberg_sl2::hash_strict(text.as_bytes()), fingerprint: Rope::text_fingerprint(text),
} }
} }
} }

View File

@ -73,9 +73,9 @@ impl KeymapFile {
"Expected first item in array to be a string." "Expected first item in array to be a string."
))); )));
}; };
gpui::build_action(&name, Some(data)) cx.build_action(&name, Some(data))
} }
Value::String(name) => gpui::build_action(&name, None), Value::String(name) => cx.build_action(&name, None),
Value::Null => Ok(no_action()), Value::Null => Ok(no_action()),
_ => { _ => {
return Some(Err(anyhow!("Expected two-element array, got {action:?}"))) return Some(Err(anyhow!("Expected two-element array, got {action:?}")))

View File

@ -16,6 +16,9 @@ pub fn test_settings() -> String {
.unwrap(); .unwrap();
util::merge_non_null_json_value_into( util::merge_non_null_json_value_into(
serde_json::json!({ serde_json::json!({
"ui_font_family": "Courier",
"ui_font_features": {},
"ui_font_size": 14,
"buffer_font_family": "Courier", "buffer_font_family": "Courier",
"buffer_font_features": {}, "buffer_font_features": {},
"buffer_font_size": 14, "buffer_font_size": 14,

View File

@ -60,13 +60,12 @@ fn main() {
.unwrap(); .unwrap();
cx.set_global(store); cx.set_global(store);
theme2::init(cx); theme2::init(theme2::LoadThemes::All, cx);
let selector = let selector =
story_selector.unwrap_or(StorySelector::Component(ComponentStory::Workspace)); story_selector.unwrap_or(StorySelector::Component(ComponentStory::Workspace));
let theme_registry = cx.global::<ThemeRegistry>(); let theme_registry = cx.global::<ThemeRegistry>();
let mut theme_settings = ThemeSettings::get_global(cx).clone(); let mut theme_settings = ThemeSettings::get_global(cx).clone();
theme_settings.active_theme = theme_registry.get(&theme_name).unwrap(); theme_settings.active_theme = theme_registry.get(&theme_name).unwrap();
ThemeSettings::override_global(theme_settings, cx); ThemeSettings::override_global(theme_settings, cx);
@ -114,6 +113,7 @@ impl Render for StoryWrapper {
.flex() .flex()
.flex_col() .flex_col()
.size_full() .size_full()
.font("Zed Mono")
.child(self.story.clone()) .child(self.story.clone())
} }
} }

View File

@ -0,0 +1,17 @@
[package]
name = "storybook3"
version = "0.1.0"
edition = "2021"
publish = false
[[bin]]
name = "storybook"
path = "src/storybook3.rs"
[dependencies]
anyhow.workspace = true
gpui = { package = "gpui2", path = "../gpui2" }
ui = { package = "ui2", path = "../ui2", features = ["stories"] }
theme = { package = "theme2", path = "../theme2", features = ["stories"] }
settings = { package = "settings2", path = "../settings2"}

View File

@ -0,0 +1,73 @@
use anyhow::Result;
use gpui::AssetSource;
use gpui::{
div, px, size, AnyView, Bounds, Div, Render, ViewContext, VisualContext, WindowBounds,
WindowOptions,
};
use settings::{default_settings, Settings, SettingsStore};
use std::borrow::Cow;
use std::sync::Arc;
use theme::ThemeSettings;
use ui::{prelude::*, ContextMenuStory};
struct Assets;
impl AssetSource for Assets {
fn load(&self, _path: &str) -> Result<Cow<[u8]>> {
todo!();
}
fn list(&self, _path: &str) -> Result<Vec<SharedString>> {
Ok(vec![])
}
}
fn main() {
let asset_source = Arc::new(Assets);
gpui::App::production(asset_source).run(move |cx| {
let mut store = SettingsStore::default();
store
.set_default_settings(default_settings().as_ref(), cx)
.unwrap();
cx.set_global(store);
ui::settings::init(cx);
theme::init(theme::LoadThemes::JustBase, cx);
cx.open_window(
WindowOptions {
bounds: WindowBounds::Fixed(Bounds {
origin: Default::default(),
size: size(px(1500.), px(780.)).into(),
}),
..Default::default()
},
move |cx| {
let ui_font_size = ThemeSettings::get_global(cx).ui_font_size;
cx.set_rem_size(ui_font_size);
cx.build_view(|cx| TestView {
story: cx.build_view(|_| ContextMenuStory).into(),
})
},
);
cx.activate(true);
})
}
struct TestView {
story: AnyView,
}
impl Render for TestView {
type Element = Div<Self>;
fn render(&mut self, _cx: &mut ViewContext<Self>) -> Self::Element {
div()
.flex()
.flex_col()
.size_full()
.font("Helvetica")
.child(self.story.clone())
}
}

View File

@ -304,13 +304,13 @@ impl TerminalPanel {
.pane .pane
.read(cx) .read(cx)
.items() .items()
.map(|item| item.id().as_u64()) .map(|item| item.item_id().as_u64())
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let active_item_id = self let active_item_id = self
.pane .pane
.read(cx) .read(cx)
.active_item() .active_item()
.map(|item| item.id().as_u64()); .map(|item| item.item_id().as_u64());
let height = self.height; let height = self.height;
let width = self.width; let width = self.width;
self.pending_serialization = cx.background_executor().spawn( self.pending_serialization = cx.background_executor().spawn(

View File

@ -9,7 +9,7 @@ pub mod terminal_panel;
// use crate::terminal_element::TerminalElement; // use crate::terminal_element::TerminalElement;
use editor::{scroll::autoscroll::Autoscroll, Editor}; use editor::{scroll::autoscroll::Autoscroll, Editor};
use gpui::{ use gpui::{
actions, div, img, red, register_action, AnyElement, AppContext, Component, DispatchPhase, Div, actions, div, img, red, Action, AnyElement, AppContext, Component, DispatchPhase, Div,
EventEmitter, FocusEvent, FocusHandle, Focusable, FocusableComponent, FocusableView, EventEmitter, FocusEvent, FocusHandle, Focusable, FocusableComponent, FocusableView,
InputHandler, InteractiveComponent, KeyDownEvent, Keystroke, Model, MouseButton, InputHandler, InteractiveComponent, KeyDownEvent, Keystroke, Model, MouseButton,
ParentComponent, Pixels, Render, SharedString, Styled, Task, View, ViewContext, VisualContext, ParentComponent, Pixels, Render, SharedString, Styled, Task, View, ViewContext, VisualContext,
@ -32,7 +32,7 @@ use workspace::{
notifications::NotifyResultExt, notifications::NotifyResultExt,
register_deserializable_item, register_deserializable_item,
searchable::{SearchEvent, SearchOptions, SearchableItem}, searchable::{SearchEvent, SearchOptions, SearchableItem},
ui::{ContextMenu, ContextMenuItem, Label}, ui::{ContextMenu, Label},
CloseActiveItem, NewCenterTerminal, Pane, ToolbarItemLocation, Workspace, WorkspaceId, CloseActiveItem, NewCenterTerminal, Pane, ToolbarItemLocation, Workspace, WorkspaceId,
}; };
@ -55,12 +55,10 @@ const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
pub struct ScrollTerminal(pub i32); pub struct ScrollTerminal(pub i32);
#[register_action] #[derive(Clone, Debug, Default, Deserialize, PartialEq, Action)]
#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
pub struct SendText(String); pub struct SendText(String);
#[register_action] #[derive(Clone, Debug, Default, Deserialize, PartialEq, Action)]
#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
pub struct SendKeystroke(String); pub struct SendKeystroke(String);
actions!(Clear, Copy, Paste, ShowCharacterPalette, SearchTest); actions!(Clear, Copy, Paste, ShowCharacterPalette, SearchTest);
@ -87,7 +85,7 @@ pub struct TerminalView {
has_new_content: bool, has_new_content: bool,
//Currently using iTerm bell, show bell emoji in tab until input is received //Currently using iTerm bell, show bell emoji in tab until input is received
has_bell: bool, has_bell: bool,
context_menu: Option<ContextMenu>, context_menu: Option<View<ContextMenu>>,
blink_state: bool, blink_state: bool,
blinking_on: bool, blinking_on: bool,
blinking_paused: bool, blinking_paused: bool,
@ -302,10 +300,14 @@ impl TerminalView {
position: gpui::Point<Pixels>, position: gpui::Point<Pixels>,
cx: &mut ViewContext<Self>, cx: &mut ViewContext<Self>,
) { ) {
self.context_menu = Some(ContextMenu::new(vec![ self.context_menu = Some(cx.build_view(|cx| {
ContextMenuItem::entry(Label::new("Clear"), Clear), ContextMenu::new(cx)
ContextMenuItem::entry(Label::new("Close"), CloseActiveItem { save_intent: None }), .entry(Label::new("Clear"), Box::new(Clear))
])); .entry(
Label::new("Close"),
Box::new(CloseActiveItem { save_intent: None }),
)
}));
dbg!(&position); dbg!(&position);
// todo!() // todo!()
// self.context_menu // self.context_menu
@ -1126,7 +1128,7 @@ mod tests {
pub async fn init_test(cx: &mut TestAppContext) -> (Model<Project>, View<Workspace>) { pub async fn init_test(cx: &mut TestAppContext) -> (Model<Project>, View<Workspace>) {
let params = cx.update(AppState::test); let params = cx.update(AppState::test);
cx.update(|cx| { cx.update(|cx| {
theme::init(cx); theme::init(theme::LoadThemes::JustBase, cx);
Project::init_settings(cx); Project::init_settings(cx);
language::init(cx); language::init(cx);
}); });

View File

@ -100,6 +100,11 @@ impl ThemeRegistry {
.ok_or_else(|| anyhow!("theme not found: {}", name)) .ok_or_else(|| anyhow!("theme not found: {}", name))
.cloned() .cloned()
} }
pub fn load_user_themes(&mut self) {
#[cfg(not(feature = "importing-themes"))]
self.insert_user_theme_familes(crate::all_user_themes());
}
} }
impl Default for ThemeRegistry { impl Default for ThemeRegistry {
@ -110,9 +115,6 @@ impl Default for ThemeRegistry {
this.insert_theme_families([one_family()]); this.insert_theme_families([one_family()]);
#[cfg(not(feature = "importing-themes"))]
this.insert_user_theme_familes(crate::all_user_themes());
this this
} }
} }

View File

@ -34,6 +34,10 @@ pub struct ThemeSettingsContent {
#[serde(default)] #[serde(default)]
pub ui_font_size: Option<f32>, pub ui_font_size: Option<f32>,
#[serde(default)] #[serde(default)]
pub ui_font_family: Option<String>,
#[serde(default)]
pub ui_font_features: Option<FontFeatures>,
#[serde(default)]
pub buffer_font_family: Option<String>, pub buffer_font_family: Option<String>,
#[serde(default)] #[serde(default)]
pub buffer_font_size: Option<f32>, pub buffer_font_size: Option<f32>,
@ -117,13 +121,13 @@ impl settings::Settings for ThemeSettings {
user_values: &[&Self::FileContent], user_values: &[&Self::FileContent],
cx: &mut AppContext, cx: &mut AppContext,
) -> Result<Self> { ) -> Result<Self> {
let themes = cx.default_global::<Arc<ThemeRegistry>>(); let themes = cx.default_global::<ThemeRegistry>();
let mut this = Self { let mut this = Self {
ui_font_size: defaults.ui_font_size.unwrap_or(16.).into(), ui_font_size: defaults.ui_font_size.unwrap().into(),
ui_font: Font { ui_font: Font {
family: "Helvetica".into(), family: defaults.ui_font_family.clone().unwrap().into(),
features: Default::default(), features: defaults.ui_font_features.clone().unwrap(),
weight: Default::default(), weight: Default::default(),
style: Default::default(), style: Default::default(),
}, },
@ -149,6 +153,13 @@ impl settings::Settings for ThemeSettings {
this.buffer_font.features = value; this.buffer_font.features = value;
} }
if let Some(value) = value.ui_font_family {
this.ui_font.family = value.into();
}
if let Some(value) = value.ui_font_features {
this.ui_font.features = value;
}
if let Some(value) = &value.theme { if let Some(value) = &value.theme {
if let Some(theme) = themes.get(value).log_err() { if let Some(theme) = themes.get(value).log_err() {
this.active_theme = theme; this.active_theme = theme;

View File

@ -31,8 +31,25 @@ pub enum Appearance {
Dark, Dark,
} }
pub fn init(cx: &mut AppContext) { #[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum LoadThemes {
/// Only load the base theme.
///
/// No user themes will be loaded.
JustBase,
/// Load all of the built-in themes.
All,
}
pub fn init(themes_to_load: LoadThemes, cx: &mut AppContext) {
cx.set_global(ThemeRegistry::default()); cx.set_global(ThemeRegistry::default());
match themes_to_load {
LoadThemes::JustBase => (),
LoadThemes::All => cx.global_mut::<ThemeRegistry>().load_user_themes(),
}
ThemeSettings::register(cx); ThemeSettings::register(cx);
} }

View File

@ -178,6 +178,7 @@ impl<V: 'static> Button<V> {
.text_ui() .text_ui()
.rounded_md() .rounded_md()
.bg(self.variant.bg_color(cx)) .bg(self.variant.bg_color(cx))
.cursor_pointer()
.hover(|style| style.bg(self.variant.bg_color_hover(cx))) .hover(|style| style.bg(self.variant.bg_color_hover(cx)))
.active(|style| style.bg(self.variant.bg_color_active(cx))); .active(|style| style.bg(self.variant.bg_color_active(cx)));

View File

@ -1,82 +1,258 @@
use crate::{prelude::*, ListItemVariant}; use std::cell::RefCell;
use std::rc::Rc;
use crate::prelude::*;
use crate::{v_stack, Label, List, ListEntry, ListItem, ListSeparator, ListSubHeader}; use crate::{v_stack, Label, List, ListEntry, ListItem, ListSeparator, ListSubHeader};
use gpui::{
overlay, px, Action, AnchorCorner, AnyElement, Bounds, Dismiss, DispatchPhase, Div,
FocusHandle, LayoutId, ManagedView, MouseButton, MouseDownEvent, Pixels, Point, Render, View,
};
pub enum ContextMenuItem {
Header(SharedString),
Entry(Label, Box<dyn gpui::Action>),
Separator,
}
impl Clone for ContextMenuItem {
fn clone(&self) -> Self {
match self {
ContextMenuItem::Header(name) => ContextMenuItem::Header(name.clone()),
ContextMenuItem::Entry(label, action) => {
ContextMenuItem::Entry(label.clone(), action.boxed_clone())
}
ContextMenuItem::Separator => ContextMenuItem::Separator,
}
}
}
impl ContextMenuItem {
fn to_list_item<V: 'static>(self) -> ListItem {
match self {
ContextMenuItem::Header(label) => ListSubHeader::new(label).into(),
ContextMenuItem::Entry(label, action) => ListEntry::new(label)
.variant(ListItemVariant::Inset)
.on_click(action)
.into(),
ContextMenuItem::Separator => ListSeparator::new().into(),
}
}
pub fn header(label: impl Into<SharedString>) -> Self {
Self::Header(label.into())
}
pub fn separator() -> Self {
Self::Separator
}
pub fn entry(label: Label, action: impl Action) -> Self {
Self::Entry(label, Box::new(action))
}
}
#[derive(Component, Clone)]
pub struct ContextMenu { pub struct ContextMenu {
items: Vec<ContextMenuItem>, items: Vec<ListItem>,
focus_handle: FocusHandle,
}
impl ManagedView for ContextMenu {
fn focus_handle(&self, cx: &gpui::AppContext) -> FocusHandle {
self.focus_handle.clone()
}
} }
impl ContextMenu { impl ContextMenu {
pub fn new(items: impl IntoIterator<Item = ContextMenuItem>) -> Self { pub fn new(cx: &mut WindowContext) -> Self {
Self { Self {
items: items.into_iter().collect(), items: Default::default(),
focus_handle: cx.focus_handle(),
} }
} }
// todo!()
// cx.add_action(ContextMenu::select_first); pub fn header(mut self, title: impl Into<SharedString>) -> Self {
// cx.add_action(ContextMenu::select_last); self.items.push(ListItem::Header(ListSubHeader::new(title)));
// cx.add_action(ContextMenu::select_next); self
// cx.add_action(ContextMenu::select_prev); }
// cx.add_action(ContextMenu::confirm);
fn render<V: 'static>(self, _view: &mut V, cx: &mut ViewContext<V>) -> impl Component<V> { pub fn separator(mut self) -> Self {
v_stack() self.items.push(ListItem::Separator(ListSeparator));
.flex() self
.bg(cx.theme().colors().elevated_surface_background) }
.border()
.border_color(cx.theme().colors().border) pub fn entry(mut self, label: Label, action: Box<dyn Action>) -> Self {
.child(List::new( self.items.push(ListEntry::new(label).action(action).into());
self.items self
.into_iter() }
.map(ContextMenuItem::to_list_item::<V>)
.collect(), pub fn confirm(&mut self, _: &menu::Confirm, cx: &mut ViewContext<Self>) {
)) // todo!()
.on_mouse_down_out(|_, _, cx| cx.dispatch_action(Box::new(menu::Cancel))) cx.emit(Dismiss);
}
pub fn cancel(&mut self, _: &menu::Cancel, cx: &mut ViewContext<Self>) {
cx.emit(Dismiss);
}
}
impl Render for ContextMenu {
type Element = Div<Self>;
// todo!()
fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
div().elevation_2(cx).flex().flex_row().child(
v_stack()
.min_w(px(200.))
.track_focus(&self.focus_handle)
.on_mouse_down_out(|this: &mut Self, _, cx| this.cancel(&Default::default(), cx))
// .on_action(ContextMenu::select_first)
// .on_action(ContextMenu::select_last)
// .on_action(ContextMenu::select_next)
// .on_action(ContextMenu::select_prev)
.on_action(ContextMenu::confirm)
.on_action(ContextMenu::cancel)
.flex_none()
// .bg(cx.theme().colors().elevated_surface_background)
// .border()
// .border_color(cx.theme().colors().border)
.child(List::new(self.items.clone())),
)
}
}
pub struct MenuHandle<V: 'static, M: ManagedView> {
id: Option<ElementId>,
child_builder: Option<Box<dyn FnOnce(bool) -> AnyElement<V> + 'static>>,
menu_builder: Option<Rc<dyn Fn(&mut V, &mut ViewContext<V>) -> View<M> + 'static>>,
anchor: Option<AnchorCorner>,
attach: Option<AnchorCorner>,
}
impl<V: 'static, M: ManagedView> MenuHandle<V, M> {
pub fn id(mut self, id: impl Into<ElementId>) -> Self {
self.id = Some(id.into());
self
}
pub fn menu(mut self, f: impl Fn(&mut V, &mut ViewContext<V>) -> View<M> + 'static) -> Self {
self.menu_builder = Some(Rc::new(f));
self
}
pub fn child<R: Component<V>>(mut self, f: impl FnOnce(bool) -> R + 'static) -> Self {
self.child_builder = Some(Box::new(|b| f(b).render()));
self
}
/// anchor defines which corner of the menu to anchor to the attachment point
/// (by default the cursor position, but see attach)
pub fn anchor(mut self, anchor: AnchorCorner) -> Self {
self.anchor = Some(anchor);
self
}
/// attach defines which corner of the handle to attach the menu's anchor to
pub fn attach(mut self, attach: AnchorCorner) -> Self {
self.attach = Some(attach);
self
}
}
pub fn menu_handle<V: 'static, M: ManagedView>() -> MenuHandle<V, M> {
MenuHandle {
id: None,
child_builder: None,
menu_builder: None,
anchor: None,
attach: None,
}
}
pub struct MenuHandleState<V, M> {
menu: Rc<RefCell<Option<View<M>>>>,
position: Rc<RefCell<Point<Pixels>>>,
child_layout_id: Option<LayoutId>,
child_element: Option<AnyElement<V>>,
menu_element: Option<AnyElement<V>>,
}
impl<V: 'static, M: ManagedView> Element<V> for MenuHandle<V, M> {
type ElementState = MenuHandleState<V, M>;
fn element_id(&self) -> Option<gpui::ElementId> {
Some(self.id.clone().expect("menu_handle must have an id()"))
}
fn layout(
&mut self,
view_state: &mut V,
element_state: Option<Self::ElementState>,
cx: &mut crate::ViewContext<V>,
) -> (gpui::LayoutId, Self::ElementState) {
let (menu, position) = if let Some(element_state) = element_state {
(element_state.menu, element_state.position)
} else {
(Rc::default(), Rc::default())
};
let mut menu_layout_id = None;
let menu_element = menu.borrow_mut().as_mut().map(|menu| {
let mut overlay = overlay::<V>().snap_to_window();
if let Some(anchor) = self.anchor {
overlay = overlay.anchor(anchor);
}
overlay = overlay.position(*position.borrow());
let mut view = overlay.child(menu.clone()).render();
menu_layout_id = Some(view.layout(view_state, cx));
view
});
let mut child_element = self
.child_builder
.take()
.map(|child_builder| (child_builder)(menu.borrow().is_some()));
let child_layout_id = child_element
.as_mut()
.map(|child_element| child_element.layout(view_state, cx));
let layout_id = cx.request_layout(
&gpui::Style::default(),
menu_layout_id.into_iter().chain(child_layout_id),
);
(
layout_id,
MenuHandleState {
menu,
position,
child_element,
child_layout_id,
menu_element,
},
)
}
fn paint(
&mut self,
bounds: Bounds<gpui::Pixels>,
view_state: &mut V,
element_state: &mut Self::ElementState,
cx: &mut crate::ViewContext<V>,
) {
if let Some(child) = element_state.child_element.as_mut() {
child.paint(view_state, cx);
}
if let Some(menu) = element_state.menu_element.as_mut() {
menu.paint(view_state, cx);
return;
}
let Some(builder) = self.menu_builder.clone() else {
return;
};
let menu = element_state.menu.clone();
let position = element_state.position.clone();
let attach = self.attach.clone();
let child_layout_id = element_state.child_layout_id.clone();
cx.on_mouse_event(move |view_state, event: &MouseDownEvent, phase, cx| {
if phase == DispatchPhase::Bubble
&& event.button == MouseButton::Right
&& bounds.contains_point(&event.position)
{
cx.stop_propagation();
cx.prevent_default();
let new_menu = (builder)(view_state, cx);
let menu2 = menu.clone();
cx.subscribe(&new_menu, move |this, modal, e, cx| match e {
&Dismiss => {
*menu2.borrow_mut() = None;
cx.notify();
}
})
.detach();
*menu.borrow_mut() = Some(new_menu);
*position.borrow_mut() = if attach.is_some() && child_layout_id.is_some() {
attach
.unwrap()
.corner(cx.layout_bounds(child_layout_id.unwrap()))
} else {
cx.mouse_position()
};
cx.notify();
}
});
}
}
impl<V: 'static, M: ManagedView> Component<V> for MenuHandle<V, M> {
fn render(self) -> AnyElement<V> {
AnyElement::new(self)
} }
} }
use gpui::Action;
#[cfg(feature = "stories")] #[cfg(feature = "stories")]
pub use stories::*; pub use stories::*;
@ -84,7 +260,18 @@ pub use stories::*;
mod stories { mod stories {
use super::*; use super::*;
use crate::story::Story; use crate::story::Story;
use gpui::{action, Div, Render}; use gpui::{actions, Div, Render, VisualContext};
actions!(PrintCurrentDate);
fn build_menu(cx: &mut WindowContext, header: impl Into<SharedString>) -> View<ContextMenu> {
cx.build_view(|cx| {
ContextMenu::new(cx).header(header).separator().entry(
Label::new("Print current time"),
PrintCurrentDate.boxed_clone(),
)
})
}
pub struct ContextMenuStory; pub struct ContextMenuStory;
@ -92,22 +279,84 @@ mod stories {
type Element = Div<Self>; type Element = Div<Self>;
fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element { fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
#[action]
struct PrintCurrentDate {}
Story::container(cx) Story::container(cx)
.child(Story::title_for::<_, ContextMenu>(cx))
.child(Story::label(cx, "Default"))
.child(ContextMenu::new([
ContextMenuItem::header("Section header"),
ContextMenuItem::Separator,
ContextMenuItem::entry(Label::new("Print current time"), PrintCurrentDate {}),
]))
.on_action(|_, _: &PrintCurrentDate, _| { .on_action(|_, _: &PrintCurrentDate, _| {
if let Ok(unix_time) = std::time::UNIX_EPOCH.elapsed() { if let Ok(unix_time) = std::time::UNIX_EPOCH.elapsed() {
println!("Current Unix time is {:?}", unix_time.as_secs()); println!("Current Unix time is {:?}", unix_time.as_secs());
} }
}) })
.flex()
.flex_row()
.justify_between()
.child(
div()
.flex()
.flex_col()
.justify_between()
.child(
menu_handle()
.id("test2")
.child(|is_open| {
Label::new(if is_open {
"TOP LEFT"
} else {
"RIGHT CLICK ME"
})
.render()
})
.menu(move |_, cx| build_menu(cx, "top left")),
)
.child(
menu_handle()
.id("test1")
.child(|is_open| {
Label::new(if is_open {
"BOTTOM LEFT"
} else {
"RIGHT CLICK ME"
})
.render()
})
.anchor(AnchorCorner::BottomLeft)
.attach(AnchorCorner::TopLeft)
.menu(move |_, cx| build_menu(cx, "bottom left")),
),
)
.child(
div()
.flex()
.flex_col()
.justify_between()
.child(
menu_handle()
.id("test3")
.child(|is_open| {
Label::new(if is_open {
"TOP RIGHT"
} else {
"RIGHT CLICK ME"
})
.render()
})
.anchor(AnchorCorner::TopRight)
.menu(move |_, cx| build_menu(cx, "top right")),
)
.child(
menu_handle()
.id("test4")
.child(|is_open| {
Label::new(if is_open {
"BOTTOM RIGHT"
} else {
"RIGHT CLICK ME"
})
.render()
})
.anchor(AnchorCorner::BottomRight)
.attach(AnchorCorner::TopRight)
.menu(move |_, cx| build_menu(cx, "bottom right")),
),
)
} }
} }
} }

View File

@ -1,5 +1,5 @@
use crate::{h_stack, prelude::*, ClickHandler, Icon, IconElement}; use crate::{h_stack, prelude::*, ClickHandler, Icon, IconElement};
use gpui::{prelude::*, AnyView, MouseButton}; use gpui::{prelude::*, Action, AnyView, MouseButton};
use std::sync::Arc; use std::sync::Arc;
struct IconButtonHandlers<V: 'static> { struct IconButtonHandlers<V: 'static> {
@ -19,6 +19,7 @@ pub struct IconButton<V: 'static> {
color: TextColor, color: TextColor,
variant: ButtonVariant, variant: ButtonVariant,
state: InteractionState, state: InteractionState,
selected: bool,
tooltip: Option<Box<dyn Fn(&mut V, &mut ViewContext<V>) -> AnyView + 'static>>, tooltip: Option<Box<dyn Fn(&mut V, &mut ViewContext<V>) -> AnyView + 'static>>,
handlers: IconButtonHandlers<V>, handlers: IconButtonHandlers<V>,
} }
@ -31,6 +32,7 @@ impl<V: 'static> IconButton<V> {
color: TextColor::default(), color: TextColor::default(),
variant: ButtonVariant::default(), variant: ButtonVariant::default(),
state: InteractionState::default(), state: InteractionState::default(),
selected: false,
tooltip: None, tooltip: None,
handlers: IconButtonHandlers::default(), handlers: IconButtonHandlers::default(),
} }
@ -56,6 +58,11 @@ impl<V: 'static> IconButton<V> {
self self
} }
pub fn selected(mut self, selected: bool) -> Self {
self.selected = selected;
self
}
pub fn tooltip( pub fn tooltip(
mut self, mut self,
tooltip: impl Fn(&mut V, &mut ViewContext<V>) -> AnyView + 'static, tooltip: impl Fn(&mut V, &mut ViewContext<V>) -> AnyView + 'static,
@ -69,14 +76,18 @@ impl<V: 'static> IconButton<V> {
self self
} }
pub fn action(self, action: Box<dyn Action>) -> Self {
self.on_click(move |this, cx| cx.dispatch_action(action.boxed_clone()))
}
fn render(mut self, _view: &mut V, cx: &mut ViewContext<V>) -> impl Component<V> { fn render(mut self, _view: &mut V, cx: &mut ViewContext<V>) -> impl Component<V> {
let icon_color = match (self.state, self.color) { let icon_color = match (self.state, self.color) {
(InteractionState::Disabled, _) => TextColor::Disabled, (InteractionState::Disabled, _) => TextColor::Disabled,
(InteractionState::Active, _) => TextColor::Error, (InteractionState::Active, _) => TextColor::Selected,
_ => self.color, _ => self.color,
}; };
let (bg_color, bg_hover_color, bg_active_color) = match self.variant { let (mut bg_color, bg_hover_color, bg_active_color) = match self.variant {
ButtonVariant::Filled => ( ButtonVariant::Filled => (
cx.theme().colors().element_background, cx.theme().colors().element_background,
cx.theme().colors().element_hover, cx.theme().colors().element_hover,
@ -89,27 +100,32 @@ impl<V: 'static> IconButton<V> {
), ),
}; };
if self.selected {
bg_color = bg_hover_color;
}
let mut button = h_stack() let mut button = h_stack()
.id(self.id.clone()) .id(self.id.clone())
.justify_center() .justify_center()
.rounded_md() .rounded_md()
.p_1() .p_1()
.bg(bg_color) .bg(bg_color)
.cursor_pointer()
.hover(|style| style.bg(bg_hover_color)) .hover(|style| style.bg(bg_hover_color))
.active(|style| style.bg(bg_active_color)) .active(|style| style.bg(bg_active_color))
.child(IconElement::new(self.icon).color(icon_color)); .child(IconElement::new(self.icon).color(icon_color));
if let Some(click_handler) = self.handlers.click.clone() { if let Some(click_handler) = self.handlers.click.clone() {
button = button button = button.on_mouse_down(MouseButton::Left, move |state, event, cx| {
.on_mouse_down(MouseButton::Left, move |state, event, cx| { cx.stop_propagation();
cx.stop_propagation(); click_handler(state, cx);
click_handler(state, cx); })
})
.cursor_pointer();
} }
if let Some(tooltip) = self.tooltip.take() { if let Some(tooltip) = self.tooltip.take() {
button = button.tooltip(move |view: &mut V, cx| (tooltip)(view, cx)) if !self.selected {
button = button.tooltip(move |view: &mut V, cx| (tooltip)(view, cx))
}
} }
button button

View File

@ -81,13 +81,12 @@ pub use stories::*;
mod stories { mod stories {
use super::*; use super::*;
use crate::Story; use crate::Story;
use gpui::{action, Div, Render}; use gpui::{actions, Div, Render};
use itertools::Itertools; use itertools::Itertools;
pub struct KeybindingStory; pub struct KeybindingStory;
#[action] actions!(NoAction);
struct NoAction {}
pub fn binding(key: &str) -> gpui::KeyBinding { pub fn binding(key: &str) -> gpui::KeyBinding {
gpui::KeyBinding::new(key, NoAction {}, None) gpui::KeyBinding::new(key, NoAction {}, None)

View File

@ -117,7 +117,7 @@ impl ListHeader {
} }
} }
#[derive(Component)] #[derive(Component, Clone)]
pub struct ListSubHeader { pub struct ListSubHeader {
label: SharedString, label: SharedString,
left_icon: Option<Icon>, left_icon: Option<Icon>,
@ -172,7 +172,7 @@ pub enum ListEntrySize {
Medium, Medium,
} }
#[derive(Component)] #[derive(Component, Clone)]
pub enum ListItem { pub enum ListItem {
Entry(ListEntry), Entry(ListEntry),
Separator(ListSeparator), Separator(ListSeparator),
@ -234,6 +234,24 @@ pub struct ListEntry {
on_click: Option<Box<dyn Action>>, on_click: Option<Box<dyn Action>>,
} }
impl Clone for ListEntry {
fn clone(&self) -> Self {
Self {
disabled: self.disabled,
// TODO: Reintroduce this
// disclosure_control_style: DisclosureControlVisibility,
indent_level: self.indent_level,
label: self.label.clone(),
left_slot: self.left_slot.clone(),
overflow: self.overflow,
size: self.size,
toggle: self.toggle,
variant: self.variant,
on_click: self.on_click.as_ref().map(|opt| opt.boxed_clone()),
}
}
}
impl ListEntry { impl ListEntry {
pub fn new(label: Label) -> Self { pub fn new(label: Label) -> Self {
Self { Self {
@ -249,7 +267,7 @@ impl ListEntry {
} }
} }
pub fn on_click(mut self, action: impl Into<Box<dyn Action>>) -> Self { pub fn action(mut self, action: impl Into<Box<dyn Action>>) -> Self {
self.on_click = Some(action.into()); self.on_click = Some(action.into());
self self
} }

View File

@ -12,7 +12,6 @@ impl Story {
.flex_col() .flex_col()
.pt_2() .pt_2()
.px_4() .px_4()
.font("Zed Mono")
.bg(cx.theme().colors().background) .bg(cx.theme().colors().background)
} }

View File

@ -5,6 +5,7 @@ use crate::{ElevationIndex, UITextSize};
fn elevated<E: Styled, V: 'static>(this: E, cx: &mut ViewContext<V>, index: ElevationIndex) -> E { fn elevated<E: Styled, V: 'static>(this: E, cx: &mut ViewContext<V>, index: ElevationIndex) -> E {
this.bg(cx.theme().colors().elevated_surface_background) this.bg(cx.theme().colors().elevated_surface_background)
.z_index(index.z_index())
.rounded_lg() .rounded_lg()
.border() .border()
.border_color(cx.theme().colors().border_variant) .border_color(cx.theme().colors().border_variant)

View File

@ -1,13 +1,14 @@
use crate::{status_bar::StatusItemView, Axis, Workspace}; use crate::{status_bar::StatusItemView, Axis, Workspace};
use gpui::{ use gpui::{
div, px, Action, AnyView, AppContext, Component, Div, Entity, EntityId, EventEmitter, div, px, Action, AnchorCorner, AnyView, AppContext, Component, Div, Entity, EntityId,
FocusHandle, FocusableView, ParentComponent, Render, Styled, Subscription, View, ViewContext, EventEmitter, FocusHandle, FocusableView, ParentComponent, Render, SharedString, Styled,
WeakView, WindowContext, Subscription, View, ViewContext, VisualContext, WeakView, WindowContext,
}; };
use schemars::JsonSchema; use schemars::JsonSchema;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::sync::Arc; use std::sync::Arc;
use ui::{h_stack, IconButton, InteractionState, Tooltip}; use theme2::ActiveTheme;
use ui::{h_stack, menu_handle, ContextMenu, IconButton, InteractionState, Tooltip};
pub enum PanelEvent { pub enum PanelEvent {
ChangePosition, ChangePosition,
@ -216,11 +217,11 @@ impl Dock {
// .map_or(false, |panel| panel.has_focus(cx)) // .map_or(false, |panel| panel.has_focus(cx))
// } // }
// pub fn panel<T: Panel>(&self) -> Option<View<T>> { pub fn panel<T: Panel>(&self) -> Option<View<T>> {
// self.panel_entries self.panel_entries
// .iter() .iter()
// .find_map(|entry| entry.panel.as_any().clone().downcast()) .find_map(|entry| entry.panel.to_any().clone().downcast().ok())
// } }
pub fn panel_index_for_type<T: Panel>(&self) -> Option<usize> { pub fn panel_index_for_type<T: Panel>(&self) -> Option<usize> {
self.panel_entries self.panel_entries
@ -416,23 +417,13 @@ impl Dock {
} }
} }
// pub fn render_placeholder(&self, cx: &WindowContext) -> AnyElement<Workspace> { pub fn toggle_action(&self) -> Box<dyn Action> {
// todo!() match self.position {
// if let Some(active_entry) = self.visible_entry() { DockPosition::Left => crate::ToggleLeftDock.boxed_clone(),
// Empty::new() DockPosition::Bottom => crate::ToggleBottomDock.boxed_clone(),
// .into_any() DockPosition::Right => crate::ToggleRightDock.boxed_clone(),
// .contained() }
// .with_style(self.style(cx)) }
// .resizable::<WorkspaceBounds>(
// self.position.to_resize_handle_side(),
// active_entry.panel.size(cx),
// |_, _, _| {},
// )
// .into_any()
// } else {
// Empty::new().into_any()
// }
// }
} }
impl Render for Dock { impl Render for Dock {
@ -443,10 +434,16 @@ impl Render for Dock {
let size = entry.panel.size(cx); let size = entry.panel.size(cx);
div() div()
.border_color(cx.theme().colors().border)
.map(|this| match self.position().axis() { .map(|this| match self.position().axis() {
Axis::Horizontal => this.w(px(size)).h_full(), Axis::Horizontal => this.w(px(size)).h_full(),
Axis::Vertical => this.h(px(size)).w_full(), Axis::Vertical => this.h(px(size)).w_full(),
}) })
.map(|this| match self.position() {
DockPosition::Left => this.border_r(),
DockPosition::Right => this.border_l(),
DockPosition::Bottom => this.border_t(),
})
.child(entry.panel.to_any()) .child(entry.panel.to_any())
} else { } else {
div() div()
@ -454,40 +451,6 @@ impl Render for Dock {
} }
} }
// todo!()
// impl View for Dock {
// fn ui_name() -> &'static str {
// "Dock"
// }
// fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
// if let Some(active_entry) = self.visible_entry() {
// let style = self.style(cx);
// ChildView::new(active_entry.panel.as_any(), cx)
// .contained()
// .with_style(style)
// .resizable::<WorkspaceBounds>(
// self.position.to_resize_handle_side(),
// active_entry.panel.size(cx),
// |dock: &mut Self, size, cx| dock.resize_active_panel(size, cx),
// )
// .into_any()
// } else {
// Empty::new().into_any()
// }
// }
// fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
// if cx.is_self_focused() {
// if let Some(active_entry) = self.visible_entry() {
// cx.focus(active_entry.panel.as_any());
// } else {
// cx.focus_parent();
// }
// }
// }
// }
impl PanelButtons { impl PanelButtons {
pub fn new( pub fn new(
dock: View<Dock>, dock: View<Dock>,
@ -648,6 +611,7 @@ impl PanelButtons {
// } // }
// } // }
// here be kittens
impl Render for PanelButtons { impl Render for PanelButtons {
type Element = Div<Self>; type Element = Div<Self>;
@ -657,6 +621,13 @@ impl Render for PanelButtons {
let active_index = dock.active_panel_index; let active_index = dock.active_panel_index;
let is_open = dock.is_open; let is_open = dock.is_open;
let (menu_anchor, menu_attach) = match dock.position {
DockPosition::Left => (AnchorCorner::BottomLeft, AnchorCorner::TopLeft),
DockPosition::Bottom | DockPosition::Right => {
(AnchorCorner::BottomRight, AnchorCorner::TopRight)
}
};
let buttons = dock let buttons = dock
.panel_entries .panel_entries
.iter() .iter()
@ -664,18 +635,36 @@ impl Render for PanelButtons {
.filter_map(|(i, panel)| { .filter_map(|(i, panel)| {
let icon = panel.panel.icon(cx)?; let icon = panel.panel.icon(cx)?;
let name = panel.panel.persistent_name(); let name = panel.panel.persistent_name();
let action = panel.panel.toggle_action(cx);
let action2 = action.boxed_clone();
let mut button = IconButton::new(panel.panel.persistent_name(), icon) let mut button: IconButton<Self> = if i == active_index && is_open {
.when(i == active_index, |el| el.state(InteractionState::Active)) let action = dock.toggle_action();
.on_click(move |this, cx| cx.dispatch_action(action.boxed_clone())) let tooltip: SharedString =
.tooltip(move |_, cx| Tooltip::for_action(name, &*action2, cx)); format!("Close {} dock", dock.position.to_label()).into();
IconButton::new(name, icon)
.state(InteractionState::Active)
.action(action.boxed_clone())
.tooltip(move |_, cx| Tooltip::for_action(tooltip.clone(), &*action, cx))
} else {
let action = panel.panel.toggle_action(cx);
Some(button) IconButton::new(name, icon)
.action(action.boxed_clone())
.tooltip(move |_, cx| Tooltip::for_action(name, &*action, cx))
};
Some(
menu_handle()
.id(name)
.menu(move |_, cx| {
cx.build_view(|cx| ContextMenu::new(cx).header("SECTION"))
})
.anchor(menu_anchor)
.attach(menu_attach)
.child(|is_open| button.selected(is_open)),
)
}); });
h_stack().children(buttons) h_stack().gap_0p5().children(buttons)
} }
} }

View File

@ -240,7 +240,7 @@ pub trait ItemHandle: 'static + Send {
fn deactivated(&self, cx: &mut WindowContext); fn deactivated(&self, cx: &mut WindowContext);
fn workspace_deactivated(&self, cx: &mut WindowContext); fn workspace_deactivated(&self, cx: &mut WindowContext);
fn navigate(&self, data: Box<dyn Any>, cx: &mut WindowContext) -> bool; fn navigate(&self, data: Box<dyn Any>, cx: &mut WindowContext) -> bool;
fn id(&self) -> EntityId; fn item_id(&self) -> EntityId;
fn to_any(&self) -> AnyView; fn to_any(&self) -> AnyView;
fn is_dirty(&self, cx: &AppContext) -> bool; fn is_dirty(&self, cx: &AppContext) -> bool;
fn has_conflict(&self, cx: &AppContext) -> bool; fn has_conflict(&self, cx: &AppContext) -> bool;
@ -399,7 +399,7 @@ impl<T: Item> ItemHandle for View<T> {
if workspace if workspace
.panes_by_item .panes_by_item
.insert(self.id(), pane.downgrade()) .insert(self.item_id(), pane.downgrade())
.is_none() .is_none()
{ {
let mut pending_autosave = DelayedDebouncedEditAction::new(); let mut pending_autosave = DelayedDebouncedEditAction::new();
@ -410,7 +410,7 @@ impl<T: Item> ItemHandle for View<T> {
Some(cx.subscribe(self, move |workspace, item, event, cx| { Some(cx.subscribe(self, move |workspace, item, event, cx| {
let pane = if let Some(pane) = workspace let pane = if let Some(pane) = workspace
.panes_by_item .panes_by_item
.get(&item.id()) .get(&item.item_id())
.and_then(|pane| pane.upgrade()) .and_then(|pane| pane.upgrade())
{ {
pane pane
@ -463,7 +463,7 @@ impl<T: Item> ItemHandle for View<T> {
match event { match event {
ItemEvent::CloseItem => { ItemEvent::CloseItem => {
pane.update(cx, |pane, cx| { pane.update(cx, |pane, cx| {
pane.close_item_by_id(item.id(), crate::SaveIntent::Close, cx) pane.close_item_by_id(item.item_id(), crate::SaveIntent::Close, cx)
}) })
.detach_and_log_err(cx); .detach_and_log_err(cx);
return; return;
@ -502,7 +502,7 @@ impl<T: Item> ItemHandle for View<T> {
// }) // })
// .detach(); // .detach();
let item_id = self.id(); let item_id = self.item_id();
cx.observe_release(self, move |workspace, _, _| { cx.observe_release(self, move |workspace, _, _| {
workspace.panes_by_item.remove(&item_id); workspace.panes_by_item.remove(&item_id);
event_subscription.take(); event_subscription.take();
@ -527,7 +527,7 @@ impl<T: Item> ItemHandle for View<T> {
self.update(cx, |this, cx| this.navigate(data, cx)) self.update(cx, |this, cx| this.navigate(data, cx))
} }
fn id(&self) -> EntityId { fn item_id(&self) -> EntityId {
self.entity_id() self.entity_id()
} }
@ -712,7 +712,7 @@ impl<T: FollowableItem> FollowableItemHandle for View<T> {
self.read(cx).remote_id().or_else(|| { self.read(cx).remote_id().or_else(|| {
client.peer_id().map(|creator| ViewId { client.peer_id().map(|creator| ViewId {
creator, creator,
id: self.id().as_u64(), id: self.item_id().as_u64(),
}) })
}) })
} }

View File

@ -1,6 +1,6 @@
use gpui::{ use gpui::{
div, prelude::*, px, AnyView, Div, EventEmitter, FocusHandle, Render, Subscription, View, div, prelude::*, px, AnyView, Div, FocusHandle, ManagedView, Render, Subscription, View,
ViewContext, WindowContext, ViewContext,
}; };
use ui::{h_stack, v_stack}; use ui::{h_stack, v_stack};
@ -15,14 +15,6 @@ pub struct ModalLayer {
active_modal: Option<ActiveModal>, active_modal: Option<ActiveModal>,
} }
pub trait Modal: Render + EventEmitter<ModalEvent> {
fn focus(&self, cx: &mut WindowContext);
}
pub enum ModalEvent {
Dismissed,
}
impl ModalLayer { impl ModalLayer {
pub fn new() -> Self { pub fn new() -> Self {
Self { active_modal: None } Self { active_modal: None }
@ -30,7 +22,7 @@ impl ModalLayer {
pub fn toggle_modal<V, B>(&mut self, cx: &mut ViewContext<Self>, build_view: B) pub fn toggle_modal<V, B>(&mut self, cx: &mut ViewContext<Self>, build_view: B)
where where
V: Modal, V: ManagedView,
B: FnOnce(&mut ViewContext<V>) -> V, B: FnOnce(&mut ViewContext<V>) -> V,
{ {
if let Some(active_modal) = &self.active_modal { if let Some(active_modal) = &self.active_modal {
@ -46,17 +38,15 @@ impl ModalLayer {
pub fn show_modal<V>(&mut self, new_modal: View<V>, cx: &mut ViewContext<Self>) pub fn show_modal<V>(&mut self, new_modal: View<V>, cx: &mut ViewContext<Self>)
where where
V: Modal, V: ManagedView,
{ {
self.active_modal = Some(ActiveModal { self.active_modal = Some(ActiveModal {
modal: new_modal.clone().into(), modal: new_modal.clone().into(),
subscription: cx.subscribe(&new_modal, |this, modal, e, cx| match e { subscription: cx.subscribe(&new_modal, |this, modal, e, cx| this.hide_modal(cx)),
ModalEvent::Dismissed => this.hide_modal(cx),
}),
previous_focus_handle: cx.focused(), previous_focus_handle: cx.focused(),
focus_handle: cx.focus_handle(), focus_handle: cx.focus_handle(),
}); });
new_modal.update(cx, |modal, cx| modal.focus(cx)); cx.focus_view(&new_modal);
cx.notify(); cx.notify();
} }

View File

@ -7,9 +7,9 @@ use crate::{
use anyhow::Result; use anyhow::Result;
use collections::{HashMap, HashSet, VecDeque}; use collections::{HashMap, HashSet, VecDeque};
use gpui::{ use gpui::{
actions, prelude::*, register_action, AppContext, AsyncWindowContext, Component, Div, EntityId, actions, prelude::*, Action, AppContext, AsyncWindowContext, Component, Div, EntityId,
EventEmitter, FocusHandle, Focusable, FocusableView, Model, PromptLevel, Render, Task, View, EventEmitter, FocusHandle, Focusable, FocusableView, Model, Pixels, Point, PromptLevel, Render,
ViewContext, VisualContext, WeakView, WindowContext, Task, View, ViewContext, VisualContext, WeakView, WindowContext,
}; };
use parking_lot::Mutex; use parking_lot::Mutex;
use project2::{Project, ProjectEntryId, ProjectPath}; use project2::{Project, ProjectEntryId, ProjectPath};
@ -70,15 +70,13 @@ pub struct ActivateItem(pub usize);
// pub pane: WeakView<Pane>, // pub pane: WeakView<Pane>,
// } // }
#[register_action] #[derive(Clone, PartialEq, Debug, Deserialize, Default, Action)]
#[derive(Clone, PartialEq, Debug, Deserialize, Default)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct CloseActiveItem { pub struct CloseActiveItem {
pub save_intent: Option<SaveIntent>, pub save_intent: Option<SaveIntent>,
} }
#[register_action] #[derive(Clone, PartialEq, Debug, Deserialize, Default, Action)]
#[derive(Clone, PartialEq, Debug, Deserialize, Default)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct CloseAllItems { pub struct CloseAllItems {
pub save_intent: Option<SaveIntent>, pub save_intent: Option<SaveIntent>,
@ -104,29 +102,6 @@ actions!(
const MAX_NAVIGATION_HISTORY_LEN: usize = 1024; const MAX_NAVIGATION_HISTORY_LEN: usize = 1024;
pub fn init(cx: &mut AppContext) {
// todo!()
// cx.add_action(Pane::toggle_zoom);
// cx.add_action(|pane: &mut Pane, action: &ActivateItem, cx| {
// pane.activate_item(action.0, true, true, cx);
// });
// cx.add_action(|pane: &mut Pane, _: &ActivateLastItem, cx| {
// pane.activate_item(pane.items.len() - 1, true, true, cx);
// });
// cx.add_action(|pane: &mut Pane, _: &ActivatePrevItem, cx| {
// pane.activate_prev_item(true, cx);
// });
// cx.add_action(|pane: &mut Pane, _: &ActivateNextItem, cx| {
// pane.activate_next_item(true, cx);
// });
// cx.add_async_action(Pane::close_active_item);
// cx.add_async_action(Pane::close_inactive_items);
// cx.add_async_action(Pane::close_clean_items);
// cx.add_async_action(Pane::close_items_to_the_left);
// cx.add_async_action(Pane::close_items_to_the_right);
// cx.add_async_action(Pane::close_all_items);
}
pub enum Event { pub enum Event {
AddItem { item: Box<dyn ItemHandle> }, AddItem { item: Box<dyn ItemHandle> },
ActivateItem { local: bool }, ActivateItem { local: bool },
@ -142,7 +117,10 @@ pub enum Event {
impl fmt::Debug for Event { impl fmt::Debug for Event {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
Event::AddItem { item } => f.debug_struct("AddItem").field("item", &item.id()).finish(), Event::AddItem { item } => f
.debug_struct("AddItem")
.field("item", &item.item_id())
.finish(),
Event::ActivateItem { local } => f Event::ActivateItem { local } => f
.debug_struct("ActivateItem") .debug_struct("ActivateItem")
.field("local", local) .field("local", local)
@ -526,7 +504,7 @@ impl Pane {
.0 .0
.lock() .lock()
.paths_by_item .paths_by_item
.insert(item.id(), (project_path, abs_path)); .insert(item.item_id(), (project_path, abs_path));
} }
} }
} }
@ -550,7 +528,7 @@ impl Pane {
}; };
let existing_item_index = self.items.iter().position(|existing_item| { let existing_item_index = self.items.iter().position(|existing_item| {
if existing_item.id() == item.id() { if existing_item.item_id() == item.item_id() {
true true
} else if existing_item.is_singleton(cx) { } else if existing_item.is_singleton(cx) {
existing_item existing_item
@ -615,21 +593,21 @@ impl Pane {
self.items.iter() self.items.iter()
} }
// pub fn items_of_type<T: View>(&self) -> impl '_ + Iterator<Item = ViewHandle<T>> { pub fn items_of_type<T: Render>(&self) -> impl '_ + Iterator<Item = View<T>> {
// self.items self.items
// .iter() .iter()
// .filter_map(|item| item.as_any().clone().downcast()) .filter_map(|item| item.to_any().downcast().ok())
// } }
pub fn active_item(&self) -> Option<Box<dyn ItemHandle>> { pub fn active_item(&self) -> Option<Box<dyn ItemHandle>> {
self.items.get(self.active_item_index).cloned() self.items.get(self.active_item_index).cloned()
} }
// pub fn pixel_position_of_cursor(&self, cx: &AppContext) -> Option<Vector2F> { pub fn pixel_position_of_cursor(&self, cx: &AppContext) -> Option<Point<Pixels>> {
// self.items self.items
// .get(self.active_item_index)? .get(self.active_item_index)?
// .pixel_position_of_cursor(cx) .pixel_position_of_cursor(cx)
// } }
pub fn item_for_entry( pub fn item_for_entry(
&self, &self,
@ -646,24 +624,26 @@ impl Pane {
} }
pub fn index_for_item(&self, item: &dyn ItemHandle) -> Option<usize> { pub fn index_for_item(&self, item: &dyn ItemHandle) -> Option<usize> {
self.items.iter().position(|i| i.id() == item.id()) self.items
.iter()
.position(|i| i.item_id() == item.item_id())
} }
// pub fn toggle_zoom(&mut self, _: &ToggleZoom, cx: &mut ViewContext<Self>) { // pub fn toggle_zoom(&mut self, _: &ToggleZoom, cx: &mut ViewContext<Self>) {
// // Potentially warn the user of the new keybinding // // Potentially warn the user of the new keybinding
// let workspace_handle = self.workspace().clone(); // let workspace_handle = self.workspace().clone();
// cx.spawn(|_, mut cx| async move { notify_of_new_dock(&workspace_handle, &mut cx) }) // cx.spawn(|_, mut cx| async move { notify_of_new_dock(&workspace_handle, &mut cx) })
// .detach(); // .detach();
// if self.zoomed { // if self.zoomed {
// cx.emit(Event::ZoomOut); // cx.emit(Event::ZoomOut);
// } else if !self.items.is_empty() { // } else if !self.items.is_empty() {
// if !self.has_focus { // if !self.has_focus {
// cx.focus_self(); // cx.focus_self();
// }
// cx.emit(Event::ZoomIn);
// } // }
// cx.emit(Event::ZoomIn);
// } // }
// }
pub fn activate_item( pub fn activate_item(
&mut self, &mut self,
@ -691,9 +671,9 @@ impl Pane {
if let Some(newly_active_item) = self.items.get(index) { if let Some(newly_active_item) = self.items.get(index) {
self.activation_history self.activation_history
.retain(|&previously_active_item_id| { .retain(|&previously_active_item_id| {
previously_active_item_id != newly_active_item.id() previously_active_item_id != newly_active_item.item_id()
}); });
self.activation_history.push(newly_active_item.id()); self.activation_history.push(newly_active_item.item_id());
} }
self.update_toolbar(cx); self.update_toolbar(cx);
@ -707,25 +687,25 @@ impl Pane {
} }
} }
// pub fn activate_prev_item(&mut self, activate_pane: bool, cx: &mut ViewContext<Self>) { pub fn activate_prev_item(&mut self, activate_pane: bool, cx: &mut ViewContext<Self>) {
// let mut index = self.active_item_index; let mut index = self.active_item_index;
// if index > 0 { if index > 0 {
// index -= 1; index -= 1;
// } else if !self.items.is_empty() { } else if !self.items.is_empty() {
// index = self.items.len() - 1; index = self.items.len() - 1;
// } }
// self.activate_item(index, activate_pane, activate_pane, cx); self.activate_item(index, activate_pane, activate_pane, cx);
// } }
// pub fn activate_next_item(&mut self, activate_pane: bool, cx: &mut ViewContext<Self>) { pub fn activate_next_item(&mut self, activate_pane: bool, cx: &mut ViewContext<Self>) {
// let mut index = self.active_item_index; let mut index = self.active_item_index;
// if index + 1 < self.items.len() { if index + 1 < self.items.len() {
// index += 1; index += 1;
// } else { } else {
// index = 0; index = 0;
// } }
// self.activate_item(index, activate_pane, activate_pane, cx); self.activate_item(index, activate_pane, activate_pane, cx);
// } }
pub fn close_active_item( pub fn close_active_item(
&mut self, &mut self,
@ -735,7 +715,7 @@ impl Pane {
if self.items.is_empty() { if self.items.is_empty() {
return None; return None;
} }
let active_item_id = self.items[self.active_item_index].id(); let active_item_id = self.items[self.active_item_index].item_id();
Some(self.close_item_by_id( Some(self.close_item_by_id(
active_item_id, active_item_id,
action.save_intent.unwrap_or(SaveIntent::Close), action.save_intent.unwrap_or(SaveIntent::Close),
@ -752,106 +732,106 @@ impl Pane {
self.close_items(cx, save_intent, move |view_id| view_id == item_id_to_close) self.close_items(cx, save_intent, move |view_id| view_id == item_id_to_close)
} }
// pub fn close_inactive_items( pub fn close_inactive_items(
// &mut self, &mut self,
// _: &CloseInactiveItems, _: &CloseInactiveItems,
// cx: &mut ViewContext<Self>, cx: &mut ViewContext<Self>,
// ) -> Option<Task<Result<()>>> { ) -> Option<Task<Result<()>>> {
// if self.items.is_empty() { if self.items.is_empty() {
// return None; return None;
// } }
// let active_item_id = self.items[self.active_item_index].id(); let active_item_id = self.items[self.active_item_index].item_id();
// Some(self.close_items(cx, SaveIntent::Close, move |item_id| { Some(self.close_items(cx, SaveIntent::Close, move |item_id| {
// item_id != active_item_id item_id != active_item_id
// })) }))
// } }
// pub fn close_clean_items( pub fn close_clean_items(
// &mut self, &mut self,
// _: &CloseCleanItems, _: &CloseCleanItems,
// cx: &mut ViewContext<Self>, cx: &mut ViewContext<Self>,
// ) -> Option<Task<Result<()>>> { ) -> Option<Task<Result<()>>> {
// let item_ids: Vec<_> = self let item_ids: Vec<_> = self
// .items() .items()
// .filter(|item| !item.is_dirty(cx)) .filter(|item| !item.is_dirty(cx))
// .map(|item| item.id()) .map(|item| item.item_id())
// .collect(); .collect();
// Some(self.close_items(cx, SaveIntent::Close, move |item_id| { Some(self.close_items(cx, SaveIntent::Close, move |item_id| {
// item_ids.contains(&item_id) item_ids.contains(&item_id)
// })) }))
// } }
// pub fn close_items_to_the_left( pub fn close_items_to_the_left(
// &mut self, &mut self,
// _: &CloseItemsToTheLeft, _: &CloseItemsToTheLeft,
// cx: &mut ViewContext<Self>, cx: &mut ViewContext<Self>,
// ) -> Option<Task<Result<()>>> { ) -> Option<Task<Result<()>>> {
// if self.items.is_empty() { if self.items.is_empty() {
// return None; return None;
// } }
// let active_item_id = self.items[self.active_item_index].id(); let active_item_id = self.items[self.active_item_index].item_id();
// Some(self.close_items_to_the_left_by_id(active_item_id, cx)) Some(self.close_items_to_the_left_by_id(active_item_id, cx))
// } }
// pub fn close_items_to_the_left_by_id( pub fn close_items_to_the_left_by_id(
// &mut self, &mut self,
// item_id: usize, item_id: EntityId,
// cx: &mut ViewContext<Self>, cx: &mut ViewContext<Self>,
// ) -> Task<Result<()>> { ) -> Task<Result<()>> {
// let item_ids: Vec<_> = self let item_ids: Vec<_> = self
// .items() .items()
// .take_while(|item| item.id() != item_id) .take_while(|item| item.item_id() != item_id)
// .map(|item| item.id()) .map(|item| item.item_id())
// .collect(); .collect();
// self.close_items(cx, SaveIntent::Close, move |item_id| { self.close_items(cx, SaveIntent::Close, move |item_id| {
// item_ids.contains(&item_id) item_ids.contains(&item_id)
// }) })
// } }
// pub fn close_items_to_the_right( pub fn close_items_to_the_right(
// &mut self, &mut self,
// _: &CloseItemsToTheRight, _: &CloseItemsToTheRight,
// cx: &mut ViewContext<Self>, cx: &mut ViewContext<Self>,
// ) -> Option<Task<Result<()>>> { ) -> Option<Task<Result<()>>> {
// if self.items.is_empty() { if self.items.is_empty() {
// return None; return None;
// } }
// let active_item_id = self.items[self.active_item_index].id(); let active_item_id = self.items[self.active_item_index].item_id();
// Some(self.close_items_to_the_right_by_id(active_item_id, cx)) Some(self.close_items_to_the_right_by_id(active_item_id, cx))
// } }
// pub fn close_items_to_the_right_by_id( pub fn close_items_to_the_right_by_id(
// &mut self, &mut self,
// item_id: usize, item_id: EntityId,
// cx: &mut ViewContext<Self>, cx: &mut ViewContext<Self>,
// ) -> Task<Result<()>> { ) -> Task<Result<()>> {
// let item_ids: Vec<_> = self let item_ids: Vec<_> = self
// .items() .items()
// .rev() .rev()
// .take_while(|item| item.id() != item_id) .take_while(|item| item.item_id() != item_id)
// .map(|item| item.id()) .map(|item| item.item_id())
// .collect(); .collect();
// self.close_items(cx, SaveIntent::Close, move |item_id| { self.close_items(cx, SaveIntent::Close, move |item_id| {
// item_ids.contains(&item_id) item_ids.contains(&item_id)
// }) })
// } }
// pub fn close_all_items( pub fn close_all_items(
// &mut self, &mut self,
// action: &CloseAllItems, action: &CloseAllItems,
// cx: &mut ViewContext<Self>, cx: &mut ViewContext<Self>,
// ) -> Option<Task<Result<()>>> { ) -> Option<Task<Result<()>>> {
// if self.items.is_empty() { if self.items.is_empty() {
// return None; return None;
// } }
// Some( Some(
// self.close_items(cx, action.save_intent.unwrap_or(SaveIntent::Close), |_| { self.close_items(cx, action.save_intent.unwrap_or(SaveIntent::Close), |_| {
// true true
// }), }),
// ) )
// } }
pub(super) fn file_names_for_prompt( pub(super) fn file_names_for_prompt(
items: &mut dyn Iterator<Item = &Box<dyn ItemHandle>>, items: &mut dyn Iterator<Item = &Box<dyn ItemHandle>>,
@ -898,7 +878,7 @@ impl Pane {
let mut items_to_close = Vec::new(); let mut items_to_close = Vec::new();
let mut dirty_items = Vec::new(); let mut dirty_items = Vec::new();
for item in &self.items { for item in &self.items {
if should_close(item.id()) { if should_close(item.item_id()) {
items_to_close.push(item.boxed_clone()); items_to_close.push(item.boxed_clone());
if item.is_dirty(cx) { if item.is_dirty(cx) {
dirty_items.push(item.boxed_clone()); dirty_items.push(item.boxed_clone());
@ -951,7 +931,7 @@ impl Pane {
for item in workspace.items(cx) { for item in workspace.items(cx) {
if !items_to_close if !items_to_close
.iter() .iter()
.any(|item_to_close| item_to_close.id() == item.id()) .any(|item_to_close| item_to_close.item_id() == item.item_id())
{ {
let other_project_item_ids = item.project_item_model_ids(cx); let other_project_item_ids = item.project_item_model_ids(cx);
project_item_ids.retain(|id| !other_project_item_ids.contains(id)); project_item_ids.retain(|id| !other_project_item_ids.contains(id));
@ -979,7 +959,11 @@ impl Pane {
// Remove the item from the pane. // Remove the item from the pane.
pane.update(&mut cx, |pane, cx| { pane.update(&mut cx, |pane, cx| {
if let Some(item_ix) = pane.items.iter().position(|i| i.id() == item.id()) { if let Some(item_ix) = pane
.items
.iter()
.position(|i| i.item_id() == item.item_id())
{
pane.remove_item(item_ix, false, cx); pane.remove_item(item_ix, false, cx);
} }
})?; })?;
@ -997,7 +981,7 @@ impl Pane {
cx: &mut ViewContext<Self>, cx: &mut ViewContext<Self>,
) { ) {
self.activation_history self.activation_history
.retain(|&history_entry| history_entry != self.items[item_index].id()); .retain(|&history_entry| history_entry != self.items[item_index].item_id());
if item_index == self.active_item_index { if item_index == self.active_item_index {
let index_to_activate = self let index_to_activate = self
@ -1005,7 +989,7 @@ impl Pane {
.pop() .pop()
.and_then(|last_activated_item| { .and_then(|last_activated_item| {
self.items.iter().enumerate().find_map(|(index, item)| { self.items.iter().enumerate().find_map(|(index, item)| {
(item.id() == last_activated_item).then_some(index) (item.item_id() == last_activated_item).then_some(index)
}) })
}) })
// We didn't have a valid activation history entry, so fallback // We didn't have a valid activation history entry, so fallback
@ -1022,7 +1006,9 @@ impl Pane {
let item = self.items.remove(item_index); let item = self.items.remove(item_index);
cx.emit(Event::RemoveItem { item_id: item.id() }); cx.emit(Event::RemoveItem {
item_id: item.item_id(),
});
if self.items.is_empty() { if self.items.is_empty() {
item.deactivated(cx); item.deactivated(cx);
self.update_toolbar(cx); self.update_toolbar(cx);
@ -1043,16 +1029,20 @@ impl Pane {
.0 .0
.lock() .lock()
.paths_by_item .paths_by_item
.get(&item.id()) .get(&item.item_id())
.and_then(|(_, abs_path)| abs_path.clone()); .and_then(|(_, abs_path)| abs_path.clone());
self.nav_history self.nav_history
.0 .0
.lock() .lock()
.paths_by_item .paths_by_item
.insert(item.id(), (path, abs_path)); .insert(item.item_id(), (path, abs_path));
} else { } else {
self.nav_history.0.lock().paths_by_item.remove(&item.id()); self.nav_history
.0
.lock()
.paths_by_item
.remove(&item.item_id());
} }
if self.items.is_empty() && self.zoomed { if self.items.is_empty() && self.zoomed {
@ -1325,7 +1315,7 @@ impl Pane {
) -> Option<()> { ) -> Option<()> {
let (item_index_to_delete, item_id) = self.items().enumerate().find_map(|(i, item)| { let (item_index_to_delete, item_id) = self.items().enumerate().find_map(|(i, item)| {
if item.is_singleton(cx) && item.project_entry_ids(cx).as_slice() == [entry_id] { if item.is_singleton(cx) && item.project_entry_ids(cx).as_slice() == [entry_id] {
Some((i, item.id())) Some((i, item.item_id()))
} else { } else {
None None
} }
@ -1356,10 +1346,10 @@ impl Pane {
) -> impl Component<Self> { ) -> impl Component<Self> {
let label = item.tab_content(Some(detail), cx); let label = item.tab_content(Some(detail), cx);
let close_icon = || { let close_icon = || {
let id = item.id(); let id = item.item_id();
div() div()
.id(item.id()) .id(item.item_id())
.invisible() .invisible()
.group_hover("", |style| style.visible()) .group_hover("", |style| style.visible())
.child(IconButton::new("close_tab", Icon::Close).on_click( .child(IconButton::new("close_tab", Icon::Close).on_click(
@ -1389,7 +1379,7 @@ impl Pane {
div() div()
.group("") .group("")
.id(item.id()) .id(item.item_id())
.cursor_pointer() .cursor_pointer()
.when_some(item.tab_tooltip_text(cx), |div, text| { .when_some(item.tab_tooltip_text(cx), |div, text| {
div.tooltip(move |_, cx| cx.build_view(|cx| Tooltip::new(text.clone())).into()) div.tooltip(move |_, cx| cx.build_view(|cx| Tooltip::new(text.clone())).into())
@ -1916,8 +1906,27 @@ impl Render for Pane {
.on_action(|pane: &mut Pane, _: &SplitUp, cx| pane.split(SplitDirection::Up, cx)) .on_action(|pane: &mut Pane, _: &SplitUp, cx| pane.split(SplitDirection::Up, cx))
.on_action(|pane: &mut Pane, _: &SplitRight, cx| pane.split(SplitDirection::Right, cx)) .on_action(|pane: &mut Pane, _: &SplitRight, cx| pane.split(SplitDirection::Right, cx))
.on_action(|pane: &mut Pane, _: &SplitDown, cx| pane.split(SplitDirection::Down, cx)) .on_action(|pane: &mut Pane, _: &SplitDown, cx| pane.split(SplitDirection::Down, cx))
// cx.add_action(Pane::toggle_zoom);
// cx.add_action(|pane: &mut Pane, action: &ActivateItem, cx| {
// pane.activate_item(action.0, true, true, cx);
// });
// cx.add_action(|pane: &mut Pane, _: &ActivateLastItem, cx| {
// pane.activate_item(pane.items.len() - 1, true, true, cx);
// });
// cx.add_action(|pane: &mut Pane, _: &ActivatePrevItem, cx| {
// pane.activate_prev_item(true, cx);
// });
// cx.add_action(|pane: &mut Pane, _: &ActivateNextItem, cx| {
// pane.activate_next_item(true, cx);
// });
// cx.add_async_action(Pane::close_active_item);
// cx.add_async_action(Pane::close_inactive_items);
// cx.add_async_action(Pane::close_clean_items);
// cx.add_async_action(Pane::close_items_to_the_left);
// cx.add_async_action(Pane::close_items_to_the_right);
// cx.add_async_action(Pane::close_all_items);
.size_full() .size_full()
.on_action(|pane: &mut Self, action, cx| { .on_action(|pane: &mut Self, action: &CloseActiveItem, cx| {
pane.close_active_item(action, cx) pane.close_active_item(action, cx)
.map(|task| task.detach_and_log_err(cx)); .map(|task| task.detach_and_log_err(cx));
}) })

View File

@ -240,7 +240,7 @@ impl From<&Box<dyn SearchableItemHandle>> for AnyView {
impl PartialEq for Box<dyn SearchableItemHandle> { impl PartialEq for Box<dyn SearchableItemHandle> {
fn eq(&self, other: &Self) -> bool { fn eq(&self, other: &Self) -> bool {
self.id() == other.id() self.item_id() == other.item_id()
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -11,7 +11,7 @@ path = "src/zed2.rs"
doctest = false doctest = false
[[bin]] [[bin]]
name = "Zed" name = "Zed2"
path = "src/main.rs" path = "src/main.rs"
[dependencies] [dependencies]

View File

@ -107,7 +107,7 @@ impl LspAdapter for JsonLspAdapter {
&self, &self,
cx: &mut AppContext, cx: &mut AppContext,
) -> BoxFuture<'static, serde_json::Value> { ) -> BoxFuture<'static, serde_json::Value> {
let action_names = gpui::all_action_names(); let action_names = cx.all_action_names();
let staff_mode = cx.is_staff(); let staff_mode = cx.is_staff();
let language_names = &self.languages.language_names(); let language_names = &self.languages.language_names();
let settings_schema = cx.global::<SettingsStore>().json_schema( let settings_schema = cx.global::<SettingsStore>().json_schema(

View File

@ -140,7 +140,7 @@ fn main() {
cx.set_global(client.clone()); cx.set_global(client.clone());
theme::init(cx); theme::init(theme::LoadThemes::All, cx);
project::Project::init(&client, cx); project::Project::init(&client, cx);
client::init(&client, cx); client::init(&client, cx);
command_palette::init(cx); command_palette::init(cx);

View File

@ -1,4 +1,5 @@
use gpui::action; use gpui::Action;
use serde::Deserialize;
// If the zed binary doesn't use anything in this crate, it will be optimized away // If the zed binary doesn't use anything in this crate, it will be optimized away
// and the actions won't initialize. So we just provide an empty initialization function // and the actions won't initialize. So we just provide an empty initialization function
@ -9,12 +10,12 @@ use gpui::action;
// https://github.com/mmastrac/rust-ctor/issues/280 // https://github.com/mmastrac/rust-ctor/issues/280
pub fn init() {} pub fn init() {}
#[action] #[derive(Clone, PartialEq, Deserialize, Action)]
pub struct OpenBrowser { pub struct OpenBrowser {
pub url: String, pub url: String,
} }
#[action] #[derive(Clone, PartialEq, Deserialize, Action)]
pub struct OpenZedURL { pub struct OpenZedURL {
pub url: String, pub url: String,
} }