locationsettings.cpp 27.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
/*
 * Copyright (C) 2017 Jolla Ltd.
 * Contact: Chris Adams <chris.adams@jolla.com>
 *
 * You may use this file under the terms of the BSD license as follows:
 *
 * "Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in
 *     the documentation and/or other materials provided with the
 *     distribution.
 *   * Neither the name of Nemo Mobile nor the names of its contributors
 *     may be used to endorse or promote products derived from this
 *     software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
 */

#include "locationsettings.h"
34
#include "locationsettings_p.h"
35 36

#include <QFile>
37 38
#include <QTimer>
#include <QDebug>
39 40 41 42 43 44 45 46

#include <sailfishkeyprovider.h>
#include <sailfishkeyprovider_iniparser.h>
#include <sailfishkeyprovider_processmutex.h>

#include <networkmanager.h>
#include <networktechnology.h>

47 48
#include <limits>

49
namespace {
50 51 52 53
    const QString LocationSettingsDeprecatedCellIdPositioningEnabledKey = QStringLiteral("cell_id_positioning_enabled");
    const QString LocationSettingsDeprecatedHereEnabledKey = QStringLiteral("here_agreement_accepted");
    const QString LocationSettingsDeprecatedHereAgreementAcceptedKey = QStringLiteral("agreement_accepted");

54 55 56 57 58 59 60
    const QString PoweredPropertyName = QStringLiteral("Powered");
    const QString LocationSettingsDir = QStringLiteral("/etc/location/");
    const QString LocationSettingsFile = QStringLiteral("/etc/location/location.conf");
    const QString LocationSettingsSection = QStringLiteral("location");
    const QString LocationSettingsEnabledKey = QStringLiteral("enabled");
    const QString LocationSettingsCustomModeKey = QStringLiteral("custom_mode");
    const QString LocationSettingsGpsEnabledKey = QStringLiteral("gps\\enabled");
61 62 63 64 65

    const QString ProviderOfflineEnabledPattern = QStringLiteral("%1\\enabled");
    const QString ProviderAgreementAcceptedPattern = QStringLiteral("%1\\agreement_accepted");
    const QString ProviderOnlineEnabledPattern = QStringLiteral("%1\\online_enabled");

66 67 68 69 70 71 72 73 74 75 76 77
    const QMap<LocationSettings::DataSource, QString> AllowedDataSourcesKeys {
        { LocationSettings::OnlineDataSources, QStringLiteral("allowed_data_sources\\online") },
        { LocationSettings::DeviceSensorsData, QStringLiteral("allowed_data_sources\\device_sensors") },
        { LocationSettings::BluetoothData, QStringLiteral("allowed_data_sources\\bt_addr") },
        { LocationSettings::WlanData, QStringLiteral("allowed_data_sources\\wlan_data") },
        { LocationSettings::CellTowerData, QStringLiteral("allowed_data_sources\\cell_data") },
        { LocationSettings::GpsData, QStringLiteral("allowed_data_sources\\gps") },
        { LocationSettings::GlonassData, QStringLiteral("allowed_data_sources\\glonass") },
        { LocationSettings::BeidouData, QStringLiteral("allowed_data_sources\\beidou") },
        { LocationSettings::GalileoData, QStringLiteral("allowed_data_sources\\galileo") },
        { LocationSettings::QzssData, QStringLiteral("allowed_data_sources\\qzss") },
        { LocationSettings::SbasData, QStringLiteral("allowed_data_sources\\sbas") }
78
    };
79 80 81 82

    const QString YandexName = QStringLiteral("yandex");
    const QString HereName = QStringLiteral("here");
    const QString MlsName = QStringLiteral("mls");
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 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 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
}

IniFile::IniFile(const QString &fileName)
    : m_fileName(fileName)
    , m_keyFile(Q_NULLPTR)
    , m_error(Q_NULLPTR)
    , m_modified(false)
    , m_valid(false)
{
    m_processMutex.reset(new Sailfish::KeyProvider::ProcessMutex(qPrintable(m_fileName)));
    m_processMutex->lock();
    m_keyFile = g_key_file_new();
    if (!m_keyFile) {
        qWarning() << "Unable to allocate key file:" << m_fileName;
    } else {
        g_key_file_load_from_file(m_keyFile,
                                  qPrintable(m_fileName),
                                  G_KEY_FILE_NONE,
                                  &m_error);
        if (m_error) {
            qWarning() << "Unable to load key file:" << m_fileName << ":"
                       << m_error->code << QString::fromUtf8(m_error->message);
            g_error_free(m_error);
            m_error = Q_NULLPTR;
        } else {
            m_valid = true;
        }
    }
}

