using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using NStack;
namespace Terminal.Gui {
///
/// Determines the LayoutStyle for a , if Absolute, during , the
/// value from the will be used, if the value is Computed, then
/// will be updated from the X, Y objects and the Width and Height objects.
///
public enum LayoutStyle {
///
/// The position and size of the view are based .
///
Absolute,
///
/// The position and size of the view will be computed based on
/// , , , and . will
/// provide the absolute computed values.
///
Computed
}
///
/// View is the base class for all views on the screen and represents a visible element that can render itself and
/// contains zero or more nested views, called SubViews.
///
///
///
/// The View defines the base functionality for user interface elements in Terminal.Gui. Views
/// can contain one or more subviews, can respond to user input and render themselves on the screen.
///
///
/// Views supports two layout styles: or .
/// The choice as to which layout style is used by the View
/// is determined when the View is initialized. To create a View using Absolute layout, call a constructor that takes a
/// Rect parameter to specify the absolute position and size (the View.). To create a View
/// using Computed layout use a constructor that does not take a Rect parameter and set the X, Y, Width and Height
/// properties on the view. Both approaches use coordinates that are relative to the container they are being added to.
///
///
/// To switch between Absolute and Computed layout, use the property.
///
///
/// Computed layout is more flexible and supports dynamic console apps where controls adjust layout
/// as the terminal resizes or other Views change size or position. The X, Y, Width and Height
/// properties are Dim and Pos objects that dynamically update the position of a view.
/// The X and Y properties are of type
/// and you can use either absolute positions, percentages or anchor
/// points. The Width and Height properties are of type
/// and can use absolute position,
/// percentages and anchors. These are useful as they will take
/// care of repositioning views when view's frames are resized or
/// if the terminal size changes.
///
///
/// Absolute layout requires specifying coordinates and sizes of Views explicitly, and the
/// View will typically stay in a fixed position and size. To change the position and size use the
/// property.
///
///
/// Subviews (child views) can be added to a View by calling the method.
/// The container of a View can be accessed with the property.
///
///
/// To flag a region of the View's to be redrawn call .
/// To flag the entire view for redraw call .
///
///
/// Views have a property that defines the default colors that subviews
/// should use for rendering. This ensures that the views fit in the context where
/// they are being used, and allows for themes to be plugged in. For example, the
/// default colors for windows and toplevels uses a blue background, while it uses
/// a white background for dialog boxes and a red background for errors.
///
///
/// Subclasses should not rely on being
/// set at construction time. If a is not set on a view, the view will inherit the
/// value from its and the value might only be valid once a view has been
/// added to a SuperView.
///
///
/// By using applications will work both
/// in color as well as black and white displays.
///
///
/// Views that are focusable should implement the to make sure that
/// the cursor is placed in a location that makes sense. Unix terminals do not have
/// a way of hiding the cursor, so it can be distracting to have the cursor left at
/// the last focused view. So views should make sure that they place the cursor
/// in a visually sensible place.
///
///
/// The method is invoked when the size or layout of a view has
/// changed. The default processing system will keep the size and dimensions
/// for views that use the , and will recompute the
/// frames for the vies that use .
///
///
/// Views can also opt-in to more sophisticated initialization
/// by implementing overrides to and
/// which will be called
/// when the view is added to a .
///
///
/// If first-run-only initialization is preferred, overrides to
/// can be implemented, in which case the
/// methods will only be called if
/// is . This allows proper inheritance hierarchies
/// to override base class layout code optimally by doing so only on first run,
/// instead of on every run.
///
///
public partial class View : Responder, ISupportInitializeNotification {
internal enum Direction {
Forward,
Backward
}
// container == SuperView
View _superView = null;
View focused = null;
Direction focusDirection;
bool autoSize;
ShortcutHelper shortcutHelper;
///
/// Event fired when this view is added to another.
///
public event EventHandler Added;
///
/// Event fired when this view is removed from another.
///
public event EventHandler Removed;
///
/// Event fired when the view gets focus.
///
public event EventHandler Enter;
///
/// Event fired when the view looses focus.
///
public event EventHandler Leave;
///
/// Event fired when the view receives the mouse event for the first time.
///
public event EventHandler MouseEnter;
///
/// Event fired when the view receives a mouse event for the last time.
///
public event EventHandler MouseLeave;
///
/// Event fired when a mouse event is generated.
///
public event EventHandler MouseClick;
///
/// Event fired when the value is being changed.
///
public event EventHandler CanFocusChanged;
///
/// Event fired when the value is being changed.
///
public event EventHandler EnabledChanged;
///
/// Event fired when the value is being changed.
///
public event EventHandler VisibleChanged;
///
/// Event invoked when the is changed.
///
public event EventHandler HotKeyChanged;
Key hotKey = Key.Null;
///
/// Gets or sets the HotKey defined for this view. A user pressing HotKey on the keyboard while this view has focus will cause the Clicked event to fire.
///
public virtual Key HotKey {
get => hotKey;
set {
if (hotKey != value) {
hotKey = TextFormatter.HotKey = (value == Key.Unknown ? Key.Null : value);
}
}
}
///
/// Gets or sets the specifier character for the hotkey (e.g. '_'). Set to '\xffff' to disable hotkey support for this View instance. The default is '\xffff'.
///
public virtual Rune HotKeySpecifier {
get {
if (TextFormatter != null) {
return TextFormatter.HotKeySpecifier;
} else {
return new Rune ('\xFFFF');
}
}
set {
TextFormatter.HotKeySpecifier = value;
SetHotKey ();
}
}
///
/// This is the global setting that can be used as a global shortcut to invoke an action if provided.
///
public Key Shortcut {
get => shortcutHelper.Shortcut;
set {
if (shortcutHelper.Shortcut != value && (ShortcutHelper.PostShortcutValidation (value) || value == Key.Null)) {
shortcutHelper.Shortcut = value;
}
}
}
///
/// The keystroke combination used in the as string.
///
public ustring ShortcutTag => ShortcutHelper.GetShortcutTag (shortcutHelper.Shortcut);
///
/// The action to run if the is defined.
///
public virtual Action ShortcutAction { get; set; }
///
/// Gets or sets arbitrary data for the view.
///
/// This property is not used internally.
public object Data { get; set; }
internal Direction FocusDirection {
get => SuperView?.FocusDirection ?? focusDirection;
set {
if (SuperView != null)
SuperView.FocusDirection = value;
else
focusDirection = value;
}
}
///
/// Points to the current driver in use by the view, it is a convenience property
/// for simplifying the development of new views.
///
public static ConsoleDriver Driver => Application.Driver;
static readonly IList empty = new List (0).AsReadOnly ();
// This is null, and allocated on demand.
List subviews;
///
/// This returns a list of the subviews contained by this view.
///
/// The subviews.
public IList Subviews => subviews?.AsReadOnly () ?? empty;
// Internally, we use InternalSubviews rather than subviews, as we do not expect us
// to make the same mistakes our users make when they poke at the Subviews.
internal IList InternalSubviews => subviews ?? empty;
// This is null, and allocated on demand.
List tabIndexes;
///
/// Configurable keybindings supported by the control
///
private Dictionary KeyBindings { get; set; } = new Dictionary ();
private Dictionary> CommandImplementations { get; set; } = new Dictionary> ();
///
/// This returns a tab index list of the subviews contained by this view.
///
/// The tabIndexes.
public IList TabIndexes => tabIndexes?.AsReadOnly () ?? empty;
int tabIndex = -1;
///
/// Indicates the index of the current from the list.
///
public int TabIndex {
get { return tabIndex; }
set {
if (!CanFocus) {
tabIndex = -1;
return;
} else if (SuperView?.tabIndexes == null || SuperView?.tabIndexes.Count == 1) {
tabIndex = 0;
return;
} else if (tabIndex == value) {
return;
}
tabIndex = value > SuperView.tabIndexes.Count - 1 ? SuperView.tabIndexes.Count - 1 : value < 0 ? 0 : value;
tabIndex = GetTabIndex (tabIndex);
if (SuperView.tabIndexes.IndexOf (this) != tabIndex) {
SuperView.tabIndexes.Remove (this);
SuperView.tabIndexes.Insert (tabIndex, this);
SetTabIndex ();
}
}
}
int GetTabIndex (int idx)
{
var i = 0;
foreach (var v in SuperView.tabIndexes) {
if (v.tabIndex == -1 || v == this) {
continue;
}
i++;
}
return Math.Min (i, idx);
}
void SetTabIndex ()
{
var i = 0;
foreach (var v in SuperView.tabIndexes) {
if (v.tabIndex == -1) {
continue;
}
v.tabIndex = i;
i++;
}
}
bool tabStop = true;
///
/// This only be if the is also
/// and the focus can be avoided by setting this to
///
public bool TabStop {
get => tabStop;
set {
if (tabStop == value) {
return;
}
tabStop = CanFocus && value;
}
}
bool oldCanFocus;
int oldTabIndex;
///
public override bool CanFocus {
get => base.CanFocus;
set {
if (!addingView && IsInitialized && SuperView?.CanFocus == false && value) {
throw new InvalidOperationException ("Cannot set CanFocus to true if the SuperView CanFocus is false!");
}
if (base.CanFocus != value) {
base.CanFocus = value;
switch (value) {
case false when tabIndex > -1:
TabIndex = -1;
break;
case true when SuperView?.CanFocus == false && addingView:
SuperView.CanFocus = true;
break;
}
if (value && tabIndex == -1) {
TabIndex = SuperView != null ? SuperView.tabIndexes.IndexOf (this) : -1;
}
TabStop = value;
if (!value && SuperView?.Focused == this) {
SuperView.focused = null;
}
if (!value && HasFocus) {
SetHasFocus (false, this);
SuperView?.EnsureFocus ();
if (SuperView != null && SuperView.Focused == null) {
SuperView.FocusNext ();
if (SuperView.Focused == null) {
Application.Current.FocusNext ();
}
Application.EnsuresTopOnFront ();
}
}
if (subviews != null && IsInitialized) {
foreach (var view in subviews) {
if (view.CanFocus != value) {
if (!value) {
view.oldCanFocus = view.CanFocus;
view.oldTabIndex = view.tabIndex;
view.CanFocus = false;
view.tabIndex = -1;
} else {
if (addingView) {
view.addingView = true;
}
view.CanFocus = view.oldCanFocus;
view.tabIndex = view.oldTabIndex;
view.addingView = false;
}
}
}
}
OnCanFocusChanged ();
SetNeedsDisplay ();
}
}
}
// The frame for the object. Superview relative.
Rect frame;
///
/// Gets or sets an identifier for the view;
///
/// The identifier.
/// The id should be unique across all Views that share a SuperView.
public string Id { get; set; } = "";
///
/// Returns a value indicating if this View is currently on Top (Active)
///
public bool IsCurrentTop => Application.Current == this;
///
/// Gets or sets a value indicating whether this wants mouse position reports.
///
/// if want mouse position reports; otherwise, .
public virtual bool WantMousePositionReports { get; set; }
///
/// Gets or sets a value indicating whether this want continuous button pressed event.
///
public virtual bool WantContinuousButtonPressed { get; set; }
///
/// Gets or sets the frame for the view. The frame is relative to the view's container ().
///
/// The frame.
///
///
/// Change the Frame when using the layout style to move or resize views.
///
///
/// Altering the Frame of a view will trigger the redrawing of the
/// view as well as the redrawing of the affected regions of the .
///
///
public virtual Rect Frame {
get => frame;
set {
frame = new Rect (value.X, value.Y, Math.Max (value.Width, 0), Math.Max (value.Height, 0));
if (IsInitialized || LayoutStyle == LayoutStyle.Absolute) {
TextFormatter.Size = GetSizeNeededForTextAndHotKey ();
LayoutFrames ();
SetNeedsLayout ();
SetNeedsDisplay ();
}
}
}
///
/// The Thickness that separates a View from other SubViews of the same SuperView.
/// The Margin is not part of the View's content and is not clipped by the View's Clip Area.
///
public Frame Margin { get; private set; }
// TODO: Rename BorderFrame to Border
///
/// Thickness where a visual border (drawn using line-drawing glyphs) and the Title are drawn.
/// The Border expands inward; in other words if `Border.Thickness.Top == 2` the border and
/// title will take up the first row and the second row will be filled with spaces.
/// The Border is not part of the View's content and is not clipped by the View's `ClipArea`.
///
public Frame BorderFrame { get; private set; }
///
/// Means the Thickness inside of an element that offsets the `Content` from the Border.
/// Padding is `{0, 0, 0, 0}` by default. Padding is not part of the View's content and is not clipped by the View's `ClipArea`.
///
///
/// (NOTE: in v1 `Padding` is OUTSIDE of the `Border`).
///
public Frame Padding { get; private set; }
///
/// Helper to get the X and Y offset of the Bounds from the Frame. This is the sum of the Left and Top properties of
/// , and .
///
public Point GetBoundsOffset () => new Point (Padding?.Thickness.GetInside (Padding.Frame).X ?? 0, Padding?.Thickness.GetInside (Padding.Frame).Y ?? 0);
///
/// Creates the view's objects. This internal method is overridden by Frame to do nothing
/// to prevent recursion during View construction.
///
internal virtual void CreateFrames ()
{
void ThicknessChangedHandler (object sender, EventArgs e)
{
SetNeedsLayout ();
}
if (Margin != null) {
Margin.ThicknessChanged -= ThicknessChangedHandler;
Margin.Dispose ();
}
Margin = new Frame () { Id = "Margin", Thickness = new Thickness (0) };
Margin.ThicknessChanged += ThicknessChangedHandler;
Margin.Parent = this;
if (BorderFrame != null) {
BorderFrame.ThicknessChanged -= ThicknessChangedHandler;
BorderFrame.Dispose ();
}
// TODO: create default for borderstyle
BorderFrame = new Frame () { Id = "BorderFrame", Thickness = new Thickness (0), BorderStyle = BorderStyle.Single };
BorderFrame.ThicknessChanged += ThicknessChangedHandler;
BorderFrame.Parent = this;
// TODO: Create View.AddAdornment
if (Padding != null) {
Padding.ThicknessChanged -= ThicknessChangedHandler;
Padding.Dispose ();
}
Padding = new Frame () { Id = "Padding", Thickness = new Thickness (0) };
Padding.ThicknessChanged += ThicknessChangedHandler;
Padding.Parent = this;
}
ustring title = ustring.Empty;
///
/// The title to be displayed for this . The title will be displayed if .
/// is greater than 0.
///
/// The title.
public ustring Title {
get => title;
set {
if (!OnTitleChanging (title, value)) {
var old = title;
title = value;
SetNeedsDisplay ();
#if DEBUG
if (title != null && string.IsNullOrEmpty (Id)) {
Id = title.ToString ();
}
#endif // DEBUG
OnTitleChanged (old, title);
}
}
}
///
/// Called before the changes. Invokes the event, which can be cancelled.
///
/// The that is/has been replaced.
/// The new to be replaced.
/// `true` if an event handler canceled the Title change.
public virtual bool OnTitleChanging (ustring oldTitle, ustring newTitle)
{
var args = new TitleEventArgs (oldTitle, newTitle);
TitleChanging?.Invoke (this, args);
return args.Cancel;
}
///
/// Event fired when the is changing. Set to
/// `true` to cancel the Title change.
///
public event EventHandler TitleChanging;
///
/// Called when the has been changed. Invokes the event.
///
/// The that is/has been replaced.
/// The new to be replaced.
public virtual void OnTitleChanged (ustring oldTitle, ustring newTitle)
{
var args = new TitleEventArgs (oldTitle, newTitle);
TitleChanged?.Invoke (this, args);
}
///
/// Event fired after the has been changed.
///
public event EventHandler TitleChanged;
LayoutStyle _layoutStyle;
///
/// Controls how the View's is computed during the LayoutSubviews method, if the style is set to
/// ,
/// LayoutSubviews does not change the . If the style is
/// the is updated using
/// the , , , and properties.
///
/// The layout style.
public LayoutStyle LayoutStyle {
get => _layoutStyle;
set {
_layoutStyle = value;
SetNeedsLayout ();
}
}
///
/// The View-relative rectangle where View content is displayed. SubViews are positioned relative to
/// Bounds.Location (which is always (0, 0)) and clips drawing to
/// Bounds.Size.
///
/// The bounds.
///
///
/// The of Bounds is always (0, 0). To obtain the offset of the Bounds from the Frame use
/// .
///
///
public virtual Rect Bounds {
get {
#if DEBUG
if (LayoutStyle == LayoutStyle.Computed && !IsInitialized) {
Debug.WriteLine ($"WARNING: Bounds is being accessed before the View has been initialized. This is likely a bug. View: {this}");
}
#endif // DEBUG
var frameRelativeBounds = Padding?.Thickness.GetInside (Padding.Frame) ?? new Rect (default, Frame.Size);
return new Rect (default, frameRelativeBounds.Size);
}
set {
// BUGBUG: Margin etc.. can be null (if typeof(Frame))
Frame = new Rect (Frame.Location,
new Size (
value.Size.Width + Margin.Thickness.Horizontal + BorderFrame.Thickness.Horizontal + Padding.Thickness.Horizontal,
value.Size.Height + Margin.Thickness.Vertical + BorderFrame.Thickness.Vertical + Padding.Thickness.Vertical
)
);
;
}
}
// Diagnostics to highlight when X or Y is read before the view has been initialized
private Pos VerifyIsIntialized (Pos pos)
{
#if DEBUG
if (LayoutStyle == LayoutStyle.Computed && (!IsInitialized)) {
Debug.WriteLine ($"WARNING: \"{this}\" has not been initialized; position is indeterminate {pos}. This is likely a bug.");
}
#endif // DEBUG
return pos;
}
// Diagnostics to highlight when Width or Height is read before the view has been initialized
private Dim VerifyIsIntialized (Dim dim)
{
#if DEBUG
if (LayoutStyle == LayoutStyle.Computed && (!IsInitialized)) {
Debug.WriteLine ($"WARNING: \"{this}\" has not been initialized; dimension is indeterminate: {dim}. This is likely a bug.");
}
#endif // DEBUG
return dim;
}
Pos x, y;
///
/// Gets or sets the X position for the view (the column). Only used if the is .
///
/// The X Position.
///
/// If is changing this property has no effect and its value is indeterminate.
///
public Pos X {
get => VerifyIsIntialized (x);
set {
if (ForceValidatePosDim && !ValidatePosDim (x, value)) {
throw new ArgumentException ();
}
x = value;
OnResizeNeeded ();
}
}
///
/// Gets or sets the Y position for the view (the row). Only used if the is .
///
/// The y position (line).
///
/// If is changing this property has no effect and its value is indeterminate.
///
public Pos Y {
get => VerifyIsIntialized (y);
set {
if (ForceValidatePosDim && !ValidatePosDim (y, value)) {
throw new ArgumentException ();
}
y = value;
OnResizeNeeded ();
}
}
Dim width, height;
///
/// Gets or sets the width of the view. Only used the is .
///
/// The width.
///
/// If is changing this property has no effect and its value is indeterminate.
///
public Dim Width {
get => VerifyIsIntialized (width);
set {
if (ForceValidatePosDim && !ValidatePosDim (width, value)) {
throw new ArgumentException ("ForceValidatePosDim is enabled", nameof (Width));
}
width = value;
if (ForceValidatePosDim) {
var isValidNewAutSize = autoSize && IsValidAutoSizeWidth (width);
if (IsAdded && autoSize && !isValidNewAutSize) {
throw new InvalidOperationException ("Must set AutoSize to false before set the Width.");
}
}
OnResizeNeeded ();
}
}
///
/// Gets or sets the height of the view. Only used the is .
///
/// The height.
/// If is changing this property has no effect and its value is indeterminate.
public Dim Height {
get => VerifyIsIntialized (height);
set {
if (ForceValidatePosDim && !ValidatePosDim (height, value)) {
throw new ArgumentException ("ForceValidatePosDim is enabled", nameof (Height));
}
height = value;
if (ForceValidatePosDim) {
var isValidNewAutSize = autoSize && IsValidAutoSizeHeight (height);
if (IsAdded && autoSize && !isValidNewAutSize) {
throw new InvalidOperationException ("Must set AutoSize to false before set the Height.");
}
}
OnResizeNeeded ();
}
}
///
/// Forces validation with layout
/// to avoid breaking the and settings.
///
public bool ForceValidatePosDim { get; set; }
bool ValidatePosDim (object oldValue, object newValue)
{
if (!IsInitialized || _layoutStyle == LayoutStyle.Absolute || oldValue == null || oldValue.GetType () == newValue.GetType () || this is Toplevel) {
return true;
}
if (_layoutStyle == LayoutStyle.Computed) {
if (oldValue.GetType () != newValue.GetType () && !(newValue is Pos.PosAbsolute || newValue is Dim.DimAbsolute)) {
return true;
}
}
return false;
}
// BUGBUG: This API is broken - It should be renamed to `GetMinimumBoundsForFrame and
// should not assume Frame.Height == Bounds.Height
///
/// Gets the minimum dimensions required to fit the View's , factoring in .
///
/// The minimum dimensions required.
/// if the dimensions fit within the View's , otherwise.
///
/// Always returns if is or
/// if (Horizontal) or (Vertical) are not not set or zero.
/// Does not take into account word wrapping.
///
public bool GetMinimumBounds (out Size size)
{
size = Bounds.Size;
if (!AutoSize && !ustring.IsNullOrEmpty (TextFormatter.Text)) {
switch (TextFormatter.IsVerticalDirection (TextDirection)) {
case true:
var colWidth = TextFormatter.GetSumMaxCharWidth (new List { TextFormatter.Text }, 0, 1);
// TODO: v2 - This uses frame.Width; it should only use Bounds
if (frame.Width < colWidth &&
(Width == null ||
(Bounds.Width >= 0 &&
Width is Dim.DimAbsolute &&
Width.Anchor (0) >= 0 &&
Width.Anchor (0) < colWidth))) {
size = new Size (colWidth, Bounds.Height);
return true;
}
break;
default:
if (frame.Height < 1 &&
(Height == null ||
(Height is Dim.DimAbsolute &&
Height.Anchor (0) == 0))) {
size = new Size (Bounds.Width, 1);
return true;
}
break;
}
}
return false;
}
// BUGBUG - v2 - Should be renamed "SetBoundsToFitFrame"
///
/// Sets the size of the View to the minimum width or height required to fit (see .
///
/// if the size was changed, if
/// will not fit.
public bool SetMinWidthHeight ()
{
if (IsInitialized && GetMinimumBounds (out Size size)) {
Bounds = new Rect (Bounds.Location, size);
return true;
}
return false;
}
///
/// Gets or sets the which can be handled differently by any derived class.
///
public TextFormatter TextFormatter { get; set; }
///
/// Returns the container for this view, or null if this view has not been added to a container.
///
/// The super view.
public virtual View SuperView {
get {
return _superView;
}
set {
throw new NotImplementedException ();
}
}
///
/// Initializes a new instance of a class with the absolute
/// dimensions specified in the parameter.
///
/// The region covered by this view.
///
/// This constructor initialize a View with a of .
/// Use to initialize a View with of
///
public View (Rect frame) : this (frame, null, null) { }
///
/// Initializes a new instance of using layout.
///
///
///
/// Use , , , and properties to dynamically control the size and location of the view.
/// The will be created using
/// coordinates. The initial size () will be
/// adjusted to fit the contents of , including newlines ('\n') for multiple lines.
///
///
/// If is greater than one, word wrapping is provided.
///
///
/// This constructor initialize a View with a of .
/// Use , , , and properties to dynamically control the size and location of the view.
///
///
public View () : this (text: string.Empty, direction: TextDirection.LeftRight_TopBottom) { }
///
/// Initializes a new instance of using layout.
///
///
///
/// The will be created at the given
/// coordinates with the given string. The size () will be
/// adjusted to fit the contents of , including newlines ('\n') for multiple lines.
///
///
/// No line wrapping is provided.
///
///
/// column to locate the View.
/// row to locate the View.
/// text to initialize the property with.
public View (int x, int y, ustring text) : this (TextFormatter.CalcRect (x, y, text), text) { }
///
/// Initializes a new instance of using layout.
///
///
///
/// The will be created at the given
/// coordinates with the given string. The initial size () will be
/// adjusted to fit the contents of , including newlines ('\n') for multiple lines.
///
///
/// If rect.Height is greater than one, word wrapping is provided.
///
///
/// Location.
/// text to initialize the property with.
/// The .
public View (Rect rect, ustring text, Border border = null)
{
SetInitialProperties (text, rect, LayoutStyle.Absolute, TextDirection.LeftRight_TopBottom, border);
}
///
/// Initializes a new instance of using layout.
///
///
///
/// The will be created using
/// coordinates with the given string. The initial size () will be
/// adjusted to fit the contents of , including newlines ('\n') for multiple lines.
///
///
/// If is greater than one, word wrapping is provided.
///
///
/// text to initialize the property with.
/// The text direction.
/// The .
public View (ustring text, TextDirection direction = TextDirection.LeftRight_TopBottom, Border border = null)
{
SetInitialProperties (text, Rect.Empty, LayoutStyle.Computed, direction, border);
}
// TODO: v2 - Remove constructors with parameters
///
/// Private helper to set the initial properties of the View that were provided via constructors.
///
///
///
///
///
///
void SetInitialProperties (ustring text, Rect rect, LayoutStyle layoutStyle = LayoutStyle.Computed,
TextDirection direction = TextDirection.LeftRight_TopBottom, Border border = null)
{
TextFormatter = new TextFormatter ();
TextFormatter.HotKeyChanged += TextFormatter_HotKeyChanged;
TextDirection = direction;
shortcutHelper = new ShortcutHelper ();
CanFocus = false;
TabIndex = -1;
TabStop = false;
LayoutStyle = layoutStyle;
Border = border;
Text = text == null ? ustring.Empty : text;
LayoutStyle = layoutStyle;
var r = rect.IsEmpty ? TextFormatter.CalcRect (0, 0, text, direction) : rect;
Frame = r;
OnResizeNeeded ();
CreateFrames ();
LayoutFrames ();
}
// TODO: v2 - Hack for now
private void Border_BorderChanged (Border border)
{
//if (!border.DrawMarginFrame) BorderFrame.BorderStyle = BorderStyle.None;
BorderFrame.BorderStyle = border.BorderStyle;
BorderFrame.Thickness = new Thickness (BorderFrame.BorderStyle == BorderStyle.None ? 0 : 1);
}
///
/// Can be overridden if the has
/// different format than the default.
///
protected virtual void UpdateTextFormatterText ()
{
if (TextFormatter != null) {
TextFormatter.Text = text;
}
}
///
/// Called whenever the view needs to be resized.
/// Can be overridden if the view resize behavior is
/// different than the default.
///
protected virtual void OnResizeNeeded ()
{
var actX = x is Pos.PosAbsolute ? x.Anchor (0) : frame.X;
var actY = y is Pos.PosAbsolute ? y.Anchor (0) : frame.Y;
if (AutoSize) {
var s = GetAutoSize ();
var w = width is Dim.DimAbsolute && width.Anchor (0) > s.Width ? width.Anchor (0) : s.Width;
var h = height is Dim.DimAbsolute && height.Anchor (0) > s.Height ? height.Anchor (0) : s.Height;
frame = new Rect (new Point (actX, actY), new Size (w, h)); // Set frame, not Frame!
} else {
var w = width is Dim.DimAbsolute ? width.Anchor (0) : frame.Width;
var h = height is Dim.DimAbsolute ? height.Anchor (0) : frame.Height;
// BUGBUG: v2 - ? - If layoutstyle is absolute, this overwrites the current frame h/w with 0. Hmmm...
frame = new Rect (new Point (actX, actY), new Size (w, h)); // Set frame, not Frame!
}
//// BUGBUG: I think these calls are redundant or should be moved into just the AutoSize case
if (IsInitialized || LayoutStyle == LayoutStyle.Absolute) {
TextFormatter.Size = GetSizeNeededForTextAndHotKey ();
LayoutFrames ();
SetMinWidthHeight ();
SetNeedsLayout ();
SetNeedsDisplay ();
}
}
void TextFormatter_HotKeyChanged (object sender, KeyChangedEventArgs e)
{
HotKeyChanged?.Invoke (this, e);
}
internal bool LayoutNeeded { get; private set; } = true;
internal void SetNeedsLayout ()
{
if (LayoutNeeded)
return;
LayoutNeeded = true;
if (SuperView == null)
return;
SuperView.SetNeedsLayout ();
foreach (var view in Subviews) {
view.SetNeedsLayout ();
}
TextFormatter.NeedsFormat = true;
}
///
/// Removes the setting on this view.
///
protected void ClearLayoutNeeded ()
{
LayoutNeeded = false;
}
// The view-relative region that needs to be redrawn
internal Rect _needsDisplay { get; private set; } = Rect.Empty;
///
/// Sets a flag indicating this view needs to be redisplayed because its state has changed.
///
public void SetNeedsDisplay ()
{
if (!IsInitialized) return;
SetNeedsDisplay (Bounds);
}
///
/// Flags the view-relative region on this View as needing to be redrawn.
///
/// The view-relative region that needs to be redrawn.
public void SetNeedsDisplay (Rect region)
{
if (_needsDisplay.IsEmpty)
_needsDisplay = region;
else {
var x = Math.Min (_needsDisplay.X, region.X);
var y = Math.Min (_needsDisplay.Y, region.Y);
var w = Math.Max (_needsDisplay.Width, region.Width);
var h = Math.Max (_needsDisplay.Height, region.Height);
_needsDisplay = new Rect (x, y, w, h);
}
_superView?.SetSubViewNeedsDisplay ();
if (subviews == null)
return;
foreach (var view in subviews)
if (view.Frame.IntersectsWith (region)) {
var childRegion = Rect.Intersect (view.Frame, region);
childRegion.X -= view.Frame.X;
childRegion.Y -= view.Frame.Y;
view.SetNeedsDisplay (childRegion);
}
}
private Rect GetNeedsDisplayRectScreen (Rect containerBounds)
{
Rect rect = ViewToScreen (_needsDisplay);
if (!containerBounds.IsEmpty) {
rect.Width = Math.Min (_needsDisplay.Width, containerBounds.Width);
rect.Height = Math.Min (_needsDisplay.Height, containerBounds.Height);
}
return rect;
}
internal bool _childNeedsDisplay { get; private set; }
///
/// Indicates that any Subviews (in the list) need to be repainted.
///
public void SetSubViewNeedsDisplay ()
{
if (_childNeedsDisplay) {
return;
}
_childNeedsDisplay = true;
if (_superView != null && !_superView._childNeedsDisplay)
_superView.SetSubViewNeedsDisplay ();
}
internal bool addingView;
///
/// Adds a subview (child) to this view.
///
///
/// The Views that have been added to this view can be retrieved via the property.
/// See also
///
public virtual void Add (View view)
{
if (view == null) {
return;
}
if (subviews == null) {
subviews = new List ();
}
if (tabIndexes == null) {
tabIndexes = new List ();
}
subviews.Add (view);
tabIndexes.Add (view);
view._superView = this;
if (view.CanFocus) {
addingView = true;
if (SuperView?.CanFocus == false) {
SuperView.addingView = true;
SuperView.CanFocus = true;
SuperView.addingView = false;
}
CanFocus = true;
view.tabIndex = tabIndexes.IndexOf (view);
addingView = false;
}
if (view.Enabled && !Enabled) {
view.oldEnabled = true;
view.Enabled = false;
}
SetNeedsLayout ();
SetNeedsDisplay ();
OnAdded (new SuperViewChangedEventArgs (this, view));
if (IsInitialized && !view.IsInitialized) {
view.BeginInit ();
view.EndInit ();
}
}
///
/// Adds the specified views (children) to the view.
///
/// Array of one or more views (can be optional parameter).
///
/// The Views that have been added to this view can be retrieved via the property.
/// See also
///
public void Add (params View [] views)
{
if (views == null) {
return;
}
foreach (var view in views) {
Add (view);
}
}
///
/// Removes all subviews (children) added via or from this View.
///
public virtual void RemoveAll ()
{
if (subviews == null) {
return;
}
while (subviews.Count > 0) {
Remove (subviews [0]);
}
}
///
/// Removes a subview added via or from this View.
///
///
///
public virtual void Remove (View view)
{
if (view == null || subviews == null) return;
var touched = view.Frame;
subviews.Remove (view);
tabIndexes.Remove (view);
view._superView = null;
view.tabIndex = -1;
SetNeedsLayout ();
SetNeedsDisplay ();
foreach (var v in subviews) {
if (v.Frame.IntersectsWith (touched))
view.SetNeedsDisplay ();
}
OnRemoved (new SuperViewChangedEventArgs (this, view));
if (focused == view) {
focused = null;
}
}
void PerformActionForSubview (View subview, Action action)
{
if (subviews.Contains (subview)) {
action (subview);
}
SetNeedsDisplay ();
subview.SetNeedsDisplay ();
}
///
/// Brings the specified subview to the front so it is drawn on top of any other views.
///
/// The subview to send to the front
///
/// .
///
public void BringSubviewToFront (View subview)
{
PerformActionForSubview (subview, x => {
subviews.Remove (x);
subviews.Add (x);
});
}
///
/// Sends the specified subview to the front so it is the first view drawn
///
/// The subview to send to the front
///
/// .
///
public void SendSubviewToBack (View subview)
{
PerformActionForSubview (subview, x => {
subviews.Remove (x);
subviews.Insert (0, subview);
});
}
///
/// Moves the subview backwards in the hierarchy, only one step
///
/// The subview to send backwards
///
/// If you want to send the view all the way to the back use SendSubviewToBack.
///
public void SendSubviewBackwards (View subview)
{
PerformActionForSubview (subview, x => {
var idx = subviews.IndexOf (x);
if (idx > 0) {
subviews.Remove (x);
subviews.Insert (idx - 1, x);
}
});
}
///
/// Moves the subview backwards in the hierarchy, only one step
///
/// The subview to send backwards
///
/// If you want to send the view all the way to the back use SendSubviewToBack.
///
public void BringSubviewForward (View subview)
{
PerformActionForSubview (subview, x => {
var idx = subviews.IndexOf (x);
if (idx + 1 < subviews.Count) {
subviews.Remove (x);
subviews.Insert (idx + 1, x);
}
});
}
///
/// Clears the view region with the current color.
///
///
///
/// This clears the entire region used by this view.
///
///
public void Clear ()
{
var h = Frame.Height;
var w = Frame.Width;
for (var line = 0; line < h; line++) {
Move (0, line);
for (var col = 0; col < w; col++)
Driver.AddRune (' ');
}
}
// BUGBUG: Stupid that this takes screen-relative. We should have a tenet that says
// "View APIs only deal with View-relative coords".
///
/// Clears the specified region with the current color.
///
///
///
/// The screen-relative region to clear.
public void Clear (Rect regionScreen)
{
var h = regionScreen.Height;
var w = regionScreen.Width;
for (var line = regionScreen.Y; line < regionScreen.Y + h; line++) {
Driver.Move (regionScreen.X, line);
for (var col = 0; col < w; col++)
Driver.AddRune (' ');
}
}
///
/// Converts a point from screen-relative coordinates to view-relative coordinates.
///
/// The mapped point.
/// X screen-coordinate point.
/// Y screen-coordinate point.
public Point ScreenToView (int x, int y)
{
if (SuperView == null) {
return new Point (x - Frame.X, y - frame.Y);
} else {
var parent = SuperView.ScreenToView (x, y);
return new Point (parent.X - frame.X, parent.Y - frame.Y);
}
}
///
/// Converts a point from screen-relative coordinates to bounds-relative coordinates.
///
/// The mapped point.
/// X screen-coordinate point.
/// Y screen-coordinate point.
public Point ScreenToBounds (int x, int y)
{
if (SuperView == null) {
return new Point (x - Frame.X + GetBoundsOffset ().X, y - Frame.Y + GetBoundsOffset ().Y);
} else {
var parent = SuperView.ScreenToView (x, y);
return new Point (parent.X - frame.X, parent.Y - frame.Y);
}
}
///
/// Converts a view-relative location to a screen-relative location (col,row). The output is optionally clamped to the screen dimensions.
///
/// View-relative column.
/// View-relative row.
/// Absolute column; screen-relative.
/// Absolute row; screen-relative.
/// If , and will be clamped to the
/// screen dimensions (they never be negative and will always be less than to and
/// , respectively.
public virtual void ViewToScreen (int col, int row, out int rcol, out int rrow, bool clamped = true)
{
rcol = col + Frame.X + GetBoundsOffset ().X;
rrow = row + Frame.Y + GetBoundsOffset ().Y;
var super = SuperView;
while (super != null) {
rcol += super.Frame.X + super.GetBoundsOffset ().X;
rrow += super.Frame.Y + super.GetBoundsOffset ().Y;
super = super.SuperView;
}
// The following ensures that the cursor is always in the screen boundaries.
if (clamped) {
rrow = Math.Min (rrow, Driver.Rows - 1);
rcol = Math.Min (rcol, Driver.Cols - 1);
}
}
///
/// Converts a region in view-relative coordinates to screen-relative coordinates.
///
internal Rect ViewToScreen (Rect region)
{
ViewToScreen (region.X, region.Y, out var x, out var y, clamped: false);
return new Rect (x, y, region.Width, region.Height);
}
// Clips a rectangle in screen coordinates to the dimensions currently available on the screen
internal Rect ScreenClip (Rect regionScreen)
{
var x = regionScreen.X < 0 ? 0 : regionScreen.X;
var y = regionScreen.Y < 0 ? 0 : regionScreen.Y;
var w = regionScreen.X + regionScreen.Width >= Driver.Cols ? Driver.Cols - regionScreen.X : regionScreen.Width;
var h = regionScreen.Y + regionScreen.Height >= Driver.Rows ? Driver.Rows - regionScreen.Y : regionScreen.Height;
return new Rect (x, y, w, h);
}
///
/// Sets the 's clip region to .
///
/// The current screen-relative clip region, which can be then re-applied by setting .
///
///
/// is View-relative.
///
///
/// If and do not intersect, the clip region will be set to .
///
///
public Rect ClipToBounds ()
{
var clip = Bounds;
return SetClip (clip);
}
// BUGBUG: v2 - SetClip should return VIEW-relative so that it can be used to reset it; using Driver.Clip directly should not be necessary.
///
/// Sets the clip region to the specified view-relative region.
///
/// The current screen-relative clip region, which can be then re-applied by setting .
/// View-relative clip region.
///
/// If and do not intersect, the clip region will be set to .
///
public Rect SetClip (Rect region)
{
var previous = Driver.Clip;
Driver.Clip = Rect.Intersect (previous, ViewToScreen (region));
return previous;
}
///
/// Draws a frame in the current view, clipped by the boundary of this view
///
/// View-relative region for the frame to be drawn.
/// The padding to add around the outside of the drawn frame.
/// If set to it fill will the contents.
[ObsoleteAttribute ("This method is obsolete in v2. Use use LineCanvas or Frame instead.", false)]
public void DrawFrame (Rect region, int padding = 0, bool fill = false)
{
var scrRect = ViewToScreen (region);
var savedClip = ClipToBounds ();
Driver.DrawWindowFrame (scrRect, padding + 1, padding + 1, padding + 1, padding + 1, border: true, fill: fill);
Driver.Clip = savedClip;
}
///
/// Utility function to draw strings that contain a hotkey.
///
/// String to display, the hotkey specifier before a letter flags the next letter as the hotkey.
/// Hot color.
/// Normal color.
///
/// The hotkey is any character following the hotkey specifier, which is the underscore ('_') character by default.
/// The hotkey specifier can be changed via
///
public void DrawHotString (ustring text, Attribute hotColor, Attribute normalColor)
{
var hotkeySpec = HotKeySpecifier == (Rune)0xffff ? (Rune)'_' : HotKeySpecifier;
Application.Driver.SetAttribute (normalColor);
foreach (var rune in text) {
if (rune == hotkeySpec) {
Application.Driver.SetAttribute (hotColor);
continue;
}
Application.Driver.AddRune (rune);
Application.Driver.SetAttribute (normalColor);
}
}
///
/// Utility function to draw strings that contains a hotkey using a and the "focused" state.
///
/// String to display, the underscore before a letter flags the next letter as the hotkey.
/// If set to this uses the focused colors from the color scheme, otherwise the regular ones.
/// The color scheme to use.
public void DrawHotString (ustring text, bool focused, ColorScheme scheme)
{
if (focused)
DrawHotString (text, scheme.HotFocus, scheme.Focus);
else
DrawHotString (text, Enabled ? scheme.HotNormal : scheme.Disabled, Enabled ? scheme.Normal : scheme.Disabled);
}
///
/// This moves the cursor to the specified column and row in the view.
///
/// The move.
/// The column to move to, in view-relative coordinates.
/// the row to move to, in view-relative coordinates.
/// Whether to clip the result of the ViewToScreen method,
/// If , the and values are clamped to the screen (terminal) dimensions (0..TerminalDim-1).
public void Move (int col, int row, bool clipped = true)
{
if (Driver.Rows == 0) {
return;
}
ViewToScreen (col, row, out var rCol, out var rRow, clipped);
Driver.Move (rCol, rRow);
}
///
/// Positions the cursor in the right position based on the currently focused view in the chain.
///
/// Views that are focusable should override to ensure
/// the cursor is placed in a location that makes sense. Unix terminals do not have
/// a way of hiding the cursor, so it can be distracting to have the cursor left at
/// the last focused view. Views should make sure that they place the cursor
/// in a visually sensible place.
public virtual void PositionCursor ()
{
if (!CanBeVisible (this) || !Enabled) {
return;
}
// BUGBUG: v2 - This needs to support children of Frames too
if (focused == null && SuperView != null) {
SuperView.EnsureFocus ();
} else if (focused?.Visible == true && focused?.Enabled == true && focused?.Frame.Width > 0 && focused.Frame.Height > 0) {
focused.PositionCursor ();
} else if (focused?.Visible == true && focused?.Enabled == false) {
focused = null;
} else if (CanFocus && HasFocus && Visible && Frame.Width > 0 && Frame.Height > 0) {
Move (TextFormatter.HotKeyPos == -1 ? 0 : TextFormatter.CursorPosition, 0);
} else {
Move (frame.X, frame.Y);
}
}
// BUGBUG: v2 - Seems weird that this is in View and not Responder.
bool _hasFocus;
///
public override bool HasFocus => _hasFocus;
void SetHasFocus (bool value, View view, bool force = false)
{
if (_hasFocus != value || force) {
_hasFocus = value;
if (value) {
OnEnter (view);
} else {
OnLeave (view);
}
SetNeedsDisplay ();
}
// Remove focus down the chain of subviews if focus is removed
if (!value && focused != null) {
var f = focused;
f.OnLeave (view);
f.SetHasFocus (false, view);
focused = null;
}
}
///
/// Method invoked when a subview is being added to this view.
///
/// Event where is the subview being added.
public virtual void OnAdded (SuperViewChangedEventArgs e)
{
var view = e.Child;
view.IsAdded = true;
view.x ??= view.frame.X;
view.y ??= view.frame.Y;
view.width ??= view.frame.Width;
view.height ??= view.frame.Height;
view.Added?.Invoke (this, e);
}
///
/// Method invoked when a subview is being removed from this view.
///
/// Event args describing the subview being removed.
public virtual void OnRemoved (SuperViewChangedEventArgs e)
{
var view = e.Child;
view.IsAdded = false;
view.Removed?.Invoke (this, e);
}
///
public override bool OnEnter (View view)
{
var args = new FocusEventArgs (view);
Enter?.Invoke (this, args);
if (args.Handled)
return true;
if (base.OnEnter (view))
return true;
return false;
}
///
public override bool OnLeave (View view)
{
var args = new FocusEventArgs (view);
Leave?.Invoke (this, args);
if (args.Handled)
return true;
if (base.OnLeave (view))
return true;
return false;
}
///
/// Returns the currently focused view inside this view, or null if nothing is focused.
///
/// The focused.
public View Focused => focused;
///
/// Returns the most focused view in the chain of subviews (the leaf view that has the focus).
///
/// The most focused View.
public View MostFocused {
get {
if (Focused == null)
return null;
var most = Focused.MostFocused;
if (most != null)
return most;
return Focused;
}
}
ColorScheme colorScheme;
///
/// The color scheme for this view, if it is not defined, it returns the 's
/// color scheme.
///
public virtual ColorScheme ColorScheme {
get {
if (colorScheme == null) {
return SuperView?.ColorScheme;
}
return colorScheme;
}
set {
if (colorScheme != value) {
colorScheme = value;
SetNeedsDisplay ();
}
}
}
///
/// Displays the specified character in the specified column and row of the View.
///
/// Column (view-relative).
/// Row (view-relative).
/// Ch.
public void AddRune (int col, int row, Rune ch)
{
if (row < 0 || col < 0)
return;
if (row > frame.Height - 1 || col > frame.Width - 1)
return;
Move (col, row);
Driver.AddRune (ch);
}
///
/// Removes the and the setting on this view.
///
protected void ClearNeedsDisplay ()
{
_needsDisplay = Rect.Empty;
_childNeedsDisplay = false;
}
// TODO: Make this cancelable
///
///
///
///
public virtual bool OnDrawFrames (Rect bounds)
{
var prevClip = Driver.Clip;
if (SuperView != null) {
Driver.Clip = SuperView.ClipToBounds ();
}
Margin?.Redraw (Margin.Frame);
BorderFrame?.Redraw (BorderFrame.Frame);
Padding?.Redraw (Padding.Frame);
Driver.Clip = prevClip;
return true;
}
///
/// Redraws this view and its subviews; only redraws the views that have been flagged for a re-display.
///
/// The bounds (view-relative region) to redraw.
///
///
/// Always use (view-relative) when calling , NOT (superview-relative).
///
///
/// Views should set the color that they want to use on entry, as otherwise this will inherit
/// the last color that was set globally on the driver.
///
///
/// Overrides of must ensure they do not set Driver.Clip to a clip region
/// larger than the parameter, as this will cause the driver to clip the entire region.
///
///
public virtual void Redraw (Rect bounds)
{
if (!CanBeVisible (this)) {
return;
}
OnDrawFrames (Frame);
var prevClip = ClipToBounds ();
// TODO: Implement complete event
// OnDrawFramesComplete (Frame)
if (ColorScheme != null) {
//Driver.SetAttribute (HasFocus ? GetFocusColor () : GetNormalColor ());
Driver.SetAttribute (GetNormalColor ());
}
Clear (ViewToScreen (bounds));
// Invoke DrawContentEvent
OnDrawContent (bounds);
// Draw subviews
// TODO: Implement OnDrawSubviews (cancelable);
if (subviews != null) {
foreach (var view in subviews) {
if (view.Visible) { //!view._needsDisplay.IsEmpty || view._childNeedsDisplay || view.LayoutNeeded) {
if (true) { //view.Frame.IntersectsWith (bounds)) { // && (view.Frame.IntersectsWith (bounds) || bounds.X < 0 || bounds.Y < 0)) {
if (view.LayoutNeeded) {
view.LayoutSubviews ();
}
// Draw the subview
// Use the view's bounds (view-relative; Location will always be (0,0)
//if (view.Visible && view.Frame.Width > 0 && view.Frame.Height > 0) {
view.Redraw (view.Bounds);
//}
}
view.ClearNeedsDisplay ();
}
}
}
// Invoke DrawContentCompleteEvent
OnDrawContentComplete (bounds);
// BUGBUG: v2 - We should be able to use View.SetClip here and not have to resort to knowing Driver details.
Driver.Clip = prevClip;
ClearLayoutNeeded ();
ClearNeedsDisplay ();
}
///
/// Event invoked when the content area of the View is to be drawn.
///
///
///
/// Will be invoked before any subviews added with have been drawn.
///
///
/// Rect provides the view-relative rectangle describing the currently visible viewport into the .
///
///
public event EventHandler DrawContent;
///
/// Enables overrides to draw infinitely scrolled content and/or a background behind added controls.
///
/// The view-relative rectangle describing the currently visible viewport into the
///
/// This method will be called before any subviews added with have been drawn.
///
public virtual void OnDrawContent (Rect contentArea)
{
// TODO: Make DrawContent a cancelable event
// if (!DrawContent?.Invoke(this, new DrawEventArgs (viewport)) {
DrawContent?.Invoke (this, new DrawEventArgs (contentArea));
if (!ustring.IsNullOrEmpty (TextFormatter.Text)) {
if (TextFormatter != null) {
TextFormatter.NeedsFormat = true;
}
TextFormatter?.Draw (ViewToScreen (contentArea), HasFocus ? GetFocusColor () : GetNormalColor (),
HasFocus ? ColorScheme.HotFocus : GetHotNormalColor (),
new Rect (ViewToScreen (contentArea).Location, Bounds.Size), true);
SetSubViewNeedsDisplay ();
}
}
///
/// Event invoked when the content area of the View is completed drawing.
///
///
///
/// Will be invoked after any subviews removed with have been completed drawing.
///
///
/// Rect provides the view-relative rectangle describing the currently visible viewport into the .
///
///
public event EventHandler DrawContentComplete;
///
/// Enables overrides after completed drawing infinitely scrolled content and/or a background behind removed controls.
///
/// The view-relative rectangle describing the currently visible viewport into the
///
/// This method will be called after any subviews removed with have been completed drawing.
///
public virtual void OnDrawContentComplete (Rect viewport)
{
DrawContentComplete?.Invoke (this, new DrawEventArgs (viewport));
}
///
/// Causes the specified subview to have focus.
///
/// View.
void SetFocus (View view)
{
if (view == null) {
return;
}
//Console.WriteLine ($"Request to focus {view}");
if (!view.CanFocus || !view.Visible || !view.Enabled) {
return;
}
if (focused?._hasFocus == true && focused == view) {
return;
}
if ((focused?._hasFocus == true && focused?.SuperView == view) || view == this) {
if (!view._hasFocus) {
view._hasFocus = true;
}
return;
}
// Make sure that this view is a subview
View c;
for (c = view._superView; c != null; c = c._superView)
if (c == this)
break;
if (c == null)
throw new ArgumentException ("the specified view is not part of the hierarchy of this view");
if (focused != null)
focused.SetHasFocus (false, view);
var f = focused;
focused = view;
focused.SetHasFocus (true, f);
focused.EnsureFocus ();
// Send focus upwards
if (SuperView != null) {
SuperView.SetFocus (this);
} else {
SetFocus (this);
}
}
///
/// Causes the specified view and the entire parent hierarchy to have the focused order updated.
///
public void SetFocus ()
{
if (!CanBeVisible (this) || !Enabled) {
if (HasFocus) {
SetHasFocus (false, this);
}
return;
}
if (SuperView != null) {
SuperView.SetFocus (this);
} else {
SetFocus (this);
}
}
///
/// Invoked when a character key is pressed and occurs after the key up event.
///
public event EventHandler KeyPress;
///
public override bool ProcessKey (KeyEvent keyEvent)
{
if (!Enabled) {
return false;
}
var args = new KeyEventEventArgs (keyEvent);
KeyPress?.Invoke (this, args);
if (args.Handled)
return true;
if (Focused?.Enabled == true) {
Focused?.KeyPress?.Invoke (this, args);
if (args.Handled)
return true;
}
return Focused?.Enabled == true && Focused?.ProcessKey (keyEvent) == true;
}
///
/// Invokes any binding that is registered on this
/// and matches the
///
/// The key event passed.
protected bool? InvokeKeybindings (KeyEvent keyEvent)
{
bool? toReturn = null;
if (KeyBindings.ContainsKey (keyEvent.Key)) {
foreach (var command in KeyBindings [keyEvent.Key]) {
if (!CommandImplementations.ContainsKey (command)) {
throw new NotSupportedException ($"A KeyBinding was set up for the command {command} ({keyEvent.Key}) but that command is not supported by this View ({GetType ().Name})");
}
// each command has its own return value
var thisReturn = CommandImplementations [command] ();
// if we haven't got anything yet, the current command result should be used
if (toReturn == null) {
toReturn = thisReturn;
}
// if ever see a true then that's what we will return
if (thisReturn ?? false) {
toReturn = true;
}
}
}
return toReturn;
}
///
/// Adds a new key combination that will trigger the given
/// (if supported by the View - see )
///
/// If the key is already bound to a different it will be
/// rebound to this one
/// Commands are only ever applied to the current (i.e. this feature
/// cannot be used to switch focus to another view and perform multiple commands there)
///
///
/// The command(s) to run on the when is pressed.
/// When specifying multiple commands, all commands will be applied in sequence. The bound strike
/// will be consumed if any took effect.
public void AddKeyBinding (Key key, params Command [] command)
{
if (command.Length == 0) {
throw new ArgumentException ("At least one command must be specified", nameof (command));
}
if (KeyBindings.ContainsKey (key)) {
KeyBindings [key] = command;
} else {
KeyBindings.Add (key, command);
}
}
///
/// Replaces a key combination already bound to .
///
/// The key to be replaced.
/// The new key to be used.
protected void ReplaceKeyBinding (Key fromKey, Key toKey)
{
if (KeyBindings.ContainsKey (fromKey)) {
var value = KeyBindings [fromKey];
KeyBindings.Remove (fromKey);
KeyBindings [toKey] = value;
}
}
///
/// Checks if the key binding already exists.
///
/// The key to check.
/// If the key already exist, otherwise.
public bool ContainsKeyBinding (Key key)
{
return KeyBindings.ContainsKey (key);
}
///
/// Removes all bound keys from the View and resets the default bindings.
///
public void ClearKeybindings ()
{
KeyBindings.Clear ();
}
///
/// Clears the existing keybinding (if any) for the given .
///
///
public void ClearKeybinding (Key key)
{
KeyBindings.Remove (key);
}
///
/// Removes all key bindings that trigger the given command. Views can have multiple different
/// keys bound to the same command and this method will clear all of them.
///
///
public void ClearKeybinding (params Command [] command)
{
foreach (var kvp in KeyBindings.Where (kvp => kvp.Value.SequenceEqual (command)).ToArray ()) {
KeyBindings.Remove (kvp.Key);
}
}
///
/// States that the given supports a given
/// and what to perform to make that command happen
///
/// If the already has an implementation the
/// will replace the old one
///
/// The command.
/// The function.
protected void AddCommand (Command command, Func f)
{
// if there is already an implementation of this command
if (CommandImplementations.ContainsKey (command)) {
// replace that implementation
CommandImplementations [command] = f;
} else {
// else record how to perform the action (this should be the normal case)
CommandImplementations.Add (command, f);
}
}
///
/// Returns all commands that are supported by this .
///
///
public IEnumerable GetSupportedCommands ()
{
return CommandImplementations.Keys;
}
///
/// Gets the key used by a command.
///
/// The command to search.
/// The used by a
public Key GetKeyFromCommand (params Command [] command)
{
return KeyBindings.First (kb => kb.Value.SequenceEqual (command)).Key;
}
///
public override bool ProcessHotKey (KeyEvent keyEvent)
{
if (!Enabled) {
return false;
}
var args = new KeyEventEventArgs (keyEvent);
if (MostFocused?.Enabled == true) {
MostFocused?.KeyPress?.Invoke (this, args);
if (args.Handled)
return true;
}
if (MostFocused?.Enabled == true && MostFocused?.ProcessKey (keyEvent) == true)
return true;
if (subviews == null || subviews.Count == 0)
return false;
foreach (var view in subviews)
if (view.Enabled && view.ProcessHotKey (keyEvent))
return true;
return false;
}
///
public override bool ProcessColdKey (KeyEvent keyEvent)
{
if (!Enabled) {
return false;
}
var args = new KeyEventEventArgs (keyEvent);
KeyPress?.Invoke (this, args);
if (args.Handled)
return true;
if (MostFocused?.Enabled == true) {
MostFocused?.KeyPress?.Invoke (this, args);
if (args.Handled)
return true;
}
if (MostFocused?.Enabled == true && MostFocused?.ProcessKey (keyEvent) == true)
return true;
if (subviews == null || subviews.Count == 0)
return false;
foreach (var view in subviews)
if (view.Enabled && view.ProcessColdKey (keyEvent))
return true;
return false;
}
///
/// Invoked when a key is pressed.
///
public event EventHandler KeyDown;
///
public override bool OnKeyDown (KeyEvent keyEvent)
{
if (!Enabled) {
return false;
}
var args = new KeyEventEventArgs (keyEvent);
KeyDown?.Invoke (this, args);
if (args.Handled) {
return true;
}
if (Focused?.Enabled == true) {
Focused.KeyDown?.Invoke (this, args);
if (args.Handled) {
return true;
}
if (Focused?.OnKeyDown (keyEvent) == true) {
return true;
}
}
return false;
}
///
/// Invoked when a key is released.
///
public event EventHandler KeyUp;
///
public override bool OnKeyUp (KeyEvent keyEvent)
{
if (!Enabled) {
return false;
}
var args = new KeyEventEventArgs (keyEvent);
KeyUp?.Invoke (this, args);
if (args.Handled) {
return true;
}
if (Focused?.Enabled == true) {
Focused.KeyUp?.Invoke (this, args);
if (args.Handled) {
return true;
}
if (Focused?.OnKeyUp (keyEvent) == true) {
return true;
}
}
return false;
}
///
/// Finds the first view in the hierarchy that wants to get the focus if nothing is currently focused, otherwise, does nothing.
///
public void EnsureFocus ()
{
if (focused == null && subviews?.Count > 0) {
if (FocusDirection == Direction.Forward) {
FocusFirst ();
} else {
FocusLast ();
}
}
}
///
/// Focuses the first focusable subview if one exists.
///
public void FocusFirst ()
{
if (!CanBeVisible (this)) {
return;
}
if (tabIndexes == null) {
SuperView?.SetFocus (this);
return;
}
foreach (var view in tabIndexes) {
if (view.CanFocus && view.tabStop && view.Visible && view.Enabled) {
SetFocus (view);
return;
}
}
}
///
/// Focuses the last focusable subview if one exists.
///
public void FocusLast ()
{
if (!CanBeVisible (this)) {
return;
}
if (tabIndexes == null) {
SuperView?.SetFocus (this);
return;
}
for (var i = tabIndexes.Count; i > 0;) {
i--;
var v = tabIndexes [i];
if (v.CanFocus && v.tabStop && v.Visible && v.Enabled) {
SetFocus (v);
return;
}
}
}
///
/// Focuses the previous view.
///
/// if previous was focused, otherwise.
public bool FocusPrev ()
{
if (!CanBeVisible (this)) {
return false;
}
FocusDirection = Direction.Backward;
if (tabIndexes == null || tabIndexes.Count == 0)
return false;
if (focused == null) {
FocusLast ();
return focused != null;
}
var focusedIdx = -1;
for (var i = tabIndexes.Count; i > 0;) {
i--;
var w = tabIndexes [i];
if (w.HasFocus) {
if (w.FocusPrev ())
return true;
focusedIdx = i;
continue;
}
if (w.CanFocus && focusedIdx != -1 && w.tabStop && w.Visible && w.Enabled) {
focused.SetHasFocus (false, w);
if (w.CanFocus && w.tabStop && w.Visible && w.Enabled)
w.FocusLast ();
SetFocus (w);
return true;
}
}
if (focused != null) {
focused.SetHasFocus (false, this);
focused = null;
}
return false;
}
///
/// Focuses the next view.
///
/// if next was focused, otherwise.
public bool FocusNext ()
{
if (!CanBeVisible (this)) {
return false;
}
FocusDirection = Direction.Forward;
if (tabIndexes == null || tabIndexes.Count == 0)
return false;
if (focused == null) {
FocusFirst ();
return focused != null;
}
var focusedIdx = -1;
for (var i = 0; i < tabIndexes.Count; i++) {
var w = tabIndexes [i];
if (w.HasFocus) {
if (w.FocusNext ())
return true;
focusedIdx = i;
continue;
}
if (w.CanFocus && focusedIdx != -1 && w.tabStop && w.Visible && w.Enabled) {
focused.SetHasFocus (false, w);
if (w.CanFocus && w.tabStop && w.Visible && w.Enabled)
w.FocusFirst ();
SetFocus (w);
return true;
}
}
if (focused != null) {
focused.SetHasFocus (false, this);
focused = null;
}
return false;
}
View GetMostFocused (View view)
{
if (view == null) {
return null;
}
return view.focused != null ? GetMostFocused (view.focused) : view;
}
///
/// Sets the View's to the frame-relative coordinates if its container. The
/// container size and location are specified by and are relative to the
/// View's superview.
///
/// The supserview-relative rectangle describing View's container (nominally the
/// same as this.SuperView.Frame).
internal void SetRelativeLayout (Rect superviewFrame)
{
int newX, newW, newY, newH;
var autosize = Size.Empty;
if (AutoSize) {
// Note this is global to this function and used as such within the local functions defined
// below. In v2 AutoSize will be re-factored to not need to be dealt with in this function.
autosize = GetAutoSize ();
}
// Returns the new dimension (width or height) and location (x or y) for the View given
// the superview's Frame.X or Frame.Y
// the superview's width or height
// the current Pos (View.X or View.Y)
// the current Dim (View.Width or View.Height)
(int newLocation, int newDimension) GetNewLocationAndDimension (int superviewLocation, int superviewDimension, Pos pos, Dim dim, int autosizeDimension)
{
int newDimension, newLocation;
switch (pos) {
case Pos.PosCenter:
if (dim == null) {
newDimension = AutoSize ? autosizeDimension : superviewDimension;
} else {
newDimension = dim.Anchor (superviewDimension);
newDimension = AutoSize && autosizeDimension > newDimension ? autosizeDimension : newDimension;
}
newLocation = pos.Anchor (superviewDimension - newDimension);
break;
case Pos.PosCombine combine:
int left, right;
(left, newDimension) = GetNewLocationAndDimension (superviewLocation, superviewDimension, combine.left, dim, autosizeDimension);
(right, newDimension) = GetNewLocationAndDimension (superviewLocation, superviewDimension, combine.right, dim, autosizeDimension);
if (combine.add) {
newLocation = left + right;
} else {
newLocation = left - right;
}
newDimension = Math.Max (CalculateNewDimension (dim, newLocation, superviewDimension, autosizeDimension), 0);
break;
case Pos.PosAbsolute:
case Pos.PosAnchorEnd:
case Pos.PosFactor:
case Pos.PosFunc:
case Pos.PosView:
default:
newLocation = pos?.Anchor (superviewDimension) ?? 0;
newDimension = Math.Max (CalculateNewDimension (dim, newLocation, superviewDimension, autosizeDimension), 0);
break;
}
return (newLocation, newDimension);
}
// Recursively calculates the new dimension (width or height) of the given Dim given:
// the current location (x or y)
// the current dimension (width or height)
int CalculateNewDimension (Dim d, int location, int dimension, int autosize)
{
int newDimension;
switch (d) {
case null:
newDimension = AutoSize ? autosize : dimension;
break;
case Dim.DimCombine combine:
int leftNewDim = CalculateNewDimension (combine.left, location, dimension, autosize);
int rightNewDim = CalculateNewDimension (combine.right, location, dimension, autosize);
if (combine.add) {
newDimension = leftNewDim + rightNewDim;
} else {
newDimension = leftNewDim - rightNewDim;
}
newDimension = AutoSize && autosize > newDimension ? autosize : newDimension;
break;
case Dim.DimFactor factor when !factor.IsFromRemaining ():
newDimension = d.Anchor (dimension);
newDimension = AutoSize && autosize > newDimension ? autosize : newDimension;
break;
case Dim.DimFill:
default:
newDimension = Math.Max (d.Anchor (dimension - location), 0);
newDimension = AutoSize && autosize > newDimension ? autosize : newDimension;
break;
}
return newDimension;
}
// horizontal
(newX, newW) = GetNewLocationAndDimension (superviewFrame.X, superviewFrame.Width, x, width, autosize.Width);
// vertical
(newY, newH) = GetNewLocationAndDimension (superviewFrame.Y, superviewFrame.Height, y, height, autosize.Height);
var r = new Rect (newX, newY, newW, newH);
if (Frame != r) {
Frame = r;
// BUGBUG: Why is this AFTER setting Frame? Seems duplicative.
if (!SetMinWidthHeight ()) {
TextFormatter.Size = GetSizeNeededForTextAndHotKey ();
}
}
}
///
/// Fired after the View's method has completed.
///
///
/// Subscribe to this event to perform tasks when the has been resized or the layout has otherwise changed.
///
public event EventHandler LayoutStarted;
///
/// Raises the event. Called from before any subviews have been laid out.
///
internal virtual void OnLayoutStarted (LayoutEventArgs args)
{
LayoutStarted?.Invoke (this, args);
}
///
/// Fired after the View's method has completed.
///
///
/// Subscribe to this event to perform tasks when the has been resized or the layout has otherwise changed.
///
public event EventHandler LayoutComplete;
///
/// Event called only once when the is being initialized for the first time.
/// Allows configurations and assignments to be performed before the being shown.
/// This derived from to allow notify all the views that are being initialized.
///
public event EventHandler Initialized;
///
/// Raises the event. Called from before all sub-views have been laid out.
///
internal virtual void OnLayoutComplete (LayoutEventArgs args)
{
LayoutComplete?.Invoke (this, args);
}
internal void CollectPos (Pos pos, View from, ref HashSet nNodes, ref HashSet<(View, View)> nEdges)
{
switch (pos) {
case Pos.PosView pv:
// See #2461
//if (!from.InternalSubviews.Contains (pv.Target)) {
// throw new InvalidOperationException ($"View {pv.Target} is not a subview of {from}");
//}
if (pv.Target != this) {
nEdges.Add ((pv.Target, from));
}
foreach (var v in from.InternalSubviews) {
CollectAll (v, ref nNodes, ref nEdges);
}
return;
case Pos.PosCombine pc:
foreach (var v in from.InternalSubviews) {
CollectPos (pc.left, from, ref nNodes, ref nEdges);
CollectPos (pc.right, from, ref nNodes, ref nEdges);
}
break;
}
}
internal void CollectDim (Dim dim, View from, ref HashSet nNodes, ref HashSet<(View, View)> nEdges)
{
switch (dim) {
case Dim.DimView dv:
// See #2461
//if (!from.InternalSubviews.Contains (dv.Target)) {
// throw new InvalidOperationException ($"View {dv.Target} is not a subview of {from}");
//}
if (dv.Target != this) {
nEdges.Add ((dv.Target, from));
}
foreach (var v in from.InternalSubviews) {
CollectAll (v, ref nNodes, ref nEdges);
}
return;
case Dim.DimCombine dc:
foreach (var v in from.InternalSubviews) {
CollectDim (dc.left, from, ref nNodes, ref nEdges);
CollectDim (dc.right, from, ref nNodes, ref nEdges);
}
break;
}
}
internal void CollectAll (View from, ref HashSet nNodes, ref HashSet<(View, View)> nEdges)
{
foreach (var v in from.InternalSubviews) {
nNodes.Add (v);
if (v._layoutStyle != LayoutStyle.Computed) {
continue;
}
CollectPos (v.X, v, ref nNodes, ref nEdges);
CollectPos (v.Y, v, ref nNodes, ref nEdges);
CollectDim (v.Width, v, ref nNodes, ref nEdges);
CollectDim (v.Height, v, ref nNodes, ref nEdges);
}
}
// https://en.wikipedia.org/wiki/Topological_sorting
internal static List TopologicalSort (View superView, IEnumerable nodes, ICollection<(View From, View To)> edges)
{
var result = new List ();
// Set of all nodes with no incoming edges
var noEdgeNodes = new HashSet (nodes.Where (n => edges.All (e => !e.To.Equals (n))));
while (noEdgeNodes.Any ()) {
// remove a node n from S
var n = noEdgeNodes.First ();
noEdgeNodes.Remove (n);
// add n to tail of L
if (n != superView)
result.Add (n);
// for each node m with an edge e from n to m do
foreach (var e in edges.Where (e => e.From.Equals (n)).ToArray ()) {
var m = e.To;
// remove edge e from the graph
edges.Remove (e);
// if m has no other incoming edges then
if (edges.All (me => !me.To.Equals (m)) && m != superView) {
// insert m into S
noEdgeNodes.Add (m);
}
}
}
if (edges.Any ()) {
(var from, var to) = edges.First ();
if (from != superView?.GetTopSuperView (to, from)) {
if (!ReferenceEquals (from, to)) {
if (ReferenceEquals (from.SuperView, to)) {
throw new InvalidOperationException ($"ComputedLayout for \"{superView}\": \"{to}\" references a SubView (\"{from}\").");
} else {
throw new InvalidOperationException ($"ComputedLayout for \"{superView}\": \"{from}\" linked with \"{to}\" was not found. Did you forget to add it to {superView}?");
}
} else {
throw new InvalidOperationException ($"ComputedLayout for \"{superView}\": A recursive cycle was found in the relative Pos/Dim of the SubViews.");
}
}
}
// return L (a topologically sorted order)
return result;
} // TopologicalSort
///
/// Overriden by to do nothing, as the does not have frames.
///
internal virtual void LayoutFrames ()
{
if (Margin == null) return; // CreateFrames() has not been called yet
if (Margin.Frame.Size != Frame.Size) {
Margin.X = 0;
Margin.Y = 0;
Margin.Width = Frame.Size.Width;
Margin.Height = Frame.Size.Height;
Margin.SetNeedsLayout ();
Margin.LayoutSubviews ();
Margin.SetNeedsDisplay ();
}
var border = Margin.Thickness.GetInside (Margin.Frame);
if (border != BorderFrame.Frame) {
BorderFrame.X = border.Location.X;
BorderFrame.Y = border.Location.Y;
BorderFrame.Width = border.Size.Width;
BorderFrame.Height = border.Size.Height;
BorderFrame.SetNeedsLayout ();
BorderFrame.LayoutSubviews ();
BorderFrame.SetNeedsDisplay ();
}
var padding = BorderFrame.Thickness.GetInside (BorderFrame.Frame);
if (padding != Padding.Frame) {
Padding.X = padding.Location.X;
Padding.Y = padding.Location.Y;
Padding.Width = padding.Size.Width;
Padding.Height = padding.Size.Height;
Padding.SetNeedsLayout ();
Padding.LayoutSubviews ();
Padding.SetNeedsDisplay ();
}
}
///
/// Invoked when a view starts executing or when the dimensions of the view have changed, for example in
/// response to the container view or terminal resizing.
///
///
/// Calls (which raises the event) before it returns.
///
public virtual void LayoutSubviews ()
{
if (!LayoutNeeded) {
return;
}
LayoutFrames ();
var oldBounds = Bounds;
OnLayoutStarted (new LayoutEventArgs () { OldBounds = oldBounds });
TextFormatter.Size = GetSizeNeededForTextAndHotKey ();
// Sort out the dependencies of the X, Y, Width, Height properties
var nodes = new HashSet ();
var edges = new HashSet<(View, View)> ();
CollectAll (this, ref nodes, ref edges);
var ordered = View.TopologicalSort (SuperView, nodes, edges);
foreach (var v in ordered) {
LayoutSubview (v, new Rect (GetBoundsOffset (), Bounds.Size));
}
// If the 'to' is rooted to 'from' and the layoutstyle is Computed it's a special-case.
// Use LayoutSubview with the Frame of the 'from'
if (SuperView != null && GetTopSuperView () != null && LayoutNeeded
&& ordered.Count == 0 && edges.Count > 0 && LayoutStyle == LayoutStyle.Computed) {
(var from, var to) = edges.First ();
LayoutSubview (to, from.Frame);
}
LayoutNeeded = false;
OnLayoutComplete (new LayoutEventArgs () { OldBounds = oldBounds });
}
private void LayoutSubview (View v, Rect contentArea)
{
if (v.LayoutStyle == LayoutStyle.Computed) {
v.SetRelativeLayout (contentArea);
}
v.LayoutSubviews ();
v.LayoutNeeded = false;
}
ustring text;
///
/// The text displayed by the .
///
///
///
/// If provided, the text will be drawn before any subviews are drawn.
///
///
/// The text will be drawn starting at the view origin (0, 0) and will be formatted according
/// to the property. If the view's height is greater than 1, the
/// text will word-wrap to additional lines if it does not fit horizontally. If the view's height
/// is 1, the text will be clipped.
///
///
/// Set the to enable hotkey support. To disable hotkey support set to
/// (Rune)0xffff.
///
///
public virtual ustring Text {
get => text;
set {
text = value;
if (IsInitialized) {
SetHotKey ();
UpdateTextFormatterText ();
OnResizeNeeded ();
}
// BUGBUG: v2 - This is here as a HACK until we fix the unit tests to not check a view's dims until
// after it's been initialized. See #2450
UpdateTextFormatterText ();
#if DEBUG
if (text != null && string.IsNullOrEmpty (Id)) {
Id = text.ToString ();
}
#endif
}
}
///
/// Gets or sets a flag that determines whether the View will be automatically resized to fit the
/// within
///
/// The default is . Set to to turn on AutoSize. If then
/// and will be used if can fit;
/// if won't fit the view will be resized as needed.
///
///
/// In addition, if is the new values of and
/// must be of the same types of the existing one to avoid breaking the settings.
///
///
public virtual bool AutoSize {
get => autoSize;
set {
var v = ResizeView (value);
TextFormatter.AutoSize = v;
if (autoSize != v) {
autoSize = v;
TextFormatter.NeedsFormat = true;
UpdateTextFormatterText ();
OnResizeNeeded ();
}
}
}
///
/// Gets or sets a flag that determines whether will have trailing spaces preserved
/// or not when is enabled. If
/// any trailing spaces will be trimmed when either the property is changed or
/// when is set to .
/// The default is .
///
public virtual bool PreserveTrailingSpaces {
get => TextFormatter.PreserveTrailingSpaces;
set {
if (TextFormatter.PreserveTrailingSpaces != value) {
TextFormatter.PreserveTrailingSpaces = value;
TextFormatter.NeedsFormat = true;
}
}
}
///
/// Gets or sets how the View's is aligned horizontally when drawn. Changing this property will redisplay the .
///
/// The text alignment.
public virtual TextAlignment TextAlignment {
get => TextFormatter.Alignment;
set {
TextFormatter.Alignment = value;
UpdateTextFormatterText ();
OnResizeNeeded ();
}
}
///
/// Gets or sets how the View's is aligned vertically when drawn. Changing this property will redisplay the .
///
/// The text alignment.
public virtual VerticalTextAlignment VerticalTextAlignment {
get => TextFormatter.VerticalAlignment;
set {
TextFormatter.VerticalAlignment = value;
SetNeedsDisplay ();
}
}
///
/// Gets or sets the direction of the View's . Changing this property will redisplay the .
///
/// The text alignment.
public virtual TextDirection TextDirection {
get => TextFormatter.Direction;
set {
if (!IsInitialized) {
TextFormatter.Direction = value;
} else {
UpdateTextDirection (value);
}
}
}
private void UpdateTextDirection (TextDirection newDirection)
{
var directionChanged = TextFormatter.IsHorizontalDirection (TextFormatter.Direction)
!= TextFormatter.IsHorizontalDirection (newDirection);
TextFormatter.Direction = newDirection;
var isValidOldAutoSize = autoSize && IsValidAutoSize (out var _);
UpdateTextFormatterText ();
if ((!ForceValidatePosDim && directionChanged && AutoSize)
|| (ForceValidatePosDim && directionChanged && AutoSize && isValidOldAutoSize)) {
OnResizeNeeded ();
} else if (directionChanged && IsAdded) {
SetWidthHeight (Bounds.Size);
SetMinWidthHeight ();
} else {
SetMinWidthHeight ();
}
TextFormatter.Size = GetSizeNeededForTextAndHotKey ();
SetNeedsDisplay ();
}
///
/// Get or sets if the has been initialized (via
/// and ).
///
///
/// If first-run-only initialization is preferred, overrides to
/// can be implemented, in which case the
/// methods will only be called if
/// is . This allows proper inheritance hierarchies
/// to override base class layout code optimally by doing so only on first run,
/// instead of on every run.
///
public virtual bool IsInitialized { get; set; }
///
/// Gets information if the view was already added to the .
///
public bool IsAdded { get; private set; }
bool oldEnabled;
///
public override bool Enabled {
get => base.Enabled;
set {
if (base.Enabled != value) {
if (value) {
if (SuperView == null || SuperView?.Enabled == true) {
base.Enabled = value;
}
} else {
base.Enabled = value;
}
if (!value && HasFocus) {
SetHasFocus (false, this);
}
OnEnabledChanged ();
SetNeedsDisplay ();
if (subviews != null) {
foreach (var view in subviews) {
if (!value) {
view.oldEnabled = view.Enabled;
view.Enabled = false;
} else {
view.Enabled = view.oldEnabled;
view.addingView = false;
}
}
}
}
}
}
///
/// Gets or sets whether a view is cleared if the property is .
///
public bool ClearOnVisibleFalse { get; set; } = true;
/// >
public override bool Visible {
get => base.Visible;
set {
if (base.Visible != value) {
base.Visible = value;
if (!value) {
if (HasFocus) {
SetHasFocus (false, this);
}
if (ClearOnVisibleFalse) {
Clear ();
}
}
OnVisibleChanged ();
SetNeedsDisplay ();
}
}
}
// TODO: v2 Nuke teh Border property (rename BorderFrame to Border)
Border border;
///
public virtual Border Border {
get => border;
set {
if (border != value) {
border = value;
SetNeedsDisplay ();
if (border != null) {
Border_BorderChanged (border);
border.BorderChanged += Border_BorderChanged;
}
}
}
}
// TODO: v2 nuke This
///
///
public virtual bool IgnoreBorderPropertyOnRedraw { get; set; }
///
/// Pretty prints the View
///
///
public override string ToString ()
{
return $"{GetType ().Name}({Id})({Frame})";
}
void SetHotKey ()
{
if (TextFormatter == null) {
return; // throw new InvalidOperationException ("Can't set HotKey unless a TextFormatter has been created");
}
TextFormatter.FindHotKey (text, HotKeySpecifier, true, out _, out var hk);
if (hotKey != hk) {
HotKey = hk;
}
}
bool ResizeView (bool autoSize)
{
if (!autoSize) {
return false;
}
var aSize = true;
var nBoundsSize = GetAutoSize ();
if (nBoundsSize != Bounds.Size) {
if (ForceValidatePosDim) {
aSize = SetWidthHeight (nBoundsSize);
} else {
Height = nBoundsSize.Height;
Width = nBoundsSize.Width; // = new Rect (Bounds.X, Bounds.Y, nBoundsSize.Width, nBoundsSize.Height);
}
}
// BUGBUG: This call may be redundant
TextFormatter.Size = GetSizeNeededForTextAndHotKey ();
return aSize;
}
///
/// Resizes the View to fit the specified size.
///
///
///
bool SetWidthHeight (Size nBounds)
{
var aSize = false;
var canSizeW = TrySetWidth (nBounds.Width - GetHotKeySpecifierLength (), out var rW);
var canSizeH = TrySetHeight (nBounds.Height - GetHotKeySpecifierLength (false), out var rH);
if (canSizeW) {
aSize = true;
width = rW;
}
if (canSizeH) {
aSize = true;
height = rH;
}
if (aSize) {
Bounds = new Rect (Bounds.X, Bounds.Y, canSizeW ? rW : Bounds.Width, canSizeH ? rH : Bounds.Height);
}
return aSize;
}
///
/// Gets the dimensions required to fit using the text specified by the
/// property and accounting for any characters.
/// .
///
/// The required to fit the text.
public Size GetAutoSize ()
{
var rect = TextFormatter.CalcRect (Bounds.X, Bounds.Y, TextFormatter.Text, TextFormatter.Direction);
return new Size (rect.Size.Width - GetHotKeySpecifierLength (),
rect.Size.Height - GetHotKeySpecifierLength (false));
}
bool IsValidAutoSize (out Size autoSize)
{
var rect = TextFormatter.CalcRect (frame.X, frame.Y, TextFormatter.Text, TextDirection);
autoSize = new Size (rect.Size.Width - GetHotKeySpecifierLength (),
rect.Size.Height - GetHotKeySpecifierLength (false));
return !(ForceValidatePosDim && (!(Width is Dim.DimAbsolute) || !(Height is Dim.DimAbsolute))
|| frame.Size.Width != rect.Size.Width - GetHotKeySpecifierLength ()
|| frame.Size.Height != rect.Size.Height - GetHotKeySpecifierLength (false));
}
bool IsValidAutoSizeWidth (Dim width)
{
var rect = TextFormatter.CalcRect (frame.X, frame.Y, TextFormatter.Text, TextDirection);
var dimValue = width.Anchor (0);
return !(ForceValidatePosDim && (!(width is Dim.DimAbsolute)) || dimValue != rect.Size.Width
- GetHotKeySpecifierLength ());
}
bool IsValidAutoSizeHeight (Dim height)
{
var rect = TextFormatter.CalcRect (frame.X, frame.Y, TextFormatter.Text, TextDirection);
var dimValue = height.Anchor (0);
return !(ForceValidatePosDim && (!(height is Dim.DimAbsolute)) || dimValue != rect.Size.Height
- GetHotKeySpecifierLength (false));
}
///
/// Gets the width or height of the characters
/// in the property.
///
///
/// Only the first hotkey specifier found in is supported.
///
/// If (the default) the width required for the hotkey specifier is returned. Otherwise the height is returned.
/// The number of characters required for the . If the text direction specified
/// by does not match the parameter, 0 is returned.
public int GetHotKeySpecifierLength (bool isWidth = true)
{
if (isWidth) {
return TextFormatter.IsHorizontalDirection (TextDirection) &&
TextFormatter.Text?.Contains (HotKeySpecifier) == true
? Math.Max (Rune.ColumnWidth (HotKeySpecifier), 0) : 0;
} else {
return TextFormatter.IsVerticalDirection (TextDirection) &&
TextFormatter.Text?.Contains (HotKeySpecifier) == true
? Math.Max (Rune.ColumnWidth (HotKeySpecifier), 0) : 0;
}
}
///
/// Gets the dimensions required for ignoring a .
///
///
public Size GetSizeNeededForTextWithoutHotKey ()
{
return new Size (TextFormatter.Size.Width - GetHotKeySpecifierLength (),
TextFormatter.Size.Height - GetHotKeySpecifierLength (false));
}
///
/// Gets the dimensions required for accounting for a .
///
///
public Size GetSizeNeededForTextAndHotKey ()
{
if (ustring.IsNullOrEmpty (TextFormatter.Text)) {
if (!IsInitialized) return Size.Empty;
return Bounds.Size;
}
// BUGBUG: This IGNORES what Text is set to, using on only the current View size. This doesn't seem to make sense.
// BUGBUG: This uses Frame; in v2 it should be Bounds
return new Size (frame.Size.Width + GetHotKeySpecifierLength (),
frame.Size.Height + GetHotKeySpecifierLength (false));
}
///
public override bool OnMouseEnter (MouseEvent mouseEvent)
{
if (!Enabled) {
return true;
}
if (!CanBeVisible (this)) {
return false;
}
var args = new MouseEventEventArgs (mouseEvent);
MouseEnter?.Invoke (this, args);
return args.Handled || base.OnMouseEnter (mouseEvent);
}
///
public override bool OnMouseLeave (MouseEvent mouseEvent)
{
if (!Enabled) {
return true;
}
if (!CanBeVisible (this)) {
return false;
}
var args = new MouseEventEventArgs (mouseEvent);
MouseLeave?.Invoke (this, args);
return args.Handled || base.OnMouseLeave (mouseEvent);
}
///
/// Method invoked when a mouse event is generated
///
///
/// , if the event was handled, otherwise.
public virtual bool OnMouseEvent (MouseEvent mouseEvent)
{
if (!Enabled) {
return true;
}
if (!CanBeVisible (this)) {
return false;
}
var args = new MouseEventEventArgs (mouseEvent);
if (OnMouseClick (args))
return true;
if (MouseEvent (mouseEvent))
return true;
if (mouseEvent.Flags == MouseFlags.Button1Clicked) {
if (CanFocus && !HasFocus && SuperView != null) {
SuperView.SetFocus (this);
SetNeedsDisplay ();
}
return true;
}
return false;
}
///
/// Invokes the MouseClick event.
///
protected bool OnMouseClick (MouseEventEventArgs args)
{
if (!Enabled) {
return true;
}
MouseClick?.Invoke (this, args);
return args.Handled;
}
///
public override void OnCanFocusChanged () => CanFocusChanged?.Invoke (this, EventArgs.Empty);
///
public override void OnEnabledChanged () => EnabledChanged?.Invoke (this, EventArgs.Empty);
///
public override void OnVisibleChanged () => VisibleChanged?.Invoke (this, EventArgs.Empty);
///
protected override void Dispose (bool disposing)
{
Margin?.Dispose ();
Margin = null;
BorderFrame?.Dispose ();
Border = null;
Padding?.Dispose ();
Padding = null;
for (var i = InternalSubviews.Count - 1; i >= 0; i--) {
var subview = InternalSubviews [i];
Remove (subview);
subview.Dispose ();
}
base.Dispose (disposing);
}
///
/// Signals the View that initialization is starting. See .
///
///
///
/// Views can opt-in to more sophisticated initialization
/// by implementing overrides to and
/// which will be called
/// when the view is added to a .
///
///
/// If first-run-only initialization is preferred, overrides to
/// can be implemented too, in which case the
/// methods will only be called if
/// is . This allows proper inheritance hierarchies
/// to override base class layout code optimally by doing so only on first run,
/// instead of on every run.
///
///
public virtual void BeginInit ()
{
if (!IsInitialized) {
oldCanFocus = CanFocus;
oldTabIndex = tabIndex;
UpdateTextDirection (TextDirection);
UpdateTextFormatterText ();
SetHotKey ();
// TODO: Figure out why ScrollView and other tests fail if this call is put here
// instead of the constructor.
OnResizeNeeded ();
//InitializeFrames ();
} else {
//throw new InvalidOperationException ("The view is already initialized.");
}
if (subviews?.Count > 0) {
foreach (var view in subviews) {
if (!view.IsInitialized) {
view.BeginInit ();
}
}
}
}
///
/// Signals the View that initialization is ending. See .
///
public void EndInit ()
{
IsInitialized = true;
if (subviews != null) {
foreach (var view in subviews) {
if (!view.IsInitialized) {
view.EndInit ();
}
}
}
Initialized?.Invoke (this, EventArgs.Empty);
}
bool CanBeVisible (View view)
{
if (!view.Visible) {
return false;
}
for (var c = view.SuperView; c != null; c = c.SuperView) {
if (!c.Visible) {
return false;
}
}
return true;
}
///
/// Determines if the View's can be set to a new value.
///
///
/// Contains the width that would result if were set to "/>
/// if the View's can be changed to the specified value. False otherwise.
internal bool TrySetWidth (int desiredWidth, out int resultWidth)
{
var w = desiredWidth;
bool canSetWidth;
switch (Width) {
case Dim.DimCombine _:
case Dim.DimView _:
case Dim.DimFill _:
// It's a Dim.DimCombine and so can't be assigned. Let it have it's Width anchored.
w = Width.Anchor (w);
canSetWidth = !ForceValidatePosDim;
break;
case Dim.DimFactor factor:
// Tries to get the SuperView Width otherwise the view Width.
var sw = SuperView != null ? SuperView.Frame.Width : w;
if (factor.IsFromRemaining ()) {
sw -= Frame.X;
}
w = Width.Anchor (sw);
canSetWidth = !ForceValidatePosDim;
break;
default:
canSetWidth = true;
break;
}
resultWidth = w;
return canSetWidth;
}
///
/// Determines if the View's can be set to a new value.
///
///
/// Contains the width that would result if were set to "/>
/// if the View's can be changed to the specified value. False otherwise.
internal bool TrySetHeight (int desiredHeight, out int resultHeight)
{
var h = desiredHeight;
bool canSetHeight;
switch (Height) {
case Dim.DimCombine _:
case Dim.DimView _:
case Dim.DimFill _:
// It's a Dim.DimCombine and so can't be assigned. Let it have it's height anchored.
h = Height.Anchor (h);
canSetHeight = !ForceValidatePosDim;
break;
case Dim.DimFactor factor:
// Tries to get the SuperView height otherwise the view height.
var sh = SuperView != null ? SuperView.Frame.Height : h;
if (factor.IsFromRemaining ()) {
sh -= Frame.Y;
}
h = Height.Anchor (sh);
canSetHeight = !ForceValidatePosDim;
break;
default:
canSetHeight = true;
break;
}
resultHeight = h;
return canSetHeight;
}
///
/// Determines the current based on the value.
///
/// if is
/// or if is .
/// If it's overridden can return other values.
public virtual Attribute GetNormalColor ()
{
return Enabled ? ColorScheme.Normal : ColorScheme.Disabled;
}
///
/// Determines the current based on the value.
///
/// if is
/// or if is .
/// If it's overridden can return other values.
public virtual Attribute GetFocusColor ()
{
return Enabled ? ColorScheme.Focus : ColorScheme.Disabled;
}
///
/// Determines the current based on the value.
///
/// if is
/// or if is .
/// If it's overridden can return other values.
public virtual Attribute GetHotNormalColor ()
{
return Enabled ? ColorScheme.HotNormal : ColorScheme.Disabled;
}
///
/// Get the top superview of a given .
///
/// The superview view.
public View GetTopSuperView (View view = null, View superview = null)
{
View top = superview ?? Application.Top;
for (var v = view?.SuperView ?? (this?.SuperView); v != null; v = v.SuperView) {
top = v;
if (top == superview) {
break;
}
}
return top;
}
///
/// Finds which view that belong to the superview at the provided location.
///
/// The superview where to look for.
/// The column location in the superview.
/// The row location in the superview.
/// The found view screen relative column location.
/// The found view screen relative row location.
///
/// The view that was found at the and coordinates.
/// if no view was found.
///
public static View FindDeepestView (View start, int x, int y, out int resx, out int resy)
{
var startFrame = start.Frame;
if (!startFrame.Contains (x, y)) {
resx = 0;
resy = 0;
return null;
}
if (start.InternalSubviews != null) {
int count = start.InternalSubviews.Count;
if (count > 0) {
var rx = x - (startFrame.X + start.GetBoundsOffset ().X);
var ry = y - (startFrame.Y + start.GetBoundsOffset ().Y);
for (int i = count - 1; i >= 0; i--) {
View v = start.InternalSubviews [i];
if (v.Visible && v.Frame.Contains (rx, ry)) {
var deep = FindDeepestView (v, rx, ry, out resx, out resy);
if (deep == null)
return v;
return deep;
}
}
}
}
resx = x - startFrame.X;
resy = y - startFrame.Y;
return start;
}
}
}