logisheets_controller 1.16.1

Core spreadsheet engine for LogiSheets: formula evaluation, dependency tracking, and undo/redo.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
use imbl::HashMap;
use logisheets_base::{
    BlockCellId, BlockId, CellId, ColId, NormalCellId, RowId, SheetId, a1_notation,
    errors::{BasicError, Context},
};

pub use self::{block::BlockPlace, sheet_nav::SheetNav};

mod block;
pub mod ctx;
mod executor;
mod fetcher;
mod id_manager;
pub(crate) mod sheet_nav;
pub use executor::NavExecutor;

#[derive(Debug, Clone, Default)]
pub struct Navigator {
    pub sheet_navs: HashMap<SheetId, SheetNav>,
}

// The navigator is the only place indices and ids convert, so every failure
// here is a failed conversion and records the address it started from. The id
// in the innermost message is often not one the caller passed: resolving a
// block cell goes through the block's anchor first.
fn on_sheet(sheet_id: SheetId) -> String {
    format!("on sheet id {sheet_id}")
}

fn converting_cell(sheet_id: SheetId, row: usize, col: usize) -> String {
    format!(
        "converting cell {} (row index {row}, column index {col}) {} to a cell id",
        a1_notation(row, col),
        on_sheet(sheet_id)
    )
}

impl Navigator {
    pub fn fetch_row_id(&self, sheet_id: &SheetId, row: usize) -> Result<RowId, BasicError> {
        let fetcher = self.get_sheet_nav(sheet_id)?.get_fetcher();
        fetcher.get_row_id(row)
    }

    pub fn fetch_row_idx(&self, sheet_id: &SheetId, row: &RowId) -> Result<usize, BasicError> {
        let fetcher = self.get_sheet_nav(sheet_id)?.get_fetcher();
        fetcher
            .get_row_idx(*row)
            .context(|| format!("locating row id {row} {}", on_sheet(*sheet_id)))
    }

    pub fn fetch_col_id(&self, sheet_id: &SheetId, col: usize) -> Result<ColId, BasicError> {
        let fetcher = self.get_sheet_nav(sheet_id)?.get_fetcher();
        fetcher.get_col_id(col)
    }

    pub fn fetch_col_idx(&self, sheet_id: &SheetId, col: &ColId) -> Result<usize, BasicError> {
        let fetcher = self.get_sheet_nav(sheet_id)?.get_fetcher();
        fetcher
            .get_col_idx(*col)
            .context(|| format!("locating column id {col} {}", on_sheet(*sheet_id)))
    }

    pub fn fetch_cell_id(
        &self,
        sheet_id: &SheetId,
        row: usize,
        col: usize,
    ) -> Result<CellId, BasicError> {
        let fetcher = self.get_sheet_nav(sheet_id)?.get_fetcher();
        fetcher
            .get_cell_id(row, col)
            .context(|| converting_cell(*sheet_id, row, col))
    }

    pub fn fetch_block_cell_id(
        &self,
        sheet_id: &SheetId,
        block_id: &BlockId,
        row: usize,
        col: usize,
    ) -> Result<BlockCellId, BasicError> {
        let bp = self.get_block_place(sheet_id, block_id)?;
        if let Some((rid, cid)) = bp.get_inner_id(row, col) {
            Ok(BlockCellId {
                block_id: block_id.clone(),
                row: rid,
                col: cid,
            })
        } else {
            Err(BasicError::BlockCellIdNotFound(
                *sheet_id, *block_id, row, col,
            ))
        }
    }

    pub fn fetch_block_row_id(
        &self,
        sheet_id: &SheetId,
        block_id: &BlockId,
        row_idx: usize,
    ) -> Result<RowId, BasicError> {
        let bp = self.get_block_place(sheet_id, block_id)?;
        if let Some((rid, _)) = bp.get_inner_id(row_idx, 0) {
            Ok(rid)
        } else {
            Err(BasicError::BlockRowIdNotFound(
                *sheet_id, *block_id, row_idx,
            ))
        }
    }

