OpenCPN Partial API docs
Loading...
Searching...
No Matches
chartdbs.cpp
Go to the documentation of this file.
1/**************************************************************************
2 * Copyright (C) 2010 by David S. Register *
3 * Copyright (C) 2010 by Mark A Sikes *
4 * *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) any later version. *
9 * *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
14 * *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, see <https://www.gnu.org/licenses/>. *
17 **************************************************************************/
18
25#include "gl_headers.h"
26
27#include <wx/wxprec.h>
28
29#ifndef WX_PRECOMP
30#include <wx/wx.h>
31#endif
32
33#include <wx/arrimpl.cpp>
34#include <wx/dir.h>
35#include <wx/encconv.h>
36#include <wx/progdlg.h>
37#include <wx/regex.h>
38#include <wx/tokenzr.h>
39#include <wx/evtloop.h>
40
41#include "model/gui_events.h"
42
43#include "chartbase.h"
44#include "chartdbs.h"
45#include "flex_hash.h"
46#include "LOD_reduce.h"
47#include "mbtiles.h"
48#include "navutil.h"
49#include "pluginmanager.h"
50#include "shapefile_basemap.h"
51#include "chartdb_thread.h"
52
53#ifndef UINT32
54#define UINT32 unsigned int
55#endif
56
57#ifdef __ANDROID__
58#include "androidUTIL.h"
59#endif
60
61ChartGroupArray *g_pGroupArray;
62
63static int s_dbVersion; // Database version currently in use at runtime
64 // Needed for ChartTableEntry::GetChartType() only
65 // TODO This can go away at opencpn Version 1.3.8 and
66 // above....
68
69static ChartFamilyEnum GetChartFamily(int charttype) {
70 ChartFamilyEnum cf;
71
72 switch (charttype) {
73 case CHART_TYPE_KAP:
74 cf = CHART_FAMILY_RASTER;
75 break;
76 case CHART_TYPE_GEO:
77 cf = CHART_FAMILY_RASTER;
78 break;
79 case CHART_TYPE_S57:
80 cf = CHART_FAMILY_VECTOR;
81 break;
82 case CHART_TYPE_CM93:
83 cf = CHART_FAMILY_VECTOR;
84 break;
85 case CHART_TYPE_CM93COMP:
86 cf = CHART_FAMILY_VECTOR;
87 break;
88 case CHART_TYPE_DUMMY:
89 cf = CHART_FAMILY_RASTER;
90 break;
91 case CHART_TYPE_UNKNOWN:
92 cf = CHART_FAMILY_UNKNOWN;
93 break;
94 default:
95 cf = CHART_FAMILY_UNKNOWN;
96 break;
97 }
98 return cf;
99}
100
102// ChartTableHeader
104
105void ChartTableHeader::Read(wxInputStream &is) {
106 is.Read(this, sizeof(ChartTableHeader));
107}
108
109void ChartTableHeader::Write(wxOutputStream &os) {
110 char vb[5];
111 sprintf(vb, "V%03d", DB_VERSION_CURRENT);
112
113 memcpy(dbVersion, vb, 4);
114 os.Write(this, sizeof(ChartTableHeader));
115}
116
117bool ChartTableHeader::CheckValid() {
118 char vb[5];
119 sprintf(vb, "V%03d", DB_VERSION_CURRENT);
120 if (strncmp(vb, dbVersion, sizeof(dbVersion))) {
121 wxString msg;
122 char vbo[5];
123 memcpy(vbo, dbVersion, 4);
124 vbo[4] = 0;
125 msg.Append(wxString(vbo, wxConvUTF8));
126 msg.Prepend(" Warning: found incorrect chart db version: ");
127 wxLogMessage(msg);
128
129 // return false; // no match....
130
131 // Try previous version....
132 sprintf(vb, "V%03d", DB_VERSION_PREVIOUS);
133 if (strncmp(vb, dbVersion, sizeof(dbVersion)))
134 return false;
135 else {
136 wxLogMessage(
137 " Scheduling db upgrade to current db version on "
138 "Options->Charts page visit...");
139 return true;
140 }
141
142 } else {
143 wxString msg;
144 char vbo[5];
145 memcpy(vbo, dbVersion, 4);
146 vbo[4] = 0;
147 msg.Append(wxString(vbo, wxConvUTF8));
148 msg.Prepend("Loading chart db version: ");
149 wxLogMessage(msg);
150 }
151
152 return true;
153}
154
156// ChartTableEntry
158
159void ChartTableEntry::SetScale(int scale) {
160 Scale = scale;
161 rounding = 0;
162 // XXX find the right rounding
163 if (Scale >= 1000) rounding = 5 * pow(10, log10(Scale) - 2);
164}
165
166ChartTableEntry::ChartTableEntry(ChartBase &theChart, wxString &utf8Path) {
167 Clear();
168
169 char *pt = (char *)malloc(strlen(utf8Path.mb_str(wxConvUTF8)) + 1);
170 strcpy(pt, utf8Path.mb_str(wxConvUTF8));
171 pFullPath = pt;
172
173 SetScale(theChart.GetNativeScale());
174
175 ChartType = theChart.GetChartType();
176 ChartFamily = theChart.GetChartFamily();
177
178 Skew = theChart.GetChartSkew();
179 ProjectionType = theChart.GetChartProjectionType();
180
181 wxDateTime ed = theChart.GetEditionDate();
182 if (theChart.GetEditionDate().IsValid())
183 edition_date = theChart.GetEditionDate().GetTicks();
184
185 wxFileName fn(theChart.GetFullPath());
186 if (fn.GetModificationTime().IsValid())
187 file_date = fn.GetModificationTime().GetTicks();
188
189 m_pfilename = new wxString; // create and populate helper members
190 *m_pfilename = fn.GetFullName();
191 m_psFullPath = new wxString;
192 *m_psFullPath = utf8Path;
193 m_fullSystemPath = utf8Path;
194 m_FullPath = std::string(pFullPath);
195
196#ifdef __ANDROID__
197 m_fullSystemPath = wxString(utf8Path.mb_str(wxConvUTF8));
198#endif
199
200 Extent ext;
201 theChart.GetChartExtent(&ext);
202 LatMax = ext.NLAT;
203 LatMin = ext.SLAT;
204 LonMin = ext.WLON;
205 LonMax = ext.ELON;
206
207 m_bbox.Set(LatMin, LonMin, LatMax, LonMax);
208
209 // Fill in the PLY information
210 // LOD calculation
211 int LOD_pixels = 1;
212 double scale_max_zoom = Scale / 4;
213
214 double display_ppm = 1 / .00025; // nominal for most LCD displays
215 double meters_per_pixel_max_scale = scale_max_zoom / display_ppm;
216 double LOD_meters = meters_per_pixel_max_scale * LOD_pixels;
217
218 // double LOD_meters = 5;
219
220 // If COVR table has only one entry, us it for the primary Ply Table
221 if (theChart.GetCOVREntries() == 1) {
222 nPlyEntries = theChart.GetCOVRTablePoints(0);
223
224 if (nPlyEntries > 5 && (LOD_meters > .01)) {
225 std::vector<int> index_keep{0, nPlyEntries - 1, 1, nPlyEntries - 2};
226
227 double *DPbuffer = (double *)malloc(2 * nPlyEntries * sizeof(double));
228
229 double *pfed = DPbuffer;
230 Plypoint *ppp = (Plypoint *)theChart.GetCOVRTableHead(0);
231
232 for (int i = 0; i < nPlyEntries; i++) {
233 *pfed++ = ppp->ltp;
234 *pfed++ = ppp->lnp;
235 ppp++;
236 }
237
238 DouglasPeucker(DPbuffer, 1, nPlyEntries - 2, LOD_meters / (1852 * 60),
239 &index_keep);
240 // printf("DB DP Reduction: %d/%d\n", index_keep.size(),
241 // nPlyEntries);
242
243 // Mark the keepers by adding a simple constant to ltp
244 for (unsigned int i = 0; i < index_keep.size(); i++) {
245 DPbuffer[2 * index_keep[i]] += 2000.;
246 }
247
248 float *pf = (float *)malloc(2 * index_keep.size() * sizeof(float));
249 float *pfe = pf;
250
251 for (int i = 0; i < nPlyEntries; i++) {
252 if (DPbuffer[2 * i] > 1000.) {
253 *pfe++ = DPbuffer[2 * i] - 2000.;
254 *pfe++ = DPbuffer[(2 * i) + 1];
255 }
256 }
257
258 pPlyTable = pf;
259 nPlyEntries = index_keep.size();
260 free(DPbuffer);
261 } else {
262 float *pf = (float *)malloc(2 * nPlyEntries * sizeof(float));
263 pPlyTable = pf;
264 float *pfe = pf;
265 Plypoint *ppp = (Plypoint *)theChart.GetCOVRTableHead(0);
266
267 for (int i = 0; i < nPlyEntries; i++) {
268 *pfe++ = ppp->ltp;
269 *pfe++ = ppp->lnp;
270 ppp++;
271 }
272 }
273 }
274 // Else create a rectangular primary Ply Table from the chart extents
275 // and create AuxPly table from the COVR tables
276 else {
277 // Create new artificial Ply table from chart extents
278 nPlyEntries = 4;
279 float *pf1 = (float *)malloc(2 * 4 * sizeof(float));
280 pPlyTable = pf1;
281 float *pfe = pf1;
282 Extent fext;
283 theChart.GetChartExtent(&fext);
284
285 *pfe++ = fext.NLAT; // LatMax;
286 *pfe++ = fext.WLON; // LonMin;
287
288 *pfe++ = fext.NLAT; // LatMax;
289 *pfe++ = fext.ELON; // LonMax;
290
291 *pfe++ = fext.SLAT; // LatMin;
292 *pfe++ = fext.ELON; // LonMax;
293
294 *pfe++ = fext.SLAT; // LatMin;
295 *pfe++ = fext.WLON; // LonMin;
296
297 // Fill in the structure for pAuxPlyTable
298
299 nAuxPlyEntries = theChart.GetCOVREntries();
300 wxASSERT(nAuxPlyEntries);
301 float **pfp = (float **)malloc(nAuxPlyEntries * sizeof(float *));
302 float **pft0 = pfp;
303 int *pip = (int *)malloc(nAuxPlyEntries * sizeof(int));
304
305 for (int j = 0; j < nAuxPlyEntries; j++) {
306 int nPE = theChart.GetCOVRTablePoints(j);
307
308 if (nPE > 5 && (LOD_meters > .01)) {
309 std::vector<int> index_keep{0, nPE - 1, 1, nPE - 2};
310
311 double *DPbuffer = (double *)malloc(2 * nPE * sizeof(double));
312
313 double *pfed = DPbuffer;
314 Plypoint *ppp = (Plypoint *)theChart.GetCOVRTableHead(j);
315
316 for (int i = 0; i < nPE; i++) {
317 *pfed++ = ppp->ltp;
318 *pfed++ = ppp->lnp;
319 ppp++;
320 }
321
322 DouglasPeucker(DPbuffer, 1, nPE - 2, LOD_meters / (1852 * 60),
323 &index_keep);
324 // printf("DBa DP Reduction: %d/%d\n",
325 // index_keep.size(), nPE);
326
327 // Mark the keepers by adding a simple constant to ltp
328 for (unsigned int i = 0; i < index_keep.size(); i++) {
329 DPbuffer[2 * index_keep[i]] += 2000.;
330 }
331
332 float *pf = (float *)malloc(2 * index_keep.size() * sizeof(float));
333 float *pfe1 = pf;
334
335 for (int i = 0; i < nPE; i++) {
336 if (DPbuffer[2 * i] > 1000.) {
337 *pfe1++ = DPbuffer[2 * i] - 2000.;
338 *pfe1++ = DPbuffer[(2 * i) + 1];
339 }
340 }
341
342 pft0[j] = pf;
343 pip[j] = index_keep.size();
344 free(DPbuffer);
345 } else {
346 float *pf_entry =
347 (float *)malloc(theChart.GetCOVRTablePoints(j) * 2 * sizeof(float));
348 memcpy(pf_entry, theChart.GetCOVRTableHead(j),
349 theChart.GetCOVRTablePoints(j) * 2 * sizeof(float));
350 pft0[j] = pf_entry;
351 pip[j] = theChart.GetCOVRTablePoints(j);
352 }
353 }
354
355 pAuxPlyTable = pfp;
356 pAuxCntTable = pip;
357 }
358
359 // Get and populate the NoCovr tables
360
361 nNoCovrPlyEntries = theChart.GetNoCOVREntries();
362 if (nNoCovrPlyEntries == 0) return;
363
364 float **pfpnc = (float **)malloc(nNoCovrPlyEntries * sizeof(float *));
365 float **pft0nc = pfpnc;
366 int *pipnc = (int *)malloc(nNoCovrPlyEntries * sizeof(int));
367
368 for (int j = 0; j < nNoCovrPlyEntries; j++) {
369 float *pf_entry =
370 (float *)malloc(theChart.GetNoCOVRTablePoints(j) * 2 * sizeof(float));
371 memcpy(pf_entry, theChart.GetNoCOVRTableHead(j),
372 theChart.GetNoCOVRTablePoints(j) * 2 * sizeof(float));
373 pft0nc[j] = pf_entry;
374 pipnc[j] = theChart.GetNoCOVRTablePoints(j);
375 }
376
377 pNoCovrPlyTable = pfpnc;
378 pNoCovrCntTable = pipnc;
379}
380
382
383ChartTableEntry::~ChartTableEntry() {
384 // free(pFullPath);
385 free(pPlyTable);
386
387 for (int i = 0; i < nAuxPlyEntries; i++) free(pAuxPlyTable[i]);
388 free(pAuxPlyTable);
389 free(pAuxCntTable);
390
391 if (nNoCovrPlyEntries) {
392 for (int i = 0; i < nNoCovrPlyEntries; i++) free(pNoCovrPlyTable[i]);
393 free(pNoCovrPlyTable);
394 free(pNoCovrCntTable);
395 }
396
397 delete m_pfilename;
398 delete m_psFullPath;
399}
400
402
404
405bool ChartTableEntry::IsEarlierThan(const ChartTableEntry &cte) const {
406 wxDateTime mine(edition_date);
407 wxDateTime theirs(cte.edition_date);
408
409 if (!mine.IsValid() || !theirs.IsValid())
410 return false; // will have the effect of keeping all questionable charts
411
412 return (mine.IsEarlierThan(theirs));
413}
414
415bool ChartTableEntry::IsEqualTo(const ChartTableEntry &cte) const {
416 wxDateTime mine(edition_date);
417 wxDateTime theirs(cte.edition_date);
418
419 if (!mine.IsValid() || !theirs.IsValid())
420 return true; // will have the effect of keeping all questionable charts
421
422 return (mine.IsEqualTo(theirs));
423}
424
426
427static int convertChartType(int charttype) {
428 // Hackeroo here....
429 // dB version 14 had different ChartType Enum, patch it here
430 if (s_dbVersion == 14) {
431 switch (charttype) {
432 case 0:
433 return CHART_TYPE_KAP;
434 case 1:
435 return CHART_TYPE_GEO;
436 case 2:
437 return CHART_TYPE_S57;
438 case 3:
439 return CHART_TYPE_CM93;
440 case 4:
441 return CHART_TYPE_CM93COMP;
442 case 5:
443 return CHART_TYPE_UNKNOWN;
444 case 6:
445 return CHART_TYPE_DONTCARE;
446 case 7:
447 return CHART_TYPE_DUMMY;
448 default:
449 return CHART_TYPE_UNKNOWN;
450 }
451 }
452 return charttype;
453}
454
455static int convertChartFamily(int charttype, int chartfamily) {
456 if (s_dbVersion < 18) {
457 switch (charttype) {
458 case CHART_TYPE_KAP:
459 case CHART_TYPE_GEO:
460 return CHART_FAMILY_RASTER;
461
462 case CHART_TYPE_S57:
463 case CHART_TYPE_CM93:
464 case CHART_TYPE_CM93COMP:
465 return CHART_FAMILY_VECTOR;
466
467 default:
468 return CHART_FAMILY_UNKNOWN;
469 }
470 }
471 return chartfamily;
472}
473
474bool ChartTableEntry::Read(const ChartDatabase *pDb, wxInputStream &is) {
475 char path[4096], *cp;
476
477 Clear();
478
479 // Allow reading of current db format, and maybe others
480 ChartDatabase *pD = (ChartDatabase *)pDb;
481 int db_version = pD->GetVersion();
482
483 if (db_version == 18) {
484 // Read the path first
485 for (cp = path; (*cp = (char)is.GetC()) != 0; cp++);
486 pFullPath = (char *)malloc(cp - path + 1);
487 strncpy(pFullPath, path, cp - path + 1);
488 wxLogVerbose(" Chart %s", pFullPath);
489
490 // Create and populate the helper members
491 m_pfilename = new wxString;
492 wxString fullfilename(pFullPath, wxConvUTF8);
493 wxFileName fn(fullfilename);
494 *m_pfilename = fn.GetFullName();
495 m_psFullPath = new wxString;
496 *m_psFullPath = fullfilename;
497 m_fullSystemPath = fullfilename;
498 m_FullPath = std::string(pFullPath);
499
500#ifdef __ANDROID__
501 m_fullSystemPath = wxString(fullfilename.mb_str(wxConvUTF8));
502#endif
503 // Read the table entry
505 is.Read(&cte, sizeof(ChartTableEntry_onDisk_18));
506
507 // Transcribe the elements....
508 EntryOffset = cte.EntryOffset;
509 ChartType = cte.ChartType;
510 ChartFamily = cte.ChartFamily;
511 LatMax = cte.LatMax;
512 LatMin = cte.LatMin;
513 LonMax = cte.LonMax;
514 LonMin = cte.LonMin;
515
516 m_bbox.Set(LatMin, LonMin, LatMax, LonMax);
517
518 Skew = cte.skew;
519 ProjectionType = cte.ProjectionType;
520
521 SetScale(cte.Scale);
522 edition_date = cte.edition_date;
523 file_date = cte.file_date;
524
525 nPlyEntries = cte.nPlyEntries;
526 nAuxPlyEntries = cte.nAuxPlyEntries;
527
528 nNoCovrPlyEntries = cte.nNoCovrPlyEntries;
529
530 bValid = cte.bValid;
531
532 if (nPlyEntries) {
533 int npeSize = nPlyEntries * 2 * sizeof(float);
534 pPlyTable = (float *)malloc(npeSize);
535 is.Read(pPlyTable, npeSize);
536 }
537
538 if (nAuxPlyEntries) {
539 int napeSize = nAuxPlyEntries * sizeof(int);
540 pAuxPlyTable = (float **)malloc(nAuxPlyEntries * sizeof(float *));
541 pAuxCntTable = (int *)malloc(napeSize);
542 is.Read(pAuxCntTable, napeSize);
543
544 for (int nAuxPlyEntry = 0; nAuxPlyEntry < nAuxPlyEntries;
545 nAuxPlyEntry++) {
546 int nfSize = pAuxCntTable[nAuxPlyEntry] * 2 * sizeof(float);
547 pAuxPlyTable[nAuxPlyEntry] = (float *)malloc(nfSize);
548 is.Read(pAuxPlyTable[nAuxPlyEntry], nfSize);
549 }
550 }
551
552 if (nNoCovrPlyEntries) {
553 int napeSize = nNoCovrPlyEntries * sizeof(int);
554 pNoCovrCntTable = (int *)malloc(napeSize);
555 is.Read(pNoCovrCntTable, napeSize);
556
557 pNoCovrPlyTable = (float **)malloc(nNoCovrPlyEntries * sizeof(float *));
558 for (int i = 0; i < nNoCovrPlyEntries; i++) {
559 int nfSize = pNoCovrCntTable[i] * 2 * sizeof(float);
560 pNoCovrPlyTable[i] = (float *)malloc(nfSize);
561 is.Read(pNoCovrPlyTable[i], nfSize);
562 }
563 }
564 }
565
566 else if (db_version == 17) {
567 // Read the path first
568 for (cp = path; (*cp = (char)is.GetC()) != 0; cp++);
569 pFullPath = (char *)malloc(cp - path + 1);
570 strncpy(pFullPath, path, cp - path + 1);
571 wxLogVerbose(" Chart %s", pFullPath);
572
573 // Create and populate the helper members
574 m_pfilename = new wxString;
575 wxString fullfilename(pFullPath, wxConvUTF8);
576 wxFileName fn(fullfilename);
577 *m_pfilename = fn.GetFullName();
578 m_psFullPath = new wxString;
579 *m_psFullPath = fullfilename;
580 m_FullPath = std::string(pFullPath);
581
582 // Read the table entry
584 is.Read(&cte, sizeof(ChartTableEntry_onDisk_17));
585
586 // Transcribe the elements....
587 EntryOffset = cte.EntryOffset;
588 ChartType = cte.ChartType;
589 LatMax = cte.LatMax;
590 LatMin = cte.LatMin;
591 LonMax = cte.LonMax;
592 LonMin = cte.LonMin;
593
594 m_bbox.Set(LatMin, LatMax, LonMin, LonMax);
595
596 Skew = cte.skew;
597 ProjectionType = cte.ProjectionType;
598
599 SetScale(cte.Scale);
600 edition_date = cte.edition_date;
601 file_date = cte.file_date;
602
603 nPlyEntries = cte.nPlyEntries;
604 nAuxPlyEntries = cte.nAuxPlyEntries;
605
606 nNoCovrPlyEntries = cte.nNoCovrPlyEntries;
607
608 bValid = cte.bValid;
609
610 if (nPlyEntries) {
611 int npeSize = nPlyEntries * 2 * sizeof(float);
612 pPlyTable = (float *)malloc(npeSize);
613 is.Read(pPlyTable, npeSize);
614 }
615
616 if (nAuxPlyEntries) {
617 int napeSize = nAuxPlyEntries * sizeof(int);
618 pAuxPlyTable = (float **)malloc(nAuxPlyEntries * sizeof(float *));
619 pAuxCntTable = (int *)malloc(napeSize);
620 is.Read(pAuxCntTable, napeSize);
621
622 for (int nAuxPlyEntry = 0; nAuxPlyEntry < nAuxPlyEntries;
623 nAuxPlyEntry++) {
624 int nfSize = pAuxCntTable[nAuxPlyEntry] * 2 * sizeof(float);
625 pAuxPlyTable[nAuxPlyEntry] = (float *)malloc(nfSize);
626 is.Read(pAuxPlyTable[nAuxPlyEntry], nfSize);
627 }
628 }
629
630 if (nNoCovrPlyEntries) {
631 int napeSize = nNoCovrPlyEntries * sizeof(int);
632 pNoCovrCntTable = (int *)malloc(napeSize);
633 is.Read(pNoCovrCntTable, napeSize);
634
635 pNoCovrPlyTable = (float **)malloc(nNoCovrPlyEntries * sizeof(float *));
636 for (int i = 0; i < nNoCovrPlyEntries; i++) {
637 int nfSize = pNoCovrCntTable[i] * 2 * sizeof(float);
638 pNoCovrPlyTable[i] = (float *)malloc(nfSize);
639 is.Read(pNoCovrPlyTable[i], nfSize);
640 }
641 }
642 }
643
644 else if (db_version == 16) {
645 // Read the path first
646 for (cp = path; (*cp = (char)is.GetC()) != 0; cp++);
647 // TODO: optimize prepended dir
648 pFullPath = (char *)malloc(cp - path + 1);
649 strncpy(pFullPath, path, cp - path + 1);
650 wxLogVerbose(" Chart %s", pFullPath);
651
652 // Create and populate the helper members
653 m_pfilename = new wxString;
654 wxString fullfilename(pFullPath, wxConvUTF8);
655 wxFileName fn(fullfilename);
656 *m_pfilename = fn.GetFullName();
657 m_psFullPath = new wxString;
658 *m_psFullPath = fullfilename;
659 m_FullPath = std::string(pFullPath);
660
661 // Read the table entry
663 is.Read(&cte, sizeof(ChartTableEntry_onDisk_16));
664
665 // Transcribe the elements....
666 EntryOffset = cte.EntryOffset;
667 ChartType = cte.ChartType;
668 LatMax = cte.LatMax;
669 LatMin = cte.LatMin;
670 LonMax = cte.LonMax;
671 LonMin = cte.LonMin;
672
673 m_bbox.Set(LatMin, LatMax, LonMin, LonMax);
674
675 Skew = cte.skew;
676 ProjectionType = cte.ProjectionType;
677
678 SetScale(cte.Scale);
679 edition_date = cte.edition_date;
680 file_date = cte.file_date;
681
682 nPlyEntries = cte.nPlyEntries;
683 nAuxPlyEntries = cte.nAuxPlyEntries;
684
685 bValid = cte.bValid;
686
687 if (nPlyEntries) {
688 int npeSize = nPlyEntries * 2 * sizeof(float);
689 pPlyTable = (float *)malloc(npeSize);
690 is.Read(pPlyTable, npeSize);
691 }
692
693 if (nAuxPlyEntries) {
694 int napeSize = nAuxPlyEntries * sizeof(int);
695 pAuxPlyTable = (float **)malloc(nAuxPlyEntries * sizeof(float *));
696 pAuxCntTable = (int *)malloc(napeSize);
697 is.Read(pAuxCntTable, napeSize);
698
699 for (int nAuxPlyEntry = 0; nAuxPlyEntry < nAuxPlyEntries;
700 nAuxPlyEntry++) {
701 int nfSize = pAuxCntTable[nAuxPlyEntry] * 2 * sizeof(float);
702 pAuxPlyTable[nAuxPlyEntry] = (float *)malloc(nfSize);
703 is.Read(pAuxPlyTable[nAuxPlyEntry], nfSize);
704 }
705 }
706 }
707
708 else if (db_version == 15) {
709 // Read the path first
710 for (cp = path; (*cp = (char)is.GetC()) != 0; cp++);
711 // TODO: optimize prepended dir
712 pFullPath = (char *)malloc(cp - path + 1);
713 strncpy(pFullPath, path, cp - path + 1);
714 wxLogVerbose(" Chart %s", pFullPath);
715
716 // Read the table entry
718 is.Read(&cte, sizeof(ChartTableEntry_onDisk_15));
719
720 // Transcribe the elements....
721 EntryOffset = cte.EntryOffset;
722 ChartType = cte.ChartType;
723 LatMax = cte.LatMax;
724 LatMin = cte.LatMin;
725 LonMax = cte.LonMax;
726 LonMin = cte.LonMin;
727
728 m_bbox.Set(LatMin, LatMax, LonMin, LonMax);
729
730 SetScale(cte.Scale);
731 edition_date = cte.edition_date;
732 file_date = cte.file_date;
733
734 nPlyEntries = cte.nPlyEntries;
735 nAuxPlyEntries = cte.nAuxPlyEntries;
736
737 bValid = cte.bValid;
738
739 if (nPlyEntries) {
740 int npeSize = nPlyEntries * 2 * sizeof(float);
741 pPlyTable = (float *)malloc(npeSize);
742 is.Read(pPlyTable, npeSize);
743 }
744
745 if (nAuxPlyEntries) {
746 int napeSize = nAuxPlyEntries * sizeof(int);
747 pAuxPlyTable = (float **)malloc(nAuxPlyEntries * sizeof(float *));
748 pAuxCntTable = (int *)malloc(napeSize);
749 is.Read(pAuxCntTable, napeSize);
750
751 for (int nAuxPlyEntry = 0; nAuxPlyEntry < nAuxPlyEntries;
752 nAuxPlyEntry++) {
753 int nfSize = pAuxCntTable[nAuxPlyEntry] * 2 * sizeof(float);
754 pAuxPlyTable[nAuxPlyEntry] = (float *)malloc(nfSize);
755 is.Read(pAuxPlyTable[nAuxPlyEntry], nfSize);
756 }
757 }
758 } else if (db_version == 14) {
759 // Read the path first
760 for (cp = path; (*cp = (char)is.GetC()) != 0; cp++);
761 pFullPath = (char *)malloc(cp - path + 1);
762 strncpy(pFullPath, path, cp - path + 1);
763 wxLogVerbose(" Chart %s", pFullPath);
764
765 // Read the table entry
767 is.Read(&cte, sizeof(ChartTableEntry_onDisk_14));
768
769 // Transcribe the elements....
770 EntryOffset = cte.EntryOffset;
771 ChartType = cte.ChartType;
772 LatMax = cte.LatMax;
773 LatMin = cte.LatMin;
774 LonMax = cte.LonMax;
775 LonMin = cte.LonMin;
776
777 m_bbox.Set(LatMin, LatMax, LonMin, LonMax);
778
779 SetScale(cte.Scale);
780 edition_date = cte.edition_date;
781 file_date = 0; // file_date does not exist in V14;
782 nPlyEntries = cte.nPlyEntries;
783 nAuxPlyEntries = cte.nAuxPlyEntries;
784 bValid = cte.bValid;
785
786 if (nPlyEntries) {
787 int npeSize = nPlyEntries * 2 * sizeof(float);
788 pPlyTable = (float *)malloc(npeSize);
789 is.Read(pPlyTable, npeSize);
790 }
791
792 if (nAuxPlyEntries) {
793 int napeSize = nAuxPlyEntries * sizeof(int);
794 pAuxPlyTable = (float **)malloc(nAuxPlyEntries * sizeof(float *));
795 pAuxCntTable = (int *)malloc(napeSize);
796 is.Read(pAuxCntTable, napeSize);
797
798 for (int nAuxPlyEntry = 0; nAuxPlyEntry < nAuxPlyEntries;
799 nAuxPlyEntry++) {
800 int nfSize = pAuxCntTable[nAuxPlyEntry] * 2 * sizeof(float);
801 pAuxPlyTable[nAuxPlyEntry] = (float *)malloc(nfSize);
802 is.Read(pAuxPlyTable[nAuxPlyEntry], nfSize);
803 }
804 }
805 }
806 ChartFamily = convertChartFamily(ChartType, ChartFamily);
807 ChartType = convertChartType(ChartType);
808
809 return true;
810}
811
813
814bool ChartTableEntry::Write(const ChartDatabase *pDb, wxOutputStream &os) {
815 os.Write(pFullPath, strlen(pFullPath) + 1);
816
817 // Write the current version type only
818 // Create an on_disk table entry
820
821 // Transcribe the elements....
822 cte.EntryOffset = EntryOffset;
823 cte.ChartType = ChartType;
824 cte.ChartFamily = ChartFamily;
825 cte.LatMax = LatMax;
826 cte.LatMin = LatMin;
827 cte.LonMax = LonMax;
828 cte.LonMin = LonMin;
829
830 cte.Scale = Scale;
831 cte.edition_date = edition_date;
832 cte.file_date = file_date;
833
834 cte.nPlyEntries = nPlyEntries;
835 cte.nAuxPlyEntries = nAuxPlyEntries;
836
837 cte.skew = Skew;
838 cte.ProjectionType = ProjectionType;
839
840 cte.bValid = bValid;
841
842 cte.nNoCovrPlyEntries = nNoCovrPlyEntries;
843
844 os.Write(&cte, sizeof(ChartTableEntry_onDisk_18));
845 wxLogVerbose(" Wrote Chart %s", pFullPath);
846
847 // Write out the tables
848 if (nPlyEntries) {
849 int npeSize = nPlyEntries * 2 * sizeof(float);
850 os.Write(pPlyTable, npeSize);
851 }
852
853 if (nAuxPlyEntries) {
854 int napeSize = nAuxPlyEntries * sizeof(int);
855 os.Write(pAuxCntTable, napeSize);
856
857 for (int nAuxPlyEntry = 0; nAuxPlyEntry < nAuxPlyEntries; nAuxPlyEntry++) {
858 int nfSize = pAuxCntTable[nAuxPlyEntry] * 2 * sizeof(float);
859 os.Write(pAuxPlyTable[nAuxPlyEntry], nfSize);
860 }
861 }
862
863 if (nNoCovrPlyEntries) {
864 int ncSize = nNoCovrPlyEntries * sizeof(int);
865 os.Write(pNoCovrCntTable, ncSize);
866
867 for (int i = 0; i < nNoCovrPlyEntries; i++) {
868 int nctSize = pNoCovrCntTable[i] * 2 * sizeof(float);
869 os.Write(pNoCovrPlyTable[i], nctSize);
870 }
871 }
872
873 return true;
874}
875
877
878void ChartTableEntry::Clear() {
879 // memset(this, 0, sizeof(ChartTableEntry));
880
881 pFullPath = NULL;
882 pPlyTable = NULL;
883 pAuxPlyTable = NULL;
884 pAuxCntTable = NULL;
885 bValid = false;
886 ;
887 pNoCovrCntTable = NULL;
888 pNoCovrPlyTable = NULL;
889
890 nNoCovrPlyEntries = 0;
891 nAuxPlyEntries = 0;
892
893 m_pfilename = NULL; // a helper member, not on disk
894 m_psFullPath = NULL;
895}
896
898
899void ChartTableEntry::Disable() {
900 // Mark this chart in the database, so that it will not be seen during this
901 // run How? By setting the chart bounding box to an absurd value
902 // TODO... Fix this heinous hack
903 LatMax += (float)1000.;
904 LatMin += (float)1000.;
905}
906
907void ChartTableEntry::ReEnable() {
908 if (LatMax > 90.) {
909 LatMax -= (float)1000.;
910 LatMin -= (float)1000.;
911 }
912}
913bool ChartTableEntry::IsBasemap() const {
914 wxFileName fn(GetFullPath());
915 return (fn.GetPath().Lower().Contains("basemap"));
916}
917
918std::vector<float> ChartTableEntry::GetReducedPlyPoints() {
919 if (m_reducedPlyPoints.size()) return m_reducedPlyPoints;
920
921 // Reduce the LOD of the chart outline PlyPoints
922 float LOD_meters = 1;
923
924 float plylat, plylon;
925 const int nPoints = GetnPlyEntries();
926
927 float *fpo = GetpPlyTable();
928
929 double *ppd = new double[nPoints * 2];
930 double *ppsm = new double[nPoints * 2];
931 double *npr = ppd;
932 double *npsm = ppsm;
933 for (int i = 0; i < nPoints; i++) {
934 plylat = fpo[i * 2];
935 plylon = fpo[i * 2 + 1];
936
937 double x, y;
938 toSM(plylat, plylon, fpo[0], fpo[1], &x, &y);
939
940 *npr++ = plylon;
941 *npr++ = plylat;
942 *npsm++ = x;
943 *npsm++ = y;
944 }
945
946 std::vector<int> index_keep;
947 if (nPoints > 10) {
948 index_keep.push_back(0);
949 index_keep.push_back(nPoints - 1);
950 index_keep.push_back(1);
951 index_keep.push_back(nPoints - 2);
952
953 DouglasPeuckerM(ppsm, 1, nPoints - 2, LOD_meters, &index_keep);
954
955 } else {
956 index_keep.resize(nPoints);
957 for (int i = 0; i < nPoints; i++) index_keep[i] = i;
958 }
959
960 double *ppr = ppd;
961 for (int ip = 0; ip < nPoints; ip++) {
962 double x = *ppr++;
963 double y = *ppr++;
964
965 for (unsigned int j = 0; j < index_keep.size(); j++) {
966 if (index_keep[j] == ip) {
967 m_reducedPlyPoints.push_back(x);
968 m_reducedPlyPoints.push_back(y);
969 break;
970 }
971 }
972 }
973
974 delete[] ppd;
975 delete[] ppsm;
976
977 int nprr = m_reducedPlyPoints.size() / 2;
978
979 return m_reducedPlyPoints;
980}
981
982std::vector<float> ChartTableEntry::GetReducedAuxPlyPoints(int iTable) {
983 // Maybe need to initialize the vector
984 if (!m_reducedAuxPlyPointsVector.size()) {
985 std::vector<float> vec;
986 for (int i = 0; i < GetnAuxPlyEntries(); i++) {
987 m_reducedAuxPlyPointsVector.push_back(vec);
988 }
989 }
990
991 std::vector<float> vec;
992
993 // Invalid parameter
994 if ((unsigned int)iTable >= m_reducedAuxPlyPointsVector.size()) return vec;
995
996 if (m_reducedAuxPlyPointsVector.at(iTable).size())
997 return m_reducedAuxPlyPointsVector.at(iTable);
998
999 // Reduce the LOD of the chart outline PlyPoints
1000 float LOD_meters = 1.0;
1001
1002 const int nPoints = GetAuxCntTableEntry(iTable);
1003 float *fpo = GetpAuxPlyTableEntry(iTable);
1004
1005 double *ppd = new double[nPoints * 2];
1006 double *ppsm = new double[nPoints * 2];
1007 double *npr = ppd;
1008 double *npsm = ppsm;
1009 float plylat, plylon;
1010
1011 for (int i = 0; i < nPoints; i++) {
1012 plylat = fpo[i * 2];
1013 plylon = fpo[i * 2 + 1];
1014
1015 double x, y;
1016 toSM(plylat, plylon, fpo[0], fpo[1], &x, &y);
1017
1018 *npr++ = plylon;
1019 *npr++ = plylat;
1020 *npsm++ = x;
1021 *npsm++ = y;
1022 }
1023
1024 std::vector<int> index_keep;
1025 if (nPoints > 10) {
1026 index_keep.push_back(0);
1027 index_keep.push_back(nPoints - 1);
1028 index_keep.push_back(1);
1029 index_keep.push_back(nPoints - 2);
1030
1031 DouglasPeuckerM(ppsm, 1, nPoints - 2, LOD_meters, &index_keep);
1032
1033 } else {
1034 index_keep.resize(nPoints);
1035 for (int i = 0; i < nPoints; i++) index_keep[i] = i;
1036 }
1037
1038 int nnn = index_keep.size();
1039
1040 double *ppr = ppd;
1041 for (int ip = 0; ip < nPoints; ip++) {
1042 double x = *ppr++;
1043 double y = *ppr++;
1044
1045 for (unsigned int j = 0; j < index_keep.size(); j++) {
1046 if (index_keep[j] == ip) {
1047 vec.push_back(x);
1048 vec.push_back(y);
1049 break;
1050 }
1051 }
1052 }
1053
1054 delete[] ppd;
1055 delete[] ppsm;
1056
1057 m_reducedAuxPlyPointsVector[iTable] = vec;
1058
1059 int nprr = vec.size() / 2;
1060
1061 return vec;
1062}
1063
1065// ChartDatabase
1067const int ID_DBS_PROGRESS_UPDATE = wxNewId();
1068
1069WX_DEFINE_OBJARRAY(ChartTable);
1070
1071ChartDatabase::ChartDatabase() {
1072 bValid = false;
1073 SetBusy(false);
1074
1075 m_ChartTableEntryDummy.Clear();
1076
1077 Bind(wxEVT_OCPN_CHARTTABLEENTRYTHREAD, &ChartDatabase::OnEvtThread, this);
1078 Bind(wxEVT_COMMAND_MENU_SELECTED, &ChartDatabase::OnDBSProgressUpdate, this,
1079 ID_DBS_PROGRESS_UPDATE);
1080
1081 UpdateChartClassDescriptorArray();
1082}
1083
1084void ChartDatabase::OnDBSProgressUpdate(wxCommandEvent &evt) {
1085 int value = evt.GetInt(); // retrieve progress value
1086 if (m_pprog) {
1087 // Update dialog safely
1088 m_pprog->Update(value);
1089 }
1090}
1091
1092static int in_event;
1093void ChartDatabase::OnEvtThread(OCPN_ChartTableEntryThreadEvent &event) {
1094 if (in_event) int yyp = 4;
1095
1096 in_event++;
1097 // Capture the completed job tickets
1098 auto ticket = event.GetTicket();
1099 if (!ticket) {
1100 in_event--;
1101 return;
1102 }
1103
1104 // Update progress dialog, if present
1105 if (1 /*ticket->b_thread_safe*/) {
1106 if (m_pprog && (m_jobsRemaining > 1)) {
1107 m_progcount++;
1108 double ratio = 100. * (double)m_progcount / m_ticketcount;
1109 int val = ratio;
1110 if (((m_progcount % m_nFileProgressQuantum) == 0)) {
1111 if (val != m_progint) {
1112 m_progint = val;
1113 // printf("%d %d\n", m_progcount, val);
1114#ifdef x__WXMSW__
1115 // On Windows, Update may pump messages even without
1116 // CAN_ABORT/ELAPSED_TIME
1117 wxEventLoopBase *loop = wxEventLoopBase::GetActive();
1118 if (loop) {
1119 // Temporarily deactivate the active loop to prevent re-entrancy
1120 wxEventLoopActivator noLoop(nullptr);
1121 m_pprog->Update(val);
1122 }
1123#else
1124 m_pprog->Update(val);
1125#endif
1126 }
1127 }
1128 }
1129 }
1130
1131 if (!ticket->m_ticket_type) { // TICKET_TYPE_NORMAL
1132 bool collision_found = false;
1133 if (ticket->b_thread_safe) {
1134 wxFileName fn(ticket->m_ChartPath);
1135 ChartCollisionsHashMap::iterator it;
1136 for (it = m_full_collision_map.begin(); it != m_full_collision_map.end();
1137 ++it) {
1138 if (it->first.IsSameAs(fn.GetFullName())) {
1139 // Two files found with identical file name
1140 // For now, just drop this ticket
1141 // TODO Make an (expensive) test on file modification times
1142 collision_found = true;
1143 break;
1144 }
1145 }
1146 if (!collision_found) {
1147 m_full_collision_map[fn.GetFullName()] = 1;
1148 }
1149 // Consider TODO #1 here: Looking for more duolicates acress directories
1150 }
1151
1152 m_ticket_vector.push_back(ticket);
1153 }
1154
1155 int remaining = --m_jobsRemaining;
1156
1157 if (remaining == 0) {
1158 m_pool.Shutdown();
1159 m_pool_deferred.Shutdown();
1160 size_t a = m_ticket_vector.size();
1161
1162 if (m_deferred_ticket_vector.size()) {
1163 // Process the deferred charts in a single thread pool
1164 // load the thread pool from the prepared array
1165 // Enqueue jobs
1166 for (auto &ticket_d : m_deferred_ticket_vector) {
1167 m_pool_deferred.Push(ticket_d);
1168 m_jobsRemaining++;
1169 }
1170 m_deferred_ticket_vector.clear();
1171
1172 // Initialize progress dialog
1173 m_progcount = 0;
1174 m_progint = 0;
1175 m_ticketcount = m_jobsRemaining;
1176 m_nFileProgressQuantum = 1; // wxMax(m_ticketcount / 10, 2);
1177 if (m_pprog) m_pprog->Update(0, _("Processing charts."));
1178
1179 // Start up the queued thread, if necessary
1180 if (m_jobsRemaining) {
1181 const int workerCount = 1;
1182 if (m_pool_deferred.GetWorkerCount() < workerCount) {
1183 int threads_needed = workerCount - m_pool_deferred.GetWorkerCount();
1184 for (int i = 0; i < threads_needed; ++i) {
1185 (new PoolWorkerThread(m_pool_deferred, this))->Run();
1186 m_pool_deferred.AddWorker();
1187 }
1188 }
1189 }
1190 in_event--;
1191 return; // Let the thread run
1192 }
1193
1194 // Now m_ticket_vector is populated with verified tickets
1195 // for all specified directories.
1196
1197 // Add the CTEs from the tickets to the active table
1198 // NB: The active_chartTable was cleared by the Update() method
1199 // before this point
1200
1201 for (auto &ticket_valid : m_ticket_vector) {
1202 if (ticket_valid->m_chart_table_entry)
1203 active_chartTable.push_back(ticket_valid->m_chart_table_entry);
1204 }
1205 size_t c = m_ticket_vector.size();
1206 size_t d = active_chartTable.size();
1207
1208 // Release references to tickets
1209 m_ticket_vector.clear();
1210
1211 FinalizeChartUpdate();
1212 in_event--;
1213 } else
1214 in_event--;
1215}
1216
1217void ChartDatabase::FinalizeChartUpdate() {
1218 // Scrub CTE list, remove any invalid entries,
1219 // as tagged by directory removal
1220 active_chartTable.erase(
1221 std::remove_if(active_chartTable.begin(), active_chartTable.end(),
1222 [](const auto &cte) { return !cte->GetbValid(); }),
1223 active_chartTable.end());
1224
1225 size_t d = active_chartTable.size();
1226
1227 // And once more, setting the Entry index field
1228 active_chartTable_pathindex.clear();
1229 int i = 0;
1230 for (auto cte : active_chartTable) {
1231 active_chartTable_pathindex[cte->GetFullSystemPath()] = i;
1232 cte->SetEntryOffset(i);
1233 i++;
1234 }
1235
1236 m_nentries = active_chartTable.size();
1237 bValid = true;
1238 SetBusy(false);
1239 ChartData->SetBusy(false);
1240
1241 // Finalize the dB on disk
1242 ChartData->SaveBinary(ChartListFileName);
1243 wxLogMessage("Finished chart database Update");
1244 wxLogMessage(" ");
1245
1246 if (m_pprog) m_pprog->Destroy();
1247 m_pprog = nullptr;
1248
1249 // The Update() function may set gWorldMapLocation if at least one of the
1250 // directories contains GSHHS files. Make sure GSHHS is still accessible
1251 if (gWorldMapLocation.empty()) { // Last resort. User might have deleted all
1252 // GSHHG data, but we still might have the
1253 // default dataset distributed with OpenCPN
1254 // or from the package repository...
1255 gWorldMapLocation = gDefaultWorldMapLocation;
1256 m_gshhg_chart_loc = wxEmptyString;
1257 }
1258
1259 // Update canvas and "Crossesland" machinery
1260 if (gWorldMapLocation != m_gshhg_chart_loc) {
1261 // ..For each canvas...
1262 // TODO Move this where?
1263 // for (unsigned int i = 0; i < g_canvasArray.GetCount(); i++) {
1264 // ChartCanvas *cc = g_canvasArray.Item(i);
1265 // if (cc) cc->ResetWorldBackgroundChart();
1266 // }
1267
1268 // Reset the GSHHS singleton which is used to detect land crossing.
1269 gshhsCrossesLandReset();
1270 }
1271
1272 // Purge all charts from cache, and delete.
1273 ChartData->PurgeCache();
1274
1275 // Signal Options dialog that update is finished
1276 GuiEvents::GetInstance().options_on_finalize_chartdbs.Notify();
1277
1278 // Signal a full chart reload
1279 GuiEvents::GetInstance().on_finalize_chartdbs.Notify();
1280}
1281
1282bool ChartDatabase::ScrubGroupArray() {
1283 // For each group,
1284 // make sure that each group element (dir or chart) references at least
1285 // oneitem in the database. If not, remove the element.
1286
1287 bool b_change = false;
1288 unsigned int igroup = 0;
1289 while (igroup < g_pGroupArray->GetCount()) {
1290 bool b_chart_in_element = false;
1291 ChartGroup *pGroup = g_pGroupArray->Item(igroup);
1292
1293 for (unsigned int j = 0; j < pGroup->m_element_array.size(); j++) {
1294 const wxString &element_root = pGroup->m_element_array[j].m_element_name;
1295
1296 for (unsigned int ic = 0;
1297 ic < (unsigned int)ChartData->GetChartTableEntries(); ic++) {
1298 auto &cte = ChartData->GetChartTableEntry(ic);
1299 wxString chart_full_path = cte.GetFullSystemPath();
1300
1301 if (chart_full_path.StartsWith(element_root)) {
1302 b_chart_in_element = true;
1303 break;
1304 }
1305 }
1306
1307 // Explicit check to avoid removing a group containing only GSHHS
1308 if (!b_chart_in_element) {
1309 wxString test_string = "GSHH";
1310 if (element_root.Upper().Contains(test_string))
1311 b_chart_in_element = true;
1312 }
1313
1314 if (!b_chart_in_element) // delete the element
1315 {
1316 pGroup->m_element_array.erase(pGroup->m_element_array.begin() + j);
1317 j--;
1318 b_change = true;
1319 }
1320 }
1321
1322 igroup++; // next group
1323 }
1324
1325 return b_change;
1326}
1327
1328void ChartDatabase::UpdateChartClassDescriptorArray() {
1329 if (m_ChartClassDescriptorArray.empty()) {
1330 m_ChartClassDescriptorArray.push_back(
1331 ChartClassDescriptor("ChartKAP", "*.kap", nullptr, BUILTIN_DESCRIPTOR));
1332 m_ChartClassDescriptorArray.push_back(
1333 ChartClassDescriptor("ChartGEO", "*.geo", nullptr, BUILTIN_DESCRIPTOR));
1334 m_ChartClassDescriptorArray.push_back(
1335 ChartClassDescriptor("s57chart", "*.000", nullptr, BUILTIN_DESCRIPTOR));
1336 m_ChartClassDescriptorArray.push_back(
1337 ChartClassDescriptor("s57chart", "*.s57", nullptr, BUILTIN_DESCRIPTOR));
1338 m_ChartClassDescriptorArray.push_back(ChartClassDescriptor(
1339 "cm93compchart", "00300000.a", nullptr, BUILTIN_DESCRIPTOR));
1340 m_ChartClassDescriptorArray.push_back(ChartClassDescriptor(
1341 "ChartMbTiles", "*.mbtiles", nullptr, BUILTIN_DESCRIPTOR));
1342 }
1343 // If the PlugIn Manager exists, get the array of dynamically loadable
1344 // chart class names
1345 if (g_pi_manager) {
1346 m_ChartClassDescriptorArray.erase(
1347 std::remove_if(m_ChartClassDescriptorArray.begin(),
1348 m_ChartClassDescriptorArray.end(),
1349 [](const ChartClassDescriptor &cd) {
1350 return cd.m_descriptor_type == PLUGIN_DESCRIPTOR;
1351 }),
1352 m_ChartClassDescriptorArray.end());
1353
1354 wxArrayString array = g_pi_manager->GetPlugInChartClassNameArray();
1355 for (unsigned int j = 0; j < array.GetCount(); j++) {
1356 // Instantiate a blank chart to retrieve the directory search mask for
1357 // this chart type
1358 wxString class_name = array[j];
1359 ChartPlugInWrapper *cpiw = new ChartPlugInWrapper(class_name);
1360 if (cpiw) {
1361 wxString mask = cpiw->GetFileSearchMask();
1362
1363 // Get the plugin (ptr) that provides this chart class
1364 auto plugin_t = g_pi_manager->GetProvidingPlugin(class_name);
1365 opencpn_plugin *plugin = dynamic_cast<opencpn_plugin *>(plugin_t);
1366 // Create a new descriptor and add it to the database
1367 m_ChartClassDescriptorArray.push_back(
1368 ChartClassDescriptor(class_name, mask, plugin, PLUGIN_DESCRIPTOR));
1369 delete cpiw;
1370 }
1371 }
1372 }
1373}
1374
1375ChartTableEntry &ChartDatabase::GetChartTableEntry(int index) const {
1376 // if (index < GetChartTableEntries())
1377 return *active_chartTable[index];
1378 // TODO fix
1379 // else
1380 // return m_ChartTableEntryDummy;
1381}
1382
1383bool ChartDatabase::CompareChartDirArray(ArrayOfCDI &test_array) {
1384 // Compare the parameter "test_array" with this.m_dir_array
1385 // Return true if functionally identical (order does not signify).
1386
1387 if (test_array.GetCount() != m_dir_array.GetCount()) return false;
1388
1389 bool bfound_inner;
1390 unsigned int nfound_outer = 0;
1391
1392 for (unsigned int i = 0; i < test_array.GetCount(); i++) {
1393 ChartDirInfo p = test_array[i];
1394 bfound_inner = false;
1395 for (unsigned int j = 0; j < m_dir_array.GetCount(); j++) {
1396 ChartDirInfo q = m_dir_array[j];
1397
1398 if (p.fullpath.IsSameAs(q.fullpath)) {
1399 bfound_inner = true;
1400 break;
1401 }
1402 }
1403 if (bfound_inner) nfound_outer++;
1404 }
1405
1406 return (nfound_outer == test_array.GetCount());
1407}
1408
1409wxString ChartDatabase::GetMagicNumberCached(wxString dir) {
1410 for (unsigned int j = 0; j < m_dir_array.GetCount(); j++) {
1411 ChartDirInfo q = m_dir_array[j];
1412 if (dir.IsSameAs(q.fullpath)) return q.magic_number;
1413 }
1414
1415 return "";
1416}
1417
1418bool ChartDatabase::Read(const wxString &filePath) {
1419 ChartTableEntry entry;
1420 int entries;
1421
1422 bValid = false;
1423
1424 wxFileName file(filePath);
1425 if (!file.FileExists()) return false;
1426
1427 m_DBFileName = filePath;
1428
1429 wxFFileInputStream ifs(filePath);
1430 if (!ifs.Ok()) return false;
1431
1432 ChartTableHeader cth;
1433 cth.Read(ifs);
1434 if (!cth.CheckValid()) return false;
1435
1436 // Capture the version number
1437 char vbo[5];
1438 memcpy(vbo, cth.GetDBVersionString(), 4);
1439 vbo[4] = 0;
1440 m_dbversion = atoi(&vbo[1]);
1441 s_dbVersion = m_dbversion; // save the static copy
1442
1443 wxLogVerbose("Chartdb:Reading %d directory entries, %d table entries",
1444 cth.GetDirEntries(), cth.GetTableEntries());
1445 wxLogMessage("Chartdb: Chart directory list follows");
1446 if (0 == cth.GetDirEntries()) wxLogMessage(" Nil");
1447
1448 int ind = 0;
1449 for (int iDir = 0; iDir < cth.GetDirEntries(); iDir++) {
1450 wxString dir;
1451 int dirlen;
1452 ifs.Read(&dirlen, sizeof(int));
1453 while (dirlen > 0) {
1454 char dirbuf[1024];
1455 int alen = dirlen > 1023 ? 1023 : dirlen;
1456 if (ifs.Read(&dirbuf, alen).Eof()) goto read_error;
1457 dirbuf[alen] = 0;
1458 dirlen -= alen;
1459 dir.Append(wxString(dirbuf, wxConvUTF8));
1460 }
1461 wxString msg;
1462 msg.Printf(" Chart directory #%d: ", iDir);
1463 msg.Append(dir);
1464 wxLogMessage(msg);
1465 m_chartDirs.Add(dir);
1466 }
1467
1468 entries = cth.GetTableEntries();
1469 // active_chartTable.Alloc(entries);
1470 active_chartTable_pathindex.clear();
1471 while (entries-- && entry.Read(this, ifs)) {
1472 active_chartTable_pathindex[entry.GetFullSystemPath()] = ind++;
1473 auto sharedPtr = std::make_shared<ChartTableEntry>(entry);
1474 active_chartTable.push_back(sharedPtr);
1475 }
1476
1477 entry.Clear();
1478 bValid = true;
1479 entry.SetAvailable(true);
1480
1481 m_nentries = active_chartTable.size();
1482 return true;
1483
1484read_error:
1485 bValid = false;
1486 m_nentries = active_chartTable.size();
1487 return false;
1488}
1489
1491
1492bool ChartDatabase::Write(const wxString &filePath) {
1493 wxFileName file(filePath);
1494 wxFileName dir(
1495 file.GetPath(wxPATH_GET_SEPARATOR | wxPATH_GET_VOLUME, wxPATH_NATIVE));
1496
1497 if (!dir.DirExists() && !dir.Mkdir()) return false;
1498
1499 wxFFileOutputStream ofs(filePath);
1500 if (!ofs.Ok()) return false;
1501
1502 ChartTableHeader cth(m_chartDirs.GetCount(), active_chartTable.size());
1503 cth.Write(ofs);
1504
1505 for (int iDir = 0; iDir < cth.GetDirEntries(); iDir++) {
1506 wxString dir1 = m_chartDirs[iDir];
1507 int dirlen = dir1.length();
1508 char s[200];
1509 strncpy(s, dir1.mb_str(wxConvUTF8), 199);
1510 s[199] = 0;
1511 dirlen = strlen(s);
1512 ofs.Write(&dirlen, sizeof(int));
1513 // ofs.Write(dir.fn_str(), dirlen);
1514 ofs.Write(s, dirlen);
1515 }
1516
1517 for (UINT32 iTable = 0; iTable < active_chartTable.size(); iTable++) {
1518 auto &cte = GetChartTableEntry(iTable);
1519 cte.Write(this, ofs);
1520 }
1521
1522 // Explicitly set the version
1523 m_dbversion = DB_VERSION_CURRENT;
1524
1525 return true;
1526}
1527
1529wxString SplitPath(wxString s, wxString tkd, int nchar, int offset,
1530 int *pn_split) {
1531 wxString r;
1532 int ncr = 0;
1533
1534 int rlen = offset;
1535 wxStringTokenizer tkz(s, tkd);
1536 while (tkz.HasMoreTokens()) {
1537 wxString token = tkz.GetNextToken();
1538 if ((rlen + (int)token.Len() + 1) < nchar) {
1539 r += token;
1540 r += tkd[0];
1541 rlen += token.Len() + 1;
1542 } else {
1543 r += "\n";
1544 ncr++;
1545 for (int i = 0; i < offset; i++) {
1546 r += " ";
1547 }
1548 r += token;
1549 r += tkd[0];
1550 rlen = offset + token.Len() + 1;
1551 }
1552 }
1553
1554 if (pn_split) *pn_split = ncr;
1555
1556 return r.Mid(0, r.Len() - 1); // strip the last separator char
1557}
1558
1559wxString ChartDatabase::GetFullChartInfo(ChartBase *pc, int dbIndex,
1560 int *char_width, int *line_count) {
1561 wxString r;
1562 int lc = 0;
1563 unsigned int max_width = 0;
1564 int ncr;
1565 unsigned int target_width = 60;
1566
1567 const ChartTableEntry &cte = GetChartTableEntry(dbIndex);
1568 wxString line;
1569 line.Empty();
1570 if (pc) {
1571 line = _(" Name: ");
1572 wxString longline = pc->GetName();
1573
1574 wxString tkz;
1575 if (longline.Find(' ') != wxNOT_FOUND) // assume a proper name
1576 tkz = " ";
1577 else
1578 tkz = "/,\\"; // else a file name
1579
1580 if (longline.Len() > target_width) {
1581 line += SplitPath(pc->GetName(), tkz, target_width, 12, &ncr);
1582 max_width = wxMax(max_width, target_width + 4);
1583 lc += ncr;
1584 } else {
1585 line += longline;
1586 max_width = wxMax(max_width, line.Len() + 4);
1587 }
1588 }
1589
1590 line += "\n";
1591 r += line;
1592 lc++;
1593
1594 if (pc) // chart is loaded and available
1595 line.Printf(" %s: 1:%d", _("Scale"), pc->GetNativeScale());
1596 else
1597 line.Printf(" %s: 1:%d", _("Scale"), cte.GetScale());
1598
1599 line += "\n";
1600 max_width = wxMax(max_width, line.Len());
1601 r += line;
1602 lc++;
1603 if (pc) {
1604 wxDateTime ed = pc->GetEditionDate();
1605 if (ed.IsValid()) {
1606 line = _(" Updated: ") + ed.FormatISODate() + "\n";
1607 max_width = wxMax(max_width, line.Len());
1608 r += line;
1609 }
1610 lc++;
1611
1612 line = _(" Source Edition: ") + pc->GetSE() + "\n";
1613 max_width = wxMax(max_width, line.Len());
1614 r += line;
1615 lc++;
1616 }
1617
1618 if (pc) {
1619 line = _(" Depth Units: ") + pc->GetDepthUnits() + "\n";
1620 max_width = wxMax(max_width, line.Len());
1621 r += line;
1622 lc++;
1623
1624 line = _(" Soundings: ") + pc->GetSoundingsDatum() + "\n";
1625 max_width = wxMax(max_width, line.Len());
1626 r += line;
1627 lc++;
1628
1629 line = _(" Datum: ") + pc->GetDatumString() + "\n";
1630 max_width = wxMax(max_width, line.Len());
1631 r += line;
1632 lc++;
1633 }
1634
1635 line = _(" Projection: ");
1636 if (PROJECTION_UNKNOWN == cte.GetChartProjectionType())
1637 line += _("Unknown");
1638 else if (PROJECTION_MERCATOR == cte.GetChartProjectionType())
1639 line += _("Mercator");
1640 else if (PROJECTION_TRANSVERSE_MERCATOR == cte.GetChartProjectionType())
1641 line += _("Transverse Mercator");
1642 else if (PROJECTION_POLYCONIC == cte.GetChartProjectionType())
1643 line += _("Polyconic");
1644 else if (PROJECTION_WEB_MERCATOR == cte.GetChartProjectionType())
1645 line += _("Web Mercator (EPSG:3857)");
1646 line += "\n";
1647 max_width = wxMax(max_width, line.Len());
1648 r += line;
1649 lc++;
1650
1651 line.Empty();
1652 if (pc) {
1653 }
1654
1655 line.Empty();
1656 if (pc && pc->GetExtraInfo().Len()) {
1657 line += pc->GetExtraInfo();
1658 line += "\n";
1659 max_width = wxMax(max_width, line.Len());
1660 r += line;
1661 lc++;
1662 }
1663 if (pc) {
1664 line.Empty();
1665 line = _(" ID: ");
1666 line += pc->GetID();
1667 line += "\n";
1668 max_width = wxMax(max_width, line.Len());
1669 r += line;
1670 lc++;
1671 }
1672
1673 line = _(" ChartFile: ");
1674 wxString longline = *(cte.GetpsFullPath());
1675 if (longline.Len() > target_width) {
1676 line += SplitPath(longline, "/,\\", target_width, 15, &ncr);
1677 max_width = wxMax(max_width, target_width + 4);
1678 lc += ncr;
1679 } else {
1680 line += longline;
1681 max_width = wxMax(max_width, line.Len() + 4);
1682 }
1683 r += line;
1684 r += "\n";
1685 lc++;
1686
1687 if (line_count) *line_count = lc;
1688
1689 if (char_width) *char_width = max_width;
1690
1691 return r;
1692}
1693
1694// ----------------------------------------------------------------------------
1695// Create Chart Table Database by directory search
1696// resulting in valid pChartTable in (this)
1697// ----------------------------------------------------------------------------
1698bool ChartDatabase::Create(ArrayOfCDI &dir_array,
1699 wxGenericProgressDialog *pprog) {
1700 m_dir_array = dir_array;
1701
1702 bValid = false;
1703
1704 m_chartDirs.Clear();
1705 active_chartTable.clear();
1706 active_chartTable_pathindex.clear();
1707
1708 Update(dir_array, true, pprog); // force the update the reload everything
1709
1710 bValid = true;
1711
1712 // Explicitly set the version
1713 m_dbversion = DB_VERSION_CURRENT;
1714
1715 return true;
1716}
1717
1718/*
1719 * Traverse a directory recursively and find the GSHHG directory
1720 * that contains GSHHG data files.
1721 */
1722class GshhsTraverser : public wxDirTraverser {
1723public:
1724 GshhsTraverser() {}
1725 virtual wxDirTraverseResult OnFile(const wxString &filename) override {
1726 wxFileName fn(filename);
1727 wxFileName dir(fn.GetPath());
1728 if (fn.GetFullName().Matches("poly-*-1.dat") &&
1729 dir.GetFullName().IsSameAs("GSHHG", false)) {
1730 parent_dir = fn.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR);
1731 return wxDIR_STOP;
1732 }
1733 return wxDIR_CONTINUE;
1734 }
1735 virtual wxDirTraverseResult OnDir(const wxString &dirname) override {
1736 // Always recurse into directories.
1737 return wxDIR_CONTINUE;
1738 }
1739 wxString GetGshhsDir() const { return parent_dir; }
1740
1741private:
1742 wxString parent_dir;
1743};
1744
1745/*
1746 * Find and return the full path a of directory containing GSHHG data files.
1747 * Search recursively starting from directory.
1748 */
1749wxString findGshhgDirectory(const wxString &directory) {
1750 wxDir dir(directory);
1751 if (!dir.IsOpened()) {
1752 return wxEmptyString;
1753 }
1754 GshhsTraverser traverser;
1755 dir.Traverse(traverser, wxEmptyString, wxDIR_FILES | wxDIR_DIRS);
1756 return traverser.GetGshhsDir();
1757}
1758
1759bool ChartDatabase::UpdateChartDatabaseInplace(ArrayOfCDI &DirArray,
1760 bool b_force,
1761 wxGenericProgressDialog *_prog) {
1762 // AbstractPlatform::ShowBusySpinner();
1763
1764 m_pprog = _prog;
1765
1766 wxLogMessage(" ");
1767 wxLogMessage("Starting chart database Update...");
1768
1769 // The Update() function may set gWorldMapLocation if at least one of the
1770 // directories contains GSHHS files. Save current situation...
1771 m_gshhg_chart_loc = gWorldMapLocation;
1772 gWorldMapLocation = wxEmptyString;
1773
1774 Update(DirArray, b_force, m_pprog);
1775
1776 // AbstractPlatform::HideBusySpinner();
1777 return true;
1778}
1779
1780// ----------------------------------------------------------------------------
1781// Update existing ChartTable Database by directory search
1782// resulting in valid pChartTable in (this)
1783// ----------------------------------------------------------------------------
1784bool ChartDatabase::Update(ArrayOfCDI &dir_array, bool bForce,
1785 wxGenericProgressDialog *pprog) {
1786 m_pprog = pprog;
1787 m_ticket_vector.clear();
1788 m_full_collision_map.clear();
1789 m_jobsRemaining = 0;
1790 m_deferred_ticket_vector.clear();
1791 SetChartDirArray(dir_array);
1792
1793 bValid = false; // database is not useable right now...
1794 SetBusy(true);
1795 ChartData->SetBusy(true);
1796
1797 // Mark all charts provisionally invalid
1798 for (unsigned int i = 0; i < active_chartTable.size(); i++) {
1799 auto &cte = GetChartTableEntry(i);
1800 cte.SetValid(false);
1801 }
1802
1803 m_chartDirs.Clear();
1804
1805 if (bForce) active_chartTable.clear();
1806
1807 bool lbForce = bForce;
1808
1809 // Do a dB Version upgrade if the current one is obsolete
1810 if (s_dbVersion != DB_VERSION_CURRENT) {
1811 active_chartTable.clear();
1812 lbForce = true;
1813 s_dbVersion = DB_VERSION_CURRENT; // Update the static indicator
1814 m_dbversion = DB_VERSION_CURRENT; // and the member
1815 }
1816
1817 // Get the new charts
1818
1819 for (unsigned int j = 0; j < dir_array.GetCount(); j++) {
1820 ChartDirInfo dir_info = dir_array[j];
1821
1822 // On Android, with SDK >= 30, traversal of a folder that is
1823 // on within the "scoped storage" domain is very slow.
1824 // Aviod it....
1825#ifdef __ANDROID__
1826 if (!androidIsDirWritable(dir_info.fullpath)) continue;
1827#endif
1828
1829 wxString dir_magic;
1830 // Recursively search for a directory that contains GSHHG files starting
1831 // from dir_info.
1832 wxString gshhg_dir = findGshhgDirectory(dir_info.fullpath);
1833 if (!gshhg_dir.empty()) {
1834 // If some polygons exist in the directory, set it as the one to use for
1835 // GSHHG
1836 // TODO: We should probably compare the version and maybe resolutions
1837 // available with what is currently used...
1838 wxLogMessage("Updating GSHHG directory: %s", gshhg_dir.c_str());
1839 gWorldMapLocation = gshhg_dir;
1840 }
1841 if (dir_info.fullpath.Find("OSMSHP") != wxNOT_FOUND) {
1842 if (!wxDir::FindFirst(dir_info.fullpath, "basemap_*.shp").empty()) {
1843 gWorldShapefileLocation =
1844 dir_info.fullpath + wxFileName::GetPathSeparator();
1845 gShapeBasemap.Reset();
1846 }
1847 }
1848
1849 TraverseDirAndAddCharts(dir_info, pprog, dir_magic, lbForce);
1850
1851 // Update the dir_list entry, even if the magic values are the same
1852 dir_info.magic_number = dir_magic;
1853 dir_array.RemoveAt(j);
1854 dir_array.Insert(dir_info, j);
1855
1856 m_chartDirs.Add(dir_info.fullpath);
1857 } // for
1858
1859 // Special case, if chart dir list is truly empty
1860 if (m_chartDirs.IsEmpty() || !m_jobsRemaining) {
1861 if (!m_deferred_ticket_vector.size()) {
1862 FinalizeChartUpdate();
1863 return true;
1864 } else {
1865 auto *evt =
1866 new OCPN_ChartTableEntryThreadEvent(wxEVT_OCPN_CHARTTABLEENTRYTHREAD);
1867 auto ticket_deferred = m_deferred_ticket_vector.back();
1868 ticket_deferred->m_ticket_type = 1; // Mark as a dummy ticket.;
1869 // to trigger an event
1870 m_jobsRemaining = 1;
1871 evt->SetTicket(ticket_deferred);
1872 wxQueueEvent(this, evt);
1873 }
1874 }
1875
1876 // Initialize progress dialog
1877 m_progcount = 0;
1878 m_progint = 0;
1879 m_ticketcount = m_jobsRemaining;
1880 m_nFileProgressQuantum = wxMax(m_ticketcount / 10, 2);
1881 if (pprog) pprog->Update(0, _("Processing charts."));
1882
1883 // Start up the queued threads, if necessary
1884 if (m_jobsRemaining) {
1885 const int workerCount = 4;
1886 if (m_pool.GetWorkerCount() < workerCount) {
1887 int threads_needed = workerCount - m_pool.GetWorkerCount();
1888 for (int i = 0; i < threads_needed; ++i) {
1889 (new PoolWorkerThread(m_pool, this))->Run();
1890 m_pool.AddWorker();
1891 }
1892 }
1893 }
1894
1895 return true;
1896}
1897
1898//-------------------------------------------------------------------
1899// Find Chart dbIndex
1900//-------------------------------------------------------------------
1901
1902int ChartDatabase::FinddbIndex(wxString PathToFind) {
1903 if (active_chartTable_pathindex.find(PathToFind) !=
1904 active_chartTable_pathindex.end())
1905 return active_chartTable_pathindex[PathToFind];
1906
1907 return -1;
1908}
1909
1910//-------------------------------------------------------------------
1911// Disable Chart
1912//-------------------------------------------------------------------
1913
1914int ChartDatabase::DisableChart(wxString &PathToDisable) {
1915 int index = FinddbIndex(PathToDisable);
1916 if (index != -1) {
1917 auto &entry = GetChartTableEntry(index);
1918 entry.Disable();
1919 return 1;
1920 }
1921 return 0;
1922}
1923
1924// ----------------------------------------------------------------------------
1925// Traverse the given directory looking for charts
1926// If bupdate is true, also search the existing database for a name match.
1927// If target chart is already in database, mark the entry valid and skip
1928// additional processing
1929// ----------------------------------------------------------------------------
1930
1931int ChartDatabase::TraverseDirAndAddCharts(ChartDirInfo &dir_info,
1932 wxGenericProgressDialog *pprog,
1933 wxString &dir_magic, bool bForce) {
1934 // Extract the true dir name and magic number from the compound string
1935 wxString dir_path = dir_info.fullpath;
1936#ifdef __ANDROID__
1937 dir_path = wxString(dir_info.fullpath.mb_str(wxConvUTF8));
1938#endif
1939
1940 wxString old_magic = dir_info.magic_number;
1941 wxString new_magic = old_magic;
1942 dir_magic = old_magic; // provisionally the same
1943
1944 int nAdd = 0;
1945
1946 bool b_skipDetectDirChange = false;
1947 bool b_dirchange = false;
1948
1949 // Does this directory actually exist?
1950 if (!wxDir::Exists(dir_path)) return 0;
1951
1952 // Check to see if this is a cm93 directory root
1953 // If so, skip the DetectDirChange since it may be very slow
1954 // and give no information
1955 // Assume a change has happened, and process accordingly
1956 bool b_cm93 = Check_CM93_Structure(dir_path);
1957 if (b_cm93) {
1958 b_skipDetectDirChange = true;
1959 b_dirchange = true;
1960 }
1961
1962 // Quick scan the directory to see if it has changed
1963 // If not, there is no need to scan again.....
1964 if (!b_skipDetectDirChange)
1965 b_dirchange = DetectDirChange(dir_path, dir_info.fullpath, old_magic,
1966 new_magic, pprog);
1967
1968 if (!bForce && !b_dirchange) {
1969 wxString msg(" No change detected on directory ");
1970 msg.Append(dir_path);
1971 wxLogMessage(msg);
1972
1973 // Traverse the database, and mark as valid all charts coming from this
1974 // dir, or anywhere in its tree
1975
1976 wxFileName fn_dir(dir_path, "stuff");
1977 unsigned int dir_path_count = fn_dir.GetDirCount();
1978
1979 if (pprog) pprog->SetTitle(_("OpenCPN Chart Scan...."));
1980
1981 int nEntries = active_chartTable.size();
1982
1983 for (int ic = 0; ic < nEntries; ic++) {
1984 auto &cte = GetChartTableEntry(ic);
1985 wxFileName fn(cte.GetFullSystemPath());
1986
1987 while (fn.GetDirCount() >= dir_path_count) {
1988 if (fn.GetPath() == dir_path) {
1989 auto &cte_a = GetChartTableEntry(ic);
1990 cte_a.SetValid(true);
1991 // if(pprog)
1992 // pprog->Update((ic * 100)
1993 // /nEntries, fn.GetFullPath());
1994
1995 break;
1996 }
1997 fn.RemoveLastDir();
1998 }
1999 }
2000
2001 return 0;
2002 }
2003
2004 // There presumably was a change in the directory contents. Return the new
2005 // magic number
2006 dir_magic = new_magic;
2007
2008 // Look for all possible defined chart classes
2009 for (auto &cd : m_ChartClassDescriptorArray) {
2010 nAdd += SearchDirAndAddCharts(dir_info.fullpath, cd, pprog);
2011 }
2012
2013 return nAdd;
2014}
2015
2016bool ChartDatabase::DetectDirChange(const wxString &dir_path,
2017 const wxString &prog_label,
2018 const wxString &magic, wxString &new_magic,
2019 wxGenericProgressDialog *pprog) {
2020 if (pprog) pprog->SetTitle(_("OpenCPN Directory Scan...."));
2021
2022 // parse the magic number
2023 long long unsigned int nmagic;
2024 wxULongLong nacc = 0;
2025
2026 magic.ToULongLong(&nmagic, 10);
2027
2028 // Get an arraystring of all files
2029 wxArrayString FileList;
2030 wxDir dir(dir_path);
2031 int n_files = dir.GetAllFiles(dir_path, &FileList);
2032 FileList.Sort(); // Ensure persistent order of items being hashed.
2033
2034 FlexHash hash(sizeof nacc);
2035 hash.Reset();
2036
2037 if (pprog) pprog->Update(0, prog_label);
2038
2039 // Traverse the list of files, getting their interesting stuff to add to
2040 // accumulator
2041 for (int ifile = 0; ifile < n_files; ifile++) {
2042 wxFileName file(FileList[ifile]);
2043
2044 // NOTE. Do not ever try to optimize this code by combining `wxString`
2045 // calls. Otherwise `fileNameUTF8` will point to a stale buffer overwritten
2046 // by garbage.
2047 wxString fileNameNative = file.GetFullPath();
2048 wxScopedCharBuffer fileNameUTF8 = fileNameNative.ToUTF8();
2049 hash.Update(fileNameUTF8.data(), fileNameUTF8.length());
2050
2051 // File Size;
2052 wxULongLong size = file.GetSize();
2053 wxULongLong fileSize = ((size != wxInvalidSize) ? size : 0);
2054 hash.Update(&fileSize, (sizeof fileSize));
2055
2056 // Mod time, in ticks
2057 wxDateTime t = file.GetModificationTime();
2058 wxULongLong fileTime = t.GetTicks();
2059 hash.Update(&fileTime, (sizeof fileTime));
2060 }
2061
2062 hash.Finish();
2063 hash.Receive(&nacc);
2064
2065 // Return the calculated magic number
2066 new_magic = nacc.ToString();
2067
2068 // And do the test
2069 if (new_magic != magic)
2070 return true;
2071 else
2072 return false;
2073}
2074
2075bool ChartDatabase::IsChartDirUsed(const wxString &theDir) {
2076 wxString dir(theDir);
2077 if (dir.Last() == '/' || dir.Last() == wxFileName::GetPathSeparator())
2078 dir.RemoveLast();
2079
2080 dir.Append("*");
2081 for (UINT32 i = 0; i < active_chartTable.size(); i++) {
2082 auto &cte_u = GetChartTableEntry(i);
2083 if (cte_u.GetpsFullPath()->Matches(dir)) return true;
2084 }
2085 return false;
2086}
2087
2088//-----------------------------------------------------------------------------
2089// Validate a given directory as a cm93 root database
2090// If it appears to be a cm93 database, then return true
2091//-----------------------------------------------------------------------------
2092bool ChartDatabase::Check_CM93_Structure(wxString dir_name) {
2093 wxString filespec;
2094
2095 wxRegEx test("[0-9]+");
2096
2097 wxDir dirt(dir_name);
2098 wxString candidate;
2099
2100 if (dirt.IsOpened())
2101 wxLogMessage("check_cm93 opened dir OK: " + dir_name);
2102 else {
2103 wxLogMessage("check_cm93 NOT OPENED OK: " + dir_name);
2104 wxLogMessage("check_cm93 returns false." + dir_name);
2105 return false;
2106 }
2107
2108 bool b_maybe_found_cm93 = false;
2109 bool b_cont = dirt.GetFirst(&candidate);
2110
2111 while (b_cont) {
2112 if (test.Matches(candidate) && (candidate.Len() == 8)) {
2113 b_maybe_found_cm93 = true;
2114 break;
2115 }
2116
2117 b_cont = dirt.GetNext(&candidate);
2118 }
2119
2120 if (b_maybe_found_cm93) {
2121 wxString dir_next = dir_name;
2122 dir_next += "/";
2123 dir_next += candidate;
2124 if (wxDir::Exists(dir_next)) {
2125 wxDir dir_n(dir_next);
2126 if (dirt.IsOpened()) {
2127 wxString candidate_n;
2128
2129 wxRegEx test_n("^[A-Ga-g]");
2130 bool b_probably_found_cm93 = false;
2131 bool b_cont_n = dir_n.IsOpened() && dir_n.GetFirst(&candidate_n);
2132 while (b_cont_n) {
2133 if (test_n.Matches(candidate_n) && (candidate_n.Len() == 1)) {
2134 b_probably_found_cm93 = true;
2135 break;
2136 }
2137 b_cont_n = dir_n.GetNext(&candidate_n);
2138 }
2139
2140 if (b_probably_found_cm93) // found a directory that looks
2141 // like {dir_name}/12345678/A
2142 // probably cm93
2143 {
2144 // make sure the dir exists
2145 wxString dir_luk = dir_next;
2146 dir_luk += "/";
2147 dir_luk += candidate_n;
2148 if (wxDir::Exists(dir_luk)) return true;
2149 }
2150 }
2151 }
2152 }
2153
2154 return false;
2155}
2156
2157/*
2158//-----------------------------------------------------------------------------
2159// Validate a given directory as a cm93 root database
2160// If it appears to be a cm93 database, then return the name of an existing cell
2161file
2162// File name will be unique with respect to member element m_cm93_filename_array
2163// If not cm93, return empty string
2164//-----------------------------------------------------------------------------
2165wxString ChartDatabase::Get_CM93_FileName(wxString dir_name)
2166{
2167 wxString filespec;
2168
2169 wxRegEx test("[0-9]+");
2170
2171 wxDir dirt(dir_name);
2172 wxString candidate;
2173
2174 bool b_maybe_found_cm93 = false;
2175 bool b_cont = dirt.GetFirst(&candidate);
2176
2177 while(b_cont)
2178 {
2179 if(test.Matches(candidate)&& (candidate.Len() == 8))
2180 {
2181 b_maybe_found_cm93 = true;
2182 break;
2183 }
2184
2185 b_cont = dirt.GetNext(&candidate);
2186
2187 }
2188
2189 if(b_maybe_found_cm93)
2190 {
2191 wxString dir_next = dir_name;
2192 dir_next += "/";
2193 dir_next += candidate;
2194 if(wxDir::Exists(dir_next))
2195 {
2196 wxDir dir_n(dir_next);
2197 wxString candidate_n;
2198
2199 wxRegEx test_n("^[A-Ga-g]");
2200 bool b_probably_found_cm93 = false;
2201 bool b_cont_n = dir_n.GetFirst(&candidate_n);
2202 while(b_cont_n)
2203 {
2204 if(test_n.Matches(candidate_n) && (candidate_n.Len() ==
22051))
2206 {
2207 b_probably_found_cm93 = true;
2208 break;
2209 }
2210 b_cont_n = dir_n.GetNext(&candidate_n);
2211 }
2212
2213 if(b_probably_found_cm93) // found a directory that
2214looks like {dir_name}/12345678/A probably cm93 { // and we want to try and
2215shorten the recursive search
2216 // make sure the dir exists
2217 wxString dir_luk = dir_next;
2218 dir_luk += "/";
2219 dir_luk += candidate_n;
2220 if(wxDir::Exists(dir_luk))
2221 {
2222 wxString msg("Found probable CM93 database in
2223"); msg += dir_name; wxLogMessage(msg);
2224
2225 wxString dir_name_plus = dir_luk; // be very
2226specific about the dir_name,
2227
2228 wxDir dir_get(dir_name_plus);
2229 wxString one_file;
2230 dir_get.GetFirst(&one_file);
2231
2232 // We must return a unique file name, i.e. one
2233that has not bee seen
2234 // before in this invocation of chart dir
2235scans. bool find_unique = false; while(!find_unique)
2236 {
2237 find_unique = true;
2238 for(unsigned int ifile=0; ifile <
2239m_cm93_filename_array.GetCount(); ifile++)
2240 {
2241 if(m_cm93_filename_array[ifile] ==
2242one_file) find_unique = false;
2243 }
2244 if(!find_unique)
2245 dir_get.GetNext(&one_file);
2246 }
2247
2248 m_cm93_filename_array.Add(one_file);
2249
2250 filespec = one_file;
2251 }
2252
2253 }
2254 }
2255 }
2256
2257 return filespec;
2258}
2259*/
2260
2261int ChartDatabase::SearchDirAndAddCharts(wxString &dir_name_base,
2262 ChartClassDescriptor &chart_desc,
2263 wxGenericProgressDialog *pprog) {
2264 wxString msg("Searching directory: ");
2265 msg += dir_name_base;
2266 msg += " for ";
2267 msg += chart_desc.m_search_mask;
2268 wxLogMessage(msg);
2269
2270 wxString dir_name = dir_name_base;
2271
2272#ifdef __ANDROID__
2273 dir_name = wxString(dir_name_base.mb_str(wxConvUTF8)); // android
2274#endif
2275
2276 if (!wxDir::Exists(dir_name)) return 0;
2277
2278 wxString filespec = chart_desc.m_search_mask.Upper();
2279 wxString lowerFileSpec = chart_desc.m_search_mask.Lower();
2280 wxString filespecXZ = filespec + ".xz";
2281 wxString lowerFileSpecXZ = lowerFileSpec + ".xz";
2282 wxString filename;
2283
2284 // Count the files
2285 wxArrayString FileList;
2286 int gaf_flags = wxDIR_DEFAULT; // as default, recurse into subdirs
2287
2288 // Here is an optimization for MSW/cm93 especially
2289 // If this directory seems to be a cm93, and we are not explicitely looking
2290 // for cm93, then abort Otherwise, we will be looking thru entire cm93 tree
2291 // for non-existent .KAP files, etc.
2292
2293 bool b_found_cm93 = false;
2294 bool b_cm93 = Check_CM93_Structure(dir_name);
2295 if (b_cm93) {
2296 if (filespec != "00300000.A")
2297 return false;
2298 else {
2299 filespec = dir_name;
2300 b_found_cm93 = true;
2301 }
2302 }
2303
2304 if (!b_found_cm93) {
2305 wxDir dir(dir_name);
2306 dir.GetAllFiles(dir_name, &FileList, filespec, gaf_flags);
2307
2308#ifdef __ANDROID__
2309 if (!FileList.GetCount()) {
2310 wxArrayString afl = androidTraverseDir(dir_name, filespec);
2311 for (wxArrayString::const_iterator item = afl.begin(); item != afl.end();
2312 item++)
2313 FileList.Add(*item);
2314 }
2315#endif
2316
2317#ifndef __WXMSW__
2318 if (filespec != lowerFileSpec) {
2319 // add lowercase filespec files too
2320 wxArrayString lowerFileList;
2321 dir.GetAllFiles(dir_name, &lowerFileList, lowerFileSpec, gaf_flags);
2322
2323#ifdef __ANDROID__
2324 if (!lowerFileList.GetCount()) {
2325 wxArrayString afl = androidTraverseDir(dir_name, lowerFileSpec);
2326 for (wxArrayString::const_iterator item = afl.begin();
2327 item != afl.end(); item++)
2328 lowerFileList.Add(*item);
2329 }
2330#endif
2331
2332 for (wxArrayString::const_iterator item = lowerFileList.begin();
2333 item != lowerFileList.end(); item++)
2334 FileList.Add(*item);
2335 }
2336#endif
2337
2338#ifdef OCPN_USE_LZMA
2339 // add xz compressed files;
2340 dir.GetAllFiles(dir_name, &FileList, filespecXZ, gaf_flags);
2341 dir.GetAllFiles(dir_name, &FileList, lowerFileSpecXZ, gaf_flags);
2342#endif
2343
2344 FileList.Sort(); // Sorted processing order makes the progress bar more
2345 // meaningful to the user.
2346 } else { // This is a cm93 dataset, specified as yada/yada/cm93
2347 wxString dir_plus = dir_name;
2348 dir_plus += wxFileName::GetPathSeparator();
2349 FileList.Add(dir_plus);
2350 }
2351
2352 int nFile = FileList.GetCount();
2353
2354 if (!nFile) return false;
2355
2356 int nDirEntry = 0;
2357
2358 // Check to see if there are any charts in the DB which refer to this
2359 // directory If none at all, there is no need to scan the DB for fullpath
2360 // match of each potential addition and bthis_dir_in_dB is false.
2361 // bool bthis_dir_in_dB = IsChartDirUsed(dir_name);
2362
2363 if (pprog) pprog->SetTitle(_("OpenCPN Chart Add...."));
2364
2365 // build a hash table based on filename (without directory prefix) of
2366 // the chart to fast detect identical charts
2367 ChartCollisionsHashMap collision_map;
2368 // int nEntry = active_chartTable.GetCount();
2369 // for (int i = 0; i < nEntry; i++) {
2370 // wxString table_file_name = active_chartTable[i].GetFullSystemPath();
2371 // wxFileName table_file(table_file_name);
2372 // collision_map[table_file.GetFullName()] = i;
2373 // }
2374
2375 // Capture a vector of pending thread tickets for this directory
2376 std::vector<std::shared_ptr<ChartTableEntryJobTicket>> ticket_vector;
2377
2378 for (int ifile = 0; ifile < nFile; ifile++) {
2379 wxFileName file(FileList[ifile]);
2380 wxString full_path = file.GetFullPath();
2381 wxString file_name = file.GetFullName();
2382 wxString utf8_path = full_path;
2383
2384#ifdef __ANDROID__
2385 // The full path (full_name) is the broken Android files system
2386 // interpretation, which does not display well onscreen. So, here we
2387 // reconstruct a full path spec in UTF-8 encoding for later use in string
2388 // displays. This utf-8 string will be used to construct the chart database
2389 // entry if required.
2390 wxFileName fnbase(dir_name_base);
2391 int nDirs = fnbase.GetDirCount();
2392
2393 wxFileName file_target(FileList[ifile]);
2394
2395 for (int i = 0; i < nDirs + 1;
2396 i++) // strip off the erroneous intial directories
2397 file_target.RemoveDir(0);
2398
2399 wxString leftover_path = file_target.GetFullPath();
2400 utf8_path =
2401 dir_name_base + leftover_path; // reconstruct a fully utf-8 version
2402#endif
2403
2404 // Validate the file name again, considering MSW's semi-random treatment
2405 // of case....
2406 // TODO...something fishy here - may need to normalize saved name?
2407 if (!file_name.Matches(lowerFileSpec) && !file_name.Matches(filespec) &&
2408 !file_name.Matches(lowerFileSpecXZ) && !file_name.Matches(filespecXZ) &&
2409 !b_found_cm93) {
2410 // wxLogMessage("FileSpec test failed for:" + file_name);
2411 continue;
2412 }
2413
2414 ChartTableEntry *pnewChart = NULL;
2415 bool bAddFinal = true;
2416 int b_add_msg = 0;
2417
2418#if 0 // TODO Fix?
2419 // Check the collisions map looking for duplicates in directories already
2420 // processed, and choosing the right one.
2421// ChartCollisionsHashMap::const_iterator collision_ptr =
2422// collision_map.find(file_name);
2423// bool collision = (collision_ptr != collision_map.end());
2424// bool file_path_is_same = false;
2425// bool file_time_is_same = false;
2426// ChartTableEntry *pEntry = NULL;
2427// wxString table_file_name;
2428
2429
2430 // Allow multiple cm93 chart sets #4217
2431 if (b_found_cm93) collision = false;
2432
2433 if (collision) {
2434 pEntry = &active_chartTable[collision_ptr->second];
2435 table_file_name = pEntry->GetFullSystemPath();
2436 file_path_is_same =
2437 bthis_dir_in_dB && full_name.IsSameAs(table_file_name);
2438
2439 // If the chart full file paths are exactly the same, select the newer
2440 // one.
2441 if (file_path_is_same) {
2442 b_add_msg++;
2443
2444 // Check the file modification time
2445 time_t t_oldFile = pEntry->GetFileTime();
2446 time_t t_newFile = file.GetModificationTime().GetTicks();
2447
2448 if (t_newFile <= t_oldFile) {
2449 file_time_is_same = true;
2450 bAddFinal = false;
2451 pEntry->SetValid(true);
2452 } else {
2453 bAddFinal = true;
2454 pEntry->SetValid(false);
2455 }
2456 }
2457 }
2458#endif
2459
2460 // Check for duplicates within this directory
2461 bool collision_found = false;
2462 ChartCollisionsHashMap::iterator it;
2463 for (it = collision_map.begin(); it != collision_map.end(); ++it) {
2464 if (it->first.IsSameAs(file_name)) {
2465 // Two files found with identical file name
2466 // For now, just drop this ticket
2467 // TODO Make an (expensive) test on file modification times
2468 collision_found = true;
2469 break;
2470 }
2471 }
2472
2473 if (!collision_found) {
2474 // Create a ticket for this chart
2475 auto ticket = std::make_shared<ChartTableEntryJobTicket>();
2476 ticket->m_ChartPath = full_path;
2477 ticket->m_ChartPathUTF8 = full_path;
2478 ticket->chart_desc = chart_desc;
2479
2480 ticket_vector.push_back(ticket);
2481 collision_map[file_name] = ifile;
2482 }
2483
2484 } // the big loop
2485
2486 // Built-in chart types are all thread-safe
2487 // Check plugin charts
2488 bool is_kap = false; // chart_desc.m_class_name.IsSameAs("ChartKAP");
2489 if (chart_desc.m_descriptor_type == PLUGIN_DESCRIPTOR || is_kap) {
2490 // Check plugin charts API. API >- 118 are known to be thread-safe
2491 opencpn_plugin *plugin = chart_desc.m_plugin;
2492 opencpn_plugin_118 *provider_plugin118 = dynamic_cast<opencpn_plugin_118 *>(
2493 dynamic_cast<opencpn_plugin *>(plugin));
2494
2495 if (!provider_plugin118 || is_kap) {
2496 // old plugin, charts not thread-safe
2497 // So arrange to process the tickets in the main app thread,
2498 // during the event handler, at the end of the queue processing
2499 for (auto &ticket : ticket_vector) {
2500 ticket->b_thread_safe = false;
2501 ticket->m_provider_type = 1;
2502 ticket->provider_class_name = chart_desc.m_class_name;
2503 m_deferred_ticket_vector.push_back(ticket);
2504 }
2505 return nDirEntry;
2506 }
2507 }
2508
2509 // Chart directory is known thread-safe
2510 // load the thread pool from the prepared array
2511 // Enqueue jobs
2512 for (auto &ticket : ticket_vector) {
2513 m_pool.Push(ticket);
2514 m_jobsRemaining++;
2515 }
2516
2517 // Tickets queued, wait for completion events
2518 return nDirEntry;
2519}
2520
2521bool ChartDatabase::AddChart(wxString &chartfilename,
2522 ChartClassDescriptor &chart_desc,
2523 wxGenericProgressDialog *pprog, int isearch,
2524 bool bthis_dir_in_dB) {
2525 bool rv = false;
2526 wxFileName file(chartfilename);
2527 wxString full_name = file.GetFullPath();
2528 wxString file_name = file.GetFullName();
2529
2530 // Validate the file name again, considering MSW's semi-random treatment of
2531 // case....
2532 // TODO...something fishy here - may need to normalize saved name?
2533 // if(!file_name.Matches(lowerFileSpec) && !file_name.Matches(filespec) &&
2534 // !b_found_cm93)
2535 // continue;
2536
2537 if (pprog)
2538 pprog->Update(wxMin((m_pdifile * 100) / m_pdnFile, 100), full_name);
2539
2540 ChartTableEntry *pnewChart = NULL;
2541 bool bAddFinal = true;
2542 int b_add_msg = 0;
2543 wxString msg_fn(full_name);
2544 msg_fn.Replace("%", "%%");
2545
2546 pnewChart = CreateChartTableEntry(full_name, full_name, chart_desc);
2547 if (!pnewChart) {
2548 bAddFinal = false;
2549 wxLogMessage(wxString::Format(
2550 " CreateChartTableEntry() failed for file: %s", msg_fn.c_str()));
2551 return false;
2552 } else // traverse the existing database looking for duplicates, and choosing
2553 // the right one
2554 {
2555 int nEntry = active_chartTable.size();
2556 for (int i = 0; i < nEntry; i++) {
2557 auto &cte_a = GetChartTableEntry(i);
2558 wxString *ptable_file_name = cte_a.GetpsFullPath();
2559
2560 // If the chart full file paths are exactly the same, select the newer
2561 // one
2562 if (bthis_dir_in_dB && full_name.IsSameAs(*ptable_file_name)) {
2563 b_add_msg++;
2564
2565 // Check the file modification time
2566 auto &cte_search = GetChartTableEntry(isearch);
2567 time_t t_oldFile = cte_search.GetFileTime();
2568 time_t t_newFile = file.GetModificationTime().GetTicks();
2569
2570 if (t_newFile <= t_oldFile) {
2571 bAddFinal = false;
2572 cte_search.SetValid(true);
2573 } else {
2574 bAddFinal = true;
2575 cte_search.SetValid(false);
2576 wxLogMessage(
2577 wxString::Format(" Replacing older chart file of same path: %s",
2578 msg_fn.c_str()));
2579 }
2580
2581 break;
2582 }
2583
2584 // Look at the chart file name (without directory prefix) for a further
2585 // check for duplicates This catches the case in which the "same" chart
2586 // is in different locations, and one may be newer than the other.
2587 wxFileName table_file(*ptable_file_name);
2588
2589 if (table_file.GetFullName() == file_name) {
2590 b_add_msg++;
2591
2592 // TODO fix this...
2593#if 0
2594 if (pnewChart->IsEarlierThan(active_chartTable[isearch])) {
2595 // Make sure the compare file actually exists
2596 if (table_file.IsFileReadable()) {
2597 active_chartTable[isearch].SetValid(true);
2598 bAddFinal = false;
2599 wxLogMessage(wxString::Format(
2600 " Retaining newer chart file of same name: %s",
2601 msg_fn.c_str()));
2602 }
2603 } else if (pnewChart->IsEqualTo(active_chartTable[isearch])) {
2604 // The file names (without dir prefix) are identical,
2605 // and the mod times are identical
2606 // Prsume that this is intentional, in order to facilitate
2607 // having the same chart in multiple groups.
2608 // So, add this chart.
2609 bAddFinal = true;
2610 }
2611
2612 else {
2613 active_chartTable[isearch].SetValid(false);
2614 bAddFinal = true;
2615 wxLogMessage(
2616 wxString::Format(" Replacing older chart file of same name: %s",
2617 msg_fn.c_str()));
2618 }
2619#endif
2620 break;
2621 }
2622
2623 // TODO Look at the chart ID as a further check against duplicates
2624
2625 isearch++;
2626 if (nEntry == isearch) isearch = 0;
2627 } // for
2628 }
2629
2630 if (bAddFinal) {
2631 if (0 == b_add_msg) {
2632 wxLogMessage(
2633 wxString::Format(" Adding chart file: %s", msg_fn.c_str()));
2634 }
2635 std::shared_ptr<ChartTableEntry> sharedPtr(pnewChart);
2636 active_chartTable.push_back(sharedPtr);
2637 rv = true;
2638 } else {
2639 delete pnewChart;
2640 // wxLogMessage(wxString::Format(" Not adding chart
2641 // file: %s", msg_fn.c_str()));
2642 rv = false;
2643 }
2644
2645 m_nentries = active_chartTable.size();
2646
2647 return rv;
2648}
2649
2650bool ChartDatabase::AddSingleChart(wxString &ChartFullPath,
2651 bool b_force_full_search) {
2652 // Find a relevant chart class descriptor
2653 wxFileName fn(ChartFullPath);
2654 wxString ext = fn.GetExt();
2655 ext.Prepend("*.");
2656 wxString ext_upper = ext.MakeUpper();
2657 wxString ext_lower = ext.MakeLower();
2658 wxString dir_name = fn.GetPath();
2659
2660 // Search the array of chart class descriptors to find a match
2661 // between the search mask and the chart file extension
2662
2664 for (auto &cd : m_ChartClassDescriptorArray) {
2665 if (cd.m_descriptor_type == PLUGIN_DESCRIPTOR) {
2666 if (cd.m_search_mask == ext_upper) {
2667 desc = cd;
2668 break;
2669 }
2670 if (cd.m_search_mask == ext_lower) {
2671 desc = cd;
2672 break;
2673 }
2674 }
2675 }
2676
2677 // If we know that we need to do a full recursive search of the db,
2678 // then there is no need to verify it by doing a directory match
2679 bool b_recurse = true;
2680 if (!b_force_full_search) b_recurse = IsChartDirUsed(dir_name);
2681
2682 bool rv = AddChart(ChartFullPath, desc, NULL, 0, b_recurse);
2683
2684 // remove duplicates marked in AddChart()
2685
2686 for (unsigned int i = 0; i < active_chartTable.size(); i++) {
2687 auto &cte_r = GetChartTableEntry(i);
2688 if (!cte_r.GetbValid()) {
2689 // TODO fix this
2690 // active_chartTable.RemoveAt(i);
2691 i--; // entry is gone, recheck this index for next entry
2692 }
2693 }
2694
2695 // Update the Entry index fields
2696 for (unsigned int i = 0; i < active_chartTable.size(); i++) {
2697 auto &cte_ef = GetChartTableEntry(i);
2698 cte_ef.SetEntryOffset(i);
2699 }
2700
2701 // Get a new magic number
2702 wxString new_magic;
2703 DetectDirChange(dir_name, "", "", new_magic, 0);
2704
2705 // Update (clone) the CDI array
2706 bool bcfound = false;
2707 ArrayOfCDI NewChartDirArray;
2708
2709 ArrayOfCDI ChartDirArray = GetChartDirArray();
2710 for (unsigned int i = 0; i < ChartDirArray.GetCount(); i++) {
2711 ChartDirInfo cdi = ChartDirArray[i];
2712
2713 ChartDirInfo newcdi = cdi;
2714
2715 // If entry is found that matches this cell, clear the magic number.
2716 if (newcdi.fullpath == dir_name) {
2717 newcdi.magic_number = new_magic;
2718 bcfound = true;
2719 }
2720
2721 NewChartDirArray.Add(newcdi);
2722 }
2723
2724 if (!bcfound) {
2725 ChartDirInfo cdi;
2726 cdi.fullpath = dir_name;
2727 cdi.magic_number = new_magic;
2728 NewChartDirArray.Add(cdi);
2729 }
2730
2731 // Update the database master copy of the CDI array
2732 SetChartDirArray(NewChartDirArray);
2733
2734 // Update the list of chart dirs.
2735 m_chartDirs.Clear();
2736
2737 for (unsigned int i = 0; i < GetChartDirArray().GetCount(); i++) {
2738 ChartDirInfo cdi = GetChartDirArray()[i];
2739 m_chartDirs.Add(cdi.fullpath);
2740 }
2741
2742 m_nentries = active_chartTable.size();
2743
2744 ChartData->UpdateChartDatabaseInplace(NewChartDirArray, false, nullptr);
2745 return rv;
2746}
2747
2748bool ChartDatabase::RemoveSingleChart(wxString &ChartFullPath) {
2749 bool rv = false;
2750
2751 // Walk the chart table, looking for the target
2752 for (unsigned int i = 0; i < active_chartTable.size(); i++) {
2753 auto &cte = GetChartTableEntry(i);
2754 if (ChartFullPath.IsSameAs(cte.GetFullSystemPath())) {
2755 // Fast remove element, order not preserved
2756 std::swap(active_chartTable[i], active_chartTable.back());
2757 active_chartTable.pop_back();
2758 break;
2759 }
2760 }
2761
2762 // Update the EntryOffset fields for the array
2763 for (unsigned int i = 0; i < active_chartTable.size(); i++) {
2764 auto &pcte = GetChartTableEntry(i);
2765 pcte.SetEntryOffset(i);
2766 }
2767
2768 // Check and update the dir array
2769 wxFileName fn(ChartFullPath);
2770 wxString fd = fn.GetPath();
2771 if (!IsChartDirUsed(fd)) {
2772 // Clone a new array, removing the unused directory,
2773 ArrayOfCDI NewChartDirArray;
2774
2775 ArrayOfCDI ChartDirArray = GetChartDirArray();
2776 for (unsigned int i = 0; i < ChartDirArray.GetCount(); i++) {
2777 ChartDirInfo cdi = ChartDirArray[i];
2778
2779 ChartDirInfo newcdi = cdi;
2780
2781 if (newcdi.fullpath != fd) NewChartDirArray.Add(newcdi);
2782 }
2783
2784 SetChartDirArray(NewChartDirArray);
2785 }
2786
2787 // Update the list of chart dirs.
2788 m_chartDirs.Clear();
2789 for (unsigned int i = 0; i < GetChartDirArray().GetCount(); i++) {
2790 ChartDirInfo cdi = GetChartDirArray()[i];
2791 m_chartDirs.Add(cdi.fullpath);
2792 }
2793
2794 m_nentries = active_chartTable.size();
2795 ChartData->UpdateChartDatabaseInplace(m_dir_array, false, nullptr);
2796
2797 return rv;
2798}
2799
2801// Create a Chart object
2803
2804ChartBase *ChartDatabase::GetChart(const wxChar *theFilePath,
2805 ChartClassDescriptor &chart_desc) const {
2806 // TODO: support non-UI chart factory
2807 return NULL;
2808}
2809
2811// Create Chart Table entry by reading chart header info, etc.
2813
2814ChartTableEntry *ChartDatabase::CreateChartTableEntry(
2815 const wxString &filePath, wxString &utf8Path,
2816 ChartClassDescriptor &chart_desc) {
2817 wxString msg_fn(filePath);
2818 msg_fn.Replace("%", "%%");
2819 wxLogMessage(wxString::Format("Loading chart data for %s", msg_fn.c_str()));
2820
2821 ChartBase *pch = GetChart(filePath, chart_desc);
2822 if (pch == NULL) {
2823 wxLogMessage(
2824 wxString::Format(" ...creation failed for %s", msg_fn.c_str()));
2825 return NULL;
2826 }
2827
2828 InitReturn rc = pch->Init(filePath, HEADER_ONLY);
2829 if (rc != INIT_OK) {
2830 delete pch;
2831 wxLogMessage(
2832 wxString::Format(" ...initialization failed for %s", msg_fn.c_str()));
2833 return NULL;
2834 }
2835
2836 ChartTableEntry *ret_val = new ChartTableEntry(*pch, utf8Path);
2837 ret_val->SetValid(true);
2838
2839 delete pch;
2840
2841 return ret_val;
2842}
2843
2844bool ChartDatabase::GetCentroidOfLargestScaleChart(double *clat, double *clon,
2845 ChartFamilyEnum family) {
2846 int cur_max_i = -1;
2847 int cur_max_scale = 0;
2848
2849 int nEntry = active_chartTable.size();
2850
2851 for (int i = 0; i < nEntry; i++) {
2852 auto &cte_fam = GetChartTableEntry(i);
2853 if (GetChartFamily(cte_fam.GetChartType()) == family) {
2854 if (cte_fam.GetScale() > cur_max_scale) {
2855 cur_max_scale = cte_fam.GetScale();
2856 cur_max_i = i;
2857 }
2858 }
2859 }
2860
2861 if (cur_max_i == -1)
2862 return false; // nothing found
2863 else {
2864 auto &cte_sel = GetChartTableEntry(cur_max_i);
2865 *clat = (cte_sel.GetLatMax() + cte_sel.GetLatMin()) / 2.;
2866 *clon = (cte_sel.GetLonMin() + cte_sel.GetLonMax()) / 2.;
2867 }
2868 return true;
2869}
2870
2871//-------------------------------------------------------------------
2872// Get DBChart Projection
2873//-------------------------------------------------------------------
2874int ChartDatabase::GetDBChartProj(int dbIndex) {
2875 if ((bValid) && (dbIndex >= 0) && (dbIndex < (int)active_chartTable.size())) {
2876 auto &cte = GetChartTableEntry(dbIndex);
2877 return cte.GetChartProjectionType();
2878 } else
2879 return PROJECTION_UNKNOWN;
2880}
2881
2882//-------------------------------------------------------------------
2883// Get DBChart Family
2884//-------------------------------------------------------------------
2885int ChartDatabase::GetDBChartFamily(int dbIndex) {
2886 if ((bValid) && (dbIndex >= 0) && (dbIndex < (int)active_chartTable.size())) {
2887 auto &cte = GetChartTableEntry(dbIndex);
2888 return cte.GetChartFamily();
2889 } else
2890 return CHART_FAMILY_UNKNOWN;
2891}
2892
2893//-------------------------------------------------------------------
2894// Get DBChart FullFileName
2895//-------------------------------------------------------------------
2896wxString ChartDatabase::GetDBChartFileName(int dbIndex) {
2897 if ((bValid) && (dbIndex >= 0) && (dbIndex < (int)active_chartTable.size())) {
2898 auto &cte = GetChartTableEntry(dbIndex);
2899 return wxString(cte.GetFullSystemPath());
2900 } else
2901 return "";
2902}
2903
2904//-------------------------------------------------------------------
2905// Get DBChart Type
2906//-------------------------------------------------------------------
2907int ChartDatabase::GetDBChartType(int dbIndex) {
2908 if ((bValid) && (dbIndex >= 0) && (dbIndex < (int)active_chartTable.size())) {
2909 auto &cte = GetChartTableEntry(dbIndex);
2910 return cte.GetChartType();
2911 } else
2912 return 0;
2913}
2914
2915//-------------------------------------------------------------------
2916// Get DBChart Skew
2917//-------------------------------------------------------------------
2918float ChartDatabase::GetDBChartSkew(int dbIndex) {
2919 if ((bValid) && (dbIndex >= 0) && (dbIndex < (int)active_chartTable.size())) {
2920 auto &cte = GetChartTableEntry(dbIndex);
2921 return cte.GetChartSkew();
2922 } else
2923 return 0.;
2924}
2925
2926//-------------------------------------------------------------------
2927// Get DBChart Scale
2928//-------------------------------------------------------------------
2929int ChartDatabase::GetDBChartScale(int dbIndex) {
2930 if ((bValid) && (dbIndex >= 0) && (dbIndex < (int)active_chartTable.size())) {
2931 auto &cte = GetChartTableEntry(dbIndex);
2932 return cte.GetScale();
2933 } else
2934 return 1;
2935}
2936
2937//-------------------------------------------------------------------
2938// Get Lat/Lon Bounding Box from db
2939//-------------------------------------------------------------------
2940bool ChartDatabase::GetDBBoundingBox(int dbIndex, LLBBox &box) {
2941 if ((bValid) && (dbIndex >= 0) && (dbIndex < (int)active_chartTable.size())) {
2942 auto &entry = GetChartTableEntry(dbIndex);
2943 box.Set(entry.GetLatMin(), entry.GetLonMin(), entry.GetLatMax(),
2944 entry.GetLonMax());
2945 }
2946
2947 return true;
2948}
2949
2950const LLBBox &ChartDatabase::GetDBBoundingBox(int dbIndex) {
2951 if ((bValid) && (dbIndex >= 0)) {
2952 auto &entry = GetChartTableEntry(dbIndex);
2953 return entry.GetBBox();
2954 } else {
2955 return m_dummy_bbox;
2956 }
2957}
2958
2959//-------------------------------------------------------------------
2960// Get PlyPoint from Database
2961//-------------------------------------------------------------------
2962int ChartDatabase::GetDBPlyPoint(int dbIndex, int plyindex, float *lat,
2963 float *lon) {
2964 if ((bValid) && (dbIndex >= 0) && (dbIndex < (int)active_chartTable.size())) {
2965 const ChartTableEntry &entry = GetChartTableEntry(dbIndex);
2966 if (entry.GetnPlyEntries()) {
2967 float *fp = entry.GetpPlyTable();
2968 fp += plyindex * 2;
2969 if (lat) *lat = *fp;
2970 fp++;
2971 if (lon) *lon = *fp;
2972 }
2973 return entry.GetnPlyEntries();
2974 } else
2975 return 0;
2976}
2977
2978//-------------------------------------------------------------------
2979// Get AuxPlyPoint from Database
2980//-------------------------------------------------------------------
2981int ChartDatabase::GetDBAuxPlyPoint(int dbIndex, int plyindex, int ply,
2982 float *lat, float *lon) {
2983 if ((bValid) && (dbIndex >= 0) && (dbIndex < (int)active_chartTable.size())) {
2984 const ChartTableEntry &entry = GetChartTableEntry(dbIndex);
2985 if (entry.GetnAuxPlyEntries()) {
2986 float *fp = entry.GetpAuxPlyTableEntry(ply);
2987
2988 fp += plyindex * 2;
2989 if (lat) *lat = *fp;
2990 fp++;
2991 if (lon) *lon = *fp;
2992 }
2993
2994 return entry.GetAuxCntTableEntry(ply);
2995 } else
2996 return 0;
2997}
2998
2999int ChartDatabase::GetnAuxPlyEntries(int dbIndex) {
3000 if ((bValid) && (dbIndex >= 0) && (dbIndex < (int)active_chartTable.size())) {
3001 const ChartTableEntry &entry = GetChartTableEntry(dbIndex);
3002 return entry.GetnAuxPlyEntries();
3003 } else
3004 return 0;
3005}
3006
3007//-------------------------------------------------------------------
3008// Get vector of reduced Plypoints
3009//-------------------------------------------------------------------
3010std::vector<float> ChartDatabase::GetReducedPlyPoints(int dbIndex) {
3011 if ((bValid) && (dbIndex >= 0) && (dbIndex < (int)active_chartTable.size())) {
3012 ChartTableEntry &cte = GetChartTableEntry(dbIndex);
3013 return cte.GetReducedPlyPoints();
3014 }
3015
3016 std::vector<float> dummy;
3017 return dummy;
3018}
3019
3020//-------------------------------------------------------------------
3021// Get vector of reduced AuxPlypoints
3022//-------------------------------------------------------------------
3023std::vector<float> ChartDatabase::GetReducedAuxPlyPoints(int dbIndex,
3024 int iTable) {
3025 if ((bValid) && (dbIndex >= 0) && (dbIndex < (int)active_chartTable.size())) {
3026 auto &cte = GetChartTableEntry(dbIndex);
3027 return cte.GetReducedAuxPlyPoints(iTable);
3028 }
3029
3030 std::vector<float> dummy;
3031 return dummy;
3032}
3033
3034bool ChartDatabase::IsChartAvailable(int dbIndex) {
3035 if ((bValid) && (dbIndex >= 0) && (dbIndex < (int)active_chartTable.size())) {
3036 auto &cte = GetChartTableEntry(dbIndex);
3037
3038 // If not PLugIn chart, assume always available
3039 if (cte.GetChartType() != CHART_TYPE_PLUGIN) return true;
3040
3041 wxString *path = cte.GetpsFullPath();
3042 wxFileName fn(*path);
3043 wxString ext = fn.GetExt();
3044 ext.Prepend("*.");
3045 wxString ext_upper = ext.MakeUpper();
3046 wxString ext_lower = ext.MakeLower();
3047
3048 // Search the array of chart class descriptors to find a match
3049 // between the search mask and the the chart file extension
3050
3051 for (auto &cd : m_ChartClassDescriptorArray) {
3052 if (cd.m_descriptor_type == PLUGIN_DESCRIPTOR) {
3053 wxString search_mask = cd.m_search_mask;
3054
3055 if (search_mask == ext_upper) {
3056 return true;
3057 }
3058 if (search_mask == ext_lower) {
3059 return true;
3060 }
3061 if (path->Matches(search_mask)) {
3062 return true;
3063 }
3064 }
3065 }
3066 }
3067
3068 return false;
3069}
3070
3071void ChartDatabase::ApplyGroupArray(ChartGroupArray *pGroupArray) {
3072 wxString separator(wxFileName::GetPathSeparator());
3073
3074 for (unsigned int ic = 0; ic < active_chartTable.size(); ic++) {
3075 auto &cte = GetChartTableEntry(ic);
3076
3077 cte.ClearGroupArray();
3078
3079 wxString *chart_full_path = cte.GetpsFullPath();
3080
3081 for (unsigned int igroup = 0; igroup < pGroupArray->GetCount(); igroup++) {
3082 ChartGroup *pGroup = pGroupArray->Item(igroup);
3083 for (const auto &elem : pGroup->m_element_array) {
3084 wxString element_root = elem.m_element_name;
3085
3086 // The element may be a full single chart name
3087 // If so, add it
3088 // Otherwise, append a sep character so that similar paths are
3089 // distinguished. See FS#1060
3090 if (!chart_full_path->IsSameAs(element_root))
3091 element_root.Append(
3092 separator); // Prevent comingling similar looking path names
3093 if (chart_full_path->StartsWith(element_root)) {
3094 bool b_add = true;
3095 for (unsigned int k = 0; k < elem.m_missing_name_array.size(); k++) {
3096 const wxString &missing_item = elem.m_missing_name_array[k];
3097 if (chart_full_path->StartsWith(missing_item)) {
3098 if (chart_full_path->IsSameAs(
3099 missing_item)) // missing item is full chart name
3100 {
3101 b_add = false;
3102 break;
3103 } else {
3104 if (wxDir::Exists(missing_item)) // missing item is a dir
3105 {
3106 b_add = false;
3107 break;
3108 }
3109 }
3110 }
3111 }
3112
3113 if (b_add) cte.AddIntToGroupArray(igroup + 1);
3114 }
3115 }
3116 }
3117 }
3118}
General chart base definitions.
ChartDB * ChartData
Global instance.
Definition chartdb.cpp:71
Define threaded chart database classes.
ChartGroupArray * g_pGroupArray
Global instance.
Definition chartdbs.cpp:61
Basic chart info storage.
ChartGroupArray * g_pGroupArray
Global instance.
Definition chartdbs.cpp:61
Base class for all chart types.
Definition chartbase.h:126
Manages a database of charts, including reading, writing, and querying chart information.
Definition chartdbs.h:304
bool Create(ArrayOfCDI &dir_array, wxGenericProgressDialog *pprog)
Creates a new chart database from a list of directories.
bool Update(ArrayOfCDI &dir_array, bool bForce, wxGenericProgressDialog *pprog)
Updates the chart database.
Represents a user-defined collection of logically related charts.
Definition chartdbs.h:485
Wrapper class for plugin-based charts.
Definition chartimg.h:389
void Notify() override
Notify all listeners, no data supplied.
Class for computing hash of arbitrary length.
Definition flex_hash.h:34
EventVar options_on_finalize_chartdbs
Notified when chartdbs async operations complete, to finalize settings.
Definition gui_events.h:74
EventVar on_finalize_chartdbs
Notified when chartdbs async operations complete, to reload charts.
Definition gui_events.h:71
Base class for OpenCPN plugins.
Hash of arbitrary length.
Platform independent GL includes.
Misc GUI event vars, a singleton.
Utility functions.
PlugInManager * g_pi_manager
Global instance.
PlugInManager and helper classes – Mostly gui parts (dialogs) and plugin API stuff.
ShapeBaseChartSet gShapeBasemap
global instance
Shapefile basemap.
Represents an entry in the chart table, containing information about a single chart.
Definition chartdbs.h:187