TextFormat

This commit is contained in:
2023-08-16 19:21:50 +02:00
parent cbbf7b3704
commit 3c996f0c20
31 changed files with 304 additions and 94 deletions

View File

@@ -2,6 +2,7 @@
using TerminalUI.ConsoleDrivers;
using TerminalUI.Controls;
using TerminalUI.Models;
using TerminalUI.TextFormat;
namespace TerminalUI.Examples.Controls;
@@ -56,7 +57,8 @@ public class ProgressBarExamples
true,
null,
null,
new()
new(),
new TextFormatContext(true)
);
progressBar.Render(renderContext, position, new Size(10, 1));
}

View File

@@ -6,6 +6,8 @@ namespace TerminalUI.ConsoleDrivers;
public class DotnetDriver : IConsoleDriver
{
public bool SupportsAnsiEscapeSequence { get; protected set; }
public virtual bool Init()
{
Console.Clear();
@@ -14,7 +16,8 @@ public class DotnetDriver : IConsoleDriver
public void SetCursorPosition(Position position) => Console.SetCursorPosition(position.X, position.Y);
public void ResetColor() => Console.ResetColor();
public virtual void ResetColor() => Console.ResetColor();
public virtual void ResetStyle() => Console.ResetColor();
public Position GetCursorPosition()
{

View File

@@ -5,10 +5,12 @@ namespace TerminalUI.ConsoleDrivers;
public interface IConsoleDriver
{
bool SupportsAnsiEscapeSequence { get; }
bool Init();
void Dispose();
void SetCursorPosition(Position position);
void ResetColor();
void ResetStyle();
Position GetCursorPosition();
void Write(string text);
void Write(ReadOnlySpan<char> text);

View File

@@ -8,6 +8,11 @@ public sealed class XTermDriver : DotnetDriver
{
private Position _initialCursorPosition;
public XTermDriver()
{
SupportsAnsiEscapeSequence = true;
}
public override bool Init()
{
_initialCursorPosition = GetCursorPosition();
@@ -27,6 +32,11 @@ public sealed class XTermDriver : DotnetDriver
SetCursorPosition(_initialCursorPosition);
}
public override void ResetStyle()
{
Write("\x1b[0m");
}
public override void SetBackgroundColor(IColor background)
{
if (background == SpecialColor.None) return;

View File

@@ -71,7 +71,7 @@ public sealed partial class Border<T> : ContentView<Border<T>, T>, IDisplayView
if (contentRendered)
{
var driver = renderContext.ConsoleDriver;
driver.ResetColor();
driver.ResetStyle();
SetColorsForDriver(renderContext);
RenderTopBorder(renderContext, position, size);

View File

@@ -170,13 +170,11 @@ public sealed class Grid<T> : ChildContainerView<Grid<T>, T>, IVisibilityChangeH
_forceRerenderChildren.Clear();
}
var childContext = new RenderContext(
context.ConsoleDriver,
context.ForceRerender,
Foreground ?? context.Foreground,
Background ?? context.Background,
context.Statistics
);
var childContext = context with
{
Foreground = Foreground ?? context.Foreground,
Background = Background ?? context.Background,
};
var viewsByPosition = GroupViewsByPosition(columnWidths.Length, rowHeights.Length);
var anyRendered = false;
@@ -214,7 +212,6 @@ public sealed class Grid<T> : ChildContainerView<Grid<T>, T>, IVisibilityChangeH
int row,
IReadOnlyList<IView> forceRerenderChildren)
{
var width = columnWidths[column];
var height = rowHeights[row];
var renderSize = new Size(width, height);
@@ -238,7 +235,7 @@ public sealed class Grid<T> : ChildContainerView<Grid<T>, T>, IVisibilityChangeH
}
if (renderSize.Width == 0 || renderSize.Height == 0) return false;
if (!viewsByPosition.TryGetValue((column, row), out var children))
{
RenderEmpty(context, renderPosition, renderSize);
@@ -253,7 +250,8 @@ public sealed class Grid<T> : ChildContainerView<Grid<T>, T>, IVisibilityChangeH
true,
context.Foreground,
context.Background,
context.Statistics
context.Statistics,
context.TextFormat
);
RenderEmpty(context, renderPosition, renderSize);
}
@@ -270,7 +268,8 @@ public sealed class Grid<T> : ChildContainerView<Grid<T>, T>, IVisibilityChangeH
true,
context.Foreground,
context.Background,
context.Statistics
context.Statistics,
context.TextFormat
);
}
}

View File

@@ -85,7 +85,8 @@ public sealed partial class ItemsControl<TDataContext, TItem>
double width = 0;
double height = 0;
foreach (var child in _children)
var children = _children.ToList();
foreach (var child in children)
{
if (!child.IsVisible) continue;
@@ -149,13 +150,7 @@ public sealed partial class ItemsControl<TDataContext, TItem>
if (forceRerenderChildren.Contains(child))
{
var rerenderContext = new RenderContext(
renderContext.ConsoleDriver,
true,
renderContext.Foreground,
renderContext.Background,
renderContext.Statistics
);
var rerenderContext = renderContext with {ForceRerender = true};
neededRerender = child.Render(rerenderContext, childPosition, childSize) || neededRerender;
}
else

View File

@@ -286,7 +286,7 @@ public sealed partial class ListView<TDataContext, TItem> : View<ListView<TDataC
var driver = ApplicationContext!.ConsoleDriver;
var placeholder = new string(' ', size.Width);
driver.ResetColor();
driver.ResetStyle();
for (var i = deltaY; i < size.Height; i++)
{
driver.SetCursorPosition(position with {Y = position.Y + i});

View File

@@ -111,7 +111,7 @@ public partial class ProgressBar<T> : View<ProgressBar<T>, T>
};
}
SetColor(driver, foreground, background);
SetStyleColor(renderContext, foreground, background);
// Left border
var textStartPosition = position;
@@ -132,7 +132,7 @@ public partial class ProgressBar<T> : View<ProgressBar<T>, T>
// Transient character
if (progressQuotientWidth < progressAvailableSpace)
{
SetColor(driver, foreground, unfilledBackground);
SetStyleColor(renderContext, foreground, unfilledBackground);
RenderText(
transientChar,
driver,
@@ -147,7 +147,7 @@ public partial class ProgressBar<T> : View<ProgressBar<T>, T>
Span<char> unfilledText = stackalloc char[progressRemainderWidth];
unfilledText.Fill(unfilledCharacter);
SetColor(driver, unfilledForeground, unfilledBackground);
SetStyleColor(renderContext, unfilledForeground, unfilledBackground);
RenderText(
unfilledText,
driver,
@@ -159,7 +159,7 @@ public partial class ProgressBar<T> : View<ProgressBar<T>, T>
// Right border
if (rightCap.HasValue)
{
SetColor(driver, foreground, background);
SetStyleColor(renderContext, foreground, background);
RenderText(
rightCap.Value,
driver,

View File

@@ -25,7 +25,7 @@ public sealed partial class Rectangle<T> : View<Rectangle<T>, T>, IDisplayView
var driver = renderContext.ConsoleDriver;
var s = new string(' ', size.Width);
driver.ResetColor();
driver.ResetStyle();
if (color is not null)
{
driver.SetBackgroundColor(color);

View File

@@ -80,13 +80,7 @@ public sealed partial class StackPanel<T> : ChildContainerView<StackPanel<T>, T>
if (forceRerenderChildren.Contains(child))
{
var rerenderContext = new RenderContext(
renderContext.ConsoleDriver,
true,
renderContext.Foreground,
renderContext.Background,
renderContext.Statistics
);
var rerenderContext = renderContext with {ForceRerender = true};
neededRerender = child.Render(rerenderContext, childPosition, childSize) || neededRerender;
}
else

View File

@@ -2,8 +2,8 @@
using System.Diagnostics;
using PropertyChanged.SourceGenerator;
using TerminalUI.Color;
using TerminalUI.Extensions;
using TerminalUI.Models;
using TerminalUI.TextFormat;
using TerminalUI.Traits;
namespace TerminalUI.Controls;
@@ -16,7 +16,8 @@ public sealed partial class TextBlock<T> : View<TextBlock<T>, T>, IDisplayView
Size Size,
string? Text,
IColor? Foreground,
IColor? Background);
IColor? Background,
ITextFormat? TextFormat);
private RenderState? _lastRenderState;
private string[]? _textLines;
@@ -24,17 +25,13 @@ public sealed partial class TextBlock<T> : View<TextBlock<T>, T>, IDisplayView
[Notify] private string? _text = string.Empty;
[Notify] private TextAlignment _textAlignment = TextAlignment.Left;
[Notify] private ITextFormat? _textFormat;
public TextBlock()
{
/*this.Bind(
this,
dc => dc == null ? string.Empty : dc.ToString(),
tb => tb.Text
);*/
RerenderProperties.Add(nameof(Text));
RerenderProperties.Add(nameof(TextAlignment));
RerenderProperties.Add(nameof(TextFormat));
((INotifyPropertyChanged) this).PropertyChanged += (o, e) =>
{
@@ -58,7 +55,8 @@ public sealed partial class TextBlock<T> : View<TextBlock<T>, T>, IDisplayView
size,
Text,
foreground,
background);
background,
_textFormat);
if (!renderContext.ForceRerender && !NeedsRerender(renderState)) return false;
@@ -78,7 +76,7 @@ public sealed partial class TextBlock<T> : View<TextBlock<T>, T>, IDisplayView
_placeholderRenderDone = false;
var driver = renderContext.ConsoleDriver;
SetColor(driver, foreground, background);
SetStyleColor(renderContext, foreground, background, _textFormat);
RenderText(_textLines, driver, position, size, TransformText);

View File

@@ -104,7 +104,7 @@ public sealed partial class TextBox<T> : View<TextBox<T>, T>, IFocusable, IDispl
_lastRenderState = renderStatus;
var driver = renderContext.ConsoleDriver;
SetColor(driver, foreground, background);
SetStyleColor(renderContext, foreground, background);
RenderEmpty(renderContext, position, size);

View File

@@ -8,6 +8,7 @@ using PropertyChanged.SourceGenerator;
using TerminalUI.Color;
using TerminalUI.ConsoleDrivers;
using TerminalUI.Models;
using TerminalUI.TextFormat;
using TerminalUI.Traits;
namespace TerminalUI.Controls;
@@ -175,12 +176,12 @@ public abstract partial class View<TConcrete, T> : IView<T> where TConcrete : Vi
bool renderResult;
if (Background != null || Foreground != null)
{
var newRenderContext = new RenderContext(
renderContext.ConsoleDriver,
renderContext.ForceRerender,
Foreground ?? renderContext.Foreground,
Background ?? renderContext.Background,
renderContext.Statistics);
var newRenderContext = renderContext with
{
Foreground = Foreground ?? renderContext.Foreground,
Background = Background ?? renderContext.Background
};
renderResult = RenderMethod(newRenderContext, position, size);
}
else
@@ -202,7 +203,7 @@ public abstract partial class View<TConcrete, T> : IView<T> where TConcrete : Vi
protected void RenderEmpty(in RenderContext renderContext, Position position, Size size)
{
var driver = renderContext.ConsoleDriver;
driver.ResetColor();
driver.ResetStyle();
var placeHolder = new string(ApplicationContext!.EmptyCharacter, size.Width);
for (var i = 0; i < size.Height; i++)
@@ -309,14 +310,25 @@ public abstract partial class View<TConcrete, T> : IView<T> where TConcrete : Vi
driver.Write(contentString);
}
}
protected void SetColor(IConsoleDriver driver, IColor? foreground, IColor? background)
protected void SetStyleColor(
in RenderContext renderContext,
IColor? foreground = null,
IColor? background = null,
ITextFormat? textFormat = null)
{
var driver = renderContext.ConsoleDriver;
driver.ResetColor();
if (textFormat is { } t)
{
t.ApplyFormat(driver, renderContext.TextFormat);
}
if (foreground is not null)
{
driver.SetForegroundColor(foreground);
}
if(background is not null)
if (background is not null)
{
driver.SetBackgroundColor(background);
}
@@ -324,11 +336,9 @@ public abstract partial class View<TConcrete, T> : IView<T> where TConcrete : Vi
protected void SetColorsForDriver(in RenderContext renderContext)
{
var driver = renderContext.ConsoleDriver;
var foreground = Foreground ?? renderContext.Foreground;
var background = Background ?? renderContext.Background;
SetColor(driver, foreground, background);
SetStyleColor(renderContext, foreground, background);
}
public TChild CreateChild<TChild>() where TChild : IView<T>, new()

View File

@@ -6,7 +6,8 @@ namespace TerminalUI.ExpressionTrackers;
public abstract class ExpressionTrackerBase : IExpressionTracker
{
private object? _currentValue;
public List<string> TrackedPropertyNames { get; } = new();
private readonly List<IExpressionTracker> _propertyProxyTrackers = new();
private readonly List<string> _trackedPropertyNames = new();
protected bool SubscribeToValueChanges { get; set; } = true;
@@ -15,10 +16,22 @@ public abstract class ExpressionTrackerBase : IExpressionTracker
public object? GetValue() => _currentValue;
protected abstract object? ComputeValue();
protected void SubscribeToTracker(IExpressionTracker? expressionTracker)
protected void SubscribeToTracker(IExpressionTracker? expressionTracker, bool proxyPropertyChanged = false)
{
if (expressionTracker is null) return;
expressionTracker.Update += UpdateValueAndChangeTrackers;
if (proxyPropertyChanged)
{
expressionTracker.PropertyChanged += OnPropertyChanged;
_propertyProxyTrackers.Add(expressionTracker);
foreach (var propertyName in _trackedPropertyNames)
{
expressionTracker.TrackProperty(propertyName);
}
}
}
protected void UpdateValueAndChangeTrackers() => UpdateValueAndChangeTrackers(true);
@@ -67,16 +80,31 @@ public abstract class ExpressionTrackerBase : IExpressionTracker
}
}
private void OnCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
private void OnCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
=> UpdateValueAndChangeTrackers();
private void OnPropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName is null) return;
if (TrackedPropertyNames.Contains(e.PropertyName))
if (_trackedPropertyNames.Contains(e.PropertyName))
{
PropertyChanged?.Invoke(e.PropertyName);
}
}
protected void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(propertyName);
public void TrackProperty(string propertyName)
{
if (!_trackedPropertyNames.Contains(propertyName))
{
_trackedPropertyNames.Add(propertyName);
}
foreach (var propertyProxyTracker in _propertyProxyTrackers)
{
propertyProxyTracker.TrackProperty(propertyName);
}
}
}

View File

@@ -2,8 +2,8 @@
public interface IExpressionTracker
{
List<string> TrackedPropertyNames { get; }
event Action<string>? PropertyChanged;
event Action<bool>? Update;
object? GetValue();
void TrackProperty(string propertyName);
}

View File

@@ -28,7 +28,7 @@ public sealed class MemberTracker : ExpressionTrackerBase
if (memberExpression.Member is PropertyInfo propertyInfo)
{
_memberName = propertyInfo.Name;
parentTracker?.TrackedPropertyNames.Add(propertyInfo.Name);
parentTracker?.TrackProperty(propertyInfo.Name);
if (propertyInfo.GetMethod is { } getMethod)
{
@@ -44,7 +44,7 @@ public sealed class MemberTracker : ExpressionTrackerBase
else if (memberExpression.Member is FieldInfo fieldInfo)
{
_memberName = fieldInfo.Name;
parentTracker?.TrackedPropertyNames.Add(fieldInfo.Name);
parentTracker?.TrackProperty(fieldInfo.Name);
_valueProvider = () => CallFieldInfo(fieldInfo);
}
@@ -61,15 +61,15 @@ public sealed class MemberTracker : ExpressionTrackerBase
{
var obj = _parentTracker?.GetValue();
if (obj is null && !propertyInfo.GetMethod!.IsStatic) return null;
return propertyInfo.GetValue(_parentTracker?.GetValue());
}
private object? CallFieldInfo(FieldInfo fieldInfo)
{
var obj = _parentTracker?.GetValue();
if (obj is null && !fieldInfo.IsStatic) return null;
return fieldInfo.GetValue(_parentTracker?.GetValue());
}

View File

@@ -23,7 +23,7 @@ public class UnaryTracker : ExpressionTrackerBase
_ => throw new NotSupportedException($"Unary expression of type {unaryExpression.NodeType} is not supported.")
};
SubscribeToTracker(operandTracker);
SubscribeToTracker(operandTracker, true);
UpdateValueAndChangeTrackers();
}

View File

@@ -1,6 +1,7 @@
using System.Diagnostics;
using TerminalUI.Color;
using TerminalUI.ConsoleDrivers;
using TerminalUI.TextFormat;
namespace TerminalUI.Models;
@@ -8,19 +9,21 @@ namespace TerminalUI.Models;
public readonly ref struct RenderContext
{
private static int _renderId;
public readonly int RenderId;
public readonly IConsoleDriver ConsoleDriver;
public readonly bool ForceRerender;
public readonly IColor? Foreground;
public readonly IColor? Background;
public readonly RenderStatistics Statistics;
public int RenderId { get; init; }
public IConsoleDriver ConsoleDriver { get; init; }
public bool ForceRerender { get; init; }
public IColor? Foreground { get; init; }
public IColor? Background { get; init; }
public RenderStatistics Statistics { get; init; }
public TextFormatContext TextFormat { get; init; }
public RenderContext(
IConsoleDriver consoleDriver,
bool forceRerender,
IColor? foreground,
IColor? background,
RenderStatistics statistics)
RenderStatistics statistics,
TextFormatContext textFormat)
{
RenderId = _renderId++;
@@ -29,6 +32,7 @@ public readonly ref struct RenderContext
Foreground = foreground;
Background = background;
Statistics = statistics;
TextFormat = textFormat;
}
public static RenderContext Empty =>
@@ -37,6 +41,7 @@ public readonly ref struct RenderContext
false,
null,
null,
new RenderStatistics()
new RenderStatistics(),
new TextFormatContext(false)
);
}

