Repository navigation
Expand file tree
/
Copy pathMainWnd.Tabs.cpp
More file actions
990 lines (921 loc) · 36.5 KB
/
Copy pathMainWnd.Tabs.cpp
File metadata and controls
990 lines (921 loc) · 36.5 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
// FastFile - tab strip, session persistence, per-folder view memory
// Implements CMainWnd members moved out of the original monolithic MainWnd.cpp.
// Behaviour is unchanged; declarations live in MainWnd.h.
#include "MainWndInternal.h"
#include "FavoriteStarUI.h"
// ---- Tabs ----------------------------------------------------------------
void CMainWnd::InitTabs()
{
m_tabs.clear();
m_activeTab = -1;
if (m_pTabStrip) {
m_pTabStrip->SetBarHeight(m_settings.tabHeight);
m_pTabStrip->SetWidthPercent(m_settings.tabWidthPercent);
m_pTabStrip->SetMetrics(static_cast<int>(m_dpi));
m_pTabStrip->Clear();
}
}
std::wstring CMainWnd::TabTitleForPath(const std::wstring& path) const
{
if (IsThisPcPath(path))
return L"此电脑";
std::wstring leaf = GetShellDisplayName(path);
if (path.size() <= 3 && path.size() >= 2 && path[1] == L':') return path.substr(0, 2);
if (leaf.empty()) leaf = GetLeafName(path);
if (leaf.empty()) {
if (path.size() >= 2 && path[1] == L':')
return path.substr(0, 2);
return L"标签";
}
return leaf;
}
void CMainWnd::RebuildTabStrip()
{
if (!m_pTabStrip) return;
m_updatingTabs = true;
// The strip is a self-drawn control: hand it the model (path / title / shell icon) and it
// sizes, hit-tests and paints the tabs itself (see TabStripUI.cpp).
const int tabIconPx = DpiScale(UiTokens::TabIconPx);
m_pTabStrip->SetBarHeight(m_settings.tabHeight);
m_pTabStrip->SetWidthPercent(m_settings.tabWidthPercent);
m_pTabStrip->SetMetrics(static_cast<int>(m_dpi));
const int tabWidth=MulDiv(120,m_settings.tabWidthPercent,100);
m_pTabStrip->SetTabWidthRange(tabWidth,tabWidth,tabWidth);
m_pTabStrip->Clear();
for (int i = 0; i < static_cast<int>(m_tabs.size()); ++i) {
const std::wstring title = TabTitleForPath(m_tabs[i].path);
std::wstring icon = IsThisPcPath(m_tabs[i].path)
? GetStockIconBmp(SIID_DESKTOPPC, tabIconPx)
: GetShellIconBmp(m_tabs[i].path, true, tabIconPx);
if (icon.empty()) icon = GetStockIconBmp(SIID_FOLDER, tabIconPx);
m_pTabStrip->Add(m_tabs[i].path, title, icon, tabIconPx, i == m_activeTab, m_tabs[i].isPinned);
m_tabs[i].button = nullptr;
}
m_pTabStrip->NeedParentUpdate();
m_updatingTabs = false;
}
int CMainWnd::FindTabForPath(const std::wstring& path) const
{
const auto target = IsThisPcPath(path) || path == L"此电脑" ? std::wstring(kThisPcPath) : NormalizePath(path);
for (int i = 0; i < static_cast<int>(m_tabs.size()); ++i) {
const auto candidate = IsThisPcPath(m_tabs[i].path) ? m_tabs[i].path : NormalizePath(m_tabs[i].path);
if (PathEquals(candidate, target)) return i;
}
return -1;
}
void CMainWnd::AddTab(const std::wstring& path, bool activate, bool forceNew)
{
std::wstring target = path.empty() ? GetDefaultStartPath() : path;
if (target == L"此电脑")
target = kThisPcPath;
else if (!IsThisPcPath(target)) {
const std::wstring normalized = NormalizePath(target);
if (!normalized.empty())
target = normalized;
}
// All open-folder entry points share one directory / one tab, including + and Ctrl+T.
const int existing = FindTabForPath(target);
if (!forceNew && m_settings.reuseTabs && existing >= 0) {
if (activate && existing != m_activeTab) ActivateTab(existing);
return;
}
// Opening descendants continues the current browsing chain. Keep the exact
// existing-target lookup above this so another open tab still wins.
if (!forceNew && !m_openingExternalPaths && activate && m_activeTab >= 0 && m_activeTab < static_cast<int>(m_tabs.size()) &&
!IsThisPcPath(target) && !IsThisPcPath(m_currentPath)) {
std::wstring parent = NormalizePath(m_currentPath);
if (!parent.empty()) {
if (parent.back() != L'\\') parent.push_back(L'\\');
if (target.size() > parent.size() &&
_wcsnicmp(target.c_str(), parent.c_str(), parent.size()) == 0) {
NavigateToNow(target, true);
return;
}
}
}
TabInfo tab;
tab.path = target;
m_tabs.push_back(tab);
if (activate)
ActivateTab(static_cast<int>(m_tabs.size()) - 1);
else
RebuildTabStrip();
}
std::wstring CMainWnd::NewTabTargetForSelection() const
{
ClipboardItem selected;
bool haveSelected = false;
// The virtual details view owns its own selection/cursor. Prefer its cursor only while
// it remains selected: Ctrl-click can deliberately remove the cursor item from a range.
if (m_viewMode == ViewMode::Details
&& m_detailsCur >= 0 && m_detailsCur < static_cast<int>(m_detailsEntries.size())
&& m_detailsCur < static_cast<int>(m_detailsSel.size()) && m_detailsSel[m_detailsCur]) {
selected.path = m_detailsEntries[m_detailsCur].fullPath;
selected.isDir = m_detailsEntries[m_detailsCur].isDir;
haveSelected = true;
}
// Icon/list focus is the most recently clicked item, which is the intended target when
// a multi-selection exists. Fall back to the selected collection only if focus is gone.
if (!haveSelected && IsTileViewMode() && m_pIconTiles) {
CControlUI* focus = m_PaintManager.GetFocus();
while (focus && focus->GetParent() != m_pIconTiles)
focus = focus->GetParent();
if (focus && (focus->GetTag() & 0x100) != 0 && !focus->GetUserData().IsEmpty()) {
selected.path = focus->GetUserData().GetData();
selected.isDir = (focus->GetTag() & 1) != 0;
haveSelected = true;
}
}
if (!haveSelected && m_viewMode != ViewMode::Details && m_pFileList) {
const int current = m_pFileList->GetCurSel();
CControlUI* row = current >= 0 ? m_pFileList->GetItemAt(current) : nullptr;
IListItemUI* item = row ? static_cast<IListItemUI*>(row->GetInterface(DUI_CTR_ILISTITEM)) : nullptr;
if (row && item && item->IsSelected() && !row->GetUserData().IsEmpty()) {
selected.path = row->GetUserData().GetData();
selected.isDir = row->GetTag() != 0;
haveSelected = true;
}
}
if (!haveSelected) {
std::vector<ClipboardItem> items;
CollectSelectedItems(items);
if (!items.empty()) {
selected = items.front();
haveSelected = true;
}
}
if (haveSelected) {
if (selected.isDir) {
const std::wstring folder = NormalizePath(selected.path);
if (!folder.empty())
return folder;
} else {
const std::wstring parent = ParentPath(selected.path);
if (!parent.empty())
return parent;
}
}
return m_currentPath.empty() ? GetDefaultStartPath() : m_currentPath;
}
void CMainWnd::OnNewTabRequested()
{
AddTab(NewTabTargetForSelection(), true);
}
// ---- CTabStripUI notifications -------------------------------------------
CControlUI* CMainWnd::CreateControl(LPCTSTR pstrClass)
{
if (_tcsicmp(pstrClass, _T("TabStrip")) == 0)
return new CTabStripUI;
if (_tcsicmp(pstrClass, _T("FavoriteStar")) == 0)
return new CFavoriteStarUI;
if (_tcsicmp(pstrClass, _T("PreviewPathLabel")) == 0)
return new CPreviewPathLabelUI;
return nullptr; // everything else goes through DuiLib's own factory
}
void CMainWnd::OnTabStripSelect(int index)
{
if (index < 0 || index >= static_cast<int>(m_tabs.size()) || index == m_activeTab)
return;
ActivateTab(index);
}
void CMainWnd::OnTabStripClose(int index)
{
CloseTab(index);
}
void CMainWnd::OnTabStripReorder(int from, int to)
{
if (from < 0 || to < 0 || from == to) return;
if (from >= static_cast<int>(m_tabs.size()) || to >= static_cast<int>(m_tabs.size())) return;
// The strip already moved its own copy; mirror that on the real tab model.
TabInfo moved = m_tabs[from];
m_tabs.erase(m_tabs.begin() + from);
m_tabs.insert(m_tabs.begin() + to, std::move(moved));
if (m_activeTab == from) m_activeTab = to;
else if (from < m_activeTab && to >= m_activeTab) --m_activeTab;
else if (from > m_activeTab && to <= m_activeTab) ++m_activeTab;
SaveSession();
}
void CMainWnd::OnTabStripDragOut(int index, POINT screenPt)
{
if (index < 0 || index >= static_cast<int>(m_tabs.size())) return;
OpenPathInNewWindow(m_tabs[index].path, screenPt);
}
void CMainWnd::OnTabStripAdd()
{
OnNewTabRequested();
}
void CMainWnd::CloseOtherTabs(int keepIndex, bool rightSideOnly)
{
if (keepIndex < 0 || keepIndex >= static_cast<int>(m_tabs.size())) return;
if (m_activeTab >= 0 && m_activeTab < static_cast<int>(m_tabs.size())) {
m_tabs[m_activeTab].path = m_currentPath;
m_tabs[m_activeTab].searchFilter = m_searchFilter;
}
for (int i = static_cast<int>(m_tabs.size()) - 1; i >= 0; --i) {
if (i == keepIndex) continue;
if (m_tabs[i].isPinned) continue; // 保护:绝不关闭已固定的标签!
if (rightSideOnly && i < keepIndex) continue;
ClosedTabInfo closed;
closed.path = m_tabs[i].path;
closed.searchFilter = m_tabs[i].searchFilter;
closed.backStack = m_tabs[i].backStack;
closed.forwardStack = m_tabs[i].forwardStack;
closed.isPinned = m_tabs[i].isPinned;
m_closedTabsHistory.push_back(std::move(closed));
m_tabs.erase(m_tabs.begin() + i);
if (i < keepIndex) --keepIndex;
}
if (m_closedTabsHistory.size() > 20) {
m_closedTabsHistory.erase(m_closedTabsHistory.begin(), m_closedTabsHistory.begin() + (m_closedTabsHistory.size() - 20));
}
m_activeTab = -1;
ActivateTab(keepIndex);
RebuildTabStrip();
SaveSession();
}
void CMainWnd::CloseLeftTabs(int keepIndex)
{
if (keepIndex < 0 || keepIndex >= static_cast<int>(m_tabs.size())) return;
if (m_activeTab >= 0 && m_activeTab < static_cast<int>(m_tabs.size())) {
m_tabs[m_activeTab].path = m_currentPath;
m_tabs[m_activeTab].searchFilter = m_searchFilter;
}
for (int i = keepIndex - 1; i >= 0; --i) {
if (m_tabs[i].isPinned) continue; // 保护:绝不关闭已固定的标签!
ClosedTabInfo closed;
closed.path = m_tabs[i].path;
closed.searchFilter = m_tabs[i].searchFilter;
closed.backStack = m_tabs[i].backStack;
closed.forwardStack = m_tabs[i].forwardStack;
closed.isPinned = m_tabs[i].isPinned;
m_closedTabsHistory.push_back(std::move(closed));
m_tabs.erase(m_tabs.begin() + i);
--keepIndex;
}
if (m_closedTabsHistory.size() > 20) {
m_closedTabsHistory.erase(m_closedTabsHistory.begin(), m_closedTabsHistory.begin() + (m_closedTabsHistory.size() - 20));
}
m_activeTab = -1;
ActivateTab(keepIndex);
RebuildTabStrip();
SaveSession();
}
void CMainWnd::DuplicateTab(int index)
{
if (index < 0 || index >= static_cast<int>(m_tabs.size())) return;
if (m_activeTab >= 0 && m_activeTab < static_cast<int>(m_tabs.size())) {
m_tabs[m_activeTab].path = m_currentPath;
m_tabs[m_activeTab].searchFilter = m_searchFilter;
}
TabInfo copy = m_tabs[index];
copy.button = nullptr;
const int insertIdx = index + 1;
m_tabs.insert(m_tabs.begin() + insertIdx, std::move(copy));
m_activeTab = -1;
RebuildTabStrip();
ActivateTab(insertIdx);
SaveSession();
}
void CMainWnd::TogglePinTab(int index)
{
if (index < 0 || index >= static_cast<int>(m_tabs.size())) return;
if (m_activeTab >= 0 && m_activeTab < static_cast<int>(m_tabs.size())) {
m_tabs[m_activeTab].path = m_currentPath;
m_tabs[m_activeTab].searchFilter = m_searchFilter;
}
bool wasPinned = m_tabs[index].isPinned;
TabInfo tab = m_tabs[index];
tab.isPinned = !wasPinned;
m_tabs.erase(m_tabs.begin() + index);
int targetIdx = 0;
int pinnedCount = 0;
for (const auto& t : m_tabs) {
if (t.isPinned) pinnedCount++;
}
targetIdx = pinnedCount; // 如果固定,放在已有固定标签末尾;若取消固定,放在固定标签后第一个
if (targetIdx > static_cast<int>(m_tabs.size())) targetIdx = static_cast<int>(m_tabs.size());
m_tabs.insert(m_tabs.begin() + targetIdx, std::move(tab));
m_activeTab = -1;
RebuildTabStrip();
ActivateTab(targetIdx);
SaveSession();
}
void CMainWnd::RestoreClosedTab()
{
if (m_closedTabsHistory.empty()) {
UpdateStatus(_T("没有最近关闭的标签页"));
return;
}
if (m_activeTab >= 0 && m_activeTab < static_cast<int>(m_tabs.size())) {
m_tabs[m_activeTab].path = m_currentPath;
m_tabs[m_activeTab].searchFilter = m_searchFilter;
}
ClosedTabInfo info = m_closedTabsHistory.back();
m_closedTabsHistory.pop_back();
TabInfo tab;
tab.path = info.path;
tab.searchFilter = info.searchFilter;
tab.backStack = info.backStack;
tab.forwardStack = info.forwardStack;
tab.isPinned = info.isPinned;
int insertIdx = static_cast<int>(m_tabs.size());
if (info.isPinned) {
int pinnedCount = 0;
for (const auto& t : m_tabs) {
if (t.isPinned) pinnedCount++;
}
insertIdx = pinnedCount;
}
m_tabs.insert(m_tabs.begin() + insertIdx, std::move(tab));
m_activeTab = -1;
RebuildTabStrip();
ActivateTab(insertIdx);
std::wstring msg = L"已恢复标签页:" + TabTitleForPath(info.path);
UpdateStatus(msg.c_str());
SaveSession();
}
void CMainWnd::OpenPathInNewWindow(const std::wstring& path, POINT screenPt)
{
// "--new-window" bypasses the single-instance forwarding in main.cpp so the clone really
// becomes its own HWND.
wchar_t exe[MAX_PATH] = {};
::GetModuleFileNameW(nullptr, exe, MAX_PATH);
std::wstring cmd = L"\"" + std::wstring(exe) + L"\" --new-window";
if (!path.empty())
cmd += L" \"" + path + (IsThisPcPath(path) ? L"" : L"\\.") + L"\"";
// Hand the clone its geometry so a dragged-out tab opens exactly as big as this window,
// at the drop point, without the parent having to race the new process' own layout pass.
if ((screenPt.x != 0 || screenPt.y != 0) && m_hWnd) {
RECT rc = {};
::GetWindowRect(m_hWnd, &rc);
const int w = rc.right - rc.left, h = rc.bottom - rc.top;
if (w > 0 && h > 0) {
wchar_t geom[64] = {};
swprintf_s(geom, L" --geometry=%d,%d,%d,%d", screenPt.x - 60, screenPt.y - 16, w, h);
cmd += geom;
}
}
STARTUPINFOW si = {};
si.cb = sizeof(si);
PROCESS_INFORMATION pi = {};
if (::CreateProcessW(nullptr, &cmd[0], nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si, &pi)) {
::CloseHandle(pi.hThread);
::CloseHandle(pi.hProcess);
}
}
void CMainWnd::OnTabStripContextMenu(int index, POINT screenPt)
{
if (index < 0 || index >= static_cast<int>(m_tabs.size())) return;
enum {
kClose = 1,
kTogglePin,
kDuplicate,
kCloseLeft,
kCloseRight,
kCloseOthers,
kRestoreClosed,
kCopyPath,
kNewWindow
};
HMENU menu = ::CreatePopupMenu();
if (!menu) return;
const bool isPinned = m_tabs[index].isPinned;
bool hasUnpinnedLeft = false;
for (int i = 0; i < index; ++i) {
if (!m_tabs[i].isPinned) { hasUnpinnedLeft = true; break; }
}
const bool hasRight = index + 1 < static_cast<int>(m_tabs.size());
bool hasCloseableOthers = false;
for (int i = 0; i < static_cast<int>(m_tabs.size()); ++i) {
if (i != index && !m_tabs[i].isPinned) { hasCloseableOthers = true; break; }
}
const bool canRestore = !m_closedTabsHistory.empty();
::AppendMenuW(menu, MF_STRING | (isPinned ? MF_GRAYED : 0), kClose, L"关闭标签页\tCtrl+W");
::AppendMenuW(menu, MF_STRING, kTogglePin, isPinned ? L"取消固定标签页" : L"固定标签页");
::AppendMenuW(menu, MF_STRING, kDuplicate, L"复制标签页");
::AppendMenuW(menu, MF_STRING | (hasUnpinnedLeft ? 0 : MF_GRAYED), kCloseLeft, L"关闭左侧标签页");
::AppendMenuW(menu, MF_STRING | (hasRight ? 0 : MF_GRAYED), kCloseRight, L"关闭右侧标签页");
::AppendMenuW(menu, MF_STRING | (hasCloseableOthers ? 0 : MF_GRAYED), kCloseOthers, L"关闭其他标签页");
::AppendMenuW(menu, MF_SEPARATOR, 0, nullptr);
::AppendMenuW(menu, MF_STRING | (canRestore ? 0 : MF_GRAYED), kRestoreClosed, L"重新打开关闭的标签页\tCtrl+Shift+T");
::AppendMenuW(menu, MF_SEPARATOR, 0, nullptr);
::AppendMenuW(menu, MF_STRING, kCopyPath, L"复制路径");
::AppendMenuW(menu, MF_STRING, kNewWindow, L"在新窗口打开");
const UINT cmd = ::TrackPopupMenuEx(menu,
TPM_RETURNCMD | TPM_RIGHTBUTTON, screenPt.x, screenPt.y, m_hWnd, nullptr);
::DestroyMenu(menu);
switch (cmd) {
case kClose:
CloseTab(index);
break;
case kTogglePin:
TogglePinTab(index);
break;
case kDuplicate:
DuplicateTab(index);
break;
case kCloseLeft:
CloseLeftTabs(index);
break;
case kCloseRight:
CloseOtherTabs(index, true);
break;
case kCloseOthers:
CloseOtherTabs(index, false);
break;
case kRestoreClosed:
RestoreClosedTab();
break;
case kCopyPath: {
const std::wstring text = (m_tabs[index].path == kThisPcPath) ? L"此电脑" : m_tabs[index].path;
::OpenClipboard(m_hWnd);
::EmptyClipboard();
const size_t bytes = (text.size() + 1) * sizeof(wchar_t);
if (HGLOBAL mem = ::GlobalAlloc(GMEM_MOVEABLE, bytes)) {
if (void* dst = ::GlobalLock(mem)) {
memcpy(dst, text.c_str(), bytes);
::GlobalUnlock(mem);
::SetClipboardData(CF_UNICODETEXT, mem);
}
}
::CloseClipboard();
UpdateStatus(_T("已复制路径"));
break;
}
case kNewWindow:
OpenPathInNewWindow(m_tabs[index].path, screenPt);
break;
default:
break;
}
}
void CMainWnd::OnTabStripEmptyContextMenu(POINT screenPt)
{
enum { kNewTab = 1, kRestoreClosed };
HMENU menu = ::CreatePopupMenu();
if (!menu) return;
const bool canRestore = !m_closedTabsHistory.empty();
::AppendMenuW(menu, MF_STRING, kNewTab, L"新建标签页\tCtrl+T");
::AppendMenuW(menu, MF_STRING | (canRestore ? 0 : MF_GRAYED), kRestoreClosed, L"重新打开关闭的标签页\tCtrl+Shift+T");
const UINT cmd = ::TrackPopupMenuEx(menu,
TPM_RETURNCMD | TPM_RIGHTBUTTON, screenPt.x, screenPt.y, m_hWnd, nullptr);
::DestroyMenu(menu);
if (cmd == kNewTab) {
OnNewTabRequested();
} else if (cmd == kRestoreClosed) {
RestoreClosedTab();
}
}
// Modal confirmation for "close the window while several tabs are open". Uses the native
// task dialog so the buttons can read 关闭 / 取消 (a plain MessageBox can only offer
// 确定 / 取消) and so it inherits the app's window icon and DPI.
bool CMainWnd::ConfirmCloseWithMultipleTabs()
{
if(!m_settings.confirmClose)return true;
TASKDIALOGCONFIG cfg = {};
cfg.cbSize = sizeof(cfg);
cfg.hwndParent = m_hWnd;
cfg.dwFlags = TDF_POSITION_RELATIVE_TO_WINDOW | TDF_ALLOW_DIALOG_CANCELLATION
| TDF_SIZE_TO_CONTENT;
cfg.dwCommonButtons = 0;
cfg.pszWindowTitle = L"FastFile";
cfg.pszMainIcon = TD_WARNING_ICON;
cfg.pszMainInstruction = L"当前打开了多个标签页,确认是否关闭";
wchar_t content[128] = {};
swprintf_s(content, L"关闭窗口会同时关闭全部 %u 个标签页。",
static_cast<unsigned>(m_tabs.size()));
cfg.pszContent = content;
// First entry is the default (Enter) action; Cancel is listed second but focused, so a
// stray Enter never closes the window by accident.
const TASKDIALOG_BUTTON buttons[] = {
{ 1001, L"关闭" },
{ 1002, L"取消" },
};
cfg.pButtons = buttons;
cfg.cButtons = ARRAYSIZE(buttons);
cfg.nDefaultButton = 1002;
int pressed = 0;
const HRESULT hr = ::TaskDialogIndirect(&cfg, &pressed, nullptr, nullptr);
if (FAILED(hr))
return true; // no task dialog available: keep the previous close behaviour
return pressed == 1001;
}
void CMainWnd::CloseTab(int index)
{
if (index < 0 || index >= static_cast<int>(m_tabs.size()))
return;
ClosedTabInfo closed;
closed.path = m_tabs[index].path;
closed.searchFilter = m_tabs[index].searchFilter;
closed.backStack = m_tabs[index].backStack;
closed.forwardStack = m_tabs[index].forwardStack;
closed.isPinned = m_tabs[index].isPinned;
m_closedTabsHistory.push_back(std::move(closed));
if (m_closedTabsHistory.size() > 20) {
m_closedTabsHistory.erase(m_closedTabsHistory.begin());
}
if (m_tabs.size() <= 1) {
// Last tab: closing it closes the program (like Explorer's tabbed windows).
// WM_CLOSE runs the normal shutdown path, so the session is saved on the way out.
if (m_hWnd)
::PostMessageW(m_hWnd, WM_CLOSE, 0, 0);
return;
}
m_tabs.erase(m_tabs.begin() + index);
int next = m_activeTab;
if (index < m_activeTab)
next = m_activeTab - 1;
else if (index == m_activeTab)
next = (std::min)(index, static_cast<int>(m_tabs.size()) - 1);
m_activeTab = -1;
ActivateTab(next);
}
void CMainWnd::ActivateTab(int index)
{
if (index < 0 || index >= static_cast<int>(m_tabs.size()))
return;
// persist current tab filter/path
if (m_activeTab >= 0 && m_activeTab < static_cast<int>(m_tabs.size())) {
m_tabs[m_activeTab].path = m_currentPath;
m_tabs[m_activeTab].searchFilter = m_searchFilter;
}
m_activeTab = index;
// Switching existing tabs must not recreate them: rebuilding progressively
// clamps the strip's scroll position.
// Structural changes (new/closed tabs) still require a model rebuild.
if (m_pTabStrip && m_pTabStrip->GetCount() == static_cast<int>(m_tabs.size()))
m_pTabStrip->SetActiveTab(index);
else
RebuildTabStrip();
const TabInfo& tab = m_tabs[m_activeTab];
m_searchFilter = tab.searchFilter;
if (m_pSearchEdit)
m_searchPlaceholder = false;
m_pSearchEdit->SetAttribute(_T("textcolor"), UiTokens::ColorTextPrimary);
m_pSearchEdit->SetText(m_searchFilter.c_str());
if (m_searchFilter.empty())
SetSearchPlaceholder(true);
// Navigate without wiping the restored filter
std::wstring target = tab.path;
std::wstring savedFilter = m_searchFilter;
if (IsThisPcPath(target) || target == L"此电脑") {
m_currentPath = kThisPcPath;
if (m_pAddressEdit) m_pAddressEdit->SetText(_T("此电脑"));
} else {
std::wstring norm = NormalizePath(target);
if (norm.empty())
norm = GetDefaultStartPath();
m_currentPath = norm;
if (m_pAddressEdit) m_pAddressEdit->SetText(m_currentPath.c_str());
}
m_searchFilter = savedFilter;
if (m_pSearchEdit)
m_searchPlaceholder = false;
m_pSearchEdit->SetAttribute(_T("textcolor"), UiTokens::ColorTextPrimary);
m_pSearchEdit->SetText(m_searchFilter.c_str());
if (m_searchFilter.empty())
SetSearchPlaceholder(true);
// Every folder remembers its own view mode; switching tabs (or opening a shortcut in a new
// tab) has to apply it too, otherwise E:\软件 opened as whatever the previous tab used.
{
const ViewMode remembered = LoadFolderViewForPath(m_currentPath);
if (m_viewMode != remembered) {
m_viewMode = remembered;
m_iconAnchor = -1;
m_lastIconClickTile = nullptr;
m_lastIconClickTick = 0;
}
UpdateViewModeButtons();
}
RefreshListing();
if (!m_suspendTreeSync)
SyncTreeToPath(m_currentPath);
// A tab switch changes the source path without going through NavigateToNow().
// Refresh the path-derived UI here as well; otherwise the old breadcrumb and preview
// can remain on screen while the new tab's file view has already been rendered.
RebuildBreadcrumb();
ClearPreview();
UpdateFavoritesHighlight();
UpdateNavButtons();
}
void CMainWnd::UpdateActiveTabPath(const std::wstring& path)
{
if (m_activeTab < 0 || m_activeTab >= static_cast<int>(m_tabs.size()))
return;
m_tabs[m_activeTab].path = path;
m_tabs[m_activeTab].searchFilter = m_searchFilter;
// A folder name changes its title and tooltip, so rebuild immediately
// instead of waiting for a later tab activation to refresh the layout.
RebuildTabStrip();
}
// ---- Session persist -----------------------------------------------------
std::wstring CMainWnd::GetSessionFilePath()
{
wchar_t appdata[MAX_PATH] = {};
DWORD n = ::GetEnvironmentVariableW(L"APPDATA", appdata, MAX_PATH);
std::wstring dir;
if (n > 0 && n < MAX_PATH)
dir = appdata;
else
dir = L".";
dir += L"\\FastFile";
::CreateDirectoryW(dir.c_str(), nullptr);
return dir + L"\\session.ini";
}
std::wstring CMainWnd::GetFolderViewsFilePath()
{
wchar_t appdata[MAX_PATH] = {};
DWORD n = ::GetEnvironmentVariableW(L"APPDATA", appdata, MAX_PATH);
std::wstring dir;
if (n > 0 && n < MAX_PATH)
dir = appdata;
else
dir = L".";
dir += L"\\FastFile";
::CreateDirectoryW(dir.c_str(), nullptr);
return dir + L"\\folder_views.ini";
}
std::wstring CMainWnd::NormalizeViewKey(const std::wstring& path)
{
if (path.empty())
return {};
if (IsThisPcPath(path) || path == L"此电脑" || ::_wcsicmp(path.c_str(), L"This PC") == 0)
return kThisPcPath;
std::wstring key = NormalizePath(path);
if (key.empty())
return {};
for (auto& ch : key)
ch = static_cast<wchar_t>(towlower(ch));
return key;
}
CMainWnd::ViewMode CMainWnd::LoadFolderViewForPath(const std::wstring& path) const
{
const ViewMode kDefault = static_cast<ViewMode>(m_settings.defaultView);
if(!m_settings.rememberViews)return kDefault;
std::wstring key = NormalizeViewKey(path);
if (key.empty())
return kDefault;
std::wstring file = GetFolderViewsFilePath();
FILE* fp = nullptr;
if (_wfopen_s(&fp, file.c_str(), L"rb") != 0 || !fp)
return kDefault;
fseek(fp, 0, SEEK_END);
long sz = ftell(fp);
fseek(fp, 0, SEEK_SET);
if (sz < 4) { fclose(fp); return kDefault; }
std::wstring content;
content.resize(sz / sizeof(wchar_t));
fread(&content[0], 1, sz, fp);
fclose(fp);
if (!content.empty() && content[0] == 0xFEFF)
content.erase(content.begin());
size_t pos = 0;
while (pos < content.size()) {
size_t eol = content.find(L'\n', pos);
if (eol == std::wstring::npos) eol = content.size();
std::wstring line = content.substr(pos, eol - pos);
if (!line.empty() && line.back() == L'\r') line.pop_back();
pos = eol + 1;
if (line.empty() || line[0] == L'[' || line[0] == L';') continue;
size_t eq = line.find(L'=');
if (eq == std::wstring::npos) continue;
std::wstring k = line.substr(0, eq);
std::wstring v = line.substr(eq + 1);
if (::_wcsicmp(k.c_str(), key.c_str()) != 0) continue;
int mode = _wtoi(v.c_str());
if (mode >= 0 && mode <= static_cast<int>(ViewMode::Content))
return static_cast<ViewMode>(mode);
break;
}
return kDefault;
}
void CMainWnd::SaveFolderViewForPath(const std::wstring& path, ViewMode mode) const
{
if(!m_settings.rememberViews)return;
std::wstring key = NormalizeViewKey(path);
if (key.empty())
return;
std::wstring file = GetFolderViewsFilePath();
std::map<std::wstring, int> entries;
FILE* fp = nullptr;
if (_wfopen_s(&fp, file.c_str(), L"rb") == 0 && fp) {
fseek(fp, 0, SEEK_END);
long sz = ftell(fp);
fseek(fp, 0, SEEK_SET);
if (sz >= 4) {
std::wstring content;
content.resize(sz / sizeof(wchar_t));
fread(&content[0], 1, sz, fp);
if (!content.empty() && content[0] == 0xFEFF)
content.erase(content.begin());
size_t pos = 0;
while (pos < content.size()) {
size_t eol = content.find(L'\n', pos);
if (eol == std::wstring::npos) eol = content.size();
std::wstring line = content.substr(pos, eol - pos);
if (!line.empty() && line.back() == L'\r') line.pop_back();
pos = eol + 1;
if (line.empty() || line[0] == L'[' || line[0] == L';') continue;
size_t eq = line.find(L'=');
if (eq == std::wstring::npos) continue;
std::wstring k = line.substr(0, eq);
int v = _wtoi(line.substr(eq + 1).c_str());
if (!k.empty() && v >= 0 && v <= static_cast<int>(ViewMode::Content))
entries[k] = v;
}
}
fclose(fp);
}
entries[key] = static_cast<int>(mode);
if (_wfopen_s(&fp, file.c_str(), L"wb") != 0 || !fp)
return;
unsigned char bom[2] = { 0xFF, 0xFE };
fwrite(bom, 1, 2, fp);
auto writeLine = [&](const std::wstring& s) {
fwrite(s.c_str(), sizeof(wchar_t), s.size(), fp);
wchar_t nl = L'\n';
fwrite(&nl, sizeof(wchar_t), 1, fp);
};
writeLine(L"[FolderViews]");
for (const auto& kv : entries) {
wchar_t buf[32];
swprintf_s(buf, L"=%d", kv.second);
writeLine(kv.first + buf);
}
fclose(fp);
}
void CMainWnd::SaveSession() const
{
SaveLeftNavSplitter();
// Persist current tab path/filter first
// (const_cast not needed — write from copies)
std::wstring path = GetSessionFilePath();
FILE* fp = nullptr;
if (_wfopen_s(&fp, path.c_str(), L"wb") != 0 || !fp)
return;
// UTF-16 LE BOM
unsigned char bom[2] = { 0xFF, 0xFE };
fwrite(bom, 1, 2, fp);
auto writeLine = [&](const std::wstring& s) {
fwrite(s.c_str(), sizeof(wchar_t), s.size(), fp);
wchar_t nl = L'\n';
fwrite(&nl, sizeof(wchar_t), 1, fp);
};
writeLine(L"[Session]");
{
wchar_t buf[128];
swprintf_s(buf, L"ActiveTab=%d", m_activeTab);
writeLine(buf);
swprintf_s(buf, L"ViewMode=%d", static_cast<int>(m_viewMode));
writeLine(buf);
swprintf_s(buf, L"Recursive=%d", IsRecursiveSearch() ? 1 : 0);
writeLine(buf);
swprintf_s(buf, L"ColName=%d", m_colWidthName);
writeLine(buf);
swprintf_s(buf, L"ColMTime=%d", m_colWidthMTime);
writeLine(buf);
swprintf_s(buf, L"ColType=%d", m_colWidthType);
writeLine(buf);
swprintf_s(buf, L"ColSize=%d", m_colWidthSize);
writeLine(buf);
swprintf_s(buf, L"SortCol=%d", static_cast<int>(m_sortColumn));
writeLine(buf);
swprintf_s(buf, L"SortAsc=%d", m_sortAscending ? 1 : 0);
writeLine(buf);
swprintf_s(buf, L"Preview=%d", m_previewVisible ? 1 : 0);
writeLine(buf);
swprintf_s(buf, L"ShowHidden=%d", m_showHidden ? 1 : 0);
writeLine(buf);
swprintf_s(buf, L"FavoritesBar=%d", m_favoritesBarVisible ? 1 : 0);
writeLine(buf);
}
writeLine(L"[Tabs]");
{
wchar_t buf[64];
swprintf_s(buf, L"Count=%d", static_cast<int>(m_tabs.size()));
writeLine(buf);
}
for (int i = 0; i < (int)m_tabs.size(); ++i) {
std::wstring p = m_tabs[i].path;
if (i == m_activeTab && !m_currentPath.empty())
p = m_currentPath;
wchar_t key[64];
swprintf_s(key, L"Path%d=", i);
writeLine(std::wstring(key) + p);
swprintf_s(key, L"Filter%d=", i);
writeLine(std::wstring(key) + ((i == m_activeTab) ? m_searchFilter : m_tabs[i].searchFilter));
swprintf_s(key, L"Pinned%d=", i);
writeLine(std::wstring(key) + (m_tabs[i].isPinned ? L"1" : L"0"));
}
fclose(fp);
}
bool CMainWnd::LoadSession()
{
std::wstring path = GetSessionFilePath();
FILE* fp = nullptr;
if (_wfopen_s(&fp, path.c_str(), L"rb") != 0 || !fp)
return false;
fseek(fp, 0, SEEK_END);
long sz = ftell(fp);
fseek(fp, 0, SEEK_SET);
if (sz < 4) { fclose(fp); return false; }
std::wstring content;
content.resize(sz / sizeof(wchar_t));
fread(&content[0], 1, sz, fp);
fclose(fp);
if (!content.empty() && content[0] == 0xFEFF)
content.erase(content.begin());
int active = 0;
int viewMode = static_cast<int>(ViewMode::Tiles);
int recursive = 0;
int count = 0;
std::map<int, std::wstring> paths;
std::map<int, std::wstring> filters;
std::map<int, bool> pinned;
size_t pos = 0;
while (pos < content.size()) {
size_t eol = content.find(L'\n', pos);
if (eol == std::wstring::npos) eol = content.size();
std::wstring line = content.substr(pos, eol - pos);
if (!line.empty() && line.back() == L'\r') line.pop_back();
pos = eol + 1;
if (line.empty() || line[0] == L'[' || line[0] == L';') continue;
size_t eq = line.find(L'=');
if (eq == std::wstring::npos) continue;
std::wstring key = line.substr(0, eq);
std::wstring val = line.substr(eq + 1);
if (key == L"ActiveTab") active = _wtoi(val.c_str());
else if (key == L"ViewMode") viewMode = _wtoi(val.c_str());
else if (key == L"Recursive") recursive = _wtoi(val.c_str());
else if (key == L"ColName") m_colWidthName = (std::max)(60, _wtoi(val.c_str()));
else if (key == L"ColMTime") m_colWidthMTime = (std::max)(50, _wtoi(val.c_str()));
else if (key == L"ColType") m_colWidthType = (std::max)(50, _wtoi(val.c_str()));
else if (key == L"ColSize") m_colWidthSize = (std::max)(50, _wtoi(val.c_str()));
else if (key == L"SortCol") {
int sc = _wtoi(val.c_str());
if (sc >= 0 && sc <= 3) m_sortColumn = static_cast<SortColumn>(sc);
}
else if (key == L"SortAsc") m_sortAscending = (_wtoi(val.c_str()) != 0);
else if (key == L"Preview") m_previewVisible = (_wtoi(val.c_str()) != 0);
else if (key == L"ShowHidden") m_showHidden = (_wtoi(val.c_str()) != 0);
else if (key == L"FavoritesBar") m_favoritesBarVisible = (_wtoi(val.c_str()) != 0);
else if (key == L"Count") count = _wtoi(val.c_str());
else if (key.size() > 4 && key.compare(0, 4, L"Path") == 0)
paths[_wtoi(key.c_str() + 4)] = val;
else if (key.size() > 6 && key.compare(0, 6, L"Filter") == 0)
filters[_wtoi(key.c_str() + 6)] = val;
else if (key.size() > 6 && key.compare(0, 6, L"Pinned") == 0)
pinned[_wtoi(key.c_str() + 6)] = (_wtoi(val.c_str()) != 0);
}
if (count <= 0 || paths.empty())
return false;
if(m_settings.startup!=0) {
paths.clear();filters.clear();pinned.clear();
const auto custom=m_settings.startup==2 && m_startupOpenPaths.empty()
? ResolveFolderOpenTarget(m_settings.startupPath) : std::wstring();
paths[0]=m_settings.startup==2 && !custom.empty() ? custom : std::wstring(kThisPcPath);
count=1;active=0;
}
if(GetFileAttributesW(FastFileSettings::FilePath().c_str())!=INVALID_FILE_ATTRIBUTES) {
m_sortColumn=static_cast<SortColumn>(m_settings.sortColumn);m_sortAscending=m_settings.sortAscending;
viewMode=m_settings.defaultView;
}
m_tabs.clear();
m_activeTab = -1;
for (int i = 0; i < count; ++i) {
auto it = paths.find(i);
if (it == paths.end() || it->second.empty()) continue;
TabInfo tab;
tab.path = it->second;
auto fit = filters.find(i);
if (fit != filters.end())
tab.searchFilter = fit->second;
auto pit = pinned.find(i);
if (pit != pinned.end())
tab.isPinned = pit->second;
m_tabs.push_back(tab);
}
if (m_tabs.empty())
return false;
if (viewMode >= 0 && viewMode <= static_cast<int>(ViewMode::Content))
m_viewMode = static_cast<ViewMode>(viewMode);
if (m_pChkRecursive)
m_pChkRecursive->Selected(recursive != 0);
ApplyColumnWidths();
SetPreviewVisible(m_previewVisible);
if (m_pFavoritesBar)
m_pFavoritesBar->SetVisible(m_favoritesBarVisible);
UpdateHeaderSortIndicators();
if (active < 0 || active >= (int)m_tabs.size())
active = 0;
if(m_startupOpenPaths.empty())ActivateTab(active);
else {
// Restore the tab model, but let the external target own the first browse.
m_activeTab=active;
RebuildTabStrip();
}
RebuildBreadcrumb();
// Startup preferences decide whether paths are restored or replaced above.
UpdateStatus(_T("已就绪"));
return true;
}