open-timeline-gui 0.1.0

OpenTimeline GUI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
// SPDX-License-Identifier: GPL-3.0-or-later

//!
//! Desktop GUI entity counts
//!

use crate::{
    app::{ActionRequest, EntityOrTimelineActionRequest},
    components::OpenTimelineButton,
    config::SharedConfig,
    consts::{EDIT_BUTTON_WIDTH, VIEW_BUTTON_WIDTH},
    spawn_transaction_no_commit_send_result,
};
use eframe::egui::{self, Align, Context, Layout, ScrollArea, TextEdit, Ui, Vec2};
use egui_extras::{Column, TableBuilder};
use open_timeline_crud::{CrudError, EntityCounts, SortAlphabetically, SortByNumber};
use open_timeline_gui_core::{
    Draw, Paginator, Reload, body_text_height, widget_x_spacing, widget_y_spacing,
};
use std::sync::Arc;
use tokio::sync::mpsc::error::TryRecvError;
use tokio::sync::mpsc::{Receiver, UnboundedSender};

const UP_ARROW: &str = "";
const DOWN_ARROW: &str = "";
const UP_DOWN_ARROW: &str = "⏶⏷";

#[derive(Debug, Clone, Copy)]
struct EntityCountsTableSizes {
    row_height: f32,
    entity_name_width: f32,
    entity_date_width: f32,
    entity_tag_count_width: f32,
    edit_button_width: f32,
    view_button_width: f32,
    table_body_max_height: f32,
}

/// The entity counts GUI panel in the main window
#[derive(Debug)]
pub struct EntityCountsGui {
    /// The entity counts (if they have been fetched). These are not sorted.
    entity_counts: Option<EntityCounts>,

    /// The entity counts after they have been filtered by the search string.
    /// These are sorted.
    ///
    /// The `EntityCounts` are owned because of difficulties with referencing other
    /// fields in the same struct.
    filtered_entity_counts: Option<EntityCounts>,

    /// How the entity name column should be ordered (if at all)
    name_ordering: Option<SortAlphabetically>,

    // TODO: combine into a single enum
    /// How the count column should be ordered (if at all)
    tag_count_ordering: Option<SortByNumber>,

    // TODO: combine into a single enum
    /// How the count column should be ordered (if at all)
    start_ordering: Option<SortByNumber>,

    // TODO: combine into a single enum
    /// How the count column should be ordered (if at all)
    end_ordering: Option<SortByNumber>,

    /// Receive up-to-date `EntityCounts` after a reload requested
    rx_reload: Option<Receiver<Result<EntityCounts, CrudError>>>,

    /// Whether a reload has been requested
    requested_reload: bool,

    /// Used request new entity edit & entity view windows
    tx_action_request: UnboundedSender<ActionRequest>,

    /// Used to filter the entities (display entities whose name or value contains the
    /// this string
    filter_text: String,

    /// Handles pagination
    paginator: Paginator,

    /// Database pool
    shared_config: SharedConfig,
}

impl EntityCountsGui {
    /// Create a new entities GUI panel manager
    pub fn new(
        shared_config: SharedConfig,
        tx_action_request: UnboundedSender<ActionRequest>,
    ) -> Self {
        let mut entity_count_gui = Self {
            entity_counts: None,
            filtered_entity_counts: None,
            name_ordering: None,
            start_ordering: None,
            end_ordering: None,
            tag_count_ordering: None,
            rx_reload: None,
            requested_reload: false,
            tx_action_request,
            filter_text: String::new(),
            paginator: Paginator::new(0, 0, 100),
            shared_config,
        };
        entity_count_gui.request_reload();
        entity_count_gui
    }

    /// Update the order of the filtered entity counts
    fn update_sort(&mut self) {
        if let Some(entity_counts) = self.filtered_entity_counts.as_mut() {
            if let Some(name_ordering) = &self.name_ordering {
                entity_counts.sort_by_name(name_ordering);
            }
            if let Some(tag_count_ordering) = &self.tag_count_ordering {
                entity_counts.sort_by_tag_count(tag_count_ordering);
            }
            if let Some(start_ordering) = &self.start_ordering {
                entity_counts.sort_by_start_date(start_ordering);
            }
            if let Some(end_ordering) = &self.end_ordering {
                entity_counts.sort_by_end_date(end_ordering);
            }
        }
    }