IniFile::~IniFile()
{
    if (m_valid && m_modified) {
        g_key_file_save_to_file(m_keyFile,
                                qPrintable(m_fileName),
                                &m_error);
        if (m_error) {
            qWarning() << "Unable to save changes to key file:" << m_fileName << ":"
                       << m_error->code << QString::fromUtf8(m_error->message);
            g_error_free(m_error);
            m_error = Q_NULLPTR;
        }
    }
    if (m_keyFile) {
        g_key_file_free(m_keyFile);
    }
    m_processMutex->unlock();
}

bool IniFile::isValid() const
{
    return m_valid;
}

bool IniFile::readBool(const QString &section, const QString &key, bool *value, bool defaultValue)
{
    gboolean val = g_key_file_get_boolean(m_keyFile,
                                          qPrintable(section),
                                          qPrintable(key),
                                          &m_error);
    if (m_error) {
        // if MDM hasn't set allowed / disallowed data sources yet, the key may not exist.
        if (m_error->code != G_KEY_FILE_ERROR_KEY_NOT_FOUND) {
            // other errors should be printed to the journal.
            qWarning() << "Unable to read bool from key file:" << m_fileName << ":"
                       << section << "/" << key << ":"
                       << m_error->code << QString::fromUtf8(m_error->message);
        }
        g_error_free(m_error);
        m_error = Q_NULLPTR;
        *value = defaultValue;
        return false;
    }
    *value = val;
    return true;
}

void IniFile::writeBool(const QString &section, const QString &key, bool value)
{
    g_key_file_set_boolean(m_keyFile,
                           qPrintable(section),
                           qPrintable(key),
                           value ? TRUE : FALSE);
    m_modified = true;
}

void IniFile::writeString(const QString &section, const QString &key, const QString &value)
{
    g_key_file_set_string(m_keyFile,
                          qPrintable(section),
                          qPrintable(key),
                          qPrintable(value));
    m_modified = true;
176 177
}

178 179 180
LocationSettingsPrivate::LocationSettingsPrivate(LocationSettings::Mode mode, LocationSettings *settings)
    : QObject(settings)
    , q(settings)
181 182
    , m_locationEnabled(false)
    , m_gpsEnabled(false)
183 184
    , m_locationMode(LocationSettings::CustomMode)
    , m_settingMultipleSettings(false)
185
    , m_allowedDataSources(static_cast<LocationSettings::DataSources>(std::numeric_limits<quint32>::max()))
186 187
    , m_connMan(Q_NULLPTR)
    , m_gpsTech(Q_NULLPTR)
188 189 190 191 192 193
    , m_gpsTechInterface(mode == LocationSettings::AsynchronousMode
                         ? Q_NULLPTR
                         : new QDBusInterface("net.connman",
                                              "/net/connman/technology/gps",
                                              "net.connman.Technology",
                                              QDBusConnection::systemBus()))
194
{
195
    loadProviders();
196

197 198 199 200 201 202 203 204 205 206
    connect(&m_watcher, SIGNAL(fileChanged(QString)), this, SLOT(readSettings()));
    connect(&m_watcher, SIGNAL(directoryChanged(QString)), this, SLOT(readSettings()));

    m_watcher.addPath(LocationSettingsDir);
    if (QFile(LocationSettingsFile).exists() && m_watcher.addPath(LocationSettingsFile)) {
        readSettings();
    } else {
        qWarning() << "Unable to follow location configuration file changes";
    }

207 208 209 210 211
    if (m_gpsTechInterface) {
        QDBusConnection::systemBus().connect("net.connman",
                                             "/net/connman/technology/gps",
                                             "net.connman.Technology",
                                             "PropertyChanged",
212
                                             this, SLOT(gpsTechPropertyChanged(QString, QDBusVariant)));
213 214 215 216 217 218 219 220
    } else {
        m_connMan = NetworkManagerFactory::createInstance();
        connect(m_connMan, &NetworkManager::technologiesChanged,
                this, &LocationSettingsPrivate::findGpsTech);
        connect(m_connMan, &NetworkManager::availabilityChanged,
                this, &LocationSettingsPrivate::findGpsTech);
        findGpsTech();
    }
221 222
}

