123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449 |
- //
- // NetDriver.cs: The System.Console-based .NET driver, works on Windows and Unix, but is not particularly efficient.
- //
- // Authors:
- // Miguel de Icaza ([email protected])
- //
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading;
- using NStack;
- namespace Terminal.Gui {
- internal class NetDriver : ConsoleDriver {
- int cols, rows;
- public override int Cols => cols;
- public override int Rows => rows;
- // The format is rows, columns and 3 values on the last column: Rune, Attribute and Dirty Flag
- int [,,] contents;
- bool [] dirtyLine;
- 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 NetDriver ()
- {
- cols = Console.WindowWidth;
- rows = Console.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)) {
- Console.CursorTop = row;
- Console.CursorLeft = col;
- needMove = false;
- } else {
- Console.CursorTop = Clip.Y;
- Console.CursorLeft = Clip.X;
- needMove = true;
- }
- }
- public override void AddRune (Rune rune)
- {
- rune = MakePrintable (rune);
- if (Clip.Contains (ccol, crow)) {
- if (needMove) {
- //Console.CursorLeft = ccol;
- //Console.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 ()
- {
- Console.ResetColor ();
- Console.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) };
- }
- 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;
- Console.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)) {
- Console.BackgroundColor = (ConsoleColor)(color & 0xffff);
- }
- if (values.Contains ((color >> 16) & 0xffff)) {
- Console.ForegroundColor = (ConsoleColor)((color >> 16) & 0xffff);
- }
- }
- public override void UpdateScreen ()
- {
- int rows = Rows;
- int cols = Cols;
- Console.CursorTop = 0;
- Console.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);
- Console.Write ((char)contents [row, col, 0]);
- }
- }
- }
- public override void Refresh ()
- {
- int rows = Rows;
- int cols = Cols;
- var savedRow = Console.CursorTop;
- var savedCol = Console.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;
- Console.CursorTop = row;
- Console.CursorLeft = col;
- for (; col < cols && contents [row, col, 2] == 1; col++) {
- var color = contents [row, col, 1];
- if (color != redrawColor)
- SetColor (color);
- Console.Write ((char)contents [row, col, 0]);
- contents [row, col, 2] = 0;
- }
- }
- }
- Console.CursorTop = savedRow;
- Console.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 Key.Esc;
- case ConsoleKey.Tab:
- return keyInfo.Modifiers == ConsoleModifiers.Shift ? Key.BackTab : Key.Tab;
- case ConsoleKey.Home:
- return Key.Home;
- case ConsoleKey.End:
- return Key.End;
- case ConsoleKey.LeftArrow:
- return Key.CursorLeft;
- case ConsoleKey.RightArrow:
- return Key.CursorRight;
- case ConsoleKey.UpArrow:
- return Key.CursorUp;
- case ConsoleKey.DownArrow:
- return Key.CursorDown;
- case ConsoleKey.PageUp:
- return Key.PageUp;
- case ConsoleKey.PageDown:
- return Key.PageDown;
- case ConsoleKey.Enter:
- return Key.Enter;
- case ConsoleKey.Spacebar:
- return Key.Space;
- case ConsoleKey.Backspace:
- return Key.Backspace;
- case ConsoleKey.Delete:
- return Key.Delete;
- 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:
- 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.A + delta);
- if (keyInfo.Modifiers == ConsoleModifiers.Alt)
- return (Key)(((uint)Key.AltMask) | ((uint)Key.A + delta));
- if (keyInfo.Modifiers == ConsoleModifiers.Shift)
- return (Key)((uint)Key.A + delta);
- else
- return (Key)((uint)'a' + delta);
- }
- 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.Shift)
- return (Key)((uint)keyInfo.KeyChar);
- return (Key)((uint)Key.D0 + delta);
- }
- if (key >= ConsoleKey.F1 && key <= ConsoleKey.F10) {
- var delta = key - ConsoleKey.F1;
- return (Key)((int)Key.F1 + delta);
- }
- return (Key)(0xffffffff);
- }
- KeyModifiers keyModifiers = new KeyModifiers ();
- public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
- {
- // Note: Net doesn't support keydown/up events and thus any passed keyDown/UpHandlers will never be called
- (mainLoop.Driver as NetMainLoop).KeyPressed = delegate (ConsoleKeyInfo consoleKey) {
- var map = MapKey (consoleKey);
- if (map == (Key)0xffffffff)
- return;
- keyHandler (new KeyEvent (map, keyModifiers));
- keyUpHandler (new KeyEvent (map, keyModifiers));
- };
- }
- public override void SetColors (ConsoleColor foreground, ConsoleColor background)
- {
- throw new NotImplementedException ();
- }
- public override void SetColors (short foregroundColorId, short backgroundColorId)
- {
- throw new NotImplementedException ();
- }
- public override void CookMouse ()
- {
- }
- public override void UncookMouse ()
- {
- }
- //
- // These are for the .NET driver, but running natively on Windows, wont run
- // on the Mono emulation
- //
- }
- /// <summary>
- /// Mainloop intended to be used with the .NET System.Console API, and can
- /// be used on Windows and Unix, it is cross platform but lacks things like
- /// file descriptor monitoring.
- /// </summary>
- /// <remarks>
- /// This implementation is used for both NetDriver and FakeDriver.
- /// </remarks>
- public class NetMainLoop : IMainLoopDriver {
- AutoResetEvent keyReady = new AutoResetEvent (false);
- AutoResetEvent waitForProbe = new AutoResetEvent (false);
- ConsoleKeyInfo? keyResult = null;
- MainLoop mainLoop;
- Func<ConsoleKeyInfo> consoleKeyReaderFn = null;
- /// <summary>
- /// Invoked when a Key is pressed.
- /// </summary>
- public Action<ConsoleKeyInfo> KeyPressed;
- /// <summary>
- /// Initializes the class.
- /// </summary>
- /// <remarks>
- /// Passing a consoleKeyReaderfn is provided to support unit test sceanrios.
- /// </remarks>
- /// <param name="consoleKeyReaderFn">The method to be called to get a key from the console.</param>
- public NetMainLoop (Func<ConsoleKeyInfo> consoleKeyReaderFn = null)
- {
- if (consoleKeyReaderFn == null) {
- throw new ArgumentNullException ("key reader function must be provided.");
- }
- this.consoleKeyReaderFn = consoleKeyReaderFn;
- }
- void WindowsKeyReader ()
- {
- while (true) {
- waitForProbe.WaitOne ();
- keyResult = consoleKeyReaderFn();
- keyReady.Set ();
- }
- }
- void IMainLoopDriver.Setup (MainLoop mainLoop)
- {
- this.mainLoop = mainLoop;
- Thread readThread = new Thread (WindowsKeyReader);
- readThread.Start ();
- }
- void IMainLoopDriver.Wakeup ()
- {
- }
- bool IMainLoopDriver.EventsPending (bool wait)
- {
- long now = DateTime.UtcNow.Ticks;
- int waitTimeout;
- if (mainLoop.timeouts.Count > 0) {
- waitTimeout = (int)((mainLoop.timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
- if (waitTimeout < 0)
- return true;
- } else
- waitTimeout = -1;
- if (!wait)
- waitTimeout = 0;
- keyResult = null;
- waitForProbe.Set ();
- keyReady.WaitOne (waitTimeout);
- return keyResult.HasValue;
- }
- void IMainLoopDriver.MainIteration ()
- {
- if (keyResult.HasValue) {
- KeyPressed?.Invoke (keyResult.Value);
- keyResult = null;
- }
- }
- }
- }
|