    pub fn fetch_block_col_id(
        &self,
        sheet_id: &SheetId,
        block_id: &BlockId,
        col_idx: usize,
    ) -> Result<ColId, BasicError> {
        let bp = self.get_block_place(sheet_id, block_id)?;
        if let Some((_, cid)) = bp.get_inner_id(0, col_idx) {
            Ok(cid)
        } else {
            Err(BasicError::BlockColIdNotFound(
                *sheet_id, *block_id, col_idx,
            ))
        }
    }

    pub fn fetch_norm_cell_id(
        &self,
        sheet_id: &SheetId,
        row: usize,
        col: usize,
    ) -> Result<NormalCellId, BasicError> {
        let fetcher = self.get_sheet_nav(sheet_id)?.get_fetcher();
        fetcher
            .get_norm_cell_id(row, col)
            .context(|| converting_cell(*sheet_id, row, col))
    }

    pub fn fetch_cell_idx(
        &self,
        sheet_id: &SheetId,
        cell_id: &CellId,
    ) -> Result<(usize, usize), BasicError> {
        let fetcher = self.get_sheet_nav(sheet_id)?.get_fetcher();
        fetcher.get_cell_idx(cell_id).context(|| {
            format!(
                "resolving the position of {cell_id} {}",
                on_sheet(*sheet_id)
            )
        })
    }

    pub fn fetch_normal_cell_idx(
        &self,
        sheet_id: &SheetId,
        cell_id: &NormalCellId,
    ) -> Result<(usize, usize), BasicError> {
        let fetcher = self.get_sheet_nav(sheet_id)?.get_fetcher();
        fetcher.get_norm_cell_idx(cell_id).context(|| {
            format!(
                "resolving the position of {cell_id} {}",
                on_sheet(*sheet_id)
            )
        })
    }

    pub fn fetch_block_cell_idx(
        &self,
        sheet_id: &SheetId,
        cell_id: &BlockCellId,
    ) -> Result<(usize, usize), BasicError> {
        let fetcher = self.get_sheet_nav(sheet_id)?.get_fetcher();
        fetcher.get_block_cell_idx(cell_id).context(|| {
            format!(
                "resolving the position of {cell_id} {}",
                on_sheet(*sheet_id)
            )
        })
    }

    pub fn create_block(
        &mut self,
        sheet_id: &SheetId,
        master: NormalCellId,
        row_cnt: usize,
        col_cnt: usize,
    ) {
        let sheet_nav = self.get_sheet_nav_mut(sheet_id);
        let block_place = BlockPlace::new(
            master,
            row_cnt as u32,
            col_cnt as u32,
            String::new(),
            Default::default(),
        );
        let block_id = sheet_nav.id_manager.get_block_id();
        sheet_nav.data.blocks.insert(block_id, block_place);
        sheet_nav.cache = Default::default();
    }

    pub fn remove_block(&mut self, sheet_id: &SheetId, block_id: &BlockId) {
        let sheet_nav = self.get_sheet_nav_mut(sheet_id);
        sheet_nav.data.blocks.remove(block_id);
        sheet_nav.cache = Default::default();
    }

    pub fn move_block(
        &mut self,
        sheet_id: &SheetId,
        block_id: &BlockId,
        row_idx: usize,
        col_idx: usize,
    ) {
        if let Ok((row_cnt, col_cnt)) = self.get_block_size(sheet_id, block_id) {
            if !self.any_other_blocks_in(
                *sheet_id,
                *block_id,
                row_idx,
                col_idx,
                row_idx + row_cnt - 1,
                col_idx + col_cnt - 1,
            ) {
                let new_master = self
                    .fetch_norm_cell_id(&sheet_id, row_idx, col_idx)
                    .unwrap();
                let sheet_nav = self.get_sheet_nav_mut(sheet_id);
                if let Some(bp) = sheet_nav.data.blocks.get_mut(block_id) {
                    bp.master = new_master;
                    sheet_nav.cache = Default::default();
                }
            }
        }
    }