223
LocationSettingsPrivate::~LocationSettingsPrivate()
224 225
{
    if (m_gpsTech) {
226
        disconnect(m_gpsTech, 0, q, 0);
227 228
        m_gpsTech = 0;
    }
229 230 231

    delete m_gpsTechInterface;
    m_gpsTechInterface = 0;
232 233
}

234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
void LocationSettingsPrivate::loadProviders()
{
    // for now just hard-coding the known potential providers.
    // can be replaced with config type of thing if there's need to support more and more providers.
    if (QFile::exists(QStringLiteral("/usr/libexec/geoclue-here"))) {
        LocationProvider provider;
        provider.hasAgreement = true;
        m_providers[HereName] = provider;
    }

    if (QFile::exists(QStringLiteral("/usr/libexec/geoclue-mlsdb"))) {
        LocationProvider provider;
        provider.hasAgreement = true;
        provider.offlineCapable = true;
        m_providers[MlsName] = provider;
    }

    if (QFile::exists(QStringLiteral("/usr/libexec/geoclue-yandex"))) {
        LocationProvider provider;
        provider.hasAgreement = true; // supposedly
        m_providers[YandexName] = provider;
    }
}

bool LocationSettingsPrivate::updateProvider(const QString &name, const LocationProvider &state)
{
    if (!m_providers.contains(name)) {
        return false;
    }

    LocationProvider &provider = m_providers[name];

    bool agreementChanged = false;
    if (provider.hasAgreement && provider.agreementAccepted != state.agreementAccepted) {
        agreementChanged = true;
        provider.agreementAccepted = state.agreementAccepted;
    }

    bool onlineEnabledChanged = false;
    if (provider.onlineCapable && provider.onlineEnabled != state.onlineEnabled) {
        onlineEnabledChanged = true;
        provider.onlineEnabled = state.onlineEnabled;
    }

    bool offlineEnabledChanged = false;
    if (provider.offlineCapable && provider.offlineEnabled != state.offlineEnabled) {
        offlineEnabledChanged = true;
        provider.offlineEnabled = state.offlineEnabled;
    }

    if (m_locationMode != LocationSettings::CustomMode) {
        if (m_locationMode == LocationSettings::DeviceOnlyMode) {
            // device only doesn't need any agreements
            if (m_pendingAgreements.contains(name)) {
                m_pendingAgreements.removeOne(name);
                emit q->pendingAgreementsChanged();
            }
291 292 293 294 295 296 297 298
        } else if (provider.hasAgreement) {
            if (!provider.agreementAccepted && !m_pendingAgreements.contains(name)) {
                m_pendingAgreements.append(name);
                emit q->pendingAgreementsChanged();
            } else if (provider.agreementAccepted && m_pendingAgreements.contains(name)) {
                m_pendingAgreements.removeOne(name);
                emit q->pendingAgreementsChanged();
            }
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 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 352 353 354 355 356 357 358 359 360 361
        }
    }

    if (offlineEnabledChanged && name == MlsName) {
        emit q->mlsEnabledChanged();
    }
    if (agreementChanged || onlineEnabledChanged) {
        if (name == HereName) {
            emit q->hereStateChanged();
        } else if (name == MlsName) {
            emit q->mlsOnlineStateChanged();
        } else if (name == YandexName) {
            emit q->yandexOnlineStateChanged();
        }
    }

    return true;
}

LocationSettings::OnlineAGpsState LocationSettingsPrivate::onlineState(const QString &name, bool *valid) const
{
    LocationSettings::OnlineAGpsState result;
    bool resultValid = true;

    if (!m_providers.contains(name)) {
        resultValid = false;
        result = LocationSettings::OnlineAGpsAgreementNotAccepted;
    } else {
        LocationProvider provider = m_providers.value(name);
        if (!provider.onlineCapable) {
            resultValid = false;
            result = LocationSettings::OnlineAGpsAgreementNotAccepted;
        } else if (!provider.agreementAccepted) {
            result = LocationSettings::OnlineAGpsAgreementNotAccepted;
        } else {
            result = provider.onlineEnabled ? LocationSettings::OnlineAGpsEnabled
                                            : LocationSettings::OnlineAGpsDisabled;
        }
    }

    if (valid) {
        *valid = resultValid;
    }

    return result;
}