    /// Draw the table header row
    fn draw_table_header(
        &mut self,
        _ctx: &Context,
        ui: &mut Ui,
        table_sizes: EntityCountsTableSizes,
    ) {
        let mut sort_needs_updating = false;
        begin_table(ui, "entity_counts_header", table_sizes).header(
            table_sizes.row_height,
            |mut row| {
                // Entity names
                row.col(|ui| {
                    let arrow = match self.name_ordering {
                        None => UP_DOWN_ARROW,
                        Some(SortAlphabetically::AToZ) => UP_ARROW,
                        Some(SortAlphabetically::ZToA) => DOWN_ARROW,
                    };
                    ui.with_layout(Layout::left_to_right(Align::Center), |ui| {
                        if open_timeline_gui_core::Label::sub_heading(ui, &format!("Name {arrow}"))
                            .clicked()
                        {
                            self.tag_count_ordering = None;
                            self.start_ordering = None;
                            self.end_ordering = None;
                            match self.name_ordering {
                                None => self.name_ordering = Some(SortAlphabetically::AToZ),
                                Some(SortAlphabetically::AToZ) => {
                                    self.name_ordering = Some(SortAlphabetically::ZToA)
                                }
                                Some(SortAlphabetically::ZToA) => self.name_ordering = None,
                            }
                            sort_needs_updating = true;
                        }
                    });
                });
                // Entity start date
                row.col(|ui| {
                    let arrow = match self.start_ordering {
                        None => UP_DOWN_ARROW,
                        Some(SortByNumber::Ascending) => UP_ARROW,
                        Some(SortByNumber::Descending) => DOWN_ARROW,
                    };
                    ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
                        if open_timeline_gui_core::Label::sub_heading(ui, &format!("Start {arrow}"))
                            .clicked()
                        {
                            self.name_ordering = None;
                            self.end_ordering = None;
                            self.tag_count_ordering = None;
                            match self.start_ordering {
                                None => self.start_ordering = Some(SortByNumber::Ascending),
                                Some(SortByNumber::Ascending) => {
                                    self.start_ordering = Some(SortByNumber::Descending)
                                }
                                Some(SortByNumber::Descending) => self.start_ordering = None,
                            }
                            sort_needs_updating = true;
                        }
                    });
                });
                // Entity end date
                row.col(|ui| {
                    let arrow = match self.end_ordering {
                        None => UP_DOWN_ARROW,
                        Some(SortByNumber::Ascending) => UP_ARROW,
                        Some(SortByNumber::Descending) => DOWN_ARROW,
                    };
                    ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
                        if open_timeline_gui_core::Label::sub_heading(ui, &format!("End {arrow}"))
                            .clicked()
                        {
                            self.name_ordering = None;
                            self.start_ordering = None;
                            self.tag_count_ordering = None;
                            match self.end_ordering {
                                None => self.end_ordering = Some(SortByNumber::Ascending),
                                Some(SortByNumber::Ascending) => {
                                    self.end_ordering = Some(SortByNumber::Descending)
                                }
                                Some(SortByNumber::Descending) => self.end_ordering = None,
                            }
                            sort_needs_updating = true;
                        }
                    });
                });
                // Entity tag counts
                row.col(|ui| {
                    let arrow = match self.tag_count_ordering {
                        None => UP_DOWN_ARROW,
                        Some(SortByNumber::Ascending) => UP_ARROW,
                        Some(SortByNumber::Descending) => DOWN_ARROW,
                    };
                    ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
                        if open_timeline_gui_core::Label::sub_heading(ui, &format!("Tags {arrow}"))
                            .clicked()
                        {
                            self.name_ordering = None;
                            self.start_ordering = None;
                            self.end_ordering = None;
                            match self.tag_count_ordering {
                                None => self.tag_count_ordering = Some(SortByNumber::Ascending),
                                Some(SortByNumber::Ascending) => {
                                    self.tag_count_ordering = Some(SortByNumber::Descending)
                                }
                                Some(SortByNumber::Descending) => self.tag_count_ordering = None,
                            }
                            sort_needs_updating = true;
                        }
                    });
                });

                // Add space for edit & view buttons
                row.col(|_ui| {});
                row.col(|_ui| {});
            },
        );
        if sort_needs_updating {
            self.update_sort();
        }
    }

    /// Draw the table body
    fn draw_table_body(
        &mut self,
        _ctx: &Context,
        ui: &mut Ui,
        table_sizes: EntityCountsTableSizes,
    ) {
        let Some(entity_counts) = self.filtered_entity_counts.as_ref() else {
            panic!()
        };

        // How a page/slice (too slow otherwise)
        let offset = (self.paginator.page_index()) * self.paginator.items_per_page();
        let upper_limit = entity_counts
            .len()
            .min(offset + self.paginator.items_per_page());

        // offset..=upper_limit would overflow/be out of bounds
        let entity_counts = &entity_counts[offset..upper_limit];

        // Layouts
        let right_to_left = Layout::right_to_left(Align::Center);
        let left_to_right = Layout::left_to_right(Align::Center);

        ScrollArea::vertical()
            .max_height(table_sizes.table_body_max_height)
            .show(ui, |ui| {
                begin_table(ui, "entity_entity_counts_body", table_sizes).body(|mut body| {
                    for entity_count in entity_counts {
                        let name = entity_count.name().as_str();
                        let start = entity_count.start().as_short_date_format();
                        let end = entity_count
                            .end()
                            .map(|end| end.as_short_date_format())
                            .unwrap_or_default();

                        body.row(table_sizes.row_height, |mut row| {
                            // Entity name
                            row.col(|ui| {
                                ui.with_layout(left_to_right, |ui| {
                                    ui.add(egui::Label::new(name).truncate());
                                });
                            });
                            // Entity start
                            row.col(|ui| {
                                ui.with_layout(right_to_left, |ui| {
                                    ui.add(egui::Label::new(start).truncate());
                                });
                            });
                            // Entity end
                            row.col(|ui| {
                                ui.with_layout(right_to_left, |ui| {
                                    ui.add(egui::Label::new(end).truncate());
                                });
                            });
                            // Entity tag count
                            row.col(|ui| {
                                ui.with_layout(right_to_left, |ui| {
                                    ui.add(
                                        egui::Label::new(format!("{}", entity_count.tag_count()))
                                            .truncate(),
                                    );
                                });
                            });

                            // Button to request to edit the entity
                            row.col(|ui| {
                                if OpenTimelineButton::edit(ui).clicked() {
                                    let _ = self.tx_action_request.send(ActionRequest::Entity(
                                        EntityOrTimelineActionRequest::EditExisting(
                                            entity_count.id(),
                                        ),
                                    ));
                                }
                            });

                            // Button to request to view the entity
                            row.col(|ui| {
                                if OpenTimelineButton::view(ui).clicked() {
                                    let _ = self.tx_action_request.send(ActionRequest::Entity(
                                        EntityOrTimelineActionRequest::ViewExisting(
                                            entity_count.id(),
                                        ),
                                    ));
                                }
                            });
                        });
                    }
                });
            });
    }

    /// Update the filtered entity counts
    fn update_filtered_entity_counts(&mut self) {
        self.paginator.set_page_index(0);
        self.filtered_entity_counts = self.entity_counts.as_ref().map(|entity_counts| {
            entity_counts
                .into_iter()
                .filter(|entity_count| {
                    entity_count
                        .name()
                        .as_str()
                        .to_ascii_lowercase()
                        .contains(&self.filter_text.to_ascii_lowercase())
                })
                .cloned()
                .collect()
        });
        // If there are no entity counts after filtering, convert to None
        self.filtered_entity_counts = self
            .filtered_entity_counts
            .take()
            .filter(|filtered_entity_counts| !filtered_entity_counts.is_empty());
        self.update_sort();
    }
}

