-
Notifications
You must be signed in to change notification settings - Fork 3
/
KMZRebuilederForm.cs
11505 lines (10450 loc) · 556 KB
/
KMZRebuilederForm.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.IO;
using System.Runtime.InteropServices;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Windows.Forms;
using System.Drawing.Imaging;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;
namespace KMZRebuilder
{
public partial class KMZRebuilederForm : Form
{
static KMZRebuilederForm()
{
try
{
if (IntPtr.Size == 4) File.Copy(KMZRebuilederForm.CurrentDirectory() + @"\SQLite.Interop.x86.dll", KMZRebuilederForm.CurrentDirectory() + @"\SQLite.Interop.dll", true);
else File.Copy(KMZRebuilederForm.CurrentDirectory() + @"\SQLite.Interop.x64.dll", KMZRebuilederForm.CurrentDirectory() + @"\SQLite.Interop.dll", true);
}
catch (Exception ex) { };
}
// P/Invoke constants
private const int WM_SYSCOMMAND = 0x112;
private const int MF_STRING = 0x0;
private const int MF_SEPARATOR = 0x800;
// KMZ Viewer Commands
private const int XP_OPENFILE = 0xA801;
private const int XP_OPENLAYER = 0xA802;
private const int XP_OPENLAYERS = 0xA803;
// P/Invoke declarations
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool AppendMenu(IntPtr hMenu, int uFlags, int uIDNewItem, string lpNewItem);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool InsertMenu(IntPtr hMenu, int uPosition, int uFlags, int uIDNewItem, string lpNewItem);
private int SYSMENU_ABOUT_ID = 0x1;
private int SYSMENU_WGSFormX = 0x2;
private int SYSMENU_DefSize = 0x3;
private int SYSMENU_MinSize = 0x4;
private int SYSMENU_NEW_INST = 0x5;
public string[] args;
public MruList MyMruList;
public static WaitingBoxForm waitBox;
public MapIcons mapIcons;
private MemFile.MemoryFile memFile = null;
public Preferences Properties = Preferences.Load();
public static PointInRegionUtils PIRU = new PointInRegionUtils();
public static string CurrentDirectory()
{
return AppDomain.CurrentDomain.BaseDirectory;
// return Application.StartupPath;
// return System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
// return System.IO.Directory.GetCurrentDirectory();
// return Environment.CurrentDirectory;
// return System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
// return System.IO.Path.GetDirectory(Application.ExecutablePath);
}
public static string TempDirectory()
{
string dir = CurrentDirectory();
if (!dir.EndsWith(@"\")) dir += @"\";
dir += @"TMP\";
return dir;
}
public KMZRebuilederForm(string[] args)
{
this.args = args;
InitializeComponent();
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
System.Diagnostics.FileVersionInfo fvi = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location);
Text += " " + fvi.FileVersion + " by " + fvi.CompanyName;
RegisterFileAsses();
prepareTranslit();
MapIcons.InitZip(CurrentDirectory() + @"\mapicons\default.zip");
}
private void AfterLoadPrefs()
{
convertToToolStripMenuItem.Visible = Properties.GetBoolValue("gpiwriter_hide_old_menus_items");
}
public static void ConvertGPI2KMZ(string gpiFile, string kmzFile)
{
if (String.IsNullOrEmpty(gpiFile)) return;
if (String.IsNullOrEmpty(kmzFile)) return;
if (!File.Exists(gpiFile)) return;
if (gpiFile == kmzFile) return;
string ffext = Path.GetExtension(gpiFile).ToLower();
if (ffext == ".gpi")
{
Console.WriteLine("KMZRebuilder by milokz@gmail.com");
Console.WriteLine("Convert GPI 2 KMZ Mode");
Console.WriteLine("IN : {0}", Path.GetFileName(gpiFile));
Console.WriteLine("OUT: {0}", Path.GetFileName(kmzFile));
try
{
Preferences Props = Preferences.Load();
GPIReader.LOCALE_LANGUAGE = Props["gpi_localization"].ToUpper();
GPIReader.SAVE_MEDIA = Props.GetBoolValue("gpireader_save_media");
GPIReader.SAVE_MULTINAMES = Props.GetBoolValue("gpireader_multinames_in_desc");
GPIReader.CREATE_CATEGORY_IMAGES_IFNO = Props.GetBoolValue("gpireader_create_cat_noimage");
GPIReader.POI_IMAGE_FROM_JPEG = Props.GetBoolValue("gpireader_poi_image_from_jpeg");
Console.WriteLine("Reading input file in {0}... ", GPIReader.LOCALE_LANGUAGE);
GPIReader gpi = new GPIReader(gpiFile, AddToConsole);
Console.WriteLine("GPI name is `{0}`", gpi.Name);
Console.WriteLine("DataSource is `{0}`", gpi.DataSource);
Console.WriteLine("Saving to kml... ");
KMFile kmf = KMFile.CreateEmpty();
gpi.SaveToKML(kmf.tmp_file_dir + "doc.kml", AddToConsole);
Console.Write(String.Format("Creating {0} ... ", Path.GetFileName(kmzFile)));
try
{
MakeZIP(kmzFile, kmf.tmp_file_dir);
Console.WriteLine("Ok");
Console.Write("Deleting temporary folders... ");
string tdir = Path.GetDirectoryName(kmf.tmp_file_dir);
if (!String.IsNullOrEmpty(tdir)) try { Directory.Delete(tdir, true); }
catch { };
Console.WriteLine("Ok");
}
catch (Exception ex) { Console.WriteLine("Error: {0}", ex.Message); };
}
catch (Exception ex) { Console.WriteLine("Error: {0}", ex.Message); };
};
Console.WriteLine("DONE");
Console.WriteLine("Exiting...");
}
public static void ConvertKMZ2GPI(string kmzFile, string gpiFile)
{
if (String.IsNullOrEmpty(kmzFile)) return;
if (String.IsNullOrEmpty(gpiFile)) return;
if (!File.Exists(kmzFile)) return;
if (kmzFile == gpiFile) return;
string ffext = Path.GetExtension(kmzFile).ToLower();
bool iskmz = ffext == ".kmz";
if ((ffext == ".kml") || (iskmz))
{
Console.WriteLine("KMZRebuilder by milokz@gmail.com");
Console.WriteLine("Convert KMZ/KML 2 GPI Mode");
Console.WriteLine("IN : {0}", Path.GetFileName(kmzFile));
Console.WriteLine("OUT: {0}", Path.GetFileName(gpiFile));
Console.Write("Reading input file... ");
try
{
KMFile kmf = new KMFile(kmzFile);
if (kmf.Valid)
{
Console.WriteLine("OK");
Console.WriteLine("Project name is `{0}`", kmf.kmldocName);
int ttlpc = 0;
for(int i=0;i<kmf.kmLayers.Count;i++) ttlpc += kmf.kmLayers[i].placemarks;
Console.WriteLine("Found {0} POIs in {1} layers", ttlpc, kmf.kmLayers.Count);
try { Save2GPIInt(gpiFile, kmf, kmf.kmldocName, AddToConsole, Preferences.Load()); }
catch (Exception ex) { Console.WriteLine("Error: {0}", ex.Message); };
};
if (iskmz)
{
Console.Write("Deleting temporary folders... ");
string sdir = Path.GetDirectoryName(kmzFile);
string tdir = Path.GetDirectoryName(kmf.tmp_file_dir);
if (sdir != tdir) try { Directory.Delete(tdir, true); } catch { };
Console.WriteLine("Ok");
};
}
catch (Exception ex) { Console.WriteLine("Error: {0}", ex.Message); };
};
Console.WriteLine("DONE");
Console.WriteLine("Exiting...");
}
private static void AddToConsole(string text)
{
Console.WriteLine(text);
}
private void RegisterFileAsses()
{
FileAss.SetFileAssociation("kmz", "KMZFile", "Open in KMZRebuilder", CurrentDirectory() + @"\KMZRebuilder.exe");
FileAss.SetFileAssociation("kml", "KMLFile", "Open in KMZRebuilder", CurrentDirectory() + @"\KMZRebuilder.exe");
FileAss.SetFileAssociation("kmf", "KMZFile", "Open in KMZRebuilder", CurrentDirectory() + @"\KMZRebuilder.exe");
FileAss.SetFileAssociation("wpt", "WPTFile", "Open in KMZRebuilder", CurrentDirectory() + @"\KMZRebuilder.exe");
FileAss.SetFileAssociation("gpx", "GPXFile", "Open in KMZRebuilder", CurrentDirectory() + @"\KMZRebuilder.exe");
FileAss.SetFileAssociation("gpi", "KMZFile", "Open in KMZRebuilder", CurrentDirectory() + @"\KMZRebuilder.exe");
FileAss.SetFileAssociation("rpp", "RPPFile", "Open in KMZRebuilder", CurrentDirectory() + @"\KMZRebuilder.exe");
FileAss.SetFileOpenWith("dat", CurrentDirectory() + @"\KMZRebuilder.exe");
FileAss.SetFileOpenWith("gdb", CurrentDirectory() + @"\KMZRebuilder.exe");
FileAss.SetFileOpenWith("txt", CurrentDirectory() + @"\KMZRebuilder.exe");
FileAss.SetFileOpenWith("csv", CurrentDirectory() + @"\KMZRebuilder.exe");
FileAss.SetFileOpenWith("osm", CurrentDirectory() + @"\KMZRebuilder.exe");
FileAss.SetFileOpenWith("db3", CurrentDirectory() + @"\KMZRebuilder.exe");
FileAss.SetFileOpenWith("poi", CurrentDirectory() + @"\KMZRebuilder.exe");
FileAss.SetFileOpenWith("map", CurrentDirectory() + @"\KMZRebuilder.exe");
FileAss.SetFileOpenWith("fit", CurrentDirectory() + @"\KMZRebuilder.exe");
FileAss.SetFileOpenWith("rpp", CurrentDirectory() + @"\KMZRebuilder.exe");
FileAss.SetFileOpenWith("dxml", CurrentDirectory() + @"\KMZRebuilder.exe");
FileAss.UpdateExplorer();
}
private void FormKMZ_Load(object sender, EventArgs e)
{
//foreach (PointF loc in GoogleGeometry.GooglePolylineConverter.DecodePE("wkwzHohvz@KYOWSUIEGEu@k@o@k@_@g@GIEKK[ESCQAMDWDWDW@]Bk@TeDBODQBGDIFKJGd@YJMJMFOBQ@Q?SCYa@aCAa@Aq@@}@D]Pu@Hc@B_@?a@A]g@gD]aC_@eCq@gFGg@GeAG}AG{BIqGEcB?aBFqAJqA^eC^mBZmAZaAX{@h@yA`AgBfAsBXs@\\mA`@cClAgKjCsUj@kEPkAJg@~@iD`@{Af@_CXoBPqBPoBD_@PcBj@uCb@oBDU\\cCTaB\\cDt@iGv@gFn@mDxAeHj@mC`@aBb@qA^y@t@mAvCmEt@qA~CmIlAaD~AeE^_Av@wA~@iAdAy@jAc@^OFCj@Wf@a@jCwCp@{@L_@F_@F{ADi@h@cDLa@JSNGNCb@@`B@d@ETKZ]FSNe@dAwDLa@~C{N`BoHfAoE|AoGjBuGjCwJtAaGnAkGlC}NJe@r@yD`@qBVqAn@mCVkAbAwDDQ`@sA|AiElBuEzAuCdCsDpBmCfG{GzF{FfBaBrAiAtAaAhBq@pCq@HAJC`Ac@j@_@x@s@v@}@fBeClCuDb@o@Rc@N]DOBO@M@O?O?[Aq@?Y"))
// MessageBox.Show(loc.ToString());
MyMruList = new MruList(CurrentDirectory() + @"\KMZRebuilder.mru", MRU, 10);
MyMruList.FileSelected += new MruList.FileSelectedEventHandler(MyMruList_FileSelected);
waitBox = new WaitingBoxForm(this);
this.AllowDrop = true;
this.DragDrop += bgFiles_DragDrop;
this.DragEnter += bgFiles_DragEnter;
if(Directory.Exists(TempDirectory())) System.IO.Directory.Delete(TempDirectory(),true);
System.IO.Directory.CreateDirectory(TempDirectory());
LoadFiles(null, null);
PreLoadPlugins(openPluginsToolStripMenuItem);
}
private void LoadFiles(object sender, EventArgs e)
{
if ((args != null) && (args.Length > 0))
{
List<string> files = new List<string>();
foreach (string arg in args)
if (File.Exists(arg))
files.Add(arg);
if (files.Count > 0)
LoadFiles(files.ToArray());
};
}
private void MyMruList_FileSelected(string file_name)
{
LoadFiles(new string[] { file_name });
}
private void bgFiles_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy;
}
private void bgFiles_DragDrop(object sender, DragEventArgs e)
{
LoadFiles((string[])e.Data.GetData(DataFormats.FileDrop));
}
private void AddFiles_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Main Supported Files|*.kml;*.kmz;*.gpx;*.dat;*.wpt;*.db3;*.osm;*.gdb;*.fit;*.zip;*.rpp;*.dxml;*.gpi;*.kmf|KML Format (*.kml)|*.kml|KMZ Format (*.kmz)|*.kmz|GPX Exchange Format (*.gpx)|*.gpx|ProGorod Favorites.dat (*.dat)|*.dat|OziExplorer Waypoint File (*.wpt)|*.wpt|SASPlanet SQLite (*.db3)|*.db3|OSM Export File (*.osm)|*.osm|Navitel Waypoints (*.gdb)|*.gdb|Garmin Ant Fit (*.fit)|*.fit|Garmin POI (*.gpi)|*.gpi|KMZRebuilder Files List (*.kmf)|*.kmf";
ofd.DefaultExt = ".kmz";
ofd.Multiselect = true;
if (ofd.ShowDialog() == DialogResult.OK) LoadFiles(ofd.FileNames);
ofd.Dispose();
}
private static string KmzUnpack(string fileName)
{
string res = null;
ZipFile zf = new ZipFile(fileName);
string tmp_file_dir = KMZRebuilederForm.TempDirectory() + "IF" + DateTime.UtcNow.Ticks.ToString() + @"\";
foreach (ZipEntry zipEntry in zf)
{
if (!zipEntry.IsFile) continue;
String entryFileName = zipEntry.Name;
byte[] buffer = new byte[4096]; // 4K is optimum
Stream zipStream = zf.GetInputStream(zipEntry);
String fullZipToPath = Path.Combine(tmp_file_dir, entryFileName);
string directoryName = Path.GetDirectoryName(fullZipToPath);
if (directoryName.Length > 0)
Directory.CreateDirectory(directoryName);
using (FileStream streamWriter = File.Create(fullZipToPath))
StreamUtils.Copy(zipStream, streamWriter, buffer);
if(Path.GetExtension(fullZipToPath).ToLower()==".kml")
res = fullZipToPath;
};
zf.Close();
return res;
}
private void LoadFiles(string[] files)
{
foreach (string file in files)
if (Path.GetExtension(file).ToLower() == ".zip")
{
List<string> f2l = new List<string>();
string tmp_file_dir = KMZRebuilederForm.TempDirectory() + "IF" + DateTime.UtcNow.Ticks.ToString() + @"\";
ZipFile zf = new ZipFile(file);
foreach (ZipEntry zipEntry in zf)
{
if (!zipEntry.IsFile) continue;
String entryFileName = zipEntry.Name;
byte[] buffer = new byte[4096]; // 4K is optimum
Stream zipStream = zf.GetInputStream(zipEntry);
String fullZipToPath = Path.Combine(tmp_file_dir, entryFileName);
string directoryName = Path.GetDirectoryName(fullZipToPath);
if (directoryName.Length > 0)
Directory.CreateDirectory(directoryName);
using (FileStream streamWriter = File.Create(fullZipToPath))
StreamUtils.Copy(zipStream, streamWriter, buffer);
f2l.Add(fullZipToPath);
};
zf.Close();
if (f2l.Count > 0)
LoadFiles(f2l.ToArray());
};
int c = kmzFiles.Items.Count;
if ((files.Length == 1) && ((Path.GetExtension(files[0]).ToLower() == ".kmf")))
{
OpenFilesInList(files[0]);
return;
};
if ((files.Length == 1) && ((Path.GetExtension(files[0]).ToLower() == ".rpp")))
{
waitBox.Show("Wait", "Loading map...");
TrackSplitter pc = new TrackSplitter(this, waitBox);
pc.OpenProject(files[0], true);
pc.SetPlannerPage();
waitBox.Hide();
pc.ShowDialog();
pc.Dispose();
return;
};
if ((files.Length == 1) && ((Path.GetExtension(files[0]).ToLower() == ".dxml")))
{
waitBox.Show("Wait", "Loading map...");
TrackSplitter pc = new TrackSplitter(this, waitBox);
pc.SetPlannerPage();
pc.Payways = AvtodorTRWeb.PayWays.Load(files[0]);
waitBox.Hide();
pc.ShowDialog();
pc.Dispose();
return;
};
if ((files.Length == 1) && ((Path.GetExtension(files[0]).ToLower() == ".dbf")))
{
ImportFromDBF(files[0]);
return;
};
if ((files.Length == 1) && ((Path.GetExtension(files[0]).ToLower() == ".shp")))
{
ImportFromSHP(files[0]);
};
if ((files.Length == 1) && ((Path.GetExtension(files[0]).ToLower() == ".poi")))
{
ImportPOI(files[0]);
return;
};
if ((files.Length == 1) && ((Path.GetExtension(files[0]).ToLower() == ".map")))
{
ImportMapsForgeMap(files[0]);
return;
};
if((files.Length == 1) && ((Path.GetExtension(files[0]).ToLower() == ".csv") || (Path.GetExtension(files[0]).ToLower() == ".txt")))
{
ImportFromText(new FileInfo(files[0]));
return;
};
if ((files.Length == 1) && (Path.GetExtension(files[0]).ToLower() == ".db3"))
{
ImportDB3(files[0]);
return;
};
foreach (string file in files)
{
waitBox.Show("Loading", "Wait, loading file `" + Path.GetFileName(file) + "` ...");
bool skip = false;
foreach (object oj in kmzFiles.Items)
{
KMFile f = (KMFile)oj;
if (f.src_file_pth == file) skip = true;
};
if (!KMFile.ValidForDragDropAuto(file)) skip = true;
if (skip)
continue;
else
{
if (Path.GetExtension(file).ToLower() == ".osm")
{
FileInfo fi = new FileInfo(file);
if(file.Length > (1024*1024*300))
{
MessageBox.Show("File size is too big!", "Import .osm file", MessageBoxButtons.OK, MessageBoxIcon.Error);
waitBox.Hide();
return;
};
};
KMFile f = new KMFile(file, AddToLog);
if (!f.Valid) continue;
kmzFiles.Items.Add(f, f.isCheck);
MyMruList.AddFile(file);
if ((outName.Text == String.Empty) ||(kmzFiles.Items.Count == 1)) outName.Text = f.kmldocName;
if (f.parseError)
MessageBox.Show("File `" + Path.GetFileName(file) + "` loaded with errors!\r\nCheck your data and save it to normal file first!", "Loading", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
};
};
if (c != kmzFiles.Items.Count) ReloadListboxLayers(true);
waitBox.Hide();
}
private void ReloadListboxLayers(bool fullUpdate)
{
if (fullUpdate)
{
kmzLayers.Visible = false;
kmzLayers.Items.Clear();
};
int p = 0;
int c = 0;
int e = 0;
int s = 0;
if (kmzFiles.Items.Count == 0)
{
STT0.Text = "Layers";
STT1.Text = "";
STT2.Text = "";
STT3.Text = "";
STT4.Text = "";
STT5.Text = "";
STT6.Text = "";
if (fullUpdate)
kmzLayers.Visible = true;
return;
};
Dictionary<string, List<Point>> ATB = new Dictionary<string, List<Point>>();
for(int i=0;i<kmzFiles.Items.Count;i++)
{
KMFile f = (KMFile)kmzFiles.Items[i];
if (!f.isCheck) continue;
int r = 0;
foreach (KMLayer layer in f.kmLayers)
{
try
{
layer.ATB = -1;
if (!ATB.ContainsKey(layer.name))
ATB.Add(layer.name, new List<Point>(new Point[] { new Point(i, r) }));
else
ATB[layer.name].Add(new Point(i, r));
}
catch { };
if (fullUpdate)
kmzLayers.Items.Add(layer, layer.ischeck);
p += layer.placemarks;
if (layer.ischeck)
{
c++;
s += layer.placemarks;
};
if (layer.placemarks == 0) e++;
r++;
};
};
try
{
int next_char = 0;
foreach (KeyValuePair<string, List<Point>> atv in ATB)
if (atv.Value.Count > 1)
{
foreach (Point fl in atv.Value)
((KMFile)kmzFiles.Items[fl.X]).kmLayers[fl.Y].ATB = next_char;
next_char++;
};
}
catch { };
STT0.Text = String.Format("{0}",p);
STT1.Text = "placemark(s) in";
STT2.Text = String.Format("{0}", kmzLayers.Items.Count);
STT3.Text = "layers(s)";
STT4.Text = String.Format("{0} placemark(s) in {1} checked layer(s)", s, c);
STT5.Text = String.Format("{0} layers unchecked", kmzLayers.Items.Count - c);
STT6.Text = String.Format("{0} layers is empty", e);
if (fullUpdate)
kmzLayers.Visible = true;
}
private void ReloadXMLOnly_NoUpdateLayers()
{
if (kmzFiles.Items.Count == 0) return;
for (int i = 0; i < kmzFiles.Items.Count; i++)
{
KMFile f = (KMFile)kmzFiles.Items[i];
f.LoadKML(false);
};
}
private void kmzLayers_ItemCheck(object sender, ItemCheckEventArgs e)
{
KMLayer l = (KMLayer)kmzLayers.Items[e.Index];
l.ischeck = e.NewValue == CheckState.Checked;
ReloadListboxLayers(false);
}
private void kmzFiles_ItemCheck(object sender, ItemCheckEventArgs e)
{
KMFile f = (KMFile)kmzFiles.Items[e.Index];
f.isCheck = e.NewValue == CheckState.Checked;
ReloadListboxLayers(true);
}
private void DeleteSelected_Click(object sender, EventArgs e)
{
if (kmzFiles.SelectedItems.Count == 0) return;
for (int i = kmzFiles.SelectedIndices.Count - 1; i >= 0; i--)
{
KMFile f = (KMFile)kmzFiles.Items[kmzFiles.SelectedIndices[i]];
System.IO.Directory.Delete(f.tmp_file_dir,true);
kmzFiles.Items.RemoveAt(kmzFiles.SelectedIndices[i]);
};
ReloadListboxLayers(true);
}
private void DeleteAll_Click(object sender, EventArgs e)
{
kmzFiles.Items.Clear();
try
{
if (Directory.Exists(TempDirectory())) System.IO.Directory.Delete(TempDirectory(), true);
}
catch { };
ReloadListboxLayers(true);
}
private void DeleteChecked_Click(object sender, EventArgs e)
{
if (kmzFiles.CheckedItems.Count == 0) return;
for (int i = kmzFiles.CheckedItems.Count - 1; i >= 0; i--)
{
KMFile f = (KMFile)kmzFiles.CheckedItems[i];
System.IO.Directory.Delete(f.tmp_file_dir,true);
kmzFiles.Items.Remove(kmzFiles.CheckedItems[i]);
};
ReloadListboxLayers(true);
}
private void Save2KML(string filename, KMLayer kml)
{
log.Text = "";
AddToLog("Creating single layer KML file for layer: `" + kml.name + "`...");
waitBox.Show("Saving", "Wait, saving file...");
System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Create, System.IO.FileAccess.Write);
System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.UTF8);
sw.WriteLine("<?xml version='1.0' encoding='UTF-8'?>");
sw.WriteLine("<kml xmlns='http://www.opengis.net/kml/2.2'><Document>");
sw.WriteLine("<name>" + kml.name + "</name>");
sw.WriteLine("<createdby>" + this.Text + "</createdby>");
AddToLog(String.Format("Saving data to selected file: {0}", filename));
List<KMStyle> styles = new List<KMStyle>();
// collect all styles for layer
{
XmlNode xn = kml.file.kmlDoc.SelectNodes("kml/Document/Folder")[kml.id];
XmlNodeList xns = xn.SelectNodes("Placemark/styleUrl");
if (xns.Count > 0)
for (int x = 0; x < xns.Count; x++)
{
string stname = xns[x].ChildNodes[0].Value;
if (stname.IndexOf("#") == 0) stname = stname.Remove(0, 1);
KMStyle kms = new KMStyle(stname, kml.file, "");
bool skip = false;
foreach (KMStyle get in styles) if (get.ToString() == kms.ToString()) { skip = true; };
if (!skip) styles.Add(kms);
};
sw.WriteLine(xn.OuterXml); //Write As Is
};
// select all styles for layer
string style_history = "";
foreach (KMStyle kms in styles)
{
// HISTORY
{
string was_name = kms.name;
XmlNode xh = kml.file.kmlDoc.SelectSingleNode("kml/Document/style_history");
if (xh != null)
{
string sh = xh.InnerText;
if (!String.IsNullOrEmpty(sh))
{
string[] history = sh.Split(new char[] { ';' });
foreach (string h in history)
{
string[] was = h.Split(new char[] { '=' });
if (kms.name == was[0]) was_name = was[1];
};
};
};
if (style_history.Length > 0) style_history += ";";
style_history += kms.newname + "=" + was_name;
};
List<KMStyle> tmps = new List<KMStyle>();
XmlNode xn = kms.file.kmlDoc.SelectSingleNode("kml/Document/StyleMap[@id='" + kms.name + "']");
if (xn == null)
tmps.Add(kms);
else
{
foreach (XmlNode xn2 in xn.SelectNodes("Pair/styleUrl"))
{
string su = xn2.ChildNodes[0].Value;
if (su.IndexOf("#") == 0) su = su.Remove(0, 1);
tmps.Add(new KMStyle(su, kms.file, ""));
};
sw.WriteLine(xn.OuterXml); //Write As Is
};
foreach (KMStyle k2 in tmps)
{
xn = k2.file.kmlDoc.SelectSingleNode("kml/Document/Style[@id='" + k2.name + "']");
if(xn != null) sw.WriteLine(xn.OuterXml); //Write As Is
};
};
sw.WriteLine("<style_history>" + style_history + "</style_history>");
sw.WriteLine("</Document></kml>");
sw.Close();
fs.Close();
waitBox.Hide();
AddToLog("Done");
}
private void Save2GPX(string filename, KMLayer kml, bool writeWPT, bool writeRTE)
{
log.Text = "";
AddToLog("Creating GPX file for layer: `" + kml.name + "`...");
waitBox.Show("Saving", "Wait, savining file...");
XmlNode xn = kml.file.kmlDoc.SelectNodes("kml/Document/Folder")[kml.id];
XmlNodeList xnp = xn.SelectNodes("Placemark/Point/coordinates");
XmlNodeList xnl = xn.SelectNodes("Placemark/LineString/coordinates");
if ((xnp.Count > 0) || (xnl.Count > 0))
{
System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Create, System.IO.FileAccess.Write);
System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.UTF8);
sw.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
sw.WriteLine("<gpx xmlns=\"http://www.topografix.com/GPX/1/1\" creator=\"" + this.Text + "\" version=\"1.1\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\">");
if (xnp.Count > 0)
{
if (writeWPT)
{
AddToLog("Writing points...");
for (int x = 0; x < xnp.Count; x++)
{
string[] llz = xnp[x].ChildNodes[0].Value.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
string name = xnp[x].ParentNode.ParentNode.SelectSingleNode("name").ChildNodes[0].Value;
string description = "";
try { description = xnp[x].ParentNode.ParentNode.SelectSingleNode("description").ChildNodes[0].Value; }
catch { };
sw.WriteLine("\t<wpt lat=\"" + llz[1] + "\" lon=\"" + llz[0] + "\">");
sw.WriteLine("\t\t<name>" + name + "</name>");
sw.WriteLine("\t\t<desc><![CDATA[" + description + "]]></desc>");
sw.WriteLine("\t</wpt>");
};
};
}
if (xnl.Count > 0)
{
if (writeRTE)
{
AddToLog("Writing lines...");
for (int x = 0; x < xnl.Count; x++)
{
string[] llza = xnl[x].ChildNodes[0].Value.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
string name = xnl[x].ParentNode.ParentNode.SelectSingleNode("name").ChildNodes[0].Value;
string description = "";
try { description = xnl[x].ParentNode.ParentNode.SelectSingleNode("description").ChildNodes[0].Value; }
catch { };
sw.WriteLine("\t<rte>");
sw.WriteLine("\t\t<name>" + name + "</name>");
sw.WriteLine("\t\t<desc><![CDATA[" + description + "]]></desc>");
foreach (string llzix in llza)
{
string llzi = llzix.Trim('\r').Trim('\n');
if (String.IsNullOrEmpty(llzi)) continue;
string[] llz = llzi.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
sw.WriteLine("\t\t<rtept lat=\"" + llz[1] + "\" lon=\"" + llz[0] + "\"/>");
};
sw.WriteLine("\t</rte>");
};
}
};
if(writeRTE && writeWPT)
AddToLog("Saved " + xnp.Count.ToString() + " points and " + xnl.Count.ToString() + " lines");
else if (writeWPT)
AddToLog("Saved " + xnp.Count.ToString() + " points");
else
AddToLog("Saved " + xnl.Count.ToString() + " lines");
AddToLog(String.Format("Saving data to selected file: {0}", filename));
sw.WriteLine("</gpx>");
sw.Close();
fs.Close();
waitBox.Hide();
AddToLog("Done");
return;
};
waitBox.Hide();
AddToLog("File not created: Layer has no placemarks to save in gpx format!");
MessageBox.Show("Layer has no placemarks to save in gpx format!", "File not created", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void Save2WPT(string filename, KMLayer kml)
{
log.Text = "";
AddToLog("Creating WPT file for layer: `" + kml.name + "`...");
waitBox.Show("Saving", "Wait, savining file...");
XmlNode xn = kml.file.kmlDoc.SelectNodes("kml/Document/Folder")[kml.id];
XmlNodeList xns = xn.SelectNodes("Placemark/Point/coordinates");
if (xns.Count > 0)
{
AddToLog("Writing points...");
List<string> styles = new List<string>();
List<WPTPOI> poi = new List<WPTPOI>();
for (int x = 0; x < xns.Count; x++)
{
string[] llz = xns[x].ChildNodes[0].Value.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
string name = xns[x].ParentNode.ParentNode.SelectSingleNode("name").ChildNodes[0].Value.Replace(",", ";");
int icon = 0;
XmlNode stn = xns[x].ParentNode.ParentNode.SelectSingleNode("styleUrl");
if ((stn != null) && (stn.ChildNodes.Count > 0))
{
string style = stn.ChildNodes[0].Value;
if (styles.IndexOf(style) < 0) styles.Add(style);
icon = styles.IndexOf(style);
};
string desc = "";
XmlNode std = xns[x].ParentNode.ParentNode.SelectSingleNode("description");
if ((std != null) && (std.ChildNodes.Count > 0))
desc = std.ChildNodes[0].Value;
if (desc.Contains("wpt_skip=true")) continue;
bool toTop = false;
if (!String.IsNullOrEmpty(desc))
{
string dtl = desc.ToLower();
if (dtl.IndexOf("progorod_dat_home=yes") >= 0) toTop = true;
if (dtl.IndexOf("progorod_dat_home=1") >= 0) toTop = true;
if (dtl.IndexOf("progorod_dat_home=true") >= 0) toTop = true;
if (dtl.IndexOf("progorod_dat_office=yes") >= 0) toTop = true;
if (dtl.IndexOf("progorod_dat_office=1") >= 0) toTop = true;
if (dtl.IndexOf("progorod_dat_office=true") >= 0) toTop = true;
dtl = (new Regex(@"[\w]+=[^\r\n]+")).Replace(dtl, ""); // Remove TAGS
};
WPTPOI p = new WPTPOI();
p.Name = name;
p.Description = desc;
p.Latitude = double.Parse(llz[1].Replace("\r", "").Replace("\n", "").Replace(" ", ""), System.Globalization.CultureInfo.InvariantCulture);
p.Longitude = double.Parse(llz[0].Replace("\r", "").Replace("\n", "").Replace(" ", ""), System.Globalization.CultureInfo.InvariantCulture);
p.Symbol = icon;
if (toTop)
poi.Insert(0, p);
else
poi.Add(p);
};
WPTPOI.WriteFile(filename, poi.ToArray(), this.Text);
AddToLog("Saved " + xns.Count.ToString() + " points");
AddToLog(String.Format("Saving data to selected file: {0}", filename));
waitBox.Hide();
AddToLog("Done");
return;
};
waitBox.Hide();
AddToLog("File not created: Layer has no placemarks to save in wpt format!");
MessageBox.Show("Layer has no placemarks to save in wpt format!", "File not created", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
public override void Refresh()
{
ReloadListboxLayers(false);
try
{
base.Refresh();
}
catch { };
}
private void Save2ReportCSV(string filename, IDictionary<string,string[]> fields)
{
log.Text = "";
waitBox.Show("Saving", "Wait, saving report...");
AddToLog("Create CSV Report: " +Path.GetFileName(filename));
System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Create, System.IO.FileAccess.Write);
System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.UTF8);
sw.WriteLine(outName.Text);
sw.WriteLine("Created by " + this.Text);
foreach (KeyValuePair<string, string[]> h in fields)
sw.Write(h.Key.Replace("\t", " ") + "\t");
sw.WriteLine();
int ttlpm = 0;
int layers = 0;
for (int i = 0; i < kmzLayers.CheckedItems.Count; i++)
{
KMLayer kml = (KMLayer)kmzLayers.CheckedItems[i];
XmlNode xn = kml.file.kmlDoc.SelectNodes("kml/Document/Folder")[kml.id];
XmlNodeList xns = xn.SelectNodes("Placemark/Point/coordinates");
if (xns.Count > 0)
{
layers++;
for (int x = 0; x < xns.Count; x++)
{
ttlpm++;
string[] llz = xns[x].ChildNodes[0].Value.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
string name = xns[x].ParentNode.ParentNode.SelectSingleNode("name").ChildNodes[0].Value.Replace(",", ";");
string desc = "";
XmlNode std = xns[x].ParentNode.ParentNode.SelectSingleNode("description");
if ((std != null) && (std.ChildNodes.Count > 0))
desc = std.ChildNodes[0].Value;
string lat = llz[1].Replace("\r", "").Replace("\n", "").Replace(" ", "");
string lon = llz[0].Replace("\r", "").Replace("\n", "").Replace(" ", "");
foreach (KeyValuePair<string, string[]> h in fields)
{
string value = h.Value[0].Replace("{layer}", kml.name).Replace("{name}", name).Replace("{latitude}", lat).Replace("{longitude}", lon).Replace("{description}", desc);
if (!String.IsNullOrEmpty(h.Value[1]))
{
Regex rx = new Regex(h.Value[1]);
Match mc = rx.Match(value);
if (mc.Success)
value = mc.Groups[1].Value;
else
value = "";
};
sw.Write(value.Replace("\t", " ") + "\t");
};
sw.WriteLine();
};
};
};
sw.WriteLine(String.Format("Report {1} placemarks in {0} layer(s)", layers, ttlpm));
sw.Close();
fs.Close();
AddToLog(String.Format("Report {1} placemarks in {0} layer(s)", layers, ttlpm));
AddToLog("Done");
waitBox.Hide();
}
private void Save2ReportHTML(string filename, IDictionary<string, string[]> fields)
{
log.Text = "";
waitBox.Show("Saving", "Wait, saving report...");
AddToLog("Create HTML Report: " + Path.GetFileName(filename));
System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Create, System.IO.FileAccess.Write);
System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.UTF8);
sw.WriteLine("<html>");
sw.WriteLine("<head>");
sw.WriteLine("<title>"+outName.Text+"</title>");
sw.WriteLine("</head><body>");
sw.WriteLine("<h1>" + outName.Text + "</h1>");
sw.WriteLine("<table border=\"1\" cellpadding=\"2\" cellspacing=\"1\">");
sw.WriteLine("<tr>");
foreach (KeyValuePair<string, string[]> h in fields)
sw.WriteLine("<td><b>" + h.Key + "</b></td>");
sw.WriteLine("</tr>");
int ttlpm = 0;
int layers = 0;
for (int i = 0; i < kmzLayers.CheckedItems.Count; i++)
{
KMLayer kml = (KMLayer)kmzLayers.CheckedItems[i];
XmlNode xn = kml.file.kmlDoc.SelectNodes("kml/Document/Folder")[kml.id];
XmlNodeList xns = xn.SelectNodes("Placemark/Point/coordinates");
if (xns.Count > 0)
{
layers++;
for (int x = 0; x < xns.Count; x++)
{
ttlpm++;
string[] llz = xns[x].ChildNodes[0].Value.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
string name = xns[x].ParentNode.ParentNode.SelectSingleNode("name").ChildNodes[0].Value.Replace(",", ";");
string desc = "";
XmlNode std = xns[x].ParentNode.ParentNode.SelectSingleNode("description");
if ((std != null) && (std.ChildNodes.Count > 0))
desc = std.ChildNodes[0].Value;
string lat = llz[1].Replace("\r", "").Replace("\n", "").Replace(" ", "");
string lon = llz[0].Replace("\r", "").Replace("\n", "").Replace(" ", "");
sw.WriteLine("<tr>");
foreach (KeyValuePair<string, string[]> h in fields)
{
sw.Write("<td>");
string value = h.Value[0].Replace("{layer}", kml.name).Replace("{name}", name).Replace("{latitude}", lat).Replace("{longitude}", lon).Replace("{description}", desc);
if (!String.IsNullOrEmpty(h.Value[1]))
{
Regex rx = new Regex(h.Value[1]);
Match mc = rx.Match(value);
if (mc.Success)
value = mc.Groups[1].Value;
else
value = "";
};
sw.Write(value);
sw.Write("</td>");
};
sw.WriteLine("</tr>");
};
};
};
sw.WriteLine("</table>");
sw.WriteLine("<div>" + String.Format("Report {1} placemarks in {0} layer(s)", layers, ttlpm) + "</div>");
sw.WriteLine("<div>Created by " + this.Text + "</div>");
sw.WriteLine("</body></html>");
AddToLog(String.Format("Report {1} placemarks in {0} layer(s)", layers, ttlpm));
AddToLog("Done");
waitBox.Hide();
}
private string Save2KMZ(string filename, bool multilayers)
{
return Save2KMZ(filename, multilayers, true, null);
}
private string Save2KMZ(string filename, bool multilayers, bool createArchive)
{
return Save2KMZ(filename, multilayers, createArchive, null);
}
private string Save2KMZ(string filename, bool multilayers, bool createArchive, string desc_filter_skip)
{
log.Text = "";
waitBox.Show("Saving", "Wait, saving file...");
string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
Random random = (new Random());
string pref = new String(new char[] { chars[random.Next(chars.Length)], chars[random.Next(chars.Length)], chars[random.Next(chars.Length)] });
string zdir = KMZRebuilederForm.TempDirectory() + "OF" + DateTime.UtcNow.Ticks.ToString() + @"\";
System.IO.Directory.CreateDirectory(zdir);
System.IO.Directory.CreateDirectory(zdir + @"\images\");
AddToLog("Creating "+(multilayers ? "multi" : "single")+" layer KMZ file for selected layers...");
AddToLog("Create Temp Folder: " + zdir);
AddToLog("Create KML File: " + zdir + "doc.kml");
System.IO.FileStream fs = new System.IO.FileStream(zdir + "doc.kml", System.IO.FileMode.Create, System.IO.FileAccess.Write);
System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.UTF8);
sw.WriteLine("<?xml version='1.0' encoding='UTF-8'?>");
sw.WriteLine("<kml xmlns='http://www.opengis.net/kml/2.2'><Document>");
sw.WriteLine("<name>" + outName.Text + "</name>");
sw.WriteLine("<createdby>" + this.Text + "</createdby>");