-
Notifications
You must be signed in to change notification settings - Fork 23
/
umainform.pas
2056 lines (1767 loc) · 60.5 KB
/
umainform.pas
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
unit uMainForm;
{$mode objfpc}{$H+}
interface
uses
{$IfDef Windows}
Windows,
{$EndIf}
{$IfDef Linux}
xlib, xrandr, XRandREventWatcher,
{$EndIf}
{Messages,} SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, {ComCtrls,} ExtCtrls, StdCtrls, inifiles, Spin, {FileCtrl,}
Menus, Buttons, EditBtn, uLocalization, DateTimePicker, LCLIntf,
ScreenGrabber, uHotKeysForm, uUtilsMore, GlobalKeyHook, OldScreenshotCleaner,
UniqueInstance, uplaysound, ZStream { for Tcompressionlevel };
type
TTrayIconState = (tisDefault, tisBlackWhite, tisFlashAnimation);
{ TMainForm }
TMainForm = class(TForm)
AutoCheckForUpdatesMenuItem: TMenuItem;
FileMenuItem: TMenuItem;
ExitMenuItem: TMenuItem;
LangFlagImageList: TImageList;
MinimizeInsteadOfCloseCheckBox: TCheckBox;
PlaySoundsCheckBox: TCheckBox;
CompressionLevelComboBox: TComboBox;
OldScreenshotCleanerEnabledCheckBox: TCheckBox;
HotKetsSettingsMenuItem: TMenuItem;
CompressionLevelLabel: TLabel;
ImageFormatOptionsPanel: TPanel;
DonateMenuItem: TMenuItem;
OldScreenshotCleanerPanel: TPanel;
OldScreenshotCleanerMaxAgeUnitComboBox: TComboBox;
OldScreenshotCleanerMaxAgeValueSpinEdit: TSpinEdit;
SoundPlayer: Tplaysound;
PostCmdLabel: TLabel;
PostCmdEdit: TEdit;
CheckForUpdatesMenuItem: TMenuItem;
OutputDirEdit: TDirectoryEdit;
Timer: TTimer;
OutputDirLabel: TLabel;
CaptureIntervalLabel: TLabel;
TrayIcon: TTrayIcon;
ImageFormatLabel: TLabel;
TakeScreenshotButton: TButton;
JPEGQualityLabel: TLabel;
JPEGQualitySpinEdit: TSpinEdit;
OpenOutputDirButton: TButton;
StopWhenInactiveCheckBox: TCheckBox;
ImageFormatComboBox: TComboBox;
JPEGQualityPercentLabel: TLabel;
AutoCaptureControlGroup: TGroupBox;
StartAutoCaptureButton: TBitBtn;
StopAutoCaptureButton: TBitBtn;
TrayIconPopupMenu: TPopupMenu;
ExitTrayMenuItem: TMenuItem;
TakeScreenshotTrayMenuItem: TMenuItem;
RestoreWindowTrayMenuItem: TMenuItem;
ToggleAutoCaptureTrayMenuItem: TMenuItem;
Separator2TrayMenuItem: TMenuItem;
StartCaptureOnStartUpCheckBox: TCheckBox;
StartMinimizedCheckBox: TCheckBox;
Separator1TrayMenuItem: TMenuItem;
FileNameTemplateLabel: TLabel;
FileNameTemplateComboBox: TComboBox;
FileNameTemplateHelpButton: TButton;
GrayscaleCheckBox: TCheckBox;
ColorDepthLabel: TLabel;
ColorDepthComboBox: TComboBox;
CaptureIntervalDateTimePicker: TDateTimePicker;
TrayIconAnimationTimer: TTimer;
AutoRunCheckBox: TCheckBox;
MonitorLabel: TLabel;
MonitorComboBox: TComboBox;
MainMenu: TMainMenu;
HelpSubMenu: TMenuItem;
AboutMenuItem: TMenuItem;
OptionsSubMenu: TMenuItem;
LanguageSubMenu: TMenuItem;
SeqNumberGroup: TGroupBox;
SeqNumberValueLabel: TLabel;
SeqNumberValueSpinEdit: TSpinEdit;
SeqNumberDigitsCountSpinEdit: TSpinEdit;
SeqNumberDigitsCountLabel: TLabel;
UniqueInstance1: TUniqueInstance;
procedure CheckForUpdatesMenuItemClick(Sender: TObject);
procedure AutoCheckForUpdatesMenuItemClick(Sender: TObject);
procedure CompressionLevelComboBoxChange(Sender: TObject);
procedure ExitMenuItemClick(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure MinimizeInsteadOfCloseCheckBoxChange(Sender: TObject);
procedure OldScreenshotCleanerEnabledCheckBoxChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure HotKetsSettingsMenuItemClick(Sender: TObject);
procedure DonateMenuItemClick(Sender: TObject);
procedure OldScreenshotCleanerMaxAgeUnitComboBoxChange(Sender: TObject);
procedure OldScreenshotCleanerMaxAgeValueSpinEditChange(Sender: TObject);
procedure OutputDirEditChange(Sender: TObject);
procedure CaptureIntervalDateTimePickerChange(Sender: TObject);
procedure PlaySoundsCheckBoxChange(Sender: TObject);
procedure PostCmdEditChange(Sender: TObject);
procedure TimerTimer(Sender: TObject);
procedure ApplicationMinimize(Sender: TObject);
procedure StartAutoCaptureButtonClick(Sender: TObject);
procedure StopAutoCaptureButtonClick(Sender: TObject);
procedure TakeScreenshotButtonClick(Sender: TObject);
procedure JPEGQualitySpinEditChange(Sender: TObject);
procedure OpenOutputDirButtonClick(Sender: TObject);
procedure StopWhenInactiveCheckBoxClick(Sender: TObject);
procedure ImageFormatComboBoxChange(Sender: TObject);
procedure ToggleAutoCaptureTrayMenuItemClick(Sender: TObject);
procedure RestoreWindowTrayMenuItemClick(Sender: TObject);
procedure TakeScreenshotTrayMenuItemClick(Sender: TObject);
procedure ExitTrayMenuItemClick(Sender: TObject);
procedure StartCaptureOnStartUpCheckBoxClick(Sender: TObject);
procedure StartMinimizedCheckBoxClick(Sender: TObject);
procedure FileNameTemplateComboBoxChange(Sender: TObject);
procedure FileNameTemplateHelpButtonClick(Sender: TObject);
procedure GrayscaleCheckBoxClick(Sender: TObject);
procedure ColorDepthComboBoxChange(Sender: TObject);
procedure TrayIconAnimationTimerTimer(Sender: TObject);
procedure AutoRunCheckBoxClick(Sender: TObject);
procedure MonitorComboBoxChange(Sender: TObject);
procedure AboutMenuItemClick(Sender: TObject);
procedure TrayIconDblClick(Sender: TObject);
procedure SeqNumberValueSpinEditChange(Sender: TObject);
procedure SeqNumberDigitsCountSpinEditChange(Sender: TObject);
procedure UniqueInstance1OtherInstance(Sender: TObject;
ParamCount: Integer; const Parameters: array of String);
private
{ Private declarations }
{ Fields and variables }
AvailableLanguages: TLanguagesArray;
FLanguage: TLanguageCode; { ??? }
FColorDepth: TColorDepth;
FTrayIconState: TTrayIconState;
TrayIconIdx: 1..7;
FCounter: Integer;
FCounterDigits: Integer {Byte};
{$IfDef Windows}
PrevWndProc: WndProc;
{$EndIf}
{$IfDef Linux}
XWatcher: TXRandREventWatcherThread;
{$EndIf}
Grabber: TScreenGrabber;
FStopWhenInactive: Boolean;
FStartMinimized: Boolean;
FAutoRun: Boolean;
FGrayscale: Boolean;
KeyHook: TGlobalKeyHook;
OldScreenshotCleaner: TOldScreenshotCleaner;
FormInitialized: Boolean;
public
FileJournal: TFileJournal;
private
{ Methods }
procedure SetTimerEnabled(AEnabled: Boolean);
function GetTimerEnabled: Boolean;
function GetFinalOutputDir: String;
function GetImagePath: String;
procedure SetImageFormatByStr(FmtStr: String);
procedure SetImageFormat(Fmt: TImageFormat);
function GetImageFormat: TImageFormat;
procedure SetColorDepth(AColorDepth: TColorDepth);
function GetColorDepth: TColorDepth;
procedure SetTrayIconState(IconState: TTrayIconState);
procedure MakeScreenshot;
procedure MinimizeToTray;
procedure RestoreFromTray;
//procedure SetLanguage(Lang: TLanguage);
procedure SetLanguageByCode(LangCode: TLanguageCode);
procedure TranslateForm;
procedure InitUI;
procedure ReadSettings;
procedure UpdateColorDepthValues;
procedure UpdateMonitorList;
procedure FillMonitorList;
procedure SetMonitorId(MonitorId: Integer);
function GetMonitorId: Integer;
procedure UpdateLanguages;
procedure LanguageClick(Sender: TObject);
function GetLangCodeOfLangMenuItem(const LangItem: TMenuItem): TLanguageCode;
function FindLangMenuItem(ALangCode: TLanguageCode): TMenuItem;
procedure RecalculateLabelWidths;
procedure RecalculateLabelWidthsForSeqNumGroup;
function FormatPath(Str: string): string;
procedure SetCounter(Val: Integer);
procedure SetCounterDigits(Val: Integer);
procedure UpdateSeqNumGroupVisibility;
procedure SetJPEGQuality(Val: Integer);
function GetJPEGQuality: Integer;
procedure SetStopWhenInactive(const Val: Boolean);
procedure SetStartMinimized(const Val: Boolean);
procedure SetAutoRun(const Val: Boolean);
procedure SetGrayscale(const Val: Boolean);
procedure SetPostCommand(ACmd: String);
function GetPostCommand: String;
function GetMonitorWithCursor: Integer;
function GetAutoCheckForUpdates: Boolean;
procedure SetAutoCheckForUpdates(AVal: Boolean);
procedure SetStartAutoCaptureHotKey(AHotKey: THotKey);
procedure SetStopAutoCaptureHotKey(AHotKey: THotKey);
procedure SetSingleCaptureHotKey(AHotKey: THotKey);
procedure SetHotKey(AHotKeyId: String; AHotKey: THotKey);
procedure SetCompressionLevel(ALevel: Tcompressionlevel);
function GetCompressionLevel: Tcompressionlevel;
procedure UpdateFormAutoSize;
procedure PlaySound(const AFileName: String);
procedure SetSounds(AEnabled: Boolean);
function GetSounds: Boolean;
procedure SetMinimizeInsteadOfClose(AEnabled: Boolean);
function GetMinimizeInsteadOfClose: Boolean;
function ConfirmExit: Boolean;
procedure OnHotKeyEvent(const AHotKeyId: String);
procedure OnDebugLnEvent(Sender: TObject; S: string; var Handled: Boolean);
function OnHotKeysSaving(ASender: TObject; out AErrorMsg: string): Boolean;
procedure OnScreenshotCleanerChanged;
{$IfDef Linux}
procedure OnScreenConfigurationChanged(const AEvent: TXEvent);
{$EndIf}
{ Properties }
property IsTimerEnabled: Boolean read GetTimerEnabled write SetTimerEnabled;
property FinalOutputDir: String read GetFinalOutputDir;
property ImagePath: String read GetImagePath;
//property Language: TLanguage read FLanguage write SetLanguage;
property ImageFormat: TImageFormat read GetImageFormat write SetImageFormat;
property ColorDepth: TColorDepth read GetColorDepth write SetColorDepth;
property TrayIconState: TTrayIconState write SetTrayIconState;
property MonitorId: Integer read GetMonitorId write SetMonitorId;
property Counter: Integer read FCounter write SetCounter;
property CounterDigits: {Byte} Integer read FCounterDigits write SetCounterDigits;
property JPEGQuality: Integer read GetJPEGQuality write SetJPEGQuality;
property StopWhenInactive: Boolean read FStopWhenInactive write SetStopWhenInactive;
property StartMinimized: Boolean read FStartMinimized write SetStartMinimized;
property AutoRun: Boolean read FAutoRun write SetAutoRun;
property Grayscale: Boolean read FGrayscale write SetGrayscale;
property PostCommand: String read GetPostCommand write SetPostCommand;
property AutoCheckForUpdates: Boolean read GetAutoCheckForUpdates write SetAutoCheckForUpdates;
property CompressionLevel: Tcompressionlevel read GetCompressionLevel write SetCompressionLevel;
property Sounds: Boolean read GetSounds write SetSounds;
property MinimizeInsteadOfClose: Boolean read GetMinimizeInsteadOfClose write SetMinimizeInsteadOfClose;
// Messages
{$IfDef Windows}
procedure WMHotKey(var AMsg: TMessage); message WM_HOTKEY;
{$EndIf}
public
{ Public declarations }
end;
const
DefaultConfigIniSection = 'main';
HotKeysIniSection = 'hotkeys';
MinCaptureIntervalInSeconds = 1;
NoMonitorId = -1;
MonitorWithCursor = -2;
MinCounterValue = 1;
MinCounterDigits = 1;
MaxCounterDigits = 10;
UpdateCheckIntervalInSeconds = 3 * 24 * 60 * 60; // Every 3 days
MinOldScreenshotsRemovingPeriodValue = 1;
MaxOldScreenshotsRemovingPeriodValue = 999;
var
MainForm: TMainForm;
Ini: TIniFile;
implementation
uses uAbout, DateUtils, StrUtils, uUtils, Math,
uFileNameTemplateHelpForm, uIniHelper, UpdateChecker, FileUtil, LCLType, Idle,
uDonateForm, LazLogger;
{$R *.lfm}
const
LanguageSubMenuItemNamePrefix = 'LanguageSubMenuItem_';
{$IfDef Windows}
function WndCallback(MyHWND: HWND; uMSG: UINT; wParam: WParam; lParam: LParam): LRESULT; StdCall;
begin
case uMSG of
WM_DISPLAYCHANGE, // Screen resolution/orientation changed
WM_DEVICECHANGE: // Any hardware configuration changed (including monitors)
begin
MainForm.UpdateMonitorList;
end;
end;
//if WindowInfo^.WinControl is TForm1 then //Eliminate form1 global variable for safer handling.
// Result:= CallWindowProc(TForm1(WindowInfo^.WinControl).PrevWndProc, MyHWND, uMSG, WParam, LParam);
Result := Windows.CallWindowProc(MainForm.PrevWndProc, MyHWND, uMsg, WParam, LParam);
end;
{$EndIf}
function MyGetApplicationName: String;
begin
Result := 'AutoScreenshot';
end;
procedure TMainForm.InitUI;
var
Fmt: TImageFormat;
I: Integer;
begin
{$IFOPT D+}
MainForm.Caption := MainForm.Caption + ' [DEBUG BUILD]';
{$ENDIF}
// Set default tray icon
TrayIconState := tisDefault;
TrayIcon.Hint := Application.Title;
// Fill combobox with image formats
for Fmt in TImageFormat do
ImageFormatComboBox.Items.Append(ImageFormatInfoArray[Fmt].Name);
// Set min/max values for JPEG quality
JPEGQualitySpinEdit.MinValue := Low(TJPEGQualityRange);
JPEGQualitySpinEdit.MaxValue := High(TJPEGQualityRange);
// Icons
StartAutoCaptureButton.Glyph.LoadFromResourceName(HInstance, '_START_ICON');
StopAutoCaptureButton.Glyph.LoadFromResourceName(HInstance, '_STOP_ICON');
// Available languages
UpdateLanguages;
// Sequential number
SeqNumberValueSpinEdit.MinValue := MinCounterValue;
SeqNumberDigitsCountSpinEdit.MinValue := MinCounterDigits;
SeqNumberDigitsCountSpinEdit.MaxValue := MaxCounterDigits;
// Available monitors
UpdateMonitorList;
// Predefined filename templates
with FileNameTemplateComboBox.Items do
begin
Clear;
Append('screenshot %Y-%M-%D %H-%N-%S');
Append('%Y' + PathDelim + '%M' + PathDelim + '%D' + PathDelim + 'screenshot %H-%N-%S');
Append('%Y-%M' + PathDelim + '%D' + PathDelim + 'screenshot %H-%N-%S');
Append('%COMP' + PathDelim + '%USER' + PathDelim + 'screenshot %Y-%M-%D %H-%N-%S');
Append('screenshot %NUM');
end;
with OldScreenshotCleanerMaxAgeValueSpinEdit do
begin
MinValue := MinOldScreenshotsRemovingPeriodValue;
MaxValue := MaxOldScreenshotsRemovingPeriodValue;
end;
with OldScreenshotCleanerMaxAgeUnitComboBox.Items do
begin
Clear;
for I := Ord(Low(TIntervalUnit)) to Ord(High(TIntervalUnit)) do
Append('');
end;
end;
procedure TMainForm.ReadSettings;
const
DefaultFileNameTemplate = '%Y-%M-%D' + PathDelim + '%Y-%M-%D %H.%N.%S';
DefaultCaptureInterval = 5;
DefaultImageFormat = fmtPNG;
DefaultJPEGQuality = 80;
DefaultLanguage = 'en';
DefaultColorDepth = cd24Bit;
DefaultMonitorId = NoMonitorId;
DefaultCounterValue = MinCounterValue;
DefaultCounterDigits = 6;
DefaultCompressionLevel = cldefault;
DefaultScreenshotCleanerMaxAge: TInterval = (
Val: 1;
Unit_: iuMonths
);
LogFileName = 'log.txt';
var
DefaultOutputDir, BaseDir: String;
CfgLang, SysLang, AltLang: TLanguageCode;
FmtStr: String;
Seconds: Integer;
LogFilePath: String;
CleanerActive: Boolean;
begin
// Logging
if Ini.ReadBool(DefaultConfigIniSection, 'Logging', False) then
begin
if IsPortable then
LogFilePath := ConcatPaths([ProgramDirectory, LogFileName])
else
LogFilePath := ConcatPaths([GetAppConfigDir(False), LogFileName]);
DeleteFile(LogFilePath); // Overwrite log file
DebugLogger.LogName := LogFilePath;
//{$Define LAZLOGGER_FLUSH}
DebugLogger.CloseLogFileBetweenWrites := True; // FixMe: Better to set LAZLOGGER_FLUSH, but seems it doesn't work
DebugLogger.OnDebugLn := @OnDebugLnEvent;
end
else
begin
{$IFOPT D-}
DebugLogger.LogName :=
{$IfDef Windows}'nul'{$EndIf}
{$IfDef Linux}'/dev/null'{$ENDIF}
;
{$EndIf}
end;
if IsPortable then
BaseDir := ExtractFilePath(Application.ExeName)
else
BaseDir := GetUserPicturesDir();
DefaultOutputDir := IncludeTrailingPathDelimiter(ConcatPaths([BaseDir, 'screenshots']));
OutputDirEdit.Text := Ini.ReadString(DefaultConfigIniSection, 'OutputDir', DefaultOutputDir);
// ToDo: Check that directory exists or can be created (with subdirs if needed)
if OutputDirEdit.Text = '' then
OutputDirEdit.Text := DefaultOutputDir;
FileNameTemplateComboBox.Text := Ini.ReadString(DefaultConfigIniSection, 'FileNameTemplate', DefaultFileNameTemplate);
Seconds := Round(Ini.ReadFloat(DefaultConfigIniSection, 'CaptureInterval', DefaultCaptureInterval) * SecsPerMin);
Seconds := Max(Seconds, MinCaptureIntervalInSeconds);
CaptureIntervalDateTimePicker.Time := EncodeTime(0, 0, 0, 0);
CaptureIntervalDateTimePicker.Time := IncSecond(CaptureIntervalDateTimePicker.Time, Seconds);
StopWhenInactive := Ini.ReadBool(DefaultConfigIniSection, 'StopWhenInactive', False);
// Image format
FColorDepth := TColorDepth(0); // Set value as unitialized to prevent
// reset to max available value in UpdateColorDepthValues() before
// reading color depth from ini file
FmtStr := Ini.ReadString(DefaultConfigIniSection, 'ImageFormat',
ImageFormatInfoArray[DefaultImageFormat].Name);
try
SetImageFormatByStr(FmtStr);
except
ImageFormat := DefaultImageFormat;
end;
JPEGQuality := Ini.ReadInteger(DefaultConfigIniSection, 'JPEGQuality', DefaultJPEGQuality);
Grayscale := Ini.ReadBool(DefaultConfigIniSection, 'Grayscale', False);
// Color depth
try
ColorDepth := TColorDepth(Ini.ReadInteger(DefaultConfigIniSection,
'ColorDepth', Integer(DefaultColorDepth)));
except
FColorDepth := DefaultColorDepth;
end;
// Language
try
CfgLang := Ini.ReadString(DefaultConfigIniSection, 'Language', '');
SetLanguageByCode(CfgLang);
except
try
SysLang := GetSystemLanguageCode;
SetLanguageByCode(SysLang);
except
try
AltLang := GetAlternativeLanguage(AvailableLanguages, SysLang);
SetLanguageByCode(AltLang);
except
SetLanguageByCode(DefaultLanguage);
end;
end;
end;
// Start autocapture
Timer.Interval := SecondOfTheDay(CaptureIntervalDateTimePicker.Time) * MSecsPerSec;
StartCaptureOnStartUpCheckBox.Checked :=
Ini.ReadBool(DefaultConfigIniSection, 'StartCaptureOnStartUp', {True} False);
IsTimerEnabled := StartCaptureOnStartUpCheckBox.Checked;
// Start with OS
AutoRun := Ini.ReadBool(DefaultConfigIniSection, 'AutoRun', False);
// Start minimized
StartMinimized := Ini.ReadBool(DefaultConfigIniSection, 'StartMinimized', False);
if StartMinimized then
MinimizeToTray
else
RestoreFromTray;
// Multiple monitors
try
MonitorId := Ini.ReadInteger(DefaultConfigIniSection, 'Monitor', DefaultMonitorId);
except
MonitorId := DefaultMonitorId;
end;
// Incremental counter
Counter := Ini.ReadInteger(DefaultConfigIniSection, 'Counter', DefaultCounterValue);
CounterDigits := Ini.ReadInteger(DefaultConfigIniSection, 'CounterDigits', DefaultCounterDigits);
UpdateSeqNumGroupVisibility;
// User command
PostCommand := Ini.ReadString(DefaultConfigIniSection, 'PostCmd', '');
// Auto checking for updates
AutoCheckForUpdates := Ini.ReadBool(DefaultConfigIniSection, 'AutoCheckForUpdates', True);
// Compression level
CompressionLevel := Tcompressionlevel(Ini.ReadInteger(DefaultConfigIniSection, 'Compression', Ord(DefaultCompressionLevel)));
// Old screenshots removing
CleanerActive := Ini.ReadBool(DefaultConfigIniSection,
'OldScreenshotCleanerEnabled', False);
OldScreenshotCleaner.MaxAge := TInterval(Ini.ReadString(DefaultConfigIniSection,
'OldScreenshotCleanerMaxAge',
String(DefaultScreenshotCleanerMaxAge)));
OldScreenshotCleaner.Active := CleanerActive;
// Sounds
Sounds := Ini.ReadBool(DefaultConfigIniSection, 'Sounds', False);
// Minimize instead of close
MinimizeInsteadOfClose := Ini.ReadBool(DefaultConfigIniSection, 'MinimizeInsteadOfClose', False);
end;
procedure TMainForm.FormCreate(Sender: TObject);
const
NoHotKey: THotKey = (
ShiftState: [];
Key: VK_UNKNOWN;
);
var
///////
ColorDepthTmp: TColorDepth;
////////
LastUpdateCheck: TDateTime;
HotKey: THotKey;
IniFileName: String;
begin
{DebugLn('Program started');
DebugLn('Version: ', GetProgramVersionStr);
DebugLn('Initializing...');}
{$IfDef Windows}
{ Replace default window function with custom one
for process messages when screen configuration changed }
PrevWndProc := Windows.WNDPROC
(SetWindowLongPtr(Self.Handle, GWL_WNDPROC {GWLP_WNDPROC}, PtrUInt(@WndCallback)));
{$EndIf}
Application.OnMinimize := @ApplicationMinimize;
InitUI;
OnGetApplicationName := @MyGetApplicationName;
if IsPortable then
IniFileName := ConcatPaths([ProgramDirectory, 'config.ini'])
else
IniFileName := ConcatPaths([GetAppConfigDir(False), 'config.ini']);
Ini := TIniFile.Create(IniFileName);
Ini.WriteString(DefaultConfigIniSection, 'ProgramVersion', GetProgramVersionStr);
OldScreenshotCleaner := TOldScreenshotCleaner.Create;
OldScreenshotCleaner.OnChangeCallback := @OnScreenshotCleanerChanged;
ReadSettings;
DebugLn('Program started at ', DateTimeToStr(Now));
DebugLn('Version: ', GetProgramVersionStr);
DebugLn('Initializing...');
//if FindCmdLineSwitch('autorun') then
// OutputDebugString('AutoRun');
//////////////
ColorDepthTmp := cd24Bit; // Any value
try
ColorDepthTmp := ColorDepth;
except
end;
///////////////
Grabber := TScreenGrabber.Create(ImageFormat, {ColorDepth} ColorDepthTmp, JPEGQuality,
Grayscale, CompressionLevel);
// Check for updates when program starts
LastUpdateCheck := Ini.ReadDateTime(DefaultConfigIniSection, 'LastCheckForUpdates', 0);
if AutoCheckForUpdates then
begin
DebugLn('Last update check: %s (%d hours ago)', [DateTimeToStr(LastUpdateCheck), HoursBetween(Now, LastUpdateCheck)]);
end;
if AutoCheckForUpdates and (SecondsBetween(Now, LastUpdateCheck) > UpdateCheckIntervalInSeconds) then
CheckForUpdates(True);
// Enable global hotkeys
KeyHook := TGlobalKeyHook.Create({$IfDef Windows}Handle, 'AutoScreenshot'{$EndIf}
{$IfDef Linux}@OnHotKeyEvent{$EndIf});
HotKey := Ini.ReadHotKey(HotKeysIniSection, 'StartAutoCapture', NoHotKey);
try
KeyHook.RegisterKey('StartAutoCapture', HotKey);
except
KeyHook.RegisterKey('StartAutoCapture', NoHotKey);
end;
HotKey := Ini.ReadHotKey(HotKeysIniSection, 'StopAutoCapture', NoHotKey);
try
KeyHook.RegisterKey('StopAutoCapture', HotKey);
except
KeyHook.RegisterKey('StopAutoCapture', NoHotKey);
end;
HotKey := Ini.ReadHotKey(HotKeysIniSection, 'SingleCapture', NoHotKey);
try
KeyHook.RegisterKey('SingleCapture', HotKey);
except
KeyHook.RegisterKey('SingleCapture', NoHotKey);
end;
{$IfDef Linux}
// Enable monitor confuguration changed updates in Linux
XWatcher := TXRandREventWatcherThread.Create(RRScreenChangeNotifyMask, @OnScreenConfigurationChanged);
{$EndIf}
FileJournal := TFileJournal.Create;
FormInitialized := True;
DebugLn('Initializing finished');
end;
procedure TMainForm.CheckForUpdatesMenuItemClick(Sender: TObject);
begin
CheckForUpdates(False);
end;
procedure TMainForm.AutoCheckForUpdatesMenuItemClick(Sender: TObject);
begin
AutoCheckForUpdates := not AutoCheckForUpdates;
end;
procedure TMainForm.CompressionLevelComboBoxChange(Sender: TObject);
begin
CompressionLevel := Tcompressionlevel(CompressionLevelComboBox.ItemIndex);
end;
procedure TMainForm.ExitMenuItemClick(Sender: TObject);
begin
if ConfirmExit then
//Close;
Application.Terminate;
end;
procedure TMainForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
CanClose := not MinimizeInsteadOfClose;
if MinimizeInsteadOfClose then
MinimizeToTray;
if CanClose then
CanClose := ConfirmExit;
end;
procedure TMainForm.MinimizeInsteadOfCloseCheckBoxChange(Sender: TObject);
begin
MinimizeInsteadOfClose := MinimizeInsteadOfClose;
end;
procedure TMainForm.OldScreenshotCleanerEnabledCheckBoxChange(Sender: TObject);
begin
OldScreenshotCleaner.Active := TCheckBox(Sender).Checked;
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
FileJournal.Free;
{$IfDef Linux}
//XWatcher.Terminate;
//XWatcher.WaitFor;
XWatcher.Free;
{$EndIf}
Grabber.Free;
KeyHook.Free;
OldScreenshotCleaner.Free;
Ini.Free;
DebugLn('Program ended');
end;
procedure TMainForm.FormShow(Sender: TObject);
begin
RecalculateLabelWidths;
end;
procedure TMainForm.HotKetsSettingsMenuItemClick(Sender: TObject);
var
HotKeysForm: THotKeysForm;
begin
// ToDo: Reduce amount of code duplicates
HotKeysForm := THotKeysForm.Create(Nil, @OnHotKeysSaving);
HotKeysForm.StartAutoCaptureKey := Self.KeyHook.FindHotKey('StartAutoCapture');
HotKeysForm.StopAutoCaptureKey := Self.KeyHook.FindHotKey('StopAutoCapture');
HotKeysForm.SingleCaptureKey := Self.KeyHook.FindHotKey('SingleCapture');
HotKeysForm.ShowModal;
HotKeysForm.Free;
end;
procedure TMainForm.DonateMenuItemClick(Sender: TObject);
begin
with TDonateForm.Create(Self) do
begin
try
ShowModal;
finally
Free;
end;
end;
end;
procedure TMainForm.OldScreenshotCleanerMaxAgeUnitComboBoxChange(
Sender: TObject);
var
Interval: TInterval;
begin
Interval := OldScreenshotCleaner.MaxAge;
Interval.Unit_:= TIntervalUnit(TComboBox(Sender).ItemIndex);
OldScreenshotCleaner.MaxAge := Interval;
end;
procedure TMainForm.OldScreenshotCleanerMaxAgeValueSpinEditChange(
Sender: TObject);
var
Interval: TInterval;
begin
Interval := OldScreenshotCleaner.MaxAge;
Interval.Val := TSpinEdit(Sender).Value;
OldScreenshotCleaner.MaxAge := Interval;
end;
procedure TMainForm.OutputDirEditChange(Sender: TObject);
begin
Ini.WriteString(DefaultConfigIniSection, 'OutputDir', OutputDirEdit.Text);
end;
procedure TMainForm.CaptureIntervalDateTimePickerChange(Sender: TObject);
var
Seconds: Integer;
begin
Seconds := SecondOfTheDay(CaptureIntervalDateTimePicker.Time);
if Seconds < MinCaptureIntervalInSeconds then
begin
Seconds := MinCaptureIntervalInSeconds;
CaptureIntervalDateTimePicker.Time := EncodeTime(0, 0, 0, 0);
CaptureIntervalDateTimePicker.Time := IncSecond(CaptureIntervalDateTimePicker.Time, Seconds);
end;
Ini.WriteFloat(DefaultConfigIniSection, 'CaptureInterval', Seconds / SecsPerMin);
Timer.Interval := Seconds * MSecsPerSec;
end;
procedure TMainForm.PlaySoundsCheckBoxChange(Sender: TObject);
begin
Sounds := Sounds;
end;
procedure TMainForm.PostCmdEditChange(Sender: TObject);
begin
Ini.WriteString(DefaultConfigIniSection, 'PostCmd', PostCommand);
end;
procedure TMainForm.TimerTimer(Sender: TObject);
begin
if StopWhenInactive then
begin
// Skip taking screenshot if there are no user activity
// for autocapture interval minutes
// ToDo: May add check for screensaver active
// or user logged off from the session
// ToDo: May add comparision of current screenshot with the last one,
// and if they equal, do not save current
if Timer.Interval > UserIdleTime then
MakeScreenshot
else
DebugLn('Automatic capture skipped (Timer.Interval=%d, UserIdleTime=%d)',
[Timer.Interval, UserIdleTime]);
end
else
MakeScreenshot;
end;
function TMainForm.GetTimerEnabled: Boolean;
begin
Result := Timer.Enabled;
end;
procedure TMainForm.SetTimerEnabled(AEnabled: Boolean);
begin
Timer.Enabled := AEnabled;
StartAutoCaptureButton.Enabled := not AEnabled;
StopAutoCaptureButton.Enabled := AEnabled;
// Tray menu
ToggleAutoCaptureTrayMenuItem.Checked := AEnabled;
// Tray icon
if AEnabled then
TrayIconState := tisDefault
else
TrayIconState := tisBlackWhite;
// Play sound
if FormInitialized or AEnabled then // Prevent to play "stop" sound immediately after program starts
begin
if AEnabled then
PlaySound('start.wav')
else
PlaySound('stop.wav');
end;
if AEnabled then
DebugLn('Automatic capture started')
else
DebugLn('Automatic capture stopped');
end;
procedure TMainForm.StartAutoCaptureButtonClick(Sender: TObject);
begin
IsTimerEnabled := True;
end;
procedure TMainForm.StopAutoCaptureButtonClick(Sender: TObject);
begin
IsTimerEnabled := False;
end;
procedure TMainForm.ApplicationMinimize(Sender: TObject);
begin
MinimizeToTray;
end;
procedure TMainForm.MakeScreenshot;
var
Cmd, ImageFileName, ErrMsg: String;
begin
ImageFileName := ImagePath; // Use local variable because ImagePath() result
// may be changed on next call
PlaySound('camera_shutter.wav');
TrayIconState := tisFlashAnimation;
if MonitorId = NoMonitorId then
Grabber.CaptureAllMonitors(ImageFileName)
else
begin
if MonitorId = MonitorWithCursor then
Grabber.CaptureMonitor(ImageFileName, GetMonitorWithCursor)
else
Grabber.CaptureMonitor(ImageFileName, MonitorId);
end;
FileJournal.Add(ImageFileName);
// Run user command
try
Cmd := PostCommand;
if Cmd <> '' then
begin
Cmd := StringReplace(Cmd, '%FILENAME%', ImageFileName, [rfReplaceAll{, rfIgnoreCase}]);
DebugLn('Execute command: ', Cmd);
RunCmdInbackground(Cmd);
//DebugLn('Execution success!'); // Not works
end;
except
on E: Exception do
begin
DebugLn('Execution failed: ', E.ToString);
if not Timer.Enabled then // Manual capture
begin
ErrMsg := {'Execution of custom command failed: ' +} E.Message;
MessageDlg('Auto Screenshot', ErrMsg, mtWarning, [mbOK], '');
end;
end;
end;
// Increment counter after successful capture
//Inc(Counter);
Counter := Counter + 1;
end;
procedure TMainForm.TakeScreenshotButtonClick(Sender: TObject);
var
DefaultTransparency: Byte;
begin
DefaultTransparency := AlphaBlendValue; // Save current transparency value (usually = 255)
// Set form transparency to 100%
AlphaBlendValue := 0;
AlphaBlend := True;
try
MakeScreenshot;
finally
// Restore transparency to initial value
AlphaBlendValue := DefaultTransparency;
AlphaBlend := False;
end;
end;
procedure TMainForm.JPEGQualitySpinEditChange(Sender: TObject);
begin
if Ini = Nil then
Exit;
try
Ini.WriteInteger(DefaultConfigIniSection, 'JPEGQuality', JPEGQuality);
if Grabber <> nil then
Grabber.Quality := JPEGQuality;
finally
end;
end;
function TMainForm.GetFinalOutputDir: String;
var
BaseDir, SubDir, FullDir: String;
begin
BaseDir := Ini.ReadString(DefaultConfigIniSection, 'OutputDir', '');
SubDir := ExtractFileDir({Ini.ReadString(DefaultConfigIniSection, 'FileNameTemplate', '')} FileNameTemplateComboBox.Text);
SubDir := FormatPath(SubDir);
FullDir := IncludeTrailingPathDelimiter(ConcatPaths([BaseDir, SubDir]));
if not DirectoryExists(FullDir) then
begin
if not ForceDirectories(FullDir) then
RaiseLastOSError;
end;
Result := FullDir;
end;
function TMainForm.GetImagePath: String;
var
DirName, FileName: String;
begin
FileName := ExtractFileName(FileNameTemplateComboBox.Text);
FileName := FormatPath(FileName);
DirName := IncludeTrailingPathDelimiter(FinalOutputDir);
Result := DirName + FileName + '.' + ImageFormatInfoArray[ImageFormat].Extension;
end;
procedure TMainForm.OpenOutputDirButtonClick(Sender: TObject);
begin
OpenDocument(FinalOutputDir);
end;
procedure TMainForm.StopWhenInactiveCheckBoxClick(Sender: TObject);
begin
StopWhenInactive := StopWhenInactiveCheckBox.Checked;
end;
procedure TMainForm.ImageFormatComboBoxChange(Sender: TObject);
var
Format: TImageFormat;
IsQualityVisible, IsGrayscaleVisible, IsCompressionLevelVisible: Boolean;
begin
DisableAutoSizing;
try
Format := ImageFormat;
IsQualityVisible := ImageFormatInfoArray[Format].HasQuality;
JPEGQualitySpinEdit.Visible := IsQualityVisible;
JPEGQualityLabel.Visible := IsQualityVisible;
JPEGQualityPercentLabel.Visible := IsQualityVisible;
IsGrayscaleVisible := ImageFormatInfoArray[Format].HasGrayscale;
GrayscaleCheckBox.Visible := IsGrayscaleVisible;