<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "target.h"

#include "buildconfiguration.h"
#include "project.h"
#include "runconfiguration.h"

#include <utils/qtcassert.h>

using namespace ProjectExplorer;

namespace {
const char * const ACTIVE_BC_KEY("ProjectExplorer.Target.ActiveBuildConfiguration");
const char * const BC_KEY_PREFIX("ProjectExplorer.Target.BuildConfiguration.");
const char * const BC_COUNT_KEY("ProjectExplorer.Target.BuildConfigurationCount");

const char * const ACTIVE_RC_KEY("ProjectExplorer.Target.ActiveRunConfiguration");
const char * const RC_KEY_PREFIX("ProjectExplorer.Target.RunConfiguration.");
const char * const RC_COUNT_KEY("ProjectExplorer.Target.RunConfigurationCount");

} // namespace

// -------------------------------------------------------------------------
// Target
// -------------------------------------------------------------------------

Target::Target(Project *project, const QString &id) :
    ProjectConfiguration(id),
    m_project(project),
    m_isEnabled(true),
    m_activeBuildConfiguration(0),
    m_activeRunConfiguration(0)
{
}

Target::~Target()
{
    qDeleteAll(m_buildConfigurations);
    qDeleteAll(m_runConfigurations);
}

void Target::changeEnvironment()
{
    ProjectExplorer::BuildConfiguration *bc(qobject_cast<ProjectExplorer::BuildConfiguration *>(sender()));
    if (bc == activeBuildConfiguration())
        emit environmentChanged();
}

Project *Target::project() const
{
    return m_project;
}

void Target::addBuildConfiguration(BuildConfiguration *configuration)
{
    QTC_ASSERT(configuration && !m_buildConfigurations.contains(configuration), return);
    Q_ASSERT(configuration->target() == this);

    if (!buildConfigurationFactory())
        return;

    // Check that we don't have a configuration with the same displayName
    QString configurationDisplayName = configuration->displayName();
    QStringList displayNames;
    foreach (const BuildConfiguration *bc, m_buildConfigurations)
        displayNames << bc->displayName();
    configurationDisplayName = Project::makeUnique(configurationDisplayName, displayNames);
    configuration->setDisplayName(configurationDisplayName);

    // add it
    m_buildConfigurations.push_back(configuration);

    emit addedBuildConfiguration(configuration);

    connect(configuration, SIGNAL(environmentChanged()),
            SLOT(changeEnvironment()));

    if (!activeBuildConfiguration())
        setActiveBuildConfiguration(configuration);
}

void Target::removeBuildConfiguration(BuildConfiguration *configuration)
{
    //todo: this might be error prone
    if (!m_buildConfigurations.contains(configuration))
        return;

    m_buildConfigurations.removeOne(configuration);

    emit removedBuildConfiguration(configuration);

    if (activeBuildConfiguration() == configuration) {
        if (m_buildConfigurations.isEmpty())
            setActiveBuildConfiguration(0);
        else
            setActiveBuildConfiguration(m_buildConfigurations.at(0));
    }

    delete configuration;
}

QList<BuildConfiguration *> Target::buildConfigurations() const
{
    return m_buildConfigurations;
}

BuildConfiguration *Target::activeBuildConfiguration() const
{
    return m_activeBuildConfiguration;
}

void Target::setActiveBuildConfiguration(BuildConfiguration *configuration)
{
    if ((!configuration && m_buildConfigurations.isEmpty()) ||
        (configuration && m_buildConfigurations.contains(configuration) &&
         configuration != m_activeBuildConfiguration)) {
        m_activeBuildConfiguration = configuration;
        emit activeBuildConfigurationChanged(m_activeBuildConfiguration);
        emit environmentChanged();
    }
}

QList<RunConfiguration *> Target::runConfigurations() const
{
    return m_runConfigurations;
}

void Target::addRunConfiguration(RunConfiguration* runConfiguration)
{
    QTC_ASSERT(runConfiguration && !m_runConfigurations.contains(runConfiguration), return);
    Q_ASSERT(runConfiguration->target() == this);

    m_runConfigurations.push_back(runConfiguration);
    emit addedRunConfiguration(runConfiguration);

    if (!activeRunConfiguration())
        setActiveRunConfiguration(runConfiguration);
}

void Target::removeRunConfiguration(RunConfiguration* runConfiguration)
{
    QTC_ASSERT(runConfiguration && m_runConfigurations.contains(runConfiguration), return);

    m_runConfigurations.removeOne(runConfiguration);

    if (activeRunConfiguration() == runConfiguration) {
        if (m_runConfigurations.isEmpty())
            setActiveRunConfiguration(0);
        else
            setActiveRunConfiguration(m_runConfigurations.at(0));
    }

    emit removedRunConfiguration(runConfiguration);
    delete runConfiguration;
}

RunConfiguration* Target::activeRunConfiguration() const
{
    return m_activeRunConfiguration;
}

void Target::setActiveRunConfiguration(RunConfiguration* configuration)
{
    if ((!configuration && !m_runConfigurations.isEmpty()) ||
        (configuration && m_runConfigurations.contains(configuration) &&
         configuration != m_activeRunConfiguration)) {
        m_activeRunConfiguration = configuration;
        emit activeRunConfigurationChanged(m_activeRunConfiguration);
    }
}

bool Target::isEnabled() const
{
    return m_isEnabled;
}

QIcon Target::icon() const
{
    return m_icon;
}

void Target::setIcon(QIcon icon)
{
    m_icon = icon;
    emit iconChanged();
}

QIcon Target::overlayIcon() const
{
    return m_overlayIcon;
}

void Target::setOverlayIcon(QIcon icon)
{
    m_overlayIcon = icon;
    emit overlayIconChanged();
}

QString Target::toolTip() const
{
    return m_toolTip;
}

void Target::setToolTip(const QString &text)
{
    m_toolTip = text;
    emit toolTipChanged();
}

QVariantMap Target::toMap() const
{
    const QList<BuildConfiguration *> bcs = buildConfigurations();

    QVariantMap map(ProjectConfiguration::toMap());
    map.insert(QLatin1String(ACTIVE_BC_KEY), bcs.indexOf(m_activeBuildConfiguration));
    map.insert(QLatin1String(BC_COUNT_KEY), bcs.size());
    for (int i = 0; i < bcs.size(); ++i)
        map.insert(QString::fromLatin1(BC_KEY_PREFIX) + QString::number(i), bcs.at(i)->toMap());

    const QList<RunConfiguration *> rcs = runConfigurations();
    map.insert(QLatin1String(ACTIVE_RC_KEY), rcs.indexOf(m_activeRunConfiguration));
    map.insert(QLatin1String(RC_COUNT_KEY), rcs.size());
    for (int i = 0; i < rcs.size(); ++i)
        map.insert(QString::fromLatin1(RC_KEY_PREFIX) + QString::number(i), rcs.at(i)->toMap());

    return map;
}

void Target::setEnabled(bool enabled)
{
    if (enabled == m_isEnabled)
        return;

    m_isEnabled = enabled;
    emit targetEnabled(m_isEnabled);
}

bool Target::fromMap(const QVariantMap &map)
{
    if (!ProjectConfiguration::fromMap(map))
        return false;

    bool ok;
    int bcCount(map.value(QLatin1String(BC_COUNT_KEY), 0).toInt(&ok));
    if (!ok || bcCount < 0)
        bcCount = 0;
    int activeConfiguration(map.value(QLatin1String(ACTIVE_BC_KEY), 0).toInt(&ok));
    if (!ok || activeConfiguration < 0)
        activeConfiguration = 0;
    if (0 > activeConfiguration || bcCount < activeConfiguration)
        activeConfiguration = 0;

    for (int i = 0; i < bcCount; ++i) {
        const QString key(QString::fromLatin1(BC_KEY_PREFIX) + QString::number(i));
        if (!map.contains(key))
            return false;
        BuildConfiguration *bc(buildConfigurationFactory()->restore(this, map.value(key).toMap()));
        if (!bc)
            continue;
        addBuildConfiguration(bc);
        if (i == activeConfiguration)
            setActiveBuildConfiguration(bc);
    }
    if (buildConfigurations().isEmpty() && buildConfigurationFactory())
        return false;

    int rcCount(map.value(QLatin1String(RC_COUNT_KEY), 0).toInt(&ok));
    if (!ok || rcCount < 0)
        rcCount = 0;
    activeConfiguration = map.value(QLatin1String(ACTIVE_RC_KEY), 0).toInt(&ok);
    if (!ok || activeConfiguration < 0)
        activeConfiguration = 0;
    if (0 > activeConfiguration || rcCount < activeConfiguration)
        activeConfiguration = 0;

    for (int i = 0; i < rcCount; ++i) {
        const QString key(QString::fromLatin1(RC_KEY_PREFIX) + QString::number(i));
        if (!map.contains(key))
            return false;

        QVariantMap valueMap(map.value(key).toMap());
        IRunConfigurationFactory *factory(IRunConfigurationFactory::restoreFactory(this, valueMap));
        if (!factory)
            continue; // Skip RCs we do not know about.)

        RunConfiguration *rc(factory->restore(this, valueMap));
        if (!rc)
            continue;
        addRunConfiguration(rc);
        if (i == activeConfiguration)
            setActiveRunConfiguration(rc);
    }
    // Ignore missing RCs: We will just populate them using the default ones.

    return true;
}

// -------------------------------------------------------------------------
// ITargetFactory
// -------------------------------------------------------------------------

ITargetFactory::ITargetFactory(QObject *parent) :
    QObject(parent)
{
}

ITargetFactory::~ITargetFactory()
{
}
<commit_msg>Fix setActiveRunconfiguration(0)<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "target.h"

#include "buildconfiguration.h"
#include "project.h"
#include "runconfiguration.h"

#include <utils/qtcassert.h>

using namespace ProjectExplorer;

