/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Copyright (C) 2010 netlabs.org. OS/2 parts.
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qsettings.h"

#ifndef QT_NO_SETTINGS

#include "qsettings_p.h"
#include "qvector.h"
#include "qmap.h"
#include "qdebug.h"

/*******************************************************************************
** Define some Win32 stuff to use Open32 Reg* functions from REGISTRY.DLL
*/

extern "C" {

typedef wchar_t WCHAR;
typedef WCHAR TCHAR;

/* These definitions come from os2wdef.h in the OS/2 Toolkit */

#define APIENTRY    _System

typedef char                CHAR ,   *PCHAR ,  *LPCHAR;
typedef int                 INT,     *PINT,    *LPINT;
typedef long                LONG,    *PLONG,   *LPLONG;
typedef unsigned char       UCHAR ,  *PUCHAR,  *LPUCHAR;
typedef unsigned long       ULONG ,  *PULONG , *LPULONG;
typedef void                VOID,    *PVOID,   *LPVOID;

typedef UCHAR               BYTE,    *PBYTE,   *LPBYTE;
typedef ULONG               DWORD,   *PDWORD,  *LPDWORD;

typedef INT                 BOOL,    *PBOOL,   *LPBOOL;

typedef WCHAR               *LPWSTR, *PWSTR;
typedef const WCHAR         *LPCWSTR, *PCWSTR;

typedef CHAR                *LPSTR,  *PSTR;
typedef const CHAR          *LPCSTR, *PCSTR;

#define CONST       const

/* These definitions come from os2win.h in the OS/2 Toolkit */

typedef DWORD       ACCESS_MASK;
typedef ACCESS_MASK REGSAM;

typedef DWORD       HKEY, *PHKEY;

typedef struct _tagSECURITY_ATTRIBUTES {
    DWORD                            nLength;
    LPVOID                           lpSecurityDescriptor;
    BOOL                             bInheritHandle;
} SECURITY_ATTRIBUTES, *PSECURITY_ATTRIBUTES, *LPSECURITY_ATTRIBUTES;

typedef struct _tagFILETIME {
    DWORD dwLowDateTime;
    DWORD dwHighDateTime;
} FILETIME, *PFILETIME, *LPFILETIME;

#define HKEY_LOCAL_MACHINE      0xFFFFFFEFL
#define HKEY_CURRENT_USER       0xFFFFFFEEL
#define HKEY_USERS              0xFFFFFFEDL
#define HKEY_CLASSES_ROOT       0xFFFFFFECL

//#define DELETE                       0x00010000
#define READ_CONTROL                 0x00020000
//#define WRITE_DAC                    0x00040000
//#define WRITE_OWNER                  0x00080000
//#define SYNCHRONIZE                  0x00100000

//#define SPECIFIC_RIGHTS_ALL          0x0000FFFF
//#define STANDARD_RIGHTS_READ         (READ_CONTROL)
//#define STANDARD_RIGHTS_WRITE        (READ_CONTROL)
//#define STANDARD_RIGHTS_EXECUTE      (READ_CONTROL)
//#define STANDARD_RIGHTS_REQUIRED     0x000F0000
#define STANDARD_RIGHTS_ALL          0x001F0000

#define KEY_QUERY_VALUE         0x0001
#define KEY_SET_VALUE           0x0002
#define KEY_CREATE_SUB_KEY      0x0004
#define KEY_ENUMERATE_SUB_KEYS  0x0008
#define KEY_NOTIFY              0x0010
#define KEY_CREATE_LINK         0x0020

#define REG_OPTION_NON_VOLATILE 0x00000000L
#define REG_OPTION_VOLATILE     0x00000001L
#define REG_CREATED_NEW_KEY     0x00000001L
#define REG_OPENED_EXISTING_KEY 0x00000002L

#define KEY_READ         READ_CONTROL | KEY_QUERY_VALUE |\
                           KEY_ENUMERATE_SUB_KEYS | KEY_NOTIFY

#define KEY_WRITE        READ_CONTROL | KEY_SET_VALUE | KEY_CREATE_SUB_KEY

#define KEY_EXECUTE      KEY_READ

#define KEY_ALL_ACCESS   STANDARD_RIGHTS_ALL | KEY_QUERY_VALUE |\
                           KEY_SET_VALUE | KEY_CREATE_SUB_KEY |\
                           KEY_ENUMERATE_SUB_KEYS | KEY_NOTIFY |\
                           KEY_CREATE_LINK

#define REG_NONE                  0
#define REG_SZ                    1
#define REG_EXPAND_SZ             2
#define REG_BINARY                3
#define REG_DWORD                 4
#define REG_DWORD_LITTLE_ENDIAN   4
#define REG_DWORD_BIG_ENDIAN      5
#define REG_LINK                  6
#define REG_MULTI_SZ              7
#define REG_RESOURCE_LIST         8

/* These definitions come from winreg.h from MSVC 6.0 */
LONG APIENTRY RegCloseKey( HKEY hKey );
LONG APIENTRY RegCreateKeyExA( HKEY hKey, LPCSTR lpSubKey, DWORD Reserved, LPSTR lpClass, DWORD dwOptions, REGSAM samDesired, LPSECURITY_ATTRIBUTES lpSecurityAttributes, PHKEY phkResult, LPDWORD lpdwDisposition );
LONG APIENTRY RegCreateKeyExW( HKEY hKey,LPCWSTR lpSubKey, DWORD Reserved, LPWSTR lpClass, DWORD dwOptions, REGSAM samDesired, LPSECURITY_ATTRIBUTES lpSecurityAttributes, PHKEY phkResult, LPDWORD lpdwDisposition );
LONG APIENTRY RegDeleteKeyA( HKEY hKey, LPCSTR lpSubKey);
LONG APIENTRY RegDeleteKeyW( HKEY hKey, LPCWSTR lpSubKey);
LONG APIENTRY RegDeleteValueA( HKEY hKey, LPCSTR lpValueName );
LONG APIENTRY RegDeleteValueW( HKEY hKey, LPCWSTR lpValueName );
LONG APIENTRY RegEnumKeyExA( HKEY hKey, DWORD dwIndex, LPSTR lpName, LPDWORD lpcbName, LPDWORD lpReserved, LPSTR lpClass, LPDWORD lpcbClass, PFILETIME lpftLastWriteTime );
LONG APIENTRY RegEnumKeyExW( HKEY hKey, DWORD dwIndex, LPWSTR lpName, LPDWORD lpcbName, LPDWORD lpReserved, LPWSTR lpClass, LPDWORD lpcbClass, PFILETIME lpftLastWriteTime);
LONG APIENTRY RegEnumValueA( HKEY hKey, DWORD dwIndex, LPSTR lpValueName, LPDWORD lpcbValueName, LPDWORD lpReserved, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData );
LONG APIENTRY RegEnumValueW( HKEY hKey, DWORD dwIndex, LPWSTR lpValueName, LPDWORD lpcbValueName, LPDWORD lpReserved, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData );
LONG APIENTRY RegFlushKey( HKEY hKey );
LONG APIENTRY RegOpenKeyExA( HKEY hKey, LPCSTR lpSubKey, DWORD ulOptions, REGSAM samDesired, PHKEY phkResult );
LONG APIENTRY RegOpenKeyExW( HKEY hKey, LPCWSTR lpSubKey, DWORD ulOptions, REGSAM samDesired, PHKEY phkResult );
LONG APIENTRY RegQueryInfoKeyA( HKEY hKey, LPSTR lpClass, LPDWORD lpcbClass, LPDWORD lpReserved, LPDWORD lpcSubKeys, LPDWORD lpcbMaxSubKeyLen, LPDWORD lpcbMaxClassLen, LPDWORD lpcValues, LPDWORD lpcbMaxValueNameLen, LPDWORD lpcbMaxValueLen, LPDWORD lpcbSecurityDescriptor, PFILETIME lpftLastWriteTime );
LONG APIENTRY RegQueryInfoKeyW( HKEY hKey, LPWSTR lpClass, LPDWORD lpcbClass, LPDWORD lpReserved, LPDWORD lpcSubKeys, LPDWORD lpcbMaxSubKeyLen, LPDWORD lpcbMaxClassLen, LPDWORD lpcValues, LPDWORD lpcbMaxValueNameLen, LPDWORD lpcbMaxValueLen, LPDWORD lpcbSecurityDescriptor, PFILETIME lpftLastWriteTime );
LONG APIENTRY RegQueryValueExA( HKEY hKey, LPCSTR lpValueName, LPDWORD lpReserved, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData );
LONG APIENTRY RegQueryValueExW( HKEY hKey, LPCWSTR lpValueName, LPDWORD lpReserved, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData );
LONG APIENTRY RegSetValueExA( HKEY hKey, LPCSTR lpValueName, DWORD Reserved, DWORD dwType, CONST BYTE* lpData, DWORD cbData );
LONG APIENTRY RegSetValueExW( HKEY hKey, LPCWSTR lpValueName, DWORD Reserved, DWORD dwType, CONST BYTE* lpData, DWORD cbData );

/* These definitions come from winerror.h from MSVC 6.0 */
#define ERROR_SUCCESS                    0L
#define ERROR_FILE_NOT_FOUND             2L
#define ERROR_ACCESS_DENIED              5L
#define ERROR_NO_MORE_ITEMS              259L

} /* extern "C" */

