-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathMainForm.cs
3476 lines (3024 loc) · 159 KB
/
MainForm.cs
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 GmicAnimate;
using GmicDrosteAnimate;
// Third party libraries for symbolic math and expression evaluation.
using MathNet.Symbolics;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Text;
//using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using static FileManager;
using static GmicFilterAnimatorApp.MainForm.NativeMethods;
namespace GmicFilterAnimatorApp
{
[SupportedOSPlatform("windows")]
public partial class MainForm : Form
{
// Variables to hold the state of the application and user input.
// inputFilePath stores the path to the image file selected by the user.
private string inputFilePath;
// startParams stores the initial parameters for the filter.
private string startParams;
// endParams stores the final parameters for the filter to create a transition effect.
private string endParams;
// masterParamIndex indicates the index of the parameter that drives the transformation.
//private int masterParamIndex;
// masterParamIncrement defines the increment by which the master parameter changes.
private double masterParamIncrement;
// exponentialIncrements indicates whether exponential interpolation is used.
private bool exponentialIncrements;
// masterExponent specifies the exponent used if exponential interpolation is enabled.
//private double masterExponent;
// exponentArray can contain a custom or default set of exponents for all parameters.
private string exponentArrayString;
// createGif determines whether a GIF should be created from the resulting images.
private bool createGif;
// Flag to indicate if a cancellation has been requested by the user. To stop image generation process
private bool cancellationRequested = false;
decimal totalFramesDefault = 100;
// Track if the main form has been loaded
private bool mainFormLoaded = false;
// Setting a default array of exponents for use with exponential interpolation if no custom array is provided.
// These are arbitrarily chosen values based on experience.
//private static double[] defaultExponents = new double[] { 2, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
// Get default values from FilterParameters SingleParameterInfo class defaultStart value
private double[] defaultExponents = FilterParameters.GetParameterValuesAsList("DefaultExponent");
// Default values for the start and end parameters to be displayed as placeholders in the textboxes and if user opens parameters info window without entering any values
//private string defaultStartParams = "34,100,1,1,1,0,0,0,0,0,20,30,1,0,90,0,0,0,0,1,0,0,1,0,0,0,0,0,1,0,0";
//private string defaultEndParams = "100,100,1,1,1,0,0,0,0,0,20,30,1,0,90,0,0,0,0,1,0,0,1,0,0,0,0,0,1,0,0";
// Get default values from FilterParameters SingleParameterInfo class defaultStart value
private string defaultStartParams = FilterParameters.GetParameterValuesAsString("DefaultStart");
private string defaultEndParams = FilterParameters.GetParameterValuesAsString("DefaultEnd");
// Add lock object for thread safety when logging console outputs
private readonly object logLock = new object();
// Set dimensions for certain components to use later when resizing
public int formDefaultHeight = 0;
public int listBoxDefaultHeight = 0;
// Create variable to store strings for problems to display in messages
private string disabledTotalFramesProblem = null;
// Other variables
private int maxParallelJobs = 10;
// Get version number from assembly
static System.Version versionFull = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
public readonly string versionString = $"{versionFull.Major}.{versionFull.Minor}.{versionFull.Build}";
public MainForm()
{
InitializeComponent();
InitializeDefaults();
// Set the version number label
labelVersion.Text = $"Version {versionString}";
// Store form starting height and and listbox height to be used later when resizing
formDefaultHeight = this.Height;
listBoxDefaultHeight = listBoxFiltersMain.Height;
// Create mouse scroll handler to properly scroll increment on master increment numeric updown
nudMasterParamIndex.MouseWheel += new MouseEventHandler(this.ScrollHandlerFunction);
// Check if ffmpeg is in the same folder as the application, if not disable the GIF creation checkbox and display message
if (!CheckForFFmpeg(silent: true))
{
chkCreateGif.Enabled = false;
labelFFmpegNotFound.Visible = true;
chkCreateGif.Checked = false;
}
// For the box with the list of filters
listBoxFiltersMain.DrawMode = DrawMode.OwnerDrawFixed;
listBoxFiltersMain.ItemHeight = CompensateDPI(15); // Make sure this is enough to show the text.
listBoxFiltersMain.DrawItem += ListBoxFiltersMain_DrawItem;
Load += MainForm_Load;
// Run method to load filters file not silent, will display message asking user to update files
LoadFiltersFile(silent: true);
// Set dropdown to show the first filter and not be editable
dropdownDebugLog.SelectedIndex = 0;
dropdownDebugLog.DropDownStyle = ComboBoxStyle.DropDownList;
// Load parameters of current filter
LoadActiveFilterParameters();
UpdateParameterUI();
Console.WriteLine("Finished Loading Main Form.");
// ----------------------- Apply config preferences from Program.Config -----------------------
Program.Config.RefreshConfiguration();
txtInputFilePath.Text = Program.Config.InputFilePath;
checkBoxSingleThreadMode.Checked = Program.Config.SingleThreadMode;
chkCreateGif.Checked = Program.Config.CreateGIF;
checkBoxLogOnly.Checked = Program.Config.DontCreateImages;
checkBoxUseSameOutputDir.Checked = Program.Config.UseSameOutputDirectory;
dropdownDebugLog.SelectedIndex = Program.Config.DebugLogLevel;
checkBoxAutoMasterParamIndex.Checked = Program.Config.AutoSwitchMasterParameter;
totalFramesDefault = Program.Config.DefaultFrameCount;
maxParallelJobs = Program.Config.MaxParallelJobs;
ActivateFilter(Program.Config.DefaultFilter);
// Need to check these because otherwise it will mess with the placeholders
if (!String.IsNullOrEmpty(Program.Config.DefaultFilterStartParams))
{
StartParamsTextBoxChangeSetter = Program.Config.DefaultFilterStartParams;
}
if (!String.IsNullOrEmpty(Program.Config.DefaultFilterEndParams))
{
EndParamsTextTextBoxChangeSetter = Program.Config.DefaultFilterEndParams;
}
// This has to go after the parameter strings are loaded or else it won't be able to tell if it's a valid parameter
nudMasterParamIndex.Value = Program.Config.DefaultMasterParameterIndex;
// -------------------------------------------------------------------------------------------------
// Set the master frame default value to default (probably 100)
nudTotalFrames.Value = totalFramesDefault;
// Pseudo-disable group box with normalize radio options instead of actually disabling, so tooltip still works
// This will disable the controls inside but not the picturebox with tooltip
PseudoEnableDisable_Groupbox(enable: false, groupBoxName: "groupBoxNormalizeRadios", alwaysEnabledControls: ["infoIconAbsoluteModeMain"]);
// Launch the parameters and expressions windows if set to do so in the config
if (Program.Config.OpenParameterWindowOnStart || Program.Config.OpenExpressionsWindowOnStart)
{
if (Program.Config.OpenParameterWindowOnStart)
{
btnShowParamNames_Click(null, null);
}
if (Program.Config.OpenExpressionsWindowOnStart)
{
btnShowExpressionForm_Click(null, null);
}
// Bring main form to front
this.BringToFront();
// Arrange the windows so they don't overlap
ArrangeWindows(userPreferenceMainWindowLocation: Program.Config.CustomMainWindowPosition);
}
}
private void InitializeDefaults()
{
// Set initial values for form fields and internal variables to ensure a consistent starting state.
inputFilePath = string.Empty;
startParams = defaultStartParams;
endParams = defaultEndParams;
//masterParamIndex = 1;
masterParamIncrement = 1;
exponentialIncrements = false;
//masterExponent = 0;
exponentArrayString = string.Empty;
createGif = false;
// Start with totalframes box and master increment box read only
nudTotalFrames.Enabled = false;
nudMasterParamIncrement.Enabled = false;
// Show parameter name initially
WriteLatestParamNameStringLabel();
//#if !DEBUG
// Apply placeholders if not in debug mode
PlaceholderManager.SetPlaceholder(this.txtStartParams as System.Windows.Forms.TextBox, (string)startParams);
PlaceholderManager.SetPlaceholder(this.txtEndParams as System.Windows.Forms.TextBox, (string)endParams);
//#endif
#if DEBUG
// Set default value text in parameter value textboxes
txtInputFilePath.Text = "think.png";
//txtStartParams.Text = startParams;
//txtEndParams.Text = endParams;
inputFilePath = txtInputFilePath.Text;
//Enable test button for debugging only
//TestButton1.Visible = true;
#endif
// Set default values for the new controls
//chkExponentialIncrements.Checked = false;
//txtMasterExponent.Text = "0";
txtExponentArray.Text = string.Empty;
// Check if gmic.exe exists in the same folder
string gmicPath = Path.Combine(Application.StartupPath, "gmic.exe");
if (!File.Exists(gmicPath))
{
MessageBox.Show("This tool uses the G'MIC image processor program, but it was not found.\n\ngmic.exe is required for this application to function at all. Please make sure it is located in the same folder as this application.\n\nYou can find it at:\nhttps://gmic.eu/download.html\n\nLook for where it says 'G'MIC for Windows - Other interfaces', then the zip download for 'Command-line interface (CLI)' ", "gmic.exe Missing", MessageBoxButtons.OK, MessageBoxIcon.Warning);
// Disable start button if gmic.exe is not found and display label message
btnStart.Enabled = false;
TextLabelNearStartButton.Visible = true;
//Color it red
TextLabelNearStartButton.ForeColor = Color.Red;
TextLabelNearStartButton.Text = "gmic.exe not found.";
}
}
// Override mouse scroll increment for numeric updown control of master increment so it doesn't change by 3
private void ScrollHandlerFunction(object sender, MouseEventArgs e)
{
NumericUpDown control = (NumericUpDown)sender;
((HandledMouseEventArgs)e).Handled = true;
decimal value = control.Value + ((e.Delta > 0) ? control.Increment : -control.Increment);
control.Value = Math.Max(control.Minimum, Math.Min(value, control.Maximum));
}
//Property getter setter needs to also be able to deal with the placeholder manager event handler, otherwise it will not work
public string StartParamsTextBoxChangeSetter
{
get
{
return txtStartParams.ForeColor == Color.Gray ? "" : txtStartParams.Text;
}
set
{
if (string.IsNullOrEmpty(value))
{
txtStartParams.Text = (string)txtStartParams.Tag;
txtStartParams.ForeColor = Color.Gray;
}
else
{
txtStartParams.Text = value;
txtStartParams.ForeColor = Color.Black; // Ensure it's treated as actual data
}
RefreshGraph();
txtStartParams_TextChanged(null, null);
}
}
public string EndParamsTextTextBoxChangeSetter
{
get
{
return txtEndParams.ForeColor == Color.Gray ? "" : txtEndParams.Text;
}
set
{
if (string.IsNullOrEmpty(value))
{
txtEndParams.Text = (string)txtEndParams.Tag;
txtEndParams.ForeColor = Color.Gray;
}
else
{
txtEndParams.Text = value;
txtEndParams.ForeColor = Color.Black; // Ensure it's treated as actual data
RefreshGraph();
}
txtEndParams_TextChanged(null, null);
}
}
public string CustomExpressionArrayTextBoxChangeSetter
{
get
{
//return txtExponentArray.ForeColor == Color.Gray ? "" : txtExponentArray.Text;
return txtExponentArray.Text;
}
set
{
if (string.IsNullOrEmpty(value))
{
txtExponentArray.Text = (string)txtExponentArray.Tag;
//txtExponentArray.ForeColor = Color.Gray;
}
else
{
txtExponentArray.Text = value;
//txtExponentArray.ForeColor = Color.Black; // Ensure it's treated as actual data
}
}
}
public string CustomMasterExpressionTextBoxChangeSetter
{
get
{
//return txtMasterExponent.ForeColor == Color.Gray ? "" : txtMasterExponent.Text;
return txtMasterExponent.Text;
}
set
{
if (string.IsNullOrEmpty(value))
{
txtMasterExponent.Text = (string)txtMasterExponent.Tag;
//txtMasterExponent.ForeColor = Color.Gray;
}
else
{
txtMasterExponent.Text = value;
//txtMasterExponent.ForeColor = Color.Black; // Ensure it's treated as actual data
}
}
}
public decimal MasterParamIndexNUDChangeSetter
{
get
{
return (decimal)nudMasterParamIndex.Value;
}
set
{
nudMasterParamIndex.Value = value;
// Trigger event handler
nudMasterParamIndex_ValueChanged(null, null);
}
}
public decimal TotalFramesNUDChangeSetter
{
get
{
return (decimal)nudTotalFrames.Value;
}
set
{
nudTotalFrames.Value = value;
// Trigger event handler
nudTotalFrames_ValueChanged(null, null);
}
}
public bool AbsoluteModeCheckBoxChangeSetterMainForm
{
get
{
return checkBoxAbsoluteModeMain.Checked;
}
set
{
checkBoxAbsoluteModeMain.Checked = value;
}
}
public string ExponentModeRadioSetterMainForm
{
set
{
if (value == "NoExponents")
{
rbNoExponents.Checked = true;
rbNoExponents_CheckedChanged(null, null);
}
else if (value == "MasterExponent")
{
rbMasterExponent.Checked = true;
rbMasterExponent_CheckedChanged(null, null);
}
else if (value == "DefaultExponents")
{
rbDefaultExponents.Checked = true;
rbDefaultExponents_CheckedChanged(null, null);
}
else if (value == "CustomExponents")
{
rbCustomExponents.Checked = true;
rbCustomExponents_CheckedChanged(null, null);
}
}
}
public string NormalizersChangeSetterMainForm
{
set
{
if (value == "NormalizeStartEndClone")
{
radioNormalizeStartEnd.Checked = true;
radioNormalizeStartEnd_CheckedChanged(null, null);
}
else if (value == "NormalizeMaxRanges")
{
radioNormalizeMaxRanges.Checked = true;
radioNormalizeMaxRanges_CheckedChanged(null, null);
}
else if (value == "NormalizeExtendedRanges")
{
radioNormalizeExtendedRanges.Checked = true;
radioNormalizeExtendedRanges_CheckedChanged(null, null);
}
else if (value == "NoNormalize")
{
radioNoNormalize.Checked = true;
radioNoNormalize_CheckedChanged(null, null);
}
}
}
public (double[], double[]) CurrentParameterValuesGetter(bool returnDefaultsForFailedParse = false)
{
// Gets an array of the current parameter values start and end
// First get strings
string startParamsString = txtStartParams.Text;
string endParamsString = txtEndParams.Text;
// Try to split the parameters into arrays if they aren't empty. use ParseParamsToDoubleArray function, which will return null if it fails
double[] startValues = ParseParamsToDoublesArray(startParamsString, silent: true);
double[] endValues = ParseParamsToDoublesArray(endParamsString, silent: true);
if (startValues == null || endValues == null)
{
if (returnDefaultsForFailedParse)
{
// If the values are null, return the default values
return (ParseParamsToDoublesArray(defaultStartParams, silent: true), ParseParamsToDoublesArray(defaultEndParams, silent: true));
}
else
{
// One or both might be null here
return (startValues, endValues);
}
}
else
{
return (startValues, endValues);
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
cancellationRequested = true;
}
private void btnSelectInputFile_Click(object sender, EventArgs e)
{
// Create an OpenFileDialog to select an image file.
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Image Files (*.png, *.jpg, *.jpeg, *.bmp)|*.png;*.jpg;*.jpeg;*.bmp";
openFileDialog.Title = "Select Input Image File";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
// Store the selected file path in inputFilePath and display it in txtInputFilePath textbox.
inputFilePath = openFileDialog.FileName;
txtInputFilePath.Text = inputFilePath;
}
}
private async void btnStart_Click(object sender, EventArgs e)
{
//Set label to invisible until the process is done, and start with progress bar at 0
TextLabelNearStartButton.Visible = false;
progressBarGeneration.Value = 0;
// Validate that an input file has been selected.
if (string.IsNullOrEmpty(txtInputFilePath.Text) || !File.Exists(txtInputFilePath.Text))
{
MessageBox.Show("Please select an input image file.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
else
{
inputFilePath = txtInputFilePath.Text;
}
// Retrieve and store user inputs from the form controls.
startParams = txtStartParams.Text;
endParams = txtEndParams.Text;
int masterParamIndexAtTimeOfClick = (int)nudMasterParamIndex.Value - 1;
double masterParamIncrementAtTimeOfClick = (double)nudMasterParamIncrement.Value;
// Validate the increment for the master parameter.
if (masterParamIncrement <= 0)
{
MessageBox.Show("Master Param Increment must be greater than zero.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// Read the state of the checkbox to determine if exponential increments are to be used.
//exponentialIncrements = chkExponentialIncrements.Checked;
// Try to parse the exponent entered by the user; if parsing fails, masterExponent remains at its previously set value (initially 0).
//double.TryParse(txtMasterExponent.Text, out double masterExponent);
// Store any custom exponent array or use a default one.
//string exponentArray = txtExponentArray.Text;
// Read the state of the GIF creation option.
createGif = chkCreateGif.Checked;
// Get the start and end parameter values as a tuple of array of doubles.
double[] startValues = ParseParamsToDoublesArray(startParams, silent: false);
double[] endValues = ParseParamsToDoublesArray(endParams, silent: false);
if (startValues == null || endValues == null)
{
return;
}
// Calculate the total number of frames required based on the master parameter's range and increment.
//UpdateTotalFrames();
int totalFrames = CalcTotalFrames(startValues[masterParamIndexAtTimeOfClick], endValues[masterParamIndexAtTimeOfClick], masterParamIncrementAtTimeOfClick);
// If totalFrames is 0, alert user with message box
if (totalFrames <= 1)
{
if (endValues[masterParamIndexAtTimeOfClick] == startValues[masterParamIndexAtTimeOfClick])
{
MessageBox.Show("Start and end values for the master parameter are the same so no frames would be generated.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
MessageBox.Show("Something is wrong - no frames would be generated with the current settings. Check the master parameter increment or start and end parameters.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return;
}
// Determine the exponent mode and set up the exponents array based on user selections.
string exponentMode = null;
bool absoluteMode = false;
// Set exponents array to the default array to start
string[] exponents = Array.ConvertAll(defaultExponents, x => x.ToString());
string masterExponentStr = "?";
if (rbNoExponents.Checked)
{
exponentialIncrements = false;
}
// If the master exponent radio button is checked, check if the user has entered a value or not. If not, use the value from the default array.
else if (rbMasterExponent.Checked)
{
exponentialIncrements = true;
var (isValid, reason) = IsValidMathExpression(txtMasterExponent.Text, absoluteMode: checkBoxAbsoluteModeMain.Checked);
if (double.TryParse(txtMasterExponent.Text, out _) || isValid)
{
// Set the master exponent string in the exponents array
exponents[masterParamIndexAtTimeOfClick] = txtMasterExponent.Text;
exponentMode = "custom-master";
masterExponentStr = txtMasterExponent.Text;
absoluteMode = checkBoxAbsoluteModeMain.Checked; // Absolute mode is only relevant in custom array mode or custom master mode
}
else if (!string.IsNullOrEmpty(txtMasterExponent.Text) && !isValid)
{
MessageBox.Show(
"Invalid exponent or expression entered. Must be a decimal number or mathematicaly expression using only the variable 't' for time." +
$"\n\nEntered Value: {txtMasterExponent.Text}\nReason: {reason}",
"Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
else
{
// Convert defaultExponents to a string array
exponentMode = "default-array";
// Set the master exponent string from the default exponents array
masterExponentStr = exponents[masterParamIndexAtTimeOfClick];
}
}
else if (rbDefaultExponents.Checked)
{
// Keep exponents default
exponentialIncrements = true;
exponentMode = "default-apply-all";
masterExponentStr = exponents[masterParamIndexAtTimeOfClick];
}
else if (rbCustomExponents.Checked)
{
exponentialIncrements = true;
string exponentArrayString = txtExponentArray.Text;
if (!string.IsNullOrEmpty(exponentArrayString))
{
// Remove GMIC GUI Produced filter extra string with filter name from the start of the string if there
string stringToReplace = FilterParameters.ActiveFilter.GmicCommand;
exponentArrayString = exponentArrayString.Replace(stringToReplace, "").Replace(" ", "").Trim();
exponents = exponentArrayString.Split(',');
if (exponents.Length == FilterParameters.GetActiveParameterCount())
{
List<List<string>> invalidValues = new List<List<string>>();
// Check that all values are either valid numbers or valid math expressions. If not, alert the user to the position of the invalid value and the value itself.
for (int i = 0; i < FilterParameters.GetActiveParameterCount(); i++)
{
// Track invalid values and alert user at end of all of them, if any
// Test expression with sample values
var (isValid, reason) = IsValidMathExpression(exponents[i], absoluteMode: checkBoxAbsoluteModeMain.Checked);
if (!double.TryParse(exponents[i], out _) && !isValid)
{
invalidValues.Add(new List<string> { (i + 1).ToString(), exponents[i], $"Reason: {reason}" });
}
}
if (invalidValues.Count > 0)
{
string invalidValuesString = string.Join("\n\n", invalidValues.Select(x => $"Position {x[0]}:\nValue: {x[1]}\n{x[2]}"));
MessageBox.Show(
"Invalid exponents or expressions found in array...\n\n" + invalidValuesString,
"Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error
);
return;
}
exponentMode = "custom-array";
absoluteMode = checkBoxAbsoluteModeMain.Checked; // Absolute mode is only relevant in custom array mode or custom master mode
}
else
{
MessageBox.Show($"Exponent array must contain {FilterParameters.GetActiveParameterCount()} comma-separated values.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
else
{
MessageBox.Show("Please enter a comma-separated of custom exponents or expressions.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
// Generate a unique output directory for storing generated frames based on the input file's name.
string outputDir = CreateOutputDirectory(inputFilePath);
// Calculate interpolated parameter values for each frame using the selected interpolation method.
// Note - Master parameter is not passed in because it should just be set in the array, then the function will pull the value from the array
(List<string> interpolatedParams, List<Dictionary<string, object>> errorsInfoList) = InterpolateValues(startValues, endValues, totalFrames, masterParamIndexAtTimeOfClick, masterParamIncrementAtTimeOfClick, exponents, exponentMode, absoluteMode: absoluteMode);
// Decide frame starting number
int frameNumberStart = 1;
// If checkbox to use same directory is checked, see how many files are already in there to get next available number
if (checkBoxUseSameOutputDir.Checked)
{
// Get file with largest number at the end
frameNumberStart = CountExistingFiles(outputDir) + 1;
}
// Create the log file with metadata and interpolated parameters
CreateLogFile(outputDir: outputDir,
interpolatedParams: interpolatedParams,
exponentMode: exponentMode,
defaultExponents: defaultExponents,
masterExponentString: masterExponentStr,
frameStartNumber: frameNumberStart,
masterParamIndex: masterParamIndexAtTimeOfClick,
masterParamIncrement: masterParamIncrementAtTimeOfClick,
totalFrames: totalFrames,
exponentStringArray: exponents
);
btnStart.Visible = false;
btnCancel.Visible = true;
// See if checkbox to only log is enabled
if (!checkBoxLogOnly.Checked)
{
int debugSetting = dropdownDebugLog.SelectedIndex;
double progressIncrement = 100.0 / totalFrames;
double progressPercent = 0;
// Process each frame using the specified parameters and gmic.exe.
await Task.Run(() => ProcessFrames(outputDir, interpolatedParams, frameNumberStart, debugSetting));
// If option to delete blank frames is enabled, delete them
if (checkBoxRemoveBlankFrames.Checked)
{
// Check each file in the directory and delete if it's blank. Just get a list of the PNGs
int deletedCount = 0;
string[] filesList = Directory.GetFiles(outputDir, "*.png");
for (int i = 0; i < filesList.Length; i++)
{
// Check if the file is blank
if (FileManager.CheckAlphaChannel(filesList[i]).Count == 0)
{
// Delete the file
deletedCount++;
//Rename the file to add .blank
File.Move(filesList[i], filesList[i] + ".blank");
}
}
// If any files were deleted, resequence the files
if (deletedCount > 0)
{
FileManager fileManager = new FileManager();
string baseFileName = fileManager.GetBaseFileNameWithinFolder(outputDir);
SequenceFixResult sequenceFixResult = fileManager.FixDiscontinuousSequence(outputDir, baseFileName);
PaddingUpdateResult paddingUpdateResult = fileManager.UpdateZeroPadding(outputDir, baseFileName);
}
}
// Optionally create a GIF from the generated frames using ffmpeg.
if (createGif)
{
CreateGif(outputDir);
}
// Reset progress bar
progressBarGeneration.Value = 0;
// Open the output directory in Windows Explorer for user review.
//Process.Start("explorer.exe", outputDir);
}
else
{
// Restore start button and hide cancel button
cancellationRequested = false;
btnStart.Visible = true;
btnCancel.Visible = false;
}
}
// Function to parse parameter values from a string and return them as an array of doubles.
private double[] ParseParamsToDoublesArray(string paramsString, bool silent = false)
{
// Check if the parameters string is valid.
if (string.IsNullOrEmpty(paramsString))
{
if (!silent)
{
MessageBox.Show("Must enter values for parameters.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return null;
}
// Remove GMIC GUI Produced filter extra string from the start of the string if there. Also remove spaces from inside the string.
string commandName = FilterParameters.ActiveFilter.GmicCommand;
paramsString = paramsString.Replace(commandName, "").Replace(" ", "").Trim();
// Split the parameters string into an array.
string[] paramsArray = paramsString.Split(',');
// Ensure the parameter array has exactly correct amount of elements.
if (paramsArray.Length != FilterParameters.GetActiveParameterCount())
{
if (!silent)
{
MessageBox.Show($"Parameter arrays must contain {FilterParameters.GetActiveParameterCount()} comma-separated values." +
$"\n\nFound only {paramsArray.Length}" +
$"\n\nCurrent parameter array:\n{paramsString}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return null;
}
// Convert the parameter strings to double values and store them in an array.
double[] paramValuesArray = new double[FilterParameters.GetActiveParameterCount()];
for (int i = 0; i < FilterParameters.GetActiveParameterCount(); i++)
{
// If not text type parameter
if (FilterParameters.GetParameterType(i).ToLower() != "text")
{
// Check if the parameter value is a valid number, if not, alert the user and return null.
if (!double.TryParse(paramsArray[i], out paramValuesArray[i]))
{
if (!silent)
{
MessageBox.Show("Invalid parameter value at position " + (i + 1) + ". Please enter valid numbers.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return null;
}
}
// Check if the parameter variable index is of text type, if so set it to zero while stored internally
else if (FilterParameters.GetParameterType(i).ToLower() == "text")
{
// Check if paramsArray value is 0, if so get the text parameter value from the active filter's default value
if (paramsArray[i] == "0")
{
}
else
{
}
// Set the text parameter in active filter
FilterParameters.SetTextParameterValue(i, paramsArray[i]);
paramValuesArray[i] = 0;
}
}
// Update the active filter with the parameter string. Doesn't matter if it's start or end because it shouldn't change
//ParseParameterStringToStringAndUpdateActiveFilter(parameterString: paramsString);
// Return the array of parameter values.
return paramValuesArray;
}
private string CreateOutputDirectory(string inputFilePath)
{
string outputDir;
// If checkbox to use same directory is checked, get the latest directory and use that
if (checkBoxUseSameOutputDir.Checked)
{
outputDir = GetLatestDirectory(inputFilePath, false);
}
else
{
outputDir = GetLatestDirectory(inputFilePath, true);
Directory.CreateDirectory(outputDir);
}
return outputDir;
}
private string DecideLogFilePath(string outputDirPath)
{
// Get deepest folder name
string[] directoryParts = outputDirPath.Split(Path.DirectorySeparatorChar);
string folderName = directoryParts[directoryParts.Length - 1];
string logFilePath = Path.Combine(outputDirPath, $"{folderName}_log.txt");
int logFileNumber = 2;
// Check if log file already exists, count up until available number
while (File.Exists(logFilePath))
{
logFilePath = Path.Combine(outputDirPath, $"{folderName}_log_{logFileNumber}.txt");
logFileNumber++;
}
return logFilePath;
}
private int CountExistingFiles(string outputDir)
{
// Use filename without extension as base for counting files
int count = 0;
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(inputFilePath);
string[] files = Directory.GetFiles(outputDir, $"{fileNameWithoutExtension}_*.png");
foreach (string file in files)
{
count++;
}
return count;
}
// Get the latest directory that exists already, or none if none exist. Uses the input file name as a base, returns the latest directory with the same name.
private string GetLatestDirectory(string inputFilePath, bool getNextAvailable = false)
{
string rootOutputFolder = "Output";
// Extract the file name without extension from the input file path
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(inputFilePath);
string outputDirBase = Path.Combine(rootOutputFolder, fileNameWithoutExtension);
// Initialize the output directory name to the file name without extension
// Combine the base output folder with the file name without extension to create the initial directory name
string availableDir = outputDirBase;
// This variable will store the name of the latest existing directory found
string latestExisting = null;
// This will count the existing directories with similar names
int folderCount = 1;
// Loop through directory names to find the last existing one or find the next available if specified
while (Directory.Exists(availableDir))
{
latestExisting = availableDir;
folderCount++;
availableDir = $"{outputDirBase}_{folderCount}";
}
// If getNextAvailable is true, return the next directory name that does not exist
if (getNextAvailable)
{
return availableDir;
}
else
{
return latestExisting;
}
}
// Create getter to use the InterpolateValues function in the MainForm class from the ExpressionsForm class
public (List<string>, List<Dictionary<string, object>>) GetInterpolatedValuesForGraph(int masterParamIndex, string[] allExpressionsList, int frameCount, bool absoluteMode = false, bool silent = true)
{
// Use data from this form to interpolate values
double[] startValues = ParseParamsToDoublesArray(txtStartParams.Text, silent: silent);
double[] endValues = ParseParamsToDoublesArray(txtEndParams.Text, silent: silent);
// If the start and end values are null, just set them to 1 and 100 as general case
if (startValues == null || endValues == null)
{
// Only go to one less than the filter because add the last one separately
for (int i = 0; i < (FilterParameters.GetActiveParameterCount() - 1); i++)
{
startParams += "1,";
endParams += "100,";
}
// Add the last one without a comma
startParams += "1";
endParams += "100";
}
// Get total frame count from the main form numeric updown controller, unless frame count was passed in (won't be zero if passed in
int totalFrames;
if (frameCount == 0)
{
totalFrames = (int)nudTotalFrames.Value;
}
else
{
totalFrames = frameCount;
}
// Always use custom-master mode for this function because the calling function will send in a full array with only the master parameter expression set
string exponentMode = "custom-master";
// Returns the interpolated values for the graph and list of errors
return InterpolateValues(startValues, endValues, totalFrames, masterParamIndex, (int)nudMasterParamIncrement.Value, allExpressionsList, exponentMode, masterParamOnly: true, absoluteMode: absoluteMode);
}
// Interpolates parameter values for each frame based on given start and end parameters, and the total number of frames.
// Returns a list of strings representing the interpolated parameter values for each frame. Also returns a list of strings containing any errors that occurred during evaluation.
private (List<string>, List<Dictionary<string, object>>) InterpolateValues(double[] startValues, double[] endValues, int totalFrames, int masterIndex, double masterIncrement, string[] exponents, string exponentMode, bool masterParamOnly = false, bool absoluteMode = false)
{
double[] originalStartValues = startValues;
double[] originalEndValues = endValues;
List<int> exponentsUsingExpressions = new List<int>();
List<string> errorsList = new List<string>();
List<Dictionary<string, object>> errorsInfoList = new List<Dictionary<string, object>>();
// List to store all interpolated values for each frame.
//List<string> interpolatedValuesPerFrameStrings = new List<string>();
// List of 31 arrays of doubles to hold the interpolated values for each parameter.
double[,] interpolatedValuesPerFrameArray = new double[totalFrames, FilterParameters.GetActiveParameterCount()];
// Loop through each frame to calculate parameter values.
for (int frame = 0; frame < totalFrames; frame++)
{
// Array to hold the current set of interpolated parameters.
double[] currentValues = new double[FilterParameters.GetActiveParameterCount()];
// Loop through each parameter to interpolate its value.
for (int i = 0; i < FilterParameters.GetActiveParameterCount(); i++)
{
if (masterParamOnly && i != masterIndex)
{
// If only the master parameter is being interpolated, skip the rest.
currentValues[i] = startValues[i];
continue;
}
// Initialize the current value with the start value of the parameter.
double currentValue = startValues[i];
// Calculate the normalized time value (t) for the current frame.
double normalizedTime = (double)frame / (totalFrames - 1);
// Create variable to hold error if any
string evalErrorString = null;
string subbedExpressionString = null;
// If absolute mode is enabled but exponent mode is not custom array or custom master, set change it to custom array
// This would only be if the graph is calling it so it doesn't really matter exponent mode is set
if (absoluteMode)
{
if (exponentMode != "custom-array" && exponentMode != "custom-master")
{
exponentMode = "custom-array";
}
}
// Decide the interpolation method for the current individual parameter based on the mode set.
switch (exponentMode)
{
// If the user has specified a custom exponent for the master parameter and exponential increments are enabled.
case "custom-master":
if (i == masterIndex)