Files
Terminal.Gui/Terminal.Gui/Views/Label.cs
BDisp 49cd29853f All my pull-request at once (#345)
* Fixed key events traversal for modal dialogs

The key must be propagated initially to the first chain element
before evaluating if we should stop because of the handled or
the Modal condition. Otherwise the modal dialog
won't get any process key notification.

This fixes c072e29a68

* Fixes culture info of DataField from pr #250

* Fixes the rectangle drawing issue

* Fixes #290 issue "Redraw issue when setting coordinates of label"

* Added sub menus into menu bar with mouse and key navigation

* Needed to assume color for the Disable attribute

* Added Colors.Menu.Disabled to CursesDriver.cs

* Mouse text selection with cut, copy and paste on text fields

* Change sepChar from char to string in DateField

* Adding a disabled menu item in the demo file

* Adding a disabled menu item in the demo file

* Fixes Button repainting issue when changing the text length to one smaller

* Fixes #290 issue "Redraw issue when setting coordinates of label"

* Only demonstration of issue # 308 that even though the cursor is gray on a gray background can be viewed.

* Fixes issue #163 "ScrollView does not render some content"

* Fixed bug in Button that caused a loop redraw calling TerminalResized

* Fixes #282 "Repaint Issue"

* Removed white space

* Mouse features added to FileDialog including wheel support.

* Forget to delete this commented method.

* Changing back to MouseFlags.AllEvents in case some mouse event is not triggering.

* Add documentation on ISupportInitialize/ISupportInitializeNotification (#286)

* Switch netcoreapp target to netstandard2.0 (#284)

Fixes #283 

Instead of adding another target framework to the list, switch from netcoreapp2.0 to netstandard2.0, as ns2.0 is a subset of netcoreapp.

* Added TextView.TextChanged event (#264)

* Fixed key events traversal for modal dialogs (#288)

The key must be propagated initially to the first chain element
before evaluating if we should stop because of the handled or
the Modal condition. Otherwise the modal dialog
won't get any process key notification.

This fixes c072e29a68

* Prepare for 0.25

* Remove travis link

* Revert Daniel's change 00c5997daa as it prevents the solution from building on Mac

* Prepare for 0.26

* Restore some files that were deleted by Daniel's commit that I had not restored

* Fixed out of range exception and text redraw when navigate backward (#320)

* Typo fix (#321)

* Fixes issue #306 async/await hang (#312)

* Fixed async/await hang

* Fixed async/await hang with calling Wakeup

* Moved Wake Up into lock statement

* Support menu items that are null so they can be drawn as a menu separator (#304)

* Fixed and Enabled Library reinitialization (#291)

- Replaced static driver initialization with property getter for reference passing in Core.cs::View class, this allows the library to be reinitialized at any time.
- Made the Shutdown method on Core.cs::Application class public, since there is no reason to keep it private. Applications can shutdown the library and revert the console to the initial stage by calling it.
- Fixed a memory-leak on Drivers/WindowsDriver class by destroying the generated screen buffers at library shutdown by calling CloseHandle.
- Minor change to Core.cs::Application.Init(Func<Toplevel>) for better initialization status tracking, via backend property instead of relying on the Top field.

* Moved `ListView.ListWrapper` out of `ListView` migueldeicaza/gui.cs#313` (#315)

* Resizing the MessageBox width to accommodate all message text (#299)

* Fixed key events traversal for modal dialogs

The key must be propagated initially to the first chain element
before evaluating if we should stop because of the handled or
the Modal condition. Otherwise the modal dialog
won't get any process key notification.

This fixes c072e29a68

* Resizing the MessageBox width to accommodate all message text

Co-authored-by: Adrian Alonso <adrianalonso@gmail.com>

* Timefield format with bounds values (#303)

* Implemented lower and upper bounds to TimeField

* Passing old text to the Changed event handler

* Change sepChar from char to string in TimeField

* Changing comparison from ':' to sepChar.ToCharArray () [0]

* extract methods on ListView to make it controlable from other controls (#310)

* moveup

* MoveDown

* MovePageDown

* MovePageUp

* MarkUnmarkRow

* Allowing list items selection (#302)

* Prepare for 0.26

* Restore some files that were deleted by Daniel's commit that I had not restored

* Fixed out of range exception and text redraw when navigate backward (#320)

* Typo fix (#321)

* Fixes issue #306 async/await hang (#312)

* Fixed async/await hang

* Fixed async/await hang with calling Wakeup

* Moved Wake Up into lock statement

* Support menu items that are null so they can be drawn as a menu separator (#304)

* Fixed and Enabled Library reinitialization (#291)

- Replaced static driver initialization with property getter for reference passing in Core.cs::View class, this allows the library to be reinitialized at any time.
- Made the Shutdown method on Core.cs::Application class public, since there is no reason to keep it private. Applications can shutdown the library and revert the console to the initial stage by calling it.
- Fixed a memory-leak on Drivers/WindowsDriver class by destroying the generated screen buffers at library shutdown by calling CloseHandle.
- Minor change to Core.cs::Application.Init(Func<Toplevel>) for better initialization status tracking, via backend property instead of relying on the Top field.

* Moved `ListView.ListWrapper` out of `ListView` migueldeicaza/gui.cs#313` (#315)

* Resizing the MessageBox width to accommodate all message text (#299)

* Fixed key events traversal for modal dialogs

The key must be propagated initially to the first chain element
before evaluating if we should stop because of the handled or
the Modal condition. Otherwise the modal dialog
won't get any process key notification.

This fixes c072e29a68

* Resizing the MessageBox width to accommodate all message text

Co-authored-by: Adrian Alonso <adrianalonso@gmail.com>

* Timefield format with bounds values (#303)

* Implemented lower and upper bounds to TimeField

* Passing old text to the Changed event handler

* Change sepChar from char to string in TimeField

* Changing comparison from ':' to sepChar.ToCharArray () [0]

* extract methods on ListView to make it controlable from other controls (#310)

* moveup

* MoveDown

* MovePageDown

* MovePageUp

* MarkUnmarkRow

* Allowing list items selection (#302)

* Add documentation on ISupportInitialize/ISupportInitializeNotification (#286)

* Switch netcoreapp target to netstandard2.0 (#284)

Fixes #283 

Instead of adding another target framework to the list, switch from netcoreapp2.0 to netstandard2.0, as ns2.0 is a subset of netcoreapp.

* Added TextView.TextChanged event (#264)

* Fixed key events traversal for modal dialogs (#288)

The key must be propagated initially to the first chain element
before evaluating if we should stop because of the handled or
the Modal condition. Otherwise the modal dialog
won't get any process key notification.

This fixes c072e29a68

* Prepare for 0.25

* Remove travis link

* Revert Daniel's change 00c5997daa as it prevents the solution from building on Mac

* Prepare for 0.26

* Restore some files that were deleted by Daniel's commit that I had not restored

* Fixed out of range exception and text redraw when navigate backward (#320)

* Typo fix (#321)

* Fixes issue #306 async/await hang (#312)

* Fixed async/await hang

* Fixed async/await hang with calling Wakeup

* Moved Wake Up into lock statement

* Support menu items that are null so they can be drawn as a menu separator (#304)

* Fixed and Enabled Library reinitialization (#291)

- Replaced static driver initialization with property getter for reference passing in Core.cs::View class, this allows the library to be reinitialized at any time.
- Made the Shutdown method on Core.cs::Application class public, since there is no reason to keep it private. Applications can shutdown the library and revert the console to the initial stage by calling it.
- Fixed a memory-leak on Drivers/WindowsDriver class by destroying the generated screen buffers at library shutdown by calling CloseHandle.
- Minor change to Core.cs::Application.Init(Func<Toplevel>) for better initialization status tracking, via backend property instead of relying on the Top field.

* Moved `ListView.ListWrapper` out of `ListView` migueldeicaza/gui.cs#313` (#315)

* Resizing the MessageBox width to accommodate all message text (#299)

* Fixed key events traversal for modal dialogs

The key must be propagated initially to the first chain element
before evaluating if we should stop because of the handled or
the Modal condition. Otherwise the modal dialog
won't get any process key notification.

This fixes c072e29a68

* Resizing the MessageBox width to accommodate all message text

Co-authored-by: Adrian Alonso <adrianalonso@gmail.com>

* Timefield format with bounds values (#303)

* Implemented lower and upper bounds to TimeField

* Passing old text to the Changed event handler

* Change sepChar from char to string in TimeField

* Changing comparison from ':' to sepChar.ToCharArray () [0]

* extract methods on ListView to make it controlable from other controls (#310)

* moveup

* MoveDown

* MovePageDown

* MovePageUp

* MarkUnmarkRow

* Allowing list items selection (#302)

* Switch netcoreapp target to netstandard2.0 (#284)

Fixes #283 

Instead of adding another target framework to the list, switch from netcoreapp2.0 to netstandard2.0, as ns2.0 is a subset of netcoreapp.

* Added TextView.TextChanged event (#264)

* Prepare for 0.25

* Remove travis link

* Revert Daniel's change 00c5997daa as it prevents the solution from building on Mac

* Prepare for 0.26

* Restore some files that were deleted by Daniel's commit that I had not restored

* Fixed out of range exception and text redraw when navigate backward (#320)

* Typo fix (#321)

* Fixes issue #306 async/await hang (#312)

* Fixed async/await hang

* Fixed async/await hang with calling Wakeup

* Moved Wake Up into lock statement

* Fixed and Enabled Library reinitialization (#291)

- Replaced static driver initialization with property getter for reference passing in Core.cs::View class, this allows the library to be reinitialized at any time.
- Made the Shutdown method on Core.cs::Application class public, since there is no reason to keep it private. Applications can shutdown the library and revert the console to the initial stage by calling it.
- Fixed a memory-leak on Drivers/WindowsDriver class by destroying the generated screen buffers at library shutdown by calling CloseHandle.
- Minor change to Core.cs::Application.Init(Func<Toplevel>) for better initialization status tracking, via backend property instead of relying on the Top field.

* Moved `ListView.ListWrapper` out of `ListView` migueldeicaza/gui.cs#313` (#315)

* Resizing the MessageBox width to accommodate all message text (#299)

* Fixed key events traversal for modal dialogs

The key must be propagated initially to the first chain element
before evaluating if we should stop because of the handled or
the Modal condition. Otherwise the modal dialog
won't get any process key notification.

This fixes c072e29a68

* Resizing the MessageBox width to accommodate all message text

Co-authored-by: Adrian Alonso <adrianalonso@gmail.com>

* Timefield format with bounds values (#303)

* Implemented lower and upper bounds to TimeField

* Passing old text to the Changed event handler

* Change sepChar from char to string in TimeField

* Changing comparison from ':' to sepChar.ToCharArray () [0]

* extract methods on ListView to make it controlable from other controls (#310)

* moveup

* MoveDown

* MovePageDown

* MovePageUp

* MarkUnmarkRow

* Allowing list items selection (#302)

* Added sub menus into menu bar with mouse and key navigation

* Fetch from upstream/master

* Fetch from upstream/master

* Fetch from upstream/master

* Fetch from upstream/master

* Fetch from upstream/master

* Add documentation on ISupportInitialize/ISupportInitializeNotification (#286)

* Switch netcoreapp target to netstandard2.0 (#284)

Fixes #283 

Instead of adding another target framework to the list, switch from netcoreapp2.0 to netstandard2.0, as ns2.0 is a subset of netcoreapp.

* Added TextView.TextChanged event (#264)

* Fixed key events traversal for modal dialogs (#288)

The key must be propagated initially to the first chain element
before evaluating if we should stop because of the handled or
the Modal condition. Otherwise the modal dialog
won't get any process key notification.

This fixes c072e29a68

* Prepare for 0.25

* Remove travis link

* Revert Daniel's change 00c5997daa as it prevents the solution from building on Mac

* Prepare for 0.26

* Restore some files that were deleted by Daniel's commit that I had not restored

* Fixed out of range exception and text redraw when navigate backward (#320)

* Typo fix (#321)

* Fixes issue #306 async/await hang (#312)

* Fixed async/await hang

* Fixed async/await hang with calling Wakeup

* Moved Wake Up into lock statement

* Support menu items that are null so they can be drawn as a menu separator (#304)

* Fixed and Enabled Library reinitialization (#291)

- Replaced static driver initialization with property getter for reference passing in Core.cs::View class, this allows the library to be reinitialized at any time.
- Made the Shutdown method on Core.cs::Application class public, since there is no reason to keep it private. Applications can shutdown the library and revert the console to the initial stage by calling it.
- Fixed a memory-leak on Drivers/WindowsDriver class by destroying the generated screen buffers at library shutdown by calling CloseHandle.
- Minor change to Core.cs::Application.Init(Func<Toplevel>) for better initialization status tracking, via backend property instead of relying on the Top field.

* Moved `ListView.ListWrapper` out of `ListView` migueldeicaza/gui.cs#313` (#315)

* Resizing the MessageBox width to accommodate all message text (#299)

* Fixed key events traversal for modal dialogs

The key must be propagated initially to the first chain element
before evaluating if we should stop because of the handled or
the Modal condition. Otherwise the modal dialog
won't get any process key notification.

This fixes c072e29a68

* Resizing the MessageBox width to accommodate all message text

Co-authored-by: Adrian Alonso <adrianalonso@gmail.com>

* Timefield format with bounds values (#303)

* Implemented lower and upper bounds to TimeField

* Passing old text to the Changed event handler

* Change sepChar from char to string in TimeField

* Changing comparison from ':' to sepChar.ToCharArray () [0]

* extract methods on ListView to make it controlable from other controls (#310)

* moveup

* MoveDown

* MovePageDown

* MovePageUp

* MarkUnmarkRow

* Allowing list items selection (#302)

* Fetch from upstream/master

* Fetch from upstream/master

* Fetch from upstream/master

* Add documentation on ISupportInitialize/ISupportInitializeNotification (#286)

* Switch netcoreapp target to netstandard2.0 (#284)

Fixes #283 

Instead of adding another target framework to the list, switch from netcoreapp2.0 to netstandard2.0, as ns2.0 is a subset of netcoreapp.

* Added TextView.TextChanged event (#264)

* Fixed key events traversal for modal dialogs (#288)

The key must be propagated initially to the first chain element
before evaluating if we should stop because of the handled or
the Modal condition. Otherwise the modal dialog
won't get any process key notification.

This fixes c072e29a68

* Prepare for 0.25

* Remove travis link

* Revert Daniel's change 00c5997daa as it prevents the solution from building on Mac

* Prepare for 0.26

* Restore some files that were deleted by Daniel's commit that I had not restored

* Fixed out of range exception and text redraw when navigate backward (#320)

* Typo fix (#321)

* Fixes issue #306 async/await hang (#312)

* Fixed async/await hang

* Fixed async/await hang with calling Wakeup

* Moved Wake Up into lock statement

* Support menu items that are null so they can be drawn as a menu separator (#304)

* Fixed and Enabled Library reinitialization (#291)

- Replaced static driver initialization with property getter for reference passing in Core.cs::View class, this allows the library to be reinitialized at any time.
- Made the Shutdown method on Core.cs::Application class public, since there is no reason to keep it private. Applications can shutdown the library and revert the console to the initial stage by calling it.
- Fixed a memory-leak on Drivers/WindowsDriver class by destroying the generated screen buffers at library shutdown by calling CloseHandle.
- Minor change to Core.cs::Application.Init(Func<Toplevel>) for better initialization status tracking, via backend property instead of relying on the Top field.

* Moved `ListView.ListWrapper` out of `ListView` migueldeicaza/gui.cs#313` (#315)

* Resizing the MessageBox width to accommodate all message text (#299)

* Fixed key events traversal for modal dialogs

The key must be propagated initially to the first chain element
before evaluating if we should stop because of the handled or
the Modal condition. Otherwise the modal dialog
won't get any process key notification.

This fixes c072e29a68

* Resizing the MessageBox width to accommodate all message text

Co-authored-by: Adrian Alonso <adrianalonso@gmail.com>

* Timefield format with bounds values (#303)

* Implemented lower and upper bounds to TimeField

* Passing old text to the Changed event handler

* Change sepChar from char to string in TimeField

* Changing comparison from ':' to sepChar.ToCharArray () [0]

* extract methods on ListView to make it controlable from other controls (#310)

* moveup

* MoveDown

* MovePageDown

* MovePageUp

* MarkUnmarkRow

* Allowing list items selection (#302)

* Fetch from upstream/master

* Switch netcoreapp target to netstandard2.0 (#284)

Fixes #283 

Instead of adding another target framework to the list, switch from netcoreapp2.0 to netstandard2.0, as ns2.0 is a subset of netcoreapp.

* Added TextView.TextChanged event (#264)

* Prepare for 0.25

* Remove travis link

* Revert Daniel's change 00c5997daa as it prevents the solution from building on Mac

* Prepare for 0.26

* Restore some files that were deleted by Daniel's commit that I had not restored

* Fixed out of range exception and text redraw when navigate backward (#320)

* Typo fix (#321)

* Fixes issue #306 async/await hang (#312)

* Fixed async/await hang

* Fixed async/await hang with calling Wakeup

* Moved Wake Up into lock statement

* Support menu items that are null so they can be drawn as a menu separator (#304)

* Fixed and Enabled Library reinitialization (#291)

- Replaced static driver initialization with property getter for reference passing in Core.cs::View class, this allows the library to be reinitialized at any time.
- Made the Shutdown method on Core.cs::Application class public, since there is no reason to keep it private. Applications can shutdown the library and revert the console to the initial stage by calling it.
- Fixed a memory-leak on Drivers/WindowsDriver class by destroying the generated screen buffers at library shutdown by calling CloseHandle.
- Minor change to Core.cs::Application.Init(Func<Toplevel>) for better initialization status tracking, via backend property instead of relying on the Top field.

* Moved `ListView.ListWrapper` out of `ListView` migueldeicaza/gui.cs#313` (#315)

* Resizing the MessageBox width to accommodate all message text (#299)

* Fixed key events traversal for modal dialogs

The key must be propagated initially to the first chain element
before evaluating if we should stop because of the handled or
the Modal condition. Otherwise the modal dialog
won't get any process key notification.

This fixes c072e29a68

* Resizing the MessageBox width to accommodate all message text

Co-authored-by: Adrian Alonso <adrianalonso@gmail.com>

* Timefield format with bounds values (#303)

* Implemented lower and upper bounds to TimeField

* Passing old text to the Changed event handler

* Change sepChar from char to string in TimeField

* Changing comparison from ':' to sepChar.ToCharArray () [0]

* extract methods on ListView to make it controlable from other controls (#310)

* moveup

* MoveDown

* MovePageDown

* MovePageUp

* MarkUnmarkRow

* Allowing list items selection (#302)

* Fetch from upstream/master

* Fixes #342 and improves color change interaction.
Usage:
Colors.Base.Normal = new Terminal.Gui.Attribute (Color.Green, Color.Black);

* Inserted new line at the end  of file .
Changed method name to SetAttribute in the  ColorScheme class.

* Prepare for 0.70

* Prepare for 0.70

* Prepare for 0.70

* Prepare for 0.70

* Prepare for 0.70

* Prepare for 0.70

* Prepare for 0.70

* Prepare for 0.70

* Timefield format with bounds values (#303)

* Implemented lower and upper bounds to TimeField

* Passing old text to the Changed event handler

* Change sepChar from char to string in TimeField

* Changing comparison from ':' to sepChar.ToCharArray () [0]

* Prepare for 0.70

* Removed duplicated Attribute Disabled property

* Fixed some bugs with the mouse event and text selection, copy, cut and paste. There is still a random failure in the mouse events that lock on button released and only trigger button clicked after moving the mouse.

* Failure behavior solved. It was a threading safe issue. Driver.Wakeup () moved to the Post method on MainLoopSyncContext class solved it.

* Changed the default for RightmostButtonPressed to Button4 and enabled  clicked-drag

* Added support for Button Triple Clicked too.  FileDialog changed to deal with ButtonClicked.

* Fixed a bug with the timer when dragging.

* Fixes #343 - Added AllowsMultipleSelection to the ListView

* Fixes #346 issue with enhancers characters, but it only could be apply after the pull requests at NStack are merged because of the Rune.ColumnWidth error.

* Fixes code format.

* Enabled Button Pressed with ReportMousePosition simultaneously.

* Dragging is already working. TODO: optimize, only SetNeedsDisplay on the before/after regions.

* Fixes the extra characters that remains in case the new text length is smaller than the older.

* Fixes #349 TextField user typed input no longer fires Changed event.

* Includes ControlKeyState for all the buttons events.

* Added SetSourceAsync to ListView

* Menu enhancement that works well, even if the top level has no other views. Working in further feature that if clicked outside of the menu it will closed.

* Some more features in mouse and in core.

* Added more mouse events flags, drag features, toplevel color and more...

* Remove unnecessary SetNeedsDisplay.

* Fixes a bug in the label

* Added StatusBar from pr #201 with a  little change.

* Added features to TextField like mouse selection with copy, cut and paste shortcut keys. Now it's possible to use the combination of the Alt+Control+delta keys. It also be possible use special characters like €.

* Simplifying the menu with better performance.

* Private keyword dropped in all files and added some documentation.

* Changed demo to reflect the added and changes features.

* Added csproj and config files to verify if it won't trigger errors from Travis.

* Demo with the StatusBar.

* Patch for position of the StatusBar

* Removed unnecessary nugget packages.

* It looks like packages.config files are obsolete. Travis verification test.

* Update Designer.csproj

Use Stack 0.14

* Use NStack 0.14

* Use NStack 0.14

* Use NStack 0.14

* Use NStack 0.14

* Changed the NStack.Core and System.ValueTuple versions.

* Added System.ValueTuple to Example project.

* Remove System.ValueTuple and added NETStandard.Library to Example project.

* Try to restore the nuget packages.

* Revert "Try to restore the nuget packages."

This reverts commit 3957e022c3.

* Added NETStandard.Library ti the root packages.config

* Upgrade to "Microsoft.NETCore.Platforms" version="
2.0.1"

* Added <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>

* Targeting framework 472.

* Removed "System.ValueTuple" Version="4.5.0" from Terminal.Gui project.

* More cleaning to the projects.

* I guess you don't need this.

Co-authored-by: Adrian Alonso <adrianalonso@gmail.com>
Co-authored-by: Daniel Cazzulino <daniel@cazzulino.com>
Co-authored-by: Marius Ungureanu <teromario@yahoo.com>
Co-authored-by: miguel <miguel.de.icaza@gmail.com>
Co-authored-by: Miguel de Icaza <miguel@gnome.org>
Co-authored-by: imaras <imaras@net.hr>
Co-authored-by: Kasper B. Graversen <kbilsted@users.noreply.github.com>
Co-authored-by: Fabian R <kderazorback@me.com>
Co-authored-by: Timothy <timothyparez@gmail.com>
2020-03-31 09:26:54 -04:00

262 lines
6.5 KiB
C#

//
// Label.cs: Label control
//
// Authors:
// Miguel de Icaza (miguel@gnome.org)
//
using System;
using System.Collections.Generic;
using System.Linq;
using NStack;
namespace Terminal.Gui {
/// <summary>
/// Text alignment enumeration, controls how text is displayed.
/// </summary>
public enum TextAlignment {
/// <summary>
/// Aligns the text to the left of the frame.
/// </summary>
Left,
/// <summary>
/// Aligns the text to the right side of the frame.
/// </summary>
Right,
/// <summary>
/// Centers the text in the frame.
/// </summary>
Centered,
/// <summary>
/// Shows the line as justified text in the line.
/// </summary>
Justified
}
/// <summary>
/// Label view, displays a string at a given position, can include multiple lines.
/// </summary>
public class Label : View {
List<ustring> lines = new List<ustring> ();
bool recalcPending = true;
ustring text;
TextAlignment textAlignment;
static Rect CalcRect (int x, int y, ustring s)
{
int mw = 0;
int ml = 1;
int cols = 0;
foreach (var rune in s) {
if (rune == '\n') {
ml++;
if (cols > mw)
mw = cols;
cols = 0;
} else
cols++;
}
if (cols > mw)
mw = cols;
return new Rect (x, y, mw, ml);
}
/// <summary>
/// Public constructor: creates a label at the given
/// coordinate with the given string, computes the bounding box
/// based on the size of the string, assumes that the string contains
/// newlines for multiple lines, no special breaking rules are used.
/// </summary>
public Label (int x, int y, ustring text) : this (CalcRect (x, y, text), text)
{
}
/// <summary>
/// Public constructor: creates a label at the given
/// coordinate with the given string and uses the specified
/// frame for the string.
/// </summary>
public Label (Rect rect, ustring text) : base (rect)
{
this.text = text;
}
/// <summary>
/// Public constructor: creates a label and configures the default Width and Height based on the text, the result is suitable for Computed layout.
/// </summary>
/// <param name="text">Text.</param>
public Label (ustring text) : base ()
{
this.text = text;
var r = CalcRect (0, 0, text);
Width = r.Width;
Height = r.Height;
}
static char [] whitespace = new char [] { ' ', '\t' };
static ustring ClipAndJustify (ustring str, int width, TextAlignment talign)
{
int slen = str.RuneCount;
if (slen > width){
var uints = str.ToRunes (width);
var runes = new Rune [uints.Length];
for (int i = 0; i < uints.Length; i++)
runes [i] = uints [i];
return ustring.Make (runes);
} else {
if (talign == TextAlignment.Justified) {
// TODO: ustring needs this
var words = str.ToString ().Split (whitespace, StringSplitOptions.RemoveEmptyEntries);
int textCount = words.Sum (arg => arg.Length);
var spaces = (width- textCount) / (words.Length - 1);
var extras = (width - textCount) % words.Length;
var s = new System.Text.StringBuilder ();
//s.Append ($"tc={textCount} sp={spaces},x={extras} - ");
for (int w = 0; w < words.Length; w++) {
var x = words [w];
s.Append (x);
if (w + 1 < words.Length)
for (int i = 0; i < spaces; i++)
s.Append (' ');
if (extras > 0) {
s.Append ('_');
extras--;
}
}
return ustring.Make (s.ToString ());
}
return str;
}
}
void Recalc ()
{
recalcPending = false;
Recalc (text, lines, Frame.Width, textAlignment);
}
static void Recalc (ustring textStr, List<ustring> lineResult, int width, TextAlignment talign)
{
lineResult.Clear ();
if (textStr.IndexOf ('\n') == -1) {
lineResult.Add (ClipAndJustify (textStr, width, talign));
return;
}
int textLen = textStr.Length;
int lp = 0;
for (int i = 0; i < textLen; i++) {
Rune c = textStr [i];
if (c == '\n') {
lineResult.Add (ClipAndJustify (textStr [lp, i], width, talign));
lp = i + 1;
}
}
lineResult.Add(ClipAndJustify(textStr[lp, textLen], width, talign));
}
public override void Redraw (Rect region)
{
if (recalcPending)
Recalc ();
if (TextColor != -1)
Driver.SetAttribute (TextColor);
else
Driver.SetAttribute (ColorScheme.Normal);
Clear ();
for (int line = 0; line < lines.Count; line++) {
if (line < region.Top || line > region.Bottom)
continue;
var str = lines [line];
int x;
switch (textAlignment) {
case TextAlignment.Left:
case TextAlignment.Justified:
x = 0;
break;
case TextAlignment.Right:
x = Frame.Right - str.Length;
break;
case TextAlignment.Centered:
x = Frame.Left + (Frame.Width - str.Length) / 2;
break;
default:
throw new ArgumentOutOfRangeException ();
}
Move (x, line);
Driver.AddStr (str);
}
}
/// <summary>
/// Computes the number of lines needed to render the specified text by the Label control
/// </summary>
/// <returns>Number of lines.</returns>
/// <param name="text">Text, may contain newlines.</param>
/// <param name="width">The width for the text.</param>
public static int MeasureLines (ustring text, int width)
{
var result = new List<ustring> ();
Recalc (text, result, width, TextAlignment.Left);
return result.Count;
}
/// <summary>
/// Computes the the max width of a line or multilines needed to render by the Label control
/// </summary>
/// <returns>Max width of lines.</returns>
/// <param name="text">Text, may contain newlines.</param>
/// <param name="width">The width for the text.</param>
public static int MaxWidth(ustring text, int width)
{
var result = new List<ustring>();
Recalc(text, result, width, TextAlignment.Left);
return result.Max(s => s.RuneCount);
}
/// <summary>
/// The text displayed by this widget.
/// </summary>
public virtual ustring Text {
get => text;
set {
text = value;
recalcPending = true;
SetNeedsDisplay ();
}
}
/// <summary>
/// Controls the text-alignemtn property of the label, changing it will redisplay the label.
/// </summary>
/// <value>The text alignment.</value>
public TextAlignment TextAlignment {
get => textAlignment;
set {
textAlignment = value;
SetNeedsDisplay ();
}
}
Attribute textColor = -1;
/// <summary>
/// The color used for the label
/// </summary>
public Attribute TextColor {
get => textColor;
set {
textColor = value;
SetNeedsDisplay ();
}
}
}
}