/* End of Win32 definitions */

QT_BEGIN_NAMESPACE

/*  Keys are stored in QStrings. If the variable name starts with 'u', this is a "user"
    key, ie. "foo/bar/alpha/beta". If the variable name starts with 'r', this is a "registry"
    key, ie. "\foo\bar\alpha\beta". */

/*******************************************************************************
** Some convenience functions
*/

/*
  We don't use KEY_ALL_ACCESS because it gives more rights than what we
  need. See task 199061.
 */
static const REGSAM registryPermissions = KEY_READ | KEY_WRITE;

static QString keyPath(const QString &rKey)
{
    int idx = rKey.lastIndexOf(QLatin1Char('\\'));
    if (idx == -1)
        return QString();
    return rKey.left(idx + 1);
}

static QString keyName(const QString &rKey)
{
    int idx = rKey.lastIndexOf(QLatin1Char('\\'));

    QString res;
    if (idx == -1)
        res = rKey;
    else
        res = rKey.mid(idx + 1);

    if (res == QLatin1String("Default") || res == QLatin1String("."))
        res = QLatin1String("");

    return res;
}

static QString escapedKey(QString uKey)
{
    QChar *data = uKey.data();
    int l = uKey.length();
    for (int i = 0; i < l; ++i) {
        ushort &ucs = data[i].unicode();
        if (ucs == '\\')
            ucs = '/';
        else if (ucs == '/')
            ucs = '\\';
    }
    return uKey;
}

