<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** 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.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qdeclarativedeviceinfo_p.h"
#include "qsystemdeviceinfo.h"
#include <QMetaType>
#include <QDebug>

QT_BEGIN_NAMESPACE

Q_GLOBAL_STATIC(QSystemDeviceInfo, deviceInfo)

/*!
    \qmlclass DeviceInfo QDeclarativeDeviceInfo
    \brief The DeviceInfo element allows you to access information anbout the device and
        receive notifications from the device.

    \inherits QSystemDeviceInfo

    \ingroup qml-systeminfo

    This element is part of the \bold{QtMobility.systeminfo 1.1} module.
    It is a convience class to make QML usage easier.

    Note: To use notification signals, you need to set the monitor* properties to true.

\sa QSystemDeviceInfo
*/

/*!
    \qmlsignal DeviceInfo::batteryLevelChanged(int)

    This handler is called when battery level has changed.
*/
/*!
    \qmlsignal DeviceInfo::batteryStatusChanged(DeviceInfo::BatteryStatus)

    This handler is called when battery status has changed.

*/
/*!
    \qmlsignal DeviceInfo::powerStateChanged(DeviceINfo::PowerState)

    This handler is called when the power state has changed.
*/
/*!
    \qmlsignal DeviceInfo::currentProfileChanged(DeviceInfo::Profile)

    This handler is called when current device profile has changed.

*/
/*!
    \qmlsignal DeviceInfo::bluetoothStateChanged(bool)

    This handler is called when bluetooth power state has changed.

*/

/*!
    \qmlsignal DeviceInfo::wirelessKeyboardConnected(bool)

  This signal is emitted whenever a wireless keyboard is connected
*/

/*!
    \qmlsignal DeviceInfo::keyboardFlipped(bool)

      This signal is emitted whenever a phone flips open.
*/

/*!
    \qmlsignal DeviceInfo::deviceLocked(bool)

    This signal is emitted whenever the device lock state changes
*/

/*!
    \qmlsignal DeviceInfo::lockStatusChanged(DeviceInfo::LockTypeFlags)

    This signal is emitted whenever the lock state changes
*/

/*!
    \qmlsignal DeviceInfo::thermalStateChanged(DeviceInfo::ThermalState)

    This handler is called when thermal state has changed.
*/

QDeclarativeDeviceInfo::QDeclarativeDeviceInfo(QObject *parent) :
    QSystemDeviceInfo(parent)
{
}

/*!
   This function starts the batteryLevelChanged notification

*/

void QDeclarativeDeviceInfo::startBatteryLevelChanged(bool on)
{
    monitoringBatteryLevel = on;
    if(on) {
        connect(deviceInfo(),SIGNAL(batteryLevelChanged(int)),
                this,SIGNAL(batteryLevelChanged(int)),Qt::UniqueConnection);
    } else {
        disconnect(deviceInfo(),SIGNAL(batteryLevelChanged(int)),
                   this,SIGNAL(batteryLevelChanged(int)));
    }
}

/*!
    \qmlproperty bool DeviceInfo::monitorBatteryLevelChanges
    Use the monitorBatteryLevelChanges signal.

  */
bool QDeclarativeDeviceInfo::monitorBatteryLevelChanges()
{
    return monitoringBatteryLevel;
}

/*!
   This function starts the batteryStatusChanged notification

*/
void QDeclarativeDeviceInfo::startBatteryStatusChanged(bool on)
{
    monitoringBatteryStatus = on;
    if(on) {
    connect(deviceInfo(),SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)),
            this,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)),Qt::UniqueConnection);
    } else {
        disconnect(deviceInfo(),SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)),
                this,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)));
    }
}

/*!
    \qmlproperty bool DeviceInfo::monitorBatteryStatusChanges
    Use the monitorBatteryStatusChanges signal.
  */
bool QDeclarativeDeviceInfo::monitorBatteryStatusChanges()
{
    return monitoringBatteryStatus;
}

/*!
   This function starts the powerStateChanged notification

*/
void QDeclarativeDeviceInfo::startPowerStateChanged(bool on)
{
    monitoringPowerState = on;
    if(on) {
    connect(deviceInfo(),SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)),
            this,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)),Qt::UniqueConnection);
    } else {
        disconnect(deviceInfo(),SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)),
                this,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)));
    }
}

/*!
    \qmlproperty bool DeviceInfo::monitorPowerStateChanges
    Use the monitorPowerStateChanges signal.
  */
bool QDeclarativeDeviceInfo::monitorPowerStateChanges()
{
    return monitoringPowerState;
}

/*!
   This function is needed to start currentProfileChanged notification

*/
void QDeclarativeDeviceInfo::startCurrentProfileChanged(bool on)
{
    monitoringCurrentProfile = on;
    if(on) {
    connect(deviceInfo(),SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)),
            this,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)),Qt::UniqueConnection);
    } else {
        disconnect(deviceInfo(),SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)),
                this,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)));
    }
}

/*!
    \qmlproperty bool DeviceInfo::monitorCurrentProfileChanges
   Use the monitorCurrentProfileChanges signal.
  */
bool QDeclarativeDeviceInfo::monitorCurrentProfileChanges()
{
    return monitoringCurrentProfile;
}

/*!
   This function starts the bluetoothStateChanged notification

*/
void QDeclarativeDeviceInfo::startBluetoothStateChanged(bool on)
{
    monitorBluetoothState = on;
    if(on) {
    connect(deviceInfo(),SIGNAL(bluetoothStateChanged(bool)),
            this,SIGNAL(bluetoothStateChanged(bool)),Qt::UniqueConnection);
    } else {
        disconnect(deviceInfo(),SIGNAL(bluetoothStateChanged(bool)),
                this,SIGNAL(bluetoothStateChanged(bool)));
    }
}

/*!
    \qmlproperty bool DeviceInfo::monitorBluetoothStateChanges
    Use the bluetoothStateChanges signal.
  */
bool QDeclarativeDeviceInfo::monitorBluetoothStateChanges()
{
   return monitorBluetoothState;
}

/*!
   This function starts the thermalStateChanged notification

*/
void QDeclarativeDeviceInfo::startThermalStateChanged(bool on)
{
    monitorThermalState = on;
    if (on) {
    connect(deviceInfo(), SIGNAL(thermalStateChanged(QSystemDeviceInfo::ThermalState)),
            this, SIGNAL(thermalStateChanged(QSystemDeviceInfo::ThermalState)), Qt::UniqueConnection);
    } else {
        disconnect(deviceInfo(), SIGNAL(thermalStateChanged(QSystemDeviceInfo::ThermalState)),
                this, SIGNAL(thermalStateChanged(QSystemDeviceInfo::ThermalState)));
    }
}

/*!
    \qmlproperty bool DeviceInfo::monitorThermalStateChanges
    Use the thermalStateChanges signal.
  */
bool QDeclarativeDeviceInfo::monitorThermalStateChanges()
{
   return monitorThermalState;
}

/*!

  \qmlproperty bool DeviceInfo::monitorWirelessKeyboardConnects()

  Start the connection for the wirelessKeyboardConnected signal.
  */
bool QDeclarativeDeviceInfo::monitorWirelessKeyboardConnects()
{
 return monitoringWirelessKeyboard;
}

/*!
   This function starts the startBatteryStatusChanged notification.

*/
void QDeclarativeDeviceInfo::startWirelessKeyboardConnected(bool on)
{
    monitoringWirelessKeyboard = on;
    if(on) {
        connect(deviceInfo(),SIGNAL(wirelessKeyboardConnected(bool)),
                this,SIGNAL(wirelessKeyboardConnected(bool)),Qt::UniqueConnection);
    } else {
        disconnect(deviceInfo(),SIGNAL(wirelessKeyboardConnected(bool)),
                this,SIGNAL(wirelessKeyboardConnected(bool)));
    }
}

/*!

  \qmlproperty bool DeviceInfo::monitorKeyboardFlips()

  Start the connection for the keyboardFlipped signal.
  */
bool QDeclarativeDeviceInfo::monitorKeyboardFlips()
{
    return monitoringKeyboardFlipped;
}

/*!
   This function starts the startKeyboardFlipped notification.

*/
void QDeclarativeDeviceInfo::startKeyboardFlipped(bool on)
{
    monitoringKeyboardFlipped = on;
    if(on) {
        connect(deviceInfo(),SIGNAL(keyboardFlipped(bool)),
                this,SIGNAL(keyboardFlipped(bool)),Qt::UniqueConnection);
    } else {
        disconnect(deviceInfo(),SIGNAL(keyboardFlipped(bool)),
                this,SIGNAL(keyboardFlipped(bool)));
    }
}

/*!

  \qmlproperty bool Device::monitorDeviceLocks()

  Start the connection for the deviceLocked signal.
  */
bool QDeclarativeDeviceInfo::monitorDeviceLocks()
{
    return monitoringDeviceLocked;
}

/*!
   This function starts the startDeviceLocked notification.

*/
void QDeclarativeDeviceInfo::startDeviceLocked(bool on)
{
    monitoringDeviceLocked = on;
    if(on) {
        connect(deviceInfo(),SIGNAL(deviceLocked(bool)),
                this,SIGNAL(deviceLocked(bool)),Qt::UniqueConnection);
    } else {
        disconnect(deviceInfo(),SIGNAL(deviceLocked(bool)),
                this,SIGNAL(deviceLocked(bool)));
    }
}

/*!

  \qmlproperty bool DeviceInfo::monitorLockStatusChanges()

  Start the connection for the lockStatusChanged signal.
  */

bool QDeclarativeDeviceInfo::monitorLockStatusChanges()
{
    return monitoringLockStatusChanged;
}

/*!
   This function starts the startLockStatusChanged notification.

*/
void QDeclarativeDeviceInfo::startLockStatusChanged(bool on)
{
    monitoringLockStatusChanged = on;
    if(on) {
        connect(deviceInfo(),SIGNAL(lockStatusChanged(QSystemDeviceInfo::LockTypeFlags)),
                this,SIGNAL(lockStatusChanged(QSystemDeviceInfo::LockTypeFlags)),Qt::UniqueConnection);
    } else {
        disconnect(deviceInfo(),SIGNAL(lockStatusChanged(QSystemDeviceInfo::LockTypeFlags)),
                this,SIGNAL(lockStatusChanged(QSystemDeviceInfo::LockTypeFlags)));
    }
}

/*!
  \qmlproperty int DeviceInfo::messageRingtoneVolume()

    Returns the active profile's message ringtone volume. From 0 to 100.
  */
int QDeclarativeDeviceInfo::messageRingtoneVolume()
{
    return deviceInfo()->activeProfileDetails().messageRingtoneVolume();
}

/*!
  \qmlproperty int DeviceInfo::voiceRingtoneVolume()

    Returns the active profile's voice ringtone volume. From 0 to 100.

  */
int QDeclarativeDeviceInfo::voiceRingtoneVolume()
{
    return deviceInfo()->activeProfileDetails().voiceRingtoneVolume();
}

/*!
  \qmlproperty bool DeviceInfo::vibrationActive()

    Returns the whether the active profile's vibration is active.

  */
bool QDeclarativeDeviceInfo::vibrationActive()
{
    return deviceInfo()->activeProfileDetails().vibrationActive();
}

/*!
  \qmlproperty bool DeviceInfo::primaryKeypadLightOn()

    Returns the whether he primary keypad  or keyboard light is on.
  */
/*!
  Returns true if the primary key pad light is on, otherwise false;
  */
bool QDeclarativeDeviceInfo::primaryKeypadLightOn()
{
    return deviceInfo()->keypadLightOn(QSystemDeviceInfo::PrimaryKeypad);
}

/*!
  \qmlproperty bool DeviceInfo::secondaryKeypadLightOn()

    Returns the whether he secondary keypad or keyboard light is on.
  */
/*!
  Returns true if the key pad light is on, otherwise false;
  */
