depict-desktop 0.3.0

Desktop port of Depict
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
use std::borrow::Cow;
use std::io::{self};
use std::panic::catch_unwind;

use depict::graph_drawing::error::{Error, Kind};
use depict::graph_drawing::eval::{Val, Body};
use depict::graph_drawing::frontend::log::Record;
use depict::graph_drawing::frontend::dom::{draw, Drawing};
use depict::graph_drawing::frontend::dioxus::{render, as_data_svg};

use dioxus::prelude::*;
use dioxus_desktop::{self, Config, WindowBuilder};

use futures::StreamExt;

// use dioxus_desktop::tao::dpi::{LogicalSize};
// use dioxus_desktop::use_window;
use tao::dpi::LogicalSize;

use indoc::indoc;

const PLACEHOLDER: &str = indoc!("
person microwave food: open, start, stop / beep : heat
person food: stir
");

pub struct AppProps {
}

pub fn render_one<P>(cx: Scope<P>, record: Record) -> Option<VNode> {
    match record {
        Record::String{name, ty: _ty, names, val} => {
            // let ty = ty.unwrap_or("None".into());
            let classes = names.iter().map(|n| format!("highlight_{n}")).collect::<Vec<_>>().join(" ");
            // let key = format!("debug_{ty}_{name}");
            // eprintln!("KEY: {key}");
            cx.render(rsx!{
                div {
                    // key: "debug_{ty}_{name}",
                    class: "{classes}",
                    name.map(|name| rsx!{
                        div {
                            style: "font-weight: 700;",
                            "{name}"
                        }
                    }),
                    div {
                        style: "white-space: pre; margin-left: 10px;",
                        "{val}"
                    }
                }
            })
        },
        Record::Svg{ name, ty: _ty, names, val } => {
            let classes = names.iter().map(|n| format!("highlight_{n}")).collect::<Vec<_>>().join(" ");
            cx.render(rsx!{
                div {
                    class: "{classes}",
                    name.map(|name| rsx!{
                        div {
                            style: "font-weight: 700;",
                            "{name}"
                        }
                    }),
                    div {
                        style: "white-space: pre; margin-left: 10px;",
                        img {
                            src: "{val}",
                        }
                    }
                }
            })
        },
        _ => cx.render(rsx!{""}),
    }
}

fn render_many<P>(cx: Scope<P>, record: Record) -> Option<VNode> {
    match record {
        Record::String{..} => render_one(cx, record),
        Record::Svg{..} => render_one(cx, record),
        Record::Group{name, ty, names, val} => {
            let classes = names.iter().map(|n| format!("highlight_{n}")).collect::<Vec<_>>().join(" ");
            // let ty2 = ty.clone().unwrap_or("None".into());
            // let key = format!("debug_{ty2}_{name}");
            // eprintln!("KEY: {key}");
            cx.render(rsx!{
                div {
                    style: "margin-right: 20px;",
                    // key: "debug_{ty2}_{name}",
                    class: "{classes}",
                    details {
                        style: "padding-left: 4px;",
                        open: "true",
                        summary {
                            style: "white-space: nowrap;",
                            name.map(|name| rsx!{
                                span {
                                    "{name}: "
                                }
                            }),
                            ty.map(|ty| rsx!{
                                span {
                                    style: "font-weight: 700;",
                                    "{ty}",
                                }
                            }),
                        }
                        div {
                            style: "white-space: pre; margin-left: 10px; border-left: 1px gray solid;",
                            val.into_iter().map(|r| render_many(cx, r))
                        }
                    }
                }
            })
        },
    }
}

pub fn render_logs<P>(cx: Scope<P>, drawing: Drawing) -> Option<VNode> {
    let logs = drawing.logs;
    cx.render(rsx!{
        logs.into_iter().map(|r| render_many(cx, r))
    })
}

pub fn parse_highlights<'s>(data: &'s str) -> Result<Val<Cow<'s, str>>, Error> {
    use depict::parser::{Parser, Token};
    use depict::graph_drawing::eval::{eval, index, resolve};
    use logos::Logos;
    use std::collections::HashMap;

    if data.trim().is_empty() {
        return Ok(Val::default())
    }

    let mut p = Parser::new();
    let mut lex = Token::lexer(data);
    while let Some(tk) = lex.next() {
        p.parse(tk)
            .map_err(|_| {
                Kind::PomeloError{span: lex.span(), text: lex.slice().into()}
            })?
    }

    let items = p.end_of_input()
        .map_err(|_| {
            Kind::PomeloError{span: lex.span(), text: lex.slice().into()}
        })?;

    // eprintln!("HIGHLIGHT PARSE {items:#?}");

    let mut val = eval(&items[..]);

    // eprintln!("HIGHLIGHT EVAL {val:#?}");

    let mut scopes = HashMap::new();
    let val2 = val.clone();
    index(&val2, &mut vec![], &mut scopes);
    resolve(&mut val, &mut vec![], &scopes);

    // eprintln!("HIGHLIGHT SCOPES: {scopes:#?}");
    // eprintln!("HIGHLIGHT RESOLVE: {val:#?}");
    Ok(val)
}

