-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainForm.cs
More file actions
1656 lines (1469 loc) · 72.3 KB
/
MainForm.cs
File metadata and controls
1656 lines (1469 loc) · 72.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
using AxWMPLib;
using ExifLibrary;
using GMap.NET.MapProviders;
using Microsoft.VisualBasic;
using Microsoft.WindowsAPICodePack.Dialogs;
using Microsoft.WindowsAPICodePack.Shell;
using Microsoft.WindowsAPICodePack.Shell.PropertySystem;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Text.RegularExpressions;
namespace SetMediaProps
{
public partial class MainForm : Form
{
const char PersianDateSeparator = '-';
const string latRefNorth = "North";
const string latRefSouth = "South";
const string lonRefEast = "East";
const string lonRefWest = "West";
const string altRefAbove = "AboveSeaLevel";
const string altRefBelow = "BelowSeaLevel";
private float _latitude = int.MinValue;
private float _longitude = int.MinValue;
private float _altitude = int.MinValue;
private float savedLatitude = int.MinValue;
private float savedLongitude = int.MinValue;
private float savedAltitude = int.MinValue;
private float memmoryLatitude = 35.7523F;
private float memmoryLongitude = 51.4232F;
private float memmoryAltitude = 1412F;
static private string PersianDateTime(DateTime gDate)
{
string pDate = "";
if (gDate != DateTime.MinValue)
{
PersianCalendar pc = new PersianCalendar();
pDate = pc.GetYear(gDate).ToString().PadLeft(4, '0');
pDate += PersianDateSeparator;
pDate += pc.GetMonth(gDate).ToString().PadLeft(2, '0');
pDate += PersianDateSeparator;
pDate += pc.GetDayOfMonth(gDate).ToString().PadLeft(2, '0');
pDate += " ";
pDate += gDate.Hour.ToString().PadLeft(2, '0');
pDate += ":";
pDate += gDate.Minute.ToString().PadLeft(2, '0');
pDate += ":";
pDate += gDate.Second.ToString().PadLeft(2, '0');
}
return pDate;
}
static private string CharCorrecttions(string Name)
{
string _name = Name;
Regex regex = new Regex(@"^[0-9]{4}-[0-9]{2}-[0-9]{2}_[0-9]{6}_");
string _ext = Path.GetExtension(Name);
_name = _name.Replace(_ext, "");
_ext = _ext.ToLower().Replace("jpeg", "jpg").Replace("mpeg", "mpg");
if (regex.IsMatch(Name))
{
_name = _name.Substring(18);
}
_name = _name.Replace("۰", "");
_name = _name.Replace("۱", "");
_name = _name.Replace("۲", "");
_name = _name.Replace("۳", "");
_name = _name.Replace("۴", "");
_name = _name.Replace("۵", "");
_name = _name.Replace("۶", "");
_name = _name.Replace("۷", "");
_name = _name.Replace("۸", "");
_name = _name.Replace("۹", "");
regex = new Regex("_+/g");
_name = regex.Replace(_name, "_");
return _name + _ext;
}
static private string MakeFileName(string PersianDate, string AddedText, string Filename)
{
string res = PersianDate.Replace(" ", "_").Replace(":", "");
if (AddedText != "")
res += "_" + AddedText;
res += "_" + CharCorrecttions(Filename); ;
return res;
}
public string SetAllMediaProps(string Source, DateTime Date, string Destination)
{
int err = 0;
string ext = Path.GetExtension(Source).ToLower();
try
{
if (Array.IndexOf(new string[] { ".jpg", ".jpeg", ".png", ".gif" }, ext) >= 0)
{
var file = ImageFile.FromFile(Source);
file.Properties.Set(ExifLibrary.ExifTag.DateTimeDigitized, Date);
file.Properties.Set(ExifLibrary.ExifTag.DateTimeOriginal, Date);
file.Save(Source);
}
else if (Array.IndexOf(new string[] { ".avi", ".mpg", ".mpeg", ".mov", ".mp4" }, ext) >= 0)
{
ProcessStartInfo ExifTool = new();
Process process = new();
ExifTool.FileName = @"exiftool.exe";
ExifTool.Arguments = $"-overwrite_original \"-alldates={Date.ToString("yyyy:MM:dd HH:mm:ss")}\" -api QuickTimeUTC=1 -api LargeFileSupport=1 \"" + Source + "\"";
ExifTool.UseShellExecute = false;
ExifTool.CreateNoWindow = true;
ExifTool.LoadUserProfile = false;
ExifTool.RedirectStandardOutput = true;
ExifTool.RedirectStandardError = true;
process.StartInfo = ExifTool;
process.Start();
process.WaitForExit(30000);
string? output = process.StandardOutput.ReadLine();
string? error = process.StandardError.ReadLine();
if (output != null)
{
}
if (error != null)
{
return error;
}
if (ext == ".mov")
{
ExifTool.Arguments = $"-overwrite_original \"-CreationDate={Date.ToString("yyyy:MM:dd HH:mm:ss")}\" -api QuickTimeUTC=1 -api LargeFileSupport=1 \"" + Source + "\"";
Process movProcess = new();
movProcess.StartInfo = ExifTool;
movProcess.Start();
movProcess.WaitForExit(30000);
output = movProcess.StandardOutput.ReadLine();
error = movProcess.StandardError.ReadLine();
}
try
{
using (var shell = ShellFile.FromFilePath(Source))
{
ShellPropertyWriter w = shell.Properties.GetPropertyWriter();
w.WriteProperty(SystemProperties.System.Media.DateEncoded, Date);
w.Close();
}
}
catch (Exception)
{
}
}
}
catch (Exception e)
{
return e.Message;
}
System.IO.File.SetCreationTime(Source, Date);
System.IO.File.SetLastWriteTime(Source, Date);
// Rename File
System.IO.File.Move(Source, Destination);
return "";
}
private class Props
{
public Props(string FullPath, string AddedText)
{
FileInfo file = new FileInfo(FullPath);
if (file.Exists)
{
Path = FullPath;
Filename = file.Name;
FileExtention = file.Extension.Replace(".", "");
ShellObject? File = ShellObject.FromParsingName(FullPath);
CreateDateTime = System.IO.File.GetCreationTime(FullPath);
FinalDateTime = DateTime.MinValue;
var pictureDate = File.Properties.GetProperty(SystemProperties.System.Photo.DateTaken);
if (pictureDate.ValueAsObject == null || !DateTime.TryParse(pictureDate.ValueAsObject.ToString(), out MediaDateTime))
MediaDateTime = DateTime.MinValue;
if (MediaDateTime == DateTime.MinValue)
{
var mediaDate = File.Properties.GetProperty(SystemProperties.System.Media.DateEncoded);
if (mediaDate.ValueAsObject == null || !DateTime.TryParse(mediaDate.ValueAsObject.ToString(), out MediaDateTime))
MediaDateTime = DateTime.MinValue;
}
if (MediaDateTime == DateTime.MinValue && FileExtention.ToLower() == "mov")
{
ProcessStartInfo ExifProccess = new();
Process process = new();
ExifProccess.FileName = @"exiftool.exe";
ExifProccess.Arguments = $"-ee -n -api LargeFileSupport=1 -p \"$CreationDate\" \"" + FullPath + "\"";
ExifProccess.UseShellExecute = false;
ExifProccess.CreateNoWindow = true;
ExifProccess.LoadUserProfile = false;
ExifProccess.RedirectStandardOutput = true;
ExifProccess.RedirectStandardError = true;
process.StartInfo = ExifProccess;
//process.BeginOutputReadLine();
//process.BeginErrorReadLine();
string? output = "";
string? error = "";
//output = process.StandardOutput.ReadLine();
//error = process.StandardError.ReadLine();
process.OutputDataReceived += (sender, args) =>
{
if (output == "")
{
output = args.Data;
}
};
process.ErrorDataReceived += (sender, args) =>
{
if (error == "")
{
error = args.Data;
}
};
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit(10000);
//output = output[..output.IndexOf('+')];
if (output != null && output.Length >= 19)
{
output = output[..10].Replace(':', '/') + output[10..];
if (!DateTime.TryParse(output, out MediaDateTime))
MediaDateTime = DateTime.MinValue;
}
}
if (PersianDateTime(MediaDateTime) != "")
FinalDateTime = MediaDateTime;
var camera = File.Properties.GetProperty(SystemProperties.System.Photo.CameraModel);
Camera = (camera.ValueAsObject != null) ? camera.ValueAsObject.ToString() : "";
FinalName = MakeFileName(PersianDateTime(FinalDateTime), AddedText, Filename);
//GPS_Text = getGPSData(FullPath, out Latitude, out Longitude, out Altitude);
}
}
public string Path;
public string Filename;
public string FileExtention;
public DateTime CreateDateTime;
public DateTime MediaDateTime;
public string Camera;
public DateTime FinalDateTime;
public string GPS_Text;
public float Latitude;
public float Longitude;
public float Altitude;
public string FinalName;
}
private static string GPS_Text(float lat, float lon, float alt)
{
string GPS = $"{Math.Abs(lat):#.0000}{(lat >= 0 ? "N" : "S")}";
GPS += ", ";
GPS += $"{Math.Abs(lon):#.0000}{(lon >= 0 ? "E" : "W")}";
GPS += ", ";
GPS += $"{(alt < 0 ? "-" : "+")}{alt:#,##0}m";
return GPS;
}
private static string GetPropertyTypeName(Type type, int length)
{
if (type == null)
{
return "null";
}
if (type.IsArray || type.HasElementType)
{
return GetPropertyTypeName(type.GetElementType(), 0) + '[' + length + ']';
}
if (type.IsGenericType)
{
string name = type.Name;
if (name.IndexOf('`') >= 0)
{
name = name.Substring(0, name.IndexOf('`'));
}
name += '<';
Type[] args = type.GetGenericArguments();
for (int i = 0; i < args.Length; i++)
{
if (i > 0)
{
name += ',';
}
name += args[i].Name;
}
name += '>';
return name;
}
if (type.IsEnum)
{
return type.Name + ':' + Enum.GetUnderlyingType(type).Name;
}
return type.Name;
}
private static string getGPSData(string SourecFile, out float Lat, out float Lon, out float Alt)
{
string GPS = "";
Lat = Lon = Alt = 0;
try
{
string ext = Path.GetExtension(SourecFile).ToLower();
if (Array.IndexOf(new string[] { ".jpg", ".jpeg", ".png", ".gif" }, ext) >= 0)
{
var img = ImageFile.FromFile(SourecFile);
try
{
var lat = (MathEx.UFraction32[])img.Properties.Get(ExifLibrary.ExifTag.GPSLatitude).Value;
string? latRef = img.Properties.Get(ExifLibrary.ExifTag.GPSLatitudeRef).Value.ToString();
float _lat = (float)lat[0] + (float)lat[1] / 60 + (float)lat[2] / 3600;
Lat = _lat;
var lon = (MathEx.UFraction32[])img.Properties.Get(ExifLibrary.ExifTag.GPSLongitude).Value;
var lonRef = img.Properties.Get(ExifLibrary.ExifTag.GPSLongitudeRef).Value.ToString();
float _long = (float)lon[0] + (float)lon[1] / 60 + (float)lon[2] / 3600;
Lon = _long;
}
catch (Exception)
{
//GPS = "";
}
MathEx.UFraction32 alt;
var altRef = "";
try
{
altRef = img.Properties.Get(ExifLibrary.ExifTag.GPSAltitudeRef).Value.ToString();
}
catch (Exception)
{
altRef = altRefAbove;
}
try
{
alt = (MathEx.UFraction32)img.Properties.Get(ExifLibrary.ExifTag.GPSAltitude).Value;
float _alt = (float)alt;
Alt = _alt;
}
catch (Exception)
{
}
}
else // Video
{
ProcessStartInfo ExifProccess = new();
Process process = new();
ExifProccess.FileName = @"exiftool.exe";
ExifProccess.Arguments = $"-ee -n -api LargeFileSupport=1 -p \"$gpslatitude,$gpslongitude\" \"" + SourecFile + "\"";
ExifProccess.UseShellExecute = false;
ExifProccess.CreateNoWindow = true;
ExifProccess.LoadUserProfile = false;
ExifProccess.RedirectStandardOutput = true;
ExifProccess.RedirectStandardError = true;
process.StartInfo = ExifProccess;
//process.BeginOutputReadLine();
//process.BeginErrorReadLine();
string? output = "";
string? error = "";
//output = process.StandardOutput.ReadLine();
//error = process.StandardError.ReadLine();
process.OutputDataReceived += (sender, args) =>
{
if (output == "")
{
output = args.Data;
}
};
process.ErrorDataReceived += (sender, args) =>
{
if (error == "")
{
error = args.Data;
}
};
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit(10000);
if (output != null)
{
var _gps = output.Split(',');
float lat = float.Parse(_gps[0]);
string? latRef = lat >= 0 ? latRefNorth : latRefSouth;
Lat = lat;
float lon = float.Parse(_gps[1]);
string? lonRef = lon >= 0 ? lonRefEast : lonRefWest;
Lon = lon;
//float alt = (int)float.Parse(_gps[2]);
//string? altRef = alt >= 0 ? altRefAbove : altRefBelow;
//Alt = alt;
}
if (error != null && !error.StartsWith("Warning"))
{
Lat = Lon = 0;
}
process.Close();
process.Dispose();
process = new();
ExifProccess.Arguments = $"-ee -n -api LargeFileSupport=1 -p \"$gpsaltitude\" \"" + SourecFile + "\"";
process.StartInfo = ExifProccess;
output = "";
error = "";
process.OutputDataReceived += (sender, args) =>
{
if (output == "")
{
output = args.Data;
}
};
process.ErrorDataReceived += (sender, args) =>
{
if (error == "")
{
error = args.Data;
}
};
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit(10000);
if (output != null)
{
float alt = (int)float.Parse(output);
string? altRef = alt >= 0 ? altRefAbove : altRefBelow;
Alt = alt;
}
if (error != null && !error.StartsWith("Warning"))
{
Lat = Lon = 0;
}
}
}
catch (Exception e)
{
}
return GPS_Text(Lat, Lon, Alt);
}
private void SetMap(float Lat, float Lon, float Alt)
{
//gMap.Enabled = true;
//gMap.MarkersEnabled = true;
//gMap.GrayScaleMode = false;
if (float.IsNaN(Lat) || float.IsNaN(Lon) || float.IsNaN(Alt))
{
gMap.Position = new GMap.NET.PointLatLng(0, 0);
txtLat.Text = $"NaN";
txtLongt.Text = $"NaN";
txtAlt.Text = $"NaN";
return;
}
gMap.Position = new GMap.NET.PointLatLng(Lat, Lon);
txtLat.Text = $"{Math.Abs(Lat):#.0000}{(Lat >= 0 ? "N" : "S")}";
txtLongt.Text = $"{Math.Abs(Lon):#.0000}{(Lon >= 0 ? "E" : "W")}";
txtAlt.Text = $"{Alt:##,##0}m";
//RectLatLng bounds = gMap.ViewArea;
//List<GPoint> points = gMap.MapProvider.Projection.GetAreaTileList(bounds, (int)gMap.Zoom, 0);
//List<GPoint> tileArea = gMap.MapProvider.Projection.GetAreaTileList(gMap.MapProvider.Projection.Bounds, (int)gMap.Zoom, 1);
//gMap.MapProvider.Projection.GetTileMatrixMinXY((int)gMap.Zoom);
//string ext = Path.GetExtension(Source).ToLower();
//if (Array.IndexOf(new string[] { ".jpg", ".jpeg", ".png", ".gif" }, ext) >= 0)
//{
// var file = ImageFile.FromFile(Source);
// try
// {
// var lat = (MathEx.UFraction32[])file.Properties.Get(ExifTag.GPSLatitude).Value;
// var latRef = file.Properties.Get(ExifTag.GPSLatitudeRef).Value;
// _latitude = (float)lat[0] + (float)lat[1] / 60 + (float)lat[2] / 3600;
// if (latRef.ToString() == latRefSouth)
// {
// _latitude = _latitude * -1;
// }
// var longt = (MathEx.UFraction32[])file.Properties.Get(ExifTag.GPSLongitude).Value;
// var longtRef = file.Properties.Get(ExifTag.GPSLongitudeRef).Value;
// _longitude = (float)longt[0] + (float)longt[1] / 60 + (float)longt[2] / 3600;
// if (longtRef.ToString() == lonRefWest)
// {
// _longitude = _longitude * -1;
// }
// var alt = (MathEx.UFraction32)file.Properties.Get(ExifTag.GPSAltitude).Value;
// string altRef = altRefAbove;
// try
// {
// altRef = file.Properties.Get(ExifTag.GPSAltitudeRef).Value.ToString();
// }
// catch (Exception)
// {
// }
// _altitude = (float)alt;
// if (altRef == altRefBelow)
// {
// _altitude = _altitude * -1;
// }
// //gMap.Enabled = true;
// //gMap.MarkersEnabled = true;
// //gMap.GrayScaleMode = false;
// gMap.Position = new GMap.NET.PointLatLng(_latitude, _longitude);
// txtLat.Text = $"{Math.Abs(_latitude):#.0000}{(_latitude >= 0 ? "N" : "S")}";
// txtLongt.Text = $"{Math.Abs(_longitude):#.0000}{(_longitude >= 0 ? "E" : "W")}";
// txtAlt.Text = $"{_altitude:##,##0}m";
// }
// catch (Exception)
// {
// //gMap.MarkersEnabled = false;
// //gMap.Enabled = false;
// //gMap.GrayScaleMode = true;
// _latitude = int.MinValue;
// _longitude = int.MinValue;
// _altitude = int.MinValue;
// txtLat.Clear();
// txtLongt.Clear();
// txtAlt.Clear();
// }
// //var shell = ShellFile.FromFilePath(Source);
// //IShellProperty latitude = shell.Properties.GetProperty(SystemProperties.System.GPS.Latitude);
// //var Longitude = shell.Properties.GetProperty(SystemProperties.System.GPS.Longitude);
// //var altitude = shell.Properties.GetProperty(SystemProperties.System.GPS.Altitude);
//}
//else // Movie
//{
// try
// {
// ProcessStartInfo ExifTool = new();
// Process process = new();
// ExifTool.FileName = @"exiftool.exe";
// ExifTool.Arguments = $"-ee -n -api LargeFileSupport=1 -p \"$gpslatitude,$gpslongitude,$gpsaltitude\" \"" + Source + "\"";
// ExifTool.UseShellExecute = false;
// ExifTool.CreateNoWindow = true;
// ExifTool.LoadUserProfile = true;
// ExifTool.RedirectStandardOutput = true;
// ExifTool.RedirectStandardError = true;
// process.StartInfo = ExifTool;
// process.Start();
// process.WaitForExit();
// int exitCode = process.ExitCode;
// string? output = process.StandardOutput.ReadLine();
// string? error = process.StandardError.ReadLine();
// if (output != null)
// {
// var _gps = output.Split(',');
// _latitude = float.Parse(_gps[0]);
// _longitude = float.Parse(_gps[1]);
// _altitude = float.Parse(_gps[2]);
// gMap.Position = new GMap.NET.PointLatLng(_latitude, _longitude);
// txtLat.Text = $"{Math.Abs(_latitude):#.0000}{(_latitude >= 0 ? "N" : "S")}";
// txtLongt.Text = $"{Math.Abs(_longitude):#.0000}{(_longitude >= 0 ? "E" : "W")}";
// txtAlt.Text = $"{_altitude:##,##0}m";
// }
// if (error != null)
// {
// }
// }
// catch (Exception)
// {
// //gMap.MarkersEnabled = false;
// //gMap.Enabled = false;
// //gMap.GrayScaleMode = true;
// _latitude = int.MinValue;
// _longitude = int.MinValue;
// _altitude = int.MinValue;
// txtLat.Clear();
// txtLongt.Clear();
// }
//}
}
private DateTime RoundUp(DateTime dt, TimeSpan d)
{
return new DateTime((dt.Ticks + d.Ticks - 1) / d.Ticks * d.Ticks, dt.Kind);
}
private void SetDBGridSortable(bool active)
{
for (int i = 0; i < dataGridView_Main.ColumnCount; i++)
{
dataGridView_Main.Columns[i].SortMode = active ? DataGridViewColumnSortMode.Automatic : DataGridViewColumnSortMode.NotSortable;
}
}
public MainForm()
{
InitializeComponent();
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
System.Diagnostics.FileVersionInfo fvi = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location);
string? version = fvi.FileVersion;
Text += " - v" + version;
button_SetData.Location = new Point(97, 17);
// gMap
gMap = new GMap.NET.WindowsForms.GMapControl();
//gMap.MapProvider = GMap.NET.MapProviders.GoogleMapProvider.Instance;
gMap.AutoScroll = true;
gMap.BackColor = Color.Transparent;
gMap.Bearing = 0F;
gMap.CanDragMap = true;
gMap.Cursor = Cursors.Cross;
gMap.Dock = DockStyle.Fill;
gMap.EmptyTileColor = Color.Navy;
gMap.GrayScaleMode = false;
gMap.HelperLineOption = GMap.NET.WindowsForms.HelperLineOptions.DontShow;
gMap.LevelsKeepInMemory = 5;
gMap.Location = new Point(3, 3);
gMap.MarkersEnabled = true;
gMap.MaxZoom = 20;
gMap.MinZoom = 0;
gMap.MouseWheelZoomEnabled = true;
gMap.MouseWheelZoomType = GMap.NET.MouseWheelZoomType.ViewCenter;
gMap.Name = "gMap";
gMap.NegativeMode = false;
gMap.PolygonsEnabled = true;
gMap.RetryLoadTile = 0;
gMap.RightToLeft = RightToLeft.No;
gMap.RoutesEnabled = false;
gMap.ScaleMode = GMap.NET.WindowsForms.ScaleModes.Integer;
gMap.SelectedAreaFillColor = Color.FromArgb(((int)(((byte)(33)))), ((int)(((byte)(65)))), ((int)(((byte)(105)))), ((int)(((byte)(225)))));
gMap.ShowTileGridLines = false;
//gMap.Size = new Size(366, 233);
gMap.TabIndex = 0;
gMap.Zoom = 15D;
gMap.DoubleClick += new EventHandler(gMap_DoubleClick);
gMap.OnMapDrag += gMap_OnMapDrag;
pnlGMap.Controls.Add(gMap);
wmp.uiMode = "none";
wmp.Ctlenabled = true;
wmp.enableContextMenu = false;
wmp.settings.setMode("loop", true);
}
private void gMap_OnMapDrag()
{
float lat = (float)gMap.Position.Lat;
float lon = (float)gMap.Position.Lng;
savedLatitude = lat;
savedLongitude = lon;
lblSavedLat.Text = $"Lat: {Math.Abs(savedLatitude):#.0000}{(savedLatitude >= 0 ? "N" : "S")}";
lblSavedLongt.Text = $"Lon: {Math.Abs(savedLongitude):#.0000}{(savedLongitude >= 0 ? "E" : "W")}";
}
private void button_SelectDirectory_Click(object sender, EventArgs e)
{
//ChangeNameAndDate("xde.jpeg", DateTime.Now, "pic.jpg");
//return;
DateTime MaxValidDateTime = DateTime.MinValue;
DateTime MinModifyDateTime = DateTime.Now;
var dialog = new CommonOpenFileDialog
{
EnsurePathExists = true,
EnsureFileExists = false,
AllowNonFileSystemItems = false,
DefaultFileName = "Select Folder",
Title = "Select The Folder"
};
if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
using (WaitingForm wfm = new())
{
button_SetData.Enabled = false;
wfm.Show(this);
wfm.Width = this.Size.Width - 15;
wfm.Height = this.Size.Height - 7;
wfm.Left = this.Left + 8;
wfm.Top = this.Top;
dataGridView_Main.Rows.Clear();
var exts = new[] { ".jpg", ".jpeg", ".png", ".gif", ".avi", ".mpg", ".mpeg", ".mov", ".mp4" };
string dirToProcess = System.IO.Directory.Exists(dialog.FileName) ? dialog.FileName : Path.GetDirectoryName(dialog.FileName);
var files = System.IO.Directory.GetFiles(dirToProcess, "*.*", SearchOption.TopDirectoryOnly)
.Where(file => exts.Any(file.ToLower().EndsWith))
.ToList();
SetDBGridSortable(false);
progressBar.Value = 0;
progressBar.Maximum = files.Count;
label_progressBar.Text = "خواندن فایلها";
panel_progressBar.Show();
for (int i = 0; i < files.Count; i++)
{
Props fProps = new(files[i], textBox_Desc.Text);
int index = dataGridView_Main.Rows.Add();
dataGridView_Main.Rows[index].Cells["R"].Value = i + 1;
dataGridView_Main.Rows[index].Cells["fName"].Value = fProps.Filename;
dataGridView_Main.Rows[index].Cells["fExt"].Value = fProps.FileExtention.ToLower();
dataGridView_Main.Rows[index].Cells["fPath"].Value = fProps.Path;
dataGridView_Main.Rows[index].Cells["Camera"].Value = fProps.Camera;
dataGridView_Main.Rows[index].Cells["CreateDate"].Value = fProps.CreateDateTime;
dataGridView_Main.Rows[index].Cells["MediaDate"].Value = PersianDateTime(fProps.MediaDateTime);
dataGridView_Main.Rows[index].Cells["FinalDate"].Value = fProps.FinalDateTime;
dataGridView_Main.Rows[index].Cells["PersianFinalDateTime"].Value = PersianDateTime(fProps.FinalDateTime);
dataGridView_Main.Rows[index].Cells["AddedText"].Value = textBox_Desc.Text;
dataGridView_Main.Rows[index].Cells["FinalName"].Value = checkBox_Active.Checked ? fProps.FinalName : "";
dataGridView_Main.Rows[index].Cells["GPS"].Value = fProps.GPS_Text;
dataGridView_Main.Rows[index].Cells["Latitude"].Value = fProps.Latitude;
dataGridView_Main.Rows[index].Cells["Longitude"].Value = fProps.Longitude;
dataGridView_Main.Rows[index].Cells["Altitude"].Value = fProps.Altitude;
string ext = System.IO.Path.GetExtension(fProps.FinalName).Replace(".", "");
if (ext == "jpg" || ext == "gif" || ext == "png" || ext == "avi" || ext == "mpg" || ext == "mov" || ext == "mp4")
dataGridView_Main.Rows[index].Cells["Active"].Value = checkBox_Active.Checked;
else
{
dataGridView_Main.Rows[index].Cells["Active"].Value = false;
dataGridView_Main.Rows[index].DefaultCellStyle.BackColor = Color.Silver;
}
if (fProps.MediaDateTime != DateTime.MinValue)
{
if (MaxValidDateTime < fProps.MediaDateTime)
MaxValidDateTime = fProps.MediaDateTime;
}
else if (fProps.CreateDateTime < MinModifyDateTime)
{
MinModifyDateTime = fProps.CreateDateTime;
}
progressBar.Value++;
}
//progressBar.Hide();
label_progressBar.Text = "خواندن GPS";
progressBar.Value = 0;
/****************** Run a seperathed thread for extracting GPS data ****************/
System.Threading.Tasks.Task.Run(() =>
{
for (int i = 0; i < dataGridView_Main.Rows.Count; i++)
{
float Lat, Lon, Alt;
string GPS_Text = getGPSData(files[i], out Lat, out Lon, out Alt);
dataGridView_Main.Rows[i].Cells["GPS"].Value = GPS_Text;
dataGridView_Main.Rows[i].Cells["Latitude"].Value = Lat;
dataGridView_Main.Rows[i].Cells["Longitude"].Value = Lon;
dataGridView_Main.Rows[i].Cells["Altitude"].Value = Alt;
if (progressBar.InvokeRequired)
{
progressBar.Invoke(new Action(() => progressBar.Value++));
}
else
progressBar.Value++;
}
SetDBGridSortable(true);
if (dataGridView_Main.InvokeRequired)
dataGridView_Main.Invoke(new Action(() => { dataGridView_Main.Sort(dataGridView_Main.Columns[8], ListSortDirection.Ascending); }));
else
dataGridView_Main.Sort(dataGridView_Main.Columns[8], ListSortDirection.Ascending);
if (panel_progressBar.InvokeRequired)
panel_progressBar.Invoke(new Action(() => { panel_progressBar.Hide(); }));
else
panel_progressBar.Hide();
if (progressBar.InvokeRequired)
progressBar.Invoke(new Action(() => { progressBar.Value = 0; }));
else
progressBar.Value = 0;
if (button_SetData.InvokeRequired)
button_SetData.Invoke(new Action(() => { button_SetData.Enabled = true; }));
else
button_SetData.Enabled = true;
});
/*************************************************************************************/
DateTime DefaultDateTime = DateTime.MinValue;
string PersianDefaultDateTime = "";
if (MaxValidDateTime != DateTime.MinValue)
{
DefaultDateTime = RoundUp(MaxValidDateTime, TimeSpan.FromMinutes(15));
PersianDefaultDateTime = PersianDateTime(RoundUp(MaxValidDateTime, TimeSpan.FromMinutes(15)));
}
else
{
DefaultDateTime = RoundUp(MinModifyDateTime, TimeSpan.FromMinutes(15));
PersianDefaultDateTime = PersianDateTime(RoundUp(MinModifyDateTime, TimeSpan.FromMinutes(15)));
}
if (PersianDefaultDateTime != "")
{
num_Year.Value = int.Parse(PersianDefaultDateTime.Substring(0, 10).Split(PersianDateSeparator)[0]);
num_Month.Value = int.Parse(PersianDefaultDateTime.Substring(0, 10).Split(PersianDateSeparator)[1]);
num_Day.Value = int.Parse(PersianDefaultDateTime.Substring(0, 10).Split(PersianDateSeparator)[2]);
num_Hour.Value = DefaultDateTime.Hour;
num_Minute.Value = DefaultDateTime.Minute;
num_Second.Value = DefaultDateTime.Second;
}
for (int i = 0; i < dataGridView_Main.Rows.Count; i++)
{
if (dataGridView_Main.Rows[i].Cells["PersianFinalDateTime"].Value.ToString() == "")
{
dataGridView_Main.Rows[i].Cells["FinalDate"].Value = DefaultDateTime;
dataGridView_Main.Rows[i].Cells["PersianFinalDateTime"].Value = PersianDefaultDateTime;
if ((bool)(dataGridView_Main.Rows[i].Cells["Active"]).Value == true)
{
dataGridView_Main.Rows[i].Cells["FinalName"].Value =
MakeFileName(PersianDefaultDateTime
, dataGridView_Main.Rows[i].Cells["AddedText"].Value.ToString()
, dataGridView_Main.Rows[i].Cells["fName"].Value.ToString());
}
dataGridView_Main.Rows[i].DefaultCellStyle.BackColor = Color.FromArgb(255, 255, 192);
if (dataGridView_Main.Rows[i].Cells["MediaDate"].Value.ToString() != ""
&&
dataGridView_Main.Rows[i].Cells["MediaDate"].Value.ToString() !=
dataGridView_Main.Rows[i].Cells["PersianFinalDateTime"].Value.ToString())
{
dataGridView_Main.Rows[i].Cells["PersianFinalDateTime"].Style.ForeColor = Color.Red;
}
}
}
if (dataGridView_Main.Rows.Count > 0)
{
dataGridView_Main_RowEnter(this, new DataGridViewCellEventArgs(0, 0));
//dataGridView_Main.Rows[0].Selected = true;
dataGridView_Main.CurrentCell = dataGridView_Main.Rows[0].Cells[0];
}
wfm.Hide();
}
}
}
private void MainForm_Load(object sender, EventArgs e)
{
string Now = PersianDateTime(DateTime.Now).Substring(0, 10);
num_Year.Value = int.Parse(Now.Split(PersianDateSeparator)[0]);
num_Month.Value = int.Parse(Now.Split(PersianDateSeparator)[1]);
num_Day.Value = int.Parse(Now.Split(PersianDateSeparator)[2]);
gMap.MapProvider = GMapProviders.GoogleMap;
dataGridView_Main.Sort(dataGridView_Main.Columns["PersianFinalDateTime"], ListSortDirection.Ascending);
if (System.IO.File.Exists("Locations.csv"))
{
string[] lines = System.IO.File.ReadAllLines("Locations.csv");
var loc = (from line in lines select (line.Split(',')).ToArray()).ToArray();
try
{
foreach (string[] item in loc)
{
contextMenu.Items.Add(string.Join(",", item));
}
}
catch (Exception)
{
MessageBox.Show("خطا در خواندن فایل لوکیشن!", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
return;
using (var reader = new StreamReader(@"Locations.csv"))
{
List<string> listA = new List<string>();
List<string> listB = new List<string>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(';');
listA.Add(values[0]);
listB.Add(values[1]);
}
}
}
private void dataGridView_Main_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView_Main.IsCurrentCellDirty)
{
DataGridViewCellCollection Cells = dataGridView_Main.Rows[e.RowIndex].Cells;
if (e.ColumnIndex == 14) //Altitude
{
using (WaitingForm wfm = new())
{
wfm.Show(this);
wfm.Width = this.Size.Width - 15;
wfm.Height = this.Size.Height - 7;
wfm.Left = this.Left + 8;
wfm.Top = this.Top;
float alt = 0;
if (float.TryParse(Cells["Altitude"].Value.ToString(), out alt))
{
float lat = float.Parse(Cells["Latitude"].Value.ToString());
float lon = float.Parse(Cells["Longitude"].Value.ToString());
string? media = Cells["fPath"].Value.ToString();
wmp.Ctlcontrols.stop();
wmp.URL = null;
wmp.currentPlaylist.clear();
wmp.Refresh();
string error = "";
if (System.IO.File.Exists(media) && set_GPS_Data(media, lat, lon, alt, out error))
{
Cells["GPS"].Value = GPS_Text(lat, lon, alt);
Cells["GPS"].ToolTipText = "";
Cells["GPS"].Style.BackColor = dataGridView_Main.Rows[e.RowIndex].DefaultCellStyle.BackColor;
Cells["GPS"].ToolTipText = "";
MessageBox.Show("با موفقیت ثبت شد", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
Cells["GPS"].ToolTipText = error;
Cells["GPS"].Style.BackColor = Color.OrangeRed;
MessageBox.Show("خطا در تنظیم اطلاعات موقعیت!", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("برای ارتفاع عدد صحیح وارد کن!", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
wfm.Hide();
}
}
else
{
if ((bool)Cells["Active"].Value)
{
Regex dateTimeRegex = new Regex(@"\b(?<year>\d{4,4})-(?<month>\d{2,2})-(?<day>\d{2,2}) (?<hour>\d{2,2}):(?<min>\d{2,2}):(?<sec>\d{2,2})\b");
string pDate = Cells["PersianFinalDateTime"].Value.ToString();
if (dateTimeRegex.IsMatch(pDate))
{
Match pDateMach = dateTimeRegex.Match(pDate);
PersianCalendar pc = new PersianCalendar();
DateTime gDate = pc.ToDateTime(int.Parse(pDateMach.Groups["year"].ToString()),
int.Parse(pDateMach.Groups["month"].ToString()),
int.Parse(pDateMach.Groups["day"].ToString()),