logisheets_controller 1.16.1

Core spreadsheet engine for LogiSheets: formula evaluation, dependency tracking, and undo/redo.
Documentation
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
use crate::edit_action::{HorizontalAlignment, VerticalAlignment};
use crate::theme_manager::ThemeManager;
use crate::utils::turn_indexed_color_to_rgb;
use crate::{edit_action::Alignment, style_manager::RawStyle};
use gents_derives::TS;
use logisheets_workbook::prelude::{
    CtBorder, CtBorderPr, CtCellAlignment, CtCellProtection, CtColor, CtFill, CtFont, CtFontFamily,
    CtFontName, CtFontScheme, CtUnderlineProperty, CtVerticalAlignFontProperty, StBorderStyle,
    StGradientType, StHorizontalAlignment, StPatternType, StVerticalAlignment,
};

#[derive(Debug, Clone, TS)]
/// A cell's style resolved for rendering: theme and indexed colors are
/// already turned into RGBA [`Color`]s with tint applied.
#[ts(file_name = "style.ts")]
pub struct Style {
    pub font: Font,
    pub fill: Fill,
    pub border: Border,
    pub alignment: Option<Alignment>,
    pub protection: Option<CtCellProtection>,
    /// The number-format code (e.g. `0.00%`); formatting values with it is
    /// the host's job.
    pub formatter: String,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "font.ts", rename_all = "camelCase")]
pub struct Font {
    pub bold: bool,
    pub italic: bool,
    pub underline: Option<CtUnderlineProperty>,
    pub color: Option<Color>,
    /// Size in points.
    pub sz: Option<f64>,
    pub name: Option<CtFontName>,
    pub charset: Option<i32>,
    pub family: Option<CtFontFamily>,
    pub strike: bool,
    pub outline: bool,
    pub shadow: bool,
    pub condense: bool,
    pub extend: bool,
    pub vert_align: Option<CtVerticalAlignFontProperty>,
    pub scheme: Option<CtFontScheme>,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "fill.ts", tag = "type")]
pub enum Fill {
    PatternFill(PatternFill),
    GradientFill(GradientFill),
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "pattern_fill.ts", rename_all = "camelCase")]
pub struct PatternFill {
    pub fg_color: Option<Color>,
    pub bg_color: Option<Color>,
    pub pattern_type: Option<StPatternType>,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "gradient_fill.ts", rename_all = "camelCase")]
pub struct GradientFill {
    pub stops: Vec<GradientStop>,
    pub ty: StGradientType,
    pub degree: f64,
    pub left: f64,
    pub right: f64,
    pub top: f64,
    pub bottom: f64,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "gradient_stop.ts", rename_all = "camelCase")]
pub struct GradientStop {
    pub color: Color,
    pub position: f64,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "border_pr.ts", rename_all = "camelCase")]
pub struct BorderPr {
    pub color: Option<Color>,
    pub style: StBorderStyle,
}

#[derive(Debug, Clone, TS)]
#[ts(file_name = "border.ts", rename_all = "camelCase")]
pub struct Border {
    pub left: Option<BorderPr>,
    pub right: Option<BorderPr>,
    pub top: Option<BorderPr>,
    pub bottom: Option<BorderPr>,
    pub diagonal: Option<BorderPr>,
    pub vertical: Option<BorderPr>,
    pub horizontal: Option<BorderPr>,
    pub diagonal_up: Option<bool>,
    pub diagonal_down: Option<bool>,
    pub outline: bool,
}

/// An RGBA color as channels in `0..=255` (`alpha` defaults to 255, opaque).
///
/// This is the shape fills take (`PatternFill::fg_color` / `bg_color`) and the
/// shape resolved styles are read back in. Font and border colors in a
/// `StyleUpdateType` are ARGB hex strings instead.
#[derive(Debug, Clone, TS)]
#[ts(file_name = "color.ts", rename_all = "camelCase")]
pub struct Color {
    pub red: Option<f64>,
    pub green: Option<f64>,
    pub blue: Option<f64>,
    pub alpha: Option<f64>,
}

pub struct StyleConverter<'a> {
    pub theme_manager: &'a ThemeManager,
}

fn get_luminance(r: f64, g: f64, b: f64) -> f64 {
    0.2126 * r + 0.7152 * g + 0.0722 * b
}