bool QDeclarativeDeviceInfo::secondaryKeypadLightOn()
{
    return deviceInfo()->keypadLightOn(QSystemDeviceInfo::SecondaryKeypad);

}

/*!
  \qmlproperty QString DeviceInfo::imei

     Returns the International Mobile Equipment Identity (IMEI), or a null QString in the case of none.
  */

/*!
  \qmlproperty QString DeviceInfo::imsi
 Returns the International Mobile Subscriber Identity (IMSI), or a null QString in the case of none
  */

/*!
  \qmlproperty QString DeviceInfo::manufacturer
    Returns the name of the manufacturer of this device. In the case of desktops, the name of the vendor
    of the motherboard.
  */
/*!
  \qmlproperty QString DeviceInfo::model
    Returns the model information of the device. In the case of desktops where no
    model information is present, the CPU architect, such as i686, and machine type, such as Server,
    Desktop or Laptop.
  */
/*!
  \qmlproperty QString DeviceInfo::productName
    Returns the product name of the device. In the case where no product information is available, an empty string will be returned.

  */
/*!
  \qmlproperty int DeviceInfo::batteryLevel
   Returns the battery charge level as percentage 1 - 100 scale.
  */
/*!
  \qmlproperty InputMethodFlags DeviceInfo::inputMethodType
Returns the QSystemDeviceInfo::InputMethodFlags InputMethodType that the system uses.
  */
/*!
  \qmlproperty BatteryStatus DeviceInfo::batteryStatus
  Returns the battery charge status.
  */
/*!
  \qmlproperty bool DeviceInfo::isDeviceLocked

  Returns true if the device is locked, otherwise false.
  */
/*!
  \qmlproperty SimStatus DeviceInfo::simStatus
  Returns the QSystemDeviceInfo::simStatus status of SIM card.
  */
/*!
  \qmlproperty Profile DeviceInfo::currentProfile
  Gets the current QSystemDeviceInfo::currentProfile device profile.
  */
/*!
  \qmlproperty PowerState DeviceInfo::currentPowerState

  Gets the current QSystemDeviceInfo::currentPowerState state.
  */
/*!
  \qmlproperty bool DeviceInfo::currentBluetoothPowerState
Gets the current bluetooth power state.
  */
/*!
  \qmlproperty KeyboardTypeFlags DeviceInfo::keyboardTypes
  Returns the type of keyboards found.
  */
/*!
  \qmlproperty bool DeviceInfo::isWirelessKeyboardConnected
  Returns true if a wireless keyboard is connected, otherwise false;
  */
/*!
  \qmlproperty bool DeviceInfo::isKeyboardFlippedOpen
  Returns true if the flip keyboard is open, otherwise false;
  */

/*!
  \qmlproperty LockTypeFlags DeviceInfo::lockStatus
  Returns the QSystemDeviceInfo::LockTypeFlags type of lock state the device might be in.
  The LockType must be currently active not just enabled.
  */

/*!
  \qmlproperty string DeviceInfo::uniqueID

  Returns a unique identifier for the machine.

  Depending on security enforcement on platform, this may return a non unique number, or 0.

  */
<commit_msg>Docs: QTMOBILITY-1784. Added doc for currentThermalState<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** 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.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qdeclarativedeviceinfo_p.h"
#include "qsystemdeviceinfo.h"
#include <QMetaType>
#include <QDebug>

QT_BEGIN_NAMESPACE

Q_GLOBAL_STATIC(QSystemDeviceInfo, deviceInfo)

/*!
    \qmlclass DeviceInfo QDeclarativeDeviceInfo
    \brief The DeviceInfo element allows you to access information anbout the device and
        receive notifications from the device.

    \inherits QSystemDeviceInfo

    \ingroup qml-systeminfo

    This element is part of the \bold{QtMobility.systeminfo 1.1} module.
    It is a convience class to make QML usage easier.

    Note: To use notification signals, you need to set the monitor* properties to true.

\sa QSystemDeviceInfo
*/

/*!
    \qmlsignal DeviceInfo::batteryLevelChanged(int)

    This handler is called when battery level has changed.
*/
/*!
    \qmlsignal DeviceInfo::batteryStatusChanged(DeviceInfo::BatteryStatus)

    This handler is called when battery status has changed.

*/
/*!
    \qmlsignal DeviceInfo::powerStateChanged(DeviceINfo::PowerState)

    This handler is called when the power state has changed.
*/
/*!
    \qmlsignal DeviceInfo::currentProfileChanged(DeviceInfo::Profile)

    This handler is called when current device profile has changed.

*/
/*!
    \qmlsignal DeviceInfo::bluetoothStateChanged(bool)

    This handler is called when bluetooth power state has changed.

*/

/*!
    \qmlsignal DeviceInfo::wirelessKeyboardConnected(bool)

  This signal is emitted whenever a wireless keyboard is connected
*/

/*!
    \qmlsignal DeviceInfo::keyboardFlipped(bool)

      This signal is emitted whenever a phone flips open.
*/

/*!
    \qmlsignal DeviceInfo::deviceLocked(bool)

    This signal is emitted whenever the device lock state changes
*/

/*!
    \qmlsignal DeviceInfo::lockStatusChanged(DeviceInfo::LockTypeFlags)

    This signal is emitted whenever the lock state changes
*/

/*!
    \qmlsignal DeviceInfo::thermalStateChanged(DeviceInfo::ThermalState)

    This handler is called when thermal state has changed.
*/

QDeclarativeDeviceInfo::QDeclarativeDeviceInfo(QObject *parent) :
    QSystemDeviceInfo(parent)
{
}

/*!
   This function starts the batteryLevelChanged notification

*/

void QDeclarativeDeviceInfo::startBatteryLevelChanged(bool on)
{
    monitoringBatteryLevel = on;
    if(on) {
        connect(deviceInfo(),SIGNAL(batteryLevelChanged(int)),
                this,SIGNAL(batteryLevelChanged(int)),Qt::UniqueConnection);
    } else {
        disconnect(deviceInfo(),SIGNAL(batteryLevelChanged(int)),
                   this,SIGNAL(batteryLevelChanged(int)));
    }
}

/*!
    \qmlproperty bool DeviceInfo::monitorBatteryLevelChanges
    Use the monitorBatteryLevelChanges signal.

  */
bool QDeclarativeDeviceInfo::monitorBatteryLevelChanges()
{
    return monitoringBatteryLevel;
}

/*!
   This function starts the batteryStatusChanged notification

*/
void QDeclarativeDeviceInfo::startBatteryStatusChanged(bool on)
{
    monitoringBatteryStatus = on;
    if(on) {
    connect(deviceInfo(),SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)),
            this,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)),Qt::UniqueConnection);
    } else {
        disconnect(deviceInfo(),SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)),
                this,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)));
    }
}

/*!
    \qmlproperty bool DeviceInfo::monitorBatteryStatusChanges
    Use the monitorBatteryStatusChanges signal.
  */
bool QDeclarativeDeviceInfo::monitorBatteryStatusChanges()
{
    return monitoringBatteryStatus;
}

/*!
   This function starts the powerStateChanged notification

*/
void QDeclarativeDeviceInfo::startPowerStateChanged(bool on)
{
    monitoringPowerState = on;
    if(on) {
    connect(deviceInfo(),SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)),
            this,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)),Qt::UniqueConnection);
    } else {
        disconnect(deviceInfo(),SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)),
                this,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)));
    }
}

/*!
    \qmlproperty bool DeviceInfo::monitorPowerStateChanges
    Use the monitorPowerStateChanges signal.
  */
bool QDeclarativeDeviceInfo::monitorPowerStateChanges()
{
    return monitoringPowerState;
}

/*!
   This function is needed to start currentProfileChanged notification

*/
void QDeclarativeDeviceInfo::startCurrentProfileChanged(bool on)
{
    monitoringCurrentProfile = on;
    if(on) {
    connect(deviceInfo(),SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)),
            this,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)),Qt::UniqueConnection);
    } else {
        disconnect(deviceInfo(),SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)),
                this,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)));
    }
}

/*!
    \qmlproperty bool DeviceInfo::monitorCurrentProfileChanges
   Use the monitorCurrentProfileChanges signal.
  */
bool QDeclarativeDeviceInfo::monitorCurrentProfileChanges()
{
    return monitoringCurrentProfile;
}

/*!
   This function starts the bluetoothStateChanged notification

*/
void QDeclarativeDeviceInfo::startBluetoothStateChanged(bool on)
{
    monitorBluetoothState = on;
    if(on) {
    connect(deviceInfo(),SIGNAL(bluetoothStateChanged(bool)),
            this,SIGNAL(bluetoothStateChanged(bool)),Qt::UniqueConnection);
    } else {
        disconnect(deviceInfo(),SIGNAL(bluetoothStateChanged(bool)),
                this,SIGNAL(bluetoothStateChanged(bool)));
    }
}

/*!
    \qmlproperty bool DeviceInfo::monitorBluetoothStateChanges
    Use the bluetoothStateChanges signal.
  */
bool QDeclarativeDeviceInfo::monitorBluetoothStateChanges()
{
   return monitorBluetoothState;
}

/*!
   This function starts the thermalStateChanged notification

*/
void QDeclarativeDeviceInfo::startThermalStateChanged(bool on)
{
    monitorThermalState = on;
    if (on) {
    connect(deviceInfo(), SIGNAL(thermalStateChanged(QSystemDeviceInfo::ThermalState)),
            this, SIGNAL(thermalStateChanged(QSystemDeviceInfo::ThermalState)), Qt::UniqueConnection);
    } else {
        disconnect(deviceInfo(), SIGNAL(thermalStateChanged(QSystemDeviceInfo::ThermalState)),
                this, SIGNAL(thermalStateChanged(QSystemDeviceInfo::ThermalState)));
    }
}

/*!
    \qmlproperty bool DeviceInfo::monitorThermalStateChanges
    Use the thermalStateChanges signal.
  */
bool QDeclarativeDeviceInfo::monitorThermalStateChanges()
{
   return monitorThermalState;
}

/*!

  \qmlproperty bool DeviceInfo::monitorWirelessKeyboardConnects()

  Start the connection for the wirelessKeyboardConnected signal.
  */
bool QDeclarativeDeviceInfo::monitorWirelessKeyboardConnects()
{
 return monitoringWirelessKeyboard;
}

/*!
   This function starts the startBatteryStatusChanged notification.

*/
void QDeclarativeDeviceInfo::startWirelessKeyboardConnected(bool on)
{
    monitoringWirelessKeyboard = on;
    if(on) {
        connect(deviceInfo(),SIGNAL(wirelessKeyboardConnected(bool)),
                this,SIGNAL(wirelessKeyboardConnected(bool)),Qt::UniqueConnection);
    } else {
        disconnect(deviceInfo(),SIGNAL(wirelessKeyboardConnected(bool)),
                this,SIGNAL(wirelessKeyboardConnected(bool)));
    }
}

/*!

  \qmlproperty bool DeviceInfo::monitorKeyboardFlips()

  Start the connection for the keyboardFlipped signal.
  */
bool QDeclarativeDeviceInfo::monitorKeyboardFlips()
{
    return monitoringKeyboardFlipped;
}

/*!
   This function starts the startKeyboardFlipped notification.

*/
void QDeclarativeDeviceInfo::startKeyboardFlipped(bool on)
{
    monitoringKeyboardFlipped = on;
    if(on) {
        connect(deviceInfo(),SIGNAL(keyboardFlipped(bool)),
                this,SIGNAL(keyboardFlipped(bool)),Qt::UniqueConnection);
    } else {
        disconnect(deviceInfo(),SIGNAL(keyboardFlipped(bool)),
                this,SIGNAL(keyboardFlipped(bool)));
    }
}

/*!

  \qmlproperty bool Device::monitorDeviceLocks()

  Start the connection for the deviceLocked signal.
  */
bool QDeclarativeDeviceInfo::monitorDeviceLocks()
{
    return monitoringDeviceLocked;
}

