/// <summary>
    /// Switches to an alternate screen buffer if the terminal supports it.
    /// </summary>
    /// <param name="console">The console.</param>
    /// <param name="action">The action to execute within the alternate screen buffer.</param>
    public static void AlternateScreen(this IAnsiConsole console, Action action)
    {
        if (console is null)
        {
            throw new ArgumentNullException(nameof(console));
        }

        if (!console.Profile.Capabilities.Ansi)
        {
            throw new NotSupportedException("Alternate buffers are not supported since your terminal does not support ANSI.");
        }

        if (!console.Profile.Capabilities.AlternateBuffer)
        {
            throw new NotSupportedException("Alternate buffers are not supported by your terminal.");
        }

        console.ExclusivityMode.Run <object?>(() =>
        {
            // Switch to alternate screen
            console.Write(new ControlCode("\u001b[?1049h\u001b[H"));

            // Execute custom action
            action();

            // Switch back to primary screen
            console.Write(new ControlCode("\u001b[?1049l"));

            // Dummy result
            return(null);
        });
    }
Exemple #2
0
        internal static async Task <string> ReadLine(this IAnsiConsole console, Style?style, bool secret, IEnumerable <string>?items = null, CancellationToken cancellationToken = default)
        {
            if (console is null)
            {
                throw new ArgumentNullException(nameof(console));
            }

            style ??= Style.Plain;
            var text = string.Empty;

            var autocomplete = new List <string>(items ?? Enumerable.Empty <string>());

            while (true)
            {
                var rawKey = await console.Input.ReadKeyAsync(true, cancellationToken).ConfigureAwait(false);

                if (rawKey == null)
                {
                    continue;
                }

                var key = rawKey.Value;
                if (key.Key == ConsoleKey.Enter)
                {
                    return(text);
                }

                if (key.Key == ConsoleKey.Tab && autocomplete.Count > 0)
                {
                    var replace = AutoComplete(autocomplete, text);
                    if (!string.IsNullOrEmpty(replace))
                    {
                        // Render the suggestion
                        console.Write("\b \b".Repeat(text.Length), style);
                        console.Write(replace);
                        text = replace;
                        continue;
                    }
                }

                if (key.Key == ConsoleKey.Backspace)
                {
                    if (text.Length > 0)
                    {
                        text = text.Substring(0, text.Length - 1);
                        console.Write("\b \b");
                    }

                    continue;
                }

                if (!char.IsControl(key.KeyChar))
                {
                    text += key.KeyChar.ToString();
                    console.Write(secret ? "*" : key.KeyChar.ToString(), style);
                }
            }
        }
Exemple #3
0
        /// <summary>
        /// Renders the specified object to the console.
        /// </summary>
        /// <param name="console">The console to render to.</param>
        /// <param name="renderable">The object to render.</param>
        public static void Render(this IAnsiConsole console, IRenderable renderable)
        {
            if (console is null)
            {
                throw new ArgumentNullException(nameof(console));
            }

            if (renderable is null)
            {
                throw new ArgumentNullException(nameof(renderable));
            }

            var options  = new RenderContext(console.Encoding, console.Capabilities.LegacyConsole);
            var segments = renderable.Render(options, console.Width).ToArray();

            segments = Segment.Merge(segments).ToArray();

            foreach (var segment in segments)
            {
                if (string.IsNullOrEmpty(segment.Text))
                {
                    continue;
                }

                console.Write(segment.Text, segment.Style);
            }
        }
        public override void Run(IAnsiConsole console)
        {
            // Create the tree
            var tree = new Tree("Root")
                       .Style(Style.Parse("red"))
                       .Guide(TreeGuide.Line);

            // Add some nodes
            var foo   = tree.AddNode("[yellow]Nest objects like tables[/]");
            var table = foo.AddNode(new Table()
                                    .RoundedBorder()
                                    .AddColumn("First")
                                    .AddColumn("Second")
                                    .AddRow("1", "2")
                                    .AddRow("3", "4")
                                    .AddRow("5", "6"));

            table.AddNode("[blue]with[/]");
            table.AddNode("[blue]multiple[/]");
            table.AddNode("[blue]children too[/]");

            var bar = tree.AddNode("Any IRenderable can be nested, such as [yellow]calendars[/]");

            bar.AddNode(new Calendar(2020, 12)
                        .Border(TableBorder.Rounded)
                        .BorderStyle(new Style(Color.Green3_1))
                        .AddCalendarEvent(2020, 12, 12)
                        .HideHeader());

            console.Write(tree);
        }
        public override void Run(IAnsiConsole console)
        {
            var calendar = new Calendar(2020, 10);

            calendar.HeaderStyle(Style.Parse("blue bold"));
            console.Write(calendar);
        }
        public override void Run(IAnsiConsole console)
        {
            var calendar = new Calendar(2020, 10).HighlightStyle(Style.Parse("yellow bold"));

            calendar.AddCalendarEvent(2020, 10, 11);
            console.Write(calendar);
        }
        public override void Run(IAnsiConsole console)
        {
            var image = new CanvasImage("../../../examples/Console/Canvas/cake.png");

            image.MaxWidth(16);
            console.Write(image);
        }
