PowerLine.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Text;
using System.Text.RegularExpressions;
 
namespace PowerLine
{
    public static class AnsiHelper
    {
        public static string GetCode(this ConsoleColor? color, bool forBackground = false)
        {
            string colorCode = color == null ? "Default" : color.ToString();
 
            return forBackground ? Background[colorCode] : Foreground[colorCode];
 
        }
        public static Dictionary<string, string> Foreground = new Dictionary<string, string>
            {
                {"Clear", "\u001B[39m"},
                {"Black", "\u001B[30m"}, { "DarkGray", "\u001B[90m"},
                {"DarkRed", "\u001B[31m"}, { "Red", "\u001B[91m"},
                {"DarkGreen", "\u001B[32m"}, { "Green", "\u001B[92m"},
                {"DarkYellow", "\u001B[33m"}, { "Yellow", "\u001B[93m"},
                {"DarkBlue", "\u001B[34m"}, { "Blue", "\u001B[94m"},
                {"DarkMagenta", "\u001B[35m"}, { "Magenta", "\u001B[95m"},
                {"DarkCyan", "\u001B[36m"}, { "Cyan", "\u001B[96m"},
                {"Gray", "\u001B[37m"}, { "White", "\u001B[97m"}
            };
 
        public static Dictionary<string, string> Background = new Dictionary<string, string>
            {
                {"Clear", "\u001B[49m"},
                {"Black", "\u001B[40m"}, {"DarkGray", "\u001B[100m"},
                {"DarkRed", "\u001B[41m"}, {"Red", "\u001B[101m"},
                {"DarkGreen", "\u001B[42m"}, {"Green", "\u001B[102m"},
                {"DarkYellow", "\u001B[43m"}, {"Yellow", "\u001B[103m"},
                {"DarkBlue", "\u001B[44m"}, {"Blue", "\u001B[104m"},
                {"DarkMagenta", "\u001B[45m"}, {"Magenta", "\u001B[105m"},
                {"DarkCyan", "\u001B[46m"}, {"Cyan", "\u001B[106m"},
                {"Gray", "\u001B[47m"}, {"White", "\u001B[107m"},
            };
 
 
        public static string WriteAnsi(ConsoleColor? foreground, ConsoleColor? background, string value, bool clear = false)
        {
            var output = new StringBuilder();
 
            output.Append(background.GetCode(true));
            output.Append(foreground.GetCode());
 
            output.Append(value);
            if (clear)
            {
                output.Append(AnsiHelper.Background["Clear"]);
                output.Append(AnsiHelper.Foreground["Clear"]);
            }
            return output.ToString();
        }
 
        public static string GetString(object @object)
        {
            return (string)LanguagePrimitives.ConvertTo(@object is ScriptBlock ? ((ScriptBlock)@object).Invoke() : @object, typeof(string));
        }
 
        static AnsiHelper()
        {
            Console.ResetColor();
            Foreground.Add("Default", Foreground[Console.ForegroundColor.ToString()]);
            Background.Add("Default", Background[Console.BackgroundColor.ToString()]);
        }
 
        public struct EscapeCodes
        {
            public static readonly string ESC = "\u001B[";
            public static readonly string Clear = "\u001B[0m";
            public static readonly string PromptLocation = "\u001B[s";
            public static readonly string Recall = "\u001B[u";
        };
    }
    public class Block
    {
        private string _text;
        /// <summary>
        /// Gets or sets the object. The Object will be converted to string when it's set, and this property always returns a string.
        /// </summary>
        /// <value>A string</value>
        public virtual object Object
        {
            get
            {
                return _text;
            }
            set
            {
                _text = (string)LanguagePrimitives.ConvertTo(value, typeof(string));
 
                // If there's actually no output, report a negative length to ignore this block
                if (string.IsNullOrEmpty(_text))
                {
                    Length = -1;
                }
                else
                {
                    // The Length is measured without escape sequences (ESC + non-letters + any letter)
                    Length = _escapeCode.Replace(_text, "").Length;
                }
            }
        }
        private Regex _escapeCode = new Regex("\u001B\\P{L}+\\p{L}", RegexOptions.Compiled);
 
