Example #1
0
        public void ToString_with_non_ansi_omits_ANSI_codes()
        {
            var span = new TextSpanFormatter().ParseToSpan(
                $"one{ForegroundColorSpan.Red()}two{ForegroundColorSpan.Reset()}three"
                );

            span.ToString(OutputMode.NonAnsi).Should().Be("onetwothree");
        }
Example #2
0
        private void TextChanged(string text)
        {
            SpannableString span;

            var(isLongText, index) = WeiboTextBlock.CheckIsLongWeibo(text);
            if (isLongText)
            {
                var length = index + 2;
                text = text.Remove(index) + "х╚нд";
                span = new SpannableString(text);
                var colorSpan = new ForegroundColorSpan(Android.Graphics.Color.Blue);
                span.SetSpan(colorSpan, index, length, SpanTypes.ExclusiveExclusive);
            }
            else
            {
                span = new SpannableString(text);
            }
            var matches = Regex.Matches(text, WeiboTextBlock.REGEX).Cast <Match>();

            foreach (var item in matches)
            {
                var at    = item.Groups[1];
                var topic = item.Groups[2];
                var emoji = item.Groups[3];
                var url   = item.Groups[4];
                if (at.Success)
                {
                    var clickableSpan = new ExClickableSpan();
                    clickableSpan.OnClicked += (sender, e) =>
                    {
                        Element.InvokeUserClicked(at.Value.Replace("#", ""));
                    };
                    span.SetSpan(clickableSpan, at.Index, at.Index + at.Length, SpanTypes.ExclusiveExclusive);
                }
                if (topic.Success)
                {
                    var clickableSpan = new ExClickableSpan();
                    clickableSpan.OnClicked += (sender, e) =>
                    {
                        Element.InvokeTopicClicked(topic.Value.Replace("#", ""));
                    };
                    span.SetSpan(clickableSpan, topic.Index, topic.Index + topic.Length, SpanTypes.ExclusiveExclusive);
                }
                //if (emoji.Success && StaticResource.Emotions.Any(e => e.Value == emoji.Value))
                //{

                //}
                if (url.Success)
                {
                    var clickableSpan = new ExClickableSpan();
                    clickableSpan.OnClicked += (sender, e) =>
                    {
                        Element.InvokeTopicClicked(url.Value.Replace("#", ""));
                    };
                    span.SetSpan(clickableSpan, url.Index, url.Index + url.Length, SpanTypes.ExclusiveExclusive);
                }
            }
        }
        public void When_spans_are_nested_then_content_length_can_be_calculated()
        {
            var span = new ContainerSpan(
                ForegroundColorSpan.Red(),
                new ContentSpan("content"),
                ForegroundColorSpan.Reset());

            span.ContentLength.Should().Be("content".Length);
        }
        public void ToString_with_ansi_includes_ANSI_codes()
        {
            var span = new TextSpanFormatter()
                       .ParseToSpan($"one{ForegroundColorSpan.Red()}two{ForegroundColorSpan.Reset()}three");

            span.ToString(OutputMode.Ansi)
            .Should()
            .Be($"one{Ansi.Color.Foreground.Red.EscapeSequence}two{Ansi.Color.Foreground.Default.EscapeSequence}three");
        }
        public void ForegroundColorSpans_with_the_same_name_are_equal()
        {
            var one = new ForegroundColorSpan("green", Ansi.Color.Foreground.Green);
            var two = new ForegroundColorSpan("green", Ansi.Color.Foreground.Green);

            one.Equals(two).Should().BeTrue();

            one.Invoking(code => code.Equals(null)).Should().NotThrow <NullReferenceException>();
        }
Example #6
0
        public void ForegroundColorSpans_with_different_names_are_not_equal()
        {
            var one = new ForegroundColorSpan("red", Ansi.Color.Foreground.Green);
            var two = new ForegroundColorSpan("green", Ansi.Color.Foreground.Green);

            one.Equals(two)
            .Should()
            .BeFalse();
        }