/// Convert raw style to style, which is more friendly to frontend.
impl<'a> StyleConverter<'a> {
    pub fn convert_style(&self, raw_style: RawStyle) -> Style {
        let fill = self.convert_fill(raw_style.fill);
        let luminance = match &fill {
            Fill::PatternFill(pf) => {
                if let Some(color) = &pf.fg_color {
                    if let (Some(r), Some(g), Some(b)) = (color.red, color.green, color.blue) {
                        get_luminance(r, g, b)
                    } else {
                        255.
                    }
                } else {
                    255.
                }
            }
            Fill::GradientFill(gf) => {
                if !gf.stops.is_empty() {
                    let stop = &gf.stops[0];
                    let color = &stop.color;
                    if let (Some(r), Some(g), Some(b)) = (color.red, color.green, color.blue) {
                        get_luminance(r, g, b)
                    } else {
                        255.
                    }
                } else {
                    255.
                }
            }
        };
        Style {
            font: self.convert_font(raw_style.font, luminance),
            fill,
            border: self.convert_border(raw_style.border),
            alignment: raw_style.alignment.map(|v| self.convert_alignment(v)),
            protection: raw_style.protection,
            formatter: raw_style.formatter,
        }
    }

    fn convert_font(&self, font: CtFont, luminance: f64) -> Font {
        let color = match font.color {
            Some(c) => Some(self.convert_font_color(c, luminance)),
            None => Some(get_auto_color(luminance)),
        };
        Font {
            bold: font.bold,
            italic: font.italic,
            underline: font.underline.clone(),
            color,
            sz: font.sz.as_ref().map_or(None, |s| Some(s.val)),
            name: font.name.clone(),
            charset: font.charset.as_ref().map_or(None, |s| Some(s.val)),
            family: font.family.clone(),
            strike: font.strike,
            outline: font.outline,
            shadow: font.shadow,
            condense: font.condense,
            extend: font.extend,
            vert_align: font.vert_align.clone(),
            scheme: font.scheme.clone(),
        }
    }

    fn convert_fill(&self, fill: CtFill) -> Fill {
        match fill {
            CtFill::PatternFill(pf) => Fill::PatternFill(PatternFill {
                fg_color: pf.fg_color.map_or(None, |c| Some(self.convert_color(c))),
                bg_color: pf.bg_color.map_or(None, |c| Some(self.convert_color(c))),
                pattern_type: pf.pattern_type.clone(),
            }),
            CtFill::GradientFill(gf) => Fill::GradientFill(GradientFill {
                stops: gf
                    .stops
                    .into_iter()
                    .map(|stop| GradientStop {
                        color: self.convert_color(stop.color),
                        position: stop.position,
                    })
                    .collect(),
                ty: gf.ty.clone(),
                degree: gf.degree,
                left: gf.left,
                right: gf.right,
                top: gf.top,
                bottom: gf.bottom,
            }),
        }
    }

    fn convert_alignment(&self, raw: CtCellAlignment) -> Alignment {
        let horizontal = if let Some(h) = raw.horizontal {
            match h {
                StHorizontalAlignment::General => Some(HorizontalAlignment::General),
                StHorizontalAlignment::Left => Some(HorizontalAlignment::Left),
                StHorizontalAlignment::Center => Some(HorizontalAlignment::Center),
                StHorizontalAlignment::Right => Some(HorizontalAlignment::Right),
                StHorizontalAlignment::Fill => Some(HorizontalAlignment::Fill),
                StHorizontalAlignment::Justify => Some(HorizontalAlignment::Justify),
                StHorizontalAlignment::CenterContinuous => {
                    Some(HorizontalAlignment::CenterContinuous)
                }
                StHorizontalAlignment::Distributed => Some(HorizontalAlignment::Distributed),
            }
        } else {
            None
        };
        let vertical = if let Some(v) = raw.vertical {
            match v {
                StVerticalAlignment::Top => Some(VerticalAlignment::Top),
                StVerticalAlignment::Center => Some(VerticalAlignment::Center),
                StVerticalAlignment::Bottom => Some(VerticalAlignment::Bottom),
                StVerticalAlignment::Justify => Some(VerticalAlignment::Justify),
                StVerticalAlignment::Distributed => Some(VerticalAlignment::Distributed),
            }
        } else {
            None
        };
        let wrap_text = raw.wrap_text;
        Alignment {
            horizontal,
            vertical,
            wrap_text,
        }
    }

    fn convert_border(&self, border: CtBorder) -> Border {
        Border {
            left: border
                .left
                .map_or(None, |pr| Some(self.convert_border_pr(pr))),
            right: border
                .right
                .map_or(None, |pr| Some(self.convert_border_pr(pr))),
            top: border
                .top
                .map_or(None, |pr| Some(self.convert_border_pr(pr))),
            bottom: border
                .bottom
                .map_or(None, |pr| Some(self.convert_border_pr(pr))),
            diagonal: border
                .diagonal
                .map_or(None, |pr| Some(self.convert_border_pr(pr))),
            vertical: border
                .vertical
                .map_or(None, |pr| Some(self.convert_border_pr(pr))),
            horizontal: border
                .horizontal
                .map_or(None, |pr| Some(self.convert_border_pr(pr))),
            diagonal_up: border.diagonal_up,
            diagonal_down: border.diagonal_down,
            outline: border.outline,
        }
    }