/*!
   This function starts the startDeviceLocked notification.

*/
void QDeclarativeDeviceInfo::startDeviceLocked(bool on)
{
    monitoringDeviceLocked = on;
    if(on) {
        connect(deviceInfo(),SIGNAL(deviceLocked(bool)),
                this,SIGNAL(deviceLocked(bool)),Qt::UniqueConnection);
    } else {
        disconnect(deviceInfo(),SIGNAL(deviceLocked(bool)),
                this,SIGNAL(deviceLocked(bool)));
    }
}

/*!

  \qmlproperty bool DeviceInfo::monitorLockStatusChanges()

  Start the connection for the lockStatusChanged signal.
  */

bool QDeclarativeDeviceInfo::monitorLockStatusChanges()
{
    return monitoringLockStatusChanged;
}

/*!
   This function starts the startLockStatusChanged notification.

*/
void QDeclarativeDeviceInfo::startLockStatusChanged(bool on)
{
    monitoringLockStatusChanged = on;
    if(on) {
        connect(deviceInfo(),SIGNAL(lockStatusChanged(QSystemDeviceInfo::LockTypeFlags)),
                this,SIGNAL(lockStatusChanged(QSystemDeviceInfo::LockTypeFlags)),Qt::UniqueConnection);
    } else {
        disconnect(deviceInfo(),SIGNAL(lockStatusChanged(QSystemDeviceInfo::LockTypeFlags)),
                this,SIGNAL(lockStatusChanged(QSystemDeviceInfo::LockTypeFlags)));
    }
}

/*!
  \qmlproperty int DeviceInfo::messageRingtoneVolume()

    Returns the active profile's message ringtone volume. From 0 to 100.
  */
int QDeclarativeDeviceInfo::messageRingtoneVolume()
{
    return deviceInfo()->activeProfileDetails().messageRingtoneVolume();
}

/*!
  \qmlproperty int DeviceInfo::voiceRingtoneVolume()

    Returns the active profile's voice ringtone volume. From 0 to 100.

  */
int QDeclarativeDeviceInfo::voiceRingtoneVolume()
{
    return deviceInfo()->activeProfileDetails().voiceRingtoneVolume();
}

/*!
  \qmlproperty bool DeviceInfo::vibrationActive()

    Returns the whether the active profile's vibration is active.

  */
bool QDeclarativeDeviceInfo::vibrationActive()
{
    return deviceInfo()->activeProfileDetails().vibrationActive();
}

/*!
  \qmlproperty bool DeviceInfo::primaryKeypadLightOn()

    Returns the whether he primary keypad  or keyboard light is on.
  */
/*!
  Returns true if the primary key pad light is on, otherwise false;
  */
bool QDeclarativeDeviceInfo::primaryKeypadLightOn()
{
    return deviceInfo()->keypadLightOn(QSystemDeviceInfo::PrimaryKeypad);
}

/*!
  \qmlproperty bool DeviceInfo::secondaryKeypadLightOn()

    Returns the whether he secondary keypad or keyboard light is on.
  */
/*!
  Returns true if the key pad light is on, otherwise false;
  */
bool QDeclarativeDeviceInfo::secondaryKeypadLightOn()
{
    return deviceInfo()->keypadLightOn(QSystemDeviceInfo::SecondaryKeypad);

}

/*!
  \qmlproperty QString DeviceInfo::imei

     Returns the International Mobile Equipment Identity (IMEI), or a null QString in the case of none.
  */

/*!
  \qmlproperty QString DeviceInfo::imsi
 Returns the International Mobile Subscriber Identity (IMSI), or a null QString in the case of none
  */

/*!
  \qmlproperty QString DeviceInfo::manufacturer
    Returns the name of the manufacturer of this device. In the case of desktops, the name of the vendor
    of the motherboard.
  */
/*!
  \qmlproperty QString DeviceInfo::model
    Returns the model information of the device. In the case of desktops where no
    model information is present, the CPU architect, such as i686, and machine type, such as Server,
    Desktop or Laptop.
  */
/*!
  \qmlproperty QString DeviceInfo::productName
    Returns the product name of the device. In the case where no product information is available, an empty string will be returned.

  */
/*!
  \qmlproperty int DeviceInfo::batteryLevel
   Returns the battery charge level as percentage 1 - 100 scale.
  */
/*!
  \qmlproperty InputMethodFlags DeviceInfo::inputMethodType
Returns the QSystemDeviceInfo::InputMethodFlags InputMethodType that the system uses.
  */
/*!
  \qmlproperty BatteryStatus DeviceInfo::batteryStatus
  Returns the battery charge status.
  */
/*!
  \qmlproperty bool DeviceInfo::isDeviceLocked

  Returns true if the device is locked, otherwise false.
  */
/*!
  \qmlproperty SimStatus DeviceInfo::simStatus
  Returns the QSystemDeviceInfo::simStatus status of SIM card.
  */
/*!
  \qmlproperty Profile DeviceInfo::currentProfile
  Gets the current QSystemDeviceInfo::currentProfile device profile.
  */
/*!
  \qmlproperty PowerState DeviceInfo::currentPowerState

  Gets the current QSystemDeviceInfo::currentPowerState state.
  */
/*!
  \qmlproperty bool DeviceInfo::currentBluetoothPowerState
Gets the current bluetooth power state.
  */
/*!
  \qmlproperty KeyboardTypeFlags DeviceInfo::keyboardTypes
  Returns the type of keyboards found.
  */
/*!
  \qmlproperty bool DeviceInfo::isWirelessKeyboardConnected
  Returns true if a wireless keyboard is connected, otherwise false;
  */
/*!
  \qmlproperty bool DeviceInfo::isKeyboardFlippedOpen
  Returns true if the flip keyboard is open, otherwise false;
  */

/*!
  \qmlproperty LockTypeFlags DeviceInfo::lockStatus
  Returns the QSystemDeviceInfo::LockTypeFlags type of lock state the device might be in.
  The LockType must be currently active not just enabled.
  */

/*!
    \qmlproperty ThermalState DeviceInfo::currentThermalState
    Returns the current thermal state of the device.

    \since 1.2
    \sa QSystemDeviceInfo::ThermalState
*/

/*!
  \qmlproperty string DeviceInfo::uniqueID

  Returns a unique identifier for the machine.

  Depending on security enforcement on platform, this may return a non unique number, or 0.

  */
<|endoftext|>


<commit_before>#include <unordered_map>
#include <memory>
#include <glog/logging.h>
#include "streams.h"
#include "util.h"
#include <scheduler.h>

void call_rescue(e_t e, const children_t& children) {
  for (auto& s: children) {
    s(e);
  }
}

stream_t prn() {
  return [](e_t e) {
    LOG(INFO) << "prn() " <<  event_to_json(e);
  };
}

stream_t with(const with_changes_t& changes, const children_t& children) {
  return [=](e_t e) {
    Event ne(e);
    for (auto &kv: changes) {
      VLOG(3) << "with()  first: " << kv.first << " second: " << kv.second;
      set_event_value(ne, kv.first, kv.second, true);
    }
    call_rescue(ne, children);
  };
}

stream_t with_ifempty(
    const with_changes_t& changes,
    const children_t& children)
{
  return [=](e_t e) {
    Event ne(e);
    for (auto &kv: changes) {
      VLOG(3) << "default()  first: " << kv.first << " second: " << kv.second;
      set_event_value(ne, kv.first, kv.second, false);
    }
    call_rescue(ne, children);
  };
}

stream_t split(const split_clauses_t clauses,
               const children_t& default_children)
{
  return [=](e_t e) {
    VLOG(3) << "split()";
    for (auto const &pair: clauses) {
      if (pair.first(e)) {
        VLOG(3) << "split() clause found";
        call_rescue(e, pair.second);
        return;
      }
    }
    if (default_children.size() > 0) {
      VLOG(3) << "split() default";
      call_rescue(e, default_children);
    }
  };
}

typedef std::unordered_map<std::string, const children_t> by_streams_map_t;

stream_t by(const by_keys_t& keys, const by_streams_t& streams) {
  by_streams_map_t streams_map;

  return [=](e_t e) mutable {
    VLOG(3) << "by()";

    if (keys.size() == 0) {
      return;
    }

    std::string key("");
    for (auto &k: keys) {
      std::string value = string_to_value(e, k);
      if (value == "__nil__") {
        LOG(ERROR) << "by() field empty: " << k;
      }
      key += value + "-";
    }

    VLOG(3) << "by() key: " << key;
    auto it = streams_map.find(key);
    if (it == streams_map.end()) {
      VLOG(3) << "by() key not found. Creating stream.";
      children_t children;
      for (auto &s: streams) {
        children.push_back(s());
      }
      streams_map.insert({key, std::move(children)});
      call_rescue(e, streams_map.find(key)->second);
    } else {
      VLOG(3) << "by() stream exists. ";
      call_rescue(e, it->second);
    }
  };
}

stream_t where(const predicate_t& predicate, const children_t& children,
               const children_t& else_children)
{
  return [=](e_t e) {
    if (predicate(e)) {
      call_rescue(e, children);
    } else {
      call_rescue(e, else_children);
    }
  };
}

stream_t rate(const int interval, const children_t& children) {
  std::shared_ptr<double> rate(std::make_shared<double>(0));
  g_scheduler.add_periodic_task(
     [=]() mutable
      {
        VLOG(3) << "rate-timer()";
        Event e;
        e.set_metric_f(*rate / interval);
        e.set_time(time(0));
        *rate = 0;
        VLOG(3) << "rate-timer() value: " << e.metric_f();
        call_rescue(e, children);
      },
      interval
  );

  return [=](e_t e) mutable {
    VLOG(3) << "rate() rate += e.metric";
    (*rate) += metric_to_double(e);
  };
}

stream_t changed_state(std::string initial, const children_t& children) {
  std::string last_state(initial);

  return [=](e_t e) mutable {
    VLOG(3) << "changed_state() last_state: "
            << last_state << " new state " << e.state();
    if (last_state != e.state()) {
      VLOG(3) << "changed_state() state change";
      last_state.assign(e.state());
      call_rescue(e, children);
    }
  };
}

stream_t tagged_any(const tags_t& tags, const children_t& children) {
  return [=](e_t e) {
    VLOG(3) << "tagged_any()";
    if (tagged_any_(e, tags)) {
      VLOG(3) << "tagged_any() match";
      call_rescue(e, children);
    }
  };
}

stream_t tagged_all(const tags_t& tags, const children_t& children) {
  return [=](e_t e) {
    VLOG(3) << "tagged_all()";
    if (tagged_all_(e, tags)) {
      VLOG(3) << "tagged_all() match";
      call_rescue(e, children);
    }
  };
}

bool tagged_any_(e_t e, const tags_t& tags) {
  for (auto &tag: tags) {
    if (tag_exists(e, tag)) {
      return true;
    }
  }
  return false;
}

bool tagged_all_(e_t e, const tags_t& tags) {
  for (auto &tag: tags) {
    if (!tag_exists(e, tag)) {
      return false;
    }
  }
  return true;
}

stream_t send_index(class index& idx) {
  return [&](e_t e) {
    if (e.state() != "expired") {
      idx.add_event(e);
    }
  };
}

void streams::add_stream(stream_t stream) {
  VLOG(3) << "adding stream";
  streams_.push_back(stream);
}

void streams::process_message(const Msg& message) {
  VLOG(3) << "process message. num of streams " << streams_.size();
  unsigned long int sec = time(0);
  for (int i = 0; i < message.events_size(); i++) {
    const Event &event = message.events(i);
    if (!event.has_time()) {
      Event nevent(event);
      nevent.set_time(sec);
      push_event(std::move(nevent));
    } else {
      push_event(event);
    }
  }
}

void streams::push_event(const Event& e) {
  for (auto& s: streams_) {
    s(e);
  }
}

<commit_msg>Refactor with and with_ifempty<commit_after>#include <unordered_map>
#include <memory>
#include <glog/logging.h>
#include "streams.h"
#include "util.h"
#include <scheduler.h>