pub fn app(cx: Scope<AppProps>) -> Element {
    let model = use_state(&cx, || String::from(PLACEHOLDER));
    let drawing = use_state(&cx, Drawing::default);
    let highlight = use_state(&cx, || String::from(""));

    let drawing_sender = use_coroutine(cx, |mut rx| {
        let drawing = drawing.clone();
        async move {
            while let Some(msg) = rx.next().await {
                drawing.set(msg);
            }
        }
    });

    let model_sender = use_coroutine(cx, |mut rx| {
        let drawing_sender = drawing_sender.clone();
        async move {
            let mut prev_model: Option<String> = None;
            while let Some(model) = rx.next().await {
                if Some(&model) != prev_model.as_ref() {
                    let model_str: &str = &model;
                    let nodes = if model_str.trim().is_empty() {
                        Ok(Ok(Drawing::default()))
                    } else {
                        catch_unwind(|| {
                            draw(model.clone())
                        })
                    };
                    let model = model.clone();
                    match nodes {
                        Ok(Ok(drawing)) => {
                            prev_model = Some(model);
                            drawing_sender.send(drawing);
                        },
                        Ok(Err(err)) => {
                            eprintln!("DRAWING ERROR: {err:#?}");
                        }
                        Err(_) => {
                            eprintln!("PANIC: {nodes:#?}");
                        }
                    }
                }
            }
        }
    });

    // let desktop = cx.consume_context::<dioxus_desktop::desktop_context::DesktopContext>().unwrap();
    // desktop.devtool();
    // let window = use_window(&cx);
    // window.devtool();

    let nodes = render(cx, drawing.get().clone());
    let logs = render_logs(cx, drawing.get().clone());

    let status_v = drawing.get().status_v;
    let status_h = drawing.get().status_h;
    let collisions = &drawing.get().collisions;
    let status_c = collisions.len();

    let show_logs = use_state(&cx, || {
        #[cfg(debug_assertions)]
        return true;
        #[cfg(not(debug_assertions))]
        return false;
    });

    let show_collisions = use_state(&cx, ||{
        #[cfg(debug_assertions)]
        return true;
        #[cfg(not(debug_assertions))]
        return false;
    });

    model_sender.send(model.get().clone());

    let viewbox_width = drawing.get().viewbox_width;
    let viewbox_height = drawing.get().viewbox_height;
    let _crossing_number = cx.render(rsx!(match drawing.get().crossing_number {
        Some(cn) => rsx!(span { "{cn}" }),
        None => rsx!(div{}),
    }));

    let data_svg = as_data_svg(drawing.get().clone());

    // parse and eval the highlight string to get a sub-model to highlight
    let highlight_styles = match parse_highlights(&highlight.get()[..]) {
        Ok(Val::Process { body: Some(Body::All(bs)), .. }) => {
            // cx.render(rsx!{"OOPS"})
            cx.render(rsx!{
                bs.iter().map(|b| {
                    match b {
                        Val::Process { name: Some(pname), .. } | Val::Process { label: Some(pname), .. } => {
                            let style = format!(".box.highlight_{pname} {{ background-color: red; color: white; }} .highlight_{pname} {{ color: red; }}");
                            // eprintln!("STYLE: {style}");
                            rsx!{
                                style {
                                    "{style}"
                                }
                            }
                        },
                        Val::Chain{ name: Some(cname), .. } => {
                            let style = format!(".arrow.highlight_{cname} {{ color: red; }}");
                            // eprintln!("STYLE: {style}");
                            rsx!{
                                style {
                                    "{style}"
                                }
                            }
                        }
                        Val::Chain{ path, .. } => {
                            rsx!{
                                path.windows(2).map(|pq| {
                                    match &pq[0] {
                                        Val::Process { name: Some(pname), .. } | Val::Process { label: Some(pname), .. } => {
                                            match &pq[1] {
                                                Val::Process { name: Some(qname), .. } | Val::Process { label: Some(qname), .. } => {
                                                    let style = format!(".arrow.{pname}_{qname} svg > path {{ stroke: red; }}");
                                                    // eprintln!("STYLE: {style}");
                                                    rsx!{
                                                        style {
                                                            "{style}"
                                                        }
                                                    }
                                                }
                                                _ => {
                                                    // eprintln!("UNSTYLE CHAIN WINDOW: {pq:#?}");
                                                    rsx!{()}
                                                }
                                            }
                                        }
                                        _ => {
                                            // eprintln!("UNSTYLE CHAIN: {pq:#?}");
                                            rsx!{()}
                                        }
                                    }
                                })
                            }
                        }
                        _ => {
                            // eprintln!("UNSTYLE: {b:#?}");
                            rsx!{()}
                        }
                    }
                })
            })
        },
        Err(e) => {
            let e = format!("{e:#?}");
            cx.render(rsx!{
                div {
                    e
                }
            })
        },
        _ => {
            cx.render(rsx!{()})
        }
    };

    let mut colliding_rects = collisions.iter().flat_map(|(ri, rj)| vec![ri, rj]).collect::<Vec<_>>();
    colliding_rects.sort_by_key(|r| &r.id);
    colliding_rects.dedup();

    let num_rects = colliding_rects.len();
    let collision_nodes = colliding_rects.iter().enumerate().filter_map(|(n, r)| {
        let color = colorous::COOL.eval_rational(n, num_rects);
        let w = r.r - r.l;
        let h = r.b - r.t;
        cx.render(rsx!{
            div {
                key: "{r.id}_col",
                style: "position: absolute; display: border-box; left: {r.l}px; top: {r.t}px; width: {w}px; height: {h}px; z-index: 100; border: 1px solid rgba({color.r}, {color.g}, {color.b}, 0.9); background: rgba({color.r}, {color.b}, {color.g}, 0.5);",
            }
        })
    }).into_iter().collect::<Vec<_>>().into_iter();

    let syntax_guide = depict::graph_drawing::frontend::dioxus::syntax_guide(cx)?;

    let style_default = "
        svg { stroke: currentColor; stroke-width: 1; }
        .fake svg { stroke: hsl(0, 0%, 50%); }
        path { stroke-dasharray: none; }
        .arrow.fake path { stroke-dasharray: 5; }
        .keyword { font-weight: bold; color: rgb(207, 34, 46); }
        .example { font-size: 0.625rem; font-family: ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,\"Liberation Mono\",\"Courier New\",monospace; }
    ";
    cx.render(rsx!{
        head {
            style {
                "{style_default}"
            }
            highlight_styles
        }
        div {
            // key: "editor",
            style: "width: 100%; z-index: 20; padding: 1rem;",
            div {
                style: "max-width: 36rem; margin-left: auto; margin-right: auto; flex-direction: column;",
                div {
                    // key: "editor_label",
                    "Model"
                }
                div {
                    // key: "editor_editor",
                    textarea {
                        style: "border-width: 1px; border-color: #000;",
                        rows: "6",
                        cols: "80",
                        autocomplete: "off",
                        // autocorrect: "off",
                        // autocapitalize: "off",
                        "autocapitalize": "off",
                        autofocus: "true",
                        spellcheck: "false",
                        // placeholder: "",
                        oninput: move |e| {
                            model.set(e.value.clone());
                            model_sender.send(e.value.clone());
                        },
                        "{model}"
                    }
                }
                div {
                    "Sub-model to Highlight"
                }
                div {
                    textarea {
                        style: "border-width 1px; border-color: #000;",
                        rows: "1",
                        cols: "80",
                        autocomplete: "off",
                        "autocapitalize": "off",
                        spellcheck: "false",
                        oninput: move |e| {
                            highlight.set(e.value.clone());
                        }
                    }
                }
                div {
                    style: "display: flex; flex-direction: row; justify-content: space-between;",
                    syntax_guide,
                    div {
                        details {
                            style: "display: flex; flex-direction: column; align-self: end; font-size: 0.875rem; line-height: 1.25rem;",
                            summary {
                                span {
                                    "Tools",
                                }
                            },
                            // EXPORT
                            div {
                                a {
                                    href: "{data_svg}",
                                    download: "depict.svg",
                                    "Export SVG"
                                }
                            }
                            // LICENSES
                            div {
                                details {
                                    summary {
                                        style: "font-size: 0.875rem; line-height: 1.25rem; --tw-text-opacity: 1; color: rgba(156, 163, 175, var(--tw-text-opacity));",
                                        "Licenses",
                                    },
                                    div {
                                        depict::licenses::LICENSES.dirs().map(|dir| {
                                            let path = dir.path().display();
                                            cx.render(rsx!{
                                                div {
                                                    key: "{path}",
                                                    span {
                                                        style: "font-style: italic; text-decoration: underline;",
                                                        "{path}"
                                                    },
                                                    ul {
                                                        dir.files().map(|f| {
                                                            let file_path = f.path();
                                                            let file_contents = f.contents_utf8().unwrap();
                                                            cx.render(rsx!{
                                                                details {
                                                                    key: "{file_path:?}",
                                                                    style: "white-space: pre;",
                                                                    summary {
                                                                        "{file_path:?}"
                                                                    }
                                                                    "{file_contents}"
                                                                }
                                                            })
                                                        })
                                                    }
                                                }
                                            })
                                        })
                                    }
                                }
                            }
                            // LOG CONTROLS
                            div {
                                button {
                                    onclick: move |_| show_logs.modify(|v| !v),
                                    "Show debug logs"
                                }
                            }
                            div {
                                button {
                                    onclick: move |_| show_collisions.modify(|v| !v),
                                    "Show colliding boxes"
                                }
                            }
                        }
                    }
                }
                // div {
                //     style: "font-size: 0.875rem; line-height: 1.25rem; --tw-text-opacity: 1; color: rgba(156, 163, 175, var(--tw-text-opacity)); width: 100%;",
                //     span {
                //         style: "color: #000;",
                //         "Crossing Number: "
                //     }
                //     span {
                //         style: "font-style: italic;",
                //         crossing_number
                //     }
                // }
                show_logs.then(|| rsx!{
                        div {
                        style: "font-size: 0.875rem; line-height: 1.25rem; --tw-text-opacity: 1; color: rgba(156, 163, 175, var(--tw-text-opacity)); width: 100%;",
                        span {
                            style: "color: #000;",
                            "Solution Status: "
                        }
                        span {
                            style: "font-style: italic;",
                            "v: {status_v:?} h: {status_h:?} c: {status_c:?}"
                        }
                    }
                })
            }
        }
        // DRAWING
        div {
            div {
                style: "position: relative; width: {viewbox_width}px; height: {viewbox_height}px; margin-left: auto; margin-right: auto; border-width: 1px; border-color: #000; margin-bottom: 40px;",
                nodes
                show_collisions.then(|| rsx!{
                    collision_nodes
                })
            }
        }
        // LOGS
        div {
            style: "display: flex; flex-direction: row; overflow-x: auto;",
            show_logs.then(|| rsx!{
                logs
            })
        }
    })
}

pub fn main() -> io::Result<()> {
    let mut menu_bar = tao::menu::MenuBar::new();
    let mut app_menu = tao::menu::MenuBar::new();
    let mut edit_menu = tao::menu::MenuBar::new();

    edit_menu.add_native_item(tao::menu::MenuItem::Undo);
    edit_menu.add_native_item(tao::menu::MenuItem::Redo);
    edit_menu.add_native_item(tao::menu::MenuItem::Separator);
    edit_menu.add_native_item(tao::menu::MenuItem::Cut);
    edit_menu.add_native_item(tao::menu::MenuItem::Copy);
    edit_menu.add_native_item(tao::menu::MenuItem::Paste);
    edit_menu.add_native_item(tao::menu::MenuItem::Separator);
    edit_menu.add_native_item(tao::menu::MenuItem::SelectAll);

    app_menu.add_native_item(tao::menu::MenuItem::CloseWindow);
    app_menu.add_native_item(tao::menu::MenuItem::Quit);
    menu_bar.add_submenu("Depict", true, app_menu);
    menu_bar.add_submenu("Edit", true, edit_menu);

    dioxus_desktop::launch_with_props(app,
        AppProps {},
        Config::new().with_window(
            WindowBuilder::new()
                .with_inner_size(LogicalSize::new(1200.0f64, 700.0f64))
                .with_title("Depict")
                .with_menu(menu_bar)
        ));

    // let mut vdom = VirtualDom::new(app);
    // let _ = vdom.rebuild();
    // let text = render_vdom(&vdom);
    // eprintln!("{text}");

    Ok(())
}