#nullable enable
using System.Diagnostics;
namespace Terminal.Gui;
///
/// Specifies how will compute the dimension.
///
[Flags]
public enum DimAutoStyle
{
///
/// The dimension will be computed using both the view's and
/// (whichever is larger).
///
Auto = Content | Text,
///
/// The dimensions will be computed based on the View's non-Text content.
///
/// If is explicitly set (is not ) then
///
/// will be used to determine the dimension.
///
///
/// Otherwise, the Subview in with the largest corresponding position plus dimension
/// will determine the dimension.
///
///
/// The corresponding dimension of the view's will be ignored.
///
///
Content = 0,
///
///
/// The corresponding dimension of the view's , formatted using the
/// settings,
/// will be used to determine the dimension.
///
///
/// The corresponding dimensions of the will be ignored.
///
///
Text = 1
}
///
/// Indicates the dimension for operations.
///
public enum Dimension
{
///
/// No dimension specified.
///
None = 0,
///
/// The height dimension.
///
Height = 1,
///
/// The width dimension.
///
Width = 2
}
///
///
/// A Dim object describes the dimensions of a . Dim is the type of the
/// and properties of . Dim objects enable
/// Computed Layout (see ) to automatically manage the dimensions of a view.
///
///
/// Integer values are implicitly convertible to an absolute . These objects are created using
/// the static methods described below. The objects can be combined with the addition and
/// subtraction operators.
///
///
///
///
///
///
/// Dim Object Description
///
/// -
///
///
///
///
/// Creates a object that automatically sizes the view to fit
/// the view's Text, SubViews, or ContentArea.
///
///
/// -
///
///
///
///
/// Creates a object that computes the dimension by executing the provided
/// function. The function will be called every time the dimension is needed.
///
///
/// -
///
///
///
///
/// Creates a object that is a percentage of the width or height of the
/// SuperView.
///
///
/// -
///
///
///
///
/// Creates a object that fills the dimension from the View's X position
/// to the end of the super view's width, leaving the specified number of columns for a margin.
///
///
/// -
///
///
///
///
/// Creates a object that tracks the Width of the specified
/// .
///
///
/// -
///
///
///
///
/// Creates a object that tracks the Height of the specified
/// .
///
///
///
///
///
///
public abstract class Dim
{
#region static Dim creation methods
/// Creates an Absolute from the specified integer value.
/// The Absolute .
/// The value to convert to the .
public static Dim? Absolute (int size) { return new DimAbsolute (size); }
///
/// Creates a object that automatically sizes the view to fit all the view's Content, Subviews, and/or Text.
///
///
///
/// See .
///
///
///
/// This initializes a with two SubViews. The view will be automatically sized to fit the two
/// SubViews.
///
/// var button = new Button () { Text = "Click Me!", X = 1, Y = 1, Width = 10, Height = 1 };
/// var textField = new TextField { Text = "Type here", X = 1, Y = 2, Width = 20, Height = 1 };
/// var view = new Window () { Title = "MyWindow", X = 0, Y = 0, Width = Dim.Auto (), Height = Dim.Auto () };
/// view.Add (button, textField);
///
///
/// The object.
///
/// Specifies how will compute the dimension. The default is .
///
/// The minimum dimension the View's ContentSize will be constrained to.
/// The maximum dimension the View's ContentSize will be fit to. NOT CURRENTLY SUPPORTED.
public static Dim? Auto (DimAutoStyle style = DimAutoStyle.Auto, Dim? minimumContentDim = null, Dim? maximumContentDim = null)
{
if (maximumContentDim is { })
{
Debug.WriteLine (@"WARNING: maximumContentDim is not fully implemented.");
}
return new DimAuto ()
{
MinimumContentDim = minimumContentDim,
MaximumContentDim = maximumContentDim,
Style = style
};
}
///
/// Creates a object that fills the dimension, leaving the specified margin.
///
/// The Fill dimension.
/// Margin to use.
public static Dim? Fill (int margin = 0) { return new DimFill (margin); }
///
/// Creates a function object that computes the dimension by executing the provided function.
/// The function will be called every time the dimension is needed.
///
/// The function to be executed.
/// The returned from the function.
public static Dim Func (Func function) { return new DimFunc (function); }
/// Creates a object that tracks the Height of the specified .
/// The height of the other .
/// The view that will be tracked.
public static Dim Height (View view) { return new DimView (view, Dimension.Height); }
/// Creates a percentage object that is a percentage of the width or height of the SuperView.
/// The percent object.
/// A value between 0 and 100 representing the percentage.
///
/// If the dimension is computed using the View's position ( or
/// ).
/// If the dimension is computed using the View's .
///
///
/// This initializes a that will be centered horizontally, is 50% of the way down, is 30% the
/// height,
/// and is 80% the width of the SuperView.
///
/// var textView = new TextField {
/// X = Pos.Center (),
/// Y = Pos.Percent (50),
/// Width = Dim.Percent (80),
/// Height = Dim.Percent (30),
/// };
///
///
public static Dim? Percent (float percent, bool usePosition = false)
{
if (percent is < 0 or > 100)
{
throw new ArgumentException ("Percent value must be between 0 and 100");
}
return new DimPercent (percent / 100, usePosition);
}
/// Creates a object that tracks the Width of the specified .
/// The width of the other .
/// The view that will be tracked.
public static Dim Width (View view) { return new DimView (view, Dimension.Width); }
#endregion static Dim creation methods
#region virtual methods
///
/// Gets a dimension that is anchored to a certain point in the layout.
/// This method is typically used internally by the layout system to determine the size of a View.
///
/// The width of the area where the View is being sized (Superview.ContentSize).
///
/// An integer representing the calculated dimension. The way this dimension is calculated depends on the specific
/// subclass of Dim that is used. For example, DimAbsolute returns a fixed dimension, DimFactor returns a
/// dimension that is a certain percentage of the super view's size, and so on.
///
internal virtual int GetAnchor (int size) { return 0; }
///
/// Calculates and returns the dimension of a object. It takes into account the location of the
/// , it's SuperView's ContentSize, and whether it should automatically adjust its size based on its
/// content.
///
///
/// The starting point from where the size calculation begins. It could be the left edge for width calculation or the
/// top edge for height calculation.
///
/// The size of the SuperView's content. It could be width or height.
/// The View that holds this Pos object.
/// Width or Height
///
/// The calculated size of the View. The way this size is calculated depends on the specific subclass of Dim that
/// is used.
///
internal virtual int Calculate (int location, int superviewContentSize, View us, Dimension dimension)
{
return Math.Max (GetAnchor (superviewContentSize - location), 0);
}
///
/// Diagnostics API to determine if this Dim object references other views.
///
///
internal virtual bool ReferencesOtherViews () { return false; }
#endregion virtual methods
#region operators
/// Adds a to a , yielding a new .
/// The first to add.
/// The second to add.
/// The that is the sum of the values of left and right.
public static Dim operator + (Dim? left, Dim? right)
{
if (left is DimAbsolute && right is DimAbsolute)
{
return new DimAbsolute (left.GetAnchor (0) + right.GetAnchor (0));
}
var newDim = new DimCombine (true, left, right);
(left as DimView)?.Target.SetNeedsLayout ();
return newDim;
}
/// Creates an Absolute from the specified integer value.
/// The Absolute .
/// The value to convert to the pos.
public static implicit operator Dim (int n) { return new DimAbsolute (n); }
///
/// Subtracts a from a , yielding a new
/// .
///
/// The to subtract from (the minuend).
/// The to subtract (the subtrahend).
/// The that is the left minus right.
public static Dim operator - (Dim? left, Dim? right)
{
if (left is DimAbsolute && right is DimAbsolute)
{
return new DimAbsolute (left.GetAnchor (0) - right.GetAnchor (0));
}
var newDim = new DimCombine (false, left, right);
(left as DimView)?.Target.SetNeedsLayout ();
return newDim;
}
#endregion operators
}
///
/// Represents a dimension that is a fixed size.
///
///
///
/// This is a low-level API that is typically used internally by the layout system. Use the various static
/// methods on the class to create objects instead.
///
///
///
public class DimAbsolute (int size) : Dim
{
///
public override bool Equals (object? other) { return other is DimAbsolute abs && abs.Size == Size; }
///
public override int GetHashCode () { return Size.GetHashCode (); }
///
/// Gets the size of the dimension.
///
public int Size { get; } = size;
///
public override string ToString () { return $"Absolute({Size})"; }
internal override int GetAnchor (int size) { return Size; }
internal override int Calculate (int location, int superviewContentSize, View us, Dimension dimension)
{
return Math.Max (GetAnchor (0), 0);
}
}
///
/// Represents a dimension that automatically sizes the view to fit all the view's Content, SubViews, and/or Text.
///
///
///
/// See .
///
///
/// This is a low-level API that is typically used internally by the layout system. Use the various static
/// methods on the class to create objects instead.
///
///
public class DimAuto () : Dim
{
private readonly Dim? _maximumContentDim;
///
/// Gets the maximum dimension the View's ContentSize will be fit to. NOT CURRENTLY SUPPORTED.
///
// ReSharper disable once ConvertToAutoProperty
public required Dim? MaximumContentDim
{
get => _maximumContentDim;
init => _maximumContentDim = value;
}
private readonly Dim? _minimumContentDim;
///
/// Gets the minimum dimension the View's ContentSize will be constrained to.
///
// ReSharper disable once ConvertToAutoProperty
public required Dim? MinimumContentDim
{
get => _minimumContentDim;
init => _minimumContentDim = value;
}
private readonly DimAutoStyle _style;
///
/// Gets the style of the DimAuto.
///
// ReSharper disable once ConvertToAutoProperty
public required DimAutoStyle Style
{
get => _style;
init => _style = value;
}
///
public override string ToString () { return $"Auto({Style},{MinimumContentDim},{MaximumContentDim})"; }
internal override int Calculate (int location, int superviewContentSize, View us, Dimension dimension)
{
var textSize = 0;
var subviewsSize = 0;
int autoMin = MinimumContentDim?.GetAnchor (superviewContentSize) ?? 0;
if (Style.HasFlag (DimAutoStyle.Text))
{
textSize = int.Max (autoMin, dimension == Dimension.Width ? us.TextFormatter.Size.Width : us.TextFormatter.Size.Height);
}
if (Style.HasFlag (DimAutoStyle.Content))
{
if (us._contentSize is { })
{
subviewsSize = dimension == Dimension.Width ? us.ContentSize.Width : us.ContentSize.Height;
}
else
{
// TODO: This whole body of code is a WIP (for https://github.com/gui-cs/Terminal.Gui/pull/3451).
subviewsSize = 0;
List subviews;
if (dimension == Dimension.Width)
{
subviews = us.Subviews.Where (v => v.X is not PosAnchorEnd && v.Width is not DimFill).ToList ();
}
else
{
subviews = us.Subviews.Where (v => v.Y is not PosAnchorEnd && v.Height is not DimFill).ToList ();
}
for (var i = 0; i < subviews.Count; i++)
{
View v = subviews [i];
int size = dimension == Dimension.Width ? v.Frame.X + v.Frame.Width : v.Frame.Y + v.Frame.Height;
if (size > subviewsSize)
{
subviewsSize = size;
}
}
if (dimension == Dimension.Width)
{
subviews = us.Subviews.Where (v => v.X is PosAnchorEnd).ToList ();
}
else
{
subviews = us.Subviews.Where (v => v.Y is PosAnchorEnd).ToList ();
}
int maxAnchorEnd = 0;
for (var i = 0; i < subviews.Count; i++)
{
View v = subviews [i];
maxAnchorEnd = dimension == Dimension.Width ? v.Frame.Width : v.Frame.Height;
}
subviewsSize += maxAnchorEnd;
if (dimension == Dimension.Width)
{
subviews = us.Subviews.Where (v => v.Width is DimFill).ToList ();
}
else
{
subviews = us.Subviews.Where (v => v.Height is DimFill).ToList ();
}
for (var i = 0; i < subviews.Count; i++)
{
View v = subviews [i];
if (dimension == Dimension.Width)
{
v.SetRelativeLayout (new Size (autoMin - subviewsSize, 0));
}
else
{
v.SetRelativeLayout (new Size (0, autoMin - subviewsSize));
}
}
}
}
// All sizes here are content-relative; ignoring adornments.
// We take the largest of text and content.
int max = int.Max (textSize, subviewsSize);
// And, if min: is set, it wins if larger
max = int.Max (max, autoMin);
// Factor in adornments
Thickness thickness = us.GetAdornmentsThickness ();
if (dimension == Dimension.Width)
{
max += thickness.Horizontal;
}
else
{
max += thickness.Vertical;
}
// If max: is set, clamp the return - BUGBUG: Not tested
return int.Min (max, MaximumContentDim?.GetAnchor (superviewContentSize) ?? max);
}
internal override bool ReferencesOtherViews ()
{
// BUGBUG: This is not correct. _contentSize may be null.
return false; //_style.HasFlag (DimAutoStyle.Content);
}
///
public override bool Equals (object? other)
{
if (other is not DimAuto auto)
{
return false;
}
return auto.MinimumContentDim == MinimumContentDim &&
auto.MaximumContentDim == MaximumContentDim &&
auto.Style == Style;
}
///
public override int GetHashCode ()
{
return HashCode.Combine (MinimumContentDim, MaximumContentDim, Style);
}
}
///
/// Represents a dimension that is a combination of two other dimensions.
///
///
/// Indicates whether the two dimensions are added or subtracted. If , the dimensions are added,
/// otherwise they are subtracted.
///
///
/// This is a low-level API that is typically used internally by the layout system. Use the various static
/// methods on the class to create objects instead.
///
/// The left dimension.
/// The right dimension.
public class DimCombine (bool add, Dim? left, Dim? right) : Dim
{
///
/// Gets whether the two dimensions are added or subtracted.
///
public bool Add { get; } = add;
///
/// Gets the left dimension.
///
public Dim? Left { get; } = left;
///
/// Gets the right dimension.
///
public Dim? Right { get; } = right;
///
public override string ToString () { return $"Combine({Left}{(Add ? '+' : '-')}{Right})"; }
internal override int GetAnchor (int size)
{
int la = Left!.GetAnchor (size);
int ra = Right!.GetAnchor (size);
if (Add)
{
return la + ra;
}
return la - ra;
}
internal override int Calculate (int location, int superviewContentSize, View us, Dimension dimension)
{
int leftNewDim = Left!.Calculate (location, superviewContentSize, us, dimension);
int rightNewDim = Right!.Calculate (location, superviewContentSize, us, dimension);
int newDimension;
if (Add)
{
newDimension = leftNewDim + rightNewDim;
}
else
{
newDimension = Math.Max (0, leftNewDim - rightNewDim);
}
return newDimension;
}
///
/// Diagnostics API to determine if this Dim object references other views.
///
///
internal override bool ReferencesOtherViews ()
{
if (Left!.ReferencesOtherViews ())
{
return true;
}
if (Right!.ReferencesOtherViews ())
{
return true;
}
return false;
}
}
///
/// Represents a dimension that is a percentage of the width or height of the SuperView.
///
///
/// This is a low-level API that is typically used internally by the layout system. Use the various static
/// methods on the class to create objects instead.
///
/// The percentage.
///
/// If the dimension is computed using the View's position ( or
/// ).
/// If the dimension is computed using the View's .
///
public class DimPercent (float percent, bool usePosition = false) : Dim
{
///
public override bool Equals (object? other) { return other is DimPercent f && f.Percent == Percent && f.UsePosition == UsePosition; }
///
public override int GetHashCode () { return Percent.GetHashCode (); }
///
/// Gets the percentage.
///
public new float Percent { get; } = percent;
///
///
///
public override string ToString () { return $"Percent({Percent},{UsePosition})"; }
///
/// Gets whether the dimension is computed using the View's position or ContentSize.
///
public bool UsePosition { get; } = usePosition;
internal override int GetAnchor (int size) { return (int)(size * Percent); }
internal override int Calculate (int location, int superviewContentSize, View us, Dimension dimension)
{
return UsePosition ? Math.Max (GetAnchor (superviewContentSize - location), 0) : GetAnchor (superviewContentSize);
}
}
///
/// Represents a dimension that fills the dimension, leaving the specified margin.
///
///
/// This is a low-level API that is typically used internally by the layout system. Use the various static
/// methods on the class to create objects instead.
///
/// The margin to not fill.
public class DimFill (int margin) : Dim
{
///
public override bool Equals (object? other) { return other is DimFill fill && fill.Margin == Margin; }
///
public override int GetHashCode () { return Margin.GetHashCode (); }
///
/// Gets the margin to not fill.
///
public int Margin { get; } = margin;
///
public override string ToString () { return $"Fill({Margin})"; }
internal override int GetAnchor (int size) { return size - Margin; }
}
///
/// Represents a function object that computes the dimension by executing the provided function.
///
///
/// This is a low-level API that is typically used internally by the layout system. Use the various static
/// methods on the class to create objects instead.
///
///
public class DimFunc (Func dim) : Dim
{
///
public override bool Equals (object? other) { return other is DimFunc f && f.Func () == Func (); }
///
/// Gets the function that computes the dimension.
///
public new Func Func { get; } = dim;
///
public override int GetHashCode () { return Func.GetHashCode (); }
///
public override string ToString () { return $"DimFunc({Func ()})"; }
internal override int GetAnchor (int size) { return Func (); }
}
///
/// Represents a dimension that tracks the Height or Width of the specified View.
///
///
/// This is a low-level API that is typically used internally by the layout system. Use the various static
/// methods on the class to create objects instead.
///
public class DimView : Dim
{
///
/// Initializes a new instance of the class.
///
/// The view the dimension is anchored to.
/// Indicates which dimension is tracked.
public DimView (View view, Dimension dimension)
{
Target = view;
Dimension = dimension;
}
///
/// Gets the indicated dimension of the View.
///
public Dimension Dimension { get; }
///
public override bool Equals (object? other) { return other is DimView abs && abs.Target == Target && abs.Dimension == Dimension; }
///
public override int GetHashCode () { return Target.GetHashCode (); }
///
/// Gets the View the dimension is anchored to.
///
public View Target { get; init; }
///
public override string ToString ()
{
if (Target == null)
{
throw new NullReferenceException ();
}
string dimString = Dimension switch
{
Dimension.Height => "Height",
Dimension.Width => "Width",
_ => "unknown"
};
return $"View({dimString},{Target})";
}
internal override int GetAnchor (int size)
{
return Dimension switch
{
Dimension.Height => Target.Frame.Height,
Dimension.Width => Target.Frame.Width,
_ => 0
};
}
internal override bool ReferencesOtherViews () { return true; }
}