Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 40 additions & 13 deletions EMRALD_Sim/FormMain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ public partial class FormMain : Form, IMessageDispHandling
private int _pathResultsInterval = -1;
private List<string> _recentFiles = new List<string>();
private bool _skipApplyOptionsOnce = false;
private bool _applyingOptionsToUI = false;
private bool _isCommandLineRun = false;
private bool _pendingAutoRun = false; // command-line run is deferred to FormMain_Load so the window handle exists before the sim marshals UI updates
private Options_cur _curSimOptions = new Options_cur();
Expand Down Expand Up @@ -892,10 +893,11 @@ private void UIProgressCallback(TimeSpan runTime, int runCnt, bool logFailedComp
private void DispResults(TimeSpan runTime, int runCnt, bool logFailedComps, int? threadNum)
{
int curT = 0;
if (_running && cbMultiThreaded.Checked && cbCurThread.Visible)
curT = cbCurThread.SelectedIndex;
bool showOverallResults = threadNum == null;
if (!showOverallResults && _running && cbMultiThreaded.Checked && cbCurThread.Visible)
curT = Math.Max(cbCurThread.SelectedIndex, 0);

if ((_lastError == "") && ((threadNum == null) || (curT == (int)threadNum))) //only update for specified thread or if there is none specified
if ((_lastError == "") && (showOverallResults || (curT == threadNum.Value))) //only update for specified thread or if there is none specified
{
lbl_ResultHeader.Text = _sim.name + " " + runCnt.ToString() + " of " + tbRunCnt.Text + " runs.";
lblRunTime.Text = runTime.ToString("g");
Expand Down Expand Up @@ -1166,7 +1168,16 @@ private void ApplyOptionsToUI()
tbLogRunStart.Text = _curSimOptions.debugStartIdx > 0 ? _curSimOptions.debugStartIdx.ToString() : "1";
tbLogRunEnd.Text = _curSimOptions.debugEndIdx > 0 ? _curSimOptions.debugEndIdx.ToString() : tbRunCnt.Text;

cbMultiThreaded.Checked = _curSimOptions.threads > 0;
_applyingOptionsToUI = true;
try
{
cbMultiThreaded.Checked = _curSimOptions.threads > 0;
}
finally
{
_applyingOptionsToUI = false;
}
UpdateMultiThreadControlsVisibility();

// Coupling settings
if (_curSimOptions.couplingInfo == null)
Expand Down Expand Up @@ -1232,6 +1243,16 @@ private void ApplyOptionsToUI()
ValidateOptionsVariables();
}

private void UpdateMultiThreadControlsVisibility()
{
tbThreads.Visible = cbMultiThreaded.Checked;
lblThreads.Visible = cbMultiThreaded.Checked;
cbClearTemps.Visible = cbMultiThreaded.Checked;
lbl_CurThread.Visible = cbMultiThreaded.Checked && (!_running);
cbCurThread.Visible = cbMultiThreaded.Checked;
bttnPathRefs.Visible = cbMultiThreaded.Checked;
}

// Verify that every name in _curSimOptions.variables and initVars exists in the loaded model.
// Reports any mismatches to the console and to txtMStatus.
private void ValidateOptionsVariables()
Expand Down Expand Up @@ -1700,13 +1721,24 @@ private void btn_DebugOpen_Click(object sender, EventArgs e)

private void cbMultiThreaded_CheckedChanged(object sender, EventArgs e)
{
if (_applyingOptionsToUI)
{
UpdateMultiThreadControlsVisibility();
SetCurThreadCB();
return;
}

Cursor.Current = Cursors.WaitCursor;
try
{
if (_sim == null)
if (_sim == null || !_validSim || string.IsNullOrWhiteSpace(_sim.modelTxt))
{
MessageBox.Show("You must load a model before enabling multi-threaded mode.", "No Model Loaded", MessageBoxButtons.OK, MessageBoxIcon.Warning);
cbMultiThreaded.Checked = false;
if (cbMultiThreaded.Checked)
{
MessageBox.Show("You must load a valid model before enabling multi-threaded mode.", "No Valid Model Loaded", MessageBoxButtons.OK, MessageBoxIcon.Warning);
cbMultiThreaded.Checked = false;
}
UpdateMultiThreadControlsVisibility();
return;
}

Expand Down Expand Up @@ -1764,12 +1796,7 @@ private void cbMultiThreaded_CheckedChanged(object sender, EventArgs e)
tbSeed.Enabled = false;
}

tbThreads.Visible = cbMultiThreaded.Checked;
lblThreads.Visible = cbMultiThreaded.Checked;
cbClearTemps.Visible = cbMultiThreaded.Checked;
lbl_CurThread.Visible = cbMultiThreaded.Checked && (!_running);
cbCurThread.Visible = cbMultiThreaded.Checked;
bttnPathRefs.Visible = cbMultiThreaded.Checked;
UpdateMultiThreadControlsVisibility();

LoadLib.SetThreads(tbThreads.Text);
SetCurThreadCB();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -180,10 +180,11 @@ export const EventActions: React.FC<EventActionsProps> = ({ state }) => {
&nbsp;
{action.name}
</Typography>
{isStateInCurrentDiagram(action) ? (
{isStateInCurrentDiagram(action, state.diagramName) ? (
<></>
) : (
<FaLink
data-testid="diagram-link-icon"
onClick={() => {
openDiagramFromNewState(action);
}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,11 @@ export const ImmediateActions: React.FC<ImmediateActionsProps> = ({
}}
>
<Typography sx={{ fontSize: 10, ml: '5px' }}>{action}</Typography>
{isStateInCurrentDiagram(actionValue) ? (
{isStateInCurrentDiagram(actionValue, state.diagramName) ? (
<></>
) : (
<FaLink
data-testid="diagram-link-icon"
onClick={() => {
if (actionValue) {
openDiagramFromNewState(actionValue);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -265,12 +265,19 @@ export function useEmraldDiagram() {

// Check if the new states are in this diagram (the one this hook instance
// is bound to), not whichever diagram last rendered into the shared signal.
const isStateInCurrentDiagram = (action?: Action) =>
action
? getActionNewStates(action).every(newState =>
getCurrentDiagramStates().includes(newState),
)
: false;
const isStateInCurrentDiagram = (action?: Action, diagramName?: string) => {
if (!action) {
return false;
}

const diagramStates = diagramName
? (getDiagramByDiagramName(diagramName)?.states ?? [])
: getCurrentDiagramStates();

return getActionNewStates(action).every(newState =>
diagramStates.includes(newState),
);
};

// Find and open window for diagram that has new states
const openDiagramFromNewState = (action: Action) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ interface ActionFormContextType {
openSimVarParams?: boolean;
makeInputFileCode?: string;
exePath?: string;
exeFromPreCode: boolean;
processOutputFileCode?: string;
formData?: MAAPFormData;
hasError: boolean;
Expand Down Expand Up @@ -98,6 +99,7 @@ interface ActionFormContextType {
setNewStateItems: Dispatch<SetStateAction<NewStateItem[] | undefined>>;
setMakeInputFileCode: Dispatch<SetStateAction<string | undefined>>;
setExePath: Dispatch<SetStateAction<string | undefined>>;
setExeFromPreCode: Dispatch<SetStateAction<boolean>>;
setProcessOutputFileCode: Dispatch<SetStateAction<string | undefined>>;
setFormData: Dispatch<SetStateAction<MAAPFormData | undefined>>;
setHasError: Dispatch<SetStateAction<boolean>>;
Expand Down Expand Up @@ -193,6 +195,7 @@ export const ActionFormContextProvider: React.FC<PropsWithChildren> = ({
const [reqPropsFilled, setReqPropsFilled] = useState<boolean>(false);
const [originalName, setOriginalName] = useState<string>();
const [exePath, setExePath] = useState(formData?.exePath);
const [exeFromPreCode, setExeFromPreCode] = useState(false);
const { updateVariable, createVariable } = useVariableContext();
const [returnProcess, setReturnProcess] = useState<
ReturnProcessType | undefined
Expand Down Expand Up @@ -371,6 +374,7 @@ export const ActionFormContextProvider: React.FC<PropsWithChildren> = ({
simEndTime,
makeInputFileCode,
exePath,
...(actType === 'atRunExtApp' ? { ExeFromPreCode: exeFromPreCode } : {}),
processOutputFileCode,
openSimVarParams,
mainItem: true,
Expand Down Expand Up @@ -588,6 +592,7 @@ export const ActionFormContextProvider: React.FC<PropsWithChildren> = ({
setSimEndTime(undefined);
setMakeInputFileCode(undefined);
setExePath(undefined);
setExeFromPreCode(false);
setProcessOutputFileCode(undefined);
setFormData(undefined); // Assuming formData can be undefined
setHasError(false); // Default value for hasError
Expand Down Expand Up @@ -650,6 +655,7 @@ export const ActionFormContextProvider: React.FC<PropsWithChildren> = ({
// run app items
setMakeInputFileCode(actionData?.makeInputFileCode);
setExePath(actionData?.exePath);
setExeFromPreCode(actionData?.ExeFromPreCode ?? false);
setProcessOutputFileCode(actionData?.processOutputFileCode);
setFormData(actionData?.formData);
setRaType(actionData?.raType);
Expand Down Expand Up @@ -680,6 +686,7 @@ export const ActionFormContextProvider: React.FC<PropsWithChildren> = ({
simEndTime,
makeInputFileCode,
exePath,
exeFromPreCode,
processOutputFileCode,
formData,
hasError,
Expand Down Expand Up @@ -712,6 +719,7 @@ export const ActionFormContextProvider: React.FC<PropsWithChildren> = ({
setNewStateItems,
setMakeInputFileCode,
setExePath,
setExeFromPreCode,
setProcessOutputFileCode,
setFormData,
setHasError,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import type { CustomFormType } from '../../../../../types/EMRALD_Model';
import {
Box,
Checkbox,
FormControl,
FormControlLabel,
InputLabel,
MenuItem,
Radio,
RadioGroup,
Select,
Tooltip,
Typography,
} from '@mui/material';
import { startCase } from 'lodash';
Expand All @@ -28,6 +30,7 @@ export const RunApplication: React.FC = () => {
codeVariables,
makeInputFileCode,
exePath,
exeFromPreCode,
processOutputFileCode,
raType,
returnProcess,
Expand All @@ -36,6 +39,7 @@ export const RunApplication: React.FC = () => {
addToUsedVariables,
setMakeInputFileCode,
setExePath,
setExeFromPreCode,
setProcessOutputFileCode,
setRaType,
setFormData,
Expand Down Expand Up @@ -128,6 +132,19 @@ export const RunApplication: React.FC = () => {
codeVariables={codeVariables}
/>

<Tooltip title="Check this box if the preprocessor code determines the executable and is art of the return string">
<FormControlLabel
control={
<Checkbox
checked={exeFromPreCode}
onChange={event => {
setExeFromPreCode(event.target.checked);
}}
/>
}
label="Exe in Preprocessor code"
/>
</Tooltip>
<TextFieldComponent
label="Executable Location"
value={exePath ?? ''}
Expand Down
59 changes: 49 additions & 10 deletions Emrald-UI/src/components/layout/Header/menuOptions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,41 @@ import {
type TimelineOptions,
} from '../../diagrams/SankeyTimelineDiagram/SankeyTimelineDiagram';

function normalizeModelObjType(model: EMRALD_Model): EMRALD_Model {
type StateWithLegacyGeometry = EMRALD_Model['StateList'][number] & {
geometry?: unknown;
};

type LogicNodeWithLegacyRootName = EMRALD_Model['LogicNodeList'][number] & {
rootName?: string;
};

const normalizeState = (state: EMRALD_Model['StateList'][number]) => {
const { geometry: _geometry, ...stateWithoutGeometry }
= state as StateWithLegacyGeometry;
return stateWithoutGeometry;
};

const normalizeLogicNode = (
logicNode: EMRALD_Model['LogicNodeList'][number],
) => {
const { rootName, isRoot, ...logicNodeWithoutRootName }
= logicNode as LogicNodeWithLegacyRootName;
return {
...logicNodeWithoutRootName,
isRoot: isRoot || rootName === logicNode.name,
};
};

return {
...model,
objType: 'EMRALD_Model',
StateList: model.StateList.map(state => normalizeState(state)),
LogicNodeList: model.LogicNodeList.map(logicNode => normalizeLogicNode(logicNode)),
templates: model.templates?.map(template => normalizeModelObjType(template)),
};
}

export const projectOptions = {
New(newProject: () => void) {
newProject();
Expand Down Expand Up @@ -52,10 +87,10 @@ export const projectOptions = {
const upgradedModel = upgradeModel(content);
if (upgradedModel) {
upgradedModel.id = uuidv4();
populateNewData(upgradedModel);
populateNewData(normalizeModelObjType(upgradedModel));
}
} else {
populateNewData(parsedContent);
populateNewData(normalizeModelObjType(parsedContent));
}
} catch (error) {
console.error('Invalid JSON format');
Expand Down Expand Up @@ -105,12 +140,12 @@ export const projectOptions = {
if (
Object.prototype.hasOwnProperty.call(parsedContent, 'emraldVersion')
) {
mergeNewData(parsedContent);
mergeNewData(normalizeModelObjType(parsedContent));
} else {
const upgradedModel = upgradeModel(content);
if (upgradedModel) {
upgradedModel.id = uuidv4();
mergeNewData(upgradedModel);
mergeNewData(normalizeModelObjType(upgradedModel));
}
}
} catch (error) {
Expand Down Expand Up @@ -139,7 +174,7 @@ export const projectOptions = {
validationResult: ModelValidationResult,
) => boolean | Promise<boolean>,
) => {
const data = structuredClone(appData.value);
const data = normalizeModelObjType(structuredClone(appData.value));
data.desc = data.desc ?? ''; // Ensure desc is a string before validating and saving.

const validationResult = validateModel(data);
Expand Down Expand Up @@ -274,12 +309,12 @@ export const projectOptions = {
if (
Object.prototype.hasOwnProperty.call(parsedContent, 'emraldVersion')
) {
compareData(parsedContent);
compareData(normalizeModelObjType(parsedContent));
} else {
const upgradedModel = upgradeModel(content);
if (upgradedModel) {
upgradedModel.id = uuidv4();
compareData(upgradedModel);
compareData(normalizeModelObjType(upgradedModel));
}
}
} catch (error) {
Expand Down Expand Up @@ -333,12 +368,12 @@ export const templateSubMenuOptions = {
const parsedContent = JSON.parse(content) as EMRALD_Model[];
for (const model of parsedContent) {
if (Object.prototype.hasOwnProperty.call(model, 'emraldVersion')) {
mergeTemplateToList(model);
mergeTemplateToList(normalizeModelObjType(model));
} else {
const upgradedModel = upgradeModel(JSON.stringify(model));
if (upgradedModel) {
upgradedModel.id = uuidv4();
mergeTemplateToList(upgradedModel);
mergeTemplateToList(normalizeModelObjType(upgradedModel));
}
}
}
Expand Down Expand Up @@ -368,7 +403,11 @@ export const templateSubMenuOptions = {
return 'error';
}
// Convert JSON data to a string
const jsonString = JSON.stringify(templates, null, 2);
const jsonString = JSON.stringify(
templates.map(template => normalizeModelObjType(template)),
null,
2,
);

// Create a Blob (Binary Large Object) with the JSON string
const blob = new Blob([jsonString], { type: 'application/json' });
Expand Down
Loading