static QString unescapedKey(QString rKey)
{
    return escapedKey(rKey);
}

typedef QMap<QString, QString> NameSet;

static void mergeKeySets(NameSet *dest, const NameSet &src)
{
    NameSet::const_iterator it = src.constBegin();
    for (; it != src.constEnd(); ++it)
        dest->insert(unescapedKey(it.key()), QString());
}

static void mergeKeySets(NameSet *dest, const QStringList &src)
{
    QStringList::const_iterator it = src.constBegin();
    for (; it != src.constEnd(); ++it)
        dest->insert(unescapedKey(*it), QString());
}

/*******************************************************************************
** Wrappers for the insane windows registry API
*/

static QByteArray errorCodeToString(DWORD errorCode)
{
    QByteArray result;
    switch (errorCode) {
        case ERROR_FILE_NOT_FOUND:
            result = "ERROR_FILE_NOT_FOUND"; break;
        case ERROR_ACCESS_DENIED:
            result = "ERROR_ACCESS_DENIED"; break;
        case ERROR_NO_MORE_ITEMS:
            result = "ERROR_NO_MORE_ITEMS"; break;
    default:
        result = QString().sprintf("Error %lu", errorCode).toLatin1();
            break;
    }

    return result;
}

// Open a key with the specified perms
static HKEY openKey(HKEY parentHandle, REGSAM perms, const QString &rSubKey)
{
    HKEY resultHandle = 0;

    LONG res = RegOpenKeyExA(parentHandle, rSubKey.toLocal8Bit(),
                             0, perms, &resultHandle);
    if (res == ERROR_SUCCESS)
        return resultHandle;

    return 0;
}

// Open a key with the specified perms, create it if it does not exist
static HKEY createOrOpenKey(HKEY parentHandle, REGSAM perms, const QString &rSubKey)
{
    // try to open it
    HKEY resultHandle = openKey(parentHandle, perms, rSubKey);
    if (resultHandle != 0)
        return resultHandle;

    // try to create it
    LONG res = RegCreateKeyExA(parentHandle, rSubKey.toLocal8Bit(), 0, 0,
                               REG_OPTION_NON_VOLATILE, perms, 0, &resultHandle, 0);
    if (res == ERROR_SUCCESS)
        return resultHandle;

    qWarning("QSettings: RegCreateKeyEx(%s) failed with %s",
             rSubKey.toUtf8().data(), errorCodeToString(res).data());

    return 0;
}

