/*!
 * This test will check a descriptor that has all the data perfectly available.
 */
void
Ut_ThemeDescriptor::testPerfectDescriptor ()
{
    ThemeDescriptor *desc, *desc1;

    desc = new ThemeDescriptor (
            NULL,
            DIRNAMEDesktopFilePerfect, 
            CODENAMEDesktopFilePerfect);
    desc1 = new ThemeDescriptor (
            NULL,
            DIRNAMEDesktopFilePerfect, 
            CODENAMEDesktopFilePerfect);

    SYS_DEBUG ("*** valid     = %s", SYS_BOOL(desc->isValid()));
    SYS_DEBUG ("*** visible   = %s", SYS_BOOL(desc->isVisible()));
    SYS_DEBUG ("*** name      = %s", SYS_STR(desc->name()));
    SYS_DEBUG ("*** codeName  = %s", SYS_STR(desc->codeName()));
    SYS_DEBUG ("*** iconName  = %s", SYS_STR(desc->iconName()));
    
    QVERIFY(desc->isValid());
    QVERIFY(desc->isVisible());
    QVERIFY(desc->name() == NAMEDesktopFilePerfect);
    QVERIFY(desc->codeName() == CODENAMEDesktopFilePerfect);
    QVERIFY(desc->iconName() == ICONDesktopFilePerfect);

    /*
     * Testing the operator== variants here.
     */
    QVERIFY(*desc == QString(CODENAMEDesktopFilePerfect));
    QVERIFY(*desc == QString(NAMEDesktopFilePerfect));
    QVERIFY(*desc == *desc1);

    delete desc;
}
void
SignalSink::print ()
{
    SYS_DEBUG ("*** m_PSMValueReceived            = %s", SYS_BOOL (m_PSMValueReceived));
    if (m_PSMValueReceived) {
        SYS_DEBUG ("*** m_PSMValue                    = %s", SYS_BOOL (m_PSMValue));
    }

    SYS_DEBUG ("*** m_RemainingCapacityReceived = %s",
            SYS_BOOL(m_RemainingCapacityReceived));
    if (m_RemainingCapacityReceived) {
            SYS_DEBUG ("*** m_RemainingCapacity     = %d", m_RemainingCapacity);

    }

    SYS_DEBUG ("*** m_AnimationRateReceived       = %s", 
            SYS_BOOL(m_AnimationRateReceived));
    if (m_AnimationRateReceived) {
        SYS_DEBUG ("*** m_AnimationRate               = %d", m_AnimationRate);
    }

    SYS_DEBUG ("*** m_BarValueReceived            = %s", SYS_BOOL(m_BarValueReceived));
    if (m_BarValueReceived) {
        SYS_DEBUG ("*** m_BarValue                    = %d", m_BarValue);
    }
}
void
OfflineBrief::setToggle (
        bool toggle)
{
    SYS_DEBUG ("toggle = %s", SYS_BOOL (toggle));
    /*
     * Don't do anything if we already in the desired mode
     */
    if (toggle && m_LastMode == QmDeviceMode::Flight)
        return;
    else if ((! toggle) && m_LastMode == QmDeviceMode::Normal)
        return;

#ifdef HAVE_QMSYSTEM
    if (! toggle)
    {
        MMessageBox* dialog =
                             //% "Exit offline mode?"
            new MMessageBox (qtTrId ("qtn_offl_exiting_title"),
                             //% "Connections will be restored."
                             qtTrId ("qtn_offl_exiting"),
                             M::YesButton | M::NoButton);
        /*
         * This will set the 'Normal' mode if dialog accepted
         */
        connect (dialog, SIGNAL (accepted ()),
                 SLOT (processDialogResult ()));
        /*
         * This will switch back the button for the proper state
         */
        connect (dialog, SIGNAL (rejected ()),
                 this, SIGNAL (valuesChanged ()));
        dialog->appear (MApplication::activeWindow (),
                        MSceneWindow::DestroyWhenDone);
    }
    else
    {
        bool success = m_DevMode->setMode (QmDeviceMode::Flight);
        SYS_DEBUG ("m_DevMode->setMode (Flight) success: %s", SYS_BOOL (success));
        if (success)
        {
            m_infoBanner = new MBanner;
            m_infoBanner->setStyleName ("InformationBanner");
            m_infoBanner->setObjectName ("InfoBanner");

            //% "Closing all connections. Switching to offline mode."
            m_infoBanner->setTitle (qtTrId ("qtn_offl_entering"));
            m_infoBanner->appear (
                MApplication::activeWindow (),
                MSceneWindow::DestroyWhenDone);
            // Set to NULL, as will destroy itself
            m_infoBanner = 0;
        }
    }
#endif
}
/*!
 * Reads the PSMAuto value, a boolean that sets if the device should go into
 * power save mode automatically. This method is only reads the GConf database.
 */
