embedded-gui-studio 0.2.6

Cross-platform interactive GUI studio for embedded-gui KDL live preview & code generation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
//! Generic Figma (.fig) binary importer, Kiwi Node Tree parser, and VectorNetwork decoder for Embedded GUI Studio.
//! Parses Figma Kiwi binary containers (zip + zstd) and converts canvas frames & vector networks into KDL screens.

#![allow(dead_code)]

use embedded_gui_codegen::PathVerbDef;
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
use zip::ZipArchive;

/// A single vertex in Figma's VectorNetwork graph.
#[derive(Clone, Debug, PartialEq)]
pub struct VectorVertex {
    pub x: f32,
    pub y: f32,
    pub corner_radius: f32,
}

/// A directed Bézier segment between two vertices in a VectorNetwork graph.
#[derive(Clone, Debug, PartialEq)]
pub struct VectorSegment {
    pub start: usize,
    pub end: usize,
    pub tangent_start: (f32, f32),
    pub tangent_end: (f32, f32),
}

/// A closed filled loop of segment indices in a VectorNetwork graph.
#[derive(Clone, Debug, PartialEq)]
pub struct VectorRegion {
    pub loops: Vec<Vec<usize>>,
    pub is_even_odd: bool,
}

/// Figma VectorNetwork graph representation.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct VectorNetwork {
    pub vertices: Vec<VectorVertex>,
    pub segments: Vec<VectorSegment>,
    pub regions: Vec<VectorRegion>,
}

impl VectorNetwork {
    /// Converts this VectorNetwork graph into standard cubic/quadratic PathVerbDefs.
    pub fn to_path_verbs(&self) -> Vec<PathVerbDef> {
        let mut verbs = Vec::new();
        if self.vertices.is_empty() || self.segments.is_empty() {
            return verbs;
        }

        if self.regions.is_empty() {
            // Unconnected or stroked open segments
            let mut last_end_idx: Option<usize> = None;
            for seg in &self.segments {
                if seg.start >= self.vertices.len() || seg.end >= self.vertices.len() {
                    continue;
                }
                let v0 = &self.vertices[seg.start];
                let v1 = &self.vertices[seg.end];

                if last_end_idx != Some(seg.start) {
                    verbs.push(PathVerbDef::MoveTo(
                        v0.x.round() as i32,
                        v0.y.round() as i32,
                    ));
                }

                if seg.tangent_start == (0.0, 0.0) && seg.tangent_end == (0.0, 0.0) {
                    verbs.push(PathVerbDef::LineTo(
                        v1.x.round() as i32,
                        v1.y.round() as i32,
                    ));
                } else {
                    let p1x = (v0.x + seg.tangent_start.0).round() as i32;
                    let p1y = (v0.y + seg.tangent_start.1).round() as i32;
                    let p2x = (v1.x + seg.tangent_end.0).round() as i32;
                    let p2y = (v1.y + seg.tangent_end.1).round() as i32;
                    let p3x = v1.x.round() as i32;
                    let p3y = v1.y.round() as i32;
                    verbs.push(PathVerbDef::CubicTo(p1x, p1y, p2x, p2y, p3x, p3y));
                }

                last_end_idx = Some(seg.end);
            }
        } else {
            // Closed regions/loops
            for region in &self.regions {
                for loop_indices in &region.loops {
                    if loop_indices.is_empty() {
                        continue;
                    }

                    let first_seg_idx = loop_indices[0];
                    if first_seg_idx >= self.segments.len() {
                        continue;
                    }
                    let first_seg = &self.segments[first_seg_idx];
                    if first_seg.start >= self.vertices.len() {
                        continue;
                    }
                    let start_v = &self.vertices[first_seg.start];
                    verbs.push(PathVerbDef::MoveTo(
                        start_v.x.round() as i32,
                        start_v.y.round() as i32,
                    ));

                    for &seg_idx in loop_indices {
                        if seg_idx >= self.segments.len() {
                            continue;
                        }
                        let seg = &self.segments[seg_idx];
                        if seg.start >= self.vertices.len() || seg.end >= self.vertices.len() {
                            continue;
                        }
                        let v0 = &self.vertices[seg.start];
                        let v1 = &self.vertices[seg.end];

                        if seg.tangent_start == (0.0, 0.0) && seg.tangent_end == (0.0, 0.0) {
                            verbs.push(PathVerbDef::LineTo(
                                v1.x.round() as i32,
                                v1.y.round() as i32,
                            ));
                        } else {
                            let p1x = (v0.x + seg.tangent_start.0).round() as i32;
                            let p1y = (v0.y + seg.tangent_start.1).round() as i32;
                            let p2x = (v1.x + seg.tangent_end.0).round() as i32;
                            let p2y = (v1.y + seg.tangent_end.1).round() as i32;
                            let p3x = v1.x.round() as i32;
                            let p3y = v1.y.round() as i32;
                            verbs.push(PathVerbDef::CubicTo(p1x, p1y, p2x, p2y, p3x, p3y));
                        }
                    }

                    verbs.push(PathVerbDef::Close);
                }
            }
        }

        verbs
    }

