Merge branch 'zed2' into gpui2-element-renderer

This commit is contained in:
Marshall Bowers
2023-10-26 10:10:10 +02:00
13 changed files with 417 additions and 277 deletions

1
Cargo.lock generated
View File

@@ -3006,7 +3006,6 @@ dependencies = [
"libc",
"log",
"parking_lot 0.11.2",
"rand 0.8.5",
"regex",
"rope",
"serde",

View File

@@ -35,7 +35,6 @@ gpui2 = { path = "../gpui2", optional = true}
[dev-dependencies]
gpui2 = { path = "../gpui2", features = ["test-support"] }
rand.workspace = true
[features]
test-support = ["gpui2/test-support"]

View File

@@ -1222,62 +1222,57 @@ pub fn copy_recursive<'a>(
#[cfg(test)]
mod tests {
use super::*;
use gpui2::{Executor, TestDispatcher};
use rand::prelude::*;
use gpui2::Executor;
use serde_json::json;
#[test]
fn test_fake_fs() {
let dispatcher = TestDispatcher::new(StdRng::seed_from_u64(0));
let executor = Executor::new(Arc::new(dispatcher));
#[gpui2::test]
async fn test_fake_fs(executor: Executor) {
let fs = FakeFs::new(executor.clone());
executor.block(async move {
fs.insert_tree(
"/root",
json!({
"dir1": {
"a": "A",
"b": "B"
},
"dir2": {
"c": "C",
"dir3": {
"d": "D"
}
fs.insert_tree(
"/root",
json!({
"dir1": {
"a": "A",
"b": "B"
},
"dir2": {
"c": "C",
"dir3": {
"d": "D"
}
}),
)
}
}),
)
.await;
assert_eq!(
fs.files(),
vec![
PathBuf::from("/root/dir1/a"),
PathBuf::from("/root/dir1/b"),
PathBuf::from("/root/dir2/c"),
PathBuf::from("/root/dir2/dir3/d"),
]
);
fs.insert_symlink("/root/dir2/link-to-dir3", "./dir3".into())
.await;
assert_eq!(
fs.files(),
vec![
PathBuf::from("/root/dir1/a"),
PathBuf::from("/root/dir1/b"),
PathBuf::from("/root/dir2/c"),
PathBuf::from("/root/dir2/dir3/d"),
]
);
fs.insert_symlink("/root/dir2/link-to-dir3", "./dir3".into())
.await;
assert_eq!(
fs.canonicalize("/root/dir2/link-to-dir3".as_ref())
.await
.unwrap(),
PathBuf::from("/root/dir2/dir3"),
);
assert_eq!(
fs.canonicalize("/root/dir2/link-to-dir3/d".as_ref())
.await
.unwrap(),
PathBuf::from("/root/dir2/dir3/d"),
);
assert_eq!(
fs.load("/root/dir2/link-to-dir3/d".as_ref()).await.unwrap(),
"D",
);
});
assert_eq!(
fs.canonicalize("/root/dir2/link-to-dir3".as_ref())
.await
.unwrap(),
PathBuf::from("/root/dir2/dir3"),
);
assert_eq!(
fs.canonicalize("/root/dir2/link-to-dir3/d".as_ref())
.await
.unwrap(),
PathBuf::from("/root/dir2/dir3/d"),
);
assert_eq!(
fs.load("/root/dir2/link-to-dir3/d".as_ref()).await.unwrap(),
"D",
);
}
}

View File

@@ -48,6 +48,14 @@ impl TestAppContext {
}
}
pub fn remove_all_windows(&self) {
// todo!("use app quit instead")
}
pub fn clear_globals(&self) {
// todo!("use app quit instead")
}
pub fn refresh(&mut self) -> Result<()> {
let mut lock = self.app.lock();
lock.refresh();

View File

@@ -17,6 +17,8 @@ mod styled;
mod subscription;
mod svg_renderer;
mod taffy;
#[cfg(any(test, feature = "test-support"))]
mod test;
mod text_system;
mod util;
mod view;
@@ -48,6 +50,8 @@ pub use styled::*;
pub use subscription::*;
pub use svg_renderer::*;
pub use taffy::{AvailableSpace, LayoutId};
#[cfg(any(test, feature = "test-support"))]
pub use test::*;
pub use text_system::*;
pub use util::arc_cow::ArcCow;
pub use view::*;

View File

@@ -75,6 +75,10 @@ impl TestDispatcher {
count: self.state.lock().random.gen_range(0..10),
}
}
pub fn run_until_parked(&self) {
while self.poll() {}
}
}
impl Clone for TestDispatcher {

51
crates/gpui2/src/test.rs Normal file
View File

@@ -0,0 +1,51 @@
use crate::TestDispatcher;
use rand::prelude::*;
use std::{
env,
panic::{self, RefUnwindSafe},
};
pub fn run_test(
mut num_iterations: u64,
max_retries: usize,
test_fn: &mut (dyn RefUnwindSafe + Fn(TestDispatcher)),
on_fail_fn: Option<fn()>,
_fn_name: String, // todo!("re-enable fn_name")
) {
let starting_seed = env::var("SEED")
.map(|seed| seed.parse().expect("invalid SEED variable"))
.unwrap_or(0);
let is_randomized = num_iterations > 1;
if let Ok(iterations) = env::var("ITERATIONS") {
num_iterations = iterations.parse().expect("invalid ITERATIONS variable");
}
for seed in starting_seed..starting_seed + num_iterations {
let mut retry = 0;
loop {
if is_randomized {
eprintln!("seed = {seed}");
}
let result = panic::catch_unwind(|| {
let dispatcher = TestDispatcher::new(StdRng::seed_from_u64(seed));
test_fn(dispatcher);
});
match result {
Ok(_) => break,
Err(error) => {
if retry < max_retries {
println!("retrying: attempt {}", retry);
retry += 1;
} else {
if is_randomized {
eprintln!("failing seed: {}", seed);
}
on_fail_fn.map(|f| f());
panic::resume_unwind(error);
}
}
}
}
}
}

View File

@@ -2,6 +2,7 @@ use proc_macro::TokenStream;
mod derive_element;
mod style_helpers;
mod test;
#[proc_macro]
pub fn style_helpers(args: TokenStream) -> TokenStream {
@@ -12,3 +13,8 @@ pub fn style_helpers(args: TokenStream) -> TokenStream {
pub fn derive_element(input: TokenStream) -> TokenStream {
derive_element::derive_element(input)
}
#[proc_macro_attribute]
pub fn test(args: TokenStream, function: TokenStream) -> TokenStream {
test::test(args, function)
}

View File

@@ -0,0 +1,245 @@
use proc_macro::TokenStream;
use proc_macro2::Ident;
use quote::{format_ident, quote};
use std::mem;
use syn::{
parse_macro_input, parse_quote, spanned::Spanned as _, AttributeArgs, FnArg,
ItemFn, Lit, Meta, NestedMeta, Type,
};
pub fn test(args: TokenStream, function: TokenStream) -> TokenStream {
let args = syn::parse_macro_input!(args as AttributeArgs);
let mut max_retries = 0;
let mut num_iterations = 1;
let mut on_failure_fn_name = quote!(None);
for arg in args {
match arg {
NestedMeta::Meta(Meta::NameValue(meta)) => {
let key_name = meta.path.get_ident().map(|i| i.to_string());
let result = (|| {
match key_name.as_deref() {
Some("retries") => max_retries = parse_int(&meta.lit)?,
Some("iterations") => num_iterations = parse_int(&meta.lit)?,
Some("on_failure") => {
if let Lit::Str(name) = meta.lit {
let mut path = syn::Path {
leading_colon: None,
segments: Default::default(),
};
for part in name.value().split("::") {
path.segments.push(Ident::new(part, name.span()).into());
}
on_failure_fn_name = quote!(Some(#path));
} else {
return Err(TokenStream::from(
syn::Error::new(
meta.lit.span(),
"on_failure argument must be a string",
)
.into_compile_error(),
));
}
}
_ => {
return Err(TokenStream::from(
syn::Error::new(meta.path.span(), "invalid argument")
.into_compile_error(),
))
}
}
Ok(())
})();
if let Err(tokens) = result {
return tokens;
}
}
other => {
return TokenStream::from(
syn::Error::new_spanned(other, "invalid argument").into_compile_error(),
)
}
}
}
let mut inner_fn = parse_macro_input!(function as ItemFn);
if max_retries > 0 && num_iterations > 1 {
return TokenStream::from(
syn::Error::new_spanned(inner_fn, "retries and randomized iterations can't be mixed")
.into_compile_error(),
);
}
let inner_fn_attributes = mem::take(&mut inner_fn.attrs);
let inner_fn_name = format_ident!("_{}", inner_fn.sig.ident);
let outer_fn_name = mem::replace(&mut inner_fn.sig.ident, inner_fn_name.clone());
let mut outer_fn: ItemFn = if inner_fn.sig.asyncness.is_some() {
// Pass to the test function the number of app contexts that it needs,
// based on its parameter list.
let mut cx_vars = proc_macro2::TokenStream::new();
let mut cx_teardowns = proc_macro2::TokenStream::new();
let mut inner_fn_args = proc_macro2::TokenStream::new();
for (ix, arg) in inner_fn.sig.inputs.iter().enumerate() {
if let FnArg::Typed(arg) = arg {
if let Type::Path(ty) = &*arg.ty {
let last_segment = ty.path.segments.last();
match last_segment.map(|s| s.ident.to_string()).as_deref() {
Some("StdRng") => {
inner_fn_args.extend(quote!(rand::SeedableRng::seed_from_u64(seed),));
continue;
}
Some("Executor") => {
inner_fn_args.extend(quote!(gpui2::Executor::new(
std::sync::Arc::new(dispatcher.clone())
),));
continue;
}
_ => {}
}
} else if let Type::Reference(ty) = &*arg.ty {
if let Type::Path(ty) = &*ty.elem {
let last_segment = ty.path.segments.last();
if let Some("TestAppContext") =
last_segment.map(|s| s.ident.to_string()).as_deref()
{
let cx_varname = format_ident!("cx_{}", ix);
cx_vars.extend(quote!(
let mut #cx_varname = gpui2::TestAppContext::new(
dispatcher.clone()
);
));
cx_teardowns.extend(quote!(
#cx_varname.remove_all_windows();
dispatcher.run_until_parked();
#cx_varname.clear_globals();
dispatcher.run_until_parked();
));
inner_fn_args.extend(quote!(&mut #cx_varname,));
continue;
}
}
}
}
return TokenStream::from(
syn::Error::new_spanned(arg, "invalid argument").into_compile_error(),
);
}
parse_quote! {
#[test]
fn #outer_fn_name() {
#inner_fn
gpui2::run_test(
#num_iterations as u64,
#max_retries,
&mut |dispatcher| {
let executor = gpui2::Executor::new(std::sync::Arc::new(dispatcher.clone()));
#cx_vars
executor.block(#inner_fn_name(#inner_fn_args));
#cx_teardowns
},
#on_failure_fn_name,
stringify!(#outer_fn_name).to_string(),
);
}
}
} else {
// Pass to the test function the number of app contexts that it needs,
// based on its parameter list.
let mut cx_vars = proc_macro2::TokenStream::new();
let mut cx_teardowns = proc_macro2::TokenStream::new();
let mut inner_fn_args = proc_macro2::TokenStream::new();
for (ix, arg) in inner_fn.sig.inputs.iter().enumerate() {
if let FnArg::Typed(arg) = arg {
if let Type::Path(ty) = &*arg.ty {
let last_segment = ty.path.segments.last();
if let Some("StdRng") = last_segment.map(|s| s.ident.to_string()).as_deref() {
inner_fn_args.extend(quote!(rand::SeedableRng::seed_from_u64(seed),));
continue;
}
} else if let Type::Reference(ty) = &*arg.ty {
if let Type::Path(ty) = &*ty.elem {
let last_segment = ty.path.segments.last();
match last_segment.map(|s| s.ident.to_string()).as_deref() {
Some("AppContext") => {
let cx_varname = format_ident!("cx_{}", ix);
let cx_varname_lock = format_ident!("cx_{}_lock", ix);
cx_vars.extend(quote!(
let mut #cx_varname = gpui2::TestAppContext::new(
dispatcher.clone()
);
let mut #cx_varname_lock = cx_varname.app.lock();
));
inner_fn_args.extend(quote!(&mut #cx_varname_lock,));
cx_teardowns.extend(quote!(
#cx_varname.remove_all_windows();
dispatcher.run_until_parked();
#cx_varname.clear_globals();
dispatcher.run_until_parked();
));
continue;
}
Some("TestAppContext") => {
let cx_varname = format_ident!("cx_{}", ix);
cx_vars.extend(quote!(
let mut #cx_varname = gpui2::TestAppContext::new(
dispatcher.clone()
);
));
cx_teardowns.extend(quote!(
#cx_varname.remove_all_windows();
dispatcher.run_until_parked();
#cx_varname.clear_globals();
dispatcher.run_until_parked();
));
inner_fn_args.extend(quote!(&mut #cx_varname,));
continue;
}
_ => {}
}
}
}
}
return TokenStream::from(
syn::Error::new_spanned(arg, "invalid argument").into_compile_error(),
);
}
parse_quote! {
#[test]
fn #outer_fn_name() {
#inner_fn
gpui2::run_test(
#num_iterations as u64,
#max_retries,
&mut |dispatcher| {
#cx_vars
#inner_fn_name(#inner_fn_args);
#cx_teardowns
},
#on_failure_fn_name,
stringify!(#outer_fn_name).to_string(),
);
}
}
};
outer_fn.attrs.extend(inner_fn_attributes);
TokenStream::from(quote!(#outer_fn))
}
fn parse_int(literal: &Lit) -> Result<usize, TokenStream> {
let result = if let Lit::Int(int) = &literal {
int.base10_parse()
} else {
Err(syn::Error::new(literal.span(), "must be an integer"))
};
result.map_err(|err| TokenStream::from(err.into_compile_error()))
}

View File

@@ -1,3 +1,7 @@
use crate::Buffer;
use gpui2::{Context, TestAppContext};
use text::{Point, ToPoint};
// use crate::language_settings::{
// AllLanguageSettings, AllLanguageSettingsContent, LanguageSettingsContent,
// };
@@ -219,28 +223,29 @@
// );
// }
// #[gpui::test]
// async fn test_apply_diff(cx: &mut gpui::TestAppContext) {
// let text = "a\nbb\nccc\ndddd\neeeee\nffffff\n";
// let buffer = cx.add_model(|cx| Buffer::new(0, cx.model_id() as u64, text));
// let anchor = buffer.read_with(cx, |buffer, _| buffer.anchor_before(Point::new(3, 3)));
// #[gpui::test] todo!()
#[gpui2::test]
async fn test_apply_diff(cx: &mut TestAppContext) {
let text = "a\nbb\nccc\ndddd\neeeee\nffffff\n";
let buffer = cx.entity(|cx| Buffer::new(0, cx.entity_id().as_u64(), text));
let anchor = buffer.update(cx, |buffer, _| buffer.anchor_before(Point::new(3, 3)));
// let text = "a\nccc\ndddd\nffffff\n";
// let diff = buffer.read_with(cx, |b, cx| b.diff(text.into(), cx)).await;
// buffer.update(cx, |buffer, cx| {
// buffer.apply_diff(diff, cx).unwrap();
// assert_eq!(buffer.text(), text);
// assert_eq!(anchor.to_point(buffer), Point::new(2, 3));
// });
let text = "a\nccc\ndddd\nffffff\n";
let diff = buffer.update(cx, |b, cx| b.diff(text.into(), cx)).await;
buffer.update(cx, |buffer, cx| {
buffer.apply_diff(diff, cx).unwrap();
assert_eq!(buffer.text(), text);
assert_eq!(anchor.to_point(buffer), Point::new(2, 3));
});
// let text = "a\n1\n\nccc\ndd2dd\nffffff\n";
// let diff = buffer.read_with(cx, |b, cx| b.diff(text.into(), cx)).await;
// buffer.update(cx, |buffer, cx| {
// buffer.apply_diff(diff, cx).unwrap();
// assert_eq!(buffer.text(), text);
// assert_eq!(anchor.to_point(buffer), Point::new(4, 4));
// });
// }
let text = "a\n1\n\nccc\ndd2dd\nffffff\n";
let diff = buffer.update(cx, |b, cx| b.diff(text.into(), cx)).await;
buffer.update(cx, |buffer, cx| {
buffer.apply_diff(diff, cx).unwrap();
assert_eq!(buffer.text(), text);
assert_eq!(anchor.to_point(buffer), Point::new(4, 4));
});
}
// #[gpui::test(iterations = 10)]
// async fn test_normalize_whitespace(cx: &mut gpui::TestAppContext) {

View File

@@ -1,184 +0,0 @@
pub use crate::{old_theme, ButtonVariant, ElementExt, Theme};
use gpui2::{rgb, Hsla, WindowContext};
use strum::EnumIter;
#[derive(Clone, Copy)]
pub struct PlayerThemeColors {
pub cursor: Hsla,
pub selection: Hsla,
}
impl PlayerThemeColors {
pub fn new(cx: &WindowContext, ix: usize) -> Self {
let theme = old_theme(cx);
if ix < theme.players.len() {
Self {
cursor: theme.players[ix].cursor,
selection: theme.players[ix].selection,
}
} else {
Self {
cursor: rgb::<Hsla>(0xff00ff),
selection: rgb::<Hsla>(0xff00ff),
}
}
}
}
#[derive(Clone, Copy, Debug)]
pub struct SyntaxColor {
pub comment: Hsla,
pub string: Hsla,
pub function: Hsla,
pub keyword: Hsla,
}
impl SyntaxColor {
pub fn new(cx: &WindowContext) -> Self {
let theme = old_theme(cx);
Self {
comment: theme
.syntax
.get("comment")
.cloned()
.unwrap_or_else(|| rgb::<Hsla>(0xff00ff)),
string: theme
.syntax
.get("string")
.cloned()
.unwrap_or_else(|| rgb::<Hsla>(0xff00ff)),
function: theme
.syntax
.get("function")
.cloned()
.unwrap_or_else(|| rgb::<Hsla>(0xff00ff)),
keyword: theme
.syntax
.get("keyword")
.cloned()
.unwrap_or_else(|| rgb::<Hsla>(0xff00ff)),
}
}
}
/// ThemeColor is the primary interface for coloring elements in the UI.
///
/// It is a mapping layer between semantic theme colors and colors from the reference library.
///
/// While we are between zed and zed2 we use this to map semantic colors to the old theme.
#[derive(Clone, Copy)]
pub struct ThemeColor {
pub transparent: Hsla,
pub mac_os_traffic_light_red: Hsla,
pub mac_os_traffic_light_yellow: Hsla,
pub mac_os_traffic_light_green: Hsla,
pub border: Hsla,
pub border_variant: Hsla,
pub border_focused: Hsla,
pub border_transparent: Hsla,
/// The background color of an elevated surface, like a modal, tooltip or toast.
pub elevated_surface: Hsla,
pub surface: Hsla,
/// Window background color of the base app
pub background: Hsla,
/// Default background for elements like filled buttons,
/// text fields, checkboxes, radio buttons, etc.
/// - TODO: Map to step 3.
pub filled_element: Hsla,
/// The background color of a hovered element, like a button being hovered
/// with a mouse, or hovered on a touch screen.
/// - TODO: Map to step 4.
pub filled_element_hover: Hsla,
/// The background color of an active element, like a button being pressed,
/// or tapped on a touch screen.
/// - TODO: Map to step 5.
pub filled_element_active: Hsla,
/// The background color of a selected element, like a selected tab,
/// a button toggled on, or a checkbox that is checked.
pub filled_element_selected: Hsla,
pub filled_element_disabled: Hsla,
pub ghost_element: Hsla,
/// The background color of a hovered element with no default background,
/// like a ghost-style button or an interactable list item.
/// - TODO: Map to step 3.
pub ghost_element_hover: Hsla,
/// - TODO: Map to step 4.
pub ghost_element_active: Hsla,
pub ghost_element_selected: Hsla,
pub ghost_element_disabled: Hsla,
pub text: Hsla,
pub text_muted: Hsla,
pub text_placeholder: Hsla,
pub text_disabled: Hsla,
pub text_accent: Hsla,
pub icon_muted: Hsla,
pub syntax: SyntaxColor,
pub status_bar: Hsla,
pub title_bar: Hsla,
pub toolbar: Hsla,
pub tab_bar: Hsla,
/// The background of the editor
pub editor: Hsla,
pub editor_subheader: Hsla,
pub editor_active_line: Hsla,
pub terminal: Hsla,
pub image_fallback_background: Hsla,
pub git_created: Hsla,
pub git_modified: Hsla,
pub git_deleted: Hsla,
pub git_conflict: Hsla,
pub git_ignored: Hsla,
pub git_renamed: Hsla,
pub players: [PlayerThemeColors; 8],
}
/// Colors used exclusively for syntax highlighting.
///
/// For now we deserialize these from a theme.
/// These will be defined statically in the new theme.
#[derive(Default, PartialEq, EnumIter, Clone, Copy)]
pub enum HighlightColor {
#[default]
Default,
Comment,
String,
Function,
Keyword,
}
impl HighlightColor {
pub fn hsla(&self, theme: &Theme) -> Hsla {
match self {
Self::Default => theme
.syntax
.get("primary")
.cloned()
.expect("Couldn't find `primary` in theme.syntax"),
Self::Comment => theme
.syntax
.get("comment")
.cloned()
.expect("Couldn't find `comment` in theme.syntax"),
Self::String => theme
.syntax
.get("string")
.cloned()
.expect("Couldn't find `string` in theme.syntax"),
Self::Function => theme
.syntax
.get("function")
.cloned()
.expect("Couldn't find `function` in theme.syntax"),
Self::Keyword => theme
.syntax
.get("keyword")
.cloned()
.expect("Couldn't find `keyword` in theme.syntax"),
}
}
}

View File

@@ -17,7 +17,6 @@
// TODO: Fix warnings instead of supressing.
#![allow(dead_code, unused_variables)]
mod color;
mod components;
mod element_ext;
mod elements;

View File

@@ -3,7 +3,6 @@ pub use gpui2::{
StatelessInteractive, Styled, ViewContext, WindowContext,
};
pub use crate::color::*;
pub use crate::elevation::*;
use crate::settings::user_settings;
pub use crate::{old_theme, theme, ButtonVariant, ElementExt, Theme};
@@ -27,13 +26,17 @@ pub enum FileSystemStatus {
Deleted,
}
impl FileSystemStatus {
pub fn to_string(&self) -> String {
match self {
Self::None => "None".to_string(),
Self::Conflict => "Conflict".to_string(),
Self::Deleted => "Deleted".to_string(),
}
impl std::fmt::Display for FileSystemStatus {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
Self::None => "None",
Self::Conflict => "Conflict",
Self::Deleted => "Deleted",
}
)
}
}
@@ -49,17 +52,6 @@ pub enum GitStatus {
}
impl GitStatus {
pub fn to_string(&self) -> String {
match self {
Self::None => "None".to_string(),
Self::Created => "Created".to_string(),
Self::Modified => "Modified".to_string(),
Self::Deleted => "Deleted".to_string(),
Self::Conflict => "Conflict".to_string(),
Self::Renamed => "Renamed".to_string(),
}
}
pub fn hsla(&self, cx: &WindowContext) -> Hsla {
let theme = theme(cx);
@@ -74,6 +66,23 @@ impl GitStatus {
}
}
impl std::fmt::Display for GitStatus {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
Self::None => "None",
Self::Created => "Created",
Self::Modified => "Modified",
Self::Deleted => "Deleted",
Self::Conflict => "Conflict",
Self::Renamed => "Renamed",
}
)
}
}
#[derive(Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, EnumIter)]
pub enum DiagnosticStatus {
#[default]