void call_rescue(e_t e, const children_t& children) {
  for (auto& s: children) {
    s(e);
  }
}

stream_t prn() {
  return [](e_t e) {
    LOG(INFO) << "prn() " <<  event_to_json(e);
  };
}

stream_t with(const with_changes_t & changes,
              const bool & replace,
              const children_t & children)
{
  return [=](e_t e) {
    Event ne(e);
    for (auto &kv: changes) {
      set_event_value(ne, kv.first, kv.second, replace);
    }
    call_rescue(ne, children);
  };
}

stream_t with(const with_changes_t& changes, const children_t& children) {
  return with(changes, true, children);
}

stream_t with_ifempty(
    const with_changes_t& changes,
    const children_t& children)
{
  return with(changes, false, children);
}

stream_t split(const split_clauses_t clauses,
               const children_t& default_children)
{
  return [=](e_t e) {
    VLOG(3) << "split()";
    for (auto const &pair: clauses) {
      if (pair.first(e)) {
        VLOG(3) << "split() clause found";
        call_rescue(e, pair.second);
        return;
      }
    }
    if (default_children.size() > 0) {
      VLOG(3) << "split() default";
      call_rescue(e, default_children);
    }
  };
}

typedef std::unordered_map<std::string, const children_t> by_streams_map_t;

stream_t by(const by_keys_t& keys, const by_streams_t& streams) {
  by_streams_map_t streams_map;

  return [=](e_t e) mutable {
    VLOG(3) << "by()";

    if (keys.size() == 0) {
      return;
    }

    std::string key("");
    for (auto &k: keys) {
      std::string value = string_to_value(e, k);
      if (value == "__nil__") {
        LOG(ERROR) << "by() field empty: " << k;
      }
      key += value + "-";
    }

    VLOG(3) << "by() key: " << key;
    auto it = streams_map.find(key);
    if (it == streams_map.end()) {
      VLOG(3) << "by() key not found. Creating stream.";
      children_t children;
      for (auto &s: streams) {
        children.push_back(s());
      }
      streams_map.insert({key, std::move(children)});
      call_rescue(e, streams_map.find(key)->second);
    } else {
      VLOG(3) << "by() stream exists. ";
      call_rescue(e, it->second);
    }
  };
}

stream_t where(const predicate_t& predicate, const children_t& children,
               const children_t& else_children)
{
  return [=](e_t e) {
    if (predicate(e)) {
      call_rescue(e, children);
    } else {
      call_rescue(e, else_children);
    }
  };
}

stream_t rate(const int interval, const children_t& children) {
  std::shared_ptr<double> rate(std::make_shared<double>(0));
  g_scheduler.add_periodic_task(
     [=]() mutable
      {
        VLOG(3) << "rate-timer()";
        Event e;
        e.set_metric_f(*rate / interval);
        e.set_time(time(0));
        *rate = 0;
        VLOG(3) << "rate-timer() value: " << e.metric_f();
        call_rescue(e, children);
      },
      interval
  );

  return [=](e_t e) mutable {
    VLOG(3) << "rate() rate += e.metric";
    (*rate) += metric_to_double(e);
  };
}

stream_t changed_state(std::string initial, const children_t& children) {
  std::string last_state(initial);

  return [=](e_t e) mutable {
    VLOG(3) << "changed_state() last_state: "
            << last_state << " new state " << e.state();
    if (last_state != e.state()) {
      VLOG(3) << "changed_state() state change";
      last_state.assign(e.state());
      call_rescue(e, children);
    }
  };
}

stream_t tagged_any(const tags_t& tags, const children_t& children) {
  return [=](e_t e) {
    VLOG(3) << "tagged_any()";
    if (tagged_any_(e, tags)) {
      VLOG(3) << "tagged_any() match";
      call_rescue(e, children);
    }
  };
}

stream_t tagged_all(const tags_t& tags, const children_t& children) {
  return [=](e_t e) {
    VLOG(3) << "tagged_all()";
    if (tagged_all_(e, tags)) {
      VLOG(3) << "tagged_all() match";
      call_rescue(e, children);
    }
  };
}

bool tagged_any_(e_t e, const tags_t& tags) {
  for (auto &tag: tags) {
    if (tag_exists(e, tag)) {
      return true;
    }
  }
  return false;
}

bool tagged_all_(e_t e, const tags_t& tags) {
  for (auto &tag: tags) {
    if (!tag_exists(e, tag)) {
      return false;
    }
  }
  return true;
}

stream_t send_index(class index& idx) {
  return [&](e_t e) {
    if (e.state() != "expired") {
      idx.add_event(e);
    }
  };
}

void streams::add_stream(stream_t stream) {
  VLOG(3) << "adding stream";
  streams_.push_back(stream);
}

void streams::process_message(const Msg& message) {
  VLOG(3) << "process message. num of streams " << streams_.size();
  unsigned long int sec = time(0);
  for (int i = 0; i < message.events_size(); i++) {
    const Event &event = message.events(i);
    if (!event.has_time()) {
      Event nevent(event);
      nevent.set_time(sec);
      push_event(std::move(nevent));
    } else {
      push_event(event);
    }
  }
}

void streams::push_event(const Event& e) {
  for (auto& s: streams_) {
    s(e);
  }
}

<|endoftext|>