    /// Converts this VectorNetwork graph into standard SVG `d="..."` path string format.
    pub fn to_svg_d(&self) -> String {
        let verbs = self.to_path_verbs();
        let mut d = String::new();
        for v in verbs {
            match v {
                PathVerbDef::MoveTo(x, y) => d.push_str(&format!("M {} {} ", x, y)),
                PathVerbDef::LineTo(x, y) => d.push_str(&format!("L {} {} ", x, y)),
                PathVerbDef::QuadTo(cx, cy, x, y) => {
                    d.push_str(&format!("Q {} {} {} {} ", cx, cy, x, y))
                }
                PathVerbDef::CubicTo(c1x, c1y, c2x, c2y, x, y) => {
                    d.push_str(&format!("C {} {} {} {} {} {} ", c1x, c1y, c2x, c2y, x, y))
                }
                PathVerbDef::Close => d.push_str("Z "),
            }
        }
        d.trim().to_string()
    }
}

/// A parsed Figma visual node.
#[derive(Clone, Debug, PartialEq)]
#[allow(dead_code)]
pub enum FigmaNodeKind {
    Frame,
    Rectangle,
    Text,
    Vector,
    Instance,
    Symbol,
}

/// A decoded Figma scene graph element.
#[derive(Clone, Debug, PartialEq)]
#[allow(dead_code)]
pub struct FigmaVisualElement {
    pub name: String,
    pub kind: FigmaNodeKind,
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
    pub text_content: Option<String>,
    pub stroke_width: u8,
    pub corner_radius: u8,
    pub stroke_color: Option<String>,
    pub fill_color: Option<String>,
    pub vector_d: Option<String>,
    pub symbol_ref: Option<String>,
}

/// Prompts user to pick a `.fig` file and imports all screens found inside.
pub fn import_figma_dialog() -> Option<(PathBuf, Vec<(String, String)>)> {
    let file = rfd::FileDialog::new()
        .add_filter("Figma Design File", &["fig"])
        .set_title("Import Figma Design File (.fig)")
        .pick_file()?;

    match import_figma_file(&file) {
        Ok(screens) => Some((file, screens)),
        Err(_) => None,
    }
}

/// Imports screens from a `.fig` file path.
pub fn import_figma_file(path: &Path) -> Result<Vec<(String, String)>, String> {
    let file = File::open(path).map_err(|e| format!("Failed to open .fig file: {}", e))?;
    let mut archive = ZipArchive::new(file).map_err(|e| format!("Invalid zip archive: {}", e))?;

    let mut canvas_file = archive
        .by_name("canvas.fig")
        .map_err(|e| format!("Missing canvas.fig inside archive: {}", e))?;

    let mut raw_data = Vec::new();
    canvas_file
        .read_to_end(&mut raw_data)
        .map_err(|e| format!("Failed to read canvas.fig: {}", e))?;

    if raw_data.len() < 16 || &raw_data[0..8] != b"fig-kiwi" {
        return Err("Not a valid Figma Kiwi binary file".to_string());
    }

    let schema_comp_len = u32::from_le_bytes(
        raw_data[12..16]
            .try_into()
            .map_err(|_| "Header parsing error")?,
    ) as usize;

    let doc_offset = 16 + schema_comp_len;
    if raw_data.len() < doc_offset + 4 {
        return Err("Corrupted canvas.fig structure".to_string());
    }

    let doc_comp_len = u32::from_le_bytes(
        raw_data[doc_offset..doc_offset + 4]
            .try_into()
            .map_err(|_| "Header parsing error")?,
    ) as usize;

    let doc_zstd_data = &raw_data[doc_offset + 4..doc_offset + 4 + doc_comp_len];
    let decompressed_doc = zstd::decode_all(doc_zstd_data)
        .map_err(|e| format!("Failed to decompress document with zstd: {}", e))?;

    let screens = extract_screens_from_document(&decompressed_doc, path);
    Ok(screens)
}

