lb-rs 26.11.25

The rust library for interacting with your lockbook.
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
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
use std::collections::HashMap;
use std::fmt::Write;

use bezier_rs::{Bezier, Subpath};
use glam::{DAffine2, DMat2, DVec2};
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use usvg::tiny_skia_path::{PathSegment, Point};
use usvg::{Options, Paint, Transform};
use uuid::Uuid;

use super::WeakTransform;
use super::diff::DiffState;
use super::element::{
    Color, DynamicColor, EditableElement, ManipulatorGroupId, Path, Stroke,
    SvgSerializationContext, SvgSerialize, WeakImages, WeakPathPressures,
};

const ZOOM_G_ID: &str = "lb_master_transform";
const WEAK_IMAGE_G_ID: &str = "lb_images";
const WEAK_PATH_PRESSURES_G_ID: &str = "lb_path_pressures";
const WEAK_VIEWPORT_SETTINGS_G_ID: &str = "lb_viewport_settings";

#[derive(Default, Clone)]
pub struct Buffer {
    pub elements: IndexMap<Uuid, EditableElement>,
    pub weak_images: WeakImages,
    pub weak_path_pressures: WeakPathPressures,
    /// Read-only compatibility data from drawings saved by older clients.
    /// Never used to transform geometry or included in new serialization.
    pub weak_viewport_settings: WeakViewportSettings,
    pub has_legacy_viewport: bool,
    pub id_map: HashMap<Uuid, String>,
}

#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq)]
pub struct WeakRect {
    pub min: (f32, f32),
    pub max: (f32, f32),
}

#[derive(Clone, Default, Copy, Serialize, Deserialize)]
pub struct WeakViewportSettings {
    /// the drawable rect in the master-transformed plane
    pub bounded_rect: Option<WeakRect>,
    pub master_transform: WeakTransform,
    pub viewport_transform: Option<WeakTransform>,
    pub left_locked: bool,
    pub right_locked: bool,
    pub bottom_locked: bool,
    pub top_locked: bool,
}

impl Buffer {
    pub fn new(content: &str) -> Self {
        let mut elements = IndexMap::default();
        let mut id_map = HashMap::default();
        let mut weak_images = WeakImages::default();
        let mut weak_path_pressures = WeakPathPressures::default();
        let mut weak_viewport_settings = WeakViewportSettings::default();
        let has_legacy_viewport =
            content.contains(WEAK_VIEWPORT_SETTINGS_G_ID) || content.contains(ZOOM_G_ID);

        let maybe_tree = usvg::Tree::from_str(content, &Options::default());

        if let Err(err) = maybe_tree {
            tracing::warn!("{err:#?}");
        } else {
            let utree = maybe_tree.unwrap();

            utree.root().children().iter().for_each(|u_el| {
                parse_child(
                    u_el,
                    &mut elements,
                    &mut weak_viewport_settings,
                    &mut id_map,
                    &mut weak_images,
                    &mut weak_path_pressures,
                )
            });
        }

        if has_legacy_viewport {
            // Older writers baked element edits into `d` while also writing
            // the element transform. Preserve the geometry those clients saw.
            // Their viewport was already removed when the document was saved.
            for el in elements.values_mut() {
                if let EditableElement::Path(path) = el {
                    path.data.apply_transform(u_transform_to_bezier(
                        &path.transform.invert().unwrap_or_default(),
                    ));
                }
            }
        }

        Self {
            elements,
            id_map,
            weak_images,
            weak_viewport_settings,
            weak_path_pressures,
            has_legacy_viewport,
        }
    }