<commit_before>/*=============================================================================
	Copyright (c) 2012-2013 Richard Otis

    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/

// declaration for CompositionSet class

#ifndef COMPOSITIONSET_INCLUDED
#define COMPOSITIONSET_INCLUDED

#include "libgibbs/include/models.hpp"
#include "libgibbs/include/constraint.hpp"
#include "libgibbs/include/optimizer/ast_set.hpp"
#include "libgibbs/include/conditions.hpp"
#include "libgibbs/include/utils/ast_caching.hpp"
#include "libtdb/include/structure.hpp"
#include <memory>
#include <set>
#include <list>
#include <boost/bimap.hpp>
#include <boost/numeric/ublas/symmetric.hpp>
#include <boost/numeric/ublas/vector.hpp>

// A CompositionSet works with libtdb's Phase class
// Its purpose is to handle the optimizer's specific configuration for the given conditions and models
// Multiple CompositionSets of the same Phase can be created to handle miscibility gaps
class CompositionSet {
public:
	double evaluate_objective(evalconditions const&, boost::bimap<std::string, int> const &, double* const) const;
	double evaluate_objective(evalconditions const &, std::map<std::string,double> const &) const;
	std::map<int,double> evaluate_objective_gradient(
			evalconditions const&, boost::bimap<std::string, int> const &, double* const) const;
	std::map<int,double> evaluate_objective_gradient(
			evalconditions const &, std::map<std::string,double> const &) const;
	std::map<std::list<int>,double> evaluate_objective_hessian(
			evalconditions const&, boost::bimap<std::string, int> const &, double* const) const;
	boost::numeric::ublas::symmetric_matrix<double,boost::numeric::ublas::lower> evaluate_objective_hessian_matrix(
				evalconditions const& conditions,
				boost::bimap<std::string, int> const &main_indices,
				std::vector<double> const &x) const;
	std::set<std::list<int>> hessian_sparsity_structure(boost::bimap<std::string, int> const &) const;
	std::vector<double> make_feasible_point(sublattice_set const &sublset, std::vector<double> const &x) const;
	std::string name() const { return cset_name; }
	// make CompositionSet from existing Phase
	CompositionSet(
			const Phase &phaseobj,
			const parameter_set &pset,
			const sublattice_set &sublset,
			boost::bimap<std::string, int> const &main_indices);

	CompositionSet() { }

	CompositionSet(CompositionSet &&other) {
		cset_name = std::move(other.cset_name);
		models = std::move(other.models);
		jac_g_trees = std::move(other.jac_g_trees);
		hessian_data = std::move(other.hessian_data);
		tree_data = std::move(other.tree_data);
		first_derivatives = std::move(other.first_derivatives);
		symbols = std::move(other.symbols);
		cm = std::move(other.cm);
		phase_indices = std::move(other.phase_indices);
		constraint_null_space_matrix = std::move(other.constraint_null_space_matrix);
		constraint_particular_solution = std::move(other.constraint_particular_solution);
	}
	CompositionSet& operator=(CompositionSet &&other) {
		cset_name = std::move(other.cset_name);
		models = std::move(other.models);
		jac_g_trees = std::move(other.jac_g_trees);
		hessian_data = std::move(other.hessian_data);
		tree_data = std::move(other.tree_data);
		first_derivatives = std::move(other.first_derivatives);
		symbols = std::move(other.symbols);
		cm = std::move(other.cm);
		phase_indices = std::move(other.phase_indices);
		constraint_null_space_matrix = std::move(other.constraint_null_space_matrix);
		constraint_particular_solution = std::move(other.constraint_particular_solution);
	}
	const std::vector<jacobian_entry>& get_jacobian() const { return jac_g_trees; };
	const std::vector<Constraint>& get_constraints() const { return cm.constraints; };
	const boost::bimap<std::string, int>& get_variable_map() const { return phase_indices; };
	const boost::numeric::ublas::matrix<double>& get_constraint_null_space_matrix() const { return constraint_null_space_matrix; };
	const ASTSymbolMap& get_symbols() const { return symbols; };
	CompositionSet(const CompositionSet &) = delete;
	CompositionSet& operator=(const CompositionSet &) = delete;
private:
	std::string cset_name;
	std::map<std::string,std::unique_ptr<EnergyModel>> models;
	std::map<int,boost::spirit::utree> first_derivatives;
	boost::bimap<std::string, int> phase_indices;
	std::vector<jacobian_entry> jac_g_trees;
	hessian_set hessian_data;
	ast_set tree_data;
	ASTSymbolMap symbols; // maps special symbols to ASTs and their derivatives
	ConstraintManager cm; // handles constraints internal to the phase, e.g., site fraction balances
	void build_constraint_basis_matrices(sublattice_set const &sublset);
	boost::numeric::ublas::matrix<double> constraint_null_space_matrix;
	boost::numeric::ublas::vector<double> constraint_particular_solution;
};

#endif
<commit_msg>Added constraint_extents member<commit_after>/*=============================================================================
	Copyright (c) 2012-2014 Richard Otis

    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/

// declaration for CompositionSet class

#ifndef COMPOSITIONSET_INCLUDED
#define COMPOSITIONSET_INCLUDED

#include "libgibbs/include/models.hpp"
#include "libgibbs/include/constraint.hpp"
#include "libgibbs/include/optimizer/ast_set.hpp"
#include "libgibbs/include/conditions.hpp"
#include "libgibbs/include/utils/ast_caching.hpp"
#include "libtdb/include/structure.hpp"
#include <boost/bimap.hpp>
#include <boost/numeric/ublas/symmetric.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <memory>
#include <set>
#include <list>
#include <vector>
#include <utility>

// A CompositionSet works with libtdb's Phase class
// Its purpose is to handle the optimizer's specific configuration for the given conditions and models
// Multiple CompositionSets of the same Phase can be created to handle miscibility gaps
class CompositionSet {
public:
	double evaluate_objective(evalconditions const&, boost::bimap<std::string, int> const &, double* const) const;
	double evaluate_objective(evalconditions const &, std::map<std::string,double> const &) const;
	std::map<int,double> evaluate_objective_gradient(
			evalconditions const&, boost::bimap<std::string, int> const &, double* const) const;
	std::map<int,double> evaluate_objective_gradient(
			evalconditions const &, std::map<std::string,double> const &) const;
	std::map<std::list<int>,double> evaluate_objective_hessian(
			evalconditions const&, boost::bimap<std::string, int> const &, double* const) const;
	boost::numeric::ublas::symmetric_matrix<double,boost::numeric::ublas::lower> evaluate_objective_hessian_matrix(
				evalconditions const& conditions,
				boost::bimap<std::string, int> const &main_indices,
				std::vector<double> const &x) const;
	std::set<std::list<int>> hessian_sparsity_structure(boost::bimap<std::string, int> const &) const;
	std::vector<double> make_feasible_point(sublattice_set const &sublset, std::vector<double> const &x) const;
	std::string name() const { return cset_name; }
	// make CompositionSet from existing Phase
	CompositionSet(
			const Phase &phaseobj,
			const parameter_set &pset,
			const sublattice_set &sublset,
			boost::bimap<std::string, int> const &main_indices);

	CompositionSet() { }

	CompositionSet(CompositionSet &&other) {
		cset_name = std::move(other.cset_name);
		models = std::move(other.models);
		jac_g_trees = std::move(other.jac_g_trees);
		hessian_data = std::move(other.hessian_data);
		tree_data = std::move(other.tree_data);
		first_derivatives = std::move(other.first_derivatives);
		symbols = std::move(other.symbols);
		cm = std::move(other.cm);
		phase_indices = std::move(other.phase_indices);
		constraint_null_space_matrix = std::move(other.constraint_null_space_matrix);
		constraint_particular_solution = std::move(other.constraint_particular_solution);
		constraint_extents = std::move(other.constraint_extents);
	}
	CompositionSet& operator=(CompositionSet &&other) {
		cset_name = std::move(other.cset_name);
		models = std::move(other.models);
		jac_g_trees = std::move(other.jac_g_trees);
		hessian_data = std::move(other.hessian_data);
		tree_data = std::move(other.tree_data);
		first_derivatives = std::move(other.first_derivatives);
		symbols = std::move(other.symbols);
		cm = std::move(other.cm);
		phase_indices = std::move(other.phase_indices);
		constraint_null_space_matrix = std::move(other.constraint_null_space_matrix);
		constraint_particular_solution = std::move(other.constraint_particular_solution);
		constraint_extents = std::move(other.constraint_extents);
	}
	const std::vector<jacobian_entry>& get_jacobian() const { return jac_g_trees; };
	const std::vector<Constraint>& get_constraints() const { return cm.constraints; };
	const boost::bimap<std::string, int>& get_variable_map() const { return phase_indices; };
	const boost::numeric::ublas::matrix<double>& get_constraint_null_space_matrix() const { return constraint_null_space_matrix; };
	const std::vector<std::pair<double,double> >& get_constraint_extents() const { return constraint_extents; };
	const ASTSymbolMap& get_symbols() const { return symbols; };
	CompositionSet(const CompositionSet &) = delete;
	CompositionSet& operator=(const CompositionSet &) = delete;
private:
	std::string cset_name;
	std::map<std::string,std::unique_ptr<EnergyModel>> models;
	std::map<int,boost::spirit::utree> first_derivatives;
	boost::bimap<std::string, int> phase_indices;
	std::vector<jacobian_entry> jac_g_trees;
	hessian_set hessian_data;
	ast_set tree_data;
	ASTSymbolMap symbols; // maps special symbols to ASTs and their derivatives
	ConstraintManager cm; // handles constraints internal to the phase, e.g., site fraction balances
	void build_constraint_basis_matrices(sublattice_set const &sublset);
	boost::numeric::ublas::matrix<double> constraint_null_space_matrix;
	boost::numeric::ublas::vector<double> constraint_particular_solution;
	std::vector<std::pair<double,double> > constraint_extents;
};

#endif
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015 Cryptonomex, Inc., and contributors.
 *
 * The MIT License
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
#include <algorithm>
#include <graphene/protocol/fee_schedule.hpp>

#include <fc/io/raw.hpp>

#define MAX_FEE_STABILIZATION_ITERATION 4

namespace graphene { namespace protocol {

   fee_schedule::fee_schedule()
   {
   }

   fee_schedule fee_schedule::get_default()
   {
      fee_schedule result;
      for( int i = 0; i < fee_parameters().count(); ++i )
      {
         fee_parameters x; x.set_which(i);
         result.parameters.insert(x);
      }
      return result;
   }

   struct set_fee_visitor
   {
      typedef void result_type;
      asset _fee;

      set_fee_visitor( asset f ):_fee(f){}

      template<typename OpType>
      void operator()( OpType& op )const
      {
         op.fee = _fee;
      }
   };

   struct zero_fee_visitor
   {
      typedef void result_type;

      template<typename ParamType>
      result_type operator()(  ParamType& op )const
      {
         memset( (char*)&op, 0, sizeof(op) );
      }
   };

   void fee_schedule::zero_all_fees()
   {
      *this = get_default();
      for( fee_parameters& i : parameters )
         i.visit( zero_fee_visitor() );
      this->scale = 0;
   }

   asset fee_schedule::set_fee( operation& op, const price& core_exchange_rate )const
   {
      auto f = calculate_fee( op, core_exchange_rate );
      auto f_max = f;
      for( int i=0; i<MAX_FEE_STABILIZATION_ITERATION; i++ )
      {
         op.visit( set_fee_visitor( f_max ) );
         auto f2 = calculate_fee( op, core_exchange_rate );
         if( f == f2 )
            break;
         f_max = std::max( f_max, f2 );
         f = f2;
         if( i == 0 )
         {
            // no need for warnings on later iterations
            wlog( "set_fee requires multiple iterations to stabilize with core_exchange_rate ${p} on operation ${op}",
               ("p", core_exchange_rate) ("op", op) );
         }
      }
      return f_max;
   }

   void chain_parameters::validate()const
   {
      get_current_fees().validate();
      FC_ASSERT( reserve_percent_of_fee <= GRAPHENE_100_PERCENT );
      FC_ASSERT( network_percent_of_fee <= GRAPHENE_100_PERCENT );
      FC_ASSERT( lifetime_referrer_percent_of_fee <= GRAPHENE_100_PERCENT );
      FC_ASSERT( network_percent_of_fee + lifetime_referrer_percent_of_fee <= GRAPHENE_100_PERCENT );

      FC_ASSERT( block_interval >= GRAPHENE_MIN_BLOCK_INTERVAL );
      FC_ASSERT( block_interval <= GRAPHENE_MAX_BLOCK_INTERVAL );
      FC_ASSERT( block_interval > 0 );
      FC_ASSERT( maintenance_interval > block_interval,
                 "Maintenance interval must be longer than block interval" );
      FC_ASSERT( maintenance_interval % block_interval == 0,
                 "Maintenance interval must be a multiple of block interval" );
      FC_ASSERT( maximum_transaction_size >= GRAPHENE_MIN_TRANSACTION_SIZE_LIMIT,
                 "Transaction size limit is too low" );
      FC_ASSERT( maximum_block_size >= GRAPHENE_MIN_BLOCK_SIZE_LIMIT,
                 "Block size limit is too low" );
      FC_ASSERT( maximum_time_until_expiration > block_interval,
                 "Maximum transaction expiration time must be greater than a block interval" );
      FC_ASSERT( maximum_proposal_lifetime - committee_proposal_review_period > block_interval,
                 "Committee proposal review period must be less than the maximum proposal lifetime" );
   }

} } // graphene::protocol
<commit_msg>Fix compiler warnings<commit_after>/*
 * Copyright (c) 2015 Cryptonomex, Inc., and contributors.
 *
 * The MIT License
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
#include <algorithm>
#include <graphene/protocol/fee_schedule.hpp>

#include <fc/io/raw.hpp>

#define MAX_FEE_STABILIZATION_ITERATION 4

namespace graphene { namespace protocol {

   fee_schedule::fee_schedule()
   {
   }

   fee_schedule fee_schedule::get_default()
   {
      fee_schedule result;
      for( size_t i = 0; i < fee_parameters().count(); ++i )
      {
         fee_parameters x; x.set_which(i);
         result.parameters.insert(x);
      }
      return result;
   }

   struct set_fee_visitor
   {
      typedef void result_type;
      asset _fee;

      set_fee_visitor( asset f ):_fee(f){}

      template<typename OpType>
      void operator()( OpType& op )const
      {
         op.fee = _fee;
      }
   };

   struct zero_fee_visitor
   {
      typedef void result_type;

      template<typename ParamType>
      result_type operator()(  ParamType& op )const
      {
         memset( (char*)&op, 0, sizeof(op) );
      }
   };

   void fee_schedule::zero_all_fees()
   {
      *this = get_default();
      for( fee_parameters& i : parameters )
         i.visit( zero_fee_visitor() );
      this->scale = 0;
   }

   asset fee_schedule::set_fee( operation& op, const price& core_exchange_rate )const
   {
      auto f = calculate_fee( op, core_exchange_rate );
      auto f_max = f;
      for( size_t i=0; i<MAX_FEE_STABILIZATION_ITERATION; i++ )
      {
         op.visit( set_fee_visitor( f_max ) );
         auto f2 = calculate_fee( op, core_exchange_rate );
         if( f == f2 )
            break;
         f_max = std::max( f_max, f2 );
         f = f2;
         if( i == 0 )
         {
            // no need for warnings on later iterations
            wlog( "set_fee requires multiple iterations to stabilize with core_exchange_rate ${p} on operation ${op}",
               ("p", core_exchange_rate) ("op", op) );
         }
      }
      return f_max;
   }

   void chain_parameters::validate()const
   {
      get_current_fees().validate();
      FC_ASSERT( reserve_percent_of_fee <= GRAPHENE_100_PERCENT );
      FC_ASSERT( network_percent_of_fee <= GRAPHENE_100_PERCENT );
      FC_ASSERT( lifetime_referrer_percent_of_fee <= GRAPHENE_100_PERCENT );
      FC_ASSERT( network_percent_of_fee + lifetime_referrer_percent_of_fee <= GRAPHENE_100_PERCENT );

      FC_ASSERT( block_interval >= GRAPHENE_MIN_BLOCK_INTERVAL );
      FC_ASSERT( block_interval <= GRAPHENE_MAX_BLOCK_INTERVAL );
      FC_ASSERT( block_interval > 0 );
      FC_ASSERT( maintenance_interval > block_interval,
                 "Maintenance interval must be longer than block interval" );
      FC_ASSERT( maintenance_interval % block_interval == 0,
                 "Maintenance interval must be a multiple of block interval" );
      FC_ASSERT( maximum_transaction_size >= GRAPHENE_MIN_TRANSACTION_SIZE_LIMIT,
                 "Transaction size limit is too low" );
      FC_ASSERT( maximum_block_size >= GRAPHENE_MIN_BLOCK_SIZE_LIMIT,
                 "Block size limit is too low" );
      FC_ASSERT( maximum_time_until_expiration > block_interval,
                 "Maximum transaction expiration time must be greater than a block interval" );
      FC_ASSERT( maximum_proposal_lifetime - committee_proposal_review_period > block_interval,
                 "Committee proposal review period must be less than the maximum proposal lifetime" );
   }

} } // graphene::protocol
<|endoftext|>


<commit_before>/*
 *  File: tileSet.cpp
 *
 *  Description:  Implements TileSet class
 */

#include <tileSet.hpp>

// No params constructor method for TileSet
TileSet::TileSet() {

}

// Constructor method for TileSet
// Recivies the integer w, that represents the width of a tile
// Recivies the integer h, that represents the height of a tile
// Recivies the string file, that represents file path
TileSet::TileSet(int w, int h, string file) {
	Load(w, h, file);
}

// Loads the tileset from the file
// Recivies the integer w, that represents the width of a tile
// Recivies the integer h, that represents the height of a tile
// Recivies the string file, that represents file path
void TileSet::Load(int  w, int h, string file) {
	// Attributes the value of the width and height of a tile
	tileWidth = w;
	tileHeight = h;

	// Opens the file with the tileSet
	tileSet.Open(file);

	// Defines the numbers of rows and columns of the tileSet
	rows = tileSet.GetHeight()/tileHeight;
	columns = tileSet.GetWidth()/tileWidth;
}

// Render the tileSet
void TileSet::Render(unsigned int index,float x,float y, float extScale) {
	if ((int)index<(rows*columns)) {
		tileSet.SetClip(tileWidth*(index%columns),(tileHeight*(index/columns)),
											tileWidth,tileHeight);
		tileSet.Render(x,y,0,extScale);
	}
	// TODO: else (do nothing)
}

