-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
FrmMainApp.cs
3460 lines (3039 loc) · 138 KB
/
FrmMainApp.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 System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows.Forms;
using AutoUpdaterDotNET;
using geoTagNinja;
using GeoTagNinja.Helpers;
using GeoTagNinja.Model;
using GeoTagNinja.Properties;
using GeoTagNinja.View.DialogAndMessageBoxes;
using GeoTagNinja.View.EditFileForm;
using GeoTagNinja.View.ListView;
using Microsoft.Web.WebView2.Core;
using Microsoft.WindowsAPICodePack.Taskbar;
using NLog;
using NLog.Config;
using NLog.Targets;
using TimeZoneConverter;
using static GeoTagNinja.Helpers.HelperControlAndMessageBoxHandling;
using static GeoTagNinja.Model.SourcesAndAttributes;
#pragma warning disable CS8632 // The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
namespace GeoTagNinja;
public partial class FrmMainApp : Form
{
#region Constants / Fields / Variables
#region Constants
internal const string DoubleQuote = "\"";
internal const string ParentFolder = "..";
internal const string NullStringEquivalentGeneric = "-";
internal const string NullStringEquivalentBlank = ""; // fml.
internal const string NullStringEquivalentZero = "0"; // fml.
internal const int NullIntEquivalent = 0;
internal const double NullDoubleEquivalent = 0.0;
internal static readonly DateTime NullDateTimeEquivalent =
new(year: 1, month: 1, day: 1, hour: 0, minute: 0, second: 0);
#endregion
#region Fields
/// <summary>
/// The EXIFTool used in this application.
/// Note that it must be disposed of (done by Form_Closing)!
/// </summary>
private readonly ExifTool _ExifTool = new();
/// <summary>
/// The server that receives messages from clients via our named pipe.
/// </summary>
private readonly SingleInstance_PipeServer NamedPipeServer;
/// <summary>
/// These two make the elements of the main listview accessible to other classes.
/// </summary>
public ListView.ListViewItemCollection ListViewItems => lvw_FileList.Items;
public ListView.ColumnHeaderCollection ListViewColumnHeaders => lvw_FileList.Columns;
/// <summary>
/// Returns the currently set application language for localization.
/// </summary>
private static string AppLanguage => _AppLanguage;
/// <summary>
/// Returns the list of elements in the currently opened directory.
/// </summary>
public static DirectoryElementCollection DirectoryElements { get; } = new();
#endregion
#region Variables
internal static DataTable DtLanguageLabels;
internal static DataTable DtFavourites;
// CustomCityLogic
internal static string FolderName;
internal static string _AppLanguage = "English"; // default to english
internal static List<string> LstFavourites = new();
private static bool _showLocToMapDialogChoice = true;
private static bool _rememberLocToMapDialogChoice;
// ReSharper disable once InconsistentNaming
private FrmSettings FrmSettings;
// ReSharper disable once InconsistentNaming
internal FrmEditFileData FrmEditFileData;
// ReSharper disable once InconsistentNaming
private FrmImportExportGpx FrmImportExportGpx;
private string _mapHtmlTemplateCode = "";
internal static bool RemoveGeoDataIsRunning;
private static bool _StopProcessingRows;
// this is for copy-paste
// the elements are: EA, Value, Changed?
internal static Dictionary<ElementAttribute, Tuple<string, bool>> CopyPoolDict = new();
// this is for checking if files need to be re-parsed.
internal static DataTable DtToponomySessionData;
internal static List<string> filesToEditGUIDStringList = new();
internal static readonly TaskbarManager TaskbarManagerInstance =
TaskbarManager.Instance;
#endregion
#endregion
#region Form/App Related
internal static readonly Logger Logger = LogManager.GetCurrentClassLogger();
/// <summary>
/// This is the main Form for the app. This particular section handles the initialisation of the form and loading
/// various defaults.
/// </summary>
public FrmMainApp()
{
_ = InitialiseApplication();
#region Define Logging Config
// Set up logging
LoggingConfiguration config = new();
string logFileLocation =
Path.Combine(path1: HelperVariables.UserDataFolderPath, path2: "logfile.txt");
if (File.Exists(path: logFileLocation))
{
File.Delete(path: logFileLocation);
}
FileTarget logfile = new(name: "logfile") { FileName = logFileLocation };
#if (DEBUG)
config.AddRule(minLevel: LogLevel.Trace, maxLevel: LogLevel.Fatal,
target: logfile);
#else
config.AddRule(minLevel: LogLevel.Info, maxLevel: LogLevel.Fatal, target: logfile);
#endif
logfile.Layout =
@"${longdate}|${level:uppercase=true}|${callsite:includeNamespace=false:includeSourcePath=false:methodName=true}|${message:withexception=true}";
ConsoleTarget logconsole = new(name: "logconsole");
config.AddRule(minLevel: LogLevel.Info, maxLevel: LogLevel.Fatal,
target: logconsole);
// Apply config
LogManager.Configuration = config;
#endregion
int procID = Process.GetCurrentProcess()
.Id;
Logger.Info(message: "Constructor: Starting GTN with process ID " + procID);
Logger.Info(message: "Collection mode: " + Program.collectionModeEnabled);
if (Program.collectionModeEnabled)
{
Logger.Info(message: "Collection source: " + Program.collectionFileLocation);
}
if (Program.singleInstance_Highlander)
{
NamedPipeServer =
new SingleInstance_PipeServer(messageCallback: PipeCmd_ShowMessage);
}
DirectoryElements.ExifTool = _ExifTool;
Logger.Info(message: "Constructor: Done");
}
/// <summary>
/// Async method to force all startup elements into one group, which are then awaited.
/// The idea is that user shouldn't see stuff like "tmi_help" changing its shape into Help while waiting for the app to
/// boot up.
/// </summary>
/// <returns></returns>
private async Task<Task> InitialiseApplication()
{
Visible = false;
SuspendLayout();
Task[] tasks =
[
HelperDataOtherDataRelated.GenericCreateDataTables(),
HelperGenericAppStartup.AppStartupCreateDatabaseFile(),
HelperGenericAppStartup.AppStartupWriteDefaultSettings(),
HelperGenericAppStartup.AppStartupReadSQLiteTables(),
HelperGenericAppStartup.AppStartupReadAppLanguage(),
HelperGenericAppStartup.AppStartupReadCustomCityLogic(),
HelperGenericAppStartup.AppStartupReadAPILanguage(),
HelperGenericAppStartup.AppStartupApplyDefaults(),
HelperDataLanguageTZ.DataReadLanguageDataFromCSV(),
HelperDataLanguageTZ.DataReadCountryCodeDataFromCSV(),
HelperGenericAppStartup.AppStartupCheckWebView2(),
AppStartupInitializeComponentFrmMainApp(),
AppStartupSetAppTheme(),
AppStartupEnableDoubleBuffering()
];
FormClosing += FrmMainApp_FormClosing;
//AppStartupApplyVisualStyleDefaults();
ResumeLayout();
Visible = true;
await Task.WhenAll(tasks: tasks);
return Task.CompletedTask;
}
/// <summary>
/// Handles the initial loading - adds various elements and ensures the app functions.
/// </summary>
/// <param name="sender">Unused</param>
/// <param name="e">Unused</param>
private async void FrmMainApp_Load(object sender,
EventArgs e)
{
Logger.Info(message: "OnLoad: Starting");
// icon
Logger.Trace(message: "Setting Icon");
Icon = Resources.AppIcon;
// clear both tables, just in case + generic cleanup
try
{
Logger.Debug(message: "Remove Stage 1 AttributeValues");
foreach (DirectoryElement dirElemFileToModify in DirectoryElements)
{
{
foreach (ElementAttribute attribute in (ElementAttribute[])
Enum.GetValues(enumType: typeof(ElementAttribute)))
{
dirElemFileToModify.RemoveAttributeValue(
attribute: attribute,
version: DirectoryElement.AttributeVersion
.Stage1EditFormIntraTabTransferQueue);
}
}
}
Logger.Debug(message: "Clear DtFileDataToWriteStage3ReadyToWrite");
foreach (DirectoryElement dirElemFileToModify in DirectoryElements)
{
{
foreach (ElementAttribute attribute in (ElementAttribute[])
Enum.GetValues(enumType: typeof(ElementAttribute)))
{
dirElemFileToModify.RemoveAttributeValue(
attribute: attribute,
version: DirectoryElement.AttributeVersion
.Stage3ReadyToWrite);
}
}
}
}
catch (Exception ex)
{
Logger.Fatal(message: "Error: " + ex.Message);
CustomMessageBox customMessageBox = new(
text: GenericGetMessageBoxText(
messageBoxName: "mbx_FrmMainApp_ErrorClearingFileDataQTables") +
ex.Message,
caption: GenericGetMessageBoxCaption(
captionType: MessageBoxCaption.Error.ToString()),
buttons: MessageBoxButtons.OK,
icon: MessageBoxIcon.Error);
customMessageBox.ShowDialog();
}
try
{
HelperFileSystemOperators.FsoCleanUpUserFolder();
}
catch (Exception ex)
{
// not really fatal
Logger.Error(message: "Error: " + ex.Message);
}
// Setup the List View
try
{
lvw_FileList.ReadAndApplySetting(appLanguage: AppLanguage);
}
catch (Exception ex)
{
Logger.Error(message: "Error: " + ex.Message);
CustomMessageBox customMessageBox = new(
text: GenericGetMessageBoxText(
messageBoxName: "mbx_FrmMainApp_ErrorResizingColumns") +
ex.Message,
caption: GenericGetMessageBoxCaption(
captionType: MessageBoxCaption.Error.ToString()),
buttons: MessageBoxButtons.OK,
icon: MessageBoxIcon.Error)
;
customMessageBox.ShowDialog();
}
// can't log inside.
Logger.Debug(message: "Run CoreWebView2InitializationCompleted");
wbv_MapArea.CoreWebView2InitializationCompleted +=
webView_CoreWebView2InitializationCompleted;
if (!Program.collectionModeEnabled)
{
HelperGenericAppStartup.AppSetupInitialiseStartupFolder(
toolStripTextBox: tbx_FolderName);
}
// initialise webView2
await InitialiseWebView();
// assign labels to objects
AppStartupAssignLabelsToObjects();
// load lvwFileList
lvw_FileList_LoadOrUpdate();
splitContainerMain.Paint += splitContainerControl_Paint;
splitContainerMain.Invalidate();
Logger.Trace(message: "Assign 'Enter' Key behaviour to tbx_lng");
nud_lng.KeyPress += (sndr,
ev) =>
{
if (ev.KeyChar.Equals(obj: (char)13))
{
btn_NavigateMapGo.PerformClick();
ev.Handled = true; // suppress default handling
}
};
HelperGenericAppStartup.AppStartupLoadFavourites();
HelperGenericAppStartup.AppStartupLoadCustomRules();
AppStartupGetLastLatLngFromSettings();
HelperGenericAppStartup.AppStartupGetOverwriteBlankToponomy();
HelperGenericAppStartup.AppStartupGetToponomyRadiusAndMaxRows();
Request_Map_NavigateGo();
await HelperAPIVersionCheckers.CheckForNewVersions();
LaunchAutoUpdater();
Logger.Info(message: "OnLoad: Done.");
}
/// <summary>
/// This fires up the autoupdater
/// </summary>
private static void LaunchAutoUpdater()
{
HelperNonStatic updateHelper = new();
#if DEBUG
//AutoUpdater.InstalledVersion = new Version(version: "1.2"); // here for testing only.
#endif
AutoUpdater.Synchronous =
true; // needs to be true otherwise the single pipe instance crashes. (well, I think _that_ crashes, something does.)
AutoUpdater.ParseUpdateInfoEvent += updateHelper.AutoUpdaterOnParseUpdateInfoEvent;
AutoUpdater.CheckForUpdateEvent += updateHelper.AutoUpdaterOnCheckForUpdateEvent;
string updateJsonPath =
Path.Combine(path1: HelperVariables.UserDataFolderPath,
path2: "updateJsonData.json");
AutoUpdater.Start(appCast: Path.Combine(updateJsonPath));
}
/// <summary>
/// When the app closes we want to make sure there's nothing in the write-queue.
/// ...once that's dealt with we write the details of the app layout (e.g. column widths) to sqlite.
/// </summary>
/// <param name="sender">Unused</param>
/// <param name="e">Unused</param>
private async void FrmMainApp_FormClosing(object sender,
FormClosingEventArgs e)
{
Logger.Debug(message: "OnClose: Starting");
NamedPipeServer.stopServing();
// this will trigger a write-to-file question/process
await HelperFileSystemOperators.FsoCheckOutstandingFileDataOkayToChangeFolderAsync(isTheAppClosing: true);
PerformAppClosingProcedure();
}
internal void PerformAppClosingProcedure(bool extractNewExifTool = true)
{
// Write column widths to db
Logger.Trace(message: "Write column widths to db");
lvw_FileList.PersistSettings();
AppClosingPersistData();
// Clean up
Logger.Trace(message: "Set pbx_imagePreview.Image = null");
pbx_imagePreview.Image = null; // unlocks files. theoretically.
HelperDataApplicationSettings.DataDeleteSQLitesettingsCleanup();
HelperDataApplicationSettings.DataVacuumDatabase();
// Shut down ExifTool
Logger.Debug(message: "OnClose: Dispose ExifTool");
_ExifTool.Dispose();
// Unzip new exiftool version if there is one
if (File.Exists(path: HelperVariables.ExifToolExePathRoamingTemp) && extractNewExifTool)
{
try
{
// okay this is a bit silly now but given that the ET distrib is no longer a single-file there's a lot of fuckery to be dealt with
// the zip file has a structure such as c:\Users\nemet\AppData\Roaming\GeoTagNinja\exiftool-12.89_64.zip\exiftool-12.89_64\exiftool(-k).exe
// i swear to all the f...king gods this has been the most useless move i've seen with ET development in the last decade.
// so we do the following
// 1: delete exiftool
File.Delete(path: HelperVariables.ExifToolExePathRoamingPerm);
// 2: delete the exiftool_files folder and anything in it.
string exifToolFilesDir =
Path.Combine(path1: HelperVariables.UserDataFolderPath, path2: "exiftool_files");
if (Directory.Exists(path: exifToolFilesDir))
{
Directory.Delete(path: exifToolFilesDir, recursive: true);
}
// 2b: this shouldn't really happen but anyway:
string tempExtractDir = Path.Combine(path1: HelperVariables.UserDataFolderPath,
path2: Path.GetFileNameWithoutExtension(path: HelperVariables.ExifToolExePathRoamingTemp));
if (Directory.Exists(path: tempExtractDir))
{
Directory.Delete(path: tempExtractDir, recursive: true);
}
// 3: unzip
ZipFile.ExtractToDirectory(
sourceArchiveFileName: HelperVariables.ExifToolExePathRoamingTemp,
destinationDirectoryName: HelperVariables.UserDataFolderPath);
// 4: move to parent
Directory.Move(
sourceDirName: Path.Combine(path1: tempExtractDir, path2: "exiftool_files"),
destDirName: Path.Combine(path1: HelperVariables.UserDataFolderPath, path2: "exiftool_files"));
File.Move(sourceFileName: Path.Combine(path1: tempExtractDir, path2: "exiftool(-k).exe"),
destFileName: HelperVariables.ExifToolExePathRoamingPerm);
}
catch
{
// nothing. basically if there's no exiftool.exe in this folder the app will temporarily revert to the prepackaged one.
}
}
// Clean up Roaming folder
HelperFileSystemOperators.FsoCleanUpUserFolder();
Logger.Debug(message: "OnClose: Done.");
}
private void AppClosingPersistData()
{
// Write lat/long + visual settings for future reference to db
Logger.Debug(message: "Write lat/long + visual settings for future reference to db");
List<AppSettingContainer> settingsToWrite = new();
List<KeyValuePair<string, string>> persistDataSettingsList = new()
{
new KeyValuePair<string, string>(key: "lastLat", value: nud_lat.Text),
new KeyValuePair<string, string>(key: "lastLng", value: nud_lng.Text),
new KeyValuePair<string, string>(key: "splitContainerMainSplitterDistance",
value: splitContainerMain.SplitterDistance.ToString(provider: CultureInfo.InvariantCulture)),
new KeyValuePair<string, string>(key: "splitContainerLeftTopSplitterDistance",
value: splitContainerLeftTop.SplitterDistance.ToString(provider: CultureInfo.InvariantCulture))
};
settingsToWrite.AddRange(collection: persistDataSettingsList.Select(selector: persistDataSetting =>
new AppSettingContainer
{
TableName = "settings", SettingTabPage = "generic", SettingId = persistDataSetting.Key,
SettingValue = persistDataSetting.Value
}));
HelperDataApplicationSettings.DataWriteSQLiteSettings(settingsToWrite: settingsToWrite);
// Log stuff
foreach (KeyValuePair<string, string> keyValuePair in persistDataSettingsList)
{
Logger.Debug(
message:
$"Writing setting.settingId {keyValuePair.Key}, setting.settingValue {keyValuePair.Value}.");
}
}
private void PipeCmd_ShowMessage(string text)
{
CustomMessageBox customMessageBox = new(
text: $"Pipe Server has this message:\n{text}",
caption: "Pipe Server",
buttons: MessageBoxButtons.OK,
icon: MessageBoxIcon.Information);
customMessageBox.ShowDialog();
}
#endregion
#region Map Stuff
/// <summary>
/// Provides an interaction layer between the map and the app. The reason why we're using string instead of proper
/// numbers
/// ... is that the API only deals with English-formatted numbers whereas we can't force that necessarily on the user
/// if they have
/// ... other Culture setting.
/// ... Also if the user zooms out too much they can click on a map-area (coordinate) that's not "real" so we are
/// dealing with that in this code.
/// </summary>
/// <param name="sender">Unused</param>
/// <param name="e">Unused</param>
private void wbv_MapArea_WebMessageReceived(object sender,
CoreWebView2WebMessageReceivedEventArgs e)
{
string jsonString = e.WebMessageAsJson;
MapWebMessage mapWebMessage =
JsonSerializer.Deserialize<MapWebMessage>(json: jsonString);
string strLat =
mapWebMessage?.lat.ToString(provider: CultureInfo.InvariantCulture);
string strLng =
mapWebMessage?.lng.ToString(provider: CultureInfo.InvariantCulture);
bool isDragged = mapWebMessage is
{
isDragged: true
};
double.TryParse(s: strLat, style: NumberStyles.Any,
provider: CultureInfo.InvariantCulture,
result: out
double dblLat); // trust me i hate this f...king culture thing as much as possible...
double.TryParse(s: strLng, style: NumberStyles.Any,
provider: CultureInfo.InvariantCulture,
result: out
double dblLng); // trust me i hate this f...king culture thing as much as possible...
// if the user zooms out too much they can encounter an "unreal" coordinate.
double correctedDblLat =
HelperExifDataPointInteractions.GenericCorrectInvalidCoordinate(
coordHalfPair: dblLat);
double correctedDblLng =
HelperExifDataPointInteractions.GenericCorrectInvalidCoordinate(
coordHalfPair: dblLng);
nud_lat.Text = correctedDblLat.ToString(provider: CultureInfo.InvariantCulture);
nud_lng.Text = correctedDblLng.ToString(provider: CultureInfo.InvariantCulture);
nud_lat.Value = Convert.ToDecimal(value: correctedDblLat,
provider: CultureInfo.InvariantCulture);
nud_lng.Value = Convert.ToDecimal(value: correctedDblLng,
provider: CultureInfo.InvariantCulture);
if (isDragged && askIfUserWantsToSaveDraggedMapData())
{
btn_loctToFile.PerformClick();
}
}
/// <summary>
/// Needed for the proper functioning of webview2
/// </summary>
/// <param name="sender">Unused</param>
/// <param name="e">Unused</param>
private void webView_CoreWebView2InitializationCompleted(object sender,
CoreWebView2InitializationCompletedEventArgs e)
{
}
/// <summary>
/// Checks if the user wants to have a "dragged datapoint" actioned to be sent onto selected files.
/// </summary>
/// <returns></returns>
private bool askIfUserWantsToSaveDraggedMapData()
{
CustomMessageBox customMessageBox = new(
text: GenericGetMessageBoxText(
messageBoxName: "mbx_FrmMainApp_QuestionAddDraggedDataPointToFiles"),
caption: GenericGetMessageBoxCaption(
captionType: MessageBoxCaption.Question.ToString()),
buttons: MessageBoxButtons.YesNo,
icon: MessageBoxIcon.Question);
DialogResult dialogResult = customMessageBox.ShowDialog();
return dialogResult == DialogResult.Yes;
}
/// <summary>
/// Handles the clicking on Go button
/// </summary>
/// <param name="sender">Unused</param>
/// <param name="e">Unused</param>
private void btn_NavigateMapGo_Click(object sender,
EventArgs e)
{
HelperVariables.LstTrackPath.Clear();
HelperVariables.HsMapMarkers.Clear();
HelperVariables.HsMapMarkers.Add(item: ParseLatLngTextBox());
Request_Map_NavigateGo();
}
/// <summary>
/// Handles the clicking on "ToFile" button. See comments above re: why we're using strings (culture-related issue)
/// This now also handles "btn_loctToFileDestination" click as well.
/// </summary>
/// <param name="sender">Name of the button that has been clicked</param>
/// <param name="e">Unused</param>
private async void btn_loctToFile_Click(object sender,
EventArgs e)
{
// convert selected lat/long to str
string strGPSLatitudeOnTheMap = nud_lat.Text.Replace(oldChar: ',', newChar: '.');
string strGPSLongitudeOnTheMap = nud_lng.Text.Replace(oldChar: ',', newChar: '.');
_StopProcessingRows = false;
GeoResponseToponomy readJsonToponomy = new();
Button btn = (Button)sender;
string senderName = btn.Name;
// lat/long gets written regardless of update-toponomy-choice
if (double.TryParse(s: strGPSLatitudeOnTheMap,
style: NumberStyles.Any,
provider: CultureInfo.InvariantCulture,
result: out double _) &&
double.TryParse(s: strGPSLongitudeOnTheMap,
style: NumberStyles.Any,
provider: CultureInfo.InvariantCulture,
result: out double _))
{
if (lvw_FileList.SelectedItems.Count > 0)
{
HelperGenericFileLocking.FileListBeingUpdated = true;
foreach (ListViewItem lvi in lvw_FileList.SelectedItems)
{
DirectoryElement dirElemFileToModify =
lvi.Tag as DirectoryElement;
// don't do folders...
if (dirElemFileToModify.Type == DirectoryElement.ElementType.File)
{
string fileNameWithoutPath =
dirElemFileToModify.ItemNameWithoutPath;
// check it's not in the read-queue.
while (HelperGenericFileLocking.GenericLockCheckLockFile(
fileNameWithoutPath: fileNameWithoutPath))
{
await Task.Delay(millisecondsDelay: 10);
}
if (senderName == "btn_loctToFile")
{
string tmpCoords =
strGPSLatitudeOnTheMap + ";" + strGPSLongitudeOnTheMap !=
";"
? strGPSLatitudeOnTheMap +
";" +
strGPSLongitudeOnTheMap
: "";
List<(ElementAttribute attribute, string value)> attributes =
new()
{
(ElementAttribute.GPSLatitude,
strGPSLatitudeOnTheMap),
(ElementAttribute.GPSLongitude,
strGPSLongitudeOnTheMap),
(ElementAttribute.Coordinates, tmpCoords)
};
foreach ((ElementAttribute attribute, string value) in
attributes)
{
dirElemFileToModify.SetAttributeValueAnyType(
attribute: attribute,
value: value,
version: DirectoryElement.AttributeVersion
.Stage3ReadyToWrite,
isMarkedForDeletion: false);
}
if (!_rememberLocToMapDialogChoice)
{
ShowLocToMapDialog();
}
DataTable dtToponomy = new();
DataTable dtAltitude = new();
if (_showLocToMapDialogChoice)
{
lvw_FileList_UpdateTagsFromWeb(
strGpsLatitude: strGPSLatitudeOnTheMap,
strGpsLongitude: strGPSLongitudeOnTheMap, lvi: lvi);
}
}
else if (senderName == "btn_loctToFileDestination")
{
string tmpCoords =
strGPSLatitudeOnTheMap + ";" + strGPSLongitudeOnTheMap !=
";"
? strGPSLatitudeOnTheMap +
";" +
strGPSLongitudeOnTheMap
: "";
List<(ElementAttribute attribute, string value)>
attributesAndValues = new()
{
(ElementAttribute.GPSDestLatitude,
strGPSLatitudeOnTheMap),
(ElementAttribute.GPSDestLongitude,
strGPSLongitudeOnTheMap),
(ElementAttribute.DestCoordinates, tmpCoords)
};
foreach ((ElementAttribute attribute, string value) in
attributesAndValues)
{
dirElemFileToModify.SetAttributeValueAnyType(
attribute: attribute,
value: value,
version: DirectoryElement.AttributeVersion
.Stage3ReadyToWrite,
isMarkedForDeletion: false);
}
}
await FileListViewReadWrite
.ListViewUpdateRowFromDEStage3ReadyToWrite(lvi: lvi);
}
}
HelperGenericFileLocking.FileListBeingUpdated = false;
}
}
// Not logging this.
FileListViewReadWrite.ListViewCountItemsWithGeoData();
void ShowLocToMapDialog()
{
Dictionary<string, string> checkboxDictionary = new()
{
{
HelperDataLanguageTZ.DataReadDTObjectText(
objectType: ControlType.CheckBox,
objectName: "ckb_QuestionAddToponomyDontAskAgain"
),
"_remember"
}
};
Dictionary<string, string> buttonsDictionary = new()
{
{
HelperDataLanguageTZ.DataReadDTObjectText(
objectType: ControlType.Button,
objectName: "btn_Yes"
),
"yes"
},
{
HelperDataLanguageTZ.DataReadDTObjectText(
objectType: ControlType.Button,
objectName: "btn_No"
),
"no"
}
};
// via https://stackoverflow.com/a/17385937/3968494
List<string> getLocToMapDialogChoice =
DialogWithOrWithoutCheckBox.DisplayAndReturnList(
labelText: HelperDataLanguageTZ.DataReadDTObjectText(
objectType: ControlType.Label,
objectName: "lbl_QuestionAddToponomy"
),
caption: GenericGetMessageBoxCaption(
captionType: MessageBoxCaption.Question.ToString()),
buttonsDictionary: buttonsDictionary,
orientation: "Horizontal", checkboxesDictionary: checkboxDictionary);
_showLocToMapDialogChoice = getLocToMapDialogChoice.Contains(item: "yes");
_rememberLocToMapDialogChoice =
getLocToMapDialogChoice.Contains(item: "_remember");
}
}
/// <summary>
/// Parses the tbx_lat and tbx_lng text boxes.
/// If the contents is a valid double, returns touple (lat, lng)
/// with values as string and dec separator ".".
/// Otherwise default "0" is returned for both.
/// </summary>
private (string, string) ParseLatLngTextBox()
{
Logger.Trace(message: "Starting parseLatLngTextBox ...");
// Default values if text field is empty
string LatCoordinate = "0";
string LngCoordinate = "0";
// Get txtbox contents
string strLatCoordinate = "";
string strLngCoordinate = "";
if (!string.IsNullOrEmpty(value: nud_lat.Text))
{
strLatCoordinate = nud_lat.Text.Replace(oldChar: ',', newChar: '.');
}
if (!string.IsNullOrEmpty(value: nud_lng.Text))
{
strLngCoordinate = nud_lng.Text.Replace(oldChar: ',', newChar: '.');
}
// Check if it's a valid double -> otherwise defaults above
try
{
Logger.Trace(message: "parseLatLngTextBox");
double parsedLat;
double parsedLng;
if (double.TryParse(s: strLatCoordinate, style: NumberStyles.Any,
provider: CultureInfo.InvariantCulture,
result: out parsedLat) &&
double.TryParse(s: strLngCoordinate, style: NumberStyles.Any,
provider: CultureInfo.InvariantCulture,
result: out parsedLng))
{
LatCoordinate = strLatCoordinate;
LngCoordinate = strLngCoordinate;
Logger.Trace(message: "parseLatLngTextBox OK - LatCoordinate: " +
strLatCoordinate +
" - LngCoordinate: " +
strLngCoordinate);
}
}
catch (Exception ex)
{
Logger.Fatal(message: "Error: " + ex.Message);
CustomMessageBox customMessageBox = new(
text: GenericGetMessageBoxText(
messageBoxName: "mbx_FrmMainApp_ErrorNavigateMapGoHTMLCode") +
ex.Message,
caption: GenericGetMessageBoxCaption(
captionType: MessageBoxCaption.Error.ToString()),
buttons: MessageBoxButtons.OK,
icon: MessageBoxIcon.Error);
customMessageBox.ShowDialog();
}
return (LatCoordinate, LngCoordinate);
}
private void UpdateWebView(IDictionary<string, string> replacements)
{
string htmlCode = _mapHtmlTemplateCode;
// If set, replace arcgis key
if (HelperVariables.UserSettingArcGisApiKey != null)
{
htmlCode = htmlCode.Replace(oldValue: "yourApiKey",
newValue: HelperVariables
.UserSettingArcGisApiKey);
}
Logger.Trace(message: "HelperStatic.UserSettingArcGisApiKey == null: " +
(HelperVariables.UserSettingArcGisApiKey == null));
foreach (KeyValuePair<string, string> replacement in replacements)
{
Logger.Trace(message: string.Format(format: "Replace: {0} -> {1}",
arg0: replacement.Key,
arg1: replacement.Value));
htmlCode =
htmlCode.Replace(oldValue: replacement.Key, newValue: replacement.Value);
}
// show the decoded location on the map
try
{
Logger.Trace(message: "Calling wbv_MapArea.NavigateToString");
wbv_MapArea.NavigateToString(htmlContent: htmlCode);
Logger.Trace(message: "Calling wbv_MapArea.NavigateToString - OK");
}
catch (Exception ex)
{
Logger.Fatal(message: "Error: " + ex.Message);
CustomMessageBox customMessageBox = new(
text: GenericGetMessageBoxText(
messageBoxName:
"mbx_FrmMainApp_ErrorInitializeWebViewNavigateToStringInHTMLFile") +
ex.Message,
caption: GenericGetMessageBoxCaption(
captionType: MessageBoxCaption.Error.ToString()),
buttons: MessageBoxButtons.OK,
icon: MessageBoxIcon.Error);
customMessageBox.ShowDialog();
}
}
/// <summary>
/// Handles the navigation to a coordinate on the map. Replaces hard-coded values w/ user-provided ones
/// ... and executes the navigation action.
/// </summary>
[SuppressMessage(category: "ReSharper", checkId: "InconsistentNaming")]
internal void Request_Map_NavigateGo()
{
Logger.Debug(message: "Starting");
// Set up replacements
IDictionary<string, string> htmlReplacements = new Dictionary<string, string>();
HelperVariables.HTMLAddMarker = "";
HelperVariables.HTMLCreatePoints = ""; // this is ok as-is, won't break the map if stays so.
double dblLat = 0;
double dblLng = 0;
double dblMinLat = 180;
double dblMinLng = 180;
double dblMaxLat = -180;
double dblMaxLng = -180;
// Add markers on map for every marker-item and
// find viewing rect. for map (min / max of all markers to enclose all of them)
if (HelperVariables.HsMapMarkers.Count > 0 ||
HelperVariables.LstTrackPath.Count > 0)
{
if (HelperVariables.HsMapMarkers.Count > 0)
{
foreach ((string strLat, string strLng) locationCoord in HelperVariables.HsMapMarkers)
{
AssignViewingRectangle(locationCoord: locationCoord, addMarker: true);
}
}
htmlReplacements.Add(key: "{ HTMLAddMarker }",
value: HelperVariables.HTMLAddMarker);
if (HelperVariables.LstTrackPath.Count > 0)
{
foreach ((string strLat, string strLng) locationCoord in HelperVariables.LstTrackPath)
{
{
AssignViewingRectangle(locationCoord: locationCoord, addMarker: false);
}
}
}
HelperVariables.LastLat = dblLat;
HelperVariables.LastLng = dblLng;
HelperVariables.MinLat = dblMinLat;
HelperVariables.MinLng = dblMinLng;
HelperVariables.MaxLat = dblMaxLat;
HelperVariables.MaxLng = dblMaxLng;
}
else
{
// No markers added
htmlReplacements.Add(key: "{ HTMLAddMarker }", value: "");
}
Logger.Trace(message: "Added " +
HelperVariables.HsMapMarkers.Count +
" map markers.");
string createPointsStr = "";
string showLinesStr = "";
string showPointsStr = "";
string showFOVStr = "";
string showDestinationPolyLineStr = "";
string multiCoordsDefaultStr = """
var #multiCoordsNum# = [
[#multiCoordsList#]
];
var plArray = [];