Example #7
0
        public void A_ForegroundColorSpan_and_a_BackgroundColorSpan_having_the_same_name_are_not_equal()
        {
            var one = new ForegroundColorSpan("green", Ansi.Color.Foreground.Green);
            var two = new BackgroundColorSpan("green", Ansi.Color.Foreground.Green);

            one.Equals(two)
            .Should()
            .BeFalse();
        }
Example #8
0
        public static ICharSequence ToColored(this System.String text, Color color)
        {
            ForegroundColorSpan span = new ForegroundColorSpan(color);

            SpannableString spannable = new SpannableString(text);

            spannable.SetSpan(span, 0, spannable.Length(), SpanTypes.ExclusiveExclusive);

            return(spannable);
        }
        private void Render(TextSpan span, Region region = null)
        {
            if (span == null)
            {
                span = TextSpan.Empty();
            }
            else if (_resetAfterRender)
            {
                span = new ContainerSpan(
                    span,
                    ForegroundColorSpan.Reset(),
                    BackgroundColorSpan.Reset());
            }

            if (_mode == OutputMode.Auto)
            {
                _mode = _terminal?.DetectOutputMode() ??
                        OutputMode.PlainText;
            }


            TextSpanVisitor visitor;

            switch (_mode)
            {
            case OutputMode.NonAnsi:
                visitor = new NonAnsiRenderingSpanVisitor(
                    _terminal,
                    region);
                break;

            case OutputMode.Ansi:
                visitor = new AnsiRenderingSpanVisitor(
                    _console,
                    region);
                break;

            case OutputMode.PlainText:
                visitor = new FileRenderingSpanVisitor(
                    _console.Out,
                    new Region(region.Left,
                               region.Top,
                               region.Width,
                               region.Height,
                               false));
                break;

            default:
                throw new NotSupportedException();
            }

            visitor.Visit(span);
        }
Example #10
0
        public static ContainerSpan StyleGrade(this string @string, double performance, Interval?range)
        {
            var y = (range ?? Interval.Unit).UnitNormalize(performance);
            // poor man's color scale, red - yellow - green
            var hsv = new Hsv(h: (float)(y * 120), s: 1, v: 1);
            var rgb = (Rgb24)colorConverter.ToRgb(hsv);

            return(new ContainerSpan(
                       ForegroundColorSpan.Rgb(rgb.R, rgb.G, rgb.B),
                       new ContentSpan(@string),
                       ForegroundColorSpan.Reset()));
        }
        public void ForegroundColorSpans_are_removed_during_file_rendering()
        {
            var span = _spanFormatter.ParseToSpan(
                $"{ForegroundColorSpan.Red()}red {ForegroundColorSpan.Blue()}blue {ForegroundColorSpan.Green()}green {ForegroundColorSpan.Reset()}or a {ForegroundColorSpan.Rgb(12, 34, 56)}little of each.");

            var renderer = new ConsoleRenderer(_console, OutputMode.File);

            var expected = "red blue green or a little of each.";

            renderer.RenderToRegion(span, new Region(0, 0, expected.Length, 1, false));

            _console.Out.ToString().Should().Be(expected);
        }
