12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511 |
- //
- // WindowsDriver.cs: Windows specific driver
- //
- // Authors:
- // Miguel de Icaza ([email protected])
- // Nick Van Dyck ([email protected])
- //
- // Copyright (c) 2018
- //
- // Permission is hereby granted, free of charge, to any person obtaining a copy
- // of this software and associated documentation files (the "Software"), to deal
- // in the Software without restriction, including without limitation the rights
- // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- // copies of the Software, and to permit persons to whom the Software is
- // furnished to do so, subject to the following conditions:
- //
- // The above copyright notice and this permission notice shall be included in all
- // copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- // SOFTWARE.
- //
- using NStack;
- using System;
- using System.Runtime.InteropServices;
- using System.Threading;
- using System.Threading.Tasks;
- namespace Terminal.Gui {
- internal class WindowsConsole {
- public const int STD_OUTPUT_HANDLE = -11;
- public const int STD_INPUT_HANDLE = -10;
- public const int STD_ERROR_HANDLE = -12;
- internal IntPtr InputHandle, OutputHandle;
- IntPtr ScreenBuffer;
- uint originalConsoleMode;
- public WindowsConsole ()
- {
- InputHandle = GetStdHandle (STD_INPUT_HANDLE);
- OutputHandle = GetStdHandle (STD_OUTPUT_HANDLE);
- originalConsoleMode = ConsoleMode;
- var newConsoleMode = originalConsoleMode;
- newConsoleMode |= (uint)(ConsoleModes.EnableMouseInput | ConsoleModes.EnableExtendedFlags);
- newConsoleMode &= ~(uint)ConsoleModes.EnableQuickEditMode;
- newConsoleMode &= ~(uint)ConsoleModes.EnableProcessedInput;
- ConsoleMode = newConsoleMode;
- }
- public CharInfo [] OriginalStdOutChars;
- public bool WriteToConsole (CharInfo [] charInfoBuffer, Coord coords, SmallRect window)
- {
- if (ScreenBuffer == IntPtr.Zero) {
- ScreenBuffer = CreateConsoleScreenBuffer (
- DesiredAccess.GenericRead | DesiredAccess.GenericWrite,
- ShareMode.FileShareRead | ShareMode.FileShareWrite,
- IntPtr.Zero,
- 1,
- IntPtr.Zero
- );
- if (ScreenBuffer == INVALID_HANDLE_VALUE) {
- var err = Marshal.GetLastWin32Error ();
- if (err != 0)
- throw new System.ComponentModel.Win32Exception (err);
- }
- if (!SetConsoleActiveScreenBuffer (ScreenBuffer)) {
- var err = Marshal.GetLastWin32Error ();
- throw new System.ComponentModel.Win32Exception (err);
- }
- OriginalStdOutChars = new CharInfo [Console.WindowHeight * Console.WindowWidth];
- ReadConsoleOutput (OutputHandle, OriginalStdOutChars, coords, new Coord () { X = 0, Y = 0 }, ref window);
- }
- return WriteConsoleOutput (ScreenBuffer, charInfoBuffer, coords, new Coord () { X = window.Left, Y = window.Top }, ref window);
- }
- public void ReadFromConsoleOutput (Size size, Coord coords)
- {
- ScreenBuffer = CreateConsoleScreenBuffer (
- DesiredAccess.GenericRead | DesiredAccess.GenericWrite,
- ShareMode.FileShareRead | ShareMode.FileShareWrite,
- IntPtr.Zero,
- 1,
- IntPtr.Zero
- );
- if (ScreenBuffer == INVALID_HANDLE_VALUE) {
- var err = Marshal.GetLastWin32Error ();
- if (err != 0)
- throw new System.ComponentModel.Win32Exception (err);
- }
- if (!SetConsoleActiveScreenBuffer (ScreenBuffer)) {
- var err = Marshal.GetLastWin32Error ();
- throw new System.ComponentModel.Win32Exception (err);
- }
- OriginalStdOutChars = new CharInfo [size.Height * size.Width];
- SmallRect window = new SmallRect ();
- ReadConsoleOutput (OutputHandle, OriginalStdOutChars, coords, new Coord () { X = 0, Y = 0 }, ref window);
- }
- public bool SetCursorPosition (Coord position)
- {
- return SetConsoleCursorPosition (ScreenBuffer, position);
- }
- public void Cleanup ()
- {
- ConsoleMode = originalConsoleMode;
- //ContinueListeningForConsoleEvents = false;
- if (!SetConsoleActiveScreenBuffer (OutputHandle)) {
- var err = Marshal.GetLastWin32Error ();
- Console.WriteLine ("Error: {0}", err);
- }
- if (ScreenBuffer != IntPtr.Zero)
- CloseHandle (ScreenBuffer);
- ScreenBuffer = IntPtr.Zero;
- }
- //bool ContinueListeningForConsoleEvents = true;
- public uint ConsoleMode {
- get {
- uint v;
- GetConsoleMode (InputHandle, out v);
- return v;
- }
- set {
- SetConsoleMode (InputHandle, value);
- }
- }
- [Flags]
- public enum ConsoleModes : uint {
- EnableProcessedInput = 1,
- EnableMouseInput = 16,
- EnableQuickEditMode = 64,
- EnableExtendedFlags = 128,
- }
- [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
- public struct KeyEventRecord {
- [FieldOffset (0), MarshalAs (UnmanagedType.Bool)]
- public bool bKeyDown;
- [FieldOffset (4), MarshalAs (UnmanagedType.U2)]
- public ushort wRepeatCount;
- [FieldOffset (6), MarshalAs (UnmanagedType.U2)]
- public ushort wVirtualKeyCode;
- [FieldOffset (8), MarshalAs (UnmanagedType.U2)]
- public ushort wVirtualScanCode;
- [FieldOffset (10)]
- public char UnicodeChar;
- [FieldOffset (12), MarshalAs (UnmanagedType.U4)]
- public ControlKeyState dwControlKeyState;
- }
- [Flags]
- public enum ButtonState {
- Button1Pressed = 1,
- Button2Pressed = 4,
- Button3Pressed = 8,
- Button4Pressed = 16,
- RightmostButtonPressed = 2,
- WheeledUp = unchecked((int)0x780000),
- WheeledDown = unchecked((int)0xFF880000),
- }
- [Flags]
- public enum ControlKeyState {
- RightAltPressed = 1,
- LeftAltPressed = 2,
- RightControlPressed = 4,
- LeftControlPressed = 8,
- ShiftPressed = 16,
- NumlockOn = 32,
- ScrolllockOn = 64,
- CapslockOn = 128,
- EnhancedKey = 256
- }
- [Flags]
- public enum EventFlags {
- MouseMoved = 1,
- DoubleClick = 2,
- MouseWheeled = 4,
- MouseHorizontalWheeled = 8
- }
- [StructLayout (LayoutKind.Explicit)]
- public struct MouseEventRecord {
- [FieldOffset (0)]
- public Coordinate MousePosition;
- [FieldOffset (4)]
- public ButtonState ButtonState;
- [FieldOffset (8)]
- public ControlKeyState ControlKeyState;
- [FieldOffset (12)]
- public EventFlags EventFlags;
- public override string ToString ()
- {
- return $"[Mouse({MousePosition},{ButtonState},{ControlKeyState},{EventFlags}";
- }
- }
- [StructLayout (LayoutKind.Sequential)]
- public struct Coordinate {
- public short X;
- public short Y;
- public Coordinate (short X, short Y)
- {
- this.X = X;
- this.Y = Y;
- }
- public override string ToString () => $"({X},{Y})";
- };
- public struct WindowBufferSizeRecord {
- public Coordinate size;
- public WindowBufferSizeRecord (short x, short y)
- {
- this.size = new Coordinate (x, y);
- }
- public override string ToString () => $"[WindowBufferSize{size}";
- }
- [StructLayout (LayoutKind.Sequential)]
- public struct MenuEventRecord {
- public uint dwCommandId;
- }
- [StructLayout (LayoutKind.Sequential)]
- public struct FocusEventRecord {
- public uint bSetFocus;
- }
- public enum EventType : ushort {
- Focus = 0x10,
- Key = 0x1,
- Menu = 0x8,
- Mouse = 2,
- WindowBufferSize = 4
- }
- [StructLayout (LayoutKind.Explicit)]
- public struct InputRecord {
- [FieldOffset (0)]
- public EventType EventType;
- [FieldOffset (4)]
- public KeyEventRecord KeyEvent;
- [FieldOffset (4)]
- public MouseEventRecord MouseEvent;
- [FieldOffset (4)]
- public WindowBufferSizeRecord WindowBufferSizeEvent;
- [FieldOffset (4)]
- public MenuEventRecord MenuEvent;
- [FieldOffset (4)]
- public FocusEventRecord FocusEvent;
- public override string ToString ()
- {
- switch (EventType) {
- case EventType.Focus:
- return FocusEvent.ToString ();
- case EventType.Key:
- return KeyEvent.ToString ();
- case EventType.Menu:
- return MenuEvent.ToString ();
- case EventType.Mouse:
- return MouseEvent.ToString ();
- case EventType.WindowBufferSize:
- return WindowBufferSizeEvent.ToString ();
- default:
- return "Unknown event type: " + EventType;
- }
- }
- };
- [Flags]
- enum ShareMode : uint {
- FileShareRead = 1,
- FileShareWrite = 2,
- }
- [Flags]
- enum DesiredAccess : uint {
- GenericRead = 2147483648,
- GenericWrite = 1073741824,
- }
- [StructLayout (LayoutKind.Sequential)]
- public struct ConsoleScreenBufferInfo {
- public Coord dwSize;
- public Coord dwCursorPosition;
- public ushort wAttributes;
- public SmallRect srWindow;
- public Coord dwMaximumWindowSize;
- }
- [StructLayout (LayoutKind.Sequential)]
- public struct Coord {
- public short X;
- public short Y;
- public Coord (short X, short Y)
- {
- this.X = X;
- this.Y = Y;
- }
- public override string ToString () => $"({X},{Y})";
- };
- [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
- public struct CharUnion {
- [FieldOffset (0)] public char UnicodeChar;
- [FieldOffset (0)] public byte AsciiChar;
- }
- [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
- public struct CharInfo {
- [FieldOffset (0)] public CharUnion Char;
- [FieldOffset (2)] public ushort Attributes;
- }
- [StructLayout (LayoutKind.Sequential)]
- public struct SmallRect {
- public short Left;
- public short Top;
- public short Right;
- public short Bottom;
- public static void MakeEmpty (ref SmallRect rect)
- {
- rect.Left = -1;
- }
- public static void Update (ref SmallRect rect, short col, short row)
- {
- if (rect.Left == -1) {
- //System.Diagnostics.Debugger.Log (0, "debug", $"damager From Empty {col},{row}\n");
- rect.Left = rect.Right = col;
- rect.Bottom = rect.Top = row;
- return;
- }
- if (col >= rect.Left && col <= rect.Right && row >= rect.Top && row <= rect.Bottom)
- return;
- if (col < rect.Left)
- rect.Left = col;
- if (col > rect.Right)
- rect.Right = col;
- if (row < rect.Top)
- rect.Top = row;
- if (row > rect.Bottom)
- rect.Bottom = row;
- //System.Diagnostics.Debugger.Log (0, "debug", $"Expanding {rect.ToString ()}\n");
- }
- public override string ToString ()
- {
- return $"Left={Left},Top={Top},Right={Right},Bottom={Bottom}";
- }
- }
- [StructLayout (LayoutKind.Sequential)]
- public struct ConsoleKeyInfoEx {
- public ConsoleKeyInfo consoleKeyInfo;
- public bool CapsLock;
- public bool NumLock;
- public ConsoleKeyInfoEx (ConsoleKeyInfo consoleKeyInfo, bool capslock, bool numlock)
- {
- this.consoleKeyInfo = consoleKeyInfo;
- CapsLock = capslock;
- NumLock = numlock;
- }
- }
- [DllImport ("kernel32.dll", SetLastError = true)]
- static extern IntPtr GetStdHandle (int nStdHandle);
- [DllImport ("kernel32.dll", SetLastError = true)]
- static extern bool CloseHandle (IntPtr handle);
- [DllImport ("kernel32.dll", EntryPoint = "ReadConsoleInputW", CharSet = CharSet.Unicode)]
- public static extern bool ReadConsoleInput (
- IntPtr hConsoleInput,
- IntPtr lpBuffer,
- uint nLength,
- out uint lpNumberOfEventsRead);
- [DllImport ("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
- static extern bool ReadConsoleOutput (
- IntPtr hConsoleOutput,
- [Out] CharInfo [] lpBuffer,
- Coord dwBufferSize,
- Coord dwBufferCoord,
- ref SmallRect lpReadRegion
- );
- [DllImport ("kernel32.dll", EntryPoint = "WriteConsoleOutput", SetLastError = true, CharSet = CharSet.Unicode)]
- static extern bool WriteConsoleOutput (
- IntPtr hConsoleOutput,
- CharInfo [] lpBuffer,
- Coord dwBufferSize,
- Coord dwBufferCoord,
- ref SmallRect lpWriteRegion
- );
- [DllImport ("kernel32.dll")]
- static extern bool SetConsoleCursorPosition (IntPtr hConsoleOutput, Coord dwCursorPosition);
- [DllImport ("kernel32.dll")]
- static extern bool GetConsoleMode (IntPtr hConsoleHandle, out uint lpMode);
- [DllImport ("kernel32.dll")]
- static extern bool SetConsoleMode (IntPtr hConsoleHandle, uint dwMode);
- [DllImport ("kernel32.dll", SetLastError = true)]
- static extern IntPtr CreateConsoleScreenBuffer (
- DesiredAccess dwDesiredAccess,
- ShareMode dwShareMode,
- IntPtr secutiryAttributes,
- UInt32 flags,
- IntPtr screenBufferData
- );
- internal static IntPtr INVALID_HANDLE_VALUE = new IntPtr (-1);
- [DllImport ("kernel32.dll", SetLastError = true)]
- static extern bool SetConsoleActiveScreenBuffer (IntPtr Handle);
- [DllImport ("kernel32.dll", SetLastError = true)]
- static extern bool GetNumberOfConsoleInputEvents (IntPtr handle, out uint lpcNumberOfEvents);
- public uint InputEventCount {
- get {
- uint v;
- GetNumberOfConsoleInputEvents (InputHandle, out v);
- return v;
- }
- }
- public InputRecord [] ReadConsoleInput ()
- {
- const int bufferSize = 1;
- var pRecord = Marshal.AllocHGlobal (Marshal.SizeOf<InputRecord> () * bufferSize);
- try {
- ReadConsoleInput (InputHandle, pRecord, bufferSize,
- out var numberEventsRead);
- return numberEventsRead == 0
- ? null
- : new [] { Marshal.PtrToStructure<InputRecord> (pRecord) };
- } catch (Exception) {
- return null;
- } finally {
- Marshal.FreeHGlobal (pRecord);
- }
- }
- // Not needed on the constructor. Perhaps could be used on resizing. To study.
- [DllImport ("kernel32.dll", ExactSpelling = true)]
- static extern IntPtr GetConsoleWindow ();
- [DllImport ("user32.dll")]
- [return: MarshalAs (UnmanagedType.Bool)]
- static extern bool GetWindowPlacement (IntPtr hWnd, ref WindowPlacement lpwndpl);
- [DllImport ("user32.dll", SetLastError = true)]
- [return: MarshalAs (UnmanagedType.Bool)]
- static extern bool SetWindowPlacement (IntPtr hWnd, [In] ref WindowPlacement lpwndpl);
- internal struct WindowPlacement {
- public int length;
- public int flags;
- public int showCmd;
- public System.Drawing.Point ptMinPosition;
- public System.Drawing.Point ptMaxPosition;
- public System.Drawing.Rectangle rcNormalPosition;
- public System.Drawing.Rectangle rcDevice;
- }
- // flags
- public const int WPF_SET_MIN_POSITION = 1;
- public const int WPF_RESTORE_TO_MAXIMIZED = 2;
- public const int WPF_ASYNC_WINDOWPLACEMENT = 4;
- // showCmd
- public const int HIDE = 0;
- public const int NORMAL = 1;
- public const int SHOW_MINIMIZED = 2;
- public const int SHOW_MAXIMIZED = 3;
- public const int SHOW_NOACTIVATE = 4;
- public const int SHOW = 5;
- public const int MINIMIZE = 6;
- public const int SHOW_MIN_NOACTIVE = 7;
- public const int SHOW_NA = 8;
- public const int RESTORE = 9;
- public const int SHOW_DEFAULT = 10;
- public const int FORCE_MINIMIZE = 11;
- internal WindowPlacement GetWindow ()
- {
- IntPtr thisConsole = GetConsoleWindow ();
- WindowPlacement placement = new WindowPlacement {
- length = Marshal.SizeOf (typeof (WindowPlacement))
- };
- GetWindowPlacement (thisConsole, ref placement);
- return placement;
- }
- internal void SetWindow (int showCmd)
- {
- IntPtr thisConsole = GetConsoleWindow ();
- WindowPlacement placement = new WindowPlacement {
- length = Marshal.SizeOf (typeof (WindowPlacement)),
- showCmd = showCmd
- };
- SetWindowPlacement (thisConsole, ref placement);
- }
- #if false
- [DllImport ("kernel32.dll", SetLastError = true)]
- static extern bool GetConsoleScreenBufferInfo (IntPtr hConsoleOutput, out ConsoleScreenBufferInfo ConsoleScreenBufferInfo);
- // Theoretically GetConsoleScreenBuffer height should give the console Window size, but the Top is always 0.
- // It does not work, however, and always returns the size the window was initially created at
- internal Size GetWindowSize (IntPtr handle)
- {
- GetConsoleScreenBufferInfo (handle, out ConsoleScreenBufferInfo consoleScreenBufferInfo);
- return new Size (consoleScreenBufferInfo.srWindow.Right - consoleScreenBufferInfo.srWindow.Left + 1,
- consoleScreenBufferInfo.srWindow.Bottom - consoleScreenBufferInfo.srWindow.Top + 1);
- }
- #endif
- }
- internal class WindowsDriver : ConsoleDriver {
- static bool sync = false;
- WindowsConsole.CharInfo [] OutputBuffer;
- int cols, rows, top;
- WindowsConsole winConsole;
- WindowsConsole.SmallRect damageRegion;
- public override int Cols => cols;
- public override int Rows => rows;
- public override int Top => top;
- public override bool HeightAsBuffer { get; set; }
- public WindowsConsole WinConsole {
- get => winConsole;
- private set => winConsole = value;
- }
- Action<KeyEvent> keyHandler;
- Action<KeyEvent> keyDownHandler;
- Action<KeyEvent> keyUpHandler;
- Action<MouseEvent> mouseHandler;
- public WindowsDriver ()
- {
- winConsole = new WindowsConsole ();
- }
- bool winChanging;
- public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
- {
- this.keyHandler = keyHandler;
- this.keyDownHandler = keyDownHandler;
- this.keyUpHandler = keyUpHandler;
- this.mouseHandler = mouseHandler;
- var mLoop = mainLoop.Driver as WindowsMainLoop;
- mLoop.ProcessInput = (e) => ProcessInput (e);
- mLoop.WinChanged = (e) => ChangeWin (e);
- }
- void ChangeWin (Size size)
- {
- if (!HeightAsBuffer) {
- winChanging = true;
- top = 0;
- cols = size.Width;
- rows = size.Height;
- var bufferCoords = new WindowsConsole.Coord () {
- X = (short)cols,
- Y = (short)rows
- };
- winConsole.ReadFromConsoleOutput (size, bufferCoords);
- ResizeScreen ();
- UpdateOffScreen ();
- if (!winChanging) {
- TerminalResized.Invoke ();
- } else {
- System.Diagnostics.Debugger.Break ();
- }
- }
- }
- void ProcessInput (WindowsConsole.InputRecord inputEvent)
- {
- switch (inputEvent.EventType) {
- case WindowsConsole.EventType.Key:
- var map = MapKey (ToConsoleKeyInfoEx (inputEvent.KeyEvent));
- if (map == (Key)0xffffffff) {
- KeyEvent key = new KeyEvent ();
- // Shift = VK_SHIFT = 0x10
- // Ctrl = VK_CONTROL = 0x11
- // Alt = VK_MENU = 0x12
- if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.CapslockOn)) {
- inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.CapslockOn;
- }
- if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ScrolllockOn)) {
- inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.ScrolllockOn;
- }
- if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.NumlockOn)) {
- inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.NumlockOn;
- }
- switch (inputEvent.KeyEvent.dwControlKeyState) {
- case WindowsConsole.ControlKeyState.RightAltPressed:
- case WindowsConsole.ControlKeyState.RightAltPressed |
- WindowsConsole.ControlKeyState.LeftControlPressed |
- WindowsConsole.ControlKeyState.EnhancedKey:
- case WindowsConsole.ControlKeyState.EnhancedKey:
- key = new KeyEvent (Key.CtrlMask | Key.AltMask, keyModifiers);
- break;
- case WindowsConsole.ControlKeyState.LeftAltPressed:
- key = new KeyEvent (Key.AltMask, keyModifiers);
- break;
- case WindowsConsole.ControlKeyState.RightControlPressed:
- case WindowsConsole.ControlKeyState.LeftControlPressed:
- key = new KeyEvent (Key.CtrlMask, keyModifiers);
- break;
- case WindowsConsole.ControlKeyState.ShiftPressed:
- key = new KeyEvent (Key.ShiftMask, keyModifiers);
- break;
- case WindowsConsole.ControlKeyState.NumlockOn:
- break;
- case WindowsConsole.ControlKeyState.ScrolllockOn:
- break;
- case WindowsConsole.ControlKeyState.CapslockOn:
- break;
- default:
- switch (inputEvent.KeyEvent.wVirtualKeyCode) {
- case 0x10:
- key = new KeyEvent (Key.ShiftMask, keyModifiers);
- break;
- case 0x11:
- key = new KeyEvent (Key.CtrlMask, keyModifiers);
- break;
- case 0x12:
- key = new KeyEvent (Key.AltMask, keyModifiers);
- break;
- default:
- key = new KeyEvent (Key.Unknown, keyModifiers);
- break;
- }
- break;
- }
- if (inputEvent.KeyEvent.bKeyDown)
- keyDownHandler (key);
- else
- keyUpHandler (key);
- } else {
- if (inputEvent.KeyEvent.bKeyDown) {
- // Key Down - Fire KeyDown Event and KeyStroke (ProcessKey) Event
- keyDownHandler (new KeyEvent (map, keyModifiers));
- keyHandler (new KeyEvent (map, keyModifiers));
- } else {
- keyUpHandler (new KeyEvent (map, keyModifiers));
- }
- }
- if (!inputEvent.KeyEvent.bKeyDown) {
- keyModifiers = null;
- }
- break;
- case WindowsConsole.EventType.Mouse:
- mouseHandler (ToDriverMouse (inputEvent.MouseEvent));
- if (IsButtonReleased)
- mouseHandler (ToDriverMouse (inputEvent.MouseEvent));
- break;
- case WindowsConsole.EventType.WindowBufferSize:
- if (HeightAsBuffer) {
- cols = inputEvent.WindowBufferSizeEvent.size.X;
- rows = inputEvent.WindowBufferSizeEvent.size.Y;
- ResizeScreen ();
- UpdateOffScreen ();
- TerminalResized?.Invoke ();
- }
- break;
- case WindowsConsole.EventType.Focus:
- break;
- }
- }
- WindowsConsole.ButtonState? LastMouseButtonPressed = null;
- bool IsButtonPressed = false;
- bool IsButtonReleased = false;
- bool IsButtonDoubleClicked = false;
- Point point;
- MouseEvent ToDriverMouse (WindowsConsole.MouseEventRecord mouseEvent)
- {
- MouseFlags mouseFlag = MouseFlags.AllEvents;
- if (IsButtonDoubleClicked) {
- Application.MainLoop.AddIdle (() => {
- ProcessButtonDoubleClickedAsync ().ConfigureAwait (false);
- return false;
- });
- }
- // The ButtonState member of the MouseEvent structure has bit corresponding to each mouse button.
- // This will tell when a mouse button is pressed. When the button is released this event will
- // be fired with it's bit set to 0. So when the button is up ButtonState will be 0.
- // To map to the correct driver events we save the last pressed mouse button so we can
- // map to the correct clicked event.
- if ((LastMouseButtonPressed != null || IsButtonReleased) && mouseEvent.ButtonState != 0) {
- LastMouseButtonPressed = null;
- IsButtonPressed = false;
- IsButtonReleased = false;
- }
- if ((mouseEvent.ButtonState != 0 && mouseEvent.EventFlags == 0 && LastMouseButtonPressed == null && !IsButtonDoubleClicked) ||
- (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved &&
- mouseEvent.ButtonState != 0 && !IsButtonReleased && !IsButtonDoubleClicked)) {
- switch (mouseEvent.ButtonState) {
- case WindowsConsole.ButtonState.Button1Pressed:
- mouseFlag = MouseFlags.Button1Pressed;
- break;
- case WindowsConsole.ButtonState.Button2Pressed:
- mouseFlag = MouseFlags.Button2Pressed;
- break;
- case WindowsConsole.ButtonState.RightmostButtonPressed:
- mouseFlag = MouseFlags.Button3Pressed;
- break;
- }
- if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
- mouseFlag |= MouseFlags.ReportMousePosition;
- point = new Point ();
- IsButtonReleased = false;
- } else {
- point = new Point () {
- X = mouseEvent.MousePosition.X,
- Y = mouseEvent.MousePosition.Y
- };
- }
- LastMouseButtonPressed = mouseEvent.ButtonState;
- IsButtonPressed = true;
- if ((mouseFlag & MouseFlags.ReportMousePosition) == 0) {
- Application.MainLoop.AddIdle (() => {
- ProcessContinuousButtonPressedAsync (mouseEvent, mouseFlag).ConfigureAwait (false);
- return false;
- });
- }
- } else if ((mouseEvent.EventFlags == 0 || mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) &&
- LastMouseButtonPressed != null && !IsButtonReleased && !IsButtonDoubleClicked) {
- switch (LastMouseButtonPressed) {
- case WindowsConsole.ButtonState.Button1Pressed:
- mouseFlag = MouseFlags.Button1Released;
- break;
- case WindowsConsole.ButtonState.Button2Pressed:
- mouseFlag = MouseFlags.Button2Released;
- break;
- case WindowsConsole.ButtonState.RightmostButtonPressed:
- mouseFlag = MouseFlags.Button3Released;
- break;
- }
- IsButtonPressed = false;
- IsButtonReleased = true;
- } else if ((mouseEvent.EventFlags == 0 || mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) &&
- IsButtonReleased) {
- var p = new Point () {
- X = mouseEvent.MousePosition.X,
- Y = mouseEvent.MousePosition.Y
- };
- //if (p == point) {
- switch (LastMouseButtonPressed) {
- case WindowsConsole.ButtonState.Button1Pressed:
- mouseFlag = MouseFlags.Button1Clicked;
- break;
- case WindowsConsole.ButtonState.Button2Pressed:
- mouseFlag = MouseFlags.Button2Clicked;
- break;
- case WindowsConsole.ButtonState.RightmostButtonPressed:
- mouseFlag = MouseFlags.Button3Clicked;
- break;
- }
- point = new Point () {
- X = mouseEvent.MousePosition.X,
- Y = mouseEvent.MousePosition.Y
- };
- //} else {
- // mouseFlag = 0;
- //}
- LastMouseButtonPressed = null;
- IsButtonReleased = false;
- } else if (mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.DoubleClick)) {
- switch (mouseEvent.ButtonState) {
- case WindowsConsole.ButtonState.Button1Pressed:
- mouseFlag = MouseFlags.Button1DoubleClicked;
- break;
- case WindowsConsole.ButtonState.Button2Pressed:
- mouseFlag = MouseFlags.Button2DoubleClicked;
- break;
- case WindowsConsole.ButtonState.RightmostButtonPressed:
- mouseFlag = MouseFlags.Button3DoubleClicked;
- break;
- }
- IsButtonDoubleClicked = true;
- } else if (mouseEvent.EventFlags == 0 && mouseEvent.ButtonState != 0 && IsButtonDoubleClicked) {
- switch (mouseEvent.ButtonState) {
- case WindowsConsole.ButtonState.Button1Pressed:
- mouseFlag = MouseFlags.Button1TripleClicked;
- break;
- case WindowsConsole.ButtonState.Button2Pressed:
- mouseFlag = MouseFlags.Button2TripleClicked;
- break;
- case WindowsConsole.ButtonState.RightmostButtonPressed:
- mouseFlag = MouseFlags.Button3TripleClicked;
- break;
- }
- IsButtonDoubleClicked = false;
- } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled) {
- switch (mouseEvent.ButtonState) {
- case WindowsConsole.ButtonState.WheeledUp:
- mouseFlag = MouseFlags.WheeledUp;
- break;
- case WindowsConsole.ButtonState.WheeledDown:
- mouseFlag = MouseFlags.WheeledDown;
- break;
- }
- } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled &&
- mouseEvent.ControlKeyState == WindowsConsole.ControlKeyState.ShiftPressed) {
- switch (mouseEvent.ButtonState) {
- case WindowsConsole.ButtonState.WheeledUp:
- mouseFlag = MouseFlags.WheeledLeft;
- break;
- case WindowsConsole.ButtonState.WheeledDown:
- mouseFlag = MouseFlags.WheeledRight;
- break;
- }
- } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
- if (mouseEvent.MousePosition.X != point.X || mouseEvent.MousePosition.Y != point.Y) {
- mouseFlag = MouseFlags.ReportMousePosition;
- point = new Point ();
- } else {
- mouseFlag = 0;
- }
- } else if (mouseEvent.ButtonState == 0 && mouseEvent.EventFlags == 0) {
- mouseFlag = 0;
- }
- mouseFlag = SetControlKeyStates (mouseEvent, mouseFlag);
- return new MouseEvent () {
- X = mouseEvent.MousePosition.X,
- Y = mouseEvent.MousePosition.Y,
- Flags = mouseFlag
- };
- }
- async Task ProcessButtonDoubleClickedAsync ()
- {
- await Task.Delay (200);
- IsButtonDoubleClicked = false;
- }
- async Task ProcessContinuousButtonPressedAsync (WindowsConsole.MouseEventRecord mouseEvent, MouseFlags mouseFlag)
- {
- while (IsButtonPressed) {
- await Task.Delay (200);
- var me = new MouseEvent () {
- X = mouseEvent.MousePosition.X,
- Y = mouseEvent.MousePosition.Y,
- Flags = mouseFlag
- };
- var view = Application.wantContinuousButtonPressedView;
- if (view == null) {
- break;
- }
- if (IsButtonPressed && (mouseFlag & MouseFlags.ReportMousePosition) == 0) {
- mouseHandler (me);
- }
- }
- }
- static MouseFlags SetControlKeyStates (WindowsConsole.MouseEventRecord mouseEvent, MouseFlags mouseFlag)
- {
- if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed) ||
- mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed))
- mouseFlag |= MouseFlags.ButtonCtrl;
- if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed))
- mouseFlag |= MouseFlags.ButtonShift;
- if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed) ||
- mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed))
- mouseFlag |= MouseFlags.ButtonAlt;
- return mouseFlag;
- }
- KeyModifiers keyModifiers;
- public WindowsConsole.ConsoleKeyInfoEx ToConsoleKeyInfoEx (WindowsConsole.KeyEventRecord keyEvent)
- {
- var state = keyEvent.dwControlKeyState;
- bool shift = (state & WindowsConsole.ControlKeyState.ShiftPressed) != 0;
- bool alt = (state & (WindowsConsole.ControlKeyState.LeftAltPressed | WindowsConsole.ControlKeyState.RightAltPressed)) != 0;
- bool control = (state & (WindowsConsole.ControlKeyState.LeftControlPressed | WindowsConsole.ControlKeyState.RightControlPressed)) != 0;
- bool capslock = (state & (WindowsConsole.ControlKeyState.CapslockOn)) != 0;
- bool numlock = (state & (WindowsConsole.ControlKeyState.NumlockOn)) != 0;
- bool scrolllock = (state & (WindowsConsole.ControlKeyState.ScrolllockOn)) != 0;
- if (keyModifiers == null)
- keyModifiers = new KeyModifiers ();
- if (shift)
- keyModifiers.Shift = shift;
- if (alt)
- keyModifiers.Alt = alt;
- if (control)
- keyModifiers.Ctrl = control;
- if (capslock)
- keyModifiers.Capslock = capslock;
- if (numlock)
- keyModifiers.Numlock = numlock;
- if (scrolllock)
- keyModifiers.Scrolllock = scrolllock;
- var ConsoleKeyInfo = new ConsoleKeyInfo (keyEvent.UnicodeChar, (ConsoleKey)keyEvent.wVirtualKeyCode, shift, alt, control);
- return new WindowsConsole.ConsoleKeyInfoEx (ConsoleKeyInfo, capslock, numlock);
- }
- public Key MapKey (WindowsConsole.ConsoleKeyInfoEx keyInfoEx)
- {
- var keyInfo = keyInfoEx.consoleKeyInfo;
- 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, Key.Space);
- 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.NumPad0:
- return keyInfoEx.NumLock ? Key.D0 : Key.InsertChar;
- case ConsoleKey.NumPad1:
- return keyInfoEx.NumLock ? Key.D1 : Key.End;
- case ConsoleKey.NumPad2:
- return keyInfoEx.NumLock ? Key.D2 : Key.CursorDown;
- case ConsoleKey.NumPad3:
- return keyInfoEx.NumLock ? Key.D3 : Key.PageDown;
- case ConsoleKey.NumPad4:
- return keyInfoEx.NumLock ? Key.D4 : Key.CursorLeft;
- case ConsoleKey.NumPad5:
- return keyInfoEx.NumLock ? Key.D5 : (Key)((uint)keyInfo.KeyChar);
- case ConsoleKey.NumPad6:
- return keyInfoEx.NumLock ? Key.D6 : Key.CursorRight;
- case ConsoleKey.NumPad7:
- return keyInfoEx.NumLock ? Key.D7 : Key.Home;
- case ConsoleKey.NumPad8:
- return keyInfoEx.NumLock ? Key.D8 : Key.CursorUp;
- case ConsoleKey.NumPad9:
- return keyInfoEx.NumLock ? Key.D9 : Key.PageUp;
- 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;
- //var alphaBase = ((keyInfo.Modifiers == ConsoleModifiers.Shift) ^ (keyInfoEx.CapsLock)) ? 'A' : 'a';
- 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 || (keyInfo.KeyChar != 0 && keyInfo.KeyChar >= 1 && keyInfo.KeyChar <= 26)) {
- return MapKeyModifiers (keyInfo, (Key)((uint)Key.A + delta));
- }
- }
- //return (Key)((uint)alphaBase + delta);
- 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.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
- 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 (Key)((uint)keyInfo.KeyChar);
- }
- return (Key)(0xffffffff);
- }
- 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;
- }
- public override void Init (Action terminalResized)
- {
- TerminalResized = terminalResized;
- cols = Console.WindowWidth;
- rows = Console.WindowHeight;
- #if false
- winConsole.ShowWindow (WindowsConsole.RESTORE);
- #endif
- WindowsConsole.SmallRect.MakeEmpty (ref damageRegion);
- ResizeScreen ();
- UpdateOffScreen ();
- Colors.TopLevel = new ColorScheme ();
- Colors.Base = new ColorScheme ();
- Colors.Dialog = new ColorScheme ();
- Colors.Menu = new ColorScheme ();
- Colors.Error = new ColorScheme ();
- 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.DarkBlue);
- Colors.Base.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
- Colors.Base.HotNormal = MakeColor (ConsoleColor.DarkCyan, ConsoleColor.DarkBlue);
- Colors.Base.HotFocus = MakeColor (ConsoleColor.Blue, ConsoleColor.Gray);
- Colors.Menu.Normal = MakeColor (ConsoleColor.White, ConsoleColor.DarkGray);
- Colors.Menu.Focus = MakeColor (ConsoleColor.White, ConsoleColor.Black);
- Colors.Menu.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.DarkGray);
- Colors.Menu.HotFocus = MakeColor (ConsoleColor.Yellow, ConsoleColor.Black);
- Colors.Menu.Disabled = MakeColor (ConsoleColor.Gray, ConsoleColor.DarkGray);
- Colors.Dialog.Normal = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
- Colors.Dialog.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.DarkGray);
- Colors.Dialog.HotNormal = MakeColor (ConsoleColor.DarkBlue, ConsoleColor.Gray);
- Colors.Dialog.HotFocus = MakeColor (ConsoleColor.DarkBlue, ConsoleColor.DarkGray);
- Colors.Error.Normal = MakeColor (ConsoleColor.DarkRed, ConsoleColor.White);
- Colors.Error.Focus = MakeColor (ConsoleColor.White, ConsoleColor.DarkRed);
- Colors.Error.HotNormal = MakeColor (ConsoleColor.Black, ConsoleColor.White);
- Colors.Error.HotFocus = MakeColor (ConsoleColor.Black, ConsoleColor.DarkRed);
- }
- void ResizeScreen ()
- {
- OutputBuffer = new WindowsConsole.CharInfo [Rows * Cols];
- Clip = new Rect (0, 0, Cols, Rows);
- damageRegion = new WindowsConsole.SmallRect () {
- Top = 0,
- Left = 0,
- Bottom = (short)Rows,
- Right = (short)Cols
- };
- }
- void UpdateOffScreen ()
- {
- for (int row = 0; row < rows; row++) {
- for (int col = 0; col < cols; col++) {
- int position = row * cols + col;
- OutputBuffer [position].Attributes = (ushort)Colors.TopLevel.Normal;
- OutputBuffer [position].Char.UnicodeChar = ' ';
- }
- }
- winChanging = false;
- }
- int ccol, crow;
- public override void Move (int col, int row)
- {
- ccol = col;
- crow = row;
- }
- public override void AddRune (Rune rune)
- {
- rune = MakePrintable (rune);
- var position = crow * Cols + ccol;
- if (Clip.Contains (ccol, crow)) {
- OutputBuffer [position].Attributes = (ushort)currentAttribute;
- OutputBuffer [position].Char.UnicodeChar = (char)rune;
- WindowsConsole.SmallRect.Update (ref damageRegion, (short)ccol, (short)crow);
- }
- ccol++;
- var runeWidth = Rune.ColumnWidth (rune);
- if (runeWidth > 1) {
- for (int i = 1; i < runeWidth; i++) {
- AddStr (" ");
- }
- }
- //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);
- }
- int currentAttribute;
- public override void SetAttribute (Attribute c)
- {
- currentAttribute = c.value;
- }
- Attribute MakeColor (ConsoleColor f, ConsoleColor b)
- {
- // Encode the colors into the int value.
- return new Attribute () {
- value = ((int)f | (int)b << 4),
- foreground = (Color)f,
- background = (Color)b
- };
- }
- public override Attribute MakeAttribute (Color fore, Color back)
- {
- return MakeColor ((ConsoleColor)fore, (ConsoleColor)back);
- }
- public override void Refresh ()
- {
- UpdateScreen ();
- #if false
- var bufferCoords = new WindowsConsole.Coord (){
- X = (short)Clip.Width,
- Y = (short)Clip.Height
- };
- var window = new WindowsConsole.SmallRect (){
- Top = 0,
- Left = 0,
- Right = (short)Clip.Right,
- Bottom = (short)Clip.Bottom
- };
- UpdateCursor();
- winConsole.WriteToConsole (OutputBuffer, bufferCoords, window);
- #endif
- }
- public override void UpdateScreen ()
- {
- if (damageRegion.Left == -1)
- return;
- var bufferCoords = new WindowsConsole.Coord () {
- X = (short)Clip.Width,
- Y = (short)Clip.Height
- };
- //var window = new WindowsConsole.SmallRect () {
- // Top = 0,
- // Left = 0,
- // Right = (short)Clip.Right,
- // Bottom = (short)Clip.Bottom
- //};
- UpdateCursor ();
- winConsole.WriteToConsole (OutputBuffer, bufferCoords, damageRegion);
- //System.Diagnostics.Debugger.Log(0, "debug", $"Region={damageRegion.Right - damageRegion.Left},{damageRegion.Bottom - damageRegion.Top}\n");
- WindowsConsole.SmallRect.MakeEmpty (ref damageRegion);
- }
- public override void UpdateCursor ()
- {
- var position = new WindowsConsole.Coord () {
- X = (short)ccol,
- Y = (short)crow
- };
- winConsole.SetCursorPosition (position);
- }
- public override void End ()
- {
- winConsole.Cleanup ();
- }
- #region Unused
- public override void SetColors (ConsoleColor foreground, ConsoleColor background)
- {
- }
- public override void SetColors (short foregroundColorId, short backgroundColorId)
- {
- }
- public override void Suspend ()
- {
- }
- public override void StartReportingMouseMoves ()
- {
- }
- public override void StopReportingMouseMoves ()
- {
- }
- public override void UncookMouse ()
- {
- }
- public override void CookMouse ()
- {
- }
- #endregion
- }
- /// <summary>
- /// Mainloop intended to be used with the <see cref="WindowsDriver"/>, and can
- /// only be used on Windows.
- /// </summary>
- /// <remarks>
- /// This implementation is used for WindowsDriver.
- /// </remarks>
- internal class WindowsMainLoop : IMainLoopDriver {
- ManualResetEventSlim eventReady = new ManualResetEventSlim (false);
- ManualResetEventSlim waitForProbe = new ManualResetEventSlim (false);
- ManualResetEventSlim winChange = new ManualResetEventSlim (false);
- MainLoop mainLoop;
- ConsoleDriver consoleDriver;
- WindowsConsole winConsole;
- bool winChanged;
- WindowsConsole.WindowPlacement windowPlacement;
- Size windowSize;
- CancellationTokenSource tokenSource = new CancellationTokenSource ();
- // The records that we keep fetching
- WindowsConsole.InputRecord [] result = new WindowsConsole.InputRecord [1];
- /// <summary>
- /// Invoked when a Key is pressed or released.
- /// </summary>
- public Action<WindowsConsole.InputRecord> ProcessInput;
- /// <summary>
- /// Invoked when the window is changed.
- /// </summary>
- public Action<Size> WinChanged;
- public WindowsMainLoop (ConsoleDriver consoleDriver = null)
- {
- if (consoleDriver == null) {
- throw new ArgumentNullException ("Console driver instance must be provided.");
- }
- this.consoleDriver = consoleDriver;
- winConsole = ((WindowsDriver)consoleDriver).WinConsole;
- }
- void IMainLoopDriver.Setup (MainLoop mainLoop)
- {
- this.mainLoop = mainLoop;
- Task.Run (WindowsInputHandler);
- Task.Run (CheckWinChange);
- }
- void WindowsInputHandler ()
- {
- while (true) {
- waitForProbe.Wait ();
- waitForProbe.Reset ();
- result = winConsole.ReadConsoleInput ();
- eventReady.Set ();
- }
- }
- void CheckWinChange ()
- {
- while (true) {
- winChange.Wait ();
- winChange.Reset ();
- WaitWinChange ();
- winChanged = true;
- eventReady.Set ();
- }
- }
- void WaitWinChange ()
- {
- while (true) {
- if (!consoleDriver.HeightAsBuffer) {
- windowPlacement = winConsole.GetWindow ();
- if (windowPlacement.rcNormalPosition.Size.Height > -1) {
- windowSize = new Size (Math.Max (((windowPlacement.rcNormalPosition.Size.Width -
- windowPlacement.rcNormalPosition.X) / 8) - 2, 0),
- Math.Max (((windowPlacement.rcNormalPosition.Size.Height -
- windowPlacement.rcNormalPosition.Y) / 16) - 7, 0));
- if (windowPlacement.showCmd != WindowsConsole.SHOW_MAXIMIZED
- && (windowSize.Width != consoleDriver.Cols || windowSize.Height != consoleDriver.Rows)) {
- return;
- } else if (windowPlacement.showCmd == WindowsConsole.SHOW_MAXIMIZED
- && (Console.LargestWindowWidth != consoleDriver.Cols || Console.LargestWindowHeight != consoleDriver.Rows)) {
- windowSize = new Size (Console.LargestWindowWidth, Console.LargestWindowHeight);
- return;
- }
- }
- }
- }
- }
- void IMainLoopDriver.Wakeup ()
- {
- //tokenSource.Cancel ();
- eventReady.Set ();
- }
- bool IMainLoopDriver.EventsPending (bool wait)
- {
- if (CheckTimers (wait, out var waitTimeout)) {
- return true;
- }
- //result = null;
- waitForProbe.Set ();
- winChange.Set ();
- try {
- if (!tokenSource.IsCancellationRequested) {
- eventReady.Wait (waitTimeout, tokenSource.Token);
- }
- } catch (OperationCanceledException) {
- return true;
- } finally {
- eventReady.Reset ();
- }
- if (!tokenSource.IsCancellationRequested) {
- return result != null || CheckTimers (wait, out waitTimeout) || winChanged;
- }
- tokenSource.Dispose ();
- tokenSource = new CancellationTokenSource ();
- return true;
- }
- bool CheckTimers (bool wait, out int waitTimeout)
- {
- long now = DateTime.UtcNow.Ticks;
- 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;
- int ic;
- lock (mainLoop.idleHandlers) {
- ic = mainLoop.idleHandlers.Count;
- }
- return ic > 0;
- }
- void IMainLoopDriver.MainIteration ()
- {
- if (result != null) {
- var inputEvent = result [0];
- result = null;
- ProcessInput?.Invoke (inputEvent);
- }
- if (winChanged) {
- winChanged = false;
- WinChanged?.Invoke (windowSize);
- }
- }
- }
- }
|