Browse Source

Merge pull request #624 from fergusonr/combobox_fixes

ComboBox supports Dim.Fill() Dim.Percent()
Charlie Kindel 5 years ago
parent
commit
41442216c6

+ 22 - 21
Example/demo.cs

@@ -421,26 +421,27 @@ static class Demo {
 		MessageBox.Query (60, 10, "Selected Animals", result == "" ? "No animals selected" : result, "Ok");
 	}
 
-	//static void ComboBoxDemo ()
-	//{
-	//	IList<string> items = new List<string> ();
-	//	foreach (var dir in new [] { "/etc", @"\windows\System32" }) {
-	//		if (Directory.Exists (dir)) {
-	//			items = Directory.GetFiles (dir)
-	//			.Select (Path.GetFileName)
-	//			.Where (x => char.IsLetterOrDigit (x [0]))
-	//			.Distinct ()
-	//			.OrderBy (x => x).ToList ();
-	//		}
-	//	}
-	//	var list = new ComboBox (0, 0, 36, 7, items);
-	//	list.Changed += (object sender, ustring text) => { Application.RequestStop (); };
-
-	//	var d = new Dialog ("Select source file", 40, 12) { list };
-	//	Application.Run (d);
-
-	//	MessageBox.Query (60, 10, "Selected file", list.Text.ToString() == "" ? "Nothing selected" : list.Text.ToString(), "Ok");
-	//}
+	static void ComboBoxDemo ()
+	{
+		IList<string> items = new List<string> ();
+		foreach (var dir in new [] { "/etc", @"\windows\System32" }) {
+			if (Directory.Exists (dir)) {
+				items = Directory.GetFiles (dir)
+				.Select (Path.GetFileName)
+				.Where (x => char.IsLetterOrDigit (x [0]))
+				.Distinct ()
+				.OrderBy (x => x).ToList ();
+			}
+		}
+		var list = new ComboBox () { X = 0, Y = 0, Width = 36, Height = 7 };
+		list.SetSource(items.ToList());
+		list.SelectedItemChanged += (object sender, ustring text) => { Application.RequestStop (); };
+
+		var d = new Dialog ("Select source file", 40, 12) { list };
+		Application.Run (d);
+
+		MessageBox.Query (60, 10, "Selected file", list.Text.ToString() == "" ? "Nothing selected" : list.Text.ToString(), "Ok");
+	}
 	#endregion
 
 