View File

@@ -1,5 +1,6 @@
using TerminalUI.Controls;
using TerminalUI.Models;
using TerminalUI.TextFormat;
using TerminalUI.Traits;
namespace TerminalUI;
@@ -83,7 +84,8 @@ public class RenderEngine : IRenderEngine
true,
null,
null,
new RenderStatistics()
new RenderStatistics(),
new TextFormatContext(driver.SupportsAnsiEscapeSequence)
),
initialPosition,
size);
@@ -95,7 +97,8 @@ public class RenderEngine : IRenderEngine
false,
null,
null,
new RenderStatistics()
new RenderStatistics(),
new TextFormatContext(driver.SupportsAnsiEscapeSequence)
),
initialPosition,
size);

View File

@@ -0,0 +1,25 @@
using TerminalUI.ConsoleDrivers;
namespace TerminalUI.TextFormat;
public class AnsiFormat : ITextFormat
{
public bool IsUnderline { get; set; }
public bool IsItalic { get; set; }
public bool IsBold { get; set; }
public bool CanApply(TextFormatContext context) => context.SupportsAnsi;
public void ApplyFormat(IConsoleDriver consoleDriver, TextFormatContext context)
{
if (!context.SupportsAnsi) return;
if (IsUnderline)
consoleDriver.Write("\x01b[4m");
if (IsItalic)
consoleDriver.Write("\x01b[3m");
if (IsBold)
consoleDriver.Write("\x01b[1m");
}
}

