-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathGalleryView.cs
More file actions
2121 lines (1806 loc) · 88.7 KB
/
GalleryView.cs
File metadata and controls
2121 lines (1806 loc) · 88.7 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 AndroidSideloader;
using AndroidSideloader.Utilities;
using JR.Utils.GUI.Forms;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public enum SortField { Name, LastUpdated, Size, Popularity }
public enum SortDirection { Ascending, Descending }
public class FastGalleryPanel : Control
{
// Data
private List<ListViewItem> _items;
private List<ListViewItem> _originalItems; // Keep original for re-sorting
private int _tileWidth;
private int _tileHeight;
private readonly int _spacing;
private readonly int _baseTileWidth;
private readonly int _baseTileHeight;
// Grouping
private Dictionary<string, List<ListViewItem>> _groupedByPackage;
private List<GroupedTile> _displayTiles;
private int _expandedTileIndex = -1;
private float _expandOverlayOpacity = 0f;
private float _targetExpandOverlayOpacity = 0f;
private int _overlayHoveredVersion = -1;
private Rectangle _overlayRect;
private List<Rectangle> _versionRects;
private int _overlayScrollOffset = 0;
private int _overlayMaxScroll = 0;
private class GroupedTile
{
public string PackageName;
public string GameName;
public string BaseGameName; // Common name across all versions
public List<ListViewItem> Versions;
public ListViewItem Primary => Versions[0];
}
// Sorting
private SortField _currentSortField = SortField.Name;
private SortDirection _currentSortDirection = SortDirection.Ascending;
public SortField CurrentSortField => _currentSortField;
public SortDirection CurrentSortDirection => _currentSortDirection;
private readonly Panel _sortPanel;
private readonly List<Button> _sortButtons;
private Label _sortStatusLabel;
private ModernSlider _sizeSlider;
private Label _sizeLabel;
private const int SORT_PANEL_HEIGHT = 36;
private const int SLIDER_MIN = 100;
private const int SLIDER_MAX = 150;
private const int SLIDER_DEFAULT = 100;
// Layout
private int _columns;
private int _rows;
private int _contentHeight;
private int _leftPadding;
// Smooth scrolling
private float _scrollY;
private float _targetScrollY;
private bool _isScrolling;
private readonly VScrollBar _scrollBar;
// Animation
private readonly System.Windows.Forms.Timer _animationTimer;
private readonly Dictionary<int, TileAnimationState> _tileStates;
// Image cache (LRU)
private readonly Dictionary<string, Image> _imageCache;
private readonly Queue<string> _cacheOrder;
private const int MAX_CACHE_SIZE = 200;
// Interaction
private int _hoveredIndex = -1;
public int _selectedIndex = -1;
private ListViewItem _selectedItem = null;
private bool _isHoveringDeleteButton = false;
// Context Menu & Favorites
private ContextMenuStrip _contextMenu;
private int _rightClickedIndex = -1;
private int _rightClickedVersionIndex = -1;
private HashSet<string> _favoritesCache;
// Rendering
private Bitmap _backBuffer;
// Visual constants
private const int CORNER_RADIUS = 10;
private const int THUMB_CORNER_RADIUS = 8;
private const float HOVER_SCALE = 1.08f;
private const float ANIMATION_SPEED = 0.33f;
private const float SCROLL_SMOOTHING = 0.3f;
private const int DELETE_BUTTON_SIZE = 26;
private const int DELETE_BUTTON_MARGIN = 6;
private const int VERSION_ROW_HEIGHT = 44;
private const int OVERLAY_PADDING = 10;
private const int OVERLAY_MAX_HEIGHT = 320;
// Theme colors
private static readonly Color TileBorderHover = Color.FromArgb(93, 203, 173);
private static readonly Color TileBorderSelected = Color.FromArgb(200, 200, 200);
private static readonly Color TileBorderFavorite = Color.FromArgb(255, 215, 0);
private static readonly Color BadgeFavoriteBg = Color.FromArgb(200, 255, 180, 0);
private static readonly Color TextColor = Color.FromArgb(245, 255, 255, 255);
private static readonly Color BadgeInstalledBg = Color.FromArgb(180, 60, 145, 230);
private static readonly Color BadgeDownloadedBg = Color.FromArgb(180, 80, 175, 150);
private static readonly Color DeleteButtonBg = Color.FromArgb(200, 180, 50, 50);
private static readonly Color DeleteButtonHoverBg = Color.FromArgb(255, 220, 70, 70);
private static readonly Color SortButtonBg = Color.FromArgb(40, 42, 48);
private static readonly Color SortButtonActiveBg = Color.FromArgb(93, 203, 173);
private static readonly Color SortButtonHoverBg = Color.FromArgb(55, 58, 65);
private static readonly Color OverlayBgColor = Color.FromArgb(250, 28, 30, 36);
private static readonly Color VersionRowHoverBg = Color.FromArgb(255, 45, 48, 56);
public event EventHandler<int> TileClicked;
public event EventHandler<int> TileDoubleClicked;
public event EventHandler<int> TileDeleteClicked;
public event EventHandler<int> TileRightClicked;
public event EventHandler<string> TileHovered; // Update release notes for hovered grouped sub-item
public event EventHandler<SortField> SortChanged;
[DllImport("dwmapi.dll")]
private static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int attrValue, int attrSize);
[DllImport("uxtheme.dll", CharSet = CharSet.Unicode)]
private static extern int SetWindowTheme(IntPtr hwnd, string pszSubAppName, string pszSubIdList);
private void ApplyModernScrollbars()
{
if (_scrollBar == null || !_scrollBar.IsHandleCreated) return;
int dark = 1;
int hr = DwmSetWindowAttribute(_scrollBar.Handle, 20, ref dark, sizeof(int));
if (hr != 0) DwmSetWindowAttribute(_scrollBar.Handle, 19, ref dark, sizeof(int));
if (SetWindowTheme(_scrollBar.Handle, "DarkMode_Explorer", null) != 0)
SetWindowTheme(_scrollBar.Handle, "Explorer", null);
}
private class TileAnimationState
{
public float Scale = 1.0f;
public float TargetScale = 1.0f;
public float BorderOpacity = 0f;
public float TargetBorderOpacity = 0f;
public float BackgroundBrightness = 30f;
public float TargetBackgroundBrightness = 30f;
public float SelectionOpacity = 0f;
public float TargetSelectionOpacity = 0f;
public float TooltipOpacity = 0f;
public float TargetTooltipOpacity = 0f;
public float DeleteButtonOpacity = 0f;
public float TargetDeleteButtonOpacity = 0f;
public float FavoriteOpacity = 0f;
public float TargetFavoriteOpacity = 0f;
public float GroupBadgeOpacity = 0f;
public float TargetGroupBadgeOpacity = 0f;
}
private class ModernSlider : Control
{
private int _minimum = 100;
private int _maximum = 150;
private int _value = 100;
private bool _dragging;
private bool _hovering;
private float _hoverOpacity;
private readonly System.Windows.Forms.Timer _fadeTimer;
private static readonly Color TrackBg = Color.FromArgb(50, 52, 58);
private static readonly Color TrackFill = Color.FromArgb(93, 203, 173);
private static readonly Color ThumbColor = Color.FromArgb(93, 203, 173);
private static readonly Color ThumbHoverColor = Color.FromArgb(130, 220, 195);
private static readonly Color ThumbBorderColor = Color.FromArgb(255, 255, 255);
private const int TRACK_HEIGHT = 4;
private const int THUMB_RADIUS = 5;
private const int THUMB_HOVER_RADIUS = 7;
public event EventHandler ValueChanged;
public int Minimum { get { return _minimum; } set { _minimum = value; Invalidate(); } }
public int Maximum { get { return _maximum; } set { _maximum = value; Invalidate(); } }
public int Value
{
get { return _value; }
set
{
int clamped = Math.Max(_minimum, Math.Min(_maximum, value));
if (clamped != _value) { _value = clamped; ValueChanged?.Invoke(this, EventArgs.Empty); Invalidate(); }
}
}
public ModernSlider()
{
SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint |
ControlStyles.OptimizedDoubleBuffer | ControlStyles.SupportsTransparentBackColor, true);
BackColor = Color.Transparent;
Height = 26;
Width = 100;
Cursor = Cursors.Hand;
_fadeTimer = new System.Windows.Forms.Timer { Interval = 16 };
_fadeTimer.Tick += (s, e) =>
{
float target = (_hovering || _dragging) ? 1.0f : 0f;
float diff = target - _hoverOpacity;
if (Math.Abs(diff) > 0.02f) { _hoverOpacity += diff * 0.3f; Invalidate(); }
else { _hoverOpacity = target; _fadeTimer.Stop(); Invalidate(); }
};
}
private int GetTrackLeft() { return THUMB_HOVER_RADIUS + 1; }
private int GetTrackRight() { return Width - THUMB_HOVER_RADIUS - 1; }
private int ValueToX()
{
if (_maximum <= _minimum) return GetTrackLeft();
float ratio = (float)(_value - _minimum) / (_maximum - _minimum);
return GetTrackLeft() + (int)(ratio * (GetTrackRight() - GetTrackLeft()));
}
private int XToValue(int x)
{
float ratio = (float)(x - GetTrackLeft()) / (GetTrackRight() - GetTrackLeft());
ratio = Math.Max(0f, Math.Min(1f, ratio));
return _minimum + (int)(ratio * (_maximum - _minimum));
}
protected override void OnPaint(PaintEventArgs e)
{
var g = e.Graphics;
g.SmoothingMode = SmoothingMode.AntiAlias;
int cy = Height / 2;
int trackLeft = GetTrackLeft();
int trackRight = GetTrackRight();
int thumbX = ValueToX();
// Track background
using (var trackPath = CreatePillPath(trackLeft, cy - TRACK_HEIGHT / 2, trackRight - trackLeft, TRACK_HEIGHT))
using (var trackBrush = new SolidBrush(TrackBg))
g.FillPath(trackBrush, trackPath);
// Track fill (left of thumb)
if (thumbX > trackLeft)
{
int fillWidth = thumbX - trackLeft;
using (var fillPath = CreatePillPath(trackLeft, cy - TRACK_HEIGHT / 2, fillWidth, TRACK_HEIGHT))
using (var fillBrush = new SolidBrush(TrackFill))
g.FillPath(fillBrush, fillPath);
}
// Thumb hover glow
if (_hoverOpacity > 0.01f)
{
int glowRadius = THUMB_HOVER_RADIUS + 4;
using (var glowBrush = new SolidBrush(Color.FromArgb((int)(30 * _hoverOpacity), TrackFill)))
g.FillEllipse(glowBrush, thumbX - glowRadius, cy - glowRadius, glowRadius * 2, glowRadius * 2);
}
// Thumb
int thumbR = THUMB_RADIUS + (int)((THUMB_HOVER_RADIUS - THUMB_RADIUS) * _hoverOpacity);
Color currentThumb = BlendColor(ThumbColor, ThumbHoverColor, _hoverOpacity);
using (var thumbBrush = new SolidBrush(currentThumb))
g.FillEllipse(thumbBrush, thumbX - thumbR, cy - thumbR, thumbR * 2, thumbR * 2);
// Thumb border
using (var borderPen = new Pen(Color.FromArgb((int)(60 * (1f - _hoverOpacity * 0.5f)), ThumbBorderColor), 1.5f))
g.DrawEllipse(borderPen, thumbX - thumbR, cy - thumbR, thumbR * 2, thumbR * 2);
}
private static Color BlendColor(Color a, Color b, float t)
{
return Color.FromArgb(
(int)(a.R + (b.R - a.R) * t),
(int)(a.G + (b.G - a.G) * t),
(int)(a.B + (b.B - a.B) * t));
}
private static GraphicsPath CreatePillPath(int x, int y, int width, int height)
{
var path = new GraphicsPath();
if (width <= 0) { path.AddEllipse(x, y, height, height); return path; }
int r = height;
path.AddArc(x, y, r, r, 90, 180);
path.AddArc(x + width - r, y, r, r, 270, 180);
path.CloseFigure();
return path;
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if (e.Button == MouseButtons.Left) { _dragging = true; Value = XToValue(e.X); }
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if (_dragging) Value = XToValue(e.X);
}
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
_dragging = false;
}
protected override void OnMouseEnter(EventArgs e)
{
base.OnMouseEnter(e);
_hovering = true;
_fadeTimer.Start();
}
protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave(e);
_hovering = false;
if (!_dragging) _fadeTimer.Start();
}
protected override void Dispose(bool disposing)
{
if (disposing) { _fadeTimer?.Stop(); _fadeTimer?.Dispose(); }
base.Dispose(disposing);
}
}
public FastGalleryPanel(List<ListViewItem> items, int tileWidth, int tileHeight, int spacing, int initialWidth, int initialHeight)
{
_originalItems = items ?? new List<ListViewItem>();
_items = new List<ListViewItem>(_originalItems);
_displayTiles = new List<GroupedTile>();
_groupedByPackage = new Dictionary<string, List<ListViewItem>>(StringComparer.OrdinalIgnoreCase);
_versionRects = new List<Rectangle>();
_baseTileWidth = tileWidth;
_baseTileHeight = tileHeight;
int savedSize = Math.Max(SLIDER_MIN, Math.Min(SLIDER_MAX, SettingsManager.Instance.GalleryTileSize));
float initScale = savedSize / 100f;
_tileWidth = Math.Max(80, (int)(tileWidth * initScale));
_tileHeight = Math.Max(55, (int)(tileHeight * initScale));
_spacing = spacing;
_imageCache = new Dictionary<string, Image>(StringComparer.OrdinalIgnoreCase);
_cacheOrder = new Queue<string>();
_tileStates = new Dictionary<int, TileAnimationState>();
_sortButtons = new List<Button>();
RefreshFavoritesCache();
// Avoid any implicit padding from the control container
Padding = Padding.Empty;
Margin = Padding.Empty;
Size = new Size(initialWidth, initialHeight);
SetStyle(ControlStyles.AllPaintingInWmPaint |
ControlStyles.UserPaint |
ControlStyles.OptimizedDoubleBuffer |
ControlStyles.Selectable |
ControlStyles.ResizeRedraw, true);
BackColor = Color.FromArgb(24, 26, 30);
// Create context menu
CreateContextMenu();
// Create sort panel
_sortPanel = CreateSortPanel();
Controls.Add(_sortPanel);
LayoutSliderControls();
// Scrollbar - direct interaction jumps immediately (no smooth scroll)
_scrollBar = new VScrollBar { Minimum = 0, SmallChange = _tileHeight / 2, LargeChange = _tileHeight * 2 };
_scrollBar.Scroll += (s, e) =>
{
_scrollY = _scrollBar.Value;
_targetScrollY = _scrollBar.Value;
_isScrolling = false;
Invalidate();
};
_scrollBar.HandleCreated += (s, e) => ApplyModernScrollbars();
Controls.Add(_scrollBar);
// Animation timer (~120fps)
_animationTimer = new System.Windows.Forms.Timer { Interval = 8 };
_animationTimer.Tick += AnimationTimer_Tick;
_animationTimer.Start();
// Apply initial sort
ApplySort();
RecalculateLayout();
}
private string GetBaseGameName(List<ListViewItem> versions)
{
if (versions == null || versions.Count == 0) return "";
// If only one version, use actual name
if (versions.Count == 1) return versions[0].Text;
// Strip parentheses (...) from all names - except (MR-Fix), then use the shortest result
var strippedNames = versions.Select(v =>
{
string name = v.Text;
bool hasMrFix = name.IndexOf("(MR-Fix)", StringComparison.OrdinalIgnoreCase) >= 0;
name = System.Text.RegularExpressions.Regex.Replace(name, @"\s*\([^)]*\)", "").Trim();
return hasMrFix ? name + " (MR-Fix)" : name;
});
return strippedNames.OrderBy(n => n.Length).First();
}
private void BuildGroupedTiles()
{
_groupedByPackage.Clear();
_displayTiles.Clear();
foreach (var item in _items)
{
string packageName = item.SubItems.Count > 2 ? item.SubItems[2].Text : "";
if (string.IsNullOrEmpty(packageName)) packageName = item.Text;
if (!_groupedByPackage.ContainsKey(packageName))
_groupedByPackage[packageName] = new List<ListViewItem>();
_groupedByPackage[packageName].Add(item);
}
foreach (var kvp in _groupedByPackage)
{
kvp.Value.Sort((a, b) =>
{
var dateA = ParseDate(a.SubItems.Count > 4 ? a.SubItems[4].Text : "");
var dateB = ParseDate(b.SubItems.Count > 4 ? b.SubItems[4].Text : "");
return dateB.CompareTo(dateA);
});
_displayTiles.Add(new GroupedTile
{
PackageName = kvp.Key,
GameName = kvp.Value[0].Text,
BaseGameName = GetBaseGameName(kvp.Value),
Versions = kvp.Value
});
}
SortDisplayTiles();
_tileStates.Clear();
for (int i = 0; i < _displayTiles.Count; i++)
_tileStates[i] = new TileAnimationState();
}
private void SortDisplayTiles()
{
switch (_currentSortField)
{
case SortField.Name:
_displayTiles = _currentSortDirection == SortDirection.Ascending
? _displayTiles.OrderBy(t => t.BaseGameName, new GameNameComparer()).ToList()
: _displayTiles.OrderByDescending(t => t.BaseGameName, new GameNameComparer()).ToList();
break;
case SortField.LastUpdated:
_displayTiles = _currentSortDirection == SortDirection.Ascending
? _displayTiles.OrderBy(t => t.Versions.Max(v => ParseDate(v.SubItems.Count > 4 ? v.SubItems[4].Text : ""))).ToList()
: _displayTiles.OrderByDescending(t => t.Versions.Max(v => ParseDate(v.SubItems.Count > 4 ? v.SubItems[4].Text : ""))).ToList();
break;
case SortField.Size:
_displayTiles = _currentSortDirection == SortDirection.Ascending
? _displayTiles.OrderBy(t => t.Versions.Max(v => ParseSize(v.SubItems.Count > 5 ? v.SubItems[5].Text : "0"))).ToList()
: _displayTiles.OrderByDescending(t => t.Versions.Max(v => ParseSize(v.SubItems.Count > 5 ? v.SubItems[5].Text : "0"))).ToList();
break;
case SortField.Popularity:
if (_currentSortDirection == SortDirection.Ascending)
_displayTiles = _displayTiles.OrderByDescending(t => ParsePopularity(t.Primary.SubItems.Count > 6 ? t.Primary.SubItems[6].Text : "-"))
.ThenBy(t => t.BaseGameName, new GameNameComparer()).ToList();
else
_displayTiles = _displayTiles.OrderBy(t => ParsePopularity(t.Primary.SubItems.Count > 6 ? t.Primary.SubItems[6].Text : "-"))
.ThenBy(t => t.BaseGameName, new GameNameComparer()).ToList();
break;
}
}
private Panel CreateSortPanel()
{
var panel = new Panel
{
Height = SORT_PANEL_HEIGHT,
Dock = DockStyle.Top,
BackColor = Color.FromArgb(28, 30, 34),
Padding = new Padding(8, 4, 8, 4)
};
var label = new Label
{
Text = "Sort by:",
ForeColor = Color.FromArgb(180, 180, 180),
Font = new Font("Segoe UI", 9f),
AutoSize = true,
Location = new Point(10, 9)
};
panel.Controls.Add(label);
int buttonX = 70;
SortField[] fields = { SortField.Name, SortField.LastUpdated, SortField.Size, SortField.Popularity };
string[] texts = { "Name", "Updated", "Size", "Popularity" };
for (int i = 0; i < fields.Length; i++)
{
var btn = CreateSortButton(texts[i], fields[i], buttonX);
panel.Controls.Add(btn);
_sortButtons.Add(btn);
buttonX += btn.Width + 6;
}
_sortStatusLabel = new Label
{
Text = GetSortStatusText(),
ForeColor = Color.FromArgb(140, 140, 140),
Font = new Font("Segoe UI", 8.5f, FontStyle.Italic),
AutoSize = true,
Location = new Point(buttonX + 10, 9)
};
panel.Controls.Add(_sortStatusLabel);
// Tile size slider (right-aligned)
_sizeLabel = new Label
{
Text = "Tile Size",
ForeColor = Color.FromArgb(140, 140, 140),
Font = new Font("Segoe UI", 8.5f),
AutoSize = true,
Anchor = AnchorStyles.Top | AnchorStyles.Right
};
panel.Controls.Add(_sizeLabel);
_sizeSlider = new ModernSlider
{
Minimum = SLIDER_MIN,
Maximum = SLIDER_MAX,
Value = Math.Max(SLIDER_MIN, Math.Min(SLIDER_MAX, SettingsManager.Instance.GalleryTileSize)),
Height = 22,
Width = 100,
Anchor = AnchorStyles.Top | AnchorStyles.Right
};
_sizeSlider.ValueChanged += SizeSlider_ValueChanged;
panel.Controls.Add(_sizeSlider);
// Position slider controls on the right side
panel.Resize += (s, ev) => LayoutSliderControls();
UpdateSortButtonStyles();
return panel;
}
private string GetSortStatusText()
{
switch (_currentSortField)
{
case SortField.Name: return _currentSortDirection == SortDirection.Ascending ? "A → Z" : "Z → A";
case SortField.LastUpdated: return _currentSortDirection == SortDirection.Ascending ? "Oldest → Newest" : "Newest → Oldest";
case SortField.Size: return _currentSortDirection == SortDirection.Ascending ? "Smallest → Largest" : "Largest → Smallest";
case SortField.Popularity: return _currentSortDirection == SortDirection.Ascending ? "Least → Most Popular" : "Most → Least Popular";
default: return "";
}
}
private Button CreateSortButton(string text, SortField field, int x)
{
var btn = new Button
{
Text = field == _currentSortField ? GetSortButtonText(text) : text,
Tag = field,
FlatStyle = FlatStyle.Flat,
Font = new Font("Segoe UI", 8.5f),
ForeColor = Color.White,
BackColor = SortButtonBg,
Size = new Size(text == "Popularity" ? 90 : 75, 26),
Location = new Point(x, 5),
Cursor = Cursors.Hand
};
btn.FlatAppearance.BorderSize = 0;
btn.FlatAppearance.MouseOverBackColor = SortButtonHoverBg;
btn.FlatAppearance.MouseDownBackColor = SortButtonActiveBg;
btn.Click += (s, e) => OnSortButtonClick(field);
return btn;
}
private string GetSortButtonText(string baseText)
{
return baseText + (_currentSortDirection == SortDirection.Ascending ? " ▲" : " ▼");
}
private void OnSortButtonClick(SortField field)
{
if (_currentSortField == field)
// Toggle direction
_currentSortDirection = _currentSortDirection == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending;
else
{
_currentSortField = field;
// Popularity, LastUpdated, Size default to descending (most popular/newest/largest first)
// Name defaults to ascending (A-Z)
_currentSortDirection = field == SortField.Name ? SortDirection.Ascending : SortDirection.Descending;
}
UpdateSortButtonStyles();
ApplySort();
SortChanged?.Invoke(this, field);
}
private void UpdateSortButtonStyles()
{
foreach (var btn in _sortButtons)
{
var field = (SortField)btn.Tag;
bool isActive = field == _currentSortField;
string baseText = field == SortField.Name ? "Name" : field == SortField.LastUpdated ? "Updated" : field == SortField.Size ? "Size" : "Popularity";
btn.Text = isActive ? GetSortButtonText(baseText) : baseText;
// Set appropriate hover color based on active state
btn.BackColor = isActive ? SortButtonActiveBg : SortButtonBg;
btn.ForeColor = isActive ? Color.FromArgb(24, 26, 30) : Color.White;
btn.FlatAppearance.MouseOverBackColor = isActive ? Color.FromArgb(110, 215, 190) : SortButtonHoverBg;
btn.FlatAppearance.MouseDownBackColor = isActive ? Color.FromArgb(80, 180, 155) : SortButtonActiveBg;
}
// Update the sort status label
if (_sortStatusLabel != null) _sortStatusLabel.Text = GetSortStatusText();
}
private void LayoutSliderControls()
{
if (_sortPanel == null || _sizeSlider == null || _sizeLabel == null) return;
int panelWidth = _sortPanel.ClientSize.Width;
_sizeSlider.Location = new Point(panelWidth - _sizeSlider.Width - 8, 5);
_sizeLabel.Location = new Point(_sizeSlider.Left - _sizeLabel.Width - 4, 9);
}
private void SizeSlider_ValueChanged(object sender, EventArgs e)
{
float scale = _sizeSlider.Value / 100f;
_tileWidth = Math.Max(80, (int)(_baseTileWidth * scale));
_tileHeight = Math.Max(55, (int)(_baseTileHeight * scale));
SettingsManager.Instance.GalleryTileSize = _sizeSlider.Value;
SettingsManager.Instance.Save();
CloseOverlay();
RecalculateLayout();
Invalidate();
}
private void ApplySort()
{
// Reset original order
_items = new List<ListViewItem>(_originalItems);
// Reset selection and hover
_hoveredIndex = -1;
_selectedIndex = -1;
_selectedItem = null;
CloseOverlay();
BuildGroupedTiles();
// Reset scroll position
_scrollY = 0;
_targetScrollY = 0;
RecalculateLayout();
Invalidate();
}
private void CloseOverlay()
{
_expandedTileIndex = -1;
_targetExpandOverlayOpacity = 0f;
_overlayHoveredVersion = -1;
_overlayScrollOffset = 0;
_rightClickedVersionIndex = -1;
}
public void SetSortState(SortField field, SortDirection direction)
{
_currentSortField = field;
_currentSortDirection = direction;
UpdateSortButtonStyles();
ApplySort();
}
private int ParsePopularity(string popStr)
{
if (string.IsNullOrEmpty(popStr)) return int.MaxValue; // Unranked goes to end
popStr = popStr.Trim();
if (popStr == "-") return int.MaxValue; // Unranked goes to end
if (popStr.StartsWith("#") && int.TryParse(popStr.Substring(1), out int rank)) return rank;
if (int.TryParse(popStr, out int rawNum)) return rawNum; // Fallback: try parsing as raw number
return int.MaxValue; // Unparseable goes to end
}
// Custom sort to match list sort behaviour: '_' before digits, digits before letters (case-insensitive)
private class GameNameComparer : IComparer<string>
{
public int Compare(string x, string y)
{
if (x == y) return 0;
if (x == null) return -1;
if (y == null) return 1;
int minLen = Math.Min(x.Length, y.Length);
for (int i = 0; i < minLen; i++)
{
int orderX = GetCharOrder(x[i]);
int orderY = GetCharOrder(y[i]);
if (orderX != orderY) return orderX.CompareTo(orderY);
// Same category, compare case-insensitively
int cmp = char.ToLowerInvariant(x[i]).CompareTo(char.ToLowerInvariant(y[i]));
if (cmp != 0) return cmp;
}
return x.Length.CompareTo(y.Length); // Shorter string comes first
}
private static int GetCharOrder(char c)
{
// Order: underscore (0), digits (1), letters (2), everything else (3)
if (c == '_') return 0;
if (char.IsDigit(c)) return 1;
if (char.IsLetter(c)) return 2;
return 3;
}
}
private DateTime ParseDate(string dateStr)
{
if (string.IsNullOrEmpty(dateStr)) return DateTime.MinValue;
string[] formats = { "yyyy-MM-dd HH:mm 'UTC'", "yyyy-MM-dd HH:mm" };
return DateTime.TryParseExact(dateStr, formats, System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.AssumeUniversal | System.Globalization.DateTimeStyles.AdjustToUniversal,
out DateTime date) ? date : DateTime.MinValue;
}
private double ParseSize(string sizeStr)
{
if (string.IsNullOrEmpty(sizeStr)) return 0;
sizeStr = sizeStr.Trim(); // Remove whitespace
// Handle new format: "1.23 GB" or "123 MB"
if (sizeStr.EndsWith(" GB", StringComparison.OrdinalIgnoreCase))
{
if (double.TryParse(sizeStr.Substring(0, sizeStr.Length - 3).Trim(), System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture, out double gb)) return gb * 1024.0; // Convert GB to MB for consistent sorting
}
else if (sizeStr.EndsWith(" MB", StringComparison.OrdinalIgnoreCase))
{
if (double.TryParse(sizeStr.Substring(0, sizeStr.Length - 3).Trim(), System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture, out double mb)) return mb;
}
// Fallback: try parsing as raw number
if (double.TryParse(sizeStr, System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture, out double raw)) return raw;
return 0;
}
public void UpdateItems(List<ListViewItem> newItems)
{
if (newItems == null) newItems = new List<ListViewItem>();
_originalItems = new List<ListViewItem>(newItems);
_items = new List<ListViewItem>(newItems);
// Reset selection and hover states
_hoveredIndex = -1;
_selectedIndex = -1;
_selectedItem = null;
_isHoveringDeleteButton = false;
CloseOverlay();
// Reset scroll position for new results
_scrollY = 0;
_targetScrollY = 0;
_isScrolling = false;
// Refresh favorites cache and re-apply sort
RefreshFavoritesCache();
ApplySort();
}
public ListViewItem GetItemAtIndex(int index)
{
if (_selectedItem != null) return _selectedItem;
if (index >= 0 && index < _displayTiles.Count)
return _displayTiles[index].Primary;
return null;
}
private bool IsItemInstalled(ListViewItem item)
{
if (item == null) return false;
return item.ForeColor.ToArgb() == MainForm.ColorInstalled.ToArgb() ||
item.ForeColor.ToArgb() == MainForm.ColorUpdateAvailable.ToArgb() ||
item.ForeColor.ToArgb() == MainForm.ColorDonateGame.ToArgb();
}
private bool IsAnyVersionInstalled(GroupedTile tile)
{
return tile.Versions.Any(v => IsItemInstalled(v));
}
private Rectangle GetDeleteButtonRect(int index, int row, int col, int scrollY)
{
if (!_tileStates.TryGetValue(index, out var state)) state = new TileAnimationState();
int baseX = _leftPadding + col * (_tileWidth + _spacing);
int baseY = _spacing + SORT_PANEL_HEIGHT + row * (_tileHeight + _spacing) - scrollY;
float scale = state.Scale;
int scaledW = (int)(_tileWidth * scale);
int scaledH = (int)(_tileHeight * scale);
int x = baseX - (scaledW - _tileWidth) / 2;
int y = baseY - (scaledH - _tileHeight) / 2;
// Position delete button in bottom-right corner of thumbnail
int btnX = x + scaledW - DELETE_BUTTON_SIZE - 2 - DELETE_BUTTON_MARGIN;
int btnY = y + 2 + scaledH - DELETE_BUTTON_SIZE - DELETE_BUTTON_MARGIN - 20;
return new Rectangle(btnX, btnY, DELETE_BUTTON_SIZE, DELETE_BUTTON_SIZE);
}
private void AnimationTimer_Tick(object sender, EventArgs e)
{
bool needsRedraw = false;
// Smooth scrolling
if (_isScrolling)
{
float diff = _targetScrollY - _scrollY;
if (Math.Abs(diff) > 0.5f)
{
_scrollY += diff * SCROLL_SMOOTHING;
_scrollY = Math.Max(0, Math.Min(_scrollY, Math.Max(0, _contentHeight - (Height - SORT_PANEL_HEIGHT))));
if (_scrollBar.Visible && _scrollBar.Value != (int)_scrollY)
_scrollBar.Value = Math.Max(_scrollBar.Minimum, Math.Min(_scrollBar.Maximum - _scrollBar.LargeChange + 1, (int)_scrollY));
needsRedraw = true;
}
else { _scrollY = _targetScrollY; _isScrolling = false; }
}
if (Math.Abs(_expandOverlayOpacity - _targetExpandOverlayOpacity) > 0.01f)
{
_expandOverlayOpacity += (_targetExpandOverlayOpacity - _expandOverlayOpacity) * 0.4f;
needsRedraw = true;
}
else _expandOverlayOpacity = _targetExpandOverlayOpacity;
// Update overlay hover state based on current mouse position
if (_expandedTileIndex >= 0 && _expandOverlayOpacity > 0.5f && _versionRects.Count > 0)
{
var mousePos = PointToClient(Cursor.Position);
int newHover = GetOverlayVersionAtPoint(mousePos.X, mousePos.Y);
if (newHover != _overlayHoveredVersion)
{
_overlayHoveredVersion = newHover;
needsRedraw = true;
// Update release notes when hovering over a version
if (newHover >= 0 && newHover < _displayTiles[_expandedTileIndex].Versions.Count)
{
var hoveredVersion = _displayTiles[_expandedTileIndex].Versions[newHover];
string releaseName = hoveredVersion.SubItems.Count > 1 ? hoveredVersion.SubItems[1].Text : "";
TileHovered?.Invoke(this, releaseName);
}
}
}
// Tile animations - only process visible tiles for performance
int scrollYInt = (int)_scrollY;
int startRow = Math.Max(0, (scrollYInt - _spacing - _tileHeight) / (_tileHeight + _spacing));
int endRow = Math.Min(_rows - 1, (scrollYInt + Height + _tileHeight) / (_tileHeight + _spacing));
for (int row = startRow; row <= endRow; row++)
{
for (int col = 0; col < _columns; col++)
{
int index = row * _columns + col;
if (index >= _displayTiles.Count) break;
if (!_tileStates.TryGetValue(index, out var state))
{
state = new TileAnimationState();
_tileStates[index] = state;
}
var tile = _displayTiles[index];
bool isHovered = index == _hoveredIndex && _expandedTileIndex < 0;
bool isSelected = index == _selectedIndex;
bool isInstalled = IsAnyVersionInstalled(tile);
string pkgName = tile.Primary.SubItems.Count > 1 ? tile.Primary.SubItems[1].Text : "";
bool isFavorite = _favoritesCache.Contains(pkgName);
state.TargetFavoriteOpacity = isFavorite ? 1.0f : 0f;
state.TargetScale = isHovered ? HOVER_SCALE : 1.0f;
state.TargetBorderOpacity = isHovered ? 1.0f : 0f;
state.TargetBackgroundBrightness = isHovered ? 45f : (isSelected ? 38f : 30f);
state.TargetSelectionOpacity = isSelected ? 1.0f : 0f;
state.TargetTooltipOpacity = isHovered ? 1.0f : 0f;
state.TargetDeleteButtonOpacity = (isHovered && isInstalled) ? 1.0f : 0f;
state.TargetGroupBadgeOpacity = tile.Versions.Count > 1 ? 1.0f : 0f;
needsRedraw |= AnimateValue(ref state.Scale, state.TargetScale, ANIMATION_SPEED, 0.001f);
needsRedraw |= AnimateValue(ref state.BorderOpacity, state.TargetBorderOpacity, ANIMATION_SPEED, 0.01f);
needsRedraw |= AnimateValue(ref state.BackgroundBrightness, state.TargetBackgroundBrightness, ANIMATION_SPEED, 0.5f);
needsRedraw |= AnimateValue(ref state.SelectionOpacity, state.TargetSelectionOpacity, ANIMATION_SPEED, 0.01f);
needsRedraw |= AnimateValue(ref state.TooltipOpacity, state.TargetTooltipOpacity, 0.35f, 0.01f);
needsRedraw |= AnimateValue(ref state.DeleteButtonOpacity, state.TargetDeleteButtonOpacity, 0.35f, 0.01f);
needsRedraw |= AnimateValue(ref state.FavoriteOpacity, state.TargetFavoriteOpacity, 0.35f, 0.01f);
needsRedraw |= AnimateValue(ref state.GroupBadgeOpacity, state.TargetGroupBadgeOpacity, 0.35f, 0.01f);
}
}
if (needsRedraw) Invalidate();
}
private bool AnimateValue(ref float current, float target, float speed, float threshold)
{
if (Math.Abs(current - target) > threshold)
{
current += (target - current) * speed;
return true;
}
current = target;
return false;
}
protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified)
{
if (height <= 0 && Height > 0) height = Height;
if (width <= 0 && Width > 0) width = Width;
base.SetBoundsCore(x, y, width, height, specified);
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
if (Width > 0 && Height > 0 && _scrollBar != null) { RecalculateLayout(); Refresh(); }
}
protected override void OnParentChanged(EventArgs e)
{
base.OnParentChanged(e);
if (Parent != null && !IsDisposed && !Disposing) RecalculateLayout();
}
private void RecalculateLayout()
{
if (IsDisposed || Disposing || _scrollBar == null || Width <= 0 || Height <= 0) return;
int availableHeight = Height - SORT_PANEL_HEIGHT;
_scrollBar.SetBounds(Width - _scrollBar.Width, SORT_PANEL_HEIGHT, _scrollBar.Width, availableHeight);
int availableWidth = Width - _scrollBar.Width - _spacing * 2;
_columns = Math.Max(1, (availableWidth + _spacing) / (_tileWidth + _spacing));
_rows = (int)Math.Ceiling((double)_displayTiles.Count / _columns);
_contentHeight = _rows * (_tileHeight + _spacing) + _spacing + 20;
int usedWidth = _columns * (_tileWidth + _spacing) - _spacing;
_leftPadding = Math.Max(_spacing, (availableWidth - usedWidth) / 2 + _spacing);
_scrollBar.Maximum = Math.Max(0, _contentHeight);
_scrollBar.LargeChange = Math.Max(1, availableHeight);
_scrollBar.Visible = _contentHeight > availableHeight;
_scrollY = Math.Max(0, Math.Min(_scrollY, Math.Max(0, _contentHeight - availableHeight)));
_targetScrollY = _scrollY;
if (_scrollBar.Visible) _scrollBar.Value = (int)_scrollY;
if (_backBuffer == null || _backBuffer.Width != Width || _backBuffer.Height != Height)
{
_backBuffer?.Dispose();
_backBuffer = new Bitmap(Math.Max(1, Width), Math.Max(1, Height));
}
}
protected override void OnPaint(PaintEventArgs e)
{
if (_backBuffer == null) return;
using (var g = Graphics.FromImage(_backBuffer))