diff --git a/crates/gpui/src/platform/mac/text_system.rs b/crates/gpui/src/platform/mac/text_system.rs index 21fe3c70a8..138a465775 100644 --- a/crates/gpui/src/platform/mac/text_system.rs +++ b/crates/gpui/src/platform/mac/text_system.rs @@ -143,7 +143,7 @@ impl PlatformTextSystem for MacTextSystem { fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result> { Ok(self.0.read().fonts[font_id.0] - .typographic_bounds(glyph_id.into())? + .typographic_bounds(glyph_id.0)? .into()) } @@ -221,11 +221,13 @@ impl MacTextSystemState { } fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result> { - 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 { - self.fonts[font_id.0].glyph_for_char(ch).map(Into::into) + self.fonts[font_id.0] + .glyph_for_char(ch) + .map(|glyph_id| GlyphId(glyph_id)) } fn id_for_native_font(&mut self, requested_font: CTFont) -> FontId { @@ -259,7 +261,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 +336,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 +421,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), diff --git a/crates/gpui/src/text_system.rs b/crates/gpui/src/text_system.rs index 1d097ca1ee..9662247e6f 100644 --- a/crates/gpui/src/text_system.rs +++ b/crates/gpui/src/text_system.rs @@ -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, platform_text_system: Arc, @@ -65,6 +68,7 @@ impl TextSystem { } } + /// Get a list of all available font names from the operating system. pub fn all_font_names(&self) -> Vec { let mut names: BTreeSet<_> = self .platform_text_system @@ -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>]) -> 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 { 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 { 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> { 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 captial 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(&self, view_id: EntityId, f: impl FnOnce() -> R) -> R { + pub(crate) fn with_view(&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, 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> { + /// Get the rasterized size and location of a specific, rendered glyph. + pub(crate) 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) @@ -409,7 +445,7 @@ impl TextSystem { } } - pub fn rasterize_glyph( + pub(crate) fn rasterize_glyph( &self, params: &RenderGlyphParams, ) -> Result<(Size, Vec)> { @@ -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, text_system: Arc, @@ -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, + /// The underline style (if any) pub underline: Option, } +/// 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 for u32 { - fn from(value: GlyphId) -> Self { - value.0 - } -} - -impl From for GlyphId { - fn from(num: u16) -> Self { - GlyphId(num as u32) - } -} - -impl From 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) -> Font { Font { family: family.into(), @@ -608,10 +643,17 @@ pub fn font(family: impl Into) -> 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. diff --git a/crates/gpui/src/text_system/font_features.rs b/crates/gpui/src/text_system/font_features.rs index ce93fd5bc9..1824932328 100644 --- a/crates/gpui/src/text_system/font_features.rs +++ b/crates/gpui/src/text_system/font_features.rs @@ -4,7 +4,9 @@ use schemars::{ }; macro_rules! create_definitions { - ($($(#[$meta:meta])* ($name:ident, $idx:expr)),* $(,)?) => { + ($($(#[$meta:meta])* ($name:ident, $idx:expr), ($comment:tt)),* $(,)?) => { + + /// The font 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 { $( + /// $comment pub fn $name(&self) -> Option { if (self.enabled & (1 << $idx)) != 0 { Some(true) @@ -125,7 +128,7 @@ macro_rules! create_definitions { } create_definitions!( - (calt, 0), + (calt, 0, CALT), (case, 1), (cpsp, 2), (frac, 3), diff --git a/crates/gpui/src/window/element_cx.rs b/crates/gpui/src/window/element_cx.rs index 132cc72a5c..c48374529e 100644 --- a/crates/gpui/src/window/element_cx.rs +++ b/crates/gpui/src/window/element_cx.rs @@ -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 methds 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(&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(&mut self, style: Option, f: F) -> R where F: FnOnce(&mut Self) -> R, @@ -979,9 +998,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 { let mut bounds = self .window diff --git a/crates/refineable/derive_refineable/src/derive_refineable.rs b/crates/refineable/derive_refineable/src/derive_refineable.rs index bc906daece..294738b20e 100644 --- a/crates/refineable/derive_refineable/src/derive_refineable.rs +++ b/crates/refineable/derive_refineable/src/derive_refineable.rs @@ -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() {