namespace {
const char * const ACTIVE_BC_KEY("ProjectExplorer.Target.ActiveBuildConfiguration");
const char * const BC_KEY_PREFIX("ProjectExplorer.Target.BuildConfiguration.");
const char * const BC_COUNT_KEY("ProjectExplorer.Target.BuildConfigurationCount");

const char * const ACTIVE_RC_KEY("ProjectExplorer.Target.ActiveRunConfiguration");
const char * const RC_KEY_PREFIX("ProjectExplorer.Target.RunConfiguration.");
const char * const RC_COUNT_KEY("ProjectExplorer.Target.RunConfigurationCount");

} // namespace

// -------------------------------------------------------------------------
// Target
// -------------------------------------------------------------------------

Target::Target(Project *project, const QString &id) :
    ProjectConfiguration(id),
    m_project(project),
    m_isEnabled(true),
    m_activeBuildConfiguration(0),
    m_activeRunConfiguration(0)
{
}

Target::~Target()
{
    qDeleteAll(m_buildConfigurations);
    qDeleteAll(m_runConfigurations);
}

void Target::changeEnvironment()
{
    ProjectExplorer::BuildConfiguration *bc(qobject_cast<ProjectExplorer::BuildConfiguration *>(sender()));
    if (bc == activeBuildConfiguration())
        emit environmentChanged();
}

Project *Target::project() const
{
    return m_project;
}

void Target::addBuildConfiguration(BuildConfiguration *configuration)
{
    QTC_ASSERT(configuration && !m_buildConfigurations.contains(configuration), return);
    Q_ASSERT(configuration->target() == this);

    if (!buildConfigurationFactory())
        return;

    // Check that we don't have a configuration with the same displayName
    QString configurationDisplayName = configuration->displayName();
    QStringList displayNames;
    foreach (const BuildConfiguration *bc, m_buildConfigurations)
        displayNames << bc->displayName();
    configurationDisplayName = Project::makeUnique(configurationDisplayName, displayNames);
    configuration->setDisplayName(configurationDisplayName);

    // add it
    m_buildConfigurations.push_back(configuration);

    emit addedBuildConfiguration(configuration);

    connect(configuration, SIGNAL(environmentChanged()),
            SLOT(changeEnvironment()));

    if (!activeBuildConfiguration())
        setActiveBuildConfiguration(configuration);
}

void Target::removeBuildConfiguration(BuildConfiguration *configuration)
{
    //todo: this might be error prone
    if (!m_buildConfigurations.contains(configuration))
        return;

    m_buildConfigurations.removeOne(configuration);

    emit removedBuildConfiguration(configuration);

    if (activeBuildConfiguration() == configuration) {
        if (m_buildConfigurations.isEmpty())
            setActiveBuildConfiguration(0);
        else
            setActiveBuildConfiguration(m_buildConfigurations.at(0));
    }

    delete configuration;
}

QList<BuildConfiguration *> Target::buildConfigurations() const
{
    return m_buildConfigurations;
}

BuildConfiguration *Target::activeBuildConfiguration() const
{
    return m_activeBuildConfiguration;
}

void Target::setActiveBuildConfiguration(BuildConfiguration *configuration)
{
    if ((!configuration && m_buildConfigurations.isEmpty()) ||
        (configuration && m_buildConfigurations.contains(configuration) &&
         configuration != m_activeBuildConfiguration)) {
        m_activeBuildConfiguration = configuration;
        emit activeBuildConfigurationChanged(m_activeBuildConfiguration);
        emit environmentChanged();
    }
}

QList<RunConfiguration *> Target::runConfigurations() const
{
    return m_runConfigurations;
}

void Target::addRunConfiguration(RunConfiguration* runConfiguration)
{
    QTC_ASSERT(runConfiguration && !m_runConfigurations.contains(runConfiguration), return);
    Q_ASSERT(runConfiguration->target() == this);

    m_runConfigurations.push_back(runConfiguration);
    emit addedRunConfiguration(runConfiguration);

    if (!activeRunConfiguration())
        setActiveRunConfiguration(runConfiguration);
}

void Target::removeRunConfiguration(RunConfiguration* runConfiguration)
{
    QTC_ASSERT(runConfiguration && m_runConfigurations.contains(runConfiguration), return);

    m_runConfigurations.removeOne(runConfiguration);

    if (activeRunConfiguration() == runConfiguration) {
        if (m_runConfigurations.isEmpty())
            setActiveRunConfiguration(0);
        else
            setActiveRunConfiguration(m_runConfigurations.at(0));
    }

    emit removedRunConfiguration(runConfiguration);
    delete runConfiguration;
}

RunConfiguration* Target::activeRunConfiguration() const
{
    return m_activeRunConfiguration;
}

void Target::setActiveRunConfiguration(RunConfiguration* configuration)
{
    if ((!configuration && m_runConfigurations.isEmpty()) ||
        (configuration && m_runConfigurations.contains(configuration) &&
         configuration != m_activeRunConfiguration)) {
        m_activeRunConfiguration = configuration;
        emit activeRunConfigurationChanged(m_activeRunConfiguration);
    }
}

bool Target::isEnabled() const
{
    return m_isEnabled;
}

QIcon Target::icon() const
{
    return m_icon;
}

void Target::setIcon(QIcon icon)
{
    m_icon = icon;
    emit iconChanged();
}

QIcon Target::overlayIcon() const
{
    return m_overlayIcon;
}

void Target::setOverlayIcon(QIcon icon)
{
    m_overlayIcon = icon;
    emit overlayIconChanged();
}

QString Target::toolTip() const
{
    return m_toolTip;
}

void Target::setToolTip(const QString &text)
{
    m_toolTip = text;
    emit toolTipChanged();
}

QVariantMap Target::toMap() const
{
    const QList<BuildConfiguration *> bcs = buildConfigurations();

    QVariantMap map(ProjectConfiguration::toMap());
    map.insert(QLatin1String(ACTIVE_BC_KEY), bcs.indexOf(m_activeBuildConfiguration));
    map.insert(QLatin1String(BC_COUNT_KEY), bcs.size());
    for (int i = 0; i < bcs.size(); ++i)
        map.insert(QString::fromLatin1(BC_KEY_PREFIX) + QString::number(i), bcs.at(i)->toMap());

    const QList<RunConfiguration *> rcs = runConfigurations();
    map.insert(QLatin1String(ACTIVE_RC_KEY), rcs.indexOf(m_activeRunConfiguration));
    map.insert(QLatin1String(RC_COUNT_KEY), rcs.size());
    for (int i = 0; i < rcs.size(); ++i)
        map.insert(QString::fromLatin1(RC_KEY_PREFIX) + QString::number(i), rcs.at(i)->toMap());

    return map;
}

void Target::setEnabled(bool enabled)
{
    if (enabled == m_isEnabled)
        return;

    m_isEnabled = enabled;
    emit targetEnabled(m_isEnabled);
}

bool Target::fromMap(const QVariantMap &map)
{
    if (!ProjectConfiguration::fromMap(map))
        return false;

    bool ok;
    int bcCount(map.value(QLatin1String(BC_COUNT_KEY), 0).toInt(&ok));
    if (!ok || bcCount < 0)
        bcCount = 0;
    int activeConfiguration(map.value(QLatin1String(ACTIVE_BC_KEY), 0).toInt(&ok));
    if (!ok || activeConfiguration < 0)
        activeConfiguration = 0;
    if (0 > activeConfiguration || bcCount < activeConfiguration)
        activeConfiguration = 0;

    for (int i = 0; i < bcCount; ++i) {
        const QString key(QString::fromLatin1(BC_KEY_PREFIX) + QString::number(i));
        if (!map.contains(key))
            return false;
        BuildConfiguration *bc(buildConfigurationFactory()->restore(this, map.value(key).toMap()));
        if (!bc)
            continue;
        addBuildConfiguration(bc);
        if (i == activeConfiguration)
            setActiveBuildConfiguration(bc);
    }
    if (buildConfigurations().isEmpty() && buildConfigurationFactory())
        return false;

    int rcCount(map.value(QLatin1String(RC_COUNT_KEY), 0).toInt(&ok));
    if (!ok || rcCount < 0)
        rcCount = 0;
    activeConfiguration = map.value(QLatin1String(ACTIVE_RC_KEY), 0).toInt(&ok);
    if (!ok || activeConfiguration < 0)
        activeConfiguration = 0;
    if (0 > activeConfiguration || rcCount < activeConfiguration)
        activeConfiguration = 0;

    for (int i = 0; i < rcCount; ++i) {
        const QString key(QString::fromLatin1(RC_KEY_PREFIX) + QString::number(i));
        if (!map.contains(key))
            return false;

        QVariantMap valueMap(map.value(key).toMap());
        IRunConfigurationFactory *factory(IRunConfigurationFactory::restoreFactory(this, valueMap));
        if (!factory)
            continue; // Skip RCs we do not know about.)

        RunConfiguration *rc(factory->restore(this, valueMap));
        if (!rc)
            continue;
        addRunConfiguration(rc);
        if (i == activeConfiguration)
            setActiveRunConfiguration(rc);
    }
    // Ignore missing RCs: We will just populate them using the default ones.

    return true;
}

// -------------------------------------------------------------------------
// ITargetFactory
// -------------------------------------------------------------------------

ITargetFactory::ITargetFactory(QObject *parent) :
    QObject(parent)
{
}

ITargetFactory::~ITargetFactory()
{
}
<|endoftext|>


<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2010 Wes Hardaker <marble@ws6z.com>
//

#include "AprsObject.h"

#include <QtGui/QPixmap>

#include "MarbleDebug.h"
#include "MarbleDirs.h"
#include "GeoPainter.h"
#include "GeoAprsCoordinates.h"

using namespace Marble;

AprsObject::AprsObject( const GeoAprsCoordinates &at, QString &name )
    : m_myName( name ),
      m_seenFrom( GeoAprsCoordinates::FromNowhere ),
      m_havePixmap ( false ),
      m_pixmapFilename( ),
      m_pixmap( 0 )
{
    m_history.push_back( at );
}