void LocationSettingsPrivate::updateOnlineAgpsState(const QString &name, LocationSettings::OnlineAGpsState state)
{
    if (!m_providers.contains(name)) {
        return;
    }
    LocationProvider provider = m_providers.value(name);
    if (state == LocationSettings::OnlineAGpsAgreementNotAccepted) {
        provider.agreementAccepted = false;
    } else {
        provider.agreementAccepted = true;
        provider.onlineEnabled = (state == LocationSettings::OnlineAGpsEnabled);
    }
    updateProvider(name, provider);
    writeSettings();
}

362
void LocationSettingsPrivate::gpsTechPropertyChanged(const QString &propertyName, const QDBusVariant &)
363 364 365 366 367 368 369
{
    if (propertyName == PoweredPropertyName) {
        emit q->gpsFlightModeChanged();
    }
}

void LocationSettingsPrivate::findGpsTech()
370 371 372 373 374 375
{
    NetworkTechnology *newGpsTech = m_connMan->getTechnology(QStringLiteral("gps"));
    if (newGpsTech == m_gpsTech) {
        return; // no change.
    }
    if (m_gpsTech) {
376
        disconnect(m_gpsTech, 0, q, 0);
377 378 379 380
    }
    m_gpsTech = newGpsTech;
    if (m_gpsTech) {
        connect(m_gpsTech, &NetworkTechnology::poweredChanged,
381
                q, &LocationSettings::gpsFlightModeChanged);
382
    }
383 384 385
    emit q->gpsFlightModeChanged();
}

386
static void checkOnlineStates(LocationSettings::OnlineAGpsState mode, bool *allOn, bool *allOff)
387
{
388 389
    if (mode == LocationSettings::OnlineAGpsEnabled) {
        *allOff = false;
390
    } else {
391
        *allOn = false;
392 393 394
    }
}

395 396
LocationSettings::LocationMode
LocationSettingsPrivate::calculateLocationMode() const
397
{
398 399
    bool allNetworkOn = true;
    bool allNetworkOff = true;
400

401
    bool networkLocationExists = false;
402
    bool allOfflineEnabled = true;
403 404 405 406 407 408 409 410 411 412 413 414 415

    for (const QString &name : m_providers.keys()) {
        bool valid = true;
        LocationSettings::OnlineAGpsState state = onlineState(name, &valid);
        if (valid) {
            networkLocationExists = true;
            checkOnlineStates(state, &allNetworkOn, &allNetworkOff);
        }

        LocationProvider provider = m_providers.value(name);
        if (provider.offlineCapable && !provider.offlineEnabled) {
            allOfflineEnabled = false;
        }
416
    }
417

418 419 420 421 422 423 424
    if (m_gpsEnabled && allNetworkOn && networkLocationExists && allOfflineEnabled) {
        return LocationSettings::HighAccuracyMode;
    } else if (!m_gpsEnabled && allNetworkOn && allOfflineEnabled) {
        return LocationSettings::BatterySavingMode;
    } else if (m_gpsEnabled && allNetworkOff && allOfflineEnabled) {
        return LocationSettings::DeviceOnlyMode;
    }
425

426 427
    return LocationSettings::CustomMode;
}
428

429 430 431 432 433 434 435 436 437 438 439 440 441 442
LocationSettings::LocationSettings(QObject *parent)
    : QObject(parent)
    , d_ptr(new LocationSettingsPrivate(LocationSettings::AsynchronousMode, this))
{
}

LocationSettings::LocationSettings(LocationSettings::Mode mode, QObject *parent)
    : QObject(parent)
    , d_ptr(new LocationSettingsPrivate(mode, this))
{
}

LocationSettings::~LocationSettings()
{
443 444 445 446
}

bool LocationSettings::locationEnabled() const
{
447 448
    Q_D(const LocationSettings);
    return d->m_locationEnabled;
449 450 451 452
}

void LocationSettings::setLocationEnabled(bool enabled)
{
453 454 455 456
    Q_D(LocationSettings);
    if (enabled != d->m_locationEnabled) {
        d->m_locationEnabled = enabled;
        d->writeSettings();
457 458 459 460 461 462
        emit locationEnabledChanged();
    }
}

bool LocationSettings::gpsEnabled() const
{
463 464
    Q_D(const LocationSettings);
    return d->m_gpsEnabled;
465 466 467 468
}

