Repository navigation
Expand file tree
/
Copy pathMainWndRegressionTests.cpp
More file actions
4906 lines (4849 loc) · 333 KB
/
Copy pathMainWndRegressionTests.cpp
File metadata and controls
4906 lines (4849 loc) · 333 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
#include "MainWndInternal.h"
#include "FavoriteStarUI.h"
#include "ShellMenuUtil.h"
#include "ExplorerAgentProtocol.h"
#include "FastFileAbout.h"
namespace { bool ForceNewWindowRequested(); }
class FastFileActivationWindow : public CMainWnd {
public:
// HKCU overrides are process-local; do not spawn an unisolated agent here.
void EnableExplorerAgent() {}
HWND Create(HWND parent,LPCTSTR title,DWORD style,DWORD extendedStyle) {
HWND window=CMainWnd::Create(parent,title,style,extendedStyle);
if(window) {
SetPropW(window,L"FastFile.Test.Initialized",reinterpret_cast<HANDLE>(1));
if(ForceNewWindowRequested())SetPropW(window,L"FastFile.Test.ForcedNewWindow",reinterpret_cast<HANDLE>(1));
}
return window;
}
};
// Compile the production entry point into the process-launch regression. This
// avoids a test-only substitute for command parsing and single-instance IPC.
#define wWinMain FastFileActivationEntry
#define CMainWnd FastFileActivationWindow
#include "../src/main.cpp"
#undef CMainWnd
#undef wWinMain
#include <iostream>
#include <functional>
#include <atomic>
#include <thread>
#include <exdisp.h>
#include <shlguid.h>
#include <propvarutil.h>
#include "ShellWindowRegistration.h"
#include <sddl.h>
#pragma comment(lib, "advapi32.lib")
#include <shldisp.h>
namespace {
// A live OleGetClipboard proxy cannot be put back after clearing its backing
// clipboard: flushing that proxy can recursively read itself. Snapshot data first.
IDataObject* SnapshotClipboard() {
IDataObject* source=nullptr;
if (FAILED(OleGetClipboard(&source)) || !source) return nullptr;
IDataObject* snapshot=nullptr;
if (FAILED(SHCreateDataObject(nullptr,0,nullptr,nullptr,IID_PPV_ARGS(&snapshot)))) {
source->Release();return nullptr;
}
IEnumFORMATETC* formats=nullptr;
if (SUCCEEDED(source->EnumFormatEtc(DATADIR_GET,&formats))) {
FORMATETC format{};
while (formats->Next(1,&format,nullptr)==S_OK) {
STGMEDIUM medium{};
if (SUCCEEDED(source->GetData(&format,&medium))) {
if (FAILED(snapshot->SetData(&format,&medium,TRUE))) ReleaseStgMedium(&medium);
}
CoTaskMemFree(format.ptd);
}
formats->Release();
}
source->Release();return snapshot;
}
class ScrollBarDragFixture : public CFluentScrollBarUI {
public:
bool Captured() const { return (m_uThumbState & UISTATE_CAPTURED) != 0; }
POINT ThumbPoint() const { return {m_rcThumb.left+1,m_rcThumb.top+2}; }
WPARAM TimerId() const { return DEFAULT_TIMERID; }
};
// Counts files and the newest write time in the user's real icon cache tree
// (%TEMP%\FastFileIconCache), read-only, to prove a test run never touches it.
void UserIconCacheSnapshot(size_t& files, ULONGLONG& newest) {
files = 0; newest = 0;
wchar_t temp[MAX_PATH]{}; GetTempPathW(MAX_PATH, temp);
std::vector<std::wstring> pending{ std::wstring(temp) + L"FastFileIconCache" };
while (!pending.empty()) {
const std::wstring dir = pending.back(); pending.pop_back();
WIN32_FIND_DATAW fd{}; HANDLE h = FindFirstFileW((dir + L"\\*").c_str(), &fd);
if (h == INVALID_HANDLE_VALUE) continue;
do {
if (!wcscmp(fd.cFileName, L".") || !wcscmp(fd.cFileName, L"..")) continue;
if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { pending.push_back(dir + L"\\" + fd.cFileName); continue; }
++files;
newest = (std::max)(newest, (ULONGLONG(fd.ftLastWriteTime.dwHighDateTime) << 32) | fd.ftLastWriteTime.dwLowDateTime);
} while (FindNextFileW(h, &fd));
FindClose(h);
}
}
bool AppIconMatchesSource() {
wchar_t module[MAX_PATH]{}; GetModuleFileNameW(nullptr,module,_countof(module));
PathRemoveFileSpecW(module);
const std::wstring directory=module;
std::ifstream input(directory+L"\\..\\..\\res\\FastFile.ico",std::ios::binary);
std::vector<char> source((std::istreambuf_iterator<char>(input)),{});
if(source.size()<6) return false;
auto word=[](const char* p) {WORD value;memcpy(&value,p,2);return value;};
auto dword=[](const char* p) {DWORD value;memcpy(&value,p,4);return value;};
const WORD count=word(source.data()+4);
if(!count || source.size()<6+size_t(count)*16) return false;
HMODULE app=LoadLibraryExW((directory+L"\\FastFile.exe").c_str(),nullptr,
LOAD_LIBRARY_AS_DATAFILE|LOAD_LIBRARY_AS_IMAGE_RESOURCE);
if(!app) return false;
HRSRC group=FindResourceW(app,MAKEINTRESOURCEW(1),RT_GROUP_ICON);
const char* data=group ? static_cast<const char*>(LockResource(LoadResource(app,group))) : nullptr;
bool ok=data && SizeofResource(app,group)>=6+DWORD(count)*14 && word(data+4)==count;
if(!ok) std::cerr<<"icon diagnostic source="<<count<<" resource="<<(data?word(data+4):0)<<"\n";
for(int i=0;ok && i<count;++i) {
const char* entry=source.data()+6+i*16;
const char* compiled=data+6+i*14;
const DWORD bytes=dword(entry+8),offset=dword(entry+12);
HRSRC icon=FindResourceW(app,MAKEINTRESOURCEW(word(compiled+12)),RT_ICON);
const void* bitmap=icon ? LockResource(LoadResource(app,icon)) : nullptr;
// rc.exe can fill planes/bit-depth metadata for PNG-compressed entries;
// pixel dimensions and the actual embedded image bytes must match.
ok=memcmp(entry,compiled,4)==0 && dword(compiled+8)==bytes && size_t(offset)+bytes<=source.size() &&
bitmap && SizeofResource(app,icon)==bytes && memcmp(bitmap,source.data()+offset,bytes)==0;
if(!ok)std::cerr<<"icon diagnostic entry="<<i<<" source bytes="<<bytes<<" embedded bytes="<<(icon?SizeofResource(app,icon):0)<<"\n";
}
FreeLibrary(app);return ok;
}
// Dismisses (and counts) any dialog box this process opens on the harness's hidden desktop,
// so a native confirmation can only fail a check, never block the suite or reach the user.
class NativeDialogGuard {
public:
NativeDialogGuard() : m_desktop(GetThreadDesktop(GetCurrentThreadId())) {
m_worker = std::thread([this] {
if (m_desktop) SetThreadDesktop(m_desktop);
while (!m_stop.load()) {
EnumDesktopWindows(m_desktop, [](HWND window, LPARAM data) -> BOOL {
auto* self = reinterpret_cast<NativeDialogGuard*>(data);
DWORD process = 0; GetWindowThreadProcessId(window, &process);
wchar_t name[64]{}; GetClassNameW(window, name, _countof(name));
if (process == GetCurrentProcessId() && IsWindowVisible(window) && wcscmp(name, L"#32770") == 0) {
wchar_t title[256]{}; GetWindowTextW(window, title, _countof(title));
char utf8[768]{}; WideCharToMultiByte(CP_UTF8, 0, title, -1, utf8, sizeof(utf8), nullptr, nullptr);
std::cerr << " dialog dismissed on the hidden desktop: " << utf8 << '\n';
++self->m_dismissed;
PostMessageW(window, WM_COMMAND, IDCANCEL, 0);
PostMessageW(window, WM_CLOSE, 0, 0);
}
return TRUE;
}, reinterpret_cast<LPARAM>(this));
Sleep(100);
}
});
}
~NativeDialogGuard() { m_stop.store(true); if (m_worker.joinable()) m_worker.join(); }
int Dismissed() const { return m_dismissed.load(); }
private:
HDESK m_desktop = nullptr;
std::atomic<bool> m_stop{false};
std::atomic<int> m_dismissed{0};
std::thread m_worker;
};
// Item-by-item comparison (ids, types, states, texts, submenu shape) of two queried menus.
bool SameShellMenu(HMENU left, HMENU right, std::string* why = nullptr, bool compareIds = true) {
const int count = GetMenuItemCount(left);
if (count != GetMenuItemCount(right)) {
if (why) *why = "count " + std::to_string(count) + " vs " + std::to_string(GetMenuItemCount(right));
return false;
}
for (int i = 0; i < count; ++i) {
wchar_t a[512]{}, b[512]{};
MENUITEMINFOW x{}, y{}; x.cbSize = y.cbSize = sizeof(MENUITEMINFOW);
x.fMask = y.fMask = MIIM_ID | MIIM_FTYPE | MIIM_STATE | MIIM_SUBMENU | MIIM_STRING;
x.dwTypeData = a; x.cch = _countof(a); y.dwTypeData = b; y.cch = _countof(b);
if (!GetMenuItemInfoW(left, i, TRUE, &x) || !GetMenuItemInfoW(right, i, TRUE, &y)) return false;
// A cascading item's wID is its HMENU handle, which differs per query.
if ((compareIds && !x.hSubMenu && x.wID != y.wID) || x.fType != y.fType || (x.fState & ~MFS_HILITE) != (y.fState & ~MFS_HILITE)
|| wcscmp(a, b) != 0 || (x.hSubMenu != nullptr) != (y.hSubMenu != nullptr)) {
if (why) {
char ua[512]{}, ub[512]{};
WideCharToMultiByte(CP_UTF8, 0, a, -1, ua, sizeof(ua), nullptr, nullptr);
WideCharToMultiByte(CP_UTF8, 0, b, -1, ub, sizeof(ub), nullptr, nullptr);
char line[1400]{};
sprintf_s(line, "item %d shown{id=%u type=0x%x state=0x%x sub=%d \"%s\"} raw{id=%u type=0x%x state=0x%x sub=%d \"%s\"}",
i, x.wID, x.fType, x.fState, x.hSubMenu != nullptr, ua, y.wID, y.fType, y.fState, y.hSubMenu != nullptr, ub);
*why = line;
}
return false;
}
}
return true;
}
// The raw Windows menu for comparison: GetUIObjectOf / CreateViewObject + QueryContextMenu
// with no host involvement (callers may site it the way FastFile sites its own menus).
struct RawShellMenu {
IContextMenu* menu = nullptr; HMENU popup = nullptr; UINT last = 0;
RawShellMenu() = default;
RawShellMenu(const RawShellMenu&) = delete;
RawShellMenu& operator=(const RawShellMenu&) = delete;
~RawShellMenu() { if (popup) DestroyMenu(popup); if (menu) menu->Release(); }
bool Query(UINT flags) {
if (!menu) return false;
if (popup) DestroyMenu(popup);
popup = CreatePopupMenu();
const HRESULT hr = menu->QueryContextMenu(popup, 0, 1, 0x7FFF, flags);
last = SUCCEEDED(hr) ? 1 + HRESULT_CODE(hr) : 0;
return SUCCEEDED(hr);
}
bool Item(PCIDLIST_ABSOLUTE item, HWND owner) {
IShellFolder* parent = nullptr; PCUITEMID_CHILD child = nullptr;
if (!item || FAILED(SHBindToParent(item, IID_PPV_ARGS(&parent), &child))) return false;
parent->GetUIObjectOf(owner, 1, &child, IID_IContextMenu, nullptr, reinterpret_cast<void**>(&menu));
parent->Release();
return menu != nullptr;
}
bool Path(const std::wstring& path, HWND owner) {
PIDLIST_ABSOLUTE item = nullptr;
if (FAILED(SHParseDisplayName(path.c_str(), nullptr, &item, 0, nullptr))) return false;
const bool ok = Item(item, owner); CoTaskMemFree(item); return ok;
}
bool Computer(HWND owner) {
PIDLIST_ABSOLUTE item = nullptr;
if (FAILED(SHGetKnownFolderIDList(FOLDERID_ComputerFolder, 0, nullptr, &item))) return false;
const bool ok = Item(item, owner); CoTaskMemFree(item); return ok;
}
bool Background(const std::wstring& folder, HWND owner) {
IShellFolder* shellFolder = nullptr; PIDLIST_ABSOLUTE item = nullptr;
if (FAILED(SHParseDisplayName(folder.c_str(), nullptr, &item, 0, nullptr))) return false;
SHBindToObject(nullptr, item, nullptr, IID_PPV_ARGS(&shellFolder)); CoTaskMemFree(item);
if (!shellFolder) return false;
shellFolder->CreateViewObject(owner, IID_PPV_ARGS(&menu)); shellFolder->Release();
return menu != nullptr;
}
};
// Counts (and blocks) popup-menu windows (#32768) created on this thread, so a native
// menu that something tries to show is observed without ever appearing.
int blockedMenuWindows = 0;
LRESULT CALLBACK BlockMenuWindows(int code, WPARAM wParam, LPARAM lParam) {
if (code == HCBT_CREATEWND) {
wchar_t name[32]{}; GetClassNameW(reinterpret_cast<HWND>(wParam), name, _countof(name));
if (wcscmp(name, L"#32768") == 0) { ++blockedMenuWindows; return 1; }
}
return CallNextHookEx(nullptr, code, wParam, lParam);
}
// Menu id of the canonical verb in a queried menu (0 if absent).
UINT VerbCommand(IContextMenu* menu, HMENU popup, UINT last, const wchar_t* verb) {
const int pos = ShellMenuUtil::FindVerb(menu, popup, 1, last, verb);
return pos >= 0 ? GetMenuItemID(popup, pos) : 0;
}
}
struct ShellBrowserHostTestAccess {
static HWND EditControl(ShellBrowserHost& host) {
return host.m_listWindow ? ListView_GetEditControl(host.m_listWindow) : nullptr;
}
static void CancelEdit(ShellBrowserHost& host) {
if (host.m_listWindow) ListView_CancelEditLabel(host.m_listWindow);
}
static HWND ListWindow(ShellBrowserHost& host) { return host.m_listWindow; }
static ShellBrowserHost::ViewCounters Counters(ShellBrowserHost& host) { return host.m_counters; }
static bool HasListSpacer(ShellBrowserHost& host) { return host.m_listSpacer != nullptr; }
static int ResolveItemIcon(ShellBrowserHost& host, int index, HIMAGELIST* outIml = nullptr) { return host.ResolveItemIcon(index, outIml); }
static HIMAGELIST SmallImageList(ShellBrowserHost& host) { return host.GetSmallImageList(); }
static HIMAGELIST SystemSmallImageList(ShellBrowserHost& host) { return host.GetSystemSmallImageList(); }
static void ClearShellSmallImages(ShellBrowserHost& host) {
host.m_shellSmallImages = nullptr;
if (host.m_listWindow) ListView_SetImageList(host.m_listWindow, nullptr, LVSIL_SMALL);
}
static LRESULT CALLBACK PendingPrivateIcon(HWND window, UINT msg, WPARAM wp, LPARAM lp,
UINT_PTR, DWORD_PTR) {
if (msg == LVM_GETITEMW && lp) {
auto* item = reinterpret_cast<LVITEMW*>(lp);
if (item->mask & LVIF_IMAGE) { item->iImage = 0; return TRUE; }
}
return DefSubclassProc(window, msg, wp, lp);
}
static bool PendingIconUsesItemIdentity(ShellBrowserHost& host) {
IFolderView2* view = View(host);
if (!view) return false;
IShellItem* item = nullptr; PIDLIST_ABSOLUTE pidl = nullptr;
SHFILEINFO expected{};
const bool ready = SUCCEEDED(view->GetItem(0, IID_PPV_ARGS(&item))) && item
&& SUCCEEDED(SHGetIDListFromObject(item, &pidl)) && pidl
&& SHGetFileInfoW(reinterpret_cast<LPCWSTR>(pidl), 0, &expected, sizeof(expected),
SHGFI_PIDL | SHGFI_SYSICONINDEX | SHGFI_SMALLICON);
CoTaskMemFree(pidl); if (item) item->Release(); view->Release();
if (!ready || expected.iIcon == 0 || !host.m_listWindow) return false;
const auto savedImages = host.m_shellSmallImages;
const auto savedView = host.m_viewWindow;
host.m_shellSmallImages = nullptr;
host.m_viewWindow = nullptr;
const bool hooked = SetWindowSubclass(host.m_listWindow, PendingPrivateIcon, 0xF501, 0) != FALSE;
HIMAGELIST images = nullptr;
const int resolved = hooked ? host.ResolveItemIcon(0, &images) : -1;
if (hooked) RemoveWindowSubclass(host.m_listWindow, PendingPrivateIcon, 0xF501);
host.m_shellSmallImages = savedImages; host.m_viewWindow = savedView;
return resolved == expected.iIcon && images == host.GetSystemSmallImageList();
}
static void Probe(ShellBrowserHost& host, int item) { host.m_probeItem = item; host.m_probeTick = 0; }
static LONGLONG ProbeTick(ShellBrowserHost& host) { return host.m_probeTick; }
static bool MediaAspectRatio(ShellBrowserHost& host,const std::wstring& path,int sourceW,int sourceH) {
// These drawing tests use a synthetic root layout; view switches may
// recreate a native child before the host's normal layout pass.
host.SetBounds({0,0,640,640});
IFolderView2* view=View(host);if(!view)return false;
int count=0,index=-1;view->ItemCount(SVGIO_ALLVIEW,&count);
for(int i=0;i<count;++i) {
IShellItem* item=nullptr;PWSTR name=nullptr;
if(SUCCEEDED(view->GetItem(i,IID_PPV_ARGS(&item)))) {
if(SUCCEEDED(item->GetDisplayName(SIGDN_FILESYSPATH,&name))) {
if(_wcsicmp(name,path.c_str())==0)index=i;
CoTaskMemFree(name);
}item->Release();
}
}view->Release();if(index<0)return false;
RECT client{};GetClientRect(host.m_listWindow,&client);
HDC screen=GetDC(nullptr),dc=CreateCompatibleDC(screen);
HBITMAP bitmap=CreateCompatibleBitmap(screen,client.right,client.bottom);auto old=SelectObject(dc,bitmap);
FillRect(dc,&client,reinterpret_cast<HBRUSH>(GetStockObject(WHITE_BRUSH)));
NMLVCUSTOMDRAW draw{};draw.nmcd.hdc=dc;draw.nmcd.dwItemSpec=index;
draw.nmcd.dwDrawStage=CDDS_ITEMPREPAINT;
host.DrawIconItem(&draw); // placeholder + async request
SettleThumbs(host);
FillRect(dc,&client,reinterpret_cast<HBRUSH>(GetStockObject(WHITE_BRUSH)));
host.DrawIconItem(&draw); // cached thumbnail
POINT point{};ListView_GetItemPosition(host.m_listWindow,index,&point);
const int pad=MulDiv(8,host.m_dpi,96),size=host.m_iconSlot;
RECT content{size,size,0,0};int colored=0;
for(int y=0;y<size;++y)for(int x=0;x<size;++x) {
const COLORREF color=GetPixel(dc,point.x+pad+x,point.y+pad+y);
if(GetRValue(color)<80 && GetGValue(color)>60 && GetGValue(color)<150 && GetBValue(color)>140) {
++colored;
content.left=(std::min)(content.left,LONG(x));content.top=(std::min)(content.top,LONG(y));
content.right=(std::max)(content.right,LONG(x+1));content.bottom=(std::max)(content.bottom,LONG(y+1));
}
}
SelectObject(dc,old);DeleteObject(bitmap);DeleteDC(dc);ReleaseDC(nullptr,screen);
const int width=content.right-content.left,height=content.bottom-content.top;
if(!sourceW || !sourceH)return colored>100;
return width>0 && height>0 &&
abs(width*sourceH-height*sourceW)<=3*(sourceW+sourceH) &&
abs(content.left-(size-content.right))<=4 && abs(content.top-(size-content.bottom))<=4;
}
// Async thumbnails: pump until the worker has delivered every queued thumbnail.
static bool SettleThumbs(ShellBrowserHost& host, DWORD timeout = 6000) {
const DWORD deadline = GetTickCount() + timeout;
DWORD quietSince = GetTickCount();
while (GetTickCount() < deadline) {
MSG message;
while (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) {
if (message.message == WM_QUIT) continue;
TranslateMessage(&message); DispatchMessageW(&message);
}
if (!host.m_thumbPending.empty()) quietSince = GetTickCount();
else if (GetTickCount() - quietSince >= 150) return true;
Sleep(5);
}
return host.m_thumbPending.empty();
}
static size_t PendingThumbs(ShellBrowserHost& host) { return host.m_thumbPending.size(); }
static size_t CachedThumbs(ShellBrowserHost& host) { return host.m_thumbLru.size(); }
static std::vector<std::wstring> CachedKeys(ShellBrowserHost& host) {
std::vector<std::wstring> keys; for (const auto& entry : host.m_thumbLru) keys.push_back(entry.key); return keys;
}
static UINT ThumbGeneration(ShellBrowserHost& host) { return host.m_thumbGeneration.load(); }
static bool IconCell(ShellBrowserHost& host, int index, RECT& cell) { return host.IconCell(index, cell); }
static LRESULT DrawItem(ShellBrowserHost& host, HDC dc, int index) {
NMLVCUSTOMDRAW draw{}; draw.nmcd.hdc = dc; draw.nmcd.dwItemSpec = index; draw.nmcd.dwDrawStage = CDDS_ITEMPREPAINT;
return host.DrawIconItem(&draw);
}
// Hands the UI thread a finished thumbnail result as the worker would.
static void Deliver(ShellBrowserHost& host, int item, const std::wstring& path, const std::wstring& key, UINT generation) {
BITMAPINFO info{}; info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
info.bmiHeader.biWidth = 8; info.bmiHeader.biHeight = -8; info.bmiHeader.biPlanes = 1; info.bmiHeader.biBitCount = 32;
void* bits = nullptr;
HBITMAP bitmap = CreateDIBSection(nullptr, &info, DIB_RGB_COLORS, &bits, nullptr, 0);
{
std::lock_guard<std::mutex> lock(host.m_thumbMutex);
host.m_thumbResults.push_back({key, path, bitmap, item, generation});
}
host.OnThumbsReady();
}
static bool HasThumb(ShellBrowserHost& host, const std::wstring& key) { return host.m_thumbIndex.count(key) != 0; }
static std::wstring Key(ShellBrowserHost& host, int index, std::wstring* pathOut = nullptr) {
IFolderView2* view = View(host); std::wstring key;
IShellItem* item = nullptr;
if (view && SUCCEEDED(view->GetItem(index, IID_PPV_ARGS(&item)))) {
PWSTR path = nullptr;
if (SUCCEEDED(item->GetDisplayName(SIGDN_DESKTOPABSOLUTEPARSING, &path))) {
key = ShellBrowserHost::ThumbKey(item, path, host.m_iconSlot);
if (pathOut) *pathOut = path;
CoTaskMemFree(path);
}
item->Release();
}
if (view) view->Release();
return key;
}
static void Request(ShellBrowserHost& host, int index) {
IFolderView2* view = View(host); IShellItem* item = nullptr;
if (view && SUCCEEDED(view->GetItem(index, IID_PPV_ARGS(&item)))) {
PWSTR path = nullptr;
if (SUCCEEDED(item->GetDisplayName(SIGDN_DESKTOPABSOLUTEPARSING, &path))) {
host.RequestThumb(item, ShellBrowserHost::ThumbKey(item, path, host.m_iconSlot), path, index);
CoTaskMemFree(path);
}
item->Release();
}
if (view) view->Release();
}
static void Cancel(ShellBrowserHost& host) { host.CancelThumbRequests(); }
static void ClearThumbs(ShellBrowserHost& host) { host.ClearItemImages(); }
// LRU on a detached host with synthetic bitmaps (bytes = 64 + w*h*4).
static bool LruEviction() {
ShellBrowserHost host;
auto make = [] {
BITMAPINFO info{}; info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
info.bmiHeader.biWidth = 10; info.bmiHeader.biHeight = -10; info.bmiHeader.biPlanes = 1; info.bmiHeader.biBitCount = 32;
void* bits = nullptr; return CreateDIBSection(nullptr, &info, DIB_RGB_COLORS, &bits, nullptr, 0);
};
host.SetThumbnailCacheLimits(1u << 20, 3);
for (const wchar_t* key : {L"a", L"b", L"c"}) host.StoreThumb(key, make());
HBITMAP touched = nullptr;
bool ok = host.LookupThumb(L"a", touched) && touched; // a becomes most recent
host.StoreThumb(L"d", make()); // evicts b (least recent)
HBITMAP probe = nullptr;
ok = ok && !host.LookupThumb(L"b", probe) && host.LookupThumb(L"a", probe) && host.LookupThumb(L"c", probe)
&& host.LookupThumb(L"d", probe) && host.m_counters.thumbEvictions == 1 && host.m_thumbLru.size() == 3;
// Byte cap: 464 bytes each, 1000-byte cap keeps the two most recent.
host.SetThumbnailCacheLimits(1000, 100);
ok = ok && host.m_thumbLru.size() == 2 && host.m_thumbBytes <= 1000 && host.LookupThumb(L"d", probe)
&& host.m_counters.thumbEvictions == 2;
// Never a clear-all: 300 entries under a generous cap all stay.
host.SetThumbnailCacheLimits(64u << 20, 1000);
for (int i = 0; i < 300; ++i) host.StoreThumb(L"k" + std::to_wstring(i), make());
ok = ok && host.m_thumbLru.size() == 302 && host.LookupThumb(L"k0", probe);
host.ClearItemImages();
return ok && host.m_thumbLru.empty() && host.m_thumbBytes == 0;
}
static bool ShellMediaThumbnail(ShellBrowserHost& host,const std::wstring& path) {
return MediaAspectRatio(host,path,0,0);
}
static bool SkipsGroupThumbnail(ShellBrowserHost& host,int index) {
host.ClearItemImages();
NMLVCUSTOMDRAW draw{};
draw.nmcd.dwItemSpec=index;draw.nmcd.dwDrawStage=CDDS_ITEMPREPAINT;
draw.dwItemType=LVCDI_GROUP;
const auto before=host.m_counters;
return host.DrawIconItem(&draw)==CDRF_DODEFAULT && host.m_thumbLru.empty()
&& host.m_counters.thumbRequests==before.thumbRequests && host.m_counters.syncExtractions==before.syncExtractions;
}
static bool SkipsClippedThumbnail(ShellBrowserHost& host,int index) {
HWND list=host.m_listWindow;
RECT bounds{};GetWindowRect(list,&bounds);
host.ClearItemImages();
SetWindowPos(list,nullptr,0,0,bounds.right-bounds.left,0,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
HDC dc=GetDC(list);
NMLVCUSTOMDRAW draw{};draw.nmcd.hdc=dc;draw.nmcd.dwItemSpec=index;draw.nmcd.dwDrawStage=CDDS_ITEMPREPAINT;
const auto before=host.m_counters;
host.DrawIconItem(&draw);
const bool skipped=host.m_thumbLru.empty() && host.m_thumbPending.empty()
&& host.m_counters.thumbRequests==before.thumbRequests && host.m_counters.syncExtractions==before.syncExtractions;
ReleaseDC(list,dc);
SetWindowPos(list,nullptr,0,0,bounds.right-bounds.left,bounds.bottom-bounds.top,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE);
return skipped;
}
static bool ContainsThumbnail(ShellBrowserHost& host,int index) {
HWND list=host.m_listWindow;
if(!list || !host.m_iconSlot) return false;
RECT bounds{};GetClientRect(list,&bounds);
HDC screen=GetDC(nullptr),dc=CreateCompatibleDC(screen);
HBITMAP bitmap=CreateCompatibleBitmap(screen,bounds.right,bounds.bottom);
auto old=SelectObject(dc,bitmap);
FillRect(dc,&bounds,reinterpret_cast<HBRUSH>(GetStockObject(WHITE_BRUSH)));
NMLVCUSTOMDRAW draw{};draw.nmcd.hdc=dc;draw.nmcd.dwItemSpec=index;draw.nmcd.dwDrawStage=CDDS_ITEMPREPAINT;
host.DrawIconItem(&draw);
SettleThumbs(host);
FillRect(dc,&bounds,reinterpret_cast<HBRUSH>(GetStockObject(WHITE_BRUSH)));
host.DrawIconItem(&draw);
int pixels=0;
for(int y=0;y<bounds.bottom;y+=2) for(int x=0;x<bounds.right;x+=2)
{ const COLORREF color=GetPixel(dc,x,y);
pixels+=GetRValue(color)<80 && GetGValue(color)>60 && GetGValue(color)<150 && GetBValue(color)>140; }
SelectObject(dc,old);DeleteObject(bitmap);DeleteDC(dc);ReleaseDC(nullptr,screen);
return pixels>100;
}
static void DumpVisibleView(ShellBrowserHost& host) {
RECT bounds{};GetClientRect(host.m_listWindow,&bounds);
std::cerr<<"native list="<<host.m_listWindow<<" visible="<<IsWindowVisible(host.m_listWindow)
<<" size="<<bounds.right<<","<<bounds.bottom<<" count="<<(host.m_listWindow?ListView_GetItemCount(host.m_listWindow):-1)<<'\n';
IShellView* view=nullptr;HWND root=nullptr;
if(SUCCEEDED(host.m_browser->GetCurrentView(IID_PPV_ARGS(&view)))){view->GetWindow(&root);view->Release();}
std::cerr<<"view root="<<root<<" visible="<<IsWindowVisible(root)<<'\n';
for(HWND frame=root;frame;frame=GetParent(frame)) {
wchar_t name[64]{};GetClassNameW(frame,name,_countof(name));RECT rc{};GetClientRect(frame,&rc);
std::wcerr<<L"parent="<<name<<L" size="<<rc.right<<L","<<rc.bottom<<L" visible="<<IsWindowVisible(frame)<<L"\n";
if(frame==host.m_parent)break;
}
EnumChildWindows(root,[](HWND child,LPARAM)->BOOL {
wchar_t name[64]{};GetClassNameW(child,name,_countof(name));RECT rectangle{};GetClientRect(child,&rectangle);
std::wcerr<<name<<L" visible="<<IsWindowVisible(child)<<L" size="<<rectangle.right<<L","<<rectangle.bottom<<L"\n";return TRUE;
},0);
}
static bool ContainerVisible(ShellBrowserHost& host) {
IShellView* view = nullptr;
if (FAILED(host.m_browser->GetCurrentView(IID_PPV_ARGS(&view)))) return false;
HWND handle = nullptr; view->GetWindow(&handle); view->Release();
if (!handle) return false;
while (GetParent(handle) && GetParent(handle) != host.m_parent) handle = GetParent(handle);
return (GetWindowLongPtrW(handle, GWL_STYLE) & WS_VISIBLE) != 0;
}
static IFolderView2* View(ShellBrowserHost& host) {
IFolderView2* view = nullptr;
host.m_browser->GetCurrentView(IID_PPV_ARGS(&view));
return view;
}
static HRESULT ActivateSelection(ShellBrowserHost& host) {
IShellView* view=nullptr;
if(FAILED(host.m_browser->GetCurrentView(IID_PPV_ARGS(&view))))return E_FAIL;
const HRESULT result=host.DefaultCommand(view);view->Release();return result;
}
};
namespace DuiLib {
struct TabStripRegressionAccess {
static bool RoundedIcon(const std::wstring& png) {
CTabStripUI strip;strip.SetMetrics(144);strip.Add(L"fixture",L"图片",png,24,true);
Gdiplus::Bitmap canvas(80,54,PixelFormat32bppARGB);
{Gdiplus::Graphics graphics(&canvas);graphics.Clear(Gdiplus::Color(0,0,0,0));
strip.DrawTabIcon(graphics,0,{0,0,200,54});}
Gdiplus::Color corner,center;canvas.GetPixel(15,15,&corner);canvas.GetPixel(27,27,¢er);
return corner.GetAlpha()==0 && center.GetAlpha()==255;
}
static std::vector<LONG> LayoutSnapshot(DuiLib::CTabStripUI& strip) {
std::vector<LONG> result{strip.m_scrollX, strip.m_plus.left, strip.m_plus.right};
for (auto& tab : strip.m_tabs) {
result.insert(result.end(), {tab.body.left, tab.body.right, tab.width});
}
return result;
}
static std::vector<DWORD> PaintPixels(CTabStripUI& strip) {
const RECT bounds=strip.GetPos();const int width=bounds.right,height=bounds.bottom;
BITMAPINFO info{};info.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
info.bmiHeader.biWidth=width;info.bmiHeader.biHeight=-height;
info.bmiHeader.biPlanes=1;info.bmiHeader.biBitCount=32;info.bmiHeader.biCompression=BI_RGB;
HDC screen=GetDC(nullptr),dc=CreateCompatibleDC(screen);void* pixels=nullptr;
HBITMAP bitmap=CreateDIBSection(screen,&info,DIB_RGB_COLORS,&pixels,nullptr,0);
std::vector<DWORD> result;
if(bitmap && pixels) {
auto old=SelectObject(dc,bitmap);RECT canvas{0,0,width,height};
FillRect(dc,&canvas,reinterpret_cast<HBRUSH>(GetStockObject(WHITE_BRUSH)));
strip.DoPaint(dc,canvas,nullptr);GdiFlush();
result.assign(static_cast<DWORD*>(pixels),static_cast<DWORD*>(pixels)+width*height);
SelectObject(dc,old);
}
if(bitmap)DeleteObject(bitmap);DeleteDC(dc);ReleaseDC(nullptr,screen);return result;
}
static bool NoAutomaticMotion(CTabStripUI& strip,UINT dpi) {
strip.Clear();strip.SetMetrics(dpi);strip.SetDarkMode(false);
strip.SetPos({0,0,1000,MulDiv(29,dpi,96)},false);
auto stable=[&] {
const auto layout=LayoutSnapshot(strip);
const auto first=PaintPixels(strip);
Sleep(180);TEventUI tick{};tick.Type=UIEVENT_TIMER;tick.wParam=1;strip.DoEvent(tick);
return !first.empty() && first==PaintPixels(strip) && layout==LayoutSnapshot(strip);
};
strip.Add(L"C:\\",L"C:",L"",MulDiv(16,dpi,96),true);
strip.Add(L"D:\\",L"Program Files",L"",MulDiv(16,dpi,96),false);
bool ok=stable();
strip.Insert(1,L"E:\\",L"新磁盘",L"",MulDiv(16,dpi,96));ok=stable() && ok;
strip.SetActiveTab(1);ok=stable() && ok;
strip.SetTabTitle(1,L"新文件夹 — longer title");ok=stable() && ok;
strip.Reorder(1,2);ok=stable() && ok;
strip.RemoveAt(1);ok=stable() && ok;
const POINT plus{(strip.m_plus.left+strip.m_plus.right)/2,(strip.m_plus.top+strip.m_plus.bottom)/2};
ok=strip.HitTest(plus).part==CTabStripUI::Part::Plus && strip.m_plus.left>strip.m_tabs.back().body.right && ok;
for(int i=0;i<12;++i)strip.Add(std::to_wstring(i),L"Overflow folder",L"",MulDiv(16,dpi,96),true);
strip.EnsureTabVisible(0);const int scroll=strip.m_scrollX;
TEventUI wheel{};wheel.Type=UIEVENT_SCROLLWHEEL;wheel.wParam=SB_LINEDOWN;strip.DoEvent(wheel);
ok=strip.m_scrollX>scroll && stable() && ok;
return ok;
}
static bool SeparatorPixels(DuiLib::CTabStripUI& strip,UINT dpi,bool dark) {
strip.Clear();strip.SetMetrics(dpi);strip.SetDarkMode(dark);
for(int i=0;i<3;++i)strip.Add(std::to_wstring(i),L"标签",L"",MulDiv(16,dpi,96),i==2);
const int width=MulDiv(1000,dpi,96),height=MulDiv(29,dpi,96);strip.SetPos({0,0,width,height},false);
HDC screen=GetDC(nullptr),dc=CreateCompatibleDC(screen);
HBITMAP bitmap=CreateCompatibleBitmap(screen,width,height);auto old=SelectObject(dc,bitmap);
RECT canvas{0,0,width,height};FillRect(dc,&canvas,reinterpret_cast<HBRUSH>(GetStockObject(WHITE_BRUSH)));
strip.DoPaint(dc,canvas,nullptr);
const int x=strip.m_tabs[0].body.right+MulDiv(UiTokens::TabCardGap,dpi,96)/2;
const COLORREF expected=dark ? RGB(0x50,0x50,0x50):RGB(0xcf,0xcf,0xcf);
const bool line=GetPixel(dc,x,height/2)==expected && GetPixel(dc,x,height/2- MulDiv(10,dpi,96))!=expected;
const bool seam=strip.m_tabs[0].body.left==0 && GetPixel(dc,0,height/2)==GetPixel(dc,1,height/2);
SelectObject(dc,old);DeleteObject(bitmap);DeleteDC(dc);ReleaseDC(nullptr,screen);
strip.SetDarkMode(false);return line && seam && strip.GetFixedHeight()==height && strip.m_plus.top>=0 && strip.m_plus.bottom<=height;
}
static bool Check(DuiLib::CTabStripUI& strip) {
const std::wstring longName(80,L'长');
for(UINT dpi:{96u,144u,192u}) {
strip.Clear();strip.SetMetrics(dpi);
strip.SetTabWidthRange(UiTokens::TabMinW,UiTokens::TabSelMinW,UiTokens::TabMaxW);
strip.Add(L"D:\\"+longName,L"中文 "+longName+L"尾部甲",L"",MulDiv(16,dpi,96),true);
strip.Add(L"D:\\短",L"短",L"",MulDiv(16,dpi,96),false);
strip.SetPos({0,0,1200,MulDiv(29,dpi,96)},false);
const int expected=MulDiv(180,dpi,96);
if(strip.m_tabs[0].width!=expected || strip.m_tabs[1].width!=expected)return false;
const auto before=PaintPixels(strip);
strip.SetTabTitle(0,L"中文 "+longName+L"尾部乙");
if(before.empty() || before!=PaintPixels(strip))return false; // hidden suffix changes no pixels
strip.SetActiveTab(1);
if(strip.m_tabs[0].width!=expected || strip.m_tabs[1].width!=expected)return false;
const auto close=strip.m_tabs[0].close;
const auto hit=strip.HitTest({(close.left+close.right)/2,(close.top+close.bottom)/2});
if(hit.part!=CTabStripUI::Part::Close || hit.index!=0)return false;
TEventUI hover{};hover.Type=UIEVENT_MOUSEMOVE;
hover.ptMouse={strip.m_tabs[0].body.left+MulDiv(15,dpi,96),strip.GetPos().bottom/2};
strip.DoEvent(hover);
if(std::wstring(strip.GetToolTip())!=strip.m_tabs[0].path)return false;
strip.SetPos({0,0,MulDiv(220,dpi,96),MulDiv(29,dpi,96)},false);
strip.SetActiveTab(0);strip.SetActiveTab(1);
if(strip.m_tabs[0].width!=expected || strip.m_tabs[1].width!=expected
|| strip.m_scrollX<=0 || strip.m_plus.right>strip.GetPos().right)return false;
}
return true;
}
static bool CheckPinningAndEnhancedTabs(DuiLib::CTabStripUI& strip) {
for (UINT dpi : { 96u, 144u }) {
strip.Clear();
strip.SetMetrics(dpi);
strip.SetTabWidthRange(UiTokens::TabMinW, UiTokens::TabSelMinW, UiTokens::TabMaxW);
strip.Add(L"C:\\Pinned", L"固定标签", L"", MulDiv(16, dpi, 96), true, true);
strip.Add(L"D:\\Normal1", L"普通1", L"", MulDiv(16, dpi, 96), false, false);
strip.Add(L"E:\\Normal2", L"普通2", L"", MulDiv(16, dpi, 96), false, false);
strip.SetPos({ 0, 0, 1200, MulDiv(29, dpi, 96) }, false);
if (strip.GetPinnedCount() != 1) return false;
if (!strip.IsTabPinned(0) || strip.IsTabPinned(1) || strip.IsTabPinned(2)) return false;
const int expectedPinW = MulDiv(40, dpi, 96);
if (strip.m_tabs[0].width != expectedPinW) return false;
if (strip.m_tabs[0].close.right != 0) return false;
const POINT ptOnPin = { (strip.m_tabs[0].body.left + strip.m_tabs[0].body.right) / 2,
(strip.m_tabs[0].body.top + strip.m_tabs[0].body.bottom) / 2 };
if (strip.HitTest(ptOnPin).part != CTabStripUI::Part::Body) return false;
strip.Reorder(0, 2);
if (!strip.IsTabPinned(0)) return false;
strip.Reorder(2, 0);
if (!strip.IsTabPinned(0) || strip.m_tabs[1].path != L"E:\\Normal2") return false;
strip.SetTabPinned(0, false);
if (strip.GetPinnedCount() != 0 || strip.IsTabPinned(0)) return false;
const int normalW = MulDiv(180, dpi, 96);
if (strip.m_tabs[0].width != normalW) return false;
if (strip.m_tabs[0].close.right == 0) return false;
}
return true;
}
};
}
// A provider that implements owner drawing through IContextMenu3 only, plus
// a legacy mode. Deliberately leaves GDI state changed like an extension can.
class ShellMenuDrawingFixture : public IContextMenu3 {
public:
bool modern = true;
bool modernUnavailable = false;
HRESULT status = S_OK;
int modernCalls = 0, legacyCalls = 0, measures = 0, draws = 0;
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void** out) override {
if (!out) return E_POINTER;
*out = nullptr;
if (iid == IID_IUnknown || iid == IID_IContextMenu || iid == IID_IContextMenu2 || (modern && iid == IID_IContextMenu3)) {
*out = static_cast<IContextMenu3*>(this); AddRef(); return S_OK;
}
return E_NOINTERFACE;
}
ULONG STDMETHODCALLTYPE AddRef() override { return ++refs; }
ULONG STDMETHODCALLTYPE Release() override { return --refs; }
HRESULT STDMETHODCALLTYPE QueryContextMenu(HMENU menu, UINT pos, UINT first, UINT, UINT) override {
InsertMenuW(menu, pos, MF_BYPOSITION | MF_OWNERDRAW, first, reinterpret_cast<LPCWSTR>(this));
InsertMenuW(menu, pos + 1, MF_BYPOSITION | MF_STRING, first + 1, L"正常中文菜单");
return MAKE_HRESULT(SEVERITY_SUCCESS, 0, 2);
}
HRESULT STDMETHODCALLTYPE InvokeCommand(LPCMINVOKECOMMANDINFO) override { return E_NOTIMPL; }
HRESULT STDMETHODCALLTYPE GetCommandString(UINT_PTR, UINT, UINT*, LPSTR, UINT) override { return E_NOTIMPL; }
HRESULT STDMETHODCALLTYPE HandleMenuMsg(UINT message, WPARAM, LPARAM data) override {
++legacyCalls;
return modern && !modernUnavailable ? E_NOTIMPL : Process(message, data, nullptr);
}
HRESULT STDMETHODCALLTYPE HandleMenuMsg2(UINT message, WPARAM, LPARAM data, LRESULT* result) override {
++modernCalls;
return modernUnavailable ? E_NOTIMPL : Process(message, data, result);
}
private:
ULONG refs = 1;
HRESULT Process(UINT message, LPARAM data, LRESULT* result) {
if (status != S_OK) return status;
if (result) *result = 0;
if (message == WM_MEASUREITEM) {
auto* item = reinterpret_cast<MEASUREITEMSTRUCT*>(data);
item->itemWidth = 240; item->itemHeight = 36; ++measures;
if (result) *result = TRUE;
} else if (message == WM_DRAWITEM) {
auto* item = reinterpret_cast<DRAWITEMSTRUCT*>(data);
RECT text = item->rcItem;
DrawTextW(item->hDC, L"第三方中文菜单", -1, &text, DT_SINGLELINE | DT_VCENTER);
++draws;
// The next standard item must not inherit this font, color or clip.
SelectObject(item->hDC, GetStockObject(SYSTEM_FIXED_FONT));
SetTextColor(item->hDC, RGB(12, 34, 56));
SetBkMode(item->hDC, OPAQUE);
IntersectClipRect(item->hDC, 0, 0, 1, 1);
if (result) *result = TRUE;
} else if (message == WM_MENUCHAR && result) {
*result = MAKELRESULT(1, MNC_EXECUTE);
}
return S_OK;
}
};
struct MainWndRegressionAccess {
static void ClearUndoStacks(CMainWnd& window) {
window.m_undoStack.clear();
window.m_redoStack.clear();
}
inline static CMainWnd* menuCaptureOwner = nullptr;
inline static std::wstring menuCapturePath;
static void CALLBACK CaptureOwnedMenu(HWND, UINT, UINT_PTR timer, DWORD) {
KillTimer(nullptr, timer);
HWND popup = nullptr;
EnumThreadWindows(GetCurrentThreadId(), [](HWND candidate, LPARAM out)->BOOL {
wchar_t cls[64]{}; GetClassNameW(candidate, cls, _countof(cls));
if (IsWindowVisible(candidate) && wcscmp(cls, L"#32768") == 0) {
*reinterpret_cast<HWND*>(out) = candidate; return FALSE;
}
return TRUE;
}, reinterpret_cast<LPARAM>(&popup));
if (popup && menuCaptureOwner) {
RECT rect{}; GetWindowRect(popup, &rect);
HDC screen = GetDC(popup), dc = CreateCompatibleDC(screen);
HBITMAP bitmap = CreateCompatibleBitmap(screen, rect.right - rect.left, rect.bottom - rect.top);
HGDIOBJ previous = SelectObject(dc, bitmap);
const BOOL printed = PrintWindow(popup, dc, 0);
CLSID png{};
if (printed && menuCaptureOwner->GetPngEncoderClsid(&png)) {
Gdiplus::Bitmap image(bitmap, nullptr);
image.Save(menuCapturePath.c_str(), &png, nullptr);
}
SelectObject(dc, previous); DeleteObject(bitmap); DeleteDC(dc); ReleaseDC(popup, screen);
}
EndMenu();
}
static int DiagnoseQuickMenu(CMainWnd& window, const std::vector<CMainWnd::QuickRow>& rows, const std::wstring& directory) {
if (rows.empty()) return 1;
window.StopQuickAccessSync();
ShowWindow(window.m_hWnd, SW_SHOWNOACTIVATE);
RECT owner{}; GetWindowRect(window.m_hWnd, &owner);
const POINT point{owner.left + 80, owner.top + 80};
const auto& row = rows.front();
auto dump = [&](const char* tag, HMENU popup) {
MENUINFO info{}; info.cbSize = sizeof(info); info.fMask = MIM_STYLE; GetMenuInfo(popup, &info);
std::cout << tag << " style=" << info.dwStyle << " rows=" << GetMenuItemCount(popup) << '\n';
for (int i = 0; i < GetMenuItemCount(popup); ++i) {
wchar_t text[512]{}; MENUITEMINFOW item{}; item.cbSize = sizeof(item);
item.fMask = MIIM_ID | MIIM_FTYPE | MIIM_BITMAP | MIIM_STRING;
item.dwTypeData = text; item.cch = _countof(text);
GetMenuItemInfoW(popup, i, TRUE, &item);
char utf8[2048]{}; WideCharToMultiByte(CP_UTF8, 0, text, -1, utf8, sizeof(utf8), nullptr, nullptr);
std::cout << " " << i << " id=" << item.wID << " type=" << item.fType
<< " callback=" << (item.hbmpItem == HBMMENU_CALLBACK) << " text=" << utf8 << '\n';
}
};
menuCaptureOwner = &window;
for (int variant = 0; variant < 3; ++variant) {
IContextMenu* menu = nullptr; HMENU popup = nullptr; UINT last = 0;
if (variant < 2) {
auto* absolute = reinterpret_cast<PCIDLIST_ABSOLUTE>(row.shellId.data());
IShellFolder* parent = nullptr; PCUITEMID_CHILD child = nullptr;
if (FAILED(SHBindToParent(absolute, IID_PPV_ARGS(&parent), &child))) return 1;
const HRESULT ui = parent->GetUIObjectOf(window.m_hWnd, 1, &child, IID_IContextMenu, nullptr, reinterpret_cast<void**>(&menu));
parent->Release(); if (FAILED(ui)) return 1;
popup = CreatePopupMenu();
const HRESULT queried = menu->QueryContextMenu(popup, 0, 1, 0x7fff, CMF_NORMAL);
if (FAILED(queried)) { DestroyMenu(popup); menu->Release(); return 1; }
last = 1 + HRESULT_CODE(queried);
} else if (!window.BuildShellItemMenu({row.path}, &menu, &popup, &last)) return 1;
const char* tag = variant == 0 ? "home-raw" : variant == 1 ? "home-current" : "filesystem";
dump(tag, popup);
menuCapturePath = directory + (variant == 0 ? L"\\home-raw.png" : variant == 1 ? L"\\home-current.png" : L"\\filesystem.png");
const UINT_PTR timer = SetTimer(nullptr, 0, 350, CaptureOwnedMenu);
if (variant == 0) {
// Untouched provider layout: no separator normalization or additions.
window.m_pCtxMenu = menu;
menu->QueryInterface(IID_PPV_ARGS(&window.m_pCtxMenu2));
menu->QueryInterface(IID_PPV_ARGS(&window.m_pCtxMenu3));
TrackPopupMenuEx(popup, TPM_RETURNCMD | TPM_RIGHTBUTTON, point.x, point.y, window.m_hWnd, nullptr);
if (window.m_pCtxMenu3) window.m_pCtxMenu3->Release();
if (window.m_pCtxMenu2) window.m_pCtxMenu2->Release();
window.m_pCtxMenu = nullptr; window.m_pCtxMenu2 = nullptr; window.m_pCtxMenu3 = nullptr;
} else {
window.TrackPopupShellMenu(menu, popup, point, 1, last);
}
KillTimer(nullptr, timer); dump(tag, popup);
DestroyMenu(popup); menu->Release();
}
menuCaptureOwner = nullptr;
return 0;
}
static int CheckShellMenuDrawing(CMainWnd& window) {
int failures = 0;
auto check = [&](bool ok, const char* name) { if (!ok) { ++failures; std::cerr << "FAIL " << name << '\n'; } };
HDC screen = GetDC(window.m_hWnd), dc = CreateCompatibleDC(screen);
HBITMAP bitmap = CreateCompatibleBitmap(screen, 260, 48);
HGDIOBJ previous = SelectObject(dc, bitmap);
for (bool modern : {true, false}) {
ShellMenuDrawingFixture menu; menu.modern = modern;
window.m_pCtxMenu2 = &menu;
window.m_pCtxMenu3 = modern ? &menu : nullptr;
MEASUREITEMSTRUCT measure{}; measure.CtlType = ODT_MENU;
LRESULT result = -7; bool handled = false;
window.ForwardShellMenuMessage(WM_MEASUREITEM, 0, reinterpret_cast<LPARAM>(&measure), &result, &handled);
check(handled && result == TRUE && measure.itemHeight == 36 && measure.itemWidth == 240,
modern ? "IContextMenu3 measures owner-drawn rows and returns its result" : "IContextMenu2 measurement returns TRUE");
DRAWITEMSTRUCT draw{}; draw.CtlType = ODT_MENU; draw.hDC = dc; draw.rcItem = {0, 0, 260, 48};
RECT clipBefore{}, clipAfter{}; GetClipBox(dc, &clipBefore);
const auto font = GetCurrentObject(dc, OBJ_FONT);
const auto color = GetTextColor(dc); const int mode = GetBkMode(dc);
result = -7; handled = false;
window.ForwardShellMenuMessage(WM_DRAWITEM, 0, reinterpret_cast<LPARAM>(&draw), &result, &handled);
GetClipBox(dc, &clipAfter);
check(handled && result == TRUE && menu.draws == 1, "menu drawing is handled exactly once");
check(GetCurrentObject(dc, OBJ_FONT) == font && GetTextColor(dc) == color && GetBkMode(dc) == mode
&& EqualRect(&clipBefore, &clipAfter), "extension drawing cannot leak GDI state into following rows");
if (modern) {
result = -7; handled = false;
window.ForwardShellMenuMessage(WM_MENUCHAR, 0, 0, &result, &handled);
check(handled && result == MAKELRESULT(1, MNC_EXECUTE) && menu.legacyCalls == 0,
"modern menu keyboard result is preserved without dispatching legacy messages");
}
const int before = menu.modernCalls + menu.legacyCalls;
measure.CtlType = ODT_BUTTON; handled = false;
window.ForwardShellMenuMessage(WM_MEASUREITEM, 0, reinterpret_cast<LPARAM>(&measure), &result, &handled);
check(!handled && before == menu.modernCalls + menu.legacyCalls, "menu routing leaves owner-drawn controls alone");
measure.CtlType = ODT_MENU; menu.status = S_FALSE; handled = false;
window.ForwardShellMenuMessage(WM_MEASUREITEM, 0, reinterpret_cast<LPARAM>(&measure), &result, &handled);
check(!handled, "S_FALSE is not reported as a handled menu message");
if (modern) {
menu.status = S_OK; menu.modernUnavailable = true;
measure.itemHeight = 0; handled = false; result = -7;
window.ForwardShellMenuMessage(WM_MEASUREITEM, 0, reinterpret_cast<LPARAM>(&measure), &result, &handled);
check(handled && result == TRUE && measure.itemHeight == 36,
"unimplemented modern message falls back to the available legacy handler");
}
window.m_pCtxMenu2 = nullptr; window.m_pCtxMenu3 = nullptr;
// Baseline implementation intentionally leaks state; reset the test DC
// so the next case still starts with a valid normal drawing context.
SelectClipRgn(dc, nullptr); SelectObject(dc, font); SetTextColor(dc, color); SetBkMode(dc, mode);
}
// Exercise the actual TrackPopupMenu message loop with the modern-only
// provider: cancelled popup never invokes a user command.
const bool shown = IsWindowVisible(window.m_hWnd) != FALSE;
if (!shown) ShowWindow(window.m_hWnd, SW_SHOWNOACTIVATE);
ShellMenuDrawingFixture popupMenu;
HMENU popup = CreatePopupMenu(); popupMenu.QueryContextMenu(popup, 0, 1, 0x7fff, CMF_NORMAL);
// Shell extensions may replace separator-only lazy submenu placeholders
// on WM_INITMENUPOPUP. The host must not empty those provider-owned menus.
HMENU lazySubmenu = CreatePopupMenu();
AppendMenuW(lazySubmenu, MF_SEPARATOR, 0, nullptr);
AppendMenuW(popup, MF_POPUP, reinterpret_cast<UINT_PTR>(lazySubmenu), L"延迟加载子菜单");
RECT owner{}; GetWindowRect(window.m_hWnd, &owner);
const UINT_PTR timer = SetTimer(nullptr, 0, 250, [](HWND, UINT, UINT_PTR id, DWORD) { EndMenu(); KillTimer(nullptr, id); });
check(timer != 0, "owner-draw popup cancellation timer starts");
if (timer) {
window.TrackPopupShellMenu(&popupMenu, popup, {owner.left + 80, owner.top + 80}, 1, 3);
KillTimer(nullptr, timer);
check(popupMenu.measures > 0 && popupMenu.draws > 0 && popupMenu.legacyCalls == 0,
"real popup measures and paints modern-only Chinese owner-drawn entries");
check(!window.m_pCtxMenu2 && !window.m_pCtxMenu3, "popup releases active drawing interfaces on close");
check(GetMenuItemCount(lazySubmenu) == 1,
"popup preserves provider-owned lazy submenu placeholders");
}
DestroyMenu(popup);
if (!shown) ShowWindow(window.m_hWnd, SW_HIDE);
SelectObject(dc, previous); DeleteObject(bitmap); DeleteDC(dc); ReleaseDC(window.m_hWnd, screen);
return failures;
}
static void ConfigureQuickFixture(CMainWnd& window, const std::wstring& source) {
window.m_quickReadSource = source;
}
static bool WaitQuickFixture(CMainWnd& window) {
const ULONGLONG deadline = GetTickCount64() + 10000;
while (window.m_quickReadPending && GetTickCount64() < deadline) {
MSG msg{};
while (PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) {
if (msg.message != WM_QUIT && !CPaintManagerUI::TranslateMessage(&msg)) { TranslateMessage(&msg); DispatchMessageW(&msg); }
}
Sleep(10);
}
return !window.m_quickReadPending;
}
static int CheckSystemQuickAccess(CMainWnd& window, const std::wstring& fixture) {
int failures = 0;
auto check = [&](bool ok, const char* name) { if (!ok) { ++failures; std::cerr << "FAIL " << name << '\n'; } };
const ULONGLONG deadline = GetTickCount64() + 10000;
while (window.m_quickReadPending && GetTickCount64() < deadline) {
MSG msg{};
while (PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessageW(&msg); }
Sleep(10);
}
check(!window.m_quickReadPending, "background Shell snapshot completes");
window.StopQuickAccessSync();
std::vector<CMainWnd::QuickRow> systemRows;
const HRESULT readSystem = CMainWnd::ReadSystemQuickRows(systemRows);
check(SUCCEEDED(readSystem), "read live Windows Home namespace without changing pins or privacy");
wchar_t captureDirectory[32768]{};
if (GetEnvironmentVariableW(L"FASTFILE_QUICK_MENU_DIAGNOSTICS", captureDirectory, _countof(captureDirectory)))
return DiagnoseQuickMenu(window, systemRows, captureDirectory);
IShellDispatch* systemShell = nullptr;
Folder* systemFolder = nullptr;
FolderItems* systemItems = nullptr;
VARIANT home{}; home.vt = VT_BSTR;
home.bstrVal = SysAllocString(L"shell:::{f874310e-b6b7-47dc-bc84-b9e6b38f5903}");
HRESULT automation = CoCreateInstance(CLSID_Shell, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&systemShell));
if (SUCCEEDED(automation)) automation = systemShell->NameSpace(home, &systemFolder);
if (SUCCEEDED(automation) && systemFolder) automation = systemFolder->Items(&systemItems);
long systemCount = -1;
if (systemItems) automation = systemItems->get_Count(&systemCount);
check(SUCCEEDED(automation) && systemCount == long(systemRows.size()),
"live snapshot count matches independent Shell.Application Home enumeration");
if (systemItems && systemCount == long(systemRows.size())) {
for (long i = 0; i < systemCount; ++i) {
VARIANT index{}; index.vt = VT_I4; index.lVal = i;
FolderItem* item = nullptr;
BSTR name = nullptr; VARIANT_BOOL isFolder = VARIANT_FALSE;
HRESULT itemHr = systemItems->Item(index, &item);
if (SUCCEEDED(itemHr) && item) itemHr = item->get_Name(&name);
if (item) item->get_IsFolder(&isFolder);
check(SUCCEEDED(itemHr) && name && systemRows[size_t(i)].label == name
&& systemRows[size_t(i)].isFolder == (isFolder != VARIANT_FALSE),
"live ordering, names and item types match the independent system enumeration");
if (name) SysFreeString(name);
if (item) item->Release();
}
}
std::cout << "System Home snapshot: " << systemRows.size() << " entries (paths omitted)\n";
if (systemItems) systemItems->Release();
if (systemFolder) systemFolder->Release();
if (systemShell) systemShell->Release();
VariantClear(&home);
if (!systemRows.empty()) {
CMainWnd::QuickSnapshot live; live.result = S_OK; live.rows = systemRows;
window.ApplyQuickSnapshot(live);
check(!window.m_quickRows.empty() && window.m_quickRows.front().shellId == systemRows.front().shellId,
"live quick row popup keeps the Windows Home parent identity");
const bool shown = IsWindowVisible(window.m_hWnd) != FALSE;
if (!shown) ShowWindow(window.m_hWnd, SW_SHOWNOACTIVATE);
RECT owner{}; GetWindowRect(window.m_hWnd, &owner);
const UINT_PTR timer = SetTimer(nullptr, 0, 250, [](HWND, UINT, UINT_PTR id, DWORD) { EndMenu(); KillTimer(nullptr, id); });
check(timer != 0, "live Home popup cancellation timer starts");
if (timer) {
// Query and paint only; never choose a verb on a user item.
window.ShowQuickRowContextMenu(0, {owner.left + 80, owner.top + 80});
KillTimer(nullptr, timer);
check(!window.m_pCtxMenu2 && !window.m_pCtxMenu3, "real Home row menu closes with drawing interfaces cleared");
}
{
// Same row through the track seam: exactly the Windows Home item menu, no extras.
RawShellMenu raw; bool same = false; int calls = 0;
const UINT flags = CMainWnd::ShellItemMenuFlags(false, false);
if (raw.Item(reinterpret_cast<PCIDLIST_ABSOLUTE>(window.m_quickRows.front().shellId.data()), window.m_hWnd)) {
if (window.m_shellBrowser) window.m_shellBrowser->SiteContextMenu(raw.menu);
raw.Query(flags);
}
window.m_trackMenuHook = [&](IContextMenu*, HMENU shownPopup) -> UINT {
++calls; same = raw.popup && SameShellMenu(shownPopup, raw.popup); return 0u;
};
window.ShowQuickRowContextMenu(0, {owner.left + 80, owner.top + 80});
window.m_trackMenuHook = nullptr;
check(calls == 1 && same && window.m_lastShellMenuFlags == flags,
"live Quick Access row menu is the unmodified Windows Home item menu (no FastFile extras)");
}
if (!shown) ShowWindow(window.m_hWnd, SW_HIDE);
}
// Only this run's freshly-created temporary directory is changed. Never
// unpin existing user items; the guard removes our own pin on every exit.
const std::wstring pinFixture = fixture + L"\\FastFile-QuickAccess-Pin-Test";
CreateDirectoryW(pinFixture.c_str(), nullptr);
auto findPin = [&](std::vector<CMainWnd::QuickRow>& entries) -> int {
for (size_t i = 0; i < entries.size(); ++i)
if (CMainWnd::PathEquals(entries[i].path, pinFixture) && entries[i].pinned) return int(i);
return -1;
};
auto removeOwnedPin = [&] {
std::vector<CMainWnd::QuickRow> entries;
if (SUCCEEDED(CMainWnd::ReadSystemQuickRows(entries))) {
const int index = findPin(entries);
if (index >= 0) return CMainWnd::InvokeQuickVerb(nullptr, entries[size_t(index)].shellPath,
"unpinfromhome", entries[size_t(index)].shellId);
}
return S_FALSE;
};
auto cleanup = std::unique_ptr<int, std::function<void(int*)>>(reinterpret_cast<int*>(1), [&](int*) { removeOwnedPin(); });
const HRESULT pinResult = CMainWnd::InvokeQuickVerb(nullptr, pinFixture, "pintohome");
check(SUCCEEDED(pinResult), "real system pin verb accepts only the owned temporary fixture");
int pinnedIndex = -1;