-
Notifications
You must be signed in to change notification settings - Fork 772
Expand file tree
/
Copy pathEventWindow.xaml.cs
More file actions
2166 lines (1956 loc) · 86.4 KB
/
Copy pathEventWindow.xaml.cs
File metadata and controls
2166 lines (1956 loc) · 86.4 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
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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Diagnostics.Tracing.StackSources;
using EventSources;
using Microsoft.Diagnostics.Symbols;
using Microsoft.Diagnostics.Tracing;
using Microsoft.Diagnostics.Tracing.Etlx;
using Microsoft.Diagnostics.Tracing.Stacks;
using Microsoft.Diagnostics.Tracing.TraceUtilities.FilterQueryExpression;
using Microsoft.Diagnostics.Utilities;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using Utilities;
namespace PerfView
{
/// <summary>
/// Interaction logic for SelectProcess.xaml
/// </summary>
public partial class EventWindow : WindowBase
{
public static bool TruncateRawEventData = true;
public EventWindow(Window parent, EventSource source) : base(parent)
{
throw new NotImplementedException();
}
public EventWindow(EventWindow template)
: this(template.ParentWindow, template.DataSource)
{
TextFilterTextBox.Text = template.TextFilterTextBox.Text;
StartTextBox.CopyFrom(template.StartTextBox);
StartTextBox.Text = template.StartTextBox.Text;
EndTextBox.CopyFrom(template.EndTextBox);
EndTextBox.Text = template.EndTextBox.Text;
MaxRetTextBox.CopyFrom(template.MaxRetTextBox);
MaxRetTextBox.Text = template.MaxRetTextBox.Text;
ProcessFilterTextBox.CopyFrom(template.ProcessFilterTextBox);
ProcessFilterTextBox.Text = template.ProcessFilterTextBox.Text;
EventTypeFilterTextBox.Text = template.EventTypeFilterTextBox.Text;
FindTextBox.CopyFrom(template.FindTextBox);
FindTextBox.Text = template.FindTextBox.Text;
EventTypeFilterTextBox.Text = template.EventTypeFilterTextBox.Text;
var selection = EventTypes.SelectedItems;
selection.Clear();
foreach (var item in template.EventTypes.SelectedItems)
{
selection.Add(item);
}
// Copy timestamp column visibility settings from template
ShowTimeStampColumnsMenuItem.IsChecked = template.ShowTimeStampColumnsMenuItem.IsChecked;
ShowLocalTimeMenuItem.IsChecked = template.ShowLocalTimeMenuItem.IsChecked;
ShowLocalTimeMenuItem.IsEnabled = template.ShowLocalTimeMenuItem.IsEnabled;
Update();
}
public EventWindow(Window parent, PerfViewEventSource data)
{
DataSource = data;
ParentWindow = parent;
InitializeComponent();
Title = DataSource.Title;
Grid.CopyingRowClipboardContent += delegate (object sender, DataGridRowClipboardEventArgs e)
{
for (int i = 0; i < e.ClipboardRowContent.Count; i++)
{
var clipboardContent = e.ClipboardRowContent[i];
string morphedContent = null;
if (e.IsColumnHeadersRow)
{
morphedContent = GetColumnHeaderText(clipboardContent.Column);
}
else
{
var cellContent = clipboardContent.Content;
if (cellContent is float)
{
morphedContent = PerfDataGrid.GoodPrecision((float)cellContent, clipboardContent.Column);
}
else if (cellContent is double)
{
morphedContent = PerfDataGrid.GoodPrecision((double)cellContent, clipboardContent.Column);
}
else if (cellContent != null)
{
morphedContent = cellContent.ToString();
}
else
{
morphedContent = "";
}
}
if (e.ClipboardRowContent.Count > 1 && i + e.StartColumnDisplayIndex != Grid.Columns.Count - 1)
{
morphedContent = PadForColumn(morphedContent, i + e.StartColumnDisplayIndex);
}
// TODO Ugly, morph two cells on different rows into one line for the correct cut/paste experience
// for ranges.
if (m_clipboardRangeEnd != m_clipboardRangeStart) // If we have just 2 things selected (and I can tell them apart)
{
if (PerfDataGrid.VeryClose(morphedContent, m_clipboardRangeStart))
{
e.ClipboardRowContent.Clear();
morphedContent = morphedContent + " " + m_clipboardRangeEnd;
e.ClipboardRowContent.Add(new DataGridClipboardCellContent(clipboardContent.Item, clipboardContent.Column, morphedContent));
return;
}
else if (PerfDataGrid.VeryClose(morphedContent, m_clipboardRangeEnd))
{
e.ClipboardRowContent.Clear();
return;
}
}
e.ClipboardRowContent[i] = new DataGridClipboardCellContent(clipboardContent.Item, clipboardContent.Column, morphedContent);
}
};
Closing += delegate (object sender, CancelEventArgs e)
{
if (StatusBar.IsWorking)
{
StatusBar.LogError("Cancel work before closing window.");
e.Cancel = true;
return;
}
DataSource.Viewer = null;
};
Loaded += delegate
{
EventTypeFilterTextBox.Focus();
};
m_source = DataSource.GetEventSource();
var processNames = m_source.ProcessNames;
if (processNames != null)
{
ProcessFilterTextBox.HistoryLength = processNames.Count + 5;
ProcessFilterTextBox.SetHistory(processNames);
}
m_userDefinedColumns = new List<DataGridColumn>();
foreach (var gridColumn in Grid.Columns)
{
if (((string)gridColumn.Header).StartsWith("Field"))
{
m_userDefinedColumns.Add(gridColumn);
}
}
EventTypes.ItemsSource = m_source.EventNames;
Grid.Sorting += delegate (object sender, DataGridSortingEventArgs e)
{
e.Handled = true;
var direction = (e.Column.SortDirection != ListSortDirection.Ascending ? ListSortDirection.Ascending : ListSortDirection.Descending);
e.Column.SortDirection = direction;
var lcv = (ListCollectionView)CollectionViewSource.GetDefaultView(Grid.ItemsSource);
lcv.CustomSort = new LogicalGridDataComparer<EventRecord>(e.Column.SortMemberPath, direction);
};
MultiLineViewPaneHidden = (App.UserConfigData["MultiLineViewPaneHidden"] == "true");
// Initialize timestamp column visibility based on user preference
bool showTimeStampColumns = App.UserConfigData["EventWindowShowTimeStampColumns"] != "false"; // Default to true
ShowTimeStampColumnsMenuItem.IsChecked = showTimeStampColumns;
if (!showTimeStampColumns)
{
// Hide both timestamp columns and disable the timezone menu
foreach (var column in Grid.Columns)
{
if (column == OriginTimeStampColumn || column == LocalTimeStampColumn)
{
column.Visibility = Visibility.Hidden;
}
}
ShowLocalTimeMenuItem.IsEnabled = false;
}
else
{
ShowLocalTimeMenuItem.IsEnabled = true;
}
}
public PerfViewEventSource DataSource { get; private set; }
public Window ParentWindow { get; private set; }
public bool UseLocalTime { get; set; } = false;
public void SaveDataToCsvFile(string csvFileName, int maxNonRestFields = int.MaxValue)
{
var savedNonRestFields = m_source.NonRestFields;
try
{
string listSeparator = Thread.CurrentThread.CurrentCulture.TextInfo.ListSeparator;
m_source.NonRestFields = Math.Min(m_source.ColumnsToDisplay == null ? 0 : m_source.ColumnsToDisplay.Count, maxNonRestFields);
using (var csvFile = File.CreateText(csvFileName))
{
// Write out column header
csvFile.Write("Event Name{0}Time MSec{0}Process Name", listSeparator);
var maxField = 0;
var hasRest = true;
if (m_source.ColumnsToDisplay != null)
{
hasRest = false;
foreach (var columnName in m_source.ColumnsToDisplay)
{
Debug.Assert(!columnName.Contains(listSeparator));
if (maxField >= m_source.NonRestFields)
{
hasRest = true;
break;
}
maxField++;
csvFile.Write("{0}{1}", listSeparator, columnName);
}
}
if (hasRest)
{
csvFile.Write("{0}Rest", listSeparator);
}
csvFile.WriteLine();
// Write out events
m_source.ForEach(delegate (EventRecord _event)
{
// We have exceeded MaxRet, skip it.
if (_event.EventName == null)
{
return false;
}
csvFile.Write("{0}{1}{2:f3}{1}{3}", _event.EventName, listSeparator, _event.TimeStampRelatveMSec, EscapeForCsv(_event.ProcessName, listSeparator));
var fields = _event.DisplayFields;
for (int i = 0; i < maxField; i++)
{
csvFile.Write("{0}{1}", listSeparator, EscapeForCsv(fields[i], listSeparator));
}
if (hasRest)
{
csvFile.Write("{0}{1}", listSeparator, EscapeForCsv(_event.Rest, listSeparator));
}
csvFile.WriteLine();
return true;
});
}
}
finally
{
m_source.NonRestFields = savedNonRestFields;
}
}
public bool MultiLineViewPaneHidden
{
get { return m_MultiLineViewPaneHidden; }
set
{
if (value == m_MultiLineViewPaneHidden)
{
return;
}
if (value)
{
App.UserConfigData["MultiLineViewPaneHidden"] = "true";
m_MultiLineViewPaneHidden = true;
MultiLineViewPaneRowDef.MaxHeight = 0;
}
else
{
App.UserConfigData["MultiLineViewPaneHidden"] = "false";
m_MultiLineViewPaneHidden = false;
MultiLineViewPaneRowDef.MaxHeight = Double.PositiveInfinity;
}
}
}
private bool m_MultiLineViewPaneHidden;
public void SaveDataToXmlFile(string xmlFileName)
{
// Sadly, streamWriter does not have a way of setting the IFormatProvider property
// So we have to do it in this ugly, global variable way.
var savedCulture = Thread.CurrentThread.CurrentCulture;
try
{
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var xmlExcapesExceptQuote = new char[] { '<', '>', '\'', '&' };
using (var xmlFile = File.CreateText(xmlFileName))
{
// Write out column header
xmlFile.WriteLine("<Events>");
m_source.ForEach(delegate (EventRecord _event)
{
// We have exceeded MaxRet, skip it.
if (_event.EventName == null)
{
return false;
}
xmlFile.Write(" <Event EventName=\"{0}\" TimeMsec=\"{1:f3}\" ProcessName=\"{2}\"",
_event.EventName, _event.TimeStampRelatveMSec, XmlUtilities.XmlEscape(_event.ProcessName));
bool displayRest = true;
if (m_source.ColumnsToDisplay != null)
{
displayRest = m_source.ColumnsToDisplay.Count > m_source.NonRestFields;
var limit = Math.Min(m_source.ColumnsToDisplay.Count, m_source.NonRestFields);
for (int i = 0; i < limit; i++)
{
var columnName = m_source.ColumnsToDisplay[i];
xmlFile.Write("{0}=\"{1}\"", columnName, XmlUtilities.XmlEscape(_event.DisplayFields[i]));
}
}
if (displayRest)
{
var rest = _event.Rest;
if (rest.Contains("\\\"") || rest.IndexOfAny(xmlExcapesExceptQuote) >= 0)
{
// Rest contains name="XXXX" and we have determined that the XXX has either
// XML special characters or quoted quotes e.g. \"
// So we need to transform this to legal XML data.
// TODO painfully slow, fragile, trickly
rest = XmlUtilities.XmlEscape(_event.Rest); // First escape all XML special chars (including quotes)
rest = rest.Replace(""", "\""); // Put back all the quotes
rest = Regex.Replace(rest, "\\\\(\\\\*)\"", "$1"e;"); // But escape the escaped quotes.
}
xmlFile.Write(" ");
xmlFile.Write(rest);
}
xmlFile.WriteLine("/>");
return true;
});
xmlFile.WriteLine("</Events>");
}
}
finally
{
Thread.CurrentThread.CurrentCulture = savedCulture;
}
}
private void DoHyperlinkHelp(object sender, ExecutedRoutedEventArgs e)
{
var param = e.Parameter as string;
if (param == null)
{
param = "EventViewerQuickStart"; // This is the F1 help
}
StatusBar.Log("Displaying Users Guide in Web Browser.");
MainWindow.DisplayUsersGuide(param);
}
private void DoClose(object sender, RoutedEventArgs e)
{
Close();
}
private void DoOpenParent(object sender, RoutedEventArgs e)
{
for (; ; )
{
try
{
if (ParentWindow != null)
{
ParentWindow.Visibility = System.Windows.Visibility.Visible;
ParentWindow.Focus();
}
return;
}
catch (InvalidOperationException)
{
// This means the window was closed, fix our parent to skip it.
var asStackWindow = ParentWindow as PerfView.StackWindow;
if (asStackWindow != null)
{
ParentWindow = asStackWindow.ParentWindow;
continue;
}
var asEventWindow = ParentWindow as EventWindow;
if (asEventWindow != null)
{
ParentWindow = asEventWindow.ParentWindow;
continue;
}
break;
}
}
}
internal void DoUpdate(object sender, RoutedEventArgs e)
{
Update();
}
private void DoFind(object sender, RoutedEventArgs e)
{
FindTextBox.Focus();
}
private void DoFindEnter(object sender, RoutedEventArgs e)
{
Find(null);
DoFindNext(sender, e);
}
private void DoFindNext(object sender, RoutedEventArgs e)
{
StatusBar.Status = "";
bool ret = Find(FindTextBox.Text);
if (!ret)
{
StatusBar.LogError("Could not find " + FindTextBox.Text + ".");
}
}
private void DoOpenCpuStacks(object sender, ExecutedRoutedEventArgs e)
{
OpenStacks(null);
}
private void DoOpenAnyStacks(object sender, ExecutedRoutedEventArgs e)
{
OpenStacks("Any");
}
private void DoOpenAnyStartStopStacks(object sender, ExecutedRoutedEventArgs e)
{
OpenStacks("Any Stacks (with StartStop Activities)");
}
private void DoOpenAnyTaskTreeStacks(object sender, ExecutedRoutedEventArgs e)
{
OpenStacks("Any TaskTree");
}
private void DoOpenThreadStacks(object sender, ExecutedRoutedEventArgs e)
{
OpenStacks("Thread Time (with Tasks)");
}
private void OpenStacks(string stackSourceName)
{
// TODO this could be confusing as we have filtered out everything before a range and can't get it back.
if (DataSource != null)
{
// If we have selected exactly two items, use that as the time limits, otherwise use what is the my dialog.
var startTimeRelativeMSec = m_source.StartTimeRelativeMSec;
var endTimeRelativeMSec = m_source.EndTimeRelativeMSec;
var selectedCells = Grid.SelectedCells;
if (selectedCells.Count == 2)
{
string start = GetCellStringValue(selectedCells[0]);
double parsedStart;
if (!double.TryParse(start, out parsedStart))
{
StatusBar.LogError("Could not parse " + start + " as a number.");
OpenSelectedStacks(stackSourceName, selectedCells);
return;
}
startTimeRelativeMSec = parsedStart;
string end = this.GetCellStringValue(selectedCells[1]);
if (!double.TryParse(end, out endTimeRelativeMSec))
{
this.StatusBar.LogError("Could not parse " + end + " as a number.");
this.OpenSelectedStacks(stackSourceName, selectedCells);
return;
}
// Make sure that start < end
if (endTimeRelativeMSec < startTimeRelativeMSec)
{
var tmp = startTimeRelativeMSec;
startTimeRelativeMSec = endTimeRelativeMSec;
endTimeRelativeMSec = tmp;
}
}
else if (selectedCells.Count != 2)
{
OpenSelectedStacks(stackSourceName, selectedCells);
return;
}
// TODO FIX NOW: this should call a routine that does the opening of the stack view
// (m_lookedUpCachedSymbolsForETLData should not be needed ...)
StatusBar.StartWork("Reading " + DataSource.Name, delegate ()
{
// This is where the work gets done.
PerfViewStackSource dataSource = null;
var dataFile = DataSource.DataFile;
if (dataFile != null)
{
if (stackSourceName == null)
{
stackSourceName = dataFile.DefaultStackSourceName;
}
dataSource = dataFile.GetStackSource(stackSourceName);
}
if (dataSource == null)
{
throw new ApplicationException("Could not find stack source " + stackSourceName);
}
var stackSource = dataSource.GetStackSource(StatusBar.LogWriter, startTimeRelativeMSec - .001, endTimeRelativeMSec + .001);
if (!m_lookedUpCachedSymbolsForETLData)
{
// Lookup all the symbols you can from the cache.
m_lookedUpCachedSymbolsForETLData = true;
StatusBar.Log("Quick Looking up symbols from PDB cache.");
var etlDataFile = dataFile as ETLPerfViewData;
if (etlDataFile != null)
{
var traceLog = etlDataFile.GetTraceLog(StatusBar.LogWriter);
using (var reader = etlDataFile.GetSymbolReader(StatusBar.LogWriter,
SymbolReaderOptions.CacheOnly | SymbolReaderOptions.NoNGenSymbolCreation))
{
// TODO FIX NOW, make this so that it uses the stacks in the view.
var moduleFiles = ETLPerfViewData.GetInterestingModuleFiles(etlDataFile, 5.0, StatusBar.LogWriter, null);
foreach (var moduleFile in moduleFiles)
{
traceLog.CodeAddresses.LookupSymbolsForModule(reader, moduleFile);
}
}
}
StatusBar.Log("Quick Done looking up symbols from PDB cache.");
}
StatusBar.EndWork(delegate ()
{
App.CommandProcessor.NoExitOnElevate = true; // Don't exit because we might have state
var stackWindow = new PerfView.StackWindow(this, dataSource);
stackWindow.StatusBar.Log("Read " + DataSource.Name);
dataSource.ConfigureStackWindow(stackWindow);
stackWindow.StartTextBox.Text = startTimeRelativeMSec.ToString();
stackWindow.EndTextBox.Text = endTimeRelativeMSec.ToString();
stackWindow.Show();
stackWindow.SetStackSource(stackSource);
});
});
}
}
private void OpenSelectedStacks(string stackSourceName, IList<DataGridCellInfo> selectedCells)
{
if (selectedCells == null || selectedCells.Count == 0)
{
StatusBar.LogError("No events selected.");
return;
}
StatusBar.StartWork("Reading " + DataSource.Name, delegate ()
{
PerfViewStackSource dataSource = null;
var dataFile = DataSource.DataFile;
if (dataFile != null)
{
if (stackSourceName == null)
{
stackSourceName = dataFile.DefaultStackSourceName;
}
dataSource = dataFile.GetStackSource(stackSourceName);
}
if (dataSource == null)
{
throw new ApplicationException("Could not find stack source " + stackSourceName);
}
// Collect unique event records (a row may have multiple selected cells).
var uniqueRecords = selectedCells
.Select(c => c.Item as EventRecord)
.Where(r => r != null)
.Distinct()
.ToList();
if (uniqueRecords.Count == 0)
{
StatusBar.EndWork(delegate ()
{
StatusBar.LogError("No event records found in selection.");
});
return;
}
StackSource aggregateSource;
// For ETW sources, filter by exact EventIndex so concurrent events on other
// threads at the same timestamp are excluded.
var etwRecords = uniqueRecords.OfType<ETWEventSource.ETWEventRecord>().ToList();
var startTimeRelativeMSec = etwRecords.Min(r => r.TimeStampRelatveMSec);
var endTimeRelativeMSec = etwRecords.Max(r => r.TimeStampRelatveMSec);
if (etwRecords.Count == uniqueRecords.Count)
{
var selectedIndices = new HashSet<EventIndex>(etwRecords.Select(r => r.Index));
aggregateSource = dataSource.GetStackSource(
StatusBar.LogWriter,
startTimeRelativeMSec - .001,
endTimeRelativeMSec + .001,
data => selectedIndices.Contains(data.EventIndex));
}
else
{
// Fall back to per-event time windows for non-ETW sources.
var sources = new List<StackSource>();
foreach (var record in uniqueRecords)
{
sources.Add(dataSource.GetStackSource(
StatusBar.LogWriter,
record.TimeStampRelatveMSec - .001,
record.TimeStampRelatveMSec + .001));
}
aggregateSource = InternStackSource.Merge(sources);
}
if (aggregateSource == null)
{
StatusBar.EndWork(delegate ()
{
StatusBar.LogError("Could not open stacks for selected events.");
});
return;
}
if (!m_lookedUpCachedSymbolsForETLData)
{
m_lookedUpCachedSymbolsForETLData = true;
StatusBar.Log("Quick Looking up symbols from PDB cache.");
var etlDataFile = dataFile as ETLPerfViewData;
if (etlDataFile != null)
{
var traceLog = etlDataFile.GetTraceLog(StatusBar.LogWriter);
using (var reader = etlDataFile.GetSymbolReader(StatusBar.LogWriter,
SymbolReaderOptions.CacheOnly | SymbolReaderOptions.NoNGenSymbolCreation))
{
var moduleFiles = ETLPerfViewData.GetInterestingModuleFiles(etlDataFile, 5.0, StatusBar.LogWriter, null);
foreach (var moduleFile in moduleFiles)
{
traceLog.CodeAddresses.LookupSymbolsForModule(reader, moduleFile);
}
}
}
StatusBar.Log("Quick Done looking up symbols from PDB cache.");
}
StatusBar.EndWork(delegate ()
{
App.CommandProcessor.NoExitOnElevate = true;
var stackWindow = new PerfView.StackWindow(this, dataSource);
stackWindow.StatusBar.Log("Read " + DataSource.Name);
dataSource.ConfigureStackWindow(stackWindow);
stackWindow.StartTextBox.Text = startTimeRelativeMSec.ToString();
stackWindow.EndTextBox.Text = endTimeRelativeMSec.ToString();
stackWindow.Show();
stackWindow.SetStackSource(aggregateSource);
});
});
}
private void DoProcessFilter(object sender, ExecutedRoutedEventArgs e)
{
var selectedCells = Grid.SelectedCells;
if (selectedCells.Count != 1)
{
throw new ApplicationException("No cells selected.");
}
ProcessFilterTextBox.Text = GetCellStringValue(selectedCells[0]);
Update();
}
private void DoShowEventCounterGraph(object sender, ExecutedRoutedEventArgs e)
{
if (EventTypes.SelectedItems.Count != 1)
{
return;
}
if (!((string)EventTypes.SelectedItems[0]).EndsWith("/EventCounters"))
{
return;
}
Update();
string templatePath = Path.Combine(SupportFiles.SupportFileDir, "EventCounterVisualization.html");
string template = File.ReadAllText(templatePath);
var counters = BuildCounters(m_source);
var firstCounter = true;
var sb = new StringBuilder();
sb.Append("var data = [");
foreach (var counter in counters)
{
if (firstCounter)
{
firstCounter = false;
}
else
{
sb.Append(",");
}
sb.Append("{");
sb.Append(@"name:""");
sb.Append(counter.Key);
sb.Append(@""", points:[");
var firstPoint = true;
foreach (var point in counter.Value)
{
if (firstPoint)
{
firstPoint = false;
}
else
{
sb.Append(",");
}
sb.Append("{ X:");
sb.Append(point.Item1.ToString(CultureInfo.InvariantCulture));
sb.Append(", Y:");
sb.Append(point.Item2.ToString(CultureInfo.InvariantCulture));
sb.Append("}");
}
sb.Append("]}");
}
sb.Append("];");
string html = Path.GetTempFileName() + ".html";
File.WriteAllText(html, template.Replace("// REPLACE-DATA-HERE", sb.ToString()));
string uri = "file:///" + html.Replace('\\', '/').Replace(" ", "%20");
Process.Start(uri);
}
private const string PayloadToken = "Payload=\"{";
private const string PayloadTokenNetCore = "Payload\":{";
private const string NameToken = "Name\":";
private const string DisplayNameToken = "DisplayName\":";
private const string MeanToken = "Mean\":";
private const string IncrementToken = "Increment\":";
private const string IntervalToken = "IntervalSec\":";
private Dictionary<string, List<Tuple<double, double>>> BuildCounters(EventSource source)
{
// look for events from "EventCounters"
// i.e. within Payload={...}, need to find Name, DisplayName and IntervalSec fields
// however, two counter types exist:
// - Mean: Min, Max, Mean fields
// - Sum: Increment field with the delta of the values between the last fetch and the current one
//
double t = 0;
var counters = new Dictionary<string, List<Tuple<double, double>>>();
source.ForEach(delegate (EventRecord event_)
{
string rest = event_.Rest;
if (rest == null)
{
return false;
}
// ensure that a payload is available
var pos = rest.IndexOf(PayloadToken);
if (pos == -1)
{
pos = rest.IndexOf(PayloadTokenNetCore);
if (pos == -1)
{
return false;
}
else
{
pos += PayloadTokenNetCore.Length;
}
}
else
{
pos += PayloadToken.Length;
}
// get Name and DisplayName fields value
// i.e. use display name if available (.NET Core) or name otherwise
string name = GetStringField(rest, NameToken, ref pos);
if (name == null)
return false;
string displayName = GetStringField(rest, DisplayNameToken, ref pos);
if (displayName == null)
displayName = name;
// check for Mean or Sum type of counter value
var value = GetNumericField(rest, IncrementToken, ref pos);
if (value == null)
{
value = GetNumericField(rest, MeanToken, ref pos);
if (value == null)
return false;
}
var interval = GetNumericField(rest, IntervalToken, ref pos);
if (interval == null)
return false;
string namePart = displayName;
string meanPart = value;
string intervalSecPart = interval;
double mean;
double intervalSec;
if (!double.TryParse(meanPart, out mean))
{
return false;
}
if (!double.TryParse(intervalSecPart, out intervalSec))
{
return false;
}
if (!counters.TryGetValue(namePart, out var points))
{
points = new List<Tuple<double, double>>();
counters.Add(namePart, points);
}
points.Add(Tuple.Create(t, mean));
t += intervalSec;
return true;
});
return counters;
}
private string GetStringField(string payload, string token, ref int pos)
{
var next = pos;
// a string field is stored in the payload as:
// <token>"<value>"
// note that <token> has the following format: <field>=
//
next = payload.IndexOf(token, next);
if (next == -1)
return null;
next += token.Length;
if (payload[next] != '"')
return null;
// skip the " at the beginning of the field value
next++;
var end = payload.IndexOf('"', next);
if (end == -1)
return null;
var length = end - next;
pos = end;
return payload.Substring(next, length);
}
private string GetNumericField(string payload, string field, ref int pos)
{
var next = pos;
// a numeric field is stored in the payload as:
// <token><value>
// note that <token> has the following format: <field>:
//
next = payload.IndexOf(field, next);
if (next == -1)
return null;
next += field.Length;
var end = payload.IndexOf(',', next);
// handle the case of the last numeric value of the payload
// i.e. look for " }" instead of ","
if (end == -1)
{
end = payload.IndexOf(" }", next);
if (end == -1)
return null;
}
var length = end - next;
pos = next;
return payload.Substring(next, length);
}
private void DoRangeFilter(object sender, ExecutedRoutedEventArgs e)
{
if (Histogram.IsFocused)
{
var start = Histogram.SelectionStart;
var end = Histogram.SelectionLength + start;
if (start < 0 || end == start)
{
StatusBar.LogError("No selection in the Histogram was made.");
return;
}
StartTextBox.Text = (m_bucketTimeMSec * start + m_source.StartTimeRelativeMSec).ToString("n3");
EndTextBox.Text = (m_bucketTimeMSec * end + m_source.StartTimeRelativeMSec).ToString("n3");
Update();
return;
}
var selectedCells = Grid.SelectedCells;
if (selectedCells.Count != 2)
{
StatusBar.LogError("You must select two cells to set the range.");
return;
}
StartTextBox.Text = GetCellStringValue(selectedCells[0]);
EndTextBox.Text = GetCellStringValue(selectedCells[1]);
Update();
}
private void DoEventTypesKey(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
DoUpdate(sender, e);
}
}
private void DoCancel(object sender, ExecutedRoutedEventArgs e)
{
StatusBar.AbortWork();
}
private void DoNewWindow(object sender, ExecutedRoutedEventArgs e)
{
var newEventViewer = new EventWindow(this);
newEventViewer.Show();
Update();
}
private void DoToggleMultiLineViewPane(object sender, ExecutedRoutedEventArgs e)
{
MultiLineViewPaneHidden = !MultiLineViewPaneHidden;
}
private void DoColumnsToDisplayListClick(object sender, RoutedEventArgs e)
{
if (EventTypes.SelectedItems.Count == 0)
{
StatusBar.LogError("No event types selected.");
return;
}
var eventFilter = new List<string>(EventTypes.SelectedItems.Count);
foreach (var item in EventTypes.SelectedItems)
{
eventFilter.Add((string)item);
}
var columns = m_source.AllColumnNames(eventFilter);
if (columns == null)
{
StatusBar.LogError("This EventSource does not support column names.");
return;
}
var columnsWithWildCard = new List<string>(columns);
columnsWithWildCard.Add("*");
ColumnsToDisplayListBox.ItemsSource = columnsWithWildCard;
ColumnsToDisplayPopup.IsOpen = true;
}
private void DoColumnsToDisplayListBoxKey(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter || e.Key == Key.Return)
{
UpdateColumnsToDisplay();
DoUpdate(sender, e);
}
else if (e.Key == Key.Tab)
{
UpdateColumnsToDisplay();
}
else if (e.Key == Key.Escape)
{
ColumnsToDisplayPopup.IsOpen = false;
}
}
private void DoColumnsToDisplayListBoxDoubleClick(object sender, MouseButtonEventArgs e)
{
UpdateColumnsToDisplay();
DoUpdate(sender, e);