void LocationSettings::setGpsEnabled(bool enabled)
{
469 470 471 472
    Q_D(LocationSettings);
    if (enabled != d->m_gpsEnabled) {
        d->m_gpsEnabled = enabled;
        d->writeSettings();
473 474 475 476 477 478
        emit gpsEnabledChanged();
    }
}

bool LocationSettings::gpsFlightMode() const
{
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
    Q_D(const LocationSettings);
    if (d->m_gpsTechInterface) {
        QDBusReply<QVariantMap> reply = d->m_gpsTechInterface->call("GetProperties");
        if (reply.error().isValid()) {
            qWarning() << reply.error().message();
        } else {
            QVariantMap props = reply.value();
            if (props.contains(PoweredPropertyName)) {
                return !props.value(PoweredPropertyName).toBool();
            } else {
                qWarning() << "Powered property not returned for GPS technology!";
            }
        }
        return false;
    }
    return d->m_gpsTech == Q_NULLPTR ? false : !(d->m_gpsTech->powered());
495 496 497 498
}

void LocationSettings::setGpsFlightMode(bool flightMode)
{
499 500 501 502 503 504 505 506 507 508
    Q_D(LocationSettings);
    if (d->m_gpsTechInterface) {
        QDBusReply<void> reply = d->m_gpsTechInterface->call("SetProperty",
                                                             PoweredPropertyName,
                                                             QVariant::fromValue<QDBusVariant>(QDBusVariant(QVariant::fromValue<bool>(!flightMode))));
        if (reply.error().isValid()) {
            qWarning() << reply.error().message();
        }
    } else if (d->m_gpsTech && d->m_gpsTech->powered() == flightMode) {
        d->m_gpsTech->setPowered(!flightMode);
509 510 511 512 513 514 515 516
    }
}

bool LocationSettings::gpsAvailable() const
{
    return QFile::exists(QStringLiteral("/usr/libexec/geoclue-hybris"));
}

517 518 519 520 521
QStringList LocationSettings::locationProviders() const
{
    Q_D(const LocationSettings);
    return d->m_providers.keys();
}
522

523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
LocationProvider LocationSettings::providerInfo(const QString &name) const
{
    Q_D(const LocationSettings);
    return d->m_providers.value(name.toLower());
}

bool LocationSettings::updateLocationProvider(const QString &name, const LocationProvider &providerState)
{
    Q_D(LocationSettings);
    if (!d->updateProvider(name.toLower(), providerState)) {
        return false;
    }

    d->writeSettings();
    return true;
}

/*Mozilla Location services*/
541 542
bool LocationSettings::mlsEnabled() const
{
543
    Q_D(const LocationSettings);
544
    return d->m_providers.value(MlsName).offlineEnabled;
545 546 547 548
}

void LocationSettings::setMlsEnabled(bool enabled)
{
549 550 551 552
    if (mlsAvailable() && enabled != mlsEnabled()) {
        LocationProvider provider = providerInfo(MlsName);
        provider.offlineEnabled = enabled;
        updateLocationProvider(MlsName, provider);
553 554 555 556 557
    }
}

LocationSettings::OnlineAGpsState LocationSettings::mlsOnlineState() const
{
558
    Q_D(const LocationSettings);
559
    return d->onlineState(MlsName);
560 561 562 563
}

void LocationSettings::setMlsOnlineState(LocationSettings::OnlineAGpsState state)
{
564
    Q_D(LocationSettings);
565
    d->updateOnlineAgpsState(MlsName, state);
566 567 568 569
}

bool LocationSettings::mlsAvailable() const
{
570
    Q_D(const LocationSettings);
571
    return d->m_providers.contains(MlsName);
572 573
}

574 575
/*Yandex  services*/
LocationSettings::OnlineAGpsState LocationSettings::yandexOnlineState() const
576 577
{
    Q_D(const LocationSettings);
578
    return d->onlineState(YandexName);
579 580
}

581
void LocationSettings::setYandexOnlineState(LocationSettings::OnlineAGpsState state)
582 583
{
    Q_D(LocationSettings);
584
    d->updateOnlineAgpsState(YandexName, state);
585 586
}

587
bool LocationSettings::yandexAvailable() const
588 589
{
    Q_D(const LocationSettings);
590
    return d->m_providers.contains(YandexName);
591 592 593
}

