Пример #1
0
    /// <summary>
    /// Initializes a new instance of the <see cref="RenderHookScope"/> class.
    /// </summary>
    /// <param name="console">The console to attach the render hook to.</param>
    /// <param name="hook">The render hook.</param>
    public RenderHookScope(IAnsiConsole console, IRenderHook hook)
    {
        _console = console ?? throw new ArgumentNullException(nameof(console));
        _hook    = hook ?? throw new ArgumentNullException(nameof(hook));

        _console.Pipeline.Attach(_hook);
    }
Пример #2
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);
            }
        }
Пример #3
0
 public DefaultCommand(IAnsiConsole console)
 {
     _console     = console;
     _fileSystem  = new FileSystem();
     _environment = new Environment();
     _globber     = new Globber(_fileSystem, _environment);
 }
Пример #4
0
    public static string Build(IAnsiConsole console, IRenderable renderable)
    {
        var builder = new StringBuilder();

        foreach (var segment in renderable.GetSegments(console))
        {
            if (segment.IsControlCode)
            {
                builder.Append(segment.Text);
                continue;
            }

            var parts = segment.Text.NormalizeNewLines().Split(new[] { '\n' });
            foreach (var(_, _, last, part) in parts.Enumerate())
            {
                if (!string.IsNullOrEmpty(part))
                {
                    builder.Append(Build(console.Profile, part, segment.Style));
                }

                if (!last)
                {
                    builder.Append(Environment.NewLine);
                }
            }
        }

        return(builder.ToString());
    }
Пример #5
0
        internal LiveDisplayContext(IAnsiConsole console, IRenderable target)
        {
            _console = console ?? throw new ArgumentNullException(nameof(console));

            Live = new LiveRenderable(_console, target);
            Lock = new object();
        }
Пример #6
0
        public FakeAnsiConsole(
            ColorSystem colors,
            AnsiSupport ansi = AnsiSupport.Yes,
            int width        = 80)
        {
            _exclusivityLock = new FakeExclusivityMode();
            _writer          = new StringWriter();

            var factory = new AnsiConsoleFactory();

            _console = factory.Create(new AnsiConsoleSettings
            {
                Ansi        = ansi,
                ColorSystem = (ColorSystemSupport)colors,
                Out         = _writer,
                Enrichment  = new ProfileEnrichment
                {
                    UseDefaultEnrichers = false,
                },
            });

            _console.Profile.Width = width;
            _console.Profile.Capabilities.Unicode = true;

            Input = new FakeConsoleInput();
        }
Пример #7
0
 public AnalyzeCommand(IAnsiConsole console)
 {
     _console  = console ?? throw new ArgumentNullException(nameof(console));
     _builder  = new ProjectBuilder(console);
     _analyzer = new ProjectAnalyzer();
     _reporter = new ProjectReporter(console);
 }
Пример #8
0
        public override void Run(IAnsiConsole console)
        {
            var calendar = new Calendar(2020, 10);

            calendar.HeaderStyle(Style.Parse("blue bold"));
            console.Write(calendar);
        }
Пример #9
0
        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);
        }
Пример #10
0
        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);
        }
        /// <inheritdoc/>
        int IListPromptStrategy <T> .CalculatePageSize(IAnsiConsole console, int totalItemCount, int requestedPageSize)
        {
            // The instructions take up two rows including a blank line
            var extra = 2;

            if (Title != null)
            {
                // Title takes up two rows including a blank line
                extra += 2;
            }

            // Scrolling?
            if (totalItemCount > requestedPageSize)
            {
                // The scrolling instructions takes up one row
                extra++;
            }

            var pageSize = requestedPageSize;

            if (pageSize > console.Profile.Height - extra)
            {
                pageSize = console.Profile.Height - extra;
            }

            return(pageSize);
        }
