Skip to main content

cosmic_text/
lib.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//
3// This is a Martensite fork of cosmic-text. Upstream code style is preserved.
4//
5// This crate inherits workspace lints but overrides the following rules
6// because it is a vendored upstream fork whose code we do not own:
7// - `unsafe_code`: upstream uses `unsafe` for fontdb face data sharing.
8// - `missing_docs`: upstream does not document every public item.
9// - `clippy::all`: upstream code style differs from workspace conventions.
10// - `rustdoc::broken_intra_doc_links`: upstream links don't resolve in fork context.
11#![allow(unsafe_code)]
12#![allow(missing_docs)]
13#![allow(clippy::all)]
14#![allow(rustdoc::broken_intra_doc_links)]
15
16//! # COSMIC Text
17//!
18//! This library provides advanced text handling in a generic way. It provides abstractions for
19//! shaping, font discovery, font fallback, layout, rasterization, and editing. Shaping utilizes
20//! harfrust, font discovery utilizes fontdb, and the rasterization is optional and utilizes
21//! swash. The other features are developed internal to this library.
22//!
23//! It is recommended that you start by creating a [`FontSystem`], after which you can create a
24//! [`Buffer`], provide it with some text, and then inspect the layout it produces. At this
25//! point, you can use the `SwashCache` to rasterize glyphs into either images or pixels.
26//!
27//! ```
28//! use cosmic_text::{Attrs, Color, FontSystem, SwashCache, Buffer, Metrics, Shaping};
29//!
30//! // A FontSystem provides access to detected system fonts, create one per application
31//! let mut font_system = FontSystem::new();
32//!
33//! // A SwashCache stores rasterized glyphs, create one per application
34//! let mut swash_cache = SwashCache::new();
35//!
36//! // Text metrics indicate the font size and line height of a buffer
37//! let metrics = Metrics::new(14.0, 20.0);
38//!
39//! // A Buffer provides shaping and layout for a UTF-8 string, create one per text widget
40//! let mut buffer = Buffer::new(&mut font_system, metrics);
41//!
42//! // Borrow buffer together with the font system for more convenient method calls
43//! let mut buffer = buffer.borrow_with(&mut font_system);
44//!
45//! // Attributes indicate what font to choose
46//! let attrs = Attrs::new();
47//!
48//! // Set size and text
49//! buffer.set_size(Some(80.0), Some(25.0));
50//! buffer.set_text("Hello, Rust! 🦀\n", &attrs, Shaping::Advanced, None);
51//!
52//! // Inspect the output runs
53//! for run in buffer.layout_runs() {
54//!     for glyph in run.glyphs.iter() {
55//!         println!("{:#?}", glyph);
56//!     }
57//! }
58//!
59//! // Create a default text color
60//! let text_color = Color::rgb(0xFF, 0xFF, 0xFF);
61//!
62//! // Draw the buffer (for performance, instead use SwashCache directly)
63//! buffer.draw(&mut swash_cache, text_color, |x, y, w, h, color| {
64//!     // Fill in your code here for drawing rectangles
65//! });
66//! ```
67
68// Not interested in these lints
69#![allow(clippy::new_without_default)]
70// TODO: address occurrences and then deny
71//
72// Overflows can produce unpredictable results and are only checked in debug builds
73#![allow(clippy::arithmetic_side_effects)]
74// Indexing a slice can cause panics and that is something we always want to avoid
75#![allow(clippy::indexing_slicing)]
76// Soundness issues
77//
78// Dereferencing unaligned pointers may be undefined behavior
79#![deny(clippy::cast_ptr_alignment)]
80// Ensure all types have a debug impl
81#![deny(missing_debug_implementations)]
82// This is usually a serious issue - a missing import of a define where it is interpreted
83// as a catch-all variable in a match, for example
84#![deny(unreachable_patterns)]
85// Ensure that all must_use results are used
86#![deny(unused_must_use)]
87// Style issues
88//
89// Documentation not ideal
90#![warn(clippy::doc_markdown)]
91// Document possible errors
92#![warn(clippy::missing_errors_doc)]
93// Document possible panics
94#![warn(clippy::missing_panics_doc)]
95// Ensure semicolons are present
96#![warn(clippy::semicolon_if_nothing_returned)]
97// Ensure numbers are readable
98#![warn(clippy::unreadable_literal)]
99// Martensite fork: relax upstream deny(unwrap_used) since test code uses unwrap
100#![allow(clippy::unwrap_used)]
101// Martensite fork: relax upstream warns that fail under -D warnings in CI
102#![allow(clippy::doc_markdown)]
103#![allow(clippy::missing_errors_doc)]
104#![allow(clippy::missing_panics_doc)]
105#![allow(clippy::semicolon_if_nothing_returned)]
106#![allow(clippy::unreadable_literal)]
107#![allow(clippy::unwrap_or_default)]
108#![allow(clippy::manual_unwrap_or)]
109#![allow(clippy::unnecessary_lazy_evaluations)]
110#![allow(clippy::redundant_closure)]
111#![allow(clippy::needless_range_loop)]
112#![allow(unused_imports)]
113#![cfg_attr(not(feature = "std"), no_std)]
114extern crate alloc;
115
116#[cfg(not(any(feature = "std", feature = "no_std")))]
117compile_error!("Either the `std` or `no_std` feature must be enabled");
118
119pub use self::attrs::*;
120mod attrs;
121
122pub use self::bidi_para::*;
123mod bidi_para;
124
125pub use self::buffer::*;
126mod buffer;
127
128pub use self::buffer_line::*;
129mod buffer_line;
130
131pub use self::cached::*;
132mod cached;
133
134pub use self::glyph_cache::*;
135mod glyph_cache;
136
137pub use self::cursor::*;
138mod cursor;
139
140pub use self::edit::*;
141mod edit;
142
143pub use self::font::*;
144mod font;
145
146pub use self::layout::*;
147mod layout;
148
149pub use self::line_ending::*;
150mod line_ending;
151
152pub use self::render::*;
153mod render;
154
155pub use self::shape::*;
156mod shape;
157
158pub use self::shape_run_cache::*;
159mod shape_run_cache;
160
161#[cfg(feature = "swash")]
162pub use self::swash::*;
163#[cfg(feature = "swash")]
164mod swash;
165
166mod math;
167
168type BuildHasher = core::hash::BuildHasherDefault<rustc_hash::FxHasher>;
169
170#[cfg(feature = "std")]
171type HashMap<K, V> = std::collections::HashMap<K, V, BuildHasher>;
172#[cfg(not(feature = "std"))]
173type HashMap<K, V> = hashbrown::HashMap<K, V, BuildHasher>;
174
175#[cfg(all(test, feature = "std"))]
176mod tests {
177    use crate::{Attrs, Buffer, FontSystem, Metrics};
178
179    #[test]
180    fn metrics_new_stores_values() {
181        let metrics = Metrics::new(14.0, 20.0);
182        assert_eq!(metrics.font_size, 14.0);
183        assert_eq!(metrics.line_height, 20.0);
184    }
185
186    #[test]
187    fn metrics_relative_calculates_line_height() {
188        let metrics = Metrics::relative(10.0, 1.5);
189        assert_eq!(metrics.font_size, 10.0);
190        assert_eq!(metrics.line_height, 15.0);
191    }
192
193    #[test]
194    fn metrics_scale_multiplies_values() {
195        let metrics = Metrics::new(10.0, 20.0).scale(2.0);
196        assert_eq!(metrics.font_size, 20.0);
197        assert_eq!(metrics.line_height, 40.0);
198    }
199
200    #[test]
201    fn metrics_default_is_zero() {
202        let metrics = Metrics::default();
203        assert_eq!(metrics.font_size, 0.0);
204        assert_eq!(metrics.line_height, 0.0);
205    }
206
207    #[test]
208    fn metrics_display_formats_values() {
209        let metrics = Metrics::new(14.0, 20.0);
210        assert_eq!(format!("{}", metrics), "14px / 20px");
211    }
212
213    #[test]
214    fn attrs_new_has_sane_defaults() {
215        let attrs = Attrs::new();
216        assert!(attrs.color_opt.is_none(), "default color should be unset");
217        assert_eq!(attrs.metadata, 0, "default metadata should be zero");
218    }
219
220    #[test]
221    fn attrs_setters_are_fluent() {
222        let attrs = Attrs::new().metadata(42);
223        assert_eq!(attrs.metadata, 42);
224    }
225
226    #[test]
227    fn buffer_new_empty_has_no_lines() {
228        let buffer = Buffer::new_empty(Metrics::new(14.0, 20.0));
229        assert!(buffer.lines.is_empty(), "new_empty buffer has no lines");
230    }
231
232    #[test]
233    fn buffer_new_with_font_system_seeds_a_line() {
234        let mut font_system = FontSystem::new();
235        let buffer = Buffer::new(&mut font_system, Metrics::new(14.0, 20.0));
236        // Buffer::new seeds an empty text line, so there is exactly one line.
237        assert_eq!(buffer.lines.len(), 1);
238    }
239
240    #[test]
241    fn font_system_new_constructs_database() {
242        let font_system = FontSystem::new();
243        // The Debug impl must surface the FontSystem type name.
244        let debug = format!("{:?}", font_system);
245        assert!(
246            debug.contains("FontSystem"),
247            "FontSystem debug output should contain its type name"
248        );
249    }
250}