Fix clippy lints in GPUI and finish documenting GPUI modules (#4188)

TODO:
- [x] Clippy pass
- [x] Element / WindowContext refactor
- [x] `geometry `
- [x] `text_system`
- [x] `styled`
- [x] `element_cx`

Release Notes:

- N/A
This commit is contained in:
Mikayla Maki 2024-01-22 19:56:47 -08:00 committed by GitHub
commit 3d5bce643c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
31 changed files with 387 additions and 120 deletions

View file

@ -15,6 +15,7 @@ runs:
# will have more fixes & suppression for the standard lint set
run: |
cargo clippy --workspace --all-features --all-targets -- -A clippy::all -D clippy::dbg_macro -D clippy::todo
cargo clippy -p gpui
- name: Find modified migrations
shell: bash -euxo pipefail {0}

View file

@ -25,13 +25,12 @@ use crate::{
use anyhow::{anyhow, Result};
use collections::{FxHashMap, FxHashSet, VecDeque};
use futures::{channel::oneshot, future::LocalBoxFuture, Future};
use parking_lot::Mutex;
use slotmap::SlotMap;
use std::{
any::{type_name, TypeId},
cell::{Ref, RefCell, RefMut},
marker::PhantomData,
mem,
ops::{Deref, DerefMut},
path::{Path, PathBuf},
rc::{Rc, Weak},
@ -109,6 +108,7 @@ pub struct App(Rc<AppCell>);
/// configured, you'll start the app with `App::run`.
impl App {
/// Builds an app with the given asset source.
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
Self(AppContext::new(
current_platform(),
@ -224,7 +224,7 @@ pub struct AppContext {
pub(crate) entities: EntityMap,
pub(crate) new_view_observers: SubscriberSet<TypeId, NewViewListener>,
pub(crate) windows: SlotMap<WindowId, Option<Window>>,
pub(crate) keymap: Arc<Mutex<Keymap>>,
pub(crate) keymap: Rc<RefCell<Keymap>>,
pub(crate) global_action_listeners:
FxHashMap<TypeId, Vec<Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Self)>>>,
pending_effects: VecDeque<Effect>,
@ -242,6 +242,7 @@ pub struct AppContext {
}
impl AppContext {
#[allow(clippy::new_ret_no_self)]
pub(crate) fn new(
platform: Rc<dyn Platform>,
asset_source: Arc<dyn AssetSource>,
@ -285,7 +286,7 @@ impl AppContext {
entities,
new_view_observers: SubscriberSet::new(),
windows: SlotMap::with_key(),
keymap: Arc::new(Mutex::new(Keymap::default())),
keymap: Rc::new(RefCell::new(Keymap::default())),
global_action_listeners: FxHashMap::default(),
pending_effects: VecDeque::new(),
pending_notifications: FxHashSet::default(),
@ -763,7 +764,7 @@ impl AppContext {
/// so it can be held across `await` points.
pub fn to_async(&self) -> AsyncAppContext {
AsyncAppContext {
app: unsafe { mem::transmute(self.this.clone()) },
app: self.this.clone(),
background_executor: self.background_executor.clone(),
foreground_executor: self.foreground_executor.clone(),
}
@ -996,13 +997,13 @@ impl AppContext {
/// Register key bindings.
pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
self.keymap.lock().add_bindings(bindings);
self.keymap.borrow_mut().add_bindings(bindings);
self.pending_effects.push_back(Effect::Refresh);
}
/// Clear all key bindings in the app.
pub fn clear_key_bindings(&mut self) {
self.keymap.lock().clear();
self.keymap.borrow_mut().clear();
self.pending_effects.push_back(Effect::Refresh);
}
@ -1106,7 +1107,7 @@ impl AppContext {
/// Sets the menu bar for this application. This will replace any existing menu bar.
pub fn set_menus(&mut self, menus: Vec<Menu>) {
self.platform.set_menus(menus, &self.keymap.lock());
self.platform.set_menus(menus, &self.keymap.borrow());
}
/// Dispatch an action to the currently active window or global action handler

View file

@ -242,7 +242,7 @@ impl Clone for AnyModel {
assert_ne!(prev_count, 0, "Detected over-release of a model.");
}
let this = Self {
Self {
entity_id: self.entity_id,
entity_type: self.entity_type,
entity_map: self.entity_map.clone(),
@ -254,8 +254,7 @@ impl Clone for AnyModel {
.write()
.leak_detector
.handle_created(self.entity_id),
};
this
}
}
}

View file

@ -203,20 +203,16 @@ impl PartialEq for Hsla {
impl PartialOrd for Hsla {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
// SAFETY: The total ordering relies on this always being Some()
Some(
self.h
.total_cmp(&other.h)
.then(self.s.total_cmp(&other.s))
.then(self.l.total_cmp(&other.l).then(self.a.total_cmp(&other.a))),
)
Some(self.cmp(other))
}
}
impl Ord for Hsla {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
// SAFETY: The partial comparison is a total comparison
unsafe { self.partial_cmp(other).unwrap_unchecked() }
self.h
.total_cmp(&other.h)
.then(self.s.total_cmp(&other.s))
.then(self.l.total_cmp(&other.l).then(self.a.total_cmp(&other.a)))
}
}

View file

@ -133,9 +133,7 @@ pub trait Render: 'static + Sized {
}
impl Render for () {
fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
()
}
fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {}
}
/// You can derive [`IntoElement`] on any type that implements this trait.

View file

@ -1008,10 +1008,9 @@ pub(crate) type ActionListener = Box<dyn Fn(&dyn Any, DispatchPhase, &mut Window
#[track_caller]
pub fn div() -> Div {
#[cfg(debug_assertions)]
let interactivity = {
let mut interactivity = Interactivity::default();
interactivity.location = Some(*core::panic::Location::caller());
interactivity
let interactivity = Interactivity {
location: Some(*core::panic::Location::caller()),
..Default::default()
};
#[cfg(not(debug_assertions))]

View file

@ -222,7 +222,7 @@ impl OverlayPositionMode {
) -> (Point<Pixels>, Bounds<Pixels>) {
match self {
OverlayPositionMode::Window => {
let anchor_position = anchor_position.unwrap_or_else(|| bounds.origin);
let anchor_position = anchor_position.unwrap_or(bounds.origin);
let bounds = anchor_corner.get_bounds(anchor_position, size);
(anchor_position, bounds)
}

View file

@ -181,7 +181,7 @@ impl Element for UniformList {
let shared_scroll_offset = element_state
.interactive
.scroll_offset
.get_or_insert_with(|| Rc::default())
.get_or_insert_with(Rc::default)
.clone();
let item_height = self.measure_item(Some(padded_bounds.size.width), cx).height;

View file

@ -1,3 +1,7 @@
//! The GPUI geometry module is a collection of types and traits that
//! can be used to describe common units, concepts, and the relationships
//! between them.
use core::fmt::Debug;
use derive_more::{Add, AddAssign, Div, DivAssign, Mul, Neg, Sub, SubAssign};
use refineable::Refineable;
@ -8,13 +12,17 @@ use std::{
ops::{Add, Div, Mul, MulAssign, Sub},
};
/// An axis along which a measurement can be made.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum Axis {
/// The y axis, or up and down
Vertical,
/// The x axis, or left and right
Horizontal,
}
impl Axis {
/// Swap this axis to the opposite axis.
pub fn invert(&self) -> Self {
match self {
Axis::Vertical => Axis::Horizontal,
@ -23,11 +31,15 @@ impl Axis {
}
}
/// A trait for accessing the given unit along a certain axis.
pub trait Along {
/// The unit associated with this type
type Unit;
/// Returns the unit along the given axis.
fn along(&self, axis: Axis) -> Self::Unit;
/// Applies the given function to the unit along the given axis and returns a new value.
fn apply_along(&self, axis: Axis, f: impl FnOnce(Self::Unit) -> Self::Unit) -> Self;
}
@ -47,7 +59,9 @@ pub trait Along {
#[refineable(Debug)]
#[repr(C)]
pub struct Point<T: Default + Clone + Debug> {
/// The x coordinate of the point.
pub x: T,
/// The y coordinate of the point.
pub y: T,
}
@ -334,7 +348,9 @@ impl<T: Clone + Default + Debug> Clone for Point<T> {
#[refineable(Debug)]
#[repr(C)]
pub struct Size<T: Clone + Default + Debug> {
/// The width component of the size.
pub width: T,
/// The height component of the size.
pub height: T,
}
@ -640,7 +656,9 @@ impl Size<Length> {
#[refineable(Debug)]
#[repr(C)]
pub struct Bounds<T: Clone + Default + Debug> {
/// The origin point of this area.
pub origin: Point<T>,
/// The size of the rectangle.
pub size: Size<T>,
}
@ -1192,9 +1210,13 @@ impl<T: Clone + Debug + Copy + Default> Copy for Bounds<T> {}
#[refineable(Debug)]
#[repr(C)]
pub struct Edges<T: Clone + Default + Debug> {
/// The size of the top edge.
pub top: T,
/// The size of the right edge.
pub right: T,
/// The size of the bottom edge.
pub bottom: T,
/// The size of the left edge.
pub left: T,
}
@ -1600,9 +1622,13 @@ impl From<f32> for Edges<Pixels> {
#[refineable(Debug)]
#[repr(C)]
pub struct Corners<T: Clone + Default + Debug> {
/// The value associated with the top left corner.
pub top_left: T,
/// The value associated with the top right corner.
pub top_right: T,
/// The value associated with the bottom right corner.
pub bottom_right: T,
/// The value associated with the bottom left corner.
pub bottom_left: T,
}
@ -2020,13 +2046,13 @@ impl Eq for Pixels {}
impl PartialOrd for Pixels {
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
self.0.partial_cmp(&other.0)
Some(self.cmp(other))
}
}
impl Ord for Pixels {
fn cmp(&self, other: &Self) -> cmp::Ordering {
self.partial_cmp(other).unwrap()
self.0.total_cmp(&other.0)
}
}

View file

@ -26,6 +26,9 @@
//! TODO!(docs): Wrap up with a conclusion and links to other places? Zed / GPUI website?
//! Discord for chatting about it? Other tutorials or references?
#![deny(missing_docs)]
#![allow(clippy::type_complexity)]
#[macro_use]
mod action;
mod app;

View file

@ -343,7 +343,7 @@ impl ExternalPaths {
impl Render for ExternalPaths {
fn render(&mut self, _: &mut ViewContext<Self>) -> impl IntoElement {
() // Intentionally left empty because the platform will render icons for the dragged files
// Intentionally left empty because the platform will render icons for the dragged files
}
}

View file

@ -54,13 +54,12 @@ use crate::{
KeyContext, Keymap, KeymatchResult, Keystroke, KeystrokeMatcher, WindowContext,
};
use collections::FxHashMap;
use parking_lot::Mutex;
use smallvec::{smallvec, SmallVec};
use std::{
any::{Any, TypeId},
cell::RefCell,
mem,
rc::Rc,
sync::Arc,
};
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
@ -73,7 +72,7 @@ pub(crate) struct DispatchTree {
focusable_node_ids: FxHashMap<FocusId, DispatchNodeId>,
view_node_ids: FxHashMap<EntityId, DispatchNodeId>,
keystroke_matchers: FxHashMap<SmallVec<[KeyContext; 4]>, KeystrokeMatcher>,
keymap: Arc<Mutex<Keymap>>,
keymap: Rc<RefCell<Keymap>>,
action_registry: Rc<ActionRegistry>,
}
@ -96,7 +95,7 @@ pub(crate) struct DispatchActionListener {
}
impl DispatchTree {
pub fn new(keymap: Arc<Mutex<Keymap>>, action_registry: Rc<ActionRegistry>) -> Self {
pub fn new(keymap: Rc<RefCell<Keymap>>, action_registry: Rc<ActionRegistry>) -> Self {
Self {
node_stack: Vec::new(),
context_stack: Vec::new(),
@ -307,7 +306,7 @@ impl DispatchTree {
action: &dyn Action,
context_stack: &Vec<KeyContext>,
) -> Vec<KeyBinding> {
let keymap = self.keymap.lock();
let keymap = self.keymap.borrow();
keymap
.bindings_for_action(action)
.filter(|binding| {
@ -440,9 +439,7 @@ impl DispatchTree {
#[cfg(test)]
mod tests {
use std::{rc::Rc, sync::Arc};
use parking_lot::Mutex;
use std::{cell::RefCell, rc::Rc};
use crate::{Action, ActionRegistry, DispatchTree, KeyBinding, KeyContext, Keymap};
@ -496,7 +493,7 @@ mod tests {
registry.load_action::<TestAction>();
let keymap = Arc::new(Mutex::new(keymap));
let keymap = Rc::new(RefCell::new(keymap));
let tree = DispatchTree::new(keymap, Rc::new(registry));

View file

@ -1,4 +1,12 @@
use crate::{Action, KeyBinding, KeyBindingContextPredicate, KeyContext, Keystroke, NoAction};
mod binding;
mod context;
mod matcher;
pub use binding::*;
pub use context::*;
pub(crate) use matcher::*;
use crate::{Action, Keystroke, NoAction};
use collections::HashSet;
use smallvec::SmallVec;
use std::{

View file

@ -267,8 +267,8 @@ impl KeyBindingContextPredicate {
'(' => {
source = skip_whitespace(&source[1..]);
let (predicate, rest) = Self::parse_expr(source, 0)?;
if rest.starts_with(')') {
source = skip_whitespace(&rest[1..]);
if let Some(stripped) = rest.strip_prefix(')') {
source = skip_whitespace(stripped);
Ok((predicate, source))
} else {
Err(anyhow!("expected a ')'"))

View file

@ -1,11 +1,10 @@
use crate::{KeyBinding, KeyContext, Keymap, KeymapVersion, Keystroke};
use parking_lot::Mutex;
use smallvec::SmallVec;
use std::sync::Arc;
use std::{cell::RefCell, rc::Rc};
pub(crate) struct KeystrokeMatcher {
pending_keystrokes: Vec<Keystroke>,
keymap: Arc<Mutex<Keymap>>,
keymap: Rc<RefCell<Keymap>>,
keymap_version: KeymapVersion,
}
@ -15,8 +14,8 @@ pub struct KeymatchResult {
}
impl KeystrokeMatcher {
pub fn new(keymap: Arc<Mutex<Keymap>>) -> Self {
let keymap_version = keymap.lock().version();
pub fn new(keymap: Rc<RefCell<Keymap>>) -> Self {
let keymap_version = keymap.borrow().version();
Self {
pending_keystrokes: Vec::new(),
keymap_version,
@ -42,7 +41,8 @@ impl KeystrokeMatcher {
keystroke: &Keystroke,
context_stack: &[KeyContext],
) -> KeymatchResult {
let keymap = self.keymap.lock();
let keymap = self.keymap.borrow();
// Clear pending keystrokes if the keymap has changed since the last matched keystroke.
if keymap.version() != self.keymap_version {
self.keymap_version = keymap.version();
@ -72,7 +72,7 @@ impl KeystrokeMatcher {
}
}
if bindings.len() == 0 && pending_key.is_none() && self.pending_keystrokes.len() > 0 {
if bindings.is_empty() && pending_key.is_none() && !self.pending_keystrokes.is_empty() {
drop(keymap);
self.pending_keystrokes.remove(0);
return self.match_keystroke(keystroke, context_stack);

View file

@ -1,9 +0,0 @@
mod binding;
mod context;
mod keymap;
mod matcher;
pub use binding::*;
pub use context::*;
pub use keymap::*;
pub(crate) use matcher::*;

View file

@ -397,7 +397,7 @@ impl PlatformInputHandler {
let Some(range) = self.handler.selected_text_range(cx) else {
return;
};
self.handler.replace_text_in_range(Some(range), &input, cx);
self.handler.replace_text_in_range(Some(range), input, cx);
}
}

View file

@ -143,7 +143,7 @@ impl PlatformTextSystem for MacTextSystem {
fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>> {
Ok(self.0.read().fonts[font_id.0]
.typographic_bounds(glyph_id.into())?
.typographic_bounds(glyph_id.0)?
.into())
}
@ -221,11 +221,11 @@ impl MacTextSystemState {
}
fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
Ok(self.fonts[font_id.0].advance(glyph_id.into())?.into())
Ok(self.fonts[font_id.0].advance(glyph_id.0)?.into())
}
fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {
self.fonts[font_id.0].glyph_for_char(ch).map(Into::into)
self.fonts[font_id.0].glyph_for_char(ch).map(GlyphId)
}
fn id_for_native_font(&mut self, requested_font: CTFont) -> FontId {
@ -259,7 +259,7 @@ impl MacTextSystemState {
let scale = Transform2F::from_scale(params.scale_factor);
Ok(font
.raster_bounds(
params.glyph_id.into(),
params.glyph_id.0,
params.font_size.into(),
scale,
HintingOptions::None,
@ -334,7 +334,7 @@ impl MacTextSystemState {
.native_font()
.clone_with_font_size(f32::from(params.font_size) as CGFloat)
.draw_glyphs(
&[u32::from(params.glyph_id) as CGGlyph],
&[params.glyph_id.0 as CGGlyph],
&[CGPoint::new(
(subpixel_shift.x / params.scale_factor) as CGFloat,
(subpixel_shift.y / params.scale_factor) as CGFloat,
@ -419,7 +419,7 @@ impl MacTextSystemState {
let glyph_utf16_ix = usize::try_from(*glyph_utf16_ix).unwrap();
ix_converter.advance_to_utf16_ix(glyph_utf16_ix);
glyphs.push(ShapedGlyph {
id: (*glyph_id).into(),
id: GlyphId(*glyph_id as u32),
position: point(position.x as f32, position.y as f32).map(px),
index: ix_converter.utf8_ix,
is_emoji: self.is_emoji(font_id),
@ -651,7 +651,7 @@ mod lenient_font_attributes {
#[cfg(test)]
mod tests {
use crate::{font, px, FontRun, MacTextSystem, PlatformTextSystem};
use crate::{font, px, FontRun, GlyphId, MacTextSystem, PlatformTextSystem};
#[test]
fn test_wrap_line() {
@ -690,8 +690,8 @@ mod tests {
assert_eq!(layout.len, line.len());
assert_eq!(layout.runs.len(), 1);
assert_eq!(layout.runs[0].glyphs.len(), 2);
assert_eq!(layout.runs[0].glyphs[0].id, 68u32.into()); // a
// There's no glyph for \u{feff}
assert_eq!(layout.runs[0].glyphs[1].id, 69u32.into()); // b
assert_eq!(layout.runs[0].glyphs[0].id, GlyphId(68u32)); // a
// There's no glyph for \u{feff}
assert_eq!(layout.runs[0].glyphs[1].id, GlyphId(69u32)); // b
}
}

View file

@ -7,7 +7,7 @@ use crate::{
SizeRefinement, Styled, TextRun,
};
use collections::HashSet;
use refineable::{Cascade, Refineable};
use refineable::Refineable;
use smallvec::SmallVec;
pub use taffy::style::{
AlignContent, AlignItems, AlignSelf, Display, FlexDirection, FlexWrap, JustifyContent,
@ -15,10 +15,12 @@ pub use taffy::style::{
};
#[cfg(debug_assertions)]
/// Use this struct for interfacing with the 'debug_below' styling from your own elements.
/// If a parent element has this style set on it, then this struct will be set as a global in
/// GPUI.
pub struct DebugBelow;
pub type StyleCascade = Cascade<Style>;
/// The CSS styling that can be applied to an element via the `Styled` trait
#[derive(Clone, Refineable, Debug)]
#[refineable(Debug)]
pub struct Style {
@ -104,16 +106,20 @@ pub struct Style {
/// Box Shadow of the element
pub box_shadow: SmallVec<[BoxShadow; 2]>,
/// TEXT
/// The text style of this element
pub text: TextStyleRefinement,
/// The mouse cursor style shown when the mouse pointer is over an element.
pub mouse_cursor: Option<CursorStyle>,
/// The z-index to set for this element
pub z_index: Option<u16>,
/// Whether to draw a red debugging outline around this element
#[cfg(debug_assertions)]
pub debug: bool,
/// Whether to draw a red debugging outline around this element and all of it's conforming children
#[cfg(debug_assertions)]
pub debug_below: bool,
}
@ -124,40 +130,71 @@ impl Styled for StyleRefinement {
}
}
/// The value of the visibility property, similar to the CSS property `visibility`
#[derive(Default, Clone, Copy, Debug, Eq, PartialEq)]
pub enum Visibility {
/// The element should be drawn as normal.
#[default]
Visible,
/// The element should not be drawn, but should still take up space in the layout.
Hidden,
}
/// The possible values of the box-shadow property
#[derive(Clone, Debug)]
pub struct BoxShadow {
/// What color should the shadow have?
pub color: Hsla,
/// How should it be offset from it's element?
pub offset: Point<Pixels>,
/// How much should the shadow be blurred?
pub blur_radius: Pixels,
/// How much should the shadow spread?
pub spread_radius: Pixels,
}
/// How to handle whitespace in text
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub enum WhiteSpace {
/// Normal line wrapping when text overflows the width of the element
#[default]
Normal,
/// No line wrapping, text will overflow the width of the element
Nowrap,
}
/// The properties that can be used to style text in GPUI
#[derive(Refineable, Clone, Debug, PartialEq)]
#[refineable(Debug)]
pub struct TextStyle {
/// The color of the text
pub color: Hsla,
/// The font family to use
pub font_family: SharedString,
/// The font features to use
pub font_features: FontFeatures,
/// The font size to use, in pixels or rems.
pub font_size: AbsoluteLength,
/// The line height to use, in pixels or fractions
pub line_height: DefiniteLength,
/// The font weight, e.g. bold
pub font_weight: FontWeight,
/// The font style, e.g. italic
pub font_style: FontStyle,
/// The background color of the text
pub background_color: Option<Hsla>,
/// The underline style of the text
pub underline: Option<UnderlineStyle>,
/// How to handle whitespace in the text
pub white_space: WhiteSpace,
}
@ -180,6 +217,7 @@ impl Default for TextStyle {
}
impl TextStyle {
/// Create a new text style with the given highlighting applied.
pub fn highlight(mut self, style: impl Into<HighlightStyle>) -> Self {
let style = style.into();
if let Some(weight) = style.font_weight {
@ -208,6 +246,7 @@ impl TextStyle {
self
}
/// Get the font configured for this text style.
pub fn font(&self) -> Font {
Font {
family: self.font_family.clone(),
@ -222,6 +261,7 @@ impl TextStyle {
self.line_height.to_pixels(self.font_size, rem_size).round()
}
/// Convert this text style into a [`TextRun`], for the given length of the text.
pub fn to_run(&self, len: usize) -> TextRun {
TextRun {
len,
@ -238,19 +278,33 @@ impl TextStyle {
}
}
/// A highlight style to apply, similar to a `TextStyle` except
/// for a single font, uniformly sized and spaced text.
#[derive(Copy, Clone, Debug, Default, PartialEq)]
pub struct HighlightStyle {
/// The color of the text
pub color: Option<Hsla>,
/// The font weight, e.g. bold
pub font_weight: Option<FontWeight>,
/// The font style, e.g. italic
pub font_style: Option<FontStyle>,
/// The background color of the text
pub background_color: Option<Hsla>,
/// The underline style of the text
pub underline: Option<UnderlineStyle>,
/// Similar to the CSS `opacity` property, this will cause the text to be less vibrant.
pub fade_out: Option<f32>,
}
impl Eq for HighlightStyle {}
impl Style {
/// Get the text style in this element style.
pub fn text_style(&self) -> Option<&TextStyleRefinement> {
if self.text.is_some() {
Some(&self.text)
@ -259,6 +313,8 @@ impl Style {
}
}
/// Get the content mask for this element style, based on the given bounds.
/// If the element does not hide it's overflow, this will return `None`.
pub fn overflow_mask(
&self,
bounds: Bounds<Pixels>,
@ -480,20 +536,29 @@ impl Default for Style {
}
}
/// The properties that can be applied to an underline.
#[derive(Refineable, Copy, Clone, Default, Debug, PartialEq, Eq)]
#[refineable(Debug)]
pub struct UnderlineStyle {
/// The thickness of the underline.
pub thickness: Pixels,
/// The color of the underline.
pub color: Option<Hsla>,
/// Whether the underline should be wavy, like in a spell checker.
pub wavy: bool,
}
/// The kinds of fill that can be applied to a shape.
#[derive(Clone, Debug)]
pub enum Fill {
/// A solid color fill.
Color(Hsla),
}
impl Fill {
/// Unwrap this fill into a solid color, if it is one.
pub fn color(&self) -> Option<Hsla> {
match self {
Fill::Color(color) => Some(*color),
@ -539,6 +604,8 @@ impl From<&TextStyle> for HighlightStyle {
}
impl HighlightStyle {
/// Blend this highlight style with another.
/// Non-continuous properties, like font_weight and font_style, are overwritten.
pub fn highlight(&mut self, other: HighlightStyle) {
match (self.color, other.color) {
(Some(self_color), Some(other_color)) => {
@ -612,6 +679,7 @@ impl From<Rgba> for HighlightStyle {
}
}
/// Combine and merge the highlights and ranges in the two iterators.
pub fn combine_highlights(
a: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
b: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,

View file

@ -7,17 +7,21 @@ use crate::{BoxShadow, TextStyleRefinement};
use smallvec::{smallvec, SmallVec};
use taffy::style::{Display, Overflow};
/// A trait for elements that can be styled.
/// Use this to opt-in to a CSS-like styling API.
pub trait Styled: Sized {
/// Returns a reference to the style memory of this element.
fn style(&mut self) -> &mut StyleRefinement;
gpui_macros::style_helpers!();
/// Set the z-index of this element.
fn z_index(mut self, z_index: u16) -> Self {
self.style().z_index = Some(z_index);
self
}
/// Sets the size of the element to the full width and height.
/// Sets the size of the element to sthe full width and height.
fn full(mut self) -> Self {
self.style().size.width = Some(relative(1.).into());
self.style().size.height = Some(relative(1.).into());
@ -88,6 +92,7 @@ pub trait Styled: Sized {
self
}
/// Set the cursor style when hovering over this element
fn cursor(mut self, cursor: CursorStyle) -> Self {
self.style().mouse_cursor = Some(cursor);
self
@ -511,16 +516,19 @@ pub trait Styled: Sized {
self
}
/// Get the text style that has been configured on this element.
fn text_style(&mut self) -> &mut Option<TextStyleRefinement> {
let style: &mut StyleRefinement = self.style();
&mut style.text
}
/// Set the text color of this element, this value cascades to it's child elements.
fn text_color(mut self, color: impl Into<Hsla>) -> Self {
self.text_style().get_or_insert_with(Default::default).color = Some(color.into());
self
}
/// Set the font weight of this element, this value cascades to it's child elements.
fn font_weight(mut self, weight: FontWeight) -> Self {
self.text_style()
.get_or_insert_with(Default::default)
@ -528,6 +536,7 @@ pub trait Styled: Sized {
self
}
/// Set the background color of this element, this value cascades to it's child elements.
fn text_bg(mut self, bg: impl Into<Hsla>) -> Self {
self.text_style()
.get_or_insert_with(Default::default)
@ -535,6 +544,7 @@ pub trait Styled: Sized {
self
}
/// Set the text size of this element, this value cascades to it's child elements.
fn text_size(mut self, size: impl Into<AbsoluteLength>) -> Self {
self.text_style()
.get_or_insert_with(Default::default)
@ -542,6 +552,8 @@ pub trait Styled: Sized {
self
}
/// Set the text size to 'extra small',
/// see the [Tailwind Docs](https://tailwindcss.com/docs/font-size#setting-the-font-size)
fn text_xs(mut self) -> Self {
self.text_style()
.get_or_insert_with(Default::default)
@ -549,6 +561,8 @@ pub trait Styled: Sized {
self
}
/// Set the text size to 'small',
/// see the [Tailwind Docs](https://tailwindcss.com/docs/font-size#setting-the-font-size)
fn text_sm(mut self) -> Self {
self.text_style()
.get_or_insert_with(Default::default)
@ -556,6 +570,7 @@ pub trait Styled: Sized {
self
}
/// Reset the text styling for this element and it's children.
fn text_base(mut self) -> Self {
self.text_style()
.get_or_insert_with(Default::default)
@ -563,6 +578,8 @@ pub trait Styled: Sized {
self
}
/// Set the text size to 'large',
/// see the [Tailwind Docs](https://tailwindcss.com/docs/font-size#setting-the-font-size)
fn text_lg(mut self) -> Self {
self.text_style()
.get_or_insert_with(Default::default)
@ -570,6 +587,8 @@ pub trait Styled: Sized {
self
}
/// Set the text size to 'extra large',
/// see the [Tailwind Docs](https://tailwindcss.com/docs/font-size#setting-the-font-size)
fn text_xl(mut self) -> Self {
self.text_style()
.get_or_insert_with(Default::default)
@ -577,6 +596,8 @@ pub trait Styled: Sized {
self
}
/// Set the text size to 'extra-extra large',
/// see the [Tailwind Docs](https://tailwindcss.com/docs/font-size#setting-the-font-size)
fn text_2xl(mut self) -> Self {
self.text_style()
.get_or_insert_with(Default::default)
@ -584,6 +605,8 @@ pub trait Styled: Sized {
self
}
/// Set the text size to 'extra-extra-extra large',
/// see the [Tailwind Docs](https://tailwindcss.com/docs/font-size#setting-the-font-size)
fn text_3xl(mut self) -> Self {
self.text_style()
.get_or_insert_with(Default::default)
@ -591,6 +614,7 @@ pub trait Styled: Sized {
self
}
/// Remove the text decoration on this element, this value cascades to it's child elements.
fn text_decoration_none(mut self) -> Self {
self.text_style()
.get_or_insert_with(Default::default)
@ -598,6 +622,7 @@ pub trait Styled: Sized {
self
}
/// Set the color for the underline on this element
fn text_decoration_color(mut self, color: impl Into<Hsla>) -> Self {
let style = self.text_style().get_or_insert_with(Default::default);
let underline = style.underline.get_or_insert_with(Default::default);
@ -605,6 +630,7 @@ pub trait Styled: Sized {
self
}
/// Set the underline to a solid line
fn text_decoration_solid(mut self) -> Self {
let style = self.text_style().get_or_insert_with(Default::default);
let underline = style.underline.get_or_insert_with(Default::default);
@ -612,6 +638,7 @@ pub trait Styled: Sized {
self
}
/// Set the underline to a wavy line
fn text_decoration_wavy(mut self) -> Self {
let style = self.text_style().get_or_insert_with(Default::default);
let underline = style.underline.get_or_insert_with(Default::default);
@ -619,6 +646,7 @@ pub trait Styled: Sized {
self
}
/// Set the underline to be 0 thickness, see the [Tailwind Docs](https://tailwindcss.com/docs/text-decoration-thickness)
fn text_decoration_0(mut self) -> Self {
let style = self.text_style().get_or_insert_with(Default::default);
let underline = style.underline.get_or_insert_with(Default::default);
@ -626,6 +654,7 @@ pub trait Styled: Sized {
self
}
/// Set the underline to be 1px thick, see the [Tailwind Docs](https://tailwindcss.com/docs/text-decoration-thickness)
fn text_decoration_1(mut self) -> Self {
let style = self.text_style().get_or_insert_with(Default::default);
let underline = style.underline.get_or_insert_with(Default::default);
@ -633,6 +662,7 @@ pub trait Styled: Sized {
self
}
/// Set the underline to be 2px thick, see the [Tailwind Docs](https://tailwindcss.com/docs/text-decoration-thickness)
fn text_decoration_2(mut self) -> Self {
let style = self.text_style().get_or_insert_with(Default::default);
let underline = style.underline.get_or_insert_with(Default::default);
@ -640,6 +670,7 @@ pub trait Styled: Sized {
self
}
/// Set the underline to be 4px thick, see the [Tailwind Docs](https://tailwindcss.com/docs/text-decoration-thickness)
fn text_decoration_4(mut self) -> Self {
let style = self.text_style().get_or_insert_with(Default::default);
let underline = style.underline.get_or_insert_with(Default::default);
@ -647,6 +678,7 @@ pub trait Styled: Sized {
self
}
/// Set the underline to be 8px thick, see the [Tailwind Docs](https://tailwindcss.com/docs/text-decoration-thickness)
fn text_decoration_8(mut self) -> Self {
let style = self.text_style().get_or_insert_with(Default::default);
let underline = style.underline.get_or_insert_with(Default::default);
@ -654,6 +686,7 @@ pub trait Styled: Sized {
self
}
/// Change the font on this element and it's children.
fn font(mut self, family_name: impl Into<SharedString>) -> Self {
self.text_style()
.get_or_insert_with(Default::default)
@ -661,6 +694,7 @@ pub trait Styled: Sized {
self
}
/// Set the line height on this element and it's children.
fn line_height(mut self, line_height: impl Into<DefiniteLength>) -> Self {
self.text_style()
.get_or_insert_with(Default::default)
@ -668,12 +702,14 @@ pub trait Styled: Sized {
self
}
/// Draw a debug border around this element.
#[cfg(debug_assertions)]
fn debug(mut self) -> Self {
self.style().debug = Some(true);
self
}
/// Draw a debug border on all conforming elements below this element.
#[cfg(debug_assertions)]
fn debug_below(mut self) -> Self {
self.style().debug_below = Some(true);

View file

@ -41,7 +41,6 @@ where
/// are inert, meaning that they won't be listed when calling `[SubscriberSet::remove]` or `[SubscriberSet::retain]`.
/// This method returns a tuple of a [`Subscription`] and an `impl FnOnce`, and you can use the latter
/// to activate the [`Subscription`].
#[must_use]
pub fn insert(
&self,
emitter_key: EmitterKey,

View file

@ -12,22 +12,16 @@ use taffy::{
Taffy,
};
type NodeMeasureFn =
Box<dyn FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut WindowContext) -> Size<Pixels>>;
pub struct TaffyLayoutEngine {
taffy: Taffy,
styles: FxHashMap<LayoutId, Style>,
children_to_parents: FxHashMap<LayoutId, LayoutId>,
absolute_layout_bounds: FxHashMap<LayoutId, Bounds<Pixels>>,
computed_layouts: FxHashSet<LayoutId>,
nodes_to_measure: FxHashMap<
LayoutId,
Box<
dyn FnMut(
Size<Option<Pixels>>,
Size<AvailableSpace>,
&mut WindowContext,
) -> Size<Pixels>,
>,
>,
nodes_to_measure: FxHashMap<LayoutId, NodeMeasureFn>,
}
static EXPECT_MESSAGE: &str = "we should avoid taffy layout errors by construction if possible";

View file

@ -26,15 +26,18 @@ use std::{
sync::Arc,
};
/// An opaque identifier for a specific font.
#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug)]
#[repr(C)]
pub struct FontId(pub usize);
/// An opaque identifier for a specific font family.
#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug)]
pub struct FontFamilyId(pub usize);
pub(crate) const SUBPIXEL_VARIANTS: u8 = 4;
/// The GPUI text layout and rendering sub system.
pub struct TextSystem {
line_layout_cache: Arc<LineLayoutCache>,
platform_text_system: Arc<dyn PlatformTextSystem>,
@ -65,13 +68,14 @@ impl TextSystem {
}
}
/// Get a list of all available font names from the operating system.
pub fn all_font_names(&self) -> Vec<String> {
let mut names: BTreeSet<_> = self
.platform_text_system
.all_font_names()
.into_iter()
.collect();
names.extend(self.platform_text_system.all_font_families().into_iter());
names.extend(self.platform_text_system.all_font_families());
names.extend(
self.fallback_font_stack
.iter()
@ -79,10 +83,13 @@ impl TextSystem {
);
names.into_iter().collect()
}
/// Add a font's data to the text system.
pub fn add_fonts(&self, fonts: &[Arc<Vec<u8>>]) -> Result<()> {
self.platform_text_system.add_fonts(fonts)
}
/// Get the FontId for the configure font family and style.
pub fn font_id(&self, font: &Font) -> Result<FontId> {
let font_id = self.font_ids_by_font.read().get(font).copied();
if let Some(font_id) = font_id {
@ -120,10 +127,14 @@ impl TextSystem {
);
}
/// Get the bounding box for the given font and font size.
/// A font's bounding box is the smallest rectangle that could enclose all glyphs
/// in the font. superimposed over one another.
pub fn bounding_box(&self, font_id: FontId, font_size: Pixels) -> Bounds<Pixels> {
self.read_metrics(font_id, |metrics| metrics.bounding_box(font_size))
}
/// Get the typographic bounds for the given character, in the given font and size.
pub fn typographic_bounds(
&self,
font_id: FontId,
@ -142,6 +153,7 @@ impl TextSystem {
}))
}
/// Get the advance width for the given character, in the given font and size.
pub fn advance(&self, font_id: FontId, font_size: Pixels, ch: char) -> Result<Size<Pixels>> {
let glyph_id = self
.platform_text_system
@ -153,26 +165,35 @@ impl TextSystem {
Ok(result * font_size)
}
/// Get the number of font size units per 'em square',
/// Per MDN: "an abstract square whose height is the intended distance between
/// lines of type in the same type size"
pub fn units_per_em(&self, font_id: FontId) -> u32 {
self.read_metrics(font_id, |metrics| metrics.units_per_em)
}
/// Get the height of a capital letter in the given font and size.
pub fn cap_height(&self, font_id: FontId, font_size: Pixels) -> Pixels {
self.read_metrics(font_id, |metrics| metrics.cap_height(font_size))
}
/// Get the height of the x character in the given font and size.
pub fn x_height(&self, font_id: FontId, font_size: Pixels) -> Pixels {
self.read_metrics(font_id, |metrics| metrics.x_height(font_size))
}
/// Get the recommended distance from the baseline for the given font
pub fn ascent(&self, font_id: FontId, font_size: Pixels) -> Pixels {
self.read_metrics(font_id, |metrics| metrics.ascent(font_size))
}
/// Get the recommended distance below the baseline for the given font,
/// in single spaced text.
pub fn descent(&self, font_id: FontId, font_size: Pixels) -> Pixels {
self.read_metrics(font_id, |metrics| metrics.descent(font_size))
}
/// Get the recommended baseline offset for the given font and line height.
pub fn baseline_offset(
&self,
font_id: FontId,
@ -199,10 +220,14 @@ impl TextSystem {
}
}
pub fn with_view<R>(&self, view_id: EntityId, f: impl FnOnce() -> R) -> R {
pub(crate) fn with_view<R>(&self, view_id: EntityId, f: impl FnOnce() -> R) -> R {
self.line_layout_cache.with_view(view_id, f)
}
/// Layout the given line of text, at the given font_size.
/// Subsets of the line can be styled independently with the `runs` parameter.
/// Generally, you should prefer to use `TextLayout::shape_line` instead, which
/// can be painted directly.
pub fn layout_line(
&self,
text: &str,
@ -234,6 +259,12 @@ impl TextSystem {
Ok(layout)
}
/// Shape the given line, at the given font_size, for painting to the screen.
/// Subsets of the line can be styled independently with the `runs` parameter.
///
/// Note that this method can only shape a single line of text. It will panic
/// if the text contains newlines. If you need to shape multiple lines of text,
/// use `TextLayout::shape_text` instead.
pub fn shape_line(
&self,
text: SharedString,
@ -273,6 +304,9 @@ impl TextSystem {
})
}
/// Shape a multi line string of text, at the given font_size, for painting to the screen.
/// Subsets of the text can be styled independently with the `runs` parameter.
/// If `wrap_width` is provided, the line breaks will be adjusted to fit within the given width.
pub fn shape_text(
&self,
text: SharedString,
@ -381,6 +415,7 @@ impl TextSystem {
self.line_layout_cache.finish_frame(reused_views)
}
/// Returns a handle to a line wrapper, for the given font and font size.
pub fn line_wrapper(self: &Arc<Self>, font: Font, font_size: Pixels) -> LineWrapperHandle {
let lock = &mut self.wrapper_pool.lock();
let font_id = self.resolve_font(&font);
@ -397,7 +432,8 @@ impl TextSystem {
}
}
pub fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
/// Get the rasterized size and location of a specific, rendered glyph.
pub(crate) 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)
@ -409,7 +445,7 @@ impl TextSystem {
}
}
pub fn rasterize_glyph(
pub(crate) fn rasterize_glyph(
&self,
params: &RenderGlyphParams,
) -> Result<(Size<DevicePixels>, Vec<u8>)> {
@ -425,6 +461,7 @@ struct FontIdWithSize {
font_size: Pixels,
}
/// A handle into the text system, which can be used to compute the wrapped layout of text
pub struct LineWrapperHandle {
wrapper: Option<LineWrapper>,
text_system: Arc<TextSystem>,
@ -517,40 +554,28 @@ impl Display for FontStyle {
}
}
/// A styled run of text, for use in [`TextLayout`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TextRun {
// number of utf8 bytes
/// A number of utf8 bytes
pub len: usize,
/// The font to use for this run.
pub font: Font,
/// The color
pub color: Hsla,
/// The background color (if any)
pub background_color: Option<Hsla>,
/// The underline style (if any)
pub underline: Option<UnderlineStyle>,
}
/// An identifier for a specific glyph, as returned by [`TextSystem::layout_line`].
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
#[repr(C)]
pub struct GlyphId(u32);
impl From<GlyphId> for u32 {
fn from(value: GlyphId) -> Self {
value.0
}
}
impl From<u16> for GlyphId {
fn from(num: u16) -> Self {
GlyphId(num as u32)
}
}
impl From<u32> for GlyphId {
fn from(num: u32) -> Self {
GlyphId(num)
}
}
pub struct GlyphId(pub(crate) u32);
#[derive(Clone, Debug, PartialEq)]
pub struct RenderGlyphParams {
pub(crate) struct RenderGlyphParams {
pub(crate) font_id: FontId,
pub(crate) glyph_id: GlyphId,
pub(crate) font_size: Pixels,
@ -571,6 +596,7 @@ impl Hash for RenderGlyphParams {
}
}
/// The parameters for rendering an emoji glyph.
#[derive(Clone, Debug, PartialEq)]
pub struct RenderEmojiParams {
pub(crate) font_id: FontId,
@ -590,14 +616,23 @@ impl Hash for RenderEmojiParams {
}
}
/// The configuration details for identifying a specific font.
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct Font {
/// The font family name.
pub family: SharedString,
/// The font features to use.
pub features: FontFeatures,
/// The font weight.
pub weight: FontWeight,
/// The font style.
pub style: FontStyle,
}
/// Get a [`Font`] for a given name.
pub fn font(family: impl Into<SharedString>) -> Font {
Font {
family: family.into(),
@ -608,10 +643,17 @@ pub fn font(family: impl Into<SharedString>) -> Font {
}
impl Font {
/// Set this Font to be bold
pub fn bold(mut self) -> Self {
self.weight = FontWeight::BOLD;
self
}
/// Set this Font to be italic
pub fn italic(mut self) -> Self {
self.style = FontStyle::Italic;
self
}
}
/// A struct for storing font metrics.

View file

@ -5,6 +5,8 @@ use schemars::{
macro_rules! create_definitions {
($($(#[$meta:meta])* ($name:ident, $idx:expr)),* $(,)?) => {
/// The OpenType features that can be configured for a given font.
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash)]
pub struct FontFeatures {
enabled: u64,
@ -13,6 +15,7 @@ macro_rules! create_definitions {
impl FontFeatures {
$(
/// Get the current value of the corresponding OpenType feature
pub fn $name(&self) -> Option<bool> {
if (self.enabled & (1 << $idx)) != 0 {
Some(true)

View file

@ -6,29 +6,41 @@ use derive_more::{Deref, DerefMut};
use smallvec::SmallVec;
use std::sync::Arc;
/// Set the text decoration for a run of text.
#[derive(Debug, Clone)]
pub struct DecorationRun {
/// The length of the run in utf-8 bytes.
pub len: u32,
/// The color for this run
pub color: Hsla,
/// The background color for this run
pub background_color: Option<Hsla>,
/// The underline style for this run
pub underline: Option<UnderlineStyle>,
}
/// A line of text that has been shaped and decorated.
#[derive(Clone, Default, Debug, Deref, DerefMut)]
pub struct ShapedLine {
#[deref]
#[deref_mut]
pub(crate) layout: Arc<LineLayout>,
/// The text that was shaped for this line.
pub text: SharedString,
pub(crate) decoration_runs: SmallVec<[DecorationRun; 32]>,
}
impl ShapedLine {
/// The length of the line in utf-8 bytes.
#[allow(clippy::len_without_is_empty)]
pub fn len(&self) -> usize {
self.layout.len
}
/// Paint the line of text to the window.
pub fn paint(
&self,
origin: Point<Pixels>,
@ -48,20 +60,25 @@ impl ShapedLine {
}
}
/// A line of text that has been shaped, decorated, and wrapped by the text layout system.
#[derive(Clone, Default, Debug, Deref, DerefMut)]
pub struct WrappedLine {
#[deref]
#[deref_mut]
pub(crate) layout: Arc<WrappedLineLayout>,
/// The text that was shaped for this line.
pub text: SharedString,
pub(crate) decoration_runs: SmallVec<[DecorationRun; 32]>,
}
impl WrappedLine {
/// The length of the underlying, unwrapped layout, in utf-8 bytes.
#[allow(clippy::len_without_is_empty)]
pub fn len(&self) -> usize {
self.layout.len()
}
/// Paint this line of text to the window.
pub fn paint(
&self,
origin: Point<Pixels>,

View file

@ -8,31 +8,50 @@ use std::{
sync::Arc,
};
/// A laid out and styled line of text
#[derive(Default, Debug)]
pub struct LineLayout {
/// The font size for this line
pub font_size: Pixels,
/// The width of the line
pub width: Pixels,
/// The ascent of the line
pub ascent: Pixels,
/// The descent of the line
pub descent: Pixels,
/// The shaped runs that make up this line
pub runs: Vec<ShapedRun>,
/// The length of the line in utf-8 bytes
pub len: usize,
}
/// A run of text that has been shaped .
#[derive(Debug)]
pub struct ShapedRun {
/// The font id for this run
pub font_id: FontId,
/// The glyphs that make up this run
pub glyphs: SmallVec<[ShapedGlyph; 8]>,
}
/// A single glyph, ready to paint.
#[derive(Clone, Debug)]
pub struct ShapedGlyph {
/// The ID for this glyph, as determined by the text system.
pub id: GlyphId,
/// The position of this glyph in it's containing line.
pub position: Point<Pixels>,
/// The index of this glyph in the original text.
pub index: usize,
/// Whether this glyph is an emoji
pub is_emoji: bool,
}
impl LineLayout {
/// The index for the character at the given x coordinate
pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
if x >= self.width {
None
@ -71,6 +90,7 @@ impl LineLayout {
self.len
}
/// The x position of the character at the given index
pub fn x_for_index(&self, index: usize) -> Pixels {
for run in &self.runs {
for glyph in &run.glyphs {
@ -148,30 +168,44 @@ impl LineLayout {
}
}
/// A line of text that has been wrapped to fit a given width
#[derive(Default, Debug)]
pub struct WrappedLineLayout {
/// The line layout, pre-wrapping.
pub unwrapped_layout: Arc<LineLayout>,
/// The boundaries at which the line was wrapped
pub wrap_boundaries: SmallVec<[WrapBoundary; 1]>,
/// The width of the line, if it was wrapped
pub wrap_width: Option<Pixels>,
}
/// A boundary at which a line was wrapped
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct WrapBoundary {
/// The index in the run just before the line was wrapped
pub run_ix: usize,
/// The index of the glyph just before the line was wrapped
pub glyph_ix: usize,
}
impl WrappedLineLayout {
/// The length of the underlying text, in utf8 bytes.
#[allow(clippy::len_without_is_empty)]
pub fn len(&self) -> usize {
self.unwrapped_layout.len
}
/// The width of this line, in pixels, whether or not it was wrapped.
pub fn width(&self) -> Pixels {
self.wrap_width
.unwrap_or(Pixels::MAX)
.min(self.unwrapped_layout.width)
}
/// The size of the whole wrapped text, for the given line_height.
/// can span multiple lines if there are multiple wrap boundaries.
pub fn size(&self, line_height: Pixels) -> Size<Pixels> {
Size {
width: self.width(),
@ -179,26 +213,32 @@ impl WrappedLineLayout {
}
}
/// The ascent of a line in this layout
pub fn ascent(&self) -> Pixels {
self.unwrapped_layout.ascent
}
/// The descent of a line in this layout
pub fn descent(&self) -> Pixels {
self.unwrapped_layout.descent
}
/// The wrap boundaries in this layout
pub fn wrap_boundaries(&self) -> &[WrapBoundary] {
&self.wrap_boundaries
}
/// The font size of this layout
pub fn font_size(&self) -> Pixels {
self.unwrapped_layout.font_size
}
/// The runs in this layout, sans wrapping
pub fn runs(&self) -> &[ShapedRun] {
&self.unwrapped_layout.runs
}
/// The index corresponding to a given position in this layout for the given line height.
pub fn index_for_position(
&self,
position: Point<Pixels>,
@ -376,6 +416,7 @@ impl LineLayoutCache {
}
}
/// A run of text with a single font.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub struct FontRun {
pub(crate) len: usize,

View file

@ -2,6 +2,7 @@ use crate::{px, FontId, FontRun, Pixels, PlatformTextSystem};
use collections::HashMap;
use std::{iter, sync::Arc};
/// The GPUI line wrapper, used to wrap lines of text to a given width.
pub struct LineWrapper {
platform_text_system: Arc<dyn PlatformTextSystem>,
pub(crate) font_id: FontId,
@ -11,6 +12,7 @@ pub struct LineWrapper {
}
impl LineWrapper {
/// The maximum indent that can be applied to a line.
pub const MAX_INDENT: u32 = 256;
pub(crate) fn new(
@ -27,6 +29,7 @@ impl LineWrapper {
}
}
/// Wrap a line of text to the given width with this wrapper's font and font size.
pub fn wrap_line<'a>(
&'a mut self,
line: &'a str,
@ -122,9 +125,12 @@ impl LineWrapper {
}
}
/// A boundary between two lines of text.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Boundary {
/// The index of the last character in a line
pub ix: usize,
/// The indent of the next line.
pub next_indent: u32,
}

View file

@ -1257,7 +1257,7 @@ impl<'a> WindowContext<'a> {
} else if let Some(currently_pending) = self.window.pending_input.take() {
if bindings
.iter()
.all(|binding| !currently_pending.used_by_binding(&binding))
.all(|binding| !currently_pending.used_by_binding(binding))
{
self.replay_pending_input(currently_pending)
}
@ -2560,7 +2560,7 @@ impl Display for ElementId {
ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
ElementId::Integer(ix) => write!(f, "{}", ix)?,
ElementId::Name(name) => write!(f, "{}", name)?,
ElementId::FocusHandle(__) => write!(f, "FocusHandle")?,
ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
}

View file

@ -1,3 +1,17 @@
//! The element context is the main interface for interacting with the frame during a paint.
//!
//! Elements are hierarchical and with a few exceptions the context accumulates state in a stack
//! as it processes all of the elements in the frame. The methods that interact with this stack
//! are generally marked with `with_*`, and take a callback to denote the region of code that
//! should be executed with that state.
//!
//! The other main interface is the `paint_*` family of methods, which push basic drawing commands
//! to the GPU. Everything in a GPUI app is drawn with these methods.
//!
//! There are also several internal methods that GPUI uses, such as [`ElementContext::with_element_state`]
//! to call the paint and layout methods on elements. These have been included as they're often useful
//! for taking manual control of the layouting or painting of specialized elements.
use std::{
any::{Any, TypeId},
borrow::{Borrow, BorrowMut, Cow},
@ -153,6 +167,9 @@ pub struct ElementContext<'a> {
}
impl<'a> WindowContext<'a> {
/// Convert this window context into an ElementContext in this callback.
/// If you need to use this method, you're probably intermixing the imperative
/// and declarative APIs, which is not recommended.
pub fn with_element_context<R>(&mut self, f: impl FnOnce(&mut ElementContext) -> R) -> R {
f(&mut ElementContext {
cx: WindowContext::new(self.app, self.window),
@ -338,6 +355,8 @@ impl<'a> ElementContext<'a> {
self.window.next_frame.next_stacking_order_id = next_stacking_order_id;
}
/// Push a text style onto the stack, and call a function with that style active.
/// Use [`AppContext::text_style`] to get the current, combined text style.
pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
where
F: FnOnce(&mut Self) -> R,
@ -714,6 +733,8 @@ impl<'a> ElementContext<'a> {
/// Paint a monochrome (non-emoji) glyph into the scene for the next frame at the current z-index.
/// The y component of the origin is the baseline of the glyph.
/// You should generally prefer to use the [`ShapedLine::paint`] or [`WrappedLine::paint`] methods in the [`text_system`].
/// This method is only useful if you need to paint a single glyph that has already been shaped.
pub fn paint_glyph(
&mut self,
origin: Point<Pixels>,
@ -771,6 +792,8 @@ impl<'a> ElementContext<'a> {
/// Paint an emoji glyph into the scene for the next frame at the current z-index.
/// The y component of the origin is the baseline of the glyph.
/// You should generally prefer to use the [`ShapedLine::paint`] or [`WrappedLine::paint`] methods in the [`text_system`].
/// This method is only useful if you need to paint a single emoji that has already been shaped.
pub fn paint_emoji(
&mut self,
origin: Point<Pixels>,
@ -979,9 +1002,8 @@ impl<'a> ElementContext<'a> {
self.window.layout_engine = Some(layout_engine);
}
/// Obtain the bounds computed for the given LayoutId relative to the window. This method should not
/// be invoked until the paint phase begins, and will usually be invoked by GPUI itself automatically
/// in order to pass your element its `Bounds` automatically.
/// Obtain the bounds computed for the given LayoutId relative to the window. This method will usually be invoked by
/// GPUI itself automatically in order to pass your element its `Bounds` automatically.
pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
let mut bounds = self
.window
@ -1040,7 +1062,7 @@ impl<'a> ElementContext<'a> {
let text_system = self.text_system().clone();
text_system.with_view(view_id, || {
if self.window.next_frame.view_stack.last() == Some(&view_id) {
return f(self);
f(self)
} else {
self.window.next_frame.view_stack.push(view_id);
let result = f(self);
@ -1056,7 +1078,7 @@ impl<'a> ElementContext<'a> {
let text_system = self.text_system().clone();
text_system.with_view(view_id, || {
if self.window.next_frame.view_stack.last() == Some(&view_id) {
return f(self);
f(self)
} else {
self.window.next_frame.view_stack.push(view_id);
self.window

View file

@ -108,6 +108,9 @@ pub mod core_video {
impl_CFTypeDescription!(CVMetalTextureCache);
impl CVMetalTextureCache {
/// # Safety
///
/// metal_device must be valid according to CVMetalTextureCacheCreate
pub unsafe fn new(metal_device: *mut MTLDevice) -> Result<Self> {
let mut this = ptr::null();
let result = CVMetalTextureCacheCreate(
@ -124,6 +127,9 @@ pub mod core_video {
}
}
/// # Safety
///
/// The arguments to this function must be valid according to CVMetalTextureCacheCreateTextureFromImage
pub unsafe fn create_texture_from_image(
&self,
source: CVImageBufferRef,
@ -434,6 +440,12 @@ pub mod video_toolbox {
impl_CFTypeDescription!(VTCompressionSession);
impl VTCompressionSession {
/// Create a new compression session.
///
/// # Safety
///
/// The callback must be a valid function pointer. and the callback_data must be valid
/// in whatever terms that callback expects.
pub unsafe fn new(
width: usize,
height: usize,
@ -465,6 +477,9 @@ pub mod video_toolbox {
}
}
/// # Safety
///
/// The arguments to this function must be valid according to VTCompressionSessionEncodeFrame
pub unsafe fn encode_frame(
&self,
buffer: CVImageBufferRef,

View file

@ -245,10 +245,14 @@ pub fn derive_refineable(input: TokenStream) -> TokenStream {
}
let gen = quote! {
/// A refinable version of [`#ident`], see that documentation for details.
#[derive(Clone)]
#derive_stream
pub struct #refinement_ident #impl_generics {
#( #field_visibilities #field_names: #wrapped_types ),*
#(
#[allow(missing_docs)]
#field_visibilities #field_names: #wrapped_types
),*
}
impl #impl_generics Refineable for #ident #ty_generics
@ -304,6 +308,7 @@ pub fn derive_refineable(input: TokenStream) -> TokenStream {
impl #impl_generics #refinement_ident #ty_generics
#where_clause
{
/// Returns `true` if all fields are `Some`
pub fn is_some(&self) -> bool {
#(
if self.#field_names.is_some() {