        /// <summary>
        /// Gets or Sets the background color for the block
        /// </summary>
        public virtual ConsoleColor? BackgroundColor { get; set; }
 
        /// <summary>
        /// Gets or Sets the foreground color for the block
        /// </summary>
        public virtual ConsoleColor? ForegroundColor { get; set; }
 
        /// <summary>
        /// Gets the length of the text representation (without ANSI escape sequences).
        /// </summary>
        public virtual int Length { get; private set; }
 
        /// <summary>
        /// This constructor is here so we can allow partial matches to the property names.
        /// </summary>
        /// <param name="values"></param>
        public Block(IDictionary values) : this()
        {
            foreach (string key in values.Keys)
            {
                var pattern = "^" + Regex.Escape(key);
                if ("bg".Equals(key, System.StringComparison.InvariantCultureIgnoreCase) || Regex.IsMatch("BackgroundColor", pattern, RegexOptions.IgnoreCase))
                {
                    BackgroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), values[key].ToString(), true);
                }
                else if ("fg".Equals(key, System.StringComparison.InvariantCultureIgnoreCase) || Regex.IsMatch("ForegroundColor", pattern, RegexOptions.IgnoreCase))
                {
                    ForegroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), values[key].ToString(), true);
                }
                else if (Regex.IsMatch("text", pattern, RegexOptions.IgnoreCase) || Regex.IsMatch("Content", pattern, RegexOptions.IgnoreCase) || Regex.IsMatch("Object", pattern, RegexOptions.IgnoreCase))
                {
                    Object = values[key];
                }
                //else if (Regex.IsMatch("Clear", pattern, RegexOptions.IgnoreCase))
                //{
                // Clear = (bool)values[key];
                //}
                else
                {
                    throw new ArgumentException("Unknown key '" + key + "' in hashtable. Allowed values are BackgroundColor, ForegroundColor, and Object (also called Content or Text)");
                }
            }
        }
        // Make sure we can output plain text
        public Block(string Text) : this()
        {
            Object = Text;
        }
 
        // Make sure we support the default ctor
        public Block() { Length = -1; }
 
        public override string ToString()
        {
            // If there's nothing but escape codes, don't bother outputting new colors
            if (Length == 0)
            {
                return (string)Object;
            }
            return AnsiHelper.WriteAnsi(ForegroundColor, BackgroundColor, (string)Object);
        }
 
        // override object.Equals
        public override bool Equals(object obj)
        {
            if (obj == null || GetType() != obj.GetType())
            {
                // Console.WriteLine(GetType().FullName + " is not " + obj.GetType().FullName);
                return false;
            }
 
            var other = obj as Block;
 
            return Object == other.Object && ForegroundColor == other.ForegroundColor && BackgroundColor == other.BackgroundColor;
        }
 
        // override object.GetHashCode
        public override int GetHashCode()
        {
            return Object.GetHashCode() + BackgroundColor.GetHashCode() + ForegroundColor.GetHashCode();
        }
    }
 
    /// <summary>
    /// The block factory is a Block which supports scriptblocks that output blocks ...
    /// </summary>
    public class BlockFactory
    {
        /// <summary>
        /// Gets or Sets the background color for the block
        /// </summary>
        public virtual ConsoleColor? DefaultBackgroundColor { get; set; }
 
        /// <summary>
        /// Gets or Sets the foreground color for the block
        /// </summary>
        public virtual ConsoleColor? DefaultForegroundColor { get; set; }
 
        /// <summary>
        /// Gets or Sets the object to be rendered.
        /// Can be any object, but with particular support for nested lists of objects, blocks, or ScriptBlocks which output them.
        /// </summary>
        public virtual object Object { get; set; }
 
        /// <summary>
        /// This constructor is here so we can allow partial matches to the property names.
        /// </summary>
        /// <param name="values"></param>
        public BlockFactory(IDictionary values)
        {
            foreach (string key in values.Keys)
            {
                var pattern = "^" + Regex.Escape(key);
                if ("bg".Equals(key, System.StringComparison.InvariantCultureIgnoreCase) || Regex.IsMatch("BackgroundColor", pattern, RegexOptions.IgnoreCase) || Regex.IsMatch("DefaultBackgroundColor", pattern, RegexOptions.IgnoreCase))
                {
                    DefaultBackgroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), values[key].ToString(), true);
                }
                else if ("fg".Equals(key, System.StringComparison.InvariantCultureIgnoreCase) || Regex.IsMatch("ForegroundColor", pattern, RegexOptions.IgnoreCase) || Regex.IsMatch("DefaultForegroundColor", pattern, RegexOptions.IgnoreCase))
                {
                    DefaultForegroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), values[key].ToString(), true);
                }
                else if (Regex.IsMatch("text", pattern, RegexOptions.IgnoreCase) || Regex.IsMatch("Content", pattern, RegexOptions.IgnoreCase) || Regex.IsMatch("Object", pattern, RegexOptions.IgnoreCase))
                {
                    Object = values[key];
                }
                //else if (Regex.IsMatch("Clear", pattern, RegexOptions.IgnoreCase))
                //{
                // Clear = (bool)values[key];
                //}
                else
                {
                    throw new ArgumentException("Unknown key '" + key + "' in " + values.GetType().Name + ". Allowed values are BackgroundColor (or bg), ForegroundColor (or fg), and Object (also called Content or Text)");
                }
            }
        }
 
        public BlockFactory(Block block)
        {
            Object = block;
        }
 
        public BlockFactory(params Block[] blocks)
        {
            Object = blocks;
        }
 
        public Block[] GetBlocks()
        {
            // There are four allowed values:
            // 1. A scriptblock, which outputs one of the other possibilities
            // 2. One or more blocks
            // 3. Things we'll convert to text
            var cache = Object;
            Block[] blocks;
 
            // if it's a scriptblock, get the output
            if (cache is ScriptBlock)
            {
                cache = ((ScriptBlock)cache).Invoke();
            }
 
            // Try to convert it to blocks
            try
            {
                blocks = LanguagePrimitives.ConvertTo<Block[]>(cache);
                foreach (var block in blocks)
                {
                    block.BackgroundColor = block.BackgroundColor ?? DefaultBackgroundColor;
                    block.ForegroundColor = block.ForegroundColor ?? DefaultForegroundColor;
                };
            }
            catch
            {
                // If all else fails, make new ones using our default colors
                blocks = LanguagePrimitives.ConvertTo<string[]>(cache)
                                            .Select(o => new Block
                                            {
                                                Object = o,
                                                BackgroundColor = DefaultBackgroundColor,
                                                ForegroundColor = DefaultForegroundColor
                                            }).ToArray();
            }
            return blocks;
        }
    }
 
    public class Column
    {
        /// <summary>
        /// Gets the blocks
        /// </summary>
        public virtual List<BlockFactory> Blocks { get; private set; }
 
        public Column()
        {
            Blocks = new List<BlockFactory>();
            Length = -1;
        }
 
        public Column(params BlockFactory[] blocks) : this()
        {
            Blocks.AddRange(blocks);
        }
 
        public Column(params Block[] blocks) : this()
        {
            // Convert BlockBase to BlockFactory
            Blocks.AddRange(blocks.Select(b => new BlockFactory(b)));
        }
 
        public Column(params object[] blocks) : this()
        {
            foreach (object block in blocks)
            {
                Blocks.AddRange(LanguagePrimitives.ConvertTo<BlockFactory[]>(block));
                continue;
            }
        }
 
        public ConsoleColor? StartBackgroundColor { get; private set; }
 
        public ConsoleColor? EndBackgroundColor { get; private set; }
 
        public int Length { get; private set; }
 
        private Block[] ValidBlocks { get; set; }
 
        public Block[] PreCalculateValues()
        {
            // Calculate all the text and remove empty blocks
            ValidBlocks = Blocks.SelectMany(factory => factory.GetBlocks()).Where(e => e.Length >= 0).ToArray();
            Length = -1;
            Block block;
            if (ValidBlocks.Any())
            {
                StartBackgroundColor = (block = ValidBlocks.First(b => b.BackgroundColor != null)) == null ? null : block.BackgroundColor;
                EndBackgroundColor = (block = ValidBlocks.Last(b => b.BackgroundColor != null)) == null ? null : block.BackgroundColor;
                Length = ValidBlocks.Sum(b => b.Length) + (ValidBlocks.Length - 1);
            }
            return ValidBlocks;
        }
 
        public string ToString(string separator, string colorSeparator, bool rightJustified = false)
        {
            // Initialize variables ...
            var output = new StringBuilder();
            Block[] ValidBlocks = PreCalculateValues();
 
            for (int l = 0; l < ValidBlocks.Length; l++)
            {
                var block = ValidBlocks[l];
                output.Append(block.ToString());
 
                // Write a separator between blocks, unless the next one has no (non-escape) text
                if (l < ValidBlocks.Length - 1 && ValidBlocks[l + 1].Length > 0)
                {
                    // if the colors are the same, use the separator
                    if (block.BackgroundColor == ValidBlocks[l + 1].BackgroundColor)
                    {
                        output.Append(separator);
                    }
                    // if they're different, use the colorSeparator
                    else
                    {
                        if (rightJustified)
                        {
                            output.Append(AnsiHelper.WriteAnsi(ValidBlocks[l + 1].BackgroundColor, block.BackgroundColor, colorSeparator));
                        }
                        else
                        {
                            output.Append(AnsiHelper.WriteAnsi(block.BackgroundColor, ValidBlocks[l + 1].BackgroundColor, colorSeparator));
                        }
                    }
                }
            }
            // clear colors at the end of each column
            output.Append(AnsiHelper.Foreground["Default"]);
            output.Append(AnsiHelper.Background["Default"]);
            return output.ToString();
        }
 
        public override string ToString()
        {
            return ToString(Prompt.Separator, Prompt.ColorSeparator);
        }
    }
 
 
    public class Line
    {
        public List<Column> Columns { get; private set; }
 
        public Line()
        {
            Columns = new List<Column>();
        }
 
        public Line(params Column[] blocks) : this()
        {
            Columns.AddRange(blocks);
        }
 
        public Line(object[] columns) : this()
        {
            Column[] cols;
            if (LanguagePrimitives.TryConvertTo(columns, out cols))
            {
                Columns.AddRange(cols);
                return;
            }
 
            // Console.WriteLine("Fallback to single column");
            Column column;
            if (LanguagePrimitives.TryConvertTo(columns, out column))
            {
                Columns.Add(column);
                return;
            }
 
            // Console.WriteLine("Fallback to casting one at a time");
            foreach (object col in columns)
            {
                if (col == null)
                {
                    Columns.Add(new Column());
                    continue;
                }
 
                if (LanguagePrimitives.TryConvertTo(columns, out column))
                {
                    Columns.Add(column);
                    continue;
                }
 
                // Console.WriteLine("Fallback to block factories");
                // This should let us skip explicitly having columns
                BlockFactory[] factories;
                if (LanguagePrimitives.TryConvertTo(columns, out factories))
                {
                    Columns.Add(new Column(factories));
                    continue;
                }
 
                // Console.WriteLine("Fallback to a single block factory");
                BlockFactory factory;
                if (LanguagePrimitives.TryConvertTo(columns, out factory))
                {
                    Columns.Add(new Column(factory));
                    continue;
                }
            }
        }
 
        public List<Column> PreCalculateValues()
        {
            // Calculate all the text and remove empty blocks
            foreach (var column in Columns)
            {
                if (column != null)
                {
                    column.PreCalculateValues();
                }
            }
 
            return Columns;
        }
 
        public override string ToString()
        {
            return ToString(Console.BufferWidth);
        }
 
        public string ToString(int width)
        {
            var Columns = PreCalculateValues();
 
            var output = new StringBuilder();
            // Output each block with appropriate separators and caps
            for (int l = 0; l < Columns.Count;)
            {
                var column = Columns[l];
                // Use null columns as spacers
                if (column != null && column.Length > 0)
                {
                    string text = column.ToString(Prompt.Separator, Prompt.ColorSeparator);
                    output.Append(text);
                    output.Append(AnsiHelper.WriteAnsi(column.EndBackgroundColor, null, Prompt.ColorSeparator));
                }
 
                // Force the prompt location to the end of the first column
                output.Append(AnsiHelper.EscapeCodes.PromptLocation);
 
                // CURRENTLY we only support two columns, so ...
                // if there are more columns, the next one is right-aligned
                if (Columns.Count > ++l)
                {
                    column = Columns[l];
                    // Use null columns as spacers
                    if (column != null && column.Length > 0)
                    {
                        // Move to the start location for the next column
                        output.Append(AnsiHelper.EscapeCodes.ESC + (width - column.Length) + "G");
 
                        output.Append(AnsiHelper.WriteAnsi(column.StartBackgroundColor, null, Prompt.ReverseColorSeparator));
                        output.Append(column.ToString(Prompt.ReverseSeparator, Prompt.ReverseColorSeparator, true));
                    }
                }
 
                if (Columns.Count > ++l)
                {
                    // Because we only support two columns, if there are still more columns, they must go on the next line
                    output.Append("\n");
                }
            }
 
            return output.ToString();
        }
    }
 
    public class Prompt
    {
        public static string ColorSeparator = "\u258C"; // ▌
        public static string ReverseColorSeparator = "\u2590"; // ▐
        public static string Separator = "\u25BA"; // ►
        public static string ReverseSeparator = "\u25C4"; // ◄
        public static string Branch = "\ue0a0"; // Branch symbol
        public static string Lock = "\ue0a2"; // Padlock
        public static string Gear = "\u26ef"; // The settings icon, I use it for debug
        public static string Power = "\u26a1"; // The Power lightning-bolt icon
 
        public List<Line> Lines { get; private set; }
        public ScriptBlock Title { get; set; }
        public bool SetCurrentDirectory { get; set; }
        public int PrefixLines { get; set; }
 
        public Prompt()
        {
            Lines = new List<Line>();
        }
 
        public Prompt(int prefixLines, params Line[] lines) : this()
        {
            PrefixLines = prefixLines;
            Lines.AddRange(lines);
        }
 
        public Prompt(params Line[] lines) : this()
        {
            Lines.AddRange(lines);
        }
 
        public Prompt(object[] lines) : this()
        {
            if (lines.First() is int)
            {
                PrefixLines = (int)lines.First();
                lines = lines.Skip(1).ToArray();
            }
 
            Line[] lns;
            if (LanguagePrimitives.TryConvertTo(lines, out lns))
            {
                Lines.AddRange(lns);
                return;
            }
 
            Line ln;
            if (LanguagePrimitives.TryConvertTo(lines, out ln))
            {
                Lines.Add(ln);
                return;
            }
 
            foreach (object line in lines)
            {
                Lines.Add(LanguagePrimitives.ConvertTo<Line>(line));
                continue;
            }
        }
 
        public override string ToString()
        {
            return ToString(Console.BufferWidth);
        }
 
        public string ToString(int width)
        {
            var output = new StringBuilder();
 
            // Move up to previous line(s)
            if (PrefixLines != 0)
            {
                output.Append(AnsiHelper.EscapeCodes.ESC + Math.Abs(PrefixLines) + "A");
            }
 
            output.Append(string.Join("\n", Lines.Select(l => l.ToString(width))));
            output.Append(AnsiHelper.Foreground["Default"]);
            output.Append(AnsiHelper.Background["Default"]);
            output.Append(AnsiHelper.EscapeCodes.Recall);
 
            return output.ToString();
        }
 
    }
}