Commit 35ce1705 authored by Alexander Dietsch's avatar Alexander Dietsch

Simulator:

-Fixed minor bugs occuring on rare conditions

Dissertation:
Finished dissertation
parent 8f0d4580
......@@ -41,7 +41,7 @@ namespace LWSimulatorCons
}
} },
{
"e|execute", "automatically run the program; sets clock-rate to 0 and sets parameter '--quarantined'",
"r|run", "automatically run the code; sets clock-rate to 0 and sets parameter '--quarantined'",
v => {
if(v != null)
{
......@@ -73,11 +73,11 @@ namespace LWSimulatorCons
"q|quarantined", "disallow the simulator to save the options so they won't carry over to the next start; will be set automatically if paremeter '--run' is set",
v => quarantined = v != null },
{
"R|variables=", "set variable file",
"V|variables=", "set variable file",
v => variablePath = v },
{
"r|limit-variables=", "limit the number of variables that any program is allowed to use at most; default is 100",
"v|limit-variables=", "limit the number of variables that any code is allowed to use at most; default is 100",
v => {
if (!tryParseValue(v,out limitVariables))
{
......@@ -86,7 +86,7 @@ namespace LWSimulatorCons
}
} },
{
"s|limit-steps=", "limit the number of steps that any program is allowed to do at most before being interrupted; default is 0 (off)",
"s|limit-steps=", "limit the number of steps that any code is allowed to do at most before being interrupted; default is 0 (off)",
v => {
if (!tryParseValue(v,out limitSteps))
{
......@@ -159,7 +159,7 @@ namespace LWSimulatorCons
if (!errors[0] && limitVariables != long.MaxValue)
{
if(limitVariables <= 0 || !simulator.setOptionVal("maxRegAm",limitVariables))
if(limitVariables <= 0 || !simulator.setOptionVal("maxVarAm",limitVariables))
{
errorInd = true;
errors[1] = true;
......@@ -218,9 +218,9 @@ namespace LWSimulatorCons
{
if(!simulator.allInitialized())
{
printLog("WARNING: The LWSimulator DLL uses callback functions unknown to this console application.");
printLog(new List<string> { "WARNING: The LWSimulator DLL uses callback functions unknown to this console application." });
}
simulator.runProgram(program);
simulator.runProgram(program,inputPath);
waitForFinish.WaitOne();
#if (DEBUG)
Console.ReadLine();
......@@ -294,15 +294,18 @@ namespace LWSimulatorCons
return true;
}
private static void printLog(string s)
private static void printLog(List<string> s)
{
if (logLevel == 2 && !s.StartsWith("Code returned") && !s.StartsWith("Syntax"))
return;
if (logLevel == 1 && !(s.StartsWith("WARNING") || s.StartsWith("ERROR") || s.StartsWith("Code returned") || s.StartsWith("Syntax")))
return;
if (logLevel == 0 && s.StartsWith("DEBUG"))
return;
Console.WriteLine(s);
for (int i = 0; i < s.Count; i++)
{
if (logLevel == 2 && !s[i].StartsWith("Code returned") && !s[i].StartsWith("Syntax"))
continue;
if (logLevel == 1 && !(s[i].StartsWith("WARNING") || s[i].StartsWith("ERROR") || s[i].StartsWith("Code returned") || s[i].StartsWith("Syntax")))
continue;
if (logLevel == 0 && s[i].StartsWith("DEBUG"))
continue;
Console.WriteLine(s[i]);
}
}
/// <summary>
......
......@@ -18,9 +18,9 @@ namespace LWSimulatorGUI
{
InitializeComponent();
simul = coord;
nUDValue.Value = simul.getOptionVal("defRegVal");
nUDValue.Value = simul.getOptionVal("defVarVal");
nUDVariable.Maximum = simul.getVariableAmount() - 1;
nUDVariableAm.Maximum = simul.getOptionVal("maxRegAm") - simul.getVariableAmount();
nUDVariableAm.Maximum = simul.getOptionVal("maxVarAm") - simul.getVariableAmount();
// Attempt to get some uniformity between platforms
nUDVariableAm.Location = new Point(lInsert.Location.X + lInsert.Width + 6, nUDVariableAm.Location.Y);
......
......@@ -93,23 +93,23 @@
<Compile Include="CustomRichTextBox.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="DeleteRegisters.cs">
<Compile Include="DeleteVariables.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="DeleteRegisters.Designer.cs">
<DependentUpon>DeleteRegisters.cs</DependentUpon>
<Compile Include="DeleteVariables.Designer.cs">
<DependentUpon>DeleteVariables.cs</DependentUpon>
</Compile>
<Compile Include="ShiftRegisters.cs">
<Compile Include="ShiftVariables.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="ShiftRegisters.Designer.cs">
<DependentUpon>ShiftRegisters.cs</DependentUpon>
<Compile Include="ShiftVariables.Designer.cs">
<DependentUpon>ShiftVariables.cs</DependentUpon>
</Compile>
<Compile Include="InsertRegisters.cs">
<Compile Include="InsertVariables.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="InsertRegisters.Designer.cs">
<DependentUpon>InsertRegisters.cs</DependentUpon>
<Compile Include="InsertVariables.Designer.cs">
<DependentUpon>InsertVariables.cs</DependentUpon>
</Compile>
<Compile Include="DoubleBufferedListBox.cs">
<SubType>Component</SubType>
......@@ -140,14 +140,14 @@
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="SimpleGUISimulation.cs" />
<EmbeddedResource Include="DeleteRegisters.resx">
<DependentUpon>DeleteRegisters.cs</DependentUpon>
<EmbeddedResource Include="DeleteVariables.resx">
<DependentUpon>DeleteVariables.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="ShiftRegisters.resx">
<DependentUpon>ShiftRegisters.cs</DependentUpon>
<EmbeddedResource Include="ShiftVariables.resx">
<DependentUpon>ShiftVariables.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="InsertRegisters.resx">
<DependentUpon>InsertRegisters.cs</DependentUpon>
<EmbeddedResource Include="InsertVariables.resx">
<DependentUpon>InsertVariables.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="LogWindow.resx">
<DependentUpon>LogWindow.cs</DependentUpon>
......
......@@ -191,16 +191,19 @@ namespace LWSimulatorGUI
/// Makes the GUI add a line.
/// </summary>
/// <param name="line">The line to be added.</param>
internal void addLine_Notify(string line)
internal void addLine_Notify(List<string> lines)
{
if (line.StartsWith("DEBUG"))
if(simulator.getOptionVal("advancedLog") == 0)
return;
lock(toAddToLog)
{
if (toAddToLog.Count >= simulator.getOptionVal("maxLogLines"))
toAddToLog.RemoveFirst();
toAddToLog.AddLast(line);
for (int i = 0; i < lines.Count; i++)
{
if (lines[i].StartsWith("DEBUG"))
if (simulator.getOptionVal("advancedLog") == 0)
continue;
if (toAddToLog.Count >= simulator.getOptionVal("maxLogLines"))
toAddToLog.RemoveFirst();
toAddToLog.AddLast(lines[i]);
}
}
if (InvokeRequired)
this.Invoke((MethodInvoker)delegate
......
......@@ -429,7 +429,7 @@ namespace LWSimulatorGUI
changeCurCharIndex(curCharIndex);
// create & set Point pt to (0,0)
Point pt = new Point(0, 0);
// get First Index & First Line from richTextBox1
// get First Index & First Line
int First_Index = fCTBProgram.GetCharIndexFromPosition(pt);
int First_Line = fCTBProgram.GetLineFromCharIndex(First_Index);
// set X & Y coordinates of Point pt to ClientRectangle Width & Height respectively
......@@ -803,7 +803,7 @@ namespace LWSimulatorGUI
/// <param name="e">Arguments of the type <see cref="ElapsedEventArgs">ElapsedEventArgs</see></param>
private void FailSafeTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
log.addLine_Notify("DEBUG: FailSafe timed out; Rechecking state.");
log.addLine_Notify(new List<string> { "DEBUG: FailSafe timed out; Rechecking state." });
UpdateRunningStateChange();
}
......@@ -991,7 +991,7 @@ namespace LWSimulatorGUI
if (lineNumb == -1)
lineNumb = fCTBProgram.Lines.Length;
log.addLine_Notify(string.Format("Syntax error in line {0}, position {1}: {2}", lineNumb, p.Position - totalCount, p.Message));
log.addLine_Notify(new List<string> { string.Format("Syntax error in line {0}, position {1}: {2}", lineNumb, p.Position - totalCount, p.Message) });
}
}
}
......@@ -1118,7 +1118,7 @@ namespace LWSimulatorGUI
if (!string.IsNullOrEmpty(currentFilePath))
oFDRegs.InitialDirectory = Path.GetDirectoryName(currentFilePath);
oFDRegs.Filter = "LWVariable files (*.lwreg)|*.lwreg|txt files (*.txt)|*.txt|All files (*.*)|*.*";
oFDRegs.Filter = "LWVariable files (*.lwVar)|*.lwVar|txt files (*.txt)|*.txt|All files (*.*)|*.*";
oFDRegs.FilterIndex = 1;
oFDRegs.RestoreDirectory = true;
oFDRegs.CheckFileExists = true;
......@@ -1160,12 +1160,12 @@ namespace LWSimulatorGUI
else
suggestedName = String.Format("{0}_Variables", Path.GetFileNameWithoutExtension(currentFilePath));
SaveFileDialog save = new SaveFileDialog();
save.Filter = "LWVariable files (*.lwreg)|*.lwreg|txt files (*.txt)|*.txt|All files (*.*)|*.*";
save.Filter = "LWVariable files (*.lwVar)|*.lwVar|txt files (*.txt)|*.txt|All files (*.*)|*.*";
save.FilterIndex = 1;
save.RestoreDirectory = true;
save.OverwritePrompt = true;
save.CheckPathExists = true;
save.FileName = suggestedName + ".lwreg";
save.FileName = suggestedName + ".lwVar";
if (save.ShowDialog() == DialogResult.OK)
{
......
......@@ -23,8 +23,8 @@ namespace LWSimulatorGUI
new ToolTip().SetToolTip(pBHelpRegDefVal, "Initializes every newly added variable with given number.");
new ToolTip().SetToolTip(pBHelpAdvancedLog, "Log will not only display actions of the program\nbut also debug information.");
simulator = simul;
nUDVariables.Value = simul.getOptionVal("maxRegAm");
nUDRegDefVal.Value = simul.getOptionVal("defRegVal");
nUDVariables.Value = simul.getOptionVal("maxVarAm");
nUDRegDefVal.Value = simul.getOptionVal("defVarVal");
nUDLogLines.Value = simul.getOptionVal("maxLogLines");
chBClearLog.Checked = (simul.getOptionVal("clearLog") != 0);
chBAdvancedLog.Checked = (simul.getOptionVal("advancedLog") != 0);
......@@ -84,9 +84,9 @@ namespace LWSimulatorGUI
{
List<string> unableOptions = new List<string>();
bool validDir = Directory.Exists(tBDirPath.Text);
if (!simulator.setOptionVal("maxRegAm", (long)nUDVariables.Value))
if (!simulator.setOptionVal("maxVarAm", (long)nUDVariables.Value))
unableOptions.Add("-Maximum number of variables");
if(!simulator.setOptionVal("defRegVal", (long)nUDRegDefVal.Value))
if(!simulator.setOptionVal("defVarVal", (long)nUDRegDefVal.Value))
unableOptions.Add("-Default value of variables");
if(!simulator.setOptionVal("maxLogLines", (long)nUDLogLines.Value))
unableOptions.Add("-Maximum number of log lines");
......
......@@ -45,8 +45,8 @@ namespace LWSimulatorGUI
clearLog = emptyDummyMethod;
updateOptions = dummyMethod<string>;
logMessage = dummyMethod<string>;
optionVals.Add("maxRegAm", 100);
optionVals.Add("defRegVal", 0);
optionVals.Add("maxVarAm", 100);
optionVals.Add("defVarVal", 0);
optionVals.Add("maxLogLines", 300);
optionVals.Add("clearLog", 1);
optionVals.Add("timePerStep", 100);
......
......@@ -27,7 +27,7 @@ namespace MainLWSimulator
// Actions used
private Action<byte> notifyRunningStateChanged; // actionSet[0]
private Action<string> logMessage; // actionSet[1]
private Action<List<string>> logMessage; // actionSet[1]
private Action clearLog; // actionSet[2]
private Action<string> updateOptions; // actionSet[3]
private Action<int> startUpdateVariables; // actionSet[4]
......@@ -36,11 +36,14 @@ namespace MainLWSimulator
private Action<int> updateCharIndex; // actionSet[7]
private Action<string> saveLog; // actionSet[8]
// Keeping a backlog in case of fast forwarding
private List<string> backlog = new List<string>();
// Boolean Array to check whether all functions were properly set
private volatile bool[] actionSet = new bool[ACTION_COUNT];
// Variable for running state
private volatile byte running = 0; //0 - Program stopped; 1 - Program running; 2 - Program paused; 3 - In Single Step; 4 - Clean Up State
private volatile byte running = 0; //0 - Program stopped; 1 - Program running; 2 - Program paused; 3 - Single Step; 4 - Clean Up State; 5 - Fast Traversing
// object to lock runningState; WHENEVER RUNNING IS UPDATED MAKE SURE TO CALL notifyRunningStateChanged
private object runningLock = new object();
......@@ -72,7 +75,7 @@ namespace MainLWSimulator
private LWInterpreter lwInterpret;
// Variables
private LWVariables lwReg;
private LWVariables lwVar;
// Parser components by TinyPG
......@@ -89,7 +92,7 @@ namespace MainLWSimulator
private void dummyAction()
{
if (actionSet[1])
logMessage("WARNING: Trying to call a method that was not set.");
writeLogMessage("DEBUG: Trying to call a method that was not set.");
}
// Dummy Function for any kind of Action with one input
......@@ -120,7 +123,7 @@ namespace MainLWSimulator
loadOptions();
notifyRunningStateChanged = dummyAction<byte>;
logMessage = dummyAction<string>;
logMessage = dummyAction<List<string>>;
clearLog = dummyAction;
updateOptions = dummyAction<string>;
startUpdateVariables = dummyAction<int>;
......@@ -130,7 +133,7 @@ namespace MainLWSimulator
saveLog = dummyAction<string>;
lwTimer = new LWTimer(this, waitBetweenSteps, waitForCommandExecutionFinish, waitForTimerTick);
lwReg = new LWVariables(this);
lwVar = new LWVariables(this);
tPGscanner = new Scanner();
tPGparser = new Parser(tPGscanner);
}
......@@ -140,9 +143,9 @@ namespace MainLWSimulator
/// </summary>
private void setHardLimits()
{
HARDLIMITVALSHIGH.Add("maxRegAm", 10000);
HARDLIMITVALSHIGH.Add("maxVarAm", 10000);
HARDLIMITVALSHIGH.Add("maxStepAm", long.MaxValue);
HARDLIMITVALSHIGH.Add("defRegVal", 99999999999999);
HARDLIMITVALSHIGH.Add("defVarVal", 99999999999999);
HARDLIMITVALSHIGH.Add("maxLogLines", 10000);
HARDLIMITVALSHIGH.Add("clearLog", long.MaxValue);
HARDLIMITVALSHIGH.Add("timePerStep", 1000*1000); // 1000 seconds
......@@ -151,9 +154,9 @@ namespace MainLWSimulator
HARDLIMITVALSHIGH.Add("doHighlight", long.MaxValue);
HARDLIMITVALSHIGH.Add("cursorAtCurrent", long.MaxValue);
HARDLIMITVALSLOW.Add("maxRegAm", 1);
HARDLIMITVALSLOW.Add("maxVarAm", 1);
HARDLIMITVALSLOW.Add("maxStepAm", long.MinValue);
HARDLIMITVALSLOW.Add("defRegVal", 0);
HARDLIMITVALSLOW.Add("defVarVal", 0);
HARDLIMITVALSLOW.Add("maxLogLines", 1);
HARDLIMITVALSLOW.Add("clearLog", long.MinValue);
HARDLIMITVALSLOW.Add("timePerStep", 0);
......@@ -162,9 +165,9 @@ namespace MainLWSimulator
HARDLIMITVALSLOW.Add("doHighlight", long.MinValue);
HARDLIMITVALSLOW.Add("cursorAtCurrent", long.MinValue);
ALLOWRUNNINGCHANGE.Add("maxRegAm", 0);
ALLOWRUNNINGCHANGE.Add("maxVarAm", 0);
ALLOWRUNNINGCHANGE.Add("maxStepAm", 1);
ALLOWRUNNINGCHANGE.Add("defRegVal", 0);
ALLOWRUNNINGCHANGE.Add("defVarVal", 0);
ALLOWRUNNINGCHANGE.Add("maxLogLines", 2);
ALLOWRUNNINGCHANGE.Add("clearLog", 2);
ALLOWRUNNINGCHANGE.Add("timePerStep", 2);
......@@ -199,9 +202,9 @@ namespace MainLWSimulator
if (defVals)
{
optionVals.Clear();
optionVals.Add("maxRegAm", 100);
optionVals.Add("maxVarAm", 100);
optionVals.Add("maxStepAm", -50);
optionVals.Add("defRegVal", 0);
optionVals.Add("defVarVal", 0);
optionVals.Add("maxLogLines", 300);
optionVals.Add("clearLog", 1);
optionVals.Add("timePerStep", 100);
......@@ -226,9 +229,9 @@ namespace MainLWSimulator
long tmp;
if (!long.TryParse(loadedOpts[0], out tmp))
return false;
if (tmp < HARDLIMITVALSLOW["maxRegAm"] || tmp > HARDLIMITVALSHIGH["maxRegAm"])
if (tmp < HARDLIMITVALSLOW["maxVarAm"] || tmp > HARDLIMITVALSHIGH["maxVarAm"])
return false;
optionVals.Add("maxRegAm", tmp);
optionVals.Add("maxVarAm", tmp);
if(!long.TryParse(loadedOpts[1], out tmp))
return false;
......@@ -238,9 +241,9 @@ namespace MainLWSimulator
if (!long.TryParse(loadedOpts[2], out tmp))
return false;
if (tmp < HARDLIMITVALSLOW["defRegVal"] || tmp > HARDLIMITVALSHIGH["defRegVal"])
if (tmp < HARDLIMITVALSLOW["defVarVal"] || tmp > HARDLIMITVALSHIGH["defVarVal"])
return false;
optionVals.Add("defRegVal", tmp);
optionVals.Add("defVarVal", tmp);
if (!long.TryParse(loadedOpts[3], out tmp))
return false;
......@@ -301,9 +304,9 @@ namespace MainLWSimulator
try
{
string[] tmp = new string[OPTIONS_AM];
tmp[0] = optionVals["maxRegAm"].ToString();
tmp[0] = optionVals["maxVarAm"].ToString();
tmp[1] = optionVals["maxStepAm"].ToString();
tmp[2] = optionVals["defRegVal"].ToString();
tmp[2] = optionVals["defVarVal"].ToString();
tmp[3] = optionVals["maxLogLines"].ToString();
tmp[4] = optionVals["clearLog"].ToString();
tmp[5] = optionVals["timePerStep"].ToString();
......@@ -355,18 +358,18 @@ namespace MainLWSimulator
return false;
lock (runningLock)
{
if ((running != 0 && ALLOWRUNNINGCHANGE[name] == 0) || (running != 0 && running != 2 && ALLOWRUNNINGCHANGE[name] == 1))
if (running != 0 && (ALLOWRUNNINGCHANGE[name] == 0 || (running != 2 && ALLOWRUNNINGCHANGE[name] == 1)))
return false;
}
optionVals[name] = val;
if (name == "defRegVal")
lwReg.updateDefVal(val);
if(name == "maxRegAm")
if (name == "defVarVal")
lwVar.updateDefVal(val);
if(name == "maxVarAm")
{
if (lwReg.getSize() > val)
if (lwVar.getSize() > val)
{
bool changed;
lwReg.setSize((int)val, out changed);
lwVar.setSize((int)val, out changed);
if (!changed)
{
writeLogMessage("ERROR: Internal Interpreter Error; please inform developer.");
......@@ -445,13 +448,13 @@ namespace MainLWSimulator
/// <param name="clear">Function for clearing the log.</param>
/// <param name="saveLog">Function to save Log</param>
/// <returns>True on success; false if tried to set while running simulation.</returns>
public bool setLogFuncs(Action<string> logMsg, Action clear, Action<string> saveLog)
public bool setLogFuncs(Action<List<string>> logMsg, Action clear, Action<string> saveLog)
{
lock (runningLock)
{
if (running != 0)
{
logMessage("ERROR: Cannot set functions for logging while running simulation.");
writeLogMessage("ERROR: Cannot set functions for logging while running simulation.");
return false;
}
if (logMsg != null)
......@@ -484,7 +487,7 @@ namespace MainLWSimulator
{
if (running != 0)
{
logMessage("ERROR: Cannot set functions for running while running simulation.");
writeLogMessage("ERROR: Cannot set functions for running while running simulation.");
return false;
}
if (notifyStateChanged != null)
......@@ -507,7 +510,7 @@ namespace MainLWSimulator
{
if (running != 0)
{
logMessage("ERROR: Cannot set functions to update options while running simulation.");
writeLogMessage("ERROR: Cannot set functions to update options while running simulation.");
return false;
}
if (updateOptions != null)
......@@ -523,16 +526,16 @@ namespace MainLWSimulator
/// Sets Functions that need to be called on updating variables; split in 3 Functions for better performance with GUI.
/// </summary>
/// <param name="startUpdate">Function to be called when starting an update</param>
/// <param name="updateReg">Function to be called to actually update</param>
/// <param name="updateVar">Function to be called to actually update</param>
/// <param name="performUpdate">Function to be called when update is done</param>
/// <returns>True on success; false if tried to set while running simulation.</returns>
public bool setUpdateVariableFuncs(Action<int> startUpdate, Action<int,long> updateReg, Action performUpdate)
public bool setUpdateVariableFuncs(Action<int> startUpdate, Action<int,long> updateVar, Action performUpdate)
{
lock (runningLock)
{
if (running != 0)
{
logMessage("ERROR: Cannot set Functions to update variables while running simulation.");
writeLogMessage("ERROR: Cannot set Functions to update variables while running simulation.");
return false;
}
if (startUpdate != null)
......@@ -541,9 +544,9 @@ namespace MainLWSimulator
actionSet[4] = true;
}
if (updateReg != null)
if (updateVar != null)
{
setUpdateVariables = updateReg;
setUpdateVariables = updateVar;
actionSet[5] = true;
}
......@@ -567,7 +570,7 @@ namespace MainLWSimulator
{
if (running != 0)
{
logMessage("ERROR: Cannot set functions for running while running simulation.");
writeLogMessage("ERROR: Cannot set functions for running while running simulation.");
return false;
}
if (changeCurInd != null)
......@@ -608,7 +611,6 @@ namespace MainLWSimulator
/// <param name="code">Program code; optional parameter if already <see cref="setProgram(string)"/> was used.</param>
public void runProgram(string code = null, string path = null)
{
setProgram(code, path);
lock (runningLock)
{
if (running != 0 && running != 2)
......@@ -619,6 +621,10 @@ namespace MainLWSimulator
if (running == 0)
{
// reset log
if (getOptionVal("clearLog") != 0)
clearLog();
setProgram(code, path);
if (!createDefaultEnvironment())
return;
......@@ -647,7 +653,7 @@ namespace MainLWSimulator
{
lock (runningLock)
{
if (running != 1)
if (running != 1 && running != 5)
{
notifyRunningStateChanged(running); // Caller called invalid function; notify caller that his believed running state might be off
return;
......@@ -675,6 +681,9 @@ namespace MainLWSimulator
if (running == 0)
{
// reset log
if (getOptionVal("clearLog") != 0)
clearLog();
setProgram(code, path);
if (!createDefaultEnvironment())
return;
......@@ -703,6 +712,15 @@ namespace MainLWSimulator
{
lock (runningLock)
{
if(running == 0)
{
notifyRunningStateChanged(running); // Caller called invalid function; notify caller that his believed running state might be off
return;
}
if (running == 4)
return;
running = 4;
notifyRunningStateChanged(running);
lwTimer.changeState(false);
......@@ -717,7 +735,7 @@ namespace MainLWSimulator
waitForCodeExecutionFinish.Set();
if(userTerminated)
{
logMessage("--------- Simulation Terminated By User ---------");
writeLogMessage("--------- Simulation Terminated By User ---------");
}
if(getOptionVal("alwaysSaveLog")!=0 && !String.IsNullOrEmpty(logDirectory))
saveLog(logDirectory);
......@@ -767,19 +785,16 @@ namespace MainLWSimulator
return false;
// backup the current variables
lwReg.createBackup();
lwVar.createBackup();
// reset ResetEvents
waitForTimerTick.Reset();
waitForCommandExecutionFinish.Reset();
waitBetweenSteps.Reset();
waitForCodeExecutionFinish.Reset();
// reset log
if (getOptionVal("clearLog") != 0)
clearLog();
bool error = false;
lwInterpret = new LWInterpreter(this, lwReg, lineLengths, tPGtree, null, waitForTimerTick, waitForCommandExecutionFinish, waitForCodeExecutionFinish, out error);
lwInterpret = new LWInterpreter(this, lwVar, lineLengths, tPGtree, null, waitForTimerTick, waitForCommandExecutionFinish, waitForCodeExecutionFinish, out error);
if (error)
return false;
ThreadPool.QueueUserWorkItem(unused =>
......@@ -803,6 +818,29 @@ namespace MainLWSimulator
}
#endregion
/// <summary>
/// Writes out all the accumulated messages.
/// </summary>
internal void flushMessages()
{
List<string> toWrite;
if (backlog.Count != 0)
{
if (onUnix)
{
toWrite = new List<string>();
for (int i = 0; i < backlog.Count; i++)
{
toWrite.Add(backlog[i]);
}
}
else
toWrite = new List<string>(backlog);
backlog.Clear();
logMessage(toWrite);
}
}
/// <summary>
/// Function to write a string into the log;
/// Used in coordinator, so all components have access.
......@@ -810,7 +848,22 @@ namespace MainLWSimulator
/// <param name="s">Log Message</param>
internal void writeLogMessage(string s)
{
logMessage(s);
bool exit = false;
if (!Monitor.IsEntered(runningLock))
{
exit = true;
Monitor.Enter(runningLock);
}
while (getOptionVal("maxLogLines") < backlog.Count + 1)
backlog.RemoveAt(0);
backlog.Add(s);
if (running != 5)
{
flushMessages();
}
if (exit)
Monitor.Exit(runningLock);
}
#region VariableActions
......@@ -847,7 +900,7 @@ namespace MainLWSimulator
/// <returns>Number of variables</returns>
public int getVariableAmount()
{
return lwReg.getSize();
return lwVar.getSize();
}
/// <summary>
......@@ -857,7 +910,7 @@ namespace MainLWSimulator
/// <returns>Value of the variable</returns>
public long getVariableValue(int index)
{
return lwReg.getVariable(index);
return lwVar.getVariable(index);
}
/// <summary>
......@@ -872,10 +925,10 @@ namespace MainLWSimulator
{
if (running != 0)
{
logMessage("ERROR: Cannot edit variables while running simulation.");
writeLogMessage("ERROR: Cannot edit variables while running simulation.");
return false;
}
return lwReg.editVariable(index, value, false);
return lwVar.editVariable(index, value, false);
}
}
......@@ -893,10 +946,10 @@ namespace MainLWSimulator
{
if (running != 0)
{
logMessage("ERROR: Cannot insert variables while running simulation.");
writeLogMessage("ERROR: Cannot insert variables while running simulation.");
return false;
}
return lwReg.insertVariables(position, count, value);
return lwVar.insertVariables(position, count, value);
}
}
......@@ -912,10 +965,10 @@ namespace MainLWSimulator
{
if (running != 0)
{
logMessage("ERROR: Cannot remove variables while running simulation.");
writeLogMessage("ERROR: Cannot remove variables while running simulation.");
return false;
}
lwReg.removeVariables(position, count);
lwVar.removeVariables(position, count);
return true;
}
}
......@@ -933,10 +986,10 @@ namespace MainLWSimulator
{
if (running != 0)
{
logMessage("ERROR: Cannot shift variables while running simulation.");
writeLogMessage("ERROR: Cannot shift variables while running simulation.");
return false;
}
return lwReg.shiftVariables(position, count, shiftAmount);
return lwVar.shiftVariables(position, count, shiftAmount