GeoDataCoordinates.cpp 58.2 KB
Newer Older
1
//
2
// This file is part of the Marble Virtual Globe.
3 4 5 6 7
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
Jens-Michael Hoffmann's avatar
Jens-Michael Hoffmann committed
8 9 10
// Copyright 2004-2007 Torsten Rahn <tackat@kde.org>
// Copyright 2007-2008 Inge Wallin  <ingwa@kde.org>
// Copyright 2008      Patrick Spendrin <ps_ml@gmx.de>
11
// Copyright 2011      Friedrich W. H. Kossebau <kossebau@kde.org>
12
// Copyright 2011      Bernhard Beschow <bbeschow@cs.tu-berlin.de>
13
// Copyright 2015      Alejandro Garcia Montoro <alejandro.garciamontoro@gmail.com>
14 15 16
//


Torsten Rahn's avatar
Torsten Rahn committed
17
#include "GeoDataCoordinates.h"
18
#include "GeoDataCoordinates_p.h"
19

20 21 22 23 24 25 26
#include <qmath.h>
#include <QRegExp>
#include <QLocale>
#include <QString>
#include <QStringList>
#include <QCoreApplication>
#include <QAtomicInt>
Anke Boersma's avatar
Anke Boersma committed
27
#include <QDataStream>
28
#include <QPointF>
29
#include <QStringBuilder>
30

31
#include "MarbleGlobal.h"
32
#include "MarbleDebug.h"
33

34 35
#include "Quaternion.h"

36 37 38
namespace Marble
{

39 40 41 42
// Helper class for GeoDataCoordinates::fromString(...)
class LonLatParser
{
private:
43 44
    enum DirPosition { PrefixDir, PostfixDir };

45 46 47 48 49 50
    /**
     * Parses the double value from the input string in system locale
     * if it contains the system locale decimalpoint char,
     * otherwise parses it in the C locale.
     */
    static double parseDouble(const QString& input);
51
    static QString createDecimalPointExp();
52 53 54
    static QString regExp( const QString& string );
    static void getLocaleList( QStringList& localeList, const QString& localeListString,
                               const QLatin1String& placeholder, const QString& separator );
55
    static bool isDirection( const QString& input, const QString& direction);
56
    static bool isDirection( const QString& input, const QStringList& directions);
57 58 59 60
    static bool isOneOfDirections( const QString& input,
                                   const QString& firstDirection,
                                   const QString& secondDirection,
                                   bool& isFirstDirection);
61 62 63 64
    static bool isOneOfDirections( const QString& input,
                                   const QStringList& firstDirections,
                                   const QStringList& secondDirections,
                                   bool& isFirstDirection);
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99

    /**
     * function template for the function calculating the degree value from
     * the captured texts with the degree, the minutes, the seconds and the signedness
     * (or less, depending on what the function actually expects)
     * @param regex the regexp to take the texts from
     * @param c the index in the list of captured texts of @p regex to start with
     * @param isPosHemisphere if the texts of the degree value are relative to the pos hemisphere
     * @return the calculated degree value
     */
    static qreal degreeValueFromDMS( const QRegExp& regex, int c, bool isPosHemisphere );
    static qreal degreeValueFromDM( const QRegExp& regex, int c, bool isPosHemisphere );
    static qreal degreeValueFromD( const QRegExp& regex, int c, bool isPosHemisphere );

public:
    LonLatParser();
    /**
     * @brief parses the complete @p input string and sets the lon and lat properties if successful.
     * @param input the string to parse, must not have other content than the coordinates
     * @return @c true on successful parsing, @c false otherwise.
     */
    bool parse( const QString& input );
    /**
    * @brief return the lon value from the last successful parsing
    */
    qreal lon() const { return m_lon; }
    /**
    * @brief return the lat value from the last successful parsing
    */
    qreal lat() const { return m_lat; }

private:
    /**
     * @brief tries to parse the input with the given reg expression and get the lon and lat values
     * @param input the string to parse, must not have other content than the coordinates
100
     * @param dirPosition position of the dir in the list of captured texts
101 102
     * @return @c true on successful parsing, @c false otherwise.
     */
103 104 105
    bool tryMatchFromDms( const QString& input, DirPosition dirPosition );
    bool tryMatchFromDm( const QString& input, DirPosition dirPosition );
    bool tryMatchFromD( const QString& input, DirPosition dirPosition );
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147

    /**
    * @brief initializes also all properties which only need to be lazily initialized
    */
    void initAll();
    /**
     * @brief checks if the both passed directions are correct, also returns more data about them
     * @param dir1 first direction string
     * @param dir1 second direction string
     * @param isDir1LonDir is set to @c true if first direction string is a longitude direction,
     *                     @c false otherwise
     * @param isLonDirPosHemisphere is set to @c true if longitude direction is in positive hemisphere,
     *                              @c false otherwise
     * @param isLatDirPosHemisphere is set to @c true if latitude direction is in positive hemisphere,
     *                              @c false otherwise
     * @return @c true if @p dir1 and @p dir2 are correct, @c false otherwise.
     */
    bool isCorrectDirections( const QString& dir1, const QString& dir2,
                              bool& isDir1LonDir,
                              bool& isLonDirPosHemisphere, bool& isLatDirPosHemisphere ) const;
    bool isLocaleLonDirection( const QString& input,
                               bool& isDirPosHemisphere ) const;
    bool isLocaleLatDirection( const QString& input,
                               bool& isDirPosHemisphere ) const;
    bool isLonDirection( const QString& input,
                         bool& isDirPosHemisphere ) const;
    bool isLatDirection( const QString& input,
                         bool& isDirPosHemisphere ) const;

private:
    qreal m_lon;
    qreal m_lat;

private: // helper values
    const QString m_north;
    const QString m_east;
    const QString m_south;
    const QString m_west;

