logisheets_controller 1.0.0

the core of LogiSheets
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
use std::collections::HashMap;

use super::{cell_positioner::CellPositioner, worksheet::Worksheet};
use crate::{
    controller::{
        display::{
            BlockField, CellCoordinateWithSheet, CellPosition, ShadowCellInfo, SheetInfo,
            TempCellChange, TempStatusDiff, Value as DisplayValue,
        },
        status::Status,
    },
    edit_action::{ActionEffect, PayloadsAction, SheetCellId, StatusCode},
    lock::{locked_write, new_locked, Locked},
    CellInfo, Controller,
};
use crate::{
    edit_action::{EditAction, EphemeralCellInput},
    errors::{Error, Result},
};
use logisheets_base::{
    async_func::{AsyncCalcResult, Task},
    errors::BasicError,
    BlockCellId, BlockId, CellId, ColId, RowId, SheetId, TextId,
};
use logisheets_lexer::lex;
use logisheets_workbook::logisheets::AppData;

const CALC_CONDITION_EPHEMERAL_ID: u64 = 225715;

pub(crate) type CellPositionerDefault = CellPositioner<1000>;

pub struct Workbook {
    controller: Controller,
    cell_positioners: Locked<HashMap<SheetId, Locked<CellPositionerDefault>>>,
}

impl Default for Workbook {
    fn default() -> Self {
        Self {
            controller: Default::default(),
            cell_positioners: new_locked(HashMap::new()),
        }
    }
}

impl Workbook {
    /// Create an empty workbook.
    pub fn new() -> Self {
        Workbook {
            controller: Default::default(),
            cell_positioners: new_locked(HashMap::new()),
        }
    }

    /// Execute the `EditAction`
    pub fn handle_action(&mut self, action: EditAction) -> ActionEffect {
        self.controller.handle_action(action)
    }

    pub fn get_sheet_name_by_idx(&self, idx: usize) -> Result<String> {
        let sheet_id = self
            .controller
            .status
            .sheet_info_manager
            .pos
            .get(idx)
            .ok_or(BasicError::SheetIdxExceed(idx))?;
        let name = self
            .controller
            .status
            .sheet_id_manager
            .get_string(sheet_id)
            .ok_or(BasicError::SheetIdNotFound(*sheet_id))?;
        Ok(name)
    }

    /// Execute the `EditAction` on the temp branch. Subsequent calls accumulate on the same branch
    /// until `commit_temp_status` or `clean_temp_status` is called.
    pub fn handle_action_in_temp_status(&mut self, action: PayloadsAction) -> ActionEffect {
        self.controller.handle_action_in_temp_status(action)
    }

    pub fn commit_temp_status(&mut self) {
        self.controller.commit_temp_status();
    }

    pub fn clean_temp_status(&mut self) {
        self.controller.clean_temp_status();
    }

    pub fn toggle_status(&mut self, _use_temp: bool) {
        // No-op: self.status always reflects the active state (temp or real).
    }

    pub fn batch_get_cell_info_by_id(&self, ids: Vec<SheetCellId>) -> Result<Vec<CellInfo>> {
        let mut result = Vec::new();
        for id in ids {
            let sheet_id = id.sheet_id;
            let worksheet = self.get_sheet_by_id(sheet_id)?;
            let info = worksheet.get_cell_info_by_cell_id(&id.cell_id)?;
            result.push(info);
        }
        Ok(result)
    }

    pub fn batch_get_cell_coordinate_with_sheet_by_id(
        &self,
        ids: Vec<SheetCellId>,
    ) -> Result<Vec<CellCoordinateWithSheet>> {
        let mut result = Vec::new();
        for id in ids {
            let sheet_id = id.sheet_id;
            let worksheet = self.get_sheet_by_id(sheet_id)?;
            let coordinate = worksheet.get_cell_coordinate_by_id(&id.cell_id)?;
            result.push(CellCoordinateWithSheet {
                sheet_idx: self.get_sheet_idx_by_id(sheet_id)?,
                coordinate,
            });
        }
        Ok(result)
    }

    pub fn get_cell_info_by_id(&self, id: SheetCellId) -> Result<CellInfo> {
        let sheet_id = id.sheet_id;
        let worksheet = self.get_sheet_by_id(sheet_id)?;
        worksheet.get_cell_info_by_cell_id(&id.cell_id)
    }

