Files
Terminal.Gui/Terminal.Gui/ConsoleDrivers/FakeDriver/FakeDriver.cs
Thomas Nind a8628e7c28 Feature/graphs (#1201)
* Empty GraphView with basic axis

* Added ISeries

* Added zoom

* Fixed zoom

* Tests and scrolling

* Refactored AxisView into abstract base

* Added atomic mass example

* Added Y axis labels

* Added Y axis labels

* comments

* Refactored axis to not be floating views

* Split axis drawing code to seperate draw line from draw labels

* Added MarginBottom and MarginLeft

* Added bar graph

* Fixes horizontal axis label generation

* Fixed axis labels changing during scrolling

* Added test for overlapping cells

* Added TestReversing_ScreenToGraphSpace

* Changed graph space from float to decimal

* Added axis labels

* Fixed issues where labels/axis overspilled bounds

* Fixed origin screen coordinates being off by 1 in y axis

* Added Orientation to BarSeries

* Added comments and standardised Name to Text

* Added prototype 'population pyramid'

* Fixed bar graphs not stopping at axis

* Added Reset and Ctrl to speed up scrolling

* Added line graph

* Fixed LineSeries implementation

* Made LineSeries Points readonly and sort on add

* Fixed RectangleD.GetHasCode()

* Improved performance of LineSeries

* Added color to graph

* Fixed colors not working on linux

* Added Visible and ColorGetter

* Added Ctrl+G Next Graph

* Added MultiBarSeries

* Fixed layout issue with population pyramid

* fixed y label overspill and origin rendering

* Fixed warnings

* Made examples prettier

* Fixed xAxis potentially drawing labels outside of control area

* Fixed multi bar example labels

* Added IAnnotation

* Added example of using GraphPosition in IAnnotation

* Fixed Annotations drawing outside of graph bounds

* Fixed Reset() not clearing Annotations and sp fixes

* Changed line drawing to Bresenham's line algorithm and deleted CohenSutherland
Testing for collisions with screen space is very slow and gives quite thick lines.  I looked at Xiaolin Wu which supports anti aliasing but this also would require more work to look good (out of the box it just looks thick).

* Fixed layout/whitespace

* Graph now renders without series if annotations are present

* Fixed ScreenToGraphSpace rect overload

* Added SeriesDrawMode for when it is easier/faster for a series to draw itself all in one go

* Added LegendAnnotation

* Added tests for correct bounds

* Added more tests

* Changed GraphView namespace to Terminal.Gui.Graphs

* Made Line2D and Horizontal/Vertical axis private classes

* Made AxisIncrementToRender.Text internal to avoid confusing user when implementing `LabelGetterDelegate`

* Changed back from decimal to float

* Refactored axis label drawing to avoid rounding errors

* Fixed over spilling bounds when drawing bars/axis increments

* Re-implemented disco colors

* Added Minimum to Axis

* Fixed tests build and render order

* Fixed test by adjusting epsilon

* tidyup, docs and warning fixes

* Standardised parameter order and added axis test

* Fixed x axis line drawing into margins and added tests

* Fixed axis increment rendering in margins, tests and tidyup examples

* Added test for BarSeries

* Added more BarSeriesTests

* Split GraphView.cs into sub files as suggested

* Fixed pointlessly passing around ConsoleDriver and Bounds

* Fixed colored bars not reseting color before drawing labels

* spelling fixes

* Replaced System.Drawing with code copied from dotnet/corefx repo

* Change to trigger CI

* Added tests for MultiBarSeries

* Added test support for Asserting exact graph contents

* Added xml doc where missing from System.Drawing Types

* Standardised unit test namespaces to Terminal.Gui

* Fixed namespace correctly this time after merging main

* Fixed test to avoid using Attribute constructor

* Reduced code duplication in test by moving InitFakeDriver to static in GraphViewTests

* Added TextAnnotationTests and improved GraphViewTests.AssertDriverContentsAre

* Added more TextAnnotation tests and fixed file indentation

* Added tests for Legend and Path
And fixed TruncateOrPad being off by 1 when truncating

* Removed unused paths in TruncateOrPad
2021-04-28 08:38:25 -07:00

466 lines
13 KiB
C#

//
// FakeDriver.cs: A fake ConsoleDriver for unit tests.
//
// Authors:
// Charlie Kindel (github.com/tig)
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using NStack;
namespace Terminal.Gui {
/// <summary>
/// Implements a mock ConsoleDriver for unit testing
/// </summary>
public class FakeDriver : ConsoleDriver {
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
int cols, rows;
public override int Cols => cols;
public override int Rows => rows;
public override int Top => 0;
public override bool HeightAsBuffer { get; set; }
// The format is rows, columns and 3 values on the last column: Rune, Attribute and Dirty Flag
int [,,] contents;
bool [] dirtyLine;
/// <summary>
/// Assists with testing, the format is rows, columns and 3 values on the last column: Rune, Attribute and Dirty Flag
/// </summary>
public int [,,] Contents => contents;
void UpdateOffscreen ()
{
int cols = Cols;
int rows = Rows;
contents = new int [rows, cols, 3];
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
contents [r, c, 0] = ' ';
contents [r, c, 1] = MakeColor (ConsoleColor.Gray, ConsoleColor.Black);
contents [r, c, 2] = 0;
}
}
dirtyLine = new bool [rows];
for (int row = 0; row < rows; row++)
dirtyLine [row] = true;
}
static bool sync = false;
public FakeDriver ()
{
cols = FakeConsole.WindowWidth;
rows = FakeConsole.WindowHeight; // - 1;
UpdateOffscreen ();
}
bool needMove;
// Current row, and current col, tracked by Move/AddCh only
int ccol, crow;
public override void Move (int col, int row)
{
ccol = col;
crow = row;
if (Clip.Contains (col, row)) {
FakeConsole.CursorTop = row;
FakeConsole.CursorLeft = col;
needMove = false;
} else {
FakeConsole.CursorTop = Clip.Y;
FakeConsole.CursorLeft = Clip.X;
needMove = true;
}
}
public override void AddRune (Rune rune)
{
rune = MakePrintable (rune);
if (Clip.Contains (ccol, crow)) {
if (needMove) {
//MockConsole.CursorLeft = ccol;
//MockConsole.CursorTop = crow;
needMove = false;
}
contents [crow, ccol, 0] = (int)(uint)rune;
contents [crow, ccol, 1] = currentAttribute;
contents [crow, ccol, 2] = 1;
dirtyLine [crow] = true;
} else
needMove = true;
ccol++;
//if (ccol == Cols) {
// ccol = 0;
// if (crow + 1 < Rows)
// crow++;
//}
if (sync)
UpdateScreen ();
}
public override void AddStr (ustring str)
{
foreach (var rune in str)
AddRune (rune);
}
public override void End ()
{
FakeConsole.ResetColor ();
FakeConsole.Clear ();
}
static Attribute MakeColor (ConsoleColor f, ConsoleColor b)
{
// Encode the colors into the int value.
return new Attribute (
value: ((((int)f) & 0xffff) << 16) | (((int)b) & 0xffff),
foreground: (Color)f,
background: (Color)b
);
}
public override void Init (Action terminalResized)
{
Colors.TopLevel = new ColorScheme ();
Colors.Base = new ColorScheme ();
Colors.Dialog = new ColorScheme ();
Colors.Menu = new ColorScheme ();
Colors.Error = new ColorScheme ();
Clip = new Rect (0, 0, Cols, Rows);
Colors.TopLevel.Normal = MakeColor (ConsoleColor.Green, ConsoleColor.Black);
Colors.TopLevel.Focus = MakeColor (ConsoleColor.White, ConsoleColor.DarkCyan);
Colors.TopLevel.HotNormal = MakeColor (ConsoleColor.DarkYellow, ConsoleColor.Black);
Colors.TopLevel.HotFocus = MakeColor (ConsoleColor.DarkBlue, ConsoleColor.DarkCyan);
Colors.Base.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Blue);
Colors.Base.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Cyan);
Colors.Base.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Blue);
Colors.Base.HotFocus = MakeColor (ConsoleColor.Yellow, ConsoleColor.Cyan);
// Focused,
// Selected, Hot: Yellow on Black
// Selected, text: white on black
// Unselected, hot: yellow on cyan
// unselected, text: same as unfocused
Colors.Menu.HotFocus = MakeColor (ConsoleColor.Yellow, ConsoleColor.Black);
Colors.Menu.Focus = MakeColor (ConsoleColor.White, ConsoleColor.Black);
Colors.Menu.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Cyan);
Colors.Menu.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Cyan);
Colors.Menu.Disabled = MakeColor (ConsoleColor.DarkGray, ConsoleColor.Cyan);
Colors.Dialog.Normal = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
Colors.Dialog.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Cyan);
Colors.Dialog.HotNormal = MakeColor (ConsoleColor.Blue, ConsoleColor.Gray);
Colors.Dialog.HotFocus = MakeColor (ConsoleColor.Blue, ConsoleColor.Cyan);
Colors.Error.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Red);
Colors.Error.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
Colors.Error.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Red);
Colors.Error.HotFocus = Colors.Error.HotNormal;
//MockConsole.Clear ();
}
public override Attribute MakeAttribute (Color fore, Color back)
{
return MakeColor ((ConsoleColor)fore, (ConsoleColor)back);
}
int redrawColor = -1;
void SetColor (int color)
{
redrawColor = color;
IEnumerable<int> values = Enum.GetValues (typeof (ConsoleColor))
.OfType<ConsoleColor> ()
.Select (s => (int)s);
if (values.Contains (color & 0xffff)) {
FakeConsole.BackgroundColor = (ConsoleColor)(color & 0xffff);
}
if (values.Contains ((color >> 16) & 0xffff)) {
FakeConsole.ForegroundColor = (ConsoleColor)((color >> 16) & 0xffff);
}
}
public override void UpdateScreen ()
{
int rows = Rows;
int cols = Cols;
FakeConsole.CursorTop = 0;
FakeConsole.CursorLeft = 0;
for (int row = 0; row < rows; row++) {
dirtyLine [row] = false;
for (int col = 0; col < cols; col++) {
contents [row, col, 2] = 0;
var color = contents [row, col, 1];
if (color != redrawColor)
SetColor (color);
FakeConsole.Write ((char)contents [row, col, 0]);
}
}
}
public override void Refresh ()
{
int rows = Rows;
int cols = Cols;
var savedRow = FakeConsole.CursorTop;
var savedCol = FakeConsole.CursorLeft;
for (int row = 0; row < rows; row++) {
if (!dirtyLine [row])
continue;
dirtyLine [row] = false;
for (int col = 0; col < cols; col++) {
if (contents [row, col, 2] != 1)
continue;
FakeConsole.CursorTop = row;
FakeConsole.CursorLeft = col;
for (; col < cols && contents [row, col, 2] == 1; col++) {
var color = contents [row, col, 1];
if (color != redrawColor)
SetColor (color);
FakeConsole.Write ((char)contents [row, col, 0]);
contents [row, col, 2] = 0;
}
}
}
FakeConsole.CursorTop = savedRow;
FakeConsole.CursorLeft = savedCol;
}
public override void UpdateCursor ()
{
//
}
public override void StartReportingMouseMoves ()
{
}
public override void StopReportingMouseMoves ()
{
}
public override void Suspend ()
{
}
int currentAttribute;
public override void SetAttribute (Attribute c)
{
currentAttribute = c.Value;
}
Key MapKey (ConsoleKeyInfo keyInfo)
{
switch (keyInfo.Key) {
case ConsoleKey.Escape:
return MapKeyModifiers (keyInfo, Key.Esc);
case ConsoleKey.Tab:
return keyInfo.Modifiers == ConsoleModifiers.Shift ? Key.BackTab : Key.Tab;
case ConsoleKey.Home:
return MapKeyModifiers (keyInfo, Key.Home);
case ConsoleKey.End:
return MapKeyModifiers (keyInfo, Key.End);
case ConsoleKey.LeftArrow:
return MapKeyModifiers (keyInfo, Key.CursorLeft);
case ConsoleKey.RightArrow:
return MapKeyModifiers (keyInfo, Key.CursorRight);
case ConsoleKey.UpArrow:
return MapKeyModifiers (keyInfo, Key.CursorUp);
case ConsoleKey.DownArrow:
return MapKeyModifiers (keyInfo, Key.CursorDown);
case ConsoleKey.PageUp:
return MapKeyModifiers (keyInfo, Key.PageUp);
case ConsoleKey.PageDown:
return MapKeyModifiers (keyInfo, Key.PageDown);
case ConsoleKey.Enter:
return MapKeyModifiers (keyInfo, Key.Enter);
case ConsoleKey.Spacebar:
return MapKeyModifiers (keyInfo, keyInfo.KeyChar == 0 ? Key.Space : (Key)keyInfo.KeyChar);
case ConsoleKey.Backspace:
return MapKeyModifiers (keyInfo, Key.Backspace);
case ConsoleKey.Delete:
return MapKeyModifiers (keyInfo, Key.DeleteChar);
case ConsoleKey.Insert:
return MapKeyModifiers (keyInfo, Key.InsertChar);
case ConsoleKey.Oem1:
case ConsoleKey.Oem2:
case ConsoleKey.Oem3:
case ConsoleKey.Oem4:
case ConsoleKey.Oem5:
case ConsoleKey.Oem6:
case ConsoleKey.Oem7:
case ConsoleKey.Oem8:
case ConsoleKey.Oem102:
case ConsoleKey.OemPeriod:
case ConsoleKey.OemComma:
case ConsoleKey.OemPlus:
case ConsoleKey.OemMinus:
if (keyInfo.KeyChar == 0)
return Key.Unknown;
return (Key)((uint)keyInfo.KeyChar);
}
var key = keyInfo.Key;
if (key >= ConsoleKey.A && key <= ConsoleKey.Z) {
var delta = key - ConsoleKey.A;
if (keyInfo.Modifiers == ConsoleModifiers.Control) {
return (Key)(((uint)Key.CtrlMask) | ((uint)Key.A + delta));
}
if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
return (Key)(((uint)Key.AltMask) | ((uint)Key.A + delta));
}
if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
if (keyInfo.KeyChar == 0) {
return (Key)(((uint)Key.AltMask | (uint)Key.CtrlMask) | ((uint)Key.A + delta));
} else {
return (Key)((uint)keyInfo.KeyChar);
}
}
return (Key)((uint)keyInfo.KeyChar);
}
if (key >= ConsoleKey.D0 && key <= ConsoleKey.D9) {
var delta = key - ConsoleKey.D0;
if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
return (Key)(((uint)Key.AltMask) | ((uint)Key.D0 + delta));
}
if (keyInfo.Modifiers == ConsoleModifiers.Control) {
return (Key)(((uint)Key.CtrlMask) | ((uint)Key.D0 + delta));
}
if (keyInfo.KeyChar == 0 || keyInfo.KeyChar == 30) {
return MapKeyModifiers (keyInfo, (Key)((uint)Key.D0 + delta));
}
return (Key)((uint)keyInfo.KeyChar);
}
if (key >= ConsoleKey.F1 && key <= ConsoleKey.F12) {
var delta = key - ConsoleKey.F1;
if ((keyInfo.Modifiers & (ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
return MapKeyModifiers (keyInfo, (Key)((uint)Key.F1 + delta));
}
return (Key)((uint)Key.F1 + delta);
}
if (keyInfo.KeyChar != 0) {
return MapKeyModifiers (keyInfo, (Key)((uint)keyInfo.KeyChar));
}
return (Key)(0xffffffff);
}
KeyModifiers keyModifiers;
private Key MapKeyModifiers (ConsoleKeyInfo keyInfo, Key key)
{
Key keyMod = new Key ();
if ((keyInfo.Modifiers & ConsoleModifiers.Shift) != 0)
keyMod = Key.ShiftMask;
if ((keyInfo.Modifiers & ConsoleModifiers.Control) != 0)
keyMod |= Key.CtrlMask;
if ((keyInfo.Modifiers & ConsoleModifiers.Alt) != 0)
keyMod |= Key.AltMask;
return keyMod != Key.Null ? keyMod | key : key;
}
Action<KeyEvent> keyHandler;
Action<KeyEvent> keyUpHandler;
public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
{
this.keyHandler = keyHandler;
this.keyUpHandler = keyUpHandler;
// Note: Net doesn't support keydown/up events and thus any passed keyDown/UpHandlers will never be called
(mainLoop.Driver as FakeMainLoop).KeyPressed += (consoleKey) => ProcessInput (consoleKey);
}
void ProcessInput (ConsoleKeyInfo consoleKey)
{
var map = MapKey (consoleKey);
if (map == (Key)0xffffffff)
return;
if (keyModifiers == null) {
keyModifiers = new KeyModifiers ();
}
if (consoleKey.Modifiers.HasFlag (ConsoleModifiers.Alt)) {
keyModifiers.Alt = true;
}
if (consoleKey.Modifiers.HasFlag (ConsoleModifiers.Shift)) {
keyModifiers.Shift = true;
}
if (consoleKey.Modifiers.HasFlag (ConsoleModifiers.Control)) {
keyModifiers.Ctrl = true;
}
keyHandler (new KeyEvent (map, keyModifiers));
keyUpHandler (new KeyEvent (map, keyModifiers));
keyModifiers = new KeyModifiers ();
}
public override Attribute GetAttribute ()
{
return currentAttribute;
}
/// <inheritdoc/>
public override bool GetCursorVisibility (out CursorVisibility visibility)
{
visibility = CursorVisibility.Default;
return false;
}
/// <inheritdoc/>
public override bool SetCursorVisibility (CursorVisibility visibility)
{
return false;
}
/// <inheritdoc/>
public override bool EnsureCursorVisibility ()
{
return false;
}
public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control)
{
ProcessInput (new ConsoleKeyInfo (keyChar, key, shift, alt, control));
}
#region Unused
public override void SetColors (ConsoleColor foreground, ConsoleColor background)
{
}
public override void SetColors (short foregroundColorId, short backgroundColorId)
{
throw new NotImplementedException ();
}
public override void CookMouse ()
{
}
public override void UncookMouse ()
{
}
#endregion
#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
}
}