Example #12
0
        public async ValueTask DestroyProgressBar()
        {
            await context.Factory.Run(() =>
            {
                ReportProgress(1.0);
                progress = null;

                WriteLine(new ContainerSpan(
                              CursorControlSpan.Show(),
                              ForegroundColorSpan.Reset(),
                              BackgroundColorSpan.Reset()));
            });
        }
        public void ForegroundColorSpans_are_replaced_with_ANSI_codes_during_ANSI_rendering()
        {
            var span = _spanFormatter.ParseToSpan(
                $"{ForegroundColorSpan.Red()}red {ForegroundColorSpan.Blue()}blue {ForegroundColorSpan.Green()}green {ForegroundColorSpan.Reset()}or a {ForegroundColorSpan.Rgb(12, 34, 56)}little of each.");

            var renderer = new ConsoleRenderer(_console, OutputMode.Ansi);

            renderer.RenderToRegion(span, new Region(0, 0, 200, 1, false));

            _console.Out
            .ToString()
            .Should()
            .Contain(
                $"{Ansi.Color.Foreground.Red.EscapeSequence}red {Ansi.Color.Foreground.Blue.EscapeSequence}blue {Ansi.Color.Foreground.Green.EscapeSequence}green {Ansi.Color.Foreground.Default.EscapeSequence}or a {Ansi.Color.Foreground.Rgb(12, 34, 56).EscapeSequence}little of each.");
        }
        public void When_in_ANSI_mode_then_ContentWritten_events_do_not_include_escape_sequences()
        {
            var terminal = (TestTerminal)GetTerminal();

            var renderer = new ConsoleRenderer(terminal, OutputMode.Ansi);

            var region = new Region(0, 0, 4, 1);

            renderer.RenderToRegion($"{ForegroundColorSpan.Red()}text{ForegroundColorSpan.Reset()}", region);

            terminal.Events
            .Should()
            .Contain(e => e is TestTerminal.ContentWritten &&
                     ((TestTerminal.ContentWritten)e).Content == "text");
        }
        SpannableStringBuilder Spannla(Color Renk, string textt)
        {
            ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Renk);

            string title = textt;
            SpannableStringBuilder ssBuilder = new SpannableStringBuilder(title);

            ssBuilder.SetSpan(
                foregroundColorSpan,
                0,
                title.Length,
                SpanTypes.ExclusiveExclusive
                );
            return(ssBuilder);
        }
        public void ContentWritten_events_do_not_include_escape_sequences()
        {
            var console = new TestConsole();

            var renderer = new ConsoleRenderer(console, OutputMode.Ansi);

            var region = new Region(0, 0, 4, 1);

            renderer.RenderToRegion($"{ForegroundColorSpan.Red()}text{ForegroundColorSpan.Reset()}", region);

            console.Events
            .Should()
            .Contain(e => e is ContentWritten &&
                     ((ContentWritten)e).Content == "text");
        }
        public void Spans_have_a_start_relative_to_the_parent_span()
        {
            var span = new ContainerSpan(
                ForegroundColorSpan.Red(),
                new ContentSpan("first"),
                ForegroundColorSpan.Blue(),
                new ContentSpan("second"),
                ForegroundColorSpan.Reset());

            span[0].Start.Should().Be(0);
            span[1].Start.Should().Be(0);
            span[2].Start.Should().Be("first".Length);
            span[3].Start.Should().Be("first".Length);
            span[4].Start.Should().Be("firstsecond".Length);
        }
Example #18
0
        public void RenderToRegion(
            Span span,
            Region region)
        {
            SpanVisitor visitor;

            if (span == null)
            {
                span = Span.Empty();
            }
            else if (_resetAfterRender)
            {
                span = new ContainerSpan(
                    span,
                    ForegroundColorSpan.Reset(),
                    BackgroundColorSpan.Reset());
            }

            switch (Mode)
            {
            case OutputMode.NonAnsi:
                visitor = new NonAnsiRenderingSpanVisitor(
                    _terminal,
                    region);
                break;

            case OutputMode.Ansi:
                visitor = new AnsiRenderingSpanVisitor(
                    _console,
                    region);
                break;

            case OutputMode.File:
                visitor = new FileRenderingSpanVisitor(
                    _console.Out,
                    new Region(region.Left,
                               region.Top,
                               region.Width,
                               region.Height,
                               false));
                break;

            default:
                throw new NotSupportedException();
            }

            visitor.Visit(span);
        }