    pub fn delete_sheet(&mut self, sheet_id: &SheetId) {
        self.sheet_navs.remove(sheet_id);
    }

    pub fn create_sheet(&mut self, sheet_id: SheetId) {
        self.sheet_navs.insert(sheet_id, SheetNav::default());
    }

    pub fn get_affected_blockplace(
        &self,
        sheet_id: &SheetId,
        line_idx: usize,
        cnt: usize,
        is_row: bool,
    ) -> Result<Vec<BlockId>, BasicError> {
        let sheet_nav = self
            .sheet_navs
            .get(sheet_id)
            .ok_or(BasicError::SheetIdNotFound(*sheet_id))?;
        let mut result: Vec<BlockId> = vec![];
        sheet_nav.data.blocks.iter().for_each(|(b_id, bp)| {
            let master = &bp.master;
            let master_idx = self.fetch_normal_cell_idx(sheet_id, &master);
            if let Ok((m_row, m_col)) = master_idx {
                let (row_cnt, col_cnt) = bp.get_block_size();
                if is_row && intersect(m_row, m_row + row_cnt - 1, line_idx, line_idx + cnt - 1) {
                    result.push(b_id.clone())
                } else if !is_row
                    && intersect(m_col, m_col + col_cnt - 1, line_idx, line_idx + cnt - 1)
                {
                    result.push(b_id.clone())
                }
            }
        });
        Ok(result)
    }

    #[inline]
    pub fn get_block_place(
        &self,
        sheet_id: &SheetId,
        block_id: &BlockId,
    ) -> Result<&BlockPlace, BasicError> {
        let sheet_nav = self
            .sheet_navs
            .get(sheet_id)
            .ok_or(BasicError::SheetIdNotFound(*sheet_id))?;
        let block_place = sheet_nav
            .data
            .blocks
            .get(block_id)
            .ok_or(BasicError::BlockIdNotFound(*sheet_id, *block_id))?;
        Ok(block_place)
    }

    #[inline]
    pub fn get_block_size(
        &self,
        sheet_id: &SheetId,
        block_id: &BlockId,
    ) -> Result<(usize, usize), BasicError> {
        let bp = self.get_block_place(sheet_id, block_id)?;
        Ok(bp.get_block_size())
    }

    /// Absolute rectangles `(start_row, start_col, end_row, end_col)` of every
    /// block on the sheet. Used by data-boundary navigation (Ctrl+Arrow) to
    /// treat block edges as hard stops. Blocks whose master can't be resolved
    /// or that are degenerate (zero rows/cols) are skipped.
    pub fn get_block_rects(&self, sheet_id: &SheetId) -> Vec<(usize, usize, usize, usize)> {
        let sheet_nav = match self.sheet_navs.get(sheet_id) {
            Some(sn) => sn,
            None => return vec![],
        };
        let mut rects = vec![];
        for (_block_id, bp) in sheet_nav.data.blocks.iter() {
            let (m_row, m_col) = match self.fetch_normal_cell_idx(sheet_id, &bp.master) {
                Ok(idx) => idx,
                Err(_) => continue,
            };
            let (row_cnt, col_cnt) = bp.get_block_size();
            if row_cnt == 0 || col_cnt == 0 {
                continue;
            }
            rects.push((m_row, m_col, m_row + row_cnt - 1, m_col + col_cnt - 1));
        }
        rects
    }

    #[inline]
    pub fn get_master_cell(
        &self,
        sheet_id: &SheetId,
        block_id: &BlockId,
    ) -> Result<NormalCellId, BasicError> {
        let bp = self.get_block_place(sheet_id, block_id)?;
        let nc = bp.master;
        Ok(nc)
    }

    pub fn add_sheet_id(&mut self, sheet_id: &SheetId) {
        self.get_sheet_nav_mut(sheet_id);
    }

    fn get_sheet_nav_mut(&mut self, sheet_id: &SheetId) -> &mut SheetNav {
        if let Some(_) = self.sheet_navs.get(sheet_id) {
            self.sheet_navs.get_mut(sheet_id).unwrap()
        } else {
            self.sheet_navs
                .insert(sheet_id.clone(), SheetNav::default());
            self.sheet_navs.get_mut(sheet_id).unwrap()
        }
    }