// Returns the width of the TileSet
int TileSet::GetWidth() {
	return tileWidth;
}

// Returns the height of the TileSet
int TileSet::GetHeight() {
	return tileHeight;
}

// Returns the number of tiles in the tileSet
int TileSet::GetTileCount() {
	return rows*columns;
}
<commit_msg>Refactories commentaries technique at file tileSet.cpp<commit_after>/*!
*  \file File tileSet.cpp
*  \brief Implementation of the class TileSet
*
*  Auxiliary documentation
*  \sa tileSet.hpp
*/
#include <tileSet.hpp>

/*!
	@class TileSet
	@brief This class provides the tile sets to the game
*/

//! A constructor.
    /*!
    This is a empty constructor method of TileSet class
    */
TileSet::TileSet() {

}

//! A constructor.
    /*!
    *	This is a constructor method of TileSet class
		*	\param w
		*	\brief A positive integer, that represents width of a tile
		*	\param h
		*	\brief A positive integer, that represents height of a tile
		*	\param file
		*	\brief A string, that represents path of the file with the tile set
    */
TileSet::TileSet(int w, int h, string file) {
	Load(w, h, file);
}

/*!
	@fn void TileSet::Load(int  w, int h, string file)
	@brief Method that loads the tile set from the file
	@param w
	@brief A positive integer, that represents width of a tile
	@param h
	@brief A positive integer, that represents height of a tile
	@param file
	@brief A string, that represents path of the file with the tile set
	@return The execution of this method returns no value
*/
void TileSet::Load(int  w, int h, string file) {
	//! Attributes the value of the width and height of a tile
	tileWidth = w;
	tileHeight = h;

	//! Opens the file with the tile set
	tileSet.Open(file);

	//! Defines the numbers of rows and columns of the tile set
	rows = tileSet.GetHeight() / tileHeight;
	columns = tileSet.GetWidth() / tileWidth;
}

/*!
	@fn void TileSet::Render(unsigned int index, float x, float y, float extScale)
	@brief Method that renders the tile set
	@param index
	@brief A unsigned integer
	@param x
	@brief A float
	@param y
	@brief A float
	@param extScale
	@brief A float
	@return The execution of this method returns no value
	@warning Method that requires review of comment
*/
void TileSet::Render(unsigned int index, float x, float y, float extScale) {
	//! Checks if the number of tiles is bigger that the index
	if ((int)index < (rows * columns)) {
		tileSet.SetClip(tileWidth * (index % columns),
										(tileHeight * (index / columns)), tileWidth, tileHeight);
		tileSet.Render(x, y, 0, extScale);
	}
	//! \warning else (do nothing)
}

/*!
	@fn int TileSet::GetWidth()
	@brief A getter of the attribute tileWidth
	@return A positive integer, that represents the width of a tile
*/
int TileSet::GetWidth() {
	return tileWidth;
}

/*!
	@fn int TileSet::GetHeight()
	@brief A getter of the attribute tileHeight
	@return A positive integer, that represents the height of a tile
*/
int TileSet::GetHeight() {
	return tileHeight;
}

/*!
	@fn int TileSet::GetTileCount()
	@brief Method that returns the number of tiles in the tile set
	@return A positive integer, that number of tiles in the tile set
*/
int TileSet::GetTileCount() {
	return rows*columns;
}
<|endoftext|>


<commit_before>/* Copyright 2007-2015 QReal Research Group
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. */

#include "generatorBase/robotsGeneratorPluginBase.h"

#include <QtCore/QDateTime>

#include <qrkernel/platformInfo.h>
#include <qrutils/inFile.h>
#include <qrutils/nameNormalizer.h>
#include <qrutils/parserErrorReporter.h>
#include <qrgui/textEditor/qscintillaTextEdit.h>

using namespace generatorBase;
using namespace qReal;
using namespace utils;

/// If file info creation and modification timestamps differ less than on this value it is considered
/// that file was created and filled at the same time.
const int maxTimestampsDifference = 3000;

RobotsGeneratorPluginBase::RobotsGeneratorPluginBase()
{
}

RobotsGeneratorPluginBase::~RobotsGeneratorPluginBase()
{
}

QString RobotsGeneratorPluginBase::defaultFilePath(const QString &projectName) const
{
	return projectName;
}

QString RobotsGeneratorPluginBase::generatorName() const
{
	return QString();
}

QString RobotsGeneratorPluginBase::defaultProjectName() const
{
	const QString filePath = mProjectManager->saveFilePath();
	return filePath.isEmpty() ? "example" : QFileInfo(filePath).completeBaseName();
}

bool RobotsGeneratorPluginBase::canGenerateTo(const QString &project)
{
	const QFileInfo fileInfo = generationTarget(project);
	const int difference = fileInfo.lastModified().toMSecsSinceEpoch() - fileInfo.created().toMSecsSinceEpoch();
	return !fileInfo.exists() || difference < maxTimestampsDifference;
}

void RobotsGeneratorPluginBase::onCurrentRobotModelChanged(kitBase::robotModel::RobotModelInterface &model)
{
	if (robotModels().count() == 1) {
		kitBase::robotModel::RobotModelInterface * const ourModel = robotModels()[0];;
		for (const ActionInfo &action : customActions()) {
			if (action.isAction()) {
				action.action()->setVisible(ourModel == &model);
			} else {
				action.menu()->setVisible(ourModel == &model);
			}
		}
	}
}

void RobotsGeneratorPluginBase::onCurrentDiagramChanged(const TabInfo &info)
{
	const bool enabled = info.type() == TabInfo::TabType::code || info.type() == TabInfo::TabType::editor;
	for (const ActionInfo &action : customActions()) {
		if (action.isAction()) {
			action.action()->setEnabled(enabled);
		} else {
			action.menu()->setEnabled(enabled);
		}
	}
}

QFileInfo RobotsGeneratorPluginBase::generationTarget(const QString &pathFromRoot) const
{
	return QFileInfo(PlatformInfo::invariantSettingsPath("pathToGeneratorRoot") + "/" + defaultFilePath(pathFromRoot));
}

QFileInfo RobotsGeneratorPluginBase::srcPath()
{
	const Id &activeDiagram = mMainWindowInterface->activeDiagram();

	int exampleNumber = 0;
	QString projectName;

	do {
		projectName = NameNormalizer::normalizeStrongly(defaultProjectName(), false)
				+ (exampleNumber > 0 ? QString::number(exampleNumber) : "");
		++exampleNumber;
	} while (!canGenerateTo(projectName));

	QFileInfo fileInfo = generationTarget(projectName);
	const QList<QFileInfo> pathsList = mCodePath.values(activeDiagram);

	if (!pathsList.isEmpty()) {
		for (const QFileInfo &path : pathsList) {
			if (mTextManager->isDefaultPath(path.absoluteFilePath())
				&& !mTextManager->isModifiedEver(path.absoluteFilePath())
				&& !mTextManager->generatorName(path.absoluteFilePath()).compare(generatorName()))
			{
				fileInfo = path;
				break;
			}
		}
	}

	return fileInfo;
}

QFileInfo RobotsGeneratorPluginBase::generateCodeForProcessing()
{
	QFileInfo fileInfo;
	const Id &activeDiagram = mMainWindowInterface->activeDiagram();

	if (!activeDiagram.isNull()) {
		if (generateCode(false)) {
			for (const QFileInfo &path : mCodePath.values(activeDiagram)) {
				if (mTextManager->isDefaultPath(path.absoluteFilePath())
					&& (!mTextManager->isModifiedEver(path.absoluteFilePath()))
					&& !mTextManager->generatorName(path.absoluteFilePath()).compare(generatorName()))
				{
					fileInfo = path;
					break;
				}
			}
		} else {
			return QFileInfo();
		}
	} else if (auto code = dynamic_cast<text::QScintillaTextEdit *>(mMainWindowInterface->currentTab())) {
		fileInfo = QFileInfo(mTextManager->path(code));
		mTextManager->saveText(false);
	}

	return fileInfo;
}

void RobotsGeneratorPluginBase::init(const kitBase::KitPluginConfigurator &configurator)
{
	mProjectManager = &configurator.qRealConfigurator().projectManager();
	mSystemEvents = &configurator.qRealConfigurator().systemEvents();
	mTextManager = &configurator.qRealConfigurator().textManager();

	mMainWindowInterface = &configurator.qRealConfigurator().mainWindowInterpretersInterface();
	mRepo = dynamic_cast<const qrRepo::RepoApi *>(&configurator.qRealConfigurator().logicalModelApi().logicalRepoApi());
	mProjectManager = &configurator.qRealConfigurator().projectManager();
	mRobotModelManager = &configurator.robotModelManager();
	mTextLanguage = &configurator.textLanguage();

	mParserErrorReporter.reset(new ParserErrorReporter(*mTextLanguage, *mMainWindowInterface->errorReporter()
			, configurator.qRealConfigurator().logicalModelApi().editorManagerInterface()));

	connect(mSystemEvents, SIGNAL(codePathChanged(qReal::Id, QFileInfo, QFileInfo))
			, this, SLOT(regenerateCode(qReal::Id, QFileInfo, QFileInfo)));
	connect(mSystemEvents, SIGNAL(newCodeAppeared(qReal::Id, QFileInfo)), this, SLOT(addNewCode(qReal::Id, QFileInfo)));
	connect(mSystemEvents, SIGNAL(diagramClosed(qReal::Id)), this, SLOT(removeDiagram(qReal::Id)));
	connect(mSystemEvents, SIGNAL(codeTabClosed(QFileInfo)), this, SLOT(removeCode(QFileInfo)));

	connect(mRobotModelManager, &kitBase::robotModel::RobotModelManagerInterface::robotModelChanged
			, this, &RobotsGeneratorPluginBase::onCurrentRobotModelChanged);
	connect(mSystemEvents, &SystemEvents::activeTabChanged, this, &RobotsGeneratorPluginBase::onCurrentDiagramChanged);
}

QString RobotsGeneratorPluginBase::friendlyKitName() const
{
	// Kit friendly name is already defined in interpreter kit plugins.
	return QString();
}

bool RobotsGeneratorPluginBase::generateCode(bool openTab)
{
	mProjectManager->save();
	/// @todo: clearErrors() and clear() are absolutely different methods without documentation - wtf?
	mMainWindowInterface->errorReporter()->clearErrors();
	mMainWindowInterface->errorReporter()->clear();

	MasterGeneratorBase * const generator = masterGenerator();
	const QFileInfo path = srcPath();

	generator->initialize();
	generator->setProjectDir(path);

	const QString generatedSrcPath = generator->generate(language().indent());

	if (mMainWindowInterface->errorReporter()->wereErrors()) {
		delete generator;
		return false;
	}

	const Id activeDiagram = mMainWindowInterface->activeDiagram();

	const QString generatedCode = utils::InFile::readAll(generatedSrcPath);
	if (!generatedCode.isEmpty()) {
		mTextManager->showInTextEditor(path, generatorName(), language());
	}

	if (!openTab) {
		mMainWindowInterface->activateItemOrDiagram(activeDiagram);
	}

	delete generator;
	return true;
}

void RobotsGeneratorPluginBase::regenerateCode(const qReal::Id &diagram
		, const QFileInfo &oldFileInfo
		, const QFileInfo &newFileInfo)
{
	if (!oldFileInfo.completeSuffix().compare(language().extension)) {
		mCodePath.remove(diagram, oldFileInfo);
		mCodePath.insert(diagram, newFileInfo);
		regenerateExtraFiles(newFileInfo);
	}
}

void RobotsGeneratorPluginBase::addNewCode(const Id &diagram, const QFileInfo &fileInfo)
{
	mCodePath.insert(diagram, fileInfo);
}

void RobotsGeneratorPluginBase::removeDiagram(const qReal::Id &diagram)
{
	mCodePath.remove(diagram);
}