View File

@@ -0,0 +1,13 @@
using TerminalUI.ConsoleDrivers;
namespace TerminalUI.TextFormat;
public readonly struct EmptyFormat : ITextFormat
{
public static EmptyFormat Instance => new();
public bool CanApply(TextFormatContext context) => true;
public void ApplyFormat(IConsoleDriver consoleDriver, TextFormatContext context)
{
}
}

View File

@@ -0,0 +1,23 @@
using TerminalUI.ConsoleDrivers;
namespace TerminalUI.TextFormat;
public class FormatCollection : ITextFormat
{
public List<ITextFormat> Formats { get; } = new();
public Func<IReadOnlyList<ITextFormat>, TextFormatContext, bool> CanApplyPredicate { get; set; } = DefaultCanApplyPredicate;
public bool CanApply(TextFormatContext context) => CanApplyPredicate(Formats, context);
public void ApplyFormat(IConsoleDriver consoleDriver, TextFormatContext context)
{
foreach (var format in Formats)
{
format.ApplyFormat(consoleDriver, context);
}
}
public static bool DefaultCanApplyPredicate(IReadOnlyList<ITextFormat> formats, TextFormatContext context)
=> formats.Any(format => format.CanApply(context));
}

View File

@@ -0,0 +1,9 @@
using TerminalUI.ConsoleDrivers;
namespace TerminalUI.TextFormat;
public interface ITextFormat
{
bool CanApply(TextFormatContext context);
void ApplyFormat(IConsoleDriver consoleDriver, TextFormatContext context);
}