@@ -571,7 +572,7 @@ static class Demo {
 			new MenuBarItem ("_List Demos", new MenuItem [] {
 				new MenuItem ("Select _Multiple Items", "", () => ListSelectionDemo (true)),
 				new MenuItem ("Select _Single Item", "", () => ListSelectionDemo (false)),
-//				new MenuItem ("Search Single Item", "", ComboBoxDemo)
+				new MenuItem ("Search Single Item", "", ComboBoxDemo)
 			}),
 			new MenuBarItem ("A_ssorted", new MenuItem [] {
 				new MenuItem ("_Show text alignments", "", () => ShowTextAlignments ()),

+ 0 - 6
Terminal.Gui/Terminal.Gui.csproj

@@ -183,12 +183,6 @@
     <PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.0" PrivateAssets="true" />
     <PackageReference Include="NStack.Core" Version="0.14.0" />
   </ItemGroup>
-  <ItemGroup Condition="'$(Configuration)'!='Debug'">
-    <PackageReference Include="SauceControl.InheritDoc" Version="1.0.0" PrivateAssets="all" />
-  </ItemGroup>
-  <ItemGroup>
-    <Compile Remove="Views\ComboBox.cs" />
-  </ItemGroup>
   <!--<ItemGroup>
     <Reference Include="NStack">
       <HintPath>..\..\..\Users\miguel\.nuget\packages\nstack.core\0.14.0\lib\netstandard2.0\NStack.dll</HintPath>

+ 144 - 80
Terminal.Gui/Views/ComboBox.cs

@@ -6,8 +6,10 @@
 //
 
 using System;
-using System.Linq;
+using System.Collections;
 using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
 using NStack;
 
 namespace Terminal.Gui {
@@ -15,6 +17,40 @@ namespace Terminal.Gui {
 	/// ComboBox control
 	/// </summary>
 	public class ComboBox : View {
+
+
+		IListDataSource source;
+		/// <summary>
+		/// Gets or sets the <see cref="IListDataSource"/> backing this <see cref="ComboBox"/>, enabling custom rendering.
+		/// </summary>
+		/// <value>The source.</value>
+		/// <remarks>
+		///  Use <see cref="SetSource"/> to set a new <see cref="IList"/> source.
+		/// </remarks>
+		public IListDataSource Source {
+			get => source;
+			set {
+				source = value;
+				SetNeedsDisplay ();
+			}
+		}
+
+		/// <summary>
+		/// Sets the source of the <see cref="ComboBox"/> to an <see cref="IList"/>.
+		/// </summary>
+		/// <value>An object implementing the IList interface.</value>
+		/// <remarks>
+		///  Use the <see cref="Source"/> property to set a new <see cref="IListDataSource"/> source and use custome rendering.
+		/// </remarks>
+		public void SetSource (IList source)
+		{
+			if (source == null)
+				Source = null;
+			else {
+				Source = MakeWrapper (source);
+			}
+		}
+
 		/// <summary>
 		///   Changed event, raised when the selection has been confirmed.
 		/// </summary>
@@ -22,15 +58,14 @@ namespace Terminal.Gui {
 		///   Client code can hook up to this event, it is
 		///   raised when the selection has been confirmed.
 		/// </remarks>
-		public Action<ustring> SelectedItemChanged;
+		public event EventHandler<ustring> SelectedItemChanged;
 
-		IList<string> listsource;
-		IList<string> searchset;
+		IList searchset;
 		ustring text = "";
 		TextField search;
 		ListView listview;
-		int x;
-		int y;
+		int x = 0;
+		int y = 0;
 		int height;
 		int width;
 		bool autoHide = true;
@@ -40,48 +75,57 @@ namespace Terminal.Gui {
 		/// </summary>
 		public ComboBox () : base()
 		{
-			search = new TextField ("") { LayoutStyle = LayoutStyle.Computed };
-			listview = new ListView () { LayoutStyle = LayoutStyle.Computed, CanFocus = true /* why? */ };
+			ColorScheme = Colors.Base;
+
+			search = new TextField ("");
+			listview = new ListView () { LayoutStyle = LayoutStyle.Computed, CanFocus = true };
 
 			Initialize ();
 		}
 
-		/// <summary>
-		/// Public constructor
-		/// </summary>
-		/// <param name="x">The x coordinate</param>
-		/// <param name="y">The y coordinate</param>
-		/// <param name="w">The width</param>
-		/// <param name="h">The height</param>
-		/// <param name="source">Auto completion source</param>
-		public ComboBox (int x, int y, int w, int h, IList<string> source)
-		{
-			SetSource (source);
-			this.x = x;
-			this.y = y;
-			height = h;
-			width = w;
+		///// <summary>
+		///// Public constructor
+		///// </summary>
+		///// <param name="rect"></param>
+		///// <param name="source"></param>
+		//public ComboBox (Rect rect, IList source) : base (rect)
+		//{
+		//	SetSource (source);
+		//	this.x = rect.X;
+		//	this.y = rect.Y;
+		//	this.height = rect.Height;
+		//	this.width = rect.Width;
 
-			search = new TextField (x, y, w, "");
+		//	search = new TextField ("") { X = rect.X, Y = rect.Y, Width = width };
 
-			listview = new ListView (new Rect (x, y + 1, w, 0), listsource.ToList ()) {
-				LayoutStyle = LayoutStyle.Computed,
-			};
+		//	listview = new ListView (new Rect (rect.X, rect.Y + 1, width, 0), source) { LayoutStyle = LayoutStyle.Computed};
 
-			Initialize ();
+		//	Initialize ();
+		//}
+
+		static IListDataSource MakeWrapper (IList source)
+		{
+			return new ListWrapper (source);
 		}
 
 		private void Initialize()
 		{
-			search.Changed += Search_Changed;
+			search.TextChanged += Search_Changed;
+
+			// On resize
+			LayoutComplete += (LayoutEventArgs a) => {
+
+				search.Width = Bounds.Width;
+				listview.Width = autoHide ? Bounds.Width - 1 : Bounds.Width;
+			};
+
+			listview.SelectedItemChanged += (ListViewItemEventArgs e) => {
 
-			listview.SelectedChanged += (object sender, ListViewItemEventArgs e) => {
 				if(searchset.Count > 0)
-					SetValue (searchset [listview.SelectedItem]);
+					SetValue ((string)searchset [listview.SelectedItem]);
 			};
 
-			// TODO: LayoutComplete event breaks cursor up/down. Revert to Application.Loaded 
-			Application.Loaded += (sender, a) => {
+			Application.Loaded += (Application.ResizedEventArgs a) => {
 				// Determine if this view is hosted inside a dialog
 				for (View view = this.SuperView; view != null; view = view.SuperView) {
 					if (view is Dialog) {
@@ -90,7 +134,7 @@ namespace Terminal.Gui {
 					}
 				}
 
-				searchset = autoHide ? new List<string> () : listsource;
+				ResetSearchSet ();
 
 				// Needs to be re-applied for LayoutStyle.Computed
 				// If Dim or Pos are null, these are the from the parametrized constructor
@@ -102,22 +146,29 @@ namespace Terminal.Gui {
 				else
 					listview.Y = Pos.Bottom (search);
 
-				if (Width == null)
+				if (Width == null) {
 					listview.Width = CalculateWidth ();
-				else {
-					width = GetDimAsInt (Width);
+					search.Width = width;
+				} else {
+					width = GetDimAsInt (Width, a, vertical: false);
+					search.Width = width;
 					listview.Width = CalculateWidth ();
 				}
 
-				if (Height == null)
-					listview.Height = CalculatetHeight ();
-				else {
-					height = GetDimAsInt (Height);
+				if (Height == null) {
+					var h = CalculatetHeight ();
+					listview.Height = h;
+					this.Height = h + 1; // adjust view to account for search box
+				} else {
+					if (height == 0)
+						height = GetDimAsInt (Height, a, vertical: true);
+
 					listview.Height = CalculatetHeight ();
+					this.Height = height + 1; // adjust view to account for search box
 				}
 
 				if (this.Text != null)
-					Search_Changed (search, Text);
+					Search_Changed (Text);
 
 				if (autoHide)
 					listview.ColorScheme = Colors.Menu;
@@ -131,20 +182,12 @@ namespace Terminal.Gui {
 			this.SetFocus(search);
 		}
 
-		/// <summary>
-		/// Set search list source
-		/// </summary>
-		public void SetSource(IList<string> source)
-		{
-			listsource = new List<string> (source);
-		}
-
-		private void Search_MouseClick (object sender, MouseEventArgs e)
+		private void Search_MouseClick (MouseEventArgs e)
 		{
 			if (e.MouseEvent.Flags != MouseFlags.Button1Clicked)
 				return;
 
-			SuperView.SetFocus ((View)sender);
+			SuperView.SetFocus (search);
 		}
 
 		///<inheritdoc/>
@@ -158,11 +201,23 @@ namespace Terminal.Gui {
 			return true;
 		}
 
+		/// <summary>
+		/// Invokes the SelectedChanged event if it is defined.
+		/// </summary>
+		/// <returns></returns>
+		public virtual bool OnSelectedChanged ()
+		{
+			// Note: Cannot rely on "listview.SelectedItem != lastSelectedItem" because the list is dynamic. 
+			// So we cannot optimize. Ie: Don't call if not changed
+			SelectedItemChanged?.Invoke (this, search.Text);
+
+			return true;
+		}
+
 		///<inheritdoc/>
 		public override bool ProcessKey(KeyEvent e)
 		{
-			if (e.Key == Key.Tab)
-			{
+			if (e.Key == Key.Tab) {
 				base.ProcessKey(e);
 				return false; // allow tab-out to next control
 			}
@@ -173,10 +228,10 @@ namespace Terminal.Gui {
 					return true;
 				}
 
-				SetValue( searchset [listview.SelectedItem]);
+				SetValue((string)searchset [listview.SelectedItem]);
 				search.CursorPosition = search.Text.Length;
-				Search_Changed (search, search.Text);
-				Changed?.Invoke (this, text);
+				Search_Changed (search.Text);
+				OnSelectedChanged ();
 
 				searchset.Clear();
 				listview.Clear ();
@@ -188,7 +243,7 @@ namespace Terminal.Gui {
 
 			if (e.Key == Key.CursorDown && search.HasFocus && listview.SelectedItem == 0 && searchset.Count > 0) { // jump to list
 				this.SetFocus (listview);
-				SetValue (searchset [listview.SelectedItem]);
+				SetValue ((string)searchset [listview.SelectedItem]);
 				return true;
 			}
 
@@ -205,7 +260,7 @@ namespace Terminal.Gui {
 			if (e.Key == Key.Esc) {
 				this.SetFocus (search);
 				search.Text = text = "";
-				Changed?.Invoke (this, search.Text);
+				OnSelectedChanged ();
 				return true;
 			}
 
@@ -235,10 +290,10 @@ namespace Terminal.Gui {
 
 		private void SetValue(ustring text)
 		{
-			search.Changed -= Search_Changed;
+			search.TextChanged -= Search_Changed;
 			this.text = search.Text = text;
 			search.CursorPosition = 0;
-			search.Changed += Search_Changed;
+			search.TextChanged += Search_Changed;
 		}
 
 		/// <summary>
@@ -247,26 +302,38 @@ namespace Terminal.Gui {
 		private void Reset()
 		{
 			search.Text = text = "";
-			Changed?.Invoke (this, search.Text);
-			searchset = autoHide ? new List<string> () : listsource;
+			OnSelectedChanged();
 
-			listview.SetSource(searchset.ToList());
+			ResetSearchSet ();
+
+			listview.SetSource(searchset);
 			listview.Height = CalculatetHeight ();
 
 			this.SetFocus(search);
 		}
 
-		private void Search_Changed (object sender, ustring text)
+		private void ResetSearchSet()
+		{
+			if (autoHide) {
+				if (searchset == null)
+					searchset = new List<string> ();
+				else
+					searchset.Clear ();
+			} else
+				searchset = source.ToList ();
+		}
+
+		private void Search_Changed (ustring text)
 		{
-			if (listsource == null) // Object initialization
+			if (source == null) // Object initialization
 				return;
 
-			if (string.IsNullOrEmpty (search.Text.ToString()))
-				searchset = autoHide ? new List<string> () : listsource;
+			if (string.IsNullOrEmpty (search.Text.ToString ()))
+				ResetSearchSet ();
 			else
-				searchset = listsource.Where (x => x.StartsWith (search.Text.ToString (), StringComparison.CurrentCultureIgnoreCase)).ToList ();
+				searchset = source.ToList().Cast<string>().Where (x => x.StartsWith (search.Text.ToString (), StringComparison.CurrentCultureIgnoreCase)).ToList();
 
-			listview.SetSource (searchset.ToList ());
+			listview.SetSource (searchset);
 			listview.Height = CalculatetHeight ();
 
 			listview.Redraw (new Rect (0, 0, width, height)); // for any view behind this
@@ -295,18 +362,15 @@ namespace Terminal.Gui {
 		/// Get DimAbsolute as integer value
 		/// </summary>
 		/// <param name="dim"></param>
+		/// <param name="a"></param>
+		/// <param name="vertical"></param>
 		/// <returns></returns>
-		private int GetDimAsInt(Dim dim)
+		private int GetDimAsInt (Dim dim, Application.ResizedEventArgs a, bool vertical)
 		{
-			if (!(dim is Dim.DimAbsolute))
-				throw new ArgumentException ("Dim must be an absolute value");
-
-			// Anchor in the case of DimAbsolute returns absolute value. No documentation on what Anchor() does so not sure if this will change in the future.
-			//
-			// TODO: Does Dim need:- 
-			//		public static implicit operator int (Dim d)
-			//
-			return dim.Anchor (0);
+			if (dim is Dim.DimAbsolute)
+				return dim.Anchor (0);
+			else
+				return vertical ? dim.Anchor (a.Rows) : dim.Anchor (a.Cols);
 		}
 	}
 }

+ 9 - 8
UICatalog/Scenarios/ListsAndCombos.cs

@@ -32,27 +32,28 @@ namespace UICatalog.Scenarios {
 			var listview = new ListView (items) {
 				X = 0,
 				Y = Pos.Bottom (lbListView) + 1,
+				Height = Dim.Fill(2),
 				Width = 30
 			};
-			listview.OpenSelectedItem += (object sender, ListViewItemEventArgs e) => lbListView.Text = items [listview.SelectedItem];
+			listview.OpenSelectedItem += (ListViewItemEventArgs e) => lbListView.Text = items [listview.SelectedItem];
 			Win.Add (lbListView, listview);
 
 			// ComboBox
 			var lbComboBox = new Label ("ComboBox") {
 				ColorScheme = Colors.TopLevel,
 				X = Pos.Right (lbListView) + 1,
-				Width = 30
+				Width = Dim.Percent(60)
 			};
 
-			var comboBox = new ComboBox() {
-				X = Pos.Right(listview) + 1 , 
-				Y = Pos.Bottom (lbListView) +1,
-				Height = 10,
-				Width = 30
+			var comboBox = new ComboBox () {
+				X = Pos.Right (listview) + 1,
+				Y = Pos.Bottom (lbListView) + 1,
+				Height = Dim.Fill (2),
+				Width = Dim.Percent(60)
 			};
 			comboBox.SetSource (items);
 
-			comboBox.Changed += (object sender, ustring text) => lbComboBox.Text = text;
+			comboBox.SelectedItemChanged += (object sender, ustring text) => lbComboBox.Text = text;
 			Win.Add (lbComboBox, comboBox);
 		}
 	}

+ 12 - 10
UICatalog/Scenarios/Unicode.cs

@@ -35,16 +35,18 @@ namespace UICatalog {
 			var checkBox = new CheckBox (" ~  s  gui.cs   master ↑10") { X = 15, Y = Pos.Y (label), Width = Dim.Percent (50) };
 			Win.Add (checkBox);
 
-			//label = new Label ("ComboBox:") { X = Pos.X (label), Y = Pos.Bottom (label) + 1 };
-			//Win.Add (label);
-			//var comboBox = new ComboBox (1, 1, 30, 5, new List<string> () { "item #1", " ~  s  gui.cs   master ↑10", "Со_хранить" }) {
-			//	X = 15,
-			//	Y = Pos.Y (label),
-			//	Width = 30,
-			//	ColorScheme = Colors.Error
-			//};
-			//Win.Add (comboBox);
-			//comboBox.Text = " ~  s  gui.cs   master ↑10";
+			label = new Label ("ComboBox:") { X = Pos.X (label), Y = Pos.Bottom (label) + 1 };
+			Win.Add (label);
+			var comboBox = new ComboBox () {
+				X = 15,
+				Y = Pos.Y (label),
+				Width = Dim.Percent (50),
+				ColorScheme = Colors.Error
+			};
+			comboBox.SetSource (new List<string> () { "item #1", " ~  s  gui.cs   master ↑10", "Со_хранить" });
+
+			Win.Add (comboBox);
+			comboBox.Text = " ~  s  gui.cs   master ↑10";
 
 			label = new Label ("HexView:") { X = Pos.X (label), Y = Pos.Bottom (label) + 2 };
 			Win.Add (label);

+ 0 - 4
UICatalog/UICatalog.csproj

@@ -8,10 +8,6 @@
     <LangVersion>8.0</LangVersion>
   </PropertyGroup>
 
-  <ItemGroup>
-    <Compile Remove="Scenarios\ListsAndCombos.cs" />
-  </ItemGroup>
-
   <ItemGroup>
     <ProjectReference Include="..\Terminal.Gui\Terminal.Gui.csproj" />
   </ItemGroup>