impl Reload for EntityCountsGui {
    fn request_reload(&mut self) {
        self.requested_reload = true;
        let (tx, rx) = tokio::sync::mpsc::channel(1);
        self.rx_reload = Some(rx);
        let shared_config = Arc::clone(&self.shared_config);
        spawn_transaction_no_commit_send_result!(
            shared_config,
            bounded,
            tx,
            |transaction| async move { EntityCounts::fetch_all(transaction).await }
        );
    }

    fn check_reload_response(&mut self) {
        if let Some(rx) = self.rx_reload.as_mut() {
            match rx.try_recv() {
                Ok(msg) => match msg {
                    Ok(entity_counts) => {
                        self.entity_counts = Some(entity_counts);
                        self.paginator.set_page_index(0);
                        self.update_filtered_entity_counts();
                        self.rx_reload = None;
                        self.update_sort();
                        self.requested_reload = false;
                    }
                    Err(error) => eprintln!("Error fetching entity counts: {error}"),
                },
                Err(TryRecvError::Empty) => (),
                Err(TryRecvError::Disconnected) => (),
            }
        }
    }
}

impl Draw for EntityCountsGui {
    fn draw(&mut self, ctx: &Context, ui: &mut Ui) {
        self.check_reload_response();

        // Input to filter by text
        let filter_input = ui.add(
            TextEdit::singleline(&mut self.filter_text)
                .desired_width(f32::INFINITY)
                .hint_text("Filter by entity name"),
        );
        if filter_input.changed() {
            self.update_filtered_entity_counts();
        }
        ui.separator();

        // Get number of entities.  If there aren't any let the user know and return
        if let Some(entity_counts) = &self.filtered_entity_counts {
            self.paginator.set_total_count(entity_counts.len());
        } else {
            open_timeline_gui_core::Label::none(ui);
            return;
        }

        // Sizes
        let available_width = ui.available_width();
        let available_height = ui.available_height();
        let row_height = body_text_height(ui);
        let x_spacing = widget_x_spacing(ui);
        let y_spacing = widget_y_spacing(ui);
        let tag_count_width = 100.0;
        let date_width = 100.0;
        let table_max_height = available_height - (y_spacing * 3.0) - (row_height * 1.0);
        let table_body_max_height = table_max_height - (y_spacing * 1.0) - (row_height * 1.0);
        let entity_name_width = available_width
            - tag_count_width
            - (2.0 * date_width)
            - EDIT_BUTTON_WIDTH
            - VIEW_BUTTON_WIDTH
            - (5.0 * x_spacing);

        // Stop underflows (cause egui to crash)
        let table_max_height = table_max_height.max(0.0);
        let table_body_max_height = table_body_max_height.max(0.0);
        let entity_name_width = entity_name_width.max(0.0);

        // Table sizes
        let table_sizes = EntityCountsTableSizes {
            row_height,
            entity_name_width,
            entity_date_width: tag_count_width,
            entity_tag_count_width: tag_count_width,
            edit_button_width: EDIT_BUTTON_WIDTH,
            view_button_width: VIEW_BUTTON_WIDTH,
            table_body_max_height,
        };

        // Table
        ui.allocate_ui(Vec2::from([available_width, table_body_max_height]), |ui| {
            ui.set_min_size(Vec2::from([available_width, table_max_height]));
            self.draw_table_header(ctx, ui, table_sizes);
            self.draw_table_body(ctx, ui, table_sizes);
        });
        ui.separator();

        // Pagination controls
        self.paginator.draw(ctx, ui);
    }
}

/// Begin creating a table.  Used by both the table header and table body
/// drawing functions to ensure the columns match up
fn begin_table<'a>(
    ui: &'a mut Ui,
    id: &str,
    table_sizes: EntityCountsTableSizes,
) -> TableBuilder<'a> {
    TableBuilder::new(ui)
        .id_salt(id)
        .striped(true)
        .column(Column::exact(table_sizes.entity_name_width))
        .column(Column::exact(table_sizes.entity_date_width))
        .column(Column::exact(table_sizes.entity_date_width))
        .column(Column::exact(table_sizes.entity_tag_count_width))
        .column(Column::exact(table_sizes.edit_button_width))
        .column(Column::exact(table_sizes.view_button_width))
}