From ccb6eb4379c7639106239221551180699dfdf261 Mon Sep 17 00:00:00 2001 From: Avril Date: Sun, 24 May 2020 04:22:24 +0100 Subject: [PATCH] Initial commit --- .gitignore | 360 ++++++++++++++++++++++++++++++ termsync.sln | 31 +++ termsync/AsyncTools.cs | 200 +++++++++++++++++ termsync/Control.cs | 44 ++++ termsync/Mutations.cs | 58 +++++ termsync/Terminal.cs | 466 +++++++++++++++++++++++++++++++++++++++ termsync/termsync.csproj | 7 + test/Program.cs | 47 ++++ test/test.csproj | 12 + 9 files changed, 1225 insertions(+) create mode 100644 .gitignore create mode 100644 termsync.sln create mode 100644 termsync/AsyncTools.cs create mode 100644 termsync/Control.cs create mode 100644 termsync/Mutations.cs create mode 100644 termsync/Terminal.cs create mode 100644 termsync/termsync.csproj create mode 100644 test/Program.cs create mode 100644 test/test.csproj diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..83ba081 --- /dev/null +++ b/.gitignore @@ -0,0 +1,360 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*[.json, .xml, .info] + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd diff --git a/termsync.sln b/termsync.sln new file mode 100644 index 0000000..aff8a79 --- /dev/null +++ b/termsync.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29609.76 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "termsync", "termsync\termsync.csproj", "{2CBA290C-FF91-4825-B96B-83A0F9151F9E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "test", "test\test.csproj", "{B4D9D0D8-C63A-479A-8443-48CCBFBB1C56}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {2CBA290C-FF91-4825-B96B-83A0F9151F9E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2CBA290C-FF91-4825-B96B-83A0F9151F9E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2CBA290C-FF91-4825-B96B-83A0F9151F9E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2CBA290C-FF91-4825-B96B-83A0F9151F9E}.Release|Any CPU.Build.0 = Release|Any CPU + {B4D9D0D8-C63A-479A-8443-48CCBFBB1C56}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B4D9D0D8-C63A-479A-8443-48CCBFBB1C56}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B4D9D0D8-C63A-479A-8443-48CCBFBB1C56}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B4D9D0D8-C63A-479A-8443-48CCBFBB1C56}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {E035A5E5-8125-44B3-8F69-557971CAFB19} + EndGlobalSection +EndGlobal diff --git a/termsync/AsyncTools.cs b/termsync/AsyncTools.cs new file mode 100644 index 0000000..d8639e6 --- /dev/null +++ b/termsync/AsyncTools.cs @@ -0,0 +1,200 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using System.Linq; +using System.Collections.Generic; + +namespace termsync.Tools +{ + sealed class AsyncMutex : IDisposable + { + private readonly SemaphoreSlim sem; + + public AsyncMutex() + { + sem = new SemaphoreSlim(1, 1); + } + private AsyncMutex(SemaphoreSlim from) + { + sem = from; + } + + private class Lock : IDisposable + { + public AsyncMutex Parent { get; } + public Lock(AsyncMutex held) + { + Parent = held; + } + + public void Dispose() + { + Parent.sem.Release(); + } + } + + public IDisposable Acquire(int msTimeout, CancellationToken token = default) + { + sem.Wait(msTimeout, token); + return new Lock(this); + } + + public IDisposable Acquire(CancellationToken token) + { + sem.Wait(token); + return new Lock(this); + } + + public IDisposable Acquire() + { + sem.Wait(); + return new Lock(this); + } + + public async Task AcquireAsync(int msTimeout, CancellationToken token = default) + { + await sem.WaitAsync(msTimeout, token); + return new Lock(this); + } + + public async Task AcquireAsync(CancellationToken token = default) + { + await sem.WaitAsync(token); + return new Lock(this); + } + + public void Dispose() + { + sem.Dispose(); + } + + public static AsyncMutex Semaphore(int count, int max) + { + SemaphoreSlim sem = new SemaphoreSlim(count, max); + return new AsyncMutex(sem); + } + public static AsyncMutex Semaphore(int count) + => Semaphore(count, count); + } + + static class ExAsyncTools + { + #region Then() + public static async Task Then(this Task t, Action lam) + { + await t; + lam(); + } + public static Task Then(this Task t, Action lam, CancellationToken token) + => Then(t, (_) => lam(), token); + public static async Task Then(this Task t, Action lam, CancellationToken token) + { + TaskCompletionSource fail = new TaskCompletionSource(); + + using (token.Register(() => fail.TrySetResult(false))) + { + if ((await Task.WhenAny(t, fail.Task)) == t) + { + lam(token); + } + token.ThrowIfCancellationRequested(); + } + } + public static async Task Then(this Task t, Func lam) + { + await t; + await lam(); + } + public static Task Then(this Task t, Func lam, CancellationToken token) + => Then(t, (_) => lam(), token); + public static async Task Then(this Task t, Func lam, CancellationToken token) + { + TaskCompletionSource fail = new TaskCompletionSource(); + + using (token.Register(() => fail.TrySetResult(false))) + { + if ((await Task.WhenAny(t, fail.Task)) == t) + { + await lam(token); + } + token.ThrowIfCancellationRequested(); + } + } + public static async Task Then(this Task t, Action lam) + { + T res = await t; + lam(res); + return res; + } + public static Task Then(this Task t, Action lam, CancellationToken token) + => Then(t, (v, _) => lam(v), token); + public static async Task Then(this Task t, Action lam, CancellationToken token) + { + TaskCompletionSource fail = new TaskCompletionSource(); + + using (token.Register(() => fail.TrySetResult(false))) + { + if ((await Task.WhenAny(t, fail.Task)) == t) + { + var res = t.Result; + lam(res, token); + return res; + } + throw new OperationCanceledException(); + } + } + public static async Task Then(this Task t, Func lam) + { + T res = await t; + return lam(res); + } + public static Task Then(this Task t, Func lam, CancellationToken token) + => Then(t, (v, _) => lam(v), token); + public static async Task Then(this Task t, Func lam, CancellationToken token) + { + TaskCompletionSource fail = new TaskCompletionSource(); + + using (token.Register(() => fail.TrySetResult(false))) + { + if ((await Task.WhenAny(t, fail.Task)) == t) + { + var res = t.Result; + res = lam(res, token); + return res; + } + throw new OperationCanceledException(); + } + } + public static async Task Then(this Task t, Func> lam) + { + return await lam(await t); + } + public static Task Then(this Task t, Func> lam, CancellationToken token) + => Then(t, (x, _) => lam(x), token); + public static async Task Then(this Task t, Func> lam, CancellationToken token) + { + TaskCompletionSource fail = new TaskCompletionSource(); + + using (token.Register(() => fail.TrySetResult(false))) + { + if ((await Task.WhenAny(t, fail.Task)) == t) + { + var res = t.Result; + res = await lam(res, token); + return res; + } + throw new OperationCanceledException(); + } + } + #endregion + + public static CancellationTokenSource Link(this in CancellationToken token, params CancellationToken[] others) + { + return CancellationTokenSource.CreateLinkedTokenSource(new CancellationToken[] { token }.Concat(others).ToArray()); + } + + + } + + +} diff --git a/termsync/Control.cs b/termsync/Control.cs new file mode 100644 index 0000000..073cdc8 --- /dev/null +++ b/termsync/Control.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; + +namespace termsync +{ + enum DeleteLocation + { + Before, //Backspace + After, //DEL + } + enum MoveDirection + { + Left,Right, + } + enum ControlType + { + Print, //WriteLine + + Move, //Move the cursor + Delete, //Delete a character from input + Commit, //Commit input + Echo, // Add a character to input + + ChangePrompt, + } + readonly struct ControlValue + { + public readonly ControlType Type; + + public readonly object Value; + + public readonly TaskCompletionSource Processed; + + public ControlValue(ControlType type, object value) + { + Type = type; + Value = value; + + Processed = new TaskCompletionSource(); + } + } +} diff --git a/termsync/Mutations.cs b/termsync/Mutations.cs new file mode 100644 index 0000000..1ca2e4d --- /dev/null +++ b/termsync/Mutations.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading; +using System.Threading.Channels; +using System.Threading.Tasks; + +namespace termsync +{ + static partial class Terminal + { + private static class Mutation + { + public static void ClearInputBuffer() + { + Console.CursorLeft = 0; + Console.Write(new string(' ', Console.WindowWidth - 1)); + Console.CursorLeft = 0; + } + + public static void RedrawInputBuffer(bool prompt=true) + { + if(prompt) + Console.Write(Prompt); + + if (InputBuffer.Count > 0) + Console.Write(InputBuffer.ToArray()); + if (InputAt > -1) + Console.CursorLeft -= InputBuffer.Count - InputAt; + } + + public static void MoveBackOne() + { + Console.MoveBufferArea(Console.CursorLeft + 1, Console.CursorTop, InputBuffer.Count - InputAt, 1, Console.CursorLeft, Console.CursorTop); + } + public static void MoveForwardOne() + { + Console.MoveBufferArea(Console.CursorLeft, Console.CursorTop, InputBuffer.Count - InputAt, 1, Console.CursorLeft + 1, Console.CursorTop); + } + + public static async Task FlushAsync(ChannelWriter lines, CancellationToken token =default) + { + ClearInputBuffer(); + var inp = new string(InputBuffer.ToArray()); + var line_send= lines.WriteAsync(inp, token); + InputBuffer.Clear(); + InputAt = -1; + + RedrawInputBuffer(); + + if (WriteLineOnFlush) + await WriteLine(Prompt + inp, token); + + await line_send; + } + } + } +} diff --git a/termsync/Terminal.cs b/termsync/Terminal.cs new file mode 100644 index 0000000..074a830 --- /dev/null +++ b/termsync/Terminal.cs @@ -0,0 +1,466 @@ +using System; +using System.Threading.Tasks; +using System.Threading; +using System.Threading.Channels; + +using termsync.Tools; +using System.Collections.Generic; + +namespace termsync +{ + /// + /// A Write container that aquires a mutex on `Terminal`, preventing other writes while held. + /// + public sealed class TermLock : IDisposable + { + private readonly CancellationTokenSource cancel; + private readonly AsyncMutex GlobalMutex; + private IDisposable held_lock = null; + internal TermLock(AsyncMutex mutex, CancellationToken token=default) + { + GlobalMutex = mutex; + + cancel = CancellationTokenSource.CreateLinkedTokenSource(token); + } + + internal async Task Acquire() + { + held_lock = await GlobalMutex.AcquireAsync(cancel.Token); + } + + /// + /// Write a line with lock held. + /// + public Task WriteLine(string line) + { + return Terminal.WriteLineAndWait(line, cancel.Token); + } + + public void Dispose() + { + cancel.Cancel(); + cancel.Dispose(); + if(held_lock!=null) + { + held_lock.Dispose(); + held_lock = null; + } + } + + ~TermLock() + { + if (held_lock != null) + { + held_lock.Dispose(); + held_lock = null; + } + } + } + + public sealed class TermStage : IAsyncDisposable + { + private readonly AsyncMutex mutex = new AsyncMutex(); + private readonly List lines = new List(); + private readonly CancellationTokenSource cancel; + private readonly AsyncMutex globalMutex; + private readonly CancellationToken originalToken; + + internal TermStage(AsyncMutex globalM, CancellationToken token) + { + originalToken = token; + globalMutex = globalM; + cancel = CancellationTokenSource.CreateLinkedTokenSource(token); + } + + public async Task WriteLine(string line) + { + using (await mutex.AcquireAsync(cancel.Token)) + { + lines.Add(line); + } + } + + public async ValueTask DisposeAsync() + { + await mutex.AcquireAsync(cancel.Token); + + cancel.Cancel(); + + mutex.Dispose(); + cancel.Dispose(); + + using (await globalMutex.AcquireAsync(originalToken)) + { + foreach (var line in lines) + { + await Terminal.WriteLineAndWait(line, originalToken); + } + } + + lines.Clear(); + } + } + + //TODO: WriteLine staging that doesn't block until read to commit all. + + /// + /// Terminal control global state. + /// + public static partial class Terminal + { + #region Sync + private static readonly CancellationTokenSource CancelAll = new CancellationTokenSource(); + private static ChannelReader Input; + private static ChannelWriter Output; + + private static readonly AsyncMutex ConsoleMutex = new AsyncMutex(); + + #endregion + #region Buffer + private static readonly List InputBuffer = new List(); + /// + /// The place in the that the user is writing to. + /// + private static int InputAt = -1; + public static string Prompt { get; private set; } = "> "; + private static bool WriteLineOnFlush = true; + + #endregion + + #region Control + private static readonly AsyncMutex UserWriteMutex = new AsyncMutex(); + private static readonly AsyncMutex UserReadMutex = new AsyncMutex(); + + /// + /// Acquire global Write lock mutex. + /// + public static async Task Lock() + { + var l = new TermLock(UserWriteMutex, CancelAll.Token); + await l.Acquire(); + return l; + } + + /// + /// Create a staging container that will write all lines at once on DisposeAsync(). + /// + public static TermStage Stage() + { + return new TermStage(UserWriteMutex, CancelAll.Token); + } + + private static async Task SendAndWait(ControlValue value, CancellationToken token = default) + { + TaskCompletionSource onCancel = new TaskCompletionSource(); + using var reg = token.Register(() => + { + onCancel.SetResult(false); + }); + await Output.WriteAsync(value, token); + + + if (await Task.WhenAny(value.Processed.Task, onCancel.Task) == value.Processed.Task) + { + return value.Processed.Task.Result; + } + else throw new OperationCanceledException(); + } + /// + /// Write a line to the Terminal and wait for it to appear. + /// + /// The line + public static async Task WriteLine(string line) + { + using(await UserWriteMutex.AcquireAsync(CancelAll.Token)) + { + await SendAndWait(new ControlValue(ControlType.Print, line), CancelAll.Token); + } + } + internal static ValueTask WriteLine(string str, CancellationToken token) + { + return Output.WriteAsync(new ControlValue(ControlType.Print, str), token); + } + internal static Task WriteLineAndWait(string str, CancellationToken token) + { + return SendAndWait(new ControlValue(ControlType.Print, str), token); + } + + /// + /// Read a line from the user. + /// + public static async Task ReadLine(CancellationToken token=default) + { + using var cancel = CancellationTokenSource.CreateLinkedTokenSource(CancelAll.Token, token); + token = cancel.Token; + + using (await UserReadMutex.AcquireAsync(token)) + { + return await Input.ReadAsync(token); + } + } + + /// + /// Change the user prompt. + /// + /// New prompt. + public static async Task ChangePrompt(string prompt) + { + using (await UserWriteMutex.AcquireAsync(CancelAll.Token)) + { + await SendAndWait(new ControlValue(ControlType.ChangePrompt, prompt), CancelAll.Token); + } + } + + #endregion + + /// + /// Initialise terminal control. Writes go through after this. + /// + /// The control task. + public static Task Initialise() + { + + var input = Channel.CreateUnbounded(); + var output = Channel.CreateBounded(10); + + Input = input.Reader; + Output = output.Writer; + + AppDomain.CurrentDomain.ProcessExit += (_, __) => Cleanup(); + var t_output = Task.Run(async () => + { + try + { + await ctrl_output(output.Reader, input.Writer); + } + catch (OperationCanceledException) { } + catch (Exception ex) + { + if (!CancelAll.IsCancellationRequested) + CancelAll.Cancel(); + } + }); + + var t_input = Task.Run(async () => + { + try + { + await ctrl_intput(); + } + catch (OperationCanceledException) { } + catch (Exception ex) + { + if(!CancelAll.IsCancellationRequested) + CancelAll.Cancel(); + } + }); + + return Task.Run(async () => + { + await Task.WhenAll(t_input, t_output); + }); + } + + private static async Task ctrl_output(ChannelReader output, ChannelWriter lines) + { + await foreach(var value in output.ReadAllAsync(CancelAll.Token)) + { + object result = null; + try + { + switch (value.Type) + { + case ControlType.Print when value.Value is string line: + using (await ConsoleMutex.AcquireAsync(CancelAll.Token)) + { + Mutation.ClearInputBuffer(); + Console.WriteLine(line); + Mutation.RedrawInputBuffer(); + } + break; + case ControlType.Move: + using (await ConsoleMutex.AcquireAsync(CancelAll.Token)) + { + if (InputAt == -1) InputAt = InputBuffer.Count; + switch ((MoveDirection)value.Value) + { + case MoveDirection.Left: + if (InputAt > 0) + { + InputAt -= 1; + Console.CursorLeft -= 1; + } + break; + case MoveDirection.Right: + if (InputAt < InputBuffer.Count) + { + InputAt += 1; + Console.CursorLeft += 1; + } + break; + } + if (InputAt >= InputBuffer.Count) + InputAt = -1; + } + break; + case ControlType.Delete: + using (await ConsoleMutex.AcquireAsync(CancelAll.Token)) + { + switch ((DeleteLocation)value.Value) + { + case DeleteLocation.After: + if (InputBuffer.Count > 0) + { + if (InputAt >= 0 && InputAt < InputBuffer.Count) + { + InputBuffer.RemoveAt(InputAt); + + Console.Write(" \b"); + Mutation.MoveBackOne(); + } + } + break; + case DeleteLocation.Before: + if (InputBuffer.Count > 0) + { + if (InputAt > 0 && InputAt < InputBuffer.Count) + { + InputBuffer.RemoveAt(InputAt - 1); + InputAt -= 1; + + Console.Write("\b"); + Mutation.MoveBackOne(); + } + else if (InputAt != 0) + { + InputBuffer.RemoveAt(InputBuffer.Count - 1); + Console.Write("\b \b"); + } + } + break; + } + } + break; + case ControlType.Commit: + using (await ConsoleMutex.AcquireAsync(CancelAll.Token)) + { + await Mutation.FlushAsync(lines, CancelAll.Token); + } + break; + case ControlType.Echo: + using (await ConsoleMutex.AcquireAsync(CancelAll.Token)) + { + var input = value.Value as string; + if (input == null) continue; + for (int i = 0; i < input.Length; i++) + { + switch (input[i]) + { + case '\n': + case '\r': + //Should be handled by `Commit`, something went wrong if they end up here. + break; + case '\b': + //Ditto for `Delete`. + break; + default: + { + if (((InputAt == -1) ? Console.CursorLeft : Console.CursorLeft + (InputBuffer.Count - InputAt)) >= Console.BufferWidth - 1) break; //TODO: Scrolling buffer? + + if (InputAt >= 0 && InputAt < InputBuffer.Count) + { + InputBuffer.Insert(InputAt, input[i]); + InputAt += 1; + + Mutation.MoveForwardOne(); + } + else + { + InputBuffer.Add(input[i]); + } + Console.Write(input[i]); + } + break; + } + } + } + break; + case ControlType.ChangePrompt: + using (await ConsoleMutex.AcquireAsync(CancelAll.Token)) + { + Prompt = (string)value.Value; + + Mutation.ClearInputBuffer(); + Mutation.RedrawInputBuffer(); + } + break; + } + } + finally + { + value.Processed.SetResult(result); + } + } + + lines.Complete(); + InputBuffer.Clear(); + } + /// + /// Read from the Console and pipe buffer control events to `Output`. + /// + private static async Task ctrl_intput() + { + while (!CancelAll.IsCancellationRequested) + { + var key = Console.ReadKey(true); // This blocks. + + if (CancelAll.IsCancellationRequested) break; + switch (key.Key) + { + case ConsoleKey.LeftArrow: + await Output.WriteAsync(new ControlValue(ControlType.Move, MoveDirection.Left), CancelAll.Token); + + break; + case ConsoleKey.RightArrow: + await Output.WriteAsync(new ControlValue(ControlType.Move, MoveDirection.Right), CancelAll.Token); + + break; + case ConsoleKey.Delete: + await Output.WriteAsync(new ControlValue(ControlType.Delete, DeleteLocation.After), CancelAll.Token); + break; + case ConsoleKey.Backspace: + await Output.WriteAsync(new ControlValue(ControlType.Delete, DeleteLocation.Before), CancelAll.Token); + break; + case ConsoleKey.Enter: + await Output.WriteAsync(new ControlValue(ControlType.Commit, null), CancelAll.Token); + break; + default: + await Output.WriteAsync(new ControlValue(ControlType.Echo, new string(new[] { key.KeyChar })), CancelAll.Token); + break; + } + + } + } + + /// + /// Close all channels. + /// + public static void Close() + { + Output.Complete(); + } + private static void Cleanup() + { + try + { + Output.Complete(); + } + catch { } + if (!CancelAll.IsCancellationRequested) + CancelAll.Cancel(); + + CancelAll.Dispose(); + ConsoleMutex.Dispose(); + } + } +} diff --git a/termsync/termsync.csproj b/termsync/termsync.csproj new file mode 100644 index 0000000..01ca256 --- /dev/null +++ b/termsync/termsync.csproj @@ -0,0 +1,7 @@ + + + + netcoreapp3.1 + + + diff --git a/test/Program.cs b/test/Program.cs new file mode 100644 index 0000000..1dfa485 --- /dev/null +++ b/test/Program.cs @@ -0,0 +1,47 @@ +using System; +using System.Threading.Tasks; +using termsync; + +namespace test +{ + class Program + { + static async Task Main(string[] args) + { + _ = Terminal.Initialise(); + + await Terminal.WriteLine("Hiya!"); + await Terminal.WriteLine("Another line..."); + var line = await Terminal.ReadLine(); + await Terminal.WriteLine("Line: " + line); + + await Task.WhenAll(Task.Run(async () => + { + await using (var stage = Terminal.Stage()) + { + await stage.WriteLine("One line"); + await stage.WriteLine("Two line"); + await stage.WriteLine("Three line"); + await stage.WriteLine("Four"); + } + }), + Task.Run(async () => + { + using (var lck = await Terminal.Lock()) + { + await lck.WriteLine("One line locked"); + await lck.WriteLine("Two line locked"); + await lck.WriteLine("Three line locked"); + await lck.WriteLine("Four locked"); + } + })); + + await Terminal.ChangePrompt("USER> " + await Terminal.ReadLine()+":: "); + + await Terminal.WriteLine("New prompt!"); + await Terminal.ReadLine(); + + Terminal.Close(); + } + } +} diff --git a/test/test.csproj b/test/test.csproj new file mode 100644 index 0000000..8ef6f70 --- /dev/null +++ b/test/test.csproj @@ -0,0 +1,12 @@ + + + + Exe + netcoreapp3.1 + + + + + + +