void RobotsGeneratorPluginBase::removeCode(const QFileInfo &fileInfo)
{
	const Id &diagram = mCodePath.key(fileInfo);
	mCodePath.remove(diagram, fileInfo);
}
<commit_msg>Fix redundant semicolon<commit_after>/* Copyright 2007-2015 QReal Research Group
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. */

#include "generatorBase/robotsGeneratorPluginBase.h"

#include <QtCore/QDateTime>

#include <qrkernel/platformInfo.h>
#include <qrutils/inFile.h>
#include <qrutils/nameNormalizer.h>
#include <qrutils/parserErrorReporter.h>
#include <qrgui/textEditor/qscintillaTextEdit.h>

using namespace generatorBase;
using namespace qReal;
using namespace utils;

/// If file info creation and modification timestamps differ less than on this value it is considered
/// that file was created and filled at the same time.
const int maxTimestampsDifference = 3000;

RobotsGeneratorPluginBase::RobotsGeneratorPluginBase()
{
}

RobotsGeneratorPluginBase::~RobotsGeneratorPluginBase()
{
}

QString RobotsGeneratorPluginBase::defaultFilePath(const QString &projectName) const
{
	return projectName;
}

QString RobotsGeneratorPluginBase::generatorName() const
{
	return QString();
}

QString RobotsGeneratorPluginBase::defaultProjectName() const
{
	const QString filePath = mProjectManager->saveFilePath();
	return filePath.isEmpty() ? "example" : QFileInfo(filePath).completeBaseName();
}

bool RobotsGeneratorPluginBase::canGenerateTo(const QString &project)
{
	const QFileInfo fileInfo = generationTarget(project);
	const int difference = fileInfo.lastModified().toMSecsSinceEpoch() - fileInfo.created().toMSecsSinceEpoch();
	return !fileInfo.exists() || difference < maxTimestampsDifference;
}

void RobotsGeneratorPluginBase::onCurrentRobotModelChanged(kitBase::robotModel::RobotModelInterface &model)
{
	if (robotModels().count() == 1) {
		kitBase::robotModel::RobotModelInterface * const ourModel = robotModels()[0];
		for (const ActionInfo &action : customActions()) {
			if (action.isAction()) {
				action.action()->setVisible(ourModel == &model);
			} else {
				action.menu()->setVisible(ourModel == &model);
			}
		}
	}
}

void RobotsGeneratorPluginBase::onCurrentDiagramChanged(const TabInfo &info)
{
	const bool enabled = info.type() == TabInfo::TabType::code || info.type() == TabInfo::TabType::editor;
	for (const ActionInfo &action : customActions()) {
		if (action.isAction()) {
			action.action()->setEnabled(enabled);
		} else {
			action.menu()->setEnabled(enabled);
		}
	}
}

QFileInfo RobotsGeneratorPluginBase::generationTarget(const QString &pathFromRoot) const
{
	return QFileInfo(PlatformInfo::invariantSettingsPath("pathToGeneratorRoot") + "/" + defaultFilePath(pathFromRoot));
}

QFileInfo RobotsGeneratorPluginBase::srcPath()
{
	const Id &activeDiagram = mMainWindowInterface->activeDiagram();

	int exampleNumber = 0;
	QString projectName;

	do {
		projectName = NameNormalizer::normalizeStrongly(defaultProjectName(), false)
				+ (exampleNumber > 0 ? QString::number(exampleNumber) : "");
		++exampleNumber;
	} while (!canGenerateTo(projectName));

	QFileInfo fileInfo = generationTarget(projectName);
	const QList<QFileInfo> pathsList = mCodePath.values(activeDiagram);

	if (!pathsList.isEmpty()) {
		for (const QFileInfo &path : pathsList) {
			if (mTextManager->isDefaultPath(path.absoluteFilePath())
				&& !mTextManager->isModifiedEver(path.absoluteFilePath())
				&& !mTextManager->generatorName(path.absoluteFilePath()).compare(generatorName()))
			{
				fileInfo = path;
				break;
			}
		}
	}

	return fileInfo;
}

QFileInfo RobotsGeneratorPluginBase::generateCodeForProcessing()
{
	QFileInfo fileInfo;
	const Id &activeDiagram = mMainWindowInterface->activeDiagram();

	if (!activeDiagram.isNull()) {
		if (generateCode(false)) {
			for (const QFileInfo &path : mCodePath.values(activeDiagram)) {
				if (mTextManager->isDefaultPath(path.absoluteFilePath())
					&& (!mTextManager->isModifiedEver(path.absoluteFilePath()))
					&& !mTextManager->generatorName(path.absoluteFilePath()).compare(generatorName()))
				{
					fileInfo = path;
					break;
				}
			}
		} else {
			return QFileInfo();
		}
	} else if (auto code = dynamic_cast<text::QScintillaTextEdit *>(mMainWindowInterface->currentTab())) {
		fileInfo = QFileInfo(mTextManager->path(code));
		mTextManager->saveText(false);
	}

	return fileInfo;
}

void RobotsGeneratorPluginBase::init(const kitBase::KitPluginConfigurator &configurator)
{
	mProjectManager = &configurator.qRealConfigurator().projectManager();
	mSystemEvents = &configurator.qRealConfigurator().systemEvents();
	mTextManager = &configurator.qRealConfigurator().textManager();

	mMainWindowInterface = &configurator.qRealConfigurator().mainWindowInterpretersInterface();
	mRepo = dynamic_cast<const qrRepo::RepoApi *>(&configurator.qRealConfigurator().logicalModelApi().logicalRepoApi());
	mProjectManager = &configurator.qRealConfigurator().projectManager();
	mRobotModelManager = &configurator.robotModelManager();
	mTextLanguage = &configurator.textLanguage();

	mParserErrorReporter.reset(new ParserErrorReporter(*mTextLanguage, *mMainWindowInterface->errorReporter()
			, configurator.qRealConfigurator().logicalModelApi().editorManagerInterface()));

	connect(mSystemEvents, SIGNAL(codePathChanged(qReal::Id, QFileInfo, QFileInfo))
			, this, SLOT(regenerateCode(qReal::Id, QFileInfo, QFileInfo)));
	connect(mSystemEvents, SIGNAL(newCodeAppeared(qReal::Id, QFileInfo)), this, SLOT(addNewCode(qReal::Id, QFileInfo)));
	connect(mSystemEvents, SIGNAL(diagramClosed(qReal::Id)), this, SLOT(removeDiagram(qReal::Id)));
	connect(mSystemEvents, SIGNAL(codeTabClosed(QFileInfo)), this, SLOT(removeCode(QFileInfo)));

	connect(mRobotModelManager, &kitBase::robotModel::RobotModelManagerInterface::robotModelChanged
			, this, &RobotsGeneratorPluginBase::onCurrentRobotModelChanged);
	connect(mSystemEvents, &SystemEvents::activeTabChanged, this, &RobotsGeneratorPluginBase::onCurrentDiagramChanged);
}

QString RobotsGeneratorPluginBase::friendlyKitName() const
{
	// Kit friendly name is already defined in interpreter kit plugins.
	return QString();
}

bool RobotsGeneratorPluginBase::generateCode(bool openTab)
{
	mProjectManager->save();
	/// @todo: clearErrors() and clear() are absolutely different methods without documentation - wtf?
	mMainWindowInterface->errorReporter()->clearErrors();
	mMainWindowInterface->errorReporter()->clear();

	MasterGeneratorBase * const generator = masterGenerator();
	const QFileInfo path = srcPath();

	generator->initialize();
	generator->setProjectDir(path);

	const QString generatedSrcPath = generator->generate(language().indent());

	if (mMainWindowInterface->errorReporter()->wereErrors()) {
		delete generator;
		return false;
	}

	const Id activeDiagram = mMainWindowInterface->activeDiagram();

	const QString generatedCode = utils::InFile::readAll(generatedSrcPath);
	if (!generatedCode.isEmpty()) {
		mTextManager->showInTextEditor(path, generatorName(), language());
	}

	if (!openTab) {
		mMainWindowInterface->activateItemOrDiagram(activeDiagram);
	}

	delete generator;
	return true;
}

void RobotsGeneratorPluginBase::regenerateCode(const qReal::Id &diagram
		, const QFileInfo &oldFileInfo
		, const QFileInfo &newFileInfo)
{
	if (!oldFileInfo.completeSuffix().compare(language().extension)) {
		mCodePath.remove(diagram, oldFileInfo);
		mCodePath.insert(diagram, newFileInfo);
		regenerateExtraFiles(newFileInfo);
	}
}

void RobotsGeneratorPluginBase::addNewCode(const Id &diagram, const QFileInfo &fileInfo)
{
	mCodePath.insert(diagram, fileInfo);
}

void RobotsGeneratorPluginBase::removeDiagram(const qReal::Id &diagram)
{
	mCodePath.remove(diagram);
}