Example #19
0
        public void Span_starts_update_when_parent_is_added_to_another_parent_span()
        {
            var innerContainerSpan = new ContainerSpan(
                ForegroundColorSpan.Red(),
                new ContentSpan("second"),
                ForegroundColorSpan.Blue(),
                new ContentSpan("third"),
                ForegroundColorSpan.Reset()
                );

            var outerContainer = new ContainerSpan(new ContentSpan("first"), innerContainerSpan);

            innerContainerSpan[0].Start.Should().Be("first".Length);
            innerContainerSpan[1].Start.Should().Be("first".Length);
            innerContainerSpan[2].Start.Should().Be("firstsecond".Length);
            innerContainerSpan[3].Start.Should().Be("firstsecond".Length);
            innerContainerSpan[4].Start.Should().Be("firstsecondthird".Length);
        }
            private void UpdateKeySummary(string providerAPI)
            {
                if (!String.IsNullOrWhiteSpace(Settings.API_KEY))
                {
                    var keyVerified = Settings.KeyVerified;

                    ForegroundColorSpan colorSpan = new ForegroundColorSpan(keyVerified ?
                                                                            Color.Green : Color.Red);
                    ISpannable summary = new SpannableString(keyVerified ?
                                                             GetString(Resource.String.message_keyverified) : GetString(Resource.String.message_keyinvalid));
                    summary.SetSpan(colorSpan, 0, summary.Length(), 0);
                    keyEntry.SummaryFormatted = summary;
                }
                else
                {
                    keyEntry.Summary = Activity.GetString(Resource.String.pref_summary_apikey, providerAPI);
                }
            }
            public DirectoryView(DirectoryInfo directory)
            {
                if (directory == null)
                {
                    throw new ArgumentNullException(nameof(directory));
                }

                var formatter = new SpanFormatter();

                formatter.AddFormatter <DateTime>(d => $"{d:d} {ForegroundColorSpan.DarkGray()}{d:t}");

                Add(new ContentView(""));
                Add(new ContentView(""));

                Add(new ContentView($"Directory: {directory.FullName}"));

                Add(new ContentView(""));
                Add(new ContentView(""));

                var directoryContents = directory.EnumerateFileSystemInfos()
                                        .OrderBy(f => f is DirectoryInfo
                                                                   ? 0
                                                                   : 1).ToList();

                var tableView = new TableView <FileSystemInfo>();

                tableView.Items = directoryContents;
                tableView.AddColumn(f => f is DirectoryInfo
                                     ? Span($"{ForegroundColorSpan.LightGreen()}{f.Name} ")
                                     : Span($"{ForegroundColorSpan.White()}{f.Name} "),
                                    new ContentView(formatter.ParseToSpan($"{Ansi.Text.UnderlinedOn}Name{Ansi.Text.UnderlinedOff}")));

                tableView.AddColumn(f => formatter.Format(f.CreationTime),
                                    new ContentView(formatter.ParseToSpan($"{Ansi.Text.UnderlinedOn}Created{Ansi.Text.UnderlinedOff}")));
                tableView.AddColumn(f => formatter.Format(f.LastWriteTime),
                                    new ContentView(formatter.ParseToSpan($"{Ansi.Text.UnderlinedOn}Modified{Ansi.Text.UnderlinedOff}")));

                Add(tableView);

                Span Span(FormattableString formattableString)
                {
                    return(formatter.ParseToSpan(formattableString));
                }
            }
