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 pFullPath = NULL;
880 pPlyTable = NULL;
881 pAuxPlyTable = NULL;
882 pAuxCntTable = NULL;
883 bValid = false;
884 ;
885 pNoCovrCntTable = NULL;
886 pNoCovrPlyTable = NULL;
887
888 nNoCovrPlyEntries = 0;
889 nAuxPlyEntries = 0;
890
891 m_pfilename = NULL; // a helper member, not on disk
892 m_psFullPath = NULL;
893 Scale = 1e8; // Very small scale
894}
895
897
898void ChartTableEntry::Disable() {
899 // Mark this chart in the database, so that it will not be seen during this
900 // run How? By setting the chart bounding box to an absurd value
901 // TODO... Fix this heinous hack
902 LatMax += (float)1000.;
903 LatMin += (float)1000.;
904}
905
906void ChartTableEntry::ReEnable() {
907 if (LatMax > 90.) {
908 LatMax -= (float)1000.;
909 LatMin -= (float)1000.;
910 }
911}
912bool ChartTableEntry::IsBasemap() const {
913 wxFileName fn(GetFullPath());
914 return (fn.GetPath().Lower().Contains("basemap"));
915}
916
917std::vector<float> ChartTableEntry::GetReducedPlyPoints() {
918 if (m_reducedPlyPoints.size()) return m_reducedPlyPoints;
919
920 // Reduce the LOD of the chart outline PlyPoints
921 float LOD_meters = 1;
922
923 float plylat, plylon;
924 const int nPoints = GetnPlyEntries();
925
926 float *fpo = GetpPlyTable();
927
928 double *ppd = new double[nPoints * 2];
929 double *ppsm = new double[nPoints * 2];
930 double *npr = ppd;
931 double *npsm = ppsm;
932 for (int i = 0; i < nPoints; i++) {
933 plylat = fpo[i * 2];
934 plylon = fpo[i * 2 + 1];
935
936 double x, y;
937 toSM(plylat, plylon, fpo[0], fpo[1], &x, &y);
938
939 *npr++ = plylon;
940 *npr++ = plylat;
941 *npsm++ = x;
942 *npsm++ = y;
943 }
944
945 std::vector<int> index_keep;
946 if (nPoints > 10) {
947 index_keep.push_back(0);
948 index_keep.push_back(nPoints - 1);
949 index_keep.push_back(1);
950 index_keep.push_back(nPoints - 2);
951
952 DouglasPeuckerM(ppsm, 1, nPoints - 2, LOD_meters, &index_keep);
953
954 } else {
955 index_keep.resize(nPoints);
956 for (int i = 0; i < nPoints; i++) index_keep[i] = i;
957 }
958
959 double *ppr = ppd;
960 for (int ip = 0; ip < nPoints; ip++) {
961 double x = *ppr++;
962 double y = *ppr++;
963
964 for (unsigned int j = 0; j < index_keep.size(); j++) {
965 if (index_keep[j] == ip) {
966 m_reducedPlyPoints.push_back(x);
967 m_reducedPlyPoints.push_back(y);
968 break;
969 }
970 }
971 }
972
973 delete[] ppd;
974 delete[] ppsm;
975
976 int nprr = m_reducedPlyPoints.size() / 2;
977
978 return m_reducedPlyPoints;
979}
980
981std::vector<float> ChartTableEntry::GetReducedAuxPlyPoints(int iTable) {
982 // Maybe need to initialize the vector
983 if (!m_reducedAuxPlyPointsVector.size()) {
984 std::vector<float> vec;
985 for (int i = 0; i < GetnAuxPlyEntries(); i++) {
986 m_reducedAuxPlyPointsVector.push_back(vec);
987 }
988 }
989
990 std::vector<float> vec;
991
992 // Invalid parameter
993 if ((unsigned int)iTable >= m_reducedAuxPlyPointsVector.size()) return vec;
994
995 if (m_reducedAuxPlyPointsVector.at(iTable).size())
996 return m_reducedAuxPlyPointsVector.at(iTable);
997
998 // Reduce the LOD of the chart outline PlyPoints
999 float LOD_meters = 1.0;
1000
1001 const int nPoints = GetAuxCntTableEntry(iTable);
1002 float *fpo = GetpAuxPlyTableEntry(iTable);
1003
1004 double *ppd = new double[nPoints * 2];
1005 double *ppsm = new double[nPoints * 2];
1006 double *npr = ppd;
1007 double *npsm = ppsm;
1008 float plylat, plylon;
1009
1010 for (int i = 0; i < nPoints; i++) {
1011 plylat = fpo[i * 2];
1012 plylon = fpo[i * 2 + 1];
1013
1014 double x, y;
1015 toSM(plylat, plylon, fpo[0], fpo[1], &x, &y);
1016
1017 *npr++ = plylon;
1018 *npr++ = plylat;
1019 *npsm++ = x;
1020 *npsm++ = y;
1021 }
1022
1023 std::vector<int> index_keep;
1024 if (nPoints > 10) {
1025 index_keep.push_back(0);
1026 index_keep.push_back(nPoints - 1);
1027 index_keep.push_back(1);
1028 index_keep.push_back(nPoints - 2);
1029
1030 DouglasPeuckerM(ppsm, 1, nPoints - 2, LOD_meters, &index_keep);
1031
1032 } else {
1033 index_keep.resize(nPoints);
1034 for (int i = 0; i < nPoints; i++) index_keep[i] = i;
1035 }
1036
1037 int nnn = index_keep.size();
1038
1039 double *ppr = ppd;
1040 for (int ip = 0; ip < nPoints; ip++) {
1041 double x = *ppr++;
1042 double y = *ppr++;
1043
1044 for (unsigned int j = 0; j < index_keep.size(); j++) {
1045 if (index_keep[j] == ip) {
1046 vec.push_back(x);
1047 vec.push_back(y);
1048 break;
1049 }
1050 }
1051 }
1052
1053 delete[] ppd;
1054 delete[] ppsm;
1055
1056 m_reducedAuxPlyPointsVector[iTable] = vec;
1057
1058 int nprr = vec.size() / 2;
1059
1060 return vec;
1061}
1062
1064// ChartDatabase
1066const int ID_DBS_PROGRESS_UPDATE = wxNewId();
1067
1068WX_DEFINE_OBJARRAY(ChartTable);
1069
1070ChartDatabase::ChartDatabase() {
1071 bValid = false;
1072 SetBusy(false);
1073
1074 m_ChartTableEntryDummy.Clear();
1075
1076 Bind(wxEVT_OCPN_CHARTTABLEENTRYTHREAD, &ChartDatabase::OnEvtThread, this);
1077 Bind(wxEVT_COMMAND_MENU_SELECTED, &ChartDatabase::OnDBSProgressUpdate, this,
1078 ID_DBS_PROGRESS_UPDATE);
1079
1080 UpdateChartClassDescriptorArray();
1081}
1082
1083void ChartDatabase::OnDBSProgressUpdate(wxCommandEvent &evt) {
1084 int value = evt.GetInt(); // retrieve progress value
1085 if (m_pprog) {
1086 // Update dialog safely
1087 m_pprog->Update(value);
1088 }
1089}
1090
1091static int in_event;
1092void ChartDatabase::OnEvtThread(OCPN_ChartTableEntryThreadEvent &event) {
1093 if (in_event) int yyp = 4;
1094
1095 in_event++;
1096 // Capture the completed job tickets
1097 auto ticket = event.GetTicket();
1098 if (!ticket) {
1099 in_event--;
1100 return;
1101 }
1102
1103 // Update progress dialog, if present
1104 if (1 /*ticket->b_thread_safe*/) {
1105 if (m_pprog && (m_jobsRemaining > 1)) {
1106 m_progcount++;
1107 double ratio = 100. * (double)m_progcount / m_ticketcount;
1108 int val = ratio;
1109 if (((m_progcount % m_nFileProgressQuantum) == 0)) {
1110 if (val != m_progint) {
1111 m_progint = val;
1112 // printf("%d %d\n", m_progcount, val);
1113#ifdef x__WXMSW__
1114 // On Windows, Update may pump messages even without
1115 // CAN_ABORT/ELAPSED_TIME
1116 wxEventLoopBase *loop = wxEventLoopBase::GetActive();
1117 if (loop) {
1118 // Temporarily deactivate the active loop to prevent re-entrancy
1119 wxEventLoopActivator noLoop(nullptr);
1120 m_pprog->Update(val);
1121 }
1122#else
1123 m_pprog->Update(val);
1124#endif
1125 }
1126 }
1127 }
1128 }
1129
1130 if (!ticket->m_ticket_type) { // TICKET_TYPE_NORMAL
1131 bool collision_found = false;
1132 if (ticket->b_thread_safe) {
1133 wxFileName fn(ticket->m_ChartPath);
1134 ChartCollisionsHashMap::iterator it;
1135 for (it = m_full_collision_map.begin(); it != m_full_collision_map.end();
1136 ++it) {
1137 if (it->first.IsSameAs(fn.GetFullName())) {
1138 // Two files found with identical file name
1139 // For now, just drop this ticket
1140 // TODO Make an (expensive) test on file modification times
1141 collision_found = true;
1142 break;
1143 }
1144 }
1145 if (!collision_found) {
1146 m_full_collision_map[fn.GetFullName()] = 1;
1147 }
1148 // Consider TODO #1 here: Looking for more duolicates acress directories
1149 }
1150
1151 m_ticket_vector.push_back(ticket);
1152 }
1153
1154 int remaining = --m_jobsRemaining;
1155
1156 if (remaining == 0) {
1157 m_pool.Shutdown();
1158 m_pool_deferred.Shutdown();
1159 size_t a = m_ticket_vector.size();
1160
1161 if (m_deferred_ticket_vector.size()) {
1162 // Process the deferred charts in a single thread pool
1163 // load the thread pool from the prepared array
1164 // Enqueue jobs
1165 for (auto &ticket_d : m_deferred_ticket_vector) {
1166 m_pool_deferred.Push(ticket_d);
1167 m_jobsRemaining++;
1168 }
1169 m_deferred_ticket_vector.clear();
1170
1171 // Initialize progress dialog
1172 m_progcount = 0;
1173 m_progint = 0;
1174 m_ticketcount = m_jobsRemaining;
1175 m_nFileProgressQuantum = 1; // wxMax(m_ticketcount / 10, 2);
1176 if (m_pprog) m_pprog->Update(0, _("Processing charts."));
1177
1178 // Start up the queued thread, if necessary
1179 if (m_jobsRemaining) {
1180 const int workerCount = 1;
1181 if (m_pool_deferred.GetWorkerCount() < workerCount) {
1182 int threads_needed = workerCount - m_pool_deferred.GetWorkerCount();
1183 for (int i = 0; i < threads_needed; ++i) {
1184 (new PoolWorkerThread(m_pool_deferred, this))->Run();
1185 m_pool_deferred.AddWorker();
1186 }
1187 }
1188 }
1189 in_event--;
1190 return; // Let the thread run
1191 }
1192
1193 // Now m_ticket_vector is populated with verified tickets
1194 // for all specified directories.
1195
1196 // Add the CTEs from the tickets to the active table
1197 // NB: The active_chartTable was cleared by the Update() method
1198 // before this point
1199
1200 for (auto &ticket_valid : m_ticket_vector) {
1201 if (ticket_valid->m_chart_table_entry)
1202 active_chartTable.push_back(ticket_valid->m_chart_table_entry);
1203 }
1204 size_t c = m_ticket_vector.size();
1205 size_t d = active_chartTable.size();
1206
1207 // Release references to tickets
1208 m_ticket_vector.clear();
1209
1210 FinalizeChartUpdate();
1211 in_event--;
1212 } else
1213 in_event--;
1214}
1215
1216void ChartDatabase::FinalizeChartUpdate() {
1217 // Scrub CTE list, remove any invalid entries,
1218 // as tagged by directory removal
1219 active_chartTable.erase(
1220 std::remove_if(active_chartTable.begin(), active_chartTable.end(),
1221 [](const auto &cte) { return !cte->GetbValid(); }),
1222 active_chartTable.end());
1223
1224 size_t d = active_chartTable.size();
1225
1226 // And once more, setting the Entry index field
1227 active_chartTable_pathindex.clear();
1228 int i = 0;
1229 for (auto cte : active_chartTable) {
1230 active_chartTable_pathindex[cte->GetFullSystemPath()] = i;
1231 cte->SetEntryOffset(i);
1232 i++;
1233 }
1234
1235 m_nentries = active_chartTable.size();
1236 bValid = true;
1237 SetBusy(false);
1238 ChartData->SetBusy(false);
1239
1240 // Finalize the dB on disk
1241 ChartData->SaveBinary(ChartListFileName);
1242 wxLogMessage("Finished chart database Update");
1243 wxLogMessage(" ");
1244
1245 if (m_pprog) m_pprog->Destroy();
1246 m_pprog = nullptr;
1247
1248 // The Update() function may set gWorldMapLocation if at least one of the
1249 // directories contains GSHHS files. Make sure GSHHS is still accessible
1250 if (gWorldMapLocation.empty()) { // Last resort. User might have deleted all
1251 // GSHHG data, but we still might have the
1252 // default dataset distributed with OpenCPN
1253 // or from the package repository...
1254 gWorldMapLocation = gDefaultWorldMapLocation;
1255 m_gshhg_chart_loc = wxEmptyString;
1256 }
1257
1258 // Update canvas and "Crossesland" machinery
1259 if (gWorldMapLocation != m_gshhg_chart_loc) {
1260 // ..For each canvas...
1261 // TODO Move this where?
1262 // for (unsigned int i = 0; i < g_canvasArray.GetCount(); i++) {
1263 // ChartCanvas *cc = g_canvasArray.Item(i);
1264 // if (cc) cc->ResetWorldBackgroundChart();
1265 // }
1266
1267 // Reset the GSHHS singleton which is used to detect land crossing.
1268 gshhsCrossesLandReset();
1269 }
1270
1271 // Purge all charts from cache, and delete.
1272 ChartData->PurgeCache();
1273
1274 // Signal Options dialog that update is finished
1275 GuiEvents::GetInstance().options_on_finalize_chartdbs.Notify();
1276
1277 // Signal a full chart reload
1278 GuiEvents::GetInstance().on_finalize_chartdbs.Notify();
1279}
1280
1281bool ChartDatabase::ScrubGroupArray() {
1282 // For each group,
1283 // make sure that each group element (dir or chart) references at least
1284 // oneitem in the database. If not, remove the element.
1285
1286 bool b_change = false;
1287 unsigned int igroup = 0;
1288 while (igroup < g_pGroupArray->GetCount()) {
1289 bool b_chart_in_element = false;
1290 ChartGroup *pGroup = g_pGroupArray->Item(igroup);
1291
1292 for (unsigned int j = 0; j < pGroup->m_element_array.size(); j++) {
1293 const wxString &element_root = pGroup->m_element_array[j].m_element_name;
1294
1295 for (unsigned int ic = 0;
1296 ic < (unsigned int)ChartData->GetChartTableEntries(); ic++) {
1297 auto &cte = ChartData->GetChartTableEntry(ic);
1298 wxString chart_full_path = cte.GetFullSystemPath();
1299
1300 if (chart_full_path.StartsWith(element_root)) {
1301 b_chart_in_element = true;
1302 break;
1303 }
1304 }
1305
1306 // Explicit check to avoid removing a group containing only GSHHS
1307 if (!b_chart_in_element) {
1308 wxString test_string = "GSHH";
1309 if (element_root.Upper().Contains(test_string))
1310 b_chart_in_element = true;
1311 }
1312
1313 if (!b_chart_in_element) // delete the element
1314 {
1315 pGroup->m_element_array.erase(pGroup->m_element_array.begin() + j);
1316 j--;
1317 b_change = true;
1318 }
1319 }
1320
1321 igroup++; // next group
1322 }
1323
1324 return b_change;
1325}
1326
1327void ChartDatabase::UpdateChartClassDescriptorArray() {
1328 if (m_ChartClassDescriptorArray.empty()) {
1329 m_ChartClassDescriptorArray.push_back(
1330 ChartClassDescriptor("ChartKAP", "*.kap", nullptr, BUILTIN_DESCRIPTOR));
1331 m_ChartClassDescriptorArray.push_back(
1332 ChartClassDescriptor("ChartGEO", "*.geo", nullptr, BUILTIN_DESCRIPTOR));
1333 m_ChartClassDescriptorArray.push_back(
1334 ChartClassDescriptor("s57chart", "*.000", nullptr, BUILTIN_DESCRIPTOR));
1335 m_ChartClassDescriptorArray.push_back(
1336 ChartClassDescriptor("s57chart", "*.s57", nullptr, BUILTIN_DESCRIPTOR));
1337 m_ChartClassDescriptorArray.push_back(ChartClassDescriptor(
1338 "cm93compchart", "00300000.a", nullptr, BUILTIN_DESCRIPTOR));
1339 m_ChartClassDescriptorArray.push_back(ChartClassDescriptor(
1340 "ChartMbTiles", "*.mbtiles", nullptr, BUILTIN_DESCRIPTOR));
1341 }
1342 // If the PlugIn Manager exists, get the array of dynamically loadable
1343 // chart class names
1344 if (g_pi_manager) {
1345 m_ChartClassDescriptorArray.erase(
1346 std::remove_if(m_ChartClassDescriptorArray.begin(),
1347 m_ChartClassDescriptorArray.end(),
1348 [](const ChartClassDescriptor &cd) {
1349 return cd.m_descriptor_type == PLUGIN_DESCRIPTOR;
1350 }),
1351 m_ChartClassDescriptorArray.end());
1352
1353 wxArrayString array = g_pi_manager->GetPlugInChartClassNameArray();
1354 for (unsigned int j = 0; j < array.GetCount(); j++) {
1355 // Instantiate a blank chart to retrieve the directory search mask for
1356 // this chart type
1357 wxString class_name = array[j];
1358 ChartPlugInWrapper *cpiw = new ChartPlugInWrapper(class_name);
1359 if (cpiw) {
1360 wxString mask = cpiw->GetFileSearchMask();
1361
1362 // Get the plugin (ptr) that provides this chart class
1363 auto plugin_t = g_pi_manager->GetProvidingPlugin(class_name);
1364 opencpn_plugin *plugin = dynamic_cast<opencpn_plugin *>(plugin_t);
1365 // Create a new descriptor and add it to the database
1366 m_ChartClassDescriptorArray.push_back(
1367 ChartClassDescriptor(class_name, mask, plugin, PLUGIN_DESCRIPTOR));
1368 delete cpiw;
1369 }
1370 }
1371 }
1372}
1373
1374ChartTableEntry &ChartDatabase::GetChartTableEntry(int index) {
1375 if (index < GetChartTableEntries())
1376 return *active_chartTable[index];
1377 else
1378 return m_ChartTableEntryDummy;
1379}
1380
1381bool ChartDatabase::CompareChartDirArray(ArrayOfCDI &test_array) {
1382 // Compare the parameter "test_array" with this.m_dir_array
1383 // Return true if functionally identical (order does not signify).
1384
1385 if (test_array.GetCount() != m_dir_array.GetCount()) return false;
1386
1387 bool bfound_inner;
1388 unsigned int nfound_outer = 0;
1389
1390 for (unsigned int i = 0; i < test_array.GetCount(); i++) {
1391 ChartDirInfo p = test_array[i];
1392 bfound_inner = false;
1393 for (unsigned int j = 0; j < m_dir_array.GetCount(); j++) {
1394 ChartDirInfo q = m_dir_array[j];
1395
1396 if (p.fullpath.IsSameAs(q.fullpath)) {
1397 bfound_inner = true;
1398 break;
1399 }
1400 }
1401 if (bfound_inner) nfound_outer++;
1402 }
1403
1404 return (nfound_outer == test_array.GetCount());
1405}
1406
1407wxString ChartDatabase::GetMagicNumberCached(wxString dir) {
1408 for (unsigned int j = 0; j < m_dir_array.GetCount(); j++) {
1409 ChartDirInfo q = m_dir_array[j];
1410 if (dir.IsSameAs(q.fullpath)) return q.magic_number;
1411 }
1412
1413 return "";
1414}
1415
1416bool ChartDatabase::Read(const wxString &filePath) {
1417 ChartTableEntry entry;
1418 int entries;
1419
1420 bValid = false;
1421
1422 wxFileName file(filePath);
1423 if (!file.FileExists()) return false;
1424
1425 m_DBFileName = filePath;
1426
1427 wxFFileInputStream ifs(filePath);
1428 if (!ifs.Ok()) return false;
1429
1430 ChartTableHeader cth;
1431 cth.Read(ifs);
1432 if (!cth.CheckValid()) return false;
1433
1434 // Capture the version number
1435 char vbo[5];
1436 memcpy(vbo, cth.GetDBVersionString(), 4);
1437 vbo[4] = 0;
1438 m_dbversion = atoi(&vbo[1]);
1439 s_dbVersion = m_dbversion; // save the static copy
1440
1441 wxLogVerbose("Chartdb:Reading %d directory entries, %d table entries",
1442 cth.GetDirEntries(), cth.GetTableEntries());
1443 wxLogMessage("Chartdb: Chart directory list follows");
1444 if (0 == cth.GetDirEntries()) wxLogMessage(" Nil");
1445
1446 int ind = 0;
1447 for (int iDir = 0; iDir < cth.GetDirEntries(); iDir++) {
1448 wxString dir;
1449 int dirlen;
1450 ifs.Read(&dirlen, sizeof(int));
1451 while (dirlen > 0) {
1452 char dirbuf[1024];
1453 int alen = dirlen > 1023 ? 1023 : dirlen;
1454 if (ifs.Read(&dirbuf, alen).Eof()) goto read_error;
1455 dirbuf[alen] = 0;
1456 dirlen -= alen;
1457 dir.Append(wxString(dirbuf, wxConvUTF8));
1458 }
1459 wxString msg;
1460 msg.Printf(" Chart directory #%d: ", iDir);
1461 msg.Append(dir);
1462 wxLogMessage(msg);
1463 m_chartDirs.Add(dir);
1464 }
1465
1466 entries = cth.GetTableEntries();
1467 // active_chartTable.Alloc(entries);
1468 active_chartTable_pathindex.clear();
1469 while (entries-- && entry.Read(this, ifs)) {
1470 active_chartTable_pathindex[entry.GetFullSystemPath()] = ind++;
1471 auto sharedPtr = std::make_shared<ChartTableEntry>(entry);
1472 active_chartTable.push_back(sharedPtr);
1473 }
1474
1475 entry.Clear();
1476 bValid = true;
1477 entry.SetAvailable(true);
1478
1479 m_nentries = active_chartTable.size();
1480 return true;
1481
1482read_error:
1483 bValid = false;
1484 m_nentries = active_chartTable.size();
1485 return false;
1486}
1487
1489
1490bool ChartDatabase::Write(const wxString &filePath) {
1491 wxFileName file(filePath);
1492 wxFileName dir(
1493 file.GetPath(wxPATH_GET_SEPARATOR | wxPATH_GET_VOLUME, wxPATH_NATIVE));
1494
1495 if (!dir.DirExists() && !dir.Mkdir()) return false;
1496
1497 wxFFileOutputStream ofs(filePath);
1498 if (!ofs.Ok()) return false;
1499
1500 ChartTableHeader cth(m_chartDirs.GetCount(), active_chartTable.size());
1501 cth.Write(ofs);
1502
1503 for (int iDir = 0; iDir < cth.GetDirEntries(); iDir++) {
1504 wxString dir1 = m_chartDirs[iDir];
1505 int dirlen = dir1.length();
1506 char s[200];
1507 strncpy(s, dir1.mb_str(wxConvUTF8), 199);
1508 s[199] = 0;
1509 dirlen = strlen(s);
1510 ofs.Write(&dirlen, sizeof(int));
1511 // ofs.Write(dir.fn_str(), dirlen);
1512 ofs.Write(s, dirlen);
1513 }
1514
1515 for (UINT32 iTable = 0; iTable < active_chartTable.size(); iTable++) {
1516 auto &cte = GetChartTableEntry(iTable);
1517 cte.Write(this, ofs);
1518 }
1519
1520 // Explicitly set the version
1521 m_dbversion = DB_VERSION_CURRENT;
1522
1523 return true;
1524}
1525
1527wxString SplitPath(wxString s, wxString tkd, int nchar, int offset,
1528 int *pn_split) {
1529 wxString r;
1530 int ncr = 0;
1531
1532 int rlen = offset;
1533 wxStringTokenizer tkz(s, tkd);
1534 while (tkz.HasMoreTokens()) {
1535 wxString token = tkz.GetNextToken();
1536 if ((rlen + (int)token.Len() + 1) < nchar) {
1537 r += token;
1538 r += tkd[0];
1539 rlen += token.Len() + 1;
1540 } else {
1541 r += "\n";
1542 ncr++;
1543 for (int i = 0; i < offset; i++) {
1544 r += " ";
1545 }
1546 r += token;
1547 r += tkd[0];
1548 rlen = offset + token.Len() + 1;
1549 }
1550 }
1551
1552 if (pn_split) *pn_split = ncr;
1553
1554 return r.Mid(0, r.Len() - 1); // strip the last separator char
1555}
1556
1557wxString ChartDatabase::GetFullChartInfo(ChartBase *pc, int dbIndex,
1558 int *char_width, int *line_count) {
1559 wxString r;
1560 int lc = 0;
1561 unsigned int max_width = 0;
1562 int ncr;
1563 unsigned int target_width = 60;
1564
1565 const ChartTableEntry &cte = GetChartTableEntry(dbIndex);
1566 wxString line;
1567 line.Empty();
1568 if (pc) {
1569 line = _(" Name: ");
1570 wxString longline = pc->GetName();
1571
1572 wxString tkz;
1573 if (longline.Find(' ') != wxNOT_FOUND) // assume a proper name
1574 tkz = " ";
1575 else
1576 tkz = "/,\\"; // else a file name
1577
1578 if (longline.Len() > target_width) {
1579 line += SplitPath(pc->GetName(), tkz, target_width, 12, &ncr);
1580 max_width = wxMax(max_width, target_width + 4);
1581 lc += ncr;
1582 } else {
1583 line += longline;
1584 max_width = wxMax(max_width, line.Len() + 4);
1585 }
1586 }
1587
1588 line += "\n";
1589 r += line;
1590 lc++;
1591
1592 if (pc) // chart is loaded and available
1593 line.Printf(" %s: 1:%d", _("Scale"), pc->GetNativeScale());
1594 else
1595 line.Printf(" %s: 1:%d", _("Scale"), cte.GetScale());
1596
1597 line += "\n";
1598 max_width = wxMax(max_width, line.Len());
1599 r += line;
1600 lc++;
1601 if (pc) {
1602 wxDateTime ed = pc->GetEditionDate();
1603 if (ed.IsValid()) {
1604 line = _(" Updated: ") + ed.FormatISODate() + "\n";
1605 max_width = wxMax(max_width, line.Len());
1606 r += line;
1607 }
1608 lc++;
1609
1610 line = _(" Source Edition: ") + pc->GetSE() + "\n";
1611 max_width = wxMax(max_width, line.Len());
1612 r += line;
1613 lc++;
1614 }
1615
1616 if (pc) {
1617 line = _(" Depth Units: ") + pc->GetDepthUnits() + "\n";
1618 max_width = wxMax(max_width, line.Len());
1619 r += line;
1620 lc++;
1621
1622 line = _(" Soundings: ") + pc->GetSoundingsDatum() + "\n";
1623 max_width = wxMax(max_width, line.Len());
1624 r += line;
1625 lc++;
1626
1627 line = _(" Datum: ") + pc->GetDatumString() + "\n";
1628 max_width = wxMax(max_width, line.Len());
1629 r += line;
1630 lc++;
1631 }
1632
1633 line = _(" Projection: ");
1634 if (PROJECTION_UNKNOWN == cte.GetChartProjectionType())
1635 line += _("Unknown");
1636 else if (PROJECTION_MERCATOR == cte.GetChartProjectionType())
1637 line += _("Mercator");
1638 else if (PROJECTION_TRANSVERSE_MERCATOR == cte.GetChartProjectionType())
1639 line += _("Transverse Mercator");
1640 else if (PROJECTION_POLYCONIC == cte.GetChartProjectionType())
1641 line += _("Polyconic");
1642 else if (PROJECTION_WEB_MERCATOR == cte.GetChartProjectionType())
1643 line += _("Web Mercator (EPSG:3857)");
1644 line += "\n";
1645 max_width = wxMax(max_width, line.Len());
1646 r += line;
1647 lc++;
1648
1649 line.Empty();
1650 if (pc) {
1651 }
1652
1653 line.Empty();
1654 if (pc && pc->GetExtraInfo().Len()) {
1655 line += pc->GetExtraInfo();
1656 line += "\n";
1657 max_width = wxMax(max_width, line.Len());
1658 r += line;
1659 lc++;
1660 }
1661 if (pc) {
1662 line.Empty();
1663 line = _(" ID: ");
1664 line += pc->GetID();
1665 line += "\n";
1666 max_width = wxMax(max_width, line.Len());
1667 r += line;
1668 lc++;
1669 }
1670
1671 line = _(" ChartFile: ");
1672 wxString longline = *(cte.GetpsFullPath());
1673 if (longline.Len() > target_width) {
1674 line += SplitPath(longline, "/,\\", target_width, 15, &ncr);
1675 max_width = wxMax(max_width, target_width + 4);
1676 lc += ncr;
1677 } else {
1678 line += longline;
1679 max_width = wxMax(max_width, line.Len() + 4);
1680 }
1681 r += line;
1682 r += "\n";
1683 lc++;
1684
1685 if (line_count) *line_count = lc;
1686
1687 if (char_width) *char_width = max_width;
1688
1689 return r;
1690}
1691
1692// ----------------------------------------------------------------------------
1693// Create Chart Table Database by directory search
1694// resulting in valid pChartTable in (this)
1695// ----------------------------------------------------------------------------
1696bool ChartDatabase::Create(ArrayOfCDI &dir_array,
1697 wxGenericProgressDialog *pprog) {
1698 m_dir_array = dir_array;
1699
1700 bValid = false;
1701
1702 m_chartDirs.Clear();
1703 active_chartTable.clear();
1704 active_chartTable_pathindex.clear();
1705
1706 Update(dir_array, true, pprog); // force the update the reload everything
1707
1708 bValid = true;
1709
1710 // Explicitly set the version
1711 m_dbversion = DB_VERSION_CURRENT;
1712
1713 return true;
1714}
1715
1716/*
1717 * Traverse a directory recursively and find the GSHHG directory
1718 * that contains GSHHG data files.
1719 */
1720class GshhsTraverser : public wxDirTraverser {
1721public:
1722 GshhsTraverser() {}
1723 virtual wxDirTraverseResult OnFile(const wxString &filename) override {
1724 wxFileName fn(filename);
1725 wxFileName dir(fn.GetPath());
1726 if (fn.GetFullName().Matches("poly-*-1.dat") &&
1727 dir.GetFullName().IsSameAs("GSHHG", false)) {
1728 parent_dir = fn.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR);
1729 return wxDIR_STOP;
1730 }
1731 return wxDIR_CONTINUE;
1732 }
1733 virtual wxDirTraverseResult OnDir(const wxString &dirname) override {
1734 // Always recurse into directories.
1735 return wxDIR_CONTINUE;
1736 }
1737 wxString GetGshhsDir() const { return parent_dir; }
1738
1739private:
1740 wxString parent_dir;
1741};
1742
1743/*
1744 * Find and return the full path a of directory containing GSHHG data files.
1745 * Search recursively starting from directory.
1746 */
1747wxString findGshhgDirectory(const wxString &directory) {
1748 wxDir dir(directory);
1749 if (!dir.IsOpened()) {
1750 return wxEmptyString;
1751 }
1752 GshhsTraverser traverser;
1753 dir.Traverse(traverser, wxEmptyString, wxDIR_FILES | wxDIR_DIRS);
1754 return traverser.GetGshhsDir();
1755}
1756
1757bool ChartDatabase::UpdateChartDatabaseInplace(ArrayOfCDI &DirArray,
1758 bool b_force,
1759 wxGenericProgressDialog *_prog) {
1760 // AbstractPlatform::ShowBusySpinner();
1761
1762 m_pprog = _prog;
1763
1764 wxLogMessage(" ");
1765 wxLogMessage("Starting chart database Update...");
1766
1767 // The Update() function may set gWorldMapLocation if at least one of the
1768 // directories contains GSHHS files. Save current situation...
1769 m_gshhg_chart_loc = gWorldMapLocation;
1770 gWorldMapLocation = wxEmptyString;
1771
1772 Update(DirArray, b_force, m_pprog);
1773
1774 // AbstractPlatform::HideBusySpinner();
1775 return true;
1776}
1777
1778// ----------------------------------------------------------------------------
1779// Update existing ChartTable Database by directory search
1780// resulting in valid pChartTable in (this)
1781// ----------------------------------------------------------------------------
1782bool ChartDatabase::Update(ArrayOfCDI &dir_array, bool bForce,
1783 wxGenericProgressDialog *pprog) {
1784 m_pprog = pprog;
1785 m_ticket_vector.clear();
1786 m_full_collision_map.clear();
1787 m_jobsRemaining = 0;
1788 m_deferred_ticket_vector.clear();
1789 SetChartDirArray(dir_array);
1790
1791 bValid = false; // database is not useable right now...
1792 SetBusy(true);
1793 ChartData->SetBusy(true);
1794
1795 // Mark all charts provisionally invalid
1796 for (unsigned int i = 0; i < active_chartTable.size(); i++) {
1797 auto &cte = GetChartTableEntry(i);
1798 cte.SetValid(false);
1799 }
1800
1801 m_chartDirs.Clear();
1802
1803 if (bForce) active_chartTable.clear();
1804
1805 bool lbForce = bForce;
1806
1807 // Do a dB Version upgrade if the current one is obsolete
1808 if (s_dbVersion != DB_VERSION_CURRENT) {
1809 active_chartTable.clear();
1810 lbForce = true;
1811 s_dbVersion = DB_VERSION_CURRENT; // Update the static indicator
1812 m_dbversion = DB_VERSION_CURRENT; // and the member
1813 }
1814
1815 // Get the new charts
1816
1817 for (unsigned int j = 0; j < dir_array.GetCount(); j++) {
1818 ChartDirInfo dir_info = dir_array[j];
1819
1820 // On Android, with SDK >= 30, traversal of a folder that is
1821 // on within the "scoped storage" domain is very slow.
1822 // Aviod it....
1823#ifdef __ANDROID__
1824 if (!androidIsDirWritable(dir_info.fullpath)) continue;
1825#endif
1826
1827 wxString dir_magic;
1828 // Recursively search for a directory that contains GSHHG files starting
1829 // from dir_info.
1830 wxString gshhg_dir = findGshhgDirectory(dir_info.fullpath);
1831 if (!gshhg_dir.empty()) {
1832 // If some polygons exist in the directory, set it as the one to use for
1833 // GSHHG
1834 // TODO: We should probably compare the version and maybe resolutions
1835 // available with what is currently used...
1836 wxLogMessage("Updating GSHHG directory: %s", gshhg_dir.c_str());
1837 gWorldMapLocation = gshhg_dir;
1838 }
1839
1840 // If the user has added a directory containig an extended OSMSHP basemap
1841 // then capture the location, and reset the basemap render amchine.
1842 if (dir_info.fullpath.Find("OSMSHP") != wxNOT_FOUND) {
1843 if (!wxDir::FindFirst(dir_info.fullpath, "basemap_*.shp").empty()) {
1844 wxLogMessage("Updating OSMSHP directory: %s", dir_info.fullpath);
1845 gWorldShapefileLocation =
1846 dir_info.fullpath + wxFileName::GetPathSeparator();
1847 gShapeBasemap.Reset();
1848 }
1849 }
1850
1851 TraverseDirAndAddCharts(dir_info, pprog, dir_magic, lbForce);
1852
1853 // Update the dir_list entry, even if the magic values are the same
1854 dir_info.magic_number = dir_magic;
1855 dir_array.RemoveAt(j);
1856 dir_array.Insert(dir_info, j);
1857
1858 m_chartDirs.Add(dir_info.fullpath);
1859 } // for
1860
1861 // Special case, if chart dir list is truly empty
1862 if (m_chartDirs.IsEmpty() || !m_jobsRemaining) {
1863 if (!m_deferred_ticket_vector.size()) {
1864 FinalizeChartUpdate();
1865 return true;
1866 } else {
1867 auto *evt =
1868 new OCPN_ChartTableEntryThreadEvent(wxEVT_OCPN_CHARTTABLEENTRYTHREAD);
1869 auto ticket_deferred = m_deferred_ticket_vector.back();
1870 ticket_deferred->m_ticket_type = 1; // Mark as a dummy ticket.;
1871 // to trigger an event
1872 m_jobsRemaining = 1;
1873 evt->SetTicket(ticket_deferred);
1874 wxQueueEvent(this, evt);
1875 }
1876 }
1877
1878 // Initialize progress dialog
1879 m_progcount = 0;
1880 m_progint = 0;
1881 m_ticketcount = m_jobsRemaining;
1882 m_nFileProgressQuantum = wxMax(m_ticketcount / 10, 2);
1883 if (pprog) pprog->Update(0, _("Processing charts."));
1884
1885 // Start up the queued threads, if necessary
1886 if (m_jobsRemaining) {
1887 const int workerCount = 4;
1888 if (m_pool.GetWorkerCount() < workerCount) {
1889 int threads_needed = workerCount - m_pool.GetWorkerCount();
1890 for (int i = 0; i < threads_needed; ++i) {
1891 (new PoolWorkerThread(m_pool, this))->Run();
1892 m_pool.AddWorker();
1893 }
1894 }
1895 }
1896
1897 return true;
1898}
1899
1900//-------------------------------------------------------------------
1901// Find Chart dbIndex
1902//-------------------------------------------------------------------
1903
1904int ChartDatabase::FinddbIndex(wxString PathToFind) {
1905 if (active_chartTable_pathindex.find(PathToFind) !=
1906 active_chartTable_pathindex.end())
1907 return active_chartTable_pathindex[PathToFind];
1908
1909 return -1;
1910}
1911
1912//-------------------------------------------------------------------
1913// Disable Chart
1914//-------------------------------------------------------------------
1915
1916int ChartDatabase::DisableChart(wxString &PathToDisable) {
1917 int index = FinddbIndex(PathToDisable);
1918 if (index != -1) {
1919 auto &entry = GetChartTableEntry(index);
1920 entry.Disable();
1921 return 1;
1922 }
1923 return 0;
1924}
1925
1926// ----------------------------------------------------------------------------
1927// Traverse the given directory looking for charts
1928// If bupdate is true, also search the existing database for a name match.
1929// If target chart is already in database, mark the entry valid and skip
1930// additional processing
1931// ----------------------------------------------------------------------------
1932
1933int ChartDatabase::TraverseDirAndAddCharts(ChartDirInfo &dir_info,
1934 wxGenericProgressDialog *pprog,
1935 wxString &dir_magic, bool bForce) {
1936 // Extract the true dir name and magic number from the compound string
1937 wxString dir_path = dir_info.fullpath;
1938#ifdef __ANDROID__
1939 dir_path = wxString(dir_info.fullpath.mb_str(wxConvUTF8));
1940#endif
1941
1942 wxString old_magic = dir_info.magic_number;
1943 wxString new_magic = old_magic;
1944 dir_magic = old_magic; // provisionally the same
1945
1946 int nAdd = 0;
1947
1948 bool b_skipDetectDirChange = false;
1949 bool b_dirchange = false;
1950
1951 // Does this directory actually exist?
1952 if (!wxDir::Exists(dir_path)) return 0;
1953
1954 // Check to see if this is a cm93 directory root
1955 // If so, skip the DetectDirChange since it may be very slow
1956 // and give no information
1957 // Assume a change has happened, and process accordingly
1958 bool b_cm93 = Check_CM93_Structure(dir_path);
1959 if (b_cm93) {
1960 b_skipDetectDirChange = true;
1961 b_dirchange = true;
1962 }
1963
1964 // Quick scan the directory to see if it has changed
1965 // If not, there is no need to scan again.....
1966 if (!b_skipDetectDirChange)
1967 b_dirchange = DetectDirChange(dir_path, dir_info.fullpath, old_magic,
1968 new_magic, pprog);
1969
1970 if (!bForce && !b_dirchange) {
1971 wxString msg(" No change detected on directory ");
1972 msg.Append(dir_path);
1973 wxLogMessage(msg);
1974
1975 // Traverse the database, and mark as valid all charts coming from this
1976 // dir, or anywhere in its tree
1977
1978 wxFileName fn_dir(dir_path, "stuff");
1979 unsigned int dir_path_count = fn_dir.GetDirCount();
1980
1981 if (pprog) pprog->SetTitle(_("OpenCPN Chart Scan...."));
1982
1983 int nEntries = active_chartTable.size();
1984
1985 for (int ic = 0; ic < nEntries; ic++) {
1986 auto &cte = GetChartTableEntry(ic);
1987 wxFileName fn(cte.GetFullSystemPath());
1988
1989 while (fn.GetDirCount() >= dir_path_count) {
1990 if (fn.GetPath() == dir_path) {
1991 auto &cte_a = GetChartTableEntry(ic);
1992 cte_a.SetValid(true);
1993 // if(pprog)
1994 // pprog->Update((ic * 100)
1995 // /nEntries, fn.GetFullPath());
1996
1997 break;
1998 }
1999 fn.RemoveLastDir();
2000 }
2001 }
2002
2003 return 0;
2004 }
2005
2006 // There presumably was a change in the directory contents. Return the new
2007 // magic number
2008 dir_magic = new_magic;
2009
2010 // Look for all possible defined chart classes
2011 for (auto &cd : m_ChartClassDescriptorArray) {
2012 nAdd += SearchDirAndAddCharts(dir_info.fullpath, cd, pprog);
2013 }
2014
2015 return nAdd;
2016}
2017
2018bool ChartDatabase::DetectDirChange(const wxString &dir_path,
2019 const wxString &prog_label,
2020 const wxString &magic, wxString &new_magic,
2021 wxGenericProgressDialog *pprog) {
2022 if (pprog) pprog->SetTitle(_("OpenCPN Directory Scan...."));
2023
2024 // parse the magic number
2025 long long unsigned int nmagic;
2026 wxULongLong nacc = 0;
2027
2028 magic.ToULongLong(&nmagic, 10);
2029
2030 // Get an arraystring of all files
2031 wxArrayString FileList;
2032 wxDir dir(dir_path);
2033 int n_files = dir.GetAllFiles(dir_path, &FileList);
2034 FileList.Sort(); // Ensure persistent order of items being hashed.
2035
2036 FlexHash hash(sizeof nacc);
2037 hash.Reset();
2038
2039 if (pprog) pprog->Update(0, prog_label);
2040
2041 // Traverse the list of files, getting their interesting stuff to add to
2042 // accumulator
2043 for (int ifile = 0; ifile < n_files; ifile++) {
2044 wxFileName file(FileList[ifile]);
2045
2046 // NOTE. Do not ever try to optimize this code by combining `wxString`
2047 // calls. Otherwise `fileNameUTF8` will point to a stale buffer overwritten
2048 // by garbage.
2049 wxString fileNameNative = file.GetFullPath();
2050 wxScopedCharBuffer fileNameUTF8 = fileNameNative.ToUTF8();
2051 hash.Update(fileNameUTF8.data(), fileNameUTF8.length());
2052
2053 // File Size;
2054 wxULongLong size = file.GetSize();
2055 wxULongLong fileSize = ((size != wxInvalidSize) ? size : 0);
2056 hash.Update(&fileSize, (sizeof fileSize));
2057
2058 // Mod time, in ticks
2059 wxDateTime t = file.GetModificationTime();
2060 wxULongLong fileTime = t.GetTicks();
2061 hash.Update(&fileTime, (sizeof fileTime));
2062 }
2063
2064 hash.Finish();
2065 hash.Receive(&nacc);
2066
2067 // Return the calculated magic number
2068 new_magic = nacc.ToString();
2069
2070 // And do the test
2071 if (new_magic != magic)
2072 return true;
2073 else
2074 return false;
2075}
2076
2077bool ChartDatabase::IsChartDirUsed(const wxString &theDir) {
2078 wxString dir(theDir);
2079 if (dir.Last() == '/' || dir.Last() == wxFileName::GetPathSeparator())
2080 dir.RemoveLast();
2081
2082 dir.Append("*");
2083 for (UINT32 i = 0; i < active_chartTable.size(); i++) {
2084 auto &cte_u = GetChartTableEntry(i);
2085 if (cte_u.GetpsFullPath()->Matches(dir)) return true;
2086 }
2087 return false;
2088}
2089
2090//-----------------------------------------------------------------------------
2091// Validate a given directory as a cm93 root database
2092// If it appears to be a cm93 database, then return true
2093//-----------------------------------------------------------------------------
2094bool ChartDatabase::Check_CM93_Structure(wxString dir_name) {
2095 wxString filespec;
2096
2097 wxRegEx test("[0-9]+");
2098
2099 wxDir dirt(dir_name);
2100 wxString candidate;
2101
2102 if (dirt.IsOpened())
2103 wxLogMessage("check_cm93 opened dir OK: " + dir_name);
2104 else {
2105 wxLogMessage("check_cm93 NOT OPENED OK: " + dir_name);
2106 wxLogMessage("check_cm93 returns false." + dir_name);
2107 return false;
2108 }
2109
2110 bool b_maybe_found_cm93 = false;
2111 bool b_cont = dirt.GetFirst(&candidate);
2112
2113 while (b_cont) {
2114 if (test.Matches(candidate) && (candidate.Len() == 8)) {
2115 b_maybe_found_cm93 = true;
2116 break;
2117 }
2118
2119 b_cont = dirt.GetNext(&candidate);
2120 }
2121
2122 if (b_maybe_found_cm93) {
2123 wxString dir_next = dir_name;
2124 dir_next += "/";
2125 dir_next += candidate;
2126 if (wxDir::Exists(dir_next)) {
2127 wxDir dir_n(dir_next);
2128 if (dirt.IsOpened()) {
2129 wxString candidate_n;
2130
2131 wxRegEx test_n("^[A-Ga-g]");
2132 bool b_probably_found_cm93 = false;
2133 bool b_cont_n = dir_n.IsOpened() && dir_n.GetFirst(&candidate_n);
2134 while (b_cont_n) {
2135 if (test_n.Matches(candidate_n) && (candidate_n.Len() == 1)) {
2136 b_probably_found_cm93 = true;
2137 break;
2138 }
2139 b_cont_n = dir_n.GetNext(&candidate_n);
2140 }
2141
2142 if (b_probably_found_cm93) // found a directory that looks
2143 // like {dir_name}/12345678/A
2144 // probably cm93
2145 {
2146 // make sure the dir exists
2147 wxString dir_luk = dir_next;
2148 dir_luk += "/";
2149 dir_luk += candidate_n;
2150 if (wxDir::Exists(dir_luk)) return true;
2151 }
2152 }
2153 }
2154 }
2155
2156 return false;
2157}
2158
2159/*
2160//-----------------------------------------------------------------------------
2161// Validate a given directory as a cm93 root database
2162// If it appears to be a cm93 database, then return the name of an existing cell
2163file
2164// File name will be unique with respect to member element m_cm93_filename_array
2165// If not cm93, return empty string
2166//-----------------------------------------------------------------------------
2167wxString ChartDatabase::Get_CM93_FileName(wxString dir_name)
2168{
2169 wxString filespec;
2170
2171 wxRegEx test("[0-9]+");
2172
2173 wxDir dirt(dir_name);
2174 wxString candidate;
2175
2176 bool b_maybe_found_cm93 = false;
2177 bool b_cont = dirt.GetFirst(&candidate);
2178
2179 while(b_cont)
2180 {
2181 if(test.Matches(candidate)&& (candidate.Len() == 8))
2182 {
2183 b_maybe_found_cm93 = true;
2184 break;
2185 }
2186
2187 b_cont = dirt.GetNext(&candidate);
2188
2189 }
2190
2191 if(b_maybe_found_cm93)
2192 {
2193 wxString dir_next = dir_name;
2194 dir_next += "/";
2195 dir_next += candidate;
2196 if(wxDir::Exists(dir_next))
2197 {
2198 wxDir dir_n(dir_next);
2199 wxString candidate_n;
2200
2201 wxRegEx test_n("^[A-Ga-g]");
2202 bool b_probably_found_cm93 = false;
2203 bool b_cont_n = dir_n.GetFirst(&candidate_n);
2204 while(b_cont_n)
2205 {
2206 if(test_n.Matches(candidate_n) && (candidate_n.Len() ==
22071))
2208 {
2209 b_probably_found_cm93 = true;
2210 break;
2211 }
2212 b_cont_n = dir_n.GetNext(&candidate_n);
2213 }
2214
2215 if(b_probably_found_cm93) // found a directory that
2216looks like {dir_name}/12345678/A probably cm93 { // and we want to try and
2217shorten the recursive search
2218 // make sure the dir exists
2219 wxString dir_luk = dir_next;
2220 dir_luk += "/";
2221 dir_luk += candidate_n;
2222 if(wxDir::Exists(dir_luk))
2223 {
2224 wxString msg("Found probable CM93 database in
2225"); msg += dir_name; wxLogMessage(msg);
2226
2227 wxString dir_name_plus = dir_luk; // be very
2228specific about the dir_name,
2229
2230 wxDir dir_get(dir_name_plus);
2231 wxString one_file;
2232 dir_get.GetFirst(&one_file);
2233
2234 // We must return a unique file name, i.e. one
2235that has not bee seen
2236 // before in this invocation of chart dir
2237scans. bool find_unique = false; while(!find_unique)
2238 {
2239 find_unique = true;
2240 for(unsigned int ifile=0; ifile <
2241m_cm93_filename_array.GetCount(); ifile++)
2242 {
2243 if(m_cm93_filename_array[ifile] ==
2244one_file) find_unique = false;
2245 }
2246 if(!find_unique)
2247 dir_get.GetNext(&one_file);
2248 }
2249
2250 m_cm93_filename_array.Add(one_file);
2251
2252 filespec = one_file;
2253 }
2254
2255 }
2256 }
2257 }
2258
2259 return filespec;
2260}
2261*/
2262
2263int ChartDatabase::SearchDirAndAddCharts(wxString &dir_name_base,
2264 ChartClassDescriptor &chart_desc,
2265 wxGenericProgressDialog *pprog) {
2266 wxString msg("Searching directory: ");
2267 msg += dir_name_base;
2268 msg += " for ";
2269 msg += chart_desc.m_search_mask;
2270 wxLogMessage(msg);
2271
2272 wxString dir_name = dir_name_base;
2273
2274#ifdef __ANDROID__
2275 dir_name = wxString(dir_name_base.mb_str(wxConvUTF8)); // android
2276#endif
2277
2278 if (!wxDir::Exists(dir_name)) return 0;
2279
2280 wxString filespec = chart_desc.m_search_mask.Upper();
2281 wxString lowerFileSpec = chart_desc.m_search_mask.Lower();
2282 wxString filespecXZ = filespec + ".xz";
2283 wxString lowerFileSpecXZ = lowerFileSpec + ".xz";
2284 wxString filename;
2285
2286 // Count the files
2287 wxArrayString FileList;
2288 int gaf_flags = wxDIR_DEFAULT; // as default, recurse into subdirs
2289
2290 // Here is an optimization for MSW/cm93 especially
2291 // If this directory seems to be a cm93, and we are not explicitely looking
2292 // for cm93, then abort Otherwise, we will be looking thru entire cm93 tree
2293 // for non-existent .KAP files, etc.
2294
2295 bool b_found_cm93 = false;
2296 bool b_cm93 = Check_CM93_Structure(dir_name);
2297 if (b_cm93) {
2298 if (filespec != "00300000.A")
2299 return false;
2300 else {
2301 filespec = dir_name;
2302 b_found_cm93 = true;
2303 }
2304 }
2305
2306 if (!b_found_cm93) {
2307 wxDir dir(dir_name);
2308 dir.GetAllFiles(dir_name, &FileList, filespec, gaf_flags);
2309
2310#ifdef __ANDROID__
2311 if (!FileList.GetCount()) {
2312 wxArrayString afl = androidTraverseDir(dir_name, filespec);
2313 for (wxArrayString::const_iterator item = afl.begin(); item != afl.end();
2314 item++)
2315 FileList.Add(*item);
2316 }
2317#endif
2318
2319#ifndef __WXMSW__
2320 if (filespec != lowerFileSpec) {
2321 // add lowercase filespec files too
2322 wxArrayString lowerFileList;
2323 dir.GetAllFiles(dir_name, &lowerFileList, lowerFileSpec, gaf_flags);
2324
2325#ifdef __ANDROID__
2326 if (!lowerFileList.GetCount()) {
2327 wxArrayString afl = androidTraverseDir(dir_name, lowerFileSpec);
2328 for (wxArrayString::const_iterator item = afl.begin();
2329 item != afl.end(); item++)
2330 lowerFileList.Add(*item);
2331 }
2332#endif
2333
2334 for (wxArrayString::const_iterator item = lowerFileList.begin();
2335 item != lowerFileList.end(); item++)
2336 FileList.Add(*item);
2337 }
2338#endif
2339
2340#ifdef OCPN_USE_LZMA
2341 // add xz compressed files;
2342 dir.GetAllFiles(dir_name, &FileList, filespecXZ, gaf_flags);
2343 dir.GetAllFiles(dir_name, &FileList, lowerFileSpecXZ, gaf_flags);
2344#endif
2345
2346 FileList.Sort(); // Sorted processing order makes the progress bar more
2347 // meaningful to the user.
2348 } else { // This is a cm93 dataset, specified as yada/yada/cm93
2349 wxString dir_plus = dir_name;
2350 dir_plus += wxFileName::GetPathSeparator();
2351 FileList.Add(dir_plus);
2352 }
2353
2354 int nFile = FileList.GetCount();
2355
2356 if (!nFile) return false;
2357
2358 int nDirEntry = 0;
2359
2360 // Check to see if there are any charts in the DB which refer to this
2361 // directory If none at all, there is no need to scan the DB for fullpath
2362 // match of each potential addition and bthis_dir_in_dB is false.
2363 // bool bthis_dir_in_dB = IsChartDirUsed(dir_name);
2364
2365 if (pprog) pprog->SetTitle(_("OpenCPN Chart Add...."));
2366
2367 // build a hash table based on filename (without directory prefix) of
2368 // the chart to fast detect identical charts
2369 ChartCollisionsHashMap collision_map;
2370 // int nEntry = active_chartTable.GetCount();
2371 // for (int i = 0; i < nEntry; i++) {
2372 // wxString table_file_name = active_chartTable[i].GetFullSystemPath();
2373 // wxFileName table_file(table_file_name);
2374 // collision_map[table_file.GetFullName()] = i;
2375 // }
2376
2377 // Capture a vector of pending thread tickets for this directory
2378 std::vector<std::shared_ptr<ChartTableEntryJobTicket>> ticket_vector;
2379
2380 for (int ifile = 0; ifile < nFile; ifile++) {
2381 wxFileName file(FileList[ifile]);
2382 wxString full_path = file.GetFullPath();
2383 wxString file_name = file.GetFullName();
2384 wxString utf8_path = full_path;
2385
2386#ifdef __ANDROID__
2387 // The full path (full_name) is the broken Android files system
2388 // interpretation, which does not display well onscreen. So, here we
2389 // reconstruct a full path spec in UTF-8 encoding for later use in string
2390 // displays. This utf-8 string will be used to construct the chart database
2391 // entry if required.
2392 wxFileName fnbase(dir_name_base);
2393 int nDirs = fnbase.GetDirCount();
2394
2395 wxFileName file_target(FileList[ifile]);
2396
2397 for (int i = 0; i < nDirs + 1;
2398 i++) // strip off the erroneous intial directories
2399 file_target.RemoveDir(0);
2400
2401 wxString leftover_path = file_target.GetFullPath();
2402 utf8_path =
2403 dir_name_base + leftover_path; // reconstruct a fully utf-8 version
2404#endif
2405
2406 // Validate the file name again, considering MSW's semi-random treatment
2407 // of case....
2408 // TODO...something fishy here - may need to normalize saved name?
2409 if (!file_name.Matches(lowerFileSpec) && !file_name.Matches(filespec) &&
2410 !file_name.Matches(lowerFileSpecXZ) && !file_name.Matches(filespecXZ) &&
2411 !b_found_cm93) {
2412 // wxLogMessage("FileSpec test failed for:" + file_name);
2413 continue;
2414 }
2415
2416 ChartTableEntry *pnewChart = NULL;
2417 bool bAddFinal = true;
2418 int b_add_msg = 0;
2419
2420#if 0 // TODO Fix?
2421 // Check the collisions map looking for duplicates in directories already
2422 // processed, and choosing the right one.
2423// ChartCollisionsHashMap::const_iterator collision_ptr =
2424// collision_map.find(file_name);
2425// bool collision = (collision_ptr != collision_map.end());
2426// bool file_path_is_same = false;
2427// bool file_time_is_same = false;
2428// ChartTableEntry *pEntry = NULL;
2429// wxString table_file_name;
2430
2431
2432 // Allow multiple cm93 chart sets #4217
2433 if (b_found_cm93) collision = false;
2434
2435 if (collision) {
2436 pEntry = &active_chartTable[collision_ptr->second];
2437 table_file_name = pEntry->GetFullSystemPath();
2438 file_path_is_same =
2439 bthis_dir_in_dB && full_name.IsSameAs(table_file_name);
2440
2441 // If the chart full file paths are exactly the same, select the newer
2442 // one.
2443 if (file_path_is_same) {
2444 b_add_msg++;
2445
2446 // Check the file modification time
2447 time_t t_oldFile = pEntry->GetFileTime();
2448 time_t t_newFile = file.GetModificationTime().GetTicks();
2449
2450 if (t_newFile <= t_oldFile) {
2451 file_time_is_same = true;
2452 bAddFinal = false;
2453 pEntry->SetValid(true);
2454 } else {
2455 bAddFinal = true;
2456 pEntry->SetValid(false);
2457 }
2458 }
2459 }
2460#endif
2461
2462 // Check for duplicates within this directory
2463 bool collision_found = false;
2464 ChartCollisionsHashMap::iterator it;
2465 for (it = collision_map.begin(); it != collision_map.end(); ++it) {
2466 if (it->first.IsSameAs(file_name)) {
2467 // Two files found with identical file name
2468 // For now, just drop this ticket
2469 // TODO Make an (expensive) test on file modification times
2470 collision_found = true;
2471 break;
2472 }
2473 }
2474
2475 if (!collision_found) {
2476 // Create a ticket for this chart
2477 auto ticket = std::make_shared<ChartTableEntryJobTicket>();
2478 ticket->m_ChartPath = full_path;
2479 ticket->m_ChartPathUTF8 = full_path;
2480 ticket->chart_desc = chart_desc;
2481
2482 ticket_vector.push_back(ticket);
2483 collision_map[file_name] = ifile;
2484 }
2485
2486 } // the big loop
2487
2488 // Built-in chart types are all thread-safe
2489 // Check plugin charts
2490 bool is_kap = false; // chart_desc.m_class_name.IsSameAs("ChartKAP");
2491 if (chart_desc.m_descriptor_type == PLUGIN_DESCRIPTOR || is_kap) {
2492 // Check plugin charts API. API >- 118 are known to be thread-safe
2493 opencpn_plugin *plugin = chart_desc.m_plugin;
2494 opencpn_plugin_118 *provider_plugin118 = dynamic_cast<opencpn_plugin_118 *>(
2495 dynamic_cast<opencpn_plugin *>(plugin));
2496
2497 if (!provider_plugin118 || is_kap) {
2498 // old plugin, charts not thread-safe
2499 // So arrange to process the tickets in the main app thread,
2500 // during the event handler, at the end of the queue processing
2501 for (auto &ticket : ticket_vector) {
2502 ticket->b_thread_safe = false;
2503 ticket->m_provider_type = 1;
2504 ticket->provider_class_name = chart_desc.m_class_name;
2505 m_deferred_ticket_vector.push_back(ticket);
2506 }
2507 return nDirEntry;
2508 }
2509 }
2510
2511 // Chart directory is known thread-safe
2512 // load the thread pool from the prepared array
2513 // Enqueue jobs
2514 for (auto &ticket : ticket_vector) {
2515 m_pool.Push(ticket);
2516 m_jobsRemaining++;
2517 }
2518
2519 // Tickets queued, wait for completion events
2520 return nDirEntry;
2521}
2522
2523bool ChartDatabase::AddChart(wxString &chartfilename,
2524 ChartClassDescriptor &chart_desc,
2525 wxGenericProgressDialog *pprog, int isearch,
2526 bool bthis_dir_in_dB) {
2527 bool rv = false;
2528 wxFileName file(chartfilename);
2529 wxString full_name = file.GetFullPath();
2530 wxString file_name = file.GetFullName();
2531
2532 // Validate the file name again, considering MSW's semi-random treatment of
2533 // case....
2534 // TODO...something fishy here - may need to normalize saved name?
2535 // if(!file_name.Matches(lowerFileSpec) && !file_name.Matches(filespec) &&
2536 // !b_found_cm93)
2537 // continue;
2538
2539 if (pprog)
2540 pprog->Update(wxMin((m_pdifile * 100) / m_pdnFile, 100), full_name);
2541
2542 ChartTableEntry *pnewChart = NULL;
2543 bool bAddFinal = true;
2544 int b_add_msg = 0;
2545 wxString msg_fn(full_name);
2546 msg_fn.Replace("%", "%%");
2547
2548 pnewChart = CreateChartTableEntry(full_name, full_name, chart_desc);
2549 if (!pnewChart) {
2550 bAddFinal = false;
2551 wxLogMessage(wxString::Format(
2552 " CreateChartTableEntry() failed for file: %s", msg_fn.c_str()));
2553 return false;
2554 } else // traverse the existing database looking for duplicates, and choosing
2555 // the right one
2556 {
2557 int nEntry = active_chartTable.size();
2558 for (int i = 0; i < nEntry; i++) {
2559 auto &cte_a = GetChartTableEntry(i);
2560 wxString *ptable_file_name = cte_a.GetpsFullPath();
2561
2562 // If the chart full file paths are exactly the same, select the newer
2563 // one
2564 if (bthis_dir_in_dB && full_name.IsSameAs(*ptable_file_name)) {
2565 b_add_msg++;
2566
2567 // Check the file modification time
2568 auto &cte_search = GetChartTableEntry(isearch);
2569 time_t t_oldFile = cte_search.GetFileTime();
2570 time_t t_newFile = file.GetModificationTime().GetTicks();
2571
2572 if (t_newFile <= t_oldFile) {
2573 bAddFinal = false;
2574 cte_search.SetValid(true);
2575 } else {
2576 bAddFinal = true;
2577 cte_search.SetValid(false);
2578 wxLogMessage(
2579 wxString::Format(" Replacing older chart file of same path: %s",
2580 msg_fn.c_str()));
2581 }
2582
2583 break;
2584 }
2585
2586 // Look at the chart file name (without directory prefix) for a further
2587 // check for duplicates This catches the case in which the "same" chart
2588 // is in different locations, and one may be newer than the other.
2589 wxFileName table_file(*ptable_file_name);
2590
2591 if (table_file.GetFullName() == file_name) {
2592 b_add_msg++;
2593
2594 // TODO fix this...
2595#if 0
2596 if (pnewChart->IsEarlierThan(active_chartTable[isearch])) {
2597 // Make sure the compare file actually exists
2598 if (table_file.IsFileReadable()) {
2599 active_chartTable[isearch].SetValid(true);
2600 bAddFinal = false;
2601 wxLogMessage(wxString::Format(
2602 " Retaining newer chart file of same name: %s",
2603 msg_fn.c_str()));
2604 }
2605 } else if (pnewChart->IsEqualTo(active_chartTable[isearch])) {
2606 // The file names (without dir prefix) are identical,
2607 // and the mod times are identical
2608 // Prsume that this is intentional, in order to facilitate
2609 // having the same chart in multiple groups.
2610 // So, add this chart.
2611 bAddFinal = true;
2612 }
2613
2614 else {
2615 active_chartTable[isearch].SetValid(false);
2616 bAddFinal = true;
2617 wxLogMessage(
2618 wxString::Format(" Replacing older chart file of same name: %s",
2619 msg_fn.c_str()));
2620 }
2621#endif
2622 break;
2623 }
2624
2625 // TODO Look at the chart ID as a further check against duplicates
2626
2627 isearch++;
2628 if (nEntry == isearch) isearch = 0;
2629 } // for
2630 }
2631
2632 if (bAddFinal) {
2633 if (0 == b_add_msg) {
2634 wxLogMessage(
2635 wxString::Format(" Adding chart file: %s", msg_fn.c_str()));
2636 }
2637 std::shared_ptr<ChartTableEntry> sharedPtr(pnewChart);
2638 active_chartTable.push_back(sharedPtr);
2639 rv = true;
2640 } else {
2641 delete pnewChart;
2642 // wxLogMessage(wxString::Format(" Not adding chart
2643 // file: %s", msg_fn.c_str()));
2644 rv = false;
2645 }
2646
2647 m_nentries = active_chartTable.size();
2648
2649 return rv;
2650}
2651
2652bool ChartDatabase::AddSingleChart(wxString &ChartFullPath,
2653 bool b_force_full_search) {
2654 // Find a relevant chart class descriptor
2655 wxFileName fn(ChartFullPath);
2656 wxString ext = fn.GetExt();
2657 ext.Prepend("*.");
2658 wxString ext_upper = ext.MakeUpper();
2659 wxString ext_lower = ext.MakeLower();
2660 wxString dir_name = fn.GetPath();
2661
2662 // Search the array of chart class descriptors to find a match
2663 // between the search mask and the chart file extension
2664
2666 for (auto &cd : m_ChartClassDescriptorArray) {
2667 if (cd.m_descriptor_type == PLUGIN_DESCRIPTOR) {
2668 if (cd.m_search_mask == ext_upper) {
2669 desc = cd;
2670 break;
2671 }
2672 if (cd.m_search_mask == ext_lower) {
2673 desc = cd;
2674 break;
2675 }
2676 }
2677 }
2678
2679 // If we know that we need to do a full recursive search of the db,
2680 // then there is no need to verify it by doing a directory match
2681 bool b_recurse = true;
2682 if (!b_force_full_search) b_recurse = IsChartDirUsed(dir_name);
2683
2684 bool rv = AddChart(ChartFullPath, desc, NULL, 0, b_recurse);
2685
2686 // remove duplicates marked in AddChart()
2687
2688 for (unsigned int i = 0; i < active_chartTable.size(); i++) {
2689 auto &cte_r = GetChartTableEntry(i);
2690 if (!cte_r.GetbValid()) {
2691 // TODO fix this
2692 // active_chartTable.RemoveAt(i);
2693 i--; // entry is gone, recheck this index for next entry
2694 }
2695 }
2696
2697 // Update the Entry index fields
2698 for (unsigned int i = 0; i < active_chartTable.size(); i++) {
2699 auto &cte_ef = GetChartTableEntry(i);
2700 cte_ef.SetEntryOffset(i);
2701 }
2702
2703 // Get a new magic number
2704 wxString new_magic;
2705 DetectDirChange(dir_name, "", "", new_magic, 0);
2706
2707 // Update (clone) the CDI array
2708 bool bcfound = false;
2709 ArrayOfCDI NewChartDirArray;
2710
2711 ArrayOfCDI ChartDirArray = GetChartDirArray();
2712 for (unsigned int i = 0; i < ChartDirArray.GetCount(); i++) {
2713 ChartDirInfo cdi = ChartDirArray[i];
2714
2715 ChartDirInfo newcdi = cdi;
2716
2717 // If entry is found that matches this cell, clear the magic number.
2718 if (newcdi.fullpath == dir_name) {
2719 newcdi.magic_number = new_magic;
2720 bcfound = true;
2721 }
2722
2723 NewChartDirArray.Add(newcdi);
2724 }
2725
2726 if (!bcfound) {
2727 ChartDirInfo cdi;
2728 cdi.fullpath = dir_name;
2729 cdi.magic_number = new_magic;
2730 NewChartDirArray.Add(cdi);
2731 }
2732
2733 // Update the database master copy of the CDI array
2734 SetChartDirArray(NewChartDirArray);
2735
2736 // Update the list of chart dirs.
2737 m_chartDirs.Clear();
2738
2739 for (unsigned int i = 0; i < GetChartDirArray().GetCount(); i++) {
2740 ChartDirInfo cdi = GetChartDirArray()[i];
2741 m_chartDirs.Add(cdi.fullpath);
2742 }
2743
2744 m_nentries = active_chartTable.size();
2745
2746 ChartData->UpdateChartDatabaseInplace(NewChartDirArray, false, nullptr);
2747 return rv;
2748}
2749
2750bool ChartDatabase::RemoveSingleChart(wxString &ChartFullPath) {
2751 bool rv = false;
2752
2753 // Walk the chart table, looking for the target
2754 for (unsigned int i = 0; i < active_chartTable.size(); i++) {
2755 auto &cte = GetChartTableEntry(i);
2756 if (ChartFullPath.IsSameAs(cte.GetFullSystemPath())) {
2757 // Fast remove element, order not preserved
2758 std::swap(active_chartTable[i], active_chartTable.back());
2759 active_chartTable.pop_back();
2760 break;
2761 }
2762 }
2763
2764 // Update the EntryOffset fields for the array
2765 for (unsigned int i = 0; i < active_chartTable.size(); i++) {
2766 auto &pcte = GetChartTableEntry(i);
2767 pcte.SetEntryOffset(i);
2768 }
2769
2770 // Check and update the dir array
2771 wxFileName fn(ChartFullPath);
2772 wxString fd = fn.GetPath();
2773 if (!IsChartDirUsed(fd)) {
2774 // Clone a new array, removing the unused directory,
2775 ArrayOfCDI NewChartDirArray;
2776
2777 ArrayOfCDI ChartDirArray = GetChartDirArray();
2778 for (unsigned int i = 0; i < ChartDirArray.GetCount(); i++) {
2779 ChartDirInfo cdi = ChartDirArray[i];
2780
2781 ChartDirInfo newcdi = cdi;
2782
2783 if (newcdi.fullpath != fd) NewChartDirArray.Add(newcdi);
2784 }
2785
2786 SetChartDirArray(NewChartDirArray);
2787 }
2788
2789 // Update the list of chart dirs.
2790 m_chartDirs.Clear();
2791 for (unsigned int i = 0; i < GetChartDirArray().GetCount(); i++) {
2792 ChartDirInfo cdi = GetChartDirArray()[i];
2793 m_chartDirs.Add(cdi.fullpath);
2794 }
2795
2796 m_nentries = active_chartTable.size();
2797 ChartData->UpdateChartDatabaseInplace(m_dir_array, false, nullptr);
2798
2799 return rv;
2800}
2801
2803// Create a Chart object
2805
2806ChartBase *ChartDatabase::GetChart(const wxChar *theFilePath,
2807 ChartClassDescriptor &chart_desc) const {
2808 // TODO: support non-UI chart factory
2809 return NULL;
2810}
2811
2813// Create Chart Table entry by reading chart header info, etc.
2815
2816ChartTableEntry *ChartDatabase::CreateChartTableEntry(
2817 const wxString &filePath, wxString &utf8Path,
2818 ChartClassDescriptor &chart_desc) {
2819 wxString msg_fn(filePath);
2820 msg_fn.Replace("%", "%%");
2821 wxLogMessage(wxString::Format("Loading chart data for %s", msg_fn.c_str()));
2822
2823 ChartBase *pch = GetChart(filePath, chart_desc);
2824 if (pch == NULL) {
2825 wxLogMessage(
2826 wxString::Format(" ...creation failed for %s", msg_fn.c_str()));
2827 return NULL;
2828 }
2829
2830 InitReturn rc = pch->Init(filePath, HEADER_ONLY);
2831 if (rc != INIT_OK) {
2832 delete pch;
2833 wxLogMessage(
2834 wxString::Format(" ...initialization failed for %s", msg_fn.c_str()));
2835 return NULL;
2836 }
2837
2838 ChartTableEntry *ret_val = new ChartTableEntry(*pch, utf8Path);
2839 ret_val->SetValid(true);
2840
2841 delete pch;
2842
2843 return ret_val;
2844}
2845
2846bool ChartDatabase::GetCentroidOfLargestScaleChart(double *clat, double *clon,
2847 ChartFamilyEnum family) {
2848 int cur_max_i = -1;
2849 int cur_max_scale = 0;
2850
2851 int nEntry = active_chartTable.size();
2852
2853 for (int i = 0; i < nEntry; i++) {
2854 auto &cte_fam = GetChartTableEntry(i);
2855 if (GetChartFamily(cte_fam.GetChartType()) == family) {
2856 if (cte_fam.GetScale() > cur_max_scale) {
2857 cur_max_scale = cte_fam.GetScale();
2858 cur_max_i = i;
2859 }
2860 }
2861 }
2862
2863 if (cur_max_i == -1)
2864 return false; // nothing found
2865 else {
2866 auto &cte_sel = GetChartTableEntry(cur_max_i);
2867 *clat = (cte_sel.GetLatMax() + cte_sel.GetLatMin()) / 2.;
2868 *clon = (cte_sel.GetLonMin() + cte_sel.GetLonMax()) / 2.;
2869 }
2870 return true;
2871}
2872
2873//-------------------------------------------------------------------
2874// Get DBChart Projection
2875//-------------------------------------------------------------------
2876int ChartDatabase::GetDBChartProj(int dbIndex) {
2877 if ((bValid) && (dbIndex >= 0) && (dbIndex < (int)active_chartTable.size())) {
2878 auto &cte = GetChartTableEntry(dbIndex);
2879 return cte.GetChartProjectionType();
2880 } else
2881 return PROJECTION_UNKNOWN;
2882}
2883
2884//-------------------------------------------------------------------
2885// Get DBChart Family
2886//-------------------------------------------------------------------
2887int ChartDatabase::GetDBChartFamily(int dbIndex) {
2888 if ((bValid) && (dbIndex >= 0) && (dbIndex < (int)active_chartTable.size())) {
2889 auto &cte = GetChartTableEntry(dbIndex);
2890 return cte.GetChartFamily();
2891 } else
2892 return CHART_FAMILY_UNKNOWN;
2893}
2894
2895//-------------------------------------------------------------------
2896// Get DBChart FullFileName
2897//-------------------------------------------------------------------
2898wxString ChartDatabase::GetDBChartFileName(int dbIndex) {
2899 if ((bValid) && (dbIndex >= 0) && (dbIndex < (int)active_chartTable.size())) {
2900 auto &cte = GetChartTableEntry(dbIndex);
2901 return wxString(cte.GetFullSystemPath());
2902 } else
2903 return "";
2904}
2905
2906//-------------------------------------------------------------------
2907// Get DBChart Type
2908//-------------------------------------------------------------------
2909int ChartDatabase::GetDBChartType(int dbIndex) {
2910 if ((bValid) && (dbIndex >= 0) && (dbIndex < (int)active_chartTable.size())) {
2911 auto &cte = GetChartTableEntry(dbIndex);
2912 return cte.GetChartType();
2913 } else
2914 return 0;
2915}
2916
2917//-------------------------------------------------------------------
2918// Get DBChart Skew
2919//-------------------------------------------------------------------
2920float ChartDatabase::GetDBChartSkew(int dbIndex) {
2921 if ((bValid) && (dbIndex >= 0) && (dbIndex < (int)active_chartTable.size())) {
2922 auto &cte = GetChartTableEntry(dbIndex);
2923 return cte.GetChartSkew();
2924 } else
2925 return 0.;
2926}
2927
2928//-------------------------------------------------------------------
2929// Get DBChart Scale
2930//-------------------------------------------------------------------
2931int ChartDatabase::GetDBChartScale(int dbIndex) {
2932 if ((bValid) && (dbIndex >= 0) && (dbIndex < (int)active_chartTable.size())) {
2933 auto &cte = GetChartTableEntry(dbIndex);
2934 return cte.GetScale();
2935 } else
2936 return 1;
2937}
2938
2939//-------------------------------------------------------------------
2940// Get Lat/Lon Bounding Box from db
2941//-------------------------------------------------------------------
2942bool ChartDatabase::GetDBBoundingBox(int dbIndex, LLBBox &box) {
2943 if ((bValid) && (dbIndex >= 0) && (dbIndex < (int)active_chartTable.size())) {
2944 auto &entry = GetChartTableEntry(dbIndex);
2945 box.Set(entry.GetLatMin(), entry.GetLonMin(), entry.GetLatMax(),
2946 entry.GetLonMax());
2947 }
2948
2949 return true;
2950}
2951
2952const LLBBox &ChartDatabase::GetDBBoundingBox(int dbIndex) {
2953 if ((bValid) && (dbIndex >= 0)) {
2954 auto &entry = GetChartTableEntry(dbIndex);
2955 return entry.GetBBox();
2956 } else {
2957 return m_dummy_bbox;
2958 }
2959}
2960
2961//-------------------------------------------------------------------
2962// Get PlyPoint from Database
2963//-------------------------------------------------------------------
2964int ChartDatabase::GetDBPlyPoint(int dbIndex, int plyindex, float *lat,
2965 float *lon) {
2966 if ((bValid) && (dbIndex >= 0) && (dbIndex < (int)active_chartTable.size())) {
2967 const ChartTableEntry &entry = GetChartTableEntry(dbIndex);
2968 if (entry.GetnPlyEntries()) {
2969 float *fp = entry.GetpPlyTable();
2970 fp += plyindex * 2;
2971 if (lat) *lat = *fp;
2972 fp++;
2973 if (lon) *lon = *fp;
2974 }
2975 return entry.GetnPlyEntries();
2976 } else
2977 return 0;
2978}
2979
2980//-------------------------------------------------------------------
2981// Get AuxPlyPoint from Database
2982//-------------------------------------------------------------------
2983int ChartDatabase::GetDBAuxPlyPoint(int dbIndex, int plyindex, int ply,
2984 float *lat, float *lon) {
2985 if ((bValid) && (dbIndex >= 0) && (dbIndex < (int)active_chartTable.size())) {
2986 const ChartTableEntry &entry = GetChartTableEntry(dbIndex);
2987 if (entry.GetnAuxPlyEntries()) {
2988 float *fp = entry.GetpAuxPlyTableEntry(ply);
2989
2990 fp += plyindex * 2;
2991 if (lat) *lat = *fp;
2992 fp++;
2993 if (lon) *lon = *fp;
2994 }
2995
2996 return entry.GetAuxCntTableEntry(ply);
2997 } else
2998 return 0;
2999}
3000
3001int ChartDatabase::GetnAuxPlyEntries(int dbIndex) {
3002 if ((bValid) && (dbIndex >= 0) && (dbIndex < (int)active_chartTable.size())) {
3003 const ChartTableEntry &entry = GetChartTableEntry(dbIndex);
3004 return entry.GetnAuxPlyEntries();
3005 } else
3006 return 0;
3007}
3008
3009//-------------------------------------------------------------------
3010// Get vector of reduced Plypoints
3011//-------------------------------------------------------------------
3012std::vector<float> ChartDatabase::GetReducedPlyPoints(int dbIndex) {
3013 if ((bValid) && (dbIndex >= 0) && (dbIndex < (int)active_chartTable.size())) {
3014 ChartTableEntry &cte = GetChartTableEntry(dbIndex);
3015 return cte.GetReducedPlyPoints();
3016 }
3017
3018 std::vector<float> dummy;
3019 return dummy;
3020}
3021
3022//-------------------------------------------------------------------
3023// Get vector of reduced AuxPlypoints
3024//-------------------------------------------------------------------
3025std::vector<float> ChartDatabase::GetReducedAuxPlyPoints(int dbIndex,
3026 int iTable) {
3027 if ((bValid) && (dbIndex >= 0) && (dbIndex < (int)active_chartTable.size())) {
3028 auto &cte = GetChartTableEntry(dbIndex);
3029 return cte.GetReducedAuxPlyPoints(iTable);
3030 }
3031
3032 std::vector<float> dummy;
3033 return dummy;
3034}
3035
3036bool ChartDatabase::IsChartAvailable(int dbIndex) {
3037 if ((bValid) && (dbIndex >= 0) && (dbIndex < (int)active_chartTable.size())) {
3038 auto &cte = GetChartTableEntry(dbIndex);
3039
3040 // If not PLugIn chart, assume always available
3041 if (cte.GetChartType() != CHART_TYPE_PLUGIN) return true;
3042
3043 wxString *path = cte.GetpsFullPath();
3044 wxFileName fn(*path);
3045 wxString ext = fn.GetExt();
3046 ext.Prepend("*.");
3047 wxString ext_upper = ext.MakeUpper();
3048 wxString ext_lower = ext.MakeLower();
3049
3050 // Search the array of chart class descriptors to find a match
3051 // between the search mask and the the chart file extension
3052
3053 for (auto &cd : m_ChartClassDescriptorArray) {
3054 if (cd.m_descriptor_type == PLUGIN_DESCRIPTOR) {
3055 wxString search_mask = cd.m_search_mask;
3056
3057 if (search_mask == ext_upper) {
3058 return true;
3059 }
3060 if (search_mask == ext_lower) {
3061 return true;
3062 }
3063 if (path->Matches(search_mask)) {
3064 return true;
3065 }
3066 }
3067 }
3068 }
3069
3070 return false;
3071}
3072
3073void ChartDatabase::ApplyGroupArray(ChartGroupArray *pGroupArray) {
3074 wxString separator(wxFileName::GetPathSeparator());
3075
3076 for (unsigned int ic = 0; ic < active_chartTable.size(); ic++) {
3077 auto &cte = GetChartTableEntry(ic);
3078
3079 cte.ClearGroupArray();
3080
3081 wxString *chart_full_path = cte.GetpsFullPath();
3082
3083 for (unsigned int igroup = 0; igroup < pGroupArray->GetCount(); igroup++) {
3084 ChartGroup *pGroup = pGroupArray->Item(igroup);
3085 for (const auto &elem : pGroup->m_element_array) {
3086 wxString element_root = elem.m_element_name;
3087
3088 // The element may be a full single chart name
3089 // If so, add it
3090 // Otherwise, append a sep character so that similar paths are
3091 // distinguished. See FS#1060
3092 if (!chart_full_path->IsSameAs(element_root))
3093 element_root.Append(
3094 separator); // Prevent comingling similar looking path names
3095 if (chart_full_path->StartsWith(element_root)) {
3096 bool b_add = true;
3097 for (unsigned int k = 0; k < elem.m_missing_name_array.size(); k++) {
3098 const wxString &missing_item = elem.m_missing_name_array[k];
3099 if (chart_full_path->StartsWith(missing_item)) {
3100 if (chart_full_path->IsSameAs(
3101 missing_item)) // missing item is full chart name
3102 {
3103 b_add = false;
3104 break;
3105 } else {
3106 if (wxDir::Exists(missing_item)) // missing item is a dir
3107 {
3108 b_add = false;
3109 break;
3110 }
3111 }
3112 }
3113 }
3114
3115 if (b_add) cte.AddIntToGroupArray(igroup + 1);
3116 }
3117 }
3118 }
3119 }
3120}
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:486
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