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
2 changes: 1 addition & 1 deletion Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
<PackageVersion Include="System.IO.Abstractions" Version="[22.0.16,23)" />
<PackageVersion Include="Wcwidth" Version="[4.0.0,)" />
<PackageVersion Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="[1.21.2,2)" />
<PackageVersion Include="Serilog" Version="4.2.0" />
<PackageVersion Include="Serilog" Version="4.3.0" />
<PackageVersion Include="Serilog.Extensions.Logging" Version="9.0.0" />
<PackageVersion Include="Serilog.Sinks.Debug" Version="3.0.0" />
<PackageVersion Include="Serilog.Sinks.File" Version="6.0.0" />
Expand Down
30 changes: 13 additions & 17 deletions Examples/Example/Example.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// A simple Terminal.Gui example in C# - using C# 9.0 Top-level statements
#nullable enable
// A simple Terminal.Gui example in C# - using C# 9.0 Top-level statements

// This is a simple example application. For the full range of functionality
// see the UICatalog project
Expand All @@ -8,26 +9,30 @@
using Terminal.Gui.ViewBase;
using Terminal.Gui.Views;

// Example metadata
[assembly: Terminal.Gui.Examples.ExampleMetadata ("Simple Example", "A basic login form demonstrating Terminal.Gui fundamentals")]
[assembly: Terminal.Gui.Examples.ExampleCategory ("Getting Started")]
[assembly: Terminal.Gui.Examples.ExampleDemoKeyStrokes (KeyStrokes = ["a", "d", "m", "i", "n", "Tab", "p", "a", "s", "s", "w", "o", "r", "d", "Enter", "Esc"], Order = 1)]

// Override the default configuration for the application to use the Light theme
ConfigurationManager.RuntimeConfig = """{ "Theme": "Light" }""";
ConfigurationManager.Enable (ConfigLocations.All);

IApplication app = Application.Create ();

IApplication app = Application.Create (example: true);
app.Init ();
app.Run<ExampleWindow> ();
string? result = app.GetResult<string> ();

// Dispose the app to clean up and enable Console.WriteLine below
app.Dispose ();

// To see this output on the screen it must be done after shutdown,
// which restores the previous screen.
Console.WriteLine ($@"Username: {ExampleWindow.UserName}");
Console.WriteLine ($@"Username: {result}");