AprsObject::AprsObject( const qreal &lon, const qreal &lat,
                        const QString &name, int where )
    : m_myName( name ),
      m_seenFrom( where ),
      m_havePixmap ( false ),
      m_pixmapFilename( ),
      m_pixmap( 0 )
{
    m_history.push_back( GeoAprsCoordinates( lon, lat, 0,
                                             GeoAprsCoordinates::Degree ) );
}

AprsObject::~AprsObject()
{
    delete m_pixmap;
}

GeoAprsCoordinates
AprsObject::location()
{
    return m_history.last();
}

void
AprsObject::setLocation( GeoAprsCoordinates location )
{
    // Not ideal but it's unlikely they'll jump to the *exact* same spot again
    if ( !m_history.contains( location ) ) {
        m_history.push_back( location );
        mDebug() << "  moved: " << m_myName.toLocal8Bit().data();
    } else {
        int index = m_history.indexOf( location );
        QTime now;
        m_history[index].setTimestamp( now );
        m_history[index].addSeenFrom( location.seenFrom() );
    }
}

void
AprsObject::setLocation( qreal lon, qreal lat, int from )
{
    setLocation( GeoAprsCoordinates( lon, lat, 0,
                                     GeoAprsCoordinates::Degree, from ) );
}

void
AprsObject::setPixmapId( QString &pixmap )
{
    QString pixmapFilename = MarbleDirs::path( pixmap );
    if ( QFile( pixmapFilename ).exists() ) {
        m_havePixmap = true;
        m_pixmapFilename = pixmapFilename;
        // We can't load the pixmap here since it's used in a different thread
    }
    else {
        m_havePixmap = false;
    }
}

void
AprsObject::setSeenFrom( int where )
{
    m_seenFrom = ( m_seenFrom | where );
}

QColor
AprsObject::calculatePaintColor( GeoPainter *painter ) const
{
    QTime now;
    return calculatePaintColor( painter, m_seenFrom, now );
}

QColor
AprsObject::calculatePaintColor( GeoPainter *painter, int from, const QTime &time,
                           int fadeTime ) const
{
    QColor color;
    if ( from & GeoAprsCoordinates::Directly ) {
        color = QColor( 0, 201, 0, 255 ); // oxygen green if direct
    } else if ( (from & ( GeoAprsCoordinates::FromTCPIP | GeoAprsCoordinates::FromTTY ) ) == ( GeoAprsCoordinates::FromTCPIP | GeoAprsCoordinates::FromTTY ) ) {
        color = QColor( 176, 0, 141, 255 ); // oxygen purple if both
    } else if  ( from & GeoAprsCoordinates::FromTCPIP ) {
        color = QColor( 255, 0, 0, 255 ); // oxygen red if net
    } else if  ( from & GeoAprsCoordinates::FromTTY ) {
        color = QColor( 0, 0, 201, 255 ); // oxygen blue if TNC TTY relay
    } else if ( from & ( GeoAprsCoordinates::FromFile ) ) {
        color = QColor( 255, 255, 0, 255 ); // oxygen yellow if file only
    } else {
        mDebug() << "**************************************** unknown from: "
                 << from;
        color = QColor( 0, 0, 0, 255 ); // shouldn't happen but a user
                                        // could mess up I suppose we
                                        // should at least draw it in
                                        // something.
    }

    if ( fadeTime > 0 && time.elapsed() > fadeTime ) { // 5 min ( 600000 ms )
        color.setAlpha( 160 );
    }

    painter->setPen( color );
    return color;
}

void
AprsObject::render( GeoPainter *painter, ViewportParams *viewport,
                    int fadeTime, int hideTime )
{
    Q_UNUSED( viewport );

    if ( hideTime > 0 && m_history.last().timestamp().elapsed() > hideTime )
        return;

    QColor baseColor = calculatePaintColor( painter, m_seenFrom,
                                      m_history.last().timestamp(),
                                      fadeTime );

    if ( m_history.count() > 1 ) {

        QList<GeoAprsCoordinates>::iterator spot = m_history.begin();
        QList<GeoAprsCoordinates>::iterator endSpot = m_history.end();
        QList<GeoAprsCoordinates>::iterator lastspot;

        for( ++spot, lastspot = m_history.begin();
             spot != endSpot;
             ++spot, ++lastspot ) {

            if ( hideTime > 0 && ( *spot ).timestamp().elapsed() > hideTime )
                break;

            // draw the line in the base color
            painter->setPen( baseColor );
            painter->drawLine( *lastspot, *spot );

            // draw the new circle in whatever is appropriate for that point
            calculatePaintColor( painter, ( *spot ).seenFrom(), ( *spot ).timestamp(),
                           fadeTime );
            painter->drawRect( *spot, 5, 5, false );
        }
    }

    // Always draw the symbol then the text last so it's on top
    if ( m_havePixmap ) {
        if ( ! m_pixmap )
            m_pixmap = new QPixmap ( m_pixmapFilename );
        if ( m_pixmap && ! m_pixmap->isNull() )
            painter->drawPixmap( m_history.last(), *m_pixmap );
        else
            painter->drawRect( m_history.last(), 6, 6 );
    }
    else
        painter->drawRect( m_history.last(), 6, 6 );

    painter->setPen( baseColor );
    painter->drawText( m_history.last(), m_myName );
}
<commit_msg>construct a GeoDataLineString<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2010 Wes Hardaker <marble@ws6z.com>
//

#include "AprsObject.h"

#include <QtGui/QPixmap>

#include "MarbleDebug.h"
#include "MarbleDirs.h"
#include "GeoDataLineString.h"
#include "GeoPainter.h"
#include "GeoAprsCoordinates.h"

using namespace Marble;

AprsObject::AprsObject( const GeoAprsCoordinates &at, QString &name )
    : m_myName( name ),
      m_seenFrom( GeoAprsCoordinates::FromNowhere ),
      m_havePixmap ( false ),
      m_pixmapFilename( ),
      m_pixmap( 0 )
{
    m_history.push_back( at );
}

AprsObject::AprsObject( const qreal &lon, const qreal &lat,
                        const QString &name, int where )
    : m_myName( name ),
      m_seenFrom( where ),
      m_havePixmap ( false ),
      m_pixmapFilename( ),
      m_pixmap( 0 )
{
    m_history.push_back( GeoAprsCoordinates( lon, lat, 0,
                                             GeoAprsCoordinates::Degree ) );
}

AprsObject::~AprsObject()
{
    delete m_pixmap;
}

GeoAprsCoordinates
AprsObject::location()
{
    return m_history.last();
}

void
AprsObject::setLocation( GeoAprsCoordinates location )
{
    // Not ideal but it's unlikely they'll jump to the *exact* same spot again
    if ( !m_history.contains( location ) ) {
        m_history.push_back( location );
        mDebug() << "  moved: " << m_myName.toLocal8Bit().data();
    } else {
        int index = m_history.indexOf( location );
        QTime now;
        m_history[index].setTimestamp( now );
        m_history[index].addSeenFrom( location.seenFrom() );
    }
}

void
AprsObject::setLocation( qreal lon, qreal lat, int from )
{
    setLocation( GeoAprsCoordinates( lon, lat, 0,
                                     GeoAprsCoordinates::Degree, from ) );
}

void
AprsObject::setPixmapId( QString &pixmap )
{
    QString pixmapFilename = MarbleDirs::path( pixmap );
    if ( QFile( pixmapFilename ).exists() ) {
        m_havePixmap = true;
        m_pixmapFilename = pixmapFilename;
        // We can't load the pixmap here since it's used in a different thread
    }
    else {
        m_havePixmap = false;
    }
}

void
AprsObject::setSeenFrom( int where )
{
    m_seenFrom = ( m_seenFrom | where );
}

QColor
AprsObject::calculatePaintColor( GeoPainter *painter ) const
{
    QTime now;
    return calculatePaintColor( painter, m_seenFrom, now );
}

QColor
AprsObject::calculatePaintColor( GeoPainter *painter, int from, const QTime &time,
                           int fadeTime ) const
{
    QColor color;
    if ( from & GeoAprsCoordinates::Directly ) {
        color = QColor( 0, 201, 0, 255 ); // oxygen green if direct
    } else if ( (from & ( GeoAprsCoordinates::FromTCPIP | GeoAprsCoordinates::FromTTY ) ) == ( GeoAprsCoordinates::FromTCPIP | GeoAprsCoordinates::FromTTY ) ) {
        color = QColor( 176, 0, 141, 255 ); // oxygen purple if both
    } else if  ( from & GeoAprsCoordinates::FromTCPIP ) {
        color = QColor( 255, 0, 0, 255 ); // oxygen red if net
    } else if  ( from & GeoAprsCoordinates::FromTTY ) {
        color = QColor( 0, 0, 201, 255 ); // oxygen blue if TNC TTY relay
    } else if ( from & ( GeoAprsCoordinates::FromFile ) ) {
        color = QColor( 255, 255, 0, 255 ); // oxygen yellow if file only
    } else {
        mDebug() << "**************************************** unknown from: "
                 << from;
        color = QColor( 0, 0, 0, 255 ); // shouldn't happen but a user
                                        // could mess up I suppose we
                                        // should at least draw it in
                                        // something.
    }

    if ( fadeTime > 0 && time.elapsed() > fadeTime ) { // 5 min ( 600000 ms )
        color.setAlpha( 160 );
    }

    painter->setPen( color );
    return color;
}

