Skip to main content

mln_style/style/
diff.rs

1//! What changed between two versions of a style, which the renderer reads
2//! to find what to redo: [`StyleDiff`].
3
4use std::cmp::Ordering;
5use std::sync::Arc;
6
7use crate::collections::VecMap;
8use crate::layer::LayerList;
9use crate::source::{Source, SourceList};
10use crate::style::Style;
11use crate::{image, sort};
12
13/// How a layer differs between two layer lists.
14#[derive(Clone, Copy, PartialEq, Eq, Debug)]
15pub enum LayerChange {
16    /// Only in the new list.
17    Added,
18    /// Only in the old list.
19    Removed,
20    /// In both, as another type: a removal and an addition.
21    Replaced,
22    /// In both, with other values that only need evaluating again.
23    Restyled,
24    /// In both, with other values that tiles are laid out with, so its
25    /// source lays them out again.
26    Relaid,
27}
28
29impl LayerChange {
30    /// Whether the change needs the layer's tiles laid out again.
31    #[must_use]
32    pub fn relayouts(self) -> bool {
33        matches!(self, LayerChange::Added | LayerChange::Replaced | LayerChange::Relaid)
34    }
35
36    /// Whether the layer leaves the old list's render layers.
37    #[must_use]
38    pub fn removes(self) -> bool {
39        matches!(self, LayerChange::Removed | LayerChange::Replaced)
40    }
41
42    /// Whether the layer needs a new render layer.
43    #[must_use]
44    pub fn adds(self) -> bool {
45        matches!(self, LayerChange::Added | LayerChange::Replaced)
46    }
47
48    /// Whether the layer keeps its render layer with new values.
49    #[must_use]
50    pub fn restyles(self) -> bool {
51        matches!(self, LayerChange::Restyled | LayerChange::Relaid)
52    }
53}
54
55/// The layers that differ between two layer lists, by id. A layer whose
56/// style data is the same `Arc` in both lists has no entry.
57#[derive(Clone, Debug, Default)]
58pub struct LayerChanges {
59    changes: VecMap<Arc<str>, LayerChange>,
60    /// Whether the layers in both lists are in another order, or a layer was
61    /// added or removed: the drawing order needs building again.
62    pub order_changed: bool,
63}
64
65impl LayerChanges {
66    /// What changed from `old` to `new`. A layer found in both is matched by
67    /// id, wherever it is: one that only moved has no entry, and sets
68    /// `order_changed`.
69    #[must_use]
70    pub fn between(old: &Arc<LayerList>, new: &Arc<LayerList>) -> LayerChanges {
71        if Arc::ptr_eq(old, new) {
72            return LayerChanges::default();
73        }
74        let mut changes: Vec<(Arc<str>, LayerChange)> = Vec::new();
75        let mut order_changed = false;
76        let mut previous_index = None;
77        for layer in new.iter() {
78            let Some((index, before)) = old.get_full(layer.id()) else {
79                changes.push((Arc::from(layer.id()), LayerChange::Added));
80                continue;
81            };
82            let (before, after) = (before.style(), layer.style());
83            if before.info().name != after.info().name {
84                changes.push((Arc::from(layer.id()), LayerChange::Replaced));
85                continue;
86            }
87            order_changed |= previous_index.is_some_and(|previous| index < previous);
88            previous_index = Some(index);
89            if Arc::ptr_eq(before, after) {
90                continue;
91            }
92            let change = if before.layout_difference(&**after) { LayerChange::Relaid } else { LayerChange::Restyled };
93            changes.push((Arc::from(layer.id()), change));
94        }
95        for layer in old.iter() {
96            if new.get(layer.id()).is_none() {
97                changes.push((Arc::from(layer.id()), LayerChange::Removed));
98            }
99        }
100        sort::sort_by(&mut changes, |(a, _), (b, _)| a.cmp(b));
101        let changes: VecMap<Arc<str>, LayerChange> = changes.into_iter().collect();
102        let order_changed = order_changed || changes.values().any(|change| !change.restyles());
103        LayerChanges { changes, order_changed }
104    }
105
106    /// The change of the layer `id`, if it changed.
107    #[must_use]
108    pub fn get(&self, id: &str) -> Option<LayerChange> {
109        self.changes.get(id).copied()
110    }
111
112    /// Each changed layer's id and change, in id order.
113    pub fn iter(&self) -> impl Iterator<Item = (&Arc<str>, LayerChange)> {
114        self.changes.iter().map(|(id, change)| (id, *change))
115    }
116
117    #[must_use]
118    pub fn is_empty(&self) -> bool {
119        self.changes.is_empty()
120    }
121}
122
123/// The items, by id, that differ between two id-sorted lists of shared
124/// values: sources or images.
125pub struct ItemChanges<V> {
126    /// Only in the new list, or in both as another kind (a source of
127    /// another type).
128    pub added: VecMap<String, V>,
129    /// Only in the old list, or in both as another kind.
130    pub removed: VecMap<String, V>,
131    /// The new values of the items in both whose values differ.
132    pub changed: VecMap<String, V>,
133}
134
135impl<V> Default for ItemChanges<V> {
136    fn default() -> Self {
137        ItemChanges { added: VecMap::new(), removed: VecMap::new(), changed: VecMap::new() }
138    }
139}
140
141impl<V: Clone> ItemChanges<V> {
142    /// Merges `old` and `new`, both sorted by id with unique ids. An item
143    /// whose id is in both but that `same_kind` tells apart is removed and
144    /// added; one that `same` tells apart is changed.
145    fn between(
146        old: &[V],
147        new: &[V],
148        id: impl Fn(&V) -> &str,
149        same_kind: impl Fn(&V, &V) -> bool,
150        same: impl Fn(&V, &V) -> bool,
151    ) -> ItemChanges<V> {
152        let (mut removed, mut added, mut changed) = (Vec::new(), Vec::new(), Vec::new());
153        let (mut old_items, mut new_items) = (old.iter().peekable(), new.iter().peekable());
154        loop {
155            let order = match (old_items.peek(), new_items.peek()) {
156                (None, None) => break,
157                (Some(_), None) => Ordering::Less,
158                (None, Some(_)) => Ordering::Greater,
159                (Some(before), Some(after)) => id(before).cmp(id(after)),
160            };
161            match order {
162                Ordering::Less => removed.extend(old_items.next()),
163                Ordering::Greater => added.extend(new_items.next()),
164                Ordering::Equal => {
165                    let (Some(before), Some(after)) = (old_items.next(), new_items.next()) else { break };
166                    if !same_kind(before, after) {
167                        removed.push(before);
168                        added.push(after);
169                    } else if !same(before, after) {
170                        changed.push(after);
171                    }
172                }
173            }
174        }
175        // Each list is in id order, which the maps keep.
176        let map = |items: Vec<&V>| items.into_iter().map(|item| (id(item).to_owned(), item.clone())).collect();
177        ItemChanges { added: map(added), removed: map(removed), changed: map(changed) }
178    }
179}
180
181impl<V> ItemChanges<V> {
182    #[must_use]
183    pub fn is_empty(&self) -> bool {
184        self.added.is_empty() && self.removed.is_empty() && self.changed.is_empty()
185    }
186}
187
188/// The sources of `list` in id order.
189#[must_use]
190pub fn sources_by_id(list: &SourceList) -> Vec<Source> {
191    let mut sources: Vec<_> = list.iter().cloned().collect();
192    sort::sort_by(&mut sources, |a, b| a.id().cmp(b.id()));
193    sources
194}
195
196/// What a renderer has to redo to go from one version of a style to
197/// another: the change class of each layer, source and image.
198///
199/// It compares the two versions, not the edits between them, so it answers
200/// for however many versions came in between. Parts whose `Arc` is the same
201/// in both come out empty without a walk. Light, sky and global state
202/// aren't in it: a renderer compares them by their own pointers.
203#[derive(Default)]
204pub struct StyleDiff {
205    pub layers: LayerChanges,
206    /// A source of another type with the same id is removed and added.
207    pub sources: ItemChanges<Source>,
208    pub images: ItemChanges<Arc<image::StyleImage>>,
209}
210
211impl StyleDiff {
212    /// What changed from `old` to `new`. `None` is a renderer with nothing
213    /// yet, for which every layer, source and image of `new` is added.
214    #[must_use]
215    pub fn between(old: Option<&Style>, new: &Style) -> StyleDiff {
216        let empty_layers = Arc::default();
217        let old_layers = old.map_or(&empty_layers, Style::layer_list);
218        let layers = LayerChanges::between(old_layers, new.layer_list());
219
220        let sources = match old {
221            Some(old) if Arc::ptr_eq(old.sources(), new.sources()) => ItemChanges::default(),
222            _ => ItemChanges::between(
223                &old.map(|old| sources_by_id(old.sources())).unwrap_or_default(),
224                &sources_by_id(new.sources()),
225                Source::id,
226                |before, after| before.info().name == after.info().name,
227                Source::ptr_eq,
228            ),
229        };
230
231        let images = match old {
232            Some(old) if Arc::ptr_eq(old.images(), new.images()) => ItemChanges::default(),
233            _ => ItemChanges::between(
234                old.map_or(&[][..], |old| old.images().as_slice()),
235                new.images(),
236                |image| &image.id,
237                |_, _| true,
238                Arc::ptr_eq,
239            ),
240        };
241
242        StyleDiff { layers, sources, images }
243    }
244}
245
246#[cfg(test)]
247#[path = "diff_test.rs"]
248mod tests;