// Open or create a key in read-write mode if possible, otherwise read-only
static HKEY createOrOpenKey(HKEY parentHandle, const QString &rSubKey, bool *readOnly)
{
    // try to open or create it read/write
    HKEY resultHandle = createOrOpenKey(parentHandle, registryPermissions, rSubKey);
    if (resultHandle != 0) {
        if (readOnly != 0)
            *readOnly = false;
        return resultHandle;
    }

    // try to open or create it read/only
    resultHandle = createOrOpenKey(parentHandle, KEY_READ, rSubKey);
    if (resultHandle != 0) {
        if (readOnly != 0)
            *readOnly = true;
        return resultHandle;
    }
    return 0;
}

static QStringList childKeysOrGroups(HKEY parentHandle, QSettingsPrivate::ChildSpec spec)
{
    QStringList result;
    DWORD numKeys;
    DWORD maxKeySize;
    DWORD numSubgroups;
    DWORD maxSubgroupSize;

    // Find the number of keys and subgroups, as well as the max of their lengths.
    LONG res = RegQueryInfoKeyA(parentHandle, 0, 0, 0, &numSubgroups, &maxSubgroupSize, 0,
                                &numKeys, &maxKeySize, 0, 0, 0);
    if (res != ERROR_SUCCESS) {
        qWarning("QSettings: RegQueryInfoKey() failed with %s", errorCodeToString(res).data());
        return result;
    }

    ++maxSubgroupSize;
    ++maxKeySize;

    int n;
    int m;
    if (spec == QSettingsPrivate::ChildKeys) {
        n = numKeys;
        m = maxKeySize;
    } else {
        n = numSubgroups;
        m = maxSubgroupSize;
    }

    /* The size does not include the terminating null character. */
    ++m;

    // Get the list
    QByteArray buff(m, 0);
    for (int i = 0; i < n; ++i) {
        QString item;
        DWORD l = buff.size();
        if (spec == QSettingsPrivate::ChildKeys)
            res = RegEnumValueA(parentHandle, i, buff.data(), &l, 0, 0, 0, 0);
        else
            res = RegEnumKeyExA(parentHandle, i, buff.data(), &l, 0, 0, 0, 0);
        if (res == ERROR_SUCCESS)
            item = QString::fromLocal8Bit(buff.data(), l);

        if (res != ERROR_SUCCESS) {
            qWarning("QSettings: RegEnumValue() failed with %s", errorCodeToString(res).data());
            continue;
        }
        if (item.isEmpty())
            item = QLatin1String(".");
        result.append(item);
    }
    return result;
}

static void allKeys(HKEY parentHandle, const QString &rSubKey, NameSet *result)
{
    HKEY handle = openKey(parentHandle, KEY_READ, rSubKey);
    if (handle == 0)
        return;

    QStringList childKeys = childKeysOrGroups(handle, QSettingsPrivate::ChildKeys);
    QStringList childGroups = childKeysOrGroups(handle, QSettingsPrivate::ChildGroups);
    RegCloseKey(handle);

    for (int i = 0; i < childKeys.size(); ++i) {
        QString s = rSubKey;
        if (!s.isEmpty())
            s += QLatin1Char('\\');
        s += childKeys.at(i);
        result->insert(s, QString());
    }

    for (int i = 0; i < childGroups.size(); ++i) {
        QString s = rSubKey;
        if (!s.isEmpty())
            s += QLatin1Char('\\');
        s += childGroups.at(i);
        allKeys(parentHandle, s, result);
    }
}

static void deleteChildGroups(HKEY parentHandle)
{
    QStringList childGroups = childKeysOrGroups(parentHandle, QSettingsPrivate::ChildGroups);

    for (int i = 0; i < childGroups.size(); ++i) {
        QString group = childGroups.at(i);

        // delete subgroups in group
        HKEY childGroupHandle = openKey(parentHandle, registryPermissions, group);
        if (childGroupHandle == 0)
            continue;
        deleteChildGroups(childGroupHandle);
        RegCloseKey(childGroupHandle);

        // delete group itself
        LONG res = RegDeleteKeyA(parentHandle, group.toLocal8Bit());
        if (res != ERROR_SUCCESS) {
            qWarning("QSettings: RegDeleteKey(%s): %s", group.toUtf8().data(),
                     errorCodeToString(res).data());
            return;
        }
    }
}

/*******************************************************************************
** class RegistryKey
*/

