<commit_before>/*
 *  kalarmresource.cpp  -  Akonadi resource for KAlarm
 *  Program:  kalarm
 *  Copyright © 2009 by David Jarvie <djarvie@kde.org>
 *
 *  This library is free software; you can redistribute it and/or modify it
 *  under the terms of the GNU Library General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or (at your
 *  option) any later version.
 *
 *  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 Library General Public
 *  License for more details.
 *
 *  You should have received a copy of the GNU Library General Public License
 *  along with this library; see the file COPYING.LIB.  If not, write to the
 *  Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 *  02110-1301, USA.
 */

#include "kalarmresource.h"
#include "kalarmmimetypevisitor.h"
#include "kaeventdata.h"

#include <kcal/calendarlocal.h>
#include <kcal/incidence.h>

#include <klocale.h>
#include <kdebug.h>

#include <boost/shared_ptr.hpp>

static QLatin1String MIME_ACTIVE("application/x-vnd.kde.alarms.active");
static QLatin1String MIME_ARCHIVED("application/x-vnd.kde.alarms.archived");
static QLatin1String MIME_TEMPLATE("application/x-vnd.kde.alarms.template");

using namespace Akonadi;
using namespace KCal;

typedef boost::shared_ptr<KAEventData> EventPtr;

KAlarmResource::KAlarmResource(const QString& id)
    : ICalResourceBase(id, i18nc("Filedialog filter for *.ics *.ical", "KAlarm Calendar File")),
      mMimeVisitor(new KAlarmMimeTypeVisitor())
{
    QStringList mimeTypes;
    if (id.contains("_active"))
        mimeTypes << MIME_ACTIVE;
    else if (id.contains("_archived"))
        mimeTypes << MIME_ARCHIVED;
    else if (id.contains("_template"))
        mimeTypes << MIME_TEMPLATE;
    else
        mimeTypes << QLatin1String("application/x-vnd.kde.alarms")
                  << MIME_ACTIVE << MIME_ARCHIVED << MIME_TEMPLATE;
    initialise(mimeTypes, "kalarm");
}

KAlarmResource::~KAlarmResource()
{
}

bool KAlarmResource::doRetrieveItem(const Akonadi::Item& item, const QSet<QByteArray>& parts)
{
    Q_UNUSED(parts);
    const QString rid = item.remoteId();
    const KCal::Event* kcalEvent = calendar()->event(rid);
    if (!kcalEvent)
    {
        emit error(i18n("Event with uid '%1' not found.", rid));
        return false;
    }

    if (kcalEvent->alarms().isEmpty())
    {
        emit error(i18n("Event with uid '%1' contains no usable alarms.", rid));
        return false;
    }

    KAEventData* event = new KAEventData(0, kcalEvent);
    QString mime = mimeType(event);
    if (mime.isEmpty())
    {
        emit error(i18n("Event with uid '%1' contains no usable alarms.", rid));
        delete event;
        return false;
    }

    Item i = item;
    i.setMimeType(mime);
    i.setPayload<EventPtr>(EventPtr(event));
    itemRetrieved(i);
    return true;
}

void KAlarmResource::itemAdded(const Akonadi::Item&  item, const Akonadi::Collection&)
{
    if (!checkItemAddedChanged<EventPtr>(item, CheckForAdded))
        return;
    EventPtr e = item.payload<EventPtr>();
    KCal::Event* kcalEvent = new KCal::Event;
#ifdef __GNUC__
#warning Should updateKCalEvent() third parameter be true for archived events?
#endif
    e->updateKCalEvent(kcalEvent, false, false);
    calendar()->addIncidence(kcalEvent);

    Item it(item);
    it.setRemoteId(kcalEvent->uid());
    scheduleWrite();
    changeCommitted(it);
}

void KAlarmResource::itemChanged(const Akonadi::Item& item, const QSet<QByteArray>& parts)
{
    Q_UNUSED(parts)
    if (!checkItemAddedChanged<EventPtr>(item, CheckForChanged))
        return;
    EventPtr payload = item.payload<EventPtr>();
    if (item.remoteId() != payload->id())
    {
        cancelTask(i18n("Item ID %1 differs from payload ID %2.").arg(item.remoteId()).arg(payload->id()));
        return;
    }
    KCal::Incidence* incidence = calendar()->incidence(item.remoteId());
    if (incidence)
    {
        if (!mMimeVisitor->isEvent(incidence))
        {
            calendar()->deleteIncidence(incidence);   // it's not an Event
            incidence = 0;
        }
        else
        {
#ifdef __GNUC__
#warning Should updateKCalEvent() third parameter be true for archived events?
#endif
            payload->updateKCalEvent(static_cast<KCal::Event*>(incidence), false, false);
            calendar()->setModified(true);
        }
    }
    if (!incidence)
    {
        // not in the calendar yet, should not happen -> add it
        KCal::Event* kcalEvent = new KCal::Event;
#ifdef __GNUC__
#warning Should updateKCalEvent() third parameter be true for archived events?
#endif
        payload->updateKCalEvent(kcalEvent, false, false);
        calendar()->addIncidence(kcalEvent);
    }
    scheduleWrite();
    changeCommitted(item);
}

void KAlarmResource::doRetrieveItems(const Akonadi::Collection&)
{
    Event::List events = calendar()->events();
    Item::List items;
    foreach (Event* kcalEvent, events)
    {
        if (kcalEvent->alarms().isEmpty())
            continue;    // ignore events without alarms

        KAEventData* event = new KAEventData(0, kcalEvent);
        QString mime = mimeType(event);
        if (mime.isEmpty())
            continue;   // event has no usable alarms

        Item item(mime);
        item.setRemoteId(kcalEvent->uid());
        item.setPayload(EventPtr(event));
        items << item;
    }
    itemsRetrieved(items);
}

QString KAlarmResource::mimeType(const KAEventData* event)
{
    if (event->valid())
    {
        switch (event->category())
        {
            case KCalEvent::ACTIVE:    return MIME_ACTIVE;
            case KCalEvent::ARCHIVED:  return MIME_ARCHIVED;
            case KCalEvent::TEMPLATE:  return MIME_TEMPLATE;
            default:
                break;
        }
    }
    return QString();
}

AKONADI_RESOURCE_MAIN(KAlarmResource)

#include "kalarmresource.moc"
<commit_msg>Fix date-only alarms in akonadi resource<commit_after>/*
 *  kalarmresource.cpp  -  Akonadi resource for KAlarm
 *  Program:  kalarm
 *  Copyright © 2009 by David Jarvie <djarvie@kde.org>
 *
 *  This library is free software; you can redistribute it and/or modify it
 *  under the terms of the GNU Library General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or (at your
 *  option) any later version.
 *
 *  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 Library General Public
 *  License for more details.
 *
 *  You should have received a copy of the GNU Library General Public License
 *  along with this library; see the file COPYING.LIB.  If not, write to the
 *  Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 *  02110-1301, USA.
 */

#include "kalarmresource.h"
#include "kalarmmimetypevisitor.h"
#include "kaeventdata.h"

#include <kcal/calendarlocal.h>
#include <kcal/incidence.h>

#include <klocale.h>
#include <kdebug.h>

#include <boost/shared_ptr.hpp>

static QLatin1String MIME_ACTIVE("application/x-vnd.kde.alarms.active");
static QLatin1String MIME_ARCHIVED("application/x-vnd.kde.alarms.archived");
static QLatin1String MIME_TEMPLATE("application/x-vnd.kde.alarms.template");

using namespace Akonadi;
using namespace KCal;

typedef boost::shared_ptr<KAEventData> EventPtr;

KAlarmResource::KAlarmResource(const QString& id)
    : ICalResourceBase(id, i18nc("Filedialog filter for *.ics *.ical", "KAlarm Calendar File")),
      mMimeVisitor(new KAlarmMimeTypeVisitor())
{
    // Set a default start-of-day time for date-only alarms.
    KAEventData::setStartOfDay(QTime(0,0,0));

    QStringList mimeTypes;
    if (id.contains("_active"))
        mimeTypes << MIME_ACTIVE;
    else if (id.contains("_archived"))
        mimeTypes << MIME_ARCHIVED;
    else if (id.contains("_template"))
        mimeTypes << MIME_TEMPLATE;
    else
        mimeTypes << QLatin1String("application/x-vnd.kde.alarms")
                  << MIME_ACTIVE << MIME_ARCHIVED << MIME_TEMPLATE;
    initialise(mimeTypes, "kalarm");
}

KAlarmResource::~KAlarmResource()
{
}

bool KAlarmResource::doRetrieveItem(const Akonadi::Item& item, const QSet<QByteArray>& parts)
{
    Q_UNUSED(parts);
    const QString rid = item.remoteId();
    const KCal::Event* kcalEvent = calendar()->event(rid);
    if (!kcalEvent)
    {
        emit error(i18n("Event with uid '%1' not found.", rid));
        return false;
    }

    if (kcalEvent->alarms().isEmpty())
    {
        emit error(i18n("Event with uid '%1' contains no usable alarms.", rid));
        return false;
    }

    KAEventData* event = new KAEventData(0, kcalEvent);
    QString mime = mimeType(event);
    if (mime.isEmpty())
    {
        emit error(i18n("Event with uid '%1' contains no usable alarms.", rid));
        delete event;
        return false;
    }

    Item i = item;
    i.setMimeType(mime);
    i.setPayload<EventPtr>(EventPtr(event));
    itemRetrieved(i);
    return true;
}

void KAlarmResource::itemAdded(const Akonadi::Item&  item, const Akonadi::Collection&)
{
    if (!checkItemAddedChanged<EventPtr>(item, CheckForAdded))
        return;
    EventPtr e = item.payload<EventPtr>();
    KCal::Event* kcalEvent = new KCal::Event;
#ifdef __GNUC__
#warning Should updateKCalEvent() third parameter be true for archived events?
#endif
    e->updateKCalEvent(kcalEvent, false, false);
    calendar()->addIncidence(kcalEvent);

    Item it(item);
    it.setRemoteId(kcalEvent->uid());
    scheduleWrite();
    changeCommitted(it);
}

void KAlarmResource::itemChanged(const Akonadi::Item& item, const QSet<QByteArray>& parts)
{
    Q_UNUSED(parts)
    if (!checkItemAddedChanged<EventPtr>(item, CheckForChanged))
        return;
    EventPtr payload = item.payload<EventPtr>();
    if (item.remoteId() != payload->id())
    {
        cancelTask(i18n("Item ID %1 differs from payload ID %2.").arg(item.remoteId()).arg(payload->id()));
        return;
    }
    KCal::Incidence* incidence = calendar()->incidence(item.remoteId());
    if (incidence)
    {
        if (!mMimeVisitor->isEvent(incidence))
        {
            calendar()->deleteIncidence(incidence);   // it's not an Event
            incidence = 0;
        }
        else
        {
#ifdef __GNUC__
#warning Should updateKCalEvent() third parameter be true for archived events?
#endif
            payload->updateKCalEvent(static_cast<KCal::Event*>(incidence), false, false);
            calendar()->setModified(true);
        }
    }
    if (!incidence)
    {
        // not in the calendar yet, should not happen -> add it
        KCal::Event* kcalEvent = new KCal::Event;
#ifdef __GNUC__
#warning Should updateKCalEvent() third parameter be true for archived events?
#endif
        payload->updateKCalEvent(kcalEvent, false, false);
        calendar()->addIncidence(kcalEvent);
    }
    scheduleWrite();
    changeCommitted(item);
}