Exemple #8
0
 /// <summary>
 /// Refreshes the live display.
 /// </summary>
 public void Refresh()
 {
     lock (Lock)
     {
         _console.Write(new ControlCode(string.Empty));
     }
 }
        public void OnAllMutantsTested(IReadOnlyProjectComponent reportComponent)
        {
            var files = reportComponent.GetAllFiles();

            if (files.Any())
            {
                // print empty line for readability
                _console.WriteLine();
                _console.WriteLine();
                _console.WriteLine("All mutants have been tested, and your mutation score has been calculated");

                var table = new Table()
                            .RoundedBorder()
                            .AddColumn("File", c => c.NoWrap())
                            .AddColumn("% score", c => c.Alignment(Justify.Right).NoWrap())
                            .AddColumn("# killed", c => c.Alignment(Justify.Right).NoWrap())
                            .AddColumn("# timeout", c => c.Alignment(Justify.Right).NoWrap())
                            .AddColumn("# survived", c => c.Alignment(Justify.Right).NoWrap())
                            .AddColumn("# no cov", c => c.Alignment(Justify.Right).NoWrap())
                            .AddColumn("# error", c => c.Alignment(Justify.Right).NoWrap());

                DisplayComponent(reportComponent, table);

                foreach (var file in files)
                {
                    DisplayComponent(file, table);
                }

                _console.Write(table);
            }
        }
        public void OnAllMutantsTested(IReadOnlyProjectComponent reportComponent)
        {
            Tree root = null;

            var stack = new Stack <IHasTreeNodes>();

            // setup display handlers
            reportComponent.DisplayFolder = (IReadOnlyProjectComponent current) =>
            {
                var name = Path.GetFileName(current.RelativePath);

                if (root is null)
                {
                    root = new Tree("All files" + DisplayComponent(current));
                    stack.Push(root);
                }
                else if (!string.IsNullOrWhiteSpace(name))
                {
                    stack.Push(stack.Peek().AddNode(name + DisplayComponent(current)));
                }
            };

            reportComponent.DisplayFile = (IReadOnlyProjectComponent current) =>
            {
                var name = Path.GetFileName(current.RelativePath);

                var fileNode = stack.Peek().AddNode(name + DisplayComponent(current));

                if (current.FullPath == current.Parent.Children.Last().FullPath)
                {
                    stack.Pop();
                }

                var totalMutants = current.TotalMutants();
                foreach (var mutant in totalMutants)
                {
                    var status = mutant.ResultStatus switch
                    {
                        MutantStatus.Killed or MutantStatus.Timeout => $"[Green][[{mutant.ResultStatus}]][/]",
                             MutantStatus.NoCoverage => $"[Yellow][[{mutant.ResultStatus}]][/]",
                             _ => $"[Red][[{mutant.ResultStatus}]][/]",
                    };

                    var mutantNode = fileNode.AddNode(status + $" {mutant.Mutation.DisplayName} on line {mutant.Line}");
                    mutantNode.AddNode(Markup.Escape($"[-] {mutant.Mutation.OriginalNode}"));
                    mutantNode.AddNode(Markup.Escape($"[+] {mutant.Mutation.ReplacementNode}"));
                }
            };

            // print empty line for readability
            _console.WriteLine();
            _console.WriteLine();
            _console.WriteLine("All mutants have been tested, and your mutation score has been calculated");

            // start recursive invocation of handlers
            reportComponent.Display();

            _console.Write(root);
        }