/*HERE*/
594 595
LocationSettings::OnlineAGpsState LocationSettings::hereState() const
{
596
    Q_D(const LocationSettings);
597
    return d->onlineState(HereName);
598 599 600 601
}

void LocationSettings::setHereState(LocationSettings::OnlineAGpsState state)
{
602
    Q_D(LocationSettings);
603
    d->updateOnlineAgpsState(HereName, state);
604 605 606 607
}

bool LocationSettings::hereAvailable() const
{
608
    Q_D(const LocationSettings);
609
    return d->m_providers.contains(HereName);
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
}

LocationSettings::LocationMode LocationSettings::locationMode() const
{
    Q_D(const LocationSettings);
    return d->m_locationMode;
}

void LocationSettings::setLocationMode(LocationMode locationMode)
{
    Q_D(LocationSettings);

    LocationSettings::LocationMode oldLocationMode = this->locationMode();
    if (oldLocationMode == locationMode) {
        return;
    }

    d->m_settingMultipleSettings = true;
    d->m_locationMode = locationMode;
629 630 631

    if (locationMode != CustomMode) {
        setGpsEnabled(locationMode == HighAccuracyMode || locationMode == DeviceOnlyMode);
632
        bool enableOnline = (locationMode != DeviceOnlyMode);
633

634 635 636 637 638
        for (const QString &name : d->m_providers.keys()) {
            LocationProvider provider = d->m_providers.value(name);
            provider.offlineEnabled = true;
            provider.onlineEnabled = enableOnline;
            d->updateProvider(name, provider);
639
        }
640 641 642
    } else if (d->m_pendingAgreements.isEmpty()) {
        d->m_pendingAgreements.clear();
        emit pendingAgreementsChanged();
643 644 645 646 647
    }

    d->m_settingMultipleSettings = false;
    d->writeSettings();
    emit locationModeChanged();
648 649 650 651 652 653
}

QStringList LocationSettings::pendingAgreements() const
{
    Q_D(const LocationSettings);
    return d->m_pendingAgreements;
654 655
}

656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
LocationSettings::DataSources LocationSettings::allowedDataSources() const
{
    Q_D(const LocationSettings);
    return d->m_allowedDataSources;
}

void LocationSettings::setAllowedDataSources(LocationSettings::DataSources dataSources)
{
    Q_D(LocationSettings);
    if (dataSources == d->m_allowedDataSources)
        return;

    d->m_allowedDataSources = dataSources;
    d->writeSettings();
    emit allowedDataSourcesChanged();
}