class RegistryKey
{
public:
    RegistryKey(HKEY parent_handle = 0, const QString &key = QString(), bool read_only = true);
    QString key() const;
    HKEY handle() const;
    HKEY parentHandle() const;
    bool readOnly() const;
    void close();
private:
    HKEY m_parent_handle;
    mutable HKEY m_handle;
    QString m_key;
    mutable bool m_read_only;
};

RegistryKey::RegistryKey(HKEY parent_handle, const QString &key, bool read_only)
{
    m_parent_handle = parent_handle;
    m_handle = 0;
    m_read_only = read_only;
    m_key = key;
}

QString RegistryKey::key() const
{
    return m_key;
}

HKEY RegistryKey::handle() const
{
    if (m_handle != 0)
        return m_handle;

    if (m_read_only)
        m_handle = openKey(m_parent_handle, KEY_READ, m_key);
    else
        m_handle = createOrOpenKey(m_parent_handle, m_key, &m_read_only);

    return m_handle;
}

HKEY RegistryKey::parentHandle() const
{
    return m_parent_handle;
}

bool RegistryKey::readOnly() const
{
    return m_read_only;
}

void RegistryKey::close()
{
    if (m_handle != 0)
        RegCloseKey(m_handle);
    m_handle = 0;
}

typedef QVector<RegistryKey> RegistryKeyList;

/*******************************************************************************
** class QOS2SettingsPrivate
*/

class QOS2SettingsPrivate : public QSettingsPrivate
{
public:
    QOS2SettingsPrivate(QSettings::Scope scope, const QString &organization,
                        const QString &application);
    QOS2SettingsPrivate(QString rKey);
    ~QOS2SettingsPrivate();

    void remove(const QString &uKey);
    void set(const QString &uKey, const QVariant &value);
    bool get(const QString &uKey, QVariant *value) const;
    QStringList children(const QString &uKey, ChildSpec spec) const;
    void clear();
    void sync();
    void flush();
    bool isWritable() const;
    HKEY writeHandle() const;
    bool readKey(HKEY parentHandle, const QString &rSubKey, QVariant *value) const;
    QString fileName() const;

private:
    RegistryKeyList regList; // list of registry locations to search for keys
    bool deleteWriteHandleOnExit;
};

QOS2SettingsPrivate::QOS2SettingsPrivate(QSettings::Scope scope, const QString &organization,
                                         const QString &application)
    : QSettingsPrivate(QSettings::NativeFormat, scope, organization, application)
{
    deleteWriteHandleOnExit = false;

    if (!organization.isEmpty()) {
        QString prefix = QLatin1String("Software\\") + organization;
        QString orgPrefix = prefix + QLatin1String("\\OrganizationDefaults");
        QString appPrefix = prefix + QLatin1Char('\\') + application;

        if (scope == QSettings::UserScope) {
            if (!application.isEmpty())
                regList.append(RegistryKey(HKEY_CURRENT_USER, appPrefix, !regList.isEmpty()));

            regList.append(RegistryKey(HKEY_CURRENT_USER, orgPrefix, !regList.isEmpty()));
        }

        if (!application.isEmpty())
            regList.append(RegistryKey(HKEY_LOCAL_MACHINE, appPrefix, !regList.isEmpty()));

        regList.append(RegistryKey(HKEY_LOCAL_MACHINE, orgPrefix, !regList.isEmpty()));
    }

    if (regList.isEmpty())
        setStatus(QSettings::AccessError);
}

QOS2SettingsPrivate::QOS2SettingsPrivate(QString rPath)
    : QSettingsPrivate(QSettings::NativeFormat)
{
    deleteWriteHandleOnExit = false;

    if (rPath.startsWith(QLatin1String("\\")))
        rPath = rPath.mid(1);

    if (rPath.startsWith(QLatin1String("HKEY_CURRENT_USER\\")))
        regList.append(RegistryKey(HKEY_CURRENT_USER, rPath.mid(18), false));
    else if (rPath == QLatin1String("HKEY_CURRENT_USER"))
        regList.append(RegistryKey(HKEY_CURRENT_USER, QString(), false));
    else if (rPath.startsWith(QLatin1String("HKEY_LOCAL_MACHINE\\")))
        regList.append(RegistryKey(HKEY_LOCAL_MACHINE, rPath.mid(19), false));
    else if (rPath == QLatin1String("HKEY_LOCAL_MACHINE"))
        regList.append(RegistryKey(HKEY_LOCAL_MACHINE, QString(), false));
    else if (rPath.startsWith(QLatin1String("HKEY_CLASSES_ROOT\\")))
        regList.append(RegistryKey(HKEY_CLASSES_ROOT, rPath.mid(18), false));
    else if (rPath == QLatin1String("HKEY_CLASSES_ROOT"))
        regList.append(RegistryKey(HKEY_CLASSES_ROOT, QString(), false));
    else if (rPath.startsWith(QLatin1String("HKEY_USERS\\")))
        regList.append(RegistryKey(HKEY_USERS, rPath.mid(11), false));
    else if (rPath == QLatin1String(QLatin1String("HKEY_USERS")))
        regList.append(RegistryKey(HKEY_USERS, QString(), false));
    else
        regList.append(RegistryKey(HKEY_LOCAL_MACHINE, rPath, false));
}

