tessera_ui/dp.rs
1//! # Density-Independent Pixels (Dp)
2//!
3//! This module provides the [`Dp`] type for representing density-independent pixels,
4//! a fundamental unit for UI scaling in the Tessera framework.
5//!
6//! ## Overview
7//!
8//! Density-independent pixels (dp) are a virtual pixel unit that provides consistent
9//! visual sizing across different screen densities. Unlike physical pixels, dp units
10//! automatically scale based on the device's screen density, ensuring that UI elements
11//! appear at the same physical size regardless of the display's pixel density.
12//!
13//! ## Scale Factor
14//!
15//! The conversion between dp and physical pixels is controlled by a global scale factor
16//! stored in [`SCALE_FACTOR`]. This factor is typically set based on the device's DPI
17//! (dots per inch) and user preferences.
18//!
19//! ## Usage
20//!
21//! ```
22//! use tessera_ui::Dp;
23//!
24//! // Create a dp value
25//! let padding = Dp(16.0);
26//!
27//! // Convert to pixels for rendering
28//! let pixels = padding.to_pixels_f32();
29//!
30//! // Create from pixel values
31//! let dp_from_pixels = Dp::from_pixels_f32(48.0);
32//! ```
33//!
34//! ## Relationship with Px
35//!
36//! The [`Dp`] type works closely with the [`Px`] type (physical pixels). You can
37//! convert between them using the provided methods, with the conversion automatically
38//! applying the current scale factor.
39
40use std::sync::OnceLock;
41
42use parking_lot::RwLock;
43
44use crate::Px;
45
46/// Global scale factor for converting between density-independent pixels and physical pixels.
47///
48/// This static variable holds the current scale factor used for dp-to-pixel conversions.
49/// It's typically initialized once during application startup based on the device's
50/// screen density and user scaling preferences.
51///
52/// The scale factor represents how many physical pixels correspond to one dp unit.
53/// For example:
54/// - Scale factor of 1.0: 1 dp = 1 pixel (standard density)
55/// - Scale factor of 2.0: 1 dp = 2 pixels (high density)
56/// - Scale factor of 0.75: 1 dp = 0.75 pixels (low density)
57///
58/// # Thread Safety
59///
60/// This variable uses `OnceLock<RwLock<f64>>` to ensure thread-safe access while
61/// allowing the scale factor to be updated during runtime if needed.
62pub static SCALE_FACTOR: OnceLock<RwLock<f64>> = OnceLock::new();
63
64/// Density-independent pixels (dp) for UI scaling.
65///
66/// `Dp` represents a length measurement that remains visually consistent across
67/// different screen densities. This is essential for creating UIs that look the
68/// same physical size on devices with varying pixel densities.
69///
70/// ## Design Philosophy
71///
72/// The dp unit is inspired by Android's density-independent pixel system and
73/// provides a device-agnostic way to specify UI dimensions. When you specify
74/// a button height of `Dp(48.0)`, it will appear roughly the same physical
75/// size on a low-DPI laptop screen and a high-DPI mobile device.
76///
77/// ## Internal Representation
78///
79/// The `Dp` struct wraps a single `f64` value representing the dp measurement.
80/// This value is converted to physical pixels using the global [`SCALE_FACTOR`]
81/// when rendering operations require pixel-precise measurements.
82///
83/// ## Examples
84///
85/// ```
86/// use tessera_ui::Dp;
87///
88/// // Common UI measurements in dp
89/// let small_padding = Dp(8.0);
90/// let medium_padding = Dp(16.0);
91/// let button_height = Dp(48.0);
92/// let large_spacing = Dp(32.0);
93///
94/// // Convert to pixels for rendering
95/// let pixels = button_height.to_pixels_f32();
96/// // Result depends on the current scale factor
97/// ```
98///
99/// ## Arithmetic Operations
100///
101/// While `Dp` doesn't implement arithmetic operators directly, you can perform
102/// operations on the inner value:
103///
104/// ```
105/// use tessera_ui::Dp;
106///
107/// let base_size = Dp(16.0);
108/// let double_size = Dp(base_size.0 * 2.0);
109/// let half_size = Dp(base_size.0 / 2.0);
110/// ```
111#[derive(Debug, Default, Clone, Copy, PartialEq, PartialOrd)]
112pub struct Dp(pub f64);
113
114impl Dp {
115 /// A constant representing zero density-independent pixels.
116 ///
117 /// # Examples
118 ///
119 /// ```
120 /// use tessera_ui::Dp;
121 ///
122 /// let zero_dp = Dp::ZERO;
123 /// assert_eq!(zero_dp, Dp(0.0));
124 /// ```
125 pub const ZERO: Dp = Dp(0.0);
126
127 /// Creates a new `Dp` instance with the specified value.
128 ///
129 /// This is a const function, allowing `Dp` values to be created at compile time.
130 ///
131 /// # Arguments
132 ///
133 /// * `value` - The dp value as a floating-point number
134 ///
135 /// # Examples
136 ///
137 /// ```
138 /// use tessera_ui::Dp;
139 ///
140 /// const BUTTON_HEIGHT: Dp = Dp::new(48.0);
141 /// let padding = Dp::new(16.0);
142 /// ```
143 pub const fn new(value: f64) -> Self {
144 Dp(value)
145 }
146
147 /// Converts this dp value to physical pixels as an `f64`.
148 ///
149 /// This method applies the current global scale factor to convert density-independent
150 /// pixels to physical pixels. The scale factor is read from [`SCALE_FACTOR`].
151 ///
152 /// # Returns
153 ///
154 /// The equivalent value in physical pixels as a 64-bit floating-point number.
155 /// If the scale factor hasn't been initialized, defaults to 1.0 (no scaling).
156 ///
157 /// # Examples
158 ///
159 /// ```
160 /// use tessera_ui::Dp;
161 ///
162 /// let dp_value = Dp(24.0);
163 /// let pixels = dp_value.to_pixels_f64();
164 /// // Result depends on the current scale factor
165 /// ```
166 pub fn to_pixels_f64(&self) -> f64 {
167 let scale_factor = SCALE_FACTOR.get().map(|lock| *lock.read()).unwrap_or(1.0);
168 self.0 * scale_factor
169 }
170
171 /// Creates a `Dp` value from physical pixels specified as an `f64`.
172 ///
173 /// This method performs the inverse conversion of [`to_pixels_f64`](Self::to_pixels_f64),
174 /// converting physical pixels back to density-independent pixels using the current
175 /// global scale factor.
176 ///
177 /// # Arguments
178 ///
179 /// * `value` - The pixel value as a 64-bit floating-point number
180 ///
181 /// # Returns
182 ///
183 /// A new `Dp` instance representing the equivalent dp value.
184 /// If the scale factor hasn't been initialized, defaults to 1.0 (no scaling).
185 ///
186 /// # Examples
187 ///
188 /// ```
189 /// use tessera_ui::Dp;
190 ///
191 /// // Convert 96 pixels to dp (assuming 2.0 scale factor = 48 dp)
192 /// let dp_value = Dp::from_pixels_f64(96.0);
193 /// ```
194 pub fn from_pixels_f64(value: f64) -> Self {
195 let scale_factor = SCALE_FACTOR.get().map(|lock| *lock.read()).unwrap_or(1.0);
196 Dp(value / scale_factor)
197 }
198
199 /// Converts this dp value to physical pixels as a `u32`.
200 ///
201 /// This method applies the current global scale factor and truncates the result
202 /// to an unsigned 32-bit integer. This is commonly used for rendering operations
203 /// that require integer pixel coordinates.
204 ///
205 /// # Returns
206 ///
207 /// The equivalent value in physical pixels as an unsigned 32-bit integer.
208 /// The result is truncated (not rounded) from the floating-point calculation.
209 /// If the scale factor hasn't been initialized, defaults to 1.0 (no scaling).
210 ///
211 /// # Examples
212 ///
213 /// ```
214 /// use tessera_ui::Dp;
215 ///
216 /// let dp_value = Dp(24.5);
217 /// let pixels = dp_value.to_pixels_u32();
218 /// // With scale factor 2.0: 24.5 * 2.0 = 49.0 -> 49u32
219 /// ```
220 ///
221 /// # Note
222 ///
223 /// Values are truncated, not rounded. For more precise control over rounding
224 /// behavior, use [`to_pixels_f64`](Self::to_pixels_f64) and apply your preferred
225 /// rounding method.
226 pub fn to_pixels_u32(&self) -> u32 {
227 let scale_factor = SCALE_FACTOR.get().map(|lock| *lock.read()).unwrap_or(1.0);
228 (self.0 * scale_factor) as u32
229 }
230
231 /// Creates a `Dp` value from physical pixels specified as a `u32`.
232 ///
233 /// This method converts an unsigned 32-bit integer pixel value to density-independent
234 /// pixels using the current global scale factor. The integer is first converted to
235 /// `f64` for the calculation.
236 ///
237 /// # Arguments
238 ///
239 /// * `value` - The pixel value as an unsigned 32-bit integer
240 ///
241 /// # Returns
242 ///
243 /// A new `Dp` instance representing the equivalent dp value.
244 /// If the scale factor hasn't been initialized, defaults to 1.0 (no scaling).
245 ///
246 /// # Examples
247 ///
248 /// ```
249 /// use tessera_ui::Dp;
250 ///
251 /// // Convert 96 pixels to dp (assuming 2.0 scale factor = 48.0 dp)
252 /// let dp_value = Dp::from_pixels_u32(96);
253 /// ```
254 pub fn from_pixels_u32(value: u32) -> Self {
255 let scale_factor = SCALE_FACTOR.get().map(|lock| *lock.read()).unwrap_or(1.0);
256 Dp((value as f64) / scale_factor)
257 }
258
259 /// Converts this dp value to physical pixels as an `f32`.
260 ///
261 /// This method applies the current global scale factor and converts the result
262 /// to a 32-bit floating-point number. This is commonly used for graphics APIs
263 /// that work with `f32` coordinates.
264 ///
265 /// # Returns
266 ///
267 /// The equivalent value in physical pixels as a 32-bit floating-point number.
268 /// If the scale factor hasn't been initialized, defaults to 1.0 (no scaling).
269 ///
270 /// # Examples
271 ///
272 /// ```
273 /// use tessera_ui::Dp;
274 ///
275 /// let dp_value = Dp(24.0);
276 /// let pixels = dp_value.to_pixels_f32();
277 /// // With scale factor 1.5: 24.0 * 1.5 = 36.0f32
278 /// ```
279 ///
280 /// # Precision Note
281 ///
282 /// Converting from `f64` to `f32` may result in precision loss for very large
283 /// or very precise values. For maximum precision, use [`to_pixels_f64`](Self::to_pixels_f64).
284 pub fn to_pixels_f32(&self) -> f32 {
285 let scale_factor = SCALE_FACTOR.get().map(|lock| *lock.read()).unwrap_or(1.0);
286 (self.0 * scale_factor) as f32
287 }
288
289 /// Creates a `Dp` value from physical pixels specified as an `f32`.
290 ///
291 /// This method converts a 32-bit floating-point pixel value to density-independent
292 /// pixels using the current global scale factor. The `f32` value is first converted
293 /// to `f64` for internal calculations.
294 ///
295 /// # Arguments
296 ///
297 /// * `value` - The pixel value as a 32-bit floating-point number
298 ///
299 /// # Returns
300 ///
301 /// A new `Dp` instance representing the equivalent dp value.
302 /// If the scale factor hasn't been initialized, defaults to 1.0 (no scaling).
303 ///
304 /// # Examples
305 ///
306 /// ```
307 /// use tessera_ui::Dp;
308 ///
309 /// // Convert 36.0 pixels to dp (assuming 1.5 scale factor = 24.0 dp)
310 /// let dp_value = Dp::from_pixels_f32(36.0);
311 /// ```
312 pub fn from_pixels_f32(value: f32) -> Self {
313 let scale_factor = SCALE_FACTOR.get().map(|lock| *lock.read()).unwrap_or(1.0);
314 Dp((value as f64) / scale_factor)
315 }
316
317 /// Converts this `Dp` value to a `Px` (physical pixels) value.
318 ///
319 /// This method provides a convenient way to convert between the two pixel
320 /// types used in the Tessera framework. It applies the current scale factor
321 /// and creates a `Px` instance from the result.
322 ///
323 /// # Returns
324 ///
325 /// A new `Px` instance representing the equivalent physical pixel value.
326 ///
327 /// # Examples
328 ///
329 /// ```
330 /// use tessera_ui::Dp;
331 ///
332 /// let dp_value = Dp(24.0);
333 /// let px_value = dp_value.to_px();
334 /// // px_value now contains the scaled pixel equivalent
335 /// ```
336 ///
337 /// # See Also
338 ///
339 /// * [`Px::to_dp`] - For the inverse conversion
340 /// * [`to_pixels_f32`](Self::to_pixels_f32) - For direct `f32` pixel conversion
341 pub fn to_px(&self) -> Px {
342 Px::from_f32(self.to_pixels_f32())
343 }
344}
345
346impl From<f64> for Dp {
347 /// Creates a `Dp` instance from an `f64` value.
348 ///
349 /// This implementation allows for convenient conversion from floating-point
350 /// numbers to `Dp` values using the `into()` method or direct assignment
351 /// in contexts where type coercion occurs.
352 ///
353 /// # Arguments
354 ///
355 /// * `value` - The dp value as a 64-bit floating-point number
356 ///
357 /// # Examples
358 ///
359 /// ```
360 /// use tessera_ui::Dp;
361 ///
362 /// let dp1: Dp = 24.0.into();
363 /// let dp2 = Dp::from(16.0);
364 ///
365 /// // In function calls that expect Dp
366 /// fn set_padding(padding: Dp) { /* ... */ }
367 /// set_padding(8.0.into());
368 /// ```
369 fn from(value: f64) -> Self {
370 Dp::new(value)
371 }
372}
373
374impl From<Px> for Dp {
375 /// Creates a `Dp` instance from a `Px` (physical pixels) value.
376 ///
377 /// This implementation enables seamless conversion between the two pixel
378 /// types used in the Tessera framework. The conversion applies the inverse
379 /// of the current scale factor to convert physical pixels back to
380 /// density-independent pixels.
381 ///
382 /// # Arguments
383 ///
384 /// * `px` - A `Px` instance representing physical pixels
385 ///
386 /// # Examples
387 ///
388 /// ```
389 /// use tessera_ui::{Dp, Px};
390 ///
391 /// let px_value = Px::from_f32(48.0);
392 /// let dp_value: Dp = px_value.into();
393 ///
394 /// // Or using From::from
395 /// let dp_value2 = Dp::from(px_value);
396 /// ```
397 ///
398 /// # See Also
399 ///
400 /// * [`to_px`](Self::to_px) - For the inverse conversion
401 /// * [`from_pixels_f64`](Self::from_pixels_f64) - For direct pixel-to-dp conversion
402 fn from(px: Px) -> Self {
403 Dp::from_pixels_f64(px.to_dp().0)
404 }
405}