673
void LocationSettingsPrivate::readSettings()
674
{
675 676 677 678 679
    bool locationEnabled = false;
    bool customMode = false;
    bool gpsEnabled = false;

    // MDM allowed data source key values
680
    LocationSettings::DataSources allowedDataSources = static_cast<LocationSettings::DataSources>(std::numeric_limits<quint32>::max());
681 682 683 684 685 686 687

    // Read values from the settings file.  Scope ensures process mutex locking.
    {
        IniFile ini(LocationSettingsFile);
        if (!ini.isValid()) {
            qWarning() << "Unable to read location configuration settings!";
            return;
688
        }
689 690

        // read the deprecated keys first for backward compatibility
691 692 693
        bool oldMlsEnabled = false;
        bool oldHereEnabled = false;
        bool oldHereAgreementAccepted = false;
694 695 696 697 698 699 700 701
        ini.readBool(LocationSettingsSection, LocationSettingsDeprecatedCellIdPositioningEnabledKey, &oldMlsEnabled);
        ini.readBool(LocationSettingsSection, LocationSettingsDeprecatedHereEnabledKey, &oldHereEnabled);
        ini.readBool(LocationSettingsSection, LocationSettingsDeprecatedHereAgreementAcceptedKey, &oldHereAgreementAccepted);

        // then read the current keys
        ini.readBool(LocationSettingsSection, LocationSettingsEnabledKey, &locationEnabled);
        ini.readBool(LocationSettingsSection, LocationSettingsCustomModeKey, &customMode);
        ini.readBool(LocationSettingsSection, LocationSettingsGpsEnabledKey, &gpsEnabled);
702 703 704 705 706 707 708 709 710 711 712 713 714 715

        for (const QString &name : m_providers.keys()) {
            LocationProvider provider;
            if (name == MlsName) {
                provider.offlineEnabled = oldMlsEnabled;
            } else if (name == HereName) {
                provider.onlineEnabled = oldHereEnabled;
                provider.agreementAccepted = oldHereAgreementAccepted;
            }
            ini.readBool(LocationSettingsSection, ProviderOfflineEnabledPattern.arg(name), &provider.offlineEnabled);
            ini.readBool(LocationSettingsSection, ProviderOnlineEnabledPattern.arg(name), &provider.onlineEnabled);
            ini.readBool(LocationSettingsSection, ProviderAgreementAcceptedPattern.arg(name), &provider.agreementAccepted);
            updateProvider(name, provider);
        }
716 717 718 719 720 721 722 723 724 725 726

        // read the MDM allowed allowed data source keys
        bool dataSourceAllowed = true;
        for (QMap<LocationSettings::DataSource, QString>::const_iterator
                it = AllowedDataSourcesKeys.constBegin();
                it != AllowedDataSourcesKeys.constEnd();
                it++) {
            ini.readBool(LocationSettingsSection, it.value(), &dataSourceAllowed, true);
            if (!dataSourceAllowed) {
                allowedDataSources &= ~it.key();
            }
727 728 729 730 731
        }
    }

    if (m_locationEnabled != locationEnabled) {
        m_locationEnabled = locationEnabled;
732
        emit q->locationEnabledChanged();
733 734
    }

735 736 737 738 739
    if (m_allowedDataSources != allowedDataSources) {
        m_allowedDataSources = allowedDataSources;
        emit q->allowedDataSourcesChanged();
    }

740 741
    if (m_gpsEnabled != gpsEnabled) {
        m_gpsEnabled = gpsEnabled;
742
        emit q->gpsEnabledChanged();
743 744
    }

745 746 747 748
    if ((m_locationMode == LocationSettings::CustomMode) != customMode) {
        if (customMode) {
            m_locationMode = LocationSettings::CustomMode;
            emit q->locationModeChanged();
749 750 751 752
            if (!m_pendingAgreements.isEmpty()) {
                m_pendingAgreements.clear();
                emit q->pendingAgreementsChanged();
            }
753 754 755 756 757
        } else {
            m_locationMode = calculateLocationMode();
            emit q->locationModeChanged();
        }
    }
758 759
}

760
void LocationSettingsPrivate::writeSettings()
761
{
762 763 764 765
    if (m_settingMultipleSettings) {
        return; // wait to write settings until all settings have been set.
    }

766 767 768 769 770 771
    // new file would be owned by creating process uid. we cannot allow this since the access is handled with group
    if (!QFile(LocationSettingsFile).exists()) {
        qWarning() << "Location settings configuration file does not exist. Refusing to create new.";
        return;
    }

772 773 774 775 776 777 778
    // write the values to the conf file
    {
        IniFile ini(LocationSettingsFile);

        ini.writeBool(LocationSettingsSection, LocationSettingsEnabledKey, m_locationEnabled);
        ini.writeBool(LocationSettingsSection, LocationSettingsCustomModeKey, m_locationMode == LocationSettings::CustomMode);
        ini.writeBool(LocationSettingsSection, LocationSettingsGpsEnabledKey, m_gpsEnabled);
779 780 781 782 783 784 785 786 787 788 789 790 791

        for (const QString &name : m_providers.keys()) {
            LocationProvider provider = m_providers.value(name);
            if (provider.offlineCapable) {
                ini.writeBool(LocationSettingsSection, ProviderOfflineEnabledPattern.arg(name), provider.offlineEnabled);
            }
            if (provider.onlineCapable) {
                ini.writeBool(LocationSettingsSection, ProviderOnlineEnabledPattern.arg(name), provider.onlineEnabled);
            }
            if (provider.hasAgreement) {
                ini.writeBool(LocationSettingsSection, ProviderAgreementAcceptedPattern.arg(name), provider.agreementAccepted);
            }
        }
792 793 794 795 796 797 798 799

        // write the MDM allowed allowed data source keys
        for (QMap<LocationSettings::DataSource, QString>::const_iterator
                it = AllowedDataSourcesKeys.constBegin();
                it != AllowedDataSourcesKeys.constEnd();
                it++) {
            ini.writeBool(LocationSettingsSection, it.value(), m_allowedDataSources & it.key());
        }
800 801
    }
}