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            // Initialize cell position for the restored sheet with default values
294            self.sheet_cell_positions.insert(
295                sheet_action.sheet_name.clone(),
296                crate::app::CellPosition {
297                    selected: (1, 1),
298                    view: (1, 1),
299                },
300            );
301
302            if let Err(e) = self.switch_sheet_by_index(sheet_index) {
303                self.add_notification(format!(
304                    "Restored sheet {} but couldn't switch to it: {}",
305                    sheet_action.sheet_name, e
306                ));
307            } else {
308                self.add_notification(format!("Undid sheet {} deletion", sheet_action.sheet_name));
309            }
310        } else {
311            if let Err(e) = self.switch_sheet_by_index(sheet_action.sheet_index) {
312                self.add_notification(format!(
313                    "Cannot switch to sheet {} to delete it: {}",
314                    sheet_action.sheet_name, e
315                ));
316                return Ok(());
317            }
318
319            if let Err(e) = self.workbook.delete_current_sheet() {
320                self.add_notification(format!("Failed to delete sheet: {e}"));
321                return Ok(());
322            }
323
324            self.cleanup_after_sheet_deletion(&sheet_action.sheet_name);
325            self.add_notification(format!(
326                "Redid deletion of sheet {}",
327                sheet_action.sheet_name
328            ));
329        }
330
331        Ok(())
332    }
333
334    fn cleanup_after_sheet_deletion(&mut self, sheet_name: &str) {
335        self.sheet_column_widths.remove(sheet_name);
336        self.sheet_cell_positions.remove(sheet_name);
337
338        let new_sheet_name = self.workbook.get_current_sheet_name();
339
340        // Restore saved cell position for the new current sheet or use default
341        if let Some(saved_position) = self.sheet_cell_positions.get(&new_sheet_name) {
342            // Ensure the saved position is valid for the current sheet
343            let sheet = self.workbook.get_current_sheet();
344            let valid_row = saved_position.selected.0.min(sheet.max_rows.max(1));
345            let valid_col = saved_position.selected.1.min(sheet.max_cols.max(1));
346
347            self.selected_cell = (valid_row, valid_col);
348            self.start_row = saved_position.view.0;
349            self.start_col = saved_position.view.1;
350
351            // Make sure the view position is valid relative to the selected cell
352            self.handle_scrolling();
353        } else {
354            // If no saved position exists, use default position
355            self.selected_cell = (1, 1);
356            self.start_row = 1;
357            self.start_col = 1;
358        }
359
360        if let Some(saved_widths) = self.sheet_column_widths.get(&new_sheet_name) {
361            self.column_widths = saved_widths.clone();
362        } else {
363            let max_cols = self.workbook.get_current_sheet().max_cols;
364            let default_width = 15;
365            self.column_widths = vec![default_width; max_cols + 1];
366
367            self.sheet_column_widths
368                .insert(new_sheet_name.clone(), self.column_widths.clone());
369        }
370
371        self.search_results.clear();
372        self.current_search_idx = None;
373    }
374
375    fn apply_multi_row_action(
376        &mut self,
377        multi_row_action: &MultiRowAction,
378        is_undo: bool,
379    ) -> Result<()> {
380        let current_sheet_index = self.workbook.get_current_sheet_index();
381
382        if current_sheet_index != multi_row_action.sheet_index {
383            if let Err(e) = self.switch_sheet_by_index(multi_row_action.sheet_index) {
384                self.add_notification(format!(
385                    "Cannot switch to sheet {}: {}",
386                    multi_row_action.sheet_name, e
387                ));
388                return Ok(());
389            }
390        }
391
392        let start_row = multi_row_action.start_row;
393        let end_row = multi_row_action.end_row;
394        let rows_to_restore = end_row - start_row + 1;
395
396        if is_undo {
397            let rows_data = &multi_row_action.rows_data;
398            let sheet = self.workbook.get_current_sheet_mut();
399
400            // Optimized restore function
401            Self::restore_rows(sheet, start_row, rows_data);
402
403            sheet.max_rows = sheet.max_rows.saturating_add(rows_to_restore);
404
405            // Recalculate max_cols since restoring rows might affect the maximum column count
406            self.workbook.recalculate_max_cols();
407
408            self.add_notification(format!("Undid rows {} to {} deletion", start_row, end_row));
409        } else {
410            self.workbook.delete_rows(start_row, end_row)?;
411
412            let sheet = self.workbook.get_current_sheet();
413
414            if self.selected_cell.0 > sheet.max_rows {
415                self.selected_cell.0 = sheet.max_rows.max(1);
416            }
417
418            self.add_notification(format!("Redid rows {} to {} deletion", start_row, end_row));
419        }
420
421        self.handle_scrolling();
422        self.search_results.clear();
423        self.current_search_idx = None;
424
425        Ok(())
426    }
427
428    fn apply_multi_column_action(
429        &mut self,
430        multi_column_action: &MultiColumnAction,
431        is_undo: bool,
432    ) -> Result<()> {
433        let current_sheet_index = self.workbook.get_current_sheet_index();
434
435        if current_sheet_index != multi_column_action.sheet_index {
436            if let Err(e) = self.switch_sheet_by_index(multi_column_action.sheet_index) {
437                self.add_notification(format!(
438                    "Cannot switch to sheet {}: {}",
439                    multi_column_action.sheet_name, e
440                ));
441                return Ok(());
442            }
443        }
444
445        let start_col = multi_column_action.start_col;
446        let end_col = multi_column_action.end_col;
447        let cols_to_restore = end_col - start_col + 1;
448
449        if is_undo {
450            let columns_data = &multi_column_action.columns_data;
451            let column_widths = &multi_column_action.column_widths;
452
453            let sheet = self.workbook.get_current_sheet_mut();
454
455            for col_idx in (0..cols_to_restore).rev() {
456                if col_idx < columns_data.len() {
457                    let column_data = &columns_data[col_idx];
458                    Self::restore_column_at_position(sheet, start_col, column_data);
459
460                    Self::restore_column_width(
461                        &mut self.column_widths,
462                        start_col,
463                        col_idx,
464                        column_widths,
465                    );
466                }
467            }
468
469            sheet.max_cols = sheet.max_cols.saturating_add(cols_to_restore);
470
471            // Recalculate max_rows since restoring columns might affect the maximum row count
472            self.workbook.recalculate_max_rows();
473
474            Self::trim_column_widths(&mut self.column_widths, cols_to_restore);
475            self.ensure_column_visible(start_col);
476
477            self.add_notification(format!(
478                "Undid columns {} to {} deletion",
479                index_to_col_name(start_col),
480                index_to_col_name(end_col)
481            ));
482        } else {
483            self.workbook.delete_columns(start_col, end_col)?;
484
485            let sheet = self.workbook.get_current_sheet();
486            Self::remove_column_widths(&mut self.column_widths, start_col, end_col);
487
488            if self.selected_cell.1 > sheet.max_cols {
489                self.selected_cell.1 = sheet.max_cols.max(1);
490            }
491
492            self.add_notification(format!(
493                "Redid columns {} to {} deletion",
494                index_to_col_name(start_col),
495                index_to_col_name(end_col)
496            ));
497        }
498
499        self.handle_scrolling();
500        self.search_results.clear();
501        self.current_search_idx = None;
502
503        Ok(())
504    }
505
506    fn restore_rows(
507        sheet: &mut crate::excel::Sheet,
508        position: usize,
509        rows_data: &[Vec<crate::excel::Cell>],
510    ) {
511        // Pre-allocate space by extending the vector
512        for row_data in rows_data.iter().rev() {
513            sheet.data.insert(position, row_data.clone());
514        }
515    }
516
517    fn restore_column_at_position(
518        sheet: &mut crate::excel::Sheet,
519        position: usize,
520        column_data: &[crate::excel::Cell],
521    ) {
522        for (i, row) in sheet.data.iter_mut().enumerate() {
523            if i < column_data.len() {
524                if position <= row.len() {
525                    row.insert(position, column_data[i].clone());
526                } else {
527                    let additional = position - row.len();
528                    row.reserve(additional + 1);
529                    while row.len() < position {
530                        row.push(crate::excel::Cell::empty());
531                    }
532                    row.push(column_data[i].clone());
533                }
534            }
535        }
536    }
537
538    fn restore_column_width(
539        column_widths: &mut Vec<usize>,
540        position: usize,
541        col_idx: usize,
542        width_values: &[usize],
543    ) {
544        if position < column_widths.len() {
545            let width = if col_idx < width_values.len() {
546                width_values[col_idx]
547            } else {
548                15 // Default width
549            };
550            column_widths.insert(position, width);
551        }
552    }
553
554    fn trim_column_widths(column_widths: &mut Vec<usize>, count: usize) {
555        if count >= column_widths.len() {
556            return;
557        }
558        column_widths.truncate(column_widths.len() - count);
559    }
560
561    fn remove_column_widths(column_widths: &mut Vec<usize>, start_col: usize, end_col: usize) {
562        let cols_to_remove = end_col - start_col + 1;
563
564        // Pre-allocate space for new entries to avoid multiple resizes
565        column_widths.reserve(cols_to_remove);
566
567        for col in (start_col..=end_col).rev() {
568            if column_widths.len() > col {
569                column_widths.remove(col);
570            }
571        }
572
573        // Add default widths in a single batch to avoid multiple resizes
574        let mut defaults = vec![15; cols_to_remove];
575        column_widths.append(&mut defaults);
576    }
577}
578
579impl ActionExecutor for AppState<'_> {
580    fn execute_action(&mut self, action: &ActionCommand) -> Result<()> {
581        match action {
582            ActionCommand::Cell(action) => self.execute_cell_action(action),
583            ActionCommand::Row(action) => self.execute_row_action(action),
584            ActionCommand::Column(action) => self.execute_column_action(action),
585            ActionCommand::Sheet(action) => self.execute_sheet_action(action),
586            ActionCommand::MultiRow(action) => self.execute_multi_row_action(action),
587            ActionCommand::MultiColumn(action) => self.execute_multi_column_action(action),
588        }
589    }
590
591    fn execute_cell_action(&mut self, action: &CellAction) -> Result<()> {
592        self.workbook
593            .set_cell_value(action.row, action.col, action.new_value.value.clone())
594    }
595
596    fn execute_row_action(&mut self, action: &RowAction) -> Result<()> {
597        self.workbook.delete_row(action.row)
598    }
599
600    fn execute_column_action(&mut self, action: &ColumnAction) -> Result<()> {
601        self.workbook.delete_column(action.col)
602    }
603
604    fn execute_sheet_action(&mut self, action: &SheetAction) -> Result<()> {
605        self.switch_sheet_by_index(action.sheet_index)?;
606        self.workbook.delete_current_sheet()
607    }
608
609    fn execute_multi_row_action(&mut self, action: &MultiRowAction) -> Result<()> {
610        self.workbook.delete_rows(action.start_row, action.end_row)
611    }
612
613    fn execute_multi_column_action(&mut self, action: &MultiColumnAction) -> Result<()> {
614        self.workbook
615            .delete_columns(action.start_col, action.end_col)
616    }
617}