Exemple #11
0
    /// <inheritdoc />
    public async Task WriteOutputAsync(Stream content, IOutputFormatterOptions?options = null, CancellationToken cancellationToken = default)
    {
        using var doc = await JsonDocument.ParseAsync(content, cancellationToken : cancellationToken);

        var table = ConstructTable(doc);

        _ansiConsole.Write(table);
    }
        private static string AskName(IAnsiConsole console)
        {
            console.WriteLine();
            console.Write(new Rule("[yellow]Strings[/]").RuleStyle("grey").LeftAligned());
            var name = console.Ask <string>("What's your [green]name[/]?");

            return(name);
        }
        /// <summary>
        /// Writes an empty line to the console.
        /// </summary>
        /// <param name="console">The console to write to.</param>
        public static void WriteLine(this IAnsiConsole console)
        {
            if (console is null)
            {
                throw new ArgumentNullException(nameof(console));
            }

            console.Write(Text.NewLine);
        }
        /// <summary>
        /// Writes the specified string value to the console.
        /// </summary>
        /// <param name="console">The console to write to.</param>
        /// <param name="text">The text to write.</param>
        /// <param name="style">The text style or <see cref="Style.Plain"/> if <see langword="null"/>.</param>
        public static void Write(this IAnsiConsole console, string text, Style?style)
        {
            if (console is null)
            {
                throw new ArgumentNullException(nameof(console));
            }

            console.Write(new Text(text, style));
        }
        /// <summary>
        /// Writes the text representation of the specified 32-bit
        /// unsigned integer value to the console.
        /// </summary>
        /// <param name="console">The console to write to.</param>
        /// <param name="provider">An object that supplies culture-specific formatting information.</param>
        /// <param name="value">The value to write.</param>
        public static void Write(this IAnsiConsole console, IFormatProvider provider, uint value)
        {
            if (console is null)
            {
                throw new ArgumentNullException(nameof(console));
            }

            console.Write(value.ToString(provider));
        }
        public override void Run(IAnsiConsole console)
        {
            var image = new CanvasImage("../../../examples/Console/Canvas/cake.png");

            image.MaxWidth(24);
            image.BilinearResampler();
            image.Mutate(ctx => ctx.Grayscale().Rotate(-45).EntropyCrop());
            console.Write(image);
        }
Exemple #17
0
        public void OnMutantTested(IReadOnlyMutant result)
        {
            switch (result.ResultStatus)
            {
            case MutantStatus.Killed:
                _console.Write(".");
                break;

            case MutantStatus.Survived:
                _console.Markup("[Red]S[/]");
                break;

            case MutantStatus.Timeout:
                _console.Write("T");
                break;
            }
            ;
        }
        /// <summary>
        /// Writes an empty line to the console.
        /// </summary>
        /// <param name="console">The console to write to.</param>
        public static void WriteLine(this IAnsiConsole console)
        {
            if (console is null)
            {
                throw new ArgumentNullException(nameof(console));
            }

            console.Write(Environment.NewLine, Style.Plain);
        }
    public override int Execute([NotNull] CommandContext context, [NotNull] Settings settings)
    {
        var tree = new Tree("CLI Configuration");

        tree.AddNode(ValueMarkup("Application Name", _commandModel.ApplicationName, "no application name"));
        tree.AddNode(ValueMarkup("Parsing Mode", _commandModel.ParsingMode.ToString()));

        if (settings.Commands == null || settings.Commands.Length == 0)
        {
            // If there is a default command we'll want to include it in the list too.
            var commands = _commandModel.DefaultCommand != null
                ? new[] { _commandModel.DefaultCommand }.Concat(_commandModel.Commands)
                : _commandModel.Commands;

            AddCommands(
                tree.AddNode(ParentMarkup("Commands")),
                commands,
                settings.Detailed ?? false,
                settings.IncludeHidden);
        }
        else
        {
            var         currentCommandTier = _commandModel.Commands;
            CommandInfo?currentCommand     = null;
            foreach (var command in settings.Commands)
            {
                currentCommand = currentCommandTier
                                 .SingleOrDefault(i =>
                                                  i.Name.Equals(command, StringComparison.CurrentCultureIgnoreCase) ||
                                                  i.Aliases
                                                  .Any(alias => alias.Equals(command, StringComparison.CurrentCultureIgnoreCase)));

                if (currentCommand == null)
                {
                    break;
                }

                currentCommandTier = currentCommand.Children;
            }

            if (currentCommand == null)
            {
                throw new Exception($"Command {string.Join(" ", settings.Commands)} not found");
            }

            AddCommands(
                tree.AddNode(ParentMarkup("Commands")),
                new[] { currentCommand },
                settings.Detailed ?? true,
                settings.IncludeHidden);
        }

        _writer.Write(tree);

        return(0);
    }