void KAlarmResource::doRetrieveItems(const Akonadi::Collection&)
{
    Event::List events = calendar()->events();
    Item::List items;
    foreach (Event* kcalEvent, events)
    {
        if (kcalEvent->alarms().isEmpty())
            continue;    // ignore events without alarms

        KAEventData* event = new KAEventData(0, kcalEvent);
        QString mime = mimeType(event);
        if (mime.isEmpty())
            continue;   // event has no usable alarms

        Item item(mime);
        item.setRemoteId(kcalEvent->uid());
        item.setPayload(EventPtr(event));
        items << item;
    }
    itemsRetrieved(items);
}

QString KAlarmResource::mimeType(const KAEventData* event)
{
    if (event->valid())
    {
        switch (event->category())
        {
            case KCalEvent::ACTIVE:    return MIME_ACTIVE;
            case KCalEvent::ARCHIVED:  return MIME_ARCHIVED;
            case KCalEvent::TEMPLATE:  return MIME_TEMPLATE;
            default:
                break;
        }
    }
    return QString();
}

AKONADI_RESOURCE_MAIN(KAlarmResource)

#include "kalarmresource.moc"
<|endoftext|>


<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * LXDE-Qt - a lightweight, Qt based, desktop toolset
 * http://razor-qt.org
 *
 * Copyright: 2012 Razor team
 * Authors:
 *   Alexander Sokoloff <sokoloff.a@gmail.com>
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include "plugin.h"
#include "ilxqtpanelplugin.h"
#include "lxqtpanel.h"
#include <QDebug>
#include <QProcessEnvironment>
#include <QStringList>
#include <QDir>
#include <QFileInfo>
#include <QPluginLoader>
#include <QGridLayout>
#include <QDialog>
#include <QEvent>
#include <QMenu>
#include <QMouseEvent>
#include <QApplication>
#include <QCryptographicHash>

#include <LXQt/Settings>
#include <XdgIcon>

QColor Plugin::mMoveMarkerColor= QColor(255, 0, 0, 255);

/************************************************

 ************************************************/
Plugin::Plugin(const LxQt::PluginInfo &desktopFile, const QString &settingsFile, const QString &settingsGroup, LxQtPanel *panel) :
    QFrame(panel),
    mDesktopFile(desktopFile),
    mPluginLoader(0),
    mPlugin(0),
    mPluginWidget(0),
    mAlignment(AlignLeft),
    mSettingsGroup(settingsGroup),
    mPanel(panel)
{

    mSettings = new LxQt::Settings(settingsFile, QSettings::IniFormat, this);
    connect(mSettings, SIGNAL(settingsChanged()), this, SLOT(settingsChanged()));
    mSettings->beginGroup(settingsGroup);

    mSettingsHash = calcSettingsHash();

    setWindowTitle(desktopFile.name());
    mName = desktopFile.name();

    QStringList dirs;
    dirs << QProcessEnvironment::systemEnvironment().value("LXQTPANEL_PLUGIN_PATH").split(":");
    dirs << PLUGIN_DIR;

    QString baseName = QString("lib%1.so").arg(desktopFile.id());
    bool found = false;
    foreach(QString dirName, dirs)
    {
        QFileInfo fi(QDir(dirName), baseName);

        if (fi.exists())
        {
            found = true;
            if (loadLib(fi.absoluteFilePath()))
                break;
        }
    }

    if (!isLoaded())
    {
        if (!found)
            qWarning() << QString("Plugin %1 not found in the").arg(baseName) << dirs;

        return;
    }

    setObjectName(mPlugin->themeId() + "Plugin");
    QString s = mSettings->value("alignment").toString();

    // Retrun default value
    if (s.isEmpty())
    {
        mAlignment = (mPlugin->flags().testFlag(ILxQtPanelPlugin::PreferRightAlignment)) ?
                    Plugin::AlignRight :
                    Plugin::AlignLeft;
    }
    else
    {
        mAlignment = (s.toUpper() == "RIGHT") ?
                    Plugin::AlignRight :
                    Plugin::AlignLeft;

    }

    if (mPluginWidget)
    {
        QGridLayout* layout = new QGridLayout(this);
        layout->setSpacing(0);
        layout->setMargin(0);
        layout->setContentsMargins(0, 0, 0, 0);
        setLayout(layout);
        layout->addWidget(mPluginWidget, 0, 0);
    }

    saveSettings();
}

/************************************************

 ************************************************/
Plugin::~Plugin()
{
    delete mPlugin;
    if (mPluginLoader)
    {
        mPluginLoader->unload();
        delete mPluginLoader;
    }
}

void Plugin::setAlignment(Plugin::Alignment alignment)
{
    mAlignment = alignment;
    saveSettings();
}

/************************************************

 ************************************************/
bool Plugin::loadLib(const QString &libraryName)
{
    mPluginLoader = new QPluginLoader(libraryName);

    if (!mPluginLoader->load())
    {
        qWarning() << mPluginLoader->errorString();
        return false;
    }

    QObject *obj = mPluginLoader->instance();
    if (!obj)
    {
        qWarning() << mPluginLoader->errorString();
        return false;
    }

    ILxQtPanelPluginLibrary* pluginLib= qobject_cast<ILxQtPanelPluginLibrary*>(obj);
    if (!pluginLib)
    {
        qWarning() << QString("Can't load plugin \"%1\". Plugin is not a ILxQtPanelPluginLibrary.").arg(mPluginLoader->fileName());
        delete obj;
        return false;
    }

    ILxQtPanelPluginStartupInfo startupInfo;
    startupInfo.settings = mSettings;
    startupInfo.desktopFile = &mDesktopFile;
    startupInfo.lxqtPanel = mPanel;

    mPlugin = pluginLib->instance(startupInfo);
    if (!mPlugin)
    {
        qWarning() << QString("Can't load plugin \"%1\". Plugin can't build ILxQtPanelPlugin.").arg(mPluginLoader->fileName());
        delete obj;
        return false;
    }

    mPluginWidget = mPlugin->widget();
    if (mPluginWidget)
    {
        mPluginWidget->setObjectName(mPlugin->themeId());
    }
    this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    return true;
}

/************************************************

 ************************************************/
QByteArray Plugin::calcSettingsHash()
{
    QCryptographicHash hash(QCryptographicHash::Md5);
    QStringList keys = mSettings->allKeys();
    foreach (const QString &key, keys)
    {
        hash.addData(key.toUtf8());
        hash.addData(mSettings->value(key).toByteArray());
    }
    return hash.result();
}

/************************************************

 ************************************************/
void Plugin::settingsChanged()
{
    QByteArray hash = calcSettingsHash();
    if (mSettingsHash != hash)
    {
        mSettingsHash = hash;
        mPlugin->settingsChanged();
    }
}

/************************************************

 ************************************************/
void Plugin::saveSettings()
{
    mSettings->setValue("alignment", (mAlignment == AlignLeft) ? "Left" : "Right");
    mSettings->setValue("type", mDesktopFile.id());
    mSettings->sync();

}

/************************************************

 ************************************************/
void Plugin::x11EventFilter(XEventType *event)
{
    mPlugin->x11EventFilter(event);
}

/************************************************

 ************************************************/
void Plugin::contextMenuEvent(QContextMenuEvent *event)
{
    mPanel->showPopupMenu(this);
}

/************************************************

 ************************************************/
void Plugin::mousePressEvent(QMouseEvent *event)
{
    switch (event->button())
    {
    case Qt::LeftButton:
        mPlugin->activated(ILxQtPanelPlugin::Trigger);
        break;

    case Qt::MidButton:
        mPlugin->activated(ILxQtPanelPlugin::MiddleClick);
        break;

    default:
        break;
    }
}

/************************************************

 ************************************************/
void Plugin::mouseDoubleClickEvent(QMouseEvent*)
{
    mPlugin->activated(ILxQtPanelPlugin::DoubleClick);
}

/************************************************

 ************************************************/
void Plugin::showEvent(QShowEvent *)
{
    if (mPluginWidget)
        mPluginWidget->adjustSize();
}

/************************************************

 ************************************************/
QMenu *Plugin::popupMenu() const
{
    QString name = this->name().replace("&", "&&");
    QMenu* menu = new QMenu(windowTitle());

    if (mPlugin->flags().testFlag(ILxQtPanelPlugin::HaveConfigDialog))
    {
        QAction* configAction = new QAction(tr("Configure \"%1\"").arg(name), menu);
        menu->addAction(configAction);
        connect(configAction, SIGNAL(triggered()), this, SLOT(showConfigureDialog()));
    }

    QAction* moveAction = new QAction(XdgIcon::fromTheme("transform-move"), tr("Move \"%1\"").arg(name), menu);
    menu->addAction(moveAction);
    connect(moveAction, SIGNAL(triggered()), this, SIGNAL(startMove()));

    menu->addSeparator();

    QAction* removeAction = new QAction(XdgIcon::fromTheme("dialog-close"), tr("Remove \"%1\"").arg(name), menu);
    menu->addAction(removeAction);
    connect(removeAction, SIGNAL(triggered()), this, SLOT(requestRemove()));

    return menu;
}

/************************************************

 ************************************************/
bool Plugin::isSeparate() const
{
   return mPlugin->isSeparate();
}

/************************************************

 ************************************************/
bool Plugin::isExpandable() const
{
    return mPlugin->isExpandable();
}

/************************************************

 ************************************************/
void Plugin::realign()
{
    if (mPlugin)
        mPlugin->realign();
}

/************************************************

 ************************************************/
void Plugin::showConfigureDialog()
{
    // store a pointer to each plugin using the plugins' names
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
    static QHash<QString, QPointer<QDialog> > refs;
#else
    static QHash<QString, QWeakPointer<QDialog> > refs;
#endif
    QDialog *dialog = refs[name()].data();

    if (!dialog)
    {
        dialog = mPlugin->configureDialog();
        refs[name()] = dialog;
        connect(this, SIGNAL(destroyed()), dialog, SLOT(close()));
    }

    if (!dialog)
        return;

    dialog->show();
    dialog->raise();
    dialog->activateWindow();
}

/************************************************

 ************************************************/