bool
BatteryBusinessLogic::PSMAutoValue ()
{
    MGConfItem PSMAutoKey (psm_auto_key);
    SYS_DEBUG ("value = %s", SYS_BOOL (PSMAutoKey.value ().toBool ()));
    return PSMAutoKey.value ().toBool ();
}
void
WarrantyWidget::initialize ()
{
    QSettings content (configFile, QSettings::IniFormat);

    m_warrantyTimer =
        content.value ("warrantytimer", true).toBool ();
    m_warrantyText =
        content.value ("warrantytext", "qtn_warr_terms").toString ();

    SYS_DEBUG ("show warranty timer = %s", SYS_BOOL (m_warrantyTimer));
    SYS_DEBUG ("warranty_text = %s", SYS_STR (m_warrantyText));

    if (! m_warrantyText.isEmpty ())
    {
        if (m_warrantyText.contains ("qtn_"))
            m_warrantyText = qtTrId (m_warrantyText.toAscii ().constData ());
        else
        {
            QFile warrantyFile (configPath + m_warrantyText);
            if (warrantyFile.open (QIODevice::ReadOnly | QIODevice::Text))
            {
                QTextStream inStream (&warrantyFile);
                m_warrantyText = inStream.readAll ();
            }
            else
            {
                SYS_WARNING ("Warranty text cannot be loaded!");
                m_warrantyText = "";
            }
        }
    }
}
void
ThemeCellCreator::updateCell (
        const QModelIndex &index, 
        MWidget           *cell) const
{
    CustomListItem       *listItem;
    QString               title;
    QString               codeName;
    QString               iconName;
    QString               changingTheme;
    bool                  isChangingTheme;

    if(!cell || !index.isValid()) 
        return;

    listItem = qobject_cast<CustomListItem *>(cell);
    
    changingTheme = index.data (ThemeListModel::ChangingNameRole).toString();
    title = index.data (ThemeListModel::NameRole).toString();
    codeName = index.data (ThemeListModel::CodeNameRole).toString();
    iconName = index.data (ThemeListModel::IconNameRole).toString();
    isChangingTheme = !codeName.isEmpty() && changingTheme == codeName;

    #if 1
    SYS_DEBUG ("************** %d ***************", index.row());
    SYS_DEBUG ("title           = %s", SYS_STR(title));
    SYS_DEBUG ("changingTheme   = %s", SYS_STR(changingTheme));
    SYS_DEBUG ("codeName        = %s", SYS_STR(codeName));
    SYS_DEBUG ("iconName        = %s", SYS_STR(iconName));
    SYS_DEBUG ("isChangingTheme = %s", SYS_BOOL(isChangingTheme));
    #endif

    // The title
    if (m_HighlightText.isEmpty()) {
        listItem->setTitle(title);
    } else {
        int matchingIndex = title.indexOf (
                m_HighlightText, 0, Qt::CaseInsensitive);

        if (matchingIndex != -1) {
            title.insert (matchingIndex + m_HighlightText.length(), 
                    SelectionEndTag);
            title.insert (matchingIndex, SelectionStartTag);
        }
        listItem->setTitle (title);
    }

    // The icon
    if (listItem->imageWidget()->image() != iconName)
        listItem->imageWidget()->setImage (iconName);

    // The spinner.
    if (isChangingTheme) {
        listItem->progressIndicator()->show();
    } else {
        listItem->progressIndicator()->hide();
    }

    updateListItemMode(index, listItem);
}
void
BatteryBusinessLogic::setPSMValue (
        bool enabled)
{
    bool ret = false;

    #ifdef HAVE_QMSYSTEM
    ret = m_devicemode->setPSMState (
        enabled ?
        QmDeviceMode::PSMStateOn :
        QmDeviceMode::PSMStateOff);
    #else
    /*
     * FIXME: To implement the setting of the power save mode without the help
     * of the QmSystem library.
     */
    #endif

    if (ret) {
        // Change succeed, we don't need to wait for QmSystem reply, we can emit
        // the PSMValueChanged asap to update the UI.
        SYS_DEBUG ("Emitting PSMValueReceived(%s)", SYS_BOOL(enabled));
        emit PSMValueReceived (enabled);
    } else {
        SYS_WARNING ("Failed to set PSM mode to %s",
                enabled ? 
                "QmDeviceMode::PSMStateOn" : "QmDeviceMode::PSMStateOff");
    }
}
/*!
 * Method for initialize the current-wallpaper-descriptor from filenames
 *
 * \param landscapeFile The landscape wallpaper file-name
 * \param portraitFile The portrait wallpaper file-name
 */