    /// Create a workbook from a .xlsx file.
    pub fn from_file(buf: &[u8], book_name: String) -> Result<Self> {
        let mut controller = Controller::from_file(book_name, buf)?;
        controller
            .version_manager
            .set_init_status(controller.status.clone());
        Ok(Workbook {
            controller,
            cell_positioners: new_locked(HashMap::new()),
        })
    }

    #[inline]
    pub fn get_app_data(&self) -> Vec<AppData> {
        self.controller.app_data.clone()
    }

    #[inline]
    pub fn set_app_data(&mut self, app_data: Vec<AppData>) {
        self.controller.app_data = app_data;
    }

    #[inline]
    pub fn save(&self) -> Result<Vec<u8>> {
        self.controller.save()
    }

    #[inline]
    pub fn undo(&mut self) -> bool {
        self.controller.undo()
    }

    #[inline]
    pub fn redo(&mut self) -> bool {
        self.controller.redo()
    }

    #[inline]
    pub fn handle_async_calc_results(
        &mut self,
        tasks: Vec<Task>,
        results: Vec<AsyncCalcResult>,
    ) -> ActionEffect {
        if tasks.len() != results.len() {
            return ActionEffect {
                version: 0,
                async_tasks: vec![],
                status: StatusCode::Err(1),
                value_changed: vec![],
                cell_removed: vec![],
                style_changed: vec![],
                ..Default::default()
            };
        }
        self.controller.handle_async_calc_results(tasks, results)
    }

    #[inline]
    pub fn get_all_sheet_info(&self) -> Vec<SheetInfo> {
        self.controller.get_all_sheet_info()
    }

    #[inline]
    pub fn get_cell_positioner(&self, sheet: SheetId) -> Locked<CellPositionerDefault> {
        let mut cell_positioners = locked_write(&self.cell_positioners);
        let entry = cell_positioners
            .entry(sheet)
            .or_insert_with(|| new_locked(CellPositionerDefault::new()));

        entry.clone()
    }

    pub fn get_block_values(
        &self,
        sheet_id: SheetId,
        block_id: BlockId,
        row_ids: &[RowId],
        col_ids: &[ColId],
    ) -> Result<Vec<String>> {
        let text_id_fetcher = |id: TextId| {
            self.controller
                .status
                .text_id_manager
                .get_string(&id)
                .unwrap()
        };
        let values = row_ids
            .iter()
            .zip(col_ids.iter())
            .map(|(row_id, col_id)| {
                let cell_id = CellId::BlockCell(BlockCellId {
                    block_id,
                    row: *row_id,
                    col: *col_id,
                });
                let v = self
                    .controller
                    .status
                    .container
                    .get_cell(sheet_id, &cell_id)
                    .map(|c| c.value.to_string(&text_id_fetcher))
                    .unwrap_or_default();
                v
            })
            .collect::<Vec<String>>();
        Ok(values)
    }

    pub fn get_sheet_by_name(&self, name: &str) -> Result<Worksheet> {
        let id = self.controller.get_sheet_id_by_name(name);
        if id.is_none() {
            return Err(BasicError::SheetNameNotFound(name.to_string()).into());
        }
        let sheet_id = id.unwrap();
        self.get_sheet_by_id(sheet_id)
    }

    pub fn get_sheet_idx_by_id(&self, sheet_id: SheetId) -> Result<usize> {
        self.controller
            .status
            .sheet_info_manager
            .get_sheet_idx(&sheet_id)
            .ok_or(BasicError::UnavailableSheetId(sheet_id).into())
    }

    pub fn get_sheet_by_id(&self, sheet_id: SheetId) -> Result<Worksheet> {
        let positioner = self.get_cell_positioner(sheet_id);
        let c = &self.controller;
        Ok(Worksheet {
            sheet_id,
            controller: c,
            positioner,
        })
    }

    pub fn get_sheet_idx_by_name(&self, name: &str) -> Result<usize> {
        let sheet_id = self.controller.get_sheet_id_by_name(name);
        if let Some(id) = sheet_id {
            if let Some(idx) = self.controller.status.sheet_info_manager.get_sheet_idx(&id) {
                Ok(idx)
            } else {
                Err(BasicError::SheetNameNotFound(name.to_string()).into())
            }
        } else {
            Err(BasicError::SheetNameNotFound(name.to_string()).into())
        }
    }