void Plugin::requestRemove()
{
    emit remove();
    deleteLater();
}
<commit_msg>Load the plugins translations<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * LXDE-Qt - a lightweight, Qt based, desktop toolset
 * http://razor-qt.org
 *
 * Copyright: 2012 Razor team
 * Authors:
 *   Alexander Sokoloff <sokoloff.a@gmail.com>
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include "plugin.h"
#include "ilxqtpanelplugin.h"
#include "lxqtpanel.h"
#include <QDebug>
#include <QProcessEnvironment>
#include <QStringList>
#include <QDir>
#include <QFileInfo>
#include <QPluginLoader>
#include <QGridLayout>
#include <QDialog>
#include <QEvent>
#include <QMenu>
#include <QMouseEvent>
#include <QApplication>
#include <QCryptographicHash>

#include <LXQt/Settings>
#include <LXQt/Translator>
#include <XdgIcon>

QColor Plugin::mMoveMarkerColor= QColor(255, 0, 0, 255);

/************************************************

 ************************************************/
Plugin::Plugin(const LxQt::PluginInfo &desktopFile, const QString &settingsFile, const QString &settingsGroup, LxQtPanel *panel) :
    QFrame(panel),
    mDesktopFile(desktopFile),
    mPluginLoader(0),
    mPlugin(0),
    mPluginWidget(0),
    mAlignment(AlignLeft),
    mSettingsGroup(settingsGroup),
    mPanel(panel)
{

    mSettings = new LxQt::Settings(settingsFile, QSettings::IniFormat, this);
    connect(mSettings, SIGNAL(settingsChanged()), this, SLOT(settingsChanged()));
    mSettings->beginGroup(settingsGroup);

    mSettingsHash = calcSettingsHash();

    setWindowTitle(desktopFile.name());
    mName = desktopFile.name();

    QStringList dirs;
    dirs << QProcessEnvironment::systemEnvironment().value("LXQTPANEL_PLUGIN_PATH").split(":");
    dirs << PLUGIN_DIR;

    QString baseName = QString("lib%1.so").arg(desktopFile.id());
    bool found = false;
    foreach(QString dirName, dirs)
    {
        QFileInfo fi(QDir(dirName), baseName);

        if (fi.exists())
        {
            found = true;
            if (loadLib(fi.absoluteFilePath()))
                break;
        }
    }

    if (!isLoaded())
    {
        if (!found)
            qWarning() << QString("Plugin %1 not found in the").arg(baseName) << dirs;

        return;
    }

    // Load plugin translations
    LxQt::Translator::translatePlugin(desktopFile.id(), QLatin1String("lxqt-panel"));

    setObjectName(mPlugin->themeId() + "Plugin");
    QString s = mSettings->value("alignment").toString();

    // Retrun default value
    if (s.isEmpty())
    {
        mAlignment = (mPlugin->flags().testFlag(ILxQtPanelPlugin::PreferRightAlignment)) ?
                    Plugin::AlignRight :
                    Plugin::AlignLeft;
    }
    else
    {
        mAlignment = (s.toUpper() == "RIGHT") ?
                    Plugin::AlignRight :
                    Plugin::AlignLeft;

    }

    if (mPluginWidget)
    {
        QGridLayout* layout = new QGridLayout(this);
        layout->setSpacing(0);
        layout->setMargin(0);
        layout->setContentsMargins(0, 0, 0, 0);
        setLayout(layout);
        layout->addWidget(mPluginWidget, 0, 0);
    }

    saveSettings();
}

/************************************************

 ************************************************/
Plugin::~Plugin()
{
    delete mPlugin;
    if (mPluginLoader)
    {
        mPluginLoader->unload();
        delete mPluginLoader;
    }
}

void Plugin::setAlignment(Plugin::Alignment alignment)
{
    mAlignment = alignment;
    saveSettings();
}

/************************************************

 ************************************************/
bool Plugin::loadLib(const QString &libraryName)
{
    mPluginLoader = new QPluginLoader(libraryName);

    if (!mPluginLoader->load())
    {
        qWarning() << mPluginLoader->errorString();
        return false;
    }

    QObject *obj = mPluginLoader->instance();
    if (!obj)
    {
        qWarning() << mPluginLoader->errorString();
        return false;
    }

    ILxQtPanelPluginLibrary* pluginLib= qobject_cast<ILxQtPanelPluginLibrary*>(obj);
    if (!pluginLib)
    {
        qWarning() << QString("Can't load plugin \"%1\". Plugin is not a ILxQtPanelPluginLibrary.").arg(mPluginLoader->fileName());
        delete obj;
        return false;
    }

    ILxQtPanelPluginStartupInfo startupInfo;
    startupInfo.settings = mSettings;
    startupInfo.desktopFile = &mDesktopFile;
    startupInfo.lxqtPanel = mPanel;

    mPlugin = pluginLib->instance(startupInfo);
    if (!mPlugin)
    {
        qWarning() << QString("Can't load plugin \"%1\". Plugin can't build ILxQtPanelPlugin.").arg(mPluginLoader->fileName());
        delete obj;
        return false;
    }

    mPluginWidget = mPlugin->widget();
    if (mPluginWidget)
    {
        mPluginWidget->setObjectName(mPlugin->themeId());
    }
    this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    return true;
}

/************************************************

 ************************************************/
QByteArray Plugin::calcSettingsHash()
{
    QCryptographicHash hash(QCryptographicHash::Md5);
    QStringList keys = mSettings->allKeys();
    foreach (const QString &key, keys)
    {
        hash.addData(key.toUtf8());
        hash.addData(mSettings->value(key).toByteArray());
    }
    return hash.result();
}

/************************************************

 ************************************************/
void Plugin::settingsChanged()
{
    QByteArray hash = calcSettingsHash();
    if (mSettingsHash != hash)
    {
        mSettingsHash = hash;
        mPlugin->settingsChanged();
    }
}

/************************************************

 ************************************************/
void Plugin::saveSettings()
{
    mSettings->setValue("alignment", (mAlignment == AlignLeft) ? "Left" : "Right");
    mSettings->setValue("type", mDesktopFile.id());
    mSettings->sync();

}

/************************************************

 ************************************************/
void Plugin::x11EventFilter(XEventType *event)
{
    mPlugin->x11EventFilter(event);
}

/************************************************

 ************************************************/
void Plugin::contextMenuEvent(QContextMenuEvent *event)
{
    mPanel->showPopupMenu(this);
}

/************************************************

 ************************************************/
void Plugin::mousePressEvent(QMouseEvent *event)
{
    switch (event->button())
    {
    case Qt::LeftButton:
        mPlugin->activated(ILxQtPanelPlugin::Trigger);
        break;

    case Qt::MidButton:
        mPlugin->activated(ILxQtPanelPlugin::MiddleClick);
        break;

    default:
        break;
    }
}

/************************************************

 ************************************************/
void Plugin::mouseDoubleClickEvent(QMouseEvent*)
{
    mPlugin->activated(ILxQtPanelPlugin::DoubleClick);
}

/************************************************

 ************************************************/
void Plugin::showEvent(QShowEvent *)
{
    if (mPluginWidget)
        mPluginWidget->adjustSize();
}

/************************************************

 ************************************************/
QMenu *Plugin::popupMenu() const
{
    QString name = this->name().replace("&", "&&");
    QMenu* menu = new QMenu(windowTitle());

    if (mPlugin->flags().testFlag(ILxQtPanelPlugin::HaveConfigDialog))
    {
        QAction* configAction = new QAction(tr("Configure \"%1\"").arg(name), menu);
        menu->addAction(configAction);
        connect(configAction, SIGNAL(triggered()), this, SLOT(showConfigureDialog()));
    }

    QAction* moveAction = new QAction(XdgIcon::fromTheme("transform-move"), tr("Move \"%1\"").arg(name), menu);
    menu->addAction(moveAction);
    connect(moveAction, SIGNAL(triggered()), this, SIGNAL(startMove()));

    menu->addSeparator();

    QAction* removeAction = new QAction(XdgIcon::fromTheme("dialog-close"), tr("Remove \"%1\"").arg(name), menu);
    menu->addAction(removeAction);
    connect(removeAction, SIGNAL(triggered()), this, SLOT(requestRemove()));

    return menu;
}

/************************************************

 ************************************************/
bool Plugin::isSeparate() const
{
   return mPlugin->isSeparate();
}

/************************************************

 ************************************************/
bool Plugin::isExpandable() const
{
    return mPlugin->isExpandable();
}

/************************************************

 ************************************************/
void Plugin::realign()
{
    if (mPlugin)
        mPlugin->realign();
}

/************************************************

 ************************************************/
void Plugin::showConfigureDialog()
{
    // store a pointer to each plugin using the plugins' names
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
    static QHash<QString, QPointer<QDialog> > refs;
#else
    static QHash<QString, QWeakPointer<QDialog> > refs;
#endif
    QDialog *dialog = refs[name()].data();

    if (!dialog)
    {
        dialog = mPlugin->configureDialog();
        refs[name()] = dialog;
        connect(this, SIGNAL(destroyed()), dialog, SLOT(close()));
    }

    if (!dialog)
        return;

    dialog->show();
    dialog->raise();
    dialog->activateWindow();
}

/************************************************

 ************************************************/
void Plugin::requestRemove()
{
    emit remove();
    deleteLater();
}
<|endoftext|>


<commit_before>//===-- CrossDSOCFI.cpp - Externalize this module's CFI checks ------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass exports all llvm.bitset's found in the module in the form of a
// __cfi_check function, which can be used to verify cross-DSO call targets.
//
//===----------------------------------------------------------------------===//

#include "llvm/Transforms/IPO.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/EquivalenceClasses.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalObject.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
#include "llvm/Pass.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"

using namespace llvm;

#define DEBUG_TYPE "cross-dso-cfi"

STATISTIC(TypeIds, "Number of unique type identifiers");

namespace {

struct CrossDSOCFI : public ModulePass {
  static char ID;
  CrossDSOCFI() : ModulePass(ID) {
    initializeCrossDSOCFIPass(*PassRegistry::getPassRegistry());
  }

  Module *M;
  MDNode *VeryLikelyWeights;

  ConstantInt *extractBitSetTypeId(MDNode *MD);
  void buildCFICheck();

  bool doInitialization(Module &M) override;
  bool runOnModule(Module &M) override;
};

} // anonymous namespace

INITIALIZE_PASS_BEGIN(CrossDSOCFI, "cross-dso-cfi", "Cross-DSO CFI", false,
                      false)
INITIALIZE_PASS_END(CrossDSOCFI, "cross-dso-cfi", "Cross-DSO CFI", false, false)
char CrossDSOCFI::ID = 0;

ModulePass *llvm::createCrossDSOCFIPass() { return new CrossDSOCFI; }

bool CrossDSOCFI::doInitialization(Module &Mod) {
  M = &Mod;
  VeryLikelyWeights =
      MDBuilder(M->getContext()).createBranchWeights((1U << 20) - 1, 1);

  return false;
}

