1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555 |
- //
- // Driver.cs: Curses-based Driver
- //
- // Authors:
- // Miguel de Icaza ([email protected])
- //
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Linq;
- using System.Runtime.InteropServices;
- using System.Threading.Tasks;
- using NStack;
- using Unix.Terminal;
- namespace Terminal.Gui {
- /// <summary>
- /// This is the Curses driver for the gui.cs/Terminal framework.
- /// </summary>
- internal class CursesDriver : ConsoleDriver {
- public override int Cols => Curses.Cols;
- public override int Rows => Curses.Lines;
- public override int Left => 0;
- public override int Top => 0;
- public override bool HeightAsBuffer { get; set; }
- public override IClipboard Clipboard { get => clipboard; }
- CursorVisibility? initialCursorVisibility = null;
- CursorVisibility? currentCursorVisibility = null;
- IClipboard clipboard;
- int [,,] contents;
- public override int [,,] Contents => contents;
- // Current row, and current col, tracked by Move/AddRune only
- int ccol, crow;
- bool needMove;
- public override void Move (int col, int row)
- {
- ccol = col;
- crow = row;
- if (Clip.Contains (col, row)) {
- Curses.move (row, col);
- needMove = false;
- } else {
- Curses.move (Clip.Y, Clip.X);
- needMove = true;
- }
- }
- static bool sync = false;
- public override void AddRune (Rune rune)
- {
- rune = MakePrintable (rune);
- var runeWidth = Rune.ColumnWidth (rune);
- var validClip = IsValidContent (ccol, crow, Clip);
- if (validClip) {
- if (needMove) {
- Curses.move (crow, ccol);
- needMove = false;
- }
- if (runeWidth < 2 && ccol > 0
- && Rune.ColumnWidth ((char)contents [crow, ccol - 1, 0]) > 1) {
- var curAtttib = currentAttribute;
- Curses.attrset (contents [crow, ccol - 1, 1]);
- Curses.mvaddch (crow, ccol - 1, (int)(uint)' ');
- contents [crow, ccol - 1, 0] = (int)(uint)' ';
- Curses.move (crow, ccol);
- Curses.attrset (curAtttib);
- } else if (runeWidth < 2 && ccol <= Clip.Right - 1
- && Rune.ColumnWidth ((char)contents [crow, ccol, 0]) > 1) {
- var curAtttib = currentAttribute;
- Curses.attrset (contents [crow, ccol + 1, 1]);
- Curses.mvaddch (crow, ccol + 1, (int)(uint)' ');
- contents [crow, ccol + 1, 0] = (int)(uint)' ';
- Curses.move (crow, ccol);
- Curses.attrset (curAtttib);
- }
- if (runeWidth > 1 && ccol == Clip.Right - 1) {
- Curses.addch ((int)(uint)' ');
- contents [crow, ccol, 0] = (int)(uint)' ';
- } else {
- Curses.addch ((int)(uint)rune);
- contents [crow, ccol, 0] = (int)(uint)rune;
- }
- contents [crow, ccol, 1] = currentAttribute;
- contents [crow, ccol, 2] = 1;
- } else
- needMove = true;
- ccol++;
- if (runeWidth > 1) {
- if (validClip && ccol < Clip.Right) {
- contents [crow, ccol, 1] = currentAttribute;
- contents [crow, ccol, 2] = 0;
- }
- ccol++;
- }
- if (sync)
- UpdateScreen ();
- }
- public override void AddStr (ustring str)
- {
- // TODO; optimize this to determine if the str fits in the clip region, and if so, use Curses.addstr directly
- foreach (var rune in str)
- AddRune (rune);
- }
- public override void Refresh ()
- {
- Curses.raw ();
- Curses.noecho ();
- Curses.refresh ();
- ProcessWinChange ();
- }
- private void ProcessWinChange ()
- {
- if (Curses.CheckWinChange ()) {
- ResizeScreen ();
- UpdateOffScreen ();
- TerminalResized?.Invoke ();
- }
- }
- public override void UpdateCursor () => Refresh ();
- public override void End ()
- {
- if (reportableMouseEvents.HasFlag (Curses.Event.ReportMousePosition)) {
- StopReportingMouseMoves ();
- }
- SetCursorVisibility (CursorVisibility.Default);
- Curses.endwin ();
- // I'm commenting this because was used in a trying to fix the Linux hanging and forgot to exclude it.
- // Clear and reset entire screen.
- //Console.Out.Write ("\x1b[2J");
- //Console.Out.Flush ();
- // Set top and bottom lines of a window.
- //Console.Out.Write ("\x1b[1;25r");
- //Console.Out.Flush ();
- //Set cursor key to cursor.
- //Console.Out.Write ("\x1b[?1l");
- //Console.Out.Flush ();
- }
- public override void UpdateScreen () => window.redrawwin ();
- Attribute currentAttribute;
- public override void SetAttribute (Attribute c)
- {
- currentAttribute = c;
- Curses.attrset (currentAttribute);
- }
- public Curses.Window window;
- //static short last_color_pair = 16;
- /// <summary>
- /// Creates a curses color from the provided foreground and background colors
- /// </summary>
- /// <param name="foreground">Contains the curses attributes for the foreground (color, plus any attributes)</param>
- /// <param name="background">Contains the curses attributes for the background (color, plus any attributes)</param>
- /// <returns></returns>
- public static Attribute MakeColor (short foreground, short background)
- {
- var v = (short)((int)foreground | background << 4);
- //Curses.InitColorPair (++last_color_pair, foreground, background);
- Curses.InitColorPair (v, foreground, background);
- return new Attribute (
- //value: Curses.ColorPair (last_color_pair),
- value: Curses.ColorPair (v),
- //foreground: (Color)foreground,
- foreground: MapCursesColor (foreground),
- //background: (Color)background);
- background: MapCursesColor (background));
- }
- public override Attribute MakeColor (Color fore, Color back)
- {
- return MakeColor ((short)MapColor (fore), (short)MapColor (back));
- }
- int [,] colorPairs = new int [16, 16];
- public override void SetColors (ConsoleColor foreground, ConsoleColor background)
- {
- int f = (short)foreground;
- int b = (short)background;
- var v = colorPairs [f, b];
- if ((v & 0x10000) == 0) {
- b &= 0x7;
- bool bold = (f & 0x8) != 0;
- f &= 0x7;
- v = MakeColor ((short)f, (short)b) | (bold ? Curses.A_BOLD : 0);
- colorPairs [(int)foreground, (int)background] = v | 0x1000;
- }
- SetAttribute (v & 0xffff);
- }
- Dictionary<int, int> rawPairs = new Dictionary<int, int> ();
- public override void SetColors (short foreColorId, short backgroundColorId)
- {
- int key = ((ushort)foreColorId << 16) | (ushort)backgroundColorId;
- if (!rawPairs.TryGetValue (key, out var v)) {
- v = MakeColor (foreColorId, backgroundColorId);
- rawPairs [key] = v;
- }
- SetAttribute (v);
- }
- static Key MapCursesKey (int cursesKey)
- {
- switch (cursesKey) {
- case Curses.KeyF1: return Key.F1;
- case Curses.KeyF2: return Key.F2;
- case Curses.KeyF3: return Key.F3;
- case Curses.KeyF4: return Key.F4;
- case Curses.KeyF5: return Key.F5;
- case Curses.KeyF6: return Key.F6;
- case Curses.KeyF7: return Key.F7;
- case Curses.KeyF8: return Key.F8;
- case Curses.KeyF9: return Key.F9;
- case Curses.KeyF10: return Key.F10;
- case Curses.KeyF11: return Key.F11;
- case Curses.KeyF12: return Key.F12;
- case Curses.KeyUp: return Key.CursorUp;
- case Curses.KeyDown: return Key.CursorDown;
- case Curses.KeyLeft: return Key.CursorLeft;
- case Curses.KeyRight: return Key.CursorRight;
- case Curses.KeyHome: return Key.Home;
- case Curses.KeyEnd: return Key.End;
- case Curses.KeyNPage: return Key.PageDown;
- case Curses.KeyPPage: return Key.PageUp;
- case Curses.KeyDeleteChar: return Key.DeleteChar;
- case Curses.KeyInsertChar: return Key.InsertChar;
- case Curses.KeyTab: return Key.Tab;
- case Curses.KeyBackTab: return Key.BackTab;
- case Curses.KeyBackspace: return Key.Backspace;
- case Curses.ShiftKeyUp: return Key.CursorUp | Key.ShiftMask;
- case Curses.ShiftKeyDown: return Key.CursorDown | Key.ShiftMask;
- case Curses.ShiftKeyLeft: return Key.CursorLeft | Key.ShiftMask;
- case Curses.ShiftKeyRight: return Key.CursorRight | Key.ShiftMask;
- case Curses.ShiftKeyHome: return Key.Home | Key.ShiftMask;
- case Curses.ShiftKeyEnd: return Key.End | Key.ShiftMask;
- case Curses.ShiftKeyNPage: return Key.PageDown | Key.ShiftMask;
- case Curses.ShiftKeyPPage: return Key.PageUp | Key.ShiftMask;
- case Curses.AltKeyUp: return Key.CursorUp | Key.AltMask;
- case Curses.AltKeyDown: return Key.CursorDown | Key.AltMask;
- case Curses.AltKeyLeft: return Key.CursorLeft | Key.AltMask;
- case Curses.AltKeyRight: return Key.CursorRight | Key.AltMask;
- case Curses.AltKeyHome: return Key.Home | Key.AltMask;
- case Curses.AltKeyEnd: return Key.End | Key.AltMask;
- case Curses.AltKeyNPage: return Key.PageDown | Key.AltMask;
- case Curses.AltKeyPPage: return Key.PageUp | Key.AltMask;
- case Curses.CtrlKeyUp: return Key.CursorUp | Key.CtrlMask;
- case Curses.CtrlKeyDown: return Key.CursorDown | Key.CtrlMask;
- case Curses.CtrlKeyLeft: return Key.CursorLeft | Key.CtrlMask;
- case Curses.CtrlKeyRight: return Key.CursorRight | Key.CtrlMask;
- case Curses.CtrlKeyHome: return Key.Home | Key.CtrlMask;
- case Curses.CtrlKeyEnd: return Key.End | Key.CtrlMask;
- case Curses.CtrlKeyNPage: return Key.PageDown | Key.CtrlMask;
- case Curses.CtrlKeyPPage: return Key.PageUp | Key.CtrlMask;
- case Curses.ShiftCtrlKeyUp: return Key.CursorUp | Key.ShiftMask | Key.CtrlMask;
- case Curses.ShiftCtrlKeyDown: return Key.CursorDown | Key.ShiftMask | Key.CtrlMask;
- case Curses.ShiftCtrlKeyLeft: return Key.CursorLeft | Key.ShiftMask | Key.CtrlMask;
- case Curses.ShiftCtrlKeyRight: return Key.CursorRight | Key.ShiftMask | Key.CtrlMask;
- case Curses.ShiftCtrlKeyHome: return Key.Home | Key.ShiftMask | Key.CtrlMask;
- case Curses.ShiftCtrlKeyEnd: return Key.End | Key.ShiftMask | Key.CtrlMask;
- case Curses.ShiftCtrlKeyNPage: return Key.PageDown | Key.ShiftMask | Key.CtrlMask;
- case Curses.ShiftCtrlKeyPPage: return Key.PageUp | Key.ShiftMask | Key.CtrlMask;
- case Curses.ShiftAltKeyUp: return Key.CursorUp | Key.ShiftMask | Key.AltMask;
- case Curses.ShiftAltKeyDown: return Key.CursorDown | Key.ShiftMask | Key.AltMask;
- case Curses.ShiftAltKeyLeft: return Key.CursorLeft | Key.ShiftMask | Key.AltMask;
- case Curses.ShiftAltKeyRight: return Key.CursorRight | Key.ShiftMask | Key.AltMask;
- case Curses.ShiftAltKeyNPage: return Key.PageDown | Key.ShiftMask | Key.AltMask;
- case Curses.ShiftAltKeyPPage: return Key.PageUp | Key.ShiftMask | Key.AltMask;
- case Curses.ShiftAltKeyHome: return Key.Home | Key.ShiftMask | Key.AltMask;
- case Curses.ShiftAltKeyEnd: return Key.End | Key.ShiftMask | Key.AltMask;
- case Curses.AltCtrlKeyNPage: return Key.PageDown | Key.AltMask | Key.CtrlMask;
- case Curses.AltCtrlKeyPPage: return Key.PageUp | Key.AltMask | Key.CtrlMask;
- case Curses.AltCtrlKeyHome: return Key.Home | Key.AltMask | Key.CtrlMask;
- case Curses.AltCtrlKeyEnd: return Key.End | Key.AltMask | Key.CtrlMask;
- default: return Key.Unknown;
- }
- }
- Curses.Event? lastMouseButtonPressed;
- bool isButtonPressed;
- bool cancelButtonClicked;
- bool isReportMousePosition;
- Point point;
- int buttonPressedCount;
- MouseEvent ToDriverMouse (Curses.MouseEvent cev)
- {
- MouseFlags mouseFlag = MouseFlags.AllEvents;
- if (lastMouseButtonPressed != null && cev.ButtonState != Curses.Event.ReportMousePosition) {
- lastMouseButtonPressed = null;
- isButtonPressed = false;
- }
- if (cev.ButtonState == Curses.Event.Button1Pressed
- || cev.ButtonState == Curses.Event.Button2Pressed
- || cev.ButtonState == Curses.Event.Button3Pressed) {
- isButtonPressed = true;
- buttonPressedCount++;
- } else {
- buttonPressedCount = 0;
- }
- //System.Diagnostics.Debug.WriteLine ($"buttonPressedCount: {buttonPressedCount}");
- if (buttonPressedCount == 2
- && (cev.ButtonState == Curses.Event.Button1Pressed
- || cev.ButtonState == Curses.Event.Button2Pressed
- || cev.ButtonState == Curses.Event.Button3Pressed)) {
- switch (cev.ButtonState) {
- case Curses.Event.Button1Pressed:
- mouseFlag = MouseFlags.Button1DoubleClicked;
- break;
- case Curses.Event.Button2Pressed:
- mouseFlag = MouseFlags.Button2DoubleClicked;
- break;
- case Curses.Event.Button3Pressed:
- mouseFlag = MouseFlags.Button3DoubleClicked;
- break;
- }
- cancelButtonClicked = true;
- } else if (buttonPressedCount == 3
- && (cev.ButtonState == Curses.Event.Button1Pressed
- || cev.ButtonState == Curses.Event.Button2Pressed
- || cev.ButtonState == Curses.Event.Button3Pressed)) {
- switch (cev.ButtonState) {
- case Curses.Event.Button1Pressed:
- mouseFlag = MouseFlags.Button1TripleClicked;
- break;
- case Curses.Event.Button2Pressed:
- mouseFlag = MouseFlags.Button2TripleClicked;
- break;
- case Curses.Event.Button3Pressed:
- mouseFlag = MouseFlags.Button3TripleClicked;
- break;
- }
- buttonPressedCount = 0;
- } else if ((cev.ButtonState == Curses.Event.Button1Clicked || cev.ButtonState == Curses.Event.Button2Clicked ||
- cev.ButtonState == Curses.Event.Button3Clicked) &&
- lastMouseButtonPressed == null) {
- isButtonPressed = false;
- mouseFlag = ProcessButtonClickedEvent (cev);
- } else if (((cev.ButtonState == Curses.Event.Button1Pressed || cev.ButtonState == Curses.Event.Button2Pressed ||
- cev.ButtonState == Curses.Event.Button3Pressed) && lastMouseButtonPressed == null) ||
- isButtonPressed && lastMouseButtonPressed != null && cev.ButtonState == Curses.Event.ReportMousePosition) {
- mouseFlag = MapCursesButton (cev.ButtonState);
- if (cev.ButtonState != Curses.Event.ReportMousePosition)
- lastMouseButtonPressed = cev.ButtonState;
- isButtonPressed = true;
- isReportMousePosition = false;
- if (cev.ButtonState == Curses.Event.ReportMousePosition) {
- mouseFlag = MapCursesButton ((Curses.Event)lastMouseButtonPressed) | MouseFlags.ReportMousePosition;
- cancelButtonClicked = true;
- }
- point = new Point () {
- X = cev.X,
- Y = cev.Y
- };
- if ((mouseFlag & MouseFlags.ReportMousePosition) == 0) {
- Application.MainLoop.AddIdle (() => {
- Task.Run (async () => await ProcessContinuousButtonPressedAsync (mouseFlag));
- return false;
- });
- }
- } else if ((cev.ButtonState == Curses.Event.Button1Released || cev.ButtonState == Curses.Event.Button2Released ||
- cev.ButtonState == Curses.Event.Button3Released)) {
- mouseFlag = ProcessButtonReleasedEvent (cev);
- isButtonPressed = false;
- } else if (cev.ButtonState == Curses.Event.ButtonWheeledUp) {
- mouseFlag = MouseFlags.WheeledUp;
- } else if (cev.ButtonState == Curses.Event.ButtonWheeledDown) {
- mouseFlag = MouseFlags.WheeledDown;
- } else if ((cev.ButtonState & (Curses.Event.ButtonWheeledUp & Curses.Event.ButtonShift)) != 0) {
- mouseFlag = MouseFlags.WheeledLeft;
- } else if ((cev.ButtonState & (Curses.Event.ButtonWheeledDown & Curses.Event.ButtonShift)) != 0) {
- mouseFlag = MouseFlags.WheeledRight;
- } else if (cev.ButtonState == Curses.Event.ReportMousePosition) {
- if (cev.X != point.X || cev.Y != point.Y) {
- mouseFlag = MouseFlags.ReportMousePosition;
- isReportMousePosition = true;
- point = new Point ();
- } else {
- mouseFlag = 0;
- }
- } else {
- mouseFlag = 0;
- var eFlags = cev.ButtonState;
- foreach (Enum value in Enum.GetValues (eFlags.GetType ())) {
- if (eFlags.HasFlag (value)) {
- mouseFlag |= MapCursesButton ((Curses.Event)value);
- }
- }
- }
- mouseFlag = SetControlKeyStates (cev, mouseFlag);
- return new MouseEvent () {
- X = cev.X,
- Y = cev.Y,
- //Flags = MapCursesButton (cev.ButtonState)
- Flags = mouseFlag
- };
- }
- MouseFlags ProcessButtonClickedEvent (Curses.MouseEvent cev)
- {
- lastMouseButtonPressed = cev.ButtonState;
- var mf = GetButtonState (cev, true);
- mouseHandler (ProcessButtonState (cev, mf));
- if (lastMouseButtonPressed != null && lastMouseButtonPressed == cev.ButtonState) {
- mf = GetButtonState (cev, false);
- mouseHandler (ProcessButtonState (cev, mf));
- if (lastMouseButtonPressed != null && lastMouseButtonPressed == cev.ButtonState) {
- mf = MapCursesButton (cev.ButtonState);
- }
- }
- lastMouseButtonPressed = null;
- isButtonPressed = false;
- return mf;
- }
- MouseFlags ProcessButtonReleasedEvent (Curses.MouseEvent cev)
- {
- var mf = MapCursesButton (cev.ButtonState);
- if (!cancelButtonClicked && lastMouseButtonPressed == null && !isReportMousePosition) {
- mouseHandler (ProcessButtonState (cev, mf));
- mf = GetButtonState (cev);
- } else if (isReportMousePosition) {
- mf = MouseFlags.ReportMousePosition;
- }
- cancelButtonClicked = false;
- return mf;
- }
- async Task ProcessContinuousButtonPressedAsync (MouseFlags mouseFlag)
- {
- while (isButtonPressed) {
- await Task.Delay (100);
- var me = new MouseEvent () {
- X = point.X,
- Y = point.Y,
- Flags = mouseFlag
- };
- var view = Application.WantContinuousButtonPressedView;
- if (view == null)
- break;
- if (isButtonPressed && lastMouseButtonPressed != null && (mouseFlag & MouseFlags.ReportMousePosition) == 0) {
- Application.MainLoop.Invoke (() => mouseHandler (me));
- }
- }
- }
- MouseFlags GetButtonState (Curses.MouseEvent cev, bool pressed = false)
- {
- MouseFlags mf = default;
- switch (cev.ButtonState) {
- case Curses.Event.Button1Clicked:
- if (pressed)
- mf = MouseFlags.Button1Pressed;
- else
- mf = MouseFlags.Button1Released;
- break;
- case Curses.Event.Button2Clicked:
- if (pressed)
- mf = MouseFlags.Button2Pressed;
- else
- mf = MouseFlags.Button2Released;
- break;
- case Curses.Event.Button3Clicked:
- if (pressed)
- mf = MouseFlags.Button3Pressed;
- else
- mf = MouseFlags.Button3Released;
- break;
- case Curses.Event.Button1Released:
- mf = MouseFlags.Button1Clicked;
- break;
- case Curses.Event.Button2Released:
- mf = MouseFlags.Button2Clicked;
- break;
- case Curses.Event.Button3Released:
- mf = MouseFlags.Button3Clicked;
- break;
- }
- return mf;
- }
- MouseEvent ProcessButtonState (Curses.MouseEvent cev, MouseFlags mf)
- {
- return new MouseEvent () {
- X = cev.X,
- Y = cev.Y,
- Flags = mf
- };
- }
- MouseFlags MapCursesButton (Curses.Event cursesButton)
- {
- switch (cursesButton) {
- case Curses.Event.Button1Pressed: return MouseFlags.Button1Pressed;
- case Curses.Event.Button1Released: return MouseFlags.Button1Released;
- case Curses.Event.Button1Clicked: return MouseFlags.Button1Clicked;
- case Curses.Event.Button1DoubleClicked: return MouseFlags.Button1DoubleClicked;
- case Curses.Event.Button1TripleClicked: return MouseFlags.Button1TripleClicked;
- case Curses.Event.Button2Pressed: return MouseFlags.Button2Pressed;
- case Curses.Event.Button2Released: return MouseFlags.Button2Released;
- case Curses.Event.Button2Clicked: return MouseFlags.Button2Clicked;
- case Curses.Event.Button2DoubleClicked: return MouseFlags.Button2DoubleClicked;
- case Curses.Event.Button2TrippleClicked: return MouseFlags.Button2TripleClicked;
- case Curses.Event.Button3Pressed: return MouseFlags.Button3Pressed;
- case Curses.Event.Button3Released: return MouseFlags.Button3Released;
- case Curses.Event.Button3Clicked: return MouseFlags.Button3Clicked;
- case Curses.Event.Button3DoubleClicked: return MouseFlags.Button3DoubleClicked;
- case Curses.Event.Button3TripleClicked: return MouseFlags.Button3TripleClicked;
- case Curses.Event.ButtonWheeledUp: return MouseFlags.WheeledUp;
- case Curses.Event.ButtonWheeledDown: return MouseFlags.WheeledDown;
- case Curses.Event.Button4Pressed: return MouseFlags.Button4Pressed;
- case Curses.Event.Button4Released: return MouseFlags.Button4Released;
- case Curses.Event.Button4Clicked: return MouseFlags.Button4Clicked;
- case Curses.Event.Button4DoubleClicked: return MouseFlags.Button4DoubleClicked;
- case Curses.Event.Button4TripleClicked: return MouseFlags.Button4TripleClicked;
- case Curses.Event.ButtonShift: return MouseFlags.ButtonShift;
- case Curses.Event.ButtonCtrl: return MouseFlags.ButtonCtrl;
- case Curses.Event.ButtonAlt: return MouseFlags.ButtonAlt;
- case Curses.Event.ReportMousePosition: return MouseFlags.ReportMousePosition;
- case Curses.Event.AllEvents: return MouseFlags.AllEvents;
- default: return 0;
- }
- }
- static MouseFlags SetControlKeyStates (Curses.MouseEvent cev, MouseFlags mouseFlag)
- {
- if ((cev.ButtonState & Curses.Event.ButtonCtrl) != 0 && (mouseFlag & MouseFlags.ButtonCtrl) == 0)
- mouseFlag |= MouseFlags.ButtonCtrl;
- if ((cev.ButtonState & Curses.Event.ButtonShift) != 0 && (mouseFlag & MouseFlags.ButtonShift) == 0)
- mouseFlag |= MouseFlags.ButtonShift;
- if ((cev.ButtonState & Curses.Event.ButtonAlt) != 0 && (mouseFlag & MouseFlags.ButtonAlt) == 0)
- mouseFlag |= MouseFlags.ButtonAlt;
- return mouseFlag;
- }
- KeyModifiers keyModifiers;
- KeyModifiers MapKeyModifiers (Key key)
- {
- if (keyModifiers == null)
- keyModifiers = new KeyModifiers ();
- if (!keyModifiers.Shift && (key & Key.ShiftMask) != 0)
- keyModifiers.Shift = true;
- if (!keyModifiers.Alt && (key & Key.AltMask) != 0)
- keyModifiers.Alt = true;
- if (!keyModifiers.Ctrl && (key & Key.CtrlMask) != 0)
- keyModifiers.Ctrl = true;
- return keyModifiers;
- }
- void ProcessInput ()
- {
- int wch;
- var code = Curses.get_wch (out wch);
- //System.Diagnostics.Debug.WriteLine ($"code: {code}; wch: {wch}");
- if (code == Curses.ERR)
- return;
- keyModifiers = new KeyModifiers ();
- Key k = Key.Null;
- if (code == Curses.KEY_CODE_YES) {
- if (wch == Curses.KeyResize) {
- ProcessWinChange ();
- }
- if (wch == Curses.KeyMouse) {
- Curses.getmouse (out Curses.MouseEvent ev);
- //System.Diagnostics.Debug.WriteLine ($"ButtonState: {ev.ButtonState}; ID: {ev.ID}; X: {ev.X}; Y: {ev.Y}; Z: {ev.Z}");
- mouseHandler (ToDriverMouse (ev));
- return;
- }
- k = MapCursesKey (wch);
- if (wch >= 277 && wch <= 288) { // Shift+(F1 - F12)
- wch -= 12;
- k = Key.ShiftMask | MapCursesKey (wch);
- } else if (wch >= 289 && wch <= 300) { // Ctrl+(F1 - F12)
- wch -= 24;
- k = Key.CtrlMask | MapCursesKey (wch);
- } else if (wch >= 301 && wch <= 312) { // Ctrl+Shift+(F1 - F12)
- wch -= 36;
- k = Key.CtrlMask | Key.ShiftMask | MapCursesKey (wch);
- } else if (wch >= 313 && wch <= 324) { // Alt+(F1 - F12)
- wch -= 48;
- k = Key.AltMask | MapCursesKey (wch);
- } else if (wch >= 325 && wch <= 327) { // Shift+Alt+(F1 - F3)
- wch -= 60;
- k = Key.ShiftMask | Key.AltMask | MapCursesKey (wch);
- }
- keyDownHandler (new KeyEvent (k, MapKeyModifiers (k)));
- keyHandler (new KeyEvent (k, MapKeyModifiers (k)));
- keyUpHandler (new KeyEvent (k, MapKeyModifiers (k)));
- return;
- }
- // Special handling for ESC, we want to try to catch ESC+letter to simulate alt-letter as well as Alt-Fkey
- if (wch == 27) {
- Curses.timeout (10);
- code = Curses.get_wch (out int wch2);
- if (code == Curses.KEY_CODE_YES) {
- k = Key.AltMask | MapCursesKey (wch);
- }
- if (code == 0) {
- KeyEvent key;
- // The ESC-number handling, debatable.
- // Simulates the AltMask itself by pressing Alt + Space.
- if (wch2 == (int)Key.Space) {
- k = Key.AltMask;
- } else if (wch2 - (int)Key.Space >= (uint)Key.A && wch2 - (int)Key.Space <= (uint)Key.Z) {
- k = (Key)((uint)Key.AltMask + (wch2 - (int)Key.Space));
- } else if (wch2 >= (uint)Key.A - 64 && wch2 <= (uint)Key.Z - 64) {
- k = (Key)((uint)(Key.AltMask | Key.CtrlMask) + (wch2 + 64));
- } else if (wch2 >= (uint)Key.D0 && wch2 <= (uint)Key.D9) {
- k = (Key)((uint)Key.AltMask + (uint)Key.D0 + (wch2 - (uint)Key.D0));
- } else if (wch2 == 27) {
- k = (Key)wch2;
- } else if (wch2 == Curses.KEY_CODE_SEQ) {
- int [] c = null;
- while (code == 0) {
- code = Curses.get_wch (out wch2);
- if (wch2 > 0) {
- Array.Resize (ref c, c == null ? 1 : c.Length + 1);
- c [c.Length - 1] = wch2;
- }
- }
- if (c [0] == 49 && c [1] == 59 && c [2] == 55 && c [3] >= 80 && c [3] <= 83) { // Ctrl+Alt+(F1 - F4)
- wch2 = c [3] + 185;
- k = Key.CtrlMask | Key.AltMask | MapCursesKey (wch2);
- } else if (c [0] == 49 && c [2] == 59 && c [3] == 55 && c [4] == 126 && c [1] >= 53 && c [1] <= 57) { // Ctrl+Alt+(F5 - F8)
- wch2 = c [1] == 53 ? c [1] + 216 : c [1] + 215;
- k = Key.CtrlMask | Key.AltMask | MapCursesKey (wch2);
- } else if (c [0] == 50 && c [2] == 59 && c [3] == 55 && c [4] == 126 && c [1] >= 48 && c [1] <= 52) { // Ctrl+Alt+(F9 - F12)
- wch2 = c [1] < 51 ? c [1] + 225 : c [1] + 224;
- k = Key.CtrlMask | Key.AltMask | MapCursesKey (wch2);
- } else if (c [0] == 49 && c [1] == 59 && c [2] == 56 && c [3] >= 80 && c [3] <= 83) { // Ctrl+Shift+Alt+(F1 - F4)
- wch2 = c [3] + 185;
- k = Key.CtrlMask | Key.ShiftMask | Key.AltMask | MapCursesKey (wch2);
- } else if (c [0] == 49 && c [2] == 59 && c [3] == 56 && c [4] == 126 && c [1] >= 53 && c [1] <= 57) { // Ctrl+Shift+Alt+(F5 - F8)
- wch2 = c [1] == 53 ? c [1] + 216 : c [1] + 215;
- k = Key.CtrlMask | Key.ShiftMask | Key.AltMask | MapCursesKey (wch2);
- } else if (c [0] == 50 && c [2] == 59 && c [3] == 56 && c [4] == 126 && c [1] >= 48 && c [1] <= 52) { // Ctrl+Shift+Alt+(F9 - F12)
- wch2 = c [1] < 51 ? c [1] + 225 : c [1] + 224;
- k = Key.CtrlMask | Key.ShiftMask | Key.AltMask | MapCursesKey (wch2);
- } else if (c [0] == 49 && c [1] == 59 && c [2] == 52 && c [3] == 83) { // Shift+Alt+(F4)
- wch2 = 268;
- k = Key.ShiftMask | Key.AltMask | MapCursesKey (wch2);
- } else if (c [0] == 49 && c [2] == 59 && c [3] == 52 && c [4] == 126 && c [1] >= 53 && c [1] <= 57) { // Shift+Alt+(F5 - F8)
- wch2 = c [1] < 55 ? c [1] + 216 : c [1] + 215;
- k = Key.ShiftMask | Key.AltMask | MapCursesKey (wch2);
- } else if (c [0] == 50 && c [2] == 59 && c [3] == 52 && c [4] == 126 && c [1] >= 48 && c [1] <= 52) { // Shift+Alt+(F9 - F12)
- wch2 = c [1] < 51 ? c [1] + 225 : c [1] + 224;
- k = Key.ShiftMask | Key.AltMask | MapCursesKey (wch2);
- } else if (c [0] == 54 && c [1] == 59 && c [2] == 56 && c [3] == 126) { // Shift+Ctrl+Alt+KeyNPage
- k = Key.ShiftMask | Key.CtrlMask | Key.AltMask | Key.PageDown;
- } else if (c [0] == 53 && c [1] == 59 && c [2] == 56 && c [3] == 126) { // Shift+Ctrl+Alt+KeyPPage
- k = Key.ShiftMask | Key.CtrlMask | Key.AltMask | Key.PageUp;
- } else if (c [0] == 49 && c [1] == 59 && c [2] == 56 && c [3] == 72) { // Shift+Ctrl+Alt+KeyHome
- k = Key.ShiftMask | Key.CtrlMask | Key.AltMask | Key.Home;
- } else if (c [0] == 49 && c [1] == 59 && c [2] == 56 && c [3] == 70) { // Shift+Ctrl+Alt+KeyEnd
- k = Key.ShiftMask | Key.CtrlMask | Key.AltMask | Key.End;
- } else {
- k = MapCursesKey (wch2);
- }
- } else {
- // Unfortunately there are no way to differentiate Ctrl+Alt+alfa and Ctrl+Shift+Alt+alfa.
- if (((Key)wch2 & Key.CtrlMask) != 0) {
- keyModifiers.Ctrl = true;
- }
- if (wch2 == 0) {
- k = Key.CtrlMask | Key.AltMask | Key.Space;
- } else if (wch >= (uint)Key.A && wch <= (uint)Key.Z) {
- keyModifiers.Shift = true;
- keyModifiers.Alt = true;
- } else if (wch2 < 256) {
- k = (Key)wch2;
- keyModifiers.Alt = true;
- } else {
- k = (Key)((uint)(Key.AltMask | Key.CtrlMask) + wch2);
- }
- }
- key = new KeyEvent (k, MapKeyModifiers (k));
- keyDownHandler (key);
- keyHandler (key);
- } else {
- k = Key.Esc;
- keyHandler (new KeyEvent (k, MapKeyModifiers (k)));
- }
- } else if (wch == Curses.KeyTab) {
- k = MapCursesKey (wch);
- keyDownHandler (new KeyEvent (k, MapKeyModifiers (k)));
- keyHandler (new KeyEvent (k, MapKeyModifiers (k)));
- } else {
- // Unfortunately there are no way to differentiate Ctrl+alfa and Ctrl+Shift+alfa.
- k = (Key)wch;
- if (wch == 0) {
- k = Key.CtrlMask | Key.Space;
- } else if (wch >= (uint)Key.A - 64 && wch <= (uint)Key.Z - 64) {
- if ((Key)(wch + 64) != Key.J) {
- k = Key.CtrlMask | (Key)(wch + 64);
- }
- } else if (wch >= (uint)Key.A && wch <= (uint)Key.Z) {
- keyModifiers.Shift = true;
- }
- keyDownHandler (new KeyEvent (k, MapKeyModifiers (k)));
- keyHandler (new KeyEvent (k, MapKeyModifiers (k)));
- keyUpHandler (new KeyEvent (k, MapKeyModifiers (k)));
- }
- // Cause OnKeyUp and OnKeyPressed. Note that the special handling for ESC above
- // will not impact KeyUp.
- // This is causing ESC firing even if another keystroke was handled.
- //if (wch == Curses.KeyTab) {
- // keyUpHandler (new KeyEvent (MapCursesKey (wch), keyModifiers));
- //} else {
- // keyUpHandler (new KeyEvent ((Key)wch, keyModifiers));
- //}
- }
- Action<KeyEvent> keyHandler;
- Action<KeyEvent> keyDownHandler;
- Action<KeyEvent> keyUpHandler;
- Action<MouseEvent> mouseHandler;
- public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
- {
- // Note: Curses doesn't support keydown/up events and thus any passed keyDown/UpHandlers will never be called
- Curses.timeout (0);
- this.keyHandler = keyHandler;
- this.keyDownHandler = keyDownHandler;
- this.keyUpHandler = keyUpHandler;
- this.mouseHandler = mouseHandler;
- var mLoop = mainLoop.Driver as UnixMainLoop;
- mLoop.AddWatch (0, UnixMainLoop.Condition.PollIn, x => {
- ProcessInput ();
- return true;
- });
- mLoop.WinChanged += () => {
- ProcessWinChange ();
- };
- }
- Curses.Event oldMouseEvents, reportableMouseEvents;
- public override void Init (Action terminalResized)
- {
- if (window != null)
- return;
- try {
- //Set cursor key to application.
- //Console.Out.Write ("\x1b[?1h");
- //Console.Out.Flush ();
- window = Curses.initscr ();
- Curses.set_escdelay (10);
- } catch (Exception e) {
- throw new Exception ($"Curses failed to initialize, the exception is: {e.Message}");
- }
- // Ensures that all procedures are performed at some previous closing.
- Curses.doupdate ();
- //
- // We are setting Invisible as default so we could ignore XTerm DECSUSR setting
- //
- switch (Curses.curs_set (0)) {
- case 0:
- currentCursorVisibility = initialCursorVisibility = CursorVisibility.Invisible;
- break;
- case 1:
- currentCursorVisibility = initialCursorVisibility = CursorVisibility.Underline;
- Curses.curs_set (1);
- break;
- case 2:
- currentCursorVisibility = initialCursorVisibility = CursorVisibility.Box;
- Curses.curs_set (2);
- break;
- default:
- currentCursorVisibility = initialCursorVisibility = null;
- break;
- }
- if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX)) {
- clipboard = new MacOSXClipboard ();
- } else {
- if (Is_WSL_Platform ()) {
- clipboard = new WSLClipboard ();
- } else {
- clipboard = new CursesClipboard ();
- }
- }
- Curses.raw ();
- Curses.noecho ();
- Curses.Window.Standard.keypad (true);
- reportableMouseEvents = Curses.mousemask (Curses.Event.AllEvents | Curses.Event.ReportMousePosition, out oldMouseEvents);
- TerminalResized = terminalResized;
- if (reportableMouseEvents.HasFlag (Curses.Event.ReportMousePosition))
- StartReportingMouseMoves ();
- ResizeScreen ();
- UpdateOffScreen ();
- //HLine = Curses.ACS_HLINE;
- //VLine = Curses.ACS_VLINE;
- //Stipple = Curses.ACS_CKBOARD;
- //Diamond = Curses.ACS_DIAMOND;
- //ULCorner = Curses.ACS_ULCORNER;
- //LLCorner = Curses.ACS_LLCORNER;
- //URCorner = Curses.ACS_URCORNER;
- //LRCorner = Curses.ACS_LRCORNER;
- //LeftTee = Curses.ACS_LTEE;
- //RightTee = Curses.ACS_RTEE;
- //TopTee = Curses.ACS_TTEE;
- //BottomTee = Curses.ACS_BTEE;
- //RightArrow = Curses.ACS_RARROW;
- //LeftArrow = Curses.ACS_LARROW;
- //UpArrow = Curses.ACS_UARROW;
- //DownArrow = Curses.ACS_DARROW;
- if (Curses.HasColors) {
- Curses.StartColor ();
- Curses.UseDefaultColors ();
- CreateColors ();
- } else {
- CreateColors (false);
- Colors.TopLevel.Normal = Curses.COLOR_GREEN;
- Colors.TopLevel.Focus = Curses.COLOR_WHITE;
- Colors.TopLevel.HotNormal = Curses.COLOR_YELLOW;
- Colors.TopLevel.HotFocus = Curses.COLOR_YELLOW;
- Colors.TopLevel.Disabled = Curses.A_BOLD | Curses.COLOR_GRAY;
- Colors.Base.Normal = Curses.A_NORMAL;
- Colors.Base.Focus = Curses.A_REVERSE;
- Colors.Base.HotNormal = Curses.A_BOLD;
- Colors.Base.HotFocus = Curses.A_BOLD | Curses.A_REVERSE;
- Colors.Base.Disabled = Curses.A_BOLD | Curses.COLOR_GRAY;
- Colors.Menu.Normal = Curses.A_REVERSE;
- Colors.Menu.Focus = Curses.A_NORMAL;
- Colors.Menu.HotNormal = Curses.A_BOLD;
- Colors.Menu.HotFocus = Curses.A_NORMAL;
- Colors.Menu.Disabled = Curses.A_BOLD | Curses.COLOR_GRAY;
- Colors.Dialog.Normal = Curses.A_REVERSE;
- Colors.Dialog.Focus = Curses.A_NORMAL;
- Colors.Dialog.HotNormal = Curses.A_BOLD;
- Colors.Dialog.HotFocus = Curses.A_NORMAL;
- Colors.Dialog.Disabled = Curses.A_BOLD | Curses.COLOR_GRAY;
- Colors.Error.Normal = Curses.A_BOLD;
- Colors.Error.Focus = Curses.A_BOLD | Curses.A_REVERSE;
- Colors.Error.HotNormal = Curses.A_BOLD | Curses.A_REVERSE;
- Colors.Error.HotFocus = Curses.A_REVERSE;
- Colors.Error.Disabled = Curses.A_BOLD | Curses.COLOR_GRAY;
- }
- }
- public override void ResizeScreen ()
- {
- Clip = new Rect (0, 0, Cols, Rows);
- Console.Out.Write ("\x1b[3J");
- Console.Out.Flush ();
- }
- public override void UpdateOffScreen ()
- {
- contents = new int [Rows, Cols, 3];
- for (int row = 0; row < Rows; row++) {
- for (int col = 0; col < Cols; col++) {
- //Curses.move (row, col);
- //Curses.attrset (Colors.TopLevel.Normal);
- //Curses.addch ((int)(uint)' ');
- contents [row, col, 0] = ' ';
- contents [row, col, 1] = Colors.TopLevel.Normal;
- contents [row, col, 2] = 0;
- }
- }
- }
- public static bool Is_WSL_Platform ()
- {
- // xclip does not work on WSL, so we need to use the Windows clipboard vis Powershell
- //if (new CursesClipboard ().IsSupported) {
- // // If xclip is installed on Linux under WSL, this will return true.
- // return false;
- //}
- var (exitCode, result) = ClipboardProcessRunner.Bash ("uname -a", waitForOutput: true);
- if (exitCode == 0 && result.Contains ("microsoft") && result.Contains ("WSL")) {
- return true;
- }
- return false;
- }
- static int MapColor (Color color)
- {
- switch (color) {
- case Color.Black:
- return Curses.COLOR_BLACK;
- case Color.Blue:
- return Curses.COLOR_BLUE;
- case Color.Green:
- return Curses.COLOR_GREEN;
- case Color.Cyan:
- return Curses.COLOR_CYAN;
- case Color.Red:
- return Curses.COLOR_RED;
- case Color.Magenta:
- return Curses.COLOR_MAGENTA;
- case Color.Brown:
- return Curses.COLOR_YELLOW;
- case Color.Gray:
- return Curses.COLOR_WHITE;
- case Color.DarkGray:
- //return Curses.COLOR_BLACK | Curses.A_BOLD;
- return Curses.COLOR_GRAY;
- case Color.BrightBlue:
- return Curses.COLOR_BLUE | Curses.A_BOLD | Curses.COLOR_GRAY;
- case Color.BrightGreen:
- return Curses.COLOR_GREEN | Curses.A_BOLD | Curses.COLOR_GRAY;
- case Color.BrightCyan:
- return Curses.COLOR_CYAN | Curses.A_BOLD | Curses.COLOR_GRAY;
- case Color.BrightRed:
- return Curses.COLOR_RED | Curses.A_BOLD | Curses.COLOR_GRAY;
- case Color.BrightMagenta:
- return Curses.COLOR_MAGENTA | Curses.A_BOLD | Curses.COLOR_GRAY;
- case Color.BrightYellow:
- return Curses.COLOR_YELLOW | Curses.A_BOLD | Curses.COLOR_GRAY;
- case Color.White:
- return Curses.COLOR_WHITE | Curses.A_BOLD | Curses.COLOR_GRAY;
- }
- throw new ArgumentException ("Invalid color code");
- }
- static Color MapCursesColor (int color)
- {
- switch (color) {
- case Curses.COLOR_BLACK:
- return Color.Black;
- case Curses.COLOR_BLUE:
- return Color.Blue;
- case Curses.COLOR_GREEN:
- return Color.Green;
- case Curses.COLOR_CYAN:
- return Color.Cyan;
- case Curses.COLOR_RED:
- return Color.Red;
- case Curses.COLOR_MAGENTA:
- return Color.Magenta;
- case Curses.COLOR_YELLOW:
- return Color.Brown;
- case Curses.COLOR_WHITE:
- return Color.Gray;
- case Curses.COLOR_GRAY:
- return Color.DarkGray;
- case Curses.COLOR_BLUE | Curses.COLOR_GRAY:
- return Color.BrightBlue;
- case Curses.COLOR_GREEN | Curses.COLOR_GRAY:
- return Color.BrightGreen;
- case Curses.COLOR_CYAN | Curses.COLOR_GRAY:
- return Color.BrightCyan;
- case Curses.COLOR_RED | Curses.COLOR_GRAY:
- return Color.BrightRed;
- case Curses.COLOR_MAGENTA | Curses.COLOR_GRAY:
- return Color.BrightMagenta;
- case Curses.COLOR_YELLOW | Curses.COLOR_GRAY:
- return Color.BrightYellow;
- case Curses.COLOR_WHITE | Curses.COLOR_GRAY:
- return Color.White;
- }
- throw new ArgumentException ("Invalid curses color code");
- }
- public override Attribute MakeAttribute (Color fore, Color back)
- {
- var f = MapColor (fore);
- //return MakeColor ((short)(f & 0xffff), (short)MapColor (back)) | ((f & Curses.A_BOLD) != 0 ? Curses.A_BOLD : 0);
- return MakeColor ((short)(f & 0xffff), (short)MapColor (back));
- }
- public override void Suspend ()
- {
- if (reportableMouseEvents.HasFlag (Curses.Event.ReportMousePosition))
- StopReportingMouseMoves ();
- Platform.Suspend ();
- Curses.Window.Standard.redrawwin ();
- Curses.refresh ();
- if (reportableMouseEvents.HasFlag (Curses.Event.ReportMousePosition))
- StartReportingMouseMoves ();
- }
- public override void StartReportingMouseMoves ()
- {
- Console.Out.Write ("\x1b[?1003h");
- Console.Out.Flush ();
- }
- public override void StopReportingMouseMoves ()
- {
- Console.Out.Write ("\x1b[?1003l");
- Console.Out.Flush ();
- }
- //int lastMouseInterval;
- //bool mouseGrabbed;
- public override void UncookMouse ()
- {
- //if (mouseGrabbed)
- // return;
- //lastMouseInterval = Curses.mouseinterval (0);
- //mouseGrabbed = true;
- }
- public override void CookMouse ()
- {
- //mouseGrabbed = false;
- //Curses.mouseinterval (lastMouseInterval);
- }
- public override Attribute GetAttribute ()
- {
- return currentAttribute;
- }
- /// <inheritdoc/>
- public override bool GetCursorVisibility (out CursorVisibility visibility)
- {
- visibility = CursorVisibility.Invisible;
- if (!currentCursorVisibility.HasValue)
- return false;
- visibility = currentCursorVisibility.Value;
- return true;
- }
- /// <inheritdoc/>
- public override bool SetCursorVisibility (CursorVisibility visibility)
- {
- if (initialCursorVisibility.HasValue == false)
- return false;
- Curses.curs_set (((int)visibility >> 16) & 0x000000FF);
- if (visibility != CursorVisibility.Invisible) {
- Console.Out.Write ("\x1b[{0} q", ((int)visibility >> 24) & 0xFF);
- Console.Out.Flush ();
- }
- currentCursorVisibility = visibility;
- return true;
- }
- /// <inheritdoc/>
- public override bool EnsureCursorVisibility ()
- {
- return false;
- }
- public override void SendKeys (char keyChar, ConsoleKey consoleKey, bool shift, bool alt, bool control)
- {
- Key key;
- if (consoleKey == ConsoleKey.Packet) {
- ConsoleModifiers mod = new ConsoleModifiers ();
- if (shift) {
- mod |= ConsoleModifiers.Shift;
- }
- if (alt) {
- mod |= ConsoleModifiers.Alt;
- }
- if (control) {
- mod |= ConsoleModifiers.Control;
- }
- var kchar = ConsoleKeyMapping.GetKeyCharFromConsoleKey (keyChar, mod, out uint ckey, out _);
- key = ConsoleKeyMapping.MapConsoleKeyToKey ((ConsoleKey)ckey, out bool mappable);
- if (mappable) {
- key = (Key)kchar;
- }
- } else {
- key = (Key)keyChar;
- }
- KeyModifiers km = new KeyModifiers ();
- if (shift) {
- if (keyChar == 0) {
- key |= Key.ShiftMask;
- }
- km.Shift = shift;
- }
- if (alt) {
- key |= Key.AltMask;
- km.Alt = alt;
- }
- if (control) {
- key |= Key.CtrlMask;
- km.Ctrl = control;
- }
- keyDownHandler (new KeyEvent (key, km));
- keyHandler (new KeyEvent (key, km));
- keyUpHandler (new KeyEvent (key, km));
- }
- public override bool GetColors (int value, out Color foreground, out Color background)
- {
- bool hasColor = false;
- foreground = default;
- background = default;
- int back = -1;
- IEnumerable<int> values = Enum.GetValues (typeof (ConsoleColor))
- .OfType<ConsoleColor> ()
- .Select (s => (int)s);
- if (values.Contains ((value >> 12) & 0xffff)) {
- hasColor = true;
- back = (value >> 12) & 0xffff;
- background = MapCursesColor (back);
- }
- if (values.Contains ((value - (back << 12)) >> 8)) {
- hasColor = true;
- foreground = MapCursesColor ((value - (back << 12)) >> 8);
- }
- return hasColor;
- }
- }
- internal static class Platform {
- [DllImport ("libc")]
- static extern int uname (IntPtr buf);
- [DllImport ("libc")]
- static extern int killpg (int pgrp, int pid);
- static int suspendSignal;
- static int GetSuspendSignal ()
- {
- if (suspendSignal != 0)
- return suspendSignal;
- IntPtr buf = Marshal.AllocHGlobal (8192);
- if (uname (buf) != 0) {
- Marshal.FreeHGlobal (buf);
- suspendSignal = -1;
- return suspendSignal;
- }
- try {
- switch (Marshal.PtrToStringAnsi (buf)) {
- case "Darwin":
- case "DragonFly":
- case "FreeBSD":
- case "NetBSD":
- case "OpenBSD":
- suspendSignal = 18;
- break;
- case "Linux":
- // TODO: should fetch the machine name and
- // if it is MIPS return 24
- suspendSignal = 20;
- break;
- case "Solaris":
- suspendSignal = 24;
- break;
- default:
- suspendSignal = -1;
- break;
- }
- return suspendSignal;
- } finally {
- Marshal.FreeHGlobal (buf);
- }
- }
- /// <summary>
- /// Suspends the process by sending SIGTSTP to itself
- /// </summary>
- /// <returns>The suspend.</returns>
- static public bool Suspend ()
- {
- int signal = GetSuspendSignal ();
- if (signal == -1)
- return false;
- killpg (0, signal);
- return true;
- }
- }
- /// <summary>
- /// A clipboard implementation for Linux.
- /// This implementation uses the xclip command to access the clipboard.
- /// </summary>
- /// <remarks>
- /// If xclip is not installed, this implementation will not work.
- /// </remarks>
- class CursesClipboard : ClipboardBase {
- public CursesClipboard ()
- {
- IsSupported = CheckSupport ();
- }
- string xclipPath = string.Empty;
- public override bool IsSupported { get; }
- bool CheckSupport ()
- {
- try {
- var (exitCode, result) = ClipboardProcessRunner.Bash ("which xclip", waitForOutput: true);
- if (exitCode == 0 && result.FileExists ()) {
- xclipPath = result;
- return true;
- }
- } catch (Exception) {
- // Permissions issue.
- }
- return false;
- }
- protected override string GetClipboardDataImpl ()
- {
- var tempFileName = System.IO.Path.GetTempFileName ();
- var xclipargs = "-selection clipboard -o";
- try {
- var (exitCode, result) = ClipboardProcessRunner.Bash ($"{xclipPath} {xclipargs} > {tempFileName}", waitForOutput: false);
- if (exitCode == 0) {
- if (Application.Driver is CursesDriver) {
- Curses.raw ();
- Curses.noecho ();
- }
- return System.IO.File.ReadAllText (tempFileName);
- }
- } catch (Exception e) {
- throw new NotSupportedException ($"\"{xclipPath} {xclipargs}\" failed.", e);
- } finally {
- System.IO.File.Delete (tempFileName);
- }
- return string.Empty;
- }
- protected override void SetClipboardDataImpl (string text)
- {
- var xclipargs = "-selection clipboard -i";
- try {
- var (exitCode, _) = ClipboardProcessRunner.Bash ($"{xclipPath} {xclipargs}", text, waitForOutput: false);
- if (exitCode == 0 && Application.Driver is CursesDriver) {
- Curses.raw ();
- Curses.noecho ();
- }
- } catch (Exception e) {
- throw new NotSupportedException ($"\"{xclipPath} {xclipargs} < {text}\" failed", e);
- }
- }
- }
- internal static class ClipboardProcessRunner {
- public static (int exitCode, string result) Bash (string commandLine, string inputText = "", bool waitForOutput = false)
- {
- var arguments = $"-c \"{commandLine}\"";
- var (exitCode, result) = Process ("bash", arguments, inputText, waitForOutput);
- return (exitCode, result.TrimEnd ());
- }
- public static (int exitCode, string result) Process (string cmd, string arguments, string input = null, bool waitForOutput = true)
- {
- var output = string.Empty;
- using (Process process = new Process {
- StartInfo = new ProcessStartInfo {
- FileName = cmd,
- Arguments = arguments,
- RedirectStandardOutput = true,
- RedirectStandardError = true,
- RedirectStandardInput = true,
- UseShellExecute = false,
- CreateNoWindow = true,
- }
- }) {
- var eventHandled = new TaskCompletionSource<bool> ();
- process.Start ();
- if (!string.IsNullOrEmpty (input)) {
- process.StandardInput.Write (input);
- process.StandardInput.Close ();
- }
- if (!process.WaitForExit (5000)) {
- var timeoutError = $@"Process timed out. Command line: {process.StartInfo.FileName} {process.StartInfo.Arguments}.";
- throw new TimeoutException (timeoutError);
- }
- if (waitForOutput && process.StandardOutput.Peek () != -1) {
- output = process.StandardOutput.ReadToEnd ().TrimEnd ();
- }
- if (process.ExitCode > 0) {
- output = $@"Process failed to run. Command line: {cmd} {arguments}.
- Output: {output}
- Error: {process.StandardError.ReadToEnd ()}";
- }
- if (Application.Driver is CursesDriver) {
- Curses.raw ();
- Curses.noecho ();
- }
- return (process.ExitCode, output);
- }
- }
- public static bool DoubleWaitForExit (this System.Diagnostics.Process process)
- {
- var result = process.WaitForExit (500);
- if (result) {
- process.WaitForExit ();
- }
- return result;
- }
- public static bool FileExists (this string value)
- {
- return !string.IsNullOrEmpty (value) && !value.Contains ("not found");
- }
- }
- /// <summary>
- /// A clipboard implementation for MacOSX.
- /// This implementation uses the Mac clipboard API (via P/Invoke) to copy/paste.
- /// The existance of the Mac pbcopy and pbpaste commands
- /// is used to determine if copy/paste is supported.
- /// </summary>
- class MacOSXClipboard : ClipboardBase {
- IntPtr nsString = objc_getClass ("NSString");
- IntPtr nsPasteboard = objc_getClass ("NSPasteboard");
- IntPtr utfTextType;
- IntPtr generalPasteboard;
- IntPtr initWithUtf8Register = sel_registerName ("initWithUTF8String:");
- IntPtr allocRegister = sel_registerName ("alloc");
- IntPtr setStringRegister = sel_registerName ("setString:forType:");
- IntPtr stringForTypeRegister = sel_registerName ("stringForType:");
- IntPtr utf8Register = sel_registerName ("UTF8String");
- IntPtr nsStringPboardType;
- IntPtr generalPasteboardRegister = sel_registerName ("generalPasteboard");
- IntPtr clearContentsRegister = sel_registerName ("clearContents");
- public MacOSXClipboard ()
- {
- utfTextType = objc_msgSend (objc_msgSend (nsString, allocRegister), initWithUtf8Register, "public.utf8-plain-text");
- nsStringPboardType = objc_msgSend (objc_msgSend (nsString, allocRegister), initWithUtf8Register, "NSStringPboardType");
- generalPasteboard = objc_msgSend (nsPasteboard, generalPasteboardRegister);
- IsSupported = CheckSupport ();
- }
- public override bool IsSupported { get; }
- bool CheckSupport ()
- {
- var (exitCode, result) = ClipboardProcessRunner.Bash ("which pbcopy", waitForOutput: true);
- if (exitCode != 0 || !result.FileExists ()) {
- return false;
- }
- (exitCode, result) = ClipboardProcessRunner.Bash ("which pbpaste", waitForOutput: true);
- return exitCode == 0 && result.FileExists ();
- }
- protected override string GetClipboardDataImpl ()
- {
- var ptr = objc_msgSend (generalPasteboard, stringForTypeRegister, nsStringPboardType);
- var charArray = objc_msgSend (ptr, utf8Register);
- return Marshal.PtrToStringAnsi (charArray);
- }
- protected override void SetClipboardDataImpl (string text)
- {
- IntPtr str = default;
- try {
- str = objc_msgSend (objc_msgSend (nsString, allocRegister), initWithUtf8Register, text);
- objc_msgSend (generalPasteboard, clearContentsRegister);
- objc_msgSend (generalPasteboard, setStringRegister, str, utfTextType);
- } finally {
- if (str != default) {
- objc_msgSend (str, sel_registerName ("release"));
- }
- }
- }
- [DllImport ("/System/Library/Frameworks/AppKit.framework/AppKit")]
- static extern IntPtr objc_getClass (string className);
- [DllImport ("/System/Library/Frameworks/AppKit.framework/AppKit")]
- static extern IntPtr objc_msgSend (IntPtr receiver, IntPtr selector);
- [DllImport ("/System/Library/Frameworks/AppKit.framework/AppKit")]
- static extern IntPtr objc_msgSend (IntPtr receiver, IntPtr selector, string arg1);
- [DllImport ("/System/Library/Frameworks/AppKit.framework/AppKit")]
- static extern IntPtr objc_msgSend (IntPtr receiver, IntPtr selector, IntPtr arg1);
- [DllImport ("/System/Library/Frameworks/AppKit.framework/AppKit")]
- static extern IntPtr objc_msgSend (IntPtr receiver, IntPtr selector, IntPtr arg1, IntPtr arg2);
- [DllImport ("/System/Library/Frameworks/AppKit.framework/AppKit")]
- static extern IntPtr sel_registerName (string selectorName);
- }
- /// <summary>
- /// A clipboard implementation for Linux, when running under WSL.
- /// This implementation uses the Windows clipboard to store the data, and uses Windows'
- /// powershell.exe (launched via WSL interop services) to set/get the Windows
- /// clipboard.
- /// </summary>
- class WSLClipboard : ClipboardBase {
- bool isSupported = false;
- public WSLClipboard ()
- {
- isSupported = CheckSupport ();
- }
- public override bool IsSupported {
- get {
- return isSupported = CheckSupport ();
- }
- }
- private static string powershellPath = string.Empty;
- bool CheckSupport ()
- {
- if (string.IsNullOrEmpty (powershellPath)) {
- // Specify pwsh.exe (not pwsh) to ensure we get the Windows version (invoked via WSL)
- var (exitCode, result) = ClipboardProcessRunner.Bash ("which pwsh.exe", waitForOutput: true);
- if (exitCode > 0) {
- (exitCode, result) = ClipboardProcessRunner.Bash ("which powershell.exe", waitForOutput: true);
- }
- if (exitCode == 0) {
- powershellPath = result;
- }
- }
- return !string.IsNullOrEmpty (powershellPath);
- }
- protected override string GetClipboardDataImpl ()
- {
- if (!IsSupported) {
- return string.Empty;
- }
- var (exitCode, output) = ClipboardProcessRunner.Process (powershellPath, "-noprofile -command \"Get-Clipboard\"");
- if (exitCode == 0) {
- if (Application.Driver is CursesDriver) {
- Curses.raw ();
- Curses.noecho ();
- }
- if (output.EndsWith ("\r\n")) {
- output = output.Substring (0, output.Length - 2);
- }
- return output;
- }
- return string.Empty;
- }
- protected override void SetClipboardDataImpl (string text)
- {
- if (!IsSupported) {
- return;
- }
- var (exitCode, output) = ClipboardProcessRunner.Process (powershellPath, $"-noprofile -command \"Set-Clipboard -Value \\\"{text}\\\"\"");
- if (exitCode == 0) {
- if (Application.Driver is CursesDriver) {
- Curses.raw ();
- Curses.noecho ();
- }
- }
- }
- }
- }
|