-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathOutputWindow.cs
663 lines (563 loc) · 17.4 KB
/
OutputWindow.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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
namespace Menees.Windows.Forms
{
#region Using Directives
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using tom;
#endregion
/// <summary>
/// A read-only output window that supports rich text.
/// </summary>
[ToolboxBitmap(typeof(OutputWindow), "Images.OutputWindow.bmp")]
public partial class OutputWindow : ExtendedUserControl, IOutputWindow, IFindTarget
{
#region Private Data Members
private const string DefaultFindCaption = "Find In Output";
private const int RichTextBoxDefaultTabStopWidth = 36; // From ITextDocument.DefaultTabStop
private readonly List<int> highlights = new();
private readonly Dictionary<Guid, int> outputIdToOffsetMap = new();
private int indentWidth;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance.
/// </summary>
public OutputWindow()
{
this.FindCaption = DefaultFindCaption;
this.InitializeComponent();
base.BorderStyle = BorderStyle.Fixed3D;
this.output.BorderStyle = BorderStyle.None;
this.IndentWidth = RichTextBoxDefaultTabStopWidth;
}
#endregion
#region Public Properties
/// <summary>
/// Gets whether the <see cref="Find"/> method can be used.
/// </summary>
[Browsable(false)]
public bool CanFind => this.HasText;
/// <summary>
/// Gets or sets the caption to use for find operations.
/// </summary>
[DefaultValue(DefaultFindCaption)]
[Description("The caption to use for find operations.")]
public string FindCaption { get; set; }
/// <summary>
/// Gets whether any text is currently selected in the output window.
/// </summary>
[Browsable(false)]
public bool HasSelection
{
get
{
bool result = this.output.SelectionLength > 0;
return result;
}
}
/// <summary>
/// Gets whether any text is currently in the output window.
/// </summary>
[Browsable(false)]
public bool HasText
{
get
{
bool result = this.output.TextLength > 0;
return result;
}
}
/// <summary>
/// Gets whether the output window currently has focus.
/// </summary>
[Browsable(false)]
public bool IsFocused
{
get
{
bool result = this.output.Focused;
return result;
}
}
/// <summary>
/// Gets the form that owns the output window.
/// </summary>
[Browsable(false)]
[DefaultValue(null)]
public IWin32Window OwnerWindow
{
get
{
Form result = this.output.FindForm();
return result;
}
set
{
IWin32Window currentOwner = this.OwnerWindow;
// Don't let a caller try to change it to something else.
if (currentOwner != null && currentOwner != value)
{
throw Exceptions.NewArgumentException("The OwnerWindow can only be set to the parent form.");
}
}
}
/// <summary>
/// Gets the currently selected text in the output window.
/// </summary>
[Browsable(false)]
public string SelectedText
{
get
{
string result = this.output.SelectedText;
return result;
}
}
/// <summary>
/// Gets or sets whether the output window content should word wrap.
/// </summary>
[DefaultValue(false)]
public bool WordWrap
{
get
{
return this.output.WordWrap;
}
set
{
this.output.WordWrap = value;
}
}
/// <summary>
/// Gets or sets the border style of the window.
/// </summary>
[DefaultValue(BorderStyle.Fixed3D)]
public new BorderStyle BorderStyle
{
get
{
return base.BorderStyle;
}
set
{
base.BorderStyle = value;
}
}
/// <summary>
/// Gets or sets a delegate that can remove a custom line prefix after a line is double-clicked
/// and before the line's file reference is parsed and opened.
/// </summary>
public Func<string, string>? RemoveLinePrefix { get; set; }
/// <summary>
/// Gets or sets the pixel width of each output window indent and tab stop.
/// </summary>
[DefaultValue(RichTextBoxDefaultTabStopWidth)]
public int IndentWidth
{
get => this.indentWidth;
set
{
Conditions.RequireArgument(value > 0, nameof(this.IndentWidth) + " must be positive.");
if (this.indentWidth != value)
{
this.indentWidth = value;
// The RichTextBox.SelectionTabs property supports a maximum of 32 elements.
const int MaxTabStops = 32;
int[] tabStops = new int[MaxTabStops];
for (int i = 1; i <= MaxTabStops; i++)
{
tabStops[i - 1] = value * i;
}
}
}
}
#endregion
#region Public Methods
/// <summary>
/// Appends formatted text to the output.
/// </summary>
/// <param name="message">The text to append.</param>
/// <param name="color">The text color.</param>
/// <param name="indentLevel">The indent level.</param>
/// <param name="highlight">Whether this line should be considered a highlight.</param>
/// <param name="outputId">A guid to uniquely identify this message.</param>
public void Append(string message, Color color, int indentLevel, bool highlight, Guid outputId)
{
// Try to append using the Text Object Model COM interface because it
// lets us append at the end without moving the caret/selection. That
// allows the user move around in the output while we're appending to it
// just like Visual Studio's output window does.
bool appended = this.AppendWithTom(message, color, indentLevel, highlight, outputId);
if (!appended)
{
// If the TOM COM API failed, then append the old way.
this.AppendWithSelection(message, color, indentLevel, highlight, outputId);
}
}
/// <summary>
/// Clears the output window.
/// </summary>
public void Clear()
{
this.highlights.Clear();
this.outputIdToOffsetMap.Clear();
this.output.Clear();
}
/// <summary>
/// Copies the currently selected text to the clipboard.
/// </summary>
public void Copy()
{
this.output.Copy();
}
/// <summary>
/// Finds the specified text in the output window.
/// </summary>
/// <param name="findData">The text to search for.</param>
/// <param name="findMode">Whether to find next, previous, or display a dialog.</param>
/// <returns>True if the find text was found and selected. False otherwise.</returns>
public bool Find(FindData findData, FindMode findMode)
{
TextBoxFinder finder = new(this.output);
bool result = finder.Find(this.OwnerWindow, findData, findMode);
return result;
}
/// <summary>
/// Finds the next highlight position.
/// </summary>
/// <param name="searchForward">Whether to search forward/down (if true) or backward/up (if false).</param>
/// <param name="moveCurrentPosition">Whether to move and scroll to the next highlight if found.</param>
/// <returns>True if the next highlight was found. False otherwise.</returns>
public bool FindNextHighlightPosition(bool searchForward, bool moveCurrentPosition)
{
int selectionStart = this.output.SelectionStart;
var highlight = searchForward ? this.GetNextHighlight(selectionStart) : this.GetPreviousHighlight(selectionStart);
if (moveCurrentPosition)
{
this.GoToHighlight(highlight);
}
return highlight >= 0;
}
/// <summary>
/// Finds the output entry with the specified guid.
/// </summary>
/// <param name="outputId">A guid that identifies an appended message.</param>
/// <param name="moveCurrentPosition">Whether to move and scroll to the matched output if found.</param>
/// <returns>True if the specified output was found. False otherwise.</returns>
public bool FindOutput(Guid outputId, bool moveCurrentPosition)
{
bool result = this.outputIdToOffsetMap.TryGetValue(outputId, out int offset);
if (result && moveCurrentPosition)
{
this.GoToHighlight(offset);
}
return result;
}
/// <summary>
/// Saves the output window contents to a file.
/// </summary>
/// <param name="fileName">The name of the file to save to.</param>
/// <param name="asRichText">True to save as rich text (RTF) or false to save as plain text.</param>
public void SaveContent(string fileName, bool asRichText)
{
var format = asRichText ? RichTextBoxStreamType.RichText : RichTextBoxStreamType.PlainText;
this.output.SaveFile(fileName, format);
}
/// <summary>
/// Selects all the text in the output window.
/// </summary>
public void SelectAll()
{
this.output.SelectAll();
}
#endregion
#region IOutputWindow Members
void IOutputWindow.Focus()
{
this.Focus();
}
#endregion
#region Internal Methods
internal static bool OpenLineFileReference(IWin32Window owner, string currentLine)
{
bool result = false;
if (!string.IsNullOrWhiteSpace(currentLine))
{
currentLine = currentLine.Trim();
// Parse the file path out of a line like:
// c:\projects\csharp\megabuild\forms\mainform.cs(2495,17): error CS1002: ; expected
// But also work with something like:
// c:\projects\csharp\megabuild\forms\mainform.cs
// And with threaded C++ builds like:
// 16>c:\projects\csharp\megabuild\forms\mainform.cs(2495,17): error CS1002: ; expected
//
// See if VC++ has put a build thread ID on the front of the line (e.g., 16>...).
string path = currentLine;
int threadTokenIndex = path.IndexOf('>');
if (threadTokenIndex >= 0 && threadTokenIndex < path.Length && int.TryParse(path.Substring(0, threadTokenIndex), out _))
{
path = path.Substring(threadTokenIndex + 1);
}
// A drive-letter path or a UNC path can never have a colon at index 0 or 1.
int colonPos = path.IndexOf(':', 2);
if (colonPos >= 2)
{
path = path.Substring(0, colonPos);
}
// If it ends with "(###)", strip the line/column numbers off.
int parenIndex = path.IndexOf('(');
string lineNumber = string.Empty;
if (parenIndex >= 0)
{
lineNumber = TextUtility.StripQuotes(path.Substring(parenIndex).Trim(), "(", ")").Trim();
path = path.Substring(0, parenIndex);
// If the "line number" also contains a column number (e.g., (123,21)),
// then we have throw out the column information.
for (int i = 0; i < lineNumber.Length; i++)
{
if (!char.IsDigit(lineNumber[i]))
{
lineNumber = lineNumber.Substring(0, i);
break;
}
}
}
path = path.Trim();
if (File.Exists(path) || Directory.Exists(path))
{
// If we have line information assume it came from a Visual Studio build.
if (lineNumber.Length == 0 || !(result = VisualStudioUtility.OpenFile(path, lineNumber)))
{
result = WindowsUtility.ShellExecute(owner, path);
}
}
}
return result;
}
#endregion
#region Protected Methods
/// <summary>
/// Called when the control's context menu strip has changed.
/// </summary>
protected override void OnContextMenuStripChanged(EventArgs e)
{
this.output.ContextMenuStrip = this.ContextMenuStrip;
base.OnContextMenuStripChanged(e);
}
#endregion
#region Private Event Handlers
private void RichTextBox_DoubleClick(object sender, EventArgs e)
{
string currentLine = this.output.GetCurrentLineText(false);
currentLine = this.RemoveLinePrefix?.Invoke(currentLine) ?? currentLine;
OpenLineFileReference(this.OwnerWindow, currentLine);
}
private void RichTextBox_LinkClicked(object sender, LinkClickedEventArgs e)
{
WindowsUtility.ShellExecute(this.OwnerWindow, e.LinkText ?? string.Empty);
}
#endregion
#region Private Methods
private void GoToHighlight(int index)
{
if (index >= 0)
{
this.output.Select(index, 0);
this.output.Focus();
this.output.ScrollToCaret();
}
}
private int GetPreviousHighlight(int selectionStart)
{
int result = -1;
// Do a simple linear search backwards to find the previous index.
int numHighlights = this.highlights.Count;
for (int i = numHighlights - 1; i >= 0; i--)
{
int highlight = this.highlights[i];
if (highlight < selectionStart)
{
result = highlight;
break;
}
}
return result;
}
private int GetNextHighlight(int selectionStart)
{
int result = -1;
// They're in sorted order, but I'm just going to do a simple linear search.
// There would have to be thousands of highlights before anyone would
// notice a speed difference.
foreach (int highlight in this.highlights)
{
if (highlight > selectionStart)
{
result = highlight;
break;
}
}
return result;
}
private void MoveCaretToEnd()
{
// I'm intentionally not passing TextLength because Select always
// calls that internally anyway. So we might as well let it do it.
this.output.Select(int.MaxValue, 0);
}
private void ScrollToBottom()
{
// ScrollToCaret only works if the Output window has the focus, so this is more reliable.
// Also, ScrollToCaret and ITextRange.ScrollIntoView's scrolling are occasionally "jumpy"
// and don't always scroll consistently to the very bottom.
const int WM_VSCROLL = 0x0115;
const int SB_BOTTOM = 7;
NativeMethods.SendMessage(this.output, WM_VSCROLL, SB_BOTTOM, 0);
}
private void AppendWithSelection(string message, Color color, int indentLevel, bool highlight, Guid outputId)
{
// Force the cursor to the end. This isn't necessary for
// AppendText, but for the color and indent settings it is.
this.MoveCaretToEnd();
// Store the index if this is a highlighted message.
if (highlight)
{
// The indexes stay in sorted order because we're only appending text.
this.highlights.Add(this.output.SelectionStart);
}
// If they assigned a guid to this output, the store its location.
// I'm using Dictionary.Add here, so they'll get an error if they
// try to reuse a guid for multiple outputs.
if (outputId != Guid.Empty)
{
this.outputIdToOffsetMap.Add(outputId, this.output.SelectionStart);
}
// Color
this.output.SelectionColor = color;
// Indent
this.output.SelectionIndent = this.IndentWidth * Math.Max(indentLevel, 0);
// Message
if (message != null)
{
this.output.AppendText(message);
}
this.ScrollToBottom();
}
private bool AppendWithTom(string message, Color color, int indentLevel, bool highlight, Guid outputId)
{
bool result = false;
using (var doc = new ComInterfaceRef<ITextDocument>((ITextDocument?)this.output.GetOleInterface()))
{
if (doc.Ref != null)
{
// If the caret is already at the end of the document, then we'll
// automatically scroll to the bottom after we append.
bool scrollToBottom = this.output.SelectionStart >= this.output.TextLength;
// We have to make sure the RichEdit control is writable (at least temporarily).
// Otherwise, ITextRange.CanEdit returns false, and none of ITextRange's methods
// would let us make changes.
bool previousReadOnlyState = this.output.ReadOnly;
this.output.ReadOnly = false;
try
{
// Get a new range and insertion point at the very end of the document.
using (var range = new ComInterfaceRef<ITextRange>(doc.Ref.Range(int.MaxValue, int.MaxValue)))
{
if (range.Ref != null && range.Ref.CanEdit() != 0)
{
bool setIndents = false;
using (var para = new ComInterfaceRef<ITextPara>(range.Ref.Para))
{
if (para.Ref != null)
{
para.Ref.SetIndents(0, this.IndentWidth * Math.Max(0, indentLevel), 0);
setIndents = true;
}
}
bool setColor = false;
using (var font = new ComInterfaceRef<ITextFont>(range.Ref.Font))
{
if (font.Ref != null)
{
// Adapted from the RGB macro in WinGDI.h
const int BitsPerByte = 8;
font.Ref.ForeColor = color.R | (color.G << BitsPerByte) | (color.B << (2 * BitsPerByte));
setColor = true;
}
}
// If we were able to set all the options, then go ahead and append the text.
if (setIndents && setColor)
{
range.Ref.Text = message;
result = true;
if (highlight)
{
this.highlights.Add(range.Ref.Start);
}
if (outputId != Guid.Empty)
{
this.outputIdToOffsetMap.Add(outputId, range.Ref.Start);
}
// If we're supposed to automatically scroll to the bottom, then we
// need to move the caret to the end, so we'll be able to detect
// the auto-scrolling need correctly on the next Append too.
if (scrollToBottom)
{
this.MoveCaretToEnd();
this.ScrollToBottom();
}
}
}
}
}
finally
{
this.output.ReadOnly = previousReadOnlyState;
}
}
}
return result;
}
#endregion
#region Private Types
/// <summary>
/// This is a disposable type so we can deterministically release a COM
/// reference as soon as we're done with it. Otherwise, we end up with
/// COM objects that outlive the context they're running in, and Visual
/// Studio raises "DisconnectedContext was detected" MDA warnings in
/// the debugger.
/// </summary>
private sealed class ComInterfaceRef<T> : IDisposable
where T : class
{
#region Constructors
public ComInterfaceRef(T? reference)
{
this.Ref = reference;
}
#endregion
#region Public Properties
public T? Ref { get; private set; }
#endregion
#region IDisposable Members
public void Dispose()
{
if (this.Ref != null)
{
Marshal.ReleaseComObject(this.Ref);
this.Ref = null;
}
}
#endregion
}
#endregion
}
}