Skip to main content

gpui_kit_grid/
persist.rs

1//! Saved grid layouts: the data, its text format, how a saved layout meets
2//! the current schema, and named layouts per view.
3//!
4//! No GPUI types: widths are logical pixels as `f32` and identifiers are
5//! strings, so the module can move to `gpui-base` with `model` and `engine`.
6//! The grid applies a layout and validates the result; nothing here performs
7//! I/O.
8
9use std::{collections::BTreeMap, fmt};
10
11use rustc_hash::FxHashSet;
12use serde::{Deserialize, Deserializer, Serialize, Serializer};
13
14use crate::{
15    engine::{ExpandDepth, SortDirection},
16    model::{ColumnId, OwnedValue},
17    state::ColumnZone,
18};
19
20/// A saved grid layout: the columns by [`ColumnId`] in display order, each
21/// with its width, visibility and zone, the sort, and the grouping with the
22/// expansion of its groups.
23///
24/// Plain data without a GPUI entity and without the application's column
25/// type, so one value fits every grid of the same view. Serialize it with
26/// serde or a [`LayoutCodec`]. The grid resolves it against its schema when
27/// it is applied: unknown columns are ignored and new ones are added.
28///
29/// The format is version 1 ([`GridLayout::VERSION`]). Defaults are not
30/// written: no `view_id` when there is none, no `visible` for a visible
31/// column, no `frozen` for a scrolling one, no `sort` or `group_by` when it
32/// is empty, and no `expansion` when every group is expanded and none is
33/// toggled. Reading ignores unknown fields, so a newer build can add an
34/// optional field without a new version, as `group_by` and `expansion` were
35/// added; an older build drops that field when it saves again.
36///
37/// Deserializing with serde keeps the version the data carries. The codec
38/// refuses a version this build does not read, and so does the grid when it
39/// applies a layout.
40///
41/// ```
42/// use gpui_kit_grid::{
43///     ColumnZone, GridLayout, JsonLayoutCodec, LayoutCodec, LayoutColumn, LayoutSort,
44///     SortDirection,
45/// };
46///
47/// let layout = GridLayout::new()
48///     .with_view_id("trades")
49///     .with_column(LayoutColumn::new("id", 80_f32).with_zone(ColumnZone::FrozenLeft))
50///     .with_column(LayoutColumn::new("price", 100_f32))
51///     .with_column(LayoutColumn::new("fee", 90_f32).with_visible(false))
52///     .with_sort([LayoutSort::new("price", SortDirection::Descending)]);
53///
54/// let codec = JsonLayoutCodec::default();
55/// let text = codec.encode(&layout)?;
56/// assert_eq!(
57///     text,
58///     concat!(
59///         r#"{"version":1,"view_id":"trades","columns":["#,
60///         r#"{"id":"id","width":80.0,"frozen":"left"},"#,
61///         r#"{"id":"price","width":100.0},"#,
62///         r#"{"id":"fee","width":90.0,"visible":false}],"#,
63///         r#""sort":[{"column":"price","direction":"descending"}]}"#,
64///     )
65/// );
66/// assert_eq!(codec.decode(&text)?, layout);
67/// # Ok::<(), gpui_kit_grid::LayoutError>(())
68/// ```
69///
70/// # Grouping and expansion
71///
72/// `group_by` names the grouping levels by column, the top level first. A
73/// layout without levels has no grouping: applying it removes the grid's
74/// grouping. `expansion` keeps the default depth and the groups the user
75/// toggled against it, each as its key values from the top level down; a
76/// value is never an index, and the levels of the same layout name its
77/// columns.
78///
79/// ```
80/// use gpui_kit_grid::{
81///     ExpandDepth, GridLayout, JsonLayoutCodec, LayoutCodec, LayoutExpansion, LayoutGroup,
82///     OwnedValue, SortDirection,
83/// };
84///
85/// let aapl = OwnedValue::Text("AAPL".into());
86/// let layout = GridLayout::new()
87///     .with_group_by([
88///         LayoutGroup::new("instrument", SortDirection::Ascending),
89///         LayoutGroup::new("side", SortDirection::Descending),
90///     ])
91///     .with_expansion(LayoutExpansion::new(ExpandDepth::All).with_toggled([aapl]));
92///
93/// let codec = JsonLayoutCodec::default();
94/// let text = codec.encode(&layout)?;
95/// assert_eq!(
96///     text,
97///     concat!(
98///         r#"{"version":1,"columns":[],"group_by":["#,
99///         r#"{"column":"instrument","direction":"ascending"},"#,
100///         r#"{"column":"side","direction":"descending"}],"#,
101///         r#""expansion":{"depth":"all","toggled":[["AAPL"]]}}"#,
102///     )
103/// );
104/// assert_eq!(codec.decode(&text)?, layout);
105/// # Ok::<(), gpui_kit_grid::LayoutError>(())
106/// ```
107///
108/// # Saving a grid in a dock panel
109///
110/// The grid does no I/O and does not depend on the dock. A panel hands its
111/// grid's layout to the dock in `Panel::dump`, and the panel's builder in the
112/// registry (`register_panel`) gives it back to `with_layout`.
113/// `LiveGridState::layout` reads state only, so a panel in a tab that was
114/// never shown saves its layout too. The complete, tested version is
115/// `crates/grid/tests/dock.rs`.
116///
117/// ```ignore
118/// const TRADES: &str = "trades";
119///
120/// impl TradesPanel {
121///     fn new(layout: Option<GridLayout>, cx: &mut Context<Self>) -> Self {
122///         let grid = cx.new(|cx| {
123///             let grid = LiveGridState::new_standalone(schema(), Trades, StoreOptions::default(), cx)
124///                 .with_view_id(TRADES);
125///             match layout {
126///                 Some(layout) => grid.with_layout(layout),
127///                 None => grid,
128///             }
129///         });
130///         Self { grid, focus_handle: cx.focus_handle() }
131///     }
132/// }
133///
134/// impl BasePanel for TradesPanel {
135///     fn panel_name(&self) -> &'static str {
136///         TRADES
137///     }
138///
139///     /// The dock pulls the layout when it saves; the grid needs no render.
140///     fn dump(&self, cx: &App) -> PanelState {
141///         let mut state = PanelState::new(TRADES);
142///         let layout = self.grid.read(cx).layout();
143///         state.info = PanelInfo::panel(serde_json::json!({ "grid": layout }));
144///         state
145///     }
146/// }
147///
148/// // At startup, before `DockArea::load`. A bad layout opens the panel with
149/// // the schema's layout instead of failing the load; `with_layout` ignores
150/// // a layout of a newer version.
151/// register_panel(cx, TRADES, |context, _window, cx| {
152///     let layout = match context.info() {
153///         PanelInfo::Panel(value) => value
154///             .get("grid")
155///             .and_then(|grid| serde_json::from_value::<GridLayout>(grid.clone()).ok()),
156///         _ => None,
157///     };
158///     panel_handle(cx.new(|cx| TradesPanel::new(layout, cx)))
159/// });
160/// ```
161///
162/// The dock saves on its own edits only (`DockEvent::LayoutChanged`), so
163/// changes inside a panel must trigger a save too. They are the grid's
164/// `LayoutChange`, `SortChange`, `GroupChange` and `ExpansionChange` events,
165/// which come at once, once per finished gesture or call. The application
166/// delays the write (0.5–1 s), since groups are expanded and collapsed as
167/// often as a chevron is clicked, and also writes when it quits.
168///
169/// ```ignore
170/// cx.subscribe(&grid, |app, _, event: &LiveGridEvent<u64, TradeColumn>, cx| {
171///     if matches!(
172///         event,
173///         LiveGridEvent::LayoutChange { .. }
174///             | LiveGridEvent::SortChange { .. }
175///             | LiveGridEvent::GroupChange { .. }
176///             | LiveGridEvent::ExpansionChange { .. }
177///     ) {
178///         app.schedule_save(cx);
179///     }
180/// })
181/// .detach();
182/// ```
183#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
184#[non_exhaustive]
185pub struct GridLayout {
186    version: u32,
187    #[serde(default, skip_serializing_if = "Option::is_none")]
188    view_id: Option<String>,
189    columns: Vec<LayoutColumn>,
190    #[serde(default, skip_serializing_if = "Vec::is_empty")]
191    sort: Vec<LayoutSort>,
192    #[serde(default, skip_serializing_if = "Vec::is_empty")]
193    group_by: Vec<LayoutGroup>,
194    #[serde(default, skip_serializing_if = "LayoutExpansion::is_unwritten")]
195    expansion: LayoutExpansion,
196}
197
198impl GridLayout {
199    /// The format version this build writes and the newest it reads.
200    pub const VERSION: u32 = 1;
201
202    /// An empty layout of the current version, without a view id.
203    pub fn new() -> Self {
204        Self {
205            version: Self::VERSION,
206            view_id: None,
207            columns: Vec::new(),
208            sort: Vec::new(),
209            group_by: Vec::new(),
210            expansion: LayoutExpansion::default(),
211        }
212    }
213
214    /// Names the view the layout belongs to ("trades"). A grid with another
215    /// view id refuses the layout.
216    pub fn with_view_id(mut self, view_id: impl Into<String>) -> Self {
217        self.view_id = Some(view_id.into());
218        self
219    }
220
221    /// Appends a column; the order of columns is the display order.
222    pub fn with_column(mut self, column: LayoutColumn) -> Self {
223        self.columns.push(column);
224        self
225    }
226
227    /// Replaces the sort; the first key sorts first.
228    pub fn with_sort(mut self, sort: impl IntoIterator<Item = LayoutSort>) -> Self {
229        self.sort = sort.into_iter().collect();
230        self
231    }
232
233    /// Replaces the grouping levels; the first level groups first. No levels
234    /// is no grouping.
235    pub fn with_group_by(mut self, levels: impl IntoIterator<Item = LayoutGroup>) -> Self {
236        self.group_by = levels.into_iter().collect();
237        self
238    }
239
240    /// Replaces the expansion of groups. The default, every group expanded
241    /// and none toggled, is not written.
242    pub fn with_expansion(mut self, expansion: LayoutExpansion) -> Self {
243        self.expansion = expansion;
244        self
245    }
246
247    /// The format version the layout was written in.
248    pub fn version(&self) -> u32 {
249        self.version
250    }
251
252    /// The view the layout belongs to, if it names one.
253    pub fn view_id(&self) -> Option<&str> {
254        self.view_id.as_deref()
255    }
256
257    /// The columns in display order, as saved: they may include columns the
258    /// schema no longer has, and repeats.
259    pub fn columns(&self) -> &[LayoutColumn] {
260        &self.columns
261    }
262
263    /// The first saved column with this id.
264    pub fn column(&self, id: &str) -> Option<&LayoutColumn> {
265        self.columns.iter().find(|column| column.id.as_str() == id)
266    }
267
268    /// The sort keys, first key first.
269    pub fn sort(&self) -> &[LayoutSort] {
270        &self.sort
271    }
272
273    /// The grouping levels, the top level first, as saved: they may name
274    /// columns the schema no longer has or cannot group, and repeats.
275    pub fn group_by(&self) -> &[LayoutGroup] {
276        &self.group_by
277    }
278
279    /// The expansion of groups; `None` when the layout keeps the default:
280    /// every group expanded and none toggled.
281    pub fn expansion(&self) -> Option<&LayoutExpansion> {
282        (!self.expansion.is_default()).then_some(&self.expansion)
283    }
284}
285
286/// One column of a saved layout.
287#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
288#[non_exhaustive]
289pub struct LayoutColumn {
290    id: ColumnId,
291    #[serde(deserialize_with = "deserialize_width")]
292    width: f32,
293    #[serde(default = "default_visible", skip_serializing_if = "is_visible")]
294    visible: bool,
295    #[serde(
296        rename = "frozen",
297        default,
298        skip_serializing_if = "is_scrolling",
299        with = "frozen"
300    )]
301    zone: ColumnZone,
302}
303
304impl LayoutColumn {
305    /// A visible, scrolling column. `width` is in logical pixels, so a
306    /// layout saved on a Retina screen opens with the same widths on a 1×
307    /// screen; it accepts `f32` or GPUI `Pixels`. A literal names its type
308    /// (`80_f32` or `px(80.)`): Rust does not infer `f32` through `Into`.
309    pub fn new(id: impl Into<ColumnId>, width: impl Into<f32>) -> Self {
310        Self {
311            id: id.into(),
312            width: width.into(),
313            visible: true,
314            zone: ColumnZone::Scrolling,
315        }
316    }
317
318    /// Sets the width in logical pixels. The grid clamps it to the column's
319    /// limits and replaces a width that is not a positive number.
320    pub fn with_width(mut self, width: impl Into<f32>) -> Self {
321        self.width = width.into();
322        self
323    }
324
325    /// Shows or hides the column. Default: visible.
326    pub fn with_visible(mut self, visible: bool) -> Self {
327        self.visible = visible;
328        self
329    }
330
331    /// Sets the zone. Default: [`ColumnZone::Scrolling`].
332    pub fn with_zone(mut self, zone: ColumnZone) -> Self {
333        self.zone = zone;
334        self
335    }
336
337    /// The column's identifier.
338    pub fn id(&self) -> &ColumnId {
339        &self.id
340    }
341
342    /// The width in logical pixels, as saved.
343    pub fn width(&self) -> f32 {
344        self.width
345    }
346
347    /// Returns true if the column is shown.
348    pub fn is_visible(&self) -> bool {
349        self.visible
350    }
351
352    /// The zone the column is shown in.
353    pub fn zone(&self) -> ColumnZone {
354        self.zone
355    }
356}
357
358fn default_visible() -> bool {
359    true
360}
361
362fn is_visible(visible: &bool) -> bool {
363    *visible
364}
365
366fn is_scrolling(zone: &ColumnZone) -> bool {
367    *zone == ColumnZone::Scrolling
368}
369
370/// JSON has no NaN or infinity, and serde_json writes them as `null`. Read
371/// `null` back as NaN, which the grid replaces with the schema width, so a
372/// written layout always reads back.
373fn deserialize_width<'de, D: Deserializer<'de>>(deserializer: D) -> Result<f32, D::Error> {
374    Ok(Option::<f32>::deserialize(deserializer)?.unwrap_or(f32::NAN))
375}
376
377/// The zone as the `frozen` field: `"left"`, `"right"`, or absent for a
378/// scrolling column. The format lives here rather than in the names of the
379/// `ColumnZone` variants, so renaming a variant cannot change saved layouts.
380mod frozen {
381    use serde::{Deserialize, Deserializer, Serialize, Serializer};
382
383    use crate::state::ColumnZone;
384
385    #[derive(Serialize, Deserialize)]
386    #[serde(rename_all = "lowercase")]
387    enum FrozenSide {
388        Left,
389        Right,
390    }
391
392    pub(super) fn serialize<S: Serializer>(
393        zone: &ColumnZone,
394        serializer: S,
395    ) -> Result<S::Ok, S::Error> {
396        match zone {
397            ColumnZone::FrozenLeft => Some(FrozenSide::Left),
398            ColumnZone::Scrolling => None,
399            ColumnZone::FrozenRight => Some(FrozenSide::Right),
400        }
401        .serialize(serializer)
402    }
403
404    pub(super) fn deserialize<'de, D: Deserializer<'de>>(
405        deserializer: D,
406    ) -> Result<ColumnZone, D::Error> {
407        Ok(match Option::<FrozenSide>::deserialize(deserializer)? {
408            Some(FrozenSide::Left) => ColumnZone::FrozenLeft,
409            None => ColumnZone::Scrolling,
410            Some(FrozenSide::Right) => ColumnZone::FrozenRight,
411        })
412    }
413}
414
415/// One sort key of a saved layout.
416#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
417pub struct LayoutSort {
418    column: ColumnId,
419    direction: SortDirection,
420}
421
422impl LayoutSort {
423    /// A sort key on a column.
424    pub fn new(column: impl Into<ColumnId>, direction: SortDirection) -> Self {
425        Self {
426            column: column.into(),
427            direction,
428        }
429    }
430
431    /// The sorted column.
432    pub fn column(&self) -> &ColumnId {
433        &self.column
434    }
435
436    /// The direction.
437    pub fn direction(&self) -> SortDirection {
438        self.direction
439    }
440}
441
442/// One grouping level of a saved layout: a column and the order of its
443/// groups. Serialized as a sort key is:
444/// `{"column": "instrument", "direction": "ascending"}`.
445///
446/// A level that groups by a function of the row (`GroupKey`) has no column
447/// and is not saved: a function cannot be read back from a file.
448#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
449#[non_exhaustive]
450pub struct LayoutGroup {
451    column: ColumnId,
452    direction: SortDirection,
453}
454
455impl LayoutGroup {
456    /// A grouping level on a column, its groups in `direction`.
457    pub fn new(column: impl Into<ColumnId>, direction: SortDirection) -> Self {
458        Self {
459            column: column.into(),
460            direction,
461        }
462    }
463
464    /// The grouped column.
465    pub fn column(&self) -> &ColumnId {
466        &self.column
467    }
468
469    /// The order of the level's groups.
470    pub fn direction(&self) -> SortDirection {
471        self.direction
472    }
473}
474
475/// The saved expansion of groups: the default depth, and the groups the
476/// user toggled against it. A toggled group is its key values from the top
477/// level down, one per level of the layout's `group_by`; the levels name the
478/// columns, so a path holds values only.
479///
480/// Serialized as `{"depth": "all", "toggled": [["AAPL"], ["MSFT", "Sell"]]}`.
481/// `depth` is `"all"`, `"captions"` or the number of expanded levels
482/// ([`ExpandDepth`]); a value is written as an [`OwnedValue`] is, so `12`
483/// reads back as an integer and `12.0` as a float. `toggled` is not written
484/// when it is empty. JSON has no NaN or infinity: a path with one is not
485/// written, and that group's toggle is not saved.
486///
487/// Reading drops a path with a value this build cannot hold, such as a
488/// decimal without the `decimal` feature or a kind of value a newer build
489/// added, and keeps the rest of the layout; the grid's
490/// [`LayoutReport::dropped_expansion`] counts it. Tree rows are not saved:
491/// their keys are the application's own type.
492#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
493#[non_exhaustive]
494pub struct LayoutExpansion {
495    #[serde(default)]
496    depth: ExpandDepth,
497    #[serde(default, skip_serializing_if = "TogglePaths::is_unwritten")]
498    toggled: TogglePaths,
499}
500
501impl LayoutExpansion {
502    /// `depth`, with no group toggled.
503    pub fn new(depth: ExpandDepth) -> Self {
504        Self {
505            depth,
506            toggled: TogglePaths::default(),
507        }
508    }
509
510    /// Adds a group toggled against the depth: its key values, the top level
511    /// first.
512    pub fn with_toggled(mut self, path: impl IntoIterator<Item = OwnedValue>) -> Self {
513        self.toggled.paths.push(path.into_iter().collect());
514        self
515    }
516
517    /// The default depth.
518    pub fn depth(&self) -> ExpandDepth {
519        self.depth
520    }
521
522    /// The toggled groups in saved order, each as its key values from the
523    /// top level down.
524    pub fn toggled(&self) -> &[Vec<OwnedValue>] {
525        &self.toggled.paths
526    }
527
528    /// Returns true for the default: every group expanded, none toggled.
529    pub fn is_default(&self) -> bool {
530        self.depth == ExpandDepth::All && self.toggled.paths.is_empty()
531    }
532
533    /// Returns true if writing would give the default: `ExpandDepth::All`
534    /// and no path that JSON can hold.
535    fn is_unwritten(&self) -> bool {
536        self.depth == ExpandDepth::All && self.toggled.is_unwritten()
537    }
538}
539
540/// The toggled groups of a [`LayoutExpansion`], and the number of saved
541/// paths that could not be read.
542#[derive(Clone, Debug, Default, PartialEq, Eq)]
543struct TogglePaths {
544    paths: Vec<Vec<OwnedValue>>,
545    /// Saved paths with a value this build cannot hold: dropped when read,
546    /// counted by the report, never written.
547    unreadable: usize,
548}
549
550impl TogglePaths {
551    fn is_unwritten(&self) -> bool {
552        !self.paths.iter().any(|path| is_writable(path))
553    }
554}
555
556/// JSON has no NaN or infinity, so a path with one is not written.
557fn is_writable(path: &[OwnedValue]) -> bool {
558    path.iter()
559        .all(|value| !matches!(value, OwnedValue::Float(float) if !float.is_finite()))
560}
561
562impl Serialize for TogglePaths {
563    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
564        serializer.collect_seq(self.paths.iter().filter(|path| is_writable(path)))
565    }
566}
567
568impl<'de> Deserialize<'de> for TogglePaths {
569    /// A list of lists, or the layout is not read. Each value is read as
570    /// JSON first, so a value this build cannot hold drops its path only.
571    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
572        let saved = Vec::<Vec<serde_json::Value>>::deserialize(deserializer)?;
573        let mut toggled = Self::default();
574        for path in saved {
575            match path
576                .into_iter()
577                .map(OwnedValue::deserialize)
578                .collect::<Result<Vec<_>, _>>()
579            {
580                Ok(path) => toggled.paths.push(path),
581                Err(_) => toggled.unreadable += 1,
582            }
583        }
584        Ok(toggled)
585    }
586}
587
588/// Why a layout was not read, written or applied. A grid keeps its current
589/// layout.
590#[derive(Clone, Debug, PartialEq, Eq)]
591#[non_exhaustive]
592pub enum LayoutError {
593    /// Written by a newer build (`found > GridLayout::VERSION`) or malformed
594    /// (`found == 0`).
595    UnsupportedVersion {
596        /// The version the layout carries; `u32::MAX` if it is larger.
597        found: u32,
598    },
599    /// Saved for another grid.
600    ViewMismatch {
601        /// The grid's view id.
602        expected: String,
603        /// The layout's view id.
604        found: String,
605    },
606    /// [`LayoutLibrary::insert`] needs a layout with a view id.
607    MissingViewId,
608    /// The text is not a layout in this codec's format.
609    Decode(String),
610    /// The codec could not write the layout.
611    Encode(String),
612}
613
614impl fmt::Display for LayoutError {
615    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
616        match self {
617            Self::UnsupportedVersion { found } => write!(
618                f,
619                "layout version {found} is not supported; this build reads 1 to {}",
620                GridLayout::VERSION
621            ),
622            Self::ViewMismatch { expected, found } => {
623                write!(f, "the layout is for view \"{found}\", not \"{expected}\"")
624            }
625            Self::MissingViewId => f.write_str("the layout has no view id"),
626            Self::Decode(message) => write!(f, "the layout could not be read: {message}"),
627            Self::Encode(message) => write!(f, "the layout could not be written: {message}"),
628        }
629    }
630}
631
632impl std::error::Error for LayoutError {}
633
634/// Checks that this build reads a layout version: `1..=GridLayout::VERSION`.
635pub(crate) fn check_version(found: u32) -> Result<(), LayoutError> {
636    if (1..=GridLayout::VERSION).contains(&found) {
637        Ok(())
638    } else {
639        Err(LayoutError::UnsupportedVersion { found })
640    }
641}
642
643/// What applying a saved layout had to adjust to fit the current schema.
644///
645/// The grid computes it from the schema and the saved layout, whatever the
646/// [`LayoutMerge`] returns.
647#[derive(Clone, Debug, Default, PartialEq, Eq)]
648pub struct LayoutReport {
649    ignored_columns: Vec<ColumnId>,
650    added_columns: Vec<ColumnId>,
651    dropped_sort: Vec<ColumnId>,
652    dropped_group_by: Vec<ColumnId>,
653    dropped_expansion: usize,
654}
655
656impl LayoutReport {
657    /// Compares a saved layout with the schema in `context`: saved columns
658    /// the schema does not have, schema columns the layout does not have,
659    /// sort keys that are unknown or repeat an earlier key, and the grouping
660    /// and expansion that do not fit (`ResolvedGrouping`). Each list is in
661    /// the order of its source and names an id once.
662    pub(crate) fn resolve(context: &LayoutMergeContext<'_>, saved: &GridLayout) -> Self {
663        let mut ignored_columns = Vec::new();
664        for column in saved.columns() {
665            if !context.contains(column.id().as_str()) && !ignored_columns.contains(column.id()) {
666                ignored_columns.push(column.id().clone());
667            }
668        }
669        let added_columns = context
670            .columns()
671            .iter()
672            .filter(|column| saved.column(column.id().as_str()).is_none())
673            .map(|column| column.id().clone())
674            .collect();
675        let mut sorted = FxHashSet::default();
676        let mut dropped_sort = Vec::new();
677        for key in saved.sort() {
678            let id = key.column();
679            let kept = context.contains(id.as_str()) && sorted.insert(id.as_str());
680            if !kept && !dropped_sort.contains(id) {
681                dropped_sort.push(id.clone());
682            }
683        }
684        let grouping = ResolvedGrouping::new(context, saved);
685        Self {
686            ignored_columns,
687            added_columns,
688            dropped_sort,
689            dropped_group_by: grouping.dropped_group_by,
690            dropped_expansion: grouping.dropped_expansion,
691        }
692    }
693
694    /// Saved columns that the schema no longer has; ignored.
695    pub fn ignored_columns(&self) -> &[ColumnId] {
696        &self.ignored_columns
697    }
698
699    /// Schema columns the layout did not have; added with schema defaults.
700    pub fn added_columns(&self) -> &[ColumnId] {
701        &self.added_columns
702    }
703
704    /// Sort keys on unknown columns and repeated keys; dropped.
705    pub fn dropped_sort(&self) -> &[ColumnId] {
706        &self.dropped_sort
707    }
708
709    /// Grouping levels on columns the schema does not have or cannot group,
710    /// and repeated levels; dropped, and the levels below move up. In saved
711    /// order, each id once. A column can be in [`Self::dropped_sort`] too.
712    pub fn dropped_group_by(&self) -> &[ColumnId] {
713        &self.dropped_group_by
714    }
715
716    /// The number of saved toggled groups that do not fit the restored
717    /// grouping: empty, deeper than its levels, or with a value this build
718    /// cannot hold; dropped.
719    pub fn dropped_expansion(&self) -> usize {
720        self.dropped_expansion
721    }
722
723    /// Returns true if every saved column, sort key, grouping level and
724    /// toggled group matched the schema and every schema column was saved.
725    /// Widths clamped to a column's limits do not count as adjustments.
726    pub fn is_exact(&self) -> bool {
727        self.ignored_columns.is_empty()
728            && self.added_columns.is_empty()
729            && self.dropped_sort.is_empty()
730            && self.dropped_group_by.is_empty()
731            && self.dropped_expansion == 0
732    }
733}
734
735/// A saved layout's grouping and expansion resolved against the schema: the
736/// levels and toggled groups the grid restores, and what it drops.
737/// [`LayoutReport::resolve`] takes the drops from here, so the report names
738/// exactly what restoring leaves out.
739pub(crate) struct ResolvedGrouping<'a> {
740    levels: Vec<&'a LayoutGroup>,
741    toggled: Vec<&'a [OwnedValue]>,
742    depth: ExpandDepth,
743    dropped_group_by: Vec<ColumnId>,
744    dropped_expansion: usize,
745}
746
747impl<'a> ResolvedGrouping<'a> {
748    /// Keeps the levels on schema columns that can be grouped, each column
749    /// once (the first level wins); the levels below a dropped one move up.
750    /// Keeps the toggled groups that are not empty and no deeper than the
751    /// kept levels: their values apply to the kept levels as they are, the
752    /// top level first, and are not matched again. A layout without levels
753    /// keeps its depth but no toggled group, since no level names a column
754    /// for its values. The depth stays as saved, even deeper than the
755    /// levels: it then expands as `ExpandDepth::All` does.
756    pub(crate) fn new(context: &LayoutMergeContext<'_>, saved: &'a GridLayout) -> Self {
757        let mut grouped = FxHashSet::default();
758        let mut levels = Vec::with_capacity(saved.group_by.len());
759        let mut dropped_group_by = Vec::new();
760        for level in &saved.group_by {
761            let id = level.column();
762            if context.is_groupable(id.as_str()) && grouped.insert(id.as_str()) {
763                levels.push(level);
764            } else if !dropped_group_by.contains(id) {
765                dropped_group_by.push(id.clone());
766            }
767        }
768        let expansion = &saved.expansion;
769        let toggled: Vec<&[OwnedValue]> = expansion
770            .toggled()
771            .iter()
772            .map(Vec::as_slice)
773            .filter(|path| (1..=levels.len()).contains(&path.len()))
774            .collect();
775        let dropped_expansion =
776            expansion.toggled.unreadable + (expansion.toggled().len() - toggled.len());
777        Self {
778            levels,
779            toggled,
780            depth: expansion.depth(),
781            dropped_group_by,
782            dropped_expansion,
783        }
784    }
785
786    /// The kept levels, the top level first.
787    pub(crate) fn levels(&self) -> &[&'a LayoutGroup] {
788        &self.levels
789    }
790
791    /// The kept toggled groups in saved order, each as its key values for
792    /// the kept levels from the top down.
793    pub(crate) fn toggled(&self) -> &[&'a [OwnedValue]] {
794        &self.toggled
795    }
796
797    /// The default depth, as saved.
798    pub(crate) fn depth(&self) -> ExpandDepth {
799        self.depth
800    }
801}
802
803/// Turns a layout into text and back. Called once per import or export.
804///
805/// The default is [`JsonLayoutCodec`]. Another codec can read a foreign
806/// format, such as a LiveGrid or Syncfusion XML layout.
807pub trait LayoutCodec: 'static {
808    /// Writes a layout.
809    fn encode(&self, layout: &GridLayout) -> Result<String, LayoutError>;
810
811    /// Reads a layout. Also migrates older versions of its own format, and
812    /// refuses versions it does not read with
813    /// [`LayoutError::UnsupportedVersion`].
814    fn decode(&self, text: &str) -> Result<GridLayout, LayoutError>;
815}
816
817/// The JSON format of [`GridLayout`], compact by default.
818#[derive(Clone, Copy, Debug, Default)]
819pub struct JsonLayoutCodec {
820    pretty: bool,
821}
822
823impl JsonLayoutCodec {
824    /// Writes indented JSON, one field per line, instead of one line.
825    pub fn pretty(mut self, pretty: bool) -> Self {
826        self.pretty = pretty;
827        self
828    }
829
830    /// Returns true if the codec writes indented JSON.
831    pub fn is_pretty(&self) -> bool {
832        self.pretty
833    }
834}
835
836impl LayoutCodec for JsonLayoutCodec {
837    fn encode(&self, layout: &GridLayout) -> Result<String, LayoutError> {
838        if self.pretty {
839            serde_json::to_string_pretty(layout)
840        } else {
841            serde_json::to_string(layout)
842        }
843        .map_err(|error| LayoutError::Encode(error.to_string()))
844    }
845
846    fn decode(&self, text: &str) -> Result<GridLayout, LayoutError> {
847        let decode_error = |error: serde_json::Error| LayoutError::Decode(error.to_string());
848        let value: serde_json::Value = serde_json::from_str(text).map_err(decode_error)?;
849        let Some(object) = value.as_object() else {
850            return Err(LayoutError::Decode("expected a JSON object".into()));
851        };
852        let found = match object.get("version") {
853            None => return Err(LayoutError::Decode("missing field `version`".into())),
854            Some(version) => version.as_u64().ok_or_else(|| {
855                LayoutError::Decode(format!("`version` is not a whole number: {version}"))
856            })?,
857        };
858        check_version(u32::try_from(found).unwrap_or(u32::MAX))?;
859        // A new version migrates the older ones here, by editing `value`
860        // before it is parsed.
861        serde_json::from_value(value).map_err(decode_error)
862    }
863}
864
865/// The schema as a [`LayoutMerge`] sees it: every column with its default
866/// width, visibility and zone, and whether it can be grouped.
867#[derive(Clone, Copy, Debug)]
868pub struct LayoutMergeContext<'a> {
869    columns: &'a [LayoutColumn],
870    /// Schema columns the grid may not group by; none by default.
871    ungroupable: &'a [ColumnId],
872}
873
874impl<'a> LayoutMergeContext<'a> {
875    /// The schema's columns in schema order, each with its defaults; every
876    /// column can be grouped.
877    pub(crate) fn new(columns: &'a [LayoutColumn]) -> Self {
878        Self {
879            columns,
880            ungroupable: &[],
881        }
882    }
883
884    /// Names the schema columns the grid may not group by.
885    pub(crate) fn with_ungroupable(mut self, ids: &'a [ColumnId]) -> Self {
886        self.ungroupable = ids;
887        self
888    }
889
890    /// Schema columns in schema order, with default width, zone and
891    /// visibility.
892    pub fn columns(&self) -> &'a [LayoutColumn] {
893        self.columns
894    }
895
896    /// The schema column with this id and its defaults.
897    pub fn column(&self, id: &str) -> Option<&'a LayoutColumn> {
898        self.columns
899            .iter()
900            .find(|column| column.id().as_str() == id)
901    }
902
903    /// Returns true if the schema has a column with this id.
904    pub fn contains(&self, id: &str) -> bool {
905        self.column(id).is_some()
906    }
907
908    /// Returns true if the schema has a column with this id and the grid may
909    /// group by it.
910    pub fn is_groupable(&self, id: &str) -> bool {
911        self.contains(id) && !self.ungroupable.iter().any(|column| column.as_str() == id)
912    }
913}
914
915/// Resolves a saved layout against the current schema. Called once per
916/// import.
917///
918/// The default is [`AppendNewColumns`]. An alternative could place a new
919/// column next to its neighbour in the schema, or keep unknown columns for a
920/// schema that depends on the user's permissions.
921pub trait LayoutMerge: 'static {
922    /// One entry per schema column, in display order. The grid validates
923    /// the result whatever the implementation returns: it adds missing
924    /// columns, drops unknown ones and repeats, clamps widths, splits the
925    /// order by zone and keeps one column visible.
926    fn merge(&self, context: &LayoutMergeContext<'_>, saved: &GridLayout) -> Vec<LayoutColumn>;
927}
928
929/// The default [`LayoutMerge`]: saved columns keep their order, width,
930/// visibility and zone; columns the schema no longer has are ignored, and a
931/// repeated id keeps its first entry. Schema columns the layout does not
932/// have go to the end of their zone, in schema order, with schema defaults.
933#[derive(Clone, Copy, Debug, Default)]
934pub struct AppendNewColumns;
935
936impl LayoutMerge for AppendNewColumns {
937    fn merge(&self, context: &LayoutMergeContext<'_>, saved: &GridLayout) -> Vec<LayoutColumn> {
938        fn zone_ix(zone: ColumnZone) -> usize {
939            match zone {
940                ColumnZone::FrozenLeft => 0,
941                ColumnZone::Scrolling => 1,
942                ColumnZone::FrozenRight => 2,
943            }
944        }
945
946        let mut merged = FxHashSet::default();
947        let mut zones: [Vec<LayoutColumn>; 3] = Default::default();
948        for column in saved.columns() {
949            let id = column.id().as_str();
950            if context.contains(id) && merged.insert(id) {
951                zones[zone_ix(column.zone())].push(column.clone());
952            }
953        }
954        for column in context.columns() {
955            if !merged.contains(column.id().as_str()) {
956                zones[zone_ix(column.zone())].push(column.clone());
957            }
958        }
959        zones.into_iter().flatten().collect()
960    }
961}
962
963/// Named layouts per view id, for "Save Layout As…" and a layout picker,
964/// plus the layout each view opens with.
965///
966/// Plain data: the application stores it where it keeps its settings and
967/// serializes it with serde. A view id names the kind of grid ("trades"),
968/// not a panel: every panel of a view shares its layouts. Layouts are kept
969/// as given; the grid checks their version when it applies one.
970#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
971pub struct LayoutLibrary {
972    #[serde(default)]
973    views: BTreeMap<String, ViewLayouts>,
974}
975
976#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
977struct ViewLayouts {
978    #[serde(default, skip_serializing_if = "Option::is_none")]
979    default: Option<String>,
980    #[serde(default)]
981    layouts: BTreeMap<String, GridLayout>,
982}
983
984impl LayoutLibrary {
985    /// An empty library.
986    pub fn new() -> Self {
987        Self::default()
988    }
989
990    /// Stores `layout` under its view id and `name`, replacing a layout with
991    /// that name. Fails with [`LayoutError::MissingViewId`] if the layout
992    /// has no view id.
993    pub fn insert(
994        &mut self,
995        name: impl Into<String>,
996        layout: GridLayout,
997    ) -> Result<(), LayoutError> {
998        let view_id = layout.view_id().ok_or(LayoutError::MissingViewId)?;
999        self.views
1000            .entry(view_id.to_owned())
1001            .or_default()
1002            .layouts
1003            .insert(name.into(), layout);
1004        Ok(())
1005    }
1006
1007    /// The layout of a view with this name.
1008    pub fn get(&self, view_id: &str, name: &str) -> Option<&GridLayout> {
1009        self.views.get(view_id)?.layouts.get(name)
1010    }
1011
1012    /// The names of a view's layouts, sorted by their text (byte order).
1013    pub fn names<'a>(&'a self, view_id: &str) -> impl Iterator<Item = &'a str> + use<'a> {
1014        self.views
1015            .get(view_id)
1016            .into_iter()
1017            .flat_map(|view| view.layouts.keys().map(String::as_str))
1018    }
1019
1020    /// Removes a layout. If it was the view's default, the view has no
1021    /// default afterwards.
1022    pub fn remove(&mut self, view_id: &str, name: &str) -> Option<GridLayout> {
1023        let view = self.views.get_mut(view_id)?;
1024        let layout = view.layouts.remove(name)?;
1025        if view.default.as_deref() == Some(name) {
1026            view.default = None;
1027        }
1028        if view.layouts.is_empty() {
1029            self.views.remove(view_id);
1030        }
1031        Some(layout)
1032    }
1033
1034    /// Renames a layout; the default follows it. Returns false, and changes
1035    /// nothing, if there is no layout `from` or another layout is named
1036    /// `to`.
1037    pub fn rename(&mut self, view_id: &str, from: &str, to: impl Into<String>) -> bool {
1038        let to = to.into();
1039        let Some(view) = self.views.get_mut(view_id) else {
1040            return false;
1041        };
1042        if to != from && view.layouts.contains_key(&to) {
1043            return false;
1044        }
1045        let Some(layout) = view.layouts.remove(from) else {
1046            return false;
1047        };
1048        if view.default.as_deref() == Some(from) {
1049            view.default = Some(to.clone());
1050        }
1051        view.layouts.insert(to, layout);
1052        true
1053    }
1054
1055    /// Sets the layout a view opens with when nothing else is restored, or
1056    /// clears it with `None`. Returns false, and changes nothing, if the
1057    /// view has no layout with that name.
1058    pub fn set_default(&mut self, view_id: &str, name: Option<&str>) -> bool {
1059        let view = self.views.get_mut(view_id);
1060        match (view, name) {
1061            (Some(view), Some(name)) if view.layouts.contains_key(name) => {
1062                view.default = Some(name.to_owned());
1063                true
1064            }
1065            (_, Some(_)) => false,
1066            (Some(view), None) => {
1067                view.default = None;
1068                true
1069            }
1070            (None, None) => true,
1071        }
1072    }
1073
1074    /// The name and layout a view opens with when nothing else is restored.
1075    pub fn default_layout(&self, view_id: &str) -> Option<(&str, &GridLayout)> {
1076        let view = self.views.get(view_id)?;
1077        let (name, layout) = view.layouts.get_key_value(view.default.as_deref()?)?;
1078        Some((name.as_str(), layout))
1079    }
1080}
1081
1082#[cfg(test)]
1083mod tests {
1084    use super::*;
1085
1086    /// The reference layout behind `tests/fixtures/layout-v1.json`: every
1087    /// zone, hidden columns in two zones, a fractional width and two sort
1088    /// keys.
1089    fn reference_layout() -> GridLayout {
1090        GridLayout::new()
1091            .with_view_id("trades")
1092            .with_column(LayoutColumn::new("id", 80_f32).with_zone(ColumnZone::FrozenLeft))
1093            .with_column(LayoutColumn::new("instrument", 140_f32))
1094            .with_column(LayoutColumn::new("time", 92.5_f32))
1095            .with_column(LayoutColumn::new("fee", 90_f32).with_visible(false))
1096            .with_column(LayoutColumn::new("price", 100_f32))
1097            .with_column(LayoutColumn::new("side", 60_f32).with_zone(ColumnZone::FrozenRight))
1098            .with_column(
1099                LayoutColumn::new("venue", 72_f32)
1100                    .with_visible(false)
1101                    .with_zone(ColumnZone::FrozenRight),
1102            )
1103            .with_sort([
1104                LayoutSort::new("time", SortDirection::Descending),
1105                LayoutSort::new("instrument", SortDirection::Ascending),
1106            ])
1107    }
1108
1109    #[test]
1110    fn test_layout_builder() {
1111        let empty = GridLayout::new();
1112        assert_eq!(empty.version(), GridLayout::VERSION);
1113        assert_eq!(empty.view_id(), None);
1114        assert!(empty.columns().is_empty() && empty.sort().is_empty());
1115
1116        let column = LayoutColumn::new("price", 100_f32);
1117        assert_eq!(column.id().as_str(), "price");
1118        assert_eq!(column.width(), 100.);
1119        assert!(column.is_visible());
1120        assert_eq!(column.zone(), ColumnZone::Scrolling);
1121
1122        let layout = GridLayout::new()
1123            .with_view_id("orders")
1124            .with_column(
1125                LayoutColumn::new("price", 100_f32)
1126                    .with_width(gpui_kit::px(120.))
1127                    .with_visible(false)
1128                    .with_zone(ColumnZone::FrozenRight),
1129            )
1130            .with_column(LayoutColumn::new(String::from("qty"), 60_f32))
1131            .with_column(LayoutColumn::new("price", 30_f32))
1132            .with_sort([LayoutSort::new("qty", SortDirection::Ascending)])
1133            .with_sort([LayoutSort::new("price", SortDirection::Descending)]);
1134        assert_eq!(layout.view_id(), Some("orders"));
1135        let ids: Vec<_> = layout.columns().iter().map(|c| c.id().as_str()).collect();
1136        assert_eq!(ids, ["price", "qty", "price"]);
1137        // `column` finds the first entry of a repeated id.
1138        let price = layout.column("price").unwrap();
1139        assert_eq!(price.width(), 120.);
1140        assert!(!price.is_visible());
1141        assert_eq!(price.zone(), ColumnZone::FrozenRight);
1142        assert_eq!(layout.column("fee"), None);
1143        // `with_sort` replaces the sort.
1144        assert_eq!(layout.sort().len(), 1);
1145        assert_eq!(layout.sort()[0].column().as_str(), "price");
1146        assert_eq!(layout.sort()[0].direction(), SortDirection::Descending);
1147
1148        assert!(!JsonLayoutCodec::default().is_pretty());
1149        assert!(JsonLayoutCodec::default().pretty(true).is_pretty());
1150        assert_eq!(
1151            LayoutError::UnsupportedVersion { found: 2 }.to_string(),
1152            "layout version 2 is not supported; this build reads 1 to 1"
1153        );
1154    }
1155
1156    #[test]
1157    fn test_layout_json_matches_fixture() {
1158        // Git may check the fixture out with CRLF line endings on Windows.
1159        let fixture = include_str!("../tests/fixtures/layout-v1.json").replace("\r\n", "\n");
1160        let layout = reference_layout();
1161
1162        let pretty = JsonLayoutCodec::default().pretty(true);
1163        assert_eq!(format!("{}\n", pretty.encode(&layout).unwrap()), fixture);
1164        assert_eq!(pretty.decode(&fixture).unwrap(), layout);
1165
1166        // Without grouping the layout is written byte for byte as before the
1167        // grouping fields, and it reads back without them.
1168        let ungrouped = layout
1169            .clone()
1170            .with_group_by(Vec::new())
1171            .with_expansion(LayoutExpansion::default());
1172        assert_eq!(ungrouped, layout);
1173        assert_eq!(format!("{}\n", pretty.encode(&ungrouped).unwrap()), fixture);
1174        let read = pretty.decode(&fixture).unwrap();
1175        assert!(read.group_by().is_empty());
1176        assert_eq!(read.expansion(), None);
1177
1178        // The compact form and plain serde (the dock recipe's path) read the
1179        // same layout.
1180        let codec = JsonLayoutCodec::default();
1181        let compact = codec.encode(&layout).unwrap();
1182        assert!(!compact.contains('\n'));
1183        assert_eq!(codec.decode(&compact).unwrap(), layout);
1184        assert_eq!(
1185            serde_json::from_str::<GridLayout>(&fixture).unwrap(),
1186            layout
1187        );
1188    }
1189
1190    #[test]
1191    fn test_layout_decode_defaults_and_unknown_fields() {
1192        let codec = JsonLayoutCodec::default();
1193        let layout = codec
1194            .decode(
1195                r#"{
1196                    "version": 1,
1197                    "view_id": null,
1198                    "columns": [
1199                        { "id": "a", "width": 50 },
1200                        { "id": "b", "width": 60.5, "visible": true, "frozen": null, "tint": "red" },
1201                        { "id": "c", "width": null, "visible": false, "frozen": "right" }
1202                    ],
1203                    "filters": ["a"],
1204                    "density": { "rows": "compact" }
1205                }"#,
1206            )
1207            .unwrap();
1208        assert_eq!(layout.version(), 1);
1209        assert_eq!(layout.view_id(), None);
1210        assert!(layout.sort().is_empty());
1211        let a = layout.column("a").unwrap();
1212        assert_eq!(a.width(), 50.);
1213        assert!(a.is_visible());
1214        assert_eq!(a.zone(), ColumnZone::Scrolling);
1215        let b = layout.column("b").unwrap();
1216        assert_eq!(
1217            (b.width(), b.is_visible(), b.zone()),
1218            (60.5, true, ColumnZone::Scrolling)
1219        );
1220        // A `null` width (how JSON writes NaN) reads as NaN; the grid replaces
1221        // it with the schema width.
1222        let c = layout.column("c").unwrap();
1223        assert!(c.width().is_nan());
1224        assert_eq!((c.is_visible(), c.zone()), (false, ColumnZone::FrozenRight));
1225
1226        // Saving again drops the unknown fields and writes no defaults.
1227        assert_eq!(
1228            codec.encode(&layout).unwrap(),
1229            concat!(
1230                r#"{"version":1,"columns":[{"id":"a","width":50.0},{"id":"b","width":60.5},"#,
1231                r#"{"id":"c","width":null,"visible":false,"frozen":"right"}]}"#,
1232            )
1233        );
1234
1235        // Unknown values of known fields are not a layout.
1236        for text in [
1237            r#"{"version":1,"columns":[{"id":"a","width":50,"frozen":"top"}]}"#,
1238            r#"{"version":1,"columns":[{"id":"a","width":"wide"}]}"#,
1239            r#"{"version":1,"columns":[{"width":50}]}"#,
1240            r#"{"version":1,"columns":[],"sort":[{"column":"a","direction":"up"}]}"#,
1241            r#"{"version":1,"columns":[],"group_by":[{"column":"a","direction":"up"}]}"#,
1242            r#"{"version":1,"columns":[],"group_by":[{"direction":"ascending"}]}"#,
1243            r#"{"version":1,"columns":[],"group_by":["a"]}"#,
1244            r#"{"version":1,"columns":[],"expansion":{"depth":"deep"}}"#,
1245            r#"{"version":1,"columns":[],"expansion":"all"}"#,
1246            r#"{"version":1,"columns":[],"expansion":{"toggled":"AAPL"}}"#,
1247            r#"{"version":1,"columns":[],"expansion":{"toggled":["AAPL"]}}"#,
1248        ] {
1249            assert!(
1250                matches!(codec.decode(text), Err(LayoutError::Decode(_))),
1251                "{text}"
1252            );
1253        }
1254    }
1255
1256    fn text(value: &str) -> OwnedValue {
1257        OwnedValue::Text(value.into())
1258    }
1259
1260    /// The reference layout behind `tests/fixtures/layout-v1-groups.json`:
1261    /// two grouping levels, the default depth and toggled groups of every
1262    /// kind of value, `12` and `12.0` apart. The decimal path needs the
1263    /// `decimal` feature.
1264    fn grouped_layout() -> GridLayout {
1265        let expansion = LayoutExpansion::new(ExpandDepth::All)
1266            .with_toggled([text("AAPL")])
1267            .with_toggled([text("MSFT"), text("Sell")])
1268            .with_toggled([OwnedValue::Empty])
1269            .with_toggled([OwnedValue::Bool(true)])
1270            .with_toggled([OwnedValue::Int(12)])
1271            .with_toggled([OwnedValue::Float(12.0)]);
1272        #[cfg(feature = "decimal")]
1273        let expansion =
1274            expansion.with_toggled([OwnedValue::Decimal(rust_decimal::Decimal::new(1020, 2))]);
1275        GridLayout::new()
1276            .with_view_id("trades")
1277            .with_column(LayoutColumn::new("instrument", 140_f32))
1278            .with_column(LayoutColumn::new("side", 60_f32))
1279            .with_column(LayoutColumn::new("price", 100_f32))
1280            .with_sort([LayoutSort::new("price", SortDirection::Descending)])
1281            .with_group_by([
1282                LayoutGroup::new("instrument", SortDirection::Ascending),
1283                LayoutGroup::new("side", SortDirection::Descending),
1284            ])
1285            .with_expansion(expansion)
1286    }
1287
1288    fn ids(ids: &[ColumnId]) -> Vec<&str> {
1289        ids.iter().map(ColumnId::as_str).collect()
1290    }
1291
1292    #[test]
1293    fn test_layout_groups_builder() {
1294        let level = LayoutGroup::new("side", SortDirection::Descending);
1295        assert_eq!(level.column().as_str(), "side");
1296        assert_eq!(level.direction(), SortDirection::Descending);
1297
1298        let expansion = LayoutExpansion::new(ExpandDepth::Levels(1))
1299            .with_toggled([text("AAPL")])
1300            .with_toggled(Vec::new());
1301        assert_eq!(expansion.depth(), ExpandDepth::Levels(1));
1302        assert_eq!(expansion.toggled(), [vec![text("AAPL")], Vec::new()]);
1303        assert!(!expansion.is_default());
1304        assert!(LayoutExpansion::default().is_default());
1305        assert!(!LayoutExpansion::new(ExpandDepth::Captions).is_default());
1306        assert!(
1307            !LayoutExpansion::default()
1308                .with_toggled([text("a")])
1309                .is_default()
1310        );
1311
1312        let layout = GridLayout::new()
1313            .with_group_by([level.clone()])
1314            .with_group_by([level.clone(), level.clone()])
1315            .with_expansion(LayoutExpansion::new(ExpandDepth::Captions))
1316            .with_expansion(expansion.clone());
1317        // Both builders replace.
1318        assert_eq!(layout.group_by(), [level.clone(), level]);
1319        assert_eq!(layout.expansion(), Some(&expansion));
1320        assert!(GridLayout::new().group_by().is_empty());
1321        assert_eq!(GridLayout::new().expansion(), None);
1322        assert_eq!(
1323            layout
1324                .with_expansion(LayoutExpansion::default())
1325                .expansion(),
1326            None
1327        );
1328    }
1329
1330    #[test]
1331    fn test_layout_groups_fixture() {
1332        use std::mem::discriminant;
1333
1334        let fixture = include_str!("../tests/fixtures/layout-v1-groups.json").replace("\r\n", "\n");
1335        let layout = grouped_layout();
1336        let pretty = JsonLayoutCodec::default().pretty(true);
1337        let read = pretty.decode(&fixture).unwrap();
1338        // Plain serde (the dock recipe's path) reads the same layout.
1339        assert_eq!(serde_json::from_str::<GridLayout>(&fixture).unwrap(), read);
1340
1341        // `12` reads as an integer and `12.0` as a float.
1342        let toggled = read.expansion().unwrap().toggled();
1343        assert_eq!(
1344            discriminant(&toggled[4][0]),
1345            discriminant(&OwnedValue::Int(12))
1346        );
1347        assert_eq!(
1348            discriminant(&toggled[5][0]),
1349            discriminant(&OwnedValue::Float(12.0))
1350        );
1351
1352        let schema = [
1353            LayoutColumn::new("instrument", 100_f32),
1354            LayoutColumn::new("side", 100_f32),
1355            LayoutColumn::new("price", 100_f32),
1356        ];
1357        let context = LayoutMergeContext::new(&schema);
1358        let report = LayoutReport::resolve(&context, &read);
1359        assert!(report.dropped_group_by().is_empty());
1360
1361        #[cfg(feature = "decimal")]
1362        {
1363            assert_eq!(format!("{}\n", pretty.encode(&layout).unwrap()), fixture);
1364            assert_eq!(read, layout);
1365            assert!(
1366                matches!(&toggled[6][0], OwnedValue::Decimal(value) if value.to_string() == "10.20")
1367            );
1368            assert!(report.is_exact());
1369        }
1370        #[cfg(not(feature = "decimal"))]
1371        {
1372            // Without the feature a decimal cannot be a key: the layout
1373            // reads, the path is dropped and the report counts it.
1374            assert_eq!(read.group_by(), layout.group_by());
1375            assert_eq!(toggled, layout.expansion().unwrap().toggled());
1376            assert_eq!(report.dropped_expansion(), 1);
1377            assert!(!report.is_exact());
1378            // Saving again writes the rest.
1379            assert_eq!(
1380                pretty.encode(&read).unwrap(),
1381                pretty.encode(&layout).unwrap()
1382            );
1383        }
1384        // Writing again gives the same text.
1385        let compact = JsonLayoutCodec::default();
1386        let text = compact.encode(&read).unwrap();
1387        assert_eq!(
1388            compact.encode(&compact.decode(&text).unwrap()).unwrap(),
1389            text
1390        );
1391    }
1392
1393    #[test]
1394    fn test_expansion_default_omitted() {
1395        let codec = JsonLayoutCodec::default();
1396        let empty = r#"{"version":1,"columns":[]}"#;
1397        // No grouping and the default expansion are not written; nor is a
1398        // path with a NaN or an infinity, which JSON cannot hold.
1399        for layout in [
1400            GridLayout::new().with_expansion(LayoutExpansion::new(ExpandDepth::All)),
1401            GridLayout::new()
1402                .with_group_by(Vec::new())
1403                .with_expansion(LayoutExpansion::default()),
1404            GridLayout::new().with_expansion(
1405                LayoutExpansion::default()
1406                    .with_toggled([text("a"), OwnedValue::Float(f64::NAN)])
1407                    .with_toggled([OwnedValue::Float(f64::NEG_INFINITY)]),
1408            ),
1409        ] {
1410            assert_eq!(codec.encode(&layout).unwrap(), empty);
1411        }
1412        let read = codec.decode(empty).unwrap();
1413        assert_eq!(read, GridLayout::new());
1414        assert_eq!(read.expansion(), None);
1415
1416        // Any other depth is written, without an empty `toggled`.
1417        for (depth, json) in [
1418            (ExpandDepth::Captions, r#""captions""#),
1419            (ExpandDepth::Levels(0), "0"),
1420            (ExpandDepth::Levels(3), "3"),
1421        ] {
1422            let layout = GridLayout::new().with_expansion(LayoutExpansion::new(depth));
1423            let text = codec.encode(&layout).unwrap();
1424            assert_eq!(
1425                text,
1426                format!(r#"{{"version":1,"columns":[],"expansion":{{"depth":{json}}}}}"#)
1427            );
1428            assert_eq!(codec.decode(&text).unwrap(), layout);
1429            assert_eq!(layout.expansion().map(LayoutExpansion::depth), Some(depth));
1430        }
1431
1432        // Only the paths JSON can hold are written.
1433        let mixed = GridLayout::new().with_expansion(
1434            LayoutExpansion::new(ExpandDepth::Levels(1))
1435                .with_toggled([text("a"), OwnedValue::Float(f64::INFINITY)])
1436                .with_toggled([text("b")]),
1437        );
1438        assert_eq!(
1439            codec.encode(&mixed).unwrap(),
1440            r#"{"version":1,"columns":[],"expansion":{"depth":1,"toggled":[["b"]]}}"#
1441        );
1442
1443        // `depth` reads "all", "captions" and whole numbers, and is "all"
1444        // when missing.
1445        for (json, depth) in [
1446            (r#"{"depth":"all"}"#, ExpandDepth::All),
1447            (r#"{"depth":"captions"}"#, ExpandDepth::Captions),
1448            (r#"{"depth":0}"#, ExpandDepth::Levels(0)),
1449            (r#"{"depth":2,"rows":[[1]]}"#, ExpandDepth::Levels(2)),
1450            (r#"{}"#, ExpandDepth::All),
1451            (r#"{"toggled":[]}"#, ExpandDepth::All),
1452        ] {
1453            let text = format!(r#"{{"version":1,"columns":[],"expansion":{json}}}"#);
1454            let layout = codec.decode(&text).unwrap();
1455            assert_eq!(
1456                layout
1457                    .expansion()
1458                    .map_or(ExpandDepth::All, LayoutExpansion::depth),
1459                depth,
1460                "{json}"
1461            );
1462        }
1463        for json in [r#""deep""#, r#""All""#, "-1", "1.5", "65536", "null", "[1]"] {
1464            let text = format!(r#"{{"version":1,"columns":[],"expansion":{{"depth":{json}}}}}"#);
1465            assert!(
1466                matches!(codec.decode(&text), Err(LayoutError::Decode(_))),
1467                "{json}"
1468            );
1469        }
1470    }
1471
1472    #[test]
1473    fn test_layout_report_groups() {
1474        // Five schema columns; `e` cannot be grouped.
1475        let schema = ["a", "b", "c", "d", "e"].map(|id| LayoutColumn::new(id, 50_f32));
1476        let ungroupable = [ColumnId::from("e")];
1477        let context = LayoutMergeContext::new(&schema).with_ungroupable(&ungroupable);
1478        assert!(context.is_groupable("a") && context.contains("e"));
1479        assert!(!context.is_groupable("e") && !context.is_groupable("gone"));
1480        assert!(
1481            LayoutMergeContext::new(&schema).is_groupable("e"),
1482            "every column can be grouped by default"
1483        );
1484
1485        let saved = JsonLayoutCodec::default()
1486            .decode(
1487                r#"{
1488                    "version": 1,
1489                    "columns": [
1490                        { "id": "a", "width": 50 }, { "id": "b", "width": 50 },
1491                        { "id": "c", "width": 50 }, { "id": "d", "width": 50 },
1492                        { "id": "e", "width": 50 }
1493                    ],
1494                    "sort": [
1495                        { "column": "gone", "direction": "ascending" },
1496                        { "column": "e", "direction": "ascending" }
1497                    ],
1498                    "group_by": [
1499                        { "column": "a", "direction": "ascending" },
1500                        { "column": "gone", "direction": "ascending" },
1501                        { "column": "b", "direction": "descending" },
1502                        { "column": "a", "direction": "descending" },
1503                        { "column": "e", "direction": "ascending" },
1504                        { "column": "gone", "direction": "descending" },
1505                        { "column": "c", "direction": "ascending" }
1506                    ],
1507                    "expansion": {
1508                        "depth": 9,
1509                        "toggled": [
1510                            ["x"], [], [1, 2, 3], [1, 2, 3, 4], ["x", "y"],
1511                            [{ "date": "2026-11-04" }], ["x", [1]], [18446744073709551615]
1512                        ]
1513                    }
1514                }"#,
1515            )
1516            .unwrap();
1517        // A value this build cannot hold drops its path when read.
1518        assert_eq!(saved.expansion().unwrap().toggled().len(), 5);
1519
1520        let report = LayoutReport::resolve(&context, &saved);
1521        // Unknown, repeated and ungroupable levels, in saved order, once.
1522        assert_eq!(ids(report.dropped_group_by()), ["gone", "a", "e"]);
1523        // Empty and too deep paths, and the three unreadable ones.
1524        assert_eq!(report.dropped_expansion(), 5);
1525        // A column can leave the sort and the grouping alike.
1526        assert_eq!(ids(report.dropped_sort()), ["gone"]);
1527        assert!(report.ignored_columns().is_empty() && report.added_columns().is_empty());
1528        assert!(!report.is_exact());
1529
1530        // The lower levels move up; paths apply to them as they are.
1531        let resolved = ResolvedGrouping::new(&context, &saved);
1532        let levels: Vec<_> = resolved
1533            .levels()
1534            .iter()
1535            .map(|level| (level.column().as_str(), level.direction()))
1536            .collect();
1537        assert_eq!(
1538            levels,
1539            [
1540                ("a", SortDirection::Ascending),
1541                ("b", SortDirection::Descending),
1542                ("c", SortDirection::Ascending),
1543            ]
1544        );
1545        let int = OwnedValue::Int;
1546        assert_eq!(
1547            resolved.toggled(),
1548            [
1549                &[text("x")][..],
1550                &[int(1), int(2), int(3)],
1551                &[text("x"), text("y")],
1552            ]
1553        );
1554        // The depth stays as saved, deeper than the levels.
1555        assert_eq!(resolved.depth(), ExpandDepth::Levels(9));
1556
1557        // When every level is dropped, so is every path; the depth stays.
1558        let gone = GridLayout::new()
1559            .with_group_by([LayoutGroup::new("gone", SortDirection::Ascending)])
1560            .with_expansion(LayoutExpansion::new(ExpandDepth::Captions).with_toggled([text("x")]));
1561        let report = LayoutReport::resolve(&context, &gone);
1562        assert_eq!(ids(report.dropped_group_by()), ["gone"]);
1563        assert_eq!(report.dropped_expansion(), 1);
1564        let resolved = ResolvedGrouping::new(&context, &gone);
1565        assert!(resolved.levels().is_empty() && resolved.toggled().is_empty());
1566        assert_eq!(resolved.depth(), ExpandDepth::Captions);
1567
1568        // Without grouping a depth alone is exact; a path names no column.
1569        let depth_only = |expansion: LayoutExpansion| {
1570            schema
1571                .iter()
1572                .cloned()
1573                .fold(GridLayout::new(), GridLayout::with_column)
1574                .with_expansion(expansion)
1575        };
1576        let report = LayoutReport::resolve(
1577            &context,
1578            &depth_only(LayoutExpansion::new(ExpandDepth::Levels(0))),
1579        );
1580        assert!(report.is_exact());
1581        let report = LayoutReport::resolve(
1582            &context,
1583            &depth_only(LayoutExpansion::new(ExpandDepth::Levels(0)).with_toggled([text("x")])),
1584        );
1585        assert_eq!(report.dropped_expansion(), 1);
1586
1587        // A layout that fits is exact.
1588        let fits = depth_only(
1589            LayoutExpansion::new(ExpandDepth::All)
1590                .with_toggled([text("x")])
1591                .with_toggled([text("x"), OwnedValue::Empty]),
1592        )
1593        .with_group_by([
1594            LayoutGroup::new("d", SortDirection::Descending),
1595            LayoutGroup::new("a", SortDirection::Ascending),
1596        ]);
1597        assert!(LayoutReport::resolve(&context, &fits).is_exact());
1598        assert_eq!(ResolvedGrouping::new(&context, &fits).toggled().len(), 2);
1599    }
1600
1601    #[test]
1602    fn test_old_build_reads_new_layout() {
1603        /// `GridLayout` as a build without grouping declares it.
1604        #[derive(Debug, PartialEq, Serialize, Deserialize)]
1605        struct OldLayout {
1606            version: u32,
1607            #[serde(default, skip_serializing_if = "Option::is_none")]
1608            view_id: Option<String>,
1609            columns: Vec<LayoutColumn>,
1610            #[serde(default, skip_serializing_if = "Vec::is_empty")]
1611            sort: Vec<LayoutSort>,
1612        }
1613
1614        // The old build reads the grouped fixture and keeps the rest.
1615        let fixture = include_str!("../tests/fixtures/layout-v1-groups.json");
1616        let old: OldLayout = serde_json::from_str(fixture).unwrap();
1617        let layout = grouped_layout();
1618        assert_eq!(old.version, GridLayout::VERSION);
1619        assert_eq!(old.view_id.as_deref(), layout.view_id());
1620        assert_eq!(old.columns, layout.columns());
1621        assert_eq!(old.sort, layout.sort());
1622
1623        // Saving there drops the grouping; this build reads that as a layout
1624        // without grouping.
1625        let saved_again = serde_json::to_string(&old).unwrap();
1626        let read = JsonLayoutCodec::default().decode(&saved_again).unwrap();
1627        assert_eq!(
1628            read,
1629            layout
1630                .with_group_by(Vec::new())
1631                .with_expansion(LayoutExpansion::default())
1632        );
1633
1634        // Both builds write a layout without grouping alike.
1635        let reference = reference_layout();
1636        let old = OldLayout {
1637            version: reference.version(),
1638            view_id: reference.view_id().map(str::to_owned),
1639            columns: reference.columns().to_vec(),
1640            sort: reference.sort().to_vec(),
1641        };
1642        assert_eq!(
1643            serde_json::to_string(&old).unwrap(),
1644            JsonLayoutCodec::default().encode(&reference).unwrap()
1645        );
1646    }
1647
1648    #[test]
1649    fn test_layout_round_trip_property() {
1650        const IDS: [&str; 10] = ["id", "a", "b", "c", "d", "e", "f", "g", "Цена", "量"];
1651        const PIECES: [&str; 10] = ["a", "Я", "✓", "😀", "\"", "\\", "\n", " ", "é", "中"];
1652
1653        fn value(rng: &mut fastrand::Rng) -> OwnedValue {
1654            match rng.u8(..7) {
1655                0 => OwnedValue::Empty,
1656                1 => OwnedValue::Bool(rng.bool()),
1657                2 => OwnedValue::Int(rng.i64(..)),
1658                // Any finite float, bit for bit.
1659                3 => loop {
1660                    let float = f64::from_bits(rng.u64(..));
1661                    if float.is_finite() {
1662                        break OwnedValue::Float(float);
1663                    }
1664                },
1665                // Prices, integral floats and zeros of both signs.
1666                4 => OwnedValue::Float(match rng.u8(..4) {
1667                    0 => (rng.f64() - 0.5) * 1e6,
1668                    1 => rng.i32(..) as f64,
1669                    2 => 0.,
1670                    _ => -0.,
1671                }),
1672                _ => OwnedValue::Text(
1673                    (0..rng.usize(..6))
1674                        .map(|_| PIECES[rng.usize(..PIECES.len())])
1675                        .collect::<String>()
1676                        .into(),
1677                ),
1678            }
1679        }
1680
1681        fn direction(rng: &mut fastrand::Rng) -> SortDirection {
1682            if rng.bool() {
1683                SortDirection::Ascending
1684            } else {
1685                SortDirection::Descending
1686            }
1687        }
1688
1689        let zones = [
1690            ColumnZone::FrozenLeft,
1691            ColumnZone::Scrolling,
1692            ColumnZone::FrozenRight,
1693        ];
1694        for seed in 0..300 {
1695            let mut rng = fastrand::Rng::with_seed(seed);
1696            let mut layout = GridLayout::new();
1697            if rng.bool() {
1698                layout = layout.with_view_id(PIECES[rng.usize(..PIECES.len())]);
1699            }
1700            for _ in 0..rng.usize(..=8) {
1701                layout = layout.with_column(
1702                    LayoutColumn::new(IDS[rng.usize(..IDS.len())], rng.u16(1..800) as f32 / 2.)
1703                        .with_visible(rng.bool())
1704                        .with_zone(zones[rng.usize(..3)]),
1705                );
1706            }
1707            let id = |rng: &mut fastrand::Rng| IDS[rng.usize(..IDS.len())];
1708            let sort: Vec<_> = (0..rng.usize(..=3))
1709                .map(|_| LayoutSort::new(id(&mut rng), direction(&mut rng)))
1710                .collect();
1711            let levels: Vec<_> = (0..rng.usize(..=3))
1712                .map(|_| LayoutGroup::new(id(&mut rng), direction(&mut rng)))
1713                .collect();
1714            let depth = match rng.u8(..4) {
1715                0 => ExpandDepth::All,
1716                1 => ExpandDepth::Captions,
1717                _ => ExpandDepth::Levels(rng.u16(..5)),
1718            };
1719            let mut expansion = LayoutExpansion::new(depth);
1720            for _ in 0..rng.usize(..=10) {
1721                let path: Vec<_> = (0..rng.usize(1..=3)).map(|_| value(&mut rng)).collect();
1722                expansion = expansion.with_toggled(path);
1723            }
1724            let layout = layout
1725                .with_sort(sort)
1726                .with_group_by(levels)
1727                .with_expansion(expansion);
1728
1729            for codec in [
1730                JsonLayoutCodec::default(),
1731                JsonLayoutCodec::default().pretty(true),
1732            ] {
1733                let text = codec.encode(&layout).unwrap();
1734                let read = codec.decode(&text).unwrap();
1735                assert_eq!(read, layout, "seed {seed}: {text}");
1736                // Integers stay integers and floats floats, bit for bit.
1737                assert_eq!(codec.encode(&read).unwrap(), text, "seed {seed}");
1738            }
1739        }
1740    }
1741
1742    /// Microseconds to write and to read a layout of 128 columns, three
1743    /// grouping levels and ten toggled groups. Run with `cargo test
1744    /// --release -p gpui-kit-grid --lib -- --ignored --nocapture
1745    /// test_layout_codec_timing`.
1746    #[test]
1747    #[ignore = "timing; run in release with --ignored --nocapture"]
1748    #[cfg(not(target_family = "wasm"))]
1749    fn test_layout_codec_timing() {
1750        use std::{hint::black_box, time::Instant};
1751
1752        let names: Vec<String> = (0..128).map(|ix| format!("column_{ix}")).collect();
1753        let mut expansion = LayoutExpansion::new(ExpandDepth::Levels(1));
1754        for ix in 0..10 {
1755            expansion = expansion.with_toggled([
1756                text(&format!("instrument {ix}")),
1757                text("Buy"),
1758                OwnedValue::Float(100.25 + f64::from(ix)),
1759            ]);
1760        }
1761        let layout = names
1762            .iter()
1763            .map(|name| LayoutColumn::new(name.clone(), 96.5_f32))
1764            .fold(
1765                GridLayout::new().with_view_id("trades"),
1766                GridLayout::with_column,
1767            )
1768            .with_sort([LayoutSort::new("column_3", SortDirection::Descending)])
1769            .with_group_by(
1770                names[..3]
1771                    .iter()
1772                    .map(|name| LayoutGroup::new(name.clone(), SortDirection::Ascending)),
1773            )
1774            .with_expansion(expansion);
1775
1776        let codec = JsonLayoutCodec::default();
1777        let text = codec.encode(&layout).unwrap();
1778        let micros = |run: &dyn Fn()| {
1779            (0..5)
1780                .map(|_| {
1781                    let started = Instant::now();
1782                    for _ in 0..1_000 {
1783                        run();
1784                    }
1785                    started.elapsed().as_secs_f64() * 1e6 / 1_000.
1786                })
1787                .fold(f64::MAX, f64::min)
1788        };
1789        let encode = micros(&|| {
1790            black_box(codec.encode(black_box(&layout)).unwrap());
1791        });
1792        let decode = micros(&|| {
1793            black_box(codec.decode(black_box(&text)).unwrap());
1794        });
1795        println!(
1796            "{} bytes: encode {encode:.1} µs, decode {decode:.1} µs",
1797            text.len()
1798        );
1799    }
1800
1801    #[test]
1802    fn test_layout_version_rules() {
1803        let codec = JsonLayoutCodec::default();
1804        for (text, found) in [
1805            (r#"{"version":2,"columns":[]}"#, 2),
1806            (r#"{"version":0,"columns":[]}"#, 0),
1807            // The version is checked before the rest: a newer build may have
1808            // changed what the fields mean.
1809            (r#"{"version":99,"columns":"by id"}"#, 99),
1810            (r#"{"version":4294967296,"columns":[]}"#, u32::MAX),
1811        ] {
1812            assert_eq!(
1813                codec.decode(text),
1814                Err(LayoutError::UnsupportedVersion { found }),
1815                "{text}"
1816            );
1817        }
1818        for text in [
1819            r#"{"columns":[]}"#,
1820            r#"{"version":"1","columns":[]}"#,
1821            r#"{"version":-1,"columns":[]}"#,
1822            r#"{"version":1.5,"columns":[]}"#,
1823            r#"{"version":1}"#,
1824            r#"[{"version":1,"columns":[]}]"#,
1825            "not json",
1826            "",
1827        ] {
1828            assert!(
1829                matches!(codec.decode(text), Err(LayoutError::Decode(_))),
1830                "{text}"
1831            );
1832        }
1833
1834        // Plain serde keeps the version it reads, so the grid can refuse a
1835        // layout that did not come through a codec.
1836        let newer: GridLayout = serde_json::from_str(r#"{"version":2,"columns":[]}"#).unwrap();
1837        assert_eq!(newer.version(), 2);
1838        assert_eq!(
1839            check_version(newer.version()),
1840            Err(LayoutError::UnsupportedVersion { found: 2 })
1841        );
1842        assert_eq!(check_version(GridLayout::VERSION), Ok(()));
1843    }
1844
1845    #[test]
1846    fn test_append_new_columns() {
1847        // Schema order with defaults; `fee`, `flag` and `note` are new.
1848        let schema = [
1849            LayoutColumn::new("id", 80_f32).with_zone(ColumnZone::FrozenLeft),
1850            LayoutColumn::new("name", 120_f32),
1851            LayoutColumn::new("fee", 60_f32),
1852            LayoutColumn::new("price", 90_f32),
1853            LayoutColumn::new("flag", 40_f32).with_zone(ColumnZone::FrozenLeft),
1854            LayoutColumn::new("qty", 70_f32).with_visible(false),
1855            LayoutColumn::new("note", 200_f32).with_visible(false),
1856            LayoutColumn::new("side", 50_f32).with_zone(ColumnZone::FrozenRight),
1857        ];
1858        let context = LayoutMergeContext::new(&schema);
1859        assert!(context.contains("fee") && !context.contains("gone"));
1860        assert_eq!(context.column("qty"), Some(&schema[5]));
1861
1862        let saved = GridLayout::new()
1863            .with_column(LayoutColumn::new("price", 101_f32))
1864            .with_column(LayoutColumn::new("gone", 55_f32))
1865            .with_column(LayoutColumn::new("name", 133_f32).with_visible(false))
1866            .with_column(LayoutColumn::new("price", 999_f32).with_zone(ColumnZone::FrozenLeft))
1867            .with_column(LayoutColumn::new("qty", 71_f32).with_zone(ColumnZone::FrozenRight))
1868            .with_column(LayoutColumn::new("id", 81_f32).with_zone(ColumnZone::FrozenLeft))
1869            .with_column(LayoutColumn::new("side", 51_f32).with_zone(ColumnZone::FrozenRight))
1870            .with_column(LayoutColumn::new("gone", 56_f32))
1871            .with_sort([
1872                LayoutSort::new("gone", SortDirection::Descending),
1873                LayoutSort::new("price", SortDirection::Ascending),
1874                LayoutSort::new("price", SortDirection::Descending),
1875                LayoutSort::new("side", SortDirection::Ascending),
1876                LayoutSort::new("zz", SortDirection::Ascending),
1877            ]);
1878
1879        // Saved columns keep their width, visibility and zone; the first
1880        // `price` wins; new columns end their zone in schema order with
1881        // schema defaults.
1882        let merged = AppendNewColumns.merge(&context, &saved);
1883        let expected = [
1884            LayoutColumn::new("id", 81_f32).with_zone(ColumnZone::FrozenLeft),
1885            LayoutColumn::new("flag", 40_f32).with_zone(ColumnZone::FrozenLeft),
1886            LayoutColumn::new("price", 101_f32),
1887            LayoutColumn::new("name", 133_f32).with_visible(false),
1888            LayoutColumn::new("fee", 60_f32),
1889            LayoutColumn::new("note", 200_f32).with_visible(false),
1890            LayoutColumn::new("qty", 71_f32).with_zone(ColumnZone::FrozenRight),
1891            LayoutColumn::new("side", 51_f32).with_zone(ColumnZone::FrozenRight),
1892        ];
1893        assert_eq!(merged, expected);
1894
1895        // The report comes from the schema and the saved layout, not from the
1896        // merge.
1897        let report = LayoutReport::resolve(&context, &saved);
1898        assert_eq!(ids(report.ignored_columns()), ["gone"]);
1899        assert_eq!(ids(report.added_columns()), ["fee", "flag", "note"]);
1900        assert_eq!(ids(report.dropped_sort()), ["gone", "price", "zz"]);
1901        assert!(!report.is_exact());
1902
1903        // Without saved columns the merge is the schema split by zone.
1904        let schema_only = AppendNewColumns.merge(&context, &GridLayout::new());
1905        let order: Vec<_> = schema_only.iter().map(|c| c.id().as_str()).collect();
1906        assert_eq!(
1907            order,
1908            ["id", "flag", "name", "fee", "price", "qty", "note", "side"]
1909        );
1910
1911        // Applying the merged layout again is exact and changes nothing.
1912        let round_trip = merged
1913            .iter()
1914            .cloned()
1915            .fold(GridLayout::new(), GridLayout::with_column)
1916            .with_sort([LayoutSort::new("price", SortDirection::Ascending)]);
1917        assert!(LayoutReport::resolve(&context, &round_trip).is_exact());
1918        assert_eq!(AppendNewColumns.merge(&context, &round_trip), merged);
1919    }
1920
1921    #[test]
1922    fn test_layout_library() {
1923        let trades = |width: f32| {
1924            GridLayout::new()
1925                .with_view_id("trades")
1926                .with_column(LayoutColumn::new("price", width))
1927        };
1928        let names = |library: &LayoutLibrary, view_id: &str| -> Vec<String> {
1929            library.names(view_id).map(str::to_owned).collect()
1930        };
1931
1932        let mut library = LayoutLibrary::new();
1933        assert_eq!(
1934            library.insert("Wide", GridLayout::new()),
1935            Err(LayoutError::MissingViewId)
1936        );
1937        library.insert("Wide", trades(200.)).unwrap();
1938        library.insert("Compact", trades(60.)).unwrap();
1939        library.insert("Wide", trades(240.)).unwrap();
1940        library
1941            .insert("Default", GridLayout::new().with_view_id("orders"))
1942            .unwrap();
1943        assert_eq!(names(&library, "trades"), ["Compact", "Wide"]);
1944        assert_eq!(names(&library, "orders"), ["Default"]);
1945        assert_eq!(names(&library, "positions"), Vec::<String>::new());
1946        assert_eq!(library.get("trades", "Wide"), Some(&trades(240.)));
1947        assert_eq!(library.get("orders", "Wide"), None);
1948
1949        assert_eq!(library.default_layout("trades"), None);
1950        assert!(!library.set_default("trades", Some("Missing")));
1951        assert!(!library.set_default("positions", Some("Wide")));
1952        assert!(library.set_default("trades", Some("Compact")));
1953        assert_eq!(
1954            library.default_layout("trades"),
1955            Some(("Compact", &trades(60.)))
1956        );
1957
1958        // Renaming keeps the default and never replaces another layout.
1959        assert!(!library.rename("trades", "Compact", "Wide"));
1960        assert!(!library.rename("trades", "Missing", "Other"));
1961        assert!(!library.rename("positions", "Compact", "Other"));
1962        assert!(library.rename("trades", "Compact", "Compact"));
1963        assert!(library.rename("trades", "Compact", "Narrow"));
1964        assert_eq!(names(&library, "trades"), ["Narrow", "Wide"]);
1965        assert_eq!(
1966            library.default_layout("trades"),
1967            Some(("Narrow", &trades(60.)))
1968        );
1969
1970        // The library is plain serde data.
1971        let text = serde_json::to_string(&library).unwrap();
1972        assert_eq!(
1973            serde_json::from_str::<LayoutLibrary>(&text).unwrap(),
1974            library
1975        );
1976        let mut orders_only = LayoutLibrary::new();
1977        orders_only
1978            .insert("Default", GridLayout::new().with_view_id("orders"))
1979            .unwrap();
1980        assert_eq!(
1981            serde_json::to_string(&orders_only).unwrap(),
1982            r#"{"views":{"orders":{"layouts":{"Default":{"version":1,"view_id":"orders","columns":[]}}}}}"#
1983        );
1984
1985        // Removing the default clears it; the last removal drops the view.
1986        assert_eq!(library.remove("trades", "Narrow"), Some(trades(60.)));
1987        assert_eq!(library.remove("trades", "Narrow"), None);
1988        assert_eq!(library.default_layout("trades"), None);
1989        assert!(library.set_default("trades", Some("Wide")));
1990        assert!(library.set_default("trades", None));
1991        assert_eq!(library.default_layout("trades"), None);
1992        assert_eq!(library.remove("trades", "Wide"), Some(trades(240.)));
1993        assert_eq!(names(&library, "trades"), Vec::<String>::new());
1994        assert!(library.set_default("trades", None));
1995        assert_eq!(
1996            library.get("orders", "Default").map(GridLayout::version),
1997            Some(1)
1998        );
1999    }
2000}