bool 
WallpaperCurrentDescriptor::setFromFilenames  (
            QString     landscapeFile,
            QString     portraitFile)
{
    bool retval = false;

    SYS_DEBUG ("*** landscapeFile = %s", SYS_STR(landscapeFile));
    SYS_DEBUG ("*** portraitFile  = %s", SYS_STR(portraitFile));
   
    if (!landscapeFile.isEmpty() && !landscapeFile.startsWith("/"))
        goto finalize;

    if (!portraitFile.isEmpty() && !portraitFile.startsWith("/"))
        goto finalize;


    m_LandscapeTrans = WallpaperITrans();
    m_PortraitTrans = WallpaperITrans();

    setFilename (landscapeFile, WallpaperDescriptor::Landscape);
    setFilename (portraitFile,  WallpaperDescriptor::Portrait);
    setFilename (landscapeFile, WallpaperDescriptor::OriginalLandscape);
    setFilename (portraitFile,  WallpaperDescriptor::OriginalPortrait);

    m_Valid = true;
    retval = true;

finalize:
    SYS_DEBUG ("Returning %s", SYS_BOOL(retval));
    return retval;
}
void
SignalSink::PSMValueReceived (
        bool PSMValue)
{
    SYS_DEBUG ("*** PSMValue = %s", SYS_BOOL(PSMValue));
    m_PSMValue = PSMValue;
    m_PSMValueReceived = true;
}
/*!
 * This slot will be called when the device power save mode is changed. The
 * method will send the PSMValueReceived() signal.
 */
void
BatteryBusinessLogic::PSMStateChanged (
        MeeGo::QmDeviceMode::PSMState state)
{
    bool enabled = state == QmDeviceMode::PSMStateOn;
    
    SYS_DEBUG ("Emitting PSMValueReceived (%s)", SYS_BOOL(enabled));
    emit PSMValueReceived (enabled);
}
/*
 * FIXME: This slot is only called when the dialog is accepted...
 *        Re-name this at once...
 */
void
OfflineBrief::processDialogResult ()
{
#ifdef HAVE_QMSYSTEM
    bool success = m_DevMode->setMode (QmDeviceMode::Normal);
    SYS_DEBUG ("m_DevMode->setMode (Normal) success: %s", SYS_BOOL (success));

    emit valuesChanged();
#endif
}
/*!
 * This slot will be called when the device power save mode is changed. The
 * method will send the PSMValueReceived() signal.
 */
void
BatteryBusinessLogic::PSMStateChanged (
        MeeGo::QmDeviceMode::PSMState state)
{
    m_PowerSaveMode =
        (state == MeeGo::QmDeviceMode::PSMStateOn);
    
    SYS_DEBUG ("Emitting PSMValueReceived (%s)", SYS_BOOL (m_PowerSaveMode));
    emit PSMValueReceived (m_PowerSaveMode);
}
bool
SoundSettings::isTemporaryFile (
        const QString &filePath)
{
    bool     retval = filePath.startsWith(mountPoint());

    SYS_DEBUG ("*** filePath   = %s", SYS_STR(filePath));
    SYS_DEBUG ("*** retval     = %s", SYS_BOOL(retval));

    return retval;
}
void
ThemeListModel::themeChanged (
		QString themeCodeName)
{
    QModelIndex index = indexOfCodeName (themeCodeName);

    SYS_DEBUG ("***********************************************************");
    SYS_DEBUG ("*** themeCodeName   = %s", SYS_STR(themeCodeName));
    SYS_DEBUG ("*** index.isValid() = %s", SYS_BOOL(index.isValid()));
    m_ChangingTheme = "";

    if (index.isValid())
        emit dataChanged (index, index);
}
/*
 * This function does the initialization and signal connection to QmBattery and
 * QmDeviceMode, and emits all the signals with the current values...
 *
 * FIXME: This function should be called realize() or something...
 */