    /// The blocks on this sheet that declare they analyse `block_id`, in id
    /// order so two reads of an unchanged sheet agree.
    ///
    /// A scan: analysis blocks are few and a sheet holds tens of blocks, not
    /// thousands. Reported to readers alongside the forward marker so an agent
    /// sees the relation from either end — from the table, "this is
    /// summarised"; from the summary, "this is what I summarise".
    pub fn analyzed_by(&self, sheet_id: &SheetId, block_id: BlockId) -> Vec<BlockId> {
        let Ok(sheet_nav) = self.get_sheet_nav(sheet_id) else {
            return Vec::new();
        };
        let mut out: Vec<BlockId> = sheet_nav
            .data
            .blocks
            .iter()
            .filter(|(_, bp)| bp.analyzes == Some(block_id))
            .map(|(id, _)| *id)
            .collect();
        out.sort_unstable();
        out
    }

    pub(crate) fn get_sheet_nav(&self, sheet_id: &SheetId) -> Result<&SheetNav, BasicError> {
        self.sheet_navs
            .get(sheet_id)
            .ok_or(BasicError::SheetIdNotFound(*sheet_id))
    }

    pub fn add_block_place(self, sheet_id: SheetId, block_id: BlockId, bp: BlockPlace) -> Self {
        let mut res = self;
        let sheet_nav = res.sheet_navs.get_mut(&sheet_id);
        match sheet_nav {
            Some(sn) => {
                sn.data.blocks.insert(block_id, bp);
                // Replace the cache field with a fresh `Locked<Cache>`
                // rather than mutating the existing one. Under the
                // `sequencer` feature `Locked<T> = Arc<RwLock<T>>`, so
                // the cache is structurally shared with any prior
                // `SheetNav::clone` (including `old_navigator` used by
                // the formula executor's idx-navigator path within the
                // same payload). Mutating the shared `Cache` would let
                // a Fetcher operating against the OLD SheetNav (whose
                // `data.blocks` still has the pre-insert layout) write
                // a stale `(row, col) → NormalCell` mapping into the
                // cache that's also visible to the new SheetNav — the
                // observed failure mode for InsertRowsInBlock followed
                // by BlockInput on the freshly-grown row. Re-assigning
                // gives the new SheetNav an independent Arc, so writes
                // from old-Fetcher Arc{A} don't leak into new-Fetcher
                // Arc{B}.
                sn.cache = Default::default();
                res
            }
            None => res,
        }
    }

    pub fn clean_cache(&mut self, sheet_id: SheetId) {
        if let Some(sn) = self.sheet_navs.get_mut(&sheet_id) {
            sn.cache = Default::default();
        }
    }

    pub fn any_other_blocks_in(
        &self,
        sheet_id: SheetId,
        block_id: BlockId,
        start_row: usize,
        end_row: usize,
        start_col: usize,
        end_col: usize,
    ) -> bool {
        for i in start_row..=start_col {
            for j in end_row..=end_col {
                let cell_id = self.fetch_cell_id(&sheet_id, i, j).unwrap();
                if let CellId::BlockCell(b) = cell_id {
                    if b.block_id != block_id {
                        return true;
                    }
                }
            }
        }
        false
    }

    pub fn get_available_block_id(&self, sheet_id: &SheetId) -> Result<BlockId, BasicError> {
        let sheet_nav = self.get_sheet_nav(sheet_id)?;
        let bid =
            sheet_nav.data.blocks.iter().fold(
                0 as BlockId,
                |acc, (b_id, _)| {
                    if *b_id > acc { *b_id } else { acc }
                },
            );
        Ok(bid + 1)
    }
}

fn intersect(start1: usize, end1: usize, start2: usize, end2: usize) -> bool {
    if start1 > end2 || start2 > end1 {
        false
    } else {
        true
    }
}