    pub fn reload(
        local_elements: &mut IndexMap<Uuid, EditableElement>, local_weak_images: &mut WeakImages,
        local_weak_pressures: &mut WeakPathPressures, base_buffer: &Self, remote_buffer: &Self,
    ) {
        // todo: convert weak images
        for (id, base_img) in base_buffer.weak_images.iter() {
            if let Some(remote_img) = remote_buffer.weak_images.get(id) {
                if remote_img != base_img {
                    local_weak_images.insert(*id, *remote_img);
                }
            } else {
                // this was deleted remotly
                local_weak_images.remove(id);
                local_elements.shift_remove(id);
            }
        }

        for (id, remote_img) in remote_buffer.weak_images.iter() {
            if !base_buffer.weak_images.contains_key(id) {
                local_weak_images.insert(*id, *remote_img);
            }
        }

        base_buffer
            .elements
            .iter()
            .filter_map(
                |(id, el)| if let EditableElement::Path(p) = el { Some((id, p)) } else { None },
            )
            .for_each(|(id, base_path)| {
                if let Some(EditableElement::Path(remote_path)) = remote_buffer.elements.get(id) {
                    if remote_path != base_path {
                        // this element was changed remotly
                        let mut transformed_path = remote_path.clone();
                        transformed_path.diff_state.transformed = None;
                        transformed_path.diff_state.data_changed = true;

                        local_elements.insert(*id, EditableElement::Path(transformed_path.clone()));

                        if let Some(remote_pressure) = remote_buffer.weak_path_pressures.get(id) {
                            local_weak_pressures.insert(*id, remote_pressure.clone());
                        }
                    }
                } else {
                    // this was deleted remotely
                    local_elements.shift_remove(id);
                    local_weak_pressures.remove(id);
                }
            });

        // strokes new in remote go after the nearest preceding stroke that local still has
        let mut cursor = 0;
        for (id, el) in remote_buffer.elements.iter() {
            let EditableElement::Path(remote_el) = el else { continue };
            if base_buffer.elements.contains_key(id) {
                if let Some(pos) = local_elements.get_index_of(id) {
                    cursor = pos + 1;
                }
            } else if !local_elements.contains_key(id) {
                let mut transformed_path = remote_el.clone();

                transformed_path.diff_state.data_changed = true;
                transformed_path.diff_state.transformed = None;

                local_elements.insert_before(cursor, *id, EditableElement::Path(transformed_path));
                cursor += 1;
                if let Some(base_pressure) = remote_buffer.weak_path_pressures.get(id) {
                    local_weak_pressures.insert(*id, base_pressure.clone());
                }
            }
        }
    }

    pub fn insert(&mut self, id: Uuid, mut el: EditableElement) {
        match el {
            EditableElement::Path(ref mut path) => {
                path.diff_state.data_changed = true;
                path.diff_state.transformed = None
            }
            EditableElement::Image(ref mut image) => {
                image.diff_state.data_changed = true;
                image.diff_state.transformed = None
            }
            _ => {}
        }
        self.elements.insert_before(0, id, el);
    }

    pub fn hard_remove(&mut self, id: Uuid) {
        self.elements.shift_remove(&id);
    }

    /// soft remove that marks the element as deleted but retains it in memeory
    pub fn remove(&mut self, id: Uuid) {
        if let Some(el) = self.elements.get_mut(&id) {
            match el {
                EditableElement::Path(path) => {
                    path.deleted = true;
                    path.diff_state.delete_changed = true;
                }
                EditableElement::Image(image) => {
                    image.deleted = true;
                    image.diff_state.delete_changed = true;
                }
                _ => {}
            }
        }
    }
    pub fn serialize(&self) -> String {
        serialize_inner(&self.id_map, &self.elements, &self.weak_images, &self.weak_path_pressures)
    }
}

