summaryrefslogtreecommitdiff
path: root/src/image.rs
blob: 07e8af5904e0f0fa69f01b47cc1201977769ed35 (plain)
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
use ab_glyph::{FontArc, PxScale};
use fontdb::{Database, Family, Query, Source};
use image::{ColorType, DynamicImage, ImageBuffer, imageops};
use imageproc::{
    drawing::{Canvas, draw_filled_rect_mut, draw_polygon_mut, draw_text_mut, text_size},
    point::Point,
    rect::Rect,
};
use std::{fs, io, path::Path, slice};

use crate::ast::DepthExpr;

/*
offset based mutation model, to avoid overflowing on previous image
*/

pub struct FlowChart<'a> {
    img: DynamicImage,
    offset: Offset<'a>,
    font: FontArc,
    branches: Vec<u32>,
    pxscale: PxScale,
}

// TODO: change to i32, since we converted it to i32 already so the extra len of
// u32 is useless
#[derive(Clone)]
struct Offset<'a> {
    offset: COffset,
    // center width
    branch: slice::Iter<'a, u32>,
}

#[derive(Clone)]
struct COffset {
    offset: RawOffset,
    center: u32,
}

#[derive(Clone, Copy, Debug)]
struct RawOffset {
    x: u32,
    y: u32,
}

struct MutNCOffset<'a> {
    x: &'a mut u32,
    y: &'a mut u32,
}

impl<'a> Default for FlowChart<'a> {
    fn default() -> Self {
        Self::new()
    }
}

impl<'a> FlowChart<'a> {
    // TODO: based on how much text
    const COMPONENT_TEXT_PADDING: u32 = 1 * Self::RESOLUTION_MULTIPLIER;

    const TEXT_SCALE: f32 = 12.0 * Self::RESOLUTION_MULTIPLIER as f32;
    const TEXT_LEN_WRAP: usize = 10;

    // TODO: LENGTH based on where to where
    const DIRECTION_LINE_THICKNESS: u32 = 2 * Self::RESOLUTION_MULTIPLIER / 2;
    const DIRECTION_LINE_LENGTH: u32 = 13 * Self::RESOLUTION_MULTIPLIER;
    const DIRECTION_LINE_ARROW_OFFSET: u32 = 5 * Self::RESOLUTION_MULTIPLIER / 2;

    const RESOLUTION_MULTIPLIER: u32 = 5;

    pub fn new() -> Self {
        Self {
            img: DynamicImage::new(0, 0, ColorType::Rgba8),
            offset: Offset {
                offset: COffset {
                    offset: RawOffset {
                        x: 0,
                        y: 0,
                    },
                    center: 0,
                },
                branch: [].iter(),
            },
            font: Self::get_system_font(),
            branches: vec![0],
            pxscale: PxScale::from(Self::TEXT_SCALE / 2_f32), // no idea why can't I just do it at the const...
        }
    }

    pub fn create(ast: &[DepthExpr], path: &Path) {
        let mut chart = FlowChart::new();
        chart.build(ast);
        chart
            .img
            .save(path)
            .unwrap();
    }

    fn build(&mut self, ast: &[DepthExpr]) {
        for node in ast {
            let mut skip_dir = false;
            match node {
                // DepthExpr::Decision {
                //     cond,
                //     t,
                //     then_branch,
                //     else_branch,
                // } => todo!(),
                // DepthExpr::IO(_) => todo!(),
                DepthExpr::Process(s) => {
                    println!("{}", s);
                    self.draw_process(s, VDirection::Up);
                }
                _ => skip_dir = true,
            };
            if !skip_dir {
                self.draw_direction(None, None);
            }
        }
        // self.draw_process("abcdefghijklmnospa", VDirection::Up);
        // self.draw_direction(None, None);
        // self.draw_process("abc", VDirection::Up);
        // self.draw_direction(None, None);
        // self.draw_process("a", VDirection::Up);
        // let offset = self.offset;
        // self.draw_direction(None, None);
        // self.draw_process("a", VDirection::Up);
        // self.draw_direction(None, None);
        // let a = self.draw_process("a", VDirection::Up);
        // self.draw_direction(
        //     Some(&NCOffset {
        //         x: self
        //             .offset
        //             .center,
        //         y: self
        //             .offset
        //             .y
        //             - a.y,
        //     }),
        //     Some(&NCOffset {
        //         x: offset.x + 100,
        //         y: offset.y,
        //     }),
        // );
        // self.draw_process("a", VDirection::Down);
    }