void
BatteryBusinessLogic::requestValues ()
{
    if (m_initialized)
        return;

    m_initialized = true;

    #ifdef HAVE_QMSYSTEM
    SYS_DEBUG ("Connecting to the signals of the QmBattery class");
    connect (
        m_battery, SIGNAL(chargerEvent(MeeGo::QmBattery::ChargerType)),
        this, SLOT(batteryChargerEvent(MeeGo::QmBattery::ChargerType)));
    connect (
        m_battery, SIGNAL(chargingStateChanged(MeeGo::QmBattery::ChargingState)),
        this, SLOT(chargingStateChanged(MeeGo::QmBattery::ChargingState)));
    connect (
        m_battery, SIGNAL(batteryStateChanged(MeeGo::QmBattery::BatteryState)),
        this, SLOT (batteryStateChanged(MeeGo::QmBattery::BatteryState)));

    // This will emit the batteryCharging signal,
    // and the remainingTimeValuesChanged signal
    chargingStateChanged (m_battery->getChargingState ());

    /*
     * We have two signals showing that the battery energy level has been
     * changed. We listen both of these signals.
     */
    SYS_DEBUG ("Connecting to the signals of the QmBattery class");
    connect (m_battery, SIGNAL (batteryRemainingCapacityChanged (int, int)),
            this, SLOT (batteryRemCapacityChanged (int, int)));


    // batteryBarValueReceived also emitted by chargingStateChanged ^^^
    // FIXME: Why?
    connect (m_devicemode,
             SIGNAL (devicePSMStateChanged (MeeGo::QmDeviceMode::PSMState)),
             this, SLOT (PSMStateChanged (MeeGo::QmDeviceMode::PSMState)));

    SYS_DEBUG ("Emitting PSMValueReceived(%s)",
            SYS_BOOL(m_devicemode->getPSMState () == QmDeviceMode::PSMStateOn));
    emit PSMValueReceived (m_devicemode->getPSMState () ==
                           QmDeviceMode::PSMStateOn);
    #else
    /*
     * FIXME: To create an implementation without the QmSystem
     */
    #endif
}
/*!
 * testing what happens when the MDesktopEntry does not hold the keys we expect
 * it should hold. All of the keys will return an empty string.
 */
void
Ut_ThemeDescriptor::testEmptyThemeDescriptor ()
{
    ThemeDescriptor *desc;

    desc = new ThemeDescriptor (
            NULL,
            DIRNAMEDesktopFileEmpty, 
            CODENAMEDesktopFileEmpty);

    SYS_DEBUG ("*** valid     = %s", SYS_BOOL(desc->isValid()));
    SYS_DEBUG ("*** visible   = %s", SYS_BOOL(desc->isVisible()));
    SYS_DEBUG ("*** name      = %s", SYS_STR(desc->name()));
    SYS_DEBUG ("*** codeName  = %s", SYS_STR(desc->codeName()));
    SYS_DEBUG ("*** iconName  = %s", SYS_STR(desc->iconName()));

    QVERIFY(!desc->isValid());
    QVERIFY(!desc->isVisible());
    QVERIFY(desc->name().isEmpty());
    QVERIFY(!desc->codeName().isEmpty());
    QVERIFY(desc->iconName().isEmpty());

    delete desc;
}
/*!
 * Method for initializing the current wallpaper descriptor from theme ids
 *
 * \param landscapeID The theme-image-id for the landscape wallpaper
 * \param portraitID The theme-image-id for the portrait wallpaper
 */