void
AprsObject::render( GeoPainter *painter, ViewportParams *viewport,
                    int fadeTime, int hideTime )
{
    Q_UNUSED( viewport );

    if ( hideTime > 0 && m_history.last().timestamp().elapsed() > hideTime )
        return;

    QColor baseColor = calculatePaintColor( painter, m_seenFrom,
                                      m_history.last().timestamp(),
                                      fadeTime );

    if ( m_history.count() > 1 ) {

        QList<GeoAprsCoordinates>::iterator spot = m_history.begin();
        QList<GeoAprsCoordinates>::iterator endSpot = m_history.end();

        GeoDataLineString lineString;
        lineString.setTessellate( true );
        lineString << *spot; // *spot exists because m_history.count() > 1

        for( ++spot; spot != endSpot; ++spot ) {

            if ( hideTime > 0 && ( *spot ).timestamp().elapsed() > hideTime )
                break;

            // draw the line in the base color
            painter->setPen( baseColor );
            lineString << *spot;

            // draw the new circle in whatever is appropriate for that point
            calculatePaintColor( painter, ( *spot ).seenFrom(), ( *spot ).timestamp(),
                           fadeTime );
            painter->drawRect( *spot, 5, 5 );
        }

        painter->drawPolyline( lineString );
    }

    // Always draw the symbol then the text last so it's on top
    if ( m_havePixmap ) {
        if ( ! m_pixmap )
            m_pixmap = new QPixmap ( m_pixmapFilename );
        if ( m_pixmap && ! m_pixmap->isNull() )
            painter->drawPixmap( m_history.last(), *m_pixmap );
        else
            painter->drawRect( m_history.last(), 6, 6 );
    }
    else
        painter->drawRect( m_history.last(), 6, 6 );

    painter->setPen( baseColor );
    painter->drawText( m_history.last(), m_myName );
}
<|endoftext|>


<commit_before>#pragma once
#ifndef LIGHTPTR_HPP
# define LIGHTPTR_HPP

#include <cassert>

#include <atomic>

#include <memory>

#include <utility>

#include <type_traits>

namespace detail
{
  template <typename U>
  struct ref_type
  {
    using type = U&;
  };

  template <>
  struct ref_type<void>
  {
    using type = void;
  };
}

template <typename T>
struct light_ptr
{
  template <typename U>
  struct remove_array
  {
    using type = U;
  };

  template <typename U>
  struct remove_array<U[]>
  {
    using type = U;
  };

  using counter_type = ::std::size_t;

  using element_type = typename remove_array<T>::type;

  using deleter_type = void (*)(element_type*);

  constexpr light_ptr() = default;

  explicit light_ptr(element_type* const p,
    deleter_type const d = default_deleter)
  {
    reset(p, d);
  }

  ~light_ptr() { delete_ptr(counter_ptr_, ptr_, deleter_); }

  light_ptr(light_ptr const& other) { *this = other; }

  light_ptr(light_ptr&& other) noexcept { *this = ::std::move(other); }

  light_ptr& operator=(light_ptr const& rhs)
  {
    if (*this != rhs)
    {
      dec_ref();

      counter_ptr_ = rhs.counter_ptr_;

      ptr_ = rhs.ptr_;

      deleter_ = rhs.deleter_;

      inc_ref();
    }
    // else do nothing

    return *this;
  }

  light_ptr& operator=(light_ptr&& rhs) noexcept
  {
    counter_ptr_ = rhs.counter_ptr_;
    ptr_ = rhs.ptr_;
    deleter_ = rhs.deleter_;

    rhs.counter_ptr_ = nullptr;

    return *this;
  }

  bool operator<(light_ptr const& rhs) const noexcept
  {
    return get() < rhs.get();
  }

  bool operator==(light_ptr const& rhs) const noexcept
  {
    return counter_ptr_ == rhs.counter_ptr_;
  }

  bool operator!=(light_ptr const& rhs) const noexcept
  {
    return !operator==(rhs);
  }

  explicit operator bool() const noexcept { return counter_ptr_; }

  typename ::detail::ref_type<T>::type
  operator*() const noexcept
  {
    return *static_cast<T*>(static_cast<void*>(ptr_));
  }

  T* operator->() const noexcept
  {
    return static_cast<T*>(static_cast<void*>(ptr_));
  }

  element_type* get() const noexcept { return ptr_; }

  void reset() { reset(nullptr); }

  void reset(::std::nullptr_t const p)
  {
    dec_ref();

    counter_ptr_ = nullptr;

    ptr_ = nullptr;
  }

  void reset(element_type* const p,
    deleter_type const d = default_deleter)
  {
    dec_ref();

    counter_ptr_ = new atomic_type(counter_type(1));

    ptr_ = p;

    deleter_ = d;
  }

  void swap(light_ptr& other) noexcept
  {
    ::std::swap(counter_ptr_, other.counter_ptr_);
    ::std::swap(ptr_, other.ptr_);
    ::std::swap(deleter_, other.deleter_);
  }

  bool unique() const noexcept { return counter_type(1) == use_count(); }

  counter_type use_count() const noexcept
  {
    return counter_ptr_ ? counter_ptr_->load() : counter_type{};
  }

private:
  void dec_ref() const
  {
    if (counter_ptr_ && *counter_ptr_ && !--*counter_ptr_)
    {
      delete counter_ptr_;

      deleter_(ptr_);
    }
    // else do nothing
  }

  void inc_ref() const noexcept
  {
    assert(ptr_);
    assert(counter_ptr_);
    ++*counter_ptr_;
  }

  static void default_deleter(element_type* const p)
  {
    ::std::default_delete<T>()(p);
  }

  using atomic_type = ::std::atomic<counter_type>;

  static void delete_ptr(atomic_type* const counter_ptr,
    element_type* const ptr, deleter_type const deleter)
  {
    if (counter_ptr && *counter_ptr && !--*counter_ptr)
    {
      delete counter_ptr;

      deleter(ptr);
    }
    // else do nothing
  }

private:
  atomic_type* counter_ptr_{};

  element_type* ptr_{};

  deleter_type deleter_;
};

template<class T, class... Args>
inline light_ptr<T> make_light(Args&&... args)
{
  return light_ptr<T>(new T(::std::forward<Args>(args)...));
}

namespace std
{
  template <typename T>
  struct hash
  {
    size_t operator()(light_ptr<T> const& l) const noexcept
    {
      return hash<typename light_ptr<T>::element_type*>(l.get());
    }
  };
}

#endif // LIGHTPTR_HPP
<commit_msg>delegate fix<commit_after>#pragma once
#ifndef LIGHTPTR_HPP
# define LIGHTPTR_HPP

#include <cassert>

#include <atomic>

#include <memory>

#include <utility>

#include <type_traits>

namespace detail
{
  using counter_type = ::std::size_t;

  using atomic_type = ::std::atomic<counter_type>;

  using deleter_type = void (*)(void*);

  template <typename U>
  struct ref_type
  {
    using type = U&;
  };

  template <>
  struct ref_type<void>
  {
    using type = void;
  };

  inline void dec_ref(atomic_type* const counter_ptr,
    void* const ptr, deleter_type const deleter)
  {
    if (counter_ptr && !--*counter_ptr)
    {
      delete counter_ptr;

      deleter(ptr);
    }
    // else do nothing
  }

  inline void inc_ref(atomic_type* const counter_ptr)
  {
    assert(counter_ptr);
    ++*counter_ptr;
  }
}

template <typename T>
struct light_ptr
{
  template <typename U>
  struct remove_array
  {
    using type = U;
  };

  template <typename U>
  struct remove_array<U[]>
  {
    using type = U;
  };

  using counter_type = ::detail::counter_type;

  using deleter_type = ::detail::deleter_type;

  using element_type = typename remove_array<T>::type;

  constexpr light_ptr() = default;

  explicit light_ptr(element_type* const p,
    deleter_type const d = default_deleter)
  {
    reset(p, d);
  }

  ~light_ptr() { ::detail::dec_ref(counter_ptr_, ptr_, deleter_); }

  light_ptr(light_ptr const& other) { *this = other; }

  light_ptr(light_ptr&& other) noexcept { *this = ::std::move(other); }

  light_ptr& operator=(light_ptr const& rhs)
  {
    if (*this != rhs)
    {
      ::detail::dec_ref(counter_ptr_, ptr_, deleter_);

      counter_ptr_ = rhs.counter_ptr_;

      ptr_ = rhs.ptr_;

      deleter_ = rhs.deleter_;

      ::detail::inc_ref(counter_ptr_);
    }
    // else do nothing

    return *this;
  }

  light_ptr& operator=(light_ptr&& rhs) noexcept
  {
    counter_ptr_ = rhs.counter_ptr_;
    ptr_ = rhs.ptr_;
    deleter_ = rhs.deleter_;

    rhs.counter_ptr_ = nullptr;

    return *this;
  }

  bool operator<(light_ptr const& rhs) const noexcept
  {
    return get() < rhs.get();
  }

  bool operator==(light_ptr const& rhs) const noexcept
  {
    return counter_ptr_ == rhs.counter_ptr_;
  }

  bool operator!=(light_ptr const& rhs) const noexcept
  {
    return !operator==(rhs);
  }

  explicit operator bool() const noexcept { return counter_ptr_; }

  typename ::detail::ref_type<T>::type
  operator*() const noexcept
  {
    return *static_cast<T*>(static_cast<void*>(ptr_));
  }

  T* operator->() const noexcept
  {
    return static_cast<T*>(static_cast<void*>(ptr_));
  }

  element_type* get() const noexcept { return ptr_; }

  void reset() { reset(nullptr); }

  void reset(::std::nullptr_t const p)
  {
    ::detail::dec_ref(counter_ptr_, ptr_, deleter_);

    counter_ptr_ = nullptr;

    ptr_ = nullptr;
  }

  void reset(element_type* const p,
    deleter_type const d = default_deleter)
  {
    ::detail::dec_ref(counter_ptr_, ptr_, deleter_);

    counter_ptr_ = new atomic_type(counter_type(1));

    ptr_ = p;

    deleter_ = d;
  }

  void swap(light_ptr& other) noexcept
  {
    ::std::swap(counter_ptr_, other.counter_ptr_);
    ::std::swap(ptr_, other.ptr_);
    ::std::swap(deleter_, other.deleter_);
  }

  bool unique() const noexcept { return counter_type(1) == use_count(); }

