6#include "excelimport.h"
7#include "ui_mainwindow.h"
13#include "xlsxdocument.h"
14#include "xlsxchartsheet.h"
15#include "xlsxcellrange.h"
17#include "xlsxrichstring.h"
18#include "xlsxworkbook.h"
24#include "QJsonDocument"
39#include <QInputDialog>
40#include <QStandardPaths>
50#define RECENT "SedSatrecentFiles.txt"
52#ifndef max_num_recent_files
53#define max_num_recent_files 15
57#define version "1.1.8"
58#define date_compiled "10/28/2026"
63 : QMainWindow(parent),
79 setWindowIcon(mainIcon);
86 conductor->SetWorkingFolder(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation));
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,
114 connect(
ui->actionRaw_Elemental_Profiles, &QAction::triggered,
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,
128 connect(
ui->actionAbout, &QAction::triggered,
130 connect(
ui->actionOptions, &QAction::triggered,
134 connect(
ui->ShowTabular, &QPushButton::clicked,
136 connect(
ui->btnZoom, &QPushButton::clicked,
140 connect(
ui->treeViewtools, &QTreeView::doubleClicked,
142 connect(
ui->TreeView_Results, &QTreeView::doubleClicked,
146 connect(
ui->TreeView_Results, &QWidget::customContextMenuRequested,
158 QJsonDocument tools =
loadJson(toolsPath);
160 toolsModel->setHorizontalHeaderLabels(QStringList() <<
"Tools");
162 ui->treeViewtools->setModel(toolsModel);
163 ui->treeViewtools->setEditTriggers(QAbstractItemView::NoEditTriggers);
166 QString formsPath =
resourcesPath() +
"/forms_structures.json";
170 ui->treeView->setSelectionMode(QAbstractItemView::MultiSelection);
171 ui->verticalLayout_3->setContentsMargins(0, 0, 0, 0);
172 ui->verticalLayout_3->setSpacing(0);
175 if (
ui->frame->layout())
177 ui->frame->layout()->setContentsMargins(2, 2, 2, 2);
178 ui->frame->layout()->setSpacing(2);
181 ui->frame->setVisible(
false);
191 ui->TreeView_Results->setContextMenuPolicy(Qt::CustomContextMenu);
203 ui->ShowTabular->setIcon(iconTable);
204 ui->ShowTabular->setEnabled(
false);
208 ui->btnZoom->setIcon(iconZoom);
209 ui->btnZoom->setEnabled(
false);
231 QString fileName = QFileDialog::getSaveFileName(
235 tr(
"CMB Source file (*.cmb);;All files (*.*)"),
237 QFileDialog::DontUseNativeDialog
241 if (fileName.isEmpty())
247 if (!fileName.toLower().endsWith(
".cmb"))
257 QJsonObject resultsJson;
273 if (!resultSetItem || !resultSetItem->
result)
275 qWarning() <<
"Invalid result item at row" << i;
287 QJsonObject projectJson;
291 projectJson[
"Target Group"] = QString::fromStdString(
Data()->GetTargetGroup());
301 QFile file(filePath);
303 if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
305 QMessageBox::critical(
308 tr(
"Could not open file for writing:\n%1\n\nError: %2")
310 .arg(file.errorString())
316 QFileInfo fileInfo(file);
317 conductor->SetWorkingFolder(fileInfo.absolutePath());
321 QJsonDocument jsonDocument(projectJson);
323 qint64 bytesWritten = file.write(jsonDocument.toJson());
326 if (bytesWritten == -1)
328 QMessageBox::critical(
331 tr(
"Error writing to file:\n%1\n\nError: %2")
333 .arg(file.errorString())
349 if (filePath.isEmpty())
356 statusBar()->showMessage(tr(
"Project saved successfully"), 3000);
364 if (filePath.isEmpty())
371 statusBar()->showMessage(tr(
"Project saved successfully"), 3000);
377 QString fileName = QFileDialog::getOpenFileName(
381 tr(
"CMB Source file (*.cmb);;All files (*.*)"),
383 QFileDialog::DontUseNativeDialog
386 if (fileName.isEmpty())
394 statusBar()->showMessage(tr(
"Project opened successfully"), 3000);
400 QFile file(fileName);
402 if (!file.open(QIODevice::ReadOnly))
404 QMessageBox::critical(
407 tr(
"Could not open file for reading:\n%1\n\nError: %2")
409 .arg(file.errorString())
415 QByteArray fileData = file.readAll();
418 QJsonDocument jsonDoc = QJsonDocument::fromJson(fileData);
419 if (jsonDoc.isNull())
421 QMessageBox::critical(
424 tr(
"Invalid JSON format in file:\n%1")
430 QJsonObject jsonObject = jsonDoc.object();
433 QFileInfo fileInfo(fileName);
434 conductor->SetWorkingFolder(fileInfo.absolutePath());
437 if (!file.open(QIODevice::ReadOnly))
439 QMessageBox::critical(
442 tr(
"Could not open the project:\n%1\n\n%2")
444 .arg(file.errorString())
452 QMessageBox::critical(
455 tr(
"Could not load the project:\n%1\n\n%2")
457 .arg(
Data()->LoadError())
465 if (
Data()->count(
Data()->GetTargetGroup()) == 0 && !
Data()->empty())
467 QStringList groupNames;
468 for (
const std::string& groupName :
Data()->GetGroupNames())
469 groupNames << QString::fromStdString(groupName);
471 const QString target = QInputDialog::getItem(
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())
480 QMessageBox::warning(
483 tr(
"No target group is set, so the tools that use the target samples will not run."));
487 QJsonObject resultsJson = jsonObject[
"Results"].toObject();
491 for (
const QString& key : resultsJson.keys())
494 resultSet->setToolTip(key);
499 for (
auto it = resultSet->
result->begin(); it != resultSet->
result->end(); ++it)
503 QStringList parts = QString::fromStdString(it->first).split(
"OM & Size MLR for ");
504 if (parts.size() > 1)
506 std::string source = parts[1].toStdString();
507 if (
Data()->count(source) > 0)
509 Data()->at(source).SetRegressionModels(
513 Data()->at(source).GetRegressionModels()->begin()->second.GetIndependentVariableNames()
532 ui->ShowTabular->setEnabled(
true);
533 ui->btnZoom->setEnabled(
true);
539 QString fileName = QFileDialog::getOpenFileName(
541 tr(
"Open Excel File"),
543 tr(
"Excel files (*.xlsx);;All files (*.*)"),
545 QFileDialog::DontUseNativeDialog
548 if (fileName.isEmpty())
553 QFileInfo fileInfo(fileName);
554 conductor->SetWorkingFolder(fileInfo.absolutePath());
560 QMessageBox::information(
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."),
578 QList<QStandardItem*> modelItems;
583 QList<QStandardItem*> elementItems;
589 ui->treeView->setContextMenuPolicy(Qt::CustomContextMenu);
592 connect(
ui->treeView->selectionModel(), &QItemSelectionModel::selectionChanged,
594 connect(
ui->treeView, &QWidget::customContextMenuRequested,
606 Document xlsxR(filename);
609 QMessageBox::critical(
611 tr(
"Excel Load Error"),
612 tr(
"Failed to load Excel file:\n%1").arg(filename)
618 QStringList allSheetNames = xlsxR.sheetNames();
624 QStringList* sheetsToInclude =
nullptr;
625 auto chooseSheetsDlg = std::make_unique<DialogChooseExcelSheets>(
this, &sheetsToInclude);
627 for (
const QString& sheetName : allSheetNames)
629 chooseSheetsDlg->AddItem(sheetName);
633 chooseSheetsDlg->exec();
635 if (!sheetsToInclude)
641 QStringList selectedSheets;
642 for (
const QString& sheetName : allSheetNames)
644 if (sheetsToInclude->contains(sheetName))
646 selectedSheets << sheetName;
649 delete sheetsToInclude;
651 if (selectedSheets.isEmpty())
658 auto indicateSheetDlg = std::make_unique<IndicateSheetsDialog>(
this);
659 indicateSheetDlg->Populate_Table(selectedSheets);
660 if (indicateSheetDlg->exec() != QDialog::Accepted
667 ExcelImportError importError;
668 if (!ImportExcelSheets(xlsxR, selectedSheets,
dataCollection, importError))
670 QMessageBox::warning(
this, importError.title, importError.message);
687 ui->textBrowser->setTextColor(color);
688 ui->textBrowser->append(text);
693 QStandardItem* rootItem =
new QStandardItem(key);
694 rootItem->setData(
"RootItem", Qt::UserRole);
698 for (
size_t i = 0; i < groupNames.size(); ++i)
700 QStandardItem* groupItem =
new QStandardItem(QString::fromStdString(groupNames[i]));
701 groupItem->setData(
"Group", Qt::UserRole);
702 groupItem->setData(QString::fromStdString(groupNames[i]),
groupRole);
707 for (
auto it = sampleSet->begin(); it != sampleSet->end(); ++it)
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);
714 groupItem->appendRow(sampleItem);
718 rootItem->appendRow(groupItem);
726 QStandardItem* rootItem =
new QStandardItem(key);
727 rootItem->setData(
"RootItem", Qt::UserRole);
732 for (
size_t elemIdx = 0; elemIdx < elementNames.size(); ++elemIdx)
734 QStandardItem* elementItem =
new QStandardItem(QString::fromStdString(elementNames[elemIdx]));
735 elementItem->setData(
"Element", Qt::UserRole);
736 elementItem->setData(QString::fromStdString(elementNames[elemIdx]),
elementRole);
738 for (
size_t groupIdx = 0; groupIdx < groupNames.size(); ++groupIdx)
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);
745 elementItem->appendRow(groupItem);
748 rootItem->appendRow(elementItem);
762 for (
size_t i = 0; i < groupNames.size(); ++i)
764 QStandardItem* groupItem =
new QStandardItem(QString::fromStdString(groupNames[i]));
765 groupItem->setData(
"Parent", Qt::UserRole);
770 for (
auto it = sampleSet->begin(); it != sampleSet->end(); ++it)
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);
777 groupItem->appendRow(sampleItem);
789 ui->ShowTabular->setEnabled(
false);
794 plotter =
new GeneralChartPlotter(
this);
799 ui->verticalLayout_3->addWidget(
plotter);
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]))
814 ui->treeView->selectionModel()->clearSelection();
815 ui->treeView->selectionModel()->select(changed_index,QItemSelectionModel::Select | QItemSelectionModel::Rows);
817 indexes =
ui->treeView->selectionModel()->selectedIndexes();
821 for (
int i=0; i<indexes.size(); i++)
824 if (indexes[i].data(Qt::UserRole).toString()==
"Group")
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++)
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);
836 else if (indexes[i].data(Qt::UserRole).toString()==
"Sample")
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);
843 if (indexes[i].data(Qt::UserRole).toString()==
"Element")
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());
853 plotter =
new GeneralChartPlotter(
this);
857 ui->verticalLayout_3->addWidget(
plotter);
861 plotter->AddNonUniformScatter(extracted_data,i,8,Element_Name_Selected.toStdString());
864 bool all_positive =
true;
865 for (
const auto& [group, values] : extracted_data)
866 for (
double value : values)
868 all_positive =
false;
870 plotter->SetYAxisScaleType(all_positive ? ChartAxisScale::Logarithmic : ChartAxisScale::Normal);
875 plotter->SetXAxisLabel(
"Group");
876 plotter->SetYAxisLabel(Element_Name_Selected.toStdString());
883 if (samples_selected.size()>0 && PlotType==plottype::elemental_profiles)
885 plottedData = std::make_unique<Elemental_Profile_Set>(
888 ui->ShowTabular->setEnabled(
true);
891 plotter->SetYAxisScaleType(ChartAxisScale::Logarithmic);
892 plotter->SetXAxisLabel(
"Constituent");
893 plotter->SetYAxisLabel(
"Value (log scale; zero and negative values not shown)");
898 ui->frame->setVisible(
true);
899 ui->frame->setEnabled(
true);
900 ui->btnZoom->setEnabled(
true);
905 QFile jsonFile(fileName);
906 if (!jsonFile.open(QFile::ReadOnly))
907 return QJsonDocument();
908 return QJsonDocument().fromJson(jsonFile.readAll());
912 QFile jsonFile(fileName);
913 if (!jsonFile.open(QFile::WriteOnly))
915 jsonFile.write(document.toJson());
923 const int bar = key.indexOf(
'|');
924 return bar < 0 ? key : key.mid(bar + 1);
931 QStringList keys = json.keys();
932 for (
const QString& jsonKey : keys)
935 if (json[jsonKey].isObject())
938 standardItem->appendRow(
ToQStandardItem(jsonKey, json[jsonKey].toObject()));
939 standardItem->setToolTip(
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);
957 QStandardItemModel* standardItemModel =
new QStandardItemModel();
958 QJsonObject jsonObject = jsonDocument.object();
961 standardItemModel->appendRow(rootItem);
963 return standardItemModel;
968 QModelIndexList selectedIndexes =
ui->treeView->selectionModel()->selectedIndexes();
970 if (!selectedIndexes.isEmpty())
972 return selectedIndexes[0].data(Qt::UserRole).toString();
980 QTreeView* tree =
ui->treeView;
981 QModelIndex index = tree->currentIndex();
983 if (!index.isValid())
992 menu = std::make_unique<QMenu>(
this);
996 QAction* showDistributions =
menu->addAction(
"Show fitted distributions");
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";
1004 showDistributions->setData(roleData);
1006 connect(showDistributions, &QAction::triggered,
1012 menu->exec(tree->mapToGlobal(pos));
1018 QAction* action = qobject_cast<QAction*>(sender());
1024 QStringList keysStringList = action->data().toStringList();
1025 QMap<QString, QString> keys;
1027 for (
const QString& keyValue : keysStringList)
1029 QStringList parts = keyValue.split(
"=");
1030 if (parts.size() == 2)
1032 keys[parts[0]] = parts[1];
1036 QString element = keys[
"Element"];
1037 QString group = keys[
"Group"];
1038 QString sample = keys[
"Sample"];
1039 QString actionType = keys[
"Action"];
1041 if (actionType !=
"SFD")
1048 if (group.isEmpty())
1051 TimeSeries<double> elementDist =
1052 dataCollection.GetFittedDistribution(element.toStdString())->EvaluateAsTimeSeries();
1054 plotWindow->
Plotter()->AddTimeSeries(
1056 elementDist.tToStdVector(),
1057 elementDist.ValuesToStdVector()
1064 ->GetElementDistribution(element.toStdString())
1065 ->GetFittedDistribution()
1066 ->EvaluateAsTimeSeries();
1068 plotWindow->
Plotter()->AddTimeSeries(
1070 elementDist.tToStdVector(),
1071 elementDist.ValuesToStdVector()
1078 TimeSeries<double> elementDist =
1080 ->GetElementDistribution(element.toStdString())
1081 ->GetFittedDistribution()
1082 ->EvaluateAsTimeSeries();
1084 plotWindow->
Plotter()->AddTimeSeries(
1085 (group +
":" + element).toStdString(),
1086 elementDist.tToStdVector(),
1087 elementDist.ValuesToStdVector()
1091 plotWindow->setWindowTitle(element);
1092 plotWindow->
Plotter()->SetLegend(
true);
1100 formElems->
setModel(elementTableModel);
1103 formElems->
table()->setItemDelegate(elemDelegate);
1105 ui->verticalLayout_middle->addWidget(formElems);
1116 QMessageBox::warning(
1119 tr(
"No data has been loaded."),
1124 QStringList groupNames;
1125 for (
const std::string& groupName :
dataCollection.GetGroupNames())
1126 groupNames << QString::fromStdString(groupName);
1128 const QString current = QString::fromStdString(
dataCollection.GetTargetGroup());
1130 const QString target = QInputDialog::getItem(
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."),
1136 qMax(0, groupNames.indexOf(current)),
1140 if (!ok || target.isEmpty() || target == current)
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),
1156 if (
Data()->count(
Data()->GetTargetGroup()) == 0)
1160 QMessageBox::warning(
1163 tr(
"This project has no target group. Reopen it and select the group that holds the target samples."),
1169 if (
Data()->GetOptions()->value(
"Outlier deviation threshold") == 3)
1175 double outlierThreshold =
Data()->
GetOptions()->value(
"Outlier deviation threshold");
1186 ui->verticalLayout_middle->addWidget(sampleSelector);
1196 QMessageBox::warning(
1199 tr(
"Organic Matter and Size Correction must be performed first."),
1210 ui->verticalLayout_middle->addWidget(sampleSelector);
1222 QMessageBox::warning(
1225 tr(
"No data has been loaded."),
1232 QString toolName = index.data(Qt::UserRole).toString();
1234 if (mainJsonObject.contains(toolName))
1238 QJsonObject formObject = mainJsonObject.value(toolName).toObject();
1240 centralform = std::make_unique<GenericForm>(&formObject,
this,
this);
1260 if (!resultSetItem || !resultSetItem->
result)
1262 qWarning() <<
"Invalid result item at row" << index.row();
1270 resultsWindow->setWindowTitle(resultSetItem->text());
1272 for (
auto it = resultSet->begin(); it != resultSet->end(); ++it)
1277 resultsWindow->show();
1285 bool outcome =
false;
1288 outcome =
conductor->Execute(command, arguments);
1290 catch (
const std::exception& exception)
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())));
1299 QMessageBox::critical(
this, tr(
"Analysis failed"),
1300 tr(
"The analysis '%1' stopped with an unknown error.")
1301 .arg(QString::fromStdString(command)));
1314 QString timestamp = QDateTime::currentDateTime().toString(Qt::TextDate);
1315 QString resultName = QString::fromStdString(resultsForStorage->
GetName()) +
"_" + timestamp;
1319 resultSetItem->setToolTip(resultName);
1320 resultSetItem->
result = resultsForStorage;
1326 resultsWindow->setWindowTitle(resultName);
1329 for (
auto it = resultsForStorage->begin(); it != resultsForStorage->end(); ++it)
1334 resultsWindow->show();
1360 qWarning() <<
"Attempted to delete with invalid index";
1367 int ret = QMessageBox::question(
1369 tr(
"Delete Result"),
1370 tr(
"Are you sure you want to delete '%1'?").arg(item->text()),
1371 QMessageBox::Yes | QMessageBox::No,
1375 if (ret == QMessageBox::Yes)
1384 QString recentFilePath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)
1387 QFile file(recentFilePath);
1388 if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
1398 const QByteArray contents = file.readAll();
1399 const bool readFailed = (file.error() != QFileDevice::NoError);
1400 const QString readError = file.errorString();
1405 qWarning() <<
"Failed to read recent files list:" << readError;
1409 QStringList allLines;
1410 const QStringList rawLines = QString::fromUtf8(contents).split(
'\n', Qt::SkipEmptyParts);
1412 for (
const QString& rawLine : rawLines)
1414 const QString line = rawLine.trimmed();
1415 if (!line.isEmpty())
1417 allLines.append(line);
1423 for (
int i = startIndex; i < allLines.size(); ++i)
1431 if (fileName.trimmed().isEmpty())
1436 QString trimmedFileName = fileName.trimmed();
1437 bool rewriteFile =
false;
1442 int existingIndex =
recentFiles.indexOf(trimmedFileName);
1448 QList<QAction*> actions =
ui->menuRecent->actions();
1449 int actionIndex =
recentFiles.size() - 1 - existingIndex;
1450 if (actionIndex >= 0 && actionIndex < actions.size())
1452 ui->menuRecent->removeAction(actions[actionIndex]);
1473 QList<QAction*> actions =
ui->menuRecent->actions();
1474 if (!actions.isEmpty())
1476 ui->menuRecent->removeAction(actions.last());
1486 QAction* fileAction =
new QAction(trimmedFileName,
this);
1488 QList<QAction*> actions =
ui->menuRecent->actions();
1489 if (!actions.isEmpty())
1491 ui->menuRecent->insertAction(actions.first(), fileAction);
1495 ui->menuRecent->addAction(fileAction);
1503 QString recentFilePath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)
1507 QFile file(recentFilePath);
1508 if (file.open(QIODevice::Append | QIODevice::Text))
1510 QTextStream out(&file);
1511 out << trimmedFileName <<
"\n";
1524 QString recentFilePath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)
1527 QFile file(recentFilePath);
1528 if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
1530 qWarning() <<
"Failed to write recent files list:" << file.errorString();
1534 QTextStream out(&file);
1537 out << fileName <<
"\n";
1545 QString localAppDataPath = QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation);
1547 return localAppDataPath;
1552 QAction* action = qobject_cast<QAction*>(sender());
1555 qWarning() <<
"Invalid sender in on_actionRecent_triggered";
1559 QString fileName = action->text();
1568 if (!selectedFileAction)
1573 recentFiles.removeAll(selectedFileAction->text());
1574 ui->menuRecent->removeAction(selectedFileAction);
1580 QFileInfo fileInfo(fileName);
1582 if (fileInfo.exists())
1587 QFile file(fileName);
1588 if (!file.open(QIODevice::WriteOnly))
1590 qWarning() <<
"Failed to create file:" << fileName <<
"-" << file.errorString();
1599 const QString& iconPath,
1600 const QString& toolTip,
1603 QAction* action =
new QAction(
this);
1604 action->setObjectName(text);
1605 action->setText(text);
1606 action->setToolTip(toolTip);
1608 QIcon icon(iconPath);
1611 action->setIcon(icon);
1615 qWarning() <<
"Failed to load icon:" << iconPath;
1618 ui->toolBar->addAction(action);
1619 connect(action, &QAction::triggered,
this, slot);
1630 iconPath +
"Import_Excel.png",
1631 "Import from Excel File",
1638 iconPath +
"Save.png",
1646 iconPath +
"open.png",
1652 ui->toolBar->addSeparator();
1656 "Constituents Selection/Properties",
1657 iconPath +
"Element_Props.png",
1658 "Constituents Selection/Properties",
1664 "Organic Matter and Size Correction",
1665 iconPath +
"OMSizeCorrection.png",
1666 "Organic Matter and Size Correction",
1673 iconPath +
"SelectSamples.png",
1683 qWarning() <<
"No data to display in table";
1688 tableViewer->setWindowFlag(Qt::WindowMinMaxButtonsHint);
1689 tableViewer->setWindowTitle(tr(
"Elemental Profiles"));
1691 QTableWidget* tableWidget =
plottedData->ToTable();
1692 tableViewer->
SetTable(tableWidget);
1694 tableViewer->show();
1721 return qApp->applicationDirPath() +
"/../Resources";
1724 return qApp->applicationDirPath() +
"/../../resources";
Professional about dialog for SedSat3 application.
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 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.
SourceSinkData * Data()
Returns pointer to the main data collection.
QMenu * ResultscontextMenu
Context menu for results view.
GeneralPlotter * plotter
Main plotting widget.
SourceSinkData dataCollection
Main data collection for analysis.
void showdistributionsforelements()
void on_show_data_as_table()
QString ProjectFileName
Current project file path.
QStandardItem * ToQStandardItem(const QString &key, const SourceSinkData *srcsinkdata)
std::unique_ptr< QStandardItemModel > columnViewModel
Model for column/data tree view.
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.
bool treeItemChangedProgramatically
Flag for programmatic tree changes.
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.
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.
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.
QString selectedTreeItemType
Currently selected tree item type.
void on_constituent_properties_triggered()
QStandardItemModel * ToQStandardItemModel(const SourceSinkData *srcsinkdata)
QString TreeQStringSelectedType()
void removeFromRecentList(QAction *selectedFileAction)
void writeRecentFilesList()
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.
QJsonObject buildResultsJson() const
Builds the results section of the project JSON.
QJsonDocument loadJson(const QString &fileName)
std::unique_ptr< QWidget > centralform
Central form widget.
QAction * DeleteAction
Delete action for results.
std::unique_ptr< Interface > plottedData
Currently plotted data interface.
void preparetreeviewMenu(const QPoint &pos)
void onOMSizeCorrection()
std::unique_ptr< GuiHost > analysis_host
Reports analyses through this window.
QStandardItem * ElementsToQStandardItem(const QString &key, const SourceSinkData *srcsinkdata)
void readRecentFilesList()
int sinkSheet
Index of sink sheet in Excel import.
void on_plot_raw_elemental_profiles()
void setupToolBar()
Initializes the general toolbar.
void onCustomContextMenu(const QPoint &pos)
QModelIndex indexresultselected
Currently selected result index.
void on_tree_selectionChanged(const QItemSelection &changed)
~MainWindow()
Destructor - cleans up UI resources.
void saveJson(const QJsonDocument &document, const QString &fileName)
void onIncludeExcludeSample()
void on_tool_executed(const QModelIndex &index)
GeneralChartPlotter * Plotter()
void SetTable(QTableWidget *tablewidget)
void SetResults(Results *res)
void AppendResult(const ResultItem &resultitem, const std::string &key)
QJsonObject toJsonObject()
bool ReadFromJson(const QJsonObject &jsonobject)
void SetData(SourceSinkData *_data)
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 max_num_recent_files
QString localAppFolderAddress()
Returns the local application folder address.
static QString ToolDisplayName(const QString &key)
The one place where data values entering SedSAT3 are checked.
vector< vector< double > > values
vector< string > element_names
vector< string > sample_names