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