    pub fn get_sheet_by_idx(&self, idx: usize) -> Result<Worksheet> {
        match self.controller.get_sheet_id_by_idx(idx) {
            Some(sheet_id) => Ok(Worksheet {
                sheet_id,
                controller: &self.controller,
                positioner: self.get_cell_positioner(sheet_id),
            }),
            None => Err(Error::UnavailableSheetIdx(idx)),
        }
    }

    pub fn get_sheet_count(&self) -> usize {
        self.controller.status.sheet_info_manager.pos.len()
    }

    /// To see if the formula is valid.
    pub fn check_formula(&self, f: String) -> bool {
        if f.is_empty() {
            return false;
        }
        let f = f.trim();
        if !f.starts_with('=') {
            return false;
        }
        let tokens = lex(&f[1..]);
        tokens.is_some()
    }

    pub fn get_all_block_fields(&self) -> Result<Vec<BlockField>> {
        Ok(self.controller.status.container.get_all_block_fields())
    }

    /// Returns the owner and modify policy of a block. Used by the frontend
    /// validate hook to gate writes.
    pub fn get_block_modify_info(
        &self,
        sheet_idx: usize,
        block_id: usize,
    ) -> Result<crate::edit_action::BlockModifyInfo> {
        let sheet_id = self
            .controller
            .status
            .sheet_info_manager
            .get_sheet_id(sheet_idx)
            .ok_or(BasicError::SheetIdxExceed(sheet_idx))?;
        let sheet_nav = self.controller.status.navigator.get_sheet_nav(&sheet_id)?;
        let block = sheet_nav
            .data
            .blocks
            .get(&block_id)
            .ok_or(BasicError::BlockIdNotFound(sheet_id, block_id))?;
        Ok(crate::edit_action::BlockModifyInfo {
            owner: block.owner.clone(),
            modify_policy: block.modify_policy.clone(),
        })
    }

    pub fn get_available_block_id(&self, sheet_idx: usize) -> Result<usize> {
        let sheet_id = self
            .controller
            .status
            .sheet_info_manager
            .get_sheet_id(sheet_idx)
            .ok_or(BasicError::SheetIdxExceed(sheet_idx))?;
        let block_id = self
            .controller
            .status
            .navigator
            .get_available_block_id(&sheet_id)?;
        Ok(block_id)
    }

    pub fn get_shadow_cell_id(
        &mut self,
        sheet_idx: usize,
        row_idx: usize,
        col_idx: usize,
        kind: crate::sid_assigner::ShadowKind,
    ) -> Result<SheetCellId> {
        let sheet_id = self
            .controller
            .status
            .sheet_info_manager
            .get_sheet_id(sheet_idx)
            .ok_or(BasicError::SheetIdxExceed(sheet_idx))?;
        let cell_id = self
            .controller
            .status
            .navigator
            .fetch_cell_id(&sheet_id, row_idx, col_idx)?;
        let eid = self
            .controller
            .sid_assigner
            .get_shawdow_id(sheet_id, cell_id, kind);
        Ok(SheetCellId {
            sheet_id,
            cell_id: CellId::EphemeralCell(eid),
        })
    }

    pub fn get_shawdow_cell_ids(
        &mut self,
        sheet_idx: usize,
        row_idx: Vec<usize>,
        col_idx: Vec<usize>,
        kind: crate::sid_assigner::ShadowKind,
    ) -> Result<Vec<SheetCellId>> {
        if row_idx.len() != col_idx.len() {
            return Err(BasicError::IncompleteRowColLength(row_idx.len(), col_idx.len()).into());
        }
        let sheet_id = self
            .controller
            .status
            .sheet_info_manager
            .get_sheet_id(sheet_idx)
            .ok_or(BasicError::SheetIdxExceed(sheet_idx))?;
        row_idx
            .into_iter()
            .zip(col_idx.into_iter())
            .map(|(row, col)| {
                let cell_id = self
                    .controller
                    .status
                    .navigator
                    .fetch_cell_id(&sheet_id, row, col)?;
                let eid = self
                    .controller
                    .sid_assigner
                    .get_shawdow_id(sheet_id, cell_id, kind);
                Ok(SheetCellId {
                    sheet_id,
                    cell_id: CellId::EphemeralCell(eid),
                })
            })
            .collect()
    }