/// extractBitSetTypeId - Extracts TypeId from a hash-based bitset MDNode.
ConstantInt *CrossDSOCFI::extractBitSetTypeId(MDNode *MD) {
  // This check excludes vtables for classes inside anonymous namespaces.
  auto TM = dyn_cast<ValueAsMetadata>(MD->getOperand(0));
  if (!TM)
    return nullptr;
  auto C = dyn_cast_or_null<ConstantInt>(TM->getValue());
  if (!C) return nullptr;
  // We are looking for i64 constants.
  if (C->getBitWidth() != 64) return nullptr;

  // Sanity check.
  auto FM = dyn_cast_or_null<ValueAsMetadata>(MD->getOperand(1));
  // Can be null if a function was removed by an optimization.
  if (FM) {
    auto F = dyn_cast<Function>(FM->getValue());
    // But can never be a function declaration.
    assert(!F || !F->isDeclaration());
  }
  return C;
}

/// buildCFICheck - emits __cfi_check for the current module.
void CrossDSOCFI::buildCFICheck() {
  // FIXME: verify that __cfi_check ends up near the end of the code section,
  // but before the jump slots created in LowerBitSets.
  llvm::DenseSet<uint64_t> BitSetIds;
  NamedMDNode *BitSetNM = M->getNamedMetadata("llvm.bitsets");

  if (BitSetNM)
    for (unsigned I = 0, E = BitSetNM->getNumOperands(); I != E; ++I)
      if (ConstantInt *TypeId = extractBitSetTypeId(BitSetNM->getOperand(I)))
        BitSetIds.insert(TypeId->getZExtValue());

  LLVMContext &Ctx = M->getContext();
  Constant *C = M->getOrInsertFunction(
      "__cfi_check",
      FunctionType::get(
          Type::getVoidTy(Ctx),
          {Type::getInt64Ty(Ctx), PointerType::getUnqual(Type::getInt8Ty(Ctx))},
          false));
  Function *F = dyn_cast<Function>(C);
  F->setAlignment(4096);
  auto args = F->arg_begin();
  Argument &CallSiteTypeId = *(args++);
  CallSiteTypeId.setName("CallSiteTypeId");
  Argument &Addr = *(args++);
  Addr.setName("Addr");
  assert(args == F->arg_end());

  BasicBlock *BB = BasicBlock::Create(Ctx, "entry", F);

  BasicBlock *TrapBB = BasicBlock::Create(Ctx, "trap", F);
  IRBuilder<> IRBTrap(TrapBB);
  Function *TrapFn = Intrinsic::getDeclaration(M, Intrinsic::trap);
  llvm::CallInst *TrapCall = IRBTrap.CreateCall(TrapFn);
  TrapCall->setDoesNotReturn();
  TrapCall->setDoesNotThrow();
  IRBTrap.CreateUnreachable();

  BasicBlock *ExitBB = BasicBlock::Create(Ctx, "exit", F);
  IRBuilder<> IRBExit(ExitBB);
  IRBExit.CreateRetVoid();

  IRBuilder<> IRB(BB);
  SwitchInst *SI = IRB.CreateSwitch(&CallSiteTypeId, TrapBB, BitSetIds.size());
  for (uint64_t TypeId : BitSetIds) {
    ConstantInt *CaseTypeId = ConstantInt::get(Type::getInt64Ty(Ctx), TypeId);
    BasicBlock *TestBB = BasicBlock::Create(Ctx, "test", F);
    IRBuilder<> IRBTest(TestBB);
    Function *BitsetTestFn =
        Intrinsic::getDeclaration(M, Intrinsic::bitset_test);

    Value *Test = IRBTest.CreateCall(
        BitsetTestFn, {&Addr, MetadataAsValue::get(
                                  Ctx, ConstantAsMetadata::get(CaseTypeId))});
    BranchInst *BI = IRBTest.CreateCondBr(Test, ExitBB, TrapBB);
    BI->setMetadata(LLVMContext::MD_prof, VeryLikelyWeights);

    SI->addCase(CaseTypeId, TestBB);
    ++TypeIds;
  }
}

bool CrossDSOCFI::runOnModule(Module &M) {
  if (M.getModuleFlag("Cross-DSO CFI") == nullptr)
    return false;
  buildCFICheck();
  return true;
}
<commit_msg>Cast variable to void to resolve unused variable warning in non-asserts builds.<commit_after>//===-- CrossDSOCFI.cpp - Externalize this module's CFI checks ------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass exports all llvm.bitset's found in the module in the form of a
// __cfi_check function, which can be used to verify cross-DSO call targets.
//
//===----------------------------------------------------------------------===//

#include "llvm/Transforms/IPO.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/EquivalenceClasses.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalObject.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
#include "llvm/Pass.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"

using namespace llvm;

#define DEBUG_TYPE "cross-dso-cfi"

STATISTIC(TypeIds, "Number of unique type identifiers");

namespace {

struct CrossDSOCFI : public ModulePass {
  static char ID;
  CrossDSOCFI() : ModulePass(ID) {
    initializeCrossDSOCFIPass(*PassRegistry::getPassRegistry());
  }

  Module *M;
  MDNode *VeryLikelyWeights;

  ConstantInt *extractBitSetTypeId(MDNode *MD);
  void buildCFICheck();

  bool doInitialization(Module &M) override;
  bool runOnModule(Module &M) override;
};

} // anonymous namespace

INITIALIZE_PASS_BEGIN(CrossDSOCFI, "cross-dso-cfi", "Cross-DSO CFI", false,
                      false)
INITIALIZE_PASS_END(CrossDSOCFI, "cross-dso-cfi", "Cross-DSO CFI", false, false)
char CrossDSOCFI::ID = 0;

ModulePass *llvm::createCrossDSOCFIPass() { return new CrossDSOCFI; }

bool CrossDSOCFI::doInitialization(Module &Mod) {
  M = &Mod;
  VeryLikelyWeights =
      MDBuilder(M->getContext()).createBranchWeights((1U << 20) - 1, 1);

  return false;
}

/// extractBitSetTypeId - Extracts TypeId from a hash-based bitset MDNode.
ConstantInt *CrossDSOCFI::extractBitSetTypeId(MDNode *MD) {
  // This check excludes vtables for classes inside anonymous namespaces.
  auto TM = dyn_cast<ValueAsMetadata>(MD->getOperand(0));
  if (!TM)
    return nullptr;
  auto C = dyn_cast_or_null<ConstantInt>(TM->getValue());
  if (!C) return nullptr;
  // We are looking for i64 constants.
  if (C->getBitWidth() != 64) return nullptr;

  // Sanity check.
  auto FM = dyn_cast_or_null<ValueAsMetadata>(MD->getOperand(1));
  // Can be null if a function was removed by an optimization.
  if (FM) {
    auto F = dyn_cast<Function>(FM->getValue());
    (void)F;
    // But can never be a function declaration.
    assert(!F || !F->isDeclaration());
  }
  return C;
}

/// buildCFICheck - emits __cfi_check for the current module.
void CrossDSOCFI::buildCFICheck() {
  // FIXME: verify that __cfi_check ends up near the end of the code section,
  // but before the jump slots created in LowerBitSets.
  llvm::DenseSet<uint64_t> BitSetIds;
  NamedMDNode *BitSetNM = M->getNamedMetadata("llvm.bitsets");

  if (BitSetNM)
    for (unsigned I = 0, E = BitSetNM->getNumOperands(); I != E; ++I)
      if (ConstantInt *TypeId = extractBitSetTypeId(BitSetNM->getOperand(I)))
        BitSetIds.insert(TypeId->getZExtValue());

  LLVMContext &Ctx = M->getContext();
  Constant *C = M->getOrInsertFunction(
      "__cfi_check",
      FunctionType::get(
          Type::getVoidTy(Ctx),
          {Type::getInt64Ty(Ctx), PointerType::getUnqual(Type::getInt8Ty(Ctx))},
          false));
  Function *F = dyn_cast<Function>(C);
  F->setAlignment(4096);
  auto args = F->arg_begin();
  Argument &CallSiteTypeId = *(args++);
  CallSiteTypeId.setName("CallSiteTypeId");
  Argument &Addr = *(args++);
  Addr.setName("Addr");
  assert(args == F->arg_end());

  BasicBlock *BB = BasicBlock::Create(Ctx, "entry", F);

  BasicBlock *TrapBB = BasicBlock::Create(Ctx, "trap", F);
  IRBuilder<> IRBTrap(TrapBB);
  Function *TrapFn = Intrinsic::getDeclaration(M, Intrinsic::trap);
  llvm::CallInst *TrapCall = IRBTrap.CreateCall(TrapFn);
  TrapCall->setDoesNotReturn();
  TrapCall->setDoesNotThrow();
  IRBTrap.CreateUnreachable();

  BasicBlock *ExitBB = BasicBlock::Create(Ctx, "exit", F);
  IRBuilder<> IRBExit(ExitBB);
  IRBExit.CreateRetVoid();

  IRBuilder<> IRB(BB);
  SwitchInst *SI = IRB.CreateSwitch(&CallSiteTypeId, TrapBB, BitSetIds.size());
  for (uint64_t TypeId : BitSetIds) {
    ConstantInt *CaseTypeId = ConstantInt::get(Type::getInt64Ty(Ctx), TypeId);
    BasicBlock *TestBB = BasicBlock::Create(Ctx, "test", F);
    IRBuilder<> IRBTest(TestBB);
    Function *BitsetTestFn =
        Intrinsic::getDeclaration(M, Intrinsic::bitset_test);

    Value *Test = IRBTest.CreateCall(
        BitsetTestFn, {&Addr, MetadataAsValue::get(
                                  Ctx, ConstantAsMetadata::get(CaseTypeId))});
    BranchInst *BI = IRBTest.CreateCondBr(Test, ExitBB, TrapBB);
    BI->setMetadata(LLVMContext::MD_prof, VeryLikelyWeights);

    SI->addCase(CaseTypeId, TestBB);
    ++TypeIds;
  }
}

bool CrossDSOCFI::runOnModule(Module &M) {
  if (M.getModuleFlag("Cross-DSO CFI") == nullptr)
    return false;
  buildCFICheck();
  return true;
}
<|endoftext|>


<commit_before>#include <gtest/gtest.h>

#include <string>

#include <cpr/payload.h>
#include <cpr/parameters.h>

using namespace cpr;

TEST(PayloadTests, UseStringVariableTest) {
    std::string value1 = "hello";
    std::string key2 = "key2";
    Payload payload {{"key1", value1}, {key2, "world"}};

    std::string expected = "key1=hello&key2=world";
    EXPECT_EQ(payload.GetContent(CurlHolder()), expected);
}

TEST(PayloadTests, DisableEncodingTest) {
    std::string key1 = "key1";
    std::string key2 = "key2§$%&/";
    std::string value1 = "hello.,.,";
    std::string value2 = "hello";
    Payload payload{{key1, value1}, {key2, value2}};
    payload.encode = false;

    std::string expected = key1 + '=' + value1 + '&' + key2 + '=' + value2;
    EXPECT_EQ(payload.GetContent(CurlHolder()), expected);
}

TEST(ParametersTests, UseStringVariableTest) {
    std::string value1 = "hello";
    std::string key2 = "key2";
    Parameters parameters {{"key1", value1}, {key2, "world"}};

    std::string expected = "key1=hello&key2=world";
    EXPECT_EQ(parameters.GetContent(CurlHolder()), expected);
}

TEST(ParametersTests, DisableEncodingTest) {
    std::string key1 = "key1";
    std::string key2 = "key2§$%&/";
    std::string value1 = "hello.,.,";
    std::string value2 = "hello";
    Parameters parameters{{key1, value1}, {key2, value2}};
    parameters.encode = false;

    std::string expected = key1 + '=' + value1 + '&' + key2 + '=' + value2;
    EXPECT_EQ(parameters.GetContent(CurlHolder()), expected);
}

int main(int argc, char** argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
<commit_msg>Added a test case to test url string conversion<commit_after>#include "cpr/cprtypes.h"
#include <gtest/gtest.h>

#include <string>

#include <cpr/payload.h>
#include <cpr/parameters.h>

using namespace cpr;

TEST(PayloadTests, UseStringVariableTest) {
    std::string value1 = "hello";
    std::string key2 = "key2";
    Payload payload {{"key1", value1}, {key2, "world"}};

    std::string expected = "key1=hello&key2=world";
    EXPECT_EQ(payload.GetContent(CurlHolder()), expected);
}

TEST(PayloadTests, DisableEncodingTest) {
    std::string key1 = "key1";
    std::string key2 = "key2§$%&/";
    std::string value1 = "hello.,.,";
    std::string value2 = "hello";
    Payload payload{{key1, value1}, {key2, value2}};
    payload.encode = false;

    std::string expected = key1 + '=' + value1 + '&' + key2 + '=' + value2;
    EXPECT_EQ(payload.GetContent(CurlHolder()), expected);
}

TEST(ParametersTests, UseStringVariableTest) {
    std::string value1 = "hello";
    std::string key2 = "key2";
    Parameters parameters {{"key1", value1}, {key2, "world"}};

    std::string expected = "key1=hello&key2=world";
    EXPECT_EQ(parameters.GetContent(CurlHolder()), expected);
}

TEST(ParametersTests, DisableEncodingTest) {
    std::string key1 = "key1";
    std::string key2 = "key2§$%&/";
    std::string value1 = "hello.,.,";
    std::string value2 = "hello";
    Parameters parameters{{key1, value1}, {key2, value2}};
    parameters.encode = false;

    std::string expected = key1 + '=' + value1 + '&' + key2 + '=' + value2;
    EXPECT_EQ(parameters.GetContent(CurlHolder()), expected);
}

TEST(UrlToAndFromString, UrlTests) {
    std::string s{"https://github.com/whoshuu/cpr"};
    cpr::Url url = s;
    EXPECT_EQ(s, url.str());
}

int main(int argc, char** argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>/**
 * Copyright 2014, Planet Labs, Inc.
 *
 * 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 "compositor.h"

/************************************************************************/
/*                         SceneMeasureQuality                          */
/************************************************************************/

class SceneMeasureQuality : public QualityMethodBase
{
    PLCInput *input;
    float measureValue;

public:
    SceneMeasureQuality() : QualityMethodBase("scene_measure") {}
    ~SceneMeasureQuality() {}

    /********************************************************************/
    QualityMethodBase *create(PLCContext* plContext, PLCInput* input) {

        SceneMeasureQuality *obj = new SceneMeasureQuality();
        obj->input = input;

        const char *measureName =
            plContext->strategyParams.FetchNameValueDef("scene_measure",
                                                        "NULL");
        float direction = 1.0;
        if( measureName[0] == '-' )
        {
            measureName++;
            direction = -1.0;
        }

        obj->measureValue = input->getQM(measureName);

        if( obj->measureValue < 0.0 )
        {
            CPLError( CE_Fatal, CPLE_AppDefined,
                      "Scene %s lacks quality measure %s.",
                      input->getFilename(),
                      measureName);
        }

        if( direction < 0.0 )
            obj->measureValue = 100000000.0 - obj->measureValue;

        return obj;
    }

    /********************************************************************/
    int computeQuality(PLCLine *lineObj) {

        float *quality = lineObj->getQuality();
        int width = lineObj->getWidth();

        for(int iBand=0; iBand < lineObj->getBandCount(); iBand++)
        {
            for(int i=0; i < width; i++ )
                quality[i] = measureValue;
        }

        GByte *alpha = lineObj->getAlpha();
        for(int i=0; i < width; i++ )
        {
            if( alpha[i] < 128 )
                quality[i] = -1.0;
        }

        return TRUE;
    }
};

static SceneMeasureQuality sceneMeasureQualityTemplateInstance;

<commit_msg>move initialization into a method<commit_after>/**
 * Copyright 2014, Planet Labs, Inc.
 *
 * 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 "compositor.h"

/************************************************************************/
/*                         SceneMeasureQuality                          */
/************************************************************************/

class SceneMeasureQuality : public QualityMethodBase
{
    PLCInput *input;
    float measureValue;

public:
    SceneMeasureQuality() : QualityMethodBase("scene_measure") {}
    ~SceneMeasureQuality() {}

    /********************************************************************/
    QualityMethodBase *create(PLCContext* plContext, PLCInput* input) {

        SceneMeasureQuality *obj = new SceneMeasureQuality();
        obj->initialize(plContext, input);
        return obj;
    }

    /********************************************************************/
    void initialize(PLCContext *plContext, PLCInput* input) {
        input = input;

        const char *measureName =
            plContext->strategyParams.FetchNameValueDef("scene_measure",
                                                        "NULL");
        float direction = 1.0;
        if( measureName[0] == '-' )
        {
            measureName++;
            direction = -1.0;
        }

        measureValue = input->getQM(measureName);

        if( measureValue < 0.0 )
        {
            CPLError( CE_Fatal, CPLE_AppDefined,
                      "Scene %s lacks quality measure %s.",
                      input->getFilename(),
                      measureName);
        }

        if( direction < 0.0 )
            measureValue = 100000000.0 - measureValue;
    }

    /********************************************************************/
    int computeQuality(PLCLine *lineObj) {

        float *quality = lineObj->getQuality();
        int width = lineObj->getWidth();

        for(int iBand=0; iBand < lineObj->getBandCount(); iBand++)
        {
            for(int i=0; i < width; i++ )
                quality[i] = measureValue;
        }

        GByte *alpha = lineObj->getAlpha();
        for(int i=0; i < width; i++ )
        {
            if( alpha[i] < 128 )
                quality[i] = -1.0;
        }

        return TRUE;
    }
};

static SceneMeasureQuality sceneMeasureQualityTemplateInstance;

<|endoftext|>


<commit_before>// @(#)root/oracle:$Id$
// Author: Yan Liu and Shaowen Wang   23/11/04

/*************************************************************************
 * Copyright (C) 1995-2005, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "TOracleRow.h"
#include "TOracleServer.h"
#include <string.h>

ClassImp(TOracleRow);

using namespace std;
using namespace oracle::occi;

//______________________________________________________________________________
TOracleRow::TOracleRow(ResultSet *rs, vector<MetaData> *fieldMetaData)
{
   // Single row of query result.

   fResult      = rs;
   fFieldInfo   = fieldMetaData;
   fFieldCount  = fFieldInfo->size();

   fFieldsBuffer = 0;

   GetRowData();
}

//______________________________________________________________________________
TOracleRow::~TOracleRow()
{
   // Destroy row object.

   Close();
}

//______________________________________________________________________________
void TOracleRow::Close(Option_t *)
{
   // Close row.

   if (fFieldsBuffer!=0) {
      for (int n=0;n<fFieldCount;n++)
        if (fFieldsBuffer[n]) delete[] fFieldsBuffer[n];
      delete[] fFieldsBuffer;
   }

   fFieldInfo   = 0;
   fFieldCount  = 0;
   fResult      = 0;
}

//______________________________________________________________________________
Bool_t TOracleRow::IsValid(Int_t field)
{
   // Check if row is open and field index within range.

   if (!fResult) {
      Error("IsValid", "row closed");
      return kFALSE;
   }
   if (field < 0 || field >= (Int_t)fFieldInfo->size()) {
      Error("IsValid", "field index out of bounds");
      return kFALSE;
   }
   return kTRUE;
}

//______________________________________________________________________________
ULong_t TOracleRow::GetFieldLength(Int_t field)
{
   // Get length in bytes of specified field.

   if (!IsValid(field) || fFieldInfo->size() <= 0)
      return 0;

   MetaData fieldMD = (*fFieldInfo)[field];

   return fieldMD.getInt(MetaData::ATTR_DATA_SIZE);
}

//______________________________________________________________________________
const char* TOracleRow::GetField(Int_t field)
{
   if ((field<0) || (field>=fFieldCount)) {
      Error("TOracleRow","GetField(): out-of-range or No RowData/ResultSet/MetaData");
      return 0;
   }

   return fFieldsBuffer ? fFieldsBuffer[field] : 0;
}

//______________________________________________________________________________
void TOracleRow::GetRowData()
{
   if (!fResult || !fFieldInfo || (fFieldCount<=0)) return;

   fFieldsBuffer = new char* [fFieldCount];
   for (int n=0;n<fFieldCount;n++)
     fFieldsBuffer[n] = 0;

   std::string res;

   char str_number[200];

   int fPrecision, fScale, fDataType;
   double double_val;

   try {

   for (int field=0;field<fFieldCount;field++) {
      if (fResult->isNull(field+1)) continue;

      fDataType = (*fFieldInfo)[field].getInt(MetaData::ATTR_DATA_TYPE);

      switch (fDataType) {
        case SQLT_NUM: //NUMBER
           fPrecision = (*fFieldInfo)[field].getInt(MetaData::ATTR_PRECISION);
           fScale = (*fFieldInfo)[field].getInt(MetaData::ATTR_SCALE);

           if ((fScale == 0) || (fPrecision == 0)) {
              res = fResult->getString(field+1);
           } else {
              double_val = fResult->getDouble(field+1);
              snprintf(str_number, sizeof(str_number), TSQLServer::GetFloatFormat(), double_val);
              res = str_number;
           }
           break;

        case SQLT_CHR:  // character string
        case SQLT_VCS:  // variable character string
        case SQLT_AFC: // ansi fixed char
        case SQLT_AVC: // ansi var char
           res = fResult->getString(field+1);
           break;
        case SQLT_DAT:  // Oracle native DATE type
           res = (fResult->getDate(field+1)).toText(TOracleServer::GetDatimeFormat());
           break;
        case SQLT_TIMESTAMP:     // TIMESTAMP
        case SQLT_TIMESTAMP_TZ:  // TIMESTAMP WITH TIMEZONE
        case SQLT_TIMESTAMP_LTZ: // TIMESTAMP WITH LOCAL TIMEZONE
           res = (fResult->getTimestamp(field+1)).toText(TOracleServer::GetDatimeFormat(), 0);
           break;
        default:
           Error("GetRowData","Oracle type %d not supported.", fDataType);
           continue;
      }

      int len = res.length();
      if (len>0) {
         fFieldsBuffer[field] = new char[len+1];
         strcpy(fFieldsBuffer[field], res.c_str());
      }
   }

   } catch (SQLException &oraex) {
      Error("GetRowData", "%s", (oraex.getMessage()).c_str());
   }
}
<commit_msg>From Sergey:<commit_after>// @(#)root/oracle:$Id$
// Author: Yan Liu and Shaowen Wang   23/11/04

/*************************************************************************
 * Copyright (C) 1995-2005, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "TOracleRow.h"
#include "TOracleServer.h"
#include <string.h>

ClassImp(TOracleRow);

using namespace std;
using namespace oracle::occi;

//______________________________________________________________________________
TOracleRow::TOracleRow(ResultSet *rs, vector<MetaData> *fieldMetaData)
{
   // Single row of query result.

   fResult      = rs;
   fFieldInfo   = fieldMetaData;
   fFieldCount  = fFieldInfo->size();

   fFieldsBuffer = 0;

   GetRowData();
}

//______________________________________________________________________________
TOracleRow::~TOracleRow()
{
   // Destroy row object.

   Close();
}

//______________________________________________________________________________
void TOracleRow::Close(Option_t *)
{
   // Close row.

   if (fFieldsBuffer!=0) {
      for (int n=0;n<fFieldCount;n++)
        if (fFieldsBuffer[n]) delete[] fFieldsBuffer[n];
      delete[] fFieldsBuffer;
   }

   fFieldInfo   = 0;
   fFieldCount  = 0;
   fResult      = 0;
}

//______________________________________________________________________________
Bool_t TOracleRow::IsValid(Int_t field)
{
   // Check if row is open and field index within range.

   if (!fResult) {
      Error("IsValid", "row closed");
      return kFALSE;
   }
   if (field < 0 || field >= (Int_t)fFieldInfo->size()) {
      Error("IsValid", "field index out of bounds");
      return kFALSE;
   }
   return kTRUE;
}

//______________________________________________________________________________
ULong_t TOracleRow::GetFieldLength(Int_t field)
{
   // Get length in bytes of specified field.

   if (!IsValid(field) || fFieldInfo->size() <= 0)
      return 0;

   MetaData fieldMD = (*fFieldInfo)[field];

   return fieldMD.getInt(MetaData::ATTR_DATA_SIZE);
}

//______________________________________________________________________________
const char* TOracleRow::GetField(Int_t field)
{
   if ((field<0) || (field>=fFieldCount)) {
      Error("TOracleRow","GetField(): out-of-range or No RowData/ResultSet/MetaData");
      return 0;
   }

   return fFieldsBuffer ? fFieldsBuffer[field] : 0;
}

//______________________________________________________________________________
void TOracleRow::GetRowData()
{
   if (!fResult || !fFieldInfo || (fFieldCount<=0)) return;

   fFieldsBuffer = new char* [fFieldCount];
   for (int n=0;n<fFieldCount;n++)
     fFieldsBuffer[n] = 0;

   std::string res;

   char str_number[200];

   int fPrecision, fScale, fDataType;
   double double_val;

   try {

   for (int field=0;field<fFieldCount;field++) {
      if (fResult->isNull(field+1)) continue;

      fDataType = (*fFieldInfo)[field].getInt(MetaData::ATTR_DATA_TYPE);

      switch (fDataType) {
        case SQLT_NUM: //NUMBER
           fPrecision = (*fFieldInfo)[field].getInt(MetaData::ATTR_PRECISION);
           fScale = (*fFieldInfo)[field].getInt(MetaData::ATTR_SCALE);

           if ((fScale == 0) || (fPrecision == 0)) {
              res = fResult->getString(field+1);
           } else {
              double_val = fResult->getDouble(field+1);
              snprintf(str_number, sizeof(str_number), TSQLServer::GetFloatFormat(), double_val);
              res = str_number;
           }
           break;

        case SQLT_CHR:  // character string
        case SQLT_VCS:  // variable character string
        case SQLT_AFC: // ansi fixed char
        case SQLT_AVC: // ansi var char
           res = fResult->getString(field+1);
           break;
        case SQLT_DAT:  // Oracle native DATE type
           res = (fResult->getDate(field+1)).toText(TOracleServer::GetDatimeFormat());
           break;
        case SQLT_TIMESTAMP:     // TIMESTAMP
        case SQLT_TIMESTAMP_TZ:  // TIMESTAMP WITH TIMEZONE
        case SQLT_TIMESTAMP_LTZ: // TIMESTAMP WITH LOCAL TIMEZONE
           res = (fResult->getTimestamp(field+1)).toText(TOracleServer::GetDatimeFormat(), 0);
           break;
        case SQLT_IBFLOAT:
        case SQLT_IBDOUBLE:
           res = fResult->getString(field+1);
           break;
        default:
           Error("GetRowData","Oracle type %d was not yet tested - please inform ROOT developers", fDataType);
           continue;
      }

      int len = res.length();
      if (len>0) {
         fFieldsBuffer[field] = new char[len+1];
         strcpy(fFieldsBuffer[field], res.c_str());
      }
   }

   } catch (SQLException &oraex) {
      Error("GetRowData", "%s", (oraex.getMessage()).c_str());
   }
}
<|endoftext|>


<commit_before>//----------------------------------------------------------------------------//
//                 █      █                                                   //
//                 ████████                                                   //
//               ██        ██                                                 //
//              ███  █  █  ███    AudioManager.cpp                            //
//              █ █        █ █    MonsterFramework                            //
//               ████████████                                                 //
//             █              █   Copyright (c) 2015 AmazingCow               //
//            █     █    █     █  www.AmazingCow.com                          //
//            █     █    █     █                                              //
//             █              █   N2OMatt - n2omatt@amazingcow.com            //
//               ████████████     www.amazingcow.com/n2omatt                  //
//                                                                            //
//                                                                            //
//                  This software is licensed as BSD-3                        //
//                 CHECK THE COPYING FILE TO MORE DETAILS                     //
//                                                                            //
//    Permission is granted to anyone to use this software for any purpose,   //
//   including commercial applications, and to alter it and redistribute it   //
//               freely, subject to the following restrictions:               //
//                                                                            //
//     0. You **CANNOT** change the type of the license.                      //
//     1. The origin of this software must not be misrepresented;             //
//        you must not claim that you wrote the original software.            //
//     2. If you use this software in a product, an acknowledgment in the     //
//        product IS HIGHLY APPRECIATED, both in source and binary forms.     //
//        (See opensource.AmazingCow.com/acknowledgment.html for details).    //
//        If you will not acknowledge, just send us a email. We'll be         //
//        *VERY* happy to see our work being used by other people. :)         //
//        The email is: acknowledgmentopensource@AmazingCow.com               //
//     3. Altered source versions must be plainly marked as such,             //
//        and must notbe misrepresented as being the original software.       //
//     4. This notice may not be removed or altered from any source           //
//        distribution.                                                       //
//     5. Most important, you must have fun. ;)                               //
//                                                                            //
//      Visit opensource.amazingcow.com for more open-source projects.        //
//                                                                            //
//                                  Enjoy :)                                  //
//----------------------------------------------------------------------------//

//Header
#include "MonsterFramework/include/Audio/AudioManager.h"

//Usings
USING_NS_STD_CC_CD_MF

// Singleton //
AudioManager* AudioManager::instance()
{
    static AudioManager s_instance;
    return &s_instance;
}

// CTOR/DTOR //
AudioManager::AudioManager() :
    m_pAudioEngine(SimpleAudioEngine::getInstance()),
    m_prevFxVol(m_pAudioEngine->getEffectsVolume())
{
    //Empty...
}
AudioManager::~AudioManager()
{
    //Release the SimpleAudioEngine.
    SimpleAudioEngine::end();
}

// Public Methods //
//General
void AudioManager::muteAll(bool mute)
{
    if(mute)
    {
        //Save the current volumes to later restore.
        m_prevFxVol  = getEffectsVolume();
        setEffectsVolume(0);
    }
    else
    {
        //Restore the previous volumes.
        setEffectsVolume(m_prevFxVol);
    }
    MF_LOG("AudioManager - Audio is now %s", mute ? "Off" : "On");
}
bool AudioManager::isMuted()
{
    return getEffectsVolume() == 0;
}

//Effects
void AudioManager::loadEffect(const std::string &effectId, const std::string &path)
{
#if MONSTERFRAMEWORK_DEBUG
    //In Debug mode check if file exists...
    auto fileExists = FileUtils::getInstance()->isFileExist(path.c_str());
    MF_ASSERT(fileExists, "Audio Manager - Cannot load effect file [PATH:(%s)]", path.c_str());
#endif

    //Insert a default invalid id into effects map with effectId key.
    m_effectsMap[effectId] = make_pair(path, -1);
    m_pAudioEngine->preloadEffect(path.c_str());

    MF_LOG("AudioManager - LoadEffect: (%s)", path.c_str());
}
void AudioManager::unloadEffect(const std::string &effectId)
{
    //Check if effectId is valid.
    auto it = m_effectsMap.find(effectId);
    MF_ASSERT((it == end(m_effectsMap)), "Audio Manager - Invalid EffectId %s", effectId.c_str());

    //Remove the effect from audio engine and delete it
    //from effects map.
    m_pAudioEngine->unloadEffect(it->second.first.c_str());
    m_effectsMap.erase(effectId);
}

void AudioManager::playEffect(const std::string &effectId, bool loop)
{
    //Get the iterator for effectId.
    auto it = m_effectsMap.find(effectId);
#if MONSTERFRAMEWORK_DEBUG
    //In Debug mode check if file exists...
    MF_ASSERT((it == m_effectsMap.end()), "Audio Manager - EffectId is not loaded:(%s)", effectId.c_str());
#endif

    //Play effect and update its engine id.
    int id = m_pAudioEngine->playEffect(it->second.first.c_str(), loop);
    m_effectsMap[effectId].second = id;

    //Log
    MF_LOG("AudioManager - Playing Effect:(%s) - EngineId:(%d)", effectId.c_str(), id);
}
void AudioManager::pauseEffect(const std::string &effectId)
{
    //Get the iterator for effectId.
    auto it = m_effectsMap.find(effectId);
#if MONSTERFRAMEWORK_DEBUG
    //In Debug mode check if file exists...
    MF_ASSERT((it == m_effectsMap.end()), "Audio Manager - EffectId is not loaded:(%s)", effectId.c_str());
#endif

    m_pAudioEngine->pauseEffect(it->second.second);
}
void AudioManager::pauseAllEffects()
{
    m_pAudioEngine->pauseAllEffects();
}
void AudioManager::resumeEffect(const std::string &effectId)
{
    //Get the iterator for effectId.
    auto it = m_effectsMap.find(effectId);
#if MONSTERFRAMEWORK_DEBUG
    //In Debug mode check if file exists...
    MF_ASSERT((it == m_effectsMap.end()), "Audio Manager - EffectId is not loaded:(%s)", effectId.c_str());
#endif

    m_pAudioEngine->resumeEffect(it->second.second);
}
void AudioManager::resumeAllEffects()
{
    m_pAudioEngine->resumeAllEffects();
}
void AudioManager::stopEffect(const std::string &effectId)
{
    //Get the iterator for effectId.
    auto it = m_effectsMap.find(effectId);
#if MONSTERFRAMEWORK_DEBUG
    //In Debug mode check if file exists...
    MF_ASSERT((it == m_effectsMap.end()), "Audio Manager - EffectId is not loaded:(%s)", effectId.c_str());
#endif

    m_pAudioEngine->stopEffect(it->second.second);
}
void AudioManager::stopAllEffects()
{
    m_pAudioEngine->stopAllEffects();
}

float AudioManager::getEffectsVolume()
{
    return m_pAudioEngine->getEffectsVolume();
}
void AudioManager::setEffectsVolume(float volume)
{
    m_pAudioEngine->setEffectsVolume(volume);
}
<commit_msg>Fix the wrongs ASSERT checks.<commit_after>//----------------------------------------------------------------------------//
//                 █      █                                                   //
//                 ████████                                                   //
//               ██        ██                                                 //
//              ███  █  █  ███    AudioManager.cpp                            //
//              █ █        █ █    MonsterFramework                            //
//               ████████████                                                 //
//             █              █   Copyright (c) 2015 AmazingCow               //
//            █     █    █     █  www.AmazingCow.com                          //
//            █     █    █     █                                              //
//             █              █   N2OMatt - n2omatt@amazingcow.com            //
//               ████████████     www.amazingcow.com/n2omatt                  //
//                                                                            //
//                                                                            //
//                  This software is licensed as BSD-3                        //
//                 CHECK THE COPYING FILE TO MORE DETAILS                     //
//                                                                            //
//    Permission is granted to anyone to use this software for any purpose,   //
//   including commercial applications, and to alter it and redistribute it   //
//               freely, subject to the following restrictions:               //
//                                                                            //
//     0. You **CANNOT** change the type of the license.                      //
//     1. The origin of this software must not be misrepresented;             //
//        you must not claim that you wrote the original software.            //
//     2. If you use this software in a product, an acknowledgment in the     //
//        product IS HIGHLY APPRECIATED, both in source and binary forms.     //
//        (See opensource.AmazingCow.com/acknowledgment.html for details).    //
//        If you will not acknowledge, just send us a email. We'll be         //
//        *VERY* happy to see our work being used by other people. :)         //
//        The email is: acknowledgmentopensource@AmazingCow.com               //
//     3. Altered source versions must be plainly marked as such,             //
//        and must notbe misrepresented as being the original software.       //
//     4. This notice may not be removed or altered from any source           //
//        distribution.                                                       //
//     5. Most important, you must have fun. ;)                               //
//                                                                            //
//      Visit opensource.amazingcow.com for more open-source projects.        //
//                                                                            //
//                                  Enjoy :)                                  //
//----------------------------------------------------------------------------//

//Header
#include "MonsterFramework/include/Audio/AudioManager.h"

//Usings
USING_NS_STD_CC_CD_MF

// Singleton //
AudioManager* AudioManager::instance()
{
    static AudioManager s_instance;
    return &s_instance;
}

// CTOR/DTOR //
AudioManager::AudioManager() :
    m_pAudioEngine(SimpleAudioEngine::getInstance()),
    m_prevFxVol(m_pAudioEngine->getEffectsVolume())
{
    //Empty...
}
AudioManager::~AudioManager()
{
    //Release the SimpleAudioEngine.
    SimpleAudioEngine::end();
}

// Public Methods //
//General
void AudioManager::muteAll(bool mute)
{
    if(mute)
    {
        //Save the current volumes to later restore.
        m_prevFxVol  = getEffectsVolume();
        setEffectsVolume(0);
    }
    else
    {
        //Restore the previous volumes.
        setEffectsVolume(m_prevFxVol);
    }
    MF_LOG("AudioManager - Audio is now %s", mute ? "Off" : "On");
}
bool AudioManager::isMuted()
{
    return getEffectsVolume() == 0;
}

//Effects
void AudioManager::loadEffect(const std::string &effectId, const std::string &path)
{
#if MONSTERFRAMEWORK_DEBUG
    //In Debug mode check if file exists...
    auto fileExists = FileUtils::getInstance()->isFileExist(path.c_str());
    MF_ASSERT(fileExists, "Audio Manager - Cannot load effect file [PATH:(%s)]", path.c_str());
#endif

    //Insert a default invalid id into effects map with effectId key.
    m_effectsMap[effectId] = make_pair(path, -1);
    m_pAudioEngine->preloadEffect(path.c_str());

    MF_LOG("AudioManager - LoadEffect: (%s)", path.c_str());
}
void AudioManager::unloadEffect(const std::string &effectId)
{
    //Check if effectId is valid.
    auto it = m_effectsMap.find(effectId);
    MF_ASSERT((it != end(m_effectsMap)), "Audio Manager - Invalid EffectId %s", effectId.c_str());

    //Remove the effect from audio engine and delete it from effects map.
    m_pAudioEngine->unloadEffect(it->second.first.c_str());
    m_effectsMap.erase(effectId);
}

void AudioManager::playEffect(const std::string &effectId, bool loop)
{
    //Get the iterator for effectId.
    auto it = m_effectsMap.find(effectId);
#if MONSTERFRAMEWORK_DEBUG
    //In Debug mode check if file exists...
    MF_ASSERT((it != m_effectsMap.end()), "Audio Manager - EffectId is not loaded:(%s)", effectId.c_str());
#endif

    //Play effect and update its engine id.
    int id = m_pAudioEngine->playEffect(it->second.first.c_str(), loop);
    m_effectsMap[effectId].second = id;

    //Log
    MF_LOG("AudioManager - Playing Effect:(%s) - EngineId:(%d)", effectId.c_str(), id);
}
void AudioManager::pauseEffect(const std::string &effectId)
{
    //Get the iterator for effectId.
    auto it = m_effectsMap.find(effectId);
#if MONSTERFRAMEWORK_DEBUG
    //In Debug mode check if file exists...
    MF_ASSERT((it != m_effectsMap.end()), "Audio Manager - EffectId is not loaded:(%s)", effectId.c_str());
#endif

    m_pAudioEngine->pauseEffect(it->second.second);
}
void AudioManager::pauseAllEffects()
{
    m_pAudioEngine->pauseAllEffects();
}
void AudioManager::resumeEffect(const std::string &effectId)
{
    //Get the iterator for effectId.
    auto it = m_effectsMap.find(effectId);
#if MONSTERFRAMEWORK_DEBUG
    //In Debug mode check if file exists...
    MF_ASSERT((it != m_effectsMap.end()), "Audio Manager - EffectId is not loaded:(%s)", effectId.c_str());
#endif

    m_pAudioEngine->resumeEffect(it->second.second);
}
void AudioManager::resumeAllEffects()
{
    m_pAudioEngine->resumeAllEffects();
}
void AudioManager::stopEffect(const std::string &effectId)
{
    //Get the iterator for effectId.
    auto it = m_effectsMap.find(effectId);
#if MONSTERFRAMEWORK_DEBUG
    //In Debug mode check if file exists...
    MF_ASSERT((it != m_effectsMap.end()), "Audio Manager - EffectId is not loaded:(%s)", effectId.c_str());
#endif

    m_pAudioEngine->stopEffect(it->second.second);
}
void AudioManager::stopAllEffects()
{
    m_pAudioEngine->stopAllEffects();
}

float AudioManager::getEffectsVolume()
{
    return m_pAudioEngine->getEffectsVolume();
}
void AudioManager::setEffectsVolume(float volume)
{
    m_pAudioEngine->setEffectsVolume(volume);
}
<|endoftext|>


<commit_before>/* Copyright (c) 2008-2017 the MRtrix3 contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, you can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * MRtrix 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.
 *
 * For more details, see http://www.mrtrix.org/.
 */

#include "command.h"
#include "math/math.h"
#include "image.h"
#include "thread.h"
#include "thread_queue.h"
#include "dwi/tractography/file.h"
#include "dwi/tractography/properties.h"
#include "dwi/tractography/resampling/arc.h"
#include "dwi/tractography/resampling/downsampler.h"
#include "dwi/tractography/resampling/endpoints.h"
#include "dwi/tractography/resampling/fixed_num_points.h"
#include "dwi/tractography/resampling/fixed_step_size.h"
#include "dwi/tractography/resampling/resampling.h"
#include "dwi/tractography/resampling/upsampler.h"

using namespace MR;
using namespace App;
using namespace DWI::Tractography;

void usage ()
{

  AUTHOR = "Robert E. Smith (robert.smith@florey.edu.au) and J-Donald Tournier (jdtournier@gmail.com)";

  SYNOPSIS = "Resample each streamline in a track file to a new set of vertices";

  DESCRIPTION
  + "This may be either increasing or decreasing the number of samples along "
    "each streamline, or changing the positions of the samples according to "
    "some specified trajectory."

  + DWI::Tractography::preserve_track_order_desc;

  ARGUMENTS
  + Argument ("in_tracks",  "the input track file").type_tracks_in()
  + Argument ("out_tracks", "the output resampled tracks").type_tracks_out();

  OPTIONS
    + Resampling::ResampleOption;

    // TODO Resample according to an exemplar streamline
}

typedef float value_type;

class Worker
{ NOMEMALIGN
  public:
    Worker (const std::unique_ptr<Resampling::Base>& in) :
        resampler (in->clone()) { }

    Worker (const Worker& that) :
        resampler (that.resampler->clone()) { }

    bool operator() (const Streamline<value_type>& in, Streamline<value_type>& out) const {
      return (*resampler) (in, out);
    }

  private:
    std::unique_ptr<Resampling::Base> resampler;
};

class Receiver
{ NOMEMALIGN
  public:
    Receiver (const std::string& path, const Properties& properties) :
        writer (path, properties),
        progress ("resampling streamlines") { }

    bool operator() (const Streamline<value_type>& tck) {
      auto progress_message = [&](){ return "resampling streamlines (count: " + str(writer.count) + ", skipped: " + str(writer.total_count - writer.count) + ")"; };
      writer (tck);
      progress.set_text (progress_message());
      return true;
    }

  private:
    Writer<value_type> writer;
    ProgressBar progress;

};

void run ()
{
  Properties properties;
  Reader<value_type> read (argument[0], properties);

  const std::unique_ptr<Resampling::Base> resampler (Resampling::get_resampler());

  float old_step_size = NaN;
  try {
    Properties::const_iterator i = properties.find ("output_step_size");
    if (i == properties.end()) {
      i = properties.find ("step_size");
      if (i != properties.end())
        old_step_size = to<float> (i->second);
    } else {
      old_step_size = to<float> (i->second);
    }
  } catch (...) {
    DEBUG ("Unable to read input track file step size");
  }

  float new_step_size = NaN;
  if (typeid (*resampler) == typeid (Resampling::FixedStepSize)) {
    new_step_size = dynamic_cast<Resampling::FixedStepSize*> (resampler.get())->get_step_size();
  } else if (std::isfinite (old_step_size)) {
    if (typeid (*resampler) == typeid (Resampling::Downsampler))
      new_step_size = old_step_size * dynamic_cast<Resampling::Downsampler*> (resampler.get())->get_ratio();
    if (typeid (*resampler) == typeid (Resampling::Upsampler))
      new_step_size = old_step_size / dynamic_cast<Resampling::Upsampler*> (resampler.get())->get_ratio();
  }
  properties["output_step_size"] = std::isfinite (new_step_size) ? str(new_step_size) : "variable";

  auto downsample = properties.find ("downsample_factor");
  if (downsample != properties.end())
    properties.erase (downsample);

  Worker worker (resampler);
  Receiver receiver (argument[1], properties);
  Thread::run_queue (read,
                     Thread::batch (Streamline<value_type>()),
                     Thread::multi (worker),
                     Thread::batch (Streamline<value_type>()),
                     receiver);

}

<commit_msg>tckresample: Remove compilation warnings<commit_after>/* Copyright (c) 2008-2017 the MRtrix3 contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, you can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * MRtrix 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.
 *
 * For more details, see http://www.mrtrix.org/.
 */

#include "command.h"
#include "math/math.h"
#include "image.h"
#include "thread.h"
#include "thread_queue.h"
#include "dwi/tractography/file.h"
#include "dwi/tractography/properties.h"
#include "dwi/tractography/resampling/arc.h"
#include "dwi/tractography/resampling/downsampler.h"
#include "dwi/tractography/resampling/endpoints.h"
#include "dwi/tractography/resampling/fixed_num_points.h"
#include "dwi/tractography/resampling/fixed_step_size.h"
#include "dwi/tractography/resampling/resampling.h"
#include "dwi/tractography/resampling/upsampler.h"

using namespace MR;
using namespace App;
using namespace DWI::Tractography;

void usage ()
{

  AUTHOR = "Robert E. Smith (robert.smith@florey.edu.au) and J-Donald Tournier (jdtournier@gmail.com)";

  SYNOPSIS = "Resample each streamline in a track file to a new set of vertices";

  DESCRIPTION
  + "This may be either increasing or decreasing the number of samples along "
    "each streamline, or changing the positions of the samples according to "
    "some specified trajectory."

  + DWI::Tractography::preserve_track_order_desc;

  ARGUMENTS
  + Argument ("in_tracks",  "the input track file").type_tracks_in()
  + Argument ("out_tracks", "the output resampled tracks").type_tracks_out();

  OPTIONS
    + Resampling::ResampleOption;

    // TODO Resample according to an exemplar streamline
}

typedef float value_type;

class Worker
{ NOMEMALIGN
  public:
    Worker (const std::unique_ptr<Resampling::Base>& in) :
        resampler (in->clone()) { }

    Worker (const Worker& that) :
        resampler (that.resampler->clone()) { }

    bool operator() (const Streamline<value_type>& in, Streamline<value_type>& out) const {
      return (*resampler) (in, out);
    }

  private:
    std::unique_ptr<Resampling::Base> resampler;
};

class Receiver
{ NOMEMALIGN
  public:
    Receiver (const std::string& path, const Properties& properties) :
        writer (path, properties),
        progress ("resampling streamlines") { }

    bool operator() (const Streamline<value_type>& tck) {
      auto progress_message = [&](){ return "resampling streamlines (count: " + str(writer.count) + ", skipped: " + str(writer.total_count - writer.count) + ")"; };
      writer (tck);
      progress.set_text (progress_message());
      return true;
    }

  private:
    Writer<value_type> writer;
    ProgressBar progress;

};

void run ()
{
  Properties properties;
  Reader<value_type> read (argument[0], properties);

  const std::unique_ptr<Resampling::Base> resampler (Resampling::get_resampler());

  float old_step_size = NaN;
  try {
    Properties::const_iterator i = properties.find ("output_step_size");
    if (i == properties.end()) {
      i = properties.find ("step_size");
      if (i != properties.end())
        old_step_size = to<float> (i->second);
    } else {
      old_step_size = to<float> (i->second);
    }
  } catch (...) {
    DEBUG ("Unable to read input track file step size");
  }

  float new_step_size = NaN;
  if (dynamic_cast<Resampling::FixedStepSize*>(resampler.get())) {
    new_step_size = dynamic_cast<Resampling::FixedStepSize*> (resampler.get())->get_step_size();
  } else if (std::isfinite (old_step_size)) {
    if (dynamic_cast<Resampling::Downsampler*>(resampler.get()))
      new_step_size = old_step_size * dynamic_cast<Resampling::Downsampler*> (resampler.get())->get_ratio();
    if (dynamic_cast<Resampling::Upsampler*>(resampler.get()))
      new_step_size = old_step_size / dynamic_cast<Resampling::Upsampler*> (resampler.get())->get_ratio();
  }
  properties["output_step_size"] = std::isfinite (new_step_size) ? str(new_step_size) : "variable";

  auto downsample = properties.find ("downsample_factor");
  if (downsample != properties.end())
    properties.erase (downsample);

  Worker worker (resampler);
  Receiver receiver (argument[1], properties);
  Thread::run_queue (read,
                     Thread::batch (Streamline<value_type>()),
                     Thread::multi (worker),
                     Thread::batch (Streamline<value_type>()),
                     receiver);

}

<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/external_cookie_handler.h"

#include "base/command_line.h"
#include "chrome/browser/chromeos/pipe_reader.h"
#include "chrome/browser/profile.h"
#include "chrome/common/chrome_switches.h"
#include "googleurl/src/gurl.h"
#include "net/base/cookie_store.h"
#include "net/url_request/url_request_context.h"

void ExternalCookieHandler::GetCookies(const CommandLine& parsed_command_line,
                                       Profile* profile) {
  // If there are Google External SSO cookies, add them to the cookie store.
  if (parsed_command_line.HasSwitch(switches::kCookiePipe)) {
    std::string pipe_name =
        WideToASCII(parsed_command_line.GetSwitchValue(switches::kCookiePipe));
    ExternalCookieHandler cookie_handler(new PipeReader(pipe_name));
    cookie_handler.HandleCookies(
        profile->GetRequestContext()->cookie_store());
  }
}

// static
const char ExternalCookieHandler::kGoogleAccountsUrl[] =
    "https://www.google.com/a/google.com/acs";

const int kChunkSize = 256;

// Reads up to a newline, or the end of the data, in increments of |chunk|
std::string ExternalCookieHandler::ReadLine(int chunk) {
  std::string cookie_line = reader_->Read(chunk);

  // As long as it's not an empty line...
  if (!cookie_line.empty()) {
    // and there's no newline at the end...
    while ('\n' != cookie_line[cookie_line.length() - 1]) {
      // try to pull more data...
      std::string piece = reader_->Read(chunk);
      if (piece.empty())  // only stop if there's none left.
        break;
      else
        cookie_line.append(piece);  // otherwise, append and keep going.
    }
  }

  return cookie_line;
}

bool ExternalCookieHandler::HandleCookies(net::CookieStore *cookie_store) {
  DCHECK(cookie_store);
  if (NULL != reader_.get()) {
    GURL url(ExternalCookieHandler::kGoogleAccountsUrl);
    net::CookieOptions options;
    options.set_include_httponly();

    // Each line we get is a cookie.  Grab up to a newline, then put
    // it in to the cookie jar.
    std::string cookie_line = ReadLine(kChunkSize);
    while (!cookie_line.empty()) {
      if (!cookie_store->SetCookieWithOptions(url, cookie_line, options))
        return false;
      cookie_line = ReadLine(kChunkSize);
    }
    return true;
  }
  return false;
}
<commit_msg>Fix compile bustage on chromeos builder.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/external_cookie_handler.h"

#include "base/command_line.h"
#include "chrome/browser/chromeos/pipe_reader.h"
#include "chrome/browser/net/url_request_context_getter.h"
#include "chrome/browser/profile.h"
#include "chrome/common/chrome_switches.h"
#include "googleurl/src/gurl.h"
#include "net/base/cookie_store.h"
#include "net/url_request/url_request_context.h"

void ExternalCookieHandler::GetCookies(const CommandLine& parsed_command_line,
                                       Profile* profile) {
  // If there are Google External SSO cookies, add them to the cookie store.
  if (parsed_command_line.HasSwitch(switches::kCookiePipe)) {
    std::string pipe_name =
        WideToASCII(parsed_command_line.GetSwitchValue(switches::kCookiePipe));
    ExternalCookieHandler cookie_handler(new PipeReader(pipe_name));
    cookie_handler.HandleCookies(
        profile->GetRequestContext()->GetCookieStore());
  }
}

// static
const char ExternalCookieHandler::kGoogleAccountsUrl[] =
    "https://www.google.com/a/google.com/acs";

const int kChunkSize = 256;

// Reads up to a newline, or the end of the data, in increments of |chunk|
std::string ExternalCookieHandler::ReadLine(int chunk) {
  std::string cookie_line = reader_->Read(chunk);

  // As long as it's not an empty line...
  if (!cookie_line.empty()) {
    // and there's no newline at the end...
    while ('\n' != cookie_line[cookie_line.length() - 1]) {
      // try to pull more data...
      std::string piece = reader_->Read(chunk);
      if (piece.empty())  // only stop if there's none left.
        break;
      else
        cookie_line.append(piece);  // otherwise, append and keep going.
    }
  }

  return cookie_line;
}

bool ExternalCookieHandler::HandleCookies(net::CookieStore *cookie_store) {
  DCHECK(cookie_store);
  if (NULL != reader_.get()) {
    GURL url(ExternalCookieHandler::kGoogleAccountsUrl);
    net::CookieOptions options;
    options.set_include_httponly();

    // Each line we get is a cookie.  Grab up to a newline, then put
    // it in to the cookie jar.
    std::string cookie_line = ReadLine(kChunkSize);
    while (!cookie_line.empty()) {
      if (!cookie_store->SetCookieWithOptions(url, cookie_line, options))
        return false;
      cookie_line = ReadLine(kChunkSize);
    }
    return true;
  }
  return false;
}
<|endoftext|>