void RobotsGeneratorPluginBase::removeCode(const QFileInfo &fileInfo)
{
	const Id &diagram = mCodePath.key(fileInfo);
	mCodePath.remove(diagram, fileInfo);
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/workarounds/seq_workarounds.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2017,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file workarounds/seq_workarounds.C
/// @brief Workarounds for the SEQ logic blocks
/// Workarounds are very deivce specific, so there is no attempt to generalize
/// this code in any way.
///
// *HWP HWP Owner: Louis Stermole <stermole@us.ibm.com>
// *HWP HWP Backup: Stephen Glancy <sglancy@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: FSP:HB

#include <fapi2.H>
#include <p9_mc_scom_addresses.H>

#include <generic/memory/lib/utils/scom.H>
#include <lib/workarounds/seq_workarounds.H>

namespace mss
{

namespace workarounds
{

namespace seq
{

///
/// @brief ODT Config workaround
/// For Nimbus DD1, ODT2 and ODT3 bits are swapped in each of the PHY config registers
/// @param[in] i_target the fapi2 target of the port
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
/// @note This function is called during the phy scom init procedure, after the initfile is
/// processed.
///
fapi2::ReturnCode odt_config( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target )
{
    // skip the workaroud if attribute is not set
    if (! mss::chip_ec_feature_mss_odt_config(i_target) )
    {
        return fapi2::FAPI2_RC_SUCCESS;
    }

    FAPI_INF("Running ODT Config workaround on %s", mss::c_str(i_target));

    std::vector<fapi2::buffer<uint64_t>> l_read;

    static const std::vector<uint64_t> ODT_REGS =
    {
        MCA_DDRPHY_SEQ_ODT_RD_CONFIG0_P0, MCA_DDRPHY_SEQ_ODT_RD_CONFIG1_P0,
        MCA_DDRPHY_SEQ_ODT_WR_CONFIG0_P0, MCA_DDRPHY_SEQ_ODT_WR_CONFIG1_P0
    };

    FAPI_TRY(mss::scom_suckah(i_target, ODT_REGS, l_read));

    for (auto& l_data : l_read)
    {
        // Note these bit positions are the same in RD_CONFIG* and WR_CONFIG*
        constexpr uint64_t EVEN_RANK_ODT2 = 50;
        constexpr uint64_t EVEN_RANK_ODT3 = 51;
        constexpr uint64_t ODD_RANK_ODT2 = 58;
        constexpr uint64_t ODD_RANK_ODT3 = 59;

        bool l_odt2 = 0;
        bool l_odt3 = 0;

        // swap even rank ODT2 and ODT3
        l_odt2 = l_data.getBit<EVEN_RANK_ODT2>();
        l_odt3 = l_data.getBit<EVEN_RANK_ODT3>();
        l_data.writeBit<EVEN_RANK_ODT2>(l_odt3).writeBit<EVEN_RANK_ODT3>(l_odt2);
        // swap odd rank ODT2 and ODT3
        l_odt2 = l_data.getBit<ODD_RANK_ODT2>();
        l_odt3 = l_data.getBit<ODD_RANK_ODT3>();
        l_data.writeBit<ODD_RANK_ODT2>(l_odt3).writeBit<ODD_RANK_ODT3>(l_odt2);
    }

    FAPI_TRY(mss::scom_blastah(i_target, ODT_REGS, l_read));

fapi_try_exit:
    return fapi2::current_err;
}

} // close namespace seq
} // close namespace workarounds
} // close namespace mss
<commit_msg>Updates dramint training structure<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/workarounds/seq_workarounds.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2017,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file workarounds/seq_workarounds.C
/// @brief Workarounds for the SEQ logic blocks
/// Workarounds are very device specific, so there is no attempt to generalize
/// this code in any way.
///
// *HWP HWP Owner: Louis Stermole <stermole@us.ibm.com>
// *HWP HWP Backup: Stephen Glancy <sglancy@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: FSP:HB

#include <fapi2.H>
#include <p9_mc_scom_addresses.H>

#include <generic/memory/lib/utils/scom.H>
#include <lib/workarounds/seq_workarounds.H>

namespace mss
{

namespace workarounds
{

namespace seq
{

///
/// @brief ODT Config workaround
/// For Nimbus DD1, ODT2 and ODT3 bits are swapped in each of the PHY config registers
/// @param[in] i_target the fapi2 target of the port
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
/// @note This function is called during the phy scom init procedure, after the initfile is
/// processed.
///
fapi2::ReturnCode odt_config( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target )
{
    // skip the workaroud if attribute is not set
    if (! mss::chip_ec_feature_mss_odt_config(i_target) )
    {
        return fapi2::FAPI2_RC_SUCCESS;
    }

    FAPI_INF("Running ODT Config workaround on %s", mss::c_str(i_target));

    std::vector<fapi2::buffer<uint64_t>> l_read;

    static const std::vector<uint64_t> ODT_REGS =
    {
        MCA_DDRPHY_SEQ_ODT_RD_CONFIG0_P0, MCA_DDRPHY_SEQ_ODT_RD_CONFIG1_P0,
        MCA_DDRPHY_SEQ_ODT_WR_CONFIG0_P0, MCA_DDRPHY_SEQ_ODT_WR_CONFIG1_P0
    };

    FAPI_TRY(mss::scom_suckah(i_target, ODT_REGS, l_read));

    for (auto& l_data : l_read)
    {
        // Note these bit positions are the same in RD_CONFIG* and WR_CONFIG*
        constexpr uint64_t EVEN_RANK_ODT2 = 50;
        constexpr uint64_t EVEN_RANK_ODT3 = 51;
        constexpr uint64_t ODD_RANK_ODT2 = 58;
        constexpr uint64_t ODD_RANK_ODT3 = 59;

        bool l_odt2 = 0;
        bool l_odt3 = 0;

        // swap even rank ODT2 and ODT3
        l_odt2 = l_data.getBit<EVEN_RANK_ODT2>();
        l_odt3 = l_data.getBit<EVEN_RANK_ODT3>();
        l_data.writeBit<EVEN_RANK_ODT2>(l_odt3).writeBit<EVEN_RANK_ODT3>(l_odt2);
        // swap odd rank ODT2 and ODT3
        l_odt2 = l_data.getBit<ODD_RANK_ODT2>();
        l_odt3 = l_data.getBit<ODD_RANK_ODT3>();
        l_data.writeBit<ODD_RANK_ODT2>(l_odt3).writeBit<ODD_RANK_ODT3>(l_odt2);
    }

    FAPI_TRY(mss::scom_blastah(i_target, ODT_REGS, l_read));

fapi_try_exit:
    return fapi2::current_err;
}

} // close namespace seq
} // close namespace workarounds
} // close namespace mss
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: postuninstall.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: vg $ $Date: 2007-03-26 14:11:41 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#pragma warning(push, 1) /* disable warnings within system headers */
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <msiquery.h>
#pragma warning(pop)

#include <malloc.h>

#ifdef UNICODE
#define _UNICODE
#define _tstring    wstring
#else
#define _tstring    string
#endif
#include <tchar.h>
#include <string>

#if defined(_WIN32_WINNT) && !defined(__MINGW32__)
#error YES
#endif

#include <io.h>

static std::_tstring GetMsiProperty( MSIHANDLE handle, const std::_tstring& sProperty )
{
    std::_tstring   result;
    TCHAR   szDummy[1] = TEXT("");
    DWORD   nChars = 0;

    if ( MsiGetProperty( handle, sProperty.c_str(), szDummy, &nChars ) == ERROR_MORE_DATA )
    {
        DWORD nBytes = ++nChars * sizeof(TCHAR);
        LPTSTR buffer = reinterpret_cast<LPTSTR>(_alloca(nBytes));
        ZeroMemory( buffer, nBytes );
        MsiGetProperty(handle, sProperty.c_str(), buffer, &nChars);
        result = buffer;
    }

    return  result;
}

static BOOL ExecuteCommand( LPCTSTR lpCommand, BOOL bSync )
{
    BOOL                fSuccess = FALSE;
    STARTUPINFO         si;
    PROCESS_INFORMATION pi;

    ZeroMemory( &si, sizeof(si) );
    si.cb = sizeof(si);

    fSuccess = CreateProcess(
        NULL,
        (LPTSTR)lpCommand,
        NULL,
        NULL,
        FALSE,
        0,
        NULL,
        NULL,
        &si,
        &pi
        );

    if ( fSuccess )
    {
        if ( bSync )
            WaitForSingleObject( pi.hProcess, INFINITE );

        CloseHandle( pi.hProcess );
        CloseHandle( pi.hThread );
    }

    return fSuccess;
}

extern "C" UINT __stdcall ExecutePostUninstallScript( MSIHANDLE handle )
{
    TCHAR   szValue[8192];
    DWORD   nValueSize = sizeof(szValue);
    HKEY    hKey;
    std::_tstring   sInstDir;

    std::_tstring   sProductKey = GetMsiProperty( handle, TEXT("FINDPRODUCT") );

    // MessageBox( NULL, sProductKey.c_str(), "Titel", MB_OK );

    if ( ERROR_SUCCESS == RegOpenKey( HKEY_CURRENT_USER,  sProductKey.c_str(), &hKey ) )
    {
        if ( ERROR_SUCCESS == RegQueryValueEx( hKey, TEXT("INSTALLLOCATION"), NULL, NULL, (LPBYTE)szValue, &nValueSize ) )
        {
            sInstDir = szValue;
        }
        RegCloseKey( hKey );
    }
    else if ( ERROR_SUCCESS == RegOpenKey( HKEY_LOCAL_MACHINE,  sProductKey.c_str(), &hKey ) )
    {
        if ( ERROR_SUCCESS == RegQueryValueEx( hKey, TEXT("INSTALLLOCATION"), NULL, NULL, (LPBYTE)szValue, &nValueSize ) )
        {
            sInstDir = szValue;
        }
        RegCloseKey( hKey );
    }
    else
        return ERROR_SUCCESS;

    std::_tstring   sInfFile = sInstDir + TEXT("program\\postuninstall.inf");
    std::_tstring   sCommand = _T("RUNDLL32.EXE ");

    // MessageBox( NULL, sInfFile.c_str(), "Titel", MB_OK );

    if ( (LONG)GetVersion() < 0 )
        sCommand += _T("setupx.dll");
    else
        sCommand += _T("setupapi.dll");

    sCommand += _T(",InstallHinfSection PostUninstall 132 ");
    sCommand += sInfFile;

    if ( 0 == _taccess( sInfFile.c_str(), 2 ) )
        ExecuteCommand( sCommand.c_str(), TRUE );

    DeleteFile( sInfFile.c_str() );

    return ERROR_SUCCESS;
}

<commit_msg>INTEGRATION: CWS obo12 (1.5.8); FILE MERGED 2007/05/10 13:18:08 obo 1.5.8.2: #i76713# _WIN32_WINDOWS = 0x0410 for Win98 2007/05/10 10:36:55 obo 1.5.8.1: #i76713# #error YES removed (Vista PSDK)<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: postuninstall.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: ihi $ $Date: 2007-06-05 10:50:22 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#define _WIN32_WINDOWS 0x0410
#pragma warning(push, 1) /* disable warnings within system headers */
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <msiquery.h>
#pragma warning(pop)

#include <malloc.h>

#ifdef UNICODE
#define _UNICODE
#define _tstring    wstring
#else
#define _tstring    string
#endif
#include <tchar.h>
#include <string>

#include <io.h>

static std::_tstring GetMsiProperty( MSIHANDLE handle, const std::_tstring& sProperty )
{
    std::_tstring   result;
    TCHAR   szDummy[1] = TEXT("");
    DWORD   nChars = 0;

    if ( MsiGetProperty( handle, sProperty.c_str(), szDummy, &nChars ) == ERROR_MORE_DATA )
    {
        DWORD nBytes = ++nChars * sizeof(TCHAR);
        LPTSTR buffer = reinterpret_cast<LPTSTR>(_alloca(nBytes));
        ZeroMemory( buffer, nBytes );
        MsiGetProperty(handle, sProperty.c_str(), buffer, &nChars);
        result = buffer;
    }

    return  result;
}

static BOOL ExecuteCommand( LPCTSTR lpCommand, BOOL bSync )
{
    BOOL                fSuccess = FALSE;
    STARTUPINFO         si;
    PROCESS_INFORMATION pi;

    ZeroMemory( &si, sizeof(si) );
    si.cb = sizeof(si);

    fSuccess = CreateProcess(
        NULL,
        (LPTSTR)lpCommand,
        NULL,
        NULL,
        FALSE,
        0,
        NULL,
        NULL,
        &si,
        &pi
        );

    if ( fSuccess )
    {
        if ( bSync )
            WaitForSingleObject( pi.hProcess, INFINITE );

        CloseHandle( pi.hProcess );
        CloseHandle( pi.hThread );
    }

    return fSuccess;
}

extern "C" UINT __stdcall ExecutePostUninstallScript( MSIHANDLE handle )
{
    TCHAR   szValue[8192];
    DWORD   nValueSize = sizeof(szValue);
    HKEY    hKey;
    std::_tstring   sInstDir;

    std::_tstring   sProductKey = GetMsiProperty( handle, TEXT("FINDPRODUCT") );

    // MessageBox( NULL, sProductKey.c_str(), "Titel", MB_OK );

    if ( ERROR_SUCCESS == RegOpenKey( HKEY_CURRENT_USER,  sProductKey.c_str(), &hKey ) )
    {
        if ( ERROR_SUCCESS == RegQueryValueEx( hKey, TEXT("INSTALLLOCATION"), NULL, NULL, (LPBYTE)szValue, &nValueSize ) )
        {
            sInstDir = szValue;
        }
        RegCloseKey( hKey );
    }
    else if ( ERROR_SUCCESS == RegOpenKey( HKEY_LOCAL_MACHINE,  sProductKey.c_str(), &hKey ) )
    {
        if ( ERROR_SUCCESS == RegQueryValueEx( hKey, TEXT("INSTALLLOCATION"), NULL, NULL, (LPBYTE)szValue, &nValueSize ) )
        {
            sInstDir = szValue;
        }
        RegCloseKey( hKey );
    }
    else
        return ERROR_SUCCESS;

    std::_tstring   sInfFile = sInstDir + TEXT("program\\postuninstall.inf");
    std::_tstring   sCommand = _T("RUNDLL32.EXE ");

    // MessageBox( NULL, sInfFile.c_str(), "Titel", MB_OK );

    if ( (LONG)GetVersion() < 0 )
        sCommand += _T("setupx.dll");
    else
        sCommand += _T("setupapi.dll");

    sCommand += _T(",InstallHinfSection PostUninstall 132 ");
    sCommand += sInfFile;

    if ( 0 == _taccess( sInfFile.c_str(), 2 ) )
        ExecuteCommand( sCommand.c_str(), TRUE );

    DeleteFile( sInfFile.c_str() );

    return ERROR_SUCCESS;
}

<|endoftext|>