    pub fn get_shadow_info_by_id(&self, shadow_id: u64) -> Result<ShadowCellInfo> {
        let (sheet_id, cell_id) = self
            .controller
            .sid_assigner
            .get_cell_id(shadow_id)
            .ok_or(BasicError::InvalidShadowId(shadow_id))?;
        let (start_position, end_position) = self.get_cell_position_by_id(sheet_id, cell_id)?;
        let value = self
            .get_sheet_by_id(sheet_id)?
            .get_value_by_id(&CellId::EphemeralCell(shadow_id))?;
        Ok(ShadowCellInfo {
            start_position,
            end_position,
            value,
        })
    }

    fn get_cell_position_by_id(
        &self,
        sheet_id: SheetId,
        cell_id: CellId,
    ) -> Result<(CellPosition, CellPosition)> {
        if let CellId::EphemeralCell(_) = cell_id {
            return Err(BasicError::ReferencingEphemeralCell.into());
        }

        let (row, col) = self
            .controller
            .status
            .navigator
            .fetch_cell_idx(&sheet_id, &cell_id)?;
        let ws = self.get_sheet_by_id(sheet_id)?;
        let mut positioner = locked_write(&ws.positioner);
        let x = ws.get_col_start_x(col, &mut *positioner)?;
        let y = ws.get_row_start_y(row, &mut *positioner)?;
        let end_x = ws.get_col_start_x(col + 1, &mut *positioner)?;
        let end_y = ws.get_row_start_y(row + 1, &mut *positioner)?;
        drop(positioner);
        Ok((CellPosition { x, y }, CellPosition { x: end_x, y: end_y }))
    }

    pub fn check_bind_block(
        &mut self,
        sheet_idx: usize,
        block_id: usize,
        row_count: usize,
        col_count: usize,
    ) -> Result<SheetId> {
        let sheet_id = self
            .controller
            .status
            .sheet_info_manager
            .get_sheet_id(sheet_idx)
            .unwrap();

        let block_size = self
            .controller
            .status
            .navigator
            .get_block_size(&sheet_id, &block_id)?;
        if row_count > block_size.0 || col_count > block_size.1 {
            return Err(BasicError::BindBlockSizeMismatch(block_id, row_count, col_count).into());
        }
        Ok(sheet_id)
    }

    /// Resolve a (refName, key, field) triple to the concrete cell in a
    /// block-bound table. Mirrors how the BLOCKREF formula resolves at
    /// evaluation time:
    ///   1. refName → (sheetId, blockId) via the schema manager's ref map
    ///   2. enumerate the block's key cells and find the one whose value
    ///      matches `key`
    ///   3. ask the schema to convert (keyCellId, field) → BlockCellId
    ///
    /// Returns the BlockCell wrapped in a SheetCellId for direct use with
    /// e.g. cell-changed subscriptions or batch reads.
    pub fn get_cell_id_by_block_ref(
        &self,
        ref_name: &str,
        key: &str,
        field: &str,
    ) -> Result<SheetCellId> {
        let status = &self.controller.status;
        let navigator = &status.navigator;
        let bp_fetcher = |sid: &SheetId, bid: &BlockId| navigator.get_block_place(sid, bid).ok();

        let (sheet_id, key_cell_ids) = status
            .block_schema_manager
            .get_all_key_cell_ids(ref_name, &bp_fetcher)
            .ok_or_else(|| {
                BasicError::InvalidFormula(format!("unknown block ref: {}", ref_name))
            })?;

        // Read each key cell's string value and find the one matching `key`.
        let text_fetcher = |id: TextId| status.text_id_manager.get_string(&id).unwrap_or_default();
        let key_string = key.to_string();
        let matched_key_cell = key_cell_ids
            .into_iter()
            .find(|bcid| {
                status
                    .container
                    .get_cell(sheet_id, &CellId::BlockCell(*bcid))
                    .map(|cell| cell.value.to_string(&text_fetcher) == key_string)
                    .unwrap_or(false)
            })
            .ok_or_else(|| {
                BasicError::InvalidFormula(format!(
                    "key '{}' not found in block ref '{}'",
                    key, ref_name
                ))
            })?;

        let field_string = field.to_string();
        let bcid = status
            .block_schema_manager
            .partially_resolve(ref_name, matched_key_cell, &field_string)
            .ok_or_else(|| {
                BasicError::InvalidFormula(format!(
                    "field '{}' not found in block ref '{}'",
                    field, ref_name
                ))
            })?;

        Ok(SheetCellId {
            sheet_id,
            cell_id: CellId::BlockCell(bcid),
        })
    }

