-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCaptureManager.cs
More file actions
490 lines (402 loc) · 14.9 KB
/
CaptureManager.cs
File metadata and controls
490 lines (402 loc) · 14.9 KB
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
using EnvDTE;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Imaging.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using System;
using System.Diagnostics;
using System.IO;
using System.Timers;
using VSLangProj;
// Known monikers preview: http://glyphlist.azurewebsites.net/knownmonikers/
namespace ConsoleCompare
{
/// <summary>
/// Manages the capture and comparison of a console project process and a simile file
/// </summary>
internal class CaptureManager //: IVsSolutionEvents // <-- Only necessary if we're registering solution/project events
{
// Constants for capture output and options
private const int ProcessTimeoutSeconds = 5;
private const string ProcessTimeoutMessage = "Process taking a while; probable input/output mismatch or infinite loop";
private const string StatusProcessStoppedByUser = "Comparison stopped early by user";
private const string TextProcessStoppedByUser = "Process stopped by user";
private readonly ImageMoniker IconProcessStoppedByUser = KnownMonikers.StatusStopped;
// Visual studio-level stuff
private DTE dte;
private ResultsWindow window;
//private uint solutionEventsCookie; // <-- Needed if registering for events
// Process stuff
private ConsoleSimile simile;
private System.Diagnostics.Process proc;
private System.Threading.Thread procThread;
private bool killThread; // Not the safest, but should work for our purpose of ending a thread
private System.Timers.Timer processTimeoutTimer;
/// <summary>
/// Creates a capture manager for capturing and comparing console output
/// </summary>
/// <param name="window">The window that the capture uses</param>
public CaptureManager(ResultsWindow window)
{
ThreadHelper.ThrowIfNotOnUIThread();
this.window = window;
dte = Package.GetGlobalService(typeof(DTE)) as DTE;
// Set up the timer for process timeout
processTimeoutTimer = new System.Timers.Timer(ProcessTimeoutSeconds * 1000);
processTimeoutTimer.Elapsed += ProcessTimeoutTimer_Elapsed;
// For reference: Use this to hook up solution-related events (like opening, closing, etc.)
//IVsSolution solution = ServiceProvider.GlobalProvider.GetService(typeof(SVsSolution)) as IVsSolution;
//solution?.AdviseSolutionEvents(this, out solutionEventsCookie);
}
/// <summary>
/// Begins a capture of the current project's output
/// </summary>
public void BeginCapture(ConsoleSimile simile)
{
ThreadHelper.ThrowIfNotOnUIThread();
// Verify we can actually capture
if (!VerifyValidProject())
return;
// Turn off the capture button to prevent a second simultaneous run
window.CaptureButtonEnabled = false;
window.StopButtonEnabled = true;
window.OpenButtonEnabled = false;
// Overwrite the current simile for comparison
this.simile = simile;
if (this.simile == null)
throw new ArgumentNullException("Simile cannot be null for a capture");
// Is the process alive and in progress?
if (proc != null && !proc.HasExited)
{
// Kill it to start fresh
proc.Kill();
proc.Dispose();
}
// Rebuild solution (wait for it to finish)
window.SetStatus("Building application", KnownMonikers.BuildSolution);
dte.Solution.SolutionBuild.Build(true);
// Grab the exe path and verify
string exePath = FindPathToExecutable();
if (!File.Exists(exePath))
{
window.SetStatus(
"Cannot run output comparison; compiled executable not found: " + exePath,
KnownMonikers.StatusError);
window.CaptureButtonEnabled = true;
window.StopButtonEnabled = false;
window.OpenButtonEnabled = true;
return;
}
// Reset
window.ClearAllOutputText();
// Create the process
proc = new System.Diagnostics.Process();
// Set up start info and redirects
proc.StartInfo.FileName = exePath;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.WorkingDirectory = Path.GetDirectoryName(exePath);
// Handle IO in a synchronous manner, but on another thread
// This function will start the process
killThread = false;
procThread = new System.Threading.Thread(
() => ManualIO()
);
procThread.Start();
window.SetStatus("Application started", KnownMonikers.StatusRunning);
window.BeginRunStatusAnimation();
}
/// <summary>
/// Manually processes the input/output of the console process and compares
/// it against the console simile.
/// </summary>
private void ManualIO()
{
// Start the process here so we don't have to wait for the thread to start up
// Note: Do NOT block the process here using WaitForExit(), as that
// will cause problems with the threaded nature of the UI system
proc.Start();
// Start the timer
processTimeoutTimer.Start();
// Track the previous line's ending to know if the next has to append
LineEndingType previousLineEnding = LineEndingType.NewLine;
// Track the match count as we go so we can report after
int lineCount = 0;
int matchCount = 0;
// Loop thorugh all simile lines and check against the process's output
for (int i = 0; i < simile.Count && !killThread; i++)
{
// Will we be appending this line?
bool append = previousLineEnding == LineEndingType.SameLine;
if (!append)
lineCount++;
// Grab the current line and check the type
SimileLine line = simile[i];
switch (line)
{
// Line is output from the console process
case SimileLineOutput output:
// Create the actual text based on line ending
string actual = null;
switch (output.LineEnding)
{
// New line, so just perform a standard ReadLine()
case LineEndingType.NewLine: actual = proc.StandardOutput.ReadLine(); break;
// Output expects the next line (probably input) to be on the same line,
// so we can't rely on ReadLine() for this. Need to manually grab characters.
case LineEndingType.SameLine:
actual = "";
int charCount = 0;
while(
output.RawText != actual &&
!proc.StandardOutput.EndOfStream &&
proc.StandardOutput.Peek() != -1
)
{
actual += (char)proc.StandardOutput.Read();
charCount++;
}
// TODO: Handle the case when we run out of characters before the end!
break;
}
// Do they match?
bool match = output.CompareLine(actual);
string expectedReport = match ? actual : output.RawText; // What text to report to the user?
if (match)
matchCount++;
// Swap to the UI thread to update
ThreadHelper.JoinableTaskFactory.Run(async delegate
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
// Add the text to both boxes
if (!killThread)
{
window.AddTextOutput(actual, ResultsTextType.Output, append, match);
window.AddTextExpected(expectedReport, ResultsTextType.Output, append, match);
}
});
// Save the previous ending
previousLineEnding = output.LineEnding;
break;
// Line is input from the user
case SimileLineInput input:
// Grab the data to send to the process, do so and put in both boxes
proc.StandardInput.WriteLine(input.Text);
// Swap to the UI thread to update
ThreadHelper.JoinableTaskFactory.Run(async delegate
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
// Add the text to both boxes (assuming a match since we're providing the input)
if (!killThread)
{
window.AddTextOutput(input.Text, ResultsTextType.Input, append, true);
window.AddTextExpected(input.Text, ResultsTextType.Input, append, true);
}
});
// Previous line ending is now a new line since we're simulating the user pressing enter
previousLineEnding = LineEndingType.NewLine;
// Assume input lines always match since we do those ourselves,
// though only if we're not appending to another line
if (!append)
matchCount++;
break;
}
// Kill the thread early?
if (killThread)
break;
}
// Once we're out of the loop, kill the timer
processTimeoutTimer.Stop();
// Swap to the UI thread to update
ThreadHelper.JoinableTaskFactory.Run(async delegate
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
// All done, re-enable the button and update the status bar
window.CaptureButtonEnabled = true;
window.StopButtonEnabled = false;
window.OpenButtonEnabled = true;
window.EndRunStatusAnimation();
if (killThread)
{
window.SetStatus(StatusProcessStoppedByUser, IconProcessStoppedByUser);
window.AddTextOutput(TextProcessStoppedByUser, ResultsTextType.Output, false, false);
window.AddTextExpected(TextProcessStoppedByUser, ResultsTextType.Output, false, false);
}
else
{
window.SetStatus(
$"Comparison finished - {matchCount}/{lineCount} lines match",
matchCount == lineCount ? KnownMonikers.StatusOK : KnownMonikers.StatusError);
}
});
killThread = false;
}
/// <summary>
/// Handles the timer that denotes a process has potentially taken too long
/// </summary>
public void ProcessTimeoutTimer_Elapsed(object source, ElapsedEventArgs e)
{
processTimeoutTimer.Stop();
// Swap to the UI thread to update
ThreadHelper.JoinableTaskFactory.Run(async delegate
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
// The process has been running for a while, so notify the user and disable the timer
window.SetStatusNoIconChange(ProcessTimeoutMessage);
});
}
/// <summary>
/// Stops a capture in progress, if one exists
/// </summary>
public bool StopCapture()
{
// Is there a thread going at all?
if (procThread == null || !procThread.IsAlive)
return false;
// Attempt to kill the process and the ManualIO thread
proc.Kill();
killThread = true;
return true;
}
/// <summary>
/// Helper for finding the path to the first currently loaded project's built executable
/// </summary>
/// <returns>Full path to the executable of the (first) current project</returns>
public string FindPathToExecutable()
{
ThreadHelper.ThrowIfNotOnUIThread();
// Find the first project and verify
Project firstProject = GetFirstProject();
if (firstProject == null)
return null;
// Path creation
// From: https://social.msdn.microsoft.com/Forums/vstudio/en-US/03d9d23f-e633-4a27-9b77-9029735cfa8d/how-to-get-the-right-8220output-path8221-from-envdteproject-by-code-if-8220show-advanced?forum=vsx
string fullPath = firstProject.Properties.Item("FullPath").Value.ToString();
string outputPath = firstProject.ConfigurationManager.ActiveConfiguration.Properties.Item("OutputPath").Value.ToString();
string filename = firstProject.Properties.Item("OutputFileName").Value.ToString();
string exePath = Path.Combine(fullPath, outputPath, filename);
// Quick check to verify that we're not looking at an assembly
if (exePath.EndsWith(".dll"))
exePath = exePath.Replace(".dll", ".exe");
return exePath;
}
/// <summary>
/// Helper for finding the path to the first project's folder
/// </summary>
/// <returns>The path to the first project's folder</returns>
public string FindPathToProjectFolder()
{
ThreadHelper.ThrowIfNotOnUIThread();
// Find the first project and verify
Project firstProject = GetFirstProject();
if (firstProject == null)
return null;
return firstProject.Properties.Item("FullPath").Value.ToString();
}
/// <summary>
/// Verifies that we have everything we need (a solution and
/// a console project) to proceed.
/// </summary>
/// <returns></returns>
private bool VerifyValidProject()
{
ThreadHelper.ThrowIfNotOnUIThread();
// Is there a solution?
if (dte.Solution == null)
{
window.SetStatus("No solution loaded; please load a solution with a console application.", KnownMonikers.StatusError);
return false;
}
// Is there a project?
if (dte.Solution.Projects.Count == 0)
{
window.SetStatus("No projects loaded; please load a console application project.", KnownMonikers.StatusError);
return false;
}
// Is it the right type of project?
Project firstProject = GetFirstProject();
Property outputType = firstProject.Properties.Item("OutputType");
prjOutputType projectType = (prjOutputType)outputType.Value;
if (projectType != prjOutputType.prjOutputTypeExe)
{
window.SetStatus(
"First project in solution is not a standard console application; please load a console application project.",
KnownMonikers.StatusError);
return false;
}
// Valid project
return true;
}
/// <summary>
/// Gets the first project in the current solution
/// </summary>
/// <returns>The first project, or null if no project/solution exist</returns>
private Project GetFirstProject()
{
ThreadHelper.ThrowIfNotOnUIThread();
// Verify a solution
if (dte.Solution == null)
return null;
// Find the first project using a foreach loop, as using
// the .Item(0) indexing was problematic. Seems like the first
// project is index 1, which either means the overall indexing is
// 1-based (weird) or there is some other object sitting at index 0
foreach (Project p in dte.Solution.Projects)
{
// Dirty, but relying on enumeration due to issues with .Item()
return p;
}
// No projects
return null;
}
#region Unused - Necessary for solution events
//public int OnAfterOpenProject(IVsHierarchy pHierarchy, int fAdded)
//{
// MessageBox("AFTER OPEN PROJECT");
// return VSConstants.S_OK;
//}
//public int OnQueryCloseProject(IVsHierarchy pHierarchy, int fRemoving, ref int pfCancel)
//{
// return VSConstants.S_OK;
//}
//public int OnBeforeCloseProject(IVsHierarchy pHierarchy, int fRemoved)
//{
// return VSConstants.S_OK;
//}
//public int OnAfterLoadProject(IVsHierarchy pStubHierarchy, IVsHierarchy pRealHierarchy)
//{
// MessageBox("AFTER LOAD PROJECT");
// return VSConstants.S_OK;
//}
//public int OnQueryUnloadProject(IVsHierarchy pRealHierarchy, ref int pfCancel)
//{
// return VSConstants.S_OK;
//}
//public int OnBeforeUnloadProject(IVsHierarchy pRealHierarchy, IVsHierarchy pStubHierarchy)
//{
// return VSConstants.S_OK;
//}
//public int OnAfterOpenSolution(object pUnkReserved, int fNewSolution)
//{
// MessageBox("AFTER OPEN SOLUTION");
// return VSConstants.S_OK;
//}
//public int OnQueryCloseSolution(object pUnkReserved, ref int pfCancel)
//{
// return VSConstants.S_OK;
//}
//public int OnBeforeCloseSolution(object pUnkReserved)
//{
// return VSConstants.S_OK;
//}
//public int OnAfterCloseSolution(object pUnkReserved)
//{
// return VSConstants.S_OK;
//}
#endregion
}
}