// Defines a top-level window with border and title
public sealed class ExampleWindow : Window
{
public static string UserName { get; set; }

public ExampleWindow ()
{
Title = $"Example App ({Application.QuitKey} to quit)";
Expand Down Expand Up @@ -76,8 +81,8 @@ public ExampleWindow ()
if (userNameText.Text == "admin" && passwordText.Text == "password")
{
MessageBox.Query (App, "Logging In", "Login Successful", "Ok");
UserName = userNameText.Text;
Application.RequestStop ();
Result = userNameText.Text;
App?.RequestStop ();
}
else
{
Expand All @@ -90,14 +95,5 @@ public ExampleWindow ()

// Add the views to the Window
Add (usernameLabel, userNameText, passwordLabel, passwordText, btnLogin);

var lv = new ListView
{
Y = Pos.AnchorEnd (),
Height = Dim.Auto (),
Width = Dim.Auto ()
};
lv.SetSource (["One", "Two", "Three", "Four"]);
Add (lv);
}
}
21 changes: 21 additions & 0 deletions Examples/ExampleRunner/ExampleRunner.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<!-- Version numbers are automatically updated by gitversion when a release is released -->
<!-- In the source tree the version will always be 1.0 for all projects. -->
<!-- Do not modify these. -->
<AssemblyVersion>2.0</AssemblyVersion>
<FileVersion>2.0</FileVersion>
<Version>2.0</Version>
<InformationalVersion>2.0</InformationalVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Serilog" />
<PackageReference Include="Serilog.Extensions.Logging" />
<PackageReference Include="Serilog.Sinks.Debug" />
<PackageReference Include="Serilog.Sinks.File" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Terminal.Gui\Terminal.Gui.csproj" />
</ItemGroup>
</Project>
155 changes: 155 additions & 0 deletions Examples/ExampleRunner/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
#nullable enable
// Example Runner - Demonstrates discovering and running all examples using the example infrastructure

using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Core;
using Serilog.Events;
using Terminal.Gui.App;
using Terminal.Gui.Configuration;
using Terminal.Gui.Examples;
using ILogger = Microsoft.Extensions.Logging.ILogger;

// Configure Serilog to write to Debug output and Console
Log.Logger = new LoggerConfiguration ()
.MinimumLevel.Is (LogEventLevel.Verbose)
.WriteTo.Debug ()
.CreateLogger ();

ILogger logger = LoggerFactory.Create (builder =>
{
builder
.AddSerilog (dispose: true) // Integrate Serilog with ILogger
.SetMinimumLevel (LogLevel.Trace); // Set minimum log level
}).CreateLogger ("ExampleRunner Logging");
Logging.Logger = logger;

Logging.Debug ("Logging enabled - writing to Debug output\n");

// Parse command line arguments
bool useFakeDriver = args.Contains ("--fake-driver") || args.Contains ("-f");
int timeout = 30000; // Default timeout in milliseconds

for (var i = 0; i < args.Length; i++)
{
if ((args [i] == "--timeout" || args [i] == "-t") && i + 1 < args.Length)
{
if (int.TryParse (args [i + 1], out int parsedTimeout))
{
timeout = parsedTimeout;
}
}
}

// Configure ForceDriver via ConfigurationManager if requested
if (useFakeDriver)
{
Console.WriteLine ("Using FakeDriver (forced via ConfigurationManager)\n");
ConfigurationManager.RuntimeConfig = """{ "ForceDriver": "FakeDriver" }""";
ConfigurationManager.Enable (ConfigLocations.All);
}

// Discover examples from the Examples directory
string? assemblyDir = Path.GetDirectoryName (System.Reflection.Assembly.GetExecutingAssembly ().Location);

if (assemblyDir is null)
{
Console.WriteLine ("Error: Could not determine assembly directory");

return 1;
}

// Go up to find the Examples directory - from bin/Debug/net8.0 to Examples
string examplesDir = Path.GetFullPath (Path.Combine (assemblyDir, "..", "..", "..", ".."));

if (!Directory.Exists (examplesDir))
{
Console.WriteLine ($"Error: Examples directory not found: {examplesDir}");

return 1;
}

Console.WriteLine ($"Searching for examples in: {examplesDir}\n");

// Discover all examples - look specifically in each example's bin directory
List<ExampleInfo> examples = [];
HashSet<string> seen = [];

foreach (string dir in Directory.GetDirectories (examplesDir))
{
string binDir = Path.Combine (dir, "bin", "Debug", "net8.0");

if (!Directory.Exists (binDir))
{
continue;
}

foreach (ExampleInfo example in ExampleDiscovery.DiscoverFromDirectory (binDir, "*.dll", SearchOption.TopDirectoryOnly))
{
// Don't include this runner in the list and avoid duplicates
if (example.Name != "Example Runner" && seen.Add (example.Name))
{
examples.Add (example);
}
}
}

Console.WriteLine ($"Discovered {examples.Count} examples\n");

// Run all examples sequentially
var successCount = 0;
var failCount = 0;

foreach (ExampleInfo example in examples)
{
Console.Write ($"Running: {example.Name,-40} ");

// Create context for running the example
// Note: When running with example mode, the demo keys from attributes will be used
// We don't need to inject additional keys via the context
ExampleContext context = new ()
{
DriverName = useFakeDriver ? "FakeDriver" : null,
KeysToInject = [], // Empty - let example mode handle keys from attributes
TimeoutMs = timeout,
Mode = ExecutionMode.InProcess
};

try
{
ExampleResult result = ExampleRunner.Run (example, context);

if (result.Success)
{
Console.WriteLine ($"✓ Success");
successCount++;
}
else if (result.TimedOut)
{
Console.WriteLine ($"✗ Timeout");
failCount++;
}
else
{
Console.WriteLine ($"✗ Failed: {result.ErrorMessage ?? "Unknown"}");
failCount++;
}
}
catch (Exception ex)
{
Console.WriteLine ($"✗ Exception: {ex.Message}");
failCount++;
}
}

Console.WriteLine ($"\n=== Summary: {successCount} passed, {failCount} failed ===");

if (useFakeDriver)
{
Console.WriteLine ("\nNote: Tests run with FakeDriver. Some examples may timeout if they don't respond to Esc key.");
}

// Flush logs before exiting
Log.CloseAndFlush ();

return failCount == 0 ? 0 : 1;
10 changes: 9 additions & 1 deletion Examples/FluentExample/Program.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,19 @@
#nullable enable
// Fluent API example demonstrating IRunnable with automatic disposal and result extraction

using Terminal.Gui.App;
using Terminal.Gui.Drawing;
using Terminal.Gui.ViewBase;
using Terminal.Gui.Views;

IApplication? app = Application.Create ()
// Example metadata
[assembly: Terminal.Gui.Examples.ExampleMetadata ("Fluent API Example", "Demonstrates the fluent IApplication API with IRunnable pattern")]
[assembly: Terminal.Gui.Examples.ExampleCategory ("API Patterns")]
[assembly: Terminal.Gui.Examples.ExampleCategory ("Controls")]
[assembly: Terminal.Gui.Examples.ExampleDemoKeyStrokes (KeyStrokes = ["CursorDown", "CursorDown", "CursorRight", "Enter"], Order = 1)]
[assembly: Terminal.Gui.Examples.ExampleDemoKeyStrokes (KeyStrokes = ["SetDelay:100", "Esc"], Order = 2)]

IApplication? app = Application.Create (example: true)
.Init ()
.Run<ColorPickerView> ();

Expand Down
13 changes: 12 additions & 1 deletion Examples/RunnableWrapperExample/Program.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,22 @@
#nullable enable
// Example demonstrating how to make ANY View runnable without implementing IRunnable

using Terminal.Gui.App;
using Terminal.Gui.Drawing;
using Terminal.Gui.ViewBase;
using Terminal.Gui.Views;

IApplication app = Application.Create ();
// Example metadata
[assembly: Terminal.Gui.Examples.ExampleMetadata ("Runnable Wrapper Example", "Shows how to wrap any View to make it runnable without implementing IRunnable")]
[assembly: Terminal.Gui.Examples.ExampleCategory ("API Patterns")]
[assembly: Terminal.Gui.Examples.ExampleCategory ("Views")]
[assembly: Terminal.Gui.Examples.ExampleDemoKeyStrokes (KeyStrokes = ["t", "e", "s", "t", "Esc"], Order = 1)]
[assembly: Terminal.Gui.Examples.ExampleDemoKeyStrokes (KeyStrokes = ["Enter", "Esc"], Order = 2)]
[assembly: Terminal.Gui.Examples.ExampleDemoKeyStrokes (KeyStrokes = ["Enter", "Esc"], Order = 3)]
[assembly: Terminal.Gui.Examples.ExampleDemoKeyStrokes (KeyStrokes = ["Enter", "Esc"], Order = 4)]
[assembly: Terminal.Gui.Examples.ExampleDemoKeyStrokes (KeyStrokes = ["Enter", "Esc"], Order = 5)]

IApplication app = Application.Create (example: true);
app.Init ();

// Example 1: Use extension method with result extraction
Expand Down
18 changes: 16 additions & 2 deletions Terminal.Gui/App/Application.Lifecycle.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
Expand All @@ -10,6 +11,12 @@ namespace Terminal.Gui.App;

public static partial class Application // Lifecycle (Init/Shutdown)
{
/// <summary>
/// Gets the observable collection of all application instances.
/// External observers can subscribe to this collection to monitor application lifecycle.
/// </summary>
public static ObservableCollection<IApplication> Apps { get; } = [];

/// <summary>
/// Gets the singleton <see cref="IApplication"/> instance used by the legacy static Application model.
/// </summary>
Expand All @@ -29,6 +36,10 @@ public static partial class Application // Lifecycle (Init/Shutdown)
/// <summary>
/// Creates a new <see cref="IApplication"/> instance.
/// </summary>
/// <param name="example">
/// If <see langword="true"/>, the application will run in example mode where metadata is collected
/// and demo keys are automatically sent when the first TopRunnable is modal.
/// </param>
/// <remarks>
/// The recommended pattern is for developers to call <c>Application.Create()</c> and then use the returned
/// <see cref="IApplication"/> instance for all subsequent application operations.
Expand All @@ -37,12 +48,15 @@ public static partial class Application // Lifecycle (Init/Shutdown)
/// <exception cref="InvalidOperationException">
/// Thrown if the legacy static Application model has already been used in this process.
/// </exception>
public static IApplication Create ()
public static IApplication Create (bool example = false)
{
//Debug.Fail ("Application.Create() called");
ApplicationImpl.MarkInstanceBasedModelUsed ();

return new ApplicationImpl ();
ApplicationImpl app = new ();
Apps.Add (app);

return app;
}

/// <inheritdoc cref="IApplication.Init"/>
Expand Down
Loading
Loading