    fn convert_border_pr(&self, border_pr: CtBorderPr) -> BorderPr {
        BorderPr {
            color: border_pr
                .color
                .map_or(None, |c| Some(self.convert_color(c))),
            style: border_pr.style.clone(),
        }
    }

    fn convert_font_color(&self, color: CtColor, luminance: f64) -> Color {
        if let Some(true) = color.auto {
            return get_auto_color(luminance);
        }
        self.convert_color(color)
    }

    /// Theme/indexed-aware colour conversion, for callers outside the
    /// whole-style path (a data bar's colour, say).
    pub fn convert_color_pub(&self, color: CtColor) -> Color {
        self.convert_color(color)
    }

    fn convert_color(&self, color: CtColor) -> Color {
        let tint = color.tint;
        let rgb = {
            if let Some(rgb) = &color.rgb {
                rgb.clone()
            } else if let Some(indexed) = color.indexed {
                turn_indexed_color_to_rgb(indexed)
            } else if let Some(theme) = color.theme {
                self.theme_manager.get_theme_color(theme)
            } else {
                // auto is true.
                // TODO: Figure out what auto means.
                String::from("FF000000")
            }
        };
        from_hex_str(rgb, tint)
    }
}

/// Parse an 8-digit ARGB hex string (no `#`) and apply an OOXML `tint`.
/// Anything shorter yields a color with every channel `None`.
pub fn from_hex_str(argb: String, tint: f64) -> Color {
    use colorsys::{Hsl, Rgb};
    if argb.len() < 8 {
        return Color {
            red: None,
            green: None,
            blue: None,
            alpha: None,
        };
    }
    let a = u32::from_str_radix(&argb[0..2], 16).unwrap_or(0) as f64;
    let r = u32::from_str_radix(&argb[2..4], 16).unwrap_or(0) as f64;
    let g = u32::from_str_radix(&argb[4..6], 16).unwrap_or(0) as f64;
    let b = u32::from_str_radix(&argb[6..8], 16).unwrap_or(0) as f64;
    let rgb = Rgb::new(r, g, b, None);
    let mut hsl = Hsl::from(rgb);
    let lum = {
        let lum_max = 100.;
        let lum = hsl.lightness();
        if tint < 0. {
            lum * (1. + tint)
        } else if tint == 0. {
            lum
        } else {
            lum * (1. - tint) + lum_max - lum_max * (1. - tint)
        }
    };
    hsl.set_lightness(lum);
    let rgb = Rgb::from(hsl);
    Color {
        red: Some(rgb.red()),
        green: Some(rgb.green()),
        blue: Some(rgb.blue()),
        alpha: Some(a),
    }
}

#[inline]
fn bound(upper: u8, lower: u8, v: f64) -> u8 {
    let v = v.round();
    let result = upper.min(v as u8) as u8;
    let result = result.max(lower);
    result
}

pub fn color_to_ct_color(c: Color) -> CtColor {
    let r = bound(255, 0, c.red.unwrap_or(0.));
    let g = bound(255, 0, c.green.unwrap_or(0.));
    let b = bound(255, 0, c.blue.unwrap_or(0.));
    let a = bound(255, 0, c.alpha.unwrap_or(255.));
    let argb = format!("{:02X}{:02X}{:02X}{:02X}", a, r, g, b);
    CtColor {
        auto: None,
        indexed: None,
        rgb: Some(argb),
        theme: None,
        tint: 0.,
    }
}

fn get_auto_color(luminance: f64) -> Color {
    if luminance < 128. {
        return Color {
            red: Some(255.),
            green: Some(255.),
            blue: Some(255.),
            alpha: None,
        };
    }
    return Color {
        red: Some(0.),
        green: Some(0.),
        blue: Some(0.),
        alpha: None,
    };
}

#[cfg(test)]
mod tests {
    use super::{Color, color_to_ct_color, from_hex_str};

    #[test]
    fn test_from_hex_str() {
        let argb = "FF2F4B1A".to_string();
        let tint = 0.1;
        let color = from_hex_str(argb, tint);
        println!("{:?}", color);
    }

    #[test]
    fn test_color_to_ct_color() {
        let color = Color {
            red: Some(12.),
            green: Some(28.),
            blue: Some(100.),
            alpha: Some(241.),
        };
        let result = color_to_ct_color(color);
        if result.rgb.is_none() {
            panic!("should not be none")
        }
        println!("{:?}", result.rgb.unwrap())
    }
}