    fn lookahead(&mut self, ast: &[DepthExpr]) {
        let mut largest: u32 = 0;
        let mut copy: Vec<_> = self
            .branches
            .to_vec();
        let cur = copy.first();
        copy.push(1);

        for node in ast {
            match node {
                DepthExpr::Decision {
                    cond,
                    t: _,
                    then_branch: _,
                    else_branch: _,
                } => {
                    largest = largest.max(
                        self.text_size(cond)
                            .0,
                    )
                }
                DepthExpr::IO(s) => {
                    largest = largest.max(
                        self.text_size(s)
                            .0,
                    )
                }
                DepthExpr::Process(s) => {
                    largest = largest.max(
                        self.text_size(s)
                            .0,
                    )
                }
            }
        }
    }

    fn get_system_font() -> FontArc {
        let mut db = Database::new();
        db.load_system_fonts();

        match &db
            .face(
                db.query(&Query {
                    families: &[Family::SansSerif],
                    weight: fontdb::Weight::NORMAL,
                    stretch: fontdb::Stretch::Normal,
                    style: fontdb::Style::Normal,
                })
                .or_else(|| {
                    db.faces()
                        .next()
                        .map(|f| f.id)
                })
                .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no system fonts"))
                .expect("no system fonts"),
            )
            .ok_or_else(|| io::Error::other("face missing"))
            .expect("face missing")
            .source
        {
            Source::File(path) => fs::read(path).and_then(|bytes| FontArc::try_from_vec(bytes).map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "parse font failed"))),
            Source::Binary(data) => FontArc::try_from_vec(
                data.as_ref()
                    .as_ref()
                    .to_vec(),
            )
            .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "parse font failed")),
            _ => Err(io::Error::new(io::ErrorKind::Unsupported, "unsupported font source")),
        }
        .expect("failed to load font")
    }
    fn wrap_str(s: &str) -> Vec<String> {
        s.chars()
            .collect::<Vec<_>>()
            .chunks(Self::TEXT_LEN_WRAP)
            .map(|c| {
                c.iter()
                    .collect()
            })
            .collect()
    }

    fn ext(&mut self, offset: &mut RawOffset, ext: &mut RawOffset) {
        let (curw, curh) = &mut (offset.x, offset.y);
        let (extw, exth) = &mut (ext.x, ext.y);
        let img = &mut self.img;
        let (w, h) = img.dimensions();
        let extedw = *extw + *curw;
        let extedh = *exth + *curh;
        if extedw <= w && extedh <= h {
            return;
        }
        let mut resized = ImageBuffer::from_pixel(w.max(extedw), h.max(extedh), colors::BG);
        imageops::overlay(&mut resized, img, 0, 0);
        *img = image::DynamicImage::ImageRgba8(resized);
    }

    fn draw_text(&mut self, txts: &[&str], offset: &mut MutNCOffset) {
        let (curw, curh) = (&offset.x, &mut offset.y);
        for txt in txts {
            draw_text_mut(&mut self.img, colors::FG, **curw as i32 + Self::COMPONENT_TEXT_PADDING as i32, **curh as i32 + Self::COMPONENT_TEXT_PADDING as i32, self.pxscale, &self.font, txt);
            **curh += Self::TEXT_SCALE as u32 / 2;
        }
    }

    fn text_size(&self, txt: &str) -> (u32, u32) {
        text_size(self.pxscale, &self.font, txt)
    }

    // TODO: make draw_rect func
    // TODO: Accept all directions
    fn draw_process(&mut self, txt: &str, src_dir: VDirection) -> RawOffset {
        let wrapped = Self::wrap_str(txt);
        let wrapped: Vec<&str> = wrapped
            .iter()
            .map(|s| s.as_str())
            .collect();
        let (text_w, _) = self.text_size(wrapped[0]);
        let w = text_w + (2 * Self::COMPONENT_TEXT_PADDING);
        let h = Self::TEXT_SCALE as u32 / 2 * wrapped.len() as u32 + (2 * Self::COMPONENT_TEXT_PADDING); // text_size's height is weird and incorrect
        let curh = &mut self
            .offset
            .offset
            .offset
            .y;
        if src_dir == VDirection::Down {
            *curh = curh
                .checked_sub(h)
                .unwrap_or(0);
        }
        let (curh, c) = (
            self.offset
                .offset
                .offset
                .y,
            self.offset
                .offset
                .center,
        );
        self.ext(
            &mut RawOffset {
                x: c,
                y: curh,
            },
            &mut RawOffset {
                x: w,
                y: h,
            },
        );
        let (curw, mut curh, c) = (
            self.offset
                .offset
                .offset
                .x,
            self.offset
                .offset
                .offset
                .y,
            self.offset
                .offset
                .center,
        );
        let mut cw = c.saturating_sub(w / 2);
        draw_filled_rect_mut(&mut self.img, Rect::at(cw as i32, curh as i32).of_size(w, h), colors::PROCESS);
        self.draw_text(
            &wrapped,
            // FIXME: i don't think this works, we giving them derefed value
            &mut MutNCOffset {
                x: &mut cw,
                y: &mut curh,
            },
        );
        (
            self.offset
                .offset
                .offset
                .x,
            self.offset
                .offset
                .offset
                .y,
            self.offset
                .offset
                .center,
        ) = (curw, curh, c);
        if self
            .offset
            .offset
            .center
            == 0
        {
            self.offset
                .offset
                .center = curw + (w / 2);
        }
        self.offset
            .offset
            .offset
            .y += 2 * Self::COMPONENT_TEXT_PADDING;
        RawOffset {
            x: w,
            y: h,
        }
    }

    fn draw_direction(&mut self, src: Option<&RawOffset>, dst: Option<&RawOffset>) -> RawOffset {
        let (orih, c) = (
            self.offset
                .offset
                .offset
                .y,
            self.offset
                .offset
                .center,
        );

        let (srcx, srcy) = match src {
            Some(&offset) => {
                let dx = if offset.x == 0 {
                    c as i32
                } else {
                    offset.x as i32
                };
                (dx, offset.y as i32)
            }
            None => (c as i32, orih as i32),
        };

        // perpendicular(thickness)
        let (dstx, dsty) = match dst {
            Some(&offset) => {
                let dx = if offset.x == 0 {
                    srcx
                } else {
                    offset.x as i32
                };
                (dx, offset.y as i32)
            }
            None => (srcx, srcy + (Self::DIRECTION_LINE_LENGTH - Self::DIRECTION_LINE_ARROW_OFFSET) as i32),
        };

        let xdiff = (dstx - srcx) as f32;
        let ydiff = (dsty - srcy) as f32;
        let length = (xdiff * xdiff + ydiff * ydiff)
            .sqrt()
            .max(1_f32);

        let prepx = -ydiff / length;
        let prepy = xdiff / length;

        let linemaxx = (dstx as f32 - (xdiff / length) * Self::DIRECTION_LINE_ARROW_OFFSET as f32).round() as i32;
        let linemaxy = (dsty as f32 - (ydiff / length) * Self::DIRECTION_LINE_ARROW_OFFSET as f32).round() as i32;

        let line = [
            Point::new((srcx as f32 - prepx * Self::DIRECTION_LINE_THICKNESS as f32).round() as i32, (srcy as f32 - prepy * Self::DIRECTION_LINE_THICKNESS as f32).round() as i32),
            Point::new((srcx as f32 + prepx * Self::DIRECTION_LINE_THICKNESS as f32).round() as i32, (srcy as f32 + prepy * Self::DIRECTION_LINE_THICKNESS as f32).round() as i32),
            Point::new((linemaxx as f32 + prepx * Self::DIRECTION_LINE_THICKNESS as f32).round() as i32, (linemaxy as f32 + prepy * Self::DIRECTION_LINE_THICKNESS as f32).round() as i32),
            Point::new((linemaxx as f32 - prepx * Self::DIRECTION_LINE_THICKNESS as f32).round() as i32, (linemaxy as f32 - prepy * Self::DIRECTION_LINE_THICKNESS as f32).round() as i32),
        ];

        let xc = dstx as f32 - (xdiff / length) * Self::DIRECTION_LINE_ARROW_OFFSET as f32;
        let yc = dsty as f32 - (ydiff / length) * Self::DIRECTION_LINE_ARROW_OFFSET as f32;

        let left = Point::new((xc + prepx * Self::DIRECTION_LINE_ARROW_OFFSET as f32).round() as i32, (yc + prepy * Self::DIRECTION_LINE_ARROW_OFFSET as f32).round() as i32);
        let right = Point::new((xc - prepx * Self::DIRECTION_LINE_ARROW_OFFSET as f32).round() as i32, (yc - prepy * Self::DIRECTION_LINE_ARROW_OFFSET as f32).round() as i32);
        let tip = Point::new(dstx, dsty);
        let center = Point::new(xc.round() as i32, yc.round() as i32);

        let mut maxx = srcx.max(dstx);
        let mut maxy = srcy.max(dsty);
        for p in line
            .iter()
            .copied()
            .chain([
                tip, center, left, right,
            ])
        {
            if p.x > maxx {
                maxx = p.x;
            }
            if p.y > maxy {
                maxy = p.y;
            }
        }
        self.ext(
            &mut RawOffset {
                x: c,
                y: orih,
            },
            &mut RawOffset {
                x: ((maxx - c as i32).max(0) as u32),
                y: ((maxy - orih as i32).max(0) as u32),
            },
        );
        let img = &mut self.img;

        draw_polygon_mut(img, &line, colors::DIRECT);
        draw_polygon_mut(
            img,
            &[
                tip, left, center,
            ],
            colors::DIRECT,
        );
        draw_polygon_mut(
            img,
            &[
                tip, right, center,
            ],
            colors::DIRECT,
        );

        self.offset
            .offset
            .center = dstx as u32;
        self.offset
            .offset
            .offset
            .y = dsty as u32;
        RawOffset {
            x: ((maxx - c as i32).max(0) as u32),
            y: ((maxy - orih as i32).max(0) as u32),
        }
    }
}

enum VHDirection {
    Horizontal(HDirection),
    Vertical(VDirection),
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum HDirection {
    Left,
    Right,
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum VDirection {
    Up,
    Down,
}

trait Direction: Copy + Eq + core::fmt::Debug {}
impl Direction for HDirection {}
impl Direction for VDirection {}

struct ComponentConfig<O: Direction, D: Direction> {
    ori_direction: O,
    dst_direction: D,
}

mod colors {
    use image::Rgba;
    pub const STARSTOP: Rgba<u8> = Rgba([
        63, 122, 86, 255,
    ]);
    pub const PROCESS: Rgba<u8> = Rgba([
        0, 104, 124, 255,
    ]);
    pub const IO: Rgba<u8> = Rgba([
        149, 30, 88, 255,
    ]);
    pub const DIRECT: Rgba<u8> = Rgba([
        31, 133, 53, 255,
    ]);
    pub const BG: Rgba<u8> = Rgba([
        0, 0, 0, 0,
    ]);
    pub const FG: Rgba<u8> = Rgba([
        255, 255, 255, 255,
    ]);
}