using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using NStack;
namespace Terminal.Gui {
///
/// Implement to provide custom rendering for a .
///
public interface IListDataSource {
///
/// Returns the number of elements to display
///
int Count { get; }
///
/// Returns the maximum length of elements to display
///
int Length { get; }
///
/// This method is invoked to render a specified item, the method should cover the entire provided width.
///
/// The render.
/// The list view to render.
/// The console driver to render.
/// Describes whether the item being rendered is currently selected by the user.
/// The index of the item to render, zero for the first item and so on.
/// The column where the rendering will start
/// The line where the rendering will be done.
/// The width that must be filled out.
/// The index of the string to be displayed.
///
/// The default color will be set before this method is invoked, and will be based on whether the item is selected or not.
///
void Render (ListView container, ConsoleDriver driver, bool selected, int item, int col, int line, int width, int start = 0);
///
/// Should return whether the specified item is currently marked.
///
/// , if marked, otherwise.
/// Item index.
bool IsMarked (int item);
///
/// Flags the item as marked.
///
/// Item index.
/// If set to value.
void SetMark (int item, bool value);
///
/// Return the source as IList.
///
///
IList ToList ();
}
///
/// Implement to provide custom rendering for a that
/// supports searching for items.
///
public interface IListDataSourceSearchable : IListDataSource {
///
/// Finds the first item that starts with the specified search string. Used by the default implementation
/// to support typing the first characters of an item to find it and move the selection to i.
///
/// Text to search for.
/// The index of the first item that starts with .
/// Returns if was not found.
int StartsWith (string search);
}
///
/// ListView renders a scrollable list of data where each item can be activated to perform an action.
///
///
///
/// The displays lists of data and allows the user to scroll through the data.
/// Items in the can be activated firing an event (with the ENTER key or a mouse double-click).
/// If the property is true, elements of the list can be marked by the user.
///
///
/// By default uses to render the items of any
/// object (e.g. arrays, ,
/// and other collections). Alternatively, an object that implements
/// or can be provided giving full control of what is rendered.
///
///
/// can display any object that implements the interface.
/// values are converted into values before rendering, and other values are
/// converted into by calling and then converting to .
///
///
/// To change the contents of the ListView, set the property (when
/// providing custom rendering via ) or call
/// an is being used.
///
///
/// When is set to true the rendering will prefix the rendered items with
/// [x] or [ ] and bind the SPACE key to toggle the selection. To implement a different
/// marking style set to false and implement custom rendering.
///
///
/// By default or if is set to an object that implements
/// , searching the ListView with the keyboard is supported. Users type the
/// first characters of an item, and the first item that starts with what the user types will be selected.
///
///
public class ListView : View {
int top, left;
int selected;
IListDataSource source;
///
/// Gets or sets the backing this , enabling custom rendering.
///
/// The source.
///
/// Use to set a new source.
///
public IListDataSource Source {
get => source;
set {
source = value;
navigator = null;
top = 0;
selected = 0;
lastSelectedItem = -1;
SetNeedsDisplay ();
}
}
///
/// Sets the source of the to an .
///
/// An object implementing the IList interface.
///
/// Use the property to set a new source and use custome rendering.
///
public void SetSource (IList source)
{
if (source == null && (Source == null || !(Source is ListWrapper)))
Source = null;
else {
Source = MakeWrapper (source);
}
}
///
/// Sets the source to an value asynchronously.
///
/// An item implementing the IList interface.
///
/// Use the property to set a new source and use custom rendering.
///
public Task SetSourceAsync (IList source)
{
return Task.Factory.StartNew (() => {
if (source == null && (Source == null || !(Source is ListWrapper)))
Source = null;
else
Source = MakeWrapper (source);
return source;
}, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
bool allowsMarking;
///
/// Gets or sets whether this allows items to be marked.
///
/// Set to to allow marking elements of the list.
///
/// If set to , will render items marked items with "[x]", and unmarked items with "[ ]"
/// spaces. SPACE key will toggle marking. The default is .
///
public bool AllowsMarking {
get => allowsMarking;
set {
allowsMarking = value;
if (allowsMarking) {
AddKeyBinding (Key.Space, Command.ToggleChecked);
} else {
ClearKeybinding (Key.Space);
}
SetNeedsDisplay ();
}
}
///
/// If set to more than one item can be selected. If selecting
/// an item will cause all others to be un-selected. The default is .
///
public bool AllowsMultipleSelection {
get => allowsMultipleSelection;
set {
allowsMultipleSelection = value;
if (Source != null && !allowsMultipleSelection) {
// Clear all selections except selected
for (int i = 0; i < Source.Count; i++) {
if (Source.IsMarked (i) && i != selected) {
Source.SetMark (i, false);
}
}
}
SetNeedsDisplay ();
}
}
///
/// Gets or sets the item that is displayed at the top of the .
///
/// The top item.
public int TopItem {
get => top;
set {
if (source == null)
return;
if (value < 0 || (source.Count > 0 && value >= source.Count))
throw new ArgumentException ("value");
top = value;
SetNeedsDisplay ();
}
}
///
/// Gets or sets the leftmost column that is currently visible (when scrolling horizontally).
///
/// The left position.
public int LeftItem {
get => left;
set {
if (source == null)
return;
if (value < 0 || (Maxlength > 0 && value >= Maxlength))
throw new ArgumentException ("value");
left = value;
SetNeedsDisplay ();
}
}
///
/// Gets the widest item in the list.
///
public int Maxlength => (source?.Length) ?? 0;
///
/// Gets or sets the index of the currently selected item.
///
/// The selected item.
public int SelectedItem {
get => selected;
set {
if (source == null || source.Count == 0) {
return;
}
if (value < 0 || value >= source.Count) {
throw new ArgumentException ("value");
}
selected = value;
OnSelectedChanged ();
}
}
static IListDataSource MakeWrapper (IList source)
{
return new ListWrapper (source);
}
///
/// Initializes a new instance of that will display the
/// contents of the object implementing the interface,
/// with relative positioning.
///
/// An data source, if the elements are strings or ustrings,
/// the string is rendered, otherwise the ToString() method is invoked on the result.
public ListView (IList source) : this (MakeWrapper (source))
{
}
///
/// Initializes a new instance of that will display the provided data source, using relative positioning.
///
/// object that provides a mechanism to render the data.
/// The number of elements on the collection should not change, if you must change, set
/// the "Source" property to reset the internal settings of the ListView.
public ListView (IListDataSource source) : base ()
{
this.source = source;
Initialize ();
}
///
/// Initializes a new instance of . Set the property to display something.
///
public ListView () : base ()
{
Initialize ();
}
///
/// Initializes a new instance of that will display the contents of the object implementing the interface with an absolute position.
///
/// Frame for the listview.
/// An IList data source, if the elements of the IList are strings or ustrings,
/// the string is rendered, otherwise the ToString() method is invoked on the result.
public ListView (Rect rect, IList source) : this (rect, MakeWrapper (source))
{
Initialize ();
}
///
/// Initializes a new instance of with the provided data source and an absolute position
///
/// Frame for the listview.
/// IListDataSource object that provides a mechanism to render the data.
/// The number of elements on the collection should not change, if you must change,
/// set the "Source" property to reset the internal settings of the ListView.
public ListView (Rect rect, IListDataSource source) : base (rect)
{
this.source = source;
Initialize ();
}
void Initialize ()
{
Source = source;
CanFocus = true;
// Things this view knows how to do
AddCommand (Command.LineUp, () => MoveUp ());
AddCommand (Command.LineDown, () => MoveDown ());
AddCommand (Command.ScrollUp, () => ScrollUp (1));
AddCommand (Command.ScrollDown, () => ScrollDown (1));
AddCommand (Command.PageUp, () => MovePageUp ());
AddCommand (Command.PageDown, () => MovePageDown ());
AddCommand (Command.TopHome, () => MoveHome ());
AddCommand (Command.BottomEnd, () => MoveEnd ());
AddCommand (Command.OpenSelectedItem, () => OnOpenSelectedItem ());
AddCommand (Command.ToggleChecked, () => MarkUnmarkRow ());
// Default keybindings for all ListViews
AddKeyBinding (Key.CursorUp, Command.LineUp);
AddKeyBinding (Key.P | Key.CtrlMask, Command.LineUp);
AddKeyBinding (Key.CursorDown, Command.LineDown);
AddKeyBinding (Key.N | Key.CtrlMask, Command.LineDown);
AddKeyBinding (Key.PageUp, Command.PageUp);
AddKeyBinding (Key.PageDown, Command.PageDown);
AddKeyBinding (Key.V | Key.CtrlMask, Command.PageDown);
AddKeyBinding (Key.Home, Command.TopHome);
AddKeyBinding (Key.End, Command.BottomEnd);
AddKeyBinding (Key.Enter, Command.OpenSelectedItem);
}
///
public override void Redraw (Rect bounds)
{
var current = ColorScheme.Focus;
Driver.SetAttribute (current);
Move (0, 0);
var f = Frame;
var item = top;
bool focused = HasFocus;
int col = allowsMarking ? 2 : 0;
int start = left;
for (int row = 0; row < f.Height; row++, item++) {
bool isSelected = item == selected;
var newcolor = focused ? (isSelected ? ColorScheme.Focus : GetNormalColor ())
: (isSelected ? ColorScheme.HotNormal : GetNormalColor ());
if (newcolor != current) {
Driver.SetAttribute (newcolor);
current = newcolor;
}
Move (0, row);
if (source == null || item >= source.Count) {
for (int c = 0; c < f.Width; c++)
Driver.AddRune (' ');
} else {
var rowEventArgs = new ListViewRowEventArgs (item);
OnRowRender (rowEventArgs);
if (rowEventArgs.RowAttribute != null && current != rowEventArgs.RowAttribute) {
current = (Attribute)rowEventArgs.RowAttribute;
Driver.SetAttribute (current);
}
if (allowsMarking) {
Driver.AddRune (source.IsMarked (item) ? (AllowsMultipleSelection ? Driver.Checked : Driver.Selected) :
(AllowsMultipleSelection ? Driver.UnChecked : Driver.UnSelected));
Driver.AddRune (' ');
}
Source.Render (this, Driver, isSelected, item, col, row, f.Width - col, start);
}
}
}
///
/// This event is raised when the selected item in the has changed.
///
public event Action SelectedItemChanged;
///
/// This event is raised when the user Double Clicks on an item or presses ENTER to open the selected item.
///
public event Action OpenSelectedItem;
///
/// This event is invoked when this is being drawn before rendering.
///
public event Action RowRender;
private SearchCollectionNavigator navigator;
///
public override bool ProcessKey (KeyEvent kb)
{
if (source == null) {
return base.ProcessKey (kb);
}
var result = InvokeKeybindings (kb);
if (result != null) {
return (bool)result;
}
// Enable user to find & select an item by typing text
if (SearchCollectionNavigator.IsCompatibleKey(kb)) {
if (navigator == null) {
navigator = new SearchCollectionNavigator (source.ToList ().Cast