    /// Snapshot of every cell whose value differs between the active
    /// temp branch and the committed (fork) status. Used by the host's
    /// diff layer to drive its overlay without needing JS-side
    /// snapshot/compare logic. Returns an empty diff when no temp
    /// branch is currently active.
    ///
    /// Position (`row`, `col`) reflects the *current* sheet coordinates
    /// in the temp branch — block inserts may have shifted earlier rows
    /// since the fork point. Cells whose `CellId` exists in temp but
    /// not in main (or vice versa) are skipped here; for the moment
    /// they surface as structural changes which a future revision can
    /// add to the diff.
    pub fn get_temp_status_changes(&self) -> Result<TempStatusDiff> {
        let Some(temp) = &self.controller.temp_status else {
            return Ok(TempStatusDiff::default());
        };

        let mut cells: Vec<TempCellChange> = Vec::new();
        for (sheet_id, cell_id) in &temp.accumulated_updated_cells {
            // Resolve to (row, col) via the current navigator (post-
            // temp). If the cell was deleted (no longer addressable),
            // skip it — that surfaces as a structural diff, future
            // work.
            let (row, col) = match self
                .controller
                .status
                .navigator
                .clone()
                .fetch_cell_idx(sheet_id, cell_id)
            {
                Ok(rc) => rc,
                Err(_) => continue,
            };
            let sheet_idx = match self
                .controller
                .status
                .sheet_info_manager
                .get_sheet_idx(sheet_id)
            {
                Some(i) => i,
                None => continue,
            };
            let new_value = read_display_value(&self.controller.status, *sheet_id, cell_id);
            let old_value = read_display_value(&temp.fork_status, *sheet_id, cell_id);
            cells.push(TempCellChange {
                sheet_idx,
                row,
                col,
                old_value,
                new_value,
            });
        }
        Ok(TempStatusDiff { cells })
    }

    pub fn calc_condition(&mut self, sheet_idx: usize, f: String) -> Result<bool> {
        let effect = self.handle_action(EditAction::Payloads(PayloadsAction::new().add_payload(
            EphemeralCellInput {
                sheet_idx,
                id: CALC_CONDITION_EPHEMERAL_ID,
                content: f.clone(),
            },
        )));
        let sheet_id = self
            .controller
            .status
            .sheet_info_manager
            .get_sheet_id(sheet_idx)
            .unwrap();
        if let StatusCode::Ok(_) = effect.status {
            let cell = self
                .controller
                .status
                .container
                .get_cell(
                    sheet_id,
                    &CellId::EphemeralCell(CALC_CONDITION_EPHEMERAL_ID),
                )
                .unwrap();
            if cell.value.is_error() {
                Err(BasicError::InvalidFormula(f).into())
            } else {
                Ok(cell.value.bool_value())
            }
        } else {
            Err(BasicError::InvalidFormula(f).into())
        }
    }

    /// Get the worksheet id by its index.
    ///
    /// It is not recommended to use this function because worksheet id is an internal
    /// conception. Use this only when you know what you are doing.
    pub fn get_worksheet_id(&self, sheet_idx: usize) -> Result<SheetId> {
        self.controller
            .status
            .sheet_info_manager
            .get_sheet_id(sheet_idx)
            .ok_or(BasicError::SheetIdxExceed(sheet_idx).into())
    }
}

/// Read a single cell's display value from a specific Status. The temp
/// branch and the fork (main) branch are both `Status` instances — this
/// helper lets `get_temp_status_changes` resolve old/new values without
/// going through `Worksheet` (which is tied to the live status only).
fn read_display_value(status: &Status, sheet_id: SheetId, cell_id: &CellId) -> DisplayValue {
    let Some(cell) = status.container.get_cell(sheet_id, cell_id) else {
        return DisplayValue::Empty;
    };
    match cell.value {
        logisheets_base::CellValue::Blank => DisplayValue::Empty,
        logisheets_base::CellValue::Boolean(b) => DisplayValue::Bool(b),
        logisheets_base::CellValue::Error(ref e) => DisplayValue::Error(e.to_string()),
        logisheets_base::CellValue::String(ref s) => match status.text_id_manager.get_string(s) {
            Some(r) => DisplayValue::Str(r),
            None => DisplayValue::Str(String::new()),
        },
        logisheets_base::CellValue::Number(n) => DisplayValue::Number(n),
        logisheets_base::CellValue::InlineStr(_) => DisplayValue::Empty,
        logisheets_base::CellValue::FormulaStr(ref s) => DisplayValue::Str(s.clone()),
    }
}