LCOV - code coverage report
Current view: top level - frmts/wms - minidriver_tiled_wms.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 262 375 69.9 %
Date: 2024-11-21 22:18:42 Functions: 9 11 81.8 %

          Line data    Source code
       1             : /******************************************************************************
       2             :  *
       3             :  * Project:  tiledWMS Client Driver
       4             :  * Purpose:  Implementation of the OnEarth Tiled WMS minidriver.
       5             :  *           http://onearth.jpl.nasa.gov/tiled.html
       6             :  * Author:   Lucian Plesea (Lucian dot Plesea at jpl.nasa.gov)
       7             :  *           Adam Nowacki
       8             :  *
       9             :  ******************************************************************************
      10             :  * Copyright (c) 2007, Adam Nowacki
      11             :  * Copyright (c) 2011-2012, Even Rouault <even dot rouault at spatialys.com>
      12             :  *
      13             :  * SPDX-License-Identifier: MIT
      14             :  ****************************************************************************/
      15             : 
      16             : //
      17             : // Also known as the OnEarth tile protocol
      18             : //
      19             : // A few open options are supported by tiled WMS
      20             : //
      21             : // TiledGroupName=<Name>
      22             : //
      23             : //  This option is only valid when the WMS file does not contain a
      24             : //  TiledGroupName. The name value should match exactly the name declared by the
      25             : //  server, including possible white spaces, otherwise the open will fail.
      26             : //
      27             : // Change=<key>:<value>
      28             : //
      29             : //  If the tiled group selected supports the change key, this option will set
      30             : //  the value The <key> here does not include the brackets present in the
      31             : //  GetTileService For example, if a TiledPattern include a key of ${time}, the
      32             : //  matching open option will be Change=time:<YYYY-MM-DD> The Change open option
      33             : //  may be present multiple times, with different keys If a key is not supported
      34             : //  by the selected TilePattern, the open will fail Alternate syntax is:
      35             : //  Change=<key>=<value>
      36             : //
      37             : // StoreConfiguration=Yes
      38             : //
      39             : //  This boolean option is only useful when doing a createcopy of a tiledWMS
      40             : //  dataset into another tiledWMS dataset. When set, the source tiledWMS will
      41             : //  store the server configuration into the XML metadata representation, which
      42             : //  then gets copied to the XML output. This will eliminate the need to fetch
      43             : //  the server configuration when opening the output datafile
      44             : //
      45             : 
      46             : #include "wmsdriver.h"
      47             : #include "minidriver_tiled_wms.h"
      48             : 
      49             : #include <set>
      50             : 
      51             : static const char SIG[] = "GDAL_WMS TiledWMS: ";
      52             : 
      53             : /*
      54             :  *\brief Read a number from an xml element
      55             :  */
      56             : 
      57          12 : static double getXMLNum(const CPLXMLNode *poRoot, const char *pszPath,
      58             :                         const char *pszDefault)
      59             : {  // Sets errno
      60          12 :     return CPLAtof(CPLGetXMLValue(poRoot, pszPath, pszDefault));
      61             : }
      62             : 
      63             : /*
      64             :  *\brief Read a ColorEntry XML node, return a GDALColorEntry structure
      65             :  *
      66             :  */
      67             : 
      68           0 : static GDALColorEntry GetXMLColorEntry(const CPLXMLNode *p)
      69             : {
      70             :     GDALColorEntry ce;
      71           0 :     ce.c1 = static_cast<short>(getXMLNum(p, "c1", "0"));
      72           0 :     ce.c2 = static_cast<short>(getXMLNum(p, "c2", "0"));
      73           0 :     ce.c3 = static_cast<short>(getXMLNum(p, "c3", "0"));
      74           0 :     ce.c4 = static_cast<short>(getXMLNum(p, "c4", "255"));
      75           0 :     return ce;
      76             : }
      77             : 
      78             : /************************************************************************/
      79             : /*                           SearchXMLSiblings()                        */
      80             : /************************************************************************/
      81             : 
      82             : /*
      83             :  * \brief Search for a sibling of the root node with a given name.
      84             :  *
      85             :  * Searches only the next siblings of the node passed in for the named element
      86             :  * or attribute. If the first character of the pszElement is '=', the search
      87             :  * includes the psRoot node
      88             :  *
      89             :  * @param psRoot the root node to search.  This should be a node of type
      90             :  * CXT_Element.  NULL is safe.
      91             :  *
      92             :  * @param pszElement the name of the element or attribute to search for.
      93             :  *
      94             :  *
      95             :  * @return The first matching node or NULL on failure.
      96             :  */
      97             : 
      98        1544 : static const CPLXMLNode *SearchXMLSiblings(const CPLXMLNode *psRoot,
      99             :                                            const char *pszElement)
     100             : 
     101             : {
     102        1544 :     if (psRoot == nullptr || pszElement == nullptr)
     103           0 :         return nullptr;
     104             : 
     105             :     // If the strings starts with '=', skip it and test the root
     106             :     // If not, start testing with the next sibling
     107        1544 :     if (pszElement[0] == '=')
     108          27 :         pszElement++;
     109             :     else
     110        1517 :         psRoot = psRoot->psNext;
     111             : 
     112       22188 :     for (; psRoot != nullptr; psRoot = psRoot->psNext)
     113             :     {
     114       20671 :         if ((psRoot->eType == CXT_Element || psRoot->eType == CXT_Attribute) &&
     115       20671 :             EQUAL(pszElement, psRoot->pszValue))
     116          27 :             return psRoot;
     117             :     }
     118        1517 :     return nullptr;
     119             : }
     120             : 
     121             : /************************************************************************/
     122             : /*                        SearchLeafGroupName()                         */
     123             : /************************************************************************/
     124             : 
     125             : /*
     126             :  * \brief Search for a leaf TileGroup node by name.
     127             :  *
     128             :  * @param psRoot the root node to search.  This should be a node of type
     129             :  * CXT_Element.  NULL is safe.
     130             :  *
     131             :  * @param pszElement the name of the TileGroup to search for.
     132             :  *
     133             :  * @return The XML node of the matching TileGroup or NULL on failure.
     134             :  */
     135             : 
     136        1514 : static CPLXMLNode *SearchLeafGroupName(CPLXMLNode *psRoot, const char *name)
     137             : 
     138             : {
     139        1514 :     if (psRoot == nullptr || name == nullptr)
     140           0 :         return nullptr;
     141             : 
     142             :     // Has to be a leaf TileGroup with the right name
     143        1514 :     if (nullptr == SearchXMLSiblings(psRoot->psChild, "TiledGroup"))
     144             :     {
     145        1514 :         if (EQUAL(name, CPLGetXMLValue(psRoot, "Name", "")))
     146           3 :             return psRoot;
     147             :     }
     148             :     else
     149             :     {  // Is metagroup, try children then siblings
     150           0 :         CPLXMLNode *ret = SearchLeafGroupName(psRoot->psChild, name);
     151           0 :         if (nullptr != ret)
     152           0 :             return ret;
     153             :     }
     154        1511 :     return SearchLeafGroupName(psRoot->psNext, name);
     155             : }
     156             : 
     157             : /************************************************************************/
     158             : /*                             BandInterp()                             */
     159             : /************************************************************************/
     160             : 
     161             : /*
     162             :  * \brief Utility function to calculate color band interpretation.
     163             :  * Only handles Gray, GrayAlpha, RGB and RGBA, based on total band count
     164             :  *
     165             :  * @param nbands is the total number of bands in the image
     166             :  *
     167             :  * @param band is the band number, starting with 1
     168             :  *
     169             :  * @return GDALColorInterp of the band
     170             :  */
     171             : 
     172           9 : static GDALColorInterp BandInterp(int nbands, int band)
     173             : {
     174           9 :     switch (nbands)
     175             :     {
     176           0 :         case 1:
     177           0 :             return GCI_GrayIndex;
     178           0 :         case 2:
     179           0 :             return band == 1 ? GCI_GrayIndex : GCI_AlphaBand;
     180           9 :         case 3:  // RGB
     181             :         case 4:  // RBGA
     182           9 :             if (band < 3)
     183           6 :                 return band == 1 ? GCI_RedBand : GCI_GreenBand;
     184           3 :             return band == 3 ? GCI_BlueBand : GCI_AlphaBand;
     185           0 :         default:
     186           0 :             return GCI_Undefined;
     187             :     }
     188             : }
     189             : 
     190             : /************************************************************************/
     191             : /*                              FindBbox()                              */
     192             : /************************************************************************/
     193             : 
     194             : /*
     195             :  * \brief Utility function to find the position of the bbox parameter value
     196             :  * within a request string.  The search for the bbox is case insensitive
     197             :  *
     198             :  * @param in, the string to search into
     199             :  *
     200             :  * @return The position from the beginning of the string or -1 if not found
     201             :  */
     202             : 
     203         189 : static int FindBbox(CPLString in)
     204             : {
     205             : 
     206         189 :     size_t pos = in.ifind("&bbox=");
     207         189 :     if (pos == std::string::npos)
     208           0 :         return -1;
     209         189 :     return (int)pos + 6;
     210             : }
     211             : 
     212             : /************************************************************************/
     213             : /*                         FindChangePattern()                          */
     214             : /************************************************************************/
     215             : 
     216             : /*
     217             :  * \brief Build the right request pattern based on the change request list
     218             :  * It only gets called on initialization
     219             :  * @param cdata, possible request strings, white space separated
     220             :  * @param substs, the list of substitutions to be applied
     221             :  * @param keys, the list of available substitution keys
     222             :  * @param ret The return value, a matching request or an empty string
     223             :  */
     224             : 
     225          27 : static void FindChangePattern(const char *cdata, const char *const *substs,
     226             :                               const char *const *keys, CPLString &ret)
     227             : {
     228             :     const CPLStringList aosTokens(CSLTokenizeString2(
     229          27 :         cdata, " \t\n\r", CSLT_STRIPLEADSPACES | CSLT_STRIPENDSPACES));
     230          27 :     ret.clear();
     231             : 
     232          27 :     int matchcount = CSLCount(substs);
     233          27 :     int keycount = CSLCount(keys);
     234          27 :     if (keycount < matchcount)
     235             :     {
     236           0 :         return;
     237             :     }
     238             : 
     239             :     // A valid string has only the keys in the substs list and none other
     240          36 :     for (int j = 0; j < aosTokens.size(); j++)
     241             :     {
     242          36 :         ret = aosTokens[j];  // The target string
     243          36 :         bool matches = true;
     244             : 
     245          72 :         for (int k = 0; k < keycount && keys != nullptr; k++)
     246             :         {
     247          36 :             const char *key = keys[k];
     248          36 :             int sub_number = CSLPartialFindString(substs, key);
     249          36 :             if (sub_number != -1)
     250             :             {  // It is a listed match
     251             :                 // But is the match for the key position?
     252          18 :                 char *found_key = nullptr;
     253             :                 const char *found_value =
     254          18 :                     CPLParseNameValue(substs[sub_number], &found_key);
     255          18 :                 if (found_key != nullptr && EQUAL(found_key, key))
     256             :                 {  // Should exist in the request
     257          18 :                     if (std::string::npos == ret.find(key))
     258           0 :                         matches = false;
     259          18 :                     if (matches)
     260             :                         // Execute the substitution on the "ret" string
     261          18 :                         URLSearchAndReplace(&ret, key, "%s", found_value);
     262             :                 }
     263             :                 else
     264             :                 {
     265           0 :                     matches = false;
     266             :                 }
     267          18 :                 CPLFree(found_key);
     268             :             }
     269             :             else
     270             :             {  // Key not in the subst list, should not match
     271          18 :                 if (std::string::npos != ret.find(key))
     272           9 :                     matches = false;
     273             :             }
     274             :         }  // Key loop
     275          36 :         if (matches)
     276             :         {
     277          27 :             return;  // We got the string ready, all keys accounted for and
     278             :                      // substs applied
     279             :         }
     280             :     }
     281           0 :     ret.clear();
     282             : }
     283             : 
     284             : WMSMiniDriver_TiledWMS::WMSMiniDriver_TiledWMS() = default;
     285             : 
     286             : WMSMiniDriver_TiledWMS::~WMSMiniDriver_TiledWMS() = default;
     287             : 
     288             : // Returns the scale of a WMS request as compared to the base resolution
     289         162 : double WMSMiniDriver_TiledWMS::Scale(const char *request) const
     290             : {
     291         162 :     int bbox = FindBbox(request);
     292         162 :     if (bbox < 0)
     293           0 :         return 0;
     294             :     double x, y, X, Y;
     295         162 :     CPLsscanf(request + bbox, "%lf,%lf,%lf,%lf", &x, &y, &X, &Y);
     296         162 :     return (m_data_window.m_x1 - m_data_window.m_x0) / (X - x) * m_bsx /
     297         162 :            m_data_window.m_sx;
     298             : }
     299             : 
     300             : // Finds, extracts, and returns the highest resolution request string from a
     301             : // list, starting at item i
     302          27 : CPLString WMSMiniDriver_TiledWMS::GetLowestScale(CPLStringList &list,
     303             :                                                  int i) const
     304             : {
     305          27 :     CPLString req;
     306          27 :     double scale = -1;
     307          27 :     int position = -1;
     308         162 :     while (nullptr != list[i])
     309             :     {
     310         135 :         double tscale = Scale(list[i]);
     311         135 :         if (tscale >= scale)
     312             :         {
     313          27 :             scale = tscale;
     314          27 :             position = i;
     315             :         }
     316         135 :         i++;
     317             :     }
     318          27 :     if (position > -1)
     319             :     {
     320          27 :         req = list[position];
     321             :         list.Assign(CSLRemoveStrings(list.StealList(), position, 1, nullptr),
     322          27 :                     true);
     323             :     }
     324          27 :     return req;
     325             : }
     326             : 
     327             : /*
     328             :  *\Brief Initialize minidriver with info from the server
     329             :  */
     330             : 
     331           4 : CPLErr WMSMiniDriver_TiledWMS::Initialize(CPLXMLNode *config,
     332             :                                           CPL_UNUSED char **OpenOptions)
     333             : {
     334           4 :     CPLErr ret = CE_None;
     335           8 :     CPLXMLTreeCloser tileServiceConfig(nullptr);
     336           4 :     const CPLXMLNode *TG = nullptr;
     337             : 
     338           8 :     CPLStringList requests;
     339           8 :     CPLStringList substs;
     340           8 :     CPLStringList keys;
     341           4 :     CPLStringList changes;
     342             : 
     343             :     try
     344             :     {  // Parse info from the WMS Service node
     345             :         //        m_end_url = CPLGetXMLValue(config, "AdditionalArgs", "");
     346           4 :         m_base_url = CPLGetXMLValue(config, "ServerURL", "");
     347             : 
     348           4 :         if (m_base_url.empty())
     349           0 :             throw CPLOPrintf("%s ServerURL missing.", SIG);
     350             : 
     351             :         CPLString tiledGroupName(
     352           8 :             CSLFetchNameValueDef(OpenOptions, "TiledGroupName", ""));
     353             :         tiledGroupName =
     354           4 :             CPLGetXMLValue(config, "TiledGroupName", tiledGroupName);
     355           4 :         if (tiledGroupName.empty())
     356           1 :             throw CPLOPrintf("%s TiledGroupName missing.", SIG);
     357             : 
     358             :         // Change strings, key is an attribute, value is the value of the Change
     359             :         // node Multiple keys are possible
     360             : 
     361             :         // First process the changes from open options, if present
     362           3 :         changes = CSLFetchNameValueMultiple(OpenOptions, "Change");
     363             :         // Transfer them to subst list
     364           5 :         for (int i = 0; changes && changes[i] != nullptr; i++)
     365             :         {
     366           2 :             char *key = nullptr;
     367           2 :             const char *value = CPLParseNameValue(changes[i], &key);
     368             :             // Add the ${} around the key
     369           2 :             if (value != nullptr && key != nullptr)
     370           2 :                 substs.SetNameValue(CPLOPrintf("${%s}", key), value);
     371           2 :             CPLFree(key);
     372             :         }
     373             : 
     374             :         // Then process the configuration file itself
     375           3 :         const CPLXMLNode *nodeChange = CPLSearchXMLNode(config, "Change");
     376           3 :         while (nodeChange != nullptr)
     377             :         {
     378           0 :             CPLString key = CPLGetXMLValue(nodeChange, "key", "");
     379           0 :             if (key.empty())
     380             :                 throw CPLOPrintf(
     381             :                     "%s Change element needs a non-empty \"key\" attribute",
     382           0 :                     SIG);
     383           0 :             substs.SetNameValue(key, CPLGetXMLValue(nodeChange, "", ""));
     384           0 :             nodeChange = SearchXMLSiblings(nodeChange, "Change");
     385             :         }
     386             : 
     387           3 :         m_parent_dataset->SetMetadataItem("ServerURL", m_base_url, nullptr);
     388           3 :         m_parent_dataset->SetMetadataItem("TiledGroupName", tiledGroupName,
     389           3 :                                           nullptr);
     390           5 :         for (int i = 0, n = CSLCount(substs); i < n && substs; i++)
     391           2 :             m_parent_dataset->SetMetadataItem("Change", substs[i], nullptr);
     392             : 
     393           6 :         const CPLString GTS(CPLGetXMLValue(config, "Configuration", ""));
     394           6 :         CPLString decodedGTS;
     395             : 
     396           3 :         if (GTS.size() != 0)
     397             :         {  // Probably XML encoded because it is XML itself
     398             :             decodedGTS =
     399           1 :                 GTS;  // The copy will be replaced by the decoded result
     400           1 :             WMSUtilDecode(decodedGTS,
     401             :                           CPLGetXMLValue(config, "Configuration.encoding", ""));
     402             :         }
     403             :         else
     404             :         {  // Not local, use the WMSdriver to fetch the server config
     405           4 :             CPLString getTileServiceUrl = m_base_url + "request=GetTileService";
     406             : 
     407             :             // This returns a string managed by the cfg cache, do not free
     408           2 :             const char *pszTmp = GDALWMSDataset::GetServerConfig(
     409             :                 getTileServiceUrl,
     410           2 :                 const_cast<char **>(m_parent_dataset->GetHTTPRequestOpts()));
     411           2 :             decodedGTS = pszTmp ? pszTmp : "";
     412             : 
     413           2 :             if (decodedGTS.empty())
     414           0 :                 throw CPLOPrintf("%s Can't fetch server GetTileService", SIG);
     415             :         }
     416             : 
     417             :         // decodedGTS contains the GetTileService return now
     418           3 :         tileServiceConfig.reset(CPLParseXMLString(decodedGTS));
     419           3 :         if (!tileServiceConfig)
     420             :             throw CPLOPrintf("%s Error parsing the GetTileService response",
     421           0 :                              SIG);
     422             : 
     423           3 :         if (nullptr ==
     424           3 :             (TG = CPLSearchXMLNode(tileServiceConfig.get(), "TiledPatterns")))
     425             :             throw CPLOPrintf(
     426           0 :                 "%s Can't locate TiledPatterns in server response.", SIG);
     427             : 
     428             :         // Get the global base_url and bounding box, these can be overwritten at
     429             :         // the tileGroup level They are just pointers into existing structures,
     430             :         // cleanup is not required
     431             :         const char *global_base_url =
     432           3 :             CPLGetXMLValue(tileServiceConfig.get(),
     433             :                            "TiledPatterns.OnlineResource.xlink:href", "");
     434           3 :         const CPLXMLNode *global_latlonbbox = CPLGetXMLNode(
     435             :             tileServiceConfig.get(), "TiledPatterns.LatLonBoundingBox");
     436             :         const CPLXMLNode *global_bbox =
     437           3 :             CPLGetXMLNode(tileServiceConfig.get(), "TiledPatterns.BoundingBox");
     438           3 :         const char *pszProjection = CPLGetXMLValue(
     439           3 :             tileServiceConfig.get(), "TiledPatterns.Projection", "");
     440           3 :         if (pszProjection[0] != 0)
     441           0 :             m_oSRS.SetFromUserInput(
     442             :                 pszProjection,
     443             :                 OGRSpatialReference::SET_FROM_USER_INPUT_LIMITATIONS_get());
     444             : 
     445           3 :         if (nullptr == (TG = SearchLeafGroupName(TG->psChild, tiledGroupName)))
     446             :             throw CPLOPrintf("%s No TiledGroup "
     447             :                              "%s"
     448             :                              " in server response.",
     449           0 :                              SIG, tiledGroupName.c_str());
     450             : 
     451           3 :         int band_count = atoi(CPLGetXMLValue(TG, "Bands", "3"));
     452             : 
     453           3 :         if (!GDALCheckBandCount(band_count, FALSE))
     454             :             throw CPLOPrintf("%s Invalid number of bands in server response",
     455           0 :                              SIG);
     456             : 
     457           3 :         if (nullptr != CPLGetXMLNode(TG, "Key"))
     458             :         {  // Collect all keys defined by this tileset
     459           3 :             const CPLXMLNode *node = CPLGetXMLNode(TG, "Key");
     460           6 :             while (nullptr != node)
     461             :             {  // the TEXT of the Key node
     462           3 :                 const char *val = CPLGetXMLValue(node, nullptr, nullptr);
     463           3 :                 if (nullptr != val)
     464           3 :                     keys.AddString(val);
     465           3 :                 node = SearchXMLSiblings(node, "Key");
     466             :             }
     467             :         }
     468             : 
     469             :         // Data values are attributes, they include NoData Min and Max
     470           3 :         if (nullptr != CPLGetXMLNode(TG, "DataValues"))
     471             :         {
     472             :             const char *nodata =
     473           0 :                 CPLGetXMLValue(TG, "DataValues.NoData", nullptr);
     474           0 :             if (nodata != nullptr)
     475             :             {
     476           0 :                 m_parent_dataset->WMSSetNoDataValue(nodata);
     477           0 :                 m_parent_dataset->SetTileOO("@NDV", nodata);
     478             :             }
     479           0 :             const char *min = CPLGetXMLValue(TG, "DataValues.min", nullptr);
     480           0 :             if (min != nullptr)
     481           0 :                 m_parent_dataset->WMSSetMinValue(min);
     482           0 :             const char *max = CPLGetXMLValue(TG, "DataValues.max", nullptr);
     483           0 :             if (max != nullptr)
     484           0 :                 m_parent_dataset->WMSSetMaxValue(max);
     485             :         }
     486             : 
     487           3 :         m_parent_dataset->WMSSetBandsCount(band_count);
     488             :         GDALDataType dt =
     489           3 :             GDALGetDataTypeByName(CPLGetXMLValue(TG, "DataType", "Byte"));
     490           3 :         m_parent_dataset->WMSSetDataType(dt);
     491           3 :         if (dt != GDT_Byte)
     492           0 :             m_parent_dataset->SetTileOO("@DATATYPE", GDALGetDataTypeName(dt));
     493             :         // Let the TiledGroup override the projection
     494           3 :         pszProjection = CPLGetXMLValue(TG, "Projection", "");
     495           3 :         if (pszProjection[0] != 0)
     496           3 :             m_oSRS = ProjToSRS(pszProjection);
     497             : 
     498             :         m_base_url =
     499           3 :             CPLGetXMLValue(TG, "OnlineResource.xlink:href", global_base_url);
     500           3 :         if (m_base_url[0] == '\0')
     501             :             throw CPLOPrintf(
     502           0 :                 "%s Can't locate OnlineResource in the server response", SIG);
     503             : 
     504             :         // Bounding box, local, global, local lat-lon, global lat-lon, in this
     505             :         // order
     506           3 :         const CPLXMLNode *bbox = CPLGetXMLNode(TG, "BoundingBox");
     507           3 :         if (nullptr == bbox)
     508           3 :             bbox = global_bbox;
     509           3 :         if (nullptr == bbox)
     510           3 :             bbox = CPLGetXMLNode(TG, "LatLonBoundingBox");
     511           3 :         if (nullptr == bbox)
     512           0 :             bbox = global_latlonbbox;
     513           3 :         if (nullptr == bbox)
     514             :             throw CPLOPrintf(
     515             :                 "%s Can't locate the LatLonBoundingBox in server response",
     516           0 :                 SIG);
     517             : 
     518             :         // Check for errors during conversion
     519           3 :         errno = 0;
     520           3 :         int err = 0;
     521           3 :         m_data_window.m_x0 = getXMLNum(bbox, "minx", "0");
     522           3 :         err |= errno;
     523           3 :         m_data_window.m_x1 = getXMLNum(bbox, "maxx", "-1");
     524           3 :         err |= errno;
     525           3 :         m_data_window.m_y0 = getXMLNum(bbox, "maxy", "0");
     526           3 :         err |= errno;
     527           3 :         m_data_window.m_y1 = getXMLNum(bbox, "miny", "-1");
     528           3 :         err |= errno;
     529           3 :         if (err)
     530           0 :             throw CPLOPrintf("%s Can't parse LatLonBoundingBox", SIG);
     531             : 
     532           3 :         if ((m_data_window.m_x1 - m_data_window.m_x0) <= 0 ||
     533           3 :             (m_data_window.m_y0 - m_data_window.m_y1) <= 0)
     534             :             throw CPLOPrintf(
     535           0 :                 "%s Coordinate order in BBox problem in server response", SIG);
     536             : 
     537             :         // Is there a palette?
     538             :         //
     539             :         // Format is
     540             :         // <Palette>
     541             :         //   <Size>N</Size> : Optional
     542             :         //   <Model>RGBA|RGB</Model> : Optional, defaults to RGB
     543             :         //   <Entry idx=i c1=v1 c2=v2 c3=v3 c4=v4/> :Optional
     544             :         //   <Entry .../>
     545             :         // </Palette>
     546             :         // the idx attribute is optional, it autoincrements
     547             :         // The entries are vertices, interpolation takes place in between if the
     548             :         // indices are not successive index values have to be in increasing
     549             :         // order The palette starts initialized with zeros
     550             :         //
     551             : 
     552           3 :         bool bHasColorTable = false;
     553             : 
     554           3 :         if ((band_count == 1) && CPLGetXMLNode(TG, "Palette"))
     555             :         {
     556           0 :             const CPLXMLNode *node = CPLGetXMLNode(TG, "Palette");
     557             : 
     558           0 :             int entries = static_cast<int>(getXMLNum(node, "Size", "255"));
     559           0 :             GDALPaletteInterp eInterp = GPI_RGB;  // RGB and RGBA are the same
     560             : 
     561           0 :             CPLString pModel = CPLGetXMLValue(node, "Model", "RGB");
     562           0 :             if (!pModel.empty() && pModel.find("RGB") == std::string::npos)
     563             :                 throw CPLOPrintf(
     564             :                     "%s Palette Model %s is unknown, use RGB or RGBA", SIG,
     565           0 :                     pModel.c_str());
     566             : 
     567           0 :             if ((entries < 1) || (entries > 256))
     568           0 :                 throw CPLOPrintf("%s Palette definition error", SIG);
     569             : 
     570             :             // Create it and initialize it to nothing
     571             :             int start_idx;
     572             :             int end_idx;
     573           0 :             GDALColorEntry ce_start = {0, 0, 0, 255};
     574           0 :             GDALColorEntry ce_end = {0, 0, 0, 255};
     575             : 
     576           0 :             auto poColorTable = std::make_unique<GDALColorTable>(eInterp);
     577           0 :             poColorTable->CreateColorRamp(0, &ce_start, entries - 1, &ce_end);
     578             :             // Read the values
     579           0 :             const CPLXMLNode *p = CPLGetXMLNode(node, "Entry");
     580           0 :             if (p)
     581             :             {
     582             :                 // Initialize the first entry
     583           0 :                 start_idx = static_cast<int>(getXMLNum(p, "idx", "0"));
     584           0 :                 ce_start = GetXMLColorEntry(p);
     585             : 
     586           0 :                 if (start_idx < 0)
     587             :                     throw CPLOPrintf("%s Palette index %d not allowed", SIG,
     588           0 :                                      start_idx);
     589             : 
     590           0 :                 poColorTable->SetColorEntry(start_idx, &ce_start);
     591           0 :                 while (nullptr != (p = SearchXMLSiblings(p, "Entry")))
     592             :                 {
     593             :                     // For every entry, create a ramp
     594           0 :                     ce_end = GetXMLColorEntry(p);
     595           0 :                     end_idx = static_cast<int>(
     596           0 :                         getXMLNum(p, "idx", CPLOPrintf("%d", start_idx + 1)));
     597           0 :                     if ((end_idx <= start_idx) || (start_idx >= entries))
     598             :                         throw CPLOPrintf("%s Index Error at index %d", SIG,
     599           0 :                                          end_idx);
     600             : 
     601           0 :                     poColorTable->CreateColorRamp(start_idx, &ce_start, end_idx,
     602             :                                                   &ce_end);
     603           0 :                     ce_start = ce_end;
     604           0 :                     start_idx = end_idx;
     605             :                 }
     606             :             }
     607             : 
     608             :             // Dataset has ownership
     609           0 :             m_parent_dataset->SetColorTable(poColorTable.release());
     610           0 :             bHasColorTable = true;
     611             :         }  // If palette
     612             : 
     613           3 :         int overview_count = 0;
     614           3 :         const CPLXMLNode *Pattern = TG->psChild;
     615             : 
     616           3 :         m_bsx = -1;
     617           3 :         m_bsy = -1;
     618           3 :         m_data_window.m_sx = 0;
     619           3 :         m_data_window.m_sy = 0;
     620             : 
     621          27 :         while (
     622          57 :             (nullptr != Pattern) &&
     623          27 :             (nullptr != (Pattern = SearchXMLSiblings(Pattern, "=TilePattern"))))
     624             :         {
     625             :             int mbsx, mbsy, sx, sy;
     626             :             double x, y, X, Y;
     627             : 
     628          27 :             CPLString request;
     629          27 :             FindChangePattern(Pattern->psChild->pszValue, substs, keys,
     630          27 :                               request);
     631          27 :             if (request.empty())
     632           0 :                 break;  // No point to drag, this level doesn't match the keys
     633             : 
     634          27 :             const CPLStringList aosTokens(CSLTokenizeString2(request, "&", 0));
     635             : 
     636          27 :             const char *pszWIDTH = aosTokens.FetchNameValue("WIDTH");
     637          27 :             const char *pszHEIGHT = aosTokens.FetchNameValue("HEIGHT");
     638          27 :             if (pszWIDTH == nullptr || pszHEIGHT == nullptr)
     639             :                 throw CPLOPrintf(
     640             :                     "%s Cannot find width or height parameters in %s", SIG,
     641           0 :                     request.c_str());
     642             : 
     643          27 :             mbsx = atoi(pszWIDTH);
     644          27 :             mbsy = atoi(pszHEIGHT);
     645             :             // If unset until now, try to get the projection from the
     646             :             // pattern
     647          27 :             if (m_oSRS.IsEmpty())
     648             :             {
     649           0 :                 const char *pszSRS = aosTokens.FetchNameValueDef("SRS", "");
     650           0 :                 if (pszSRS[0] != 0)
     651           0 :                     m_oSRS = ProjToSRS(pszSRS);
     652             :             }
     653             : 
     654          27 :             if (-1 == m_bsx)
     655           3 :                 m_bsx = mbsx;
     656          27 :             if (-1 == m_bsy)
     657           3 :                 m_bsy = mbsy;
     658          27 :             if ((m_bsx != mbsx) || (m_bsy != mbsy))
     659           0 :                 throw CPLOPrintf("%s Tileset uses different block sizes", SIG);
     660             : 
     661          27 :             if (CPLsscanf(aosTokens.FetchNameValueDef("BBOX", ""),
     662          27 :                           "%lf,%lf,%lf,%lf", &x, &y, &X, &Y) != 4)
     663             :                 throw CPLOPrintf("%s Error parsing BBOX, pattern %d\n", SIG,
     664           0 :                                  overview_count + 1);
     665             : 
     666             :             // Pick the largest size
     667          27 :             sx = static_cast<int>((m_data_window.m_x1 - m_data_window.m_x0) /
     668          27 :                                   (X - x) * m_bsx);
     669          27 :             sy = static_cast<int>(fabs(
     670          27 :                 (m_data_window.m_y1 - m_data_window.m_y0) / (Y - y) * m_bsy));
     671          27 :             if (sx > m_data_window.m_sx)
     672           3 :                 m_data_window.m_sx = sx;
     673          27 :             if (sy > m_data_window.m_sy)
     674           3 :                 m_data_window.m_sy = sy;
     675             : 
     676             :             // Only use overlays where the top coordinate is within a pixel from
     677             :             // the top of coverage
     678             :             double pix_off, temp;
     679          27 :             pix_off =
     680          27 :                 m_bsy * modf(fabs((Y - m_data_window.m_y0) / (Y - y)), &temp);
     681          27 :             if ((pix_off < 1) || ((m_bsy - pix_off) < 1))
     682             :             {
     683          27 :                 requests.AddString(request);
     684          27 :                 overview_count++;
     685             :             }
     686             :             else
     687             :             {  // Just a warning
     688           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
     689             :                          "%s Overlay size %dX%d can't be used due to alignment",
     690             :                          SIG, sx, sy);
     691             :             }
     692             : 
     693          27 :             Pattern = Pattern->psNext;
     694             :         }  // Search for matching TilePattern
     695             : 
     696             :         // Did we find anything
     697           3 :         if (requests.empty())
     698             :             throw CPLOPrintf("Can't find any usable TilePattern, maybe the "
     699           0 :                              "Changes are not correct?");
     700             : 
     701             :         // The tlevel is needed, the tx and ty are not used by this minidriver
     702           3 :         m_data_window.m_tlevel = 0;
     703           3 :         m_data_window.m_tx = 0;
     704           3 :         m_data_window.m_ty = 0;
     705             : 
     706             :         // Make sure the parent_dataset values are set before creating the bands
     707           3 :         m_parent_dataset->WMSSetBlockSize(m_bsx, m_bsy);
     708           3 :         m_parent_dataset->WMSSetRasterSize(m_data_window.m_sx,
     709             :                                            m_data_window.m_sy);
     710             : 
     711           3 :         m_parent_dataset->WMSSetDataWindow(m_data_window);
     712             :         // m_parent_dataset->WMSSetOverviewCount(overview_count);
     713           3 :         m_parent_dataset->WMSSetClamp(false);
     714             : 
     715             :         // Ready for the Rasterband creation
     716          30 :         for (int i = 0; i < overview_count; i++)
     717             :         {
     718          54 :             CPLString request = GetLowestScale(requests, i);
     719          27 :             double scale = Scale(request);
     720             : 
     721             :             // Base scale should be very close to 1
     722          27 :             if ((0 == i) && (fabs(scale - 1) > 1e-6))
     723           0 :                 throw CPLOPrintf("%s Base resolution pattern missing", SIG);
     724             : 
     725             :             // Prepare the request and insert it back into the list
     726             :             // Find returns an answer relative to the original string start!
     727          27 :             size_t startBbox = FindBbox(request);
     728          27 :             size_t endBbox = request.find('&', startBbox);
     729          27 :             if (endBbox == std::string::npos)
     730          27 :                 endBbox = request.size();
     731          27 :             request.replace(startBbox, endBbox - startBbox, "${GDAL_BBOX}");
     732          27 :             requests.InsertString(i, request);
     733             : 
     734             :             // Create the Rasterband or overview
     735         108 :             for (int j = 1; j <= band_count; j++)
     736             :             {
     737          81 :                 if (i != 0)
     738             :                 {
     739          72 :                     m_parent_dataset->mGetBand(j)->AddOverview(scale);
     740             :                 }
     741             :                 else
     742             :                 {  // Base resolution
     743             :                     GDALWMSRasterBand *band =
     744           9 :                         new GDALWMSRasterBand(m_parent_dataset, j, 1);
     745           9 :                     if (bHasColorTable)
     746           0 :                         band->SetColorInterpretation(GCI_PaletteIndex);
     747             :                     else
     748           9 :                         band->SetColorInterpretation(BandInterp(band_count, j));
     749           9 :                     m_parent_dataset->mSetBand(j, band);
     750             :                 }
     751             :             }
     752             :         }
     753             : 
     754           3 :         if ((overview_count == 0) || (m_bsx < 1) || (m_bsy < 1))
     755           0 :             throw CPLOPrintf("%s No usable TilePattern elements found", SIG);
     756             : 
     757             :         // Do we need to modify the output XML
     758           3 :         if (0 != CSLCount(OpenOptions))
     759             :         {
     760             :             // Get the proposed XML, it will exist at this point
     761             :             CPLXMLTreeCloser cfg_root(CPLParseXMLString(
     762           4 :                 m_parent_dataset->GetMetadataItem("XML", "WMS")));
     763           2 :             char *pszXML = nullptr;
     764             : 
     765           2 :             if (cfg_root)
     766             :             {
     767           2 :                 bool modified = false;
     768             : 
     769             :                 // Set openoption StoreConfiguration to Yes to save the server
     770             :                 // GTS in the output XML
     771           2 :                 if (CSLFetchBoolean(OpenOptions, "StoreConfiguration", 0) &&
     772             :                     nullptr ==
     773           0 :                         CPLGetXMLNode(cfg_root.get(), "Service.Configuration"))
     774             :                 {
     775           0 :                     char *xmlencodedGTS = CPLEscapeString(
     776           0 :                         decodedGTS, static_cast<int>(decodedGTS.size()),
     777             :                         CPLES_XML);
     778             : 
     779             :                     // It doesn't have a Service.Configuration element, safe to
     780             :                     // add one
     781           0 :                     CPLXMLNode *scfg = CPLCreateXMLElementAndValue(
     782             :                         CPLGetXMLNode(cfg_root.get(), "Service"),
     783             :                         "Configuration", xmlencodedGTS);
     784           0 :                     CPLAddXMLAttributeAndValue(scfg, "encoding", "XMLencoded");
     785           0 :                     modified = true;
     786           0 :                     CPLFree(xmlencodedGTS);
     787             :                 }
     788             : 
     789             :                 // Set the TiledGroupName if it's not already there and we have
     790             :                 // it as an open option
     791           3 :                 if (!CPLGetXMLNode(cfg_root.get(), "Service.TiledGroupName") &&
     792           1 :                     nullptr != CSLFetchNameValue(OpenOptions, "TiledGroupName"))
     793             :                 {
     794           1 :                     CPLCreateXMLElementAndValue(
     795             :                         CPLGetXMLNode(cfg_root.get(), "Service"),
     796             :                         "TiledGroupName",
     797             :                         CSLFetchNameValue(OpenOptions, "TiledGroupName"));
     798           1 :                     modified = true;
     799             :                 }
     800             : 
     801           2 :                 if (!substs.empty())
     802             :                 {
     803             :                     // Get all the existing Change elements
     804           4 :                     std::set<std::string> oExistingKeys;
     805             :                     auto nodechange =
     806           2 :                         CPLGetXMLNode(cfg_root.get(), "Service.Change");
     807           2 :                     while (nodechange)
     808             :                     {
     809             :                         const char *key =
     810           0 :                             CPLGetXMLValue(nodechange, "Key", nullptr);
     811           0 :                         if (key)
     812           0 :                             oExistingKeys.insert(key);
     813           0 :                         nodechange = nodechange->psNext;
     814             :                     }
     815             : 
     816           4 :                     for (int i = 0, n = substs.size(); i < n && substs; i++)
     817             :                     {
     818           2 :                         CPLString kv(substs[i]);
     819             :                         auto sep_pos =
     820           2 :                             kv.find_first_of("=:");  // It should find it
     821           2 :                         if (sep_pos == CPLString::npos)
     822           0 :                             continue;
     823           4 :                         CPLString key(kv.substr(0, sep_pos));
     824           4 :                         CPLString val(kv.substr(sep_pos + 1));
     825             :                         // Add to the cfg_root if this change is not already
     826             :                         // there
     827           2 :                         if (oExistingKeys.find(key) == oExistingKeys.end())
     828             :                         {
     829           2 :                             auto cnode = CPLCreateXMLElementAndValue(
     830             :                                 CPLGetXMLNode(cfg_root.get(), "Service"),
     831             :                                 "Change", val);
     832           2 :                             CPLAddXMLAttributeAndValue(cnode, "Key", key);
     833           2 :                             modified = true;
     834             :                         }
     835             :                     }
     836             :                 }
     837             : 
     838           2 :                 if (modified)
     839             :                 {
     840           2 :                     pszXML = CPLSerializeXMLTree(cfg_root.get());
     841           2 :                     m_parent_dataset->SetXML(pszXML);
     842             :                 }
     843             :             }
     844             : 
     845           2 :             CPLFree(pszXML);
     846             :         }
     847             :     }
     848           2 :     catch (const CPLString &msg)
     849             :     {
     850           1 :         ret = CE_Failure;
     851           1 :         CPLError(ret, CPLE_AppDefined, "%s", msg.c_str());
     852             :     }
     853             : 
     854           4 :     m_requests = std::move(requests);
     855           8 :     return ret;
     856             : }
     857             : 
     858           0 : CPLErr WMSMiniDriver_TiledWMS::TiledImageRequest(
     859             :     WMSHTTPRequest &request, const GDALWMSImageRequestInfo &iri,
     860             :     const GDALWMSTiledImageRequestInfo &tiri)
     861             : {
     862           0 :     CPLString &url = request.URL;
     863           0 :     url = m_base_url;
     864           0 :     URLPrepare(url);
     865           0 :     url += CSLGetField(m_requests.List(), -tiri.m_level);
     866           0 :     URLSearchAndReplace(&url, "${GDAL_BBOX}", "%013.8f,%013.8f,%013.8f,%013.8f",
     867           0 :                         iri.m_x0, iri.m_y1, iri.m_x1, iri.m_y0);
     868           0 :     return CE_None;
     869             : }

Generated by: LCOV version 1.14