pub fn serialize_inner(
    id_map: &HashMap<Uuid, String>, elements: &IndexMap<Uuid, EditableElement>,
    buffer_weak_images: &WeakImages, weak_pressures: &WeakPathPressures,
) -> String {
    let mut root = String::from(r#"<svg xmlns="http://www.w3.org/2000/svg">"#);
    let mut weak_images = WeakImages::default();

    for (index, (id, element)) in elements.iter().enumerate() {
        let svg_id = id_map.get(id).cloned().unwrap_or_else(|| id.to_string());
        let mut context = SvgSerializationContext {
            id: *id,
            svg_id: &svg_id,
            z_index: index,
            weak_images: &mut weak_images,
        };
        root.push_str(&element.to_string(&mut context));
    }

    weak_images.extend(buffer_weak_images.iter());

    if !weak_images.is_empty() {
        let binary_data = bincode::serialize(&weak_images).expect("Failed to serialize");
        let base64_data = base64::encode(&binary_data);

        let _ = write!(&mut root, "<g id=\"{WEAK_IMAGE_G_ID}\"> <g id=\"{base64_data}\"></g></g>");
    }

    if !weak_pressures.is_empty() {
        let binary_data = bincode::serialize(&weak_pressures).expect("Failed to serialize");
        let base64_data = base64::encode(&binary_data);

        let _ = write!(
            &mut root,
            "<g id=\"{WEAK_PATH_PRESSURES_G_ID}\"> <g id=\"{base64_data}\"></g></g>"
        );
    }

    root.push_str("</svg>");
    root
}

pub fn parse_child(
    u_el: &usvg::Node, elements: &mut IndexMap<Uuid, EditableElement>,
    weak_viewport_settings: &mut WeakViewportSettings, id_map: &mut HashMap<Uuid, String>,
    weak_images: &mut WeakImages, weak_path_pressures: &mut WeakPathPressures,
) {
    match &u_el {
        usvg::Node::Group(group) => {
            if group.id().eq(WEAK_IMAGE_G_ID) {
                if let Some(usvg::Node::Group(weak_images_g)) = group.children().first() {
                    let base64 = base64::decode(weak_images_g.id().as_bytes())
                        .expect("Failed to decode base64");

                    let decoded: WeakImages = bincode::deserialize(&base64).unwrap_or_default();
                    *weak_images = decoded;
                }
            } else if group.id().eq(WEAK_PATH_PRESSURES_G_ID) {
                if let Some(usvg::Node::Group(weak_pressures_g)) = group.children().first() {
                    let base64 = base64::decode(weak_pressures_g.id().as_bytes())
                        .expect("Failed to decode base64");

                    let decoded: WeakPathPressures =
                        bincode::deserialize(&base64).unwrap_or_default();
                    *weak_path_pressures = decoded;
                }
            } else if group.id().eq(WEAK_VIEWPORT_SETTINGS_G_ID) {
                if let Some(usvg::Node::Group(weak_viewport_settings_g)) = group.children().first()
                {
                    let base64 = base64::decode(weak_viewport_settings_g.id().as_bytes())
                        .expect("Failed to decode base64");

                    let decoded: WeakViewportSettings =
                        bincode::deserialize(&base64).unwrap_or_default();
                    *weak_viewport_settings = decoded;
                }
            } else {
                group.children().iter().for_each(|u_el| {
                    parse_child(
                        u_el,
                        elements,
                        weak_viewport_settings,
                        id_map,
                        weak_images,
                        weak_path_pressures,
                    )
                });
            }
        }

        usvg::Node::Image(_) => {}
        usvg::Node::Path(path) => {
            let diff_state = DiffState { data_changed: true, ..Default::default() };

            let id = get_internal_id(path.id(), id_map);

            let stroke = if let Some(s) = path.stroke() {
                if let Paint::Color(color) = *s.paint() {
                    let maybe_dynamic_color =
                        get_dyn_color(Color::new_rgb(color.red, color.green, color.blue));

                    Some(Stroke {
                        color: maybe_dynamic_color,
                        opacity: s.opacity().get(),
                        width: s.width().get(),
                    })
                } else {
                    None
                }
            } else {
                None
            };
            let data = usvg_d_to_subpath(path);

            elements.insert(
                id,
                EditableElement::Path(Path {
                    data,
                    visible: path.is_visible(),
                    fill: path.fill().cloned(),
                    stroke,
                    transform: path.abs_transform(),
                    diff_state,
                    deleted: false,
                }),
            );
        }
        _ => {}
    }
}

pub fn get_dyn_color(color: Color) -> DynamicColor {
    let canvas_colors = get_canvas_colors();

    let maybe_dynamic_color = if let Some(dynamic_color) = canvas_colors
        .iter()
        .find(|c| c.light.eq(&color) || c.dark.eq(&color))
    {
        *dynamic_color
    } else {
        DynamicColor { light: color, dark: color }
    };
    maybe_dynamic_color
}

fn get_internal_id(svg_id: &str, id_map: &mut HashMap<Uuid, String>) -> Uuid {
    let id: Uuid = svg_id.parse().unwrap_or(Uuid::new_v4());

    if id_map.insert(id, svg_id.to_owned()).is_some() {
        warn!(id = svg_id, "found elements  with duplicate id");
    }
    id
}

pub fn get_canvas_colors() -> Vec<DynamicColor> {
    let mut highlighter_colors = get_highlighter_colors();
    highlighter_colors.append(&mut get_pen_colors());

    highlighter_colors
}

pub fn get_highlighter_colors() -> Vec<DynamicColor> {
    let yellow =
        DynamicColor { light: Color::new_rgb(244, 250, 65), dark: Color::new_rgb(244, 250, 65) };
    let blue =
        DynamicColor { light: Color::new_rgb(65, 194, 250), dark: Color::new_rgb(65, 194, 250) };
    let pink =
        DynamicColor { light: Color::new_rgb(254, 110, 175), dark: Color::new_rgb(254, 110, 175) };
    vec![yellow, blue, pink]
}

pub fn get_pen_colors() -> Vec<DynamicColor> {
    let red =
        DynamicColor { light: Color::new_rgb(218, 21, 21), dark: Color::new_rgb(174, 33, 33) };
    let orange =
        DynamicColor { light: Color::new_rgb(255, 149, 0), dark: Color::new_rgb(255, 159, 10) };
    let yellow =
        DynamicColor { light: Color::new_rgb(255, 204, 0), dark: Color::new_rgb(255, 214, 10) };
    let green =
        DynamicColor { light: Color::new_rgb(42, 136, 49), dark: Color::new_rgb(56, 176, 65) };
    let teal =
        DynamicColor { light: Color::new_rgb(0, 128, 128), dark: Color::new_rgb(0, 147, 147) };
    let cyan =
        DynamicColor { light: Color::new_rgb(85, 190, 240), dark: Color::new_rgb(90, 200, 245) };
    let blue =
        DynamicColor { light: Color::new_rgb(62, 130, 230), dark: Color::new_rgb(54, 116, 207) };
    let indigo =
        DynamicColor { light: Color::new_rgb(75, 0, 130), dark: Color::new_rgb(64, 0, 110) };
    let purple =
        DynamicColor { light: Color::new_rgb(128, 0, 128), dark: Color::new_rgb(147, 0, 147) };
    let magenta =
        DynamicColor { light: Color::new_rgb(175, 82, 222), dark: Color::new_rgb(191, 90, 242) };
    let pink =
        DynamicColor { light: Color::new_rgb(255, 105, 180), dark: Color::new_rgb(255, 120, 190) };
    let brown =
        DynamicColor { light: Color::new_rgb(139, 69, 19), dark: Color::new_rgb(101, 53, 17) };

    let fg = DynamicColor { light: Color::black(), dark: Color::white() };

    vec![fg, red, orange, yellow, green, teal, cyan, blue, indigo, purple, brown, magenta, pink]
}

pub fn get_background_colors() -> Vec<DynamicColor> {
    let pastel_blue =
        DynamicColor { light: Color::new_rgb(226, 235, 240), dark: Color::new_rgb(5, 15, 26) };

    let soft_pink_beige =
        DynamicColor { light: Color::new_rgb(240, 230, 230), dark: Color::new_rgb(25, 16, 14) };

    let warm_gray =
        DynamicColor { light: Color::new_rgb(238, 236, 230), dark: Color::new_rgb(22, 21, 20) };

    let nice_green =
        DynamicColor { light: Color::new_rgb(226, 240, 228), dark: Color::new_rgb(10, 23, 16) };

    let bg = DynamicColor { light: Color::white(), dark: Color::black() };

    vec![soft_pink_beige, warm_gray, nice_green, pastel_blue, bg]
}

fn usvg_d_to_subpath(path: &usvg::Path) -> Subpath<ManipulatorGroupId> {
    let mut prev = Point::default();
    let mut subpath: Subpath<ManipulatorGroupId> = Subpath::new(vec![], false);
    for segment in path.data().segments() {
        match segment {
            PathSegment::MoveTo(p) => {
                prev = p;
            }
            PathSegment::CubicTo(p1, p2, p3) => {
                let bez = Bezier::from_cubic_coordinates(
                    prev.x.into(),
                    prev.y.into(),
                    p1.x.into(),
                    p1.y.into(),
                    p2.x.into(),
                    p2.y.into(),
                    p3.x.into(),
                    p3.y.into(),
                );
                subpath.append_bezier(&bez, bezier_rs::AppendType::IgnoreStart);
                prev = p3;
            }
            PathSegment::LineTo(p) => {
                let bez = Bezier::from_linear_coordinates(
                    prev.x.into(),
                    prev.y.into(),
                    p.x.into(),
                    p.y.into(),
                );
                subpath.append_bezier(&bez, bezier_rs::AppendType::IgnoreStart);
                prev = p;
            }
            _ => {}
        }
    }

    let t = path.abs_transform();

    subpath.apply_transform(DAffine2 {
        matrix2: DMat2 {
            x_axis: DVec2 { x: t.sx.into(), y: t.ky.into() },
            y_axis: DVec2 { x: t.kx.into(), y: t.sy.into() },
        },
        translation: DVec2 { x: t.tx.into(), y: t.ty.into() },
    });

    subpath
}

pub fn u_transform_to_bezier(src: &Transform) -> DAffine2 {
    glam::DAffine2 {
        matrix2: DMat2 {
            x_axis: DVec2 { x: src.sx.into(), y: src.ky.into() },
            y_axis: DVec2 { x: src.kx.into(), y: src.sy.into() },
        },
        translation: glam::DVec2 { x: src.tx.into(), y: src.ty.into() },
    }
}