Пример #12
0
        /// <summary>
        /// Writes the prompt to the console.
        /// </summary>
        /// <param name="console">The console to write the prompt to.</param>
        private void WritePrompt(IAnsiConsole console)
        {
            if (console is null)
            {
                throw new ArgumentNullException(nameof(console));
            }

            var builder = new StringBuilder();

            builder.Append(_prompt.TrimEnd());

            if (ShowChoices && Choices.Count > 0)
            {
                var choices = string.Join("/", Choices.Select(choice => TextPrompt <T> .GetTypeConverter().ConvertToInvariantString(choice)));
                builder.AppendFormat(CultureInfo.InvariantCulture, " [blue][[{0}]][/]", choices);
            }

            if (ShowDefaultValue && DefaultValue != null)
            {
                builder.AppendFormat(
                    CultureInfo.InvariantCulture,
                    " [green]({0})[/]",
                    TextPrompt <T> .GetTypeConverter().ConvertToInvariantString(DefaultValue.Value));
            }

            var markup = builder.ToString().Trim();

            if (!markup.EndsWith("?", StringComparison.OrdinalIgnoreCase) &&
                !markup.EndsWith(":", StringComparison.OrdinalIgnoreCase))
            {
                markup += ":";
            }

            console.Markup(markup + " ");
        }
Пример #13
0
        public LegacyConsoleBackend(IAnsiConsole console)
        {
            _console   = console ?? throw new System.ArgumentNullException(nameof(console));
            _lastStyle = Style.Plain;

            Cursor = new LegacyConsoleCursor();
        }
Пример #14
0
 internal ProgressContext(IAnsiConsole console, ProgressRenderer renderer)
 {
     _tasks    = new List <ProgressTask>();
     _taskLock = new object();
     _console  = console ?? throw new ArgumentNullException(nameof(console));
     _renderer = renderer ?? throw new ArgumentNullException(nameof(renderer));
 }
Пример #15
0
 public RenderableSelectionList(IAnsiConsole console, string?title, int requestedPageSize, List <T> choices, Func <T, string>?converter, Style?highlightStyle)
     : base(console, requestedPageSize, choices, converter)
 {
     _console        = console ?? throw new ArgumentNullException(nameof(console));
     _title          = title;
     _highlightStyle = highlightStyle ?? new Style(foreground: Color.Blue);
 }
Пример #16
0
        public override void Run(IAnsiConsole console)
        {
            var image = new CanvasImage("../../../examples/Console/Canvas/cake.png");

            image.MaxWidth(16);
            console.Write(image);
        }
Пример #17
0
    public LiveRenderable(IAnsiConsole console)
    {
        _console = console ?? throw new ArgumentNullException(nameof(console));

        Overflow         = VerticalOverflow.Ellipsis;
        OverflowCropping = VerticalOverflowCropping.Top;
    }
Пример #18
0
 /// <summary>
 /// Renders the exception using the specified <see cref="IAnsiConsole"/>.
 /// </summary>
 /// <param name="console">The console.</param>
 public void Render(IAnsiConsole console)
 {
     if (Pretty != null)
     {
         console?.Render(Pretty);
     }
 }
Пример #19
0
    internal Recorder Clone(IAnsiConsole console)
    {
        var recorder = new Recorder(console);

        recorder._recorded.AddRange(_recorded);
        return(recorder);
    }
Пример #20
0
    /// <summary>
    /// Initializes a new instance of the <see cref="TestConsole"/> class.
    /// </summary>
    public TestConsole()
    {
        _writer = new StringWriter();
        _cursor = new NoopCursor();

        Input             = new TestConsoleInput();
        EmitAnsiSequences = false;

        _console = AnsiConsole.Create(new AnsiConsoleSettings
        {
            Ansi            = AnsiSupport.Yes,
            ColorSystem     = (ColorSystemSupport)ColorSystem.TrueColor,
            Out             = new AnsiConsoleOutput(_writer),
            Interactive     = InteractionSupport.No,
            ExclusivityMode = new NoopExclusivityMode(),
            Enrichment      = new ProfileEnrichment
            {
                UseDefaultEnrichers = false,
            },
        });

        _console.Profile.Width                = 80;
        _console.Profile.Height               = 24;
        _console.Profile.Capabilities.Ansi    = true;
        _console.Profile.Capabilities.Unicode = true;
    }
