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;
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);
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)
}
}