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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
use crate::{
DataContainer, DataFilter, DataFormat, Error, FileInfo, MyStyle, Notification, PolarsViewError,
PolarsViewResult, Settings, SortBy, open_file, save, save_as,
};
use egui::{
CentralPanel, Color32, Context, FontId, Frame, Grid, Key, KeyboardShortcut, Layout, MenuBar,
Modifiers, Panel, RichText, ScrollArea, Stroke, ViewportCommand, style::Visuals,
};
use std::{future::Future, sync::Arc};
use tokio::sync::oneshot::{self, Receiver, error::TryRecvError};
use tracing::error;
// --- Type Aliases ---
/// Type alias for a `Result` specifically wrapping a `DataContainer` on success.
/// Simplifies function signatures involving potential data loading/processing errors.
pub type ContainerResult = PolarsViewResult<DataContainer>;
/// Type alias for a boxed, dynamically dispatched Future that yields a `ContainerResult`.
/// This allows storing and managing different asynchronous operations (load, sort, format)
/// that all eventually produce a `DataContainer` or an error.
/// - `dyn Future`: Dynamic dispatch for different future types.
/// - `Output = ContainerResult`: The future resolves to our specific result type.
/// - `+ Unpin`: Required for `async`/`await` usage in certain contexts.
/// - `+ Send + 'static`: Necessary bounds for futures used across threads (like with `tokio::spawn`).
pub type DataFuture = Box<dyn Future<Output = ContainerResult> + Unpin + Send + 'static>;
// --- Constants ---
// Define keyboard shortcuts for common actions using `egui`'s `KeyboardShortcut`.
const CTRL_O: KeyboardShortcut = KeyboardShortcut::new(Modifiers::CTRL, Key::O); // Ctrl+O for Open File
const CTRL_S: KeyboardShortcut = KeyboardShortcut::new(Modifiers::CTRL, Key::S); // Ctrl+S for Save File
const CTRL_A: KeyboardShortcut = KeyboardShortcut::new(Modifiers::CTRL, Key::A); // Ctrl+A for Save As...
// --- Main Application Struct ---
/// The main application struct for PolarsView, holding the entire UI and async state.
pub struct PolarsViewApp {
/// Holds the currently loaded data and its associated view state (`DataContainer`).
/// `None` if no data is loaded. `Arc` allows efficient sharing with async tasks.
pub data_container: Option<Arc<DataContainer>>,
/// Stores the state of the data loading/filtering parameters *last applied*.
/// Used by the side panel UI (`render_query`) to detect changes made by the user
/// to settings like SQL query, delimiter, etc. **Does not contain sort info.**
pub applied_filter: DataFilter,
/// Stores the state of the data formatting settings *last applied*.
/// Used by the side panel UI (`render_format`) to detect changes to display settings.
pub applied_format: DataFormat,
/// Info extracted from the currently loaded file.
pub file_info: Option<FileInfo>,
/// Optional Notification window for displaying errors or settings dialogs.
pub notification: Option<Box<dyn Notification + 'static>>,
/// Tokio runtime instance for managing asynchronous operations.
runtime: tokio::runtime::Runtime,
/// Receiving end of a `tokio::sync::oneshot` channel used to get results
/// back from async `DataFuture` tasks onto the UI thread.
pipe: Option<Receiver<ContainerResult>>,
/// Vector to keep track of active `tokio` task handles. (Mainly for potential future management)
tasks: Vec<tokio::task::JoinHandle<()>>,
}
impl Default for PolarsViewApp {
/// Creates a default `PolarsViewApp` instance. Initializes the runtime and sets initial state.
fn default() -> Self {
Self {
data_container: None, // No data loaded initially.
applied_filter: DataFilter::default(), // Start with default filter settings.
applied_format: DataFormat::default(), // Start with default format settings.
file_info: None, // No file_info initially.
notification: None, // No notification initially.
runtime: tokio::runtime::Builder::new_multi_thread() // Essential: Use a multi-threaded runtime.
.enable_all() // Enable necessary Tokio features (I/O, time, etc.).
.build()
.expect("Failed to build Tokio runtime"), // Runtime creation is critical.
pipe: None, // No async operation pending at start.
tasks: Vec::new(), // No tasks running at start.
}
}
}
impl PolarsViewApp {
/// Creates a new `PolarsViewApp` instance.
/// Sets the initial UI style (theme).
pub fn new(cc: &eframe::CreationContext<'_>) -> PolarsViewResult<Self> {
// Apply custom styles and dark theme (defined via `MyStyle` trait in `traits.rs`).
cc.egui_ctx.set_style_init(Visuals::dark());
cc.egui_ctx.memory_mut(|mem| {
mem.data.clear();
});
Ok(Default::default()) // Return a new app with default settings.
}
/// Creates a new `PolarsViewApp` and immediately starts loading data using a provided `DataFuture`.
/// Useful for loading data specified via command-line arguments on startup.
/// `future`: The asynchronous operation (e.g., `DataContainer::load_data`) to run.
pub fn new_with_future(
cc: &eframe::CreationContext<'_>,
future: DataFuture,
) -> PolarsViewResult<Self> {
cc.egui_ctx.set_style_init(Visuals::dark()); // Apply style.
cc.egui_ctx.memory_mut(|mem| {
mem.data.clear();
});
let mut app: Self = Default::default(); // Create default app instance.
// Initiate the asynchronous data loading process.
app.run_data_future(future, &cc.egui_ctx);
Ok(app) // Return the app (data loading will happen in the background).
}
/// Checks if a `Notification` is active and renders it using `egui::Window`.
/// Removes the notification if its `show` method returns `false` (indicating it was closed).
fn check_notification(&mut self, ctx: &Context) {
if let Some(notification) = &mut self.notification
&& !notification.show(ctx)
{
// If `show` returns false (window closed by user or logic),
// clear the notification state.
self.notification = None;
}
}
/// Checks the `oneshot` channel (`pipe`) for the result of a pending async data operation.
/// This function is called repeatedly in the `logic` loop.
///
/// Returns:
/// - `true`: If an operation is still pending (channel was empty).
/// - `false`: If a result was received (success or error) or the channel was closed.
fn check_data_pending(&mut self) -> bool {
// Take the receiver out of the Option to check it.
let Some(mut output) = self.pipe.take() else {
return false; // No receiver means no operation is pending.
};
// Try to receive the result without blocking.
match output.try_recv() {
// --- Result Received ---
Ok(data_result) => {
match data_result {
// --- Async Operation Succeeded ---
Ok(container) => {
// A new `DataContainer` was successfully produced.
// Update the application state:
// 1. Update `applied_filter` to match the filter *used* in the new container.
// This ensures the UI reflects the state of the currently displayed data.
self.applied_filter = container.filter.as_ref().clone();
// 2. Update `applied_format` similarly. Crucial for changes like `expand_cols`.
self.applied_format = container.format.as_ref().clone();
// 3. Regenerate file_info based on the new container.
self.file_info = FileInfo::from_container(&container);
// 4. Store the new `DataContainer`, wrapped in `Arc`.
self.data_container = Some(Arc::new(container));
false // Indicate loading/update is complete.
}
// --- Async Operation Failed ---
Err(err) => {
// The async task returned an error.
let error_message = err.to_string();
// Display the error in a notification window.
self.notification = Some(Box::new(Error {
message: error_message,
}));
error!("Async data operation failed: {}", err); // Log the error.
false // Indicate loading/update is complete (though failed).
}
}
}
// --- No Result Yet or Channel Closed ---
Err(try_recv_error) => match try_recv_error {
// --- Channel Empty (Operation Still Running) ---
TryRecvError::Empty => {
// The async task hasn't finished yet.
// Put the receiver back into the `Option` so we can check again next frame.
self.pipe = Some(output);
true // Indicate operation is still pending.
}
// --- Channel Closed (Sender Dropped Prematurely) ---
TryRecvError::Closed => {
// This indicates an issue, likely the sending task panicked or exited unexpectedly.
let err_msg = "Async data operation channel closed unexpectedly.".to_string();
self.notification = Some(Box::new(Error {
message: err_msg.clone(),
}));
error!("{}", err_msg); // Log the error.
false // Operation is effectively complete (failed unexpectedly).
}
},
}
}
/// Spawns a `DataFuture` onto the shared `tokio` runtime.
/// Sets up the `oneshot` channel to receive the result.
/// `future`: The async operation (boxed Future) to execute.
/// `ctx`: The `egui::Context` used to request repaints from the background task.
fn run_data_future(&mut self, future: DataFuture, ctx: &Context) {
// Basic cleanup: remove completed task handles (optional but good practice).
self.tasks.retain(|task| !task.is_finished());
// Create the single-use channel for sending the result back to the UI thread.
let (tx, rx) = oneshot::channel::<PolarsViewResult<DataContainer>>();
// Store the receiving end in `self.pipe` so `check_data_pending` can poll it.
self.pipe = Some(rx);
// Clone the egui context so the background task can request UI repaints.
let ctx_clone = ctx.clone();
// Spawn the future onto the application's Tokio runtime.
// The task runs in the background, managed by the runtime's thread pool.
let handle = self.runtime.spawn(async move {
// Await the completion of the provided async operation.
let data = future.await;
// Send the result (Ok or Err) back through the oneshot channel.
// Ignore the result of `send`; if it fails, the receiver (`pipe`) was dropped,
// which `check_data_pending` handles anyway.
if tx.send(data).is_err() {
// Log if the receiver was dropped before sending.
error!("Receiver dropped before data could be sent from async task.");
}
// Request a repaint of the UI thread. This is crucial to ensure the UI
// updates immediately after the async operation completes, especially
// if `check_data_pending` doesn't run in the *exact* same frame.
ctx_clone.request_repaint();
});
// Store the task handle.
self.tasks.push(handle);
}
// --- Event Handlers ---
/// Centralized logic to initiate data loading from a filesystem path.
fn load_file_from_path(&mut self, path: std::path::PathBuf, ctx: &Context) {
let path = std::fs::canonicalize(&path).unwrap_or(path);
tracing::info!(target: "polars_view", "Loading path: {}", path.display());
self.applied_filter
.set_path(&path)
.map(|_| {
self.applied_filter.read_data_from_file = true;
let future = DataContainer::default()
.load_data(self.applied_filter.clone(), self.applied_format.clone());
self.run_data_future(Box::new(Box::pin(future)), ctx);
self.notification = None;
})
.unwrap_or_else(|error| {
tracing::error!("Load failed for {:?}: {}", path, error);
self.notification = Some(Box::new(Error {
message: format!("Error: {}\nPath: {}", error, path.display()),
}));
});
ctx.request_repaint();
}
/// Handles the "Open File" action via native dialog.
fn handle_open_file(&mut self, ctx: &Context) {
match self.runtime.block_on(open_file()) {
Ok(path) => self.load_file_from_path(path, ctx),
Err(PolarsViewError::FileNotFound(_)) => {
tracing::debug!("File open dialog cancelled by user.");
}
Err(e) => {
self.notification = Some(Box::new(Error {
message: e.to_string(),
}));
}
}
}
/// Detects and processes files dropped onto the application window.
fn handle_dropped_files(&mut self, ctx: &Context) {
// Collect the first valid path if a drop occurred
let dropped_path = ctx.input(|i| i.raw.dropped_files.iter().find_map(|f| f.path.clone()));
// tracing::info!(target: "polars_view", "File dropped path: {:?}", dropped_path);
if let Some(path) = dropped_path {
// Log with tracing (standard Rust idiomatic way)
tracing::info!(target: "polars_view", "File dropped: {}", path.display());
self.load_file_from_path(path, ctx);
// Request repaint ensures the UI updates to show loading state immediately
ctx.request_repaint();
}
}
/// Processes global keyboard shortcuts.
fn handle_shortcuts(&mut self, ctx: &Context) {
ctx.input_mut(|i| {
if i.consume_shortcut(&CTRL_O) {
// Open File
self.handle_open_file(ctx);
}
if i.consume_shortcut(&CTRL_S) {
// Save File
self.handle_save_file(ctx);
}
if i.consume_shortcut(&CTRL_A) {
// Save As...
self.handle_save_as(ctx);
}
});
}
/// Handles the "Save" action (Ctrl+S). Saves to the *original* file path.
fn handle_save_file(&mut self, ctx: &Context) {
// Only proceed if data is loaded.
if let Some(container) = &self.data_container {
// Clone the Arc (cheap) to pass to the async task.
let container_clone = container.clone();
// Clone context for repaint request within the task.
let ctx_clone = ctx.clone();
// Spawn the save operation onto the runtime to avoid blocking the UI.
self.runtime.spawn(async move {
if let Err(err) = save(container_clone, ctx_clone).await {
// Log error if saving fails. Error notification could also be added here
// via a channel back to the main thread if more user feedback is desired.
error!("Failed to save file: {}", err);
// TODO: Notify user of save failure via channel?
}
// Note: `save` itself now requests repaint upon completion/error.
});
}
}
/// Handles the "Save As..." action (Ctrl+A). Prompts user for a new location/format.
fn handle_save_as(&mut self, ctx: &Context) {
// Only proceed if data is loaded.
if let Some(container) = &self.data_container {
// Clone Arc and context for the async task.
let container_clone = container.clone();
let ctx_clone = ctx.clone();
// Spawn the save_as operation onto the runtime.
self.runtime.spawn(async move {
if let Err(err) = save_as(container_clone, ctx_clone).await {
// Log error if saving fails. Similar notification strategy as `handle_save_file` applies.
error!("Failed to save file using 'Save As': {}", err);
}
// Note: `save_as` itself now requests repaint upon completion/error.
});
}
}
// --- UI Rendering Methods ---
/// Renders the top menu bar (`Panel::top`).
fn render_menu_bar(&mut self, ui: &mut egui::Ui) {
MenuBar::new().ui(ui, |ui| {
ui.horizontal(|ui| {
self.render_file_menu(ui); // "File" menu
self.render_help_menu(ui); // "Help" menu
// Add space and theme switch aligned to the right.
ui.with_layout(Layout::right_to_left(egui::Align::Center), |ui| {
self.render_theme(ui);
});
});
});
}
/// Renders the "File" menu contents.
fn render_file_menu(&mut self, ui: &mut egui::Ui) {
ui.menu_button("File", |ui| {
// --- File Operations ---
// Use a Grid for alignment of buttons and shortcuts.
Grid::new("file_ops_grid")
.num_columns(2)
.spacing([20.0, 10.0]) // spacing [horizontal, vertical]
.show(ui, |ui| {
// "Open File..." button
if ui.button("Open File...").clicked() {
self.handle_open_file(ui.ctx()); // Trigger the action.
ui.close(); // Close the menu after clicking.
}
ui.label("Ctrl + O");
ui.end_row();
// "Save" button (enabled only if data is loaded)
let save_enabled = self.data_container.is_some();
if ui
.add_enabled(save_enabled, egui::Button::new("Save"))
.clicked()
{
self.handle_save_file(ui.ctx());
ui.close();
}
ui.label("Ctrl + S");
ui.end_row();
// "Save As..." button (enabled only if data is loaded)
let save_as_enabled = self.data_container.is_some();
if ui
.add_enabled(save_as_enabled, egui::Button::new("Save As..."))
.clicked()
{
self.handle_save_as(ui.ctx());
ui.close();
}
ui.label("Ctrl + A");
ui.end_row();
});
ui.separator(); // Visual separator.
// --- Application Settings & Exit ---
Grid::new("app_ops_grid")
.num_columns(2) // Simplified for fewer items.
.spacing([20.0, 10.0])
.show(ui, |ui| {
// "Settings" button (Placeholder - shows a basic notification)
if ui.button("Settings").clicked() {
self.notification = Some(Box::new(Settings {})); // Show placeholder.
ui.close();
}
ui.label(""); // Placeholder for alignment.
ui.end_row();
// "Exit" button
if ui.button("Exit").clicked() {
// Send command to close the application window.
ui.ctx().send_viewport_cmd(ViewportCommand::Close);
}
ui.label("");
ui.end_row();
});
});
}
/// Renders the "Help" menu contents.
fn render_help_menu(&mut self, ui: &mut egui::Ui) {
ui.menu_button("Help", |ui| {
let url = "https://docs.rs/polars-view";
ui.hyperlink_to("Documentation", url).on_hover_text(url);
ui.separator();
ui.menu_button("About", |ui| {
Frame::default()
.stroke(Stroke::new(1.0, Color32::GRAY))
.outer_margin(2.0)
.inner_margin(10.0)
.show(ui, |ui| {
// Retrieve package info from Cargo environment variables (set at build time).
let version = env!("CARGO_PKG_VERSION");
let authors = env!("CARGO_PKG_AUTHORS");
let description = env!("CARGO_PKG_DESCRIPTION");
let name = env!("CARGO_PKG_NAME"); // Use package name for title
// Use a Grid for structured layout.
Grid::new("about_grid")
.num_columns(1)
.spacing([10.0, 8.0])
.show(ui, |ui| {
ui.set_min_width(400.0);
ui.with_layout(Layout::top_down(egui::Align::Center), |ui| {
ui.label(
RichText::new(name)
.font(FontId::proportional(28.0))
.strong(),
);
ui.label(
RichText::new(description).font(FontId::proportional(20.0)),
);
ui.label("");
ui.label(format!("Version: {version}"));
ui.label(format!("Author: {authors}"));
});
ui.end_row();
ui.separator();
ui.end_row();
ui.horizontal(|ui| {
ui.label("Powered by");
let url = "https://github.com/pola-rs/polars";
ui.hyperlink_to("Polars", url).on_hover_text(url);
});
ui.end_row();
ui.horizontal(|ui| {
ui.label("Built with");
let url = "https://github.com/emilk/egui";
ui.hyperlink_to("egui", url).on_hover_text(url);
ui.label("&");
let url_eframe =
"https://github.com/emilk/egui/tree/master/crates/eframe";
ui.hyperlink_to("eframe", url_eframe)
.on_hover_text(url_eframe);
});
ui.end_row();
ui.horizontal(|ui| {
ui.label("Inspired by");
let url_parq = "https://github.com/Kxnr/parqbench";
ui.hyperlink_to("parqbench", url_parq)
.on_hover_text(url_parq);
});
ui.end_row();
});
});
});
});
}
/// Renders the Light/Dark theme selection radio buttons.
fn render_theme(&mut self, ui: &mut egui::Ui) {
// Determine current theme.
let mut dark_mode = ui.ctx().global_style().visuals.dark_mode; // Get boolean dark_mode state.
// Use radio buttons to select the theme.
// The `radio_value` function updates the `dark_mode` variable directly if clicked.
let dark_changed = ui
.radio_value(&mut dark_mode, true, "🌙")
.on_hover_text("Dark Theme")
.changed();
let light_changed = ui
.radio_value(&mut dark_mode, false, "🔆")
.on_hover_text("Light Theme")
.changed();
if dark_changed {
ui.ctx().set_style_init(Visuals::dark());
}
if light_changed {
ui.ctx().set_style_init(Visuals::light());
}
}
/// Renders the left side panel content.
fn render_side_panel_content(&mut self, ui: &mut egui::Ui) {
ScrollArea::vertical().show(ui, |ui| {
if let Some(file_info) = &self.file_info {
ui.collapsing("Info", |ui| {
file_info.render_metadata(ui);
});
}
ui.collapsing("Format", |ui| {
if let Some(new_format) = self.applied_format.render_format(ui)
&& let Some(data_container) = &self.data_container
{
let future = data_container.as_ref().clone().update_format(new_format);
self.run_data_future(Box::new(Box::pin(future)), ui.ctx());
}
});
ui.collapsing("Query", |ui| {
if let Some(new_filter) = self.applied_filter.render_query(ui)
&& let Some(data_container) = &self.data_container
{
let future = data_container
.as_ref()
.clone()
.load_data(new_filter, self.applied_format.clone());
self.run_data_future(Box::new(Box::pin(future)), ui.ctx());
}
});
if let Some(file_info) = &self.file_info {
ui.collapsing("Columns", |ui| {
file_info.render_schema(ui);
});
}
});
}
/// Renders the bottom status bar content.
fn render_status_bar_content(&mut self, ui: &mut egui::Ui) {
ui.horizontal(|ui| {
if let Some(container) = &self.data_container {
ui.label(format!(
"File: {}",
container.filter.absolute_path.to_string_lossy()
));
ui.separator();
ui.label(format!("Sort: {} active criteria", container.sort.len()));
} else {
ui.label("No file loaded.");
}
if self.pipe.is_some() {
ui.with_layout(Layout::right_to_left(egui::Align::Center), |ui| {
ui.spinner();
ui.label("Processing... ");
});
}
});
}
}
// --- eframe::App Implementation ---
impl eframe::App for PolarsViewApp {
/// Non-UI logic updates: handles events, async tasks, and shortcuts.
fn logic(&mut self, ctx: &Context, _frame: &mut eframe::Frame) {
// 1. Handle Drag-and-Drop
self.handle_dropped_files(ctx);
// 2. Handle global keyboard shortcuts
self.handle_shortcuts(ctx);
}
/// Primary UI rendering loop.
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
// Clone context for use in closures to satisfy the borrow checker
let ctx = ui.ctx().clone();
// Check visual notifications
self.check_notification(&ctx);
// Define top panel layout
Panel::top("top_panel").show_inside(ui, |ui| {
self.render_menu_bar(ui);
});
// Define bottom panel layout
Panel::bottom("bottom_panel").show_inside(ui, |ui| {
self.render_status_bar_content(ui);
});
// Define left side panel layout
Panel::left("side_panel")
.resizable(true)
.default_size(300.0)
.show_inside(ui, |ui| {
self.render_side_panel_content(ui);
});
// Define central panel content
CentralPanel::default().show_inside(ui, |ui| {
egui::warn_if_debug_build(ui);
let is_pending = self.check_data_pending();
ui.add_enabled_ui(!is_pending, |ui| {
match &self.data_container {
Some(data_container) => {
// Variable to capture the new sort criteria requested by header clicks
let mut opt_new_sort_criteria: Option<Vec<SortBy>> = None;
ScrollArea::horizontal()
.id_salt("central_scroll")
.auto_shrink([false, false])
.show(ui, |ui| {
opt_new_sort_criteria = data_container.render_table(ui);
});
if let Some(new_criteria) = opt_new_sort_criteria {
tracing::debug!("Sort action requested. New criteria: {:#?}", new_criteria);
let future = data_container.as_ref().clone().apply_sort(new_criteria);
self.run_data_future(Box::new(Box::pin(future)), ui.ctx());
}
}
None => {
ui.centered_and_justified(|ui| {
if is_pending {
ui.spinner();
} else {
ui.label("Open a file (File > Open or Ctrl+O) or drag & drop CSV, JSON, or Parquet files here.");
}
});
}
}
});
});
}
}