bool 
WallpaperCurrentDescriptor::setFromIDs  (
            QString     landscapeID,
            QString     portraitID)
{
    bool retval = false;
   
    SYS_DEBUG ("*** landscapeID = %s", SYS_STR(landscapeID));
    SYS_DEBUG ("*** portraitID  = %s", SYS_STR(portraitID));

    /*
     * Hack, as nowadays only portrait mode image ids are pre-set...
     */
    //if (landscapeID.isEmpty())
    //    landscapeID = portraitID;

    if (landscapeID.isEmpty () && portraitID.isEmpty ())
        goto finalize;

    if (!landscapeID.isEmpty()) {
        if (landscapeID.startsWith("/")) {
            setFilename (landscapeID, WallpaperDescriptor::Landscape);
            setFilename (landscapeID, WallpaperDescriptor::OriginalLandscape);
        } else {
            setImageID (landscapeID, WallpaperDescriptor::Landscape);
            setImageID (landscapeID, WallpaperDescriptor::OriginalLandscape);
        }
    }

    if (!portraitID.isEmpty()) {
        if (portraitID.startsWith("/")) {
            setFilename (portraitID, WallpaperDescriptor::Portrait);
            setFilename (portraitID, WallpaperDescriptor::OriginalPortrait);
        } else {
            setImageID (portraitID, WallpaperDescriptor::Portrait);
            setImageID (portraitID, WallpaperDescriptor::OriginalPortrait);
        }
    }

    m_Valid = true;
    retval = true;

finalize:
    SYS_DEBUG ("Returning %s", SYS_BOOL(retval));
    return retval;
}
/*!
 * This function is called whenever some change is detected around the battery
 * and its charger. This method will try to find out if the battery is actually
 * charging and if it is the method will calculate the charging animation speed.
 *
 * What we managed to find aboput the charging is:
 * 1) The battery is not charging (despite any other info returned) if the
 *    battery is full. See NB#172929 for further details.
 */
void
BatteryBusinessLogic::recalculateChargingInfo ()
{
    #ifdef HAVE_QMSYSTEM
    QmBattery::ChargingState chargingState;
    QmBattery::BatteryState  batteryState;
    QmBattery::ChargerType   chargerType;
    bool                     charging;
    bool                     couldBeCharging;
    int                      chargingRate;
   
    chargerType = m_battery->getChargerType ();
    chargingState = m_battery->getChargingState ();
    batteryState = m_battery->getBatteryState ();

    /*
     * Carefully calculating the charging rate, the animation rate of the
     * charging indicator.
     */
    couldBeCharging =
        chargingState == QmBattery::StateCharging &&
        // This is actually not necessary, but we even check it in the unit
        // test. Just to be sure.
        chargerType != QmBattery::None;

    charging = 
        batteryState != QmBattery::StateFull &&
        chargerType != QmBattery::None &&
        chargingState != QmBattery::StateNotCharging &&
        chargingState != QmBattery::StateChargingFailed;

    chargingRate = 0;
    if (charging) 
        chargingRate = chargerType == QmBattery::Wall ?
            animation_rate_charging_wall : animation_rate_charging_usb;

    SYS_DEBUG ("*** charging       = %s", SYS_BOOL(charging));
    SYS_DEBUG ("*** m_Charging     = %s", SYS_BOOL(m_Charging));
    SYS_DEBUG ("*** chargingRate   = %d", chargingRate);
    SYS_DEBUG ("*** m_ChargingRate = %d", m_ChargingRate);

    if (chargingRate == m_ChargingRate &&
            couldBeCharging == m_Charging) 
        return;

    /*
     * If the charging rate has been changed we need to notify the ui with a
     * signal.
     */
    m_Charging = couldBeCharging;
    SYS_DEBUG ("*** chargingRate %d -> %d", m_ChargingRate, chargingRate);
    m_ChargingRate = chargingRate;       
    SYS_DEBUG ("Emitting batteryCharging(%d)", m_ChargingRate);
    emit batteryCharging (m_ChargingRate);

    /*
     * Then we need to notify everyone about the bar value. 
     * FIXME: Why exactly do we need that?
     */
    SYS_DEBUG ("Emitting batteryBarValueReceived(%d)", batteryBarValue (-1));
    emit batteryBarValueReceived (batteryBarValue (-1));

    if(batteryState == QmBattery::StateFull)
    {
        emit batteryFull();
        return;
    }

    /*
     * And the remaining battery capacity has to be recalculated.
     */
    remainingCapacityRequired();
    #else
    /*
     * FIXME: To implement a variant that does not use QmSystem.
     */
    #endif
}
/*!
 * \param desktopFileName The full path of the desktop file to read
 * \param landscapeFileName If provided the method will report failure when the
 *   desktop file contains a different file name.
 * \param portraitFileName If provided the method will report failure when the
 *   desktop file contains a different file name.
 * 
 * Reads the data stored in a desktop wile and initializes the object using the
 * data found there.
 */
