KiThe 0.3.24

A numerical suite for chemical kinetics and thermodynamics, combustion, TGA, heat and mass transfer,chemical equilibrium, chemical engeneering
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
use crate::Kinetics::experimental_kinetics::experiment_series2::SampledColumns;
use crate::gui::experimental_kinetics_gui::model::{PlotModel, TGAGUIError};
use eframe::egui;
use kithe_plot::controller::PlotController;
use kithe_plot::controller::action::Action;
use kithe_plot::model::DataSource;
use kithe_plot::view::PlotEditorView;

// This window prepares publication/export figures. The live workflow plots are
// owned by PlotModel and rendered separately by the interactive egui plot view.

impl DataSource for SampledColumns {
    fn column(&self, name: &str) -> Option<Vec<f64>> {
        SampledColumns::column(self, name)
    }

    fn column_names(&self) -> Vec<String> {
        SampledColumns::column_names(self)
    }
}

#[derive(Default)]
pub struct KiThePlotWindowState {
    pub open: bool,
    controller: Option<PlotController>,
    view: Option<PlotEditorView>,
    font_setup_pending: bool,
    reposition_on_open: bool,
    pending_catalog_project: Option<std::path::PathBuf>,
    catalog_project_error: Option<String>,
}

impl KiThePlotWindowState {
    pub(crate) fn close_window_on_layer(&mut self, layer: Option<egui::LayerId>) -> bool {
        if self.open
            && layer.is_some_and(|layer| layer.id == egui::Id::unique(Some("KiThe Plot Redactor")))
        {
            self.open = false;
            return true;
        }
        false
    }

    pub fn open_from_model(
        &mut self,
        ctx: &egui::Context,
        model: &mut PlotModel,
    ) -> Result<(), TGAGUIError> {
        if self.open {
            let layer = egui::LayerId::new(
                egui::Order::Foreground,
                egui::Id::unique(Some("KiThe Plot Redactor")),
            );
            ctx.move_to_top(layer);
            ctx.request_repaint();
            return Ok(());
        }

        let source = model.create_data_for_plot_window()?;
        let column_names = source.column_names();
        let has_samples = column_names
            .iter()
            .any(|name| source.column(name).is_some_and(|values| !values.is_empty()));
        if column_names.len() < 2 || !has_samples {
            return Err(TGAGUIError::BindingError(
                "Not enough sampled columns to open plot redactor".to_string(),
            ));
        }

        let mut controller = PlotController::new();
        controller.load_from_data_source(&source).map_err(|err| {
            TGAGUIError::BindingError(format!("Failed to load data source: {err}"))
        })?;

        self.controller = Some(controller);
        self.view = Some(PlotEditorView::new());
        install_plot_editor_font_fallbacks(ctx);
        self.font_setup_pending = true;
        self.reposition_on_open = true;
        self.open = true;
        Ok(())
    }

    pub fn show(&mut self, ctx: &egui::Context) {
        self.show_catalog_project_confirmation(ctx);
        if !self.open {
            return;
        }

        if self.font_setup_pending {
            self.font_setup_pending = false;
            ctx.request_repaint();
            return;
        }

        let Some(controller) = self.controller.as_mut() else {
            self.open = false;
            return;
        };
        let Some(view) = self.view.as_mut() else {
            self.open = false;
            return;
        };

        let available = ctx.content_rect();
        let size = egui::vec2(
            available.width().min(1200.0).max(1.0),
            available.height().min(860.0).max(1.0),
        );
        let position = egui::pos2(
            (available.center().x - size.x * 0.5).max(available.left()),
            (available.center().y - size.y * 0.5).max(available.top()),
        );

        let mut window = egui::Window::new("KiThe Plot Redactor")
            .open(&mut self.open)
            .order(egui::Order::Foreground)
            .resizable(true)
            .default_pos(position)
            .default_size(size)
            .min_size([size.x.min(480.0), size.y.min(360.0)])
            .constrain_to(available);
        if self.reposition_on_open {
            window = window.current_pos(position);
            self.reposition_on_open = false;
        }
        window.show(ctx, |ui| {
            let actions = view.draw(ui, controller);
            for action in actions {
                let _ = controller.dispatch(action);
            }
        });

        if !self.open {
            self.controller = None;
            self.view = None;
        }
    }