bool QOS2SettingsPrivate::readKey(HKEY parentHandle, const QString &rSubKey, QVariant *value) const
{
    QString rSubkeyName = keyName(rSubKey);
    QString rSubkeyPath = keyPath(rSubKey);

    // open a handle on the subkey
    HKEY handle = openKey(parentHandle, KEY_READ, rSubkeyPath);
    if (handle == 0)
        return false;

    // get the size and type of the value
    DWORD dataType;
    DWORD dataSize;
    LONG res = RegQueryValueExA(handle, rSubkeyName.toLocal8Bit(), 0, &dataType, 0, &dataSize);
    if (res != ERROR_SUCCESS) {
        RegCloseKey(handle);
        return false;
    }

    // get the value
    QByteArray data(dataSize, 0);
    res = RegQueryValueExA(handle, rSubkeyName.toLocal8Bit(), 0, 0,
                           reinterpret_cast<unsigned char*>(data.data()), &dataSize);
    if (res != ERROR_SUCCESS) {
        RegCloseKey(handle);
        return false;
    }

    // note that when getting and setting the key contents on non-Unicode systems
    // we use the Latin1 encoding instead of Local8Bit because stringToVariant()
    // and variantToString() use Latin1 to convert between QString and QByteArray.
    // Since it's not guaranteed that all characters from Latin1 may be represented
    // in Local8Bit (and vice versa), doing Latin1 -> QString -> Local8Bit ->
    // QString -> Latin1 may distort data (in particular, replace some characters
    // with ?).

    switch (dataType) {
        case REG_EXPAND_SZ:
        case REG_SZ: {
            QString s;
            if (dataSize) {
                s = QString::fromLatin1(data.constData());
            }
            if (value != 0)
                *value = stringToVariant(s);
            break;
        }

        case REG_MULTI_SZ: {
            QStringList l;
            if (dataSize) {
                int i = 0;
                for (;;) {
                    QString s = QString::fromLatin1(data.constData() + i);
                    i += s.length() + 1;

                    if (s.isEmpty())
                        break;
                    l.append(s);
                }
            }
            if (value != 0)
                *value = stringListToVariantList(l);
            break;
        }

        case REG_NONE:
        case REG_BINARY: {
            QString s;
            if (dataSize) {
                s = QString::fromLatin1(data.constData(), data.size());
            }
            if (value != 0)
                *value = stringToVariant(s);
            break;
        }

        case REG_DWORD_BIG_ENDIAN:
        case REG_DWORD: {
            Q_ASSERT(data.size() == sizeof(int));
            int i;
            memcpy((char*)&i, data.constData(), sizeof(int));
            if (value != 0)
                *value = i;
            break;
        }

        default:
            qWarning("QSettings: Unknown data %d type in Windows registry", static_cast<int>(dataType));
            if (value != 0)
                *value = QVariant();
            break;
    }

    RegCloseKey(handle);
    return true;
}

HKEY QOS2SettingsPrivate::writeHandle() const
{
    if (regList.isEmpty())
        return 0;
    const RegistryKey &key = regList.at(0);
    if (key.handle() == 0 || key.readOnly())
        return 0;
    return key.handle();
}

QOS2SettingsPrivate::~QOS2SettingsPrivate()
{
    if (deleteWriteHandleOnExit && writeHandle() != 0) {
        QString emptyKey;
        DWORD res = RegDeleteKeyA(writeHandle(), emptyKey.toLocal8Bit());
        if (res != ERROR_SUCCESS) {
            qWarning("QSettings: RegDeleteKey(%s) failed with %s",
                     regList.at(0).key().toUtf8().data(), errorCodeToString(res).data());
        }
    }

    for (int i = 0; i < regList.size(); ++i)
        regList[i].close();
}

