Rest of fixups for gpui2

This commit is contained in:
Piotr Osiewicz 2024-01-02 00:09:24 +01:00
parent 7d420edb84
commit 2621efebea
33 changed files with 184 additions and 196 deletions

View File

@ -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<AnyWindowHandle> {
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::<G>::default())
.downcast_mut::<G>()
.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();

View File

@ -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<V>(

View File

@ -327,9 +327,9 @@ impl<T: 'static> Model<T> {
cx.entities.read(self)
}
pub fn read_with<'a, R, C: Context>(
pub fn read_with<R, C: Context>(
&self,
cx: &'a C,
cx: &C,
f: impl FnOnce(&T, &AppContext) -> R,
) -> C::Result<R> {
cx.read_model(self, f)

View File

@ -262,12 +262,12 @@ impl<'a, T> Context for ModelContext<'a, T> {
impl<T> Borrow<AppContext> for ModelContext<'_, T> {
fn borrow(&self) -> &AppContext {
&self.app
self.app
}
}
impl<T> BorrowMut<AppContext> for ModelContext<'_, T> {
fn borrow_mut(&mut self) -> &mut AppContext {
&mut self.app
self.app
}
}

View File

@ -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 {

View File

@ -159,7 +159,7 @@ impl<C: RenderOnce> Element for Component<C> {
} else {
element.paint(
bounds,
&mut state.rendered_element_state.as_mut().unwrap(),
state.rendered_element_state.as_mut().unwrap(),
cx,
);
}

View File

@ -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::<T>())
{
(listener)(
&DragMoveEvent {
event: event.clone(),
bounds: bounds.bounds,
drag: PhantomData,
},
cx,
);
}
.is_some_and(|drag| drag.value.as_ref().type_id() == TypeId::of::<T>()) {
(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<Pixels>, 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<Pixels>, 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::<StyleRefinement>::default(),
focus_style: None,
in_focus_style: None,
hover_style: None,
@ -1942,13 +1932,19 @@ struct ScrollHandleState {
#[derive(Clone)]
pub struct ScrollHandle(Rc<RefCell<ScrollHandleState>>);
impl Default for ScrollHandle {
fn default() -> Self {
Self::new()
}
}
impl ScrollHandle {
pub fn new() -> Self {
Self(Rc::default())
}
pub fn offset(&self) -> Point<Pixels> {
self.0.borrow().offset.borrow().clone()
*self.0.borrow().offset.borrow()
}
pub fn top_item(&self) -> usize {

View File

@ -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

View File

@ -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)]

View File

@ -80,6 +80,12 @@ impl<T> Future for Task<T> {
#[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);

View File

@ -1601,13 +1601,13 @@ impl Edges<Pixels> {
}
}
impl Into<Edges<Pixels>> for f32 {
fn into(self) -> Edges<Pixels> {
impl From<f32> for Edges<Pixels> {
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<T> Copy for Corners<T> where T: Copy + Clone + Default + Debug {}
impl Into<Corners<Pixels>> for f32 {
fn into(self) -> Corners<Pixels> {
impl From<f32> for Corners<Pixels> {
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<Corners<Pixels>> for Pixels {
fn into(self) -> Corners<Pixels> {
impl From<Pixels> for Corners<Pixels> {
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.

View File

@ -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),

View File

@ -200,7 +200,7 @@ impl DispatchTree {
return true;
}
}
return false;
false
})
.cloned()
.collect()

View File

@ -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

View File

@ -24,7 +24,7 @@ impl KeyContext {
pub fn parse(source: &str) -> Result<Self> {
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) => {

View File

@ -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;

View File

@ -23,6 +23,12 @@ pub struct MacDispatcher {
parker: Arc<Mutex<Parker>>,
}
impl Default for MacDispatcher {
fn default() -> Self {
Self::new()
}
}
impl MacDispatcher {
pub fn new() -> Self {
MacDispatcher {

View File

@ -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");
}

View File

@ -49,7 +49,6 @@ impl MacDisplayLinker {
);
} else {
log::warn!("DisplayLink could not be obtained for {:?}", display_id);
return;
}
}

View File

@ -64,7 +64,7 @@ impl PlatformAtlas for MetalAtlas {
) -> Result<AtlasTile> {
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,
);
}

View File

@ -179,7 +179,7 @@ impl MetalRenderer {
}
pub fn layer(&self) -> &metal::MetalLayerRef {
&*self.layer
&self.layer
}
pub fn sprite_atlas(&self) -> &Arc<MetalAtlas> {
@ -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<DevicePixels> as *const _,
);
let shadow_bytes_len = mem::size_of::<Shadow>() * 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<DevicePixels> as *const _,
);
let quad_bytes_len = mem::size_of::<Quad>() * 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<DevicePixels> as *const _,
);
let quad_bytes_len = mem::size_of::<Underline>() * 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::<MonochromeSprite>() * 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::<PolychromeSprite>() * 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(

View File

@ -166,6 +166,12 @@ pub struct MacPlatformState {
finish_launching: Option<Box<dyn FnOnce()>>,
}
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<Rc<dyn PlatformDisplay>> {
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() {

View File

@ -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
}

View File

@ -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<Pixels> {
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
};
}
}
}

View File

@ -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<StackingOrder, LayerId>,
@ -26,21 +27,7 @@ pub(crate) struct SceneBuilder {
surfaces: Vec<Surface>,
}
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 {

View File

@ -60,9 +60,9 @@ impl<'a> PartialEq<&'a str> for SharedString {
}
}
impl Into<Arc<str>> for SharedString {
fn into(self) -> Arc<str> {
match self.0 {
impl From<SharedString> for Arc<str> {
fn from(val: SharedString) -> Self {
match val.0 {
ArcCow::Borrowed(borrowed) => Arc::from(borrowed),
ArcCow::Owned(owned) => owned.clone(),
}
@ -75,9 +75,9 @@ impl<T: Into<ArcCow<'static, str>>> From<T> for SharedString {
}
}
impl Into<String> for SharedString {
fn into(self) -> String {
self.0.to_string()
impl From<SharedString> for String {
fn from(val: SharedString) -> Self {
val.0.to_string()
}
}

View File

@ -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,
}
}

View File

@ -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<Item = Callback> {
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);
}

View File

@ -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<taffy::style::Style> 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<T, T2> Into<TaffyPoint<T2>> for Point<T>
impl<T, T2> From<Point<T>> for TaffyPoint<T2>
where
T: Into<T2> + Clone + Default + Debug,
{
fn into(self) -> TaffyPoint<T2> {
fn from(val: Point<T>) -> 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<U> {
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<U> {
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),
}
}
}

View File

@ -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<Bounds<DevicePixels>> {
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 {

View File

@ -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
}
}

View File

@ -221,7 +221,7 @@ impl<V: Render> From<View<V>> for AnyView {
AnyView {
model: value.model.into_any(),
layout: any_view::layout::<V>,
paint: any_view::paint::<V>,
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<V: 'static + Render> From<WeakView<V>> for AnyWeakView {
Self {
model: view.model.into(),
layout: any_view::layout::<V>,
paint: any_view::paint::<V>,
paint: any_view::paint,
}
}
}
@ -325,11 +325,7 @@ mod any_view {
(layout_id, element)
}
pub(crate) fn paint<V: 'static + Render>(
_view: &AnyView,
element: &mut AnyElement,
cx: &mut WindowContext,
) {
pub(crate) fn paint(_view: &AnyView, element: &mut AnyElement, cx: &mut WindowContext) {
element.paint(cx);
}
}

View File

@ -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<Item = LayoutId>,
) -> 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<Pixels>) {
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<T, R>(
@ -1949,7 +1949,7 @@ impl VisualContext for WindowContext<'_> {
update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
) -> Self::Result<R> {
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<AppContext> for WindowContext<'a> {
fn borrow(&self) -> &AppContext {
&self.app
self.app
}
}
impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
fn borrow_mut(&mut self) -> &mut AppContext {
&mut self.app
self.app
}
}
@ -2036,7 +2036,7 @@ pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
) -> 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<Window> + BorrowMut<AppContext> {
impl Borrow<Window> for WindowContext<'_> {
fn borrow(&self) -> &Window {
&self.window
self.window
}
}
impl BorrowMut<Window> for WindowContext<'_> {
fn borrow_mut(&mut self) -> &mut Window {
&mut self.window
self.window
}
}
@ -2939,9 +2939,9 @@ impl<V> Hash for WindowHandle<V> {
}
}
impl<V: 'static> Into<AnyWindowHandle> for WindowHandle<V> {
fn into(self) -> AnyWindowHandle {
self.any_handle
impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
fn from(val: WindowHandle<V>) -> Self {
val.any_handle
}
}