bool 
WallpaperCurrentDescriptor::setFromDesktopFile (
        const QString &desktopFileName,
        bool           checkFilenames,
        const QString &landscapeFileName,
        const QString &portraitFileName)
{
    bool           success1, success2;
    QString        value1("");
    QString        value2("");
    qreal          rval;
    bool           retval = false;

    SYS_DEBUG ("*** desktopFileName   = %s", SYS_STR(desktopFileName));
    SYS_DEBUG ("*** landscapeFileName = %s", SYS_STR(landscapeFileName));
    SYS_DEBUG ("*** portraitFileName  = %s", SYS_STR(portraitFileName));
    SYS_DEBUG ("*** checkFilenames    = %s", SYS_BOOL(checkFilenames));
    m_DesktopEntry = new MDesktopEntry (desktopFileName);

    if (!m_DesktopEntry->isValid()) {
        goto finalize;
    }

    /*
     * The edited image file name... FIXME: This is actually depends on the
     * orientation.
     * We should compare these with the values stored in the gconf database.
     */
    success1 = getValue(portraitGroupKey, editedFilenameKey, value1);
    success2 = getValue(landscapeGroupKey, editedFilenameKey, value2);
    if (!success1 && !success2) {
        SYS_DEBUG ("Non of the variants are accessed, giving up.");
        goto finalize;
    }

    /*
     * If the filenames are provided we check the desktop file data against
     * them. Even if we support only one orientation one of the filenames must
     * match.
     */
    if (checkFilenames) {
        if ((landscapeFileName.isEmpty() && portraitFileName != value1) ||
            (portraitFileName.isEmpty() && landscapeFileName != value2) ||
            (portraitFileName != value1 && landscapeFileName != value2)) {
            SYS_DEBUG ("Non of the variants are set, giving up.");
            goto finalize;
        }
    }
    
    SYS_DEBUG ("Accepting value1 = %s", SYS_STR(value1));
    SYS_DEBUG ("Accepting value2 = %s", SYS_STR(value2));
    SYS_DEBUG ("*** portraitFileName  = %s", SYS_STR(portraitFileName));
    SYS_DEBUG ("*** landscapeFileName = %s", SYS_STR(landscapeFileName));
    setFilename (value1, WallpaperDescriptor::Portrait);
    setFilename (value2, WallpaperDescriptor::Landscape);

    /*
     * FIXME: Still no support for separate files in the parent class...
     */
    setFilename (value1.isEmpty() ? value2 : value1);
    setUrl ("file://" + (value1.isEmpty() ? value2 : value1));

    /*
     * MimeType. FIXME: This should not depend on the orientation?
     */
    if (getValue(landscapeGroupKey, mimeTypeKey, value1)) {
        setMimeType (value1);
    }

    /*
     * The version number.
     */
    if (getValue(mainGroupKey, versionKey, &rval))
        m_Version = (int) rval;

    getValue (landscapeGroupKey, originalFilenameKey, value1);
    setFilename (value1, WallpaperDescriptor::OriginalLandscape);

    getValue (portraitGroupKey, originalFilenameKey, value1);
    setFilename (value1, WallpaperDescriptor::OriginalPortrait);

    getValue (landscapeGroupKey, m_LandscapeTrans);
    getValue (portraitGroupKey, m_PortraitTrans);

    retval = true;
    m_Valid = true;

finalize:
    delete m_DesktopEntry;
    m_DesktopEntry = 0;

    return retval;
}