using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using Amphora; using Annulus; using Azimuth; using Clave; using Foundations; namespace Glass.Testbed.TestCases.Errors { /// /// Throws from each kind of place a game can, to try out what is reported and what each answer does. /// public class ExceptionsTestCase : TestCase { private readonly World world; // The browser runs everything on one thread. private readonly bool hasThreads = !RuntimeInformation.IsOSPlatform(OSPlatform.Create("BROWSER")); private readonly FaultyMaterial faulty = new FaultyMaterial(); private readonly ExceptionSite scriptSite; private readonly HostWork worker; private readonly HostWork background = new HostWork("background thread"); private readonly HostWork fatal = new HostWork("fatal test"); private Label status; private string shownOutcome = string.Empty; // What last ran to its end, which a thread may write. private volatile string outcome = string.Empty; private bool throwsInUpdate; private bool scriptIsDue; private bool scriptHasFailed; public ExceptionsTestCase(World world) { this.world = world; scriptSite = new ExceptionSite(this, phase: 0); worker = new HostWork("worker thread", () => StartThread(worker, throws: false)); } private void StartThread(HostWork work, bool throws) { var thread = new Thread(() => { try { if (throws) { throw new InvalidOperationException($"A test exception from the {work}."); } outcome = $"The {work} finished."; } catch (Exception exception) { world.reporter.Post(exception, work); } }); thread.IsBackground = true; thread.Name = work.Name; thread.Start(); } private static void CrashAThread() { var thread = new Thread(() => throw new InvalidOperationException("A test exception nothing catches.")); thread.IsBackground = true; thread.Start(); } private void AddTrigger(string caption, string description, Action activated, bool enabled = true) { var button = new Button(ButtonBehavior.Default) { ButtonMaterial = world.skin.Button, Bounds = Rect.FromPositionAndSize(Vector.Zero, world.skin.ButtonSizeFor(caption)), Enabled = enabled, DebugName = caption, }; new Label(world.skin.ButtonText, caption).FillParent(button); button.OnActivate += (ButtonBase _, in KeyboardSnapshot __, KeyboardManager ___) => activated(); AddRow(button, description); } private void ThrowFatally() { try { throw new InvalidOperationException("A test exception nothing can carry on from."); } catch (Exception exception) { world.reporter.Sandbox.Record(exception, new ExceptionSite(fatal, phase: 0), notes: null, ExceptionSeverity.Fatal); } } private void AddPlayerCheckbox() { var box = new Checkbox(ButtonBehavior.Default) { UncheckedMaterial = UiPacksheetMaterials.CheckboxUnchecked, CheckedMaterial = UiPacksheetMaterials.CheckboxChecked, Bounds = Rect.FromPositionAndSize(Vector.Zero, UiPacksheetMaterials.CheckboxUnchecked.PreferredSize(Constraints.Unbounded)), Checked = !world.reporter.DeveloperMode, DebugName = "report as a player", }; box.OnCheckedChanged += checkedNow => world.reporter.DeveloperMode = !checkedNow; AddRow(box, "Report as a player would see it"); } protected override void Populate() { AddCaption("Each button throws once. The cases stop updating while a report is open"); AddPlayerCheckbox(); AddTrigger("UI handler", "Throws from this button's own handler", () => throw new InvalidOperationException("A test exception from a button.")); AddTrigger("Script step", "Throws from sandboxed code, which is then quarantined", () => { scriptHasFailed = false; scriptIsDue = true; }); AddTrigger("Frame update", "Throws from the game's own update", () => throwsInUpdate = true); AddTrigger("Drawing", "Throws while the square below is drawn", () => faulty.NextDraw.Armed = true); AddTrigger("Input handler", "Throws from a handler outside the UI, on the next click", () => world.faultyInput.Armed = true); AddTrigger("Worker thread", "Stops a thread, which continuing starts again", () => StartThread(worker, throws: true), hasThreads); AddTrigger("Background thread", "Throws on a thread that needs no restarting", () => StartThread(background, throws: true), hasThreads); AddTrigger("Fatal", "Reports an error that only quitting answers", ThrowFatally); AddTrigger("Report window", "Breaks the dark red report window, which a plain one replaces for good", () => { world.reportPanel.NextDraw.Armed = true; throwsInUpdate = true; }); AddTrigger("Crash the frame", "Throws where nothing catches it, which ends the program", () => world.CrashesNextUpdate = true); AddTrigger("Crash a thread", "Leaves a thread's exception uncaught, which ends the program", CrashAThread, hasThreads); var square = new Panel { Material = faulty }; Rect squareRow = ContentAggregator.NewRow(48); square.Bounds = squareRow.NewCol(48); Add(square); status = new Label(Widgets.SmallCaptionStyle, string.Empty); status.Bounds = ContentAggregator.NewRow(Widgets.SmallCaptionStyle.SingleLineHeight); Add(status); } // Its own frame, which is what tells the sandbox that code it guards was running. [MethodImpl(MethodImplOptions.NoInlining)] private void RunScriptStep() { if (!scriptHasFailed) { scriptHasFailed = true; throw new InvalidOperationException("A test exception from a script step."); } scriptIsDue = false; outcome = "The script step finished."; } public override void Update(Duration elapsed) { if (shownOutcome != outcome) { shownOutcome = outcome; status.Text = shownOutcome; } ExceptionSandbox sandbox = world.reporter.Sandbox; if (scriptIsDue && !sandbox.IsSkipped(scriptSite)) { try { RunScriptStep(); } catch (Exception exception) when (sandbox.Claims(exception, scriptSite, notes: null, quarantine: true)) { } } if (throwsInUpdate) { throwsInUpdate = false; throw new InvalidOperationException("A test exception from the update."); } } } }