    pub fn open_catalog_project(
        &mut self,
        ctx: &egui::Context,
        path: &std::path::Path,
    ) -> Result<(), String> {
        if self
            .controller
            .as_ref()
            .is_some_and(PlotController::has_unsaved_changes)
        {
            self.pending_catalog_project = Some(path.to_path_buf());
            self.catalog_project_error = None;
            self.open = true;
            return Ok(());
        }
        self.load_catalog_project(ctx, path)
    }

    fn load_catalog_project(
        &mut self,
        ctx: &egui::Context,
        path: &std::path::Path,
    ) -> Result<(), String> {
        let mut controller = PlotController::new();
        controller
            .dispatch(Action::OpenProject {
                path: path.to_string_lossy().into_owned(),
            })
            .map_err(|error| format!("Could not open KiThePlot project: {error}"))?;

        self.controller = Some(controller);
        self.view = Some(PlotEditorView::new());
        install_plot_editor_font_fallbacks(ctx);
        self.font_setup_pending = true;
        self.reposition_on_open = true;
        self.open = true;
        self.pending_catalog_project = None;
        self.catalog_project_error = None;
        Ok(())
    }

    fn show_catalog_project_confirmation(&mut self, ctx: &egui::Context) {
        if self.pending_catalog_project.is_none() {
            return;
        }

        let mut discard_and_open = false;
        let mut cancel = false;
        egui::Window::new("Open catalog plot project?")
            .collapsible(false)
            .resizable(false)
            .show(ctx, |ui| {
                ui.label(
                    "The Plot Editor has unsaved changes. Opening this project will discard them.",
                );
                if let Some(error) = &self.catalog_project_error {
                    ui.colored_label(egui::Color32::RED, error);
                }
                ui.horizontal(|ui| {
                    discard_and_open = ui.button("Discard changes and open").clicked();
                    cancel = ui.button("Cancel").clicked();
                });
            });

        if cancel {
            self.pending_catalog_project = None;
            self.catalog_project_error = None;
            return;
        }
        if discard_and_open && let Some(path) = self.pending_catalog_project.clone() {
            if let Err(error) = self.load_catalog_project(ctx, &path) {
                self.catalog_project_error = Some(error);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Kinetics::experimental_kinetics::experiment_series_main::{
        ExperimentMeta, ExperimentThermalMode,
    };
    use crate::Kinetics::experimental_kinetics::testing_mod::VirtualTGA;
    use kithe_plot::controller::PlotController;

    #[test]
    fn editor_accepts_columns_with_different_lengths() {
        let source = SampledColumns::new(
            vec![vec![0.0, 1.0, 2.0, 3.0], vec![10.0, 20.0]],
            vec!["time".into(), "short_mass".into()],
        );
        let mut controller = PlotController::new();
        controller
            .load_from_data_source(&source)
            .expect("ragged columns should load into KiThePlot");

        assert_eq!(controller.column_len("time"), Some(4));
        assert_eq!(controller.column_len("short_mass"), Some(2));
        assert_eq!(controller.data_summary().unwrap().max_column_len, 4);
    }

    #[test]
    fn reopening_editor_preserves_the_existing_runtime_session() {
        let data = VirtualTGA {
            time: (0..40).map(|index| index as f64).collect(),
            temperature: vec![500.0; 40],
            mass: (0..40).map(|index| 100.0 - index as f64).collect(),
        };
        let mut model = PlotModel::default();
        model
            .series
            .create_from_synthetic_data(
                &data,
                ExperimentMeta {
                    id: "editor_session".into(),
                    isothermal_temperature: Some(500.0),
                    thermal_mode: ExperimentThermalMode::Isothermal,
                    ..ExperimentMeta::default()
                },
            )
            .unwrap();
        model.set_x("editor_session", "time").unwrap();
        model.set_y("editor_session", "mass").unwrap();
        model.create_points_for_curve("editor_session").unwrap();

        let ctx = egui::Context::default();
        let mut editor = KiThePlotWindowState::default();
        ctx.begin_pass(Default::default());
        editor.open_from_model(&ctx, &mut model).unwrap();
        let mut output = ctx.end_pass();
        output.textures_delta.clear();
        let controller_before = editor.controller.as_ref().unwrap() as *const _;
        ctx.begin_pass(Default::default());
        editor.open_from_model(&ctx, &mut model).unwrap();
        let mut output = ctx.end_pass();
        output.textures_delta.clear();
        let controller_after = editor.controller.as_ref().unwrap() as *const _;

        assert_eq!(controller_before, controller_after);
        assert!(editor.open);
    }

    #[test]
    fn catalog_project_opens_inside_editor_and_keeps_embedded_data() {
        let directory = tempfile::tempdir().unwrap();
        let project_path = directory.path().join("publication.kplot");
        let source = SampledColumns::new(
            vec![vec![0.0, 1.0], vec![4.0, 5.0]],
            vec!["time".into(), "mass".into()],
        );
        let mut writer = PlotController::new();
        writer.load_from_data_source(&source).unwrap();
        writer
            .dispatch(Action::SaveProject {
                path: project_path.to_string_lossy().into_owned(),
                dimensions: kithe_plot::model::PublicationDimensions::default(),
            })
            .unwrap();

        let context = egui::Context::default();
        let mut editor = KiThePlotWindowState::default();
        context.begin_pass(Default::default());
        editor
            .open_catalog_project(&context, &project_path)
            .unwrap();
        let mut output = context.end_pass();
        output.textures_delta.clear();

        let controller = editor.controller.as_ref().unwrap();
        assert!(editor.open);
        assert_eq!(controller.column_len("time"), Some(2));
        assert_eq!(controller.column_len("mass"), Some(2));
        assert!(editor.pending_catalog_project.is_none());
    }

    #[test]
    fn invalid_catalog_project_does_not_replace_the_current_plot() {
        let directory = tempfile::tempdir().unwrap();
        let invalid_path = directory.path().join("invalid.kplot");
        std::fs::write(&invalid_path, "not a project").unwrap();
        let source = SampledColumns::new(
            vec![vec![0.0, 1.0], vec![4.0, 5.0]],
            vec!["time".into(), "mass".into()],
        );
        let mut current = PlotController::new();
        current.load_from_data_source(&source).unwrap();
        let before = current.data_summary();
        let mut editor = KiThePlotWindowState {
            controller: Some(current),
            view: Some(PlotEditorView::new()),
            open: true,
            ..KiThePlotWindowState::default()
        };

        let error = editor
            .load_catalog_project(&egui::Context::default(), &invalid_path)
            .unwrap_err();

        assert!(error.contains("Could not open KiThePlot project"));
        assert_eq!(editor.controller.as_ref().unwrap().data_summary(), before);
        assert!(editor.open);
    }

    #[test]
    fn opening_catalog_project_with_unsaved_edits_requires_confirmation() {
        let directory = tempfile::tempdir().unwrap();
        let project_path = directory.path().join("pending.kplot");
        let source = SampledColumns::new(
            vec![vec![0.0, 1.0], vec![4.0, 5.0]],
            vec!["time".into(), "mass".into()],
        );
        let mut writer = PlotController::new();
        writer.load_from_data_source(&source).unwrap();
        writer
            .dispatch(Action::SaveProject {
                path: project_path.to_string_lossy().into_owned(),
                dimensions: kithe_plot::model::PublicationDimensions::default(),
            })
            .unwrap();
        let mut editor = KiThePlotWindowState::default();
        let context = egui::Context::default();
        editor.controller = Some(writer);

        // A subsequent edit makes replacement destructive and must be confirmed.
        editor
            .controller
            .as_mut()
            .unwrap()
            .dispatch(Action::SetChartTitle("unsaved".into()))
            .unwrap();
        let current_summary = editor.controller.as_ref().unwrap().data_summary();
        editor
            .open_catalog_project(&context, &project_path)
            .unwrap();

        assert_eq!(
            editor.pending_catalog_project.as_deref(),
            Some(project_path.as_path())
        );
        assert_eq!(
            editor.controller.as_ref().unwrap().data_summary(),
            current_summary
        );
    }
}

fn install_plot_editor_font_fallbacks(ctx: &egui::Context) {
    let mut fonts = ctx.fonts(|fonts| fonts.definitions().clone());
    let proportional_fallbacks = fonts
        .families
        .get(&egui::FontFamily::Proportional)
        .cloned()
        .unwrap_or_default();
    for family in ["KiThePlot Sans", "KiThePlot Serif", "KiThePlot Mono"] {
        fonts.families.insert(
            egui::FontFamily::Name(family.into()),
            proportional_fallbacks.clone(),
        );
    }
    ctx.set_fonts(fonts);
}

impl PlotModel {
    pub fn create_data_for_plot_window(&mut self) -> Result<SampledColumns, TGAGUIError> {
        let (_, sampled) = self.column_samples_for_all_experiment_for_plotting(500)?;
        Ok(sampled)
    }
}