Example #22
0
        public ProcessesView(Process[] processes)
        {
            var formatter = new TextSpanFormatter();

            formatter.AddFormatter <TimeSpan>(t => new ContentSpan(t.ToString(@"hh\:mm\:ss")));

            Add(new ContentView(""));
            Add(new ContentView("Processes"));
            Add(new ContentView(""));

            var table = new TableView <Process> {
                Items = processes
            };

            table.AddColumn(p => p.Id, new ContentView("PID".Underline()));
            table.AddColumn(p => Name(p), new ContentView("COMMAND".Underline()));
            table.AddColumn(p => p.PrivilegedProcessorTime, new ContentView("TIME".Underline()));
            table.AddColumn(p => p.Threads.Count, new ContentView("#TH".Underline()));
            table.AddColumn(
                p => p.PrivateMemorySize64.Abbreviate(),
                new ContentView("MEM".Underline())
                );
            table.AddColumn(
                p =>
            {
#pragma warning disable CS0618 // Type or member is obsolete
                var usage = p.TrackCpuUsage().First();
#pragma warning restore CS0618 // Type or member is obsolete
                return($"{usage.UsageTotal:P}");
            },
                new ContentView("CPU".Underline())
                );

            Add(table);

            FormattableString Name(Process p)
            {
                if (!p.Responding)
                {
                    return($"{ForegroundColorSpan.Rgb(180, 0, 0)}{p.ProcessName}{ForegroundColorSpan.Reset()}");
                }
                return($"{p.ProcessName}");
            }
        }