void QOS2SettingsPrivate::remove(const QString &uKey)
{
    if (writeHandle() == 0) {
        setStatus(QSettings::AccessError);
        return;
    }

    QString rKey = escapedKey(uKey);

    // try to delete value bar in key foo
    LONG res;
    HKEY handle = openKey(writeHandle(), registryPermissions, keyPath(rKey));
    if (handle != 0) {
        res = RegDeleteValueA(handle, keyName(rKey).toLocal8Bit());
        RegCloseKey(handle);
    }

    // try to delete key foo/bar and all subkeys
    handle = openKey(writeHandle(), registryPermissions, rKey);
    if (handle != 0) {
        deleteChildGroups(handle);

        if (rKey.isEmpty()) {
            QStringList childKeys = childKeysOrGroups(handle, QSettingsPrivate::ChildKeys);

            for (int i = 0; i < childKeys.size(); ++i) {
                QString group = childKeys.at(i);

                LONG res = RegDeleteValueA(handle, group.toLocal8Bit());
                if (res != ERROR_SUCCESS) {
                    qWarning("QSettings: RegDeleteValue(%s) failed with %s",
                              group.toUtf8().data(), errorCodeToString(res).data());
                }
            }
        } else {
#if defined(Q_OS_WINCE)
            // For WinCE always Close the handle first.
            RegCloseKey(handle);
#endif
            res = RegDeleteKeyA(writeHandle(), rKey.toLocal8Bit());
            if (res != ERROR_SUCCESS) {
                qWarning("QSettings: RegDeleteKey(%s) failed with %s",
                            rKey.toUtf8().data(), errorCodeToString(res).data());
            }
        }
        RegCloseKey(handle);
    }
}

static bool stringContainsNullChar(const QString &s)
{
    for (int i = 0; i < s.length(); ++i) {
        if (s.at(i).unicode() == 0)
            return true;
    }
    return false;
}

void QOS2SettingsPrivate::set(const QString &uKey, const QVariant &value)
{
    if (writeHandle() == 0) {
        setStatus(QSettings::AccessError);
        return;
    }

    QString rKey = escapedKey(uKey);

    HKEY handle = createOrOpenKey(writeHandle(), registryPermissions, keyPath(rKey));
    if (handle == 0) {
        setStatus(QSettings::AccessError);
        return;
    }

    DWORD type;
    QByteArray regValueBuff;

    // note that when getting and setting the key contents on non-Unicode systems
    // we use the Latin1 encoding instead of Local8Bit because stringToVariant()
    // and variantToString() use Latin1 to convert between QString and QByteArray.
    // Since it's not guaranteed that all characters from Latin1 may be represented
    // in Local8Bit (and vice versa), doing Latin1 -> QString -> Local8Bit ->
    // QString -> Latin1 may distort data (in particular, replace some characters
    // with ?).

    // Determine the type
    switch (value.type()) {
        case QVariant::List:
        case QVariant::StringList: {
            // If none of the elements contains '\0', we can use REG_MULTI_SZ, the
            // native registry string list type. Otherwise we use REG_BINARY.
            type = REG_MULTI_SZ;
            QStringList l = variantListToStringList(value.toList());
            QStringList::const_iterator it = l.constBegin();
            for (; it != l.constEnd(); ++it) {
                if ((*it).length() == 0 || stringContainsNullChar(*it)) {
                    type = REG_BINARY;
                    break;
                }
            }

            if (type == REG_BINARY) {
                QString s = variantToString(value);
                regValueBuff = QByteArray((const char*)s.toLatin1(), s.length());
            } else {
                QStringList::const_iterator it = l.constBegin();
                for (; it != l.constEnd(); ++it) {
                    const QString &s = *it;
                    regValueBuff += QByteArray((const char*)s.toLatin1(), s.length() + 1);
                }
                regValueBuff.append((char)0);
            }
            break;
        }

        case QVariant::Int: {
            type = REG_DWORD;
            int i = value.toInt();
            regValueBuff = QByteArray((const char*)&i, sizeof(int));
            break;
        }

        case QVariant::ByteArray:
            // fallthrough intended

        default: {
            // If the string does not contain '\0', we can use REG_SZ, the native registry
            // string type. Otherwise we use REG_BINARY.
            QString s = variantToString(value);
            type = stringContainsNullChar(s) ? REG_BINARY : REG_SZ;
            if (type == REG_BINARY) {
                regValueBuff = QByteArray((const char*)s.toLatin1(), s.length());
            } else {
                regValueBuff = QByteArray((const char*)s.toLatin1(), s.length() + 1);
            }
            break;
        }
    }

    // set the value
    LONG res = RegSetValueExA(handle, keyName(rKey).toLocal8Bit(), 0, type,
                              reinterpret_cast<const unsigned char*>(regValueBuff.constData()),
                              regValueBuff.size());
    if (res == ERROR_SUCCESS) {
        deleteWriteHandleOnExit = false;
    } else {
        qWarning("QSettings: RegSetValueEx(%s) failed with %s",
                rKey.toUtf8().data(), errorCodeToString(res).data());
        setStatus(QSettings::AccessError);
    }

    RegCloseKey(handle);
}