Exemple #20
0
    /// <inheritdoc/>
    public void Write(IRenderable renderable)
    {
        if (renderable is null)
        {
            throw new ArgumentNullException(nameof(renderable));
        }

        _recorded.Add(renderable);

        _console.Write(renderable);
    }
        private static void Render(IAnsiConsole console, RenderContext options, IEnumerable <IRenderable> renderables)
        {
            var result = new List <Segment>();

            foreach (var renderable in renderables)
            {
                result.AddRange(renderable.Render(options, console.Profile.Width));
            }

            console.Write(Segment.Merge(result));
        }
Exemple #22
0
        /// <inheritdoc/>
        public void Write(IEnumerable <Segment> segments)
        {
            if (segments is null)
            {
                throw new ArgumentNullException(nameof(segments));
            }

            Record(segments);

            _console.Write(segments);
        }
Exemple #23
0
        public void Write(IEnumerable <Segment> segments)
        {
            if (segments is null)
            {
                return;
            }

            foreach (var segment in segments)
            {
                _console.Write(segment);
            }
        }
        /// <summary>
        /// Writes the specified string value to the console.
        /// </summary>
        /// <param name="console">The console to write to.</param>
        /// <param name="value">The value to write.</param>
        public static void Write(this IAnsiConsole console, string value)
        {
            if (console is null)
            {
                throw new ArgumentNullException(nameof(console));
            }

            if (value != null)
            {
                console.Write(value);
            }
        }
        /// <summary>
        /// Writes a VT/Ansi control code sequence to the console (if supported).
        /// </summary>
        /// <param name="console">The console to write to.</param>
        /// <param name="sequence">The VT/Ansi control code sequence to write.</param>
        public static void WriteAnsi(this IAnsiConsole console, string sequence)
        {
            if (console is null)
            {
                throw new ArgumentNullException(nameof(console));
            }

            if (console.Profile.Capabilities.Ansi)
            {
                console.Write(new ControlCode(sequence));
            }
        }
        private static string AskSport(IAnsiConsole console)
        {
            console.WriteLine();
            console.Write(new Rule("[yellow]Choices[/]").RuleStyle("grey").LeftAligned());

            return(console.Prompt(
                       new TextPrompt <string>("What's your [green]favorite sport[/]?")
                       .InvalidChoiceMessage("[red]That's not a sport![/]")
                       .DefaultValue("Sport?")
                       .AddChoice("Soccer")
                       .AddChoice("Hockey")
                       .AddChoice("Basketball")));
        }
Exemple #27
0
        internal static string ReadLine(this IAnsiConsole console, Style?style, bool secret)
        {
            if (console is null)
            {
                throw new ArgumentNullException(nameof(console));
            }

            style ??= Style.Plain;

            var result = string.Empty;

            while (true)
            {
                var key = console.Input.ReadKey(true);

                if (key.Key == ConsoleKey.Enter)
                {
                    return(result);
                }

                if (key.Key == ConsoleKey.Backspace)
                {
                    if (result.Length > 0)
                    {
                        result = result.Substring(0, result.Length - 1);
                        console.Write("\b \b");
                    }

                    continue;
                }

                result += key.KeyChar.ToString();

                if (!char.IsControl(key.KeyChar))
                {
                    console.Write(secret ? "*" : key.KeyChar.ToString(), style);
                }
            }
        }
        /// <summary>
        /// Writes the specified string value to the console.
        /// </summary>
        /// <param name="console">The console to write to.</param>
        /// <param name="segment">The segment to write.</param>
        public static void Write(this IAnsiConsole console, Segment segment)
        {
            if (console is null)
            {
                throw new ArgumentNullException(nameof(console));
            }

            if (segment is null)
            {
                throw new ArgumentNullException(nameof(segment));
            }

            console.Write(new[] { segment });
        }
Exemple #29
0
        public static void Render(this IAnsiConsole console, IRenderable renderable)
        {
            if (console is null)
            {
                throw new ArgumentNullException(nameof(console));
            }

            if (renderable is null)
            {
                throw new ArgumentNullException(nameof(renderable));
            }

            console.Write(renderable);
        }
        /// <summary>
        /// Writes the specified string value, followed by the current line terminator, to the console.
        /// </summary>
        /// <param name="console">The console to write to.</param>
        /// <param name="text">The text to write.</param>
        /// <param name="style">The text style.</param>
        public static void WriteLine(this IAnsiConsole console, string text, Style style)
        {
            if (console is null)
            {
                throw new ArgumentNullException(nameof(console));
            }

            if (text is null)
            {
                throw new ArgumentNullException(nameof(text));
            }

            console.Write(text + Environment.NewLine, style);
        }