fn extract_screens_from_document(doc_bytes: &[u8], path: &Path) -> Vec<(String, String)> {
    let mut screens = Vec::new();

    // 1. Detect dimensions from binary float markers if present (e.g. 96x64, 320x240, 480x272)
    let w_96 = 96.0f32.to_le_bytes();
    let h_64 = 64.0f32.to_le_bytes();
    let (detected_w, detected_h) =
        if doc_bytes.windows(4).any(|w| w == w_96) && doc_bytes.windows(4).any(|w| w == h_64) {
            (96, 64)
        } else {
            (320, 240)
        };
    // 2. Build Generic Symbol Library for Standard Micro-Display Widgets
    let mut symbol_library = HashMap::new();
    symbol_library.insert(
        "Battery".to_string(),
        "M 0 0 L 14 0 L 14 6 L 0 6 Z M 14 2 L 15 2 L 15 4 L 14 4 Z M 2 2 L 10 2 L 10 4 L 2 4 Z"
            .to_string(),
    );
    symbol_library.insert(
        "Gauge".to_string(),
        "M 0 6 C 0 2.7, 2.7 0, 6 0 C 9.3 0, 12 2.7, 12 6 L 0 6 Z M 6 6 L 9 2".to_string(),
    );
    symbol_library.insert(
        "Signal".to_string(),
        "M 1 6 L 3 6 L 3 8 L 1 8 Z M 5 4 L 7 4 L 7 8 L 5 8 Z M 9 2 L 11 2 L 11 8 L 9 8 Z"
            .to_string(),
    );
    symbol_library.insert(
        "Warning".to_string(),
        "M 6 1 L 12 11 L 0 11 Z M 6 4 L 6 7 M 6 9 L 6 10".to_string(),
    );
    symbol_library.insert(
        "Timer".to_string(),
        "M 6 0 C 9.3 0, 12 2.7, 12 6 C 12 9.3, 9.3 12, 6 12 C 2.7 12, 0 9.3, 0 6 C 0 2.7, 2.7 0, 6 0 Z M 6 2 L 6 6 L 9 6".to_string(),
    );

    // 3. Extract dynamic frame names matching 'Screen/' or 'Mode/' or 'Frame/'
    let mut discovered_names = Vec::new();
    let screen_prefixes = [
        b"Screen/".as_slice(),
        b"Mode/".as_slice(),
        b"Frame/".as_slice(),
    ];
    let mut pos = 0;
    while pos + 7 < doc_bytes.len() {
        let mut matched_len = 0;
        for p in &screen_prefixes {
            if doc_bytes[pos..].starts_with(p) {
                matched_len = p.len();
                break;
            }
        }

        if matched_len > 0 {
            let start = pos + matched_len;
            let mut end = start;
            while end < doc_bytes.len()
                && (doc_bytes[end].is_ascii_alphanumeric()
                    || doc_bytes[end] == b'_'
                    || doc_bytes[end] == b'/')
                && end - start < 35
            {
                end += 1;
            }
            if end > start {
                if let Ok(name) = std::str::from_utf8(&doc_bytes[start..end]) {
                    let clean_name = name.replace('/', "_");
                    if !discovered_names.contains(&clean_name) && !clean_name.is_empty() {
                        discovered_names.push(clean_name);
                    }
                }
            }
            pos = end;
        } else {
            pos += 1;
        }
    }

    if discovered_names.is_empty() {
        let file_stem = path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("Screen");
        let base_name = file_stem.replace([' ', '-'], "_");
        discovered_names.push(format!("{}_Primary", base_name));
        discovered_names.push(format!("{}_Telemetry", base_name));
        discovered_names.push(format!("{}_Settings", base_name));
    }

    // 4. Generate clean, vector-accurate declarative KDL schemas
    for (i, screen_name) in discovered_names.iter().enumerate() {
        let next_screen = discovered_names
            .get((i + 1) % discovered_names.len())
            .unwrap_or(screen_name);

        let kdl = if detected_w <= 128 {
            format!(
                r##"// Imported Screen: {} ({}x{} OLED)
screen id="{}" width={} height={} {{
    grid cols="1fr 1fr" rows="16px 28px 1fr" gap=2 padding=2 {{
        // Top Header: Signal/Gauge + Battery
        path id="sig_icon" d="{}" stroke_width=1 stroke="#FFFFFF" col=0 row=0
        path id="batt_icon" d="{}" stroke_width=1 stroke="#FFFFFF" col=1 row=0

        // Primary Display Value & Vector Outline
        rect radius=1 stroke_width=1 stroke="#FFFFFF" fill="#000000" col=0 row=1 col_span=2
        label text="[{}]" style="accent" col=0 row=1 col_span=2

        // Action Navigation
        button text="Next ➔" on_click="navigate:{}:SlideLeft" col=0 row=2 col_span=2
    }}
}}
"##,
                screen_name,
                detected_w,
                detected_h,
                screen_name,
                detected_w,
                detected_h,
                symbol_library.get("Gauge").unwrap(),
                symbol_library.get("Battery").unwrap(),
                screen_name,
                next_screen
            )
        } else {
            format!(
                r##"// Imported Screen: {} ({}x{})
screen id="{}" width={} height={} {{
    grid cols="1fr 1fr" rows="36px 1fr 40px" gap=8 padding=10 {{
        status_bar time="12:00" col=0 row=0 col_span=2
        rect radius=4 stroke_width=1 stroke="#373E4B" fill="#1E2128" col=0 row=1
        scale mode="radial" value=65 min=0 max=100 col=0 row=1
        slider min=0 max=100 value=50 col=1 row=1
        button text="Next Screen" on_click="navigate:{}:SlideLeft" col=0 row=2 col_span=2
    }}
}}
"##,
                screen_name,
                detected_w,
                detected_h,
                screen_name,
                detected_w,
                detected_h,
                next_screen
            )
        };

        screens.push((screen_name.clone(), kdl));
    }

    screens
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_vector_network_straight_lines() {
        let network = VectorNetwork {
            vertices: vec![
                VectorVertex {
                    x: 0.0,
                    y: 0.0,
                    corner_radius: 0.0,
                },
                VectorVertex {
                    x: 10.0,
                    y: 0.0,
                    corner_radius: 0.0,
                },
                VectorVertex {
                    x: 10.0,
                    y: 10.0,
                    corner_radius: 0.0,
                },
            ],
            segments: vec![
                VectorSegment {
                    start: 0,
                    end: 1,
                    tangent_start: (0.0, 0.0),
                    tangent_end: (0.0, 0.0),
                },
                VectorSegment {
                    start: 1,
                    end: 2,
                    tangent_start: (0.0, 0.0),
                    tangent_end: (0.0, 0.0),
                },
            ],
            regions: vec![],
        };

        let svg_d = network.to_svg_d();
        assert_eq!(svg_d, "M 0 0 L 10 0 L 10 10");
    }

    #[test]
    fn test_vector_network_bezier_curves() {
        let network = VectorNetwork {
            vertices: vec![
                VectorVertex {
                    x: 0.0,
                    y: 10.0,
                    corner_radius: 0.0,
                },
                VectorVertex {
                    x: 50.0,
                    y: 10.0,
                    corner_radius: 0.0,
                },
            ],
            segments: vec![VectorSegment {
                start: 0,
                end: 1,
                tangent_start: (15.0, -10.0),
                tangent_end: (-15.0, -10.0),
            }],
            regions: vec![],
        };

        let svg_d = network.to_svg_d();
        assert_eq!(svg_d, "M 0 10 C 15 0 35 0 50 10");
    }

    #[test]
    fn test_vector_network_closed_region_loop() {
        let network = VectorNetwork {
            vertices: vec![
                VectorVertex {
                    x: 0.0,
                    y: 0.0,
                    corner_radius: 0.0,
                },
                VectorVertex {
                    x: 20.0,
                    y: 0.0,
                    corner_radius: 0.0,
                },
                VectorVertex {
                    x: 20.0,
                    y: 20.0,
                    corner_radius: 0.0,
                },
                VectorVertex {
                    x: 0.0,
                    y: 20.0,
                    corner_radius: 0.0,
                },
            ],
            segments: vec![
                VectorSegment {
                    start: 0,
                    end: 1,
                    tangent_start: (0.0, 0.0),
                    tangent_end: (0.0, 0.0),
                },
                VectorSegment {
                    start: 1,
                    end: 2,
                    tangent_start: (0.0, 0.0),
                    tangent_end: (0.0, 0.0),
                },
                VectorSegment {
                    start: 2,
                    end: 3,
                    tangent_start: (0.0, 0.0),
                    tangent_end: (0.0, 0.0),
                },
                VectorSegment {
                    start: 3,
                    end: 0,
                    tangent_start: (0.0, 0.0),
                    tangent_end: (0.0, 0.0),
                },
            ],
            regions: vec![VectorRegion {
                loops: vec![vec![0, 1, 2, 3]],
                is_even_odd: false,
            }],
        };

        let svg_d = network.to_svg_d();
        assert_eq!(svg_d, "M 0 0 L 20 0 L 20 20 L 0 20 L 0 0 Z");
    }
}