1use super::*;
4
5pub(crate) fn data_uri_base64_payload(src: &str) -> Option<&str> {
7 let trimmed = src.trim();
8 let bytes = trimmed.as_bytes();
9 if bytes.len() < 5 || !bytes[..5].eq_ignore_ascii_case(b"data:") {
10 return None;
11 }
12 let needle = b";base64,";
13 bytes
14 .windows(needle.len())
15 .position(|window| window.eq_ignore_ascii_case(needle))
16 .map(|index| &trimmed[index + needle.len()..])
17}
18
19pub(crate) fn decode_base64(input: &str) -> Option<Vec<u8>> {
21 let mut out = Vec::with_capacity(input.len() * 3 / 4);
22 let mut accumulator: u32 = 0;
23 let mut bits: u32 = 0;
24 let mut padding = 0usize;
25 for &byte in input.as_bytes() {
26 if byte.is_ascii_whitespace() {
27 continue;
28 }
29 if byte == b'=' {
30 padding += 1;
31 continue;
32 }
33 if padding > 0 {
34 return None;
35 }
36 let value = match byte {
37 b'A'..=b'Z' => byte - b'A',
38 b'a'..=b'z' => byte - b'a' + 26,
39 b'0'..=b'9' => byte - b'0' + 52,
40 b'+' => 62,
41 b'/' => 63,
42 _ => return None,
43 };
44 accumulator = (accumulator << 6) | u32::from(value);
45 bits += 6;
46 if bits >= 8 {
47 bits -= 8;
48 out.push((accumulator >> bits) as u8);
49 accumulator &= (1u32 << bits) - 1;
50 }
51 }
52 if padding > 2 {
53 return None;
54 }
55 Some(out)
56}
57
58pub(crate) fn png_dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
60 const SIGNATURE: [u8; 8] = [137, 80, 78, 71, 13, 10, 26, 10];
61 if bytes.len() < 24 || bytes[..8] != SIGNATURE || &bytes[12..16] != b"IHDR" {
62 return None;
63 }
64 let width = u32::from_be_bytes([bytes[16], bytes[17], bytes[18], bytes[19]]);
65 let height = u32::from_be_bytes([bytes[20], bytes[21], bytes[22], bytes[23]]);
66 if width == 0 || height == 0 {
67 return None;
68 }
69 Some((width, height))
70}
71
72impl AppRuntime {
73 pub fn mcp_capture_screenshot_png(&mut self) -> Result<Vec<u8>, String> {
75 let overlay = self.mcp_cursor.as_ref().map(|c| (c, self.cursor_theme()));
76 strata_platform::render_to_png_bytes(
77 &self.display_list,
78 self.viewport_width as i32,
79 self.viewport_height as i32,
80 overlay,
81 )
82 }
83
84 pub(crate) fn parse_points_to_path(points_str: &str, closed: bool) -> Option<String> {
86 let coords: Vec<f32> = points_str
87 .replace(',', " ")
88 .split_whitespace()
89 .filter_map(|s| s.parse::<f32>().ok())
90 .collect();
91 if coords.len() < 2 {
92 return None;
93 }
94 let mut path = format!("M {} {}", coords[0], coords[1]);
95 for chunk in coords[2..].chunks(2) {
96 if chunk.len() == 2 {
97 path.push_str(&format!(" L {} {}", chunk[0], chunk[1]));
98 }
99 }
100 if closed {
101 path.push_str(" Z");
102 }
103 Some(path)
104 }
105
106 pub(crate) fn parse_svg_color_attr(value: &str) -> Option<strata_style::types::Color> {
108 let trimmed = value.trim();
109 if let Some(inner) = trimmed
110 .strip_prefix("var(")
111 .and_then(|s| s.strip_suffix(')'))
112 {
113 if let Some((_, fallback)) = inner.split_once(',') {
114 return strata_style::parser::parse_color(fallback.trim());
115 }
116 }
117 strata_style::parser::parse_color(trimmed)
118 }
119
120 pub(crate) fn ellipse_to_cubic_bezier_path(
122 cx: f32,
123 cy: f32,
124 rx: f32,
125 ry: f32,
126 rot_deg: f32,
127 rot_cx: f32,
128 rot_cy: f32,
129 ) -> String {
130 const KAPPA: f32 = 0.552_284_8;
131 let theta = rot_deg.to_radians();
132 let cos_t = theta.cos();
133 let sin_t = theta.sin();
134
135 let dx = cx - rot_cx;
137 let dy = cy - rot_cy;
138 let ecx = rot_cx + dx * cos_t - dy * sin_t;
139 let ecy = rot_cy + dx * sin_t + dy * cos_t;
140
141 let ux = rx * cos_t;
143 let uy = rx * sin_t;
144 let vx = -ry * sin_t;
145 let vy = ry * cos_t;
146
147 let p0 = (ecx + ux, ecy + uy);
148 let p1 = (ecx + vx, ecy + vy);
149 let p2 = (ecx - ux, ecy - uy);
150 let p3 = (ecx - vx, ecy - vy);
151
152 let c0_1 = (p0.0 + KAPPA * vx, p0.1 + KAPPA * vy);
153 let c0_2 = (p1.0 + KAPPA * ux, p1.1 + KAPPA * uy);
154
155 let c1_1 = (p1.0 - KAPPA * ux, p1.1 - KAPPA * uy);
156 let c1_2 = (p2.0 + KAPPA * vx, p2.1 + KAPPA * vy);
157
158 let c2_1 = (p2.0 - KAPPA * vx, p2.1 - KAPPA * vy);
159 let c2_2 = (p3.0 - KAPPA * ux, p3.1 - KAPPA * uy);
160
161 let c3_1 = (p3.0 + KAPPA * ux, p3.1 + KAPPA * uy);
162 let c3_2 = (p0.0 - KAPPA * vx, p0.1 - KAPPA * vy);
163
164 format!(
165 "M {:.3} {:.3} C {:.3} {:.3} {:.3} {:.3} {:.3} {:.3} C {:.3} {:.3} {:.3} {:.3} {:.3} {:.3} C {:.3} {:.3} {:.3} {:.3} {:.3} {:.3} C {:.3} {:.3} {:.3} {:.3} {:.3} {:.3} Z",
166 p0.0, p0.1,
167 c0_1.0, c0_1.1, c0_2.0, c0_2.1, p1.0, p1.1,
168 c1_1.0, c1_1.1, c1_2.0, c1_2.1, p2.0, p2.1,
169 c2_1.0, c2_1.1, c2_2.0, c2_2.1, p3.0, p3.1,
170 c3_1.0, c3_1.1, c3_2.0, c3_2.1, p0.0, p0.1,
171 )
172 }
173
174 pub(crate) fn collect_svg_items_from_blueprint(
176 blueprint: &NodeBlueprint,
177 default_view_box: (f32, f32),
178 inherited_stroke: Option<strata_style::types::Color>,
179 inherited_fill: Option<strata_style::types::Color>,
180 inherited_stroke_width: f32,
181 inherited_linecap: strata_layout::StrokeLineCap,
182 inherited_linejoin: strata_layout::StrokeLineJoin,
183 inherited_dasharray: Vec<f32>,
184 inherited_fill_rule: strata_layout::FillRule,
185 parent_color: strata_style::types::Color,
186 ) -> Vec<strata_layout::SvgItem> {
187 Self::collect_svg_items_with_transform(
188 blueprint,
189 default_view_box,
190 inherited_stroke,
191 inherited_fill,
192 false,
193 false,
194 inherited_stroke_width,
195 inherited_linecap,
196 inherited_linejoin,
197 inherited_dasharray,
198 inherited_fill_rule,
199 parent_color,
200 (0.0, default_view_box.0 * 0.5, default_view_box.1 * 0.5),
201 )
202 }
203
204 #[allow(clippy::too_many_arguments)]
205 pub(crate) fn collect_svg_items_with_transform(
206 blueprint: &NodeBlueprint,
207 default_view_box: (f32, f32),
208 inherited_stroke: Option<strata_style::types::Color>,
209 inherited_fill: Option<strata_style::types::Color>,
210 inherited_stroke_is_current: bool,
211 inherited_fill_is_current: bool,
212 inherited_stroke_width: f32,
213 inherited_linecap: strata_layout::StrokeLineCap,
214 inherited_linejoin: strata_layout::StrokeLineJoin,
215 inherited_dasharray: Vec<f32>,
216 inherited_fill_rule: strata_layout::FillRule,
217 parent_color: strata_style::types::Color,
218 inherited_rotation: (f32, f32, f32),
219 ) -> Vec<strata_layout::SvgItem> {
220 let mut items = Vec::new();
221 match blueprint {
222 NodeBlueprint::Element {
223 tag,
224 attributes,
225 children,
226 ..
227 } => {
228 let mut d = None;
229 let mut stroke = inherited_stroke;
230 let mut fill = inherited_fill;
231 let mut stroke_is_current = inherited_stroke_is_current;
232 let mut fill_is_current = inherited_fill_is_current;
233 let mut stroke_width = inherited_stroke_width;
234 let mut stroke_linecap = inherited_linecap;
235 let mut stroke_linejoin = inherited_linejoin;
236 let mut stroke_dasharray = inherited_dasharray.clone();
237 let mut fill_rule = inherited_fill_rule;
238 let mut rotation = inherited_rotation;
239
240 let mut x1 = 0.0f32;
241 let mut y1 = 0.0f32;
242 let mut x2 = 0.0f32;
243 let mut y2 = 0.0f32;
244 let mut has_line = false;
245
246 let mut cx = 0.0f32;
247 let mut cy = 0.0f32;
248 let mut r = 0.0f32;
249 let mut rx = 0.0f32;
250 let mut ry = 0.0f32;
251 let mut has_circle = false;
252 let mut has_ellipse = false;
253
254 let mut rect_x = 0.0f32;
255 let mut rect_y = 0.0f32;
256 let mut rect_w = 0.0f32;
257 let mut rect_h = 0.0f32;
258 let mut rect_rx = 0.0f32;
259 let mut has_rect = false;
260
261 let mut points = None;
262 let is_polygon = match tag {
263 Tag::Custom(s) => *s == "polygon",
264 _ => false,
265 };
266 let is_rect_tag = match tag {
267 Tag::Custom(s) => *s == "rect",
268 _ => false,
269 };
270 let is_text_tag = match tag {
271 Tag::Custom(s) => matches!(*s, "text" | "tspan"),
272 _ => false,
273 };
274 let mut text_dx = 0.0f32;
275 let mut text_dy = 0.0f32;
276 let mut text_font_size = 12.0f32;
277 let mut text_font_weight = strata_style::types::FontWeight::Normal;
278 let mut text_anchor = strata_style::TextAlign::Left;
279
280 for attr in attributes {
281 if let strata_dom::Attribute::Property { key, value } = attr {
282 match key.as_str() {
283 "d" => d = Some(value.clone()),
284 "stroke" => {
285 let v = value.trim();
286 if v.eq_ignore_ascii_case("currentcolor") {
287 stroke = Some(parent_color);
288 stroke_is_current = true;
289 } else if v.eq_ignore_ascii_case("none") {
290 stroke = None;
291 stroke_is_current = false;
292 } else if let Some(c) = Self::parse_svg_color_attr(v) {
293 stroke = Some(c);
294 stroke_is_current = false;
295 }
296 }
297 "fill" => {
298 let v = value.trim();
299 if v.eq_ignore_ascii_case("currentcolor") {
300 fill = Some(parent_color);
301 fill_is_current = true;
302 } else if v.eq_ignore_ascii_case("none") {
303 fill = None;
304 fill_is_current = false;
305 } else if let Some(c) = Self::parse_svg_color_attr(v) {
306 fill = Some(c);
307 fill_is_current = false;
308 }
309 }
310 "transform" => {
311 let trimmed = value.trim();
312 if let Some(inner) = trimmed
313 .strip_prefix("rotate(")
314 .and_then(|s| s.strip_suffix(')'))
315 {
316 let nums: Vec<f32> = inner
317 .replace(',', " ")
318 .split_whitespace()
319 .filter_map(|s| s.parse::<f32>().ok())
320 .collect();
321 if let Some(°) = nums.first() {
322 let rcx = nums
323 .get(1)
324 .copied()
325 .unwrap_or(default_view_box.0 * 0.5);
326 let rcy = nums
327 .get(2)
328 .copied()
329 .unwrap_or(default_view_box.1 * 0.5);
330 rotation = (rotation.0 + deg, rcx, rcy);
331 }
332 }
333 }
334 "stroke-width" => {
335 if let Ok(w) = value.parse::<f32>() {
336 stroke_width = w;
337 }
338 }
339 "stroke-linecap" => match value.as_str() {
340 "round" => stroke_linecap = strata_layout::StrokeLineCap::Round,
341 "square" => stroke_linecap = strata_layout::StrokeLineCap::Square,
342 "butt" => stroke_linecap = strata_layout::StrokeLineCap::Butt,
343 _ => {}
344 },
345 "stroke-linejoin" => match value.as_str() {
346 "round" => stroke_linejoin = strata_layout::StrokeLineJoin::Round,
347 "bevel" => stroke_linejoin = strata_layout::StrokeLineJoin::Bevel,
348 "miter" => stroke_linejoin = strata_layout::StrokeLineJoin::Miter,
349 _ => {}
350 },
351 "stroke-dasharray" => {
352 stroke_dasharray = value
353 .replace(',', " ")
354 .split_whitespace()
355 .filter_map(|s| s.parse::<f32>().ok())
356 .collect();
357 }
358 "fill-rule" => match value.as_str() {
359 "evenodd" => fill_rule = strata_layout::FillRule::EvenOdd,
360 "nonzero" => fill_rule = strata_layout::FillRule::NonZero,
361 _ => {}
362 },
363 "points" => points = Some(value.clone()),
364 "x1" => {
365 x1 = value.parse().unwrap_or(0.0);
366 has_line = true;
367 }
368 "y1" => {
369 y1 = value.parse().unwrap_or(0.0);
370 has_line = true;
371 }
372 "x2" => {
373 x2 = value.parse().unwrap_or(0.0);
374 has_line = true;
375 }
376 "y2" => {
377 y2 = value.parse().unwrap_or(0.0);
378 has_line = true;
379 }
380 "cx" => {
381 cx = value.parse().unwrap_or(0.0);
382 }
383 "cy" => {
384 cy = value.parse().unwrap_or(0.0);
385 }
386 "r" => {
387 r = value.parse().unwrap_or(0.0);
388 has_circle = true;
389 }
390 "rx" => {
391 let v = value.parse().unwrap_or(0.0);
392 rx = v;
393 rect_rx = v;
394 }
395 "ry" => {
396 ry = value.parse().unwrap_or(0.0);
397 has_ellipse = true;
398 }
399 "x" => {
400 rect_x = value.trim_end_matches("px").parse().unwrap_or(0.0);
401 }
402 "y" => {
403 rect_y = value.trim_end_matches("px").parse().unwrap_or(0.0);
404 }
405 "dx" => {
406 text_dx = value.trim_end_matches("px").parse().unwrap_or(0.0);
407 }
408 "dy" => {
409 text_dy = value.trim_end_matches("px").parse().unwrap_or(0.0);
410 }
411 "font-size" | "fontSize" => {
412 if let Ok(fs) = value.trim().trim_end_matches("px").parse::<f32>() {
413 text_font_size = fs.max(1.0);
414 }
415 }
416 "font-weight" | "fontWeight" => {
417 text_font_weight = match value.trim().to_ascii_lowercase().as_str() {
418 "bold" | "700" | "800" | "900" => {
419 strata_style::types::FontWeight::Bold
420 }
421 "semibold" | "600" => strata_style::types::FontWeight::SemiBold,
422 "medium" | "500" => strata_style::types::FontWeight::Medium,
423 _ => strata_style::types::FontWeight::Normal,
424 };
425 }
426 "text-anchor" | "textAnchor" => {
427 text_anchor = match value.trim().to_ascii_lowercase().as_str() {
428 "middle" => strata_style::TextAlign::Center,
429 "end" => strata_style::TextAlign::Right,
430 _ => strata_style::TextAlign::Left,
431 };
432 }
433 "width" => {
434 rect_w = value.parse().unwrap_or(0.0);
435 has_rect = true;
436 }
437 "height" => {
438 rect_h = value.parse().unwrap_or(0.0);
439 has_rect = true;
440 }
441 _ => {}
442 }
443 }
444 }
445
446 if is_text_tag {
447 let mut text_content = String::new();
448 for child in children {
449 match child {
450 NodeBlueprint::Text(t) => text_content.push_str(t),
451 NodeBlueprint::DynamicText(f) => {
452 text_content.push_str(&f());
453 }
454 _ => {}
455 }
456 }
457 if !text_content.is_empty() {
458 let resolved_fill = fill.or(stroke).or(Some(parent_color));
459 let resolved_is_current =
460 fill_is_current || (fill.is_none() && stroke.is_none());
461 items.push(strata_layout::SvgItem {
462 path_data: String::new(),
463 text: Some(strata_layout::SvgTextData {
464 content: text_content,
465 x: rect_x + text_dx,
466 y: rect_y + text_dy,
467 font_size: text_font_size,
468 font_weight: text_font_weight,
469 text_anchor,
470 }),
471 stroke_color: stroke,
472 fill_color: resolved_fill,
473 stroke_is_current_color: stroke_is_current,
474 fill_is_current_color: resolved_is_current,
475 stroke_width,
476 stroke_linecap,
477 stroke_linejoin,
478 stroke_dasharray: stroke_dasharray.clone(),
479 fill_rule,
480 view_box: default_view_box,
481 });
482 }
483 } else if let Some(path_str) = d {
484 items.push(strata_layout::SvgItem {
485 path_data: path_str,
486 text: None,
487 stroke_color: stroke,
488 fill_color: fill,
489 stroke_is_current_color: stroke_is_current,
490 fill_is_current_color: fill_is_current,
491 stroke_width,
492 stroke_linecap,
493 stroke_linejoin,
494 stroke_dasharray: stroke_dasharray.clone(),
495 fill_rule,
496 view_box: default_view_box,
497 });
498 } else if let Some(pts) = points {
499 if let Some(poly_path) = Self::parse_points_to_path(&pts, is_polygon) {
500 items.push(strata_layout::SvgItem {
501 path_data: poly_path,
502 text: None,
503 stroke_color: stroke,
504 fill_color: fill,
505 stroke_is_current_color: stroke_is_current,
506 fill_is_current_color: fill_is_current,
507 stroke_width,
508 stroke_linecap,
509 stroke_linejoin,
510 stroke_dasharray: stroke_dasharray.clone(),
511 fill_rule,
512 view_box: default_view_box,
513 });
514 }
515 } else if has_line {
516 items.push(strata_layout::SvgItem {
517 path_data: format!("M {} {} L {} {}", x1, y1, x2, y2),
518 text: None,
519 stroke_color: stroke.or(Some(parent_color)),
520 fill_color: None,
521 stroke_is_current_color: stroke_is_current || stroke.is_none(),
522 fill_is_current_color: false,
523 stroke_width,
524 stroke_linecap,
525 stroke_linejoin,
526 stroke_dasharray: stroke_dasharray.clone(),
527 fill_rule,
528 view_box: default_view_box,
529 });
530 } else if has_circle && r > 0.0 {
531 items.push(strata_layout::SvgItem {
532 path_data: Self::ellipse_to_cubic_bezier_path(
533 cx, cy, r, r, rotation.0, rotation.1, rotation.2,
534 ),
535 text: None,
536 stroke_color: stroke,
537 fill_color: fill,
538 stroke_is_current_color: stroke_is_current,
539 fill_is_current_color: fill_is_current,
540 stroke_width,
541 stroke_linecap,
542 stroke_linejoin,
543 stroke_dasharray: stroke_dasharray.clone(),
544 fill_rule,
545 view_box: default_view_box,
546 });
547 } else if has_ellipse && rx > 0.0 && ry > 0.0 {
548 items.push(strata_layout::SvgItem {
549 path_data: Self::ellipse_to_cubic_bezier_path(
550 cx, cy, rx, ry, rotation.0, rotation.1, rotation.2,
551 ),
552 text: None,
553 stroke_color: stroke,
554 fill_color: fill,
555 stroke_is_current_color: stroke_is_current,
556 fill_is_current_color: fill_is_current,
557 stroke_width,
558 stroke_linecap,
559 stroke_linejoin,
560 stroke_dasharray: stroke_dasharray.clone(),
561 fill_rule,
562 view_box: default_view_box,
563 });
564 } else if is_rect_tag && has_rect && rect_w > 0.0 && rect_h > 0.0 {
565 let rect_path = if rect_rx > 0.0 {
566 const K: f32 = 0.552_284_8;
567 let r = rect_rx.min(rect_w * 0.5).min(rect_h * 0.5);
568 let x0 = rect_x;
569 let y0 = rect_y;
570 let x1 = rect_x + rect_w;
571 let y1 = rect_y + rect_h;
572 let c = r * (1.0 - K);
573 format!(
574 "M {:.3} {:.3} L {:.3} {:.3} C {:.3} {:.3} {:.3} {:.3} {:.3} {:.3} L {:.3} {:.3} C {:.3} {:.3} {:.3} {:.3} {:.3} {:.3} L {:.3} {:.3} C {:.3} {:.3} {:.3} {:.3} {:.3} {:.3} L {:.3} {:.3} C {:.3} {:.3} {:.3} {:.3} {:.3} {:.3} Z",
575 x0 + r, y0,
576 x1 - r, y0,
577 x1 - c, y0, x1, y0 + c, x1, y0 + r,
578 x1, y1 - r,
579 x1, y1 - c, x1 - c, y1, x1 - r, y1,
580 x0 + r, y1,
581 x0 + c, y1, x0, y1 - c, x0, y1 - r,
582 x0, y0 + r,
583 x0, y0 + c, x0 + c, y0, x0 + r, y0,
584 )
585 } else {
586 format!(
587 "M {} {} h {} v {} h {} Z",
588 rect_x, rect_y, rect_w, rect_h, -rect_w
589 )
590 };
591 items.push(strata_layout::SvgItem {
592 path_data: rect_path,
593 text: None,
594 stroke_color: stroke,
595 fill_color: fill,
596 stroke_is_current_color: stroke_is_current,
597 fill_is_current_color: fill_is_current,
598 stroke_width,
599 stroke_linecap,
600 stroke_linejoin,
601 stroke_dasharray: stroke_dasharray.clone(),
602 fill_rule,
603 view_box: default_view_box,
604 });
605 }
606
607 for child in children {
609 let child_items = Self::collect_svg_items_with_transform(
610 child,
611 default_view_box,
612 stroke,
613 fill,
614 stroke_is_current,
615 fill_is_current,
616 stroke_width,
617 stroke_linecap,
618 stroke_linejoin,
619 stroke_dasharray.clone(),
620 fill_rule,
621 parent_color,
622 rotation,
623 );
624 items.extend(child_items);
625 }
626 }
627 NodeBlueprint::Fragment(children) => {
628 for child in children {
629 let child_items = Self::collect_svg_items_with_transform(
630 child,
631 default_view_box,
632 inherited_stroke,
633 inherited_fill,
634 inherited_stroke_is_current,
635 inherited_fill_is_current,
636 inherited_stroke_width,
637 inherited_linecap,
638 inherited_linejoin,
639 inherited_dasharray.clone(),
640 inherited_fill_rule,
641 parent_color,
642 inherited_rotation,
643 );
644 items.extend(child_items);
645 }
646 }
647 _ => {}
648 }
649 items
650 }
651}