Files
Terminal.Gui/Examples/UICatalog/Scenarios/SingleBackgroundWorker.cs
BDisp 00aaefb962 Fixes #3951. Adds View dependency to DimFunc and PosFunc (#4210)
* Fixes #4208. MainLoopSyncContext doesn't work with the v2 drivers

* Fixes #3951. Add DimFuncWithView with a View dependency

* Revert to iteration which will handle the necessary processes

* Revert "Revert to iteration which will handle the necessary processes"

This reverts commit 50015ac6da.

* Layout and draw before position cursor

* Add optional View parameter and property to the DimFunc and PosFunc

* Trying fix unit test error

* Revert layout changes

* Fixes #4216. Legacy drivers aren't refreshing the screen correctly on view drag

* Add assertion proving NeedsLayout is always false before call OnSubViewsLaidOut

* Fix unit test error

* Increasing time to abort

* Revert "Increasing time to abort"

This reverts commit d7306e72f3.

* Trying fix integration tests

* Still trying fix integrations unit tests

* Revert comment

* Layout is performed during the iteration

* Using Dim.Func with status bar view

* Still trying fix integrations tests by locking _subviews

* Still trying fix integrations tests by locking _subviews

* Add internal SnapshotSubviews method

* Remove lock from SnapshotSubviews method

* Using SnapshotSubviews method in the DrawSubViews method

* Remove lock from SnapshotSubviews method

* Using SnapshotSubviews method in the DrawSubViews method

* Using SnapshotSubviews

* Prevent new app if the previous wasn't yet finished

* Replace SnapshotSubviews method with ViewCollectionHelpers class

* Lock entire GuiTestContext constructor

* Using Snapshot in the ordered field

* Fixes #4221 Extra modifiers f1 to f4 in v2net (#4220)

* Assume we are running in a terminal that supports true color by default unless user explicitly forces 16

* Add support for extra modifiers for F1 to F4 keys

* Revert "Assume we are running in a terminal that supports true color by default unless user explicitly forces 16"

This reverts commit 4cc2530de0.

* Cleanup

* Update comments

* Code cleanup

---------

Co-authored-by: Tig <tig@users.noreply.github.com>

* Move ViewCollectionHelpers class to a separate file

* Remove Border.Layout call in the DoDrawAdornmentsSubViews method.

* Remove adornments layout call within the draw

---------

Co-authored-by: Tig <tig@users.noreply.github.com>
Co-authored-by: Thomas Nind <31306100+tznind@users.noreply.github.com>
2025-09-01 10:40:10 -06:00

