Guide API
Skip to main content

tvision_rs/widgets/table/
edit.rs

1//! Cell editing: the cell cursor's columns and an [`InputLine`] editor laid
2//! over one cell.
3//!
4//! The editor is a third child of the table's group, inserted on top of the
5//! rows and made current while it is open, so the keys reach it the normal
6//! way. Enter or F2 on the cell cursor opens it. The table takes the keys
7//! that end an edit before the group routes them: Enter commits (and is used
8//! up, the cursor stays on the cell), Esc cancels, Tab/Shift-Tab commit and
9//! open the next/previous editable cell of the row.
10//!
11//! The editor belongs to a row key and a model column, not to a screen
12//! position: every draw lays it over that cell again, so it follows a
13//! re-sort, a horizontal scroll, a column resize or move, a reload and a table
14//! resize (a resize also scrolls the cell into view). A cell scrolled off
15//! screen hides the editor but keeps the edit: the next key scrolls the cell
16//! back into view and goes to the editor. A cell that is gone ends the edit
17//! without storing it — at once when a reload removed its row, at the
18//! table's next event when its column was hidden — and the next key is used
19//! up, so it cannot turn into a dialog action.
20
21use super::body::{TEXT_X, row_layout};
22use super::layout::RowLayout;
23use super::model::RowKey;
24use super::{Table, TableData};
25use crate::command::Command;
26use crate::data::FieldValue;
27use crate::dialog::{MessageBoxButtons, MessageBoxKind};
28use crate::event::{Event, Key, KeyEvent};
29use crate::view::{Context, Point, Rect, SelectMode, View, ViewId};
30use crate::widgets::input_line::{InputLine, LimitMode};
31use crate::widgets::list_viewer;
32
33/// The byte limit of a cell editor (one less is the longest text; a longer
34/// cell text raises it for that editor).
35const EDIT_LIMIT: i32 = 4096;
36
37/// An open cell editor.
38pub(super) struct CellEdit {
39    /// The editor's id in the table's group.
40    pub(super) editor: ViewId,
41    /// The edited row.
42    pub(super) key: RowKey,
43    /// The edited model column.
44    pub(super) col: usize,
45    /// An error box about this edit is (or may be) on screen: the focus loss
46    /// it causes does not cancel the edit. Cleared by the next focus gain,
47    /// key or click.
48    box_open: bool,
49    /// Dropped without a [`Context`] (a programmatic focus move): hidden, and
50    /// closed at the next event, which goes on as if there were no editor.
51    dropped: bool,
52}
53
54impl TableData {
55    /// The visible, editable model columns in display order: the stops of
56    /// the cell cursor.
57    pub(super) fn editable_cols(&self) -> Vec<usize> {
58        self.col_order
59            .iter()
60            .copied()
61            .filter(|&c| self.columns[c].editable && !self.columns[c].hidden)
62            .collect()
63    }
64
65    /// The model column under the cell cursor: the remembered one while it is
66    /// still visible and editable, else the first editable column. `None`
67    /// when no visible column is editable (there is no cursor).
68    pub(super) fn cursor_col(&self) -> Option<usize> {
69        let cols = self.editable_cols();
70        self.cursor
71            .filter(|c| cols.contains(c))
72            .or_else(|| cols.first().copied())
73    }
74
75    /// Model column `col`'s cells in `l`: `[start, end)` in content cells,
76    /// `None` when it takes no cells.
77    pub(super) fn col_span(&self, l: &RowLayout, col: usize) -> Option<(i32, i32)> {
78        let lc = self.display_pos(col)? + l.frozen;
79        l.spans()
80            .into_iter()
81            .find(|&(i, _, _)| i == lc)
82            .map(|(_, s, e)| (s, e))
83    }
84
85    /// Scroll the columns of a view `size_x` wide so model column `col` is
86    /// in view (its start, when it is wider than the view). Returns whether
87    /// the offset changed.
88    pub(super) fn reveal_col(&mut self, size_x: i32, col: usize) -> bool {
89        let l = row_layout(self, size_x);
90        let Some((s, e)) = self.col_span(&l, col) else {
91            return false;
92        };
93        let old = l.clamp(self.h_offset);
94        let off = if s < old {
95            s
96        } else if e > old.saturating_add(l.view) {
97            (e - l.view).min(s)
98        } else {
99            old
100        };
101        self.h_offset = l.clamp(off);
102        self.h_offset != old
103    }
104}
105
106/// The table-local x range `[x0, x1)` model column `col`'s cells cover on
107/// screen, clipped to the scrolling part of a view `size_x` wide; `None`
108/// when no cell of it is on screen.
109pub(super) fn cell_x(d: &TableData, l: &RowLayout, size_x: i32, col: usize) -> Option<(i32, i32)> {
110    let (s, e) = d.col_span(l, col)?;
111    let lo = TEXT_X + l.frozen_width;
112    let x0 = (TEXT_X + l.text_x(s, d.h_offset)).max(lo);
113    let x1 = (TEXT_X + l.text_x(e, d.h_offset)).min(size_x);
114    (x0 < x1).then_some((x0, x1))
115}
116
117/// The editor bounds over model column `col` of display row `disp`, in a
118/// table of `size` whose rows start at `top_item`: the cell plus the cell on
119/// either side (the input line draws its text from its second cell and its
120/// scroll arrows on the outer ones), clipped to the scrolling part. `None`
121/// when the cell is not on screen.
122fn editor_rect(d: &TableData, size: Point, top_item: i32, disp: usize, col: usize) -> Option<Rect> {
123    let y = 1 + disp as i32 - top_item;
124    if y < 1 || y >= size.y {
125        return None;
126    }
127    let l = row_layout(d, size.x);
128    let (x0, x1) = cell_x(d, &l, size.x, col)?;
129    let lo = TEXT_X + l.frozen_width - 1;
130    Some(Rect::new((x0 - 1).max(lo), y, (x1 + 1).min(size.x), y + 1))
131}
132
133impl Table {
134    /// Whether a cell editor is open.
135    pub fn is_editing(&self) -> bool {
136        self.edit.is_some()
137    }
138
139    /// The model column under the cell cursor, `None` when no visible column
140    /// is [`editable`](super::ColumnSpec::editable).
141    pub fn cursor_column(&self) -> Option<usize> {
142        self.data.borrow().cursor_col()
143    }
144
145    /// The open editor.
146    pub(super) fn editor_mut(&mut self) -> Option<&mut InputLine> {
147        let id = self.edit.as_ref()?.editor;
148        self.group
149            .child_mut(id)
150            .and_then(|v| v.as_any_mut())
151            .and_then(|a| a.downcast_mut::<InputLine>())
152    }
153
154    /// Lay the editor over its cell, scrolling the cell into view first when
155    /// `reveal` (columns and rows; the bars catch up on the next publish).
156    /// An editor whose cell is not on screen is hidden. Returns whether it
157    /// is on screen.
158    pub(super) fn place_editor(&mut self, reveal: bool) -> bool {
159        let Some(e) = &self.edit else {
160            return false;
161        };
162        let (editor, key, col) = (e.editor, e.key.clone(), e.col);
163        let size = self.group.state().size;
164        let disp = if e.dropped {
165            None
166        } else {
167            self.data.borrow().display_of(&key)
168        };
169        if let Some(disp) = disp
170            && reveal
171        {
172            self.data.borrow_mut().reveal_col(size.x, col);
173            let lv = self.body_mut().lv_state();
174            let (row, rows) = (disp as i32, lv.state.size.y);
175            if row < lv.top_item {
176                lv.top_item = row;
177            } else if rows > 0 && row >= lv.top_item + rows {
178                lv.top_item = row - rows + 1;
179            }
180        }
181        let top = self.body_mut().lv_state().top_item;
182        let rect = disp.and_then(|disp| editor_rect(&self.data.borrow(), size, top, disp, col));
183        if let Some(v) = self.group.child_mut(editor) {
184            if let Some(r) = rect {
185                v.change_bounds(r);
186            }
187            v.state_mut().state.visible = rect.is_some();
188        }
189        rect.is_some()
190    }
191
192    /// Open an editor on model column `col` of the focused row, pre-filled
193    /// with the cell text, all selected. Returns whether it opened (there is
194    /// a row and the cell can be shown).
195    fn start_edit(&mut self, col: usize, ctx: &mut Context) -> bool {
196        let Some(key) = self.focused_key() else {
197            return false;
198        };
199        let (text, factory) = {
200            let mut d = self.data.borrow_mut();
201            d.cursor = Some(col);
202            let row = d.order[d.focused];
203            (
204                d.model.cell(row, col).into_owned(),
205                d.columns[col].validator.clone(),
206            )
207        };
208        let limit = EDIT_LIMIT.max(i32::try_from(text.len()).unwrap_or(i32::MAX - 1) + 1);
209        let editor = InputLine::new(
210            Rect::new(0, 0, 0, 0),
211            limit,
212            factory.map(|f| f.make()),
213            LimitMode::MaxBytes,
214        );
215        let id = self.group.insert(Box::new(editor));
216        self.edit = Some(CellEdit {
217            editor: id,
218            key,
219            col,
220            box_open: false,
221            dropped: false,
222        });
223        if !self.place_editor(true) {
224            self.close_editor(ctx);
225            return false;
226        }
227        // Loaded once placed: the input line scrolls the text to its width.
228        if let Some(editor) = self.editor_mut() {
229            editor.set_value(FieldValue::Text(text));
230        }
231        self.publish_h(ctx);
232        self.group.set_current(Some(id), SelectMode::Normal, ctx);
233        true
234    }
235
236    /// Remove the editor; the row body is current again.
237    fn close_editor(&mut self, ctx: &mut Context) {
238        if let Some(e) = self.edit.take() {
239            self.group.remove(e.editor, ctx);
240        }
241    }
242
243    /// Close the editor without storing its text.
244    pub fn cancel_edit(&mut self, ctx: &mut Context) {
245        self.close_editor(ctx);
246    }
247
248    /// Whether the edited cell still exists: the edit was not dropped, its
249    /// row is in the model and its column is visible and editable.
250    pub(super) fn edit_alive(&self) -> bool {
251        let Some(e) = &self.edit else {
252            return false;
253        };
254        let d = self.data.borrow();
255        !e.dropped
256            && d.display_of(&e.key).is_some()
257            && d.columns
258                .get(e.col)
259                .is_some_and(|c| c.editable && !c.hidden)
260    }
261
262    /// Drop the edit without a [`Context`] when focus moves to another row
263    /// than `key`'s: the editor hides and the next event closes it.
264    pub(super) fn drop_edit_unless(&mut self, key: &RowKey) {
265        if let Some(e) = &mut self.edit
266            && e.key != *key
267        {
268            e.dropped = true;
269        }
270    }
271
272    /// Cancel the edit when focus moves to another row than `key`'s, so the
273    /// editor and the focused row never disagree.
274    pub(super) fn cancel_edit_unless(&mut self, key: &RowKey, ctx: &mut Context) {
275        if self.edit.as_ref().is_some_and(|e| e.key != *key) {
276            self.cancel_edit(ctx);
277        }
278    }
279
280    /// Close an edit that is no longer alive. Unless the app dropped it, its
281    /// cell vanished under the user, so the next key (which was meant for the
282    /// editor) is used up rather than reaching the dialog.
283    pub(super) fn end_dead_edit(&mut self, ctx: &mut Context) {
284        let dropped = self.edit.as_ref().is_some_and(|e| e.dropped);
285        self.cancel_edit(ctx);
286        self.eat_key = !dropped;
287    }
288
289    /// Close an edit the app dropped before the table routes an event, so
290    /// the event goes on as if there were no editor (an Enter opens the
291    /// cursor cell's editor).
292    pub(super) fn close_dropped_edit(&mut self, ctx: &mut Context) {
293        if self.edit.as_ref().is_some_and(|e| e.dropped) {
294            self.end_dead_edit(ctx);
295        }
296    }
297
298    /// Scroll the edited cell back into view (columns and rows), publishing
299    /// the bars, and lay the editor over it. Returns whether it is on screen.
300    fn reveal_editor(&mut self, ctx: &mut Context) -> bool {
301        let Some(e) = &self.edit else {
302            return false;
303        };
304        let (key, col) = (e.key.clone(), e.col);
305        let size_x = self.group.state().size.x;
306        let disp = {
307            let mut d = self.data.borrow_mut();
308            d.reveal_col(size_x, col);
309            d.display_of(&key)
310        };
311        if let Some(disp) = disp {
312            // The edited row is the focused one: focusing it again scrolls it
313            // into view and moves the vertical bar.
314            list_viewer::focus_item_num(self.body_mut(), disp as i32, ctx);
315        }
316        self.publish_h(ctx);
317        self.place_editor(false)
318    }
319
320    /// The dialog's [`valid`](View::valid) check with an editor open:
321    /// [`Command::CANCEL`] cancels the edit; any other end command commits
322    /// it, and a refusal (its box is up) vetoes the command, like a field
323    /// whose validator refuses. The status check
324    /// ([`Command::VALID`]) and a focus release leave the edit alone.
325    pub(super) fn edit_valid(&mut self, cmd: Command, ctx: &mut Context) -> bool {
326        if self.edit.is_none() || cmd == Command::VALID || cmd == Command::RELEASED_FOCUS {
327            return true;
328        }
329        if !self.edit_alive() {
330            // Dropped, or its cell is gone: discarded, never stored.
331            self.cancel_edit(ctx);
332            return true;
333        }
334        if cmd == Command::CANCEL {
335            self.cancel_edit(ctx);
336            return true;
337        }
338        let closed = self.commit_edit(ctx);
339        self.drain(ctx);
340        closed
341    }
342
343    /// Store the editor's text: the column's validator must accept it, then
344    /// the model's [`set_cell`](super::TableModel::set_cell). A refusal shows
345    /// its message box and keeps the editor open. On success the sort is
346    /// re-applied, focus follows the row's key and
347    /// [`Command::TABLE_CELL_EDITED`] is queued; an unchanged text just
348    /// closes the editor. Returns whether the editor closed.
349    pub(super) fn commit_edit(&mut self, ctx: &mut Context) -> bool {
350        let Some(e) = &self.edit else {
351            return false;
352        };
353        let (key, col) = (e.key.clone(), e.col);
354        let Some(editor) = self.editor_mut() else {
355            self.close_editor(ctx);
356            return true;
357        };
358        let boxes = ctx.message_boxes_requested();
359        if !editor.valid(Command::OK, ctx) {
360            // The validator re-focused the editor; it may have popped an
361            // error box (the base validator shows none).
362            if ctx.message_boxes_requested() > boxes {
363                self.box_opened();
364            }
365            return false;
366        }
367        let text = editor.data.clone();
368        let stored = {
369            let mut d = self.data.borrow_mut();
370            match d.display_of(&key).map(|disp| d.order[disp]) {
371                Some(row) if d.model.cell(row, col) != text => Some(
372                    d.model
373                        .set_cell(row, col, &text)
374                        .map(|()| d.model.row_key(row)),
375                ),
376                // Unchanged, or the row is gone: nothing to store.
377                _ => None,
378            }
379        };
380        match stored {
381            Some(Err(message)) => {
382                ctx.request_message_box(
383                    message,
384                    MessageBoxKind::Error,
385                    MessageBoxButtons::ok(),
386                    None,
387                    None,
388                );
389                self.box_opened();
390                false
391            }
392            Some(Ok(new_key)) => {
393                self.close_editor(ctx);
394                // The edit may move the row (sort) or even re-key it (a
395                // model keyed by a cell).
396                let idx = {
397                    let mut d = self.data.borrow_mut();
398                    // A re-keyed row keeps its mark.
399                    if new_key != key && d.selected.remove(&key) {
400                        d.selected.insert(new_key.clone());
401                    }
402                    d.reorder();
403                    d.prune_selection();
404                    d.pending.push(Command::TABLE_CELL_EDITED);
405                    d.display_of(&new_key).unwrap_or(d.focused)
406                };
407                list_viewer::focus_item_num(self.body_mut(), idx as i32, ctx);
408                true
409            }
410            None => {
411                self.close_editor(ctx);
412                true
413            }
414        }
415    }
416
417    /// An error box about the edit is coming up.
418    fn box_opened(&mut self) {
419        if let Some(e) = &mut self.edit {
420            e.box_open = true;
421        }
422    }
423
424    /// The table's focus changed: losing it cancels an open edit, unless an
425    /// error box about the edit took it.
426    pub(super) fn edit_focus(&mut self, focused: bool, ctx: &mut Context) {
427        match &mut self.edit {
428            Some(e) if focused => e.box_open = false,
429            Some(e) if !e.box_open => self.cancel_edit(ctx),
430            _ => {}
431        }
432    }
433
434    /// An event reaching the table while an editor is open: Enter commits,
435    /// Esc cancels, Tab/Shift-Tab commit and move to the next/previous
436    /// editable cell of the row (past the last/first one the edit ends and
437    /// Tab goes on, so the focus moves); a press outside the editor cancels
438    /// (and goes on). A key that finds the editor scrolled off screen scrolls
439    /// it back first; one that finds the cell gone ends the edit and is used
440    /// up (unless the app dropped the edit). Returns whether `ev` was used.
441    pub(super) fn edit_event(&mut self, ev: &Event, ctx: &mut Context) -> bool {
442        let is_key = matches!(ev, Event::KeyDown(_));
443        if (is_key || matches!(ev, Event::MouseDown(_)))
444            && let Some(e) = &mut self.edit
445        {
446            e.box_open = false;
447        }
448        if !self.edit_alive() {
449            self.end_dead_edit(ctx);
450            // A key that finds the cell gone is used up here.
451            if is_key && self.eat_key {
452                self.eat_key = false;
453                return true;
454            }
455            return false;
456        }
457        if !self.place_editor(false) && is_key && !self.reveal_editor(ctx) {
458            // No room to show the cell at all.
459            self.cancel_edit(ctx);
460            return true;
461        }
462        match *ev {
463            Event::KeyDown(ke) if plain(ke) && ke.key == Key::Enter => {
464                self.commit_edit(ctx);
465                true
466            }
467            Event::KeyDown(ke) if plain(ke) && ke.key == Key::Esc => {
468                self.cancel_edit(ctx);
469                true
470            }
471            Event::KeyDown(ke) if !ke.modifiers.ctrl && !ke.modifiers.alt && ke.key == Key::Tab => {
472                let col = self.edit.as_ref().map(|e| e.col);
473                if !self.commit_edit(ctx) {
474                    return true;
475                }
476                // Past the last stop the Tab goes on and moves the focus.
477                col.is_some_and(|col| self.edit_neighbour(col, !ke.modifiers.shift, ctx))
478            }
479            Event::MouseDown(me) => {
480                let editor = self.edit.as_ref().map(|e| e.editor);
481                let inside = editor
482                    .and_then(|id| self.group.child_mut(id))
483                    .is_some_and(|v| {
484                        // A hidden editor is not under the pointer.
485                        v.state().state.visible && v.state().get_bounds().contains(me.position)
486                    });
487                if !inside {
488                    self.cancel_edit(ctx);
489                }
490                false
491            }
492            _ => false,
493        }
494    }
495
496    /// Open the editor on the editable column after (`forwards`) or before
497    /// model column `col` on the focused row; past either end the cursor
498    /// stays on `col` and no editor opens. Returns whether there was a
499    /// neighbour.
500    fn edit_neighbour(&mut self, col: usize, forwards: bool, ctx: &mut Context) -> bool {
501        let next = {
502            let d = self.data.borrow();
503            let cols = d.editable_cols();
504            cols.iter().position(|&c| c == col).and_then(|i| {
505                if forwards {
506                    cols.get(i + 1).copied()
507                } else {
508                    i.checked_sub(1).map(|j| cols[j])
509                }
510            })
511        };
512        match next {
513            Some(next) => {
514                self.start_edit(next, ctx);
515                true
516            }
517            None => false,
518        }
519    }
520
521    /// An event reaching the table while no editor is open: F2 edits the
522    /// cell under the cursor, and so does Enter while there is a cursor and a
523    /// focused row (else the table does not use Enter); a double-click on an
524    /// editable cell edits that cell. Returns whether `ev` was used.
525    pub(super) fn start_event(&mut self, ev: &Event, ctx: &mut Context) -> bool {
526        match *ev {
527            Event::KeyDown(ke) if plain(ke) && !ke.modifiers.shift && ke.key == Key::F(2) => {
528                match self.cursor_column() {
529                    Some(col) => {
530                        self.start_edit(col, ctx);
531                        true
532                    }
533                    None => false,
534                }
535            }
536            Event::KeyDown(ke) if plain(ke) && !ke.modifiers.shift && ke.key == Key::Enter => {
537                let Some(col) = self.cursor_column() else {
538                    return false;
539                };
540                if self.focused_key().is_none() {
541                    return false;
542                }
543                // Used like F2 even when the cell cannot be shown, so it
544                // never presses the dialog's default button instead.
545                self.start_edit(col, ctx);
546                true
547            }
548            Event::MouseDown(me)
549                if me.flags.double_click && me.buttons.left && me.position.y >= 1 =>
550            {
551                let Some((item, col)) = self.editable_cell_at(me.position) else {
552                    return false;
553                };
554                list_viewer::focus_item_num(self.body_mut(), item, ctx);
555                self.start_edit(col, ctx)
556            }
557            _ => false,
558        }
559    }
560
561    /// The display row and model column of the editable cell under
562    /// table-local `at`, if there is one.
563    fn editable_cell_at(&mut self, at: Point) -> Option<(i32, usize)> {
564        let size_x = self.group.state().size.x;
565        let lv = self.body_mut().lv_state();
566        let item = at.y - 1 + lv.top_item;
567        if item >= lv.range {
568            return None;
569        }
570        let d = self.data.borrow();
571        let l = row_layout(&d, size_x);
572        let col = l
573            .column_at(at.x - TEXT_X, d.h_offset)
574            .and_then(|lc| d.model_col(lc))?;
575        (d.columns[col].editable).then_some((item, col))
576    }
577}
578
579/// Whether `ke` has neither Ctrl nor Alt (Shift is checked per key).
580fn plain(ke: KeyEvent) -> bool {
581    !ke.modifiers.ctrl && !ke.modifiers.alt
582}