SedSat3 1.1.6
Sediment Source Apportionment Tool - Advanced statistical methods for environmental pollution research
Loading...
Searching...
No Matches
mainwindow.cpp
Go to the documentation of this file.
1// SedSAT3 – Sediment Source Assessment Tool, version 3
2// U.S. Geological Survey. See LICENSE.md and DISCLAIMER.md in the repository root.
3
4#include "mainwindow.h"
5#include "numericparsing.h"
6#include "excelimport.h"
7#include "ui_mainwindow.h"
8
9#include "QDebug"
10#include "QFileDialog"
11#include "QDir"
12#include "sourcesinkdata.h"
13#include "xlsxdocument.h"
14#include "xlsxchartsheet.h"
15#include "xlsxcellrange.h"
16#include "xlsxchart.h"
17#include "xlsxrichstring.h"
18#include "xlsxworkbook.h"
20#include "plotwindow.h"
21#include "QMessageBox"
22#include "Utilities.h"
23#include "QMap"
24#include "QJsonDocument"
26#include "elementstablemodel.h"
28#include "genericform.h"
29#include "ProgressWindow.h"
30#include "resultswindow.h"
31#include "aboutdialog.h"
32#include "resultsetitem.h"
33#include "resultitem.h"
34#include "selectsamples.h"
36#include "toolboxitem.h"
37#include "resulttableviewer.h"
38#include "optionsdialog.h"
39#include <QInputDialog>
40#include <QStandardPaths>
41//#include "MCMC.h"
42
43#ifdef _WIN32
44#define NOBYTE
45//#include <windows.h>
46
47//#pragma comment(lib "shell32.lib")
48#endif
49
50#define RECENT "SedSatrecentFiles.txt"
51
52#ifndef max_num_recent_files
53#define max_num_recent_files 15
54#endif
55
56
57#define version "1.1.8"
58#define date_compiled "10/28/2026"
59
60using namespace QXlsx;
61
62MainWindow::MainWindow(QWidget* parent)
63 : QMainWindow(parent),
64 ui(new Ui::MainWindow),
65 sinkSheet(-1),
66 plotter(nullptr),
67 columnViewModel(nullptr),
68 resultsViewModel(nullptr),
69 ResultscontextMenu(nullptr),
70 DeleteAction(nullptr),
73 conductor(nullptr)
74{
75 ui->setupUi(this);
76
77 // Set window icon
78 QIcon mainIcon(resourcesPath() + "Icons/CMBSource_Icon.png");
79 setWindowIcon(mainIcon);
80
81 // Initialize conductor. It reports warnings and progress through the host
82 // rather than reaching into this window directly, so that the same
83 // analyses can run with no interface present.
84 analysis_host = std::make_unique<GuiHost>(this);
85 conductor = std::make_unique<Conductor>(analysis_host.get());
86 conductor->SetWorkingFolder(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation));
87
88 // Setup UI components
93
94 // Initialize other components
95 centralform.reset(ui->textBrowser);
96
97 // Load recent files
99}
100
102{
103 // Menu actions - File operations
104 connect(ui->actionImport_Elemental_Profile_from_Excel, &QAction::triggered,
106 connect(ui->actionSave_Project, &QAction::triggered,
108 connect(ui->actionSave_As, &QAction::triggered,
110 connect(ui->actionOpen_Project, &QAction::triggered,
112
113 // Menu actions - Plotting
114 connect(ui->actionRaw_Elemental_Profiles, &QAction::triggered,
116
117 // Menu actions - Data operations
118 connect(ui->actionConstituent_Properties, &QAction::triggered,
120 connect(ui->actionTarget_Group, &QAction::triggered,
122 connect(ui->actionInclude_Exclude_Samples, &QAction::triggered,
124 connect(ui->actionOrganic_Matter_Size_correction, &QAction::triggered,
126
127 // Menu actions - Help and settings
128 connect(ui->actionAbout, &QAction::triggered,
130 connect(ui->actionOptions, &QAction::triggered,
132
133 // Toolbar buttons
134 connect(ui->ShowTabular, &QPushButton::clicked,
136 connect(ui->btnZoom, &QPushButton::clicked,
138
139 // Tree views
140 connect(ui->treeViewtools, &QTreeView::doubleClicked,
142 connect(ui->TreeView_Results, &QTreeView::doubleClicked,
144
145 // Results context menu
146 connect(ui->TreeView_Results, &QWidget::customContextMenuRequested,
148 connect(DeleteAction, &QAction::triggered,
150}
151
153{
154 // Load tools configuration from JSON
155 QString toolsPath = resourcesPath() + + "/tools.json";
156 // qDebug() << "Loading tools from:" << toolsPath;
157
158 QJsonDocument tools = loadJson(toolsPath);
159 QStandardItemModel* toolsModel = ToQStandardItemModel(tools);
160 toolsModel->setHorizontalHeaderLabels(QStringList() << "Tools");
161
162 ui->treeViewtools->setModel(toolsModel);
163 ui->treeViewtools->setEditTriggers(QAbstractItemView::NoEditTriggers);
164
165 // Load forms structure
166 QString formsPath = resourcesPath() + "/forms_structures.json";
167 formsstructure = loadJson(formsPath);
168
169 // Configure tree view settings
170 ui->treeView->setSelectionMode(QAbstractItemView::MultiSelection);
171 ui->verticalLayout_3->setContentsMargins(0, 0, 0, 0);
172 ui->verticalLayout_3->setSpacing(0);
173
174 // If the frame has its own layout, reduce its margins too
175 if (ui->frame->layout())
176 {
177 ui->frame->layout()->setContentsMargins(2, 2, 2, 2);
178 ui->frame->layout()->setSpacing(2);
179 }
180
181 ui->frame->setVisible(false);
182}
183
185{
186 // Initialize results model
187 resultsViewModel.reset(new QStandardItemModel());
188 resultsViewModel->setHorizontalHeaderLabels(QStringList() << "Results");
189
190 ui->TreeView_Results->setModel(resultsViewModel.get());
191 ui->TreeView_Results->setContextMenuPolicy(Qt::CustomContextMenu);
192
193 // Setup context menu
194 ResultscontextMenu = new QMenu(ui->TreeView_Results);
195 DeleteAction = new QAction("Delete", ResultscontextMenu);
197}
198
200{
201 // Setup table view button
202 QIcon iconTable(resourcesPath()+"/Icons/table.png");
203 ui->ShowTabular->setIcon(iconTable);
204 ui->ShowTabular->setEnabled(false);
205
206 // Setup zoom button
207 QIcon iconZoom(resourcesPath()+"/Icons/Zoom_Extends.png");
208 ui->btnZoom->setIcon(iconZoom);
209 ui->btnZoom->setEnabled(false);
210
211 // Call existing toolbar population method
213}
214
216{
217 // plotter is added to layout, so Qt handles it
218 // ui is deleted explicitly as always
219 delete ui;
220}
221
222QString MainWindow::getSaveFilePath(bool promptUser)
223{
224 // Use existing project file name if available and not prompting
225 if (!promptUser && !ProjectFileName.isEmpty())
226 {
227 return ProjectFileName;
228 }
229
230 // Show save file dialog
231 QString fileName = QFileDialog::getSaveFileName(
232 this,
233 tr("Save Project"),
234 ProjectFileName, // Simplified - empty QString is fine
235 tr("CMB Source file (*.cmb);;All files (*.*)"),
236 nullptr,
237 QFileDialog::DontUseNativeDialog
238 );
239
240 // User canceled
241 if (fileName.isEmpty())
242 {
243 return QString();
244 }
245
246 // Ensure .cmb extension
247 if (!fileName.toLower().endsWith(".cmb"))
248 {
249 fileName += ".cmb";
250 }
251
252 return fileName;
253}
254
256{
257 QJsonObject resultsJson;
258
259 if (!resultsViewModel)
260 {
261 return resultsJson;
262 }
263
264 for (int i = 0; i < resultsViewModel->rowCount(); ++i)
265 {
266 QStandardItem* item = resultsViewModel->item(i, 0);
267 if (!item)
268 {
269 continue;
270 }
271
272 ResultSetItem* resultSetItem = dynamic_cast<ResultSetItem*>(item);
273 if (!resultSetItem || !resultSetItem->result)
274 {
275 qWarning() << "Invalid result item at row" << i;
276 continue;
277 }
278
279 resultsJson[resultSetItem->text()] = resultSetItem->result->toJsonObject();
280 }
281
282 return resultsJson;
283}
284
286{
287 QJsonObject projectJson;
288
289 projectJson["Element Information"] = Data()->ElementInformationToJsonObject();
290 projectJson["Element Data"] = Data()->ElementDataToJsonObject();
291 projectJson["Target Group"] = QString::fromStdString(Data()->GetTargetGroup());
292 projectJson["Tools used"] = Data()->ToolsUsedToJsonObject();
293 projectJson["Options"] = Data()->OptionsToJsonObject();
294 projectJson["Results"] = buildResultsJson();
295
296 return projectJson;
297}
298
299bool MainWindow::saveProjectToFile(const QString& filePath)
300{
301 QFile file(filePath);
302
303 if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
304 {
305 QMessageBox::critical(
306 this,
307 tr("Save Error"),
308 tr("Could not open file for writing:\n%1\n\nError: %2")
309 .arg(filePath)
310 .arg(file.errorString())
311 );
312 return false;
313 }
314
315 // Set working folder based on file location
316 QFileInfo fileInfo(file);
317 conductor->SetWorkingFolder(fileInfo.absolutePath());
318
319 // Build and write JSON
320 QJsonObject projectJson = buildProjectJson();
321 QJsonDocument jsonDocument(projectJson);
322
323 qint64 bytesWritten = file.write(jsonDocument.toJson());
324 file.close();
325
326 if (bytesWritten == -1)
327 {
328 QMessageBox::critical(
329 this,
330 tr("Save Error"),
331 tr("Error writing to file:\n%1\n\nError: %2")
332 .arg(filePath)
333 .arg(file.errorString())
334 );
335 return false;
336 }
337
338 // Update project state
339 ProjectFileName = filePath;
340 addToRecentFiles(filePath, true);
341
342 return true;
343}
344
346{
347 QString filePath = getSaveFilePath(false);
348
349 if (filePath.isEmpty())
350 {
351 return; // User canceled
352 }
353
354 if (saveProjectToFile(filePath))
355 {
356 statusBar()->showMessage(tr("Project saved successfully"), 3000);
357 }
358}
359
361{
362 QString filePath = getSaveFilePath(true);
363
364 if (filePath.isEmpty())
365 {
366 return; // User canceled
367 }
368
369 if (saveProjectToFile(filePath))
370 {
371 statusBar()->showMessage(tr("Project saved successfully"), 3000);
372 }
373}
374
376{
377 QString fileName = QFileDialog::getOpenFileName(
378 this,
379 tr("Open Project"),
380 ProjectFileName, // Start in same directory as current project
381 tr("CMB Source file (*.cmb);;All files (*.*)"),
382 nullptr,
383 QFileDialog::DontUseNativeDialog
384 );
385
386 if (fileName.isEmpty())
387 {
388 return;
389 }
390
391 if (LoadModel(fileName))
392 {
393 addToRecentFiles(fileName, true);
394 statusBar()->showMessage(tr("Project opened successfully"), 3000);
395 }
396}
397
398bool MainWindow::LoadModel(const QString& fileName)
399{
400 QFile file(fileName);
401
402 if (!file.open(QIODevice::ReadOnly))
403 {
404 QMessageBox::critical(
405 this,
406 tr("Load Error"),
407 tr("Could not open file for reading:\n%1\n\nError: %2")
408 .arg(fileName)
409 .arg(file.errorString())
410 );
411 return false;
412 }
413
414 // Read and parse JSON
415 QByteArray fileData = file.readAll();
416 file.close();
417
418 QJsonDocument jsonDoc = QJsonDocument::fromJson(fileData);
419 if (jsonDoc.isNull())
420 {
421 QMessageBox::critical(
422 this,
423 tr("Load Error"),
424 tr("Invalid JSON format in file:\n%1")
425 .arg(fileName)
426 );
427 return false;
428 }
429
430 QJsonObject jsonObject = jsonDoc.object();
431
432 // Set working directory
433 QFileInfo fileInfo(fileName);
434 conductor->SetWorkingFolder(fileInfo.absolutePath());
435
436 // Load data
437 if (!file.open(QIODevice::ReadOnly))
438 {
439 QMessageBox::critical(
440 this,
441 tr("Load Error"),
442 tr("Could not open the project:\n%1\n\n%2")
443 .arg(fileName)
444 .arg(file.errorString())
445 );
446 return false;
447 }
448 const bool loaded = Data()->ReadFromFile(&file);
449 file.close();
450 if (!loaded)
451 {
452 QMessageBox::critical(
453 this,
454 tr("Load Error"),
455 tr("Could not load the project:\n%1\n\n%2")
456 .arg(fileName)
457 .arg(Data()->LoadError())
458 );
459 return false;
460 }
461
462 // Projects saved after an Excel import by builds before 10/24/2026 have
463 // no target group (the import cleared it), and every tool that uses the
464 // target samples failed on them. Ask for it instead.
465 if (Data()->count(Data()->GetTargetGroup()) == 0 && !Data()->empty())
466 {
467 QStringList groupNames;
468 for (const std::string& groupName : Data()->GetGroupNames())
469 groupNames << QString::fromStdString(groupName);
470 bool ok = false;
471 const QString target = QInputDialog::getItem(
472 this,
473 tr("Target group"),
474 tr("This project does not say which group holds the target samples.\n"
475 "Select it (save the project afterwards to keep it):"),
476 groupNames, 0, false, &ok);
477 if (ok && !target.isEmpty())
478 Data()->SetTargetGroup(target.toStdString());
479 else
480 QMessageBox::warning(
481 this,
482 tr("Target group"),
483 tr("No target group is set, so the tools that use the target samples will not run."));
484 }
485
486 // Load results
487 QJsonObject resultsJson = jsonObject["Results"].toObject();
488 resultsViewModel->clear();
489 resultsViewModel->setHorizontalHeaderLabels(QStringList() << "Results");
490
491 for (const QString& key : resultsJson.keys())
492 {
493 ResultSetItem* resultSet = new ResultSetItem(key);
494 resultSet->setToolTip(key);
495 resultSet->result = new Results();
496 resultSet->result->ReadFromJson(resultsJson.value(key).toObject());
497
498 // Process MLR results
499 for (auto it = resultSet->result->begin(); it != resultSet->result->end(); ++it)
500 {
501 if (it->second.Type() == result_type::mlrset)
502 {
503 QStringList parts = QString::fromStdString(it->first).split("OM & Size MLR for ");
504 if (parts.size() > 1)
505 {
506 std::string source = parts[1].toStdString();
507 if (Data()->count(source) > 0)
508 {
509 Data()->at(source).SetRegressionModels(
510 static_cast<MultipleLinearRegressionSet*>(it->second.Result())
511 );
513 Data()->at(source).GetRegressionModels()->begin()->second.GetIndependentVariableNames()
514 );
515 }
516 }
517 }
518 }
519
520 resultsViewModel->appendRow(resultSet);
521 }
522
523 // Finalize data
524 dataCollection.PopulateElementDistributions();
525 dataCollection.AssignAllDistributions();
527
528 // Update UI state
529 ProjectFileName = fileName;
530 setWindowTitle("SedSat3: " + ProjectFileName);
531
532 ui->ShowTabular->setEnabled(true);
533 ui->btnZoom->setEnabled(true);
534 return true;
535}
536
538{
539 QString fileName = QFileDialog::getOpenFileName(
540 this,
541 tr("Open Excel File"),
542 ProjectFileName.isEmpty() ? "" : QFileInfo(ProjectFileName).absolutePath(),
543 tr("Excel files (*.xlsx);;All files (*.*)"),
544 nullptr,
545 QFileDialog::DontUseNativeDialog
546 );
547
548 if (fileName.isEmpty())
549 {
550 return; // User canceled
551 }
552
553 QFileInfo fileInfo(fileName);
554 conductor->SetWorkingFolder(fileInfo.absolutePath());
555
556 if (ReadExcel(fileName))
557 {
559
560 QMessageBox::information(
561 this,
562 tr("Element Selection"),
563 tr("Set each constituent's type in this table. To exclude a constituent from the analysis, click its box in the 'Include in analysis' column.\n\nTo include or exclude samples, use Settings > Include/Exclude Samples."),
564 QMessageBox::Ok
565 );
566
568 }
569}
571{
572 // Create new model
573 columnViewModel = std::make_unique<QStandardItemModel>();
574 columnViewModel->setColumnCount(1);
575 columnViewModel->setHorizontalHeaderLabels(QStringList() << "Data");
576
577 // Add samples item
578 QList<QStandardItem*> modelItems;
579 modelItems.append(ToQStandardItem("Samples", &dataCollection));
580 columnViewModel->appendRow(modelItems);
581
582 // Add elements item
583 QList<QStandardItem*> elementItems;
584 elementItems.append(ElementsToQStandardItem("Elements", &dataCollection));
585 columnViewModel->appendRow(elementItems);
586
587 // Set model on tree view
588 ui->treeView->setModel(columnViewModel.get());
589 ui->treeView->setContextMenuPolicy(Qt::CustomContextMenu);
590
591 // Connect signals - modern Qt5 syntax
592 connect(ui->treeView->selectionModel(), &QItemSelectionModel::selectionChanged,
594 connect(ui->treeView, &QWidget::customContextMenuRequested,
596}
598{
599 PlotWindow *plotwindow = new PlotWindow(this);
600 plotwindow->show();
601}
602
603bool MainWindow::ReadExcel(const QString& filename)
604{
605 // Load Excel file
606 Document xlsxR(filename);
607 if (!xlsxR.load())
608 {
609 QMessageBox::critical(
610 this,
611 tr("Excel Load Error"),
612 tr("Failed to load Excel file:\n%1").arg(filename)
613 );
614 return false;
615 }
616
617 // qDebug() << "[debug] Successfully loaded xlsx file.";
618 QStringList allSheetNames = xlsxR.sheetNames();
619
620 // Clear existing data
621 dataCollection.Clear();
622
623 // Let user select sheets to import
624 QStringList* sheetsToInclude = nullptr;
625 auto chooseSheetsDlg = std::make_unique<DialogChooseExcelSheets>(this, &sheetsToInclude);
626
627 for (const QString& sheetName : allSheetNames)
628 {
629 chooseSheetsDlg->AddItem(sheetName);
630 // qDebug() << sheetName;
631 }
632
633 chooseSheetsDlg->exec();
634
635 if (!sheetsToInclude)
636 {
637 return false; // User canceled
638 }
639
640 // Filter selected sheets
641 QStringList selectedSheets;
642 for (const QString& sheetName : allSheetNames)
643 {
644 if (sheetsToInclude->contains(sheetName))
645 {
646 selectedSheets << sheetName;
647 }
648 }
649 delete sheetsToInclude;
650
651 if (selectedSheets.isEmpty())
652 {
653 return false; // No sheets selected
654 }
655
656 // Let user indicate which sheet is the sink
657 sinkSheet = -1;
658 auto indicateSheetDlg = std::make_unique<IndicateSheetsDialog>(this);
659 indicateSheetDlg->Populate_Table(selectedSheets);
660 if (indicateSheetDlg->exec() != QDialog::Accepted
661 || sinkSheet < 0 || sinkSheet >= selectedSheets.count())
662 {
663 return false; // User canceled
664 }
665
666 // Read the sheets; the checks and their messages are in excelimport.cpp
667 ExcelImportError importError;
668 if (!ImportExcelSheets(xlsxR, selectedSheets, dataCollection, importError))
669 {
670 QMessageBox::warning(this, importError.title, importError.message);
671 WriteMessageOnScreen(importError.message, Qt::red);
672 return false;
673 }
674
675 // ImportExcelSheets starts by clearing the data, which also clears the
676 // target group the sheet dialog set, so set it again here. Without it
677 // every analysis that looks up the target group failed after an import.
678 dataCollection.SetTargetGroup(selectedSheets[sinkSheet].toStdString());
679
680 // qDebug() << "Reading element information done!";
681
682 return true;
683}
684
685void MainWindow::WriteMessageOnScreen(const QString &text, QColor color)
686{
687 ui->textBrowser->setTextColor(color);
688 ui->textBrowser->append(text);
689}
690
691QStandardItem* MainWindow::ToQStandardItem(const QString& key, const SourceSinkData* /*srcsinkdata*/)
692{
693 QStandardItem* rootItem = new QStandardItem(key);
694 rootItem->setData("RootItem", Qt::UserRole);
695
696 vector<string> groupNames = dataCollection.GetGroupNames();
697
698 for (size_t i = 0; i < groupNames.size(); ++i)
699 {
700 QStandardItem* groupItem = new QStandardItem(QString::fromStdString(groupNames[i]));
701 groupItem->setData("Group", Qt::UserRole);
702 groupItem->setData(QString::fromStdString(groupNames[i]), groupRole);
703
704 Elemental_Profile_Set* sampleSet = dataCollection.GetSampleSet(groupNames[i]);
705 if (sampleSet)
706 {
707 for (auto it = sampleSet->begin(); it != sampleSet->end(); ++it)
708 {
709 QStandardItem* sampleItem = new QStandardItem(QString::fromStdString(it->first));
710 sampleItem->setData("Sample", Qt::UserRole);
711 sampleItem->setData(QString::fromStdString(groupNames[i]), groupRole);
712 sampleItem->setData(QString::fromStdString(it->first), sampleRole);
713
714 groupItem->appendRow(sampleItem);
715 }
716 }
717
718 rootItem->appendRow(groupItem);
719 }
720
721 return rootItem;
722}
723
724QStandardItem* MainWindow::ElementsToQStandardItem(const QString& key, const SourceSinkData* /*srcsinkdata*/)
725{
726 QStandardItem* rootItem = new QStandardItem(key);
727 rootItem->setData("RootItem", Qt::UserRole);
728
729 vector<string> groupNames = dataCollection.GetGroupNames();
730 vector<string> elementNames = dataCollection.GetElementNames();
731
732 for (size_t elemIdx = 0; elemIdx < elementNames.size(); ++elemIdx)
733 {
734 QStandardItem* elementItem = new QStandardItem(QString::fromStdString(elementNames[elemIdx]));
735 elementItem->setData("Element", Qt::UserRole);
736 elementItem->setData(QString::fromStdString(elementNames[elemIdx]), elementRole);
737
738 for (size_t groupIdx = 0; groupIdx < groupNames.size(); ++groupIdx)
739 {
740 QStandardItem* groupItem = new QStandardItem(QString::fromStdString(groupNames[groupIdx]));
741 groupItem->setData("GroupInElements", Qt::UserRole);
742 groupItem->setData(QString::fromStdString(elementNames[elemIdx]), elementRole);
743 groupItem->setData(QString::fromStdString(groupNames[groupIdx]), groupRole);
744
745 elementItem->appendRow(groupItem);
746 }
747
748 rootItem->appendRow(elementItem);
749 }
750
751 return rootItem;
752}
753
754QStandardItemModel* MainWindow::ToQStandardItemModel(const SourceSinkData* /*srcsinkdata*/)
755{
756 columnViewModel = std::make_unique<QStandardItemModel>();
757 columnViewModel->setColumnCount(1);
758 columnViewModel->setHorizontalHeaderLabels(QStringList() << "Groups");
759
760 vector<string> groupNames = dataCollection.GetGroupNames();
761
762 for (size_t i = 0; i < groupNames.size(); ++i)
763 {
764 QStandardItem* groupItem = new QStandardItem(QString::fromStdString(groupNames[i]));
765 groupItem->setData("Parent", Qt::UserRole);
766
767 Elemental_Profile_Set* sampleSet = dataCollection.GetSampleSet(groupNames[i]);
768 if (sampleSet)
769 {
770 for (auto it = sampleSet->begin(); it != sampleSet->end(); ++it)
771 {
772 QStandardItem* sampleItem = new QStandardItem(QString::fromStdString(it->first));
773 sampleItem->setData(QString::fromStdString(it->first), elementRole);
774 sampleItem->setData(QString::fromStdString(groupNames[i]), groupRole);
775 sampleItem->setData("Child", Qt::UserRole);
776
777 groupItem->appendRow(sampleItem);
778 }
779 }
780
781 columnViewModel->appendRow(groupItem);
782 }
783
784 return columnViewModel.get();
785}
786void MainWindow::on_tree_selectionChanged(const QItemSelection &changed)
787{
788 // qDebug()<<"Selection changed "<<changed;
789 ui->ShowTabular->setEnabled(false);
791 if (plotter==nullptr)
792 {
793#ifdef USE_QCHARTS
794 plotter = new GeneralChartPlotter(this);
795#else
796 plotter = new GeneralPlotter(this);
797#endif // USE_QCHARTS
798
799 ui->verticalLayout_3->addWidget(plotter);
800
801 }
802 plotter->Clear();
803 enum class plottype {elemental_profiles, element_scatters} PlotType = plottype::elemental_profiles;
804 vector<vector<string>> samples_selected;
805 QModelIndexList indexes = ui->treeView->selectionModel()->selectedIndexes();
806 if (changed.size()>0)
807 { QModelIndex changed_index = changed.at(0).indexes()[0];
808 if (indexes.size()>0)
809 { if (indexes.contains(changed.at(0).indexes()[0]))
810 if (changed.at(0).indexes()[0].data(Qt::UserRole)!=selectedTreeItemType && selectedTreeItemType!="None")
811 {
812 selectedTreeItemType = changed.at(0).indexes()[0].data(Qt::UserRole).toString();
814 ui->treeView->selectionModel()->clearSelection();
815 ui->treeView->selectionModel()->select(changed_index,QItemSelectionModel::Select | QItemSelectionModel::Rows);
817 indexes = ui->treeView->selectionModel()->selectedIndexes();
818 }
819 }
820 }
821 for (int i=0; i<indexes.size(); i++)
822 {
823 // qDebug()<<indexes[i].data(Qt::UserRole).toString();
824 if (indexes[i].data(Qt::UserRole).toString()=="Group")
825 {
826 QString Group_Name_Selected = indexes[i].data().toString();
827 vector<string> Sample_Names = dataCollection.GetSampleSet(Group_Name_Selected.toStdString())->GetSampleNames();
828 for (int sample_counter=0; sample_counter<Sample_Names.size(); sample_counter++)
829 {
830 vector<string> item;
831 item.push_back(indexes[i].data().toString().toStdString());
832 item.push_back(ui->treeView->selectionModel()->model()->index(sample_counter,0, indexes[i]).data().toString().toStdString());
833 samples_selected.push_back(item);
834 }
835 }
836 else if (indexes[i].data(Qt::UserRole).toString()=="Sample")
837 {
838 vector<string> item;
839 item.push_back(indexes[i].parent().data().toString().toStdString());
840 item.push_back(indexes[i].data().toString().toStdString());
841 samples_selected.push_back(item);
842 }
843 if (indexes[i].data(Qt::UserRole).toString()=="Element")
844 {
845 // qDebug()<<"Element selected!";
846 PlotType = plottype::element_scatters;
847 QString Element_Name_Selected = indexes[i].data().toString();
848 map<string,vector<double>> extracted_data = dataCollection.ExtractElementDataByGroup(Element_Name_Selected.toStdString());
849 // qDebug()<<"Data extracted!";
850 if (plotter==nullptr)
851 {
852#ifdef USE_QCHARTS
853 plotter = new GeneralChartPlotter(this);
854#else
855 plotter = new GeneralPlotter(this);
856#endif // USE_QCHARTS
857 ui->verticalLayout_3->addWidget(plotter);
858
859 }
860
861 plotter->AddNonUniformScatter(extracted_data,i,8,Element_Name_Selected.toStdString());
862 // A log axis cannot show zero or negative values (e.g. delta 13C),
863 // which used to leave such a constituent's plot empty
864 bool all_positive = true;
865 for (const auto& [group, values] : extracted_data)
866 for (double value : values)
867 if (!(value > 0))
868 all_positive = false;
869#ifdef USE_QCHARTS
870 plotter->SetYAxisScaleType(all_positive ? ChartAxisScale::Logarithmic : ChartAxisScale::Normal);
871#else
872 plotter->SetYAxisScaleType(all_positive ? AxisScale::log : AxisScale::normal);
873#endif // USE_QCHARTS
874#ifdef USE_QCHARTS
875 plotter->SetXAxisLabel("Group");
876 plotter->SetYAxisLabel(Element_Name_Selected.toStdString());
877#endif // USE_QCHARTS
878
879 }
880 }
881
882
883 if (samples_selected.size()>0 && PlotType==plottype::elemental_profiles)
884 { profiles_data extracted_data = dataCollection.ExtractConcentrationData(samples_selected);
885 plottedData = std::make_unique<Elemental_Profile_Set>(
886 dataCollection.ExtractSamplesAsProfileSet(samples_selected)
887 );
888 ui->ShowTabular->setEnabled(true);
889 plotter->AddScatters(extracted_data.sample_names,extracted_data.element_names, extracted_data.values);
890#ifdef USE_QCHARTS
891 plotter->SetYAxisScaleType(ChartAxisScale::Logarithmic);
892 plotter->SetXAxisLabel("Constituent");
893 plotter->SetYAxisLabel("Value (log scale; zero and negative values not shown)");
894#else
895 plotter->SetYAxisScaleType(AxisScale::log);
896#endif // USE_QCHARTS
897 }
898 ui->frame->setVisible(true);
899 ui->frame->setEnabled(true);
900 ui->btnZoom->setEnabled(true);
902}
903
904QJsonDocument MainWindow::loadJson(const QString &fileName) {
905 QFile jsonFile(fileName);
906 if (!jsonFile.open(QFile::ReadOnly))
907 return QJsonDocument();
908 return QJsonDocument().fromJson(jsonFile.readAll());
909}
910
911void MainWindow::saveJson(const QJsonDocument &document, const QString &fileName) {
912 QFile jsonFile(fileName);
913 if (!jsonFile.open(QFile::WriteOnly))
914 return;
915 jsonFile.write(document.toJson());
916}
917
918// A JSON object does not keep the order of its keys (QJsonObject sorts them),
919// so tools.json fixes the order with a prefix such as "03|"; the prefix is
920// not shown
921static QString ToolDisplayName(const QString& key)
922{
923 const int bar = key.indexOf('|');
924 return bar < 0 ? key : key.mid(bar + 1);
925}
926
927QStandardItem* MainWindow::ToQStandardItem(const QString& key, const QJsonObject& json)
928{
929 QStandardItem* standardItem = new QStandardItem(ToolDisplayName(key));
930
931 QStringList keys = json.keys();
932 for (const QString& jsonKey : keys)
933 {
934 const QString name = ToolDisplayName(jsonKey);
935 if (json[jsonKey].isObject())
936 {
937 // Recursively create items for nested objects
938 standardItem->appendRow(ToQStandardItem(jsonKey, json[jsonKey].toObject()));
939 standardItem->setToolTip(name);
940 }
941 else
942 {
943 // Create leaf items for values
944 QStandardItem* subItem = new ToolBoxItem(Data(), name);
945 subItem->setData(json.value(jsonKey).toString(), Qt::UserRole);
946 subItem->setData(json.value(jsonKey).toString(), Qt::UserRole + 1);
947 subItem->setToolTip(name);
948 standardItem->appendRow(subItem);
949 }
950 }
951
952 return standardItem;
953}
954
955QStandardItemModel* MainWindow::ToQStandardItemModel(const QJsonDocument& jsonDocument)
956{
957 QStandardItemModel* standardItemModel = new QStandardItemModel();
958 QJsonObject jsonObject = jsonDocument.object();
959 QStandardItem* rootItem = ToQStandardItem("Tools", jsonObject);
960
961 standardItemModel->appendRow(rootItem);
962
963 return standardItemModel;
964}
965
967{
968 QModelIndexList selectedIndexes = ui->treeView->selectionModel()->selectedIndexes();
969
970 if (!selectedIndexes.isEmpty())
971 {
972 return selectedIndexes[0].data(Qt::UserRole).toString();
973 }
974
975 return "none";
976}
977
978void MainWindow::preparetreeviewMenu(const QPoint& pos)
979{
980 QTreeView* tree = ui->treeView;
981 QModelIndex index = tree->currentIndex();
982
983 if (!index.isValid())
984 {
985 return;
986 }
987
988 // qDebug() << index.data(elementRole);
989 // qDebug() << index.data(groupRole);
990 // qDebug() << index.data(sampleRole);
991
992 menu = std::make_unique<QMenu>(this);
993
994 if (!index.data(elementRole).toString().isEmpty())
995 {
996 QAction* showDistributions = menu->addAction("Show fitted distributions");
997
998 QStringList roleData;
999 roleData << "Element=" + index.data(elementRole).toString();
1000 roleData << "Group=" + index.data(groupRole).toString();
1001 roleData << "Sample=" + index.data(sampleRole).toString();
1002 roleData << "Action=SFD";
1003
1004 showDistributions->setData(roleData);
1005
1006 connect(showDistributions, &QAction::triggered,
1008 }
1009
1010 if (menu)
1011 {
1012 menu->exec(tree->mapToGlobal(pos));
1013 }
1014}
1015
1017{
1018 QAction* action = qobject_cast<QAction*>(sender());
1019 if (!action)
1020 {
1021 return;
1022 }
1023
1024 QStringList keysStringList = action->data().toStringList();
1025 QMap<QString, QString> keys;
1026
1027 for (const QString& keyValue : keysStringList)
1028 {
1029 QStringList parts = keyValue.split("=");
1030 if (parts.size() == 2)
1031 {
1032 keys[parts[0]] = parts[1];
1033 }
1034 }
1035
1036 QString element = keys["Element"];
1037 QString group = keys["Group"];
1038 QString sample = keys["Sample"];
1039 QString actionType = keys["Action"];
1040
1041 if (actionType != "SFD")
1042 {
1043 return;
1044 }
1045
1046 PlotWindow* plotWindow = new PlotWindow(this);
1047
1048 if (group.isEmpty())
1049 {
1050 // Plot distribution for all samples
1051 TimeSeries<double> elementDist =
1052 dataCollection.GetFittedDistribution(element.toStdString())->EvaluateAsTimeSeries();
1053
1054 plotWindow->Plotter()->AddTimeSeries(
1055 "All samples",
1056 elementDist.tToStdVector(),
1057 elementDist.ValuesToStdVector()
1058 );
1059
1060 // Add distribution for each group
1061 for (auto it = dataCollection.begin(); it != dataCollection.end(); ++it)
1062 {
1063 elementDist = dataCollection.GetSampleSet(it->first)
1064 ->GetElementDistribution(element.toStdString())
1065 ->GetFittedDistribution()
1066 ->EvaluateAsTimeSeries();
1067
1068 plotWindow->Plotter()->AddTimeSeries(
1069 it->first,
1070 elementDist.tToStdVector(),
1071 elementDist.ValuesToStdVector()
1072 );
1073 }
1074 }
1075 else
1076 {
1077 // Plot distribution for specific group
1078 TimeSeries<double> elementDist =
1079 dataCollection.GetSampleSet(group.toStdString())
1080 ->GetElementDistribution(element.toStdString())
1081 ->GetFittedDistribution()
1082 ->EvaluateAsTimeSeries();
1083
1084 plotWindow->Plotter()->AddTimeSeries(
1085 (group + ":" + element).toStdString(),
1086 elementDist.tToStdVector(),
1087 elementDist.ValuesToStdVector()
1088 );
1089 }
1090
1091 plotWindow->setWindowTitle(element);
1092 plotWindow->Plotter()->SetLegend(true);
1093 plotWindow->show();
1094}
1095
1097{
1098 FormElementInformation* formElems = new FormElementInformation(this);
1099 ElementTableModel* elementTableModel = new ElementTableModel(&dataCollection, this);
1100 formElems->setModel(elementTableModel);
1101
1102 ElementTableDelegate* elemDelegate = new ElementTableDelegate(&dataCollection, this);
1103 formElems->table()->setItemDelegate(elemDelegate);
1104
1105 ui->verticalLayout_middle->addWidget(formElems);
1106 centralform.reset(formElems);
1107}
1108
1110{
1111 // A project whose target group is wrong (the import dialog used to
1112 // preselect the first sheet) could only be corrected by importing the
1113 // workbook again, because nothing here could change it.
1114 if (dataCollection.empty())
1115 {
1116 QMessageBox::warning(
1117 this,
1118 tr("SedSat3"),
1119 tr("No data has been loaded."),
1120 QMessageBox::Ok);
1121 return;
1122 }
1123
1124 QStringList groupNames;
1125 for (const std::string& groupName : dataCollection.GetGroupNames())
1126 groupNames << QString::fromStdString(groupName);
1127
1128 const QString current = QString::fromStdString(dataCollection.GetTargetGroup());
1129 bool ok = false;
1130 const QString target = QInputDialog::getItem(
1131 this,
1132 tr("Target group"),
1133 tr("Select the group that holds the target samples. Every other group "
1134 "is a source group.\n\nSave the project afterwards to keep the change."),
1135 groupNames,
1136 qMax(0, groupNames.indexOf(current)),
1137 false,
1138 &ok);
1139
1140 if (!ok || target.isEmpty() || target == current)
1141 return;
1142
1143 dataCollection.SetTargetGroup(target.toStdString());
1144
1145 // Every result in the project was computed against the previous target
1147 tr("Target group is now '%1' (it was '%2'). Results already in this "
1148 "project were computed with the previous target group, so re-run "
1149 "them. Reopen any form that is showing a group list.")
1150 .arg(target, current.isEmpty() ? tr("not set") : current),
1151 Qt::blue);
1152}
1153
1155{
1156 if (Data()->count(Data()->GetTargetGroup()) == 0)
1157 {
1158 // The bracket test below needs the target samples; without them it
1159 // threw an uncaught exception and the program closed
1160 QMessageBox::warning(
1161 this,
1162 tr("SedSat3"),
1163 tr("This project has no target group. Reopen it and select the group that holds the target samples."),
1164 QMessageBox::Ok);
1165 return;
1166 }
1167
1168 // Prompt for options if using default threshold
1169 if (Data()->GetOptions()->value("Outlier deviation threshold") == 3)
1170 {
1172 }
1173
1174 // Read the threshold after the dialog, so a value entered there is used
1175 double outlierThreshold = Data()->GetOptions()->value("Outlier deviation threshold");
1176
1177 // Perform outlier analysis
1178 Data()->OutlierAnalysisForAll(-outlierThreshold, outlierThreshold);
1179 Data()->BracketTest(false, false, false);
1180
1181 // Create and configure sample selection dialog
1182 SelectSamples* sampleSelector = new SelectSamples(this);
1183 sampleSelector->SetMode(mode::samples);
1184 sampleSelector->SetData(&dataCollection);
1185
1186 ui->verticalLayout_middle->addWidget(sampleSelector);
1187 centralform.reset(sampleSelector);
1188}
1189
1191{
1192 // Check if OM and size correction has been performed
1193 if (dataCollection.OMandSizeConstituents()[0].empty() &&
1194 dataCollection.OMandSizeConstituents()[1].empty())
1195 {
1196 QMessageBox::warning(
1197 this,
1198 tr("SedSat3"),
1199 tr("Organic Matter and Size Correction must be performed first."),
1200 QMessageBox::Ok
1201 );
1202 return;
1203 }
1204
1205 // Create and configure sample selection dialog
1206 SelectSamples* sampleSelector = new SelectSamples(this);
1207 sampleSelector->SetMode(mode::regressions);
1208 sampleSelector->SetData(&dataCollection);
1209
1210 ui->verticalLayout_middle->addWidget(sampleSelector);
1211 centralform.reset(sampleSelector);
1212}
1213
1214
1215void MainWindow::on_tool_executed(const QModelIndex& index)
1216{
1217 // qDebug() << "Tool executed" << index.data() << ":" << index.data(Qt::UserRole);
1218
1219 // Check if data has been loaded
1220 if (dataCollection.GetElementNames().empty())
1221 {
1222 QMessageBox::warning(
1223 this,
1224 tr("SedSat3"),
1225 tr("No data has been loaded."),
1226 QMessageBox::Ok
1227 );
1228 return;
1229 }
1230
1231 QJsonObject mainJsonObject = formsstructure.object();
1232 QString toolName = index.data(Qt::UserRole).toString();
1233
1234 if (mainJsonObject.contains(toolName))
1235 {
1236 // qDebug() << toolName;
1237
1238 QJsonObject formObject = mainJsonObject.value(toolName).toObject();
1239
1240 centralform = std::make_unique<GenericForm>(&formObject, this, this);
1241 dynamic_cast<GenericForm*>(centralform.get())->SetCommand(toolName);
1242 ui->verticalLayout_middle->addWidget(centralform.get());
1243 }
1244}
1245
1246void MainWindow::on_old_result_requested(const QModelIndex& index)
1247{
1248 if (!index.isValid() || !resultsViewModel)
1249 {
1250 return;
1251 }
1252
1253 QStandardItem* item = resultsViewModel->item(index.row());
1254 if (!item)
1255 {
1256 return;
1257 }
1258
1259 ResultSetItem* resultSetItem = dynamic_cast<ResultSetItem*>(item);
1260 if (!resultSetItem || !resultSetItem->result)
1261 {
1262 qWarning() << "Invalid result item at row" << index.row();
1263 return;
1264 }
1265
1266 Results* resultSet = resultSetItem->result;
1267
1268 ResultsWindow* resultsWindow = new ResultsWindow(this);
1269 resultsWindow->SetResults(resultSet);
1270 resultsWindow->setWindowTitle(resultSetItem->text());
1271
1272 for (auto it = resultSet->begin(); it != resultSet->end(); ++it)
1273 {
1274 resultsWindow->AppendResult(it->second, it->first);
1275 }
1276
1277 resultsWindow->show();
1278}
1279
1280bool MainWindow::Execute(const std::string& command, const std::map<std::string, std::string>& arguments)
1281{
1282 conductor->SetData(&dataCollection);
1283
1284 // An exception escaping an analysis would otherwise terminate the program
1285 bool outcome = false;
1286 try
1287 {
1288 outcome = conductor->Execute(command, arguments);
1289 }
1290 catch (const std::exception& exception)
1291 {
1292 QMessageBox::critical(this, tr("Analysis failed"),
1293 tr("The analysis '%1' stopped with an error:\n%2")
1294 .arg(QString::fromStdString(command), QString::fromUtf8(exception.what())));
1295 return false;
1296 }
1297 catch (...)
1298 {
1299 QMessageBox::critical(this, tr("Analysis failed"),
1300 tr("The analysis '%1' stopped with an unknown error.")
1301 .arg(QString::fromStdString(command)));
1302 return false;
1303 }
1304 if (!outcome)
1305 {
1306 return false;
1307 }
1308
1309 // Create separate copies for window and permanent storage
1310 Results* resultsForWindow = conductor->GetResults(); // For ResultsWindow
1311 Results* resultsForStorage = conductor->GetResults(); // For ResultSetItem (persists)
1312
1313 // Generate timestamp suffix
1314 QString timestamp = QDateTime::currentDateTime().toString(Qt::TextDate);
1315 QString resultName = QString::fromStdString(resultsForStorage->GetName()) + "_" + timestamp;
1316
1317 // Create result set item for permanent storage
1318 ResultSetItem* resultSetItem = new ResultSetItem(resultName);
1319 resultSetItem->setToolTip(resultName);
1320 resultSetItem->result = resultsForStorage;
1321 resultsViewModel->appendRow(resultSetItem);
1322
1323 // Create results window
1324 ResultsWindow* resultsWindow = new ResultsWindow(this);
1325 resultsWindow->SetResults(resultsForWindow);
1326 resultsWindow->setWindowTitle(resultName);
1327
1328 // Populate results window
1329 for (auto it = resultsForStorage->begin(); it != resultsForStorage->end(); ++it)
1330 {
1331 resultsWindow->AppendResult(it->second, it->first);
1332 }
1333
1334 resultsWindow->show();
1335
1336 return true;
1337}
1338
1340{
1341 AboutDialog* aboutDlg = new AboutDialog(this);
1342 aboutDlg->setVersion(version);
1343 aboutDlg->setBuildDate(date_compiled);
1344 aboutDlg->exec();
1345 delete aboutDlg;
1346}
1347
1348void MainWindow::onCustomContextMenu(const QPoint& point)
1349{
1350 indexresultselected = ui->TreeView_Results->indexAt(point);
1351 if (indexresultselected.isValid()) {
1352 ResultscontextMenu->exec(ui->TreeView_Results->viewport()->mapToGlobal(point));
1353 }
1354}
1355
1357{
1358 if (!indexresultselected.isValid())
1359 {
1360 qWarning() << "Attempted to delete with invalid index";
1361 return;
1362 }
1363
1364 QStandardItem* item = resultsViewModel->item(indexresultselected.row());
1365 if (item)
1366 {
1367 int ret = QMessageBox::question(
1368 this,
1369 tr("Delete Result"),
1370 tr("Are you sure you want to delete '%1'?").arg(item->text()),
1371 QMessageBox::Yes | QMessageBox::No,
1372 QMessageBox::No
1373 );
1374
1375 if (ret == QMessageBox::Yes)
1376 {
1377 resultsViewModel->removeRow(indexresultselected.row());
1378 }
1379 }
1380}
1381
1383{
1384 QString recentFilePath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)
1385 + "/" + RECENT;
1386
1387 QFile file(recentFilePath);
1388 if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
1389 {
1390 // qDebug() << "No recent files list found";
1391 return;
1392 }
1393
1394 // Read the whole file in one call rather than looping on QTextStream. If the
1395 // device cannot actually be read - for example an offline OneDrive placeholder
1396 // that cannot be hydrated - readLine() never advances and atEnd() never becomes
1397 // true, so the loop spins forever and startup never completes.
1398 const QByteArray contents = file.readAll();
1399 const bool readFailed = (file.error() != QFileDevice::NoError);
1400 const QString readError = file.errorString();
1401 file.close();
1402
1403 if (readFailed)
1404 {
1405 qWarning() << "Failed to read recent files list:" << readError;
1406 return;
1407 }
1408
1409 QStringList allLines;
1410 const QStringList rawLines = QString::fromUtf8(contents).split('\n', Qt::SkipEmptyParts);
1411
1412 for (const QString& rawLine : rawLines)
1413 {
1414 const QString line = rawLine.trimmed();
1415 if (!line.isEmpty())
1416 {
1417 allLines.append(line);
1418 }
1419 }
1420
1421 // Add only the most recent files (up to max_num_recent_files)
1422 int startIndex = qMax(0, allLines.size() - max_num_recent_files);
1423 for (int i = startIndex; i < allLines.size(); ++i)
1424 {
1425 addToRecentFiles(allLines[i], false);
1426 }
1427}
1428
1429void MainWindow::addToRecentFiles(const QString& fileName, bool addToFile)
1430{
1431 if (fileName.trimmed().isEmpty())
1432 {
1433 return;
1434 }
1435
1436 QString trimmedFileName = fileName.trimmed();
1437 bool rewriteFile = false;
1438
1439 // If file already exists in list, move it to the end (most recent)
1440 if (recentFiles.contains(trimmedFileName))
1441 {
1442 int existingIndex = recentFiles.indexOf(trimmedFileName);
1443
1444 // Only move if not already at the end
1445 if (existingIndex != recentFiles.count() - 1)
1446 {
1447 // Remove from menu
1448 QList<QAction*> actions = ui->menuRecent->actions();
1449 int actionIndex = recentFiles.size() - 1 - existingIndex;
1450 if (actionIndex >= 0 && actionIndex < actions.size())
1451 {
1452 ui->menuRecent->removeAction(actions[actionIndex]);
1453 }
1454
1455 // Remove from list
1456 recentFiles.removeOne(trimmedFileName);
1457 addToFile = false;
1458 rewriteFile = true;
1459 }
1460 else
1461 {
1462 return; // Already most recent, nothing to do
1463 }
1464 }
1465
1466 // Enforce maximum number of recent files
1467 if (recentFiles.size() >= max_num_recent_files)
1468 {
1469 // Remove oldest file (first in list)
1470 recentFiles.removeFirst();
1471
1472 // Remove oldest action (last in menu)
1473 QList<QAction*> actions = ui->menuRecent->actions();
1474 if (!actions.isEmpty())
1475 {
1476 ui->menuRecent->removeAction(actions.last());
1477 }
1478
1479 rewriteFile = true;
1480 }
1481
1482 // Add to list
1483 recentFiles.append(trimmedFileName);
1484
1485 // Add to menu (at the top)
1486 QAction* fileAction = new QAction(trimmedFileName, this);
1487
1488 QList<QAction*> actions = ui->menuRecent->actions();
1489 if (!actions.isEmpty())
1490 {
1491 ui->menuRecent->insertAction(actions.first(), fileAction);
1492 }
1493 else
1494 {
1495 ui->menuRecent->addAction(fileAction);
1496 }
1497
1498 connect(fileAction, &QAction::triggered, this, &MainWindow::on_actionRecent_triggered);
1499
1500 // Write to file if needed
1501 if (addToFile)
1502 {
1503 QString recentFilePath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)
1504 + "/" + RECENT;
1505 CreateFileIfDoesNotExist(recentFilePath);
1506
1507 QFile file(recentFilePath);
1508 if (file.open(QIODevice::Append | QIODevice::Text))
1509 {
1510 QTextStream out(&file);
1511 out << trimmedFileName << "\n";
1512 file.close();
1513 }
1514 }
1515
1516 if (rewriteFile)
1517 {
1519 }
1520}
1521
1523{
1524 QString recentFilePath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)
1525 + "/" + RECENT;
1526
1527 QFile file(recentFilePath);
1528 if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
1529 {
1530 qWarning() << "Failed to write recent files list:" << file.errorString();
1531 return;
1532 }
1533
1534 QTextStream out(&file);
1535 for (const QString& fileName : recentFiles)
1536 {
1537 out << fileName << "\n";
1538 }
1539
1540 file.close();
1541}
1542
1544{
1545 QString localAppDataPath = QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation);
1546 // qDebug() << "Local AppData Folder:" << localAppDataPath;
1547 return localAppDataPath;
1548}
1549
1551{
1552 QAction* action = qobject_cast<QAction*>(sender());
1553 if (!action)
1554 {
1555 qWarning() << "Invalid sender in on_actionRecent_triggered";
1556 return;
1557 }
1558
1559 QString fileName = action->text();
1560 if (LoadModel(fileName))
1561 {
1562 addToRecentFiles(fileName, false);
1563 }
1564}
1565
1566void MainWindow::removeFromRecentList(QAction* selectedFileAction)
1567{
1568 if (!selectedFileAction)
1569 {
1570 return;
1571 }
1572
1573 recentFiles.removeAll(selectedFileAction->text());
1574 ui->menuRecent->removeAction(selectedFileAction);
1576}
1577
1578bool MainWindow::CreateFileIfDoesNotExist(const QString& fileName)
1579{
1580 QFileInfo fileInfo(fileName);
1581
1582 if (fileInfo.exists())
1583 {
1584 return true; // File already exists
1585 }
1586
1587 QFile file(fileName);
1588 if (!file.open(QIODevice::WriteOnly))
1589 {
1590 qWarning() << "Failed to create file:" << fileName << "-" << file.errorString();
1591 return false;
1592 }
1593
1594 file.close();
1595 return true;
1596}
1597
1598void MainWindow::addToolBarAction(const QString& text,
1599 const QString& iconPath,
1600 const QString& toolTip,
1601 void (MainWindow::* slot)())
1602{
1603 QAction* action = new QAction(this);
1604 action->setObjectName(text);
1605 action->setText(text);
1606 action->setToolTip(toolTip);
1607
1608 QIcon icon(iconPath);
1609 if (!icon.isNull())
1610 {
1611 action->setIcon(icon);
1612 }
1613 else
1614 {
1615 qWarning() << "Failed to load icon:" << iconPath;
1616 }
1617
1618 ui->toolBar->addAction(action);
1619 connect(action, &QAction::triggered, this, slot);
1620}
1621
1622
1624{
1625 QString iconPath = resourcesPath()+"/Icons/";
1626
1627 // Import Excel
1629 "Import Excel",
1630 iconPath + "Import_Excel.png",
1631 "Import from Excel File",
1633 );
1634
1635 // Save
1637 "Save",
1638 iconPath + "Save.png",
1639 "Save Project",
1641 );
1642
1643 // Open
1645 "Open",
1646 iconPath + "open.png",
1647 "Open Project",
1649 );
1650
1651 // Separator
1652 ui->toolBar->addSeparator();
1653
1654 // Element Properties
1656 "Constituents Selection/Properties",
1657 iconPath + "Element_Props.png",
1658 "Constituents Selection/Properties",
1660 );
1661
1662 // Organic Matter and Size Correction
1664 "Organic Matter and Size Correction",
1665 iconPath + "OMSizeCorrection.png",
1666 "Organic Matter and Size Correction",
1668 );
1669
1670 // Select Samples
1672 "Select Samples",
1673 iconPath + "SelectSamples.png",
1674 "Select Samples",
1676 );
1677}
1678
1680{
1681 if (!plottedData)
1682 {
1683 qWarning() << "No data to display in table";
1684 return;
1685 }
1686
1687 ResultTableViewer* tableViewer = new ResultTableViewer(this);
1688 tableViewer->setWindowFlag(Qt::WindowMinMaxButtonsHint);
1689 tableViewer->setWindowTitle(tr("Elemental Profiles"));
1690
1691 QTableWidget* tableWidget = plottedData->ToTable();
1692 tableViewer->SetTable(tableWidget);
1693
1694 tableViewer->show();
1695}
1696
1698{
1699#ifdef USE_QCHARTS
1700 plotter->ZoomExtents();
1701#else
1702 plotter->ZoomExtends();
1703#endif // USE_QCHARTS
1704
1705
1706}
1707
1708
1710{
1711 OptionsDialog dlg(Data()->GetOptions());
1712 dlg.exec();
1713
1714}
1715
1717{
1718#ifdef Q_OS_MAC
1719 // Inside the .app bundle, resources live at Contents/Resources/
1720 // applicationDirPath() returns .../SedSat3.app/Contents/MacOS, so go up one level
1721 return qApp->applicationDirPath() + "/../Resources";
1722#else
1723 // Linux/Windows: resources sit next to the project root, two levels up from build dir
1724 return qApp->applicationDirPath() + "/../../resources";
1725#endif
1726}
Professional about dialog for SedSat3 application.
Definition aboutdialog.h:23
void setVersion(const QString &version)
Sets the application version.
void setBuildDate(const QString &date)
Sets the build date.
Manages a collection of elemental profiles (samples) for source fingerprinting analysis.
void setModel(ElementTableModel *model)
Sets the table model and the check box state from it.
bool SetCommand(const QString &cmd)
void on_actionRecent_triggered()
void addToolBarAction(const QString &text, const QString &iconPath, const QString &toolTip, void(MainWindow::*slot)())
Helper to add an action to the toolbar with icon and connection.
QString resourcesPath() const
void on_old_result_requested(const QModelIndex &index)
bool ReadExcel(const QString &filename)
Reads elemental profile data from Excel file.
QStringList recentFiles
List of recently opened files.
Definition mainwindow.h:275
SourceSinkData * Data()
Returns pointer to the main data collection.
Definition mainwindow.h:77
QMenu * ResultscontextMenu
Context menu for results view.
Definition mainwindow.h:265
void DeleteResults()
GeneralPlotter * plotter
Main plotting widget.
Definition mainwindow.h:254
SourceSinkData dataCollection
Main data collection for analysis.
Definition mainwindow.h:247
void showdistributionsforelements()
void on_show_data_as_table()
QString ProjectFileName
Current project file path.
Definition mainwindow.h:274
void onOpenProject()
QStandardItem * ToQStandardItem(const QString &key, const SourceSinkData *srcsinkdata)
std::unique_ptr< QStandardItemModel > columnViewModel
Model for column/data tree view.
Definition mainwindow.h:261
bool LoadModel(const QString &fileName)
void setupResultsView()
Initializes the results tree view and context menu.
void WriteMessageOnScreen(const QString &text, QColor color=Qt::black)
Writes a message to the application's message display area.
Ui::MainWindow * ui
Definition mainwindow.h:244
bool treeItemChangedProgramatically
Flag for programmatic tree changes.
Definition mainwindow.h:273
void setupToolsView()
Initializes the tools tree view.
bool CreateFileIfDoesNotExist(const QString &fileName)
void Populate_General_ToolBar()
std::unique_ptr< QStandardItemModel > resultsViewModel
Model for results tree view.
Definition mainwindow.h:262
bool saveProjectToFile(const QString &filePath)
Saves project data to the specified file.
QString getSaveFilePath(bool promptUser)
Gets the file path for saving, prompting user if needed.
std::unique_ptr< Conductor > conductor
Analysis command coordinator.
Definition mainwindow.h:281
void on_Options_triggered()
void addToRecentFiles(const QString &fileName, bool addToFile)
QJsonObject buildProjectJson() const
Builds the complete project JSON object.
QJsonDocument formsstructure
Forms structure definitions.
Definition mainwindow.h:269
QString selectedTreeItemType
Currently selected tree item type.
Definition mainwindow.h:272
void on_constituent_properties_triggered()
QStandardItemModel * ToQStandardItemModel(const SourceSinkData *srcsinkdata)
QString TreeQStringSelectedType()
void on_import_excel()
void removeFromRecentList(QAction *selectedFileAction)
void writeRecentFilesList()
void InitiateTables()
void setupConnections()
Sets up all signal-slot connections for UI elements.
bool Execute(const std::string &command, const std::map< std::string, std::string > &arguments)
Executes a specified analysis command.
MainWindow(QWidget *parent=nullptr)
Constructs the main window.
std::unique_ptr< QMenu > menu
Main menu.
Definition mainwindow.h:278
QJsonObject buildResultsJson() const
Builds the results section of the project JSON.
QJsonDocument loadJson(const QString &fileName)
std::unique_ptr< QWidget > centralform
Central form widget.
Definition mainwindow.h:279
QAction * DeleteAction
Delete action for results.
Definition mainwindow.h:266
std::unique_ptr< Interface > plottedData
Currently plotted data interface.
Definition mainwindow.h:258
void preparetreeviewMenu(const QPoint &pos)
void on_ZoomExtends()
void onOMSizeCorrection()
std::unique_ptr< GuiHost > analysis_host
Reports analyses through this window.
Definition mainwindow.h:280
void onAboutTriggered()
QStandardItem * ElementsToQStandardItem(const QString &key, const SourceSinkData *srcsinkdata)
void readRecentFilesList()
void onSetTargetGroup()
int sinkSheet
Index of sink sheet in Excel import.
Definition mainwindow.h:248
void on_plot_raw_elemental_profiles()
void setupToolBar()
Initializes the general toolbar.
void onCustomContextMenu(const QPoint &pos)
QModelIndex indexresultselected
Currently selected result index.
Definition mainwindow.h:282
void on_tree_selectionChanged(const QItemSelection &changed)
~MainWindow()
Destructor - cleans up UI resources.
void onSaveProject()
void saveJson(const QJsonDocument &document, const QString &fileName)
void onIncludeExcludeSample()
void on_tool_executed(const QModelIndex &index)
void onSaveProjectAs()
GeneralChartPlotter * Plotter()
Definition plotwindow.h:32
Results * result
void SetTable(QTableWidget *tablewidget)
void SetResults(Results *res)
void AppendResult(const ResultItem &resultitem, const std::string &key)
QJsonObject toJsonObject()
Definition results.cpp:33
string GetName()
Definition results.h:26
bool ReadFromJson(const QJsonObject &jsonobject)
Definition results.cpp:44
void SetData(SourceSinkData *_data)
void SetMode(mode _mode)
QMap< QString, double > * GetOptions()
Retrieves pointer to the options map.
bool ReadFromFile(QFile *fil)
Loads complete dataset from a JSON file.
void OutlierAnalysisForAll(const double &lower_threshold=-3, const double &upper_threshold=3)
Performs outlier detection on all source groups.
CMBVector BracketTest(const string &target_sample, bool correct_based_on_om_n_size, double tolerance=0)
Performs bracket test to check if target concentrations fall within source ranges.
void SetOMandSizeConstituents(const string &_omconstituent, const string &_sizeconstituent)
Sets the names of OM and particle size constituents.
QJsonObject ElementInformationToJsonObject() const
Exports element information metadata to a JSON object.
QJsonObject OptionsToJsonObject() const
Exports analysis options/settings to a JSON object.
QJsonObject ElementDataToJsonObject() const
Exports all elemental profile data to a JSON object.
bool SetTargetGroup(const string &targroup)
Sets the target/sink group designation.
QJsonArray ToolsUsedToJsonObject() const
Exports the list of analysis tools used to a JSON array.
#define RECENT
#define date_compiled
#define max_num_recent_files
QString localAppFolderAddress()
Returns the local application folder address.
static QString ToolDisplayName(const QString &key)
#define version
@ elementRole
Definition mainwindow.h:26
@ sampleRole
Definition mainwindow.h:28
@ groupRole
Definition mainwindow.h:27
The one place where data values entering SedSAT3 are checked.
vector< vector< double > > values
vector< string > element_names
vector< string > sample_names