-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileOrderTimeTool.cs
More file actions
3780 lines (3454 loc) · 171 KB
/
Copy pathFileOrderTimeTool.cs
File metadata and controls
3780 lines (3454 loc) · 171 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Globalization;
using System.IO;
using System.Linq;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
[assembly: System.Reflection.AssemblyVersion("1.8.4.5")]
[assembly: System.Reflection.AssemblyFileVersion("1.8.4.5")]
namespace FileOrderTimeTool
{
// ===== UI 调整区:单位为 100% 缩放下的逻辑像素 =====
static class Ui
{
public const int OuterMargin = 20;
public const int RowHeight = 34;
public const int RowGap = 6;
public const int ButtonHeight = 28;
public const int ActionButtonWidth = 82;
public const int ControlGap = 7;
public const int FieldGap = 7;
public const int GroupGap = 27;
public const int InputLeftInset = 6;
public const int SelectorArrowWidth = 24;
public const int SelectorTrailingGap = 7;
public const int MinimumHeight = 520;
public const int CardWidth = 152;
public const int CardHeight = 186;
public const int CardGap = 10;
public static float ScaleFormOnce(Form form)
{
using (Graphics graphics = form.CreateGraphics())
{
float scale = graphics.DpiX / 96f;
if (Math.Abs(scale - 1f) > 0.01f) form.Scale(new SizeF(scale, scale));
return scale;
}
}
}
// ===== 文本调整区:界面备注和说明文字可优先在这里修改 =====
static class UiText
{
public const string DateFeatureDisabled = "请勾选“更改文件日期”选项";
public const string DateFeatureTip = "启用后可批量修改文件的修改日期或创建日期数据。";
public const string RenameFeatureTip = "启用后按左上→右下的顺序重命名全部或选中的文件。";
public const string HelpApplicationQuestion = "问:这个应用是用来做什么的?\r\n答:本工具用于按照自定义排列顺序,批量更改文件的修改日期或创建日期,也可以批量修改文件名和扩展名。所有计划都可以先预览,实际文件更改在本次运行期间支持撤销和重做。";
public const string HelpFirstQuestion = "问:如何快速知道某个板块或设置的功能?\r\n答:将鼠标悬停在该板块或设置上约 1 秒,即可查看功能说明。";
}
static class Program
{
[STAThread]
static void Main()
{
bool createdNew;
using (Mutex instanceMutex = new Mutex(true, "Local\\FileOrderTimeTool.SingleInstance", out createdNew))
{
if (!createdNew)
{
NativeMethods.ActivateExistingInstance("批量文件排序/重命名工具", Application.ProductVersion);
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
GC.KeepAlive(instanceMutex);
}
}
}
sealed class FileItem
{
public string Path;
public Image Thumbnail;
public bool ThumbnailRequested;
public bool Selected;
public string Name { get { return System.IO.Path.GetFileName(Path); } }
public string Extension { get { return System.IO.Path.GetExtension(Path); } }
public DateTime LastWriteTime { get { try { return File.GetLastWriteTime(Path); } catch { return DateTime.MinValue; } } }
public DateTime CreationTime { get { try { return File.GetCreationTime(Path); } catch { return DateTime.MinValue; } } }
public long Size { get { try { return new FileInfo(Path).Length; } catch { return 0; } } }
}
interface IHistoryAction
{
string Name { get; }
bool Undo();
bool Redo();
}
sealed class HistoryManager
{
private readonly Stack<IHistoryAction> undoStack = new Stack<IHistoryAction>();
private readonly Stack<IHistoryAction> redoStack = new Stack<IHistoryAction>();
public event EventHandler Changed;
public bool CanUndo { get { return undoStack.Count > 0; } }
public bool CanRedo { get { return redoStack.Count > 0; } }
public void Push(IHistoryAction action)
{
undoStack.Push(action);
redoStack.Clear();
RaiseChanged();
}
public void Undo()
{
if (!CanUndo) return;
IHistoryAction action = undoStack.Pop();
if (action.Undo()) redoStack.Push(action);
else undoStack.Push(action);
RaiseChanged();
}
public void Redo()
{
if (!CanRedo) return;
IHistoryAction action = redoStack.Pop();
if (action.Redo()) undoStack.Push(action);
else redoStack.Push(action);
RaiseChanged();
}
public void Clear()
{
undoStack.Clear();
redoStack.Clear();
RaiseChanged();
}
private void RaiseChanged()
{
if (Changed != null) Changed(this, EventArgs.Empty);
}
}
sealed class OrderAction : IHistoryAction
{
private readonly FileCanvas canvas;
private readonly List<FileItem> before;
private readonly List<FileItem> after;
private readonly string name;
public OrderAction(FileCanvas canvas, List<FileItem> before, List<FileItem> after, string name)
{
this.canvas = canvas;
this.before = new List<FileItem>(before);
this.after = new List<FileItem>(after);
this.name = name;
}
public string Name { get { return name; } }
public bool Undo() { canvas.SetOrder(before); return true; }
public bool Redo() { canvas.SetOrder(after); return true; }
}
sealed class FileState
{
public FileItem Item;
public string Path;
public DateTime LastWriteTime;
public DateTime CreationTime;
public bool ChangeLastWriteTime;
public bool ChangeCreationTime;
public string Identity;
}
sealed class DiskChangeAction
{
private readonly MainForm form;
private readonly List<FileState> before;
private readonly List<FileState> after;
public DiskChangeAction(MainForm form, List<FileState> before, List<FileState> after)
{
this.form = form;
this.before = Clone(before);
this.after = Clone(after);
}
public bool Undo() { return form.ApplyDiskTransition(after, before); }
public bool Redo() { return form.ApplyDiskTransition(before, after); }
private static List<FileState> Clone(List<FileState> src)
{
List<FileState> dst = new List<FileState>();
foreach (FileState s in src)
dst.Add(new FileState { Item = s.Item, Path = s.Path, LastWriteTime = s.LastWriteTime,
CreationTime = s.CreationTime, ChangeLastWriteTime = s.ChangeLastWriteTime,
ChangeCreationTime = s.ChangeCreationTime, Identity = s.Identity });
return dst;
}
}
sealed class DiskHistoryManager
{
private readonly Stack<DiskChangeAction> undoStack = new Stack<DiskChangeAction>();
private readonly Stack<DiskChangeAction> redoStack = new Stack<DiskChangeAction>();
public event EventHandler Changed;
public bool CanUndo { get { return undoStack.Count > 0; } }
public bool CanRedo { get { return redoStack.Count > 0; } }
public void Push(DiskChangeAction action)
{
undoStack.Push(action);
redoStack.Clear();
RaiseChanged();
}
public bool Undo()
{
if (!CanUndo) return false;
DiskChangeAction action = undoStack.Peek();
if (!action.Undo()) return false;
undoStack.Pop();
redoStack.Push(action);
RaiseChanged();
return true;
}
public bool Redo()
{
if (!CanRedo) return false;
DiskChangeAction action = redoStack.Peek();
if (!action.Redo()) return false;
redoStack.Pop();
undoStack.Push(action);
RaiseChanged();
return true;
}
private void RaiseChanged()
{
if (Changed != null) Changed(this, EventArgs.Empty);
}
}
static class FileIdentityHelper
{
[StructLayout(LayoutKind.Sequential)]
private struct FILETIME_NATIVE { public uint dwLowDateTime; public uint dwHighDateTime; }
[StructLayout(LayoutKind.Sequential)]
private struct BY_HANDLE_FILE_INFORMATION
{
public uint dwFileAttributes;
public FILETIME_NATIVE ftCreationTime;
public FILETIME_NATIVE ftLastAccessTime;
public FILETIME_NATIVE ftLastWriteTime;
public uint dwVolumeSerialNumber;
public uint nFileSizeHigh;
public uint nFileSizeLow;
public uint nNumberOfLinks;
public uint nFileIndexHigh;
public uint nFileIndexLow;
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool GetFileInformationByHandle(SafeFileHandle hFile, out BY_HANDLE_FILE_INFORMATION lpFileInformation);
public static string TryGet(string path)
{
try
{
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
{
BY_HANDLE_FILE_INFORMATION info;
if (!GetFileInformationByHandle(fs.SafeFileHandle, out info)) return null;
return info.dwVolumeSerialNumber.ToString("X8", CultureInfo.InvariantCulture) + ":" +
info.nFileIndexHigh.ToString("X8", CultureInfo.InvariantCulture) + info.nFileIndexLow.ToString("X8", CultureInfo.InvariantCulture);
}
}
catch { return null; }
}
}
sealed class ShortcutBinding
{
public Keys KeyCode;
public Keys Modifiers;
public bool TabPrefix;
public ShortcutBinding Clone() { return new ShortcutBinding { KeyCode = KeyCode, Modifiers = Modifiers, TabPrefix = TabPrefix }; }
public bool Matches(Keys keyData, bool tabDown)
{
Keys code = keyData & Keys.KeyCode;
Keys mods = keyData & Keys.Modifiers;
return code == KeyCode && mods == Modifiers && tabDown == TabPrefix;
}
public string Serialize()
{
return ((int)KeyCode).ToString(CultureInfo.InvariantCulture) + "," + ((int)Modifiers).ToString(CultureInfo.InvariantCulture) + "," + (TabPrefix ? "1" : "0");
}
public static ShortcutBinding Parse(string text)
{
string[] p = (text ?? "").Split(',');
int key, mods;
if (p.Length != 3 || !int.TryParse(p[0], out key) || !int.TryParse(p[1], out mods)) return null;
return new ShortcutBinding { KeyCode = (Keys)key, Modifiers = (Keys)mods, TabPrefix = p[2] == "1" };
}
public override bool Equals(object obj)
{
ShortcutBinding b = obj as ShortcutBinding;
return b != null && b.KeyCode == KeyCode && b.Modifiers == Modifiers && b.TabPrefix == TabPrefix;
}
public override int GetHashCode() { return ((int)KeyCode * 397) ^ (int)Modifiers ^ (TabPrefix ? 1 : 0); }
public string Display()
{
List<string> parts = new List<string>();
if ((Modifiers & Keys.Control) == Keys.Control) parts.Add("Ctrl");
if ((Modifiers & Keys.Shift) == Keys.Shift) parts.Add("Shift");
if ((Modifiers & Keys.Alt) == Keys.Alt) parts.Add("Alt");
if (TabPrefix) parts.Add("Tab");
parts.Add(KeyName(KeyCode));
return string.Join("+", parts.ToArray());
}
private static string KeyName(Keys k)
{
if (k == Keys.Left) return "←";
if (k == Keys.Right) return "→";
if (k == Keys.Up) return "↑";
if (k == Keys.Down) return "↓";
if (k == Keys.Delete) return "Delete";
if (k == Keys.Enter) return "Enter";
return k.ToString();
}
}
static class ShortcutIds
{
public const string Remove = "Remove";
public const string Sort = "Sort";
public const string Undo = "Undo";
public const string Redo = "Redo";
public const string Preview = "Preview";
public const string Apply = "Apply";
public const string UndoDisk = "UndoDisk";
public const string RedoDisk = "RedoDisk";
public const string MoveLeft = "MoveLeft";
public const string MoveRight = "MoveRight";
public const string MoveFront = "MoveFront";
public const string MoveEnd = "MoveEnd";
public const string PrevSort = "PrevSort";
public const string NextSort = "NextSort";
public const string PrevDirection = "PrevDirection";
public const string NextDirection = "NextDirection";
public const string Help = "Help";
public static readonly string[] Order = new string[] { Remove, Sort, Undo, Redo, Preview, Apply, UndoDisk, RedoDisk, MoveLeft, MoveRight, MoveFront, MoveEnd, PrevSort, NextSort, PrevDirection, NextDirection, Help };
public static string Title(string id)
{
if (id == Remove) return "移除";
if (id == Sort) return "执行排序";
if (id == Undo) return "撤销";
if (id == Redo) return "重做";
if (id == Preview) return "预览";
if (id == Apply) return "应用更改";
if (id == UndoDisk) return "撤销更改";
if (id == RedoDisk) return "重做更改";
if (id == MoveLeft) return "向左移动";
if (id == MoveRight) return "向右移动";
if (id == MoveFront) return "移到最前";
if (id == MoveEnd) return "移到最后";
if (id == PrevSort) return "上一个排序方式";
if (id == NextSort) return "下一个排序方式";
if (id == PrevDirection) return "切换为升序";
if (id == NextDirection) return "切换为降序";
if (id == Help) return "使用说明";
return id;
}
public static Dictionary<string, ShortcutBinding> Defaults()
{
Dictionary<string, ShortcutBinding> d = new Dictionary<string, ShortcutBinding>();
d[Remove] = B(Keys.Delete);
d[Sort] = B(Keys.Enter);
d[Undo] = B(Keys.Z, Keys.Control);
d[Redo] = B(Keys.Z, Keys.Control | Keys.Shift);
d[Preview] = B(Keys.Enter, Keys.Alt);
d[Apply] = B(Keys.Enter, Keys.Shift);
d[UndoDisk] = B(Keys.Z, Keys.Control | Keys.Alt);
d[RedoDisk] = B(Keys.Z, Keys.Control | Keys.Shift | Keys.Alt);
d[MoveLeft] = B(Keys.Left);
d[MoveRight] = B(Keys.Right);
d[MoveFront] = B(Keys.Up);
d[MoveEnd] = B(Keys.Down);
d[PrevSort] = B(Keys.Up, Keys.None, true);
d[NextSort] = B(Keys.Down, Keys.None, true);
d[PrevDirection] = B(Keys.Up, Keys.Control, true);
d[NextDirection] = B(Keys.Down, Keys.Control, true);
d[Help] = B(Keys.F1);
return d;
}
private static ShortcutBinding B(Keys key, Keys mods = Keys.None, bool tab = false)
{
return new ShortcutBinding { KeyCode = key, Modifiers = mods, TabPrefix = tab };
}
}
sealed class FileCanvas : ScrollableControl
{
public readonly List<FileItem> Items = new List<FileItem>();
public HistoryManager History;
public event EventHandler SelectionChanged;
public event EventHandler OrderChanged;
private float canvasScale = 1f;
private int Px(int value) { return (int)Math.Round(value * canvasScale); }
private int CardW { get { return Px(Ui.CardWidth); } }
private int TileH { get { return Px(Ui.CardHeight); } }
private int MinGap { get { return Px(Ui.CardGap); } }
private int HorizontalOuterMargin { get { return Px(Ui.OuterMargin); } }
private int VerticalMargin { get { return Px(10); } }
private int ThumbW { get { return Px(128); } }
private int ThumbH { get { return Px(118); } }
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
using (Graphics g = CreateGraphics()) canvasScale = g.DpiX / 96f;
UpdateScrollSize();
}
protected override void OnScroll(ScrollEventArgs se)
{
base.OnScroll(se);
hoverIndex = -1;
itemToolTip.SetToolTip(this, null);
Invalidate();
}
private int anchorIndex = -1;
private bool mouseDown;
private int mouseDownIndex = -1;
private Point mouseDownPoint;
private bool draggingItems;
private int insertionIndex = -1;
private bool marquee;
private Rectangle marqueeRect;
private HashSet<FileItem> marqueeBase = new HashSet<FileItem>();
private bool collapseOnMouseUp;
private readonly ToolTip itemToolTip = new ToolTip();
private int hoverIndex = -1;
public event Action<int> ItemOpenRequested;
public FileCanvas()
{
DoubleBuffered = true;
AutoScroll = true;
AllowDrop = true;
BackColor = Color.White;
TabStop = true;
SetStyle(ControlStyles.Selectable, true);
itemToolTip.InitialDelay = 850;
itemToolTip.ReshowDelay = 250;
itemToolTip.AutoPopDelay = 6000;
itemToolTip.ShowAlways = true;
}
public int SelectedCount { get { return Items.Count(x => x.Selected); } }
public List<FileItem> SelectedItemsInOrder { get { return Items.Where(x => x.Selected).ToList(); } }
public void AddFiles(IEnumerable<string> paths)
{
HashSet<string> existing = new HashSet<string>(Items.Select(x => SafeFullPath(x.Path)), StringComparer.OrdinalIgnoreCase);
int added = 0;
foreach (string raw in paths)
{
try
{
if (Directory.Exists(raw)) continue;
if (!File.Exists(raw)) continue;
string full = SafeFullPath(raw);
if (existing.Contains(full)) continue;
FileItem item = new FileItem { Path = full };
Items.Add(item);
existing.Add(full);
added++;
QueueThumbnail(item);
}
catch { }
}
if (added > 0)
{
UpdateScrollSize();
Invalidate();
RaiseOrderChanged();
}
}
public void SetOrder(IEnumerable<FileItem> order)
{
Items.Clear();
Items.AddRange(order);
UpdateScrollSize();
Invalidate();
RaiseOrderChanged();
}
public void ClearSelection()
{
bool changed = false;
foreach (FileItem item in Items) if (item.Selected) { item.Selected = false; changed = true; }
if (changed) { Invalidate(); RaiseSelectionChanged(); }
}
public void SelectAllItems()
{
foreach (FileItem item in Items) item.Selected = true;
Invalidate();
RaiseSelectionChanged();
}
public void MoveSelected(bool toFront)
{
if (SelectedCount == 0) return;
List<FileItem> before = new List<FileItem>(Items);
List<FileItem> sel = Items.Where(x => x.Selected).ToList();
List<FileItem> unsel = Items.Where(x => !x.Selected).ToList();
List<FileItem> after = new List<FileItem>();
if (toFront) { after.AddRange(sel); after.AddRange(unsel); }
else { after.AddRange(unsel); after.AddRange(sel); }
if (!SameOrder(before, after))
{
SetOrder(after);
if (History != null) History.Push(new OrderAction(this, before, after, toFront ? "移动到最前" : "移动到最后"));
}
}
public void MoveSelectedOne(bool left)
{
if (SelectedCount == 0 || Items.Count <= 1) return;
List<FileItem> before = new List<FileItem>(Items);
List<FileItem> selected = Items.Where(x => x.Selected).ToList();
List<FileItem> remaining = Items.Where(x => !x.Selected).ToList();
int first = -1, last = -1;
for (int i = 0; i < Items.Count; i++)
{
if (!Items[i].Selected) continue;
if (first < 0) first = i;
last = i;
}
if (first < 0) return;
int target;
if (left) target = Math.Max(0, first - 1);
else target = Math.Min(remaining.Count, last);
remaining.InsertRange(target, selected);
if (!SameOrder(before, remaining))
{
SetOrder(remaining);
if (History != null) History.Push(new OrderAction(this, before, remaining, left ? "向左移动" : "向右移动"));
}
}
public void RemoveSelected()
{
if (SelectedCount == 0) return;
List<FileItem> before = new List<FileItem>(Items);
List<FileItem> after = Items.Where(x => !x.Selected).ToList();
SetOrder(after);
if (History != null) History.Push(new OrderAction(this, before, after, "移除选中"));
RaiseSelectionChanged();
}
public void ClearAll()
{
if (Items.Count == 0) return;
List<FileItem> before = new List<FileItem>(Items);
List<FileItem> after = new List<FileItem>();
SetOrder(after);
if (History != null) History.Push(new OrderAction(this, before, after, "清空"));
RaiseSelectionChanged();
}
public void ApplySortedOrder(List<FileItem> sorted, string actionName)
{
List<FileItem> before = new List<FileItem>(Items);
if (SameOrder(before, sorted)) return;
SetOrder(sorted);
if (History != null) History.Push(new OrderAction(this, before, sorted, actionName));
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
UpdateScrollSize();
Invalidate();
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if (Items.Count == 0)
{
TextRenderer.DrawText(e.Graphics, "请直接拖入文件进行导入", Font, ClientRectangle, Color.FromArgb(125, 125, 125),
TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding);
return;
}
e.Graphics.TranslateTransform(AutoScrollPosition.X, AutoScrollPosition.Y);
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
for (int i = 0; i < Items.Count; i++) DrawItem(e.Graphics, i, Items[i]);
if (draggingItems && insertionIndex >= 0)
{
Rectangle slot = GetSlotRect(insertionIndex);
using (Pen p = new Pen(Color.FromArgb(0, 120, 215), 3))
{
int x = slot.Left - 3;
e.Graphics.DrawLine(p, x, slot.Top + 4, x, slot.Bottom - 4);
}
}
if (marquee)
{
using (Brush b = new SolidBrush(Color.FromArgb(35, 0, 120, 215))) e.Graphics.FillRectangle(b, marqueeRect);
using (Pen p = new Pen(Color.FromArgb(0, 120, 215), 1)) e.Graphics.DrawRectangle(p, marqueeRect);
}
}
private void DrawItem(Graphics g, int index, FileItem item)
{
Rectangle r = GetItemRect(index);
Color back = item.Selected ? Color.FromArgb(218, 235, 252) : Color.White;
Color border = item.Selected ? Color.FromArgb(0, 120, 215) : Color.FromArgb(225, 225, 225);
using (Brush b = new SolidBrush(back)) g.FillRectangle(b, r);
using (Pen p = new Pen(border, item.Selected ? 2 : 1)) g.DrawRectangle(p, r);
Rectangle thumbRect = new Rectangle(r.Left + (r.Width - ThumbW) / 2, r.Top + Px(10), ThumbW, ThumbH);
using (Brush b = new SolidBrush(Color.FromArgb(248, 248, 248))) g.FillRectangle(b, thumbRect);
if (item.Thumbnail != null)
{
Rectangle fit = FitRect(item.Thumbnail.Size, thumbRect);
g.DrawImage(item.Thumbnail, fit);
}
else
{
using (Brush b = new SolidBrush(Color.FromArgb(120, 120, 120)))
using (Font f = new Font("Segoe UI", 9f))
{
string ext = item.Extension.Length > 0 ? item.Extension.TrimStart('.').ToUpperInvariant() : "FILE";
StringFormat sf = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center };
g.DrawString(ext, f, b, thumbRect, sf);
}
}
Rectangle textRect = new Rectangle(r.Left + Px(7), r.Top + Px(133), r.Width - Px(14), (int)Math.Ceiling(Font.GetHeight(g) * 2));
using (Brush textBrush = new SolidBrush(Color.FromArgb(30, 30, 30)))
using (StringFormat sf = new StringFormat())
{
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Near;
sf.Trimming = StringTrimming.EllipsisCharacter;
sf.FormatFlags = StringFormatFlags.LineLimit;
g.DrawString(item.Name, Font, textBrush, textRect, sf);
}
}
private Rectangle FitRect(Size image, Rectangle box)
{
if (image.Width <= 0 || image.Height <= 0) return box;
double scale = Math.Min((double)box.Width / image.Width, (double)box.Height / image.Height);
int w = Math.Max(1, (int)(image.Width * scale));
int h = Math.Max(1, (int)(image.Height * scale));
return new Rectangle(box.Left + (box.Width - w) / 2, box.Top + (box.Height - h) / 2, w, h);
}
private struct GridLayout
{
public int Columns;
public float Gap;
public float StartX;
public float Stride;
}
private GridLayout GetGridLayout()
{
int viewport = Math.Max(CardW, ClientSize.Width);
int usable = Math.Max(CardW, viewport - HorizontalOuterMargin * 2);
int cols = Math.Max(1, (usable + MinGap) / (CardW + MinGap));
while (cols > 1 && cols * CardW + (cols - 1) * MinGap > usable) cols--;
float gap = 0f;
float totalWidth = CardW;
if (cols > 1)
{
gap = (usable - cols * CardW) / (float)(cols - 1);
if (gap < MinGap) gap = MinGap;
totalWidth = cols * CardW + (cols - 1) * gap;
}
float startX = Math.Max(0f, (viewport - totalWidth) / 2f);
return new GridLayout { Columns = cols, Gap = gap, StartX = startX, Stride = CardW + gap };
}
private int Columns { get { return GetGridLayout().Columns; } }
private Rectangle GetItemRect(int index)
{
GridLayout gl = GetGridLayout();
int col = index % gl.Columns;
int row = index / gl.Columns;
int x = (int)Math.Round(gl.StartX + col * gl.Stride);
return new Rectangle(x, VerticalMargin + row * TileH, CardW, TileH - Px(8));
}
private Rectangle GetSlotRect(int index)
{
GridLayout gl = GetGridLayout();
int clamped = Math.Max(0, Math.Min(index, Items.Count));
int col = clamped % gl.Columns;
int row = clamped / gl.Columns;
int x = (int)Math.Round(gl.StartX + col * gl.Stride);
return new Rectangle(x, VerticalMargin + row * TileH, CardW, TileH - Px(8));
}
private int HitTest(Point clientPoint)
{
Point p = ClientToContent(clientPoint);
for (int i = 0; i < Items.Count; i++) if (GetItemRect(i).Contains(p)) return i;
return -1;
}
private int InsertionFromPoint(Point clientPoint)
{
Point p = ClientToContent(clientPoint);
GridLayout gl = GetGridLayout();
int row = Math.Max(0, (p.Y - VerticalMargin) / TileH);
int rowStart = Math.Min(Items.Count, row * gl.Columns);
int rowEnd = Math.Min(Items.Count, rowStart + gl.Columns);
if (rowStart >= Items.Count) return Items.Count;
// 行由卡片的完整垂直节距决定。鼠标仍在本行时,不会因为靠近
// 卡片下半部而提前掉到下一行;行内再按各卡片中心线决定前/后。
for (int i = rowStart; i < rowEnd; i++)
{
Rectangle card = GetItemRect(i);
if (p.X < card.Left + card.Width / 2) return i;
}
return rowEnd;
}
private Point ClientToContent(Point p)
{
return new Point(p.X - AutoScrollPosition.X, p.Y - AutoScrollPosition.Y);
}
private void UpdateScrollSize()
{
int rows = Items.Count == 0 ? 0 : (int)Math.Ceiling((double)Items.Count / Columns);
AutoScrollMinSize = new Size(0, VerticalMargin * 2 + rows * TileH);
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
Focus();
if (e.Button == MouseButtons.Right)
{
ClearSelection();
return;
}
if (e.Button != MouseButtons.Left) return;
mouseDown = true;
mouseDownPoint = e.Location;
mouseDownIndex = HitTest(e.Location);
draggingItems = false;
insertionIndex = -1;
collapseOnMouseUp = false;
bool ctrl = (ModifierKeys & Keys.Control) == Keys.Control;
bool shift = (ModifierKeys & Keys.Shift) == Keys.Shift;
if (mouseDownIndex >= 0)
{
if (shift && anchorIndex >= 0)
{
if (!ctrl) foreach (FileItem x in Items) x.Selected = false;
int a = Math.Min(anchorIndex, mouseDownIndex);
int b = Math.Max(anchorIndex, mouseDownIndex);
for (int i = a; i <= b; i++) Items[i].Selected = true;
RaiseSelectionChanged();
Invalidate();
}
else if (ctrl)
{
Items[mouseDownIndex].Selected = !Items[mouseDownIndex].Selected;
anchorIndex = mouseDownIndex;
RaiseSelectionChanged();
Invalidate();
}
else
{
if (!Items[mouseDownIndex].Selected)
{
foreach (FileItem x in Items) x.Selected = false;
Items[mouseDownIndex].Selected = true;
RaiseSelectionChanged();
Invalidate();
}
else if (SelectedCount > 1)
{
collapseOnMouseUp = true;
}
anchorIndex = mouseDownIndex;
}
}
else
{
marquee = true;
Point cp = ClientToContent(e.Location);
marqueeRect = new Rectangle(cp, Size.Empty);
marqueeBase = ctrl ? new HashSet<FileItem>(Items.Where(x => x.Selected)) : new HashSet<FileItem>();
if (!ctrl)
{
foreach (FileItem x in Items) x.Selected = false;
RaiseSelectionChanged();
Invalidate();
}
}
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if (!mouseDown) UpdateHoverTooltip(e.Location);
if (!mouseDown || e.Button != MouseButtons.Left) return;
if (marquee)
{
Point a = ClientToContent(mouseDownPoint);
Point b = ClientToContent(e.Location);
marqueeRect = NormalizeRect(a, b);
foreach (FileItem x in Items) x.Selected = marqueeBase.Contains(x);
for (int i = 0; i < Items.Count; i++)
if (marqueeRect.IntersectsWith(GetItemRect(i))) Items[i].Selected = true;
RaiseSelectionChanged();
Invalidate();
return;
}
if (mouseDownIndex >= 0 && Items[mouseDownIndex].Selected)
{
if (!draggingItems && (Math.Abs(e.X - mouseDownPoint.X) > 5 || Math.Abs(e.Y - mouseDownPoint.Y) > 5))
{
draggingItems = true;
collapseOnMouseUp = false;
}
if (draggingItems)
{
insertionIndex = InsertionFromPoint(e.Location);
Invalidate();
AutoScrollNearEdge(e.Location);
}
}
}
private void UpdateHoverTooltip(Point location)
{
int i = HitTest(location);
if (i == hoverIndex) return;
hoverIndex = i;
itemToolTip.SetToolTip(this, i >= 0 && i < Items.Count ? Items[i].Name : null);
}
protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave(e);
hoverIndex = -1;
itemToolTip.SetToolTip(this, null);
}
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
if (e.Button != MouseButtons.Left) return;
if (draggingItems && SelectedCount > 0)
{
List<FileItem> before = new List<FileItem>(Items);
List<FileItem> moving = Items.Where(x => x.Selected).ToList();
int target = insertionIndex < 0 ? Items.Count : insertionIndex;
int selectedBefore = 0;
for (int i = 0; i < Math.Min(target, Items.Count); i++) if (Items[i].Selected) selectedBefore++;
List<FileItem> remaining = Items.Where(x => !x.Selected).ToList();
int adjusted = Math.Max(0, Math.Min(remaining.Count, target - selectedBefore));
remaining.InsertRange(adjusted, moving);
if (!SameOrder(before, remaining))
{
SetOrder(remaining);
if (History != null) History.Push(new OrderAction(this, before, remaining, "拖动排序"));
}
}
else if (collapseOnMouseUp && mouseDownIndex >= 0)
{
foreach (FileItem x in Items) x.Selected = false;
Items[mouseDownIndex].Selected = true;
RaiseSelectionChanged();
Invalidate();
}
mouseDown = false;
mouseDownIndex = -1;
draggingItems = false;
insertionIndex = -1;
marquee = false;
collapseOnMouseUp = false;
Invalidate();
}
protected override void OnMouseDoubleClick(MouseEventArgs e)
{
base.OnMouseDoubleClick(e);
int i = HitTest(e.Location);
if (i >= 0)
{
if (ItemOpenRequested != null) ItemOpenRequested(i);
else try { Process.Start(Items[i].Path); } catch { }
}
}
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (e.Control && e.KeyCode == Keys.A)
{
SelectAllItems(); e.Handled = true;
}
}
protected override void OnDragEnter(DragEventArgs drgevent)
{
base.OnDragEnter(drgevent);
if (drgevent.Data != null && drgevent.Data.GetDataPresent(DataFormats.FileDrop)) drgevent.Effect = DragDropEffects.Copy;
}
protected override void OnDragOver(DragEventArgs drgevent)
{
base.OnDragOver(drgevent);
if (drgevent.Data != null && drgevent.Data.GetDataPresent(DataFormats.FileDrop)) drgevent.Effect = DragDropEffects.Copy;
}
protected override void OnDragDrop(DragEventArgs drgevent)
{
base.OnDragDrop(drgevent);
if (drgevent.Data == null || !drgevent.Data.GetDataPresent(DataFormats.FileDrop)) return;
string[] files = drgevent.Data.GetData(DataFormats.FileDrop) as string[];
if (files != null) AddFiles(files);
}
private void AutoScrollNearEdge(Point p)
{
if (!AutoScroll) return;
int y = -AutoScrollPosition.Y;
if (p.Y < 30) y = Math.Max(0, y - 24);
else if (p.Y > ClientSize.Height - 30) y += 24;
AutoScrollPosition = new Point(-AutoScrollPosition.X, y);
}
private void QueueThumbnail(FileItem item)
{
if (item.ThumbnailRequested) return;
item.ThumbnailRequested = true;
ThreadPool.QueueUserWorkItem(delegate(object state)
{
Image img = null;
try { img = ShellThumbnail.GetThumbnail(item.Path, new Size(ThumbW, ThumbH)); } catch { }
if (IsDisposed) { if (img != null) img.Dispose(); return; }
try
{
BeginInvoke((MethodInvoker)delegate
{
item.Thumbnail = img;
Invalidate();
});
}
catch { if (img != null) img.Dispose(); }
});
}
private static Rectangle NormalizeRect(Point a, Point b)
{
return Rectangle.FromLTRB(Math.Min(a.X, b.X), Math.Min(a.Y, b.Y), Math.Max(a.X, b.X), Math.Max(a.Y, b.Y));
}
private static bool SameOrder(IList<FileItem> a, IList<FileItem> b)
{
if (a.Count != b.Count) return false;
for (int i = 0; i < a.Count; i++) if (!object.ReferenceEquals(a[i], b[i])) return false;
return true;
}
private static string SafeFullPath(string path)
{
try { return System.IO.Path.GetFullPath(path); } catch { return path; }
}