304 lines
12 KiB
C#

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Threading;
namespace UICatalog.Scenarios;
[ScenarioMetadata ("Single BackgroundWorker", "A single BackgroundWorker threading opening another Toplevel")]
[ScenarioCategory ("Threading")]
[ScenarioCategory ("Arrangement")]
[ScenarioCategory ("Runnable")]
public class SingleBackgroundWorker : Scenario
{
public override void Main ()
{
Application.Run<MainApp> ().Dispose ();
Application.Shutdown ();
}
public class MainApp : Toplevel
{
private readonly ListView _listLog;
private readonly ObservableCollection<string> _log = [];
private DateTime? _startStaging;
private BackgroundWorker _worker;
public MainApp ()
{
var menu = new MenuBar
{
Menus =
[
new (
"_Options",
new MenuItem []
{
new (
"_Run Worker",
"",
() => RunWorker (),
null,
null,
KeyCode.CtrlMask | KeyCode.R
),
null,
new (
"_Quit",
"",
() => Application.RequestStop (),
null,
null,
Application.QuitKey
)
}
)
]
};
var statusBar = new StatusBar (
[
new (Application.QuitKey, "Quit", () => Application.RequestStop ()),
new (Key.R.WithCtrl, "Run Worker", RunWorker)
]);
var workerLogTop = new Toplevel
{
Title = "Worker Log Top"
};
workerLogTop.Add (
new Label { X = Pos.Center (), Y = 0, Text = "Worker Log" }
);
_listLog = new ()
{
X = 0,
Y = 2,
Width = Dim.Fill (),
Height = Dim.Fill (),
Source = new ListWrapper<string> (_log)
};
workerLogTop.Add (_listLog);
workerLogTop.Y = 1;
workerLogTop.Height = Dim.Fill (Dim.Func (_ => statusBar.Frame.Height));
Add (menu, workerLogTop, statusBar);
Title = "MainApp";
}
private void RunWorker ()
{
_worker = new () { WorkerSupportsCancellation = true };
var cancel = new Button { Text = "Cancel Worker" };
cancel.Accepting += (s, e) =>
{
if (_worker == null)
{
_log.Add ($"Worker is not running at {DateTime.Now}!");
_listLog.SetNeedsDraw ();
return;
}
_log.Add (
$"Worker {_startStaging}.{_startStaging:fff} is canceling at {DateTime.Now}!"
);
_listLog.SetNeedsDraw ();
_worker.CancelAsync ();
};
_startStaging = DateTime.Now;
_log.Add ($"Worker is started at {_startStaging}.{_startStaging:fff}");
_listLog.SetNeedsDraw ();
var md = new Dialog
{
Title = $"Running Worker started at {_startStaging}.{_startStaging:fff}", Buttons = [cancel]
};
md.Add (
new Label { X = Pos.Center (), Y = Pos.Center (), Text = "Wait for worker to finish..." }
);
_worker.DoWork += (s, e) =>
{
List<string> stageResult = new ();
for (var i = 0; i < 200; i++)
{
stageResult.Add ($"Worker {i} started at {DateTime.Now}");
e.Result = stageResult;
Thread.Sleep (1);
if (_worker.CancellationPending)
{
e.Cancel = true;
return;
}
}
};
_worker.RunWorkerCompleted += (s, e) =>
{
if (md.IsCurrentTop)
{
//Close the dialog
Application.RequestStop ();
}
if (e.Error != null)
{
// Failed
_log.Add (
$"Exception occurred {e.Error.Message} on Worker {_startStaging}.{_startStaging:fff} at {DateTime.Now}"
);
_listLog.SetNeedsDraw ();
}
else if (e.Cancelled)
{
// Canceled
_log.Add (
$"Worker {_startStaging}.{_startStaging:fff} was canceled at {DateTime.Now}!"
);
_listLog.SetNeedsDraw ();
}
else
{
// Passed
_log.Add (
$"Worker {_startStaging}.{_startStaging:fff} was completed at {DateTime.Now}."
);
_listLog.SetNeedsDraw ();
Application.LayoutAndDraw ();
var builderUI =
new StagingUIController (_startStaging, e.Result as ObservableCollection<string>);
Toplevel top = Application.Top;
top.Visible = false;
Application.Top.Visible = false;
builderUI.Load ();
builderUI.Dispose ();
top.Visible = true;
}
_worker = null;
};
_worker.RunWorkerAsync ();
Application.Run (md);
md.Dispose ();
}
}
public class StagingUIController : Window
{
private Toplevel _top;
public StagingUIController (DateTime? start, ObservableCollection<string> list)
{
_top = new ()
{
Title = "_top", Width = Dim.Fill (), Height = Dim.Fill (), Modal = true
};
_top.KeyDown += (s, e) =>
{
// Prevents App.QuitKey from closing this.
// Only Ctrl+C is allowed.
if (e == Application.QuitKey)
{
e.Handled = true;
}
};
bool Close ()
{
int n = MessageBox.Query (
50,
7,
"Close Window.",
"Are you sure you want to close this window?",
"Yes",
"No"
);
return n == 0;
}
var menu = new MenuBar
{
Menus =
[
new (
"_Stage",
new MenuItem []
{
new (
"_Close",
"",
() =>
{
if (Close ())
{
Application.RequestStop ();
}
},
null,
null,
KeyCode.CtrlMask | KeyCode.C
)
}
)
]
};
_top.Add (menu);
var statusBar = new StatusBar (
[
new (
Key.C.WithCtrl,
"Close",
() =>
{
if (Close ())
{
Application.RequestStop ();
}
}
)
]);
_top.Add (statusBar);
Y = 1;
Height = Dim.Fill (1);
Title = $"Worker started at {start}.{start:fff}";
SchemeName = "Base";
Add (
new ListView
{
X = 0,
Y = 0,
Width = Dim.Fill (),
Height = Dim.Fill (),
Source = new ListWrapper<string> (list)
}
);
_top.Add (this);
}
public void Load ()
{
Application.Run (_top);
_top.Dispose ();
_top = null;
}
}
}