1use super::*;
4
5#[derive(Debug, Clone)]
6pub(crate) enum LengthValue {
7 Auto,
8 Px(i32),
9 Percent(f32),
10 MinContent,
12 MaxContent,
14 FitContent,
16 FitContentWith(alloc::boxed::Box<LengthValue>),
18 MathExpr(String),
21}
22
23pub(crate) fn len_value<'a>(node: &'a StyledNode<'a>, name: &str) -> Option<alloc::borrow::Cow<'a, str>> {
31 let v = node.value_ref(name)?;
32 if !v.as_bytes().windows(2).any(|w| w.eq_ignore_ascii_case(b"em")) {
34 return Some(alloc::borrow::Cow::Borrowed(v));
35 }
36 let font_px = node
37 .value_ref("font-size")
38 .and_then(parse_font_size_u32)
39 .unwrap_or(16) as f32;
40 Some(alloc::borrow::Cow::Owned(crate::os_lib::css::units::resolve_em_lengths(v, font_px)))
41}
42
43pub(crate) fn parse_length_value<S: AsRef<str>>(value: Option<S>) -> Option<LengthValue> {
44 let v = value?;
45 let t = v.as_ref().trim();
46 if t.is_empty() {
47 return None;
48 }
49 if t.eq_ignore_ascii_case("auto") {
50 return Some(LengthValue::Auto);
51 }
52 if t.eq_ignore_ascii_case("min-content") {
53 return Some(LengthValue::MinContent);
54 }
55 if t.eq_ignore_ascii_case("max-content") {
56 return Some(LengthValue::MaxContent);
57 }
58 if t.eq_ignore_ascii_case("fit-content") {
59 return Some(LengthValue::FitContent);
60 }
61 if t.len() >= 13
62 && t.get(..12).is_some_and(|h| h.eq_ignore_ascii_case("fit-content("))
63 && t.ends_with(')')
64 {
65 let inner = t.get(12..t.len() - 1).unwrap_or("").trim();
66 if let Some(parsed) = parse_length_value(Some(inner)) {
67 return Some(LengthValue::FitContentWith(alloc::boxed::Box::new(parsed)));
68 }
69 }
70 if is_css_math_func(t) {
71 return Some(LengthValue::MathExpr(String::from(t)));
72 }
73 if let Some((basis, expr)) = split_calc_size(t) {
74 return calc_size_length_value(basis, expr);
75 }
76 if let Some(num) = t.strip_suffix('%') {
77 if let Ok(pct) = num.trim().parse::<f32>() {
78 return Some(LengthValue::Percent(pct / 100.0));
79 }
80 return None;
81 }
82 parse_px_like(t).map(LengthValue::Px)
83}
84
85pub(crate) fn split_calc_size(t: &str) -> Option<(&str, &str)> {
87 let t = t.trim();
88 let inner = t.get(..10).filter(|p| p.eq_ignore_ascii_case("calc-size(")).and_then(|_| t.get(10..t.len().checked_sub(1)?))?;
89 if !t.ends_with(')') {
90 return None;
91 }
92 let parts = crate::os_lib::css::split_top_level_commas(inner);
93 match parts.as_slice() {
94 [basis, expr] => Some((basis.trim(), expr.trim())),
95 _ => None,
96 }
97}
98
99pub(crate) fn calc_size_is_auto(t: &str) -> bool {
101 split_calc_size(t).is_some_and(|(basis, expr)| expr.eq_ignore_ascii_case("size") && basis.eq_ignore_ascii_case("auto"))
102}
103
104fn calc_size_length_value(basis: &str, expr: &str) -> Option<LengthValue> {
108 if expr.eq_ignore_ascii_case("size") {
109 return if basis.eq_ignore_ascii_case("any") { None } else { parse_length_value(Some(basis)) };
110 }
111 let sub = if basis.eq_ignore_ascii_case("any") {
112 String::new()
113 } else {
114 match parse_length_value(Some(basis))? {
115 LengthValue::Px(_) | LengthValue::Percent(_) | LengthValue::MathExpr(_) => alloc::format!("({})", basis),
116 _ => return None,
117 }
118 };
119 let b = expr.as_bytes();
120 let mut out = String::from("calc(");
121 let mut i = 0usize;
122 while i < b.len() {
123 let c = b[i];
124 if c.is_ascii_alphabetic() || c == b'-' && b.get(i + 1).is_some_and(|n| n.is_ascii_alphabetic()) {
125 let st = i;
126 while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'-') {
127 i += 1;
128 }
129 let word = expr.get(st..i).unwrap_or("");
130 let after_digit = st > 0 && (b[st - 1].is_ascii_digit() || b[st - 1] == b'.' || b[st - 1] == b'%');
132 if !after_digit && word.eq_ignore_ascii_case("size") {
133 if sub.is_empty() {
134 return None;
135 }
136 out.push_str(&sub);
137 } else {
138 out.push_str(word);
139 }
140 continue;
141 }
142 out.push(c as char);
143 i += 1;
144 }
145 out.push(')');
146 Some(LengthValue::MathExpr(out))
147}
148
149pub(crate) fn resolve_length_value(value: LengthValue, base: i32) -> Option<i32> {
150 resolve_length_value_with_font(value, base, 16.0)
151}
152
153pub(crate) fn resolve_length_value_with_font(value: LengthValue, base: i32, font_px: f32) -> Option<i32> {
154 match value {
155 LengthValue::Auto => None,
156 LengthValue::Px(px) => Some(px),
157 LengthValue::Percent(pct) => Some(round_f32_to_i32((base as f32) * pct)),
158 LengthValue::MinContent
161 | LengthValue::MaxContent
162 | LengthValue::FitContent
163 | LengthValue::FitContentWith(_) => None,
164 LengthValue::MathExpr(expr) => crate::os_lib::css::eval_css_math_with_font(&expr, base, font_px),
165 }
166}
167
168pub(crate) fn min_max(value: i32, min_v: Option<i32>, max_v: Option<i32>) -> i32 {
169 let mut v = value;
170 if let Some(min_v) = min_v {
171 v = v.max(min_v);
172 }
173 if let Some(max_v) = max_v {
174 v = v.min(max_v);
175 }
176 v
177}
178
179pub(crate) fn parse_aspect_ratio(s: &str) -> Option<(f32, f32)> {
182 let t = s.trim();
183 if t.is_empty() || t.eq_ignore_ascii_case("auto") {
184 return None;
185 }
186 let (num, den) = if let Some((ns, ds)) = t.split_once('/') {
187 (
188 ns.trim().parse::<f32>().ok()?,
189 ds.trim().parse::<f32>().ok()?,
190 )
191 } else {
192 (t.parse::<f32>().ok()?, 1.0)
193 };
194 if num > 0.0 && den > 0.0 {
195 Some((num, den))
196 } else {
197 None
198 }
199}
200
201pub(crate) fn round_f32_to_i32(value: f32) -> i32 {
202 if value >= 0.0 {
203 (value + 0.5) as i32
204 } else {
205 (value - 0.5) as i32
206 }
207}
208
209pub(crate) fn parse_flex_gap(node: &StyledNode, base: i32) -> (i32, i32) {
212 fn px(s: &str, base: i32) -> i32 {
213 match parse_length_value(Some(s.trim())) {
214 Some(LengthValue::Px(p)) => p,
215 Some(LengthValue::Percent(pct)) => round_f32_to_i32(base as f32 * pct).max(0),
216 _ => 0,
217 }
218 }
219 let (mut row, mut col) = (0, 0);
220 if let Some(g) = len_value(node, "gap").or_else(|| len_value(node, "grid-gap")) {
221 let mut it = g.split_whitespace();
222 if let Some(first) = it.next() {
223 row = px(first, base);
224 col = match it.next() {
225 Some(second) => px(second, base),
226 None => row,
227 };
228 }
229 }
230 if let Some(rg) = len_value(node, "row-gap").or_else(|| len_value(node, "grid-row-gap")) {
231 row = px(&rg, base);
232 }
233 if let Some(cg) = len_value(node, "column-gap").or_else(|| len_value(node, "grid-column-gap")) {
234 col = px(&cg, base);
235 }
236 (row, col)
237}
238
239pub(crate) fn resolve_edge(s: &str, base: i32) -> Option<i32> {
240 match parse_length_value(Some(s)) {
241 Some(LengthValue::Px(px)) => Some(px),
242 Some(LengthValue::Percent(pct)) if base > 0 => Some(round_f32_to_i32(base as f32 * pct)),
243 _ => None,
244 }
245}
246
247pub(crate) fn is_css_math_func(s: &str) -> bool {
248 let t = s.trim();
249 t.starts_with("calc(") || t.starts_with("min(") || t.starts_with("max(") || t.starts_with("clamp(")
250 || t.starts_with("abs(") || t.starts_with("sign(") || t.starts_with("round(")
251 || t.starts_with("mod(") || t.starts_with("rem(")
252}
253
254pub(crate) fn apply_box_value<S: AsRef<str>>(value: Option<S>, edges: &mut EdgeSizes, base: i32) {
255 let Some(v) = value else { return };
256 let v = v.as_ref();
257 let vt = v.trim();
259 if is_css_math_func(vt) {
260 if let Some(px) = crate::os_lib::css::eval_css_math(vt, base) {
261 edges.top = px;
262 edges.right = px;
263 edges.bottom = px;
264 edges.left = px;
265 }
266 return;
267 }
268 let mut vals: [Option<i32>; 4] = [None; 4];
274 let mut count = 0usize;
275 let mut any_some = false;
276 for p in vt.split_whitespace().take(4) {
277 let resolved = resolve_edge(p, base);
278 if resolved.is_some() {
279 any_some = true;
280 }
281 vals[count] = resolved;
282 count += 1;
283 }
284 if count == 0 || !any_some {
285 return;
286 }
287 let (top, right, bottom, left) = match count {
288 1 => (vals[0], vals[0], vals[0], vals[0]),
289 2 => (vals[0], vals[1], vals[0], vals[1]),
290 3 => (vals[0], vals[1], vals[2], vals[1]),
291 _ => (vals[0], vals[1], vals[2], vals[3]),
292 };
293 if let Some(v) = top {
294 edges.top = v;
295 }
296 if let Some(v) = right {
297 edges.right = v;
298 }
299 if let Some(v) = bottom {
300 edges.bottom = v;
301 }
302 if let Some(v) = left {
303 edges.left = v;
304 }
305}
306
307pub(crate) fn apply_edge_value<S: AsRef<str>>(value: Option<S>, edge: &mut i32, base: i32) {
308 if let Some(v) = value {
309 let t = v.as_ref().trim();
310 if is_css_math_func(t) {
311 if let Some(px) = crate::os_lib::css::eval_css_math(t, base) {
312 *edge = px;
313 }
314 } else if let Some(px) = resolve_edge(t, base) {
315 *edge = px;
316 }
317 }
318}
319
320pub(crate) fn parse_px_like(s: &str) -> Option<i32> {
321 let t = s.trim();
322 if t.is_empty() {
323 return None;
324 }
325 match t {
335 "thin" => return Some(1),
336 "medium" => return Some(3),
337 "thick" => return Some(5),
338 _ => {}
339 }
340 if let Some(num) = t.strip_suffix("px") {
341 return num.trim().parse::<f32>().ok().map(round_f32_to_i32);
342 }
343 if let Some(num) = t.strip_suffix("vh") {
344 let h = VIEWPORT_HINT_H.load(AtomicOrdering::Relaxed);
345 return num
346 .trim()
347 .parse::<f32>()
348 .ok()
349 .map(|v| round_f32_to_i32((v / 100.0) * h as f32));
350 }
351 if let Some(num) = t.strip_suffix("vw") {
352 let w = VIEWPORT_HINT_W.load(AtomicOrdering::Relaxed);
353 return num
354 .trim()
355 .parse::<f32>()
356 .ok()
357 .map(|v| round_f32_to_i32((v / 100.0) * w as f32));
358 }
359 if let Some(num) = t.strip_suffix("vmin") {
368 let w = VIEWPORT_HINT_W.load(AtomicOrdering::Relaxed);
369 let h = VIEWPORT_HINT_H.load(AtomicOrdering::Relaxed);
370 let m = w.min(h);
371 return num
372 .trim()
373 .parse::<f32>()
374 .ok()
375 .map(|v| round_f32_to_i32((v / 100.0) * m as f32));
376 }
377 if let Some(num) = t.strip_suffix("vmax") {
378 let w = VIEWPORT_HINT_W.load(AtomicOrdering::Relaxed);
379 let h = VIEWPORT_HINT_H.load(AtomicOrdering::Relaxed);
380 let m = w.max(h);
381 return num
382 .trim()
383 .parse::<f32>()
384 .ok()
385 .map(|v| round_f32_to_i32((v / 100.0) * m as f32));
386 }
387 if let Some(num) = t.strip_suffix("rem") {
388 return num
389 .trim()
390 .parse::<f32>()
391 .ok()
392 .map(|v| round_f32_to_i32(v * crate::os_lib::css::units::root_font_px()));
393 }
394 if let Some(num) = t.strip_suffix("em") {
395 return num
396 .trim()
397 .parse::<f32>()
398 .ok()
399 .map(|v| round_f32_to_i32(v * 16.0));
400 }
401 if let Some(num) = t.strip_suffix("in") {
406 return num.trim().parse::<f32>().ok().map(|v| round_f32_to_i32(v * 96.0));
407 }
408 if let Some(num) = t.strip_suffix("cm") {
409 return num
410 .trim()
411 .parse::<f32>()
412 .ok()
413 .map(|v| round_f32_to_i32(v * 96.0 / 2.54));
414 }
415 if let Some(num) = t.strip_suffix("mm") {
416 return num
417 .trim()
418 .parse::<f32>()
419 .ok()
420 .map(|v| round_f32_to_i32(v * 96.0 / 25.4));
421 }
422 if let Some(num) = t.strip_suffix("pt") {
423 return num
424 .trim()
425 .parse::<f32>()
426 .ok()
427 .map(|v| round_f32_to_i32(v * 96.0 / 72.0));
428 }
429 if let Some(num) = t.strip_suffix("pc") {
430 return num.trim().parse::<f32>().ok().map(|v| round_f32_to_i32(v * 16.0));
431 }
432 if let Some(num) = t.strip_suffix('q') {
433 return num
434 .trim()
435 .parse::<f32>()
436 .ok()
437 .map(|v| round_f32_to_i32(v * 96.0 / 101.6));
438 }
439 t.parse::<f32>().ok().map(round_f32_to_i32)
440}
441
442pub(crate) fn parse_letter_spacing_with_font(val: Option<&str>, containing_width: i32, font_px: f32) -> i32 {
447 match val {
448 None => 0,
449 Some(s) => {
450 let t = s.trim();
451 if t.is_empty() || t.eq_ignore_ascii_case("normal") {
452 0
453 } else if is_css_math_func(t) {
454 crate::os_lib::css::eval_css_math_with_font(t, containing_width, font_px).unwrap_or(0)
455 } else if let Some(num) = t.strip_suffix("em") {
456 num.trim()
457 .parse::<f32>()
458 .ok()
459 .map(|v| round_f32_to_i32(v * font_px))
460 .unwrap_or(0)
461 } else {
462 parse_px_like(t).unwrap_or(0)
463 }
464 }
465 }
466}
467
468pub(crate) fn parse_letter_spacing_ctx(val: Option<&str>, containing_width: i32) -> i32 {
469 parse_letter_spacing_with_font(val, containing_width, 16.0)
470}
471
472pub(crate) fn parse_letter_spacing(val: Option<&str>) -> i32 {
474 parse_letter_spacing_ctx(val, 0)
475}
476
477pub(crate) fn parse_word_spacing_with_font(val: Option<&str>, containing_width: i32, font_px: f32) -> i32 {
479 parse_letter_spacing_with_font(val, containing_width, font_px)
480}
481
482pub(crate) fn parse_word_spacing_ctx(val: Option<&str>, containing_width: i32) -> i32 {
484 parse_letter_spacing_ctx(val, containing_width)
485}
486
487pub(crate) fn parse_word_spacing(val: Option<&str>) -> i32 {
489 parse_letter_spacing_ctx(val, 0)
490}
491
492pub(crate) fn parse_font_size_u32(s: &str) -> Option<u32> {
504 crate::os_lib::css::units::parse_font_size(s)
505}
506
507pub(crate) fn shift_layout_box(layout: &mut LayoutBox, dx: i32, dy: i32) {
508 layout.dimensions.content.x += dx;
509 layout.dimensions.content.y += dy;
510 for child in &mut layout.children {
511 shift_layout_box(child, dx, dy);
512 }
513}
514
515pub(crate) fn get_image_size(data: &[u8]) -> Option<(i32, i32)> {
516 if data.len() >= 24 && &data[0..8] == b"\x89PNG\r\n\x1a\n" && &data[12..16] == b"IHDR" {
517 let w = u32::from_be_bytes(data[16..20].try_into().ok()?) as i32;
518 let h = u32::from_be_bytes(data[20..24].try_into().ok()?) as i32;
519 return Some((w, h));
520 }
521 if data.len() >= 26 && &data[0..2] == b"BM" {
522 let w = i32::from_le_bytes(data[18..22].try_into().ok()?);
523 let h = i32::from_le_bytes(data[22..26].try_into().ok()?);
524 if w > 0 && h != 0 {
525 return Some((w, h.abs()));
526 }
527 }
528 if data.len() >= 4 && data[0] == 0xFF && data[1] == 0xD8 {
529 let mut i = 2;
530 while i + 8 < data.len() {
531 if data[i] != 0xFF {
532 i += 1;
533 continue;
534 }
535 let marker = data[i + 1];
536 if marker == 0xD9 || marker == 0xDA {
537 break;
538 }
539 if marker == 0x00 || (0xD0..=0xD7).contains(&marker) {
540 i += 2;
541 continue;
542 }
543 let len = u16::from_be_bytes([data[i + 2], data[i + 3]]) as usize;
544 if (0xC0..=0xCF).contains(&marker)
545 && marker != 0xC4
546 && marker != 0xC8
547 && marker != 0xCC
548 && i + 9 < data.len()
549 {
550 let h = u16::from_be_bytes([data[i + 5], data[i + 6]]) as i32;
551 let w = u16::from_be_bytes([data[i + 7], data[i + 8]]) as i32;
552 return Some((w, h));
553 }
554 i += 2 + len;
555 }
556 }
557 None
558}
559
560pub(crate) fn get_styled_node_text(node: &StyledNode) -> String {
561 let mut text = String::new();
562 if let NodeType::Text(t) = &node.node.node_type {
563 text.push_str(t);
564 }
565 for child in &node.children {
566 text.push_str(&get_styled_node_text(child));
567 }
568 text
569}
570
571pub(crate) fn parse_length_val_simple(s: &str) -> Option<i32> {
572 if let Some(LengthValue::Px(px)) = parse_length_value(Some(s)) {
573 Some(px)
574 } else {
575 None
576 }
577}
578
579pub(crate) use core::sync::atomic::{AtomicBool, AtomicI32, AtomicU32, Ordering as AtomicOrdering};
583pub use crate::os_lib::viewport::{VIEWPORT_HINT_H, VIEWPORT_HINT_W};
584
585pub(crate) static PCT_BASE_H: AtomicI32 = AtomicI32::new(-1);
595
596pub(crate) struct PctBaseHGuard(i32);
598
599impl PctBaseHGuard {
600 pub(crate) fn set(h: i32) -> Self {
601 PctBaseHGuard(PCT_BASE_H.swap(h, AtomicOrdering::Relaxed))
602 }
603}
604
605impl Drop for PctBaseHGuard {
606 fn drop(&mut self) {
607 PCT_BASE_H.store(self.0, AtomicOrdering::Relaxed);
608 }
609}
610
611pub(crate) static FORCED_BLOCK_H: AtomicI32 = AtomicI32::new(-1);
615
616pub(crate) static GRID_PCT_BASE_W: AtomicI32 = AtomicI32::new(-1);
619
620pub(crate) static CUSTOM_FONT_GEN: AtomicU32 = AtomicU32::new(0);
623
624pub fn notify_custom_font_registered() {
625 CUSTOM_FONT_GEN.fetch_add(1, AtomicOrdering::Relaxed);
626}
627
628pub(crate) static ABS_CB_X: AtomicI32 = AtomicI32::new(0);
629pub(crate) static ABS_CB_Y: AtomicI32 = AtomicI32::new(0);
630pub(crate) static ABS_CB_W: AtomicI32 = AtomicI32::new(800);
631pub(crate) static ABS_CB_H: AtomicI32 = AtomicI32::new(600);
632pub(crate) static VP_ORIGIN_X: AtomicI32 = AtomicI32::new(0);
634pub(crate) static VP_ORIGIN_Y: AtomicI32 = AtomicI32::new(0);
635pub(crate) static FIXED_CB_ACTIVE: AtomicBool = AtomicBool::new(false);
636pub(crate) static FIXED_CB_X: AtomicI32 = AtomicI32::new(0);
637pub(crate) static FIXED_CB_Y: AtomicI32 = AtomicI32::new(0);
638pub(crate) static FIXED_CB_W: AtomicI32 = AtomicI32::new(800);
639pub(crate) static FIXED_CB_H: AtomicI32 = AtomicI32::new(600);
640
641pub(crate) fn abs_cb_get() -> (i32, i32, i32, i32) {
642 (
643 ABS_CB_X.load(AtomicOrdering::Relaxed),
644 ABS_CB_Y.load(AtomicOrdering::Relaxed),
645 ABS_CB_W.load(AtomicOrdering::Relaxed),
646 ABS_CB_H.load(AtomicOrdering::Relaxed),
647 )
648}
649pub(crate) fn abs_cb_set(x: i32, y: i32, w: i32, h: i32) {
650 ABS_CB_X.store(x, AtomicOrdering::Relaxed);
651 ABS_CB_Y.store(y, AtomicOrdering::Relaxed);
652 ABS_CB_W.store(w, AtomicOrdering::Relaxed);
653 ABS_CB_H.store(h, AtomicOrdering::Relaxed);
654}
655pub(crate) fn fixed_cb_get() -> Option<(i32, i32, i32, i32)> {
656 if FIXED_CB_ACTIVE.load(AtomicOrdering::Relaxed) {
657 Some((
658 FIXED_CB_X.load(AtomicOrdering::Relaxed),
659 FIXED_CB_Y.load(AtomicOrdering::Relaxed),
660 FIXED_CB_W.load(AtomicOrdering::Relaxed),
661 FIXED_CB_H.load(AtomicOrdering::Relaxed),
662 ))
663 } else {
664 None
665 }
666}
667pub(crate) fn fixed_cb_set(cb: Option<(i32, i32, i32, i32)>) {
668 match cb {
669 Some((x, y, w, h)) => {
670 FIXED_CB_X.store(x, AtomicOrdering::Relaxed);
671 FIXED_CB_Y.store(y, AtomicOrdering::Relaxed);
672 FIXED_CB_W.store(w, AtomicOrdering::Relaxed);
673 FIXED_CB_H.store(h, AtomicOrdering::Relaxed);
674 FIXED_CB_ACTIVE.store(true, AtomicOrdering::Relaxed);
675 }
676 None => {
677 FIXED_CB_ACTIVE.store(false, AtomicOrdering::Relaxed);
678 }
679 }
680}
681pub(crate) fn vp_origin_get() -> (i32, i32) {
682 (
683 VP_ORIGIN_X.load(AtomicOrdering::Relaxed),
684 VP_ORIGIN_Y.load(AtomicOrdering::Relaxed),
685 )
686}
687
688pub use crate::os_lib::viewport::set_viewport_hint;
689
690pub(crate) fn resolve_len_or_pct(s: &str, base: i32) -> Option<i32> {
692 match parse_length_value(Some(s)) {
693 Some(LengthValue::Px(px)) => Some(px),
694 Some(LengthValue::Percent(pct)) => Some(round_f32_to_i32(base as f32 * pct)),
695 _ => None,
696 }
697}
698
699fn scale_dim(a: i32, num: i32, den: i32) -> i32 {
701 ((a as i64 * num as i64 + den as i64 / 2) / den as i64) as i32
702}
703
704fn parse_svg_data_uri_dims(src: &str) -> Option<(i32, i32)> {
706 super::types::parse_svg_data_uri_ratio(src)
707 .map(|(w, h)| (round_f32_to_i32(w).max(1), round_f32_to_i32(h).max(1)))
708}
709
710pub(crate) fn box_natural_size(node: &StyledNode) -> Option<(i32, i32)> {
713 let NodeType::Element { tag_name, attributes, .. } = &node.node.node_type else {
714 return None;
715 };
716 match tag_name.as_str() {
717 "canvas" => {
718 let aw = attributes.get("width").and_then(|v| v.trim().parse::<i32>().ok()).filter(|&v| v > 0).unwrap_or(300);
719 let ah = attributes.get("height").and_then(|v| v.trim().parse::<i32>().ok()).filter(|&v| v > 0).unwrap_or(150);
720 Some((aw, ah))
721 }
722 "img" => {
723 let src = attributes.get("src")?;
724 if let Some(sz) = IMAGE_SIZE_CACHE.lock().as_ref().and_then(|c| c.get(src).copied()) {
725 return Some(sz);
726 }
727 if let Some(sz) = parse_svg_data_uri_dims(src) {
728 return Some(sz);
729 }
730 if src.starts_with('/') || (!src.contains("://") && !src.starts_with("data:")) {
731 let content_res = {
732 let _fs_guard = crate::kernel::fs::FS_LOCK.lock();
733 crate::kernel::fs::get_fs().read_file_checked(src)
734 };
735 if let Ok(Some((_meta, content))) = content_res {
736 if let Some((w, h)) = get_image_size(&content) {
737 let mut cache = IMAGE_SIZE_CACHE.lock();
738 if cache.is_none() {
739 *cache = Some(BTreeMap::new());
740 }
741 if let Some(ref mut map) = *cache {
742 map.insert(String::from(src), (w, h));
743 }
744 return Some((w, h));
745 }
746 }
747 }
748 None
749 }
750 _ => None,
751 }
752}
753
754pub(crate) fn get_replaced_element_size(node: &StyledNode) -> Option<(i32, i32)> {
756 get_replaced_element_size_in(node, Some(VIEWPORT_HINT_W.load(AtomicOrdering::Relaxed)))
757}
758
759pub(crate) fn get_replaced_element_size_in(
774 node: &StyledNode,
775 pct_base_w: Option<i32>,
776) -> Option<(i32, i32)> {
777 let NodeType::Element {
778 tag_name,
779 attributes,
780 ..
781 } = &node.node.node_type
782 else {
783 return None;
784 };
785 if !matches!(tag_name.as_str(), "img" | "video" | "canvas" | "input" | "textarea" | "button" | "iframe") {
789 return None;
790 }
791 if tag_name == "button"
794 && node.value_ref("display").is_some_and(|d| {
795 matches!(d.trim(), "flex" | "inline-flex" | "grid" | "inline-grid" | "-webkit-flex" | "-webkit-inline-flex")
796 })
797 {
798 return None;
799 }
800
801 let len_w = |v: &str| -> Option<i32> {
802 match parse_length_value(Some(v)) {
803 Some(LengthValue::Px(px)) => Some(px),
804 Some(LengthValue::Percent(pct)) => pct_base_w.map(|b| round_f32_to_i32(b as f32 * pct)),
805 _ => None,
806 }
807 };
808 let base_h = PCT_BASE_H.load(AtomicOrdering::Relaxed);
810 let len_h = |v: &str| -> Option<i32> {
811 match parse_length_value(Some(v)) {
812 Some(LengthValue::Px(px)) => Some(px),
813 Some(LengthValue::Percent(pct)) if base_h >= 0 => {
814 Some(round_f32_to_i32(base_h as f32 * pct))
815 }
816 _ => None,
817 }
818 };
819 let css_w = len_value(node, "width").and_then(|v| len_w(&v));
820 let css_h = len_value(node, "height").and_then(|v| len_h(&v));
821 let max_w = len_value(node, "max-width").and_then(|v| len_w(&v));
822 let max_h = len_value(node, "max-height").and_then(|v| len_h(&v));
823
824 let attr_w = attributes
825 .get("width")
826 .and_then(|v| v.trim().parse::<i32>().ok());
827 let attr_h = attributes
828 .get("height")
829 .and_then(|v| v.trim().parse::<i32>().ok());
830
831 let explicit_auto_w = node
832 .value_ref("width")
833 .is_some_and(|v| v.trim().eq_ignore_ascii_case("auto"));
834 let explicit_auto_h = node
835 .value_ref("height")
836 .is_some_and(|v| v.trim().eq_ignore_ascii_case("auto"));
837 let target_w = css_w.or(if explicit_auto_w { None } else { attr_w });
838 let target_h = css_h.or(if explicit_auto_h { None } else { attr_h });
839
840 match tag_name.as_str() {
841 "img" => {
842 if let (Some(w), Some(h)) = (target_w, target_h) {
843 if max_w.is_none() && max_h.is_none() {
844 return Some((w, h));
845 }
846 }
847 let src_opt = attributes.get("src").map(|s| s.trim());
850 let use_replaced_default = match src_opt {
851 None | Some("") => true,
852 Some(s) => s.get(..5).is_some_and(|p| p.eq_ignore_ascii_case("data:")),
853 };
854 let mut resolved_w = if use_replaced_default { 300 } else { 400 };
855 let mut resolved_h = if use_replaced_default { 150 } else { 200 };
856 if let Some(src) = attributes.get("src") {
857 let registered = {
865 let cache = IMAGE_SIZE_CACHE.lock();
866 cache.as_ref().and_then(|c| c.get(src).copied())
867 };
868 if let Some((w, h)) = registered {
869 resolved_w = w;
870 resolved_h = h;
871 } else if let Some((w, h)) = parse_svg_data_uri_dims(src) {
872 resolved_w = w;
873 resolved_h = h;
874 } else if src.starts_with('/') || (!src.contains("://") && !src.starts_with("data:")) {
875 {
876 let mut cache = IMAGE_SIZE_CACHE.lock();
877 if cache.is_none() {
878 *cache = Some(BTreeMap::new());
879 }
880 }
881 let mut cached = None;
882 if let Some(ref cache) = *IMAGE_SIZE_CACHE.lock() {
883 if let Some(&size) = cache.get(src) {
884 cached = Some(size);
885 }
886 }
887 if let Some((w, h)) = cached {
888 resolved_w = w;
889 resolved_h = h;
890 } else {
891 let content_res = {
901 let _fs_guard = crate::kernel::fs::FS_LOCK.lock();
902 crate::kernel::fs::get_fs().read_file_checked(src)
903 };
904 match content_res {
905 Ok(Some((_meta, content))) => {
906 if let Some((w, h)) = get_image_size(&content) {
907 resolved_w = w;
908 resolved_h = h;
909 if let Some(ref mut cache) = *IMAGE_SIZE_CACHE.lock() {
910 cache.insert(String::from(src), (w, h));
911 }
912 }
913 }
914 Ok(None) => {}
915 Err(e) => {
916 crate::warn!("[FS] values: failed to read image '{}': {}", src, e);
917 }
918 }
919 }
920 }
921 }
922 let (mut w, mut h) = match (target_w, target_h) {
924 (Some(w), Some(h)) => (w, h),
925 (Some(w), None) if resolved_w > 0 => (w, scale_dim(w, resolved_h, resolved_w)),
926 (None, Some(h)) if resolved_h > 0 => (scale_dim(h, resolved_w, resolved_h), h),
927 (w, h) => (w.unwrap_or(resolved_w), h.unwrap_or(resolved_h)),
928 };
929 if let Some(mw) = max_w {
931 if mw >= 0 && w > mw {
932 if target_h.is_none() && w > 0 {
933 h = scale_dim(mw, h, w);
934 }
935 w = mw;
936 }
937 }
938 if let Some(mh) = max_h {
939 if mh >= 0 && h > mh {
940 if target_w.is_none() && h > 0 {
941 w = scale_dim(mh, w, h);
942 }
943 h = mh;
944 }
945 }
946 Some((w.max(0), h.max(0)))
947 }
948 "canvas" => {
949 let cur_world = crate::os_lib::css::CUR_WORLD.load(AtomicOrdering::Relaxed);
952 let phys_w = attr_w.filter(|&v| v > 0).unwrap_or(300);
953 let phys_h = attr_h.filter(|&v| v > 0).unwrap_or(150);
954 let cw_phys = if explicit_auto_w { None } else { css_w };
955 let ch_phys = if explicit_auto_h { None } else { css_h };
956 if cur_world != 0 {
957 let resolved_inl = phys_h;
959 let resolved_blk = phys_w;
960 let ci = if explicit_auto_h { None } else { len_value(node, "height").and_then(|v| len_w(&v)) };
961 let cb = if explicit_auto_w { None } else { len_value(node, "width").and_then(|v| len_h(&v)) };
962 let max_inl = len_value(node, "max-height").and_then(|v| len_w(&v));
963 let max_blk = len_value(node, "max-width").and_then(|v| len_h(&v));
964 let (mut inl, mut blk) = match (ci, cb) {
965 (Some(i), Some(b)) => (i, b),
966 (Some(i), None) if resolved_inl > 0 => (i, scale_dim(i, resolved_blk, resolved_inl)),
967 (None, Some(b)) if resolved_blk > 0 => (scale_dim(b, resolved_inl, resolved_blk), b),
968 _ => (resolved_inl, resolved_blk),
969 };
970 if let Some(mi) = max_inl {
971 if mi >= 0 && inl > mi {
972 if cb.is_none() && inl > 0 {
973 blk = scale_dim(mi, blk, inl);
974 }
975 inl = mi;
976 }
977 }
978 if let Some(mb) = max_blk {
979 if mb >= 0 && blk > mb {
980 if ci.is_none() && blk > 0 {
981 inl = scale_dim(mb, inl, blk);
982 }
983 blk = mb;
984 }
985 }
986 Some((inl.max(0), blk.max(0)))
987 } else {
988 let (mut w, mut h) = match (cw_phys, ch_phys) {
989 (Some(w), Some(h)) => (w, h),
990 (Some(w), None) if phys_w > 0 => (w, scale_dim(w, phys_h, phys_w)),
991 (None, Some(h)) if phys_h > 0 => (scale_dim(h, phys_w, phys_h), h),
992 _ => (phys_w, phys_h),
993 };
994 if let Some(mw) = max_w {
995 if mw >= 0 && w > mw {
996 if ch_phys.is_none() && w > 0 {
997 h = scale_dim(mw, h, w);
998 }
999 w = mw;
1000 }
1001 }
1002 if let Some(mh) = max_h {
1003 if mh >= 0 && h > mh {
1004 if cw_phys.is_none() && h > 0 {
1005 w = scale_dim(mh, w, h);
1006 }
1007 h = mh;
1008 }
1009 }
1010 Some((w.max(0), h.max(0)))
1011 }
1012 }
1013 "video" => {
1014 let default_w = 400;
1015 let default_h = 240;
1016 Some((target_w.unwrap_or(default_w), target_h.unwrap_or(default_h)))
1017 }
1018 "iframe" => {
1019 let default_w = 300;
1020 let default_h = 150;
1021 Some((target_w.unwrap_or(default_w), target_h.unwrap_or(default_h)))
1022 }
1023 "input" => {
1024 let default_w = 300;
1025 let default_h = 32;
1026 Some((target_w.unwrap_or(default_w), target_h.unwrap_or(default_h)))
1027 }
1028 "textarea" => {
1029 let default_w = 400;
1030 let default_h = 200;
1031 Some((target_w.unwrap_or(default_w), target_h.unwrap_or(default_h)))
1032 }
1033 "button" => {
1034 let text = get_styled_node_text(node);
1035 let font_size = node
1036 .value_ref("font-size")
1037 .and_then(parse_font_size_u32)
1038 .unwrap_or(16);
1039 let text_w =
1040 crate::kernel::vector_font::get_vector_string_width(&text, font_size) as i32;
1041
1042 let class_val = attributes.get("class").map(|s| s.as_str()).unwrap_or("");
1043 let has_icon =
1044 class_val == "save_btn" || class_val == "load_btn" || class_val == "wrap_btn";
1045 let extra_w = if has_icon { 24 } else { 0 };
1046 let button_w = (text_w + 24 + extra_w).max(120);
1047 let button_h = 36;
1048 Some((target_w.unwrap_or(button_w), target_h.unwrap_or(button_h)))
1049 }
1050 _ => None,
1051 }
1052}
1053
1054pub fn half_leading(line_height: i32, font_size: u32) -> i32 {
1057 (line_height - (font_size as i32 + 4)).max(0) / 2
1058}
1059
1060pub fn parse_line_height<S: AsRef<str>>(val: Option<S>, font_size: u32) -> i32 {
1061 let Some(s) = val else {
1062 return (font_size as i32 + 4).max(12);
1063 };
1064 let t = s.as_ref().trim();
1065 if t.is_empty() || t == "normal" {
1066 return (font_size as i32 + 4).max(12);
1067 }
1068 if let Some(num) = t.strip_suffix("px") {
1069 return num
1070 .trim()
1071 .parse::<i32>()
1072 .unwrap_or((font_size as i32 + 4).max(12));
1073 }
1074 if let Ok(factor) = t.parse::<f32>() {
1075 return (font_size as f32 * factor) as i32;
1076 }
1077 (font_size as i32 + 4).max(12)
1078}
1079
1080pub fn resolve_border_radius_with_font(s: &str, container_w: i32, font_px: f32) -> i32 {
1083 let s = s.trim();
1084 if let Some(num) = s.strip_suffix("px") {
1085 return num.trim().parse::<f32>().map(|v| v as i32).unwrap_or(0);
1086 }
1087 if let Some(num) = s.strip_suffix('%') {
1088 return num
1089 .trim()
1090 .parse::<f32>()
1091 .map(|pct| ((pct / 100.0) * container_w as f32) as i32)
1092 .unwrap_or(0);
1093 }
1094 if let Some(num) = s.strip_suffix("rem") {
1095 return num.trim().parse::<f32>().map(|v| (v * crate::os_lib::css::units::root_font_px()) as i32).unwrap_or(0);
1096 }
1097 if let Some(num) = s.strip_suffix("em") {
1098 return num.trim().parse::<f32>().map(|v| (v * font_px) as i32).unwrap_or(0);
1099 }
1100 s.parse::<f32>().map(|v| v as i32).unwrap_or(0)
1101}
1102
1103pub fn resolve_border_radius(s: &str, container_w: i32) -> i32 {
1104 resolve_border_radius_with_font(s, container_w, 16.0)
1105}
1106
1107pub fn parse_pos_len(v: &str, font_px: f32) -> Option<i32> {
1110 let s = v.trim();
1111 if let Some(num) = s.strip_suffix("px") {
1112 num.trim().parse::<f32>().map(|v| v as i32).ok()
1113 } else if let Some(num) = s.strip_suffix("rem") {
1114 num.trim().parse::<f32>().map(|v| (v * crate::os_lib::css::units::root_font_px()) as i32).ok()
1115 } else if let Some(num) = s.strip_suffix("em") {
1116 num.trim().parse::<f32>().map(|v| (v * font_px) as i32).ok()
1117 } else {
1118 s.parse::<i32>().ok()
1119 }
1120}
1121