-
-
Notifications
You must be signed in to change notification settings - Fork 697
Expand file tree
/
Copy pathFrmSlideshow.cs
More file actions
2271 lines (1799 loc) · 66.3 KB
/
FrmSlideshow.cs
File metadata and controls
2271 lines (1799 loc) · 66.3 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
/*
ImageGlass Project - Image viewer for Windows
Copyright (C) 2010 - 2026 DUONG DIEU PHAP
Project homepage: https://imageglass.org
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using Cysharp.Text;
using D2Phap.DXControl;
using ImageGlass.Base;
using ImageGlass.Base.PhotoBox;
using ImageGlass.Base.Photoing.Codecs;
using ImageGlass.Base.Services;
using ImageGlass.Base.WinApi;
using ImageGlass.Settings;
using ImageGlass.Tools;
using ImageGlass.UI;
using ImageGlass.Viewer;
using System.ComponentModel;
using System.Diagnostics;
using System.Media;
using Timer = System.Windows.Forms.Timer;
namespace igcmd.Tools;
public partial class FrmSlideshow : ThemedForm
{
private ImageGlassTool _igTool = new();
private string _initImagePath;
private CancellationTokenSource? _loadCancelTokenSrc = new();
private MovableForm? _movableForm;
private ImageBooster _images = new();
private int _currentIndex = -1;
private IgMetadata? _currentMetadata = null;
private Timer _slideshowTimer = new() { Enabled = false };
private Stopwatch _slideshowStopwatch = new(); // slideshow stopwatch
private float _slideshowCountdown = 5; // slideshow countdown interval
private Rectangle _windowBound = new();
private FormWindowState _windowState = FormWindowState.Normal;
private int _numberImageChangeCount = 0;
private CancellationTokenSource _hideCursorCancelToken = new();
private bool _isCursorHidden = false;
private bool _isColorPickerOpen = false;
/// <summary>
/// Hotkeys list of main menu
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public static Dictionary<string, List<Hotkey>> CurrentMenuHotkeys { get; set; } = new()
{
// Open context menu
{ nameof(MnuContext), new() { new(Keys.Alt | Keys.F) } },
{ nameof(MnuPauseResumeSlideshow), new() { new(Keys.Space) } },
// MnuNavigation
{ nameof(MnuViewNext), new() { new (Keys.Right) } },
{ nameof(MnuViewPrevious), new() { new (Keys.Left) } },
{ nameof(MnuGoToFirst), new() { new (Keys.Home) } },
{ nameof(MnuGoToLast), new() { new (Keys.End) } },
{ nameof(MnuWindowFit), new() { new (Keys.F9) } },
{ nameof(MnuFrameless), new() { new (Keys.F10) } },
{ nameof(MnuFullScreen), new() { new (Keys.F11) } },
{ nameof(MnuToggleCountdown), new() { new (Keys.C) } },
{ nameof(MnuToggleCheckerboard), new() { new (Keys.B) } },
{ nameof(MnuChangeBackgroundColor), new() { new (Keys.M) } },
{ nameof(MnuCustomZoom), new() { new (Keys.Z) } },
{ nameof(MnuActualSize), new() { new (Keys.D0), new (Keys.NumPad0) } },
{ nameof(MnuAutoZoom), new() { new (Keys.D1), new (Keys.NumPad1) } },
{ nameof(MnuLockZoom), new() { new (Keys.D2), new (Keys.NumPad2) } },
{ nameof(MnuScaleToWidth), new() { new (Keys.D3), new (Keys.NumPad3) } },
{ nameof(MnuScaleToHeight), new() { new (Keys.D4), new (Keys.NumPad4) } },
{ nameof(MnuScaleToFit), new() { new (Keys.D5), new (Keys.NumPad5) } },
{ nameof(MnuScaleToFill), new() { new (Keys.D6), new (Keys.NumPad6) } },
{ nameof(MnuOpenWith), new() { new (Keys.D) } },
{ nameof(MnuOpenLocation), new() { new (Keys.L) } },
{ nameof(MnuCopyPath), new() { new (Keys.Control | Keys.L) } },
{ nameof(MnuMoveToRecycleBin), new() { new (Keys.Delete) } },
{ nameof(MnuDeleteFromHardDisk), new() { new (Keys.Shift | Keys.Delete) } },
{ nameof(MnuExitSlideshow), new() { new(Keys.Escape) } },
};
public FrmSlideshow(string initImagePath)
{
InitializeComponent();
// update the DpiApi when DPI changed.
EnableDpiApiUpdate = true;
Config.Load();
// load configs
_initImagePath = initImagePath;
Text = $"{Config.Language["FrmMain.MnuSlideshow"]} - {App.AppName}";
SetUpFrmSlideshowConfigs();
// initialize ImageGlassTool
_ = ConnectToImageGlassAsync();
// update theme icons
OnDpiChanged();
ApplyTheme(Config.Theme.Settings.IsDarkMode, Config.WindowBackdrop);
}
private void SetUpFrmSlideshowConfigs()
{
SuspendLayout();
PicMain.InterpolationScaleDown = Config.ImageInterpolationScaleDown;
PicMain.InterpolationScaleUp = Config.ImageInterpolationScaleUp;
Config.EnableSlideshow = true;
MnuToggleCountdown.Checked = Config.ShowSlideshowCountdown;
// zoom mode
SetZoomMode(Config.ZoomMode);
if (Config.ZoomMode == ZoomMode.LockZoom)
{
PicMain.ZoomFactor = Config.ZoomLockValue / 100f;
}
// menu
MnuContext.CurrentDpi = DeviceDpi;
ResumeLayout(false);
}
// Protected methods
#region Protected methods
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
_slideshowTimer.Interval = 10; // support milliseconds
_slideshowTimer.Tick += SlideshowTimer_Tick;
// Enable form movable: must be before IG_ToggleFullScreen()
IG_SetWindowMoveable(true);
// full screen slideshow
if (Config.EnableFullscreenSlideshow)
{
// toggle frameless window
IG_ToggleFrameless(Config.EnableFrameless, false);
// toggle Window fit
IG_ToggleWindowFit(Config.EnableWindowFit);
// to hide the animation effect of window border
FormBorderStyle = FormBorderStyle.None;
// load window placement from settings here to save the initial
// position of window so that when user exists the fullscreen mode,
// it can be restore correctly
WindowSettings.LoadFrmMainPlacementFromConfig(this,
SystemInformation.CaptionHeight,
SystemInformation.CaptionHeight);
IG_ToggleFullScreen(true);
}
// windowed slideshow
else
{
// load window placement from settings
WindowSettings.LoadFrmMainPlacementFromConfig(this,
SystemInformation.CaptionHeight,
SystemInformation.CaptionHeight);
// toggle frameless window
IG_ToggleFrameless(Config.EnableFrameless, false);
// toggle Window fit
IG_ToggleWindowFit(Config.EnableWindowFit);
}
// load the init image
_ = BHelper.RunAsThread(() => _ = LoadImageAsync(_initImagePath, _loadCancelTokenSrc));
// load menu hotkeys
CurrentMenuHotkeys = Config.GetAllHotkeys(CurrentMenuHotkeys);
LoadMenuHotkeys();
LoadMenuTagData();
// load language
LoadLanguage();
// start slideshow
SetSlideshowState(true);
// focus on PicMain
PicMain.Focus();
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing(e);
_igTool.Dispose();
}
protected override void ApplyTheme(bool darkMode, BackdropStyle? style = null)
{
SuspendLayout();
style ??= Config.WindowBackdrop;
var hasTransparency = EnableTransparent && style.Value != BackdropStyle.None;
if (!hasTransparency)
{
BackColor = Config.SlideshowBackgroundColor.NoAlpha();
WindowApi.SetTitleBar(Handle, Config.SlideshowBackgroundColor, Config.SlideshowBackgroundColor.InvertBlackOrWhite(220));
}
else
{
WindowApi.SetTitleBar(Handle, null, null);
}
// menu
MnuContext.Theme = Config.Theme;
// viewer
PicMain.EnableTransparent = hasTransparency;
PicMain.BackColor = Config.SlideshowBackgroundColor;
PicMain.ForeColor = PicMain.BackColor.InvertBlackOrWhite(220);
PicMain.AccentColor = WinColorsApi.GetAccentColor(true);
PicMain.NavLeftImage = Config.Theme.Settings.NavButtonLeft;
PicMain.NavRightImage = Config.Theme.Settings.NavButtonRight;
PicMain.Web2DarkMode = darkMode;
PicMain.Web2NavLeftImagePath = Config.Theme.NavLeftImagePath;
PicMain.Web2NavRightImagePath = Config.Theme.NavRightImagePath;
// set app logo on titlebar
_ = Config.UpdateFormIcon(this);
// update webview2 styles
if (PicMain.UseWebview2) PicMain.UpdateWeb2Styles(darkMode);
base.ApplyTheme(darkMode, style);
ResumeLayout(false);
}
protected override void OnSystemAccentColorChanged(SystemAccentColorChangedEventArgs e)
{
Config.Theme.LoadThemeColors();
PicMain.AccentColor = SystemAccentColorChangedEventArgs.AccentColor;
PicMain.Invalidate();
// do not handle this event again in the parent class
e.Handled = true;
base.OnSystemAccentColorChanged(e);
}
protected override void OnRequestUpdatingColorMode(SystemColorModeChangedEventArgs e)
{
base.OnRequestUpdatingColorMode(e);
// load the theme icons
OnDpiChanged();
// apply theme to controls
ApplyTheme(Config.Theme.Settings.IsDarkMode);
}
protected override void OnDpiChanged(DpiChangedEventArgs e)
{
base.OnDpiChanged(e);
MnuContext.CurrentDpi = e.DeviceDpiNew;
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
// to fix arrow keys sometimes does not regconize
if (keyData == Keys.Up
|| keyData == Keys.Down
|| keyData == Keys.Left
|| keyData == Keys.Right)
{
FrmSlideshow_KeyDown(this, new KeyEventArgs(keyData));
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
#endregion // Protected methods
// ImageGlassTool connection
#region ImageGlassTool connection
private async Task ConnectToImageGlassAsync()
{
_igTool.ToolMessageReceived += IgTool_ToolMessageReceived;
_igTool.ToolClosingRequest += IgTool_ToolClosingRequest;
await _igTool.ConnectAsync();
}
private void IgTool_ToolClosingRequest(object? sender, DisconnectedEventArgs e)
{
Close();
}
private void IgTool_ToolMessageReceived(object? sender, MessageReceivedEventArgs e)
{
if (string.IsNullOrEmpty(e.MessageData)) return;
// update image list
if (e.MessageName.Equals(ImageGlassEvents.IMAGE_LIST_UPDATED, StringComparison.InvariantCultureIgnoreCase))
{
var data = IgImageListUpdatedEventArgs.Deserialize(e.MessageData);
var newInitFile = !_initImagePath.Equals(data.InitFilePath, StringComparison.InvariantCultureIgnoreCase);
_initImagePath = data.InitFilePath ?? _initImagePath;
if (data != null && data.Files.Count > 0)
{
_ = BHelper.RunAsThread(async () =>
{
// update the current image if it's not same
if (!string.IsNullOrEmpty(data.InitFilePath) && newInitFile)
{
_ = LoadImageAsync(_initImagePath, _loadCancelTokenSrc);
}
await LoadImageListAsync(data.Files, _initImagePath);
// enable slideshow
SetSlideshowState(true, false);
});
}
return;
}
// update language
if (e.MessageName.Equals(ImageGlassEvents.LANG_UPDATED, StringComparison.InvariantCultureIgnoreCase))
{
Config.Language = new IgLang(e.MessageData, App.StartUpDir(Dir.Language));
LoadLanguage();
return;
}
// update theme
if (e.MessageName.Equals(ImageGlassEvents.THEME_UPDATED, StringComparison.InvariantCultureIgnoreCase))
{
Config.Theme = new IgTheme(e.MessageData);
ApplyTheme(Config.Theme.Settings.IsDarkMode);
return;
}
}
#endregion // ImageGlass server connection
// PicMain events
#region PicMain events
private void PicMain_Render(object? sender, RenderEventArgs e)
{
if (!_slideshowTimer.Enabled || !Config.ShowSlideshowCountdown) return;
// draw countdown text ----------------------------------------------
var countdownTime = TimeSpan.FromSeconds(_slideshowCountdown + 1);
var text = (countdownTime - _slideshowStopwatch.Elapsed).ToString("mm'∶'ss");
var font = new Font(Font.FontFamily, 30f);
var fontSize = e.Graphics.MeasureText(text, font.Name, font.Size, textDpi: DeviceDpi);
// calculate background size
var gapX = fontSize.Width / 4;
var gapY = fontSize.Height / 4;
var padding = DpiApi.Scale(30);
var bgSize = new SizeF(fontSize.Width + gapX, fontSize.Height + gapY);
var bgX = PicMain.Width - bgSize.Width - padding;
var bgY = PicMain.Height - bgSize.Height - padding;
// draw background
var borderRadius = BHelper.IsOS(WindowsOS.Win11OrLater) ? PicMain.MessageBorderRadius : 1;
var bgColor = Color.FromArgb(150, PicMain.BackColor);
var bgRect = new RectangleF(bgX, bgY, bgSize.Width, bgSize.Height);
e.Graphics.DrawRectangle(bgRect, borderRadius, bgColor, bgColor);
// calculate text position
var fontX = bgX + (bgSize.Width / 2) - (fontSize.Width / 2);
var fontY = bgY + (bgSize.Height / 2) - (fontSize.Height / 2);
// draw text
var textColor = PicMain.BackColor.InvertBlackOrWhite(150);
e.Graphics.DrawText(text, font.Name, font.Size, fontX, fontY, textColor, textDpi: DeviceDpi);
}
private void PicMain_MouseWheel(object? sender, MouseEventArgs e)
{
if (_isCursorHidden)
{
Cursor.Show();
_isCursorHidden = false;
}
DelayHideCursor();
MouseWheelAction action;
var eventType = ModifierKeys switch
{
Keys.Control => MouseWheelEvent.CtrlAndScroll,
Keys.Shift => MouseWheelEvent.ShiftAndScroll,
Keys.Alt => MouseWheelEvent.AltAndScroll,
_ => MouseWheelEvent.Scroll,
};
// Get mouse wheel action
#region Get mouse wheel action
// get user-defined mouse wheel action
if (Config.MouseWheelActions.TryGetValue(eventType, out MouseWheelAction value))
{
action = value;
}
// if not found, use the defaut mouse wheel action
else
{
switch (eventType)
{
case MouseWheelEvent.Scroll:
action = MouseWheelAction.Zoom;
break;
case MouseWheelEvent.CtrlAndScroll:
action = MouseWheelAction.PanVertically;
break;
case MouseWheelEvent.ShiftAndScroll:
action = MouseWheelAction.PanHorizontally;
break;
case MouseWheelEvent.AltAndScroll:
action = MouseWheelAction.BrowseImages;
break;
default:
action = MouseWheelAction.DoNothing;
break;
}
}
#endregion
// Run mouse wheel action
#region Run mouse wheel action
if (action == MouseWheelAction.Zoom)
{
PicMain.ZoomByDeltaToPoint(e.Delta, e.Location);
}
else if (action == MouseWheelAction.PanVertically)
{
if (e.Delta > 0)
{
PicMain.PanUp(e.Delta + PicMain.PanDistance / 4);
}
else
{
PicMain.PanDown(Math.Abs(e.Delta) + PicMain.PanDistance / 4);
}
}
else if (action == MouseWheelAction.PanHorizontally)
{
if (e.Delta > 0)
{
PicMain.PanLeft(e.Delta + PicMain.PanDistance / 4);
}
else
{
PicMain.PanRight(Math.Abs(e.Delta) + PicMain.PanDistance / 4);
}
}
else if (action == MouseWheelAction.BrowseImages)
{
if (e.Delta < 0)
{
_ = ViewNextImageAsync(1);
}
else
{
_ = ViewNextImageAsync(-1);
}
}
#endregion
}
private void PicMain_MouseClick(object? sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
// handle right-click action for webview2
if (PicMain.UseWebview2)
{
var point = this.PointToScreen(e.Location);
point.X += PicMain.Left;
point.Y += PicMain.Top;
MnuContext.Show(point);
}
}
if (_isCursorHidden)
{
Cursor.Show();
_isCursorHidden = false;
}
DelayHideCursor();
}
private void PicMain_OnNavLeftClicked(object? sender, MouseEventArgs e)
{
_ = ViewNextImageAsync(-1);
}
private void PicMain_OnNavRightClicked(object? sender, MouseEventArgs e)
{
_ = ViewNextImageAsync(1);
}
private void PicMain_OnZoomChanged(object? sender, ZoomEventArgs e)
{
// Handle window fit after zoom change
if (Config.EnableWindowFit && !e.IsPreviewingImage && (e.IsManualZoom || e.IsZoomModeChange))
{
FitWindowToImage(e.ChangeSource == ZoomChangeSource.ZoomMode);
}
LoadImageInfo(ImageInfoUpdateTypes.Zoom);
}
private void PicMain_MouseMove(object? sender, MouseEventArgs e)
{
if (_isCursorHidden)
{
Cursor.Show();
_isCursorHidden = false;
}
DelayHideCursor();
}
private void PicMain_MouseLeave(object sender, EventArgs e)
{
Cursor.Show();
_isCursorHidden = false;
}
private void PicMain_Web2NavigationCompleted(object sender, EventArgs e)
{
var langJson = BHelper.ToJson(Config.Language);
_ = PicMain.LoadWeb2LanguageAsync(langJson);
}
private void PicMain_Web2PointerDown(object sender, MouseEventArgs e)
{
if (_isCursorHidden)
{
Cursor.Show();
_isCursorHidden = false;
}
// make sure all menus closed when mouse clicked
MnuContext.Close();
}
private void PicMain_Web2KeyDown(object sender, KeyEventArgs e)
{
// pass keydown to FrmMain
this.OnKeyDown(e);
}
private void PicMain_Web2KeyUp(object sender, KeyEventArgs e)
{
// pass keyup to FrmMain
this.OnKeyUp(e);
}
#endregion // PicMain events
// Load image
#region Load image
/// <summary>
/// Loads image list
/// </summary>
/// <param name="initFilePath">The initial file path to find image index.</param>
private async Task LoadImageListAsync(IEnumerable<string> fileList, string? initFilePath = null)
{
await Task.Run(() =>
{
var list = BHelper.SortFilePathList(fileList,
Config.ImageLoadingOrder,
Config.ImageLoadingOrderType,
Config.ShouldGroupImagesByDirectory);
_images = new ImageBooster(list)
{
MaxQueue = 1,
MaxFileSizeInMbToCache = 100,
MaxImageDimensionToCache = Const.MAX_IMAGE_DIMENSION,
};
if (string.IsNullOrEmpty(initFilePath))
{
_currentIndex = 0;
return;
}
// this part of code fixes calls on legacy 8.3 filenames
// (for example opening files from IBM Notes)
var di = new DirectoryInfo(initFilePath);
initFilePath = di.FullName;
// Find the index of current image
_currentIndex = _images.IndexOf(initFilePath);
LoadImageInfo();
});
}
/// <summary>
/// View the next image
/// </summary>
private async Task ViewNextImageAsync(int step = 0)
{
_loadCancelTokenSrc?.Cancel();
_loadCancelTokenSrc = new();
// Issue #609: do not auto-reactivate slideshow if disabled
if (_slideshowTimer.Enabled)
{
_slideshowTimer.Enabled = false;
_slideshowTimer.Enabled = true;
_slideshowStopwatch.Reset();
}
// Validate image index
#region Validate image index
// temp index
var imageIndex = _currentIndex + step;
if (_images.Length > 0)
{
// Reach end of list
if (imageIndex >= _images.Length)
{
if (!Config.EnableLoopBackNavigation)
{
PicMain.ShowMessage(Config.Language[$"{Name}._ReachedFirstImage"],
Config.InAppMessageDuration);
return;
}
}
// Reach the first image of list
if (imageIndex < 0)
{
if (!Config.EnableLoopBackNavigation)
{
PicMain.ShowMessage(Config.Language[$"{Name}._ReachedLastLast"],
Config.InAppMessageDuration);
return;
}
}
}
// Check if current index is greater than upper limit
if (imageIndex >= _images.Length)
imageIndex = 0;
// Check if current index is less than lower limit
if (imageIndex < 0)
imageIndex = _images.Length - 1;
// Update current index
_currentIndex = imageIndex;
#endregion // Validate image index
await LoadImageAsync(null, _loadCancelTokenSrc);
}
/// <summary>
/// Loads image to the viewer.
/// </summary>
/// <param name="filePath">Use <see cref="_currentIndex"/> if <paramref name="filePath"/> is <c>null</c>.</param>
private async Task LoadImageAsync(string? filePath, CancellationTokenSource? tokenSrc = null)
{
if (InvokeRequired)
{
Invoke(LoadImageAsync, filePath, tokenSrc);
return;
}
IgPhoto? photo = null;
var readSettings = new CodecReadOptions()
{
ColorProfileName = Config.ColorProfile,
ApplyColorProfileForAll = Config.ShouldUseColorProfileForAll,
AutoScaleDownLargeImage = true,
UseEmbeddedThumbnailRawFormats = Config.UseEmbeddedThumbnailRawFormats,
UseEmbeddedThumbnailOtherFormats = Config.UseEmbeddedThumbnailOtherFormats,
EmbeddedThumbnailMinWidth = Config.EmbeddedThumbnailMinWidth,
EmbeddedThumbnailMinHeight = Config.EmbeddedThumbnailMinHeight,
MinDimensionToUseWIC = Config.MinDimensionToUseWIC,
FirstFrameOnly = true,
CorrectRotation = true,
};
var imgFilePath = filePath;
if (string.IsNullOrWhiteSpace(imgFilePath))
{
imgFilePath = _images.GetFilePath(_currentIndex);
}
else
{
photo = new IgPhoto(imgFilePath);
}
try
{
// get metadata
_currentMetadata = PhotoCodec.LoadMetadata(imgFilePath, readSettings);
// check if we should use Webview2 viewer
var useWebview2 = Config.UseWebview2ForSvg
&& imgFilePath.EndsWith(".svg", StringComparison.InvariantCultureIgnoreCase);
// on image loading
OnImageLoading();
// check if loading is cancelled
tokenSrc?.Token.ThrowIfCancellationRequested();
// if we are using Webview2
if (useWebview2)
{
photo = new IgPhoto(imgFilePath)
{
Metadata = _currentMetadata,
};
}
else
{
// directly load the image file, skip image list
if (photo != null)
{
await photo.LoadAsync(readSettings, tokenSrc);
}
else
{
photo = await _images.GetAsync(_currentIndex, tokenSrc: tokenSrc);
}
}
// check if loading is cancelled
tokenSrc?.Token.ThrowIfCancellationRequested();
// on image loaded
OnImageLoaded(photo, useWebview2);
}
catch (OperationCanceledException)
{
_images.CancelLoading(_currentIndex);
}
}
private void OnImageLoading()
{
if (InvokeRequired)
{
Invoke(OnImageLoading);
return;
}
PicMain.ClearMessage();
PicMain.ShowMessage(Config.Language[$"FrmMain._Loading"], null, delayMs: 1500);
LoadImageInfo(null, _currentMetadata.FilePath);
}
private void OnImageLoaded(IgPhoto photo, bool useWebview2)
{
if (InvokeRequired)
{
OnImageLoaded(photo, useWebview2);
return;
}
var error = photo.Error;
// if image needs to display in Webview2 viweer
if (useWebview2)
{
PicMain.ClearMessage();
try
{
_ = PicMain.SetImageWeb2Async(photo, _loadCancelTokenSrc.Token);
}
catch (Exception ex) { error = ex; }
}
// image error
if (error != null)
{
PicMain.SetImage(null);
var emoji = BHelper.IsOS(WindowsOS.Win11OrLater) ? "🥲" : "🙄";
var archInfo = Environment.Is64BitProcess ? "64-bit" : "32-bit";
var appVersion = App.Version + $" ({archInfo}, .NET {Environment.Version})";
var debugInfo = $"ImageGlass {Const.APP_CODE.CapitalizeFirst()} v{appVersion}" +
$"\r\n{ImageMagick.MagickNET.Version}" +
$"\r\n" +
$"\r\nℹ️ Error details:" +
$"\r\n";
var errorLines = error.StackTrace?.Split("\r\n", StringSplitOptions.RemoveEmptyEntries).Take(2) ?? [];
var errDetails = error.Message + "\r\n\r\n" + string.Join("\r\n", errorLines);
PicMain.ShowMessage(debugInfo +
error.Source + ": " + errDetails,
Config.Language[$"FrmMain.PicMain._ErrorText"] + $" {emoji}");
}
// use native viewer to display image
else if (!(photo?.ImgData.IsImageNull ?? true))
{
// set the main image
PicMain.SetImage(photo.ImgData,
resetZoom: true,
initOpacity: 0.4f,
opacityStep: 0.02f);
// update window fit
if (Config.EnableWindowFit)
{
FitWindowToImage(false);
}
PicMain.ClearMessage();
// reset countdown timer value
_slideshowCountdown = RandomizeSlideshowInterval();
// since the UI does not print milliseconds,
// this prevents the coutdown to flash the maximum value during the first tick
if (_slideshowCountdown == Math.Ceiling(_slideshowCountdown))
{
_slideshowCountdown -= 0.001f;
}
}
// load image info
LoadImageInfo(ImageInfoUpdateTypes.Dimension | ImageInfoUpdateTypes.FrameCount);
// notify image changes
if (Config.SlideshowImagesToNotifySound > 0)
{
if (_numberImageChangeCount >= Config.SlideshowImagesToNotifySound - 1)
{
SystemSounds.Asterisk.Play();
_numberImageChangeCount = 0;
}
else
{
_numberImageChangeCount++;
}
}
// Collect system garbage
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
#endregion // Load image
// Slideshow methods
#region Slideshow methods
private void FrmSlideshow_KeyDown(object sender, KeyEventArgs e)
{
if (_isCursorHidden)
{
Cursor.Show();
_isCursorHidden = false;
}
var hotkey = new Hotkey(e.KeyData);
var actions = Config.GetHotkeyActions(CurrentMenuHotkeys, hotkey);
// open context menu
if (actions.Contains(nameof(MnuContext)))
{
MnuContext.Show(this, (PicMain.Width - MnuContext.Width) / 2, (PicMain.Height - MnuContext.Height) / 2);
return;
}
#region Register and run CONTEXT MENU shortcuts
bool CheckMenuShortcut(ToolStripMenuItem mnu)
{
var menuHotkeyList = Config.GetHotkey(CurrentMenuHotkeys, mnu.Name);
var menuHotkey = menuHotkeyList.SingleOrDefault(k => k.KeyData == e.KeyData);