-
Notifications
You must be signed in to change notification settings - Fork 143
/
MainFrame.cpp
1664 lines (1441 loc) · 47.9 KB
/
MainFrame.cpp
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
// (C) Copyright Gert-Jan de Vos and Jan Wilmans 2013.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// Repository at: https://github.com/djeedjay/DebugViewPP/
#include "stdafx.h"
#include <algorithm>
#include <filesystem>
#include <boost/algorithm/string.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include "CobaltFusion/AtlWinExt.h"
#include "CobaltFusion/scope_guard.h"
#include "CobaltFusion/stringbuilder.h"
#include "CobaltFusion/dbgstream.h"
#include "CobaltFusion/hstream.h"
#include "CobaltFusion/Math.h"
#include "CobaltFusion/GuiExecutor.h"
#include "CobaltFusion/fusionassert.h"
#include "Win32/Registry.h"
#include "DebugView++Lib/ProcessReader.h"
#include "DebugView++Lib/DbgviewReader.h"
#include "DebugView++Lib/SocketReader.h"
#include "DebugView++Lib/FileReader.h"
#include "DebugView++Lib/FileIO.h"
#include "DebugView++Lib/LogFilter.h"
#include "resource.h"
#include "RunDlg.h"
#include "HistoryDlg.h"
#include "FilterDlg.h"
#include "SourcesDlg.h"
#include "AboutDlg.h"
#include "FileOptionDlg.h"
#include "LogView.h"
#include "MainFrame.h"
#include <iostream>
namespace fusion {
namespace debugviewpp {
using namespace std::chrono_literals;
std::wstring GetPersonalPath()
{
std::wstring path;
wchar_t szPath[MAX_PATH];
if (SUCCEEDED(SHGetFolderPath(nullptr, CSIDL_PERSONAL, nullptr, 0, szPath)))
{
path = szPath;
}
return path;
}
std::wstring FormatUnits(int n, const std::wstring& unit)
{
if (n == 0)
{
return L"";
}
if (n == 1)
{
return wstringbuilder() << n << " " << unit;
}
return wstringbuilder() << n << " " << unit << "s";
}
std::wstring FormatDuration(double seconds)
{
int minutes = FloorTo<int>(seconds / 60);
seconds -= 60.0 * minutes;
int hours = minutes / 60;
minutes -= 60 * hours;
int days = hours / 24;
hours -= 24 * days;
if (days > 0)
{
return wstringbuilder() << FormatUnits(days, L"day") << L" " << FormatUnits(hours, L"hour");
}
if (hours > 0)
{
return wstringbuilder() << FormatUnits(hours, L"hour") << L" " << FormatUnits(minutes, L"minute");
}
if (minutes > 0)
{
return wstringbuilder() << FormatUnits(minutes, L"minute") << L" " << FormatUnits(FloorTo<int>(seconds), L"second");
}
static const wchar_t* units[] = {L"s", L"ms", L"µs", L"ns", nullptr};
const wchar_t** unit = units;
while (*unit != nullptr && seconds > 0 && seconds < 1)
{
seconds *= 1e3;
++unit;
}
return wstringbuilder() << std::fixed << std::setprecision(3) << seconds << L" " << *unit;
}
BEGIN_MSG_MAP2(CMainFrame)
MSG_WM_CREATE(OnCreate)
MSG_WM_CLOSE(OnClose)
MSG_WM_QUERYENDSESSION(OnQueryEndSession)
MSG_WM_ENDSESSION(OnEndSession)
MSG_WM_MOUSEWHEEL(OnMouseWheel)
MSG_WM_CONTEXTMENU(OnContextMenu)
MSG_WM_SYSCOMMAND(OnSysCommand)
MESSAGE_HANDLER_EX(WM_SYSTEMTRAYICON, OnSystemTrayIcon)
COMMAND_ID_HANDLER_EX(SC_RESTORE, OnScRestore)
COMMAND_ID_HANDLER_EX(SC_CLOSE, OnScClose)
COMMAND_ID_HANDLER_EX(ID_FILE_NEWVIEW, OnFileNewTab)
COMMAND_ID_HANDLER_EX(ID_FILE_OPEN, OnFileOpen)
COMMAND_ID_HANDLER_EX(ID_FILE_RUN, OnFileRun)
COMMAND_ID_HANDLER_EX(ID_FILE_SAVE_LOG, OnFileSaveLog)
COMMAND_ID_HANDLER_EX(ID_APP_EXIT, OnFileExit)
COMMAND_ID_HANDLER_EX(ID_FILE_SAVE_VIEW, OnFileSaveView)
COMMAND_ID_HANDLER_EX(ID_FILE_SAVE_VIEW_SELECTION, OnFileSaveViewSelection)
COMMAND_ID_HANDLER_EX(ID_FILE_LOAD_CONFIGURATION, OnFileLoadConfiguration)
COMMAND_ID_HANDLER_EX(ID_FILE_SAVE_CONFIGURATION, OnFileSaveConfiguration)
COMMAND_ID_HANDLER_EX(ID_LOG_CLEAR, OnLogClear)
COMMAND_ID_HANDLER_EX(ID_LOG_CROP, OnLogCrop)
COMMAND_ID_HANDLER_EX(ID_LOG_PAUSE, OnLogPause)
COMMAND_ID_HANDLER_EX(ID_LOG_GLOBAL, OnLogGlobal)
COMMAND_ID_HANDLER_EX(ID_LOG_HISTORY, OnLogHistory)
COMMAND_ID_HANDLER_EX(ID_LOG_DEBUGVIEW_AGENT, OnLogDebugviewAgent)
COMMAND_ID_HANDLER_EX(ID_VIEW_FIND, OnViewFind)
COMMAND_ID_HANDLER_EX(ID_VIEW_FILTER, OnViewFilter)
COMMAND_ID_HANDLER_EX(ID_VIEW_CLOSE, OnViewClose)
COMMAND_ID_HANDLER_EX(ID_VIEW_DUPLICATE, OnViewDuplicate)
COMMAND_ID_HANDLER_EX(ID_LOG_SOURCES, OnSources)
COMMAND_ID_HANDLER_EX(ID_OPTIONS_LINKVIEWS, OnLinkViews)
COMMAND_ID_HANDLER_EX(ID_OPTIONS_AUTONEWLINE, OnAutoNewline)
COMMAND_ID_HANDLER_EX(ID_OPTIONS_PROCESS_PREFIX, OnProcessPrefix)
COMMAND_ID_HANDLER_EX(ID_OPTIONS_FONT, OnViewFont)
COMMAND_ID_HANDLER_EX(ID_OPTIONS_ALWAYSONTOP, OnAlwaysOnTop)
COMMAND_ID_HANDLER_EX(ID_OPTIONS_HIDE, OnHide)
COMMAND_ID_HANDLER_EX(ID_APP_ABOUT, OnAppAbout)
NOTIFY_CODE_HANDLER_EX(CTCN_BEGINITEMDRAG, OnBeginTabDrag)
NOTIFY_CODE_HANDLER_EX(CTCN_SELCHANGE, OnChangeTab)
NOTIFY_CODE_HANDLER_EX(CTCN_CLOSE, OnCloseTab)
NOTIFY_CODE_HANDLER_EX(CTCN_DELETEITEM, OnDeleteTab)
if (uMsg == EM_REPLACESEL)
{
m_logSources.AddMessage(static_cast<DWORD>(wParam), "SendMessage", Str(reinterpret_cast<wchar_t*>(lParam)));
}
// forward WM_COMMANDs directly to the active LogView, otherwise TabbedFrame forwards WM_COMMANDs to the Splitter
// which has FORWARD_NOTIFICATIONS() and sends it back the the CMainFrame causing an infinite loop
if (uMsg == WM_COMMAND)
{
if (GetViewCount() > 0)
{
GetView().SendMessage(uMsg, wParam, lParam);
}
return TRUE;
}
CHAIN_MSG_MAP(TabbedFrame)
CHAIN_MSG_MAP(CUpdateUI<CMainFrame>)
REFLECT_NOTIFICATIONS()
END_MSG_MAP()
LOGFONT& GetDefaultLogFont()
{
static LOGFONT lf;
static int initialized = GetObjectW(AtlGetDefaultGuiFont(), sizeof(lf), &lf);
return lf;
}
CMainFrame::CMainFrame() :
m_findDlg(*this),
m_tryGlobal(IsWindowsVistaOrGreater() && HasGlobalDBWinReaderRights()),
m_logFileName(L"DebugView++.dblog"),
m_txtFileName(L"Messages.dblog"),
m_configFileName(L"DebugView++.dbconf"),
m_initialPrivateBytes(ProcessInfo::GetPrivateBytes()),
m_logfont(GetDefaultLogFont()),
m_GuiExecutorClient(std::make_unique<GuiExecutorClient>()),
m_logSources(*m_GuiExecutorClient)
{
m_notifyIconData.cbSize = 0;
}
CMainFrame::~CMainFrame() = default;
void CMainFrame::SetLogging()
{
m_logWriter = std::make_unique<FileWriter>(L"debugview.dblog", m_logFile);
}
void CMainFrame::OnException()
{
errormessage("No additional information available", "Exception occurred");
}
void CMainFrame::OnException(const std::exception& ex)
{
errormessage(ex.what(), "Exception occurred");
}
BOOL CMainFrame::PreTranslateMessage(MSG* pMsg)
{
return TabbedFrame::PreTranslateMessage(pMsg);
}
BOOL CMainFrame::OnIdle()
{
UpdateUI();
UIUpdateToolBar();
UIUpdateStatusBar();
return FALSE;
}
LRESULT CMainFrame::OnCreate(const CREATESTRUCT* /*pCreate*/)
{
m_notifyIconData.cbSize = 0;
HWND hWndCmdBar = m_cmdBar.Create(*this, rcDefault, nullptr, ATL_SIMPLE_CMDBAR_PANE_STYLE);
m_cmdBar.AttachMenu(GetMenu());
m_cmdBar.LoadImages(IDR_MAINFRAME);
SetMenu(nullptr); //disable second menu bar
CreateSimpleReBar(ATL_SIMPLE_REBAR_NOBORDER_STYLE);
CReBarCtrl rebar(m_hWndToolBar);
AddSimpleReBarBand(hWndCmdBar);
HWND hWndToolBar =
CreateSimpleToolBarCtrl(rebar, IDR_MAINFRAME, 0, ATL_SIMPLE_TOOLBAR_PANE_STYLE); // DrMemory: LEAK 1696 direct bytes
AddSimpleReBarBand(hWndToolBar, nullptr, 1);
UIAddToolBar(hWndToolBar);
m_findDlg.Create(rebar);
AddSimpleReBarBand(m_findDlg, L"Find: ", 0, 10000);
SizeSimpleReBarBands();
rebar.LockBands(true);
rebar.SetNotifyWnd(*this);
m_hWndStatusBar = m_statusBar.Create(*this);
int paneIds[] = {ID_DEFAULT_PANE, ID_SELECTION_PANE, ID_VIEW_PANE, ID_LOGFILE_PANE, ID_MEMORY_PANE};
m_statusBar.SetPanes(paneIds, 5, false);
UIAddStatusBar(m_hWndStatusBar);
CreateTabWindow(*this, rcDefault, CTCS_CLOSEBUTTON | CTCS_DRAGREARRANGE);
AddFilterView(L"View");
HideTabControl();
SetLogFont();
LoadSettings();
// register object for message filtering and idle updates
CMessageLoop* pLoop = _Module.GetMessageLoop();
ATLASSERT(pLoop != nullptr);
pLoop->AddMessageFilter(this);
pLoop->AddIdleHandler(this);
m_logSources.SubscribeToUpdate([this] { return OnUpdate(); });
// Resume can throw if a second debugview is running
// so do not rely on any commands executed afterwards
Resume();
return 0;
}
void CMainFrame::OnClose()
{
SaveSettings();
DestroyWindow();
if (m_notifyIconData.cbSize != 0u)
{
Shell_NotifyIcon(NIM_DELETE, &m_notifyIconData);
m_notifyIconData.cbSize = 0;
}
#ifdef CONSOLE_DEBUG
fclose(stdout);
FreeConsole();
#endif
}
LRESULT CMainFrame::OnQueryEndSession(WPARAM /*unused*/, LPARAM /*unused*/)
{
// MSDN:
// The WM_QUERYENDSESSION message is sent when the user chooses to end the session or when an application calls one of the system
// shutdown functions When an application returns TRUE for this message, it receives the WM_ENDSESSION message. Each application should
// return TRUE or FALSE immediately upon receiving this message, and defer any cleanup operations until it receives the WM_ENDSESSION
// message.
return TRUE;
}
LRESULT CMainFrame::OnEndSession(WPARAM /*unused*/, LPARAM /*unused*/)
{
OnClose();
return TRUE;
}
void CMainFrame::UpdateUI()
{
UpdateStatusBar();
UISetCheck(ID_VIEW_TIME, GetView().GetClockTime());
UISetCheck(ID_VIEW_PROCESSCOLORS, GetView().GetViewProcessColors());
UISetCheck(ID_VIEW_SCROLL, GetView().GetAutoScroll());
UISetCheck(ID_VIEW_SCROLL_STOP, GetView().GetAutoScrollStop());
UISetCheck(ID_VIEW_BOOKMARK, GetView().GetBookmark());
for (int id = ID_VIEW_COLUMN_FIRST; id <= ID_VIEW_COLUMN_LAST; ++id)
{
UISetCheck(id, GetView().IsColumnViewed(id));
}
UISetCheck(ID_OPTIONS_LINKVIEWS, m_linkViews);
UIEnable(ID_OPTIONS_LINKVIEWS, static_cast<BOOL>(GetTabCtrl().GetItemCount() > 1));
UISetCheck(ID_OPTIONS_AUTONEWLINE, m_logSources.GetAutoNewLine());
UISetCheck(ID_OPTIONS_PROCESS_PREFIX, m_logSources.GetProcessPrefix());
UISetCheck(ID_OPTIONS_ALWAYSONTOP, GetAlwaysOnTop());
UISetCheck(ID_OPTIONS_HIDE, m_hide);
UISetCheck(ID_LOG_PAUSE, !m_pLocalReader);
UIEnable(ID_LOG_GLOBAL, !!m_pLocalReader);
UISetCheck(ID_LOG_GLOBAL, m_tryGlobal);
}
std::wstring FormatDateTime(const SYSTEMTIME& systemTime)
{
int size = GetTimeFormat(LOCALE_USER_DEFAULT, 0, &systemTime, nullptr, nullptr, 0);
size += GetDateFormat(LOCALE_USER_DEFAULT, 0, &systemTime, nullptr, nullptr, 0);
std::vector<wchar_t> buf(size);
int offset = GetDateFormat(LOCALE_USER_DEFAULT, 0, &systemTime, nullptr, buf.data(), size);
buf[offset - 1] = ' ';
GetTimeFormat(LOCALE_USER_DEFAULT, 0, &systemTime, nullptr, buf.data() + offset, size);
return std::wstring(buf.data(), size - 1);
}
std::wstring FormatDateTime(const FILETIME& fileTime)
{
return FormatDateTime(Win32::FileTimeToSystemTime(Win32::FileTimeToLocalFileTime(fileTime)));
}
std::wstring FormatBytes(size_t size)
{
static const wchar_t* units[] = {L"bytes", L"kB", L"MB", L"GB", L"TB", L"PB", L"EB", nullptr};
const wchar_t** unit = units;
const int kb = 1024;
while (size / kb > 0 && unit[1] != nullptr)
{
size = size / kb;
++unit;
}
return wstringbuilder() << size << L" " << *unit;
}
std::wstring CMainFrame::GetSelectionInfoText(const std::wstring& label, const SelectionInfo& selection) const
{
if (selection.count == 0)
{
return std::wstring();
}
if (selection.count == 1)
{
return label + L": " + FormatDateTime(m_logFile[selection.beginLine].systemTime);
}
double dt = m_logFile[selection.endLine].time - m_logFile[selection.beginLine].time;
return wstringbuilder() << label << L": " << FormatDuration(dt) << L" (" << selection.count << " lines)";
}
SelectionInfo CMainFrame::GetLogFileRange() const
{
if (m_logFile.Empty())
{
return SelectionInfo();
}
return SelectionInfo(0, m_logFile.Count() - 1, m_logFile.Count());
}
void CMainFrame::UpdateStatusBar()
{
auto isearch = GetView().GetHighlightText();
std::wstring search = wstringbuilder() << L"Searching: \"" << isearch << L"\"";
UISetText(ID_DEFAULT_PANE, isearch.empty() ? (m_pLocalReader != nullptr ? L"Ready" : L"Paused") : search.c_str());
UISetText(ID_SELECTION_PANE, GetSelectionInfoText(L"Selected", GetView().GetSelectedRange()).c_str());
UISetText(ID_VIEW_PANE, GetSelectionInfoText(L"View", GetView().GetViewRange()).c_str());
UISetText(ID_LOGFILE_PANE, GetSelectionInfoText(L"Log", GetLogFileRange()).c_str());
auto currentUsage = ProcessInfo::GetPrivateBytes();
auto memoryUsage = currentUsage > m_initialPrivateBytes ? currentUsage - m_initialPrivateBytes : 0;
UISetText(ID_MEMORY_PANE, FormatBytes(memoryUsage).c_str());
}
void CMainFrame::ProcessLines(const Lines& lines)
{
if (lines.empty())
{
return;
}
// design decision: filtering is done on the UI thread, see CLogView::Add
// changing this would introduces extra thread and thus complexity. Do that only if it solves a problem.
int views = GetViewCount();
for (int i = 0; i < views; ++i)
{
GetView(i).BeginUpdate();
}
if (m_logSources.GetProcessPrefix())
{
for (auto& line : lines)
{
AddMessage(Message(line.time, line.systemTime, line.pid, line.processName, "[" + std::to_string(line.pid) + "] " + line.message));
}
}
else
{
for (auto& line : lines)
{
AddMessage(Message(line.time, line.systemTime, line.pid, line.processName, line.message));
}
}
for (int i = 0; i < views; ++i)
{
if (GetView(i).EndUpdate() && GetTabCtrl().GetCurSel() != i)
{
SetModifiedMark(i, true);
GetTabCtrl().UpdateLayout();
GetTabCtrl().Invalidate();
}
}
}
bool CMainFrame::OnUpdate()
{
Lines bucket;
auto lines = m_logSources.GetLines();
int count = 0;
for (auto&& line : lines)
{
if (count++ < 5000)
{
bucket.emplace_back(std::move(line));
}
else
{
count = 0;
m_incomingMessages.emplace_back(std::move(bucket));
bucket = Lines();
}
}
if (!bucket.empty())
{
m_incomingMessages.emplace_back(std::move(bucket));
}
if (m_incomingMessages.empty())
{
return false;
}
auto linesbucket = std::move(m_incomingMessages.front());
m_incomingMessages.pop_front();
ProcessLines(linesbucket);
if (!m_incomingMessages.empty())
{
m_GuiExecutorClient->CallAfter(20ms, [this] { OnUpdate(); });
}
return true;
}
bool CMainFrame::OnMouseWheel(UINT nFlags, short zDelta, CPoint /*pt*/)
{
if ((nFlags & MK_CONTROL) == 0)
{
return false;
}
int size = static_cast<int>(LogFontSizeToPointSize(m_logfont.lfHeight) * std::pow(1.15, zDelta / WHEEL_DELTA) + 0.5);
size = std::max(size, 4);
size = std::min(size, 24);
m_logfont.lfHeight = LogFontSizeFromPointSize(size);
SetLogFont();
return true;
}
void CMainFrame::OnContextMenu(HWND hWnd, CPoint pt)
{
if (hWnd != m_TabCtrl)
{
SetMsgHandled(win32::False);
return;
}
CTCHITTESTINFO hit;
hit.pt = pt;
m_TabCtrl.ScreenToClient(&hit.pt);
int item = m_TabCtrl.HitTest(&hit);
CMenu menuContext;
menuContext.LoadMenu(IDR_TAB_CONTEXTMENU);
CMenuHandle menuPopup(menuContext.GetSubMenu(0));
if (item < 0)
{
menuPopup.EnableMenuItem(ID_VIEW_FILTER, MF_BYCOMMAND | MF_GRAYED);
menuPopup.EnableMenuItem(ID_VIEW_CLEAR, MF_BYCOMMAND | MF_GRAYED);
menuPopup.EnableMenuItem(ID_VIEW_CLOSE, MF_BYCOMMAND | MF_GRAYED);
}
menuPopup.TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, pt.x, pt.y, *this);
}
void CMainFrame::HandleDroppedFile(const std::wstring& file)
{
SetTitle(file);
using boost::algorithm::iequals;
auto ext = std::filesystem::path(file).extension().wstring();
if (iequals(ext, L".exe"))
{
Run(file);
}
else if (iequals(ext, L".cmd") || iequals(ext, L".bat"))
{
m_logSources.AddProcessReader(L"cmd.exe", wstringbuilder() << L"/Q /C \"" << file << "\"");
}
else
{
if (IsBinaryFileType(IdentifyFile(file)))
{
m_logSources.AddBinaryFileReader(file);
}
else
{
m_logSources.AddAnyFileReader(file, true);
}
}
}
void CMainFrame::OnDropped(const std::wstring uri)
{
if (std::filesystem::is_regular_file(uri))
{
HandleDroppedFile(uri);
}
else
{
std::wstring httpmonitor = wstringbuilder() << Win32::GetExecutionPath() << "\\debugview++plugins\\HttpMonitor.exe";
if (std::filesystem::exists(httpmonitor))
{
if (m_httpMonitorHandle)
{
::TerminateProcess(m_httpMonitorHandle.get(), 0);
}
Win32::Process process(httpmonitor, uri);
m_httpMonitorHandle = Win32::DuplicateHandle(process.GetProcessHandle());
m_jobs.AddProcessByHandle(m_httpMonitorHandle.get());
}
else
{
m_logSources.AddMessage(stringbuilder() << httpmonitor << " missing, dropped url ignored\n");
}
}
}
LRESULT CMainFrame::OnSysCommand(UINT nCommand, CPoint /*unused*/)
{
switch (nCommand)
{
case SC_MINIMIZE:
if (!m_hide)
{
break;
}
if (m_notifyIconData.cbSize == 0u)
{
m_notifyIconData.cbSize = sizeof(m_notifyIconData);
m_notifyIconData.hWnd = *this;
m_notifyIconData.uID = 1;
m_notifyIconData.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
m_notifyIconData.uCallbackMessage = WM_SYSTEMTRAYICON;
m_notifyIconData.hIcon =
AtlLoadIconImage(IDR_MAINFRAME, LR_DEFAULTCOLOR, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON));
CString sWindowText;
GetWindowText(sWindowText);
_tcscpy_s(m_notifyIconData.szTip, sWindowText);
if (!Shell_NotifyIcon(NIM_ADD, &m_notifyIconData))
{
break;
}
}
ShowWindow(SW_HIDE);
return 0;
default:
break;
}
SetMsgHandled(win32::False);
return 0;
}
LRESULT CMainFrame::OnSystemTrayIcon(UINT /*unused*/, WPARAM /*unused*/, LPARAM lParam)
{
switch (lParam)
{
case WM_LBUTTONDBLCLK: SendMessage(WM_COMMAND, SC_RESTORE); break;
case WM_RBUTTONUP: {
SetForegroundWindow(m_hWnd);
CMenuHandle menu = GetSystemMenu(0);
menu.EnableMenuItem(SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
menu.EnableMenuItem(SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
menu.EnableMenuItem(SC_SIZE, MF_BYCOMMAND | MF_GRAYED);
menu.EnableMenuItem(SC_MINIMIZE, MF_BYCOMMAND | MF_GRAYED);
menu.EnableMenuItem(SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
menu.EnableMenuItem(SC_CLOSE, MF_BYCOMMAND | MF_ENABLED);
POINT position = Win32::GetCursorPos();
menu.TrackPopupMenu(TPM_LEFTALIGN | TPM_BOTTOMALIGN, position.x, position.y, m_hWnd);
break;
}
default:
break;
}
return 0;
}
LRESULT CMainFrame::OnScRestore(UINT /*unused*/, INT /*unused*/, HWND /*unused*/)
{
if (m_notifyIconData.cbSize != 0u)
{
Shell_NotifyIcon(NIM_DELETE, &m_notifyIconData);
m_notifyIconData.cbSize = 0;
}
ShowWindow(SW_SHOW);
BringWindowToTop();
return 0;
}
LRESULT CMainFrame::OnScClose(UINT /*unused*/, INT /*unused*/, HWND /*unused*/)
{
PostMessage(WM_COMMAND, ID_APP_EXIT);
return 0;
}
const wchar_t* RegistryPath = L"Software\\Cobalt Fusion\\DebugView++";
int CMainFrame::LogFontSizeFromPointSize(int fontSize)
{
CDC dc(GetDC());
return -MulDiv(fontSize, GetDeviceCaps(dc, LOGPIXELSY), 72);
}
int CMainFrame::LogFontSizeToPointSize(int logFontSize)
{
CDC dc(GetDC());
return -MulDiv(logFontSize, 72, GetDeviceCaps(dc, LOGPIXELSY));
}
bool CMainFrame::LoadSettings()
{
auto mutex = Win32::CreateMutex(nullptr, false, L"Local\\DebugView++");
Win32::MutexLock lock(mutex.get());
DWORD x = 0;
DWORD y = 0;
DWORD cx = 0;
DWORD cy = 0;
CRegKey reg;
reg.Create(HKEY_CURRENT_USER, RegistryPath);
if (reg.QueryDWORDValue(L"X", x) == ERROR_SUCCESS && static_cast<int>(x) >= GetSystemMetrics(SM_XVIRTUALSCREEN) &&
reg.QueryDWORDValue(L"Y", y) == ERROR_SUCCESS && static_cast<int>(y) >= GetSystemMetrics(SM_YVIRTUALSCREEN) &&
reg.QueryDWORDValue(L"Width", cx) == ERROR_SUCCESS && static_cast<int>(x + cx) <= GetSystemMetrics(SM_XVIRTUALSCREEN) + GetSystemMetrics(SM_CXVIRTUALSCREEN) &&
reg.QueryDWORDValue(L"Height", cy) == ERROR_SUCCESS && static_cast<int>(y + cy) <= GetSystemMetrics(SM_YVIRTUALSCREEN) + GetSystemMetrics(SM_CYVIRTUALSCREEN))
{
SetWindowPos(nullptr, x, y, cx, cy, SWP_NOZORDER);
}
m_linkViews = Win32::RegGetDWORDValue(reg, L"LinkViews", 0) != 0;
m_logSources.SetAutoNewLine(Win32::RegGetDWORDValue(reg, L"AutoNewLine", 1) != 0);
SetAlwaysOnTop(Win32::RegGetDWORDValue(reg, L"AlwaysOnTop", 0) != 0);
m_applicationName = Win32::RegGetStringValue(reg, L"ApplicationName", L"DebugView++");
SetTitle();
m_hide = Win32::RegGetDWORDValue(reg, L"Hide", 0) != 0;
auto fontName = Win32::RegGetStringValue(reg, L"FontName", L"").substr(0, LF_FACESIZE - 1);
int fontSize = Win32::RegGetDWORDValue(reg, L"FontSize", 8);
if (!fontName.empty())
{
LOGFONT lf = {0};
m_logfont = lf;
std::copy(fontName.begin(), fontName.end(), m_logfont.lfFaceName);
m_logfont.lfHeight = LogFontSizeFromPointSize(fontSize);
SetLogFont();
}
CRegKey regViews;
if (regViews.Open(reg, L"Views") == ERROR_SUCCESS)
{
for (size_t i = 0;; ++i)
{
CRegKey regView;
if (regView.Open(regViews, WStr(wstringbuilder() << L"View" << i)) != ERROR_SUCCESS)
{
break;
}
auto name = Win32::RegGetStringValue(regView);
if (i == 0)
{
GetTabCtrl().GetItem(0)->SetText(name.c_str());
}
else
{
AddFilterView(name);
}
GetView().LoadSettings(regView);
}
GetTabCtrl().SetCurSel(Win32::RegGetDWORDValue(regViews, L"Current", 0));
GetTabCtrl().UpdateLayout();
GetTabCtrl().Invalidate();
}
CRegKey regColors;
if (regColors.Open(reg, L"Colors") == ERROR_SUCCESS)
{
auto colors = ColorDialog::GetCustomColors();
for (int i = 0; i < 16; ++i)
{
colors[i] = Win32::RegGetDWORDValue(regColors, WStr(wstringbuilder() << L"Color" << i));
}
}
return true;
}
void CMainFrame::SaveSettings()
{
auto mutex = Win32::CreateMutex(nullptr, false, L"Local\\DebugView++");
Win32::MutexLock lock(mutex.get());
auto placement = Win32::GetWindowPlacement(*this);
CRegKey reg;
reg.Create(HKEY_CURRENT_USER, RegistryPath);
reg.SetDWORDValue(L"X", placement.rcNormalPosition.left);
reg.SetDWORDValue(L"Y", placement.rcNormalPosition.top);
reg.SetDWORDValue(L"Width", placement.rcNormalPosition.right - placement.rcNormalPosition.left);
reg.SetDWORDValue(L"Height", placement.rcNormalPosition.bottom - placement.rcNormalPosition.top);
reg.SetDWORDValue(L"LinkViews", static_cast<DWORD>(m_linkViews));
reg.SetDWORDValue(L"AutoNewLine", static_cast<DWORD>(m_logSources.GetAutoNewLine()));
reg.SetDWORDValue(L"AlwaysOnTop", static_cast<DWORD>(GetAlwaysOnTop()));
reg.SetDWORDValue(L"Hide", static_cast<DWORD>(m_hide));
reg.SetStringValue(L"FontName", m_logfont.lfFaceName);
reg.SetDWORDValue(L"FontSize", LogFontSizeToPointSize(m_logfont.lfHeight));
reg.RecurseDeleteKey(L"Views");
CRegKey regViews;
regViews.Create(reg, L"Views");
regViews.SetDWORDValue(L"Current", GetTabCtrl().GetCurSel());
int views = GetViewCount();
for (int i = 0; i < views; ++i)
{
CRegKey regView;
regView.Create(regViews, WStr(wstringbuilder() << L"View" << i));
regView.SetStringValue(L"", GetView(i).GetName().c_str());
GetView(i).SaveSettings(regView);
}
CRegKey regColors;
regColors.Create(reg, L"Colors");
auto colors = ColorDialog::GetCustomColors();
for (int i = 0; i < 16; ++i)
{
regColors.SetDWORDValue(WStr(wstringbuilder() << L"Color" << i), colors[i]);
}
}
void CMainFrame::FindNext(const std::wstring& text)
{
if (!GetView().FindNext(text))
{
MessageBeep(MB_ICONASTERISK);
}
}
void CMainFrame::FindPrevious(const std::wstring& text)
{
if (!GetView().FindPrevious(text))
{
MessageBeep(MB_ICONASTERISK);
}
}
void CMainFrame::AddFilterView()
{
++m_filterNr;
CFilterDlg dlg(wstringbuilder() << L"View " << m_filterNr);
if (dlg.DoModal() != IDOK)
{
return;
}
AddFilterView(dlg.GetName(), dlg.GetFilters());
SaveSettings();
}
void CMainFrame::AddFilterView(const std::wstring& name, const LogFilter& filter)
{
AddFilterView(std::make_shared<CLogView>(name, *this, m_logFile, filter));
}
void CMainFrame::AddFilterView(std::shared_ptr<CLogView> logview)
{
auto pTabItem = std::make_unique<SelectedTabItem>();
pTabItem->Create(*this);
logview->Create(pTabItem->GetLogViewParent(), rcDefault, nullptr, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN);
logview->SetFont(m_hFont.get());
pTabItem->SetText(logview->GetName().c_str());
pTabItem->SetView(logview);
int newIndex = GetTabCtrl().GetItemCount();
// notice: InsertItem takes ownership of the raw pointer, DeleteItem calls delete
GetTabCtrl().InsertItem(newIndex, pTabItem.release());
GetTabCtrl().SetCurSel(newIndex);
ShowTabControl();
}
LRESULT CMainFrame::OnBeginTabDrag(NMHDR* pnmh)
{
auto& nmhdr = *reinterpret_cast<NMCTCITEM*>(pnmh);
return static_cast<LRESULT>(nmhdr.iItem >= GetViewCount());
}
LRESULT CMainFrame::OnChangeTab(NMHDR* pnmh)
{
SetMsgHandled(win32::False);
auto& nmhdr = *reinterpret_cast<NMCTC2ITEMS*>(pnmh);
if (nmhdr.iItem2 >= 0 && nmhdr.iItem2 < GetViewCount())
{
SetModifiedMark(nmhdr.iItem2, false);
}
if (!m_linkViews || nmhdr.iItem1 == nmhdr.iItem2 || nmhdr.iItem1 < 0 || nmhdr.iItem1 >= GetViewCount() || nmhdr.iItem2 < 0 ||
nmhdr.iItem2 >= GetViewCount())
{
return 0;
}
int line = GetView(nmhdr.iItem1).GetFocusLine();
GetView(nmhdr.iItem2).SetFocusLine(line);
return 0;
}
void CMainFrame::SetModifiedMark(int tabindex, bool modified)
{
auto name = GetView(tabindex).GetName();
if (modified)
{
name += L"*";
}
// GetTabCtrl().GetItem(nmhdr.iItem2)->SetHighlighted(modified)
GetTabCtrl().GetItem(tabindex)->SetText(name.c_str());
}
LRESULT CMainFrame::OnCloseTab(NMHDR* pnmh)
{
auto& nmhdr = *reinterpret_cast<NMCTCITEM*>(pnmh);
CloseView(nmhdr.iItem);
return 0;
}
LRESULT CMainFrame::OnDeleteTab(NMHDR* pnmh)
{
auto& nmhdr = *reinterpret_cast<NMCTCITEM*>(pnmh);
if (nmhdr.iItem >= 0 && nmhdr.iItem < GetViewCount())
{
GetView(nmhdr.iItem).DestroyWindow();
}
return FALSE;
}
void CMainFrame::OnFileNewTab(UINT /*uNotifyCode*/, int /*nID*/, CWindow /*wndCtl*/)
{
AddFilterView();
}
void CMainFrame::SaveLogFile(const std::wstring& filename)
{
UISetText(0, WStr(wstringbuilder() << "Saving " << filename));
Win32::ScopedCursor cursor(::LoadCursor(nullptr, IDC_WAIT));
std::ofstream fs;
OpenLogFile(fs, filename);
int count = m_logFile.Count();
for (int i = 0; i < count; ++i)
{
auto msg = m_logFile[i];
WriteLogFileMessage(fs, msg.time, msg.systemTime, msg.processId, msg.processName, msg.text);
}
fs.close();
if (!fs)
{
Win32::ThrowLastError(filename);
}
m_logFileName = filename;
UpdateStatusBar();
}
void CMainFrame::SaveViewFile(const std::wstring& filename)
{
UISetText(0, WStr(wstringbuilder() << "Saving view to " << filename));
Win32::ScopedCursor cursor(::LoadCursor(nullptr, IDC_WAIT));
GetView().Save(filename);
m_txtFileName = filename;
UpdateStatusBar();
}
void CMainFrame::SaveViewSelection(const std::wstring& filename)
{
UISetText(0, WStr(wstringbuilder() << "Saving selection to " << filename));
Win32::ScopedCursor cursor(::LoadCursor(nullptr, IDC_WAIT));
GetView().SaveSelection(filename);
m_txtFileName = filename;
UpdateStatusBar();
}
struct View
{
int index;
std::string name;
bool clockTime;
bool processColors;
LogFilter filters;
boost::optional<boost::property_tree::ptree> columnsPt;
};
struct SourceInfoHelper
{
SourceInfoHelper(int index, const std::wstring& description, SourceType::type sourceType) :
index(index),
sourceInfo(description, sourceType)
{
}
int index;
SourceInfo sourceInfo;
};
void CMainFrame::LoadConfiguration(const std::wstring& fileName)
{
boost::property_tree::ptree pt;
boost::property_tree::read_xml(Str(fileName), pt, boost::property_tree::xml_parser::trim_whitespace);
auto autoNewline = pt.get<bool>("DebugViewPP.AutoNewline");
auto linkViews = pt.get<bool>("DebugViewPP.LinkViews");
auto viewsPt = pt.get_child("DebugViewPP.Views");
std::vector<View> views;
for (auto& item : viewsPt)
{
if (item.first == "View")
{
View view;
auto& viewPt = item.second;
view.index = viewPt.get<int>("Index");
view.name = viewPt.get<std::string>("Name");
view.clockTime = viewPt.get<bool>("ClockTime");
view.processColors = viewPt.get<bool>("ProcessColors");
view.filters.messageFilters = MakeFilters(viewPt.get_child("MessageFilters"));
view.filters.processFilters = MakeFilters(viewPt.get_child("ProcessFilters"));