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
use crate::parser;
use base64;
use netidx::{path::Path, publisher::Value, utils};
use std::{boxed, collections::HashMap, fmt, result, str::FromStr};

#[derive(Debug, Clone, Serialize, Deserialize, PartialOrd, PartialEq)]
pub enum Source {
    Constant(Value),
    Load(Path),
    Variable(String),
    Map {
        /// the sources we are mapping from
        from: Vec<Source>,
        /// the name of the built-in 'Value -> Option Value' function
        /// that will be called each time the source produces a
        /// value. If the function returns None then no value will be
        /// produced by the source, otherwise the returned value will
        /// be produced. You must define the function in one of the
        /// scripts imported by the view. Note, if the wrapped source
        /// is a group, and the function is an aggregate function then
        /// it will operate on all the values (e.g. sum, mean, ewma,
        /// etc ...), otherwise it will operate on the first value in
        /// the group to update.
        function: String,
    },
}

impl fmt::Display for Source {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Source::Constant(v) => match v {
                Value::U32(v) => write!(f, "constant(u32, {})", v),
                Value::V32(v) => write!(f, "constant(v32, {})", v),
                Value::I32(v) => write!(f, "constant(i32, {})", v),
                Value::Z32(v) => write!(f, "constant(z32, {})", v),
                Value::U64(v) => write!(f, "constant(u64, {})", v),
                Value::V64(v) => write!(f, "constant(v64, {})", v),
                Value::I64(v) => write!(f, "constant(i64, {})", v),
                Value::Z64(v) => write!(f, "constant(z64, {})", v),
                Value::F32(v) => write!(f, "constant(f32, {})", v),
                Value::F64(v) => write!(f, "constant(f64, {})", v),
                Value::DateTime(v) => write!(f, r#"constant(datetime, "{}")"#, v),
                Value::Duration(v) => {
                    write!(f, r#"constant(duration, "{}s")"#, v.as_secs_f64())
                }
                Value::String(s) => {
                    write!(f, r#"constant(string, "{}")"#, utils::escape(&*s, '\\', '"'))
                }
                Value::Bytes(b) => write!(f, "constant(binary, {})", base64::encode(&*b)),
                Value::True => write!(f, "constant(bool, true)"),
                Value::False => write!(f, "constant(bool, false)"),
                Value::Null => write!(f, "constant(null)"),
                Value::Ok => write!(f, "constant(result, ok)"),
                Value::Error(v) => {
                    write!(f, r#"constant(result, "{}")"#, utils::escape(&*v, '\\', '"'))
                }
            },
            Source::Load(p) => {
                write!(f, r#"load_path("{}")"#, utils::escape(&*p, '\\', '"'))
            }
            Source::Variable(v) => write!(f, "load_var({})", v),
            Source::Map { from, function } => {
                write!(f, "{}(", function)?;
                for i in 0..from.len() {
                    write!(f, "{}", &from[i])?;
                    if i < from.len() - 1 {
                        write!(f, ", ")?;
                    }
                }
                write!(f, ")")
            }
        }
    }
}

impl FromStr for Source {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> result::Result<Self, Self::Err> {
        parser::parse_source(s)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialOrd, PartialEq)]
pub enum Sink {
    Store(Path),
    Variable(String),
    Navigate,
    All(Vec<Sink>),
    Confirm(boxed::Box<Sink>),
}

impl fmt::Display for Sink {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Sink::Store(p) => {
                write!(f, r#"store_path("{}")"#, utils::escape(&*p, '\\', '"'))
            }
            Sink::Variable(v) => write!(f, "store_var({})", v),
            Sink::Navigate => write!(f, "navigate()"),
            Sink::Confirm(sink) => write!(f, "confirm({})", sink),
            Sink::All(sinks) => {
                write!(f, "all(")?;
                for i in 0..sinks.len() {
                    write!(f, "{}", &sinks[i])?;
                    if i < sinks.len() - 1 {
                        write!(f, ", ")?;
                    }
                }
                write!(f, ")")
            }
        }
    }
}

impl FromStr for Sink {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> result::Result<Self, Self::Err> {
        parser::parse_sink(s)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Keybind {
    pub key: String,
    pub source: Source,
    pub sink: Sink,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum Direction {
    Horizontal,
    Vertical,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Action {
    pub source: Source,
    pub sink: Sink,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum SortDir {
    Ascending,
    Descending
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ColumnSpec {
    Exactly(Vec<String>),
    Hide(Vec<String>),
    Auto
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Table {
    pub path: Path,
    pub default_sort_column: Option<(String, SortDir)>,
    pub columns: ColumnSpec,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Button {
    pub enabled: Source,
    pub label: Source,
    pub source: Source,
    pub sink: Sink,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Toggle {
    pub enabled: Source,
    pub source: Source,
    pub sink: Sink,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Selector {
    pub enabled: Source,
    pub choices: Source,
    pub source: Source,
    pub sink: Sink,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Entry {
    pub enabled: Source,
    pub visible: Source,
    pub source: Source,
    pub sink: Sink,
}

#[derive(Debug, Copy, Clone, Serialize, PartialEq, PartialOrd, Eq, Ord, Deserialize)]
pub enum Align {
    Fill,
    Start,
    End,
    Center,
    Baseline,
}

#[derive(Debug, Copy, Clone, Serialize, PartialEq, PartialOrd, Eq, Ord, Deserialize)]
pub enum Pack {
    Start,
    End,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BoxChild {
    pub pack: Pack,
    pub padding: u64,
    pub widget: boxed::Box<Widget>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Box {
    pub direction: Direction,
    pub homogeneous: bool,
    pub spacing: u32,
    pub children: Vec<Widget>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GridChild {
    pub width: u32,
    pub height: u32,
    pub widget: boxed::Box<Widget>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GridRow {
    pub columns: Vec<Widget>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Grid {
    pub homogeneous_columns: bool,
    pub homogeneous_rows: bool,
    pub column_spacing: u32,
    pub row_spacing: u32,
    pub rows: Vec<Widget>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct RGB {
    pub r: f64,
    pub g: f64,
    pub b: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Series {
    pub title: String,
    pub line_color: RGB,
    pub x: Source,
    pub y: Source,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LinePlot {
    pub title: String,
    pub x_label: String,
    pub y_label: String,
    pub x_labels: usize,
    pub y_labels: usize,
    pub x_grid: bool,
    pub y_grid: bool,
    pub fill: Option<RGB>,
    pub margin: u32,
    pub label_area: u32,
    pub x_min: Source,
    pub x_max: Source,
    pub y_min: Source,
    pub y_max: Source,
    pub keep_points: Source,
    pub series: Vec<Series>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum WidgetKind {
    Action(Action),
    Table(Table),
    Label(Source),
    Button(Button),
    Toggle(Toggle),
    Selector(Selector),
    Entry(Entry),
    Box(Box),
    BoxChild(BoxChild),
    Grid(Grid),
    GridChild(GridChild),
    GridRow(GridRow),
    LinePlot(LinePlot),
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct WidgetProps {
    pub halign: Align,
    pub valign: Align,
    pub hexpand: bool,
    pub vexpand: bool,
    pub margin_top: u32,
    pub margin_bottom: u32,
    pub margin_start: u32,
    pub margin_end: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Widget {
    pub props: WidgetProps,
    pub kind: WidgetKind,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct View {
    pub variables: HashMap<String, Value>,
    pub keybinds: Vec<Keybind>,
    pub root: Widget,
}

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

    #[test]
    fn sink_round_trip() {
        let s = Sink::Store(Path::from(r#"/foo bar baz/"(zam)"/_ xyz+ "#));
        assert_eq!(s, s.to_string().parse::<Sink>().unwrap());
        let s = Sink::All(vec![
            Sink::Store(Path::from("/foo/bar")),
            Sink::Variable(String::from("foo")),
        ]);
        assert_eq!(s, s.to_string().parse::<Sink>().unwrap());
        let s = Sink::Navigate;
        assert_eq!(s, s.to_string().parse::<Sink>().unwrap());
        let s = Sink::Confirm(boxed::Box::new(Sink::Navigate));
        assert_eq!(s, s.to_string().parse::<Sink>().unwrap());
    }

    fn check(s: Source) {
        assert_eq!(s, s.to_string().parse::<Source>().unwrap())
    }

    #[test]
    fn source_round_trip() {
        check(Source::Constant(Value::U32(23)));
        check(Source::Constant(Value::V32(42)));
        check(Source::Constant(Value::I32(-10)));
        check(Source::Constant(Value::I32(12321)));
        check(Source::Constant(Value::Z32(-99)));
        check(Source::Constant(Value::U64(100)));
        check(Source::Constant(Value::V64(100)));
        check(Source::Constant(Value::I64(-100)));
        check(Source::Constant(Value::I64(100)));
        check(Source::Constant(Value::Z64(-100)));
        check(Source::Constant(Value::Z64(100)));
        check(Source::Constant(Value::F32(3.1415)));
        check(Source::Constant(Value::F32(3.)));
        check(Source::Constant(Value::F32(3.)));
        check(Source::Constant(Value::F64(3.1415)));
        check(Source::Constant(Value::F64(3.)));
        check(Source::Constant(Value::F64(3.)));
        let c = Chars::from(r#"I've got a lovely "bunch" of (coconuts)"#);
        check(Source::Constant(Value::String(c)));
        check(Source::Constant(Value::True));
        check(Source::Constant(Value::False));
        check(Source::Constant(Value::Null));
        check(Source::Constant(Value::Ok));
        check(Source::Constant(Value::Error(Chars::from("error"))));
        check(Source::Load(Path::from(r#"/foo bar baz/"zam"/)_ xyz+ "#)));
        check(Source::Variable(String::from("sum")));
        check(Source::Map {
            from: vec![
                Source::Constant(Value::F32(1.)),
                Source::Load(Path::from("/foo/bar")),
                Source::Map {
                    from: vec![
                        Source::Constant(Value::F32(0.)),
                        Source::Load(Path::from("/foo/baz")),
                    ],
                    function: String::from("max"),
                },
            ],
            function: String::from("sum"),
        });
    }
}