Skip to main content

egui_selectable_table/
row_selection.rs

1use ahash::{HashMap, HashMapExt, HashSet};
2use egui::Ui;
3
4#[cfg(feature = "rayon")]
5use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
6
7use std::fmt::Write as _;
8use std::hash::Hash;
9
10use crate::{ColumnOperations, ColumnOrdering, SelectableRow, SelectableTable};
11
12/// Functions related to selection of rows and columns
13#[allow(clippy::too_many_lines)]
14impl<Row, F, Conf> SelectableTable<Row, F, Conf>
15where
16    Row: Clone + Send + Sync,
17    F: Eq
18        + Hash
19        + Clone
20        + Ord
21        + Send
22        + Sync
23        + Default
24        + ColumnOperations<Row, F, Conf>
25        + ColumnOrdering<Row>,
26    Conf: Default,
27{
28    /// Selects all cells in the rectangle from (`start_id`, `start_col`) to
29    /// (`end_id`, `end_col`). Used by shift+click range selection.
30    /// For Ctrl+drag, `extend` is used to union with existing selections.
31    pub(crate) fn select_rectangle(
32        &mut self,
33        start_id: i64,
34        start_col: &F,
35        end_id: i64,
36        end_col: &F,
37        extend: bool,
38    ) {
39        let Some(start_idx) = self.indexed_ids.get(&start_id).copied() else {
40            return;
41        };
42        let Some(end_idx) = self.indexed_ids.get(&end_id).copied() else {
43            return;
44        };
45
46        let start_col_num = self.column_to_num(start_col);
47        let end_col_num = self.column_to_num(end_col);
48        let col_min = start_col_num.min(end_col_num);
49        let col_max = start_col_num.max(end_col_num);
50        let row_min = start_idx.min(end_idx);
51        let row_max = start_idx.max(end_idx);
52
53        let col_range: HashSet<F> = (col_min..=col_max)
54            .map(|i| self.all_columns[i].clone())
55            .collect();
56
57        if extend {
58            for col in &col_range {
59                self.active_columns.insert(col.clone());
60            }
61        } else {
62            self.active_columns.clone_from(&col_range);
63        }
64
65        for row_idx in row_min..=row_max {
66            let Some(row) = self.formatted_rows.get_mut(row_idx) else {
67                continue;
68            };
69            if self.select_full_row {
70                row.selected_columns.extend(self.all_columns.clone());
71            } else if extend {
72                row.selected_columns.extend(col_range.clone());
73            } else {
74                row.selected_columns.clone_from(&col_range);
75            }
76            self.active_rows.insert(row.id);
77        }
78    }
79
80    pub(crate) fn select_single_row_cell(&mut self, id: i64, column_name: &F) {
81        self.active_columns.insert(column_name.clone());
82        self.active_rows.insert(id);
83
84        let Some(target_index) = self.indexed_ids.get(&id) else {
85            return;
86        };
87        let Some(target_row) = self.formatted_rows.get_mut(*target_index) else {
88            return;
89        };
90
91        if self.select_full_row {
92            self.active_columns.extend(self.all_columns.clone());
93            target_row.selected_columns.extend(self.all_columns.clone());
94        } else {
95            target_row.selected_columns.insert(column_name.clone());
96        }
97
98        self.active_rows.insert(id);
99    }
100
101    /// Marks a row as selected, optionally selecting specific columns within the row.
102    ///
103    /// If a list of columns is provided, only those columns are marked as selected for the row.
104    /// If no column list is provided, all columns in the row are marked as selected.
105    ///
106    /// # Parameters:
107    /// - `id`: The unique identifier of the row to mark as selected.
108    /// - `column`: An optional list of columns (`Vec<F>`) to mark as selected within the row. If `None`, all columns are selected.
109    ///
110    /// # Example:
111    /// ```rust,ignore
112    /// table.mark_row_as_selected(42, Some(vec!["Name", "Age"]));
113    /// table.mark_row_as_selected(43, None); // Selects all columns in row 43
114    /// ```
115    pub fn mark_row_as_selected(&mut self, id: i64, column: Option<Vec<F>>) {
116        let Some(target_index) = self.indexed_ids.get(&id) else {
117            return;
118        };
119
120        let Some(target_row) = self.formatted_rows.get_mut(*target_index) else {
121            return;
122        };
123
124        self.active_rows.insert(id);
125
126        if let Some(column_list) = column {
127            self.active_columns.extend(column_list.clone());
128
129            target_row.selected_columns.extend(column_list);
130        } else {
131            self.active_columns.extend(self.all_columns.clone());
132
133            target_row.selected_columns.extend(self.all_columns.clone());
134        }
135    }
136
137    /// Called on every frame per cell that the pointer rests on during an active drag.
138    ///
139    /// Handles the core drag-selection logic:
140    /// 1. Computes the column range from drag start to current pointer position
141    /// 2. Updates `active_columns` to reflect exactly the rectangle's column set (not accumulated
142    ///    across multiple drags). For Ctrl+drag this unions with existing columns on each row so
143    ///    independent drag regions don't interfere.
144    /// 3. Handles "backwards movement": when the mouse moves back through previously-selected
145    ///    territory within a drag, it may need to unselect cells that are no longer in the
146    ///    active path (the `row_contains_column` / `no_checking` block)
147    /// 4. Calls `check_row_selection` bidirectionally to fill any rows skipped by fast mouse
148    ///    movement between the drag start row and current row
149    /// 5. Calls `remove_row_selection` to sync rows inside the drag range and clear rows that
150    ///    fell out of it (only for non-Ctrl; Ctrl+drag preserves committed selections)
151    pub(crate) fn select_dragged_row_cell(
152        &mut self,
153        id: i64,
154        column_name: &F,
155        is_ctrl_pressed: bool,
156    ) {
157        // If the pointer hasn't actually moved to a new cell since last frame, nothing to do
158        if self.last_active_row == Some(id) && self.last_active_column == Some(column_name.clone())
159        {
160            return;
161        }
162
163        if self.formatted_rows.is_empty() {
164            return;
165        }
166
167        self.beyond_drag_point = true;
168
169        let drag_start = self.drag_started_on.clone().expect("Drag start not found");
170
171        // Compute the column range from drag start to current position.
172        let drag_start_num = self.column_to_num(&drag_start.1);
173        let ongoing_column_num = self.column_to_num(column_name);
174
175        let col_min = drag_start_num.min(ongoing_column_num);
176        let col_max = drag_start_num.max(ongoing_column_num);
177
178        let new_column_set: HashSet<F> = (col_min..=col_max)
179            .map(|i| self.all_columns[i].clone())
180            .collect();
181
182        if is_ctrl_pressed {
183            for col in &new_column_set {
184                self.active_columns.insert(col.clone());
185            }
186        } else {
187            self.active_columns = new_column_set;
188        }
189
190        let Some(current_row_index) = self.indexed_ids.get(&id).copied() else {
191            return;
192        };
193        let Some(current_row) = self.formatted_rows.get_mut(current_row_index) else {
194            return;
195        };
196
197        // Detect "backwards movement": if the current row already has this column
198        // selected, the mouse may be moving back through previously-selected territory.
199        // We need to unselect cells that are no longer on the active path.
200        let row_contains_column = current_row.selected_columns.contains(column_name);
201
202        let mut no_checking = false;
203        // Backwards movement handling:
204        //   Row: col1 col2 (mouse here) col3 col4
205        // If mouse was on col4 last frame and is now on col2 on the same row,
206        // col4 should be unselected from this row since the mouse retracted.
207        // When crossing to a different row altogether, we clear the entire
208        // previous row's selection so the drag rectangle resizes cleanly.
209        if row_contains_column
210            && self.last_active_row.is_some()
211            && self.last_active_column.is_some()
212        {
213            if let (Some(last_active_column), Some(last_active_row)) =
214                (self.last_active_column.clone(), self.last_active_row)
215            {
216                if &last_active_column != column_name && last_active_row == id {
217                    current_row.selected_columns.remove(&last_active_column);
218                    self.active_columns.remove(&last_active_column);
219                }
220
221                let Some(last_row_index) = self.indexed_ids.get(&last_active_row).copied() else {
222                    return;
223                };
224                let Some(last_row) = self.formatted_rows.get_mut(last_row_index) else {
225                    return;
226                };
227
228                self.last_active_row = Some(id);
229
230                if id == last_row.id {
231                    if &last_active_column != column_name {
232                        self.last_active_column = Some(column_name.clone());
233                    }
234                } else {
235                    no_checking = true;
236                    last_row.selected_columns.clear();
237                }
238            }
239        } else {
240            // First time this drag touches this row. Apply the active column set.
241            // For Ctrl+drag, extend (union) to preserve columns from prior selections.
242            self.active_rows.insert(current_row.id);
243            self.last_active_row = Some(id);
244            self.last_active_column = Some(column_name.clone());
245            if is_ctrl_pressed {
246                current_row
247                    .selected_columns
248                    .extend(self.active_columns.clone());
249            } else {
250                current_row
251                    .selected_columns
252                    .clone_from(&self.active_columns);
253            }
254        }
255
256        let Some(current_row_index) = self.indexed_ids.get(&id).copied() else {
257            return;
258        };
259
260        let Some(drag_start_index) = self.indexed_ids.get(&drag_start.0).copied() else {
261            return;
262        };
263
264        if !no_checking {
265            // Walk both directions from current row toward drag start to fill
266            // any rows skipped by fast mouse movement (missed pointer-in-cell events).
267            self.check_row_selection(true, current_row_index, drag_start_index, is_ctrl_pressed);
268            self.check_row_selection(false, current_row_index, drag_start_index, is_ctrl_pressed);
269        }
270        // Sync rows inside the drag range and clear rows that left it
271        self.remove_row_selection(current_row_index, drag_start_index, is_ctrl_pressed);
272    }
273
274    /// Walks from the current row toward (or away from) the drag-start row, selecting
275    /// intermediate rows to fill gaps from fast mouse movement. Stops when hitting either
276    /// the drag-start row boundary or a row with no selection (end of previously-selected
277    /// territory). Uses a loop instead of recursion to avoid stack overflow on large tables.
278    fn check_row_selection(
279        &mut self,
280        check_previous: bool,
281        index: usize,
282        drag_start: usize,
283        is_ctrl_pressed: bool,
284    ) {
285        let mut idx = index;
286        loop {
287            if idx == 0 && check_previous {
288                return;
289            }
290            if idx + 1 == self.formatted_rows.len() && !check_previous {
291                return;
292            }
293            idx = if check_previous { idx - 1 } else { idx + 1 };
294
295            let Some(current_row) = self.formatted_rows.get(idx) else {
296                return;
297            };
298
299            // Consider a row "unselected" when we've walked past the drag-start
300            // boundary AND the row has no columns selected (meaning it's beyond
301            // the previously-selected range). Rows between current and drag-start
302            // are always treated as selected (unselected_row = false) so they
303            // get filled in even if they were missed by fast mouse movement.
304            let unselected_row = if (check_previous && idx >= drag_start)
305                || (!check_previous && idx <= drag_start)
306            {
307                false
308            } else {
309                current_row.selected_columns.is_empty()
310            };
311
312            if unselected_row {
313                return;
314            }
315
316            let Some(target_row) = self.formatted_rows.get_mut(idx) else {
317                return;
318            };
319
320            if self.select_full_row {
321                target_row.selected_columns.extend(self.all_columns.clone());
322            } else if is_ctrl_pressed {
323                target_row
324                    .selected_columns
325                    .extend(self.active_columns.clone());
326            } else {
327                target_row.selected_columns.clone_from(&self.active_columns);
328            }
329            self.active_rows.insert(target_row.id);
330        }
331    }
332
333    /// Iterates all currently-active rows and syncs their selection state.
334    /// Rows inside the drag range get their columns updated to match `active_columns`.
335    /// For non-Ctrl drags, rows outside the range are cleared entirely.
336    /// For Ctrl+drags, rows outside the range are left untouched (preserving prior selections).
337    fn remove_row_selection(
338        &mut self,
339        current_index: usize,
340        drag_start: usize,
341        is_ctrl_pressed: bool,
342    ) {
343        let active_ids = self.active_rows.clone();
344        for id in active_ids {
345            let Some(ongoing_index) = self.indexed_ids.get(&id).copied() else {
346                continue;
347            };
348            let Some(target_row) = self.formatted_rows.get_mut(ongoing_index) else {
349                continue;
350            };
351
352            if current_index > drag_start {
353                if ongoing_index >= drag_start && ongoing_index <= current_index {
354                    if self.select_full_row {
355                        target_row.selected_columns.extend(self.all_columns.clone());
356                    } else if is_ctrl_pressed {
357                        target_row
358                            .selected_columns
359                            .extend(self.active_columns.clone());
360                    } else {
361                        target_row.selected_columns.clone_from(&self.active_columns);
362                    }
363                } else if !is_ctrl_pressed {
364                    target_row.selected_columns.clear();
365                    self.active_rows.remove(&target_row.id);
366                }
367            } else if ongoing_index <= drag_start && ongoing_index >= current_index {
368                if self.select_full_row {
369                    target_row.selected_columns.extend(self.all_columns.clone());
370                } else if is_ctrl_pressed {
371                    target_row
372                        .selected_columns
373                        .extend(self.active_columns.clone());
374                } else {
375                    target_row.selected_columns.clone_from(&self.active_columns);
376                }
377            } else if !is_ctrl_pressed {
378                target_row.selected_columns.clear();
379                self.active_rows.remove(&target_row.id);
380            }
381        }
382    }
383
384    /// Unselects all currently selected rows and columns.
385    ///
386    /// Clears the selection in both rows and columns, and resets internal tracking of active rows
387    /// and columns. After this call, there will be no selected rows or columns in the table.
388    ///
389    /// # Panics:
390    /// This method will panic if the indexed ID or the corresponding row cannot be found.
391    ///
392    /// # Example:
393    /// ```rust,ignore
394    /// table.unselect_all(); // Unselects everything in the table.
395    /// ```
396    pub fn unselect_all(&mut self) {
397        for id in &self.active_rows {
398            if let Some(id_index) = self.indexed_ids.get(id)
399                && let Some(target_row) = self.formatted_rows.get_mut(*id_index)
400            {
401                target_row.selected_columns.clear();
402            }
403        }
404        self.active_columns.clear();
405        self.last_active_row = None;
406        self.last_active_column = None;
407        self.active_rows.clear();
408    }
409
410    /// Selects all rows and columns in the table.
411    ///
412    /// After calling this method, all rows will have all columns selected and visible immediately.
413    ///
414    /// # Example:
415    /// ```rust,ignore
416    /// table.select_all(); // Selects all rows and columns.
417    /// ```
418    pub fn select_all(&mut self) {
419        self.active_columns.extend(self.all_columns.clone());
420        self.active_rows.clear();
421        self.last_active_row = None;
422        self.last_active_column = None;
423
424        for row in &mut self.formatted_rows {
425            if row.selected_columns.len() != self.all_columns.len() {
426                row.selected_columns.extend(self.all_columns.clone());
427            }
428            self.active_rows.insert(row.id);
429        }
430    }
431
432    /// Retrieves the currently selected rows.
433    ///
434    /// This method returns a vector of the rows that have one or more columns selected.
435    ///
436    /// If the `select_full_row` flag is enabled, it will ensure that all columns are selected for
437    /// each active row.
438    ///
439    /// # Returns:
440    /// A `Vec` of `SelectableRow` instances that are currently selected.
441    ///
442    /// # Example:
443    /// ```rust,ignore
444    /// let selected_rows = table.get_selected_rows();
445    /// ```
446    pub fn get_selected_rows(&mut self) -> Vec<SelectableRow<Row, F>> {
447        let mut selected_rows = Vec::new();
448        if self.select_full_row {
449            self.active_columns.extend(self.all_columns.clone());
450        }
451
452        // Cannot use active rows to iter as that does not maintain any proper format
453        for row in &self.formatted_rows {
454            if row.selected_columns.is_empty() {
455                continue;
456            }
457            selected_rows.push(row.clone());
458
459            // We already got all the active rows if this matches
460            if selected_rows.len() == self.active_rows.len() {
461                break;
462            }
463        }
464        selected_rows
465    }
466
467    /// Retrieves the currently selected rows but in no particular order. Can be faster than
468    /// [`get_selected_rows`](#method.get_selected_rows) as it only checks the active rows instead of every single row.
469    ///
470    /// This method returns a vector of the rows that have one or more columns selected.
471    ///
472    /// If the `select_full_row` flag is enabled, it will ensure that all columns are selected for
473    /// each active row.
474    ///
475    /// # Returns:
476    /// A `Vec` of `SelectableRow` instances that are currently selected.
477    ///
478    /// # Example:
479    /// ```rust,ignore
480    /// let selected_rows = table.get_selected_rows();
481    /// ```
482    pub fn get_selected_rows_unsorted(&mut self) -> Vec<SelectableRow<Row, F>> {
483        if self.select_full_row {
484            self.active_columns.extend(self.all_columns.clone());
485        }
486
487        let get_row = |row_id: &i64| {
488            let row_index = self
489                .indexed_ids
490                .get(row_id)
491                .expect("Could not get id index");
492            let target_row = self
493                .formatted_rows
494                .get(*row_index)
495                .expect("Could not get row");
496
497            target_row.clone()
498        };
499
500        #[cfg(feature = "rayon")]
501        if self.use_rayon(self.active_rows.len()) {
502            return self.active_rows.par_iter().map(get_row).collect();
503        }
504
505        self.active_rows.iter().map(get_row).collect()
506    }
507
508    /// Copies selected cells to the system clipboard in a tabular format.
509    ///
510    /// This method copies only the selected cells from each row to the clipboard, and ensures
511    /// that the column widths align for better readability when pasted into a text editor or spreadsheet.
512    ///
513    /// # Parameters:
514    /// - `ui`: The UI context used for clipboard interaction.
515    ///
516    /// # Example:
517    /// ```rust,ignore
518    /// table.copy_selected_cells(&mut ui);
519    /// ```
520    pub fn copy_selected_cells(&mut self, ui: &mut Ui) {
521        let mut selected_rows = Vec::new();
522        if self.select_full_row {
523            self.active_columns.extend(self.all_columns.clone());
524        }
525
526        let mut column_max_length = HashMap::new();
527
528        // Iter through all the rows and find the rows that have at least one column as selected.
529        // Keep track of the biggest length of a value of a column
530        // active rows cannot be used here because hashset does not maintain an order.
531        // So iterating will give the rows in a different order than what is shown in the ui
532        for row in &self.formatted_rows {
533            if row.selected_columns.is_empty() {
534                continue;
535            }
536
537            for column in &self.active_columns {
538                if row.selected_columns.contains(column) {
539                    let column_text = column.column_text(&row.row_data);
540                    let field_length = column_text.len();
541                    let entry = column_max_length.entry(column).or_insert(0);
542                    if field_length > *entry {
543                        column_max_length.insert(column, field_length);
544                    }
545                }
546            }
547            selected_rows.push(row);
548            // We already got all the active rows if this matches
549            if selected_rows.len() == self.active_rows.len() {
550                break;
551            }
552        }
553
554        let mut to_copy = String::new();
555
556        // Target is to ensure a fixed length after each column value of a row.
557        // If for example highest len is 10 but the current row's
558        // column value is 5, we will add the column value and add 5 more space after that
559        // to ensure alignment
560        for row in selected_rows {
561            let mut ongoing_column = self.first_column();
562            let mut row_text = String::new();
563            loop {
564                if self.active_columns.contains(&ongoing_column)
565                    && row.selected_columns.contains(&ongoing_column)
566                {
567                    let column_text = ongoing_column.column_text(&row.row_data);
568                    let _ = write!(
569                        row_text,
570                        "{:<width$}",
571                        column_text,
572                        width = column_max_length[&ongoing_column] + 1
573                    );
574                } else if self.active_columns.contains(&ongoing_column)
575                    && !row.selected_columns.contains(&ongoing_column)
576                {
577                    let _ = write!(
578                        row_text,
579                        "{:<width$}",
580                        "",
581                        width = column_max_length[&ongoing_column] + 1
582                    );
583                }
584                if self.last_column() == ongoing_column {
585                    break;
586                }
587                ongoing_column = self.next_column(&ongoing_column);
588            }
589            to_copy.push_str(&row_text);
590            to_copy.push('\n');
591        }
592        ui.ctx().copy_text(to_copy);
593    }
594
595    /// Enables the selection of full rows in the table.
596    ///
597    /// After calling this method, selecting any column in a row will result in the entire row being selected.
598    ///
599    /// # Returns:
600    /// A new instance of the table with full row selection enabled.
601    ///
602    /// # Example:
603    /// ```rust,ignore
604    /// let table = SelectableTable::new(vec![col1, col2, col3])
605    ///     .select_full_row();
606    /// ```
607    #[must_use]
608    pub const fn select_full_row(mut self) -> Self {
609        self.select_full_row = true;
610        self
611    }
612
613    /// Sets whether the table should select full rows when a column is selected.
614    ///
615    /// # Parameters:
616    /// - `status`: `true` to enable full row selection, `false` to disable it.
617    ///
618    /// # Example:
619    /// ```rust,ignore
620    /// table.set_select_full_row(true); // Enable full row selection.
621    /// ```
622    pub const fn set_select_full_row(&mut self, status: bool) {
623        self.select_full_row = status;
624    }
625
626    /// Returns the total number of currently selected rows.
627    ///
628    /// # Returns:
629    /// - `usize`: The number of selected rows.
630    ///
631    /// # Example:
632    /// ```rust,ignore
633    /// let selected_count = table.get_total_selected_rows();
634    /// println!("{} rows selected", selected_count);
635    /// ```
636    pub fn get_total_selected_rows(&mut self) -> usize {
637        self.active_rows.len()
638    }
639}