From 4fa28b3de221f643f3515b799e01c775b1e31515 Mon Sep 17 00:00:00 2001 From: Piotr Osiewicz <24362066+osiewicz@users.noreply.github.com> Date: Mon, 1 Jan 2024 23:50:14 +0100 Subject: [PATCH 01/11] chore: fix clippy lints for rope2, sum_tree, text2 and util --- crates/rope2/src/rope2.rs | 2 +- crates/sum_tree/src/tree_map.rs | 6 ++---- crates/text2/src/locator.rs | 4 ++-- crates/text2/src/subscription.rs | 2 +- crates/text2/src/text2.rs | 2 +- crates/util/src/paths.rs | 6 +++--- 6 files changed, 10 insertions(+), 12 deletions(-) diff --git a/crates/rope2/src/rope2.rs b/crates/rope2/src/rope2.rs index 4cea1d4759032f710c92a4dcaea98a3bf4f488b9..adfcd19a6c5420f12fab5495731cea7b9e70397a 100644 --- a/crates/rope2/src/rope2.rs +++ b/crates/rope2/src/rope2.rs @@ -906,7 +906,7 @@ impl Chunk { fn clip_offset_utf16(&self, target: OffsetUtf16, bias: Bias) -> OffsetUtf16 { let mut code_units = self.0.encode_utf16(); - let mut offset = code_units.by_ref().take(target.0 as usize).count(); + let mut offset = code_units.by_ref().take(target.0).count(); if char::decode_utf16(code_units).next().transpose().is_err() { match bias { Bias::Left => offset -= 1, diff --git a/crates/sum_tree/src/tree_map.rs b/crates/sum_tree/src/tree_map.rs index edb9010e50eb172f379071ad4b2139991c5650d4..f39e3ed19a956e9c927459e9552660cf52adc874 100644 --- a/crates/sum_tree/src/tree_map.rs +++ b/crates/sum_tree/src/tree_map.rs @@ -40,7 +40,7 @@ impl TreeMap { self.0.is_empty() } - pub fn get<'a>(&self, key: &'a K) -> Option<&V> { + pub fn get(&self, key: &K) -> Option<&V> { let mut cursor = self.0.cursor::>(); cursor.seek(&MapKeyRef(Some(key)), Bias::Left, &()); if let Some(item) = cursor.item() { @@ -98,9 +98,7 @@ impl TreeMap { let from_key = MapKeyRef(Some(from)); cursor.seek(&from_key, Bias::Left, &()); - cursor - .into_iter() - .map(|map_entry| (&map_entry.key, &map_entry.value)) + cursor.map(|map_entry| (&map_entry.key, &map_entry.value)) } pub fn update(&mut self, key: &K, f: F) -> Option diff --git a/crates/text2/src/locator.rs b/crates/text2/src/locator.rs index 07b73ace05d80693a081d69f3f0aef410a228319..0fb2fa5d16ec542f12491e49d1bb22ab47ee012a 100644 --- a/crates/text2/src/locator.rs +++ b/crates/text2/src/locator.rs @@ -20,11 +20,11 @@ impl Locator { } pub fn min_ref() -> &'static Self { - &*MIN + &MIN } pub fn max_ref() -> &'static Self { - &*MAX + &MAX } pub fn assign(&mut self, other: &Self) { diff --git a/crates/text2/src/subscription.rs b/crates/text2/src/subscription.rs index b636dfcc923654619f7ea61d87b61d7abb4dbae5..878e8a2cfe0a82782300089881b8cf31b428d2c2 100644 --- a/crates/text2/src/subscription.rs +++ b/crates/text2/src/subscription.rs @@ -18,7 +18,7 @@ impl Topic { } pub fn publish(&self, edits: impl Clone + IntoIterator>) { - publish(&mut *self.0.lock(), edits); + publish(&mut self.0.lock(), edits); } pub fn publish_mut(&mut self, edits: impl Clone + IntoIterator>) { diff --git a/crates/text2/src/text2.rs b/crates/text2/src/text2.rs index c05ea1109c0665247e4b8e09e657658f52441bc6..f0931a76724aca3a01533f6a58e9ffe9970ad005 100644 --- a/crates/text2/src/text2.rs +++ b/crates/text2/src/text2.rs @@ -2655,7 +2655,7 @@ impl LineEnding { max_ix -= 1; } - if let Some(ix) = text[..max_ix].find(&['\n']) { + if let Some(ix) = text[..max_ix].find(['\n']) { if ix > 0 && text.as_bytes()[ix - 1] == b'\r' { Self::Windows } else { diff --git a/crates/util/src/paths.rs b/crates/util/src/paths.rs index 19b244383fdf2ab24cfec9381a6f8ddb87f6e977..7e8444f979b297ad7c1e198cb61b7dd9382c9ae9 100644 --- a/crates/util/src/paths.rs +++ b/crates/util/src/paths.rs @@ -67,8 +67,8 @@ impl> PathExt for T { fn icon_suffix(&self) -> Option<&str> { let file_name = self.as_ref().file_name()?.to_str()?; - if file_name.starts_with(".") { - return file_name.strip_prefix("."); + if file_name.starts_with('.') { + return file_name.strip_prefix('.'); } self.as_ref() @@ -213,7 +213,7 @@ impl Eq for PathMatcher {} impl PathMatcher { pub fn new(maybe_glob: &str) -> Result { Ok(PathMatcher { - glob: Glob::new(&maybe_glob)?.compile_matcher(), + glob: Glob::new(maybe_glob)?.compile_matcher(), maybe_path: PathBuf::from(maybe_glob), }) } From e2ec96e44a54ab9bf02fa5a71ce35cd882bcf414 Mon Sep 17 00:00:00 2001 From: Piotr Osiewicz <24362066+osiewicz@users.noreply.github.com> Date: Mon, 1 Jan 2024 23:52:07 +0100 Subject: [PATCH 02/11] Fixes for gpui2_macros --- crates/gpui2_macros/src/style_helpers.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/gpui2_macros/src/style_helpers.rs b/crates/gpui2_macros/src/style_helpers.rs index 181311807c8832a3e48dc05c445e489b7c9b22b0..b86bb2dfa60b7a97394cafe3fc4e1aaf22b87302 100644 --- a/crates/gpui2_macros/src/style_helpers.rs +++ b/crates/gpui2_macros/src/style_helpers.rs @@ -102,7 +102,7 @@ fn generate_methods() -> Vec { fn generate_predefined_setter( name: &'static str, length: &'static str, - fields: &Vec, + fields: &[TokenStream2], length_tokens: &TokenStream2, negate: bool, doc_string: &str, @@ -143,12 +143,12 @@ fn generate_predefined_setter( fn generate_custom_value_setter( prefix: &'static str, length_type: TokenStream2, - fields: &Vec, + fields: &[TokenStream2], doc_string: &str, ) -> TokenStream2 { let method_name = format_ident!("{}", prefix); - let mut iter = fields.into_iter(); + let mut iter = fields.iter(); let last = iter.next_back().unwrap(); let field_assignments = iter .map(|field_tokens| { From 86facbbe4a62486f695aba56e0c44cd448bbec60 Mon Sep 17 00:00:00 2001 From: Piotr Osiewicz <24362066+osiewicz@users.noreply.github.com> Date: Mon, 1 Jan 2024 23:56:04 +0100 Subject: [PATCH 03/11] sqlez --- crates/sqlez/src/migrations.rs | 8 ++++---- crates/sqlez/src/statement.rs | 4 ++-- crates/sqlez/src/thread_safe_connection.rs | 6 +++--- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/crates/sqlez/src/migrations.rs b/crates/sqlez/src/migrations.rs index b8e589e268c8f02693b11b7915b32eb8e0975d2f..c0d125d4df9f654364088f6af31c40c9f3192950 100644 --- a/crates/sqlez/src/migrations.rs +++ b/crates/sqlez/src/migrations.rs @@ -20,8 +20,8 @@ impl Connection { self.sqlite3, sql_str.as_c_str().as_ptr(), None, - 0 as *mut _, - 0 as *mut _, + std::ptr::null_mut(), + std::ptr::null_mut(), ); } self.last_error() @@ -59,10 +59,10 @@ impl Connection { if completed_migration != migration { return Err(anyhow!(formatdoc! {" Migration changed for {} at step {} - + Stored migration: {} - + Proposed migration: {}", domain, index, completed_migration, migration})); } else { diff --git a/crates/sqlez/src/statement.rs b/crates/sqlez/src/statement.rs index de0ad626a535cca8f18c6455435664403bb170f5..122b6d0c582c28e24e92414371f4a7c0a4e12614 100644 --- a/crates/sqlez/src/statement.rs +++ b/crates/sqlez/src/statement.rs @@ -232,13 +232,13 @@ impl<'a> Statement<'a> { .last_error() .with_context(|| format!("Failed to read text length at {index}"))?; - let slice = unsafe { slice::from_raw_parts(pointer as *const u8, len) }; + let slice = unsafe { slice::from_raw_parts(pointer, len) }; Ok(str::from_utf8(slice)?) } pub fn bind(&self, value: &T, index: i32) -> Result { debug_assert!(index > 0); - Ok(value.bind(self, index)?) + value.bind(self, index) } pub fn column(&mut self) -> Result { diff --git a/crates/sqlez/src/thread_safe_connection.rs b/crates/sqlez/src/thread_safe_connection.rs index 54241b6d72a45d412178d6be3d48cba41500fee6..98402df108e35d90b67d9aba4ac7574fd6c5b9d8 100644 --- a/crates/sqlez/src/thread_safe_connection.rs +++ b/crates/sqlez/src/thread_safe_connection.rs @@ -10,14 +10,14 @@ use crate::{connection::Connection, domain::Migrator, util::UnboundedSyncSender} const MIGRATION_RETRIES: usize = 10; type QueuedWrite = Box; -type WriteQueueConstructor = - Box Box>; +type WriteQueue = Box; +type WriteQueueConstructor = Box WriteQueue>; lazy_static! { /// List of queues of tasks by database uri. This lets us serialize writes to the database /// and have a single worker thread per db file. This means many thread safe connections /// (possibly with different migrations) could all be communicating with the same background /// thread. - static ref QUEUES: RwLock, Box>> = + static ref QUEUES: RwLock, WriteQueue>> = Default::default(); } From 7d420edb843b436e704be2aedb8f760fd53a0580 Mon Sep 17 00:00:00 2001 From: Piotr Osiewicz <24362066+osiewicz@users.noreply.github.com> Date: Tue, 2 Jan 2024 00:04:51 +0100 Subject: [PATCH 04/11] Start fixing up gpui2 --- crates/gpui2/src/geometry.rs | 9 +- .../gpui2/src/platform/mac/metal_renderer.rs | 48 +++--- crates/media/src/media.rs | 140 +++++++++--------- 3 files changed, 98 insertions(+), 99 deletions(-) diff --git a/crates/gpui2/src/geometry.rs b/crates/gpui2/src/geometry.rs index 6b4d9ae807b581eff4fe38baf913843e43bd8c83..292b0f4aa99234da2bc75e4bf3e22102dc13fec9 100644 --- a/crates/gpui2/src/geometry.rs +++ b/crates/gpui2/src/geometry.rs @@ -1896,7 +1896,6 @@ impl Into> for Pixels { Div, DivAssign, PartialEq, - PartialOrd, Serialize, Deserialize, )] @@ -2039,9 +2038,15 @@ impl Mul for Pixels { impl Eq for Pixels {} +impl PartialOrd for Pixels { + fn partial_cmp(&self, other: &Self) -> Option { + self.0.partial_cmp(&other.0) + } +} + impl Ord for Pixels { fn cmp(&self, other: &Self) -> cmp::Ordering { - self.0.partial_cmp(&other.0).unwrap() + self.partial_cmp(other).unwrap() } } diff --git a/crates/gpui2/src/platform/mac/metal_renderer.rs b/crates/gpui2/src/platform/mac/metal_renderer.rs index 68768521ee474cd25c2e98c8d38c7ea669fba1e4..7812eebf01bda8ff5fccf4605e66a188285302e2 100644 --- a/crates/gpui2/src/platform/mac/metal_renderer.rs +++ b/crates/gpui2/src/platform/mac/metal_renderer.rs @@ -174,7 +174,7 @@ impl MetalRenderer { unit_vertices, instances, sprite_atlas, - core_video_texture_cache: CVMetalTextureCache::new(device.as_ptr()).unwrap(), + core_video_texture_cache: unsafe { CVMetalTextureCache::new(device.as_ptr()).unwrap() }, } } @@ -849,28 +849,30 @@ impl MetalRenderer { media::core_video::kCVPixelFormatType_420YpCbCr8BiPlanarFullRange ); - let y_texture = self - .core_video_texture_cache - .create_texture_from_image( - surface.image_buffer.as_concrete_TypeRef(), - ptr::null(), - MTLPixelFormat::R8Unorm, - surface.image_buffer.plane_width(0), - surface.image_buffer.plane_height(0), - 0, - ) - .unwrap(); - let cb_cr_texture = self - .core_video_texture_cache - .create_texture_from_image( - surface.image_buffer.as_concrete_TypeRef(), - ptr::null(), - MTLPixelFormat::RG8Unorm, - surface.image_buffer.plane_width(1), - surface.image_buffer.plane_height(1), - 1, - ) - .unwrap(); + let y_texture = unsafe { + self.core_video_texture_cache + .create_texture_from_image( + surface.image_buffer.as_concrete_TypeRef(), + ptr::null(), + MTLPixelFormat::R8Unorm, + surface.image_buffer.plane_width(0), + surface.image_buffer.plane_height(0), + 0, + ) + .unwrap() + }; + let cb_cr_texture = unsafe { + self.core_video_texture_cache + .create_texture_from_image( + surface.image_buffer.as_concrete_TypeRef(), + ptr::null(), + MTLPixelFormat::RG8Unorm, + surface.image_buffer.plane_width(1), + surface.image_buffer.plane_height(1), + 1, + ) + .unwrap() + }; align_offset(offset); let next_offset = *offset + mem::size_of::(); diff --git a/crates/media/src/media.rs b/crates/media/src/media.rs index 1c76e6befbf42e0069dc95c2cfbd3b7a227183cf..650af06c37dbbc325bc825c06e375fef8adfe6a5 100644 --- a/crates/media/src/media.rs +++ b/crates/media/src/media.rs @@ -108,25 +108,23 @@ pub mod core_video { impl_CFTypeDescription!(CVMetalTextureCache); impl CVMetalTextureCache { - pub fn new(metal_device: *mut MTLDevice) -> Result { - unsafe { - let mut this = ptr::null(); - let result = CVMetalTextureCacheCreate( - kCFAllocatorDefault, - ptr::null(), - metal_device, - ptr::null(), - &mut this, - ); - if result == kCVReturnSuccess { - Ok(CVMetalTextureCache::wrap_under_create_rule(this)) - } else { - Err(anyhow!("could not create texture cache, code: {}", result)) - } + pub unsafe fn new(metal_device: *mut MTLDevice) -> Result { + let mut this = ptr::null(); + let result = CVMetalTextureCacheCreate( + kCFAllocatorDefault, + ptr::null(), + metal_device, + ptr::null(), + &mut this, + ); + if result == kCVReturnSuccess { + Ok(CVMetalTextureCache::wrap_under_create_rule(this)) + } else { + Err(anyhow!("could not create texture cache, code: {}", result)) } } - pub fn create_texture_from_image( + pub unsafe fn create_texture_from_image( &self, source: CVImageBufferRef, texture_attributes: CFDictionaryRef, @@ -135,24 +133,22 @@ pub mod core_video { height: usize, plane_index: usize, ) -> Result { - unsafe { - let mut this = ptr::null(); - let result = CVMetalTextureCacheCreateTextureFromImage( - kCFAllocatorDefault, - self.as_concrete_TypeRef(), - source, - texture_attributes, - pixel_format, - width, - height, - plane_index, - &mut this, - ); - if result == kCVReturnSuccess { - Ok(CVMetalTexture::wrap_under_create_rule(this)) - } else { - Err(anyhow!("could not create texture, code: {}", result)) - } + let mut this = ptr::null(); + let result = CVMetalTextureCacheCreateTextureFromImage( + kCFAllocatorDefault, + self.as_concrete_TypeRef(), + source, + texture_attributes, + pixel_format, + width, + height, + plane_index, + &mut this, + ); + if result == kCVReturnSuccess { + Ok(CVMetalTexture::wrap_under_create_rule(this)) + } else { + Err(anyhow!("could not create texture, code: {}", result)) } } } @@ -438,60 +434,56 @@ pub mod video_toolbox { impl_CFTypeDescription!(VTCompressionSession); impl VTCompressionSession { - pub fn new( + pub unsafe fn new( width: usize, height: usize, codec: CMVideoCodecType, callback: VTCompressionOutputCallback, callback_data: *const c_void, ) -> Result { - unsafe { - let mut this = ptr::null(); - let result = VTCompressionSessionCreate( - ptr::null(), - width as i32, - height as i32, - codec, - ptr::null(), - ptr::null(), - ptr::null(), - callback, - callback_data, - &mut this, - ); - - if result == 0 { - Ok(Self::wrap_under_create_rule(this)) - } else { - Err(anyhow!( - "error creating compression session, code {}", - result - )) - } + let mut this = ptr::null(); + let result = VTCompressionSessionCreate( + ptr::null(), + width as i32, + height as i32, + codec, + ptr::null(), + ptr::null(), + ptr::null(), + callback, + callback_data, + &mut this, + ); + + if result == 0 { + Ok(Self::wrap_under_create_rule(this)) + } else { + Err(anyhow!( + "error creating compression session, code {}", + result + )) } } - pub fn encode_frame( + pub unsafe fn encode_frame( &self, buffer: CVImageBufferRef, presentation_timestamp: CMTime, duration: CMTime, ) -> Result<()> { - unsafe { - let result = VTCompressionSessionEncodeFrame( - self.as_concrete_TypeRef(), - buffer, - presentation_timestamp, - duration, - ptr::null(), - ptr::null(), - ptr::null_mut(), - ); - if result == 0 { - Ok(()) - } else { - Err(anyhow!("error encoding frame, code {}", result)) - } + let result = VTCompressionSessionEncodeFrame( + self.as_concrete_TypeRef(), + buffer, + presentation_timestamp, + duration, + ptr::null(), + ptr::null(), + ptr::null_mut(), + ); + if result == 0 { + Ok(()) + } else { + Err(anyhow!("error encoding frame, code {}", result)) } } } From 2621efebeab3807201eda57a81195bdaa7909b40 Mon Sep 17 00:00:00 2001 From: Piotr Osiewicz <24362066+osiewicz@users.noreply.github.com> Date: Tue, 2 Jan 2024 00:09:24 +0100 Subject: [PATCH 05/11] Rest of fixups for gpui2 --- crates/gpui2/src/app.rs | 18 ++--- crates/gpui2/src/app/async_context.rs | 2 +- crates/gpui2/src/app/entity_map.rs | 4 +- crates/gpui2/src/app/model_context.rs | 4 +- crates/gpui2/src/color.rs | 6 +- crates/gpui2/src/element.rs | 2 +- crates/gpui2/src/elements/div.rs | 66 +++++++++---------- crates/gpui2/src/elements/text.rs | 2 +- crates/gpui2/src/elements/uniform_list.rs | 2 +- crates/gpui2/src/executor.rs | 6 ++ crates/gpui2/src/geometry.rs | 40 +++++------ crates/gpui2/src/interactive.rs | 4 +- crates/gpui2/src/key_dispatch.rs | 2 +- crates/gpui2/src/keymap/binding.rs | 2 +- crates/gpui2/src/keymap/context.rs | 4 +- crates/gpui2/src/platform/mac.rs | 4 +- crates/gpui2/src/platform/mac/dispatcher.rs | 6 ++ crates/gpui2/src/platform/mac/display.rs | 2 +- .../gpui2/src/platform/mac/display_linker.rs | 1 - crates/gpui2/src/platform/mac/metal_atlas.rs | 4 +- .../gpui2/src/platform/mac/metal_renderer.rs | 16 ++--- crates/gpui2/src/platform/mac/platform.rs | 8 ++- crates/gpui2/src/platform/mac/text_system.rs | 10 +-- crates/gpui2/src/platform/mac/window.rs | 18 +++-- crates/gpui2/src/scene.rs | 17 +---- crates/gpui2/src/shared_string.rs | 12 ++-- crates/gpui2/src/style.rs | 6 +- crates/gpui2/src/subscription.rs | 6 +- crates/gpui2/src/taffy.rs | 24 +++---- crates/gpui2/src/text_system.rs | 22 +++---- crates/gpui2/src/text_system/line_wrapper.rs | 12 ++-- crates/gpui2/src/view.rs | 12 ++-- crates/gpui2/src/window.rs | 36 +++++----- 33 files changed, 184 insertions(+), 196 deletions(-) diff --git a/crates/gpui2/src/app.rs b/crates/gpui2/src/app.rs index 8748a6024906307c9f8b0d581a390c8e9a3c179d..27410027168c0db1fb6ed6162a21d4c2068a0c9d 100644 --- a/crates/gpui2/src/app.rs +++ b/crates/gpui2/src/app.rs @@ -52,7 +52,7 @@ pub struct AppCell { impl AppCell { #[track_caller] pub fn borrow(&self) -> AppRef { - if let Some(_) = option_env!("TRACK_THREAD_BORROWS") { + if option_env!("TRACK_THREAD_BORROWS").is_some() { let thread_id = std::thread::current().id(); eprintln!("borrowed {thread_id:?}"); } @@ -61,7 +61,7 @@ impl AppCell { #[track_caller] pub fn borrow_mut(&self) -> AppRefMut { - if let Some(_) = option_env!("TRACK_THREAD_BORROWS") { + if option_env!("TRACK_THREAD_BORROWS").is_some() { let thread_id = std::thread::current().id(); eprintln!("borrowed {thread_id:?}"); } @@ -74,7 +74,7 @@ pub struct AppRef<'a>(Ref<'a, AppContext>); impl<'a> Drop for AppRef<'a> { fn drop(&mut self) { - if let Some(_) = option_env!("TRACK_THREAD_BORROWS") { + if option_env!("TRACK_THREAD_BORROWS").is_some() { let thread_id = std::thread::current().id(); eprintln!("dropped borrow from {thread_id:?}"); } @@ -86,7 +86,7 @@ pub struct AppRefMut<'a>(RefMut<'a, AppContext>); impl<'a> Drop for AppRefMut<'a> { fn drop(&mut self) { - if let Some(_) = option_env!("TRACK_THREAD_BORROWS") { + if option_env!("TRACK_THREAD_BORROWS").is_some() { let thread_id = std::thread::current().id(); eprintln!("dropped {thread_id:?}"); } @@ -130,7 +130,7 @@ impl App { let this = Rc::downgrade(&self.0); self.0.borrow().platform.on_open_urls(Box::new(move |urls| { if let Some(app) = this.upgrade() { - callback(urls, &mut *app.borrow_mut()); + callback(urls, &mut app.borrow_mut()); } })); self @@ -280,7 +280,7 @@ impl AppContext { }), }); - init_app_menus(platform.as_ref(), &mut *app.borrow_mut()); + init_app_menus(platform.as_ref(), &mut app.borrow_mut()); platform.on_quit(Box::new({ let cx = app.clone(); @@ -428,7 +428,7 @@ impl AppContext { pub fn windows(&self) -> Vec { self.windows .values() - .filter_map(|window| Some(window.as_ref()?.handle.clone())) + .filter_map(|window| Some(window.as_ref()?.handle)) .collect() } @@ -808,7 +808,7 @@ impl AppContext { self.push_effect(Effect::NotifyGlobalObservers { global_type }); self.globals_by_type .entry(global_type) - .or_insert_with(|| Box::new(G::default())) + .or_insert_with(|| Box::::default()) .downcast_mut::() .unwrap() } @@ -993,7 +993,7 @@ impl AppContext { (), Box::new(move |cx| { let future = on_quit(cx); - async move { future.await }.boxed_local() + future.boxed_local() }), ); activate(); diff --git a/crates/gpui2/src/app/async_context.rs b/crates/gpui2/src/app/async_context.rs index 92ccc118f12826076621629a470dfda5c6a545d1..e18b654a32e0b31f624443c6c0e0899f0bb89aa5 100644 --- a/crates/gpui2/src/app/async_context.rs +++ b/crates/gpui2/src/app/async_context.rs @@ -106,7 +106,7 @@ impl AsyncAppContext { .upgrade() .ok_or_else(|| anyhow!("app was released"))?; let mut lock = app.borrow_mut(); - Ok(f(&mut *lock)) + Ok(f(&mut lock)) } pub fn open_window( diff --git a/crates/gpui2/src/app/entity_map.rs b/crates/gpui2/src/app/entity_map.rs index 99d8542eba89cde981f8cbf966d298ec1d8af2af..f71cfbdebcd615daaa5758132d59f73aadd7cacd 100644 --- a/crates/gpui2/src/app/entity_map.rs +++ b/crates/gpui2/src/app/entity_map.rs @@ -327,9 +327,9 @@ impl Model { cx.entities.read(self) } - pub fn read_with<'a, R, C: Context>( + pub fn read_with( &self, - cx: &'a C, + cx: &C, f: impl FnOnce(&T, &AppContext) -> R, ) -> C::Result { cx.read_model(self, f) diff --git a/crates/gpui2/src/app/model_context.rs b/crates/gpui2/src/app/model_context.rs index 26feb2fd1befc604f7bda5b5e5a362a5a3c52dd1..e7eea726623a921f0a122e4ff12d8897264209fb 100644 --- a/crates/gpui2/src/app/model_context.rs +++ b/crates/gpui2/src/app/model_context.rs @@ -262,12 +262,12 @@ impl<'a, T> Context for ModelContext<'a, T> { impl Borrow for ModelContext<'_, T> { fn borrow(&self) -> &AppContext { - &self.app + self.app } } impl BorrowMut for ModelContext<'_, T> { fn borrow_mut(&mut self) -> &mut AppContext { - &mut self.app + self.app } } diff --git a/crates/gpui2/src/color.rs b/crates/gpui2/src/color.rs index d5514d900ffa69046ff6cb6e5ba5b287cecbb38c..df16d2c0b5664f7354cbde90e088be3cf1aee589 100644 --- a/crates/gpui2/src/color.rs +++ b/crates/gpui2/src/color.rs @@ -34,7 +34,7 @@ impl fmt::Debug for Rgba { impl Rgba { pub fn blend(&self, other: Rgba) -> Self { if other.a >= 1.0 { - return other; + other } else if other.a <= 0.0 { return *self; } else { @@ -117,7 +117,7 @@ impl TryFrom<&'_ str> for Rgba { const RRGGBB: usize = "rrggbb".len(); const RRGGBBAA: usize = "rrggbbaa".len(); - const EXPECTED_FORMATS: &'static str = "Expected #rgb, #rgba, #rrggbb, or #rrggbbaa"; + const EXPECTED_FORMATS: &str = "Expected #rgb, #rgba, #rrggbb, or #rrggbbaa"; let Some(("", hex)) = value.trim().split_once('#') else { bail!("invalid RGBA hex color: '{value}'. {EXPECTED_FORMATS}"); @@ -328,7 +328,7 @@ impl Hsla { let alpha = other.a; if alpha >= 1.0 { - return other; + other } else if alpha <= 0.0 { return self; } else { diff --git a/crates/gpui2/src/element.rs b/crates/gpui2/src/element.rs index eedc5e35b172fa4f061f26a3ba99b7ace26f0d6e..c8445cad06caeee291d388554878f28d996c67ed 100644 --- a/crates/gpui2/src/element.rs +++ b/crates/gpui2/src/element.rs @@ -159,7 +159,7 @@ impl Element for Component { } else { element.paint( bounds, - &mut state.rendered_element_state.as_mut().unwrap(), + state.rendered_element_state.as_mut().unwrap(), cx, ); } diff --git a/crates/gpui2/src/elements/div.rs b/crates/gpui2/src/elements/div.rs index fc129b4f1df6d36e9d480b9f2da7e1c5a0ac38bf..de6b185b670343d85348ebf38b7ef4b80a38465d 100644 --- a/crates/gpui2/src/elements/div.rs +++ b/crates/gpui2/src/elements/div.rs @@ -176,21 +176,18 @@ impl Interactivity { { self.mouse_move_listeners .push(Box::new(move |event, bounds, phase, cx| { - if phase == DispatchPhase::Capture { - if cx + if phase == DispatchPhase::Capture && cx .active_drag .as_ref() - .is_some_and(|drag| drag.value.as_ref().type_id() == TypeId::of::()) - { - (listener)( - &DragMoveEvent { - event: event.clone(), - bounds: bounds.bounds, - drag: PhantomData, - }, - cx, - ); - } + .is_some_and(|drag| drag.value.as_ref().type_id() == TypeId::of::()) { + (listener)( + &DragMoveEvent { + event: event.clone(), + bounds: bounds.bounds, + drag: PhantomData, + }, + cx, + ); } })); } @@ -921,12 +918,12 @@ pub struct InteractiveBounds { impl InteractiveBounds { pub fn visibly_contains(&self, point: &Point, cx: &WindowContext) -> bool { - self.bounds.contains(point) && cx.was_top_layer(&point, &self.stacking_order) + self.bounds.contains(point) && cx.was_top_layer(point, &self.stacking_order) } pub fn drag_target_contains(&self, point: &Point, cx: &WindowContext) -> bool { self.bounds.contains(point) - && cx.was_top_layer_under_active_drag(&point, &self.stacking_order) + && cx.was_top_layer_under_active_drag(point, &self.stacking_order) } } @@ -1009,8 +1006,7 @@ impl Interactivity { None, ) .ok() - .map(|mut text| text.pop()) - .flatten() + .and_then(|mut text| text.pop()) { text.paint(bounds.origin, FONT_SIZE, cx).ok(); @@ -1024,7 +1020,7 @@ impl Interactivity { { let command_held = cx.modifiers().command; cx.on_key_event({ - let text_bounds = text_bounds.clone(); + let text_bounds = text_bounds; move |e: &crate::ModifiersChangedEvent, _phase, cx| { if e.modifiers.command != command_held && text_bounds.contains(&cx.mouse_position()) @@ -1037,17 +1033,15 @@ impl Interactivity { let hovered = bounds.contains(&cx.mouse_position()); cx.on_mouse_event( move |event: &MouseMoveEvent, phase, cx| { - if phase == DispatchPhase::Capture { - if bounds.contains(&event.position) != hovered { - cx.notify(); - } + if phase == DispatchPhase::Capture && bounds.contains(&event.position) != hovered { + cx.notify(); } }, ); cx.on_mouse_event({ - let location = self.location.clone().unwrap(); - let text_bounds = text_bounds.clone(); + let location = self.location.unwrap(); + let text_bounds = text_bounds; move |e: &crate::MouseDownEvent, phase, cx| { if text_bounds.contains(&e.position) && phase.capture() @@ -1188,10 +1182,8 @@ impl Interactivity { if let Some(group_bounds) = hover_group_bounds { let hovered = group_bounds.contains(&cx.mouse_position()); cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| { - if phase == DispatchPhase::Capture { - if group_bounds.contains(&event.position) != hovered { - cx.notify(); - } + if phase == DispatchPhase::Capture && group_bounds.contains(&event.position) != hovered { + cx.notify(); } }); } @@ -1203,10 +1195,8 @@ impl Interactivity { let bounds = bounds.intersect(&cx.content_mask().bounds); let hovered = bounds.contains(&cx.mouse_position()); cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| { - if phase == DispatchPhase::Capture { - if bounds.contains(&event.position) != hovered { - cx.notify(); - } + if phase == DispatchPhase::Capture && bounds.contains(&event.position) != hovered { + cx.notify(); } }); } @@ -1366,7 +1356,7 @@ impl Interactivity { && !cx.has_active_drag(); let mut was_hovered = was_hovered.borrow_mut(); - if is_hovered != was_hovered.clone() { + if is_hovered != *was_hovered { *was_hovered = is_hovered; drop(was_hovered); @@ -1703,7 +1693,7 @@ impl Default for Interactivity { scroll_handle: None, // scroll_offset: Point::default(), group: None, - base_style: Box::new(StyleRefinement::default()), + base_style: Box::::default(), focus_style: None, in_focus_style: None, hover_style: None, @@ -1942,13 +1932,19 @@ struct ScrollHandleState { #[derive(Clone)] pub struct ScrollHandle(Rc>); +impl Default for ScrollHandle { + fn default() -> Self { + Self::new() + } +} + impl ScrollHandle { pub fn new() -> Self { Self(Rc::default()) } pub fn offset(&self) -> Point { - self.0.borrow().offset.borrow().clone() + *self.0.borrow().offset.borrow() } pub fn top_item(&self) -> usize { diff --git a/crates/gpui2/src/elements/text.rs b/crates/gpui2/src/elements/text.rs index 7716d81536117a6213133db7cdf8377f94f1f647..e0444c2f0a0a99f4217f5adcb666259609b3dca6 100644 --- a/crates/gpui2/src/elements/text.rs +++ b/crates/gpui2/src/elements/text.rs @@ -171,7 +171,7 @@ impl TextState { let line_height = text_style .line_height .to_pixels(font_size.into(), cx.rem_size()); - let text = SharedString::from(text); + let text = text; let runs = if let Some(runs) = runs { runs diff --git a/crates/gpui2/src/elements/uniform_list.rs b/crates/gpui2/src/elements/uniform_list.rs index e38a37f90d20c8612069f13daaf94ccb06c1dc89..1c237ff6ddc379473cdf8d7b5b59336593d1269c 100644 --- a/crates/gpui2/src/elements/uniform_list.rs +++ b/crates/gpui2/src/elements/uniform_list.rs @@ -41,7 +41,7 @@ where item_to_measure_index: 0, render_items: Box::new(render_range), interactivity: Interactivity { - element_id: Some(id.into()), + element_id: Some(id), base_style: Box::new(base_style), #[cfg(debug_assertions)] diff --git a/crates/gpui2/src/executor.rs b/crates/gpui2/src/executor.rs index 81fa6e64caa16daa14f76c50458771f641717f32..589493b4bb431586ed004e88e59d0d8f329334fc 100644 --- a/crates/gpui2/src/executor.rs +++ b/crates/gpui2/src/executor.rs @@ -80,6 +80,12 @@ impl Future for Task { #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] pub struct TaskLabel(NonZeroUsize); +impl Default for TaskLabel { + fn default() -> Self { + Self::new() + } +} + impl TaskLabel { pub fn new() -> Self { static NEXT_TASK_LABEL: AtomicUsize = AtomicUsize::new(1); diff --git a/crates/gpui2/src/geometry.rs b/crates/gpui2/src/geometry.rs index 292b0f4aa99234da2bc75e4bf3e22102dc13fec9..4d2137c25763709d5fa84f391e2ec6feb8cae6ee 100644 --- a/crates/gpui2/src/geometry.rs +++ b/crates/gpui2/src/geometry.rs @@ -1601,13 +1601,13 @@ impl Edges { } } -impl Into> for f32 { - fn into(self) -> Edges { +impl From for Edges { + fn from(val: f32) -> Self { Edges { - top: self.into(), - right: self.into(), - bottom: self.into(), - left: self.into(), + top: val.into(), + right: val.into(), + bottom: val.into(), + left: val.into(), } } } @@ -1840,24 +1840,24 @@ where impl Copy for Corners where T: Copy + Clone + Default + Debug {} -impl Into> for f32 { - fn into(self) -> Corners { +impl From for Corners { + fn from(val: f32) -> Self { Corners { - top_left: self.into(), - top_right: self.into(), - bottom_right: self.into(), - bottom_left: self.into(), + top_left: val.into(), + top_right: val.into(), + bottom_right: val.into(), + bottom_left: val.into(), } } } -impl Into> for Pixels { - fn into(self) -> Corners { +impl From for Corners { + fn from(val: Pixels) -> Self { Corners { - top_left: self, - top_right: self, - bottom_right: self, - bottom_left: self, + top_left: val, + top_right: val, + bottom_right: val, + bottom_left: val, } } } @@ -2522,12 +2522,12 @@ impl Debug for Length { /// /// A `DefiniteLength` representing the relative length as a fraction of the parent's size. pub fn relative(fraction: f32) -> DefiniteLength { - DefiniteLength::Fraction(fraction).into() + DefiniteLength::Fraction(fraction) } /// Returns the Golden Ratio, i.e. `~(1.0 + sqrt(5.0)) / 2.0`. pub fn phi() -> DefiniteLength { - relative(1.61803398875) + relative(1.618_034) } /// Constructs a `Rems` value representing a length in rems. diff --git a/crates/gpui2/src/interactive.rs b/crates/gpui2/src/interactive.rs index 4f4c1630770b755fd9cbc9e8e874aea46e52473f..045bb87791ef7fac625392afaccaeb5008248c63 100644 --- a/crates/gpui2/src/interactive.rs +++ b/crates/gpui2/src/interactive.rs @@ -258,7 +258,7 @@ impl InputEvent { } } - pub fn mouse_event<'a>(&'a self) -> Option<&'a dyn Any> { + pub fn mouse_event(&self) -> Option<&dyn Any> { match self { InputEvent::KeyDown { .. } => None, InputEvent::KeyUp { .. } => None, @@ -272,7 +272,7 @@ impl InputEvent { } } - pub fn keyboard_event<'a>(&'a self) -> Option<&'a dyn Any> { + pub fn keyboard_event(&self) -> Option<&dyn Any> { match self { InputEvent::KeyDown(event) => Some(event), InputEvent::KeyUp(event) => Some(event), diff --git a/crates/gpui2/src/key_dispatch.rs b/crates/gpui2/src/key_dispatch.rs index a9d717ea1acb6866ab75165bcc4c6daedd268899..ade52a13143a8ba8ea6ecaa41434f53b721262a0 100644 --- a/crates/gpui2/src/key_dispatch.rs +++ b/crates/gpui2/src/key_dispatch.rs @@ -200,7 +200,7 @@ impl DispatchTree { return true; } } - return false; + false }) .cloned() .collect() diff --git a/crates/gpui2/src/keymap/binding.rs b/crates/gpui2/src/keymap/binding.rs index 4b677b3071f3824d798a69d299e2fe2336dc1c97..24394107849e24ae80d827768573972d36b21cb3 100644 --- a/crates/gpui2/src/keymap/binding.rs +++ b/crates/gpui2/src/keymap/binding.rs @@ -54,7 +54,7 @@ impl KeyBinding { pending_keystrokes: &[Keystroke], contexts: &[KeyContext], ) -> KeyMatch { - if self.keystrokes.as_ref().starts_with(&pending_keystrokes) + if self.keystrokes.as_ref().starts_with(pending_keystrokes) && self.matches_context(contexts) { // If the binding is completed, push it onto the matches list diff --git a/crates/gpui2/src/keymap/context.rs b/crates/gpui2/src/keymap/context.rs index fb90a0c7644a310feb2070f0592a114bdd06a679..bfa97b7afe4e33706da3b35ef099341c219f80fb 100644 --- a/crates/gpui2/src/keymap/context.rs +++ b/crates/gpui2/src/keymap/context.rs @@ -24,7 +24,7 @@ impl KeyContext { pub fn parse(source: &str) -> Result { let mut context = Self::default(); let source = skip_whitespace(source); - Self::parse_expr(&source, &mut context)?; + Self::parse_expr(source, &mut context)?; Ok(context) } @@ -220,7 +220,7 @@ impl KeyBindingContextPredicate { } '!' => { let source = skip_whitespace(&source[1..]); - let (predicate, source) = Self::parse_expr(&source, PRECEDENCE_NOT)?; + let (predicate, source) = Self::parse_expr(source, PRECEDENCE_NOT)?; Ok((KeyBindingContextPredicate::Not(Box::new(predicate)), source)) } _ if is_identifier_char(next) => { diff --git a/crates/gpui2/src/platform/mac.rs b/crates/gpui2/src/platform/mac.rs index 462aa209ccb040f2df4d1a70466c1e48eb78e9a9..344910de3bc40600a8b74d6f8ad41e54b7652507 100644 --- a/crates/gpui2/src/platform/mac.rs +++ b/crates/gpui2/src/platform/mac.rs @@ -1,5 +1,5 @@ -///! Macos screen have a y axis that goings up from the bottom of the screen and -///! an origin at the bottom left of the main display. +//! Macos screen have a y axis that goings up from the bottom of the screen and +//! an origin at the bottom left of the main display. mod dispatcher; mod display; mod display_linker; diff --git a/crates/gpui2/src/platform/mac/dispatcher.rs b/crates/gpui2/src/platform/mac/dispatcher.rs index 2fb0eef3e5f03375cb6bfc1dba653f4f8043aca9..feb8925426f85e5e82e99273fab7220e59e3374f 100644 --- a/crates/gpui2/src/platform/mac/dispatcher.rs +++ b/crates/gpui2/src/platform/mac/dispatcher.rs @@ -23,6 +23,12 @@ pub struct MacDispatcher { parker: Arc>, } +impl Default for MacDispatcher { + fn default() -> Self { + Self::new() + } +} + impl MacDispatcher { pub fn new() -> Self { MacDispatcher { diff --git a/crates/gpui2/src/platform/mac/display.rs b/crates/gpui2/src/platform/mac/display.rs index b326eaa66d07bc674ebf6fb0c09d549db2dcb61f..2458533f6a3e45a6c0f7789135a8780669012d8c 100644 --- a/crates/gpui2/src/platform/mac/display.rs +++ b/crates/gpui2/src/platform/mac/display.rs @@ -41,7 +41,7 @@ impl MacDisplay { CGGetActiveDisplayList(display_count, displays.as_mut_ptr(), &mut display_count); displays.set_len(display_count as usize); - displays.into_iter().map(|display| MacDisplay(display)) + displays.into_iter().map(MacDisplay) } else { panic!("Failed to get active display list"); } diff --git a/crates/gpui2/src/platform/mac/display_linker.rs b/crates/gpui2/src/platform/mac/display_linker.rs index d8f5a675a58f4204e644f5661dfc5078b9ae4295..e367d22b3d7099cdc84fb67a97b013d3c63503e8 100644 --- a/crates/gpui2/src/platform/mac/display_linker.rs +++ b/crates/gpui2/src/platform/mac/display_linker.rs @@ -49,7 +49,6 @@ impl MacDisplayLinker { ); } else { log::warn!("DisplayLink could not be obtained for {:?}", display_id); - return; } } diff --git a/crates/gpui2/src/platform/mac/metal_atlas.rs b/crates/gpui2/src/platform/mac/metal_atlas.rs index 2110815d9f9a352f5c6c2aeb6a92da483691afa7..10ca53530e2ba16d80f07cfab1722ed0eecbebc3 100644 --- a/crates/gpui2/src/platform/mac/metal_atlas.rs +++ b/crates/gpui2/src/platform/mac/metal_atlas.rs @@ -64,7 +64,7 @@ impl PlatformAtlas for MetalAtlas { ) -> Result { let mut lock = self.0.lock(); if let Some(tile) = lock.tiles_by_key.get(key) { - return Ok(tile.clone()); + Ok(tile.clone()) } else { let (size, bytes) = build()?; let tile = lock.allocate(size, key.texture_kind()); @@ -203,7 +203,7 @@ impl MetalAtlasTexture { region, 0, bytes.as_ptr() as *const _, - u32::from(bounds.size.width.to_bytes(self.bytes_per_pixel())) as u64, + bounds.size.width.to_bytes(self.bytes_per_pixel()) as u64, ); } diff --git a/crates/gpui2/src/platform/mac/metal_renderer.rs b/crates/gpui2/src/platform/mac/metal_renderer.rs index 7812eebf01bda8ff5fccf4605e66a188285302e2..e0682024766794b232ff9c9cb260674bb852f7a4 100644 --- a/crates/gpui2/src/platform/mac/metal_renderer.rs +++ b/crates/gpui2/src/platform/mac/metal_renderer.rs @@ -179,7 +179,7 @@ impl MetalRenderer { } pub fn layer(&self) -> &metal::MetalLayerRef { - &*self.layer + &self.layer } pub fn sprite_atlas(&self) -> &Arc { @@ -206,7 +206,7 @@ impl MetalRenderer { let command_buffer = command_queue.new_command_buffer(); let mut instance_offset = 0; - let path_tiles = self.rasterize_paths(scene.paths(), &mut instance_offset, &command_buffer); + let path_tiles = self.rasterize_paths(scene.paths(), &mut instance_offset, command_buffer); let render_pass_descriptor = metal::RenderPassDescriptor::new(); let color_attachment = render_pass_descriptor @@ -429,7 +429,7 @@ impl MetalRenderer { &viewport_size as *const Size as *const _, ); - let shadow_bytes_len = mem::size_of::() * shadows.len(); + let shadow_bytes_len = std::mem::size_of_val(shadows); let buffer_contents = unsafe { (self.instances.contents() as *mut u8).add(*offset) }; unsafe { ptr::copy_nonoverlapping( @@ -489,7 +489,7 @@ impl MetalRenderer { &viewport_size as *const Size as *const _, ); - let quad_bytes_len = mem::size_of::() * quads.len(); + let quad_bytes_len = std::mem::size_of_val(quads); let buffer_contents = unsafe { (self.instances.contents() as *mut u8).add(*offset) }; unsafe { ptr::copy_nonoverlapping(quads.as_ptr() as *const u8, buffer_contents, quad_bytes_len); @@ -537,7 +537,7 @@ impl MetalRenderer { let mut prev_texture_id = None; let mut sprites = SmallVec::<[_; 1]>::new(); let mut paths_and_tiles = paths - .into_iter() + .iter() .map(|path| (path, tiles_by_path_id.get(&path.id).unwrap())) .peekable(); @@ -652,7 +652,7 @@ impl MetalRenderer { &viewport_size as *const Size as *const _, ); - let quad_bytes_len = mem::size_of::() * underlines.len(); + let quad_bytes_len = std::mem::size_of_val(underlines); let buffer_contents = unsafe { (self.instances.contents() as *mut u8).add(*offset) }; unsafe { ptr::copy_nonoverlapping( @@ -723,7 +723,7 @@ impl MetalRenderer { ); command_encoder.set_fragment_texture(SpriteInputIndex::AtlasTexture as u64, Some(&texture)); - let sprite_bytes_len = mem::size_of::() * sprites.len(); + let sprite_bytes_len = std::mem::size_of_val(sprites); let buffer_contents = unsafe { (self.instances.contents() as *mut u8).add(*offset) }; unsafe { ptr::copy_nonoverlapping( @@ -794,7 +794,7 @@ impl MetalRenderer { ); command_encoder.set_fragment_texture(SpriteInputIndex::AtlasTexture as u64, Some(&texture)); - let sprite_bytes_len = mem::size_of::() * sprites.len(); + let sprite_bytes_len = std::mem::size_of_val(sprites); let buffer_contents = unsafe { (self.instances.contents() as *mut u8).add(*offset) }; unsafe { ptr::copy_nonoverlapping( diff --git a/crates/gpui2/src/platform/mac/platform.rs b/crates/gpui2/src/platform/mac/platform.rs index 2dcfb1a58d026e9d3bcbb500741490a657a5b2b3..7dc35ba1ad9c469ed30d6f77a51958274a269587 100644 --- a/crates/gpui2/src/platform/mac/platform.rs +++ b/crates/gpui2/src/platform/mac/platform.rs @@ -166,6 +166,12 @@ pub struct MacPlatformState { finish_launching: Option>, } +impl Default for MacPlatform { + fn default() -> Self { + Self::new() + } +} + impl MacPlatform { pub fn new() -> Self { let dispatcher = Arc::new(MacDispatcher::new()); @@ -475,7 +481,6 @@ impl Platform for MacPlatform { fn displays(&self) -> Vec> { MacDisplay::all() - .into_iter() .map(|screen| Rc::new(screen) as Rc<_>) .collect() } @@ -1035,7 +1040,6 @@ extern "C" fn will_terminate(this: &mut Object, _: Sel, _: id) { extern "C" fn open_urls(this: &mut Object, _: Sel, _: id, urls: id) { let urls = unsafe { (0..urls.count()) - .into_iter() .filter_map(|i| { let url = urls.objectAtIndex(i); match CStr::from_ptr(url.absoluteString().UTF8String() as *mut c_char).to_str() { diff --git a/crates/gpui2/src/platform/mac/text_system.rs b/crates/gpui2/src/platform/mac/text_system.rs index 9ef0f321b68933454f4f72d7aecbb04460669709..88ebfd83514949bbe56e661ec5c42da053814d50 100644 --- a/crates/gpui2/src/platform/mac/text_system.rs +++ b/crates/gpui2/src/platform/mac/text_system.rs @@ -335,7 +335,7 @@ impl MacTextSystemState { } } - Ok((bitmap_size.into(), bytes)) + Ok((bitmap_size, bytes)) } } @@ -343,10 +343,10 @@ impl MacTextSystemState { // Construct the attributed string, converting UTF8 ranges to UTF16 ranges. let mut string = CFMutableAttributedString::new(); { - string.replace_str(&CFString::new(text.as_ref()), CFRange::init(0, 0)); + string.replace_str(&CFString::new(text), CFRange::init(0, 0)); let utf16_line_len = string.char_len() as usize; - let mut ix_converter = StringIndexConverter::new(text.as_ref()); + let mut ix_converter = StringIndexConverter::new(text); for run in font_runs { let utf8_end = ix_converter.utf8_ix + run.len; let utf16_start = ix_converter.utf16_ix; @@ -390,7 +390,7 @@ impl MacTextSystemState { }; let font_id = self.id_for_native_font(font); - let mut ix_converter = StringIndexConverter::new(text.as_ref()); + let mut ix_converter = StringIndexConverter::new(text); let mut glyphs = SmallVec::new(); for ((glyph_id, position), glyph_utf16_ix) in run .glyphs() @@ -453,7 +453,7 @@ impl MacTextSystemState { if ix_converter.utf8_ix >= text.len() { break; } - break_indices.push(ix_converter.utf8_ix as usize); + break_indices.push(ix_converter.utf8_ix); } break_indices } diff --git a/crates/gpui2/src/platform/mac/window.rs b/crates/gpui2/src/platform/mac/window.rs index fa39b22945e5f2176e66b68d2cd465b462bd6bf9..27e8718a5a3c3309e41640f78334e505694e81e0 100644 --- a/crates/gpui2/src/platform/mac/window.rs +++ b/crates/gpui2/src/platform/mac/window.rs @@ -488,7 +488,7 @@ impl MacWindow { let display = options .display_id .and_then(|display_id| MacDisplay::all().find(|display| display.id() == display_id)) - .unwrap_or_else(|| MacDisplay::primary()); + .unwrap_or_else(MacDisplay::primary); let mut target_screen = nil; let screens = NSScreen::screens(nil); @@ -702,7 +702,7 @@ impl PlatformWindow for MacWindow { } fn content_size(&self) -> Size { - self.0.as_ref().lock().content_size().into() + self.0.as_ref().lock().content_size() } fn scale_factor(&self) -> f32 { @@ -1339,12 +1339,10 @@ extern "C" fn window_did_change_key_status(this: &Object, selector: Sel, _: id) // The following code detects the spurious event and invokes `resignKeyWindow`: // in theory, we're not supposed to invoke this method manually but it balances out // the spurious `becomeKeyWindow` event and helps us work around that bug. - if selector == sel!(windowDidBecomeKey:) { - if !is_active { - unsafe { - let _: () = msg_send![lock.native_window, resignKeyWindow]; - return; - } + if selector == sel!(windowDidBecomeKey:) && !is_active { + unsafe { + let _: () = msg_send![lock.native_window, resignKeyWindow]; + return; } } @@ -1665,11 +1663,11 @@ extern "C" fn accepts_first_mouse(this: &Object, _: Sel, _: id) -> BOOL { unsafe { let state = get_window_state(this); let lock = state.as_ref().lock(); - return if lock.kind == WindowKind::PopUp { + if lock.kind == WindowKind::PopUp { YES } else { NO - }; + } } } diff --git a/crates/gpui2/src/scene.rs b/crates/gpui2/src/scene.rs index 687943a7b18fafcb52170ea93b628f4c58cafcbf..ad43ab829b295208589fa62ad0a3d5a5062b3426 100644 --- a/crates/gpui2/src/scene.rs +++ b/crates/gpui2/src/scene.rs @@ -14,6 +14,7 @@ pub type LayerId = u32; pub type DrawOrder = u32; +#[derive(Default)] pub(crate) struct SceneBuilder { last_order: Option<(StackingOrder, LayerId)>, layers_by_order: BTreeMap, @@ -26,21 +27,7 @@ pub(crate) struct SceneBuilder { surfaces: Vec, } -impl Default for SceneBuilder { - fn default() -> Self { - SceneBuilder { - last_order: None, - layers_by_order: BTreeMap::new(), - shadows: Vec::new(), - quads: Vec::new(), - paths: Vec::new(), - underlines: Vec::new(), - monochrome_sprites: Vec::new(), - polychrome_sprites: Vec::new(), - surfaces: Vec::new(), - } - } -} + impl SceneBuilder { pub fn build(&mut self) -> Scene { diff --git a/crates/gpui2/src/shared_string.rs b/crates/gpui2/src/shared_string.rs index c19d439e316f2de5956b249ae762e0d168f72a82..97db4bd1912dae5635d69bb1a4dfe1008ebe071c 100644 --- a/crates/gpui2/src/shared_string.rs +++ b/crates/gpui2/src/shared_string.rs @@ -60,9 +60,9 @@ impl<'a> PartialEq<&'a str> for SharedString { } } -impl Into> for SharedString { - fn into(self) -> Arc { - match self.0 { +impl From for Arc { + fn from(val: SharedString) -> Self { + match val.0 { ArcCow::Borrowed(borrowed) => Arc::from(borrowed), ArcCow::Owned(owned) => owned.clone(), } @@ -75,9 +75,9 @@ impl>> From for SharedString { } } -impl Into for SharedString { - fn into(self) -> String { - self.0.to_string() +impl From for String { + fn from(val: SharedString) -> Self { + val.0.to_string() } } diff --git a/crates/gpui2/src/style.rs b/crates/gpui2/src/style.rs index c281818c0f0bad1107d49a8b1895762c910e8af7..88d5e1b2a019f71996dc54f8afb6649d111767d8 100644 --- a/crates/gpui2/src/style.rs +++ b/crates/gpui2/src/style.rs @@ -210,7 +210,7 @@ impl TextStyle { pub fn font(&self) -> Font { Font { family: self.font_family.clone(), - features: self.font_features.clone(), + features: self.font_features, weight: self.font_weight, style: self.font_style, } @@ -232,7 +232,7 @@ impl TextStyle { }, color: self.color, background_color: self.background_color, - underline: self.underline.clone(), + underline: self.underline, } } } @@ -570,7 +570,7 @@ impl From<&TextStyle> for HighlightStyle { font_weight: Some(other.font_weight), font_style: Some(other.font_style), background_color: other.background_color, - underline: other.underline.clone(), + underline: other.underline, fade_out: None, } } diff --git a/crates/gpui2/src/subscription.rs b/crates/gpui2/src/subscription.rs index 867c83fcbb31527db4be5d1c912b013a35872290..b56c9a1ccdbe800d5e24e8a4a353ef4ff08c784c 100644 --- a/crates/gpui2/src/subscription.rs +++ b/crates/gpui2/src/subscription.rs @@ -53,7 +53,7 @@ where lock.subscribers .entry(emitter_key.clone()) .or_default() - .get_or_insert_with(|| Default::default()) + .get_or_insert_with(Default::default) .insert( subscriber_id, Subscriber { @@ -90,7 +90,7 @@ where } pub fn remove(&self, emitter: &EmitterKey) -> impl IntoIterator { - let subscribers = self.0.lock().subscribers.remove(&emitter); + let subscribers = self.0.lock().subscribers.remove(emitter); subscribers .unwrap_or_default() .map(|s| s.into_values()) @@ -131,7 +131,7 @@ where let mut lock = self.0.lock(); // Add any new subscribers that were added while invoking the callback. - if let Some(Some(new_subscribers)) = lock.subscribers.remove(&emitter) { + if let Some(Some(new_subscribers)) = lock.subscribers.remove(emitter) { subscribers.extend(new_subscribers); } diff --git a/crates/gpui2/src/taffy.rs b/crates/gpui2/src/taffy.rs index 88fb8e8814c393344faed19408351586e559fecb..0a8a470289253cc35b4f6085bf1627aeef23c0c3 100644 --- a/crates/gpui2/src/taffy.rs +++ b/crates/gpui2/src/taffy.rs @@ -29,7 +29,7 @@ pub struct TaffyLayoutEngine { >, } -static EXPECT_MESSAGE: &'static str = +static EXPECT_MESSAGE: &str = "we should avoid taffy layout errors by construction if possible"; impl TaffyLayoutEngine { @@ -246,7 +246,7 @@ impl ToTaffy for Style { fn to_taffy(&self, rem_size: Pixels) -> taffy::style::Style { taffy::style::Style { display: self.display, - overflow: self.overflow.clone().into(), + overflow: self.overflow.into(), scrollbar_width: self.scrollbar_width, position: self.position, inset: self.inset.to_taffy(rem_size), @@ -378,14 +378,14 @@ where } } -impl Into> for Point +impl From> for TaffyPoint where T: Into + Clone + Default + Debug, { - fn into(self) -> TaffyPoint { + fn from(val: Point) -> Self { TaffyPoint { - x: self.x.into(), - y: self.y.into(), + x: val.x.into(), + y: val.y.into(), } } } @@ -396,8 +396,8 @@ where { fn to_taffy(&self, rem_size: Pixels) -> TaffySize { TaffySize { - width: self.width.to_taffy(rem_size).into(), - height: self.height.to_taffy(rem_size).into(), + width: self.width.to_taffy(rem_size), + height: self.height.to_taffy(rem_size), } } } @@ -408,10 +408,10 @@ where { fn to_taffy(&self, rem_size: Pixels) -> TaffyRect { TaffyRect { - top: self.top.to_taffy(rem_size).into(), - right: self.right.to_taffy(rem_size).into(), - bottom: self.bottom.to_taffy(rem_size).into(), - left: self.left.to_taffy(rem_size).into(), + top: self.top.to_taffy(rem_size), + right: self.right.to_taffy(rem_size), + bottom: self.bottom.to_taffy(rem_size), + left: self.left.to_taffy(rem_size), } } } diff --git a/crates/gpui2/src/text_system.rs b/crates/gpui2/src/text_system.rs index ad82c4108273f55a80831dcda508b1fbb061bdcb..7c3832ec12fa55363741ee96b7cf7851cf5cd109 100644 --- a/crates/gpui2/src/text_system.rs +++ b/crates/gpui2/src/text_system.rs @@ -106,7 +106,7 @@ impl TextSystem { } pub fn units_per_em(&self, font_id: FontId) -> u32 { - self.read_metrics(font_id, |metrics| metrics.units_per_em as u32) + self.read_metrics(font_id, |metrics| metrics.units_per_em) } pub fn cap_height(&self, font_id: FontId, font_size: Pixels) -> Pixels { @@ -174,7 +174,7 @@ impl TextSystem { let layout = self .line_layout_cache - .layout_line(&text, font_size, &font_runs); + .layout_line(text, font_size, &font_runs); font_runs.clear(); self.font_runs_pool.lock().push(font_runs); @@ -208,7 +208,7 @@ impl TextSystem { len: run.len as u32, color: run.color, background_color: run.background_color, - underline: run.underline.clone(), + underline: run.underline, }); } @@ -268,7 +268,7 @@ impl TextSystem { len: run_len_within_line as u32, color: run.color, background_color: run.background_color, - underline: run.underline.clone(), + underline: run.underline, }); } @@ -287,7 +287,7 @@ impl TextSystem { lines.push(WrappedLine { layout, decoration_runs, - text: SharedString::from(line_text), + text: line_text, }); // Skip `\n` character. @@ -338,7 +338,7 @@ impl TextSystem { pub fn raster_bounds(&self, params: &RenderGlyphParams) -> Result> { let raster_bounds = self.raster_bounds.upgradable_read(); if let Some(bounds) = raster_bounds.get(params) { - Ok(bounds.clone()) + Ok(*bounds) } else { let mut raster_bounds = RwLockUpgradableReadGuard::upgrade(raster_bounds); let bounds = self.platform_text_system.glyph_raster_bounds(params)?; @@ -374,7 +374,7 @@ impl Drop for LineWrapperHandle { let wrapper = self.wrapper.take().unwrap(); state .get_mut(&FontIdWithSize { - font_id: wrapper.font_id.clone(), + font_id: wrapper.font_id, font_size: wrapper.font_size, }) .unwrap() @@ -439,8 +439,10 @@ impl FontWeight { /// Allows italic or oblique faces to be selected. #[derive(Clone, Copy, Eq, PartialEq, Debug, Hash)] +#[derive(Default)] pub enum FontStyle { /// A face that is neither italic not obliqued. + #[default] Normal, /// A form that is generally cursive in nature. Italic, @@ -448,11 +450,7 @@ pub enum FontStyle { Oblique, } -impl Default for FontStyle { - fn default() -> FontStyle { - FontStyle::Normal - } -} + impl Display for FontStyle { fn fmt(&self, f: &mut Formatter) -> fmt::Result { diff --git a/crates/gpui2/src/text_system/line_wrapper.rs b/crates/gpui2/src/text_system/line_wrapper.rs index 99950fbe1094e3ed3600620c976a9e15f0e48b13..e2f0a8a5fdbce9c0e3f81c9fb018bdf517b1db7c 100644 --- a/crates/gpui2/src/text_system/line_wrapper.rs +++ b/crates/gpui2/src/text_system/line_wrapper.rs @@ -97,14 +97,12 @@ impl LineWrapper { self.cached_ascii_char_widths[c as usize] = Some(width); width } + } else if let Some(cached_width) = self.cached_other_char_widths.get(&c) { + *cached_width } else { - if let Some(cached_width) = self.cached_other_char_widths.get(&c) { - *cached_width - } else { - let width = self.compute_width_for_char(c); - self.cached_other_char_widths.insert(c, width); - width - } + let width = self.compute_width_for_char(c); + self.cached_other_char_widths.insert(c, width); + width } } diff --git a/crates/gpui2/src/view.rs b/crates/gpui2/src/view.rs index 41d1be852cfd7e640f92c2e983a0c85ac6ed1c8d..b090ea64c70395ad827a5cb1aacf63af092b2862 100644 --- a/crates/gpui2/src/view.rs +++ b/crates/gpui2/src/view.rs @@ -221,7 +221,7 @@ impl From> for AnyView { AnyView { model: value.model.into_any(), layout: any_view::layout::, - paint: any_view::paint::, + paint: any_view::paint, } } } @@ -243,7 +243,7 @@ impl Element for AnyView { state.is_some(), "state is None. Did you include an AnyView twice in the tree?" ); - (self.paint)(&self, state.as_mut().unwrap(), cx) + (self.paint)(self, state.as_mut().unwrap(), cx) } } @@ -293,7 +293,7 @@ impl From> for AnyWeakView { Self { model: view.model.into(), layout: any_view::layout::, - paint: any_view::paint::, + paint: any_view::paint, } } } @@ -325,11 +325,7 @@ mod any_view { (layout_id, element) } - pub(crate) fn paint( - _view: &AnyView, - element: &mut AnyElement, - cx: &mut WindowContext, - ) { + pub(crate) fn paint(_view: &AnyView, element: &mut AnyElement, cx: &mut WindowContext) { element.paint(cx); } } diff --git a/crates/gpui2/src/window.rs b/crates/gpui2/src/window.rs index c20e2f7b94a3337e05b1fa755fdb624d93396213..76e5e9f64e64b7fd4c6ed37a4a5856716857c7c4 100644 --- a/crates/gpui2/src/window.rs +++ b/crates/gpui2/src/window.rs @@ -403,7 +403,7 @@ impl Window { element_id_stack: GlobalElementId::default(), rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())), next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())), - frame_arena: Arena::new(1 * 1024 * 1024), + frame_arena: Arena::new(1024 * 1024), focus_handles: Arc::new(RwLock::new(SlotMap::with_key())), focus_listeners: SubscriberSet::new(), blur_listeners: SubscriberSet::new(), @@ -637,7 +637,7 @@ impl<'a> WindowContext<'a> { let handle = self.window.handle; let display_id = self.window.display_id; - if !self.frame_consumers.contains_key(&display_id) { + if let std::collections::hash_map::Entry::Vacant(e) = self.frame_consumers.entry(display_id) { let (tx, mut rx) = mpsc::unbounded::<()>(); self.platform.set_display_link_output_callback( display_id, @@ -669,7 +669,7 @@ impl<'a> WindowContext<'a> { .ok(); } }); - self.frame_consumers.insert(display_id, consumer_task); + e.insert(consumer_task); } if self.next_frame_callbacks.is_empty() { @@ -718,7 +718,7 @@ impl<'a> WindowContext<'a> { children: impl IntoIterator, ) -> LayoutId { self.app.layout_id_buffer.clear(); - self.app.layout_id_buffer.extend(children.into_iter()); + self.app.layout_id_buffer.extend(children); let rem_size = self.rem_size(); self.window.layout_engine.as_mut().unwrap().request_layout( @@ -844,7 +844,7 @@ impl<'a> WindowContext<'a> { let text_style = self.text_style(); text_style .line_height - .to_pixels(text_style.font_size.into(), rem_size) + .to_pixels(text_style.font_size, rem_size) } /// Call to prevent the default action of an event. Currently only used to prevent @@ -966,7 +966,7 @@ impl<'a> WindowContext<'a> { pub fn add_opaque_layer(&mut self, bounds: Bounds) { let stacking_order = self.window.next_frame.z_index_stack.clone(); let depth_map = &mut self.window.next_frame.depth_map; - match depth_map.binary_search_by(|(level, _)| stacking_order.cmp(&level)) { + match depth_map.binary_search_by(|(level, _)| stacking_order.cmp(level)) { Ok(i) | Err(i) => depth_map.insert(i, (stacking_order, bounds)), } } @@ -1889,7 +1889,7 @@ impl Context for WindowContext<'_> { T: 'static, { let entity = self.entities.read(handle); - read(&*entity, &*self.app) + read(entity, &*self.app) } fn read_window( @@ -1949,7 +1949,7 @@ impl VisualContext for WindowContext<'_> { update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R, ) -> Self::Result { let mut lease = self.app.entities.lease(&view.model); - let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view); + let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, view); let result = update(&mut *lease, &mut cx); cx.app.entities.end_lease(lease); result @@ -1986,25 +1986,25 @@ impl<'a> std::ops::Deref for WindowContext<'a> { type Target = AppContext; fn deref(&self) -> &Self::Target { - &self.app + self.app } } impl<'a> std::ops::DerefMut for WindowContext<'a> { fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.app + self.app } } impl<'a> Borrow for WindowContext<'a> { fn borrow(&self) -> &AppContext { - &self.app + self.app } } impl<'a> BorrowMut for WindowContext<'a> { fn borrow_mut(&mut self) -> &mut AppContext { - &mut self.app + self.app } } @@ -2036,7 +2036,7 @@ pub trait BorrowWindow: BorrowMut + BorrowMut { ) -> R { if let Some(id) = id.map(Into::into) { let window = self.window_mut(); - window.element_id_stack.push(id.into()); + window.element_id_stack.push(id); let result = f(self); let window: &mut Window = self.borrow_mut(); window.element_id_stack.pop(); @@ -2258,13 +2258,13 @@ pub trait BorrowWindow: BorrowMut + BorrowMut { impl Borrow for WindowContext<'_> { fn borrow(&self) -> &Window { - &self.window + self.window } } impl BorrowMut for WindowContext<'_> { fn borrow_mut(&mut self) -> &mut Window { - &mut self.window + self.window } } @@ -2939,9 +2939,9 @@ impl Hash for WindowHandle { } } -impl Into for WindowHandle { - fn into(self) -> AnyWindowHandle { - self.any_handle +impl From> for AnyWindowHandle { + fn from(val: WindowHandle) -> Self { + val.any_handle } } From a3759f9a33361ca2c732fbb7a7226b22eee0f0cf Mon Sep 17 00:00:00 2001 From: Piotr Osiewicz <24362066+osiewicz@users.noreply.github.com> Date: Tue, 2 Jan 2024 00:24:11 +0100 Subject: [PATCH 06/11] Another batch of fixups --- crates/gpui2/src/window.rs | 4 ++-- .../refineable/derive_refineable/src/derive_refineable.rs | 4 +--- crates/refineable/src/refineable.rs | 8 +++----- 3 files changed, 6 insertions(+), 10 deletions(-) diff --git a/crates/gpui2/src/window.rs b/crates/gpui2/src/window.rs index 76e5e9f64e64b7fd4c6ed37a4a5856716857c7c4..bb81a85821b5e85b821ff049f911cc0d2c1e7d91 100644 --- a/crates/gpui2/src/window.rs +++ b/crates/gpui2/src/window.rs @@ -637,7 +637,7 @@ impl<'a> WindowContext<'a> { let handle = self.window.handle; let display_id = self.window.display_id; - if let std::collections::hash_map::Entry::Vacant(e) = self.frame_consumers.entry(display_id) { + if !self.frame_consumers.contains_key(&display_id) { let (tx, mut rx) = mpsc::unbounded::<()>(); self.platform.set_display_link_output_callback( display_id, @@ -669,7 +669,7 @@ impl<'a> WindowContext<'a> { .ok(); } }); - e.insert(consumer_task); + self.frame_consumers.insert(display_id, consumer_task); } if self.next_frame_callbacks.is_empty() { diff --git a/crates/refineable/derive_refineable/src/derive_refineable.rs b/crates/refineable/derive_refineable/src/derive_refineable.rs index 15293d866a0c065d5d4b48eacfe248675ed9389a..ad7678b58fe696f61c14776c316bb9d159044b2f 100644 --- a/crates/refineable/derive_refineable/src/derive_refineable.rs +++ b/crates/refineable/derive_refineable/src/derive_refineable.rs @@ -85,9 +85,7 @@ pub fn derive_refineable(input: TokenStream) -> TokenStream { // Append to where_clause or create a new one if it doesn't exist let where_clause = match where_clause.cloned() { Some(mut where_clause) => { - where_clause - .predicates - .extend(type_param_bounds.into_iter()); + where_clause.predicates.extend(type_param_bounds); where_clause.clone() } None => WhereClause { diff --git a/crates/refineable/src/refineable.rs b/crates/refineable/src/refineable.rs index b588b5b9d88400e2a50d133a3300f0a71e51f9c9..93e2e40ac605228627a5e6341093fb6b6297d2b1 100644 --- a/crates/refineable/src/refineable.rs +++ b/crates/refineable/src/refineable.rs @@ -27,7 +27,7 @@ pub struct CascadeSlot(usize); impl Cascade { pub fn reserve(&mut self) -> CascadeSlot { self.0.push(None); - return CascadeSlot(self.0.len() - 1); + CascadeSlot(self.0.len() - 1) } pub fn base(&mut self) -> &mut S::Refinement { @@ -40,10 +40,8 @@ impl Cascade { pub fn merged(&self) -> S::Refinement { let mut merged = self.0[0].clone().unwrap(); - for refinement in self.0.iter().skip(1) { - if let Some(refinement) = refinement { - merged.refine(refinement); - } + for refinement in self.0.iter().skip(1).flatten() { + merged.refine(refinement); } merged } From bcff7a863196c2a76aa4651cea5e0dae539030be Mon Sep 17 00:00:00 2001 From: Piotr Osiewicz <24362066+osiewicz@users.noreply.github.com> Date: Tue, 2 Jan 2024 12:56:53 +0100 Subject: [PATCH 07/11] gpui2: Fix instance of map_entry lint --- crates/gpui2/src/window.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/gpui2/src/window.rs b/crates/gpui2/src/window.rs index bb81a85821b5e85b821ff049f911cc0d2c1e7d91..0e40babccd4ffae9ce2c464702bef7ff30075001 100644 --- a/crates/gpui2/src/window.rs +++ b/crates/gpui2/src/window.rs @@ -26,6 +26,7 @@ use std::{ any::{Any, TypeId}, borrow::{Borrow, BorrowMut, Cow}, cell::RefCell, + collections::hash_map::Entry, fmt::Debug, future::Future, hash::{Hash, Hasher}, @@ -637,7 +638,8 @@ impl<'a> WindowContext<'a> { let handle = self.window.handle; let display_id = self.window.display_id; - if !self.frame_consumers.contains_key(&display_id) { + let mut frame_consumers = std::mem::take(&mut self.app.frame_consumers); + if let Entry::Vacant(e) = frame_consumers.entry(display_id) { let (tx, mut rx) = mpsc::unbounded::<()>(); self.platform.set_display_link_output_callback( display_id, @@ -669,8 +671,10 @@ impl<'a> WindowContext<'a> { .ok(); } }); - self.frame_consumers.insert(display_id, consumer_task); + e.insert(consumer_task); } + debug_assert!(self.app.frame_consumers.is_empty()); + self.app.frame_consumers = frame_consumers; if self.next_frame_callbacks.is_empty() { self.platform.start_display_link(display_id); From 945dba8099047c49137dc730c03097cac6024d70 Mon Sep 17 00:00:00 2001 From: Piotr Osiewicz <24362066+osiewicz@users.noreply.github.com> Date: Tue, 2 Jan 2024 12:59:40 +0100 Subject: [PATCH 08/11] gpui2: redundant_locals --- crates/gpui2/src/elements/div.rs | 20 +++++++++++++------- crates/gpui2/src/elements/text.rs | 1 - 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/crates/gpui2/src/elements/div.rs b/crates/gpui2/src/elements/div.rs index 501ee712799ff26a77d1a2303bb5a1261dd815c0..248082d04b3d0c45d5c25983a007438743e1bd67 100644 --- a/crates/gpui2/src/elements/div.rs +++ b/crates/gpui2/src/elements/div.rs @@ -176,10 +176,12 @@ impl Interactivity { { self.mouse_move_listeners .push(Box::new(move |event, bounds, phase, cx| { - if phase == DispatchPhase::Capture && cx + if phase == DispatchPhase::Capture + && cx .active_drag .as_ref() - .is_some_and(|drag| drag.value.as_ref().type_id() == TypeId::of::()) { + .is_some_and(|drag| drag.value.as_ref().type_id() == TypeId::of::()) + { (listener)( &DragMoveEvent { event: event.clone(), @@ -1020,7 +1022,6 @@ impl Interactivity { { let command_held = cx.modifiers().command; cx.on_key_event({ - let text_bounds = text_bounds; move |e: &crate::ModifiersChangedEvent, _phase, cx| { if e.modifiers.command != command_held && text_bounds.contains(&cx.mouse_position()) @@ -1033,7 +1034,9 @@ impl Interactivity { let hovered = bounds.contains(&cx.mouse_position()); cx.on_mouse_event( move |event: &MouseMoveEvent, phase, cx| { - if phase == DispatchPhase::Capture && bounds.contains(&event.position) != hovered { + if phase == DispatchPhase::Capture + && bounds.contains(&event.position) != hovered + { cx.notify(); } }, @@ -1041,7 +1044,6 @@ impl Interactivity { cx.on_mouse_event({ let location = self.location.unwrap(); - let text_bounds = text_bounds; move |e: &crate::MouseDownEvent, phase, cx| { if text_bounds.contains(&e.position) && phase.capture() @@ -1182,7 +1184,9 @@ impl Interactivity { if let Some(group_bounds) = hover_group_bounds { let hovered = group_bounds.contains(&cx.mouse_position()); cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| { - if phase == DispatchPhase::Capture && group_bounds.contains(&event.position) != hovered { + if phase == DispatchPhase::Capture + && group_bounds.contains(&event.position) != hovered + { cx.notify(); } }); @@ -1195,7 +1199,9 @@ impl Interactivity { let bounds = bounds.intersect(&cx.content_mask().bounds); let hovered = bounds.contains(&cx.mouse_position()); cx.on_mouse_event(move |event: &MouseMoveEvent, phase, cx| { - if phase == DispatchPhase::Capture && bounds.contains(&event.position) != hovered { + if phase == DispatchPhase::Capture + && bounds.contains(&event.position) != hovered + { cx.notify(); } }); diff --git a/crates/gpui2/src/elements/text.rs b/crates/gpui2/src/elements/text.rs index 834168f0b56d01e21e2508fc1993d765a5b5b321..29c93fd19e91518a96a5f663352b92519264aca9 100644 --- a/crates/gpui2/src/elements/text.rs +++ b/crates/gpui2/src/elements/text.rs @@ -171,7 +171,6 @@ impl TextState { let line_height = text_style .line_height .to_pixels(font_size.into(), cx.rem_size()); - let text = text; let runs = if let Some(runs) = runs { runs From 4af6ac25e9aef3a5974c455ded97c134e43316ea Mon Sep 17 00:00:00 2001 From: Piotr Osiewicz <24362066+osiewicz@users.noreply.github.com> Date: Tue, 2 Jan 2024 13:11:36 +0100 Subject: [PATCH 09/11] gpui2: Another round of fixups --- crates/gpui2/src/elements/div.rs | 45 ++----------------- crates/gpui2/src/elements/overlay.rs | 8 ++-- .../gpui2/src/platform/mac/metal_renderer.rs | 10 ++--- crates/gpui2/src/platform/mac/platform.rs | 10 +++-- crates/gpui2/src/window.rs | 5 +-- crates/ui2/src/components/context_menu.rs | 2 +- 6 files changed, 21 insertions(+), 59 deletions(-) diff --git a/crates/gpui2/src/elements/div.rs b/crates/gpui2/src/elements/div.rs index 248082d04b3d0c45d5c25983a007438743e1bd67..aa5fff8b3d950b86931c18a490db7ba30147dc17 100644 --- a/crates/gpui2/src/elements/div.rs +++ b/crates/gpui2/src/elements/div.rs @@ -235,7 +235,7 @@ impl Interactivity { pub fn on_boxed_action( &mut self, - action: &Box, + action: &dyn Action, listener: impl Fn(&Box, &mut WindowContext) + 'static, ) { let action = action.boxed_clone(); @@ -510,7 +510,7 @@ pub trait InteractiveElement: Sized { fn on_boxed_action( mut self, - action: &Box, + action: &dyn Action, listener: impl Fn(&Box, &mut WindowContext) + 'static, ) -> Self { self.interactivity().on_boxed_action(action, listener); @@ -877,6 +877,7 @@ impl DivState { } } +#[derive(Default)] pub struct Interactivity { pub element_id: Option, pub key_context: Option, @@ -1689,46 +1690,6 @@ impl Interactivity { } } -impl Default for Interactivity { - fn default() -> Self { - Self { - element_id: None, - key_context: None, - focusable: false, - tracked_focus_handle: None, - scroll_handle: None, - // scroll_offset: Point::default(), - group: None, - base_style: Box::::default(), - focus_style: None, - in_focus_style: None, - hover_style: None, - group_hover_style: None, - active_style: None, - group_active_style: None, - drag_over_styles: Vec::new(), - group_drag_over_styles: Vec::new(), - mouse_down_listeners: Vec::new(), - mouse_up_listeners: Vec::new(), - mouse_move_listeners: Vec::new(), - scroll_wheel_listeners: Vec::new(), - key_down_listeners: Vec::new(), - key_up_listeners: Vec::new(), - action_listeners: Vec::new(), - drop_listeners: Vec::new(), - can_drop_predicate: None, - click_listeners: Vec::new(), - drag_listener: None, - hover_listener: None, - tooltip_builder: None, - block_mouse: false, - - #[cfg(debug_assertions)] - location: None, - } - } -} - #[derive(Default)] pub struct InteractiveElementState { pub focus_handle: Option, diff --git a/crates/gpui2/src/elements/overlay.rs b/crates/gpui2/src/elements/overlay.rs index b5d8b53c7f613f92b966cd0afa025d636394b12e..69fe1201429f8b081712e4df2ad20c7cb707bc7e 100644 --- a/crates/gpui2/src/elements/overlay.rs +++ b/crates/gpui2/src/elements/overlay.rs @@ -71,9 +71,11 @@ impl Element for Overlay { .map(|child| child.layout(cx)) .collect::>(); - let mut overlay_style = Style::default(); - overlay_style.position = Position::Absolute; - overlay_style.display = Display::Flex; + let overlay_style = Style { + position: Position::Absolute, + display: Display::Flex, + ..Style::default() + }; let layout_id = cx.request_layout(&overlay_style, child_layout_ids.iter().copied()); diff --git a/crates/gpui2/src/platform/mac/metal_renderer.rs b/crates/gpui2/src/platform/mac/metal_renderer.rs index e0682024766794b232ff9c9cb260674bb852f7a4..a6cdd166d312d5eb97fc749a645a8cb09ea0dd8a 100644 --- a/crates/gpui2/src/platform/mac/metal_renderer.rs +++ b/crates/gpui2/src/platform/mac/metal_renderer.rs @@ -66,12 +66,10 @@ impl MetalRenderer { .expect("error building metal library"); fn to_float2_bits(point: crate::PointF) -> u64 { - unsafe { - let mut output = mem::transmute::<_, u32>(point.y.to_bits()) as u64; - output <<= 32; - output |= mem::transmute::<_, u32>(point.x.to_bits()) as u64; - output - } + let mut output = point.y.to_bits() as u64; + output <<= 32; + output |= point.x.to_bits() as u64; + output } let unit_vertices = [ diff --git a/crates/gpui2/src/platform/mac/platform.rs b/crates/gpui2/src/platform/mac/platform.rs index 7dc35ba1ad9c469ed30d6f77a51958274a269587..153736870a10cbfaf1b9b04f2ae77eff0ec0140c 100644 --- a/crates/gpui2/src/platform/mac/platform.rs +++ b/crates/gpui2/src/platform/mac/platform.rs @@ -225,7 +225,12 @@ impl MacPlatform { menu.setDelegate_(delegate); for item_config in menu_config.items { - menu.addItem_(self.create_menu_item(item_config, delegate, actions, keymap)); + menu.addItem_(Self::create_menu_item( + item_config, + delegate, + actions, + keymap, + )); } let menu_item = NSMenuItem::new(nil).autorelease(); @@ -242,7 +247,6 @@ impl MacPlatform { } unsafe fn create_menu_item( - &self, item: MenuItem, delegate: id, actions: &mut Vec>, @@ -348,7 +352,7 @@ impl MacPlatform { let submenu = NSMenu::new(nil).autorelease(); submenu.setDelegate_(delegate); for item in items { - submenu.addItem_(self.create_menu_item(item, delegate, actions, keymap)); + submenu.addItem_(Self::create_menu_item(item, delegate, actions, keymap)); } item.setSubmenu_(submenu); item.setTitle_(ns_string(name)); diff --git a/crates/gpui2/src/window.rs b/crates/gpui2/src/window.rs index 0e40babccd4ffae9ce2c464702bef7ff30075001..1af0f5582200e66f458ab60488d691817f60f7e0 100644 --- a/crates/gpui2/src/window.rs +++ b/crates/gpui2/src/window.rs @@ -2922,10 +2922,7 @@ impl Copy for WindowHandle {} impl Clone for WindowHandle { fn clone(&self) -> Self { - WindowHandle { - any_handle: self.any_handle, - state_type: PhantomData, - } + *self } } diff --git a/crates/ui2/src/components/context_menu.rs b/crates/ui2/src/components/context_menu.rs index 52ba2cedb2e66446f9d9a442e7ad729bb90d4821..14d0b3b18bd3154d3bd0510f6b7904eb090c7318 100644 --- a/crates/ui2/src/components/context_menu.rs +++ b/crates/ui2/src/components/context_menu.rs @@ -253,7 +253,7 @@ impl Render for ContextMenu { } = item { el = el.on_boxed_action( - action, + &**action, cx.listener(ContextMenu::on_action_dispatch), ); } From 388c2d8e7f12591341c74dc2b1e07e49755510dd Mon Sep 17 00:00:00 2001 From: Piotr Osiewicz <24362066+osiewicz@users.noreply.github.com> Date: Tue, 2 Jan 2024 13:15:57 +0100 Subject: [PATCH 10/11] cargo fmt --- crates/gpui2/src/element.rs | 6 +----- crates/gpui2/src/scene.rs | 2 -- crates/gpui2/src/taffy.rs | 3 +-- crates/gpui2/src/text_system.rs | 5 +---- 4 files changed, 3 insertions(+), 13 deletions(-) diff --git a/crates/gpui2/src/element.rs b/crates/gpui2/src/element.rs index bdb63d084ebbed6b569ad14ab6fbe519f0df4512..73ea66042e456e685600b2d5c209f05d038c096e 100644 --- a/crates/gpui2/src/element.rs +++ b/crates/gpui2/src/element.rs @@ -193,11 +193,7 @@ impl Element for Component { ((), element_state) }); } else { - element.paint( - bounds, - state.rendered_element_state.as_mut().unwrap(), - cx, - ); + element.paint(bounds, state.rendered_element_state.as_mut().unwrap(), cx); } } } diff --git a/crates/gpui2/src/scene.rs b/crates/gpui2/src/scene.rs index 7640b9b2d3519c25e62a976a3ad2c4bc7877ce38..e922c11f533680e102e67bfa7bd5d51b741678a3 100644 --- a/crates/gpui2/src/scene.rs +++ b/crates/gpui2/src/scene.rs @@ -27,8 +27,6 @@ pub(crate) struct SceneBuilder { surfaces: Vec, } - - impl SceneBuilder { pub fn build(&mut self) -> Scene { let mut orders = vec![0; self.layers_by_order.len()]; diff --git a/crates/gpui2/src/taffy.rs b/crates/gpui2/src/taffy.rs index 0a8a470289253cc35b4f6085bf1627aeef23c0c3..0ebd394217ae06c6a2256281f389ab506bfca934 100644 --- a/crates/gpui2/src/taffy.rs +++ b/crates/gpui2/src/taffy.rs @@ -29,8 +29,7 @@ pub struct TaffyLayoutEngine { >, } -static EXPECT_MESSAGE: &str = - "we should avoid taffy layout errors by construction if possible"; +static EXPECT_MESSAGE: &str = "we should avoid taffy layout errors by construction if possible"; impl TaffyLayoutEngine { pub fn new() -> Self { diff --git a/crates/gpui2/src/text_system.rs b/crates/gpui2/src/text_system.rs index 7c3832ec12fa55363741ee96b7cf7851cf5cd109..944a9b78bec2a33b4b20e4e1e1b991565d42212b 100644 --- a/crates/gpui2/src/text_system.rs +++ b/crates/gpui2/src/text_system.rs @@ -438,8 +438,7 @@ impl FontWeight { } /// Allows italic or oblique faces to be selected. -#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash)] -#[derive(Default)] +#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash, Default)] pub enum FontStyle { /// A face that is neither italic not obliqued. #[default] @@ -450,8 +449,6 @@ pub enum FontStyle { Oblique, } - - impl Display for FontStyle { fn fmt(&self, f: &mut Formatter) -> fmt::Result { Debug::fmt(self, f) From 576d8806f5e010a60a70e4d577e3158cd52c6eeb Mon Sep 17 00:00:00 2001 From: Piotr Osiewicz <24362066+osiewicz@users.noreply.github.com> Date: Tue, 2 Jan 2024 13:18:56 +0100 Subject: [PATCH 11/11] Fix up gpui1 --- crates/gpui/src/platform/mac/renderer.rs | 48 ++++++++++++------------ 1 file changed, 25 insertions(+), 23 deletions(-) diff --git a/crates/gpui/src/platform/mac/renderer.rs b/crates/gpui/src/platform/mac/renderer.rs index 85f0af1ffddb902f00bcdb15012e474547e68fa7..2eaaf6db8ed5968bc7a6e6bc2e4fbdc73320ed64 100644 --- a/crates/gpui/src/platform/mac/renderer.rs +++ b/crates/gpui/src/platform/mac/renderer.rs @@ -162,7 +162,7 @@ impl Renderer { "underline_fragment", PIXEL_FORMAT, ); - let cv_texture_cache = CVMetalTextureCache::new(device.as_ptr()).unwrap(); + let cv_texture_cache = unsafe { CVMetalTextureCache::new(device.as_ptr()).unwrap() }; Self { layer, command_queue: device.new_command_queue(), @@ -887,28 +887,30 @@ impl Renderer { core_video::kCVPixelFormatType_420YpCbCr8BiPlanarFullRange ); - let y_texture = self - .cv_texture_cache - .create_texture_from_image( - surface.image_buffer.as_concrete_TypeRef(), - ptr::null(), - MTLPixelFormat::R8Unorm, - surface.image_buffer.plane_width(0), - surface.image_buffer.plane_height(0), - 0, - ) - .unwrap(); - let cb_cr_texture = self - .cv_texture_cache - .create_texture_from_image( - surface.image_buffer.as_concrete_TypeRef(), - ptr::null(), - MTLPixelFormat::RG8Unorm, - surface.image_buffer.plane_width(1), - surface.image_buffer.plane_height(1), - 1, - ) - .unwrap(); + let y_texture = unsafe { + self.cv_texture_cache + .create_texture_from_image( + surface.image_buffer.as_concrete_TypeRef(), + ptr::null(), + MTLPixelFormat::R8Unorm, + surface.image_buffer.plane_width(0), + surface.image_buffer.plane_height(0), + 0, + ) + .unwrap() + }; + let cb_cr_texture = unsafe { + self.cv_texture_cache + .create_texture_from_image( + surface.image_buffer.as_concrete_TypeRef(), + ptr::null(), + MTLPixelFormat::RG8Unorm, + surface.image_buffer.plane_width(1), + surface.image_buffer.plane_height(1), + 1, + ) + .unwrap() + }; align_offset(offset); let next_offset = *offset + mem::size_of::();