excel_cli/app/
undo_manager.rs

1use crate::actions::{
2    ActionCommand, ActionExecutor, ActionType, CellAction, ColumnAction, MultiColumnAction,
3    MultiRowAction, RowAction, SheetAction,
4};
5use crate::app::AppState;
6use crate::utils::index_to_col_name;
7use anyhow::Result;
8use std::rc::Rc;
9
10impl AppState<'_> {
11    pub fn undo(&mut self) -> Result<()> {
12        if let Some(action) = self.undo_history.undo() {
13            self.apply_action(&action, true)?;
14
15            self.workbook.recalculate_max_rows();
16            self.workbook.recalculate_max_cols();
17            self.ensure_column_widths();
18
19            // Update cursor position if it's outside the valid range
20            let sheet = self.workbook.get_current_sheet();
21            if self.selected_cell.0 > sheet.max_rows {
22                self.selected_cell.0 = sheet.max_rows.max(1);
23            }
24            if self.selected_cell.1 > sheet.max_cols {
25                self.selected_cell.1 = sheet.max_cols.max(1);
26            }
27
28            if self.undo_history.all_undone() {
29                self.workbook.set_modified(false);
30            } else {
31                self.workbook.set_modified(true);
32            }
33        } else {
34            self.add_notification("No operations to undo".to_string());
35        }
36        Ok(())
37    }
38
39    pub fn redo(&mut self) -> Result<()> {
40        if let Some(action) = self.undo_history.redo() {
41            self.apply_action(&action, false)?;
42
43            self.workbook.recalculate_max_rows();
44            self.workbook.recalculate_max_cols();
45            self.ensure_column_widths();
46
47            // Update cursor position if it's outside the valid range
48            let sheet = self.workbook.get_current_sheet();
49            if self.selected_cell.0 > sheet.max_rows {
50                self.selected_cell.0 = sheet.max_rows.max(1);
51            }
52            if self.selected_cell.1 > sheet.max_cols {
53                self.selected_cell.1 = sheet.max_cols.max(1);
54            }
55
56            self.workbook.set_modified(true);
57        } else {
58            self.add_notification("No operations to redo".to_string());
59        }
60        Ok(())
61    }
62
63    fn apply_action(&mut self, action: &Rc<ActionCommand>, is_undo: bool) -> Result<()> {
64        match action.as_ref() {
65            ActionCommand::Cell(cell_action) => {
66                let value = if is_undo {
67                    &cell_action.old_value
68                } else {
69                    &cell_action.new_value
70                };
71                self.apply_cell_action(cell_action, value, is_undo, &cell_action.action_type)?;
72            }
73            ActionCommand::Row(row_action) => {
74                self.apply_row_action(row_action, is_undo)?;
75            }
76            ActionCommand::Column(column_action) => {
77                self.apply_column_action(column_action, is_undo)?;
78            }
79            ActionCommand::Sheet(sheet_action) => {
80                self.apply_sheet_action(sheet_action, is_undo)?;
81            }
82            ActionCommand::MultiRow(multi_row_action) => {
83                self.apply_multi_row_action(multi_row_action, is_undo)?;
84            }
85            ActionCommand::MultiColumn(multi_column_action) => {
86                self.apply_multi_column_action(multi_column_action, is_undo)?;
87            }
88        }
89        Ok(())
90    }
91
92    fn apply_cell_action(
93        &mut self,
94        cell_action: &CellAction,
95        value: &crate::excel::Cell,
96        is_undo: bool,
97        action_type: &ActionType,
98    ) -> Result<()> {
99        let current_sheet_index = self.workbook.get_current_sheet_index();
100
101        if current_sheet_index != cell_action.sheet_index {
102            if let Err(e) = self.switch_sheet_by_index(cell_action.sheet_index) {
103                self.add_notification(format!(
104                    "Cannot switch to sheet {}: {}",
105                    cell_action.sheet_name, e
106                ));
107                return Ok(());
108            }
109        }
110
111        self.workbook.get_current_sheet_mut().data[cell_action.row][cell_action.col] =
112            value.clone();
113
114        self.selected_cell = (cell_action.row, cell_action.col);
115        self.handle_scrolling();
116
117        let cell_ref = format!(
118            "{}{}",
119            crate::utils::index_to_col_name(cell_action.col),
120            cell_action.row
121        );
122
123        let operation_text = match action_type {
124            ActionType::Edit => "edit",
125            ActionType::Cut => "cut",
126            ActionType::Paste => "paste",
127            _ => "cell operation",
128        };
129
130        if current_sheet_index != cell_action.sheet_index {
131            let action_word = if is_undo { "Undid" } else { "Redid" };
132            self.add_notification(format!(
133                "{} {} operation on cell {} in sheet {}",
134                action_word, operation_text, cell_ref, cell_action.sheet_name
135            ));
136        } else {
137            let action_word = if is_undo { "Undid" } else { "Redid" };
138            self.add_notification(format!(
139                "{} {} operation on cell {}",
140                action_word, operation_text, cell_ref
141            ));
142        }
143
144        Ok(())
145    }
146
147    fn apply_row_action(&mut self, row_action: &RowAction, is_undo: bool) -> Result<()> {
148        let current_sheet_index = self.workbook.get_current_sheet_index();
149
150        if current_sheet_index != row_action.sheet_index {
151            if let Err(e) = self.switch_sheet_by_index(row_action.sheet_index) {
152                self.add_notification(format!(
153                    "Cannot switch to sheet {}: {}",
154                    row_action.sheet_name, e
155                ));
156                return Ok(());
157            }
158        }
159
160        let sheet = self.workbook.get_current_sheet_mut();
161
162        if is_undo {
163            sheet
164                .data
165                .insert(row_action.row, row_action.row_data.clone());
166
167            sheet.max_rows = sheet.max_rows.saturating_add(1);
168
169            // Recalculate max_cols since restoring a row might affect the maximum column count
170            // This is especially important if the row contained data beyond the current max_cols
171            self.workbook.recalculate_max_cols();
172
173            self.add_notification(format!("Undid row {} deletion", row_action.row));
174        } else if row_action.row < sheet.data.len() {
175            sheet.data.remove(row_action.row);
176            sheet.max_rows = sheet.max_rows.saturating_sub(1);
177
178            if self.selected_cell.0 > sheet.max_rows {
179                self.selected_cell.0 = sheet.max_rows.max(1);
180            }
181
182            self.add_notification(format!("Redid row {} deletion", row_action.row));
183        }
184
185        self.handle_scrolling();
186        self.search_results.clear();
187        self.current_search_idx = None;
188
189        Ok(())
190    }
191
192    fn apply_column_action(&mut self, column_action: &ColumnAction, is_undo: bool) -> Result<()> {
193        let current_sheet_index = self.workbook.get_current_sheet_index();
194
195        if current_sheet_index != column_action.sheet_index {
196            if let Err(e) = self.switch_sheet_by_index(column_action.sheet_index) {
197                self.add_notification(format!(
198                    "Cannot switch to sheet {}: {}",
199                    column_action.sheet_name, e
200                ));
201                return Ok(());
202            }
203        }
204
205        let sheet = self.workbook.get_current_sheet_mut();
206        let col = column_action.col;
207
208        if is_undo {
209            let column_data = &column_action.column_data;
210
211            for (i, row) in sheet.data.iter_mut().enumerate() {
212                if i < column_data.len() {
213                    if col <= row.len() {
214                        row.insert(col, column_data[i].clone());
215                    } else {
216                        while row.len() < col {
217                            row.push(crate::excel::Cell::empty());
218                        }
219                        row.push(column_data[i].clone());
220                    }
221                }
222            }
223
224            // Update both max_cols and max_rows when restoring a column
225            sheet.max_cols = sheet.max_cols.saturating_add(1);
226
227            // Recalculate max_rows since restoring a column might affect the maximum row count
228            // This is especially important if the column contained data beyond the current max_rows
229            self.workbook.recalculate_max_rows();
230
231            if col < self.column_widths.len() {
232                self.column_widths.insert(col, column_action.column_width);
233                if !self.column_widths.is_empty() {
234                    self.column_widths.pop();
235                }
236            } else {
237                while self.column_widths.len() < col {
238                    self.column_widths.push(15); // Default width
239                }
240                self.column_widths.push(column_action.column_width);
241            }
242
243            self.ensure_column_visible(col);
244            self.add_notification(format!("Undid column {} deletion", index_to_col_name(col)));
245        } else {
246            for row in sheet.data.iter_mut() {
247                if col < row.len() {
248                    row.remove(col);
249                }
250            }
251
252            sheet.max_cols = sheet.max_cols.saturating_sub(1);
253
254            if self.column_widths.len() > col {
255                self.column_widths.remove(col);
256                self.column_widths.push(15);
257            }
258
259            if self.selected_cell.1 > sheet.max_cols {
260                self.selected_cell.1 = sheet.max_cols.max(1);
261            }
262
263            self.add_notification(format!("Redid column {} deletion", index_to_col_name(col)));
264        }
265
266        self.handle_scrolling();
267        self.search_results.clear();
268        self.current_search_idx = None;
269
270        Ok(())
271    }
272
273    fn apply_sheet_action(&mut self, sheet_action: &SheetAction, is_undo: bool) -> Result<()> {
274        if is_undo {
275            let sheet_index = sheet_action.sheet_index;
276
277            if let Err(e) = self
278                .workbook
279                .insert_sheet_at_index(sheet_action.sheet_data.clone(), sheet_index)
280            {
281                self.add_notification(format!(
282                    "Failed to restore sheet {}: {}",
283                    sheet_action.sheet_name, e
284                ));
285                return Ok(());
286            }
287
288            self.sheet_column_widths.insert(
289                sheet_action.sheet_name.clone(),
290                sheet_action.column_widths.clone(),
291            );
292
293            if let Err(e) = self.switch_sheet_by_index(sheet_index) {
294                self.add_notification(format!(
295                    "Restored sheet {} but couldn't switch to it: {}",
296                    sheet_action.sheet_name, e
297                ));
298            } else {
299                self.add_notification(format!("Undid sheet {} deletion", sheet_action.sheet_name));
300            }
301        } else {
302            if let Err(e) = self.switch_sheet_by_index(sheet_action.sheet_index) {
303                self.add_notification(format!(
304                    "Cannot switch to sheet {} to delete it: {}",
305                    sheet_action.sheet_name, e
306                ));
307                return Ok(());
308            }
309
310            if let Err(e) = self.workbook.delete_current_sheet() {
311                self.add_notification(format!("Failed to delete sheet: {}", e));
312                return Ok(());
313            }
314
315            self.cleanup_after_sheet_deletion(&sheet_action.sheet_name);
316            self.add_notification(format!(
317                "Redid deletion of sheet {}",
318                sheet_action.sheet_name
319            ));
320        }
321
322        Ok(())
323    }
324
325    fn cleanup_after_sheet_deletion(&mut self, sheet_name: &str) {
326        self.sheet_column_widths.remove(sheet_name);
327
328        self.selected_cell = (1, 1);
329        self.start_row = 1;
330        self.start_col = 1;
331
332        let new_sheet_name = self.workbook.get_current_sheet_name();
333
334        if let Some(saved_widths) = self.sheet_column_widths.get(&new_sheet_name) {
335            self.column_widths = saved_widths.clone();
336        } else {
337            let max_cols = self.workbook.get_current_sheet().max_cols;
338            let default_width = 15;
339            self.column_widths = vec![default_width; max_cols + 1];
340
341            self.sheet_column_widths
342                .insert(new_sheet_name.clone(), self.column_widths.clone());
343        }
344
345        self.search_results.clear();
346        self.current_search_idx = None;
347    }
348
349    fn apply_multi_row_action(
350        &mut self,
351        multi_row_action: &MultiRowAction,
352        is_undo: bool,
353    ) -> Result<()> {
354        let current_sheet_index = self.workbook.get_current_sheet_index();
355
356        if current_sheet_index != multi_row_action.sheet_index {
357            if let Err(e) = self.switch_sheet_by_index(multi_row_action.sheet_index) {
358                self.add_notification(format!(
359                    "Cannot switch to sheet {}: {}",
360                    multi_row_action.sheet_name, e
361                ));
362                return Ok(());
363            }
364        }
365
366        let start_row = multi_row_action.start_row;
367        let end_row = multi_row_action.end_row;
368        let rows_to_restore = end_row - start_row + 1;
369
370        if is_undo {
371            let rows_data = &multi_row_action.rows_data;
372            let sheet = self.workbook.get_current_sheet_mut();
373
374            // Optimized restore function
375            Self::restore_rows(sheet, start_row, rows_data);
376
377            sheet.max_rows = sheet.max_rows.saturating_add(rows_to_restore);
378
379            // Recalculate max_cols since restoring rows might affect the maximum column count
380            self.workbook.recalculate_max_cols();
381
382            self.add_notification(format!("Undid rows {} to {} deletion", start_row, end_row));
383        } else {
384            self.workbook.delete_rows(start_row, end_row)?;
385
386            let sheet = self.workbook.get_current_sheet();
387
388            if self.selected_cell.0 > sheet.max_rows {
389                self.selected_cell.0 = sheet.max_rows.max(1);
390            }
391
392            self.add_notification(format!("Redid rows {} to {} deletion", start_row, end_row));
393        }
394
395        self.handle_scrolling();
396        self.search_results.clear();
397        self.current_search_idx = None;
398
399        Ok(())
400    }
401
402    fn apply_multi_column_action(
403        &mut self,
404        multi_column_action: &MultiColumnAction,
405        is_undo: bool,
406    ) -> Result<()> {
407        let current_sheet_index = self.workbook.get_current_sheet_index();
408
409        if current_sheet_index != multi_column_action.sheet_index {
410            if let Err(e) = self.switch_sheet_by_index(multi_column_action.sheet_index) {
411                self.add_notification(format!(
412                    "Cannot switch to sheet {}: {}",
413                    multi_column_action.sheet_name, e
414                ));
415                return Ok(());
416            }
417        }
418
419        let start_col = multi_column_action.start_col;
420        let end_col = multi_column_action.end_col;
421        let cols_to_restore = end_col - start_col + 1;
422
423        if is_undo {
424            let columns_data = &multi_column_action.columns_data;
425            let column_widths = &multi_column_action.column_widths;
426
427            let sheet = self.workbook.get_current_sheet_mut();
428
429            for col_idx in (0..cols_to_restore).rev() {
430                if col_idx < columns_data.len() {
431                    let column_data = &columns_data[col_idx];
432                    Self::restore_column_at_position(sheet, start_col, column_data);
433
434                    Self::restore_column_width(
435                        &mut self.column_widths,
436                        start_col,
437                        col_idx,
438                        column_widths,
439                    );
440                }
441            }
442
443            sheet.max_cols = sheet.max_cols.saturating_add(cols_to_restore);
444
445            // Recalculate max_rows since restoring columns might affect the maximum row count
446            self.workbook.recalculate_max_rows();
447
448            Self::trim_column_widths(&mut self.column_widths, cols_to_restore);
449            self.ensure_column_visible(start_col);
450
451            self.add_notification(format!(
452                "Undid columns {} to {} deletion",
453                index_to_col_name(start_col),
454                index_to_col_name(end_col)
455            ));
456        } else {
457            self.workbook.delete_columns(start_col, end_col)?;
458
459            let sheet = self.workbook.get_current_sheet();
460            Self::remove_column_widths(&mut self.column_widths, start_col, end_col);
461
462            if self.selected_cell.1 > sheet.max_cols {
463                self.selected_cell.1 = sheet.max_cols.max(1);
464            }
465
466            self.add_notification(format!(
467                "Redid columns {} to {} deletion",
468                index_to_col_name(start_col),
469                index_to_col_name(end_col)
470            ));
471        }
472
473        self.handle_scrolling();
474        self.search_results.clear();
475        self.current_search_idx = None;
476
477        Ok(())
478    }
479
480    fn restore_rows(
481        sheet: &mut crate::excel::Sheet,
482        position: usize,
483        rows_data: &[Vec<crate::excel::Cell>],
484    ) {
485        // Pre-allocate space by extending the vector
486        for row_data in rows_data.iter().rev() {
487            sheet.data.insert(position, row_data.clone());
488        }
489    }
490
491    fn restore_column_at_position(
492        sheet: &mut crate::excel::Sheet,
493        position: usize,
494        column_data: &[crate::excel::Cell],
495    ) {
496        for (i, row) in sheet.data.iter_mut().enumerate() {
497            if i < column_data.len() {
498                if position <= row.len() {
499                    row.insert(position, column_data[i].clone());
500                } else {
501                    let additional = position - row.len();
502                    row.reserve(additional + 1);
503                    while row.len() < position {
504                        row.push(crate::excel::Cell::empty());
505                    }
506                    row.push(column_data[i].clone());
507                }
508            }
509        }
510    }
511
512    fn restore_column_width(
513        column_widths: &mut Vec<usize>,
514        position: usize,
515        col_idx: usize,
516        width_values: &[usize],
517    ) {
518        if position < column_widths.len() {
519            let width = if col_idx < width_values.len() {
520                width_values[col_idx]
521            } else {
522                15 // Default width
523            };
524            column_widths.insert(position, width);
525        }
526    }
527
528    fn trim_column_widths(column_widths: &mut Vec<usize>, count: usize) {
529        if count >= column_widths.len() {
530            return;
531        }
532        column_widths.truncate(column_widths.len() - count);
533    }
534
535    fn remove_column_widths(column_widths: &mut Vec<usize>, start_col: usize, end_col: usize) {
536        let cols_to_remove = end_col - start_col + 1;
537
538        // Pre-allocate space for new entries to avoid multiple resizes
539        column_widths.reserve(cols_to_remove);
540
541        for col in (start_col..=end_col).rev() {
542            if column_widths.len() > col {
543                column_widths.remove(col);
544            }
545        }
546
547        // Add default widths in a single batch to avoid multiple resizes
548        let mut defaults = vec![15; cols_to_remove];
549        column_widths.append(&mut defaults);
550    }
551}
552
553impl ActionExecutor for AppState<'_> {
554    fn execute_action(&mut self, action: &ActionCommand) -> Result<()> {
555        match action {
556            ActionCommand::Cell(action) => self.execute_cell_action(action),
557            ActionCommand::Row(action) => self.execute_row_action(action),
558            ActionCommand::Column(action) => self.execute_column_action(action),
559            ActionCommand::Sheet(action) => self.execute_sheet_action(action),
560            ActionCommand::MultiRow(action) => self.execute_multi_row_action(action),
561            ActionCommand::MultiColumn(action) => self.execute_multi_column_action(action),
562        }
563    }
564
565    fn execute_cell_action(&mut self, action: &CellAction) -> Result<()> {
566        self.workbook
567            .set_cell_value(action.row, action.col, action.new_value.value.clone())
568    }
569
570    fn execute_row_action(&mut self, action: &RowAction) -> Result<()> {
571        self.workbook.delete_row(action.row)
572    }
573
574    fn execute_column_action(&mut self, action: &ColumnAction) -> Result<()> {
575        self.workbook.delete_column(action.col)
576    }
577
578    fn execute_sheet_action(&mut self, action: &SheetAction) -> Result<()> {
579        self.switch_sheet_by_index(action.sheet_index)?;
580        self.workbook.delete_current_sheet()
581    }
582
583    fn execute_multi_row_action(&mut self, action: &MultiRowAction) -> Result<()> {
584        self.workbook.delete_rows(action.start_row, action.end_row)
585    }
586
587    fn execute_multi_column_action(&mut self, action: &MultiColumnAction) -> Result<()> {
588        self.workbook
589            .delete_columns(action.start_col, action.end_col)
590    }
591}