bool QOS2SettingsPrivate::get(const QString &uKey, QVariant *value) const
{
    QString rKey = escapedKey(uKey);

    for (int i = 0; i < regList.size(); ++i) {
        HKEY handle = regList.at(i).handle();
        if (handle != 0 && readKey(handle, rKey, value))
            return true;

        if (!fallbacks)
            return false;
    }

    return false;
}

QStringList QOS2SettingsPrivate::children(const QString &uKey, ChildSpec spec) const
{
    NameSet result;
    QString rKey = escapedKey(uKey);

    for (int i = 0; i < regList.size(); ++i) {
        HKEY parent_handle = regList.at(i).handle();
        if (parent_handle == 0)
            continue;
        HKEY handle = openKey(parent_handle, KEY_READ, rKey);
        if (handle == 0)
            continue;

        if (spec == AllKeys) {
            NameSet keys;
            allKeys(handle, QLatin1String(""), &keys);
            mergeKeySets(&result, keys);
        } else { // ChildGroups or ChildKeys
            QStringList names = childKeysOrGroups(handle, spec);
            mergeKeySets(&result, names);
        }

        RegCloseKey(handle);

        if (!fallbacks)
            return result.keys();
    }

    return result.keys();
}

void QOS2SettingsPrivate::clear()
{
    remove(QString());
    deleteWriteHandleOnExit = true;
}

void QOS2SettingsPrivate::sync()
{
    RegFlushKey(writeHandle());
}

void QOS2SettingsPrivate::flush()
{
    // OS/2 does this for us.
}

QString QOS2SettingsPrivate::fileName() const
{
    if (regList.isEmpty())
        return QString();

    const RegistryKey &key = regList.at(0);
    QString result;
    if (key.parentHandle() == HKEY_CURRENT_USER)
        result = QLatin1String("\\HKEY_CURRENT_USER\\");
    else
        result = QLatin1String("\\HKEY_LOCAL_MACHINE\\");

    return result + regList.at(0).key();
}

bool QOS2SettingsPrivate::isWritable() const
{
    return writeHandle() != 0;
}

static QSettings::Format checkFormat(QSettings::Format format)
{
    if (getenv("QT_PM_NO_REGISTRY") != NULL ||
        getenv("QT_PM_REGISTRY") == NULL) {
#if defined(QT_DEBUG)
        if (getenv("QT_PM_NO_REGISTRY") != NULL)
            qDebug("QSettings: WARNING: using plain INI files due to QT_PM_NO_REGISTRY=%s",
                    getenv("QT_PM_NO_REGISTRY"));
#endif
        if (format == QSettings::NativeFormat)
            format = QSettings::IniFormat;
    }
#if defined(QT_DEBUG)
    if (getenv("QT_PM_REGISTRY") != NULL)
        qDebug("QSettings: WARNING: using Open32 registry due to QT_PM_REGISTRY=%s",
                getenv("QT_PM_REGISTRY"));
#endif

    return format;
}

QSettingsPrivate *QSettingsPrivate::create(QSettings::Format format, QSettings::Scope scope,
                                           const QString &organization, const QString &application)
{
    format = checkFormat(format);

    if (format == QSettings::NativeFormat) {
        return new QOS2SettingsPrivate(scope, organization, application);
    } else {
        return new QConfFileSettingsPrivate(format, scope, organization, application);
    }
}

QSettingsPrivate *QSettingsPrivate::create(const QString &fileName, QSettings::Format format)
{
    format = checkFormat(format);

    if (format == QSettings::NativeFormat) {
        return new QOS2SettingsPrivate(fileName);
    } else {
        return new QConfFileSettingsPrivate(fileName, format);
    }
}

QT_END_NAMESPACE
#endif // QT_NO_SETTINGS