View File

@@ -0,0 +1,23 @@
using TerminalUI.ConsoleDrivers;
namespace TerminalUI.TextFormat;
public class OrFormat : ITextFormat
{
public required ITextFormat Format1 { get; set; }
public required ITextFormat Format2 { get; set; }
public bool CanApply(TextFormatContext context) => true;
public void ApplyFormat(IConsoleDriver consoleDriver, TextFormatContext context)
{
if (Format1.CanApply(context))
{
Format1.ApplyFormat(consoleDriver, context);
}
else
{
Format2.ApplyFormat(consoleDriver, context);
}
}
}

View File

@@ -0,0 +1,20 @@
using TerminalUI.Color;
using TerminalUI.ConsoleDrivers;
namespace TerminalUI.TextFormat;
public class SimpleFormat : ITextFormat
{
public IColor? Foreground { get; init; }
public IColor? Background { get; init; }
public bool CanApply(TextFormatContext context) => true;
public void ApplyFormat(IConsoleDriver consoleDriver, TextFormatContext context)
{
if (Foreground is not null)
consoleDriver.SetForegroundColor(Foreground);
if (Background is not null)
consoleDriver.SetBackgroundColor(Background);
}
}

View File

@@ -0,0 +1,11 @@
namespace TerminalUI.TextFormat;
public readonly struct TextFormatContext
{
public readonly bool SupportsAnsi;
public TextFormatContext(bool supportsAnsi)
{
SupportsAnsi = supportsAnsi;
}
}