/// <summary> /// Prompts the user for a value for the parameter using the specified prompt message. /// The method only returns when the user has provided a new value that can be validated using <see cref="Validator"/>. /// Existing value (if any) will be overwritten. /// </summary> /// <param name="promptMessage">The prompt message.</param> public override void Prompt(ConsoleString promptMessage) { T temp = default(T); if (typeof(T).GetTypeInfo().IsEnum) { Consoles.System.Write(promptMessage); var left = Consoles.System.CursorLeft; Consoles.System.WriteLine(); temp = Consoles.System.MenuSelectEnum <T>(cleanup: MenuCleanup.RemoveMenu); Consoles.System.SetCursorPosition(left, Consoles.System.CursorTop - 1); Consoles.System.RenderLine(temp?.ToString() ?? string.Empty); } else { throw new NotSupportedException("Prompt is not supported in this intermediate state"); } //temp = Consoles.System.ReadLine<T>(_parserCustom, _parserSettings, promptMessage, validator: validator); IsSet = true; value = temp; doCallback(); }
/// <summary> /// Initializes a new instance of the <see cref="MenuDisplay{T}"/> class. /// </summary> /// <param name="point">The point where the menu should be displayed.</param> /// <param name="displayedLines"> /// The maximum number of console lines the menu display should use. /// The menu can display more options than this value. /// Values greater than the height of the console can result in odd effects.</param> public MenuDisplay(IConsole console, ConsolePoint point, int displayedLines) { _console = console ?? throw new ArgumentNullException(nameof(console)); _windowOrigin = _console.GetWindowPosition(); _origin = point; _options = new MenuOptionCollection <TOption>(); _options.CollectionChanged += OptionsCollectionChanged; _displayed = new List <ConsoleString>(); for (int i = 0; i < displayedLines; i++) { _displayed.Add(""); } _displayOffset = 0; _index = -1; _prompt = "> "; _noPrompt = " "; _prefixTop = new PrefixKeyCollection(); _prefixBottom = new PrefixKeyCollection(); _hasPrefix = false; _prefixTop.PrefixSetChanged += UpdateAllOptions; _prefixBottom.PrefixSetChanged += UpdateAllOptions; }
public void TestBasicConsoleString() { ConsoleString val = new ConsoleString("Adam"); val += " Abdelhamed"; ValidateStringCharacteristics("Adam Abdelhamed", val); }
/// <summary> /// Renders the middle portion of the progress bar that contains the message and progress fill. You must have called Render() ahead of time for this /// to make sense. /// </summary> public void Update() { var maxMessageLength = Width - 4; renderedMessage = Message; renderedMessage = renderedMessage.Replace("{%}", Math.Round(Progress * 100, 1) + " %"); if (renderedMessage.Length > maxMessageLength) { renderedMessage = renderedMessage.Substring(0, maxMessageLength - 3) + "..."; } while (renderedMessage.Length < maxMessageLength) { renderedMessage += " "; } if (indeterminateHighlightIndex < 0) { int toHighlight = (int)Math.Round(Progress * renderedMessage.Length); renderedMessage = renderedMessage.HighlightSubstring(0, toHighlight, MessageFillColor, FillColor); } else { renderedMessage = renderedMessage.HighlightSubstring(indeterminateHighlightIndex, 1, MessageFillColor, FillColor); } messageStart.Restore(); Console.Write(renderedMessage); wiper.MoveCursorToLineAfterBottom(); }
public ReadPasswordConfiguration(ConsoleString prompt, ConsoleString renderAs, bool repeatRender) { Prompt = prompt ?? throw new ArgumentNullException(nameof(prompt)); RenderAs = renderAs ?? throw new ArgumentNullException(nameof(renderAs)); RepeatRender = repeatRender; }
#pragma warning disable CS1591 // Documentation of each Visit method is redundant public override ConsoleString Visit(FormatVariableElement format, T item) { if (_variables.TryGetValue(format.Name, out var variable)) { var content = variable.Selector(item); int diff = (variable.PaddedLength ?? content.Length) - content.Length; if (diff > 0) { switch (format.Padding) { case FormatVariablePaddings.PadLeft: return(ConsoleString.FromContent(new string(' ', diff) + content)); case FormatVariablePaddings.PadRight: return(ConsoleString.FromContent(content + new string(' ', diff))); case FormatVariablePaddings.PadBoth: return(ConsoleString.FromContent(new string(' ', diff / 2) + content + new string(' ', diff - (diff / 2)))); } } return(ConsoleString.FromContent(content)); } else { return(GetErrorString("UNKNOWN VARIABLE", format.Name)); } }
public static Promise <ConsoleString> ShowRichTextInput(ConsoleString message, bool allowEscapeToCancel = true, int maxHeight = 12, ConsoleString initialValue = null) { var d = Deferred <ConsoleString> .Create(); ShowRichTextInput(message, (ret) => d.Resolve(ret), () => d.Resolve(null), allowEscapeToCancel, maxHeight, initialValue: initialValue); return(d.Promise); }
public static Promise <T?> PickFromEnum <T>(ConsoleString message) where T : struct { Deferred <T?> deferred = Deferred <T?> .Create(); var enumVals = Enum.GetValues(typeof(T)); List <T> genericVals = new List <T>(); foreach (T val in enumVals) { genericVals.Add(val); } var innerPromise = Pick(message, genericVals.Select(v => new DialogOption() { Id = v.ToString(), DisplayText = v.ToString().ToConsoleString() })); innerPromise.Finally((p) => { if (p.Exception != null) { deferred.Reject(p.Exception); } else { deferred.Resolve(innerPromise.Result != null ? (T)Enum.Parse(typeof(T), innerPromise.Result.Id) : default(T?)); } }); return(deferred.Promise); }
public void DrawString(ConsoleString str, int x, int y, bool vert = false) { var xStart = scope.X + x; x = scope.X + x; y = scope.Y + y; foreach (var character in str) { if (character.Value == '\n') { y++; x = xStart; } else if (IsInScope(x, y)) { pixels[x][y].Value = character; if (vert) { y++; } else { x++; } } } }
public void Write(ConsoleString text) { if (outputLabel != null) { outputLabel.Text += text; } }
private void SetOutput(ConsoleString text) { if (outputLabel != null) { outputLabel.Text = text; } }
public void ParseStringFlatten() { Assert.AreEqual(ConsoleString.Parse("test1test2"), new ConsoleString(new[] { new ConsoleStringSegment("test1"), new ConsoleStringSegment("test2") })); Assert.AreEqual(ConsoleString.Parse("[red:test1test2]"), ConsoleString.Parse("[red:test1][red:test2]")); Assert.AreEqual(ConsoleString.Parse("[blue:test1][red:test2]test3"), ConsoleString.Parse("[blue:test1][red:test2]test3")); Assert.AreEqual(ConsoleString.Parse("[blue:test1][red:test2test3]test4"), ConsoleString.Parse("[blue:test1][red:test2][red:test3]test4")); }
/// <summary> /// Shows a dialog with the given message and provides the user with a yes and no option /// </summary> /// <param name="message">the message to show</param> /// <returns>a promise that resolves if the yes option was cicked. it rejects if no was clicked or if the dialog was cancelled</returns> public static Promise ShowYesConfirmation(ConsoleString message) { var d = Deferred.Create(); var buttonPromise = ShowMessage(new DialogButtonOptions() { Message = message, Options = new List <DialogOption>() { DialogButtonOptions.Yes, DialogButtonOptions.No } }); buttonPromise.Then((button) => { if (button != null && button.Equals(DialogButtonOptions.Yes)) { d.Resolve(); } else { d.Reject(new Exception("No was selected")); } }); return(d.Promise); }
/// <summary> /// Shows a message and lets the user pick from a set of options defined by an enum /// </summary> /// <param name="message">the message to show</param> /// <param name="enumType">the enum type</param> /// <returns>A promise that resolves with the selected value or null if the dialog was cancelled. The promise never rejects.</returns> public static Promise <object> ShowEnumOptions(ConsoleString message, Type enumType) { Deferred <object> deferred = Deferred <object> .Create(); var rawPromise = ShowMessage(new DialogButtonOptions() { Message = message, Mode = DialogButtonsPresentationMode.Grid, Options = Enums.GetEnumValues(enumType).OrderBy(e => e.ToString()).Select(e => new DialogOption() { Id = e.ToString(), DisplayText = e.ToString().ToConsoleString(), Value = e }).ToList() }); rawPromise.Then((b) => { if (b == null) { deferred.Resolve(null); } else { deferred.Resolve(b.Value); } }); return(deferred.Promise); }
/// <summary> /// Shows a message and lets the user pick from a set of options defined by an enum /// </summary> /// <param name="message">the message to show</param> /// <param name="enumType">the enum type</param> /// <returns>A Task that resolves with the selected value or null if the dialog was cancelled. The Task never rejects.</returns> public static Task <object> ShowEnumOptions(ConsoleString message, Type enumType) { TaskCompletionSource <object> deferred = new TaskCompletionSource <object>(); var rawTask = ShowMessage(new DialogButtonOptions() { Message = message, Mode = DialogButtonsPresentationMode.Grid, Options = Enums.GetEnumValues(enumType).OrderBy(e => e.ToString()).Select(e => new DialogOption() { Id = e.ToString(), DisplayText = e.ToString().ToConsoleString(), Value = e }).ToList() }); rawTask.Then((b) => { if (b == null) { deferred.SetResult(null); } else { deferred.SetResult(b.Value); } }); return(deferred.Task); }
/// <summary> /// Shows a dialog with the given message and provides the user with a yes and no option /// </summary> /// <param name="message">the message to show</param> /// <returns>a Task that resolves if the yes option was cicked. it rejects if no was clicked or if the dialog was cancelled</returns> public static Task ShowYesConfirmation(ConsoleString message) { var d = new TaskCompletionSource <bool>(); var buttonTask = ShowMessage(new DialogButtonOptions() { Message = message, Options = new List <DialogOption>() { DialogButtonOptions.Yes, DialogButtonOptions.No } }); buttonTask.Then((button) => { if (button != null && button.Equals(DialogButtonOptions.Yes)) { d.SetResult(true); } else { d.SetException(new Exception("No was selected")); } }); return(d.Task); }
/// <summary> /// Writes the specified string value to the standard output stream. /// </summary> /// <param name="console">The console on which the action is carried out.</param> /// <param name="value">The string format to write, included color information. /// The string "[Color:Text]" will print Text to the console using Color as the foreground color.</param> /// <param name="allowcolor">if set to <c>false</c> any color information passed in <paramref name="value"/> is disregarded.</param> public static void Write(this IConsole console, ConsoleString value, bool allowcolor = true) { if (value == null) { throw new ArgumentNullException(nameof(value)); } foreach (var p in value) { var fgColor = (p.Color.HasForeground ? colors[p.Color.Foreground] : null) ?? console.ForegroundColor; var bgColor = (p.Color.HasBackground ? colors[p.Color.Background] : null) ?? console.BackgroundColor; if (allowcolor && (fgColor != console.ForegroundColor || bgColor != console.BackgroundColor)) { ConsoleColor tempFg = console.ForegroundColor; ConsoleColor tempBg = console.BackgroundColor; console.ForegroundColor = fgColor; console.BackgroundColor = bgColor; console.Render(p.Content); console.ForegroundColor = tempFg; console.BackgroundColor = tempBg; } else { console.Render(p.Content); } } }
public void ParseEmptyString() { Assert.AreEqual(ConsoleString.Empty, new ConsoleString()); Assert.AreEqual(ConsoleString.Empty, ConsoleString.Parse(string.Empty, true)); Assert.AreEqual(ConsoleString.Empty, ConsoleString.Parse(string.Empty, false)); Assert.AreEqual(ConsoleString.Empty, new ConsoleString(new[] { new ConsoleStringSegment(string.Empty) })); }
/// <summary> /// Draws the given string onto the bitmap /// </summary> /// <param name="str">the value to write</param> /// <param name="x">the x coordinate to draw the string's fist character</param> /// <param name="y">the y coordinate to draw the string's first character </param> /// <param name="vert">if true, draw vertically, else draw horizontally</param> public void DrawString(ConsoleString str, int x, int y, bool vert = false) { var xStart = x; foreach (var character in str) { if (character.Value == '\n') { y++; x = xStart; } else if (character.Value == '\r') { // ignore } else if (IsInBounds(x, y)) { Compose(x, y, character); if (vert) { y++; } else { x++; } } } }
public void TestConsoleStringWriteLine() { var existingProvider = ConsoleString.ConsoleProvider; try { var testProvider = new TestConsoleProvider(); ConsoleString.ConsoleProvider = testProvider; ConsoleString str = new ConsoleString("Adam"); bool confirmed = false; string written = ""; string target = "Adam" + Environment.NewLine; testProvider.WriteHappened += (s) => { written += s; if (written == target) { confirmed = true; } else { Assert.IsFalse(written.StartsWith(target), "Extra characters after target: '" + written + "'"); } }; str.WriteLine(); Assert.IsTrue(confirmed); } finally { ConsoleString.ConsoleProvider = existingProvider; } }
public LooseWeapon(Weapon weapon, ConsoleString displayName) { this.DisplayString = displayName; weapon.DisplayName = displayName; this.ResizeTo(displayName.Length, 1); this.InnerWeapon = weapon; }
public void TestIndexOf() { ConsoleString s = new ConsoleString("0123456789"); for (int i = 0; i < 10; i++) { Assert.AreEqual(i, s.IndexOf(i + "")); } Assert.AreEqual(0, s.IndexOf("0123456789")); Assert.AreEqual(-1, s.IndexOf("01234567890")); Assert.AreEqual(0, s.IndexOf("")); Assert.AreEqual(-1, s.IndexOf("A")); Assert.AreEqual(-1, s.IndexOf(null)); Assert.AreEqual(0, s.IndexOf("01")); Assert.AreEqual(1, s.IndexOf("12")); Assert.AreEqual(8, s.IndexOf("89")); for (int i = 0; i < 1000; i++) { s += "-"; } s += "!"; Assert.AreEqual(1010, s.IndexOf("!")); }
/// <summary> /// Reads a line of text from the console and converts it into a string array that has accounted for escape sequences and quoted string literals. /// </summary> /// <param name="initialBuffer">Optionally seed the prompt with an initial value that the end user can modify</param> /// <returns>the command line that was read</returns> public string[] ReadCommandLine(ConsoleString initialBuffer = null) { var line = ReadLine(initialBuffer).ToString(); var ret = Args.Convert(line); return(ret); }
public void Write(ConsoleString consoleString) { foreach (var c in consoleString) { Write(c); } }
public static void ShowMessage(ConsoleString message, Action<DialogButton> resultCallback, bool allowEscapeToCancel = true, int maxHeight = 6, params DialogButton [] buttons) { if(buttons.Length == 0) { throw new ArgumentException("You need to specify at least one button"); } ConsolePanel dialogContent = new ConsolePanel(); Dialog dialog = new Dialog(dialogContent); dialog.MaxHeight = maxHeight; dialog.AllowEscapeToCancel = allowEscapeToCancel; dialog.Cancelled.SubscribeForLifetime(() => { resultCallback(null); }, dialog.LifetimeManager); ScrollablePanel messagePanel = dialogContent.Add(new ScrollablePanel()).Fill(padding: new Thickness(0, 0, 1, 3)); Label messageLabel = messagePanel.ScrollableContent.Add(new Label() { Mode = LabelRenderMode.MultiLineSmartWrap, Text = message }).FillHoriontally(padding: new Thickness(3,3,0,0) ); StackPanel buttonPanel = dialogContent.Add(new StackPanel() { Margin = 1, Height = 1, Orientation = Orientation.Horizontal }).FillHoriontally(padding: new Thickness(1,0,0,0)).DockToBottom(padding: 1); Button firstButton = null; foreach (var buttonInfo in buttons) { var myButtonInfo = buttonInfo; Button b = new Button() { Text = buttonInfo.DisplayText }; b.Pressed.SubscribeForLifetime(() => { ConsoleApp.Current.LayoutRoot.Controls.Remove(dialog); resultCallback(myButtonInfo); }, dialog.LifetimeManager); buttonPanel.Controls.Add(b); firstButton = firstButton ?? b; } ConsoleApp.Current.LayoutRoot.Controls.Add(dialog); }
private static void InitImpl() { ArgPipelineObjectMapper.CurrentMapper = new JObjectArgPipelineMapper(); PipelineOutputFormatter.RegisterFormatter(typeof(JObject), FuncPipelineOutputFormatter.Create((obj) => { JObject jObj = (JObject)obj; ConsoleTableBuilder builder = new ConsoleTableBuilder(); List <ConsoleString> headers = new List <ConsoleString>() { new ConsoleString("PROPERTY", ConsoleColor.Yellow), new ConsoleString("VALUE", ConsoleColor.Yellow) }; List <List <ConsoleString> > rows = new List <List <ConsoleString> >(); foreach (var prop in jObj.Properties()) { rows.Add(new List <ConsoleString>() { new ConsoleString(prop.Name, ConsoleColor.Gray), new ConsoleString("" + prop.Value, ConsoleColor.Green) }); } var jObjRet = builder.FormatAsTable(headers, rows); jObjRet = new ConsoleString("Pipeline output of type JObject: \n") + jObjRet; return(jObjRet); })); }
private void RenderTitle(ConsoleBitmap context) { int yOffset = 0; foreach (var series in ViewModel.DataSeriesCollection) { var title = new ConsoleString(series.Title, series.PlotColor, Background); if (HasFocus && ViewModel.FocusedDataPointIndex >= 0 && ViewModel.FocusedDataPointIndex < series.DataPoints.Count && ViewModel.FocusedDataSeries == series) { var xValue = XAxisValueFormatter(series.DataPoints[ViewModel.FocusedDataPointIndex].X); var yValue = YAxisValueFormatter(series.DataPoints[ViewModel.FocusedDataPointIndex].Y); title += new ConsoleString(" ( " + xValue + ", " + yValue + " )", Application.Theme.FocusColor); } if (title.Length > MaxTitleLength) { title = title.Substring(0, MaxTitleLength) + ("_"); } var titleLeft = XAxisLeft + ((XAxisWidth / 2) - (title.Length / 2)); context.DrawString(title, titleLeft, YAxisTop + 1 + yOffset); yOffset++; } }
private static void ApplyCleanup(ConsoleString prompt, IConsole console, ConsolePoint start, ConsoleReader reader, ReadlineCleanup cleanup) { switch (cleanup) { case ReadlineCleanup.None: console.WriteLine(); break; case ReadlineCleanup.RemovePrompt: var text = reader.Text; reader.Text = string.Empty; console.SetCursorPosition(start); console.Write(new string(' ', prompt.Length)); console.SetCursorPosition(start); console.WriteLine(text); break; case ReadlineCleanup.RemoveAll: reader.Text = string.Empty; console.SetCursorPosition(start); console.Write(new string(' ', prompt.Length)); console.SetCursorPosition(start); break; } }
private static void ShowUsage(CommandLineAction specifiedAction) { if (specifiedAction == null) { ConsoleString.Write("Supported actions: ", ConsoleColor.Cyan); Console.WriteLine("Extract"); Console.WriteLine(""); return; } Console.WriteLine(""); Console.WriteLine(""); ConsoleString.WriteLine(specifiedAction.DefaultAlias, ConsoleColor.Yellow); ConsoleString.WriteLine(new string('-', 80), ConsoleColor.DarkGray); Console.WriteLine(""); Console.WriteLine(specifiedAction.Description); Console.WriteLine(""); ConsoleString.WriteLine(new string('-', 80), ConsoleColor.DarkGray); Console.WriteLine(""); switch (specifiedAction.DefaultAlias) { case "Extract": ArgUsage.GetStyledUsage <ExtractArgs>("Extract action").WriteLine(); break; } }
public void TestConsoleStringHelpers() { foreach (ConsoleColor color in Enum.GetValues(typeof(ConsoleColor))) { var method = typeof(StringEx).GetMethod("To" + color, System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public); Assert.AreEqual(new ConsoleString("Hello", color, color), method.Invoke(null, new object[] { "Hello", (RGB)color, false })); } foreach (ConsoleColor color in Enum.GetValues(typeof(ConsoleColor))) { ConsoleString baseString = new ConsoleString("Hello", null, null); var method = typeof(ConsoleString).GetMethod("To" + color); Assert.AreEqual(new ConsoleString(baseString.ToString(), color, color), method.Invoke(baseString, new object[] { (RGB)color, false })); } foreach (ConsoleColor color in Enum.GetValues(typeof(ConsoleColor))) { var method = typeof(StringEx).GetMethod("To" + color, System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public); Assert.AreEqual(new ConsoleString("Hello", color, color, true), method.Invoke(null, new object[] { "Hello", (RGB)color, true })); } foreach (ConsoleColor color in Enum.GetValues(typeof(ConsoleColor))) { ConsoleString baseString = new ConsoleString("Hello", null, null); var method = typeof(ConsoleString).GetMethod("To" + color); Assert.AreEqual(new ConsoleString(baseString.ToString(), color, color, true), method.Invoke(baseString, new object[] { (RGB)color, true })); } }
public void TestConsoleStringEdgeCases() { ConsoleString str = ConsoleString.Empty; for(int i = 0; i < 99; i++) str.Append(""); Assert.AreEqual(0, str.Length); Assert.AreEqual(string.Empty, str.ToString()); Assert.AreEqual(ConsoleString.Empty, str); ConsoleString noSegments = new ConsoleString(); noSegments.AppendUsingCurrentFormat("Adam"); ValidateStringCharacteristics("Adam", noSegments); ConsoleString nullString = null; Assert.IsTrue(nullString == null); nullString = nullString + new ConsoleString("Adam"); Assert.AreEqual(nullString, new ConsoleString("Adam")); nullString = null; Assert.IsTrue(nullString == null); Assert.IsFalse(nullString != null); nullString = nullString + "Adam"; Assert.AreEqual(nullString, new ConsoleString("Adam")); Assert.IsTrue(nullString != null); Assert.IsFalse(new ConsoleCharacter('a').Equals(null)); Assert.IsFalse(new ConsoleCharacter('a').Equals(0)); new ConsoleCharacter('a').GetHashCode(); new ConsoleString("Adam").GetHashCode(); Assert.IsTrue(new ConsoleString("Adam").Equals("Adam")); Assert.IsTrue(new ConsoleCharacter('A').Equals('A')); Assert.IsTrue(new ConsoleCharacter('A') == 'A'); Assert.IsTrue(new ConsoleCharacter('A') != 'B'); Assert.IsFalse(new ConsoleCharacter('A') == null); Assert.IsTrue(new ConsoleCharacter('A') != null); Assert.IsTrue(new ConsoleCharacter('A') == new ConsoleCharacter('A')); Assert.IsTrue(new ConsoleCharacter('A') != new ConsoleCharacter('B')); Assert.IsTrue(new ConsoleString("A") == new ConsoleString("A")); Assert.IsTrue(new ConsoleString("A") != new ConsoleString("B")); Assert.IsFalse(null == new ConsoleString("A")); Assert.IsTrue(null != new ConsoleString("B")); Assert.IsFalse(new ConsoleString("A") == null); Assert.IsTrue(new ConsoleString("A") != null); Assert.AreEqual(new ConsoleString("A"), null + new ConsoleString("A")); ConsoleString nulla = null; ConsoleString nullb = null; string nullS = null; Assert.AreEqual(null, nulla + nullb); Assert.AreEqual(null, nulla + nullS); }
public void DisplayText(ConsoleString str, bool clear = true) { if (clear) { ClearInstant(); } textToDisplay += str.GetText(); }
/// <summary> /// Creates a search result from an object, given an optional display value. /// </summary> /// <param name="value">The object to use as a result.</param> /// <param name="displayText">The display text for the result. If null, the value's ToString() method will be called</param> /// <returns>a search result</returns> public static ContextAssistSearchResult FromObject(object value, ConsoleString displayText) { if (value == null) { throw new ArgumentNullException("value", "value cannot be null"); } return new ContextAssistSearchResult(value, displayText ?? new ConsoleString(value.ToString())); }
/// <summary> /// Creates a new progress bar given a width /// </summary> /// <param name="initialMessage">an initial message to display in the progress bar</param> /// <param name="width">the width to use or null to use the default width which is one third of the console buffer width</param> public CliProgressBar(ConsoleString initialMessage = null, int? width = null) { Console = ConsoleProvider.Current; Message = initialMessage; Width = width.HasValue ? width.Value : Console.BufferWidth / 3; BorderPen = new ConsoleCharacter(' ', null, ConsoleColor.DarkGray); FillColor = ConsoleColor.Green; MessageFillColor = ConsoleColor.Black; indeterminateHighlightIndex = -1; }
public static void ConfirmYesOrNo(ConsoleString message, Action yesCallback, Action noCallback = null, int maxHeight = 10) { ShowMessage(message, (b) => { if (b != null && b.Id == "y") { yesCallback(); } else if (noCallback != null) { noCallback(); } }, true, maxHeight, new DialogButton() { Id = "y", DisplayText = "Yes", }, new DialogButton() { Id = "n", DisplayText = "No" }); }
public void TestHelpHookContextual() { try { ConsoleOutInterceptor.Instance.Attach(); ConsoleOutInterceptor.Instance.ReadAndClear(); var result = Args.InvokeAction<Command>("Action2", "-?"); var output = new ConsoleString(ConsoleOutInterceptor.Instance.ReadAndClear()); Assert.IsFalse(output.Contains("Action1", StringComparison.InvariantCultureIgnoreCase)); } finally { ConsoleOutInterceptor.Instance.Detatch(); } }
/// <summary> /// Asks the user if they are sure about performing some operation and returns true if they indicate yes and /// false if they indicate no. /// </summary> /// <param name="about">The message to display. 'Are you sure?' will be apended.</param> /// <returns>true if they indicate yes and false if they indicate no.</returns> public bool IsUserSure(ConsoleString about) { if (about.EndsWith(".")) { about = about.Substring(0, about.Length - 1); } var response = Prompt(about + ". Are you sure?", "y", "n"); if (response.Equals("y", StringComparison.InvariantCultureIgnoreCase) == true) { return true; } else { return false; } }
public void TestReplaceRegex() { ConsoleString orig = new ConsoleString("Credit Card: 1234-5678-9876-5432 - VISA"); ConsoleString cleaned = orig.ReplaceRegex(@"\d\d\d\d-\d\d\d\d-\d\d\d\d-\d\d\d\d", "xxxx-xxxx-xxxx-xxxx", ConsoleColor.White); Assert.AreEqual("Credit Card: xxxx-xxxx-xxxx-xxxx - VISA", cleaned.ToString()); ConsoleString hasPhoneNumber = new ConsoleString("Number: 222-333-4444"); hasPhoneNumber = hasPhoneNumber.ReplaceRegex(@"\d{3}-\d{3}-\d{4}", null, ConsoleColor.Green); Assert.AreEqual("Number: 222-333-4444", hasPhoneNumber.ToString()); Assert.AreEqual(new ConsoleString("222-333-4444", ConsoleColor.Green), hasPhoneNumber.Substring(8)); }
public void TestReplaceCharByChar() { var testString = "Some Test String"; for (int i = 0; i < testString.Length; i++) { ConsoleString orig = new ConsoleString(testString); ConsoleString replaced = orig.Replace(testString[i]+"", testString[i]+"", ConsoleColor.Red); Assert.AreEqual(ConsoleColor.Gray, orig[i].ForegroundColor); Assert.AreEqual(ConsoleColor.Red, replaced[i].ForegroundColor); } }
public void TestReplaceOtherCases() { ConsoleString orig = new ConsoleString("RedWBlue"); ConsoleString white = orig.Replace("W", "White", ConsoleColor.White); Assert.AreEqual("RedWBlue", orig.ToString()); Assert.AreEqual("RedWhiteBlue", white.ToString()); Assert.AreEqual("White", string.Join("",white.Where(c => c.ForegroundColor == ConsoleColor.White).Select(c=> c.Value))); }
private void FireUsageWritten(ConsoleString usage) { if (UsageWritten != null) { UsageWritten(usage); } }
public void TestMultiSegmentConsoleStringEqualityPositive() { ConsoleString[] equal = new ConsoleString[2]; for (int i = 0; i < equal.Length; i++) { equal[i] = new ConsoleString("Adam", ConsoleColor.Red); equal[i] += new ConsoleString(" M", ConsoleColor.White); equal[i] += new ConsoleString("", ConsoleColor.Black); equal[i] += new ConsoleString(" Abdelhamed", ConsoleColor.Blue); } Assert.IsTrue(equal[0].Equals(equal[1])); Assert.IsTrue(equal[1].Equals(equal[0])); Assert.IsFalse(equal[0].Equals(null)); Assert.IsFalse(equal[0].Equals(10)); }
public void TestMultiSegmentConsoleStringEqualityNegative() { ConsoleString[] equal = new ConsoleString[2]; for (int i = 0; i < equal.Length; i++) { equal[i] = new ConsoleString("Adam", ConsoleColor.Red); equal[i] += new ConsoleString(" M", i== 0 ? ConsoleColor.White : ConsoleColor.Black); equal[i] += new ConsoleString("", ConsoleColor.Black); equal[i] += new ConsoleString(" Abdelhamed", ConsoleColor.Blue); } Assert.IsFalse(equal[0].Equals(equal[1])); Assert.IsFalse(equal[1].Equals(equal[0])); ConsoleString a = new ConsoleString("Ada"); ConsoleString b = new ConsoleString("Adam"); Assert.IsFalse(a.Equals(b)); Assert.IsFalse(b.Equals(a)); }
private static void ValidateStringCharacteristics(string expected, ConsoleString actual) { Assert.AreEqual(expected, string.Join("", actual.Select(c => c.Value))); Assert.AreEqual(0, actual.CompareTo(expected)); Assert.AreEqual(expected, actual.ToString()); Assert.AreEqual(expected.Length, actual.Length); var expectedEnumerator = expected.GetEnumerator(); foreach (var character in actual) { expectedEnumerator.MoveNext(); Assert.AreEqual(expectedEnumerator.Current+"", character.ToString()); Assert.AreEqual(expectedEnumerator.Current, character.Value); character.Write(); } Assert.IsFalse(expectedEnumerator.MoveNext()); }
/// <summary> /// Reads a line of text from the console and converts it into a string array that has accounted for escape sequences and quoted string literals. /// </summary> /// <param name="initialBuffer">Optionally seed the prompt with an initial value that the end user can modify</param> /// <returns>the command line that was read</returns> public string[] ReadCommandLine(ConsoleString initialBuffer = null) { var line = ReadLine(initialBuffer).ToString(); var ret = Args.Convert(line); return ret; }
private void InitializeClearedLine() { var buffer = new List<ConsoleCharacter>(); for (int i = 0; i < Console.BufferWidth; i++) { buffer.Add(new ConsoleCharacter(' ')); } clearedLine = new ConsoleString(buffer); }
public void DrawString(ConsoleString str, int x, int y, bool vert = false) { var xStart = scope.X + x; x = scope.X + x; y = scope.Y + y; foreach (var character in str) { if(character.Value == '\n') { y++; x = xStart; } else if (IsInScope(x, y)) { pixels[x][y].Value = character; if (vert) y++; else x++; } } }
/// <summary> /// Pretends to intercept a ConsoleString /// </summary> /// <param name="value">the string to intercept</param> public void Write(ConsoleString value) { lock (intercepted) { foreach (var c in value) { intercepted.Add(c); } } }
public void TestConsoleStringHelpers() { foreach (ConsoleColor color in Enum.GetValues(typeof(ConsoleColor))) { var method = typeof(StringEx).GetMethod("To" + color, System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public); Assert.AreEqual(new ConsoleString("Hello", color, color), method.Invoke(null,new object[] { "Hello", color })); } foreach (ConsoleColor color in Enum.GetValues(typeof(ConsoleColor))) { ConsoleString baseString = new ConsoleString("Hello", null, null); var method = typeof(ConsoleString).GetMethod("To" + color); Assert.AreEqual(new ConsoleString(baseString.ToString(), color, color), method.Invoke(baseString, new object[] { color })); } }
public void TestHighlightCustomComparison() { var highlighted = new ConsoleString("Adam").Highlight("a",foregroundColor: ConsoleColor.Red, comparison: StringComparison.InvariantCultureIgnoreCase); Assert.AreEqual(highlighted[0], new ConsoleCharacter('A', ConsoleColor.Red)); Assert.AreEqual(highlighted[1], new ConsoleCharacter('d')); Assert.AreEqual(highlighted[2], new ConsoleCharacter('a', ConsoleColor.Red)); Assert.AreEqual(highlighted[3], new ConsoleCharacter('m')); Assert.AreEqual("The quick brown fox", new ConsoleString("The quick brown fox").Highlight("brown", ConsoleColor.Red).ToString()); }
public void TestSubstring() { ConsoleString orig = new ConsoleString("0123456789"); ConsoleString sub = orig.Substring(5); ConsoleString sub2 = orig.Substring(5,1); Assert.AreEqual("56789", sub.ToString()); Assert.AreEqual("5", sub2.ToString()); }
public void TestMultiSegmentConsoleString() { ConsoleString val = new ConsoleString("Adam", ConsoleColor.Red); val += new ConsoleString(" M", ConsoleColor.White); val += new ConsoleString("", ConsoleColor.Black); val += new ConsoleString(" Abdelhamed", ConsoleColor.Blue); ValidateStringCharacteristics("Adam M Abdelhamed", val); val.Write(); }
/// <summary> /// Prompts the user to select a value from a set of options. /// </summary> /// <param name="message">the prompt message</param> /// <param name="options">the options to choose from</param> /// <returns>The selected value</returns> public string Prompt(ConsoleString message, params string[] options) { var optionsString = new ConsoleString("(" + string.Join("/", options) + ")", ConsoleColor.Cyan); var prompt = message + new ConsoleString(" ") + optionsString + ": "; prompt.Write(); var option = Reader.ReadLine().ToString(); if (options.Contains(option, StringComparer.InvariantCultureIgnoreCase) == false) { Console.WriteLine("Unrecognized option: " + option); return Prompt(message, options); } else { return option; } }
public void TestIndexOf() { ConsoleString s = new ConsoleString("0123456789"); for (int i = 0; i < 10; i++) { Assert.AreEqual(i, s.IndexOf(i + "")); } Assert.AreEqual(0, s.IndexOf("0123456789")); Assert.AreEqual(-1, s.IndexOf("01234567890")); Assert.AreEqual(0, s.IndexOf("")); Assert.AreEqual(-1, s.IndexOf("A")); Assert.AreEqual(-1, s.IndexOf(null)); Assert.AreEqual(0, s.IndexOf("01")); Assert.AreEqual(1, s.IndexOf("12")); Assert.AreEqual(8, s.IndexOf("89")); for (int i = 0; i < 1000000; i++) { s += "-"; } s += "!"; Assert.AreEqual(1000010,s.IndexOf("!")); }
public void TestContains() { ConsoleString s = new ConsoleString("0123456789"); Assert.IsTrue(s.Contains("2345")); Assert.IsTrue(s.Contains("0")); Assert.IsTrue(s.Contains("01")); Assert.IsTrue(s.Contains("9")); Assert.IsTrue(s.Contains("89")); Assert.IsFalse(s.Contains("A")); Assert.IsFalse(s.Contains("0123A")); }
/// <summary> /// Reads a line of text from the console. Any interactions you've configured before calling this method will be in effect. /// </summary> /// <param name="initialBuffer">Optionally seed the prompt with an initial value that the end user can modify</param> /// <returns>a line of text from the console</returns> public ConsoleString ReadLine(ConsoleString initialBuffer = null) { RichCommandLineContext context; lock (SyncLock) { context = new RichCommandLineContext(this.HistoryManager); context.Console = this.Console; context.ConsoleStartTop = this.Console.CursorTop; context.ConsoleStartLeft = this.Console.CursorLeft; } if(initialBuffer != null) { lock (SyncLock) { context.ReplaceConsole(initialBuffer); } } while (true) { context.Reset(); context.KeyPressed = this.Console.ReadKey(true); lock (SyncLock) { context.CharacterToWrite = new ConsoleCharacter(context.KeyPressed.KeyChar); context.BufferPosition = this.Console.CursorLeft - context.ConsoleStartLeft + (this.Console.CursorTop - context.ConsoleStartTop) * this.Console.BufferWidth; if(context.BufferPosition < 0 || context.BufferPosition > context.Buffer.Count) { var message = string.Format("The cursor is not located within the bounds of the buffer. Cursor: {0},{1} Start position: {2},{3} Buffer position: {4} Buffer length: {5}", this.Console.CursorTop, this.Console.CursorLeft, context.ConsoleStartTop, context.ConsoleStartLeft, context.BufferPosition, context.Buffer.Count); try { throw new IndexOutOfRangeException(message); } catch(Exception ex) { PowerLogger.LogLine(ex.ToString()); throw; } } IKeyHandler handler = null; if (KeyHandlers.TryGetValue(context.KeyPressed.Key, out handler) == false && IsWriteable(context.KeyPressed)) { context.WriteCharacterForPressedKey(); DoSyntaxHighlighting(context); } else if (handler != null) { handler.Handle(context); if (context.Intercept == false && IsWriteable(context.KeyPressed)) { context.WriteCharacterForPressedKey(); } DoSyntaxHighlighting(context); if (context.IsFinished) { this.Console.WriteLine(); break; } } if (AfterReadKey != null) { AfterReadKey(context); } } } return new ConsoleString(context.Buffer); }
/// <summary> /// Creates a result that replaces the current token with the given selection. /// </summary> /// <param name="context">Context from the parent reader</param> /// <param name="selection">The selection string to insert</param> /// <returns>a result that replaces the current token with the given selection</returns> public static ContextAssistResult CreateInsertResult(RichCommandLineContext context, ConsoleString selection) { context.RefreshTokenInfo(); var ret = new ContextAssistResult(); bool hasInserted = false; var newBuffer = new List<ConsoleCharacter>(); foreach (var token in context.Tokens) { if (context.IsCursorOnToken(token)) { if (string.IsNullOrWhiteSpace(token.Value)) { newBuffer.AddRange(context.GetBufferSubstringFromToken(token)); ret.ConsoleRefreshLeftOffset = selection.Length; } else { var tokenOffset = context.BufferPosition - token.StartIndex; ret.ConsoleRefreshLeftOffset = selection.Length - tokenOffset; } if (hasInserted == false) { hasInserted = true; // cursor is on the current token newBuffer.AddRange(selection); } } else { // this token not be modified newBuffer.AddRange(context.GetBufferSubstringFromToken(token)); } } if (hasInserted == false) { hasInserted = true; // cursor is on the current token newBuffer.AddRange(selection); ret.ConsoleRefreshLeftOffset = selection.Length; } ret.StatusCode = ContextAssistResultStatusCode.Success; ret.NewBuffer = newBuffer; return ret; }
private static void InitImpl() { ArgPipelineObjectMapper.CurrentMapper = new JObjectArgPipelineMapper(); PipelineOutputFormatter.RegisterFormatter(typeof(JObject), FuncPipelineOutputFormatter.Create((obj) => { JObject jObj = (JObject)obj; ConsoleTableBuilder builder = new ConsoleTableBuilder(); List<ConsoleString> headers = new List<ConsoleString>() { new ConsoleString("PROPERTY", ConsoleColor.Yellow), new ConsoleString("VALUE", ConsoleColor.Yellow) }; List<List<ConsoleString>> rows = new List<List<ConsoleString>>(); foreach (var prop in jObj.Properties()) { rows.Add(new List<ConsoleString>() { new ConsoleString(prop.Name, ConsoleColor.Gray), new ConsoleString("" + prop.Value, ConsoleColor.Green) }); } var jObjRet = builder.FormatAsTable(headers, rows); jObjRet = new ConsoleString("Pipeline output of type JObject: \n") + jObjRet; return jObjRet; })); }