Пример #21
0
        public AnsiConsoleBackend(IAnsiConsole console)
        {
            _console = console ?? throw new ArgumentNullException(nameof(console));
            _builder = new AnsiBuilder(_console.Profile);

            Cursor = new AnsiConsoleCursor(this);
        }
    /// <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);
        });
    }
Пример #23
0
        /// <inheritdoc/>
        public List <T> Show(IAnsiConsole console)
        {
            if (!console.Capabilities.SupportsInteraction)
            {
                throw new NotSupportedException(
                          "Cannot show multi selection prompt since the current " +
                          "terminal isn't interactive.");
            }

            if (!console.Capabilities.SupportsAnsi)
            {
                throw new NotSupportedException(
                          "Cannot show multi selection prompt since the current " +
                          "terminal does not support ANSI escape sequences.");
            }

            var converter = Converter ?? TypeConverterHelper.ConvertToString;

            var list = new RenderableMultiSelectionList <T>(console, Title, PageSize, Choices, converter);

            using (new RenderHookScope(console, list))
            {
                console.Cursor.Hide();
                list.Redraw();

                while (true)
                {
                    var key = console.Input.ReadKey(true);
                    if (key.Key == ConsoleKey.Enter)
                    {
                        if (Required && list.Selections.Count == 0)
                        {
                            continue;
                        }

                        break;
                    }

                    if (key.Key == ConsoleKey.Spacebar)
                    {
                        list.Select();
                        list.Redraw();
                        continue;
                    }

                    if (list.Update(key.Key))
                    {
                        list.Redraw();
                    }
                }
            }

            list.Clear();
            console.Cursor.Show();

            return(list.Selections
                   .Select(index => Choices[index])
                   .ToList());
        }
Пример #24
0
        public static AsciiCastOut WrapWithAsciiCastRecorder(this IAnsiConsole ansiConsole)
        {
            AsciiCastOut castRecorder = new(ansiConsole.Profile.Out);

            ansiConsole.Profile.Out = castRecorder;

            return(castRecorder);
        }
Пример #25
0
 public HtmlReporter(StrykerOptions options, IFileSystem fileSystem = null,
                     IAnsiConsole console = null, IWebbrowserOpener processWrapper = null)
 {
     _options        = options;
     _fileSystem     = fileSystem ?? new FileSystem();
     _console        = console ?? AnsiConsole.Console;
     _processWrapper = processWrapper ?? new WebbrowserOpener();
 }
Пример #26
0
 public TorrentHandler(IFileSystem fileSystem, IAnsiConsole console,
                       AvailableArchiveParser availableArchiveParser)
 {
     _torrentDownloader      = new TorrentDownloader(fileSystem, console);
     _fileSystem             = fileSystem;
     _console                = console;
     _availableArchiveParser = availableArchiveParser;
 }
 /// <summary>
 /// Displays a prompt with two choices, yes or no.
 /// </summary>
 /// <param name="console">The console.</param>
 /// <param name="prompt">The prompt markup text.</param>
 /// <param name="defaultValue">Specifies the default answer.</param>
 /// <returns><c>true</c> if the user selected "yes", otherwise <c>false</c>.</returns>
 public static bool Confirm(this IAnsiConsole console, string prompt, bool defaultValue = true)
 {
     return(new ConfirmationPrompt(prompt)
     {
         DefaultValue = defaultValue,
     }
            .Show(console));
 }
Пример #28
0
        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);
        }
Пример #29
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);
                }
            }
        }
        /// <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);
        }