    const QString m_decimalPointExp;

private: // helper value, lazily set, in initAll();
148 149 150 151 152 153 154 155 156
    QStringList m_northLocale;
    QStringList m_eastLocale;
    QStringList m_southLocale;
    QStringList m_westLocale;

    QStringList m_degreeLocale;
    QStringList m_minutesLocale;
    QStringList m_secondsLocale;

157
    QString m_dirCapExp;
158 159 160
    QString m_degreeExp;
    QString m_minutesExp;
    QString m_secondsExp;
161 162 163 164 165
};

LonLatParser::LonLatParser()
    : m_lon( 0.0 )
    , m_lat( 0.0 )
166 167 168 169
    , m_north( QLatin1String("n") )
    , m_east(  QLatin1String("e") )
    , m_south( QLatin1String("s") )
    , m_west(  QLatin1String("w") )
170 171 172 173
    , m_decimalPointExp( createDecimalPointExp() )
{
}

174

175 176 177 178 179 180
void LonLatParser::initAll()
{
    // already all initialized?
    if (! m_dirCapExp.isEmpty() )
        return;

181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
    const QLatin1String placeholder = QLatin1String("*");
    const QString separator = QLatin1String("|");

    getLocaleList( m_northLocale, GeoDataCoordinates::tr( "*", "North direction terms, see http://techbase.kde.org/Projects/Marble/GeoDataCoordinatesTranslation" ),
                   placeholder, separator );
    getLocaleList( m_eastLocale, GeoDataCoordinates::tr( "*", "East direction terms, see http://techbase.kde.org/Projects/Marble/GeoDataCoordinatesTranslation" ),
                   placeholder, separator );
    getLocaleList( m_southLocale, GeoDataCoordinates::tr( "*", "South direction terms, see http://techbase.kde.org/Projects/Marble/GeoDataCoordinatesTranslation" ),
                   placeholder, separator );
    getLocaleList( m_westLocale, GeoDataCoordinates::tr( "*", "West direction terms, see http://techbase.kde.org/Projects/Marble/GeoDataCoordinatesTranslation" ),
                   placeholder, separator );

    // use a set to remove duplicates
    QSet<QString> dirs = QSet<QString>()
        << m_north << m_east << m_south << m_west;
    dirs += m_northLocale.toSet();
    dirs += m_eastLocale.toSet();
    dirs += m_southLocale.toSet();
    dirs += m_westLocale.toSet();

    QString fullNamesExp;
    QString simpleLetters;

    foreach( const QString& dir, dirs ) {
        // collect simple letters
        if ((dir.length() == 1) && (QLatin1Char('a')<=dir.at(0)) && (dir.at(0)<=QLatin1Char('z'))) {
            simpleLetters += dir;
            continue;
        }
210

211 212 213
        // okay to add '|' also for last, separates from firstLetters
        fullNamesExp += regExp(dir) + QLatin1Char('|');
    }
214

215 216 217 218 219 220 221 222 223 224 225
    // Sets "(north|east|south|west|[nesw])" in en, as translated names match untranslated ones
    m_dirCapExp =
        QLatin1Char('(') + fullNamesExp + QLatin1Char('[') + simpleLetters + QLatin1String("])");

    // expressions for symbols of degree, minutes and seconds
    getLocaleList( m_degreeLocale, GeoDataCoordinates::tr( "*", "Degree symbol terms, see http://techbase.kde.org/Projects/Marble/GeoDataCoordinatesTranslation" ),
                   placeholder, separator );
    getLocaleList( m_minutesLocale, GeoDataCoordinates::tr( "*", "Minutes symbol terms, see http://techbase.kde.org/Projects/Marble/GeoDataCoordinatesTranslation" ),
                   placeholder, separator );
    getLocaleList( m_secondsLocale, GeoDataCoordinates::tr( "*", "Seconds symbol terms, see http://techbase.kde.org/Projects/Marble/GeoDataCoordinatesTranslation" ),
                   placeholder, separator );
226 227 228

    // Used unicode regexp expressions:
    // x00B0: ° DEGREE SIGN
229
    // x00BA: º MASCULINE ORDINAL INDICATOR (found used as degree sign)
230
    // x2032: ′ PRIME (minutes)
231 232 233
    // x00B4: ´ ACUTE ACCENT (found as minutes sign)
    // x02CA: ˊ MODIFIER LETTER ACUTE ACCENT
    // x2019: ’ RIGHT SINGLE QUOTATION MARK
234
    // x2033: ″ DOUBLE PRIME (seconds)
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
    // x201D: ” RIGHT DOUBLE QUOTATION MARK

    m_degreeExp = QLatin1String("\\x00B0|\\x00BA");
    foreach(const QString& symbol, m_degreeLocale) {
        m_degreeExp += QLatin1Char('|') + regExp(symbol);
    }
    m_minutesExp = QLatin1String("'|\\x2032|\\x00B4|\\x20C2|\\x2019");
    foreach(const QString& symbol, m_minutesLocale) {
        m_minutesExp += QLatin1Char('|') + regExp(symbol);
    }
    m_secondsExp = QLatin1String("\"|\\x2033|\\x201D|''|\\x2032\\x2032|\\x00B4\\x00B4|\\x20C2\\x20C2|\\x2019\\x2019");
    foreach(const QString& symbol, m_secondsLocale) {
        m_secondsExp += QLatin1Char('|') + regExp(symbol);
    }
}

bool LonLatParser::parse( const QString& string )
{
    QString input = string.toLower().trimmed();
254 255 256 257

    // #1: Just two numbers, no directions, e.g. 74.2245 -32.2434 (assumes lat lon)
    {
        const QString numberCapExp = QString::fromLatin1(
258 259
            "([-+]?\\d{1,3}%1?\\d*(?:[eE][+-]?\\d+)?)(?:,|;|\\s)\\s*"
            "([-+]?\\d{1,3}%1?\\d*(?:[eE][+-]?\\d+)?)"
260 261 262 263
            ).arg(m_decimalPointExp);

        const QRegExp regex = QRegExp( numberCapExp );
        if( regex.exactMatch(input) ) {
264 265
            m_lon = parseDouble(regex.cap(2));
            m_lat = parseDouble(regex.cap(1));
266 267 268 269 270 271 272

            return true;
        }
    }

    initAll();

273 274 275
    if ( tryMatchFromD( input, PostfixDir ) ) {
        return true;
    }
276

277
    if ( tryMatchFromD( input, PrefixDir ) ) {
278 279
        return true;
    }
280

281 282 283
    if ( tryMatchFromDms( input, PostfixDir ) ) {
        return true;
    }
284

285
    if ( tryMatchFromDms( input, PrefixDir ) ) {
286 287 288
        return true;
    }

289 290 291 292 293 294 295 296 297 298 299 300 301 302
    if ( tryMatchFromDm( input, PostfixDir ) ) {
        return true;
    }

    if ( tryMatchFromDm( input, PrefixDir ) ) {
        return true;
    }

    return false;
}

// #3: Sexagesimal
bool LonLatParser::tryMatchFromDms( const QString& input, DirPosition dirPosition )
{
303
    // direction as postfix
304
    const char postfixCapExp[] =
305 306 307 308
        "([-+]?)(\\d{1,3})(?:%3|\\s)\\s*(\\d{1,2})(?:%4|\\s)\\s*"
        "(\\d{1,2}%1?\\d*)(?:%5)?\\s*%2[,;]?\\s*"
        "([-+]?)(\\d{1,3})(?:%3|\\s)\\s*(\\d{1,2})(?:%4|\\s)\\s*"
        "(\\d{1,2}%1?\\d*)(?:%5)?\\s*%2";
309

310
    // direction as prefix
311
    const char prefixCapExp[] =
312 313 314 315 316
        "%2\\s*([-+]?)(\\d{1,3})(?:%3|\\s)\\s*(\\d{1,2})(?:%4|\\s)\\s*"
        "(\\d{1,2}%1?\\d*)(?:%5)?\\s*(?:,|;|\\s)\\s*"
        "%2\\s*([-+]?)(\\d{1,3})(?:%3|\\s)\\s*(\\d{1,2})(?:%4|\\s)\\s*"
        "(\\d{1,2}%1?\\d*)(?:%5)?";

317 318 319 320 321 322 323 324 325 326
    const char *expTemplate = ( dirPosition == PostfixDir ) ? postfixCapExp
                                                            : prefixCapExp;

    const QString numberCapExp =
        QString::fromLatin1( expTemplate ).arg( m_decimalPointExp, m_dirCapExp,
                                                m_degreeExp, m_minutesExp, m_secondsExp);

    const QRegExp regex = QRegExp( numberCapExp );
    if( !regex.exactMatch( input ) ) {
        return false;
327 328
    }

329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
    bool isDir1LonDir;
    bool isLonDirPosHemisphere;
    bool isLatDirPosHemisphere;
    const QString dir1 = regex.cap( dirPosition == PostfixDir ? 5 : 1 );
    const QString dir2 = regex.cap( dirPosition == PostfixDir ? 10 : 6 );
    if ( !isCorrectDirections( dir1, dir2, isDir1LonDir,
                               isLonDirPosHemisphere, isLatDirPosHemisphere ) ) {
        return false;
    }

    const int valueStartIndex1 = (dirPosition == PostfixDir ? 1 : 2);
    const int valueStartIndex2 = (dirPosition == PostfixDir ? 6 : 7);
    m_lon = degreeValueFromDMS( regex, isDir1LonDir ? valueStartIndex1 : valueStartIndex2,
                                isLonDirPosHemisphere );
    m_lat = degreeValueFromDMS( regex, isDir1LonDir ? valueStartIndex2 : valueStartIndex1,
                                isLatDirPosHemisphere );

    return true;
}

// #4: Sexagesimal with minute precision
bool LonLatParser::tryMatchFromDm( const QString& input, DirPosition dirPosition )
{
352
    // direction as postfix
353
    const char postfixCapExp[] =
354 355
        "([-+]?)(\\d{1,3})(?:%3|\\s)\\s*(\\d{1,2}%1?\\d*)(?:%4)?\\s*%2[,;]?\\s*"
        "([-+]?)(\\d{1,3})(?:%3|\\s)\\s*(\\d{1,2}%1?\\d*)(?:%4)?\\s*%2";
356

357
    // direction as prefix
358
    const char prefixCapExp[] =
359 360 361
        "%2\\s*([-+]?)(\\d{1,3})(?:%3|\\s)\\s*(\\d{1,2}%1?\\d*)(?:%4)?\\s*(?:,|;|\\s)\\s*"
        "%2\\s*([-+]?)(\\d{1,3})(?:%3|\\s)\\s*(\\d{1,2}%1?\\d*)(?:%4)?";

362 363 364 365 366 367 368 369 370
    const char *expTemplate = ( dirPosition == PostfixDir ) ? postfixCapExp
                                                            : prefixCapExp;

    const QString numberCapExp =
        QString::fromLatin1( expTemplate ).arg( m_decimalPointExp, m_dirCapExp,
                                                m_degreeExp, m_minutesExp );
    const QRegExp regex = QRegExp( numberCapExp );
    if( !regex.exactMatch(input) ) {
        return false;
371 372
    }

373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
    bool isDir1LonDir;
    bool isLonDirPosHemisphere;
    bool isLatDirPosHemisphere;
    const QString dir1 = regex.cap( dirPosition == PostfixDir ? 4 : 1 );
    const QString dir2 = regex.cap( dirPosition == PostfixDir ? 8 : 5 );
    if ( !isCorrectDirections( dir1, dir2, isDir1LonDir,
                               isLonDirPosHemisphere, isLatDirPosHemisphere ) ) {
        return false;
    }

    const int valueStartIndex1 = ( dirPosition == PostfixDir ? 1 : 2 );
    const int valueStartIndex2 = ( dirPosition == PostfixDir ? 5 : 6 );
    m_lon = degreeValueFromDM( regex, isDir1LonDir ? valueStartIndex1 : valueStartIndex2,
                               isLonDirPosHemisphere );
    m_lat = degreeValueFromDM( regex, isDir1LonDir ? valueStartIndex2 : valueStartIndex1,
                               isLatDirPosHemisphere );

    return true;
391 392
}

393 394
// #2: Two numbers with directions
bool LonLatParser::tryMatchFromD( const QString& input, DirPosition dirPosition )
395
{
396
    // direction as postfix, e.g. 74.2245 N 32.2434 W
397
    const char postfixCapExp[] =
398 399 400 401
        "([-+]?\\d{1,3}%1?\\d*)(?:%3)?(?:\\s*)%2(?:,|;|\\s)\\s*"
        "([-+]?\\d{1,3}%1?\\d*)(?:%3)?(?:\\s*)%2";

    // direction as prefix, e.g. N 74.2245 W 32.2434
402
    const char prefixCapExp[] =
403 404 405 406 407
        "%2\\s*([-+]?\\d{1,3}%1?\\d*)(?:%3)?\\s*(?:,|;|\\s)\\s*"
        "%2\\s*([-+]?\\d{1,3}%1?\\d*)(?:%3)?";

    const char *expTemplate = ( dirPosition == PostfixDir ) ? postfixCapExp
                                                            : prefixCapExp;
408

409
    const QString numberCapExp =
410
        QString::fromLatin1( expTemplate ).arg( m_decimalPointExp, m_dirCapExp, m_degreeExp );
411
    const QRegExp regex = QRegExp( numberCapExp );
412 413
    if( !regex.exactMatch( input ) ) {
        return false;
414 415
    }

416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
    bool isDir1LonDir;
    bool isLonDirPosHemisphere;
    bool isLatDirPosHemisphere;
    const QString dir1 = regex.cap( dirPosition == PostfixDir ? 2 : 1 );
    const QString dir2 = regex.cap( dirPosition == PostfixDir ? 4 : 3 );
    if ( !isCorrectDirections( dir1, dir2, isDir1LonDir,
                               isLonDirPosHemisphere, isLatDirPosHemisphere ) ) {
        return false;
    }

    const int valueStartIndex1 = ( dirPosition == PostfixDir ? 1 : 2 );
    const int valueStartIndex2 = ( dirPosition == PostfixDir ? 3 : 4 );
    m_lon = degreeValueFromD( regex, isDir1LonDir ? valueStartIndex1 : valueStartIndex2,
                              isLonDirPosHemisphere );
    m_lat = degreeValueFromD( regex, isDir1LonDir ? valueStartIndex2 : valueStartIndex1,
                              isLatDirPosHemisphere );

    return true;
434 435
}

436 437 438 439 440 441 442 443 444 445
double LonLatParser::parseDouble(const QString& input)
{
    // Decide by decimalpoint if system locale or C locale should be tried.
    // Otherwise if first trying with a system locale when the string is in C locale,
    // the "." might be misinterpreted as thousands group separator and thus a wrong
    // value yielded
    QLocale locale = QLocale::system();
    return input.contains(locale.decimalPoint()) ? locale.toDouble(input) : input.toDouble();
}

446 447 448 449 450 451 452 453
QString LonLatParser::createDecimalPointExp()
{
    const QChar decimalPoint = QLocale::system().decimalPoint();

    return (decimalPoint == QLatin1Char('.')) ? QString::fromLatin1("\\.") :
        QLatin1String("[.") + decimalPoint + QLatin1Char(']');
}

454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
QString LonLatParser::regExp(const QString& string)
{
    QString result;
    for (int i = 0; i < string.length(); ++i) {
        const QChar c = string.at(i);
        if ((QLatin1Char('a') <= c) && (c <= QLatin1Char('z'))) {
            result += c;
        } else if (c.isSpace()) {
            result += QLatin1String("\\s");
        } else if (c == QLatin1Char('.')) {
            result += QLatin1String("\\.");
        } else {
            result += QString::fromLatin1("\\x%1").arg(c.unicode(), 4, 16, QLatin1Char('0'));
        }
    }
    return result;
}

void LonLatParser::getLocaleList( QStringList& localeList, const QString& localeListString,
                                  const QLatin1String& placeholder, const QString& separator )
474
{
475 476 477 478 479 480 481 482 483 484 485 486 487 488
    const QString lowerLocaleListString = localeListString.toLower();
    if (lowerLocaleListString != placeholder) {
        localeList = lowerLocaleListString.split(separator, QString::SkipEmptyParts);
    }
}

bool LonLatParser::isDirection( const QString& input, const QStringList& directions )
{
    return ( directions.contains(input) );
}

bool LonLatParser::isDirection( const QString& input, const QString& direction )
{
    return ( input == direction );
489 490 491 492 493 494 495 496 497 498 499
}

bool LonLatParser::isOneOfDirections( const QString& input,
                                      const QString& firstDirection,
                                      const QString& secondDirection,
                                      bool& isFirstDirection )
{
    isFirstDirection = isDirection(input, firstDirection);
    return isFirstDirection || isDirection(input, secondDirection);
}

500 501 502 503 504 505 506 507 508
bool LonLatParser::isOneOfDirections( const QString& input,
                                      const QStringList& firstDirections,
                                      const QStringList& secondDirections,
                                      bool& isFirstDirection )
{
    isFirstDirection = isDirection(input, firstDirections);
    return isFirstDirection || isDirection(input, secondDirections);
}

509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539

bool LonLatParser::isLocaleLonDirection( const QString& input,
                                         bool& isDirPosHemisphere ) const
{
    return isOneOfDirections(input, m_eastLocale, m_westLocale, isDirPosHemisphere);
}

bool LonLatParser::isLocaleLatDirection( const QString& input,
                                         bool& isDirPosHemisphere ) const
{
    return isOneOfDirections(input, m_northLocale, m_southLocale, isDirPosHemisphere);
}

bool LonLatParser::isLonDirection( const QString& input,
                                   bool& isDirPosHemisphere ) const
{
    return isOneOfDirections(input, m_east, m_west, isDirPosHemisphere);
}

bool LonLatParser::isLatDirection( const QString& input,
                                   bool& isDirPosHemisphere ) const
{
    return isOneOfDirections(input, m_north, m_south, isDirPosHemisphere);
}


qreal LonLatParser::degreeValueFromDMS( const QRegExp& regex, int c, bool isPosHemisphere )
{
    const bool isNegativeValue = (regex.cap( c++ ) == QLatin1String("-"));
    const uint degree = regex.cap( c++ ).toUInt();
    const uint minutes = regex.cap( c++ ).toUInt();
540
    const qreal seconds = parseDouble(regex.cap( c ));
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555

    qreal result = degree + (minutes*MIN2HOUR) + (seconds*SEC2HOUR);

    if (isNegativeValue)
        result *= -1;
    if (! isPosHemisphere)
        result *= -1;

    return result;
}

qreal LonLatParser::degreeValueFromDM( const QRegExp& regex, int c, bool isPosHemisphere )
{
    const bool isNegativeValue = (regex.cap( c++ ) == QLatin1String("-"));
    const uint degree = regex.cap( c++ ).toUInt();
556
    const qreal minutes = parseDouble(regex.cap( c ));
557 558 559 560 561 562 563 564 565 566 567 568 569

    qreal result = degree + (minutes*MIN2HOUR);

    if (isNegativeValue)
        result *= -1;
    if (! isPosHemisphere)
        result *= -1;

    return result;
}

qreal LonLatParser::degreeValueFromD( const QRegExp& regex, int c, bool isPosHemisphere )
{
570
    qreal result = parseDouble(regex.cap( c ));
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600

    if (! isPosHemisphere)
        result *= -1;

    return result;
}

bool LonLatParser::isCorrectDirections(const QString& dir1, const QString& dir2,
                                       bool& isDir1LonDir,
                                       bool& isLonDirPosHemisphere,
                                       bool& isLatDirPosHemisphere) const
{
    // first try localized names
    isDir1LonDir = isLocaleLonDirection(dir1, isLonDirPosHemisphere);
    const bool resultLocale = isDir1LonDir ?
        isLocaleLatDirection(dir2, isLatDirPosHemisphere) :
        (isLocaleLatDirection(dir1, isLatDirPosHemisphere) &&
         isLocaleLonDirection(dir2, isLonDirPosHemisphere));

    if (resultLocale)
        return resultLocale;

    // fallback to try english names as lingua franca
    isDir1LonDir = isLonDirection(dir1, isLonDirPosHemisphere);
    return isDir1LonDir ?
        isLatDirection(dir2, isLatDirPosHemisphere) :
        (isLatDirection(dir1, isLatDirPosHemisphere) &&
         isLonDirection(dir2, isLonDirPosHemisphere));
}

601 602 603 604
const qreal GeoDataCoordinatesPrivate::sm_semiMajorAxis = 6378137.0;
const qreal GeoDataCoordinatesPrivate::sm_semiMinorAxis = 6356752.314;
const qreal GeoDataCoordinatesPrivate::sm_eccentricitySquared = 6.69437999013e-03;
const qreal GeoDataCoordinatesPrivate::sm_utmScaleFactor = 0.9996;
Torsten Rahn's avatar
Torsten Rahn committed
605 606
GeoDataCoordinates::Notation GeoDataCoordinates::s_notation = GeoDataCoordinates::DMS;

607 608
const GeoDataCoordinates GeoDataCoordinates::null = GeoDataCoordinates( 0, 0, 0 ); // don't use default constructor!

609
GeoDataCoordinates::GeoDataCoordinates( qreal _lon, qreal _lat, qreal _alt, GeoDataCoordinates::Unit unit, int _detail )
610
  : d( new GeoDataCoordinatesPrivate( _lon, _lat, _alt, unit, _detail ) )
611
{
612
    d->ref.ref();
613 614
}

615 616 617
/* simply copy the d pointer
* it will be replaced in the detach function instead
*/
618
GeoDataCoordinates::GeoDataCoordinates( const GeoDataCoordinates& other )
619
  : d( other.d )
620
{
621
    d->ref.ref();
622 623
}

624 625
/* simply copy null's d pointer
 * it will be replaced in the detach function
626
 */
627
GeoDataCoordinates::GeoDataCoordinates()
628
  : d( null.d )
629
{
630
    d->ref.ref();
631 632
}

633 634 635 636
/*
 * only delete the private d pointer if the number of references is 0
 * remember that all copies share the same d pointer!
 */
637 638
GeoDataCoordinates::~GeoDataCoordinates()
{
639 640 641
    delete d->m_q;
    d->m_q = 0;

642 643
    if (!d->ref.deref())
        delete d;
Laurent Montel's avatar
Laurent Montel committed
644
#ifdef DEBUG_GEODATA
Patrick Spendrin's avatar
Patrick Spendrin committed
645
//    mDebug() << "delete coordinates";
646 647 648
#endif
}

649 650 651 652 653
bool GeoDataCoordinates::isValid() const
{
    return d != null.d;
}

654 655 656 657 658 659 660 661
/*
 * if only one copy exists, return
 * else make a new private d pointer object and assign the values of the current
 * one to it
 * at the end, if the number of references thus reaches 0 delete it
 * this state shouldn't happen, but if it does, we have to clean up behind us.
 */
void GeoDataCoordinates::detach()
662
{    
663
    if(d->ref.load() == 1) {
664 665 666
        delete d->m_q;
        d->m_q = 0;

667
        return;
668
    }
669 670 671 672 673 674 675

    GeoDataCoordinatesPrivate *new_d = new GeoDataCoordinatesPrivate( *d );

    if (!d->ref.deref())
        delete d;

    d = new_d;
676
    d->ref.ref();
677 678 679 680 681
}

/*
 * call detach() at the start of all non-static, non-const functions
 */
682
void GeoDataCoordinates::set( qreal _lon, qreal _lat, qreal _alt, GeoDataCoordinates::Unit unit )
683
{
684
    detach();
685
    d->m_altitude = _alt;
686
    switch( unit ){
Torsten Rahn's avatar
 
Torsten Rahn committed
687
    default:
688
    case Radian:
689 690
        d->m_lon = _lon;
        d->m_lat = _lat;
691 692
        break;
    case Degree:
693 694
        d->m_lon = _lon * DEG2RAD;
        d->m_lat = _lat * DEG2RAD;
695 696
        break;
    }
697 698
}

Torsten Rahn's avatar
 
Torsten Rahn committed
699 700 701 702 703 704 705
/*
 * call detach() at the start of all non-static, non-const functions
 */
void GeoDataCoordinates::setLongitude( qreal _lon, GeoDataCoordinates::Unit unit )
{
    detach();
    switch( unit ){
Torsten Rahn's avatar
 
Torsten Rahn committed
706
    default:
Torsten Rahn's avatar
 
Torsten Rahn committed
707 708 709 710 711 712 713 714 715
    case Radian:
        d->m_lon = _lon;
        break;
    case Degree:
        d->m_lon = _lon * DEG2RAD;
        break;
    }
}

716

Torsten Rahn's avatar
 
Torsten Rahn committed
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
/*
 * call detach() at the start of all non-static, non-const functions
 */
void GeoDataCoordinates::setLatitude( qreal _lat, GeoDataCoordinates::Unit unit )
{
    detach();
    switch( unit ){
    case Radian:
        d->m_lat = _lat;
        break;
    case Degree:
        d->m_lat = _lat * DEG2RAD;
        break;
    }
}

733
void GeoDataCoordinates::geoCoordinates( qreal& lon, qreal& lat, 
734 735 736 737
                               GeoDataCoordinates::Unit unit ) const
{
    switch ( unit ) 
    {
Torsten Rahn's avatar
 
Torsten Rahn committed
738
    default:
739
    case Radian:
740 741
            lon = d->m_lon;
            lat = d->m_lat;
742 743
        break;
    case Degree:
744 745
            lon = d->m_lon * RAD2DEG;
            lat = d->m_lat * RAD2DEG;
746 747 748 749
        break;
    }
}

750 751 752
void GeoDataCoordinates::geoCoordinates( qreal& lon, qreal& lat, qreal& alt,
                                         GeoDataCoordinates::Unit unit ) const
{
753
    geoCoordinates( lon, lat, unit );
754 755 756
    alt = d->m_altitude;
}

Torsten Rahn's avatar
 
Torsten Rahn committed
757 758
qreal GeoDataCoordinates::longitude( GeoDataCoordinates::Unit unit ) const
{
759
    switch ( unit )
Torsten Rahn's avatar
 
Torsten Rahn committed
760
    {
Patrick Spendrin's avatar
Patrick Spendrin committed
761
    default:
Torsten Rahn's avatar
 
Torsten Rahn committed
762
    case Radian:
Patrick Spendrin's avatar
Patrick Spendrin committed
763
        return d->m_lon;
Torsten Rahn's avatar
 
Torsten Rahn committed
764 765
    case Degree:
        return d->m_lon * RAD2DEG;
Torsten Rahn's avatar
 
Torsten Rahn committed
766 767 768 769 770
    }
}

qreal GeoDataCoordinates::latitude( GeoDataCoordinates::Unit unit ) const
{
771
    switch ( unit )
Torsten Rahn's avatar
 
Torsten Rahn committed
772
    {
Patrick Spendrin's avatar
Patrick Spendrin committed
773
    default:
Torsten Rahn's avatar
 
Torsten Rahn committed
774
    case Radian:
Patrick Spendrin's avatar
Patrick Spendrin committed
775
        return d->m_lat;
Torsten Rahn's avatar
 
Torsten Rahn committed
776 777
    case Degree:
        return d->m_lat * RAD2DEG;
Torsten Rahn's avatar
 
Torsten Rahn committed
778 779 780
    }
}

781
//static
Torsten Rahn's avatar
Torsten Rahn committed
782 783 784 785 786
GeoDataCoordinates::Notation GeoDataCoordinates::defaultNotation()
{
    return s_notation;
}

787
//static
Torsten Rahn's avatar
Torsten Rahn committed
788 789 790 791 792
void GeoDataCoordinates::setDefaultNotation( GeoDataCoordinates::Notation notation )
{
    s_notation = notation;
}

793
//static
794
qreal GeoDataCoordinates::normalizeLon( qreal lon, GeoDataCoordinates::Unit unit )
795
{
796
    qreal halfCircle;
Bastian Holst's avatar
Marble:  
Bastian Holst committed
797
    if ( unit == GeoDataCoordinates::Radian ) {
798 799 800 801 802 803
        halfCircle = M_PI;
    }
    else {
        halfCircle = 180;
    }

Bastian Holst's avatar
Marble:  
Bastian Holst committed
804
    if ( lon > halfCircle ) {
805 806
        int cycles = (int)( ( lon + halfCircle ) / ( 2 * halfCircle ) );
        return lon - ( cycles * 2 * halfCircle );
807
    } 
808 809 810
    if ( lon < -halfCircle ) {
        int cycles = (int)( ( lon - halfCircle ) / ( 2 * halfCircle ) );
        return lon - ( cycles * 2 * halfCircle );
811 812 813 814 815
    }

    return lon;
}

816
//static
817
qreal GeoDataCoordinates::normalizeLat( qreal lat, GeoDataCoordinates::Unit unit )
818
{
819
    qreal halfCircle;
Bastian Holst's avatar
Marble:  
Bastian Holst committed
820
    if ( unit == GeoDataCoordinates::Radian ) {
821 822 823 824 825 826 827 828
        halfCircle = M_PI;
    }
    else {
        halfCircle = 180;
    }

    if ( lat > ( halfCircle / 2.0 ) ) {
        int cycles = (int)( ( lat + halfCircle ) / ( 2 * halfCircle ) );
829
        qreal temp;
830
        if( cycles == 0 ) { // pi/2 < lat < pi
831
            temp = halfCircle - lat;
832
        } else {
833
            temp = lat - ( cycles * 2 * halfCircle );
834
        }
835 836
        if ( temp > ( halfCircle / 2.0 ) ) {
            return ( halfCircle - temp );
837
        }
838 839
        if ( temp < ( -halfCircle / 2.0 ) ) {
            return ( -halfCircle - temp );
840 841 842
        }
        return temp;
    } 
843 844
    if ( lat < ( -halfCircle / 2.0 ) ) {
        int cycles = (int)( ( lat - halfCircle ) / ( 2 * halfCircle ) );
845
        qreal temp;
846
        if( cycles == 0 ) { 
847
            temp = -halfCircle - lat;
848
        } else {
849
            temp = lat - ( cycles * 2 * halfCircle );
850
        }
851 852
        if ( temp > ( +halfCircle / 2.0 ) ) {
            return ( +halfCircle - temp );
853
        }
854 855
        if ( temp < ( -halfCircle / 2.0 ) ) {
            return ( -halfCircle - temp );
856 857 858 859 860 861
        }
        return temp;
    }
    return lat;
}

862
//static
863
void GeoDataCoordinates::normalizeLonLat( qreal &lon, qreal &lat, GeoDataCoordinates::Unit unit )
864
{
865
    qreal halfCircle;
Bastian Holst's avatar
Marble:  
Bastian Holst committed
866
    if ( unit == GeoDataCoordinates::Radian ) {
867 868 869 870 871 872 873 874 875
        halfCircle = M_PI;
    }
    else {
        halfCircle = 180;
    }

    if ( lon > +halfCircle ) {
        int cycles = (int)( ( lon + halfCircle ) / ( 2 * halfCircle ) );
        lon = lon - ( cycles * 2 * halfCircle );
876
    } 
877 878 879
    if ( lon < -halfCircle ) {
        int cycles = (int)( ( lon - halfCircle ) / ( 2 * halfCircle ) );
        lon = lon - ( cycles * 2 * halfCircle );
880 881
    }

882 883
    if ( lat > ( +halfCircle / 2.0 ) ) {
        int cycles = (int)( ( lat + halfCircle ) / ( 2 * halfCircle ) );
884
        qreal temp;
885
        if( cycles == 0 ) { // pi/2 < lat < pi
886
            temp = halfCircle - lat;
887
        } else {
888
            temp = lat - ( cycles * 2 * halfCircle );
889
        }
890 891
        if ( temp > ( +halfCircle / 2.0 ) ) {
            lat =  +halfCircle - temp;
892
        }
893 894
        if ( temp < ( -halfCircle / 2.0 ) ) {
            lat =  -halfCircle - temp;
895 896 897
        }
        lat = temp;
        if( lon > 0 ) { 
898
            lon = -halfCircle + lon;
899
        } else {
900
            lon = halfCircle + lon;
901 902
        }
    } 
903 904
    if ( lat < ( -halfCircle / 2.0 ) ) {
        int cycles = (int)( ( lat - halfCircle ) / ( 2 * halfCircle ) );
905
        qreal temp;
906
        if( cycles == 0 ) { 
907
            temp = -halfCircle - lat;
908
        } else {
909
            temp = lat - ( cycles * 2 * halfCircle );
910
        }
911 912
        if ( temp > ( +halfCircle / 2.0 ) ) {
            lat =  +halfCircle - temp;
913
        }
914 915
        if ( temp < ( -halfCircle / 2.0 ) ) {
            lat =  -halfCircle - temp;
916 917 918
        }
        lat = temp;
        if( lon > 0 ) { 
919
            lon = -halfCircle + lon;
920
        } else {
921
            lon = halfCircle + lon;
922 923 924 925 926
        }
    } 
    return;
}

927 928
GeoDataCoordinates GeoDataCoordinates::fromString( const QString& string, bool& successful )
{
929 930 931 932 933 934
    LonLatParser parser;
    successful = parser.parse(string);
    if (successful) {
        return GeoDataCoordinates( parser.lon(), parser.lat(), 0, GeoDataCoordinates::Degree );
    } else {
        return GeoDataCoordinates();
935 936 937 938
    }
}


Patrick Spendrin's avatar
Patrick Spendrin committed
939
QString GeoDataCoordinates::toString() const
Torsten Rahn's avatar
Torsten Rahn committed
940 941 942 943
{
    return GeoDataCoordinates::toString( s_notation );
}

Torsten Rahn's avatar
 
Torsten Rahn committed
944
QString GeoDataCoordinates::toString( GeoDataCoordinates::Notation notation, int precision ) const
945
{
946 947 948
        QString coordString;

        if( notation == GeoDataCoordinates::UTM ){
949
            int zoneNumber = GeoDataCoordinatesPrivate::lonLatToZone(d->m_lon, d->m_lat);
950

951 952
            // Handle lack of UTM zone number in the poles
            QString zoneString = ( zoneNumber > 0 ) ? QString::number(zoneNumber) : QString("");
953

954 955 956 957
            QString bandString = GeoDataCoordinatesPrivate::lonLatToLatitudeBand(d->m_lon, d->m_lat);

            QString eastingString  = QString::number(GeoDataCoordinatesPrivate::lonLatToEasting(d->m_lon, d->m_lat), 'f', 2);
            QString northingString = QString::number(GeoDataCoordinatesPrivate::lonLatToNorthing(d->m_lon, d->m_lat), 'f', 2);
958 959

            return QString("%1%2 %3 m E, %4 m N").arg(zoneString).arg(bandString).arg(eastingString).arg(northingString);
960 961 962 963 964 965 966 967
        }
        else{
            coordString = lonToString( d->m_lon, notation, Radian, precision )
                        + QString(", ")
                        + latToString( d->m_lat, notation, Radian, precision );
        }

        return coordString;
Torsten Rahn's avatar
 
Torsten Rahn committed
968
}
969

Torsten Rahn's avatar
 
Torsten Rahn committed
970 971 972 973 974
QString GeoDataCoordinates::lonToString( qreal lon, GeoDataCoordinates::Notation notation,  
                                                    GeoDataCoordinates::Unit unit, 
                                                    int precision,
                                                    char format )
{
975
    if( notation == GeoDataCoordinates::UTM ){
976
        /**
977
         * @FIXME: UTM needs lon + lat to know zone number and easting
978 979
         * By now, this code returns the zone+easting of the point
         * (lon, equator), but this can differ a lot at different locations
980
         * See bug 347536 https://bugs.kde.org/show_bug.cgi?id=347536
981 982 983 984
         */

        qreal lonRad = ( unit == Radian ) ? lon : lon * DEG2RAD;

985 986 987 988
        int zoneNumber = GeoDataCoordinatesPrivate::lonLatToZone(lonRad, 0);

        // Handle lack of UTM zone number in the poles
        QString result = ( zoneNumber > 0 ) ? QString::number(zoneNumber) : QString("");
989 990

        if(precision > 0){
991
            QString eastingString = QString::number( GeoDataCoordinatesPrivate::lonLatToEasting(lonRad, 0), 'f', 2 );
992
            result += QString(" %1 m E").arg(eastingString);
993 994 995
        }

        return result;
996
    }
997

998
    QString weString = ( lon < 0 ) ? tr("W") : tr("E");
Torsten Rahn's avatar
 
Torsten Rahn committed
999 1000 1001 1002 1003 1004 1005 1006

    QString lonString;

    qreal lonDegF = ( unit == Degree ) ? fabs( lon ) : fabs( (qreal)(lon) * RAD2DEG );

    // Take care of -1 case
    precision = ( precision < 0 ) ? 5 : precision;
    
1007
    if ( notation == DMS || notation == DM ) {
Torsten Rahn's avatar
 
Torsten Rahn committed
1008
        int lonDeg = (int) lonDegF;
Torsten Rahn's avatar
 
Torsten Rahn committed
1009 1010 1011 1012 1013 1014
        qreal lonMinF = 60 * (lonDegF - lonDeg);
        int lonMin = (int) lonMinF;
        qreal lonSecF = 60 * (lonMinF - lonMin);
        int lonSec = (int) lonSecF;

        // Adjustment for fuzziness (like 49.999999999999999999999)
Bernhard Beschow's avatar
Bernhard Beschow committed
1015 1016 1017 1018
        if ( precision == 0 ) {
            lonDeg = qRound( lonDegF );
        } else if ( precision <= 2 ) {
            lonMin = qRound( lonMinF );
1019
        } else if ( precision <= 4 && notation == DMS ) {
Torsten Rahn's avatar