Example #23
0
            public override void Render(ConsoleRenderer renderer, Region region)
            {
                var p    = Math.Clamp(Progress, 0, 1.0);
                var done = (int)(p * 100);

                const int textWidth  = 6;
                var       text       = p.ToString("P");
                const int aHalf      = 47;
                var       firstFill  = Math.Clamp(done, 0, aHalf);
                var       secondFill = Math.Clamp(done - (aHalf + textWidth), 0, aHalf);

                var result = new ContainerSpan(
                    Title.StyleUnderline(),
                    ": ".AsTextSpan(),
                    new ContainerSpan(
                        new string('=', firstFill).StyleColor(ForegroundColorSpan.LightGreen()),
                        new string('-', aHalf - firstFill).StyleColor(ForegroundColorSpan.LightGray())
                        ),
                    done switch
                {
Example #24
0
        private void setTextWithSyntaxHighlighting(TextView view, string input)
        {
            // don't display a trailing semicolon if there is one
            if (input.EndsWith(";"))
            {
                input = input.Substring(0, input.Length - 1);
            }

            var builder        = new SpannableStringBuilder(input);
            var highlightColor = _context.Resources.GetColor(Resource.Color.SyntaxHighlight);

            var keywordMatches = Regex.Matches(input, _keywordRegex);

            foreach (Match match in keywordMatches)
            {
                var highlightColorSpan = new ForegroundColorSpan(highlightColor);
                builder.SetSpan(highlightColorSpan, match.Index, match.Index + match.Length, SpanTypes.InclusiveInclusive);
            }

            view.TextFormatted = builder;
        }
        public DirectoryTableView(DirectoryInfo directory)
        {
            if (directory == null)
            {
                throw new ArgumentNullException(nameof(directory));
            }

            Add(new ContentView("\n"));
            Add(new ContentView(Span($"Directory: {directory.FullName.Rgb(235, 30, 180)}")));
            Add(new ContentView("\n"));

            var tableView = new TableView <FileSystemInfo>();

            tableView.Items = directory
                              .EnumerateFileSystemInfos()
                              .OrderByDescending(f => f is DirectoryInfo)
                              .ToList();

            tableView.AddColumn(
                cellValue: f => f is DirectoryInfo ? f.Name.LightGreen() : f.Name.White(),
                header: new ContentView("Name".Underline())
                );

            tableView.AddColumn(
                cellValue: f => Span(f.CreationTime),
                header: new ContentView("Created".Underline())
                );

            tableView.AddColumn(
                cellValue: f => Span(f.LastWriteTime),
                header: new ContentView("Modified".Underline())
                );

            Add(tableView);

            Formatter.AddFormatter <DateTime>(d => $"{d:d} {ForegroundColorSpan.DarkGray()}{d:t}");
        }
Example #26
0
        public SpannableStringBuilder MakeColoredText(Entry entry)
        {
            SpannableStringBuilder spannable = new SpannableStringBuilder();

            int i = 0;

            foreach (Property p in UserSettings.Current.SelectedProperties)
            {
                try {
                    Amount a     = entry.GetPropertyValue(p);
                    string value = a.ValueString();

                    if (!string.IsNullOrEmpty(value))
                    {
                        if (i > 0)
                        {
                            spannable.Append(", ");
                        }

                        spannable.Append(p.TextOnly);

                        spannable.Append(" - ");

                        var span = new ForegroundColorSpan(AndroidUI.GetPropertyColor(context, i, p));
                        spannable.Append(value);

                        spannable.SetSpan(span, spannable.Length() - value.Length, spannable.Length(), SpanTypes.ExclusiveExclusive);
                    }

                    i++;
                } catch (Exception ex) {
                    LittleWatson.ReportException(ex);
                }
            }

            return(spannable);
        }
Example #27
0
        public override void Render(ConsoleRenderer renderer, Region region)
        {
            byte r = 0;
            byte g = 0;
            byte b = 0;

            var i = 0;

            for (var x = 0; x < region.Width; x++)
            {
                for (var y = 0; y < region.Height; y++)
                {
                    if (i >= Text.Length - 1)
                    {
                        i = 0;
                    }
                    else
                    {
                        i++;
                    }

                    var subregion = new Region(
                        region.Left + x,
                        region.Top + y,
                        1,
                        1);

                    unchecked
                    {
                        renderer.RenderToRegion(
                            $"{ForegroundColorSpan.Rgb(r += 2, g += 3, b += 5)}{Text[i]}{ForegroundColorSpan.Reset()}",
                            subregion);
                    }
                }
            }
        }
Example #28
0
 public virtual void Initialize()
 {
     Add(new ContentView("\n"));
     Add(new ContentView(Span($"Sql backup utility V{Assembly.GetExecutingAssembly().GetName().Version}".Orange())));
     Add(new ContentView(Span($"Jérôme Piquot".DarkOrange())));
     Add(new ContentView("\n"));
     Add(new ContentView(Span($"Command:                 {string.Join("; ", _options.Command).White()}")));
     Add(new ContentView(Span($"Sql server:              {string.Join("; ", _options.Server).DarkGrey()}")));
     Add(new ContentView("\n"));
     Add(new ContentView(Span($"Backup directories:      {string.Join("; ", _options.BackupDirectories).DarkGrey()}")));
     Add(new ContentView(Span($"Include sub directories: {_options.IncludeSubDirectories.ToString().DarkGrey()}")));
     Add(new ContentView(Span($"Backup extensions:       {string.Join("; ", _options.BackupExtensions).DarkGrey()}")));
     Add(new ContentView(Span($"Backup type:             {_options.BackupType.ToString().DarkGrey()}")));
     Add(new ContentView(Span($"Source server:           {_options.SourceServer?.ToString().DarkGrey()}")));
     Add(new ContentView(Span($"Source database:         {_options.SourceDatabase?.ToString().DarkGrey()}")));
     Add(new ContentView(Span($"Before:                  {_options.Before?.ToString(CultureInfo.CurrentCulture).DarkGrey()}")));
     AddSummaryInformation();
     if (_backups.Any())
     {
         Add(_tableView);
         AddTableInformation();
     }
     Formatter.AddFormatter <DateTime>(d => $"{d:d} {ForegroundColorSpan.DarkGray()}{d:t}");
 }
        /// <summary>
        /// Add a button and a text link and their tapping events to the more information page.
        /// </summary>
        /// <param name="consentDialogView"></param>
        private void AddMoreInfoButtonAndLinkClick(View consentDialogView)
        {
            moreInfoBackBtn           = consentDialogView.FindViewById <Button>(Resource.Id.btn_consent_more_info_back);
            moreInfoTv                = consentDialogView.FindViewById <TextView>(Resource.Id.consent_center_more_info_content);
            moreInfoTv.MovementMethod = ScrollingMovementMethod.Instance;

            moreInfoBackBtn.SetOnClickListener(this);

            string moreInfoText = context.Resources.GetString(Resource.String.consent_more_info_text);
            SpannableStringBuilder spanMoreInfoText = new SpannableStringBuilder(moreInfoText);

            // Set the listener on the event for tapping some text.
            ClickableSpan moreInfoToucHere = new MoreInfoTouchHere(this);

            ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.ParseColor("#0000FF"));
            int moreInfoTouchHereStart = context.Resources.GetInteger(Resource.Integer.more_info_here_start);
            int moreInfoTouchHereEnd   = context.Resources.GetInteger(Resource.Integer.more_info_here_end);

            spanMoreInfoText.SetSpan(moreInfoToucHere, moreInfoTouchHereStart, moreInfoTouchHereEnd, SpanTypes.ExclusiveExclusive);
            spanMoreInfoText.SetSpan(foregroundColorSpan, moreInfoTouchHereStart, moreInfoTouchHereEnd, SpanTypes.ExclusiveExclusive);

            moreInfoTv.TextFormatted  = spanMoreInfoText;
            moreInfoTv.MovementMethod = LinkMovementMethod.Instance;
        }
Example #30
0
        /// <summary>
        /// Demonstrates various rendering capabilities.
        /// </summary>
        /// <param name="invocationContext"></param>
        /// <param name="sample">Renders a specified sample</param>
        /// <param name="height">The height of the rendering area</param>
        /// <param name="width">The width of the rendering area</param>
        /// <param name="top">The top position of the render area</param>
        /// <param name="left">The left position of the render area</param>
        /// <param name="text">The text to render</param>
        /// <param name="overwrite">Overwrite the specified region. (If not, scroll.)</param>
        public static void Main(
#pragma warning disable CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do)
            InvocationContext invocationContext,
            SampleName sample = SampleName.Dir,
            int?height        = null,
            int?width         = null,
            int top           = 0,
            int left          = 0,
            string text       = null,
            bool overwrite    = true)
#pragma warning restore CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do)
        {
            var region = new Region(left,
                                    top,
                                    width ?? Console.WindowWidth,
                                    height ?? Console.WindowHeight,
                                    overwrite);

            if (overwrite &&
                invocationContext.Console is ITerminal terminal)
            {
                terminal.Clear();
            }

            var consoleRenderer = new ConsoleRenderer(
                invocationContext.Console,
                mode: invocationContext.BindingContext.OutputMode(),
                resetAfterRender: true);

            switch (sample)
            {
            case SampleName.Colors:
            {
                var screen = new ScreenView(renderer: consoleRenderer, invocationContext.Console);
                screen.Child = new ColorsView(text ?? "*");

                screen.Render(region);
            }
            break;

            case SampleName.Dir:
                var directoryTableView = new DirectoryTableView(new DirectoryInfo(Directory.GetCurrentDirectory()));
                directoryTableView.Render(consoleRenderer, region);

                break;

            case SampleName.Moby:
                consoleRenderer.RenderToRegion(
                    $"Call me {StyleSpan.BoldOn()}{StyleSpan.UnderlinedOn()}Ishmael{StyleSpan.UnderlinedOff()}{StyleSpan.BoldOff()}. Some years ago -- never mind how long precisely -- having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world. It is a way I have of driving off the spleen and regulating the circulation. Whenever I find myself growing grim about the mouth; whenever it is a damp, drizzly November in my soul; whenever I find myself involuntarily pausing before coffin warehouses, and bringing up the rear of every funeral I meet; and especially whenever my hypos get such an upper hand of me, that it requires a strong moral principle to prevent me from deliberately stepping into the street, and {ForegroundColorSpan.Rgb(60, 0, 0)}methodically{ForegroundColorSpan.Reset()} {ForegroundColorSpan.Rgb(90, 0, 0)}knocking{ForegroundColorSpan.Reset()} {ForegroundColorSpan.Rgb(120, 0, 0)}people's{ForegroundColorSpan.Reset()} {ForegroundColorSpan.Rgb(160, 0, 0)}hats{ForegroundColorSpan.Reset()} {ForegroundColorSpan.Rgb(220, 0, 0)}off{ForegroundColorSpan.Reset()} then, I account it high time to get to sea as soon as I can. This is my substitute for pistol and ball. With a philosophical flourish Cato throws himself upon his sword; I quietly take to the ship. There is nothing surprising in this. If they but knew it, almost all men in their degree, some time or other, cherish very nearly the same feelings towards the ocean with me.",
                    region);
                break;

            case SampleName.Processes:
            {
                var view = new ProcessesView(Process.GetProcesses());
                view.Render(consoleRenderer, region);
            }

            break;

            case SampleName.TableView:
            {
                var table = new TableView <Process>
                {
                    Items = Process.GetProcesses().Where(x => !string.IsNullOrEmpty(x.MainWindowTitle)).OrderBy(p => p.ProcessName).ToList()
                };
                table.AddColumn(process => $"{process.ProcessName} ", "Name");
                table.AddColumn(process => ContentView.FromObservable(process.TrackCpuUsage(), x => $"{x.UsageTotal:P}"), "CPU", ColumnDefinition.Star(1));

                var screen = new ScreenView(renderer: consoleRenderer, invocationContext.Console)
                {
                    Child = table
                };
                screen.Render();
            }
            break;

            case SampleName.Clock:
            {
                var screen          = new ScreenView(renderer: consoleRenderer, invocationContext.Console);
                var lastTime        = DateTime.Now;
                var clockObservable = new BehaviorSubject <DateTime>(lastTime);
                var clockView       = ContentView.FromObservable(clockObservable, x => $"{x:T}");
                screen.Child = clockView;
                screen.Render();

                while (!Console.KeyAvailable)
                {
                    if (DateTime.Now - lastTime > TimeSpan.FromSeconds(1))
                    {
                        lastTime = DateTime.Now;
                        clockObservable.OnNext(lastTime);
                    }
                }
            }
            break;

            case SampleName.GridLayout:
            {
                var screen  = new ScreenView(renderer: consoleRenderer, invocationContext.Console);
                var content = new ContentView(
                    "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum for Kevin.");
                var smallContent = new ContentView("Kevin Bost");
                var longContent  = new ContentView("Hacking on System.CommandLine");

                var gridView = new GridView();
                gridView.SetColumns(
                    ColumnDefinition.SizeToContent(),
                    ColumnDefinition.Star(1),
                    ColumnDefinition.Star(0.5)
                    );
                gridView.SetRows(
                    RowDefinition.Star(0.5),
                    RowDefinition.Star(0.5)
                    );

                gridView.SetChild(smallContent, 0, 0);
                gridView.SetChild(longContent, 0, 1);
                //gridView.SetChild(content, 0, 0);
                gridView.SetChild(content, 1, 1);
                gridView.SetChild(content, 2, 0);

                screen.Child = gridView;

                screen.Render();
            }
            break;

            default:
                if (!string.IsNullOrWhiteSpace(text))
                {
                    consoleRenderer.RenderToRegion(
                        text,
                        region);
                }
                else
                {
                    var screen      = new ScreenView(renderer: consoleRenderer, invocationContext.Console);
                    var stackLayout = new StackLayoutView();
                    var content1    = new ContentView("Hello World!");
                    var content2    = new ContentView(
                        "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum for Kevin.");
                    stackLayout.Add(content2);
                    stackLayout.Add(content1);
                    stackLayout.Add(content2);
                    screen.Child = stackLayout;
                    screen.Render(new Region(0, 0, 50, Size.MaxValue));
                    //screen.Render(writer);
                }

                break;
            }

            if (!Console.IsOutputRedirected)
            {
                Console.ReadKey();
            }
        }