LCOV - code coverage report
Current view: top level - ogr/ogrsf_frmts/gpx - ogrgpxdatasource.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 375 410 91.5 %
Date: 2026-11-18 01:45:17 Functions: 15 15 100.0 %

          Line data    Source code
       1             : /******************************************************************************
       2             :  *
       3             :  * Project:  GPX Translator
       4             :  * Purpose:  Implements OGRGPXDataSource class
       5             :  * Author:   Even Rouault, even dot rouault at spatialys.com
       6             :  *
       7             :  ******************************************************************************
       8             :  * Copyright (c) 2007-2011, Even Rouault <even dot rouault at spatialys.com>
       9             :  *
      10             :  * SPDX-License-Identifier: MIT
      11             :  ****************************************************************************/
      12             : 
      13             : #include "cpl_port.h"
      14             : #include "ogr_gpx.h"
      15             : 
      16             : #include <algorithm>
      17             : #include <cstdarg>
      18             : #include <cstdio>
      19             : #include <cstring>
      20             : 
      21             : #include "cpl_conv.h"
      22             : #include "cpl_csv.h"
      23             : #include "cpl_error.h"
      24             : #include "cpl_string.h"
      25             : #include "cpl_vsi.h"
      26             : #ifdef HAVE_EXPAT
      27             : #include "expat.h"
      28             : #endif
      29             : #include "ogr_core.h"
      30             : #include "ogr_expat.h"
      31             : #include "ogr_spatialref.h"
      32             : #include "ogrsf_frmts.h"
      33             : #include "ogr_p.h"
      34             : 
      35             : constexpr int SPACE_FOR_METADATA_BOUNDS = 160;
      36             : 
      37             : /************************************************************************/
      38             : /*                         ~OGRGPXDataSource()                          */
      39             : /************************************************************************/
      40             : 
      41         112 : OGRGPXDataSource::~OGRGPXDataSource()
      42             : 
      43             : {
      44          56 :     if (m_fpOutput != nullptr)
      45             :     {
      46          24 :         if (m_nLastRteId != -1)
      47           1 :             PrintLine("</rte>");
      48          23 :         else if (m_nLastTrkId != -1)
      49             :         {
      50           2 :             PrintLine("  </trkseg>");
      51           2 :             PrintLine("</trk>");
      52             :         }
      53          24 :         PrintLine("</gpx>");
      54          24 :         if (m_bIsBackSeekable)
      55             :         {
      56             :             /* Write the <bounds> element in the reserved space */
      57          24 :             if (m_dfMinLon <= m_dfMaxLon)
      58             :             {
      59             :                 char szBounds[SPACE_FOR_METADATA_BOUNDS + 1];
      60             :                 int nRet =
      61          11 :                     CPLsnprintf(szBounds, SPACE_FOR_METADATA_BOUNDS,
      62             :                                 "<bounds minlat=\"%.15f\" minlon=\"%.15f\""
      63             :                                 " maxlat=\"%.15f\" maxlon=\"%.15f\"/>",
      64             :                                 m_dfMinLat, m_dfMinLon, m_dfMaxLat, m_dfMaxLon);
      65          11 :                 if (nRet < SPACE_FOR_METADATA_BOUNDS)
      66             :                 {
      67          11 :                     m_fpOutput->Seek(m_nOffsetBounds, SEEK_SET);
      68          11 :                     m_fpOutput->Write(szBounds, 1, strlen(szBounds));
      69             :                 }
      70             :             }
      71             :         }
      72             :     }
      73         112 : }
      74             : 
      75             : /************************************************************************/
      76             : /*                           TestCapability()                           */
      77             : /************************************************************************/
      78             : 
      79          32 : bool OGRGPXDataSource::TestCapability(const char *pszCap) const
      80             : 
      81             : {
      82          32 :     if (EQUAL(pszCap, ODsCCreateLayer))
      83          23 :         return TRUE;
      84           9 :     else if (EQUAL(pszCap, ODsCDeleteLayer))
      85           6 :         return FALSE;
      86           3 :     else if (EQUAL(pszCap, ODsCZGeometries))
      87           0 :         return TRUE;
      88             : 
      89           3 :     return FALSE;
      90             : }
      91             : 
      92             : /************************************************************************/
      93             : /*                              GetLayer()                              */
      94             : /************************************************************************/
      95             : 
      96         159 : const OGRLayer *OGRGPXDataSource::GetLayer(int iLayer) const
      97             : 
      98             : {
      99         159 :     if (iLayer < 0 || iLayer >= static_cast<int>(m_apoLayers.size()))
     100           0 :         return nullptr;
     101             : 
     102         159 :     return m_apoLayers[iLayer].get();
     103             : }
     104             : 
     105             : /************************************************************************/
     106             : /*                            ICreateLayer()                            */
     107             : /************************************************************************/
     108             : 
     109             : OGRLayer *
     110          30 : OGRGPXDataSource::ICreateLayer(const char *pszLayerName,
     111             :                                const OGRGeomFieldDefn *poGeomFieldDefn,
     112             :                                CSLConstList papszOptions)
     113             : {
     114             :     GPXGeometryType gpxGeomType;
     115          30 :     const auto eType = poGeomFieldDefn ? poGeomFieldDefn->GetType() : wkbNone;
     116          30 :     if (eType == wkbPoint || eType == wkbPoint25D)
     117             :     {
     118          10 :         if (EQUAL(pszLayerName, "track_points"))
     119           2 :             gpxGeomType = GPX_TRACK_POINT;
     120           8 :         else if (EQUAL(pszLayerName, "route_points"))
     121           2 :             gpxGeomType = GPX_ROUTE_POINT;
     122             :         else
     123           6 :             gpxGeomType = GPX_WPT;
     124             :     }
     125          20 :     else if (eType == wkbLineString || eType == wkbLineString25D)
     126             :     {
     127             :         const char *pszForceGPXTrack =
     128           5 :             CSLFetchNameValue(papszOptions, "FORCE_GPX_TRACK");
     129           5 :         if (pszForceGPXTrack && CPLTestBool(pszForceGPXTrack))
     130           0 :             gpxGeomType = GPX_TRACK;
     131             :         else
     132           5 :             gpxGeomType = GPX_ROUTE;
     133             :     }
     134          15 :     else if (eType == wkbMultiLineString || eType == wkbMultiLineString25D)
     135             :     {
     136             :         const char *pszForceGPXRoute =
     137           5 :             CSLFetchNameValue(papszOptions, "FORCE_GPX_ROUTE");
     138           5 :         if (pszForceGPXRoute && CPLTestBool(pszForceGPXRoute))
     139           0 :             gpxGeomType = GPX_ROUTE;
     140             :         else
     141           5 :             gpxGeomType = GPX_TRACK;
     142             :     }
     143          10 :     else if (eType == wkbUnknown)
     144             :     {
     145           1 :         CPLError(CE_Failure, CPLE_NotSupported,
     146             :                  "Cannot create GPX layer %s with unknown geometry type",
     147             :                  pszLayerName);
     148           1 :         return nullptr;
     149             :     }
     150             :     else
     151             :     {
     152           9 :         CPLError(CE_Failure, CPLE_NotSupported,
     153             :                  "Geometry type of `%s' not supported in GPX.\n",
     154             :                  OGRGeometryTypeToName(eType));
     155           9 :         return nullptr;
     156             :     }
     157          20 :     m_apoLayers.emplace_back(std::make_unique<OGRGPXLayer>(
     158          20 :         GetDescription(), pszLayerName, gpxGeomType, this, true, nullptr));
     159             : 
     160          20 :     return m_apoLayers.back().get();
     161             : }
     162             : 
     163             : #ifdef HAVE_EXPAT
     164             : 
     165             : /************************************************************************/
     166             : /*                      startElementValidateCbk()                       */
     167             : /************************************************************************/
     168             : 
     169        1277 : void OGRGPXDataSource::startElementValidateCbk(const char *pszNameIn,
     170             :                                                const char **ppszAttr)
     171             : {
     172        1277 :     if (m_validity == GPX_VALIDITY_UNKNOWN)
     173             :     {
     174          31 :         if (strcmp(pszNameIn, "gpx") == 0)
     175             :         {
     176          31 :             m_validity = GPX_VALIDITY_VALID;
     177         178 :             for (int i = 0; ppszAttr[i] != nullptr; i += 2)
     178             :             {
     179         147 :                 if (strcmp(ppszAttr[i], "version") == 0)
     180             :                 {
     181          31 :                     m_osVersion = ppszAttr[i + 1];
     182             :                 }
     183         116 :                 else if (strcmp(ppszAttr[i], "xmlns:ogr") == 0)
     184             :                 {
     185           1 :                     m_bUseExtensions = true;
     186             :                 }
     187             :             }
     188             :         }
     189             :         else
     190             :         {
     191           0 :             m_validity = GPX_VALIDITY_INVALID;
     192             :         }
     193             :     }
     194        1246 :     else if (m_validity == GPX_VALIDITY_VALID)
     195             :     {
     196             :         // Any <extensions> element, at any level means the file uses extensions
     197        1246 :         if (strcmp(pszNameIn, "extensions") == 0)
     198             :         {
     199          22 :             m_bUseExtensions = true;
     200             :         }
     201             : 
     202        1246 :         if (m_nDepth == 1 && strcmp(pszNameIn, "metadata") == 0)
     203             :         {
     204          29 :             m_bInMetadata = true;
     205             :         }
     206        1217 :         else if (m_nDepth == 2 && m_bInMetadata)
     207             :         {
     208         159 :             if (strcmp(pszNameIn, "name") == 0)
     209             :             {
     210          17 :                 m_osMetadataKey = "NAME";
     211             :             }
     212         142 :             else if (strcmp(pszNameIn, "desc") == 0)
     213             :             {
     214          17 :                 m_osMetadataKey = "DESCRIPTION";
     215             :             }
     216         125 :             else if (strcmp(pszNameIn, "time") == 0)
     217             :             {
     218          19 :                 m_osMetadataKey = "TIME";
     219             :             }
     220         106 :             else if (strcmp(pszNameIn, "author") == 0)
     221             :             {
     222          14 :                 m_bInMetadataAuthor = true;
     223             :             }
     224          92 :             else if (strcmp(pszNameIn, "keywords") == 0)
     225             :             {
     226          17 :                 m_osMetadataKey = "KEYWORDS";
     227             :             }
     228          75 :             else if (strcmp(pszNameIn, "copyright") == 0)
     229             :             {
     230          14 :                 std::string osAuthor;
     231          28 :                 for (int i = 0; ppszAttr[i] != nullptr; i += 2)
     232             :                 {
     233          14 :                     if (strcmp(ppszAttr[i], "author") == 0)
     234             :                     {
     235          14 :                         osAuthor = ppszAttr[i + 1];
     236             :                     }
     237             :                 }
     238          14 :                 if (!osAuthor.empty())
     239             :                 {
     240          14 :                     SetMetadataItem("COPYRIGHT_AUTHOR", osAuthor.c_str());
     241             :                 }
     242          14 :                 m_bInMetadataCopyright = true;
     243             :             }
     244          61 :             else if (strcmp(pszNameIn, "link") == 0)
     245             :             {
     246          34 :                 ++m_nMetadataLinkCounter;
     247          34 :                 std::string osHref;
     248          68 :                 for (int i = 0; ppszAttr[i] != nullptr; i += 2)
     249             :                 {
     250          34 :                     if (strcmp(ppszAttr[i], "href") == 0)
     251             :                     {
     252          34 :                         osHref = ppszAttr[i + 1];
     253             :                     }
     254             :                 }
     255          34 :                 if (!osHref.empty())
     256             :                 {
     257          34 :                     SetMetadataItem(
     258             :                         CPLSPrintf("LINK_%d_HREF", m_nMetadataLinkCounter),
     259          34 :                         osHref.c_str());
     260             :                 }
     261          34 :                 m_bInMetadataLink = true;
     262         159 :             }
     263             :         }
     264        1058 :         else if (m_nDepth == 3 && m_bInMetadataAuthor)
     265             :         {
     266          42 :             if (strcmp(pszNameIn, "name") == 0)
     267             :             {
     268          14 :                 m_osMetadataKey = "AUTHOR_NAME";
     269             :             }
     270          28 :             else if (strcmp(pszNameIn, "email") == 0)
     271             :             {
     272          28 :                 std::string osId, osDomain;
     273          42 :                 for (int i = 0; ppszAttr[i] != nullptr; i += 2)
     274             :                 {
     275          28 :                     if (strcmp(ppszAttr[i], "id") == 0)
     276             :                     {
     277          14 :                         osId = ppszAttr[i + 1];
     278             :                     }
     279          14 :                     else if (strcmp(ppszAttr[i], "domain") == 0)
     280             :                     {
     281          14 :                         osDomain = ppszAttr[i + 1];
     282             :                     }
     283             :                 }
     284          14 :                 if (!osId.empty() && !osDomain.empty())
     285             :                 {
     286          14 :                     SetMetadataItem("AUTHOR_EMAIL",
     287          14 :                                     osId.append("@").append(osDomain).c_str());
     288             :                 }
     289             :             }
     290          14 :             else if (strcmp(pszNameIn, "link") == 0)
     291             :             {
     292          14 :                 std::string osHref;
     293          28 :                 for (int i = 0; ppszAttr[i] != nullptr; i += 2)
     294             :                 {
     295          14 :                     if (strcmp(ppszAttr[i], "href") == 0)
     296             :                     {
     297          14 :                         osHref = ppszAttr[i + 1];
     298             :                     }
     299             :                 }
     300          14 :                 if (!osHref.empty())
     301             :                 {
     302          14 :                     SetMetadataItem("AUTHOR_LINK_HREF", osHref.c_str());
     303             :                 }
     304          14 :                 m_bInMetadataAuthorLink = true;
     305          42 :             }
     306             :         }
     307        1016 :         else if (m_nDepth == 3 && m_bInMetadataCopyright)
     308             :         {
     309          28 :             if (strcmp(pszNameIn, "year") == 0)
     310             :             {
     311          14 :                 m_osMetadataKey = "COPYRIGHT_YEAR";
     312             :             }
     313          14 :             else if (strcmp(pszNameIn, "license") == 0)
     314             :             {
     315          14 :                 m_osMetadataKey = "COPYRIGHT_LICENSE";
     316             :             }
     317             :         }
     318         988 :         else if (m_nDepth == 3 && m_bInMetadataLink)
     319             :         {
     320         314 :             if (strcmp(pszNameIn, "text") == 0)
     321             :             {
     322             :                 m_osMetadataKey =
     323          82 :                     CPLSPrintf("LINK_%d_TEXT", m_nMetadataLinkCounter);
     324             :             }
     325         232 :             else if (strcmp(pszNameIn, "type") == 0)
     326             :             {
     327             :                 m_osMetadataKey =
     328          82 :                     CPLSPrintf("LINK_%d_TYPE", m_nMetadataLinkCounter);
     329             :             }
     330             :         }
     331         674 :         else if (m_nDepth == 4 && m_bInMetadataAuthorLink)
     332             :         {
     333          28 :             if (strcmp(pszNameIn, "text") == 0)
     334             :             {
     335          14 :                 m_osMetadataKey = "AUTHOR_LINK_TEXT";
     336             :             }
     337          14 :             else if (strcmp(pszNameIn, "type") == 0)
     338             :             {
     339          14 :                 m_osMetadataKey = "AUTHOR_LINK_TYPE";
     340             :             }
     341             :         }
     342             :     }
     343        1277 :     m_nDepth++;
     344        1277 : }
     345             : 
     346             : /************************************************************************/
     347             : /*                       endElementValidateCbk()                        */
     348             : /************************************************************************/
     349             : 
     350        1277 : void OGRGPXDataSource::endElementValidateCbk(const char * /*pszName */)
     351             : {
     352        1277 :     m_nDepth--;
     353        1277 :     if (m_nDepth == 4 && m_bInMetadataAuthorLink)
     354             :     {
     355          28 :         if (!m_osMetadataKey.empty())
     356             :         {
     357          28 :             SetMetadataItem(m_osMetadataKey.c_str(), m_osMetadataValue.c_str());
     358             :         }
     359          28 :         m_osMetadataKey.clear();
     360          28 :         m_osMetadataValue.clear();
     361             :     }
     362        1249 :     else if (m_nDepth == 3 && (m_bInMetadataAuthor || m_bInMetadataCopyright ||
     363         344 :                                m_bInMetadataLink))
     364             :     {
     365         384 :         if (!m_osMetadataKey.empty())
     366             :         {
     367         206 :             SetMetadataItem(m_osMetadataKey.c_str(), m_osMetadataValue.c_str());
     368             :         }
     369         384 :         m_osMetadataKey.clear();
     370         384 :         m_osMetadataValue.clear();
     371         384 :         m_bInMetadataAuthorLink = false;
     372             :     }
     373         865 :     else if (m_nDepth == 2 && m_bInMetadata)
     374             :     {
     375         159 :         if (!m_osMetadataKey.empty())
     376             :         {
     377          70 :             SetMetadataItem(m_osMetadataKey.c_str(), m_osMetadataValue.c_str());
     378             :         }
     379         159 :         m_osMetadataKey.clear();
     380         159 :         m_osMetadataValue.clear();
     381         159 :         m_bInMetadataAuthor = false;
     382         159 :         m_bInMetadataCopyright = false;
     383             :     }
     384         706 :     else if (m_nDepth == 1 && m_bInMetadata)
     385             :     {
     386          29 :         m_bInMetadata = false;
     387             :     }
     388        1277 : }
     389             : 
     390             : /************************************************************************/
     391             : /*                       dataHandlerValidateCbk()                       */
     392             : /************************************************************************/
     393             : 
     394        3375 : void OGRGPXDataSource::dataHandlerValidateCbk(const char *data, int nLen)
     395             : {
     396        3375 :     if (!m_osMetadataKey.empty())
     397             :     {
     398         304 :         m_osMetadataValue.append(data, nLen);
     399             :     }
     400             : 
     401        3375 :     m_nDataHandlerCounter++;
     402        3375 :     if (m_nDataHandlerCounter >= PARSER_BUF_SIZE)
     403             :     {
     404           0 :         CPLError(CE_Failure, CPLE_AppDefined,
     405             :                  "File probably corrupted (million laugh pattern)");
     406           0 :         XML_StopParser(m_oCurrentParser, XML_FALSE);
     407             :     }
     408        3375 : }
     409             : 
     410        1277 : static void XMLCALL startElementValidateCbk(void *pUserData,
     411             :                                             const char *pszName,
     412             :                                             const char **ppszAttr)
     413             : {
     414        1277 :     OGRGPXDataSource *poDS = static_cast<OGRGPXDataSource *>(pUserData);
     415        1277 :     poDS->startElementValidateCbk(pszName, ppszAttr);
     416        1277 : }
     417             : 
     418        1277 : static void XMLCALL endElementValidateCbk(void *pUserData, const char *pszName)
     419             : {
     420        1277 :     OGRGPXDataSource *poDS = static_cast<OGRGPXDataSource *>(pUserData);
     421        1277 :     poDS->endElementValidateCbk(pszName);
     422        1277 : }
     423             : 
     424        3375 : static void XMLCALL dataHandlerValidateCbk(void *pUserData, const char *data,
     425             :                                            int nLen)
     426             : {
     427        3375 :     OGRGPXDataSource *poDS = static_cast<OGRGPXDataSource *>(pUserData);
     428        3375 :     poDS->dataHandlerValidateCbk(data, nLen);
     429        3375 : }
     430             : #endif
     431             : 
     432             : /************************************************************************/
     433             : /*                                Open()                                */
     434             : /************************************************************************/
     435             : 
     436          31 : int OGRGPXDataSource::Open(GDALOpenInfo *poOpenInfo)
     437             : 
     438             : {
     439          31 :     const char *pszFilename = poOpenInfo->pszFilename;
     440          31 :     if (poOpenInfo->eAccess == GA_Update)
     441             :     {
     442           0 :         CPLError(CE_Failure, CPLE_NotSupported,
     443             :                  "OGR/GPX driver does not support opening a file in "
     444             :                  "update mode");
     445           0 :         return FALSE;
     446             :     }
     447             : #ifdef HAVE_EXPAT
     448          31 :     SetDescription(pszFilename);
     449             : 
     450             :     /* -------------------------------------------------------------------- */
     451             :     /*      Try to open the file.                                           */
     452             :     /* -------------------------------------------------------------------- */
     453          31 :     VSILFILE *fp = VSIFOpenL(pszFilename, "r");
     454          31 :     if (fp == nullptr)
     455           0 :         return FALSE;
     456             : 
     457          31 :     m_validity = GPX_VALIDITY_UNKNOWN;
     458             : 
     459          31 :     XML_Parser oParser = OGRCreateExpatXMLParser();
     460          31 :     m_oCurrentParser = oParser;
     461          31 :     XML_SetUserData(oParser, this);
     462          31 :     XML_SetElementHandler(oParser, ::startElementValidateCbk,
     463             :                           ::endElementValidateCbk);
     464          31 :     XML_SetCharacterDataHandler(oParser, ::dataHandlerValidateCbk);
     465             : 
     466          31 :     std::vector<char> aBuf(PARSER_BUF_SIZE);
     467          31 :     int nDone = 0;
     468          31 :     unsigned int nLen = 0;
     469          31 :     int nCount = 0;
     470             : 
     471             :     /* Begin to parse the file and look for the <gpx> element */
     472             :     /* It *MUST* be the first element of an XML file */
     473             :     /* So once we have read the first element, we know if we can */
     474             :     /* handle the file or not with that driver */
     475          31 :     uint64_t nTotalBytesRead = 0;
     476           0 :     do
     477             :     {
     478          31 :         m_nDataHandlerCounter = 0;
     479          31 :         nLen = static_cast<unsigned int>(
     480          31 :             VSIFReadL(aBuf.data(), 1, aBuf.size(), fp));
     481          31 :         nTotalBytesRead += nLen;
     482          31 :         nDone = (nLen < aBuf.size());
     483          31 :         if (XML_Parse(oParser, aBuf.data(), nLen, nDone) == XML_STATUS_ERROR)
     484             :         {
     485           0 :             if (nLen <= PARSER_BUF_SIZE - 1)
     486           0 :                 aBuf[nLen] = 0;
     487             :             else
     488           0 :                 aBuf[PARSER_BUF_SIZE - 1] = 0;
     489           0 :             if (strstr(aBuf.data(), "<?xml") && strstr(aBuf.data(), "<gpx"))
     490             :             {
     491           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
     492             :                          "XML parsing of GPX file failed: %s",
     493             :                          OGRExpatGetParseError(oParser));
     494             :             }
     495           0 :             m_validity = GPX_VALIDITY_INVALID;
     496           0 :             break;
     497             :         }
     498          31 :         if (m_validity == GPX_VALIDITY_INVALID)
     499             :         {
     500           0 :             break;
     501             :         }
     502          31 :         else if (m_validity == GPX_VALIDITY_VALID)
     503             :         {
     504             :             /* If we have recognized the <gpx> element, now we try */
     505             :             /* to recognize if they are <extensions> tags */
     506             :             /* But we stop to look for after an arbitrary amount of bytes */
     507          31 :             if (m_bUseExtensions)
     508          17 :                 break;
     509          14 :             else if (nTotalBytesRead > 1024 * 1024)
     510           0 :                 break;
     511             :         }
     512             :         else
     513             :         {
     514             :             // After reading 50 * PARSER_BUF_SIZE bytes, and not finding whether the
     515             :             // file is GPX or not, we give up and fail silently.
     516           0 :             nCount++;
     517           0 :             if (nCount == 50)
     518           0 :                 break;
     519             :         }
     520          14 :     } while (!nDone && nLen > 0);
     521             : 
     522          31 :     XML_ParserFree(oParser);
     523             : 
     524          31 :     VSIFCloseL(fp);
     525             : 
     526          31 :     if (m_validity == GPX_VALIDITY_VALID)
     527             :     {
     528          31 :         CPLDebug("GPX", "%s seems to be a GPX file.", pszFilename);
     529          31 :         if (m_bUseExtensions)
     530          17 :             CPLDebug("GPX", "It uses <extensions>");
     531             : 
     532          31 :         if (m_osVersion.empty())
     533             :         {
     534             :             /* Default to 1.1 */
     535           0 :             CPLError(CE_Warning, CPLE_AppDefined,
     536             :                      "GPX schema version is unknown. "
     537             :                      "The driver may not be able to handle the file correctly "
     538             :                      "and will behave as if it is GPX 1.1.");
     539           0 :             m_osVersion = "1.1";
     540             :         }
     541          31 :         else if (m_osVersion == "1.0" || m_osVersion == "1.1")
     542             :         {
     543             :             /* Fine */
     544             :         }
     545             :         else
     546             :         {
     547           0 :             CPLError(CE_Warning, CPLE_AppDefined,
     548             :                      "GPX schema version '%s' is not handled by the driver. "
     549             :                      "The driver may not be able to handle the file correctly "
     550             :                      "and will behave as if it is GPX 1.1.",
     551             :                      m_osVersion.c_str());
     552             :         }
     553             : 
     554          31 :         m_apoLayers.emplace_back(std::make_unique<OGRGPXLayer>(
     555          31 :             GetDescription(), "waypoints", GPX_WPT, this, false,
     556          62 :             poOpenInfo->papszOpenOptions));
     557          31 :         m_apoLayers.emplace_back(std::make_unique<OGRGPXLayer>(
     558          31 :             GetDescription(), "routes", GPX_ROUTE, this, false,
     559          62 :             poOpenInfo->papszOpenOptions));
     560          31 :         m_apoLayers.emplace_back(std::make_unique<OGRGPXLayer>(
     561          31 :             GetDescription(), "tracks", GPX_TRACK, this, false,
     562          62 :             poOpenInfo->papszOpenOptions));
     563          31 :         m_apoLayers.emplace_back(std::make_unique<OGRGPXLayer>(
     564          31 :             GetDescription(), "route_points", GPX_ROUTE_POINT, this, false,
     565          62 :             poOpenInfo->papszOpenOptions));
     566          31 :         m_apoLayers.emplace_back(std::make_unique<OGRGPXLayer>(
     567          62 :             GetDescription(), "track_points", GPX_TRACK_POINT, this, false,
     568          62 :             poOpenInfo->papszOpenOptions));
     569             :     }
     570             : 
     571          31 :     return m_validity == GPX_VALIDITY_VALID;
     572             : #else
     573             :     VSILFILE *fp = VSIFOpenL(pszFilename, "r");
     574             :     if (fp)
     575             :     {
     576             :         char aBuf[256];
     577             :         unsigned int nLen =
     578             :             static_cast<unsigned int>(VSIFReadL(aBuf, 1, 255, fp));
     579             :         aBuf[nLen] = 0;
     580             :         if (strstr(aBuf, "<?xml") && strstr(aBuf, "<gpx"))
     581             :         {
     582             :             CPLError(CE_Failure, CPLE_NotSupported,
     583             :                      "OGR/GPX driver has not been built with read support. "
     584             :                      "Expat library required");
     585             :         }
     586             :         VSIFCloseL(fp);
     587             :     }
     588             :     return FALSE;
     589             : #endif
     590             : }
     591             : 
     592             : /************************************************************************/
     593             : /*                               Create()                               */
     594             : /************************************************************************/
     595             : 
     596          25 : int OGRGPXDataSource::Create(const char *pszFilename, CSLConstList papszOptions)
     597             : {
     598          25 :     if (strcmp(pszFilename, "/dev/stdout") == 0)
     599           0 :         pszFilename = "/vsistdout/";
     600             : 
     601             :     /* -------------------------------------------------------------------- */
     602             :     /*     Do not overwrite exiting file.                                   */
     603             :     /* -------------------------------------------------------------------- */
     604             :     VSIStatBufL sStatBuf;
     605             : 
     606          25 :     if (VSIStatL(pszFilename, &sStatBuf) == 0)
     607             :     {
     608           0 :         CPLError(CE_Failure, CPLE_NotSupported,
     609             :                  "You have to delete %s before being able to create it with "
     610             :                  "the GPX driver",
     611             :                  pszFilename);
     612           0 :         return FALSE;
     613             :     }
     614             : 
     615             :     /* -------------------------------------------------------------------- */
     616             :     /*      Create the output file.                                         */
     617             :     /* -------------------------------------------------------------------- */
     618             : 
     619          25 :     SetDescription(pszFilename);
     620             : 
     621          25 :     if (strcmp(pszFilename, "/vsistdout/") == 0)
     622             :     {
     623           0 :         m_bIsBackSeekable = false;
     624           0 :         m_fpOutput.reset(VSIFOpenL(pszFilename, "w"));
     625             :     }
     626             :     else
     627          25 :         m_fpOutput.reset(VSIFOpenL(pszFilename, "w+"));
     628          25 :     if (m_fpOutput == nullptr)
     629             :     {
     630           1 :         CPLError(CE_Failure, CPLE_OpenFailed, "Failed to create GPX file %s.",
     631             :                  pszFilename);
     632           1 :         return FALSE;
     633             :     }
     634             : 
     635             :     /* -------------------------------------------------------------------- */
     636             :     /*      End of line character.                                          */
     637             :     /* -------------------------------------------------------------------- */
     638          24 :     const char *pszCRLFFormat = CSLFetchNameValue(papszOptions, "LINEFORMAT");
     639             : 
     640          24 :     bool bUseCRLF =
     641             : #ifdef _WIN32
     642             :         true
     643             : #else
     644             :         false
     645             : #endif
     646             :         ;
     647          24 :     if (pszCRLFFormat == nullptr)
     648             :     {
     649             :         // Use default value for OS.
     650             :     }
     651           1 :     else if (EQUAL(pszCRLFFormat, "CRLF"))
     652           0 :         bUseCRLF = true;
     653           1 :     else if (EQUAL(pszCRLFFormat, "LF"))
     654           1 :         bUseCRLF = false;
     655             :     else
     656             :     {
     657           0 :         CPLError(CE_Warning, CPLE_AppDefined,
     658             :                  "LINEFORMAT=%s not understood, use one of CRLF or LF.",
     659             :                  pszCRLFFormat);
     660             :         // Use default value for OS.
     661             :     }
     662          24 :     m_pszEOL = (bUseCRLF) ? "\r\n" : "\n";
     663             : 
     664             :     /* -------------------------------------------------------------------- */
     665             :     /*      Look at use extensions options.                                 */
     666             :     /* -------------------------------------------------------------------- */
     667             :     const char *pszUseExtensions =
     668          24 :         CSLFetchNameValue(papszOptions, "GPX_USE_EXTENSIONS");
     669          24 :     const char *pszExtensionsNSURL = nullptr;
     670          24 :     if (pszUseExtensions && CPLTestBool(pszUseExtensions))
     671             :     {
     672           1 :         m_bUseExtensions = true;
     673             : 
     674             :         const char *pszExtensionsNSOption =
     675           1 :             CSLFetchNameValue(papszOptions, "GPX_EXTENSIONS_NS");
     676             :         const char *pszExtensionsNSURLOption =
     677           1 :             CSLFetchNameValue(papszOptions, "GPX_EXTENSIONS_NS_URL");
     678           1 :         if (pszExtensionsNSOption && pszExtensionsNSURLOption)
     679             :         {
     680           0 :             m_osExtensionsNS = pszExtensionsNSOption;
     681           0 :             pszExtensionsNSURL = pszExtensionsNSURLOption;
     682             :         }
     683             :         else
     684             :         {
     685           1 :             m_osExtensionsNS = "ogr";
     686           1 :             pszExtensionsNSURL = "http://osgeo.org/gdal";
     687             :         }
     688             :     }
     689             : 
     690             :     /* -------------------------------------------------------------------- */
     691             :     /*     Output header of GPX file.                                       */
     692             :     /* -------------------------------------------------------------------- */
     693          24 :     PrintLine("<?xml version=\"1.0\"?>");
     694          24 :     m_fpOutput->Printf("<gpx version=\"1.1\" creator=\"");
     695          24 :     const char *pszCreator = CSLFetchNameValue(papszOptions, "CREATOR");
     696          24 :     if (pszCreator)
     697             :     {
     698           1 :         char *pszXML = OGRGetXML_UTF8_EscapedString(pszCreator);
     699           1 :         m_fpOutput->Printf("%s", pszXML);
     700           1 :         CPLFree(pszXML);
     701             :     }
     702             :     else
     703             :     {
     704          23 :         m_fpOutput->Printf("GDAL %s", GDALVersionInfo("RELEASE_NAME"));
     705             :     }
     706          24 :     m_fpOutput->Printf(
     707             :         "\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
     708          24 :     if (m_bUseExtensions)
     709           1 :         m_fpOutput->Printf("xmlns:%s=\"%s\" ", m_osExtensionsNS.c_str(),
     710             :                            pszExtensionsNSURL);
     711          24 :     m_fpOutput->Printf("xmlns=\"http://www.topografix.com/GPX/1/1\" ");
     712          24 :     PrintLine("xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 "
     713             :               "http://www.topografix.com/GPX/1/1/gpx.xsd\">");
     714          24 :     PrintLine("<metadata>");
     715             :     /*
     716             :     Something like:
     717             :         <metadata>
     718             :             <name>metadata name</name>
     719             :             <desc>metadata desc</desc>
     720             :             <author>
     721             :                 <name>metadata author name</name>
     722             :                 <email id="foo" domain="example.com"/>
     723             :                 <link href="author_href"><text>author_text</text><type>author_type</type></link>
     724             :             </author>
     725             :             <copyright author="copyright author"><year>2023</year><license>my license</license></copyright>
     726             :             <link href="href"><text>text</text><type>type</type></link>
     727             :             <link href="href2"><text>text2</text><type>type2</type></link>
     728             :             <time>2007-11-25T17:58:00+01:00</time>
     729             :             <keywords>kw</keywords>
     730             :             <bounds minlat="-90" minlon="-180" maxlat="90" maxlon="179.9999999"/>
     731             :         </metadata>
     732             :     */
     733             : 
     734          24 :     if (const char *pszMetadataName =
     735          24 :             CSLFetchNameValue(papszOptions, "METADATA_NAME"))
     736             :     {
     737           1 :         char *pszXML = OGRGetXML_UTF8_EscapedString(pszMetadataName);
     738           1 :         PrintLine("  <name>%s</name>", pszXML);
     739           1 :         CPLFree(pszXML);
     740             :     }
     741             : 
     742          24 :     if (const char *pszMetadataDesc =
     743          24 :             CSLFetchNameValue(papszOptions, "METADATA_DESCRIPTION"))
     744             :     {
     745           1 :         char *pszXML = OGRGetXML_UTF8_EscapedString(pszMetadataDesc);
     746           1 :         PrintLine("  <desc>%s</desc>", pszXML);
     747           1 :         CPLFree(pszXML);
     748             :     }
     749             : 
     750             :     const char *pszMetadataAuthorName =
     751          24 :         CSLFetchNameValue(papszOptions, "METADATA_AUTHOR_NAME");
     752             :     const char *pszMetadataAuthorEmail =
     753          24 :         CSLFetchNameValue(papszOptions, "METADATA_AUTHOR_EMAIL");
     754             :     const char *pszMetadataAuthorLinkHref =
     755          24 :         CSLFetchNameValue(papszOptions, "METADATA_AUTHOR_LINK_HREF");
     756          24 :     if (pszMetadataAuthorName || pszMetadataAuthorEmail ||
     757             :         pszMetadataAuthorLinkHref)
     758             :     {
     759           1 :         PrintLine("  <author>");
     760           1 :         if (pszMetadataAuthorName)
     761             :         {
     762           1 :             char *pszXML = OGRGetXML_UTF8_EscapedString(pszMetadataAuthorName);
     763           1 :             PrintLine("    <name>%s</name>", pszXML);
     764           1 :             CPLFree(pszXML);
     765             :         }
     766           1 :         if (pszMetadataAuthorEmail)
     767             :         {
     768           2 :             const std::string osEmail(pszMetadataAuthorEmail);
     769           1 :             auto nPos = osEmail.find('@');
     770           1 :             if (nPos != std::string::npos)
     771             :             {
     772           1 :                 char *pszId = OGRGetXML_UTF8_EscapedString(
     773           2 :                     osEmail.substr(0, nPos).c_str());
     774           1 :                 char *pszDomain = OGRGetXML_UTF8_EscapedString(
     775           2 :                     osEmail.substr(nPos + 1).c_str());
     776           1 :                 PrintLine("    <email id=\"%s\" domain=\"%s\"/>", pszId,
     777             :                           pszDomain);
     778           1 :                 CPLFree(pszId);
     779           1 :                 CPLFree(pszDomain);
     780             :             }
     781             :         }
     782           1 :         if (pszMetadataAuthorLinkHref)
     783             :         {
     784             :             {
     785             :                 char *pszXML =
     786           1 :                     OGRGetXML_UTF8_EscapedString(pszMetadataAuthorLinkHref);
     787           1 :                 PrintLine("    <link href=\"%s\">", pszXML);
     788           1 :                 CPLFree(pszXML);
     789             :             }
     790           1 :             if (const char *pszMetadataAuthorLinkText = CSLFetchNameValue(
     791             :                     papszOptions, "METADATA_AUTHOR_LINK_TEXT"))
     792             :             {
     793             :                 char *pszXML =
     794           1 :                     OGRGetXML_UTF8_EscapedString(pszMetadataAuthorLinkText);
     795           1 :                 PrintLine("      <text>%s</text>", pszXML);
     796           1 :                 CPLFree(pszXML);
     797             :             }
     798           1 :             if (const char *pszMetadataAuthorLinkType = CSLFetchNameValue(
     799             :                     papszOptions, "METADATA_AUTHOR_LINK_TYPE"))
     800             :             {
     801             :                 char *pszXML =
     802           1 :                     OGRGetXML_UTF8_EscapedString(pszMetadataAuthorLinkType);
     803           1 :                 PrintLine("      <type>%s</type>", pszXML);
     804           1 :                 CPLFree(pszXML);
     805             :             }
     806           1 :             PrintLine("    </link>");
     807             :         }
     808           1 :         PrintLine("  </author>");
     809             :     }
     810             : 
     811          24 :     if (const char *pszMetadataCopyrightAuthor =
     812          24 :             CSLFetchNameValue(papszOptions, "METADATA_COPYRIGHT_AUTHOR"))
     813             :     {
     814             :         {
     815             :             char *pszXML =
     816           1 :                 OGRGetXML_UTF8_EscapedString(pszMetadataCopyrightAuthor);
     817           1 :             PrintLine("  <copyright author=\"%s\">", pszXML);
     818           1 :             CPLFree(pszXML);
     819             :         }
     820           1 :         if (const char *pszMetadataCopyrightYear =
     821           1 :                 CSLFetchNameValue(papszOptions, "METADATA_COPYRIGHT_YEAR"))
     822             :         {
     823             :             char *pszXML =
     824           1 :                 OGRGetXML_UTF8_EscapedString(pszMetadataCopyrightYear);
     825           1 :             PrintLine("      <year>%s</year>", pszXML);
     826           1 :             CPLFree(pszXML);
     827             :         }
     828           1 :         if (const char *pszMetadataCopyrightLicense =
     829           1 :                 CSLFetchNameValue(papszOptions, "METADATA_COPYRIGHT_LICENSE"))
     830             :         {
     831             :             char *pszXML =
     832           1 :                 OGRGetXML_UTF8_EscapedString(pszMetadataCopyrightLicense);
     833           1 :             PrintLine("      <license>%s</license>", pszXML);
     834           1 :             CPLFree(pszXML);
     835             :         }
     836           1 :         PrintLine("  </copyright>");
     837             :     }
     838             : 
     839          45 :     for (CSLConstList papszIter = papszOptions; papszIter && *papszIter;
     840             :          ++papszIter)
     841             :     {
     842          21 :         if (STARTS_WITH_CI(*papszIter, "METADATA_LINK_") &&
     843           6 :             strstr(*papszIter, "_HREF"))
     844             :         {
     845           2 :             const int nLinkNum = atoi(*papszIter + strlen("METADATA_LINK_"));
     846           2 :             const char *pszVal = strchr(*papszIter, '=');
     847           2 :             if (pszVal)
     848             :             {
     849             :                 {
     850           2 :                     char *pszXML = OGRGetXML_UTF8_EscapedString(pszVal + 1);
     851           2 :                     PrintLine("  <link href=\"%s\">", pszXML);
     852           2 :                     CPLFree(pszXML);
     853             :                 }
     854           2 :                 if (const char *pszText = CSLFetchNameValue(
     855             :                         papszOptions,
     856             :                         CPLSPrintf("METADATA_LINK_%d_TEXT", nLinkNum)))
     857             :                 {
     858           2 :                     char *pszXML = OGRGetXML_UTF8_EscapedString(pszText);
     859           2 :                     PrintLine("      <text>%s</text>", pszXML);
     860           2 :                     CPLFree(pszXML);
     861             :                 }
     862           2 :                 if (const char *pszType = CSLFetchNameValue(
     863             :                         papszOptions,
     864             :                         CPLSPrintf("METADATA_LINK_%d_TYPE", nLinkNum)))
     865             :                 {
     866           2 :                     char *pszXML = OGRGetXML_UTF8_EscapedString(pszType);
     867           2 :                     PrintLine("      <type>%s</type>", pszXML);
     868           2 :                     CPLFree(pszXML);
     869             :                 }
     870           2 :                 PrintLine("  </link>");
     871             :             }
     872             :         }
     873             :     }
     874             : 
     875          24 :     if (const char *pszMetadataTime =
     876          24 :             CSLFetchNameValue(papszOptions, "METADATA_TIME"))
     877             :     {
     878           1 :         char *pszXML = OGRGetXML_UTF8_EscapedString(pszMetadataTime);
     879           1 :         PrintLine("  <time>%s</time>", pszXML);
     880           1 :         CPLFree(pszXML);
     881             :     }
     882             : 
     883          24 :     if (const char *pszMetadataKeywords =
     884          24 :             CSLFetchNameValue(papszOptions, "METADATA_KEYWORDS"))
     885             :     {
     886           1 :         char *pszXML = OGRGetXML_UTF8_EscapedString(pszMetadataKeywords);
     887           1 :         PrintLine("  <keywords>%s</keywords>", pszXML);
     888           1 :         CPLFree(pszXML);
     889             :     }
     890             : 
     891          24 :     if (m_bIsBackSeekable)
     892             :     {
     893             :         /* Reserve space for <bounds .../> within <metadata> */
     894             :         char szBounds[SPACE_FOR_METADATA_BOUNDS + 1];
     895          24 :         memset(szBounds, ' ', SPACE_FOR_METADATA_BOUNDS);
     896          24 :         szBounds[SPACE_FOR_METADATA_BOUNDS] = '\0';
     897          24 :         m_nOffsetBounds = m_fpOutput->Tell();
     898          24 :         PrintLine("%s", szBounds);
     899             :     }
     900          24 :     PrintLine("</metadata>");
     901             : 
     902          24 :     return TRUE;
     903             : }
     904             : 
     905             : /************************************************************************/
     906             : /*                              AddCoord()                              */
     907             : /************************************************************************/
     908             : 
     909          41 : void OGRGPXDataSource::AddCoord(double dfLon, double dfLat)
     910             : {
     911          41 :     m_dfMinLon = std::min(m_dfMinLon, dfLon);
     912          41 :     m_dfMinLat = std::min(m_dfMinLat, dfLat);
     913          41 :     m_dfMaxLon = std::max(m_dfMaxLon, dfLon);
     914          41 :     m_dfMaxLat = std::max(m_dfMaxLat, dfLat);
     915          41 : }
     916             : 
     917             : /************************************************************************/
     918             : /*                             PrintLine()                              */
     919             : /************************************************************************/
     920             : 
     921         372 : void OGRGPXDataSource::PrintLine(const char *fmt, ...)
     922             : {
     923         744 :     CPLString osWork;
     924             :     va_list args;
     925             : 
     926         372 :     va_start(args, fmt);
     927         372 :     osWork.vPrintf(fmt, args);
     928         372 :     va_end(args);
     929             : 
     930         372 :     m_fpOutput->Write(osWork.c_str(), 1, osWork.size());
     931         372 :     m_fpOutput->Write(m_pszEOL, 1, strlen(m_pszEOL));
     932         372 : }

Generated by: LCOV version 1.14