  counter_type use_count() const noexcept
  {
    return counter_ptr_ ? counter_ptr_->load() : counter_type{};
  }

private:
  static void default_deleter(void* const p)
  {
    ::std::default_delete<T>()(static_cast<element_type*>(p));
  }

  using atomic_type = ::detail::atomic_type;

private:
  atomic_type* counter_ptr_{};

  element_type* ptr_{};

  deleter_type deleter_;
};

template<class T, class... Args>
inline light_ptr<T> make_light(Args&&... args)
{
  return light_ptr<T>(new T(::std::forward<Args>(args)...));
}

namespace std
{
  template <typename T>
  struct hash
  {
    size_t operator()(light_ptr<T> const& l) const noexcept
    {
      return hash<typename light_ptr<T>::element_type*>(l.get());
    }
  };
}

#endif // LIGHTPTR_HPP
<|endoftext|>


<commit_before>#include "ncv.h"
#include "common/convolution.hpp"
#include "opencl/opencl.h"

using namespace ncv;

const std::string conv_program_source = R"xxx(

#pragma OPENCL EXTENSION cl_amd_fp64 : enable
#pragma OPENCL EXTENSION cl_khr_fp64 : enable

__kernel void conv_kernel(
       __global const double* idata, int icols,
       __constant double* kdata, int krows, int kcols,
       __global double* odata)
{
        const int x = get_global_id(0);
        const int y = get_global_id(1);

        double sum = 0;
        for (int r = 0, kidx = 0; r < krows; r ++)
        {
                int iidx = (y + r) * icols + x;
                for (int c = 0; c < kcols; c ++, kidx ++, iidx ++)
                {
                        sum += kdata[kidx] * idata[iidx];
                }
        }

        odata[y * get_global_size(0) + x] = sum;
}

)xxx";

ncv::thread_pool_t pool;
const size_t tests = 4;

void init_matrix(int rows, int cols, matrix_t& matrix)
{
        matrix.resize(rows, cols);
        matrix.setRandom();
        matrix /= rows;
}

void init_matrices(int rows, int cols, int count, matrices_t& matrices)
{
	matrices.resize(count);
	for (int i = 0; i < count; i ++)
	{
		init_matrix(rows, cols, matrices[i]);
	}
}

void zero_matrices(matrices_t& matrices)
{
        for (size_t i = 0; i < matrices.size(); i ++)
        {
                matrices[i].setZero();
        }
}

scalar_t sum_matrices(matrices_t& matrices)
{
        scalar_t sum = 0;
        for (size_t i = 0; i < matrices.size(); i ++)
        {
                sum += matrices[i].sum();
        }
        return sum;
}

template <typename top>
void test_conv2D_1cpu(top op, const char* name, const matrices_t& idatas, const matrix_t& kdata, matrices_t& odatas)
{
        zero_matrices(odatas);

        ncv::stats_t<double, size_t> proc_stats;

        // run multiple tests
        for (size_t t = 0; t < tests; t ++)
        {
                const ncv::timer_t timer;

                for (size_t i = 0; i < idatas.size(); i ++)
                {
                        op(idatas[i], kdata, odatas[i]);
                }

                proc_stats(timer.miliseconds());
        }

        const scalar_t sum = sum_matrices(odatas);
        const size_t milis = static_cast<size_t>(proc_stats.avg());

        std::cout << name << "= " << text::resize(text::to_string(milis), 4, align::right)
                  << "ms (" << text::resize(text::to_string(sum), 12, align::left) << ")  ";
}

template <typename top>
void test_conv2D_xcpu(top op, const char* name, const matrices_t& idatas, const matrix_t& kdata,  matrices_t& odatas)
{
        zero_matrices(odatas);

        ncv::stats_t<double, size_t> proc_stats;

        // run multiple tests
        for (size_t t = 0; t < tests; t ++)
        {
                const ncv::timer_t timer;

                ncv::thread_loop(idatas.size(), [&] (size_t i)
                {
                        op(idatas[i], kdata, odatas[i]);
                }, pool);

                proc_stats(timer.miliseconds());
        }

        const scalar_t sum = sum_matrices(odatas);
        const size_t milis = static_cast<size_t>(proc_stats.avg());

        std::cout << name << "= " << text::resize(text::to_string(milis), 4, align::right)
                  << "ms (" << text::resize(text::to_string(sum), 12, align::left) << ")  ";
}

void test_conv2D_gpu(const char* name, const matrices_t& idatas, const matrix_t& kdata, matrices_t& odatas)
{
        const cl::Context& context = ocl::manager_t::instance().context();
        const cl::CommandQueue& queue = ocl::manager_t::instance().queue();

        const cl::Program program = ocl::manager_t::instance().program_from_text(conv_program_source);
        cl::Kernel kernel = cl::Kernel(program, "conv_kernel");

        const int icols = static_cast<int>(idatas[0].cols());
        const int krows = static_cast<int>(kdata.rows());
        const int kcols = static_cast<int>(kdata.cols());
        const int orows = static_cast<int>(odatas[0].rows());
        const int ocols = static_cast<int>(odatas[0].cols());

        const size_t mem_idata = idatas[0].size() * sizeof(scalar_t);
        const size_t mem_kdata = kdata.size() * sizeof(scalar_t);
        const size_t mem_odata = odatas[0].size() * sizeof(scalar_t);

        // create buffers once
        cl::Buffer cl_idata = cl::Buffer(context, CL_MEM_READ_ONLY, mem_idata, NULL);
        cl::Buffer cl_kdata = cl::Buffer(context, CL_MEM_READ_ONLY, mem_kdata, NULL);
        cl::Buffer cl_odata = cl::Buffer(context, CL_MEM_WRITE_ONLY, mem_odata, NULL);

        // setup kernel buffers once
        kernel.setArg(0, cl_idata);
        kernel.setArg(1, sizeof(int), (void*)&icols);
        kernel.setArg(2, cl_kdata);
        kernel.setArg(3, sizeof(int), (void*)&krows);
        kernel.setArg(4, sizeof(int), (void*)&kcols);
        kernel.setArg(5, cl_odata);
        queue.finish();

        // transfer constants
        cl::Event event;
        queue.enqueueWriteBuffer(cl_kdata, CL_FALSE, 0, mem_kdata, kdata.data(), NULL, &event);
        queue.finish();

        zero_matrices(odatas);

        ncv::stats_t<double, size_t> proc_stats;

        // run multiple tests
        for (size_t t = 0; t < tests; t ++)
        {
                ncv::timer_t timer;

                for (size_t i = 0; i < idatas.size(); i ++)
                {
                        // I - send inputs to gpu
                        cl::Event event;
                        queue.enqueueWriteBuffer(cl_idata, CL_FALSE, 0, mem_idata, idatas[i].data(), NULL, &event);
                        queue.finish();

                        // II - gpu processing
                        queue.enqueueNDRangeKernel(kernel, cl::NullRange, cl::NDRange(ocols, orows), cl::NullRange, NULL, &event);
                        queue.finish();

                        // III - read results from gpu
                        queue.enqueueReadBuffer(cl_odata, CL_TRUE, 0, mem_odata, odatas[i].data(), NULL, &event);
                }

                proc_stats(timer.miliseconds());
        }

        const scalar_t sum = sum_matrices(odatas);
        const size_t milis = static_cast<size_t>(proc_stats.avg());

        std::cout << name << "= " << text::resize(text::to_string(milis), 4, align::right)
                  << "ms (" << text::resize(text::to_string(sum), 12, align::left) << ")  ";
}

void test(int isize, int ksize, int n_samples)
{
        const int osize = isize - ksize + 1;

        matrices_t idatas, odatas;
        matrix_t kdata;

        init_matrices(isize, isize, n_samples, idatas);
        init_matrices(osize, osize, n_samples, odatas);
        init_matrix(ksize, ksize, kdata);

        std::cout << "mix (isize = " << isize << ", ksize = " << ksize << "): \t";
        test_conv2D_1cpu(ncv::math::conv_eib<matrix_t>, "eib(1CPU)", idatas, kdata, odatas);
        test_conv2D_xcpu(ncv::math::conv_eib<matrix_t>, "eib(xCPU)", idatas, kdata, odatas);
        test_conv2D_1cpu(ncv::math::conv_dot<matrix_t>, "dot(1CPU)", idatas, kdata, odatas);
        test_conv2D_xcpu(ncv::math::conv_dot<matrix_t>, "dot(xCPU)", idatas, kdata, odatas);
        test_conv2D_gpu("dot(GPU)", idatas, kdata, odatas);
        std::cout << std::endl;
}

int main(int argc, char* argv[])
{
        if (!ocl::manager_t::instance().valid())
        {
                exit(EXIT_FAILURE);
        }

        static const int min_isize = 24;
        static const int max_isize = 48;
        static const int min_ksize = 5;
        static const int max_ksize = 13;
        static const int n_samples = 10000;

        try
        {
                for (int isize = min_isize; isize <= max_isize; isize += 4)
                {
                        for (int ksize = min_ksize; ksize <= max_ksize; ksize ++)
                        {
                                test(isize, ksize, n_samples);
                        }
                        std::cout << std::endl;
                }
        }

        catch (cl::Error e)
        {
                log_error() << "OpenCL fatal error: <" << e.what() << "> (" << ocl::error_string(e.err()) << ")!";
        }

	return EXIT_SUCCESS;
}

<commit_msg>fix gpu convolution<commit_after>#include "ncv.h"
#include "common/convolution.hpp"
#include "opencl/opencl.h"

using namespace ncv;

const std::string conv_program_source = R"xxx(

#pragma OPENCL EXTENSION cl_amd_fp64 : enable
#pragma OPENCL EXTENSION cl_khr_fp64 : enable

__kernel void conv_kernel(
       __global const double* idata, int icols,
       __constant const double* kdata, int krows, int kcols,
       __global double* odata)
{
        const int x = get_global_id(0);
        const int y = get_global_id(1);

        double sum = 0;
        for (int r = 0, kidx = 0; r < krows; r ++)
        {
                int iidx = (y + r) * icols + x;
                for (int c = 0; c < kcols; c ++, kidx ++, iidx ++)
                {
                        sum += kdata[kidx] * idata[iidx];
                }
        }

        odata[y * get_global_size(0) + x] = sum;
}

)xxx";

ncv::thread_pool_t pool;
const size_t tests = 4;

void init_matrix(int rows, int cols, matrix_t& matrix)
{
        matrix.resize(rows, cols);
        matrix.setRandom();
        matrix /= rows;
}

void init_matrices(int rows, int cols, int count, matrices_t& matrices)
{
	matrices.resize(count);
	for (int i = 0; i < count; i ++)
	{
		init_matrix(rows, cols, matrices[i]);
	}
}

void zero_matrices(matrices_t& matrices)
{
        for (size_t i = 0; i < matrices.size(); i ++)
        {
                matrices[i].setZero();
        }
}

scalar_t sum_matrices(matrices_t& matrices)
{
        scalar_t sum = 0;
        for (size_t i = 0; i < matrices.size(); i ++)
        {
                sum += matrices[i].sum();
        }
        return sum;
}

template <typename top>
void test_conv2D_1cpu(top op, const char* name, const matrices_t& idatas, const matrix_t& kdata, matrices_t& odatas)
{
        ncv::stats_t<double, size_t> proc_stats;

        // run multiple tests
        for (size_t t = 0; t < tests; t ++)
        {
                zero_matrices(odatas);

                const ncv::timer_t timer;

                for (size_t i = 0; i < idatas.size(); i ++)
                {
                        op(idatas[i], kdata, odatas[i]);
                }

                proc_stats(timer.miliseconds());
        }

        const scalar_t sum = sum_matrices(odatas);
        const size_t milis = static_cast<size_t>(proc_stats.avg());

        std::cout << name << "= " << text::resize(text::to_string(milis), 4, align::right)
                  << "ms (" << text::resize(text::to_string(sum), 12, align::left) << ")  ";
}

template <typename top>
void test_conv2D_xcpu(top op, const char* name, const matrices_t& idatas, const matrix_t& kdata,  matrices_t& odatas)
{
        ncv::stats_t<double, size_t> proc_stats;

        // run multiple tests
        for (size_t t = 0; t < tests; t ++)
        {
                zero_matrices(odatas);

                const ncv::timer_t timer;

                ncv::thread_loop(idatas.size(), [&] (size_t i)
                {
                        op(idatas[i], kdata, odatas[i]);
                }, pool);

                proc_stats(timer.miliseconds());
        }

        const scalar_t sum = sum_matrices(odatas);
        const size_t milis = static_cast<size_t>(proc_stats.avg());

        std::cout << name << "= " << text::resize(text::to_string(milis), 4, align::right)
                  << "ms (" << text::resize(text::to_string(sum), 12, align::left) << ")  ";
}

void test_conv2D_gpu(const char* name, const matrices_t& idatas, const matrix_t& kdata, matrices_t& odatas)
{
        const cl::Context& context = ocl::manager_t::instance().context();
        const cl::CommandQueue& queue = ocl::manager_t::instance().queue();

        const cl::Program program = ocl::manager_t::instance().program_from_text(conv_program_source);
        cl::Kernel kernel = cl::Kernel(program, "conv_kernel");

        const int icols = static_cast<int>(idatas[0].cols());
        const int krows = static_cast<int>(kdata.rows());
        const int kcols = static_cast<int>(kdata.cols());
        const int orows = static_cast<int>(odatas[0].rows());
        const int ocols = static_cast<int>(odatas[0].cols());

        const size_t mem_idata = idatas[0].size() * sizeof(scalar_t);
        const size_t mem_kdata = kdata.size() * sizeof(scalar_t);
        const size_t mem_odata = odatas[0].size() * sizeof(scalar_t);

        // create buffers once
        cl::Buffer cl_idata = cl::Buffer(context, CL_MEM_READ_ONLY, mem_idata, NULL);
        cl::Buffer cl_kdata = cl::Buffer(context, CL_MEM_READ_ONLY, mem_kdata, NULL);
        cl::Buffer cl_odata = cl::Buffer(context, CL_MEM_WRITE_ONLY, mem_odata, NULL);

        // setup kernel buffers once
        kernel.setArg(0, cl_idata);
        kernel.setArg(1, sizeof(int), (void*)&icols);
        kernel.setArg(2, cl_kdata);
        kernel.setArg(3, sizeof(int), (void*)&krows);
        kernel.setArg(4, sizeof(int), (void*)&kcols);
        kernel.setArg(5, cl_odata);
        queue.finish();

        // transfer constants
        cl::Event event;
        queue.enqueueWriteBuffer(cl_kdata, CL_FALSE, 0, mem_kdata, kdata.data(), NULL, &event);
        queue.finish();

        ncv::stats_t<double, size_t> proc_stats;

        // run multiple tests
        for (size_t t = 0; t < tests; t ++)
        {
                zero_matrices(odatas);

                ncv::timer_t timer;

                for (size_t i = 0; i < idatas.size(); i ++)
                {
                        const matrix_t& idata = idatas[i];
                        matrix_t& odata = odatas[i];

                        // I - send inputs to gpu
                        cl::Event event;
                        queue.enqueueWriteBuffer(cl_idata, CL_FALSE, 0, mem_idata, idata.data(), NULL, &event);
                        queue.finish();

                        // II - gpu processing
                        queue.enqueueNDRangeKernel(kernel, cl::NullRange, cl::NDRange(ocols, orows), cl::NullRange, NULL, &event);
                        queue.finish();

                        // III - read results from gpu
                        queue.enqueueReadBuffer(cl_odata, CL_TRUE, 0, mem_odata, odata.data(), NULL, &event);
                }

                proc_stats(timer.miliseconds());
        }

        const scalar_t sum = sum_matrices(odatas);
        const size_t milis = static_cast<size_t>(proc_stats.avg());

        std::cout << name << "= " << text::resize(text::to_string(milis), 4, align::right)
                  << "ms (" << text::resize(text::to_string(sum), 12, align::left) << ")  ";
}

void test(int isize, int ksize, int n_samples)
{
        const int osize = isize - ksize + 1;

        matrices_t idatas, odatas;
        matrix_t kdata;

        init_matrices(isize, isize, n_samples, idatas);
        init_matrices(osize, osize, n_samples, odatas);
        init_matrix(ksize, ksize, kdata);

        std::cout << "mix (isize = " << isize << ", ksize = " << ksize << "): \t";
        test_conv2D_1cpu(ncv::math::conv_eib<matrix_t>, "eib(1CPU)", idatas, kdata, odatas);
        test_conv2D_xcpu(ncv::math::conv_eib<matrix_t>, "eib(xCPU)", idatas, kdata, odatas);
        test_conv2D_1cpu(ncv::math::conv_dot<matrix_t>, "dot(1CPU)", idatas, kdata, odatas);
        test_conv2D_xcpu(ncv::math::conv_dot<matrix_t>, "dot(xCPU)", idatas, kdata, odatas);
        test_conv2D_gpu("dot(GPU)", idatas, kdata, odatas);
        std::cout << std::endl;
}

int main(int argc, char* argv[])
{
        if (!ocl::manager_t::instance().valid())
        {
                exit(EXIT_FAILURE);
        }

        static const int min_isize = 24;
        static const int max_isize = 48;
        static const int min_ksize = 5;
        static const int max_ksize = 13;
        static const int n_samples = 10000;

        try
        {
                for (int isize = min_isize; isize <= max_isize; isize += 4)
                {
                        for (int ksize = min_ksize; ksize <= max_ksize; ksize ++)
                        {
                                test(isize, ksize, n_samples);
                        }
                        std::cout << std::endl;
                }
        }

        catch (cl::Error e)
        {
                log_error() << "OpenCL fatal error: <" << e.what() << "> (" << ocl::error_string(e.err()) << ")!";
        }

	return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2012-2015 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include <inviwo/qt/widgets/inviwoapplicationqt.h>
#include <inviwo/core/util/settings/systemsettings.h>
#include <inviwo/core/util/filesystem.h>
#include <inviwo/core/util/fileobserver.h>
#include <inviwo/qt/widgets/qtwidgetmodule.h>
#include <inviwo/qt/widgets/inviwoqtutils.h>

#include <thread>

#include <QApplication>
#include <QDesktopWidget>
#include <QFile>

#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
#include <QSound>
#endif

namespace inviwo {

InviwoApplicationQt::InviwoApplicationQt(std::string displayName, std::string basePath, int& argc,
    char** argv, bool movePointsOn)
    : QApplication(argc, argv)
    , InviwoApplication(argc, argv, displayName, basePath)
    , movePointsOn_(movePointsOn)
    , mainWindow_(nullptr)
    , windowDecorationOffset_(0, 0) {

    QCoreApplication::setOrganizationName("Inviwo Foundation");
    QCoreApplication::setOrganizationDomain("inviwo.org");
    QCoreApplication::setApplicationName(displayName.c_str());

    setPostEnqueueFront([this](){
        postEvent(this, new InviwoQtEvent());
    });

    fileWatcher_ = new QFileSystemWatcher(this);
    connect(fileWatcher_, SIGNAL(fileChanged(QString)), this, SLOT(fileChanged(QString)));

// Make qt write errors in the console;
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
    qInstallMessageHandler(&InviwoApplicationQt::logQtMessages);
#endif
}

InviwoApplicationQt::~InviwoApplicationQt() {}

void InviwoApplicationQt::setMainWindow(QMainWindow* mainWindow) { mainWindow_ = mainWindow; }

void InviwoApplicationQt::registerFileObserver(FileObserver* fileObserver) {
    ivwAssert(std::find(fileObservers_.begin(), fileObservers_.end(), fileObserver) ==
                  fileObservers_.end(),
              "File observer already registered.");
    fileObservers_.push_back(fileObserver);
}

void InviwoApplicationQt::startFileObservation(std::string fileName) {
    QString qFileName = QString::fromStdString(fileName);

    if (!fileWatcher_->files().contains(qFileName)) fileWatcher_->addPath(qFileName);
}

void InviwoApplicationQt::stopFileObservation(std::string fileName) {
    QString qFileName = QString::fromStdString(fileName);

    if (fileWatcher_->files().contains(qFileName)) fileWatcher_->removePath(qFileName);
}

void InviwoApplicationQt::fileChanged(QString fileName) {
    wait(200);

    if (QFile::exists(fileName)) {
        std::string fileNameStd = fileName.toLocal8Bit().constData();

        for (auto& elem : fileObservers_) {
            std::vector<std::string> observedFiles = elem->getFiles();

            if (std::find(observedFiles.begin(), observedFiles.end(), fileNameStd) !=
                observedFiles.end())
                elem->fileChanged(fileNameStd);
        }

        if (!fileWatcher_->files().contains(fileName)) {
            fileWatcher_->addPath(fileName);
        }
    }
}

void InviwoApplicationQt::closeInviwoApplication() { QCoreApplication::quit(); }

void InviwoApplicationQt::playSound(Message message) {
// Qt currently does not support playing sounds from resources
#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
    if ((dynamic_cast<BoolProperty*>(InviwoApplication::getPtr()
                                         ->getSettingsByType<SystemSettings>()
                                         ->getPropertyByIdentifier("enableSound"))->get())) {
        if (message == Message::Ok)
            QSound::play(QString::fromStdString(
                InviwoApplication::getPtr()->getPath(InviwoApplication::PATH_RESOURCES) +
                "/sounds/ok.wav"));
        else if (message == Message::Error)
            QSound::play(QString::fromStdString(
                InviwoApplication::getPtr()->getPath(InviwoApplication::PATH_RESOURCES) +
                "/sounds/error.wav"));
    }

#endif
}

std::locale InviwoApplicationQt::getUILocale() const {
    return utilqt::getCurrentStdLocale();
}

void InviwoApplicationQt::initialize(registerModuleFuncPtr regModuleFunc) {
    LogInfoCustom("InviwoInfo", "Qt Version " << QT_VERSION_STR);
    InviwoApplication::initialize(regModuleFunc);
    // Since QtWidgets are not a module we have to register it our self
    InviwoModule* module = new QtWidgetModule(this);
    registerModule(module);
}

void InviwoApplicationQt::wait(int ms) {
    if (ms <= 0) return;
    std::this_thread::sleep_for(std::chrono::milliseconds(ms));
}

#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
void InviwoApplicationQt::logQtMessages(QtMsgType type, const QMessageLogContext& context,
                                        const QString& msg) {
#ifdef IVW_DEBUG
    QByteArray localMsg = msg.toLocal8Bit();
    switch (type) {
        case QtDebugMsg:
            inviwo::LogCentral::getPtr()->log("Qt Debug", LogLevel::Info, LogAudience::Developer,
                                              context.file, context.function, context.line,
                                              msg.toUtf8().constData());

            fprintf(stderr, "Debug: %s (%s:%u, %s)\n", localMsg.constData(), context.file,
                    context.line, context.function);
            break;
        case QtWarningMsg:
            inviwo::LogCentral::getPtr()->log("Qt Warning", LogLevel::Info, LogAudience::Developer,
                                              context.file, context.function, context.line,
                                              msg.toUtf8().constData());

            fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), context.file,
                    context.line, context.function);
            break;
        case QtCriticalMsg:
            inviwo::LogCentral::getPtr()->log("Qt Critical", LogLevel::Info, LogAudience::Developer,
                                              context.file, context.function, context.line,
                                              msg.toUtf8().constData());

            fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), context.file,
                    context.line, context.function);
            break;
        case QtFatalMsg:
            inviwo::LogCentral::getPtr()->log("Qt Fatal", LogLevel::Info, LogAudience::Developer,
                                              context.file, context.function, context.line,
                                              msg.toUtf8().constData());

            fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), context.file,
                    context.line, context.function);
            abort();
            break;
        case QtInfoMsg:
            inviwo::LogCentral::getPtr()->log("Qt Info", LogLevel::Info, LogAudience::Developer,
                context.file, context.function, context.line,
                msg.toUtf8().constData());

            fprintf(stderr, "Info: %s (%s:%u, %s)\n", localMsg.constData(), context.file,
                context.line, context.function);
            break;
    }
#endif
}
#endif

QPoint InviwoApplicationQt::getWindowDecorationOffset() const { return windowDecorationOffset_; }

void InviwoApplicationQt::setWindowDecorationOffset(QPoint windowDecorationOffset) {
    windowDecorationOffset_ = windowDecorationOffset;
}

QPoint InviwoApplicationQt::movePointOntoDesktop(const QPoint& point, const QSize& size,
                                                 bool decorationOffset) {
    QPoint pos(point);
    if (movePointsOn_) {
        QDesktopWidget* desktop = QApplication::desktop();
        int primaryScreenIndex = desktop->primaryScreen();
        QRect wholeScreen = desktop->screenGeometry(primaryScreenIndex);

        for (int i = 0; i < desktop->screenCount(); i++) {
            if (i != primaryScreenIndex) wholeScreen = wholeScreen.united(desktop->screenGeometry(i));
        }

        wholeScreen.setRect(wholeScreen.x() - 10, wholeScreen.y() - 10, wholeScreen.width() + 20,
            wholeScreen.height() + 20);
        QPoint bottomRight = QPoint(point.x() + size.width(), point.y() + size.height());
        QPoint appPos = getMainWindow()->pos();

#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
        if (decorationOffset) {
            QPoint offset = getWindowDecorationOffset();
            pos -= offset;
        }
#endif

        if (!wholeScreen.contains(pos) || !wholeScreen.contains(bottomRight)) {
            // If the widget is outside visible screen
            pos = appPos;
            pos += offsetWidget();
        }
    }
    return pos;
}

QPoint InviwoApplicationQt::offsetWidget() {
    static int offsetCounter = 0;
    static ivec2 baseOffset(350, 100);

    ivec2 pos(0, 0);
    pos += baseOffset + ivec2(40 * offsetCounter++);

    if (offsetCounter == 10) {  // reset offset
        offsetCounter = 0;
        baseOffset.x += 200;
        if (baseOffset.x >= 800) {
            baseOffset.x = 350;
            baseOffset.y += 100;
            if (baseOffset.y >= 800) {
                baseOffset.y = 100;
            }
        }
    }
    return QPoint(pos.x, pos.y);
}

bool InviwoApplicationQt::event(QEvent* e) {
    if (e->type() == InviwoQtEvent::type()) {
        e->accept();
        processFront();
        return true;
    } else {
        return QApplication::event(e);
    }
}

QEvent::Type InviwoQtEvent::INVIWO_QT_EVENT = QEvent::None;

}  // namespace
<commit_msg>Qt: Compability check for added enum, see commit 5c31c21e1d647b8186e6ca29683110d428844563<commit_after>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2012-2015 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include <inviwo/qt/widgets/inviwoapplicationqt.h>
#include <inviwo/core/util/settings/systemsettings.h>
#include <inviwo/core/util/filesystem.h>
#include <inviwo/core/util/fileobserver.h>
#include <inviwo/qt/widgets/qtwidgetmodule.h>
#include <inviwo/qt/widgets/inviwoqtutils.h>

#include <thread>

#include <QApplication>
#include <QDesktopWidget>
#include <QFile>

#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
#include <QSound>
#endif

namespace inviwo {

InviwoApplicationQt::InviwoApplicationQt(std::string displayName, std::string basePath, int& argc,
    char** argv, bool movePointsOn)
    : QApplication(argc, argv)
    , InviwoApplication(argc, argv, displayName, basePath)
    , movePointsOn_(movePointsOn)
    , mainWindow_(nullptr)
    , windowDecorationOffset_(0, 0) {

    QCoreApplication::setOrganizationName("Inviwo Foundation");
    QCoreApplication::setOrganizationDomain("inviwo.org");
    QCoreApplication::setApplicationName(displayName.c_str());

    setPostEnqueueFront([this](){
        postEvent(this, new InviwoQtEvent());
    });

    fileWatcher_ = new QFileSystemWatcher(this);
    connect(fileWatcher_, SIGNAL(fileChanged(QString)), this, SLOT(fileChanged(QString)));

// Make qt write errors in the console;
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
    qInstallMessageHandler(&InviwoApplicationQt::logQtMessages);
#endif
}

InviwoApplicationQt::~InviwoApplicationQt() {}

void InviwoApplicationQt::setMainWindow(QMainWindow* mainWindow) { mainWindow_ = mainWindow; }

void InviwoApplicationQt::registerFileObserver(FileObserver* fileObserver) {
    ivwAssert(std::find(fileObservers_.begin(), fileObservers_.end(), fileObserver) ==
                  fileObservers_.end(),
              "File observer already registered.");
    fileObservers_.push_back(fileObserver);
}

void InviwoApplicationQt::startFileObservation(std::string fileName) {
    QString qFileName = QString::fromStdString(fileName);

    if (!fileWatcher_->files().contains(qFileName)) fileWatcher_->addPath(qFileName);
}

void InviwoApplicationQt::stopFileObservation(std::string fileName) {
    QString qFileName = QString::fromStdString(fileName);

    if (fileWatcher_->files().contains(qFileName)) fileWatcher_->removePath(qFileName);
}

void InviwoApplicationQt::fileChanged(QString fileName) {
    wait(200);

    if (QFile::exists(fileName)) {
        std::string fileNameStd = fileName.toLocal8Bit().constData();

        for (auto& elem : fileObservers_) {
            std::vector<std::string> observedFiles = elem->getFiles();

            if (std::find(observedFiles.begin(), observedFiles.end(), fileNameStd) !=
                observedFiles.end())
                elem->fileChanged(fileNameStd);
        }

        if (!fileWatcher_->files().contains(fileName)) {
            fileWatcher_->addPath(fileName);
        }
    }
}

void InviwoApplicationQt::closeInviwoApplication() { QCoreApplication::quit(); }

void InviwoApplicationQt::playSound(Message message) {
// Qt currently does not support playing sounds from resources
#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
    if ((dynamic_cast<BoolProperty*>(InviwoApplication::getPtr()
                                         ->getSettingsByType<SystemSettings>()
                                         ->getPropertyByIdentifier("enableSound"))->get())) {
        if (message == Message::Ok)
            QSound::play(QString::fromStdString(
                InviwoApplication::getPtr()->getPath(InviwoApplication::PATH_RESOURCES) +
                "/sounds/ok.wav"));
        else if (message == Message::Error)
            QSound::play(QString::fromStdString(
                InviwoApplication::getPtr()->getPath(InviwoApplication::PATH_RESOURCES) +
                "/sounds/error.wav"));
    }

#endif
}

std::locale InviwoApplicationQt::getUILocale() const {
    return utilqt::getCurrentStdLocale();
}

void InviwoApplicationQt::initialize(registerModuleFuncPtr regModuleFunc) {
    LogInfoCustom("InviwoInfo", "Qt Version " << QT_VERSION_STR);
    InviwoApplication::initialize(regModuleFunc);
    // Since QtWidgets are not a module we have to register it our self
    InviwoModule* module = new QtWidgetModule(this);
    registerModule(module);
}

void InviwoApplicationQt::wait(int ms) {
    if (ms <= 0) return;
    std::this_thread::sleep_for(std::chrono::milliseconds(ms));
}

#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
void InviwoApplicationQt::logQtMessages(QtMsgType type, const QMessageLogContext& context,
                                        const QString& msg) {
#ifdef IVW_DEBUG
    QByteArray localMsg = msg.toLocal8Bit();
    switch (type) {
        case QtDebugMsg:
            inviwo::LogCentral::getPtr()->log("Qt Debug", LogLevel::Info, LogAudience::Developer,
                                              context.file, context.function, context.line,
                                              msg.toUtf8().constData());

            fprintf(stderr, "Debug: %s (%s:%u, %s)\n", localMsg.constData(), context.file,
                    context.line, context.function);
            break;
        case QtWarningMsg:
            inviwo::LogCentral::getPtr()->log("Qt Warning", LogLevel::Info, LogAudience::Developer,
                                              context.file, context.function, context.line,
                                              msg.toUtf8().constData());

            fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), context.file,
                    context.line, context.function);
            break;
        case QtCriticalMsg:
            inviwo::LogCentral::getPtr()->log("Qt Critical", LogLevel::Info, LogAudience::Developer,
                                              context.file, context.function, context.line,
                                              msg.toUtf8().constData());

            fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), context.file,
                    context.line, context.function);
            break;
        case QtFatalMsg:
            inviwo::LogCentral::getPtr()->log("Qt Fatal", LogLevel::Info, LogAudience::Developer,
                                              context.file, context.function, context.line,
                                              msg.toUtf8().constData());

            fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), context.file,
                    context.line, context.function);
            abort();
            break;
#if (QT_VERSION >= QT_VERSION_CHECK(5, 5, 0))
        case QtInfoMsg:
            inviwo::LogCentral::getPtr()->log("Qt Info", LogLevel::Info, LogAudience::Developer,
                context.file, context.function, context.line,
                msg.toUtf8().constData());

            fprintf(stderr, "Info: %s (%s:%u, %s)\n", localMsg.constData(), context.file,
                context.line, context.function);
            break;
#endif
    }
#endif
}
#endif

QPoint InviwoApplicationQt::getWindowDecorationOffset() const { return windowDecorationOffset_; }

void InviwoApplicationQt::setWindowDecorationOffset(QPoint windowDecorationOffset) {
    windowDecorationOffset_ = windowDecorationOffset;
}

QPoint InviwoApplicationQt::movePointOntoDesktop(const QPoint& point, const QSize& size,
                                                 bool decorationOffset) {
    QPoint pos(point);
    if (movePointsOn_) {
        QDesktopWidget* desktop = QApplication::desktop();
        int primaryScreenIndex = desktop->primaryScreen();
        QRect wholeScreen = desktop->screenGeometry(primaryScreenIndex);

        for (int i = 0; i < desktop->screenCount(); i++) {
            if (i != primaryScreenIndex) wholeScreen = wholeScreen.united(desktop->screenGeometry(i));
        }

        wholeScreen.setRect(wholeScreen.x() - 10, wholeScreen.y() - 10, wholeScreen.width() + 20,
            wholeScreen.height() + 20);
        QPoint bottomRight = QPoint(point.x() + size.width(), point.y() + size.height());
        QPoint appPos = getMainWindow()->pos();

#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
        if (decorationOffset) {
            QPoint offset = getWindowDecorationOffset();
            pos -= offset;
        }
#endif

        if (!wholeScreen.contains(pos) || !wholeScreen.contains(bottomRight)) {
            // If the widget is outside visible screen
            pos = appPos;
            pos += offsetWidget();
        }
    }
    return pos;
}

QPoint InviwoApplicationQt::offsetWidget() {
    static int offsetCounter = 0;
    static ivec2 baseOffset(350, 100);

    ivec2 pos(0, 0);
    pos += baseOffset + ivec2(40 * offsetCounter++);

    if (offsetCounter == 10) {  // reset offset
        offsetCounter = 0;
        baseOffset.x += 200;
        if (baseOffset.x >= 800) {
            baseOffset.x = 350;
            baseOffset.y += 100;
            if (baseOffset.y >= 800) {
                baseOffset.y = 100;
            }
        }
    }
    return QPoint(pos.x, pos.y);
}

bool InviwoApplicationQt::event(QEvent* e) {
    if (e->type() == InviwoQtEvent::type()) {
        e->accept();
        processFront();
        return true;
    } else {
        return QApplication::event(e);
    }
}

QEvent::Type InviwoQtEvent::INVIWO_QT_EVENT = QEvent::None;

}  // namespace
<|endoftext|>


<commit_before>#include <stdlib.h>
#include <string.h>
#include <string>

#include <realm/util/features.h>
#include <realm/util/basic_system_errors.hpp>

using namespace realm::util;

namespace {

class system_category: public std::error_category {
    const char* name() const REALM_NOEXCEPT override;
    std::string message(int) const override;
};

system_category g_system_category;

const char* system_category::name() const REALM_NOEXCEPT
{
    return "realm.basic_system";
}

std::string system_category::message(int value) const
{
    const size_t max_msg_size = 256;
    char buffer[max_msg_size+1];

#ifdef _WIN32 // Windows version

    if (REALM_LIKELY(strerror_s(buffer, max_msg_size, value) == 0)) {
        return buffer; // Guaranteed to be truncated
    }

#elif defined __APPLE__ && defined __MACH__ // OSX, iOS and WatchOS version

    {
        const int result = strerror_r(value, buffer, max_msg_size);
        if (REALM_LIKELY(result == 0 || result == ERANGE || result == EINVAL)) {
            return buffer; // Guaranteed to be truncated
        }
    }

#elif ! REALM_ANDROID && _GNU_SOURCE // GNU specific version

    {
        char* msg = nullptr;
        if (REALM_LIKELY((msg = strerror_r(value, buffer, max_msg_size)) != nullptr)) {
            return msg; // Guaranteed to be truncated
        }
    }

#else // XSI-compliant version, used by Android

    {
        const int result = strerror_r(value, buffer, max_msg_size);
        if (REALM_LIKELY(result == 0 || result == EINVAL)) {
            buffer[max_msg_size] = 0; // For safety's sake, not guaranteed to be truncated by POSIX
            return buffer;
        }
    }

#endif

    return "Unknown error";
}

} // anonymous namespace

namespace realm {
namespace util {
namespace error {

std::error_code make_error_code(basic_system_errors err)
{
    return std::error_code(err, g_system_category);
}

} // namespace error
} // namespace util
} // namespace realm
<commit_msg>Small change to fallback description<commit_after>#include <stdlib.h>
#include <string.h>
#include <string>

#include <realm/util/features.h>
#include <realm/util/basic_system_errors.hpp>

using namespace realm::util;

namespace {

class system_category: public std::error_category {
    const char* name() const REALM_NOEXCEPT override;
    std::string message(int) const override;
};

system_category g_system_category;

const char* system_category::name() const REALM_NOEXCEPT
{
    return "realm.basic_system";
}

std::string system_category::message(int value) const
{
    const size_t max_msg_size = 256;
    char buffer[max_msg_size+1];

#ifdef _WIN32 // Windows version

    if (REALM_LIKELY(strerror_s(buffer, max_msg_size, value) == 0)) {
        return buffer; // Guaranteed to be truncated
    }

#elif defined __APPLE__ && defined __MACH__ // OSX, iOS and WatchOS version

    {
        const int result = strerror_r(value, buffer, max_msg_size);
        if (REALM_LIKELY(result == 0 || result == ERANGE || result == EINVAL)) {
            return buffer; // Guaranteed to be truncated
        }
    }

#elif ! REALM_ANDROID && _GNU_SOURCE // GNU specific version

    {
        char* msg = nullptr;
        if (REALM_LIKELY((msg = strerror_r(value, buffer, max_msg_size)) != nullptr)) {
            return msg; // Guaranteed to be truncated
        }
    }

#else // POSIX.1-2001 fallback version

    {
        const int result = strerror_r(value, buffer, max_msg_size);
        if (REALM_LIKELY(result == 0 || result == EINVAL)) {
            buffer[max_msg_size] = 0; // For safety's sake, not guaranteed to be truncated by POSIX
            return buffer;
        }
    }

#endif

    return "Unknown error";
}

} // anonymous namespace

namespace realm {
namespace util {
namespace error {

std::error_code make_error_code(basic_system_errors err)
{
    return std::error_code(err, g_system_category);
}

} // namespace error
} // namespace util
} // namespace realm
<|endoftext|>