<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: AccessibleCell.hxx,v $
 * $Revision: 1.16 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _SC_ACCESSIBLECELL_HXX
#define _SC_ACCESSIBLECELL_HXX

#include "AccessibleCellBase.hxx"
#include "global.hxx"
#include "viewdata.hxx"
#include <com/sun/star/accessibility/XAccessibleRelationSet.hpp>
#include <unotools/accessiblerelationsethelper.hxx>
#include <svx/AccessibleStaticTextBase.hxx>

class ScTabViewShell;
class ScAccessibleDocument;

/** @descr
        This base class provides an implementation of the
        AccessibleCell service.
*/
class ScAccessibleCell
    :   public  ScAccessibleCellBase,
        public  accessibility::AccessibleStaticTextBase
{
public:
    //=====  internal  ========================================================
    ScAccessibleCell(
        const ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible>& rxParent,
        ScTabViewShell* pViewShell,
        ScAddress& rCellAddress,
        sal_Int32 nIndex,
        ScSplitPos eSplitPos,
        ScAccessibleDocument* pAccDoc);

    virtual void Init();

    using ScAccessibleCellBase::disposing;
    virtual void SAL_CALL disposing();

protected:
    virtual ~ScAccessibleCell();

    using ScAccessibleCellBase::IsDefunc;

public:
    ///=====  XInterface  =====================================================

    virtual ::com::sun::star::uno::Any SAL_CALL queryInterface(
        ::com::sun::star::uno::Type const & rType )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL acquire() throw ();

    virtual void SAL_CALL release() throw ();

    ///=====  XAccessibleComponent  ============================================

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >
        SAL_CALL getAccessibleAtPoint(
        const ::com::sun::star::awt::Point& rPoint )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL grabFocus(  )
        throw (::com::sun::star::uno::RuntimeException);

protected:
    /// Return the object's current bounding box relative to the desktop.
    virtual Rectangle GetBoundingBoxOnScreen(void) const
        throw (::com::sun::star::uno::RuntimeException);

    /// Return the object's current bounding box relative to the parent object.
    virtual Rectangle GetBoundingBox(void) const
        throw (::com::sun::star::uno::RuntimeException);

public:
    ///=====  XAccessibleContext  ==============================================

    /// Return the number of currently visible children.
    // is overloaded to calculate this on demand
    virtual sal_Int32 SAL_CALL
        getAccessibleChildCount(void)
                    throw (::com::sun::star::uno::RuntimeException);

    /// Return the specified child or NULL if index is invalid.
    // is overloaded to calculate this on demand
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> SAL_CALL
        getAccessibleChild(sal_Int32 nIndex)
        throw (::com::sun::star::uno::RuntimeException,
                ::com::sun::star::lang::IndexOutOfBoundsException);

    /// Return the set of current states.
    virtual ::com::sun::star::uno::Reference<
            ::com::sun::star::accessibility::XAccessibleStateSet> SAL_CALL
        getAccessibleStateSet(void)
        throw (::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessibleRelationSet> SAL_CALL
           getAccessibleRelationSet(void)
        throw (::com::sun::star::uno::RuntimeException);

    ///=====  XServiceInfo  ====================================================

    /** Returns an identifier for the implementation of this object.
    */
    virtual ::rtl::OUString SAL_CALL
        getImplementationName(void)
        throw (::com::sun::star::uno::RuntimeException);

    /** Returns a list of all supported services.
    */
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL
        getSupportedServiceNames(void)
        throw (::com::sun::star::uno::RuntimeException);

    ///=====  XTypeProvider  ===================================================

    /// returns the possible types
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL
        getTypes()
        throw (::com::sun::star::uno::RuntimeException);

    /** Returns a implementation id.
    */
    virtual ::com::sun::star::uno::Sequence<sal_Int8> SAL_CALL
        getImplementationId(void)
        throw (::com::sun::star::uno::RuntimeException);

private:
    ScTabViewShell* mpViewShell;
    ScAccessibleDocument* mpAccDoc;

    ScSplitPos meSplitPos;

    sal_Bool IsDefunc(
        const com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessibleStateSet>& rxParentStates);
    virtual sal_Bool IsEditable(
        const com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessibleStateSet>& rxParentStates);
    sal_Bool IsOpaque(
        const com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessibleStateSet>& rxParentStates);
    sal_Bool IsSelected();

    ScDocument* GetDocument(ScTabViewShell* mpViewShell);

    ::std::auto_ptr< SvxEditSource > CreateEditSource(ScTabViewShell* pViewShell, ScAddress aCell, ScSplitPos eSplitPos);

    void FillDependends(utl::AccessibleRelationSetHelper* pRelationSet);
    void FillPrecedents(utl::AccessibleRelationSetHelper* pRelationSet);
    void AddRelation(const ScAddress& rCell,
        const sal_uInt16 aRelationType,
        ::utl::AccessibleRelationSetHelper* pRelationSet);
    void AddRelation(const ScRange& rRange,
        const sal_uInt16 aRelationType,
        ::utl::AccessibleRelationSetHelper* pRelationSet);
};

#endif
<commit_msg>INTEGRATION: CWS tbe34 (1.16.72); FILE MERGED 2008/06/23 12:44:34 tbe 1.16.72.1: #i82480# [a11y] Orca Insert-f to get text attributes doesn't work when you are in a spread sheet table cell<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: AccessibleCell.hxx,v $
 * $Revision: 1.17 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _SC_ACCESSIBLECELL_HXX
#define _SC_ACCESSIBLECELL_HXX

#include "AccessibleCellBase.hxx"
#include "global.hxx"
#include "viewdata.hxx"
#include <com/sun/star/accessibility/XAccessibleRelationSet.hpp>
#include <unotools/accessiblerelationsethelper.hxx>
#include <svx/AccessibleStaticTextBase.hxx>
#include <comphelper/uno3.hxx>

class ScTabViewShell;
class ScAccessibleDocument;

/** @descr
        This base class provides an implementation of the
        AccessibleCell service.
*/
class ScAccessibleCell
    :   public  ScAccessibleCellBase,
        public  accessibility::AccessibleStaticTextBase
{
public:
    //=====  internal  ========================================================
    ScAccessibleCell(
        const ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible>& rxParent,
        ScTabViewShell* pViewShell,
        ScAddress& rCellAddress,
        sal_Int32 nIndex,
        ScSplitPos eSplitPos,
        ScAccessibleDocument* pAccDoc);

    virtual void Init();

    using ScAccessibleCellBase::disposing;
    virtual void SAL_CALL disposing();

protected:
    virtual ~ScAccessibleCell();

    using ScAccessibleCellBase::IsDefunc;

public:
    ///=====  XInterface  =====================================================

    DECLARE_XINTERFACE()

    ///=====  XTypeProvider  ===================================================

    DECLARE_XTYPEPROVIDER()

    ///=====  XAccessibleComponent  ============================================

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >
        SAL_CALL getAccessibleAtPoint(
        const ::com::sun::star::awt::Point& rPoint )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL grabFocus(  )
        throw (::com::sun::star::uno::RuntimeException);

protected:
    /// Return the object's current bounding box relative to the desktop.
    virtual Rectangle GetBoundingBoxOnScreen(void) const
        throw (::com::sun::star::uno::RuntimeException);

    /// Return the object's current bounding box relative to the parent object.
    virtual Rectangle GetBoundingBox(void) const
        throw (::com::sun::star::uno::RuntimeException);

public:
    ///=====  XAccessibleContext  ==============================================

    /// Return the number of currently visible children.
    // is overloaded to calculate this on demand
    virtual sal_Int32 SAL_CALL
        getAccessibleChildCount(void)
                    throw (::com::sun::star::uno::RuntimeException);

    /// Return the specified child or NULL if index is invalid.
    // is overloaded to calculate this on demand
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> SAL_CALL
        getAccessibleChild(sal_Int32 nIndex)
        throw (::com::sun::star::uno::RuntimeException,
                ::com::sun::star::lang::IndexOutOfBoundsException);

    /// Return the set of current states.
    virtual ::com::sun::star::uno::Reference<
            ::com::sun::star::accessibility::XAccessibleStateSet> SAL_CALL
        getAccessibleStateSet(void)
        throw (::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessibleRelationSet> SAL_CALL
           getAccessibleRelationSet(void)
        throw (::com::sun::star::uno::RuntimeException);

    ///=====  XServiceInfo  ====================================================

    /** Returns an identifier for the implementation of this object.
    */
    virtual ::rtl::OUString SAL_CALL
        getImplementationName(void)
        throw (::com::sun::star::uno::RuntimeException);

    /** Returns a list of all supported services.
    */
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL
        getSupportedServiceNames(void)
        throw (::com::sun::star::uno::RuntimeException);

private:
    ScTabViewShell* mpViewShell;
    ScAccessibleDocument* mpAccDoc;

    ScSplitPos meSplitPos;

    sal_Bool IsDefunc(
        const com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessibleStateSet>& rxParentStates);
    virtual sal_Bool IsEditable(
        const com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessibleStateSet>& rxParentStates);
    sal_Bool IsOpaque(
        const com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessibleStateSet>& rxParentStates);
    sal_Bool IsSelected();

    ScDocument* GetDocument(ScTabViewShell* mpViewShell);

    ::std::auto_ptr< SvxEditSource > CreateEditSource(ScTabViewShell* pViewShell, ScAddress aCell, ScSplitPos eSplitPos);

    void FillDependends(utl::AccessibleRelationSetHelper* pRelationSet);
    void FillPrecedents(utl::AccessibleRelationSetHelper* pRelationSet);
    void AddRelation(const ScAddress& rCell,
        const sal_uInt16 aRelationType,
        ::utl::AccessibleRelationSetHelper* pRelationSet);
    void AddRelation(const ScRange& rRange,
        const sal_uInt16 aRelationType,
        ::utl::AccessibleRelationSetHelper* pRelationSet);
};

#endif
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * 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.
**   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
**     the names of its contributors may be used to endorse or promote
**     products derived from this software without specific prior written
**     permission.
**
** 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."
** $QT_END_LICENSE$
**
****************************************************************************/

#include "player.h"

#include "playercontrols.h"
#include "playlistmodel.h"
#include "videowidget.h"

#include <qmediaservice.h>
#include <qmediaplaylist.h>

#include <QtGui>

Player::Player(QWidget *parent)
    : QWidget(parent)
    , videoWidget(0)
    , coverLabel(0)
    , slider(0)
    , colorDialog(0)
{
//! [create-objs]
    player = new QMediaPlayer(this);
    // owned by PlaylistModel
    playlist = new QMediaPlaylist();
    player->setPlaylist(playlist);
//! [create-objs]

    connect(player, SIGNAL(durationChanged(qint64)), SLOT(durationChanged(qint64)));
    connect(player, SIGNAL(positionChanged(qint64)), SLOT(positionChanged(qint64)));
    connect(player, SIGNAL(metaDataChanged()), SLOT(metaDataChanged()));
    connect(playlist, SIGNAL(currentIndexChanged(int)), SLOT(playlistPositionChanged(int)));
    connect(player, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)),
            this, SLOT(statusChanged(QMediaPlayer::MediaStatus)));
    connect(player, SIGNAL(bufferStatusChanged(int)), this, SLOT(bufferingProgress(int)));
    connect(player, SIGNAL(error(QMediaPlayer::Error)), this, SLOT(displayErrorMessage()));

//! [2]
    videoWidget = new VideoWidget(this);
    player->setVideoOutput(videoWidget);

    playlistModel = new PlaylistModel(this);
    playlistModel->setPlaylist(playlist);
//! [2]

    playlistView = new QListView(this);
    playlistView->setModel(playlistModel);
    playlistView->setCurrentIndex(playlistModel->index(playlist->currentIndex(), 0));

    connect(playlistView, SIGNAL(activated(QModelIndex)), this, SLOT(jump(QModelIndex)));

    slider = new QSlider(Qt::Horizontal, this);
    slider->setRange(0, player->duration() / 1000);

    connect(slider, SIGNAL(sliderMoved(int)), this, SLOT(seek(int)));

    QPushButton *openButton = new QPushButton(tr("Open"), this);

    connect(openButton, SIGNAL(clicked()), this, SLOT(open()));

    PlayerControls *controls = new PlayerControls(this);
    controls->setState(player->state());
    controls->setVolume(player->volume());
    controls->setMuted(controls->isMuted());

    connect(controls, SIGNAL(play()), player, SLOT(play()));
    connect(controls, SIGNAL(pause()), player, SLOT(pause()));
    connect(controls, SIGNAL(stop()), player, SLOT(stop()));
    connect(controls, SIGNAL(next()), playlist, SLOT(next()));
    connect(controls, SIGNAL(previous()), this, SLOT(previousClicked()));
    connect(controls, SIGNAL(changeVolume(int)), player, SLOT(setVolume(int)));
    connect(controls, SIGNAL(changeMuting(bool)), player, SLOT(setMuted(bool)));
    connect(controls, SIGNAL(changeRate(qreal)), player, SLOT(setPlaybackRate(qreal)));

    connect(controls, SIGNAL(stop()), videoWidget, SLOT(update()));

    connect(player, SIGNAL(stateChanged(QMediaPlayer::State)),
            controls, SLOT(setState(QMediaPlayer::State)));
    connect(player, SIGNAL(volumeChanged(int)), controls, SLOT(setVolume(int)));
    connect(player, SIGNAL(mutedChanged(bool)), controls, SLOT(setMuted(bool)));

    QPushButton *fullScreenButton = new QPushButton(tr("FullScreen"), this);
    fullScreenButton->setCheckable(true);

    if (videoWidget != 0) {
        connect(fullScreenButton, SIGNAL(clicked(bool)), videoWidget, SLOT(setFullScreen(bool)));
        connect(videoWidget, SIGNAL(fullScreenChanged(bool)),
                fullScreenButton, SLOT(setChecked(bool)));
    } else {
        fullScreenButton->setEnabled(false);
    }

    QPushButton *colorButton = new QPushButton(tr("Color Options..."), this);
    if (videoWidget)
        connect(colorButton, SIGNAL(clicked()), this, SLOT(showColorDialog()));
    else
        colorButton->setEnabled(false);

    QBoxLayout *displayLayout = new QHBoxLayout;
    if (videoWidget)
        displayLayout->addWidget(videoWidget, 2);
    else
        displayLayout->addWidget(coverLabel, 2);
    displayLayout->addWidget(playlistView);

    QBoxLayout *controlLayout = new QHBoxLayout;
    controlLayout->setMargin(0);
    controlLayout->addWidget(openButton);
    controlLayout->addStretch(1);
    controlLayout->addWidget(controls);
    controlLayout->addStretch(1);
    controlLayout->addWidget(fullScreenButton);
    controlLayout->addWidget(colorButton);

    QBoxLayout *layout = new QVBoxLayout;
    layout->addLayout(displayLayout);
    layout->addWidget(slider);
    layout->addLayout(controlLayout);

    setLayout(layout);

    if (!player->isAvailable()) {
        QMessageBox::warning(this, tr("Service not available"),
                             tr("The QMediaPlayer object does not have a valid service.\n"\
                                "Please check the media service plugins are installed."));

        controls->setEnabled(false);
        playlistView->setEnabled(false);
        openButton->setEnabled(false);
        colorButton->setEnabled(false);
        fullScreenButton->setEnabled(false);
    }

    metaDataChanged();

    QStringList arguments = qApp->arguments();
    arguments.removeAt(0);
    addToPlaylist(arguments);
}

Player::~Player()
{
}

void Player::open()
{
#ifdef Q_WS_MAEMO_5
    QStringList fileNames;
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open Files"), "/");
    if (!fileName.isEmpty())
        fileNames << fileName;
#else
    QStringList fileNames = QFileDialog::getOpenFileNames(this, tr("Open Files"));
#endif
    addToPlaylist(fileNames);
}

void Player::addToPlaylist(const QStringList& fileNames)
{
    foreach (QString const &argument, fileNames) {
        QFileInfo fileInfo(argument);
        if (fileInfo.exists()) {
            QUrl url = QUrl::fromLocalFile(fileInfo.absoluteFilePath());
            if (fileInfo.suffix().toLower() == QLatin1String("m3u")) {
                playlist->load(url);
            } else
                playlist->addMedia(url);
        } else {
            QUrl url(argument);
            if (url.isValid()) {
                playlist->addMedia(url);
            }
        }
    }
}

void Player::durationChanged(qint64 duration)
{
    slider->setMaximum(duration / 1000);
}

void Player::positionChanged(qint64 progress)
{
    if (!slider->isSliderDown()) {
        slider->setValue(progress / 1000);
    }
}

void Player::metaDataChanged()
{
    //qDebug() << "update metadata" << player->metaData(QtMultimediaKit::Title).toString();
    if (player->isMetaDataAvailable()) {
        setTrackInfo(QString("%1 - %2")
                .arg(player->metaData(QtMultimediaKit::AlbumArtist).toString())
                .arg(player->metaData(QtMultimediaKit::Title).toString()));

        if (coverLabel) {
            QUrl url = player->metaData(QtMultimediaKit::CoverArtUrlLarge).value<QUrl>();

            coverLabel->setPixmap(!url.isEmpty()
                    ? QPixmap(url.toString())
                    : QPixmap());
        }
    }
}

void Player::previousClicked()
{
    // Go to previous track if we are within the first 5 seconds of playback
    // Otherwise, seek to the beginning.
    if(player->position() <= 5000)
        playlist->previous();
    else
        player->setPosition(0);
}

void Player::jump(const QModelIndex &index)
{
    if (index.isValid()) {
        playlist->setCurrentIndex(index.row());
        player->play();
    }
}

void Player::playlistPositionChanged(int currentItem)
{
    playlistView->setCurrentIndex(playlistModel->index(currentItem, 0));
}

void Player::seek(int seconds)
{
    player->setPosition(seconds * 1000);
}

void Player::statusChanged(QMediaPlayer::MediaStatus status)
{
    handleCursor(status);

    // handle status message
    switch (status) {
    case QMediaPlayer::UnknownMediaStatus:
    case QMediaPlayer::NoMedia:
    case QMediaPlayer::LoadedMedia:
    case QMediaPlayer::BufferingMedia:
    case QMediaPlayer::BufferedMedia:
        setStatusInfo(QString());
        break;
    case QMediaPlayer::LoadingMedia:
        setStatusInfo(tr("Loading..."));
        break;
    case QMediaPlayer::StalledMedia:
        setStatusInfo(tr("Media Stalled"));
        break;
    case QMediaPlayer::EndOfMedia:
        QApplication::alert(this);
        break;
    case QMediaPlayer::InvalidMedia:
        displayErrorMessage();
        break;
    }
}

void Player::handleCursor(QMediaPlayer::MediaStatus status)
{
#ifndef QT_NO_CURSOR
    if( status == QMediaPlayer::LoadingMedia ||
        status == QMediaPlayer::BufferingMedia ||
        status == QMediaPlayer::StalledMedia)
        setCursor(QCursor(Qt::BusyCursor));
    else
        unsetCursor();
#endif
}

void Player::bufferingProgress(int progress)
{
    setStatusInfo(tr("Buffering %4%").arg(progress));
}

void Player::setTrackInfo(const QString &info)
{
    trackInfo = info;
    if (!statusInfo.isEmpty())
        setWindowTitle(QString("%1 | %2").arg(trackInfo).arg(statusInfo));
    else
        setWindowTitle(trackInfo);
}

void Player::setStatusInfo(const QString &info)
{
    statusInfo = info;
    if (!statusInfo.isEmpty())
        setWindowTitle(QString("%1 | %2").arg(trackInfo).arg(statusInfo));
    else
        setWindowTitle(trackInfo);
}

void Player::displayErrorMessage()
{
    setStatusInfo(player->errorString());

}

void Player::showColorDialog()
{
    if (!colorDialog) {
        QSlider *brightnessSlider = new QSlider(Qt::Horizontal);
        brightnessSlider->setRange(-100, 100);
        brightnessSlider->setValue(videoWidget->brightness());
        connect(brightnessSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setBrightness(int)));
        connect(videoWidget, SIGNAL(brightnessChanged(int)), brightnessSlider, SLOT(setValue(int)));

        QSlider *contrastSlider = new QSlider(Qt::Horizontal);
        contrastSlider->setRange(-100, 100);
        contrastSlider->setValue(videoWidget->contrast());
        connect(contrastSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setContrast(int)));
        connect(videoWidget, SIGNAL(contrastChanged(int)), contrastSlider, SLOT(setValue(int)));

        QSlider *hueSlider = new QSlider(Qt::Horizontal);
        hueSlider->setRange(-100, 100);
        hueSlider->setValue(videoWidget->hue());
        connect(hueSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setHue(int)));
        connect(videoWidget, SIGNAL(hueChanged(int)), hueSlider, SLOT(setValue(int)));

        QSlider *saturationSlider = new QSlider(Qt::Horizontal);
        saturationSlider->setRange(-100, 100);
        saturationSlider->setValue(videoWidget->saturation());
        connect(saturationSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setSaturation(int)));
        connect(videoWidget, SIGNAL(saturationChanged(int)), saturationSlider, SLOT(setValue(int)));

        QFormLayout *layout = new QFormLayout;
        layout->addRow(tr("Brightness"), brightnessSlider);
        layout->addRow(tr("Contrast"), contrastSlider);
        layout->addRow(tr("Hue"), hueSlider);
        layout->addRow(tr("Saturation"), saturationSlider);

        colorDialog = new QDialog(this);
        colorDialog->setWindowTitle(tr("Color Options"));
        colorDialog->setLayout(layout);
    }
    colorDialog->show();
}
<commit_msg>Player example: removed checks if videowidget is null.<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * 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.
**   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
**     the names of its contributors may be used to endorse or promote
**     products derived from this software without specific prior written
**     permission.
**
** 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."
** $QT_END_LICENSE$
**
****************************************************************************/

#include "player.h"

#include "playercontrols.h"
#include "playlistmodel.h"
#include "videowidget.h"

#include <qmediaservice.h>
#include <qmediaplaylist.h>

#include <QtGui>

Player::Player(QWidget *parent)
    : QWidget(parent)
    , videoWidget(0)
    , coverLabel(0)
    , slider(0)
    , colorDialog(0)
{
//! [create-objs]
    player = new QMediaPlayer(this);
    // owned by PlaylistModel
    playlist = new QMediaPlaylist();
    player->setPlaylist(playlist);
//! [create-objs]

    connect(player, SIGNAL(durationChanged(qint64)), SLOT(durationChanged(qint64)));
    connect(player, SIGNAL(positionChanged(qint64)), SLOT(positionChanged(qint64)));
    connect(player, SIGNAL(metaDataChanged()), SLOT(metaDataChanged()));
    connect(playlist, SIGNAL(currentIndexChanged(int)), SLOT(playlistPositionChanged(int)));
    connect(player, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)),
            this, SLOT(statusChanged(QMediaPlayer::MediaStatus)));
    connect(player, SIGNAL(bufferStatusChanged(int)), this, SLOT(bufferingProgress(int)));
    connect(player, SIGNAL(error(QMediaPlayer::Error)), this, SLOT(displayErrorMessage()));

//! [2]
    videoWidget = new VideoWidget(this);
    player->setVideoOutput(videoWidget);

    playlistModel = new PlaylistModel(this);
    playlistModel->setPlaylist(playlist);
//! [2]

    playlistView = new QListView(this);
    playlistView->setModel(playlistModel);
    playlistView->setCurrentIndex(playlistModel->index(playlist->currentIndex(), 0));

    connect(playlistView, SIGNAL(activated(QModelIndex)), this, SLOT(jump(QModelIndex)));

    slider = new QSlider(Qt::Horizontal, this);
    slider->setRange(0, player->duration() / 1000);

    connect(slider, SIGNAL(sliderMoved(int)), this, SLOT(seek(int)));

    QPushButton *openButton = new QPushButton(tr("Open"), this);

    connect(openButton, SIGNAL(clicked()), this, SLOT(open()));

    PlayerControls *controls = new PlayerControls(this);
    controls->setState(player->state());
    controls->setVolume(player->volume());
    controls->setMuted(controls->isMuted());

    connect(controls, SIGNAL(play()), player, SLOT(play()));
    connect(controls, SIGNAL(pause()), player, SLOT(pause()));
    connect(controls, SIGNAL(stop()), player, SLOT(stop()));
    connect(controls, SIGNAL(next()), playlist, SLOT(next()));
    connect(controls, SIGNAL(previous()), this, SLOT(previousClicked()));
    connect(controls, SIGNAL(changeVolume(int)), player, SLOT(setVolume(int)));
    connect(controls, SIGNAL(changeMuting(bool)), player, SLOT(setMuted(bool)));
    connect(controls, SIGNAL(changeRate(qreal)), player, SLOT(setPlaybackRate(qreal)));

    connect(controls, SIGNAL(stop()), videoWidget, SLOT(update()));

    connect(player, SIGNAL(stateChanged(QMediaPlayer::State)),
            controls, SLOT(setState(QMediaPlayer::State)));
    connect(player, SIGNAL(volumeChanged(int)), controls, SLOT(setVolume(int)));
    connect(player, SIGNAL(mutedChanged(bool)), controls, SLOT(setMuted(bool)));

    QPushButton *fullScreenButton = new QPushButton(tr("FullScreen"), this);
    fullScreenButton->setCheckable(true);

    connect(fullScreenButton, SIGNAL(clicked(bool)), videoWidget, SLOT(setFullScreen(bool)));
    connect(videoWidget, SIGNAL(fullScreenChanged(bool)),
            fullScreenButton, SLOT(setChecked(bool)));

    QPushButton *colorButton = new QPushButton(tr("Color Options..."), this);
    connect(colorButton, SIGNAL(clicked()), this, SLOT(showColorDialog()));

    QBoxLayout *displayLayout = new QHBoxLayout;
    if (videoWidget)
        displayLayout->addWidget(videoWidget, 2);
    else
        displayLayout->addWidget(coverLabel, 2);
    displayLayout->addWidget(playlistView);

    QBoxLayout *controlLayout = new QHBoxLayout;
    controlLayout->setMargin(0);
    controlLayout->addWidget(openButton);
    controlLayout->addStretch(1);
    controlLayout->addWidget(controls);
    controlLayout->addStretch(1);
    controlLayout->addWidget(fullScreenButton);
    controlLayout->addWidget(colorButton);

    QBoxLayout *layout = new QVBoxLayout;
    layout->addLayout(displayLayout);
    layout->addWidget(slider);
    layout->addLayout(controlLayout);

    setLayout(layout);

    if (!player->isAvailable()) {
        QMessageBox::warning(this, tr("Service not available"),
                             tr("The QMediaPlayer object does not have a valid service.\n"\
                                "Please check the media service plugins are installed."));

        controls->setEnabled(false);
        playlistView->setEnabled(false);
        openButton->setEnabled(false);
        colorButton->setEnabled(false);
        fullScreenButton->setEnabled(false);
    }

    metaDataChanged();

    QStringList arguments = qApp->arguments();
    arguments.removeAt(0);
    addToPlaylist(arguments);
}

Player::~Player()
{
}

void Player::open()
{
#ifdef Q_WS_MAEMO_5
    QStringList fileNames;
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open Files"), "/");
    if (!fileName.isEmpty())
        fileNames << fileName;
#else
    QStringList fileNames = QFileDialog::getOpenFileNames(this, tr("Open Files"));
#endif
    addToPlaylist(fileNames);
}

void Player::addToPlaylist(const QStringList& fileNames)
{
    foreach (QString const &argument, fileNames) {
        QFileInfo fileInfo(argument);
        if (fileInfo.exists()) {
            QUrl url = QUrl::fromLocalFile(fileInfo.absoluteFilePath());
            if (fileInfo.suffix().toLower() == QLatin1String("m3u")) {
                playlist->load(url);
            } else
                playlist->addMedia(url);
        } else {
            QUrl url(argument);
            if (url.isValid()) {
                playlist->addMedia(url);
            }
        }
    }
}

void Player::durationChanged(qint64 duration)
{
    slider->setMaximum(duration / 1000);
}

void Player::positionChanged(qint64 progress)
{
    if (!slider->isSliderDown()) {
        slider->setValue(progress / 1000);
    }
}

void Player::metaDataChanged()
{
    //qDebug() << "update metadata" << player->metaData(QtMultimediaKit::Title).toString();
    if (player->isMetaDataAvailable()) {
        setTrackInfo(QString("%1 - %2")
                .arg(player->metaData(QtMultimediaKit::AlbumArtist).toString())
                .arg(player->metaData(QtMultimediaKit::Title).toString()));

        if (coverLabel) {
            QUrl url = player->metaData(QtMultimediaKit::CoverArtUrlLarge).value<QUrl>();

            coverLabel->setPixmap(!url.isEmpty()
                    ? QPixmap(url.toString())
                    : QPixmap());
        }
    }
}

void Player::previousClicked()
{
    // Go to previous track if we are within the first 5 seconds of playback
    // Otherwise, seek to the beginning.
    if(player->position() <= 5000)
        playlist->previous();
    else
        player->setPosition(0);
}

void Player::jump(const QModelIndex &index)
{
    if (index.isValid()) {
        playlist->setCurrentIndex(index.row());
        player->play();
    }
}

void Player::playlistPositionChanged(int currentItem)
{
    playlistView->setCurrentIndex(playlistModel->index(currentItem, 0));
}

void Player::seek(int seconds)
{
    player->setPosition(seconds * 1000);
}

void Player::statusChanged(QMediaPlayer::MediaStatus status)
{
    handleCursor(status);

    // handle status message
    switch (status) {
    case QMediaPlayer::UnknownMediaStatus:
    case QMediaPlayer::NoMedia:
    case QMediaPlayer::LoadedMedia:
    case QMediaPlayer::BufferingMedia:
    case QMediaPlayer::BufferedMedia:
        setStatusInfo(QString());
        break;
    case QMediaPlayer::LoadingMedia:
        setStatusInfo(tr("Loading..."));
        break;
    case QMediaPlayer::StalledMedia:
        setStatusInfo(tr("Media Stalled"));
        break;
    case QMediaPlayer::EndOfMedia:
        QApplication::alert(this);
        break;
    case QMediaPlayer::InvalidMedia:
        displayErrorMessage();
        break;
    }
}

void Player::handleCursor(QMediaPlayer::MediaStatus status)
{
#ifndef QT_NO_CURSOR
    if( status == QMediaPlayer::LoadingMedia ||
        status == QMediaPlayer::BufferingMedia ||
        status == QMediaPlayer::StalledMedia)
        setCursor(QCursor(Qt::BusyCursor));
    else
        unsetCursor();
#endif
}

void Player::bufferingProgress(int progress)
{
    setStatusInfo(tr("Buffering %4%").arg(progress));
}

void Player::setTrackInfo(const QString &info)
{
    trackInfo = info;
    if (!statusInfo.isEmpty())
        setWindowTitle(QString("%1 | %2").arg(trackInfo).arg(statusInfo));
    else
        setWindowTitle(trackInfo);
}

void Player::setStatusInfo(const QString &info)
{
    statusInfo = info;
    if (!statusInfo.isEmpty())
        setWindowTitle(QString("%1 | %2").arg(trackInfo).arg(statusInfo));
    else
        setWindowTitle(trackInfo);
}

void Player::displayErrorMessage()
{
    setStatusInfo(player->errorString());

}

void Player::showColorDialog()
{
    if (!colorDialog) {
        QSlider *brightnessSlider = new QSlider(Qt::Horizontal);
        brightnessSlider->setRange(-100, 100);
        brightnessSlider->setValue(videoWidget->brightness());
        connect(brightnessSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setBrightness(int)));
        connect(videoWidget, SIGNAL(brightnessChanged(int)), brightnessSlider, SLOT(setValue(int)));

        QSlider *contrastSlider = new QSlider(Qt::Horizontal);
        contrastSlider->setRange(-100, 100);
        contrastSlider->setValue(videoWidget->contrast());
        connect(contrastSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setContrast(int)));
        connect(videoWidget, SIGNAL(contrastChanged(int)), contrastSlider, SLOT(setValue(int)));

        QSlider *hueSlider = new QSlider(Qt::Horizontal);
        hueSlider->setRange(-100, 100);
        hueSlider->setValue(videoWidget->hue());
        connect(hueSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setHue(int)));
        connect(videoWidget, SIGNAL(hueChanged(int)), hueSlider, SLOT(setValue(int)));

        QSlider *saturationSlider = new QSlider(Qt::Horizontal);
        saturationSlider->setRange(-100, 100);
        saturationSlider->setValue(videoWidget->saturation());
        connect(saturationSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setSaturation(int)));
        connect(videoWidget, SIGNAL(saturationChanged(int)), saturationSlider, SLOT(setValue(int)));

        QFormLayout *layout = new QFormLayout;
        layout->addRow(tr("Brightness"), brightnessSlider);
        layout->addRow(tr("Contrast"), contrastSlider);
        layout->addRow(tr("Hue"), hueSlider);
        layout->addRow(tr("Saturation"), saturationSlider);

        colorDialog = new QDialog(this);
        colorDialog->setWindowTitle(tr("Color Options"));
        colorDialog->setLayout(layout);
    }
    colorDialog->show();
}
<|endoftext|>


<commit_before>/** @file
 * @author Edouard DUPIN
 *
 * @copyright 2016, Edouard DUPIN, all right reserved
 *
 * @license MPL v2.0 (see license file)
 */
#include <etk/etk.hpp>
#include <test-debug/debug.hpp>

//! [eproperty_sample_all]

//! [eproperty_sample_declare_interface]
#include <eproperty/Interface.hpp>
//! [eproperty_sample_declare_interface]
//! [eproperty_sample_declare_value]
#include <eproperty/Value.hpp>
//! [eproperty_sample_declare_value]
//! [eproperty_sample_declare_list]
#include <eproperty/List.hpp>
//! [eproperty_sample_declare_list]
//! [eproperty_sample_declare_range]
#include <eproperty/Range.hpp>
//! [eproperty_sample_declare_range]

//! [eproperty_sample_declare_an_enum]
enum simpleEnum {
	simpleEnum_enum1,
	simpleEnum_enum2,
	simpleEnum_enum3,
	simpleEnum_enum4,
};
//! [eproperty_sample_declare_an_enum]

//! [eproperty_sample_class_with_interface]
//! [eproperty_sample_declare_class_with_interface]
class sampleClassGroup : public eproperty::Interface {
//! [eproperty_sample_declare_class_with_interface]
	public:
		//! [eproperty_sample_declare_class_property_value]
		eproperty::Value<etk::String> propertyValue; //!< Simple property Value with type string
		//! [eproperty_sample_declare_class_property_value]
		//! [eproperty_sample_declare_class_property_list]
		eproperty::List<enum simpleEnum> propertyList; //!< Simple property List with type enumeration
		//! [eproperty_sample_declare_class_property_list]
		//! [eproperty_sample_declare_class_property_range]
		eproperty::Range<int32_t> propertyRange; //!< Simple property Range with type integer
		//! [eproperty_sample_declare_class_property_range]

		sampleClassGroup():
		//! [eproperty_sample_initialize_class_property_value]
		  propertyValue(this, "value", "default value", "optionnal Description", &sampleClassGroup::onPropertyChangeValue),
		//! [eproperty_sample_initialize_class_property_value]
		//! [eproperty_sample_initialize_class_property_list]
		  propertyList(this, "list", simpleEnum_enum4),
		//! [eproperty_sample_initialize_class_property_list]
		//! [eproperty_sample_initialize_class_property_range]
		  propertyRange(this, "range", 5646546, -5, 555555555) {
		//! [eproperty_sample_initialize_class_property_range]
			// add all enumeration values
			//! [eproperty_sample_initialize_class_property_list_add]
			propertyList.add(simpleEnum_enum1, "enum1");
			propertyList.add(simpleEnum_enum2, "enum2");
			propertyList.add(simpleEnum_enum3, "enum3");
			propertyList.add(simpleEnum_enum4, "enum4");
			//! [eproperty_sample_initialize_class_property_list_add]
			//! [eproperty_sample_initialize_class_property_list_rename]
			// Rename an element
			propertyList.rename("enum1", "new enum name");
			// Remove an element
			propertyList.remove("enum2");
			//! [eproperty_sample_initialize_class_property_list_rename]
			//! [eproperty_sample_initialize_class_property_set_direct]
			// no check on the value set (the faster in CPU cycle)
			propertyValue.setDirect("New Value to Set");
			// Check the internal value (better for range)
			propertyRange.setDirectCheck(-5555);
			//! [eproperty_sample_initialize_class_property_set_direct]
		}
		//! [eproperty_sample_initialize_class_property_value_callback]
		void onPropertyChangeValue() {
			TEST_PRINT("Property value has change ... " << *propertyValue);

			TEST_INFO("Use properties:");
			//! [eproperty_sample_get_value_value]
			TEST_INFO("    value:" << *propertyValue);
			//! [eproperty_sample_get_value_value]
			//! [eproperty_sample_get_value_range]
			TEST_INFO("    range:" << *propertyRange);
			//! [eproperty_sample_get_value_range]
			//! [eproperty_sample_get_value_list]
			TEST_INFO("    list:" << *propertyList);
			//! [eproperty_sample_get_value_list]

		}
		//! [eproperty_sample_initialize_class_property_value_callback]
};
//! [eproperty_sample_class_with_interface]

//! [eproperty_sample_class_without_interface]
class sampleClassSolo {
	public:
		eproperty::Value<etk::String> propertyValue;
		eproperty::List<enum simpleEnum> propertyList;
		eproperty::Range<int32_t> propertyRange;
		sampleClassSolo():
		//! [eproperty_sample_initialize_class_property_value2]
		  propertyValue("default value"),
		//! [eproperty_sample_initialize_class_property_value2]
		//! [eproperty_sample_initialize_class_property_list2]
		  propertyList(simpleEnum_enum4),
		//! [eproperty_sample_initialize_class_property_list2]
		//! [eproperty_sample_initialize_class_property_range2]
		  propertyRange(5646546, -5, 555555555) {
		//! [eproperty_sample_initialize_class_property_range2]
			propertyList.add(simpleEnum_enum1, "enum1");
			propertyList.add(simpleEnum_enum2, "enum2");
			propertyList.add(simpleEnum_enum3, "enum3");
			propertyList.add(simpleEnum_enum4, "enum4");
		}
};
//! [eproperty_sample_class_without_interface]

void simpleSet() {
	//! [eproperty_sample_use_declare_class]
	sampleClassGroup myClass;
	//! [eproperty_sample_use_declare_class]

	//! [eproperty_sample_use_set_value_1]
	myClass.propertyValue.set("New Value");
	myClass.propertyValue.setString("New Value 2");
	//! [eproperty_sample_use_set_value_1]
	//! [eproperty_sample_use_set_list_1]
	myClass.propertyList.set(simpleEnum_enum3);
	myClass.propertyList.setString("enum3");
	//! [eproperty_sample_use_set_list_1]
	//! [eproperty_sample_use_set_range_1]
	myClass.propertyRange.set(15621);
	myClass.propertyRange.setString("15621");
	//! [eproperty_sample_use_set_range_1]

	//! [eproperty_sample_use_set_value_2]
	myClass.properties.set("value", "New Value in string");
	//! [eproperty_sample_use_set_value_2]
	//! [eproperty_sample_use_set_list_2]
	myClass.properties.set("list", "enum4");
	//! [eproperty_sample_use_set_list_2]
	//! [eproperty_sample_use_set_range_2]
	myClass.properties.set("range", "-2");
	//! [eproperty_sample_use_set_range_2]

}
//! [eproperty_sample_all]

int main(int _argc, const char *_argv[]) {
	etk::init(_argc, _argv);
	TEST_INFO("simpleSet [START] ***************************");
	simpleSet();
	TEST_INFO("simpleSet [STOP]  ***************************");
	return 0;
}
<commit_msg>[DEBUG] build back sample<commit_after>/** @file
 * @author Edouard DUPIN
 *
 * @copyright 2016, Edouard DUPIN, all right reserved
 *
 * @license MPL v2.0 (see license file)
 */
#include <etk/etk.hpp>
#include <test-debug/debug.hpp>

//! [eproperty_sample_all]

//! [eproperty_sample_declare_interface]
#include <eproperty/Interface.hpp>
//! [eproperty_sample_declare_interface]
//! [eproperty_sample_declare_value]
#include <eproperty/Value.hpp>
//! [eproperty_sample_declare_value]
//! [eproperty_sample_declare_list]
#include <eproperty/List.hpp>
//! [eproperty_sample_declare_list]
//! [eproperty_sample_declare_range]
#include <eproperty/Range.hpp>
//! [eproperty_sample_declare_range]

//! [eproperty_sample_declare_an_enum]
enum simpleEnum {
	simpleEnum_enum1,
	simpleEnum_enum2,
	simpleEnum_enum3,
	simpleEnum_enum4,
};
// Declare type in CPP only
#include <etk/typeInfo.hpp>
ETK_DECLARE_TYPE(enum simpleEnum);
//! [eproperty_sample_declare_an_enum]

//! [eproperty_sample_class_with_interface]
//! [eproperty_sample_declare_class_with_interface]
class sampleClassGroup : public eproperty::Interface {
//! [eproperty_sample_declare_class_with_interface]
	public:
		//! [eproperty_sample_declare_class_property_value]
		eproperty::Value<etk::String> propertyValue; //!< Simple property Value with type string
		//! [eproperty_sample_declare_class_property_value]
		//! [eproperty_sample_declare_class_property_list]
		eproperty::List<enum simpleEnum> propertyList; //!< Simple property List with type enumeration
		//! [eproperty_sample_declare_class_property_list]
		//! [eproperty_sample_declare_class_property_range]
		eproperty::Range<int32_t> propertyRange; //!< Simple property Range with type integer
		//! [eproperty_sample_declare_class_property_range]

		sampleClassGroup():
		//! [eproperty_sample_initialize_class_property_value]
		  propertyValue(this, "value", "default value", "optionnal Description", &sampleClassGroup::onPropertyChangeValue),
		//! [eproperty_sample_initialize_class_property_value]
		//! [eproperty_sample_initialize_class_property_list]
		  propertyList(this, "list", simpleEnum_enum4),
		//! [eproperty_sample_initialize_class_property_list]
		//! [eproperty_sample_initialize_class_property_range]
		  propertyRange(this, "range", 5646546, -5, 555555555) {
		//! [eproperty_sample_initialize_class_property_range]
			// add all enumeration values
			//! [eproperty_sample_initialize_class_property_list_add]
			propertyList.add(simpleEnum_enum1, "enum1");
			propertyList.add(simpleEnum_enum2, "enum2");
			propertyList.add(simpleEnum_enum3, "enum3");
			propertyList.add(simpleEnum_enum4, "enum4");
			//! [eproperty_sample_initialize_class_property_list_add]
			//! [eproperty_sample_initialize_class_property_list_rename]
			// Rename an element
			propertyList.rename("enum1", "new enum name");
			// Remove an element
			propertyList.remove("enum2");
			//! [eproperty_sample_initialize_class_property_list_rename]
			//! [eproperty_sample_initialize_class_property_set_direct]
			// no check on the value set (the faster in CPU cycle)
			propertyValue.setDirect("New Value to Set");
			// Check the internal value (better for range)
			propertyRange.setDirectCheck(-5555);
			//! [eproperty_sample_initialize_class_property_set_direct]
		}
		//! [eproperty_sample_initialize_class_property_value_callback]
		void onPropertyChangeValue() {
			TEST_PRINT("Property value has change ... " << *propertyValue);

			TEST_INFO("Use properties:");
			//! [eproperty_sample_get_value_value]
			TEST_INFO("    value:" << *propertyValue);
			//! [eproperty_sample_get_value_value]
			//! [eproperty_sample_get_value_range]
			TEST_INFO("    range:" << *propertyRange);
			//! [eproperty_sample_get_value_range]
			//! [eproperty_sample_get_value_list]
			TEST_INFO("    list:" << *propertyList);
			//! [eproperty_sample_get_value_list]

		}
		//! [eproperty_sample_initialize_class_property_value_callback]
};
//! [eproperty_sample_class_with_interface]

//! [eproperty_sample_class_without_interface]
class sampleClassSolo {
	public:
		eproperty::Value<etk::String> propertyValue;
		eproperty::List<enum simpleEnum> propertyList;
		eproperty::Range<int32_t> propertyRange;
		sampleClassSolo():
		//! [eproperty_sample_initialize_class_property_value2]
		  propertyValue("default value"),
		//! [eproperty_sample_initialize_class_property_value2]
		//! [eproperty_sample_initialize_class_property_list2]
		  propertyList(simpleEnum_enum4),
		//! [eproperty_sample_initialize_class_property_list2]
		//! [eproperty_sample_initialize_class_property_range2]
		  propertyRange(5646546, -5, 555555555) {
		//! [eproperty_sample_initialize_class_property_range2]
			propertyList.add(simpleEnum_enum1, "enum1");
			propertyList.add(simpleEnum_enum2, "enum2");
			propertyList.add(simpleEnum_enum3, "enum3");
			propertyList.add(simpleEnum_enum4, "enum4");
		}
};
//! [eproperty_sample_class_without_interface]

void simpleSet() {
	//! [eproperty_sample_use_declare_class]
	sampleClassGroup myClass;
	//! [eproperty_sample_use_declare_class]

	//! [eproperty_sample_use_set_value_1]
	myClass.propertyValue.set("New Value");
	myClass.propertyValue.setString("New Value 2");
	//! [eproperty_sample_use_set_value_1]
	//! [eproperty_sample_use_set_list_1]
	myClass.propertyList.set(simpleEnum_enum3);
	myClass.propertyList.setString("enum3");
	//! [eproperty_sample_use_set_list_1]
	//! [eproperty_sample_use_set_range_1]
	myClass.propertyRange.set(15621);
	myClass.propertyRange.setString("15621");
	//! [eproperty_sample_use_set_range_1]

	//! [eproperty_sample_use_set_value_2]
	myClass.properties.set("value", "New Value in string");
	//! [eproperty_sample_use_set_value_2]
	//! [eproperty_sample_use_set_list_2]
	myClass.properties.set("list", "enum4");
	//! [eproperty_sample_use_set_list_2]
	//! [eproperty_sample_use_set_range_2]
	myClass.properties.set("range", "-2");
	//! [eproperty_sample_use_set_range_2]

}
//! [eproperty_sample_all]

int main(int _argc, const char *_argv[]) {
	etk::init(_argc, _argv);
	TEST_INFO("simpleSet [START] ***************************");
	simpleSet();
	TEST_INFO("simpleSet [STOP]  ***************************");
	return 0;
}
<|endoftext|>


<commit_before>/*
    Copyright 2005-2007 Adobe Systems Incorporated
    Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt
    or a copy at http://stlab.adobe.com/licenses.html)
*/

#include "platform_display_text.hpp"

#include <GG/adobe/dictionary.hpp>
#include <GG/adobe/string.hpp>
#include <GG/adobe/future/widgets/headers/display.hpp>
#include <GG/adobe/future/widgets/headers/widget_utils.hpp>
#include <GG/adobe/future/widgets/headers/platform_metrics.hpp>

#include <GG/TextControl.h>
#include <GG/GUI.h>
#include <GG/StyleFactory.h>

#include <string>
#include <cassert>
#include <sstream>

namespace {

    std::string field_text(const std::string& label, const adobe::any_regular_t& value, GG::Clr label_color)
    {
        std::stringstream result;
        if (!label.empty())
            result << GG::RgbaTag(label_color) << label << "</rgba> ";
        if (value != adobe::any_regular_t()) {
            adobe::type_info_t type(value.type_info());
            if (type == adobe::type_info<double>() ||
                type == adobe::type_info<bool>() ||
                type == adobe::type_info<adobe::name_t>()) {
                result << value;
            } else if (type == adobe::type_info<adobe::array_t>()) {
                result << '[';
                const adobe::array_t& array = value.cast<adobe::array_t>();
                for (adobe::array_t::const_iterator it = array.begin(), end_it = array.end();
                     it != end_it;
                     ++it) {
                    result << field_text("", *it, label_color);
                    if (boost::next(it) != end_it)
                        result << ',';
                }
                result <<  " ]";
            } else if (type == adobe::type_info<adobe::dictionary_t>()) {
                const adobe::dictionary_t& dictionary = value.cast<adobe::dictionary_t>();
                for (adobe::dictionary_t::const_iterator it = dictionary.begin(), end_it = dictionary.end();
                     it != end_it;
                     ++it) {
                    result << it->first << ": " << field_text("", it->second, label_color);
                    if (boost::next(it) != end_it)
                        result << ',';
                }
                result <<  " ]";
            } else {
                result << value.cast<adobe::string_t>();
            }
        }
        return result.str();
    }

}

namespace adobe {

    display_text_t::display_text_t(const std::string& name,
                                   const std::string& alt_text,
                                   int characters,
                                   GG::Clr color,
                                   GG::Clr label_color) :
        name_m(name),
        alt_text_m(alt_text),
        characters_m(characters),
        color_m(color),
        label_color_m(label_color)
    {}

    void display_text_t::place(const place_data_t& place_data)
    { implementation::set_control_bounds(window_m, place_data); }

    void display_text_t::display(const model_type& value)
    {
        assert(window_m);
        value_m = value;
        window_m->SetText(field_text(name_m, value_m, label_color_m));
    }

    void display_text_t::measure(extents_t& result)
    {
        assert(window_m);

        boost::shared_ptr<GG::Font> font = implementation::DefaultFont();

        extents_t space_extents(metrics::measure_text(std::string(" "), font));
        extents_t label_extents(metrics::measure_text(name_m, font));
        extents_t characters_extents(metrics::measure_text(std::string(characters_m, '0'), font));

        // set up default settings (baseline, etc.)
        result = space_extents;

        // set the width to the label width (if any)
        result.width() = label_extents.width();

        // add a guide for the label
        result.horizontal().guide_set_m.push_back(label_extents.width());

        // if there's a label, add space for a space
        if (label_extents.width() != 0)
            result.width() += space_extents.width();

        // append the character extents (if any)
        result.width() += characters_extents.width();

        // if there are character extents, add space for a space
        if (characters_extents.width() != 0)
            result.width() += space_extents.width();

        assert(result.horizontal().length_m);
    }

    void display_text_t::measure_vertical(extents_t& calculated_horizontal, const place_data_t& placed_horizontal)
    {
        assert(window_m);

        extents_t::slice_t& vert = calculated_horizontal.vertical();
        vert.length_m = Value(implementation::DefaultFont()->Lineskip());
        vert.guide_set_m.push_back(Value(implementation::DefaultFont()->Ascent()));
    }

    void display_text_t::set_label_color(GG::Clr color)
    {
        label_color_m = color;
        display(value_m);
    }

    template <>
    platform_display_type insert<display_text_t>(display_t& display,
                                                 platform_display_type& parent,
                                                 display_text_t& element)
    {
        element.window_m =
            implementation::Factory().NewTextControl(GG::X0, GG::Y0, GG::X1, GG::Y1,
                                                     element.name_m, implementation::DefaultFont(),
                                                     element.color_m, GG::FORMAT_LEFT | GG::FORMAT_TOP,
                                                     GG::INTERACTIVE);

        if (!element.alt_text_m.empty())
            implementation::set_control_alt_text(element.window_m, element.alt_text_m);

        element.color_proxy_m.initialize(
            boost::bind(&GG::TextControl::SetColor, element.window_m, _1)
        );
        element.label_color_proxy_m.initialize(
            boost::bind(&display_text_t::set_label_color, &element, _1)
        );

        return display.insert(parent, get_display(element));
    }

}
<commit_msg>Fixed broken display of dictionaries in platform_display_text.<commit_after>/*
    Copyright 2005-2007 Adobe Systems Incorporated
    Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt
    or a copy at http://stlab.adobe.com/licenses.html)
*/

#include "platform_display_text.hpp"

#include <GG/adobe/dictionary.hpp>
#include <GG/adobe/string.hpp>
#include <GG/adobe/future/widgets/headers/display.hpp>
#include <GG/adobe/future/widgets/headers/widget_utils.hpp>
#include <GG/adobe/future/widgets/headers/platform_metrics.hpp>

#include <GG/TextControl.h>
#include <GG/GUI.h>
#include <GG/StyleFactory.h>

#include <string>
#include <cassert>
#include <sstream>

namespace {

    std::string field_text(const std::string& label, const adobe::any_regular_t& value, GG::Clr label_color)
    {
        std::stringstream result;
        if (!label.empty())
            result << GG::RgbaTag(label_color) << label << "</rgba> ";
        if (value != adobe::any_regular_t()) {
            adobe::type_info_t type(value.type_info());
            if (type == adobe::type_info<double>() ||
                type == adobe::type_info<bool>() ||
                type == adobe::type_info<adobe::name_t>()) {
                result << value;
            } else if (type == adobe::type_info<adobe::array_t>()) {
                result << '[';
                const adobe::array_t& array = value.cast<adobe::array_t>();
                for (adobe::array_t::const_iterator it = array.begin(), end_it = array.end();
                     it != end_it;
                     ++it) {
                    result << field_text("", *it, label_color);
                    if (boost::next(it) != end_it)
                        result << ',';
                }
                result <<  " ]";
            } else if (type == adobe::type_info<adobe::dictionary_t>()) {
                result << '{';
                const adobe::dictionary_t& dictionary = value.cast<adobe::dictionary_t>();
                for (adobe::dictionary_t::const_iterator it = dictionary.begin(), end_it = dictionary.end();
                     it != end_it;
                     ++it) {
                    result << it->first << ": " << field_text("", it->second, label_color);
                    if (boost::next(it) != end_it)
                        result << ',';
                }
                result <<  " }";
            } else {
                result << value.cast<adobe::string_t>();
            }
        }
        return result.str();
    }

}

namespace adobe {

    display_text_t::display_text_t(const std::string& name,
                                   const std::string& alt_text,
                                   int characters,
                                   GG::Clr color,
                                   GG::Clr label_color) :
        name_m(name),
        alt_text_m(alt_text),
        characters_m(characters),
        color_m(color),
        label_color_m(label_color)
    {}

    void display_text_t::place(const place_data_t& place_data)
    { implementation::set_control_bounds(window_m, place_data); }

    void display_text_t::display(const model_type& value)
    {
        assert(window_m);
        value_m = value;
        window_m->SetText(field_text(name_m, value_m, label_color_m));
    }

    void display_text_t::measure(extents_t& result)
    {
        assert(window_m);

        boost::shared_ptr<GG::Font> font = implementation::DefaultFont();

        extents_t space_extents(metrics::measure_text(std::string(" "), font));
        extents_t label_extents(metrics::measure_text(name_m, font));
        extents_t characters_extents(metrics::measure_text(std::string(characters_m, '0'), font));

        // set up default settings (baseline, etc.)
        result = space_extents;

        // set the width to the label width (if any)
        result.width() = label_extents.width();

        // add a guide for the label
        result.horizontal().guide_set_m.push_back(label_extents.width());

        // if there's a label, add space for a space
        if (label_extents.width() != 0)
            result.width() += space_extents.width();

        // append the character extents (if any)
        result.width() += characters_extents.width();

        // if there are character extents, add space for a space
        if (characters_extents.width() != 0)
            result.width() += space_extents.width();

        assert(result.horizontal().length_m);
    }

    void display_text_t::measure_vertical(extents_t& calculated_horizontal, const place_data_t& placed_horizontal)
    {
        assert(window_m);

        extents_t::slice_t& vert = calculated_horizontal.vertical();
        vert.length_m = Value(implementation::DefaultFont()->Lineskip());
        vert.guide_set_m.push_back(Value(implementation::DefaultFont()->Ascent()));
    }

    void display_text_t::set_label_color(GG::Clr color)
    {
        label_color_m = color;
        display(value_m);
    }

    template <>
    platform_display_type insert<display_text_t>(display_t& display,
                                                 platform_display_type& parent,
                                                 display_text_t& element)
    {
        element.window_m =
            implementation::Factory().NewTextControl(GG::X0, GG::Y0, GG::X1, GG::Y1,
                                                     element.name_m, implementation::DefaultFont(),
                                                     element.color_m, GG::FORMAT_LEFT | GG::FORMAT_TOP,
                                                     GG::INTERACTIVE);

        if (!element.alt_text_m.empty())
            implementation::set_control_alt_text(element.window_m, element.alt_text_m);

        element.color_proxy_m.initialize(
            boost::bind(&GG::TextControl::SetColor, element.window_m, _1)
        );
        element.label_color_proxy_m.initialize(
            boost::bind(&display_text_t::set_label_color, &element, _1)
        );

        return display.insert(parent, get_display(element));
    }

}
<|endoftext|>


<commit_before>/*
 * Qumulus UML editor
 * Author: Frank Erens
 *
 */

#include "Enumeration.h"

QUML_BEGIN_NAMESPACE_UK

Enumeration::Enumeration() {}

Enumeration::Enumeration(QString name, Namespace* p = 0) :
        DataType(name, p) {

}

void Enumeration::addLiteral(EnumerationLiteral* l) {
    mOwnedLiterals.append(l);
    addOwnedMember(l);
}

void Enumeration::removeLiteral(EnumerationLiteral* l) {
    mOwnedLiterals.remove(l);
    removeOwnedMember(l);
}

QUML_END_NAMESPACE_UK
<commit_msg>Fix compile bug in Enumeration.<commit_after>/*
 * Qumulus UML editor
 * Author: Frank Erens
 *
 */

#include "Enumeration.h"

QUML_BEGIN_NAMESPACE_UK

Enumeration::Enumeration() {}

Enumeration::Enumeration(QString name, Namespace* p) :
        DataType(name, p) {

}

void Enumeration::addLiteral(EnumerationLiteral* l) {
    mOwnedLiterals.append(l);
    addOwnedMember(l);
}

void Enumeration::removeLiteral(EnumerationLiteral* l) {
    mOwnedLiterals.removeAll(l);
    removeOwnedMember(l);
}

QUML_END_NAMESPACE_UK
<|endoftext|>


<commit_before>#include <QNetworkRequest>
#include <QNetworkReply>
#include <QDir>
#include <QFile>
#include "program-updater.h"
#include "functions.h"
#include "json.h"

ProgramUpdater::ProgramUpdater()
	: ProgramUpdater("https://api.github.com/repos/Bionus/imgbrd-grabber")
{ }

ProgramUpdater::ProgramUpdater(QString baseUrl)
	: m_baseUrl(baseUrl)
{ }

void ProgramUpdater::checkForUpdates()
{
	QUrl url(m_baseUrl + "/releases");
	QNetworkRequest request(url);

	m_checkForUpdatesReply = m_networkAccessManager.get(request);
	connect(m_checkForUpdatesReply, &QNetworkReply::finished, this, &ProgramUpdater::checkForUpdatesDone);
}

void ProgramUpdater::checkForUpdatesDone()
{
	m_source = m_checkForUpdatesReply->readAll();

	QVariant json = Json::parse(m_source);
	QMap<QString, QVariant> lastRelease = json.toList().first().toMap();

	QString latest = lastRelease["name"].toString().mid(1);
	QString changelog = lastRelease["body"].toString();

	m_newVersion = latest;
	bool isNew = compareVersions(latest, QString(VERSION)) > 0;

	emit finished(latest, isNew, changelog);
}

void ProgramUpdater::downloadUpdate()
{
	QVariant json = Json::parse(m_source);
	QMap<QString, QVariant> lastRelease = json.toList().first().toMap();
	QMap<QString, QVariant> lastAsset = lastRelease["assets"].toList().first().toMap();

	QUrl url(lastAsset["browser_download_url"].toString());
	m_updateFilename = url.fileName();
	QNetworkRequest request(url);
	log(QString("Downloading installer from \"%1\".").arg(url.toString()));

	m_downloadReply = m_networkAccessManager.get(request);
	connect(m_downloadReply, &QNetworkReply::downloadProgress, this, &ProgramUpdater::downloadProgress);
	connect(m_downloadReply, &QNetworkReply::finished, this, &ProgramUpdater::downloadDone);
}

void ProgramUpdater::downloadDone()
{
	QUrl redir = m_downloadReply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
	if (!redir.isEmpty())
	{
		log(QString("Installer download redirected to \"%1\".").arg(redir.toString()));
		QNetworkRequest request(redir);
		m_downloadReply = m_networkAccessManager.get(request);
		connect(m_downloadReply, &QNetworkReply::downloadProgress, this, &ProgramUpdater::downloadProgress);
		connect(m_downloadReply, &QNetworkReply::finished, this, &ProgramUpdater::downloadDone);
		return;
	}

	QFile file(QDir::tempPath() + QDir::separator() + m_updateFilename);
	if (!file.open(QFile::WriteOnly | QFile::Truncate))
	{
		log(QString("Error opening installer file \"%1\".").arg(file.fileName()));
		return;
	}

	file.write(m_downloadReply->readAll());
	file.close();
	log(QString("Installer file written to \"%1\"").arg(file.fileName()));

	emit downloadFinished(file.fileName());
}
<commit_msg>Fix program updater to not download preversions<commit_after>#include <QNetworkRequest>
#include <QNetworkReply>
#include <QDir>
#include <QFile>
#include "program-updater.h"
#include "functions.h"
#include "json.h"

ProgramUpdater::ProgramUpdater()
	: ProgramUpdater("https://api.github.com/repos/Bionus/imgbrd-grabber")
{ }

ProgramUpdater::ProgramUpdater(QString baseUrl)
	: m_baseUrl(baseUrl)
{ }

void ProgramUpdater::checkForUpdates()
{
	QUrl url(m_baseUrl + "/releases/latest");
	QNetworkRequest request(url);

	m_checkForUpdatesReply = m_networkAccessManager.get(request);
	connect(m_checkForUpdatesReply, &QNetworkReply::finished, this, &ProgramUpdater::checkForUpdatesDone);
}

void ProgramUpdater::checkForUpdatesDone()
{
	m_source = m_checkForUpdatesReply->readAll();

	QVariant json = Json::parse(m_source);
	QMap<QString, QVariant> lastRelease = json.toMap();

	QString latest = lastRelease["name"].toString().mid(1);
	QString changelog = lastRelease["body"].toString();

	m_newVersion = latest;
	bool isNew = compareVersions(latest, QString(VERSION)) > 0;

	emit finished(latest, isNew, changelog);
}

void ProgramUpdater::downloadUpdate()
{
	QVariant json = Json::parse(m_source);
	QMap<QString, QVariant> lastRelease = json.toMap();
	QMap<QString, QVariant> lastAsset = lastRelease["assets"].toList().first().toMap();

	QUrl url(lastAsset["browser_download_url"].toString());
	m_updateFilename = url.fileName();
	QNetworkRequest request(url);
	log(QString("Downloading installer from \"%1\".").arg(url.toString()));

	m_downloadReply = m_networkAccessManager.get(request);
	connect(m_downloadReply, &QNetworkReply::downloadProgress, this, &ProgramUpdater::downloadProgress);
	connect(m_downloadReply, &QNetworkReply::finished, this, &ProgramUpdater::downloadDone);
}

void ProgramUpdater::downloadDone()
{
	QUrl redir = m_downloadReply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
	if (!redir.isEmpty())
	{
		log(QString("Installer download redirected to \"%1\".").arg(redir.toString()));
		QNetworkRequest request(redir);
		m_downloadReply = m_networkAccessManager.get(request);
		connect(m_downloadReply, &QNetworkReply::downloadProgress, this, &ProgramUpdater::downloadProgress);
		connect(m_downloadReply, &QNetworkReply::finished, this, &ProgramUpdater::downloadDone);
		return;
	}

	QFile file(QDir::tempPath() + QDir::separator() + m_updateFilename);
	if (!file.open(QFile::WriteOnly | QFile::Truncate))
	{
		log(QString("Error opening installer file \"%1\".").arg(file.fileName()));
		return;
	}

	file.write(m_downloadReply->readAll());
	file.close();
	log(QString("Installer file written to \"%1\"").arg(file.fileName()));

	emit downloadFinished(file.fileName());
}
<|endoftext|>


<commit_before>#include "view/RemoteSkidmarkView.h"

#include <OgreRoot.h>
#include <OgreBillboardSet.h>
#include <OgreBillboard.h>

#include <sstream>
#include <string>

namespace Rally { namespace View {

	RemoteSkidmarkView::RemoteSkidmarkView() {}

	RemoteSkidmarkView::~RemoteSkidmarkView() {}

	void RemoteSkidmarkView::attachTo(Ogre::SceneManager* sceneManager){
		skidmarkNode = sceneManager->getRootSceneNode()->createChildSceneNode();

		Ogre::BillboardType type = Ogre::BillboardType::BBT_PERPENDICULAR_SELF;
		Ogre::BillboardRotationType rotationType = Ogre::BillboardRotationType::BBR_VERTEX;
		Rally::Vector3 up(0, 0, 1);
		Rally::Vector3 common(0, 1, 0);

		skidmarkBillboards = sceneManager->createBillboardSet();
		skidmarkBillboards->setMaterialName("skidmark");
		skidmarkBillboards->setVisible(true);
		skidmarkBillboards->setBillboardType(type);
		skidmarkBillboards->setBillboardRotationType(rotationType);
		skidmarkBillboards->setCommonUpVector(up);
		skidmarkBillboards->setCommonDirection(common);
		skidmarkBillboards->setBillboardsInWorldSpace(true);
		skidmarkBillboards->setDefaultDimensions(Ogre::Real(0.2), Ogre::Real(0.4));
		skidmarkBillboards->setAutoextend(true);

		skidmarkNode->attachObject(skidmarkBillboards);
	}

	void RemoteSkidmarkView::update(const Rally::Model::RemoteCar& car){
        float tractionReq = 0.1f;

        float speed = car.getVelocity().length();

        float heightOffset = -1.0f;

        Rally::Vector3 direction = car.getVelocity().normalisedCopy();

        if(car.getTractionVector().x < tractionReq){
            createSkidmark(car.getPosition() + Ogre::Vector3(0.7f, heightOffset, 1.50f),
                Rally::Vector3(0, 1, 0), direction, car.getTractionVector().x, speed);
        }
        if(car.getTractionVector().y < tractionReq){
			createSkidmark(car.getPosition() + Ogre::Vector3(-0.7f, heightOffset, 1.50f),
                Rally::Vector3(0, 1, 0), direction, car.getTractionVector().y, speed);
        }
        if(car.getTractionVector().z < tractionReq){
			createSkidmark(car.getPosition() + Ogre::Vector3(0.7f, heightOffset, -1.25f),
                Rally::Vector3(0, 1, 0), direction, car.getTractionVector().z, speed);
        }
        if(car.getTractionVector().w < tractionReq){
			createSkidmark(car.getPosition() + Ogre::Vector3(-0.7f, heightOffset, -1.25f),
                Rally::Vector3(0, 1, 0), direction, car.getTractionVector().w, speed);
        }

	}

	void RemoteSkidmarkView::createSkidmark(Rally::Vector3 position, Rally::Vector3 normal, Rally::Vector3 direction, float traction, float speed){
		Ogre::Billboard* b = skidmarkBillboards->createBillboard(Rally::Vector3(position.x, position.y+0.05f, position.z),
			Ogre::ColourValue::Black);

        double lengthAdjust = 0.008;
        float alphaAdjust = 4.0f;

        b->setDimensions(Ogre::Real(0.2), Ogre::Real(Ogre::Math::Clamp(lengthAdjust*speed, 0.15, 1.0)));
        b->setColour(Ogre::ColourValue(1.0, 1.0, 1.0, traction*alphaAdjust));

		b->mDirection = normal;

		direction.y = 0;

		Ogre::Radian r = direction.angleBetween(Rally::Vector3(0, 0, 1));

		if(direction.z > 0 && direction.x > 0){
			r =  Ogre::Radian(Ogre::Math::PI*2) - r;
		}

		if(direction.z < 0 && direction.x > 0){
			r *= -1;
		}

		b->setRotation(r);

		if(skidmarkBillboards->getNumBillboards() > 1000)
			skidmarkBillboards->removeBillboard(skidmarkBillboards->getBillboard(skidmarkBillboards->getNumBillboards()-1000));
	}

} }
<commit_msg>Skidmark positions are now more accurate<commit_after>#include "view/RemoteSkidmarkView.h"

#include <OgreRoot.h>
#include <OgreBillboardSet.h>
#include <OgreBillboard.h>

#include <sstream>
#include <string>

namespace Rally { namespace View {

	RemoteSkidmarkView::RemoteSkidmarkView() {}

	RemoteSkidmarkView::~RemoteSkidmarkView() {}

	void RemoteSkidmarkView::attachTo(Ogre::SceneManager* sceneManager){
		skidmarkNode = sceneManager->getRootSceneNode()->createChildSceneNode();

		Ogre::BillboardType type = Ogre::BillboardType::BBT_PERPENDICULAR_SELF;
		Ogre::BillboardRotationType rotationType = Ogre::BillboardRotationType::BBR_VERTEX;
		Rally::Vector3 up(0, 0, 1);
		Rally::Vector3 common(0, 1, 0);

		skidmarkBillboards = sceneManager->createBillboardSet();
		skidmarkBillboards->setMaterialName("skidmark");
		skidmarkBillboards->setVisible(true);
		skidmarkBillboards->setBillboardType(type);
		skidmarkBillboards->setBillboardRotationType(rotationType);
		skidmarkBillboards->setCommonUpVector(up);
		skidmarkBillboards->setCommonDirection(common);
		skidmarkBillboards->setBillboardsInWorldSpace(true);
		skidmarkBillboards->setDefaultDimensions(Ogre::Real(0.15), Ogre::Real(0.4));
		skidmarkBillboards->setAutoextend(true);

		skidmarkNode->attachObject(skidmarkBillboards);
	}

	void RemoteSkidmarkView::update(const Rally::Model::RemoteCar& car){
        float tractionReq = 0.1f;

        float speed = car.getVelocity().length();

        float heightOffset = -1.0f;
        float xOffset = 0.60f;
        float zOffsetFront = 1.50f;
        float zOffsetBack = -1.25f;

        Rally::Vector3 direction = car.getVelocity().normalisedCopy();

        Rally::Vector3 normal(0, 1, 0);

        // Right front
        if(car.getTractionVector().x < tractionReq){
            createSkidmark(car.getPosition() + Ogre::Vector3(xOffset, heightOffset, zOffsetFront),
                normal, direction, car.getTractionVector().x, speed);
        }
        // Left front
        if(car.getTractionVector().y < tractionReq){
			createSkidmark(car.getPosition() + Ogre::Vector3(-xOffset, heightOffset, zOffsetFront),
                normal, direction, car.getTractionVector().y, speed);
        }
        // Right back
        if(car.getTractionVector().z < tractionReq){
			createSkidmark(car.getPosition() + Ogre::Vector3(xOffset, heightOffset, zOffsetBack),
                normal, direction, car.getTractionVector().z, speed);
        }
        // Left back
        if(car.getTractionVector().w < tractionReq){
			createSkidmark(car.getPosition() + Ogre::Vector3(-xOffset, heightOffset, zOffsetBack),
                normal, direction, car.getTractionVector().w, speed);
        }

	}

	void RemoteSkidmarkView::createSkidmark(Rally::Vector3 position, Rally::Vector3 normal, Rally::Vector3 direction, float traction, float speed){
		Ogre::Billboard* b = skidmarkBillboards->createBillboard(Rally::Vector3(position.x, position.y+0.05f, position.z),
			Ogre::ColourValue::Black);

        double lengthAdjust = 0.012;
        float alphaAdjust = 4.0f;

        b->setDimensions(Ogre::Real(0.2), Ogre::Real(Ogre::Math::Clamp(lengthAdjust*speed, 0.15, 1.0)));
        b->setColour(Ogre::ColourValue(1.0, 1.0, 1.0, traction*alphaAdjust));

		b->mDirection = normal;

		direction.y = 0;

		Ogre::Radian r = direction.angleBetween(Rally::Vector3(0, 0, 1));

		if(direction.z > 0 && direction.x > 0){
			r =  Ogre::Radian(Ogre::Math::PI*2) - r;
		}

		if(direction.z < 0 && direction.x > 0){
			r *= -1;
		}

		b->setRotation(r);

		if(skidmarkBillboards->getNumBillboards() > 1000)
			skidmarkBillboards->removeBillboard(skidmarkBillboards->getBillboard(skidmarkBillboards->getNumBillboards()-1000));
	}

} }
<|endoftext|>


<commit_before>/*
 * Copyright 1999-2004 The Apache Software Foundation.
 *
 * 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.
 */

#if !defined(XALANMAP_HEADER_GUARD_1357924680)
#define XALANMAP_HEADER_GUARD_1357924680

// Base include file.  Must be first.
#include <xalanc/Include/PlatformDefinitions.hpp>

#include <cstddef>
#include <list>
#include <algorithm>
#include <functional>
#include <utility>

#include <xercesc/framework/MemoryManager.hpp>

#include <xalanc/Include/XalanVector.hpp>

XALAN_CPP_NAMESPACE_BEGIN

typedef size_t	size_type;

template <class Key>
class XalanHash : public XALAN_STD_QUALIFIER unary_function<Key, size_type>
{
public:
	size_type operator()(const Key& key) const
	{
		const char *byteArray = reinterpret_cast<const char*>(&key);

		size_type result = 0;

		for (size_type i = 0; i < sizeof(Key); ++i)
		{
			result = (result << 1) ^ byteArray[i];
		}

		return result;
	}
};

template <class Key>
struct XalanHashMemberPointer
{

	size_type operator() (const Key * key) const
	{
		assert (key != 0);
		return key->hash();
	}
};

template <class Key>
struct XalanHashMemberReference
{

	size_type operator() (const Key& key) const
	{
		return key.hash();
	}
};

template <
		class Key,
		class Value,
		class Hash = XalanHash<Key>,
		class Comparator = XALAN_STD_QUALIFIER equal_to<Key> >
class XalanMap
{
public:

	typedef XERCES_CPP_NAMESPACE_QUALIFIER MemoryManager    MemoryManagerType;

	typedef Key					key_type;
	typedef Value				data_type;
	typedef size_t				size_type;

	typedef XALAN_STD_QUALIFIER pair<const key_type, data_type>	value_type;

	typedef XalanMap<Key, Value, Hash, Comparator>		ThisType;

	typedef size_t	size_type;

	struct Entry : public value_type
	{
		typedef value_type Parent;
		size_type	bucketIndex;

		Entry(const key_type & key, const data_type& data, size_type index) :
			value_type(key, data), bucketIndex(index)
		{
		}

		Entry() :
			value_type(key_type(),
            data_type()),
            bucketIndex(size_type())
		{
		}
	};

	typedef XALAN_STD_QUALIFIER list<Entry>					EntryListType;
	typedef typename EntryListType::iterator				EntryListIterator;
	typedef typename EntryListType::const_iterator			EntryListConstIterator;

	typedef XalanVector<typename EntryListType::iterator>	EntryPosVectorType;

	template<class ValueType, class Ref, class Ptr, class Iterator, class Map>
	struct iterator_base
	{
		typedef ValueType	value_type;
		typedef Ref		reference_type;
		typedef Ptr		pointer_type;

		typedef ThisType MapType;

		typedef iterator_base<value_type, reference_type, pointer_type, Iterator, Map> IteratorType;

		typedef iterator_base<value_type, value_type&, value_type*, EntryListIterator, MapType> iterator;

		iterator_base(
				Map&								map,
				Iterator							bucketPos) :
			m_map(&map),
			m_bucketPos(bucketPos)
		{
		}

		iterator_base(const iterator& theRhs) :
			m_map(theRhs.m_map),
			m_bucketPos(theRhs.m_bucketPos)
		{
		}

		const IteratorType & operator=(const IteratorType& theRhs)
		{
			m_map = theRhs.m_map;
			m_bucketPos = theRhs.m_bucketPos;
			return *this;
		}

		reference_type operator*() const
		{
			return *m_bucketPos;
		}

		int operator!=(const IteratorType& theRhs) const
		{
			return !operator==(theRhs);
		}

		int operator==(const IteratorType& theRhs) const
		{
			return (theRhs.m_map == m_map)
				&& (theRhs.m_bucketPos == m_bucketPos);
		}

		IteratorType& operator++()
		{
			m_bucketPos++;
			return *this;
		}

		Map*		m_map;
		Iterator	m_bucketPos;
	};

	typedef iterator_base<
		value_type,
		value_type&,
		value_type*,
		EntryListIterator,
		ThisType> iterator;

	typedef iterator_base<
		value_type,
		const value_type&,
		const value_type*,
		EntryListConstIterator,
		const ThisType> const_iterator;

	XalanMap(
			float loadFactor = 0.75,
			MemoryManagerType* theMemoryManager = 0) :
		m_memoryManager(theMemoryManager),
		m_loadFactor(loadFactor),
		m_size(0),
		m_entries(/* m_memoryManager */),
		m_buckets(10, m_entries.end(), m_memoryManager),
		m_freeList()
	{
	}

	XalanMap(const XalanMap &theRhs) :
		m_memoryManager(theRhs.m_memoryManager),
		m_loadFactor(theRhs.m_loadFactor),
		m_size(0),
		m_entries(/* m_memoryManager */),
		m_buckets(size_type(m_loadFactor * theRhs.size())+ 1, m_entries.end(), m_memoryManager),
		m_freeList()
	{
		const_iterator entry = theRhs.begin();
		while(entry != theRhs.end())
		{
			insert(*entry);
			++entry;
		}

		assert(m_size == theRhs.m_size);
	}

	~XalanMap()
	{
	}

	XalanMap & operator=(const XalanMap& theRhs)
	{
		XalanMap theTemp(theRhs);
		swap(theTemp);
		return *this;
	}

	size_type size() const
	{
		return m_size;
	}

	bool empty() const {
		return m_size == 0;
	}

	iterator begin()
	{
		return iterator(*this, m_entries.begin());
	}

	const_iterator begin() const
	{
		return const_iterator(*this, m_entries.begin());
	}

	iterator end()
	{
		return iterator(*this, m_entries.end());
	}

	const_iterator end() const
	{
		return const_iterator(*this, m_entries.end());
	}

	iterator find(const key_type& key)
	{
		size_type index = doHash(key);

		EntryListIterator bucketPos = m_buckets[index];

		while (bucketPos != m_entries.end() &&
			   bucketPos->bucketIndex == index)
		{
			if (m_equals(key,bucketPos->first))
			{
				return iterator(*this,bucketPos);
			}
			++bucketPos;
		}

		return end();
	}

	const_iterator find(const key_type& key) const
	{
		size_type index = doHash(key);

		EntryListConstIterator bucketPos = m_buckets[index];

		while (bucketPos != m_entries.end() &&
			   bucketPos->bucketIndex == index)
		{
			if (m_equals(key,bucketPos->first))
			{
				return const_iterator(*this,bucketPos);
			}
			++bucketPos;
		}

		return end();
	}

	data_type & operator[](const key_type& key)
	{
		iterator pos = find(key);

		if (pos == end())
		{
			pos = doCreateEntry(key, data_type());
		}

		return (*pos).second;
	}

	void insert(const value_type& value)
	{
		const key_type& key = value.first;
		const data_type& data = value.second;

		iterator pos = find(key);

		if (pos == end())
		{
			doCreateEntry(key, data);
		}

	}

	void erase(iterator pos)
	{
		if (pos != end())
		{
			doRemoveEntry(pos.m_bucketPos);
		}
	}

	void erase(const key_type& key)
	{
		iterator pos = find(key);

		erase(pos);
	}

	void clear()
	{
		m_size = 0;

		XALAN_STD_QUALIFIER fill(
            m_buckets.begin(),
            m_buckets.end(),
            m_entries.end());

		m_freeList.splice(
            m_freeList.begin(),
            m_entries,
            m_entries.begin(),
            m_entries.end());
	}

	void swap(ThisType& theRhs)
	{
		size_type tempSize = m_size;
		m_size = theRhs.m_size;
		theRhs.m_size = tempSize;

		MemoryManagerType* tempMemoryManager = m_memoryManager;
		m_memoryManager = theRhs.m_memoryManager;
		theRhs.m_memoryManager = tempMemoryManager;

		m_entries.swap(theRhs.m_entries);
		m_buckets.swap(theRhs.m_buckets);
		m_freeList.swap(theRhs.m_freeList);

	}

	protected:

	iterator doCreateEntry(const key_type & key, const data_type&  data)
	{
		if (size_type(m_loadFactor * size()) > m_buckets.size())
		{
			rehash();
		}

		size_type index = doHash(key);

		EntryListIterator & bucketStartPos = m_buckets[index];

		if (m_freeList.empty() == true)
		{
			Entry newEntry = Entry(key, data, index);

			if (bucketStartPos == m_entries.end())
			{
				bucketStartPos = m_entries.insert(m_entries.end(), newEntry);
			}
			else
			{
				bucketStartPos = m_entries.insert(bucketStartPos, newEntry);
			}
		}
		else
		{
			(*m_freeList.begin()).~Entry();
			new (&*m_freeList.begin()) Entry(key, data, index);

			m_entries.splice(bucketStartPos, m_freeList, m_freeList.begin());
			--bucketStartPos;
		}

		++m_size;
		return iterator(*this, bucketStartPos);
	}

	void doRemoveEntry(const EntryListIterator & toRemoveIter)
	{
		size_type index = toRemoveIter->bucketIndex;
		EntryListIterator nextPosition = ++(EntryListIterator(toRemoveIter));

		if (m_buckets[index] == toRemoveIter)
		{
			if (nextPosition->bucketIndex == index)
			{
				m_buckets[index] = nextPosition;
			}
			else
			{
				m_buckets[index] = m_entries.end();
			}
		}

		m_freeList.splice(m_freeList.begin(), m_entries, toRemoveIter, nextPosition);
		--m_size;
	}

	size_type doHash(const Key & key) const
	{
		return m_hash(key) % m_buckets.size();
	}

	void rehash()
	{
		EntryPosVectorType temp(size_type(1.6 * size()), m_entries.end(), m_memoryManager);
		m_buckets.swap(temp);
		doRehashEntries();
	}

	void doRehashEntries()
	{
		EntryListType tempEntryList;
		tempEntryList.splice(tempEntryList.begin(),m_entries, m_entries.begin(), m_entries.end());

		while (tempEntryList.begin() != tempEntryList.end())
		{
			EntryListIterator entry = tempEntryList.begin();

			entry->bucketIndex = doHash(entry->first);
			EntryListIterator & bucketStartPos = m_buckets[entry->bucketIndex];

			if (bucketStartPos == m_entries.end())
			{
				bucketStartPos = entry;
				m_entries.splice(m_entries.begin(), tempEntryList, entry);
			}
			else
			{
				m_entries.splice(bucketStartPos, tempEntryList, entry);
				--bucketStartPos;
			}
		}
	}

	// Data members...
	Hash				m_hash;

	Comparator			m_equals;

    MemoryManagerType*  m_memoryManager;

	float				m_loadFactor;

	size_type			m_size;

	EntryListType		m_entries;

    EntryPosVectorType	m_buckets;

	EntryListType		m_freeList;

};

XALAN_CPP_NAMESPACE_END

#endif  // XALANMAP_HEADER_GUARD_1357924680

<commit_msg>Remove redundant typedef to allow gcc compile<commit_after>/*
 * Copyright 1999-2004 The Apache Software Foundation.
 *
 * 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.
 */

#if !defined(XALANMAP_HEADER_GUARD_1357924680)
#define XALANMAP_HEADER_GUARD_1357924680

// Base include file.  Must be first.
#include <xalanc/Include/PlatformDefinitions.hpp>

#include <cstddef>
#include <list>
#include <algorithm>
#include <functional>
#include <utility>

#include <xercesc/framework/MemoryManager.hpp>

#include <xalanc/Include/XalanVector.hpp>

XALAN_CPP_NAMESPACE_BEGIN

typedef size_t	size_type;

template <class Key>
class XalanHash : public XALAN_STD_QUALIFIER unary_function<Key, size_type>
{
public:
	size_type operator()(const Key& key) const
	{
		const char *byteArray = reinterpret_cast<const char*>(&key);

		size_type result = 0;

		for (size_type i = 0; i < sizeof(Key); ++i)
		{
			result = (result << 1) ^ byteArray[i];
		}

		return result;
	}
};

template <class Key>
struct XalanHashMemberPointer
{

	size_type operator() (const Key * key) const
	{
		assert (key != 0);
		return key->hash();
	}
};

template <class Key>
struct XalanHashMemberReference
{

	size_type operator() (const Key& key) const
	{
		return key.hash();
	}
};

template <
		class Key,
		class Value,
		class Hash = XalanHash<Key>,
		class Comparator = XALAN_STD_QUALIFIER equal_to<Key> >
class XalanMap
{
public:

	typedef XERCES_CPP_NAMESPACE_QUALIFIER MemoryManager    MemoryManagerType;

	typedef Key					key_type;
	typedef Value				data_type;
	typedef size_t				size_type;

	typedef XALAN_STD_QUALIFIER pair<const key_type, data_type>	value_type;

	typedef XalanMap<Key, Value, Hash, Comparator>		ThisType;

	struct Entry : public value_type
	{
		typedef value_type Parent;
		size_type	bucketIndex;

		Entry(const key_type & key, const data_type& data, size_type index) :
			value_type(key, data), bucketIndex(index)
		{
		}

		Entry() :
			value_type(key_type(),
            data_type()),
            bucketIndex(size_type())
		{
		}
	};

	typedef XALAN_STD_QUALIFIER list<Entry>					EntryListType;
	typedef typename EntryListType::iterator				EntryListIterator;
	typedef typename EntryListType::const_iterator			EntryListConstIterator;

	typedef XalanVector<typename EntryListType::iterator>	EntryPosVectorType;

	template<class ValueType, class Ref, class Ptr, class Iterator, class Map>
	struct iterator_base
	{
		typedef ValueType	value_type;
		typedef Ref		reference_type;
		typedef Ptr		pointer_type;

		typedef ThisType MapType;

		typedef iterator_base<value_type, reference_type, pointer_type, Iterator, Map> IteratorType;

		typedef iterator_base<value_type, value_type&, value_type*, EntryListIterator, MapType> iterator;

		iterator_base(
				Map&								map,
				Iterator							bucketPos) :
			m_map(&map),
			m_bucketPos(bucketPos)
		{
		}

		iterator_base(const iterator& theRhs) :
			m_map(theRhs.m_map),
			m_bucketPos(theRhs.m_bucketPos)
		{
		}

		const IteratorType & operator=(const IteratorType& theRhs)
		{
			m_map = theRhs.m_map;
			m_bucketPos = theRhs.m_bucketPos;
			return *this;
		}

		reference_type operator*() const
		{
			return *m_bucketPos;
		}

		int operator!=(const IteratorType& theRhs) const
		{
			return !operator==(theRhs);
		}

		int operator==(const IteratorType& theRhs) const
		{
			return (theRhs.m_map == m_map)
				&& (theRhs.m_bucketPos == m_bucketPos);
		}

		IteratorType& operator++()
		{
			m_bucketPos++;
			return *this;
		}

		Map*		m_map;
		Iterator	m_bucketPos;
	};

	typedef iterator_base<
		value_type,
		value_type&,
		value_type*,
		EntryListIterator,
		ThisType> iterator;

	typedef iterator_base<
		value_type,
		const value_type&,
		const value_type*,
		EntryListConstIterator,
		const ThisType> const_iterator;

	XalanMap(
			float loadFactor = 0.75,
			MemoryManagerType* theMemoryManager = 0) :
		m_memoryManager(theMemoryManager),
		m_loadFactor(loadFactor),
		m_size(0),
		m_entries(/* m_memoryManager */),
		m_buckets(10, m_entries.end(), m_memoryManager),
		m_freeList()
	{
	}

	XalanMap(const XalanMap &theRhs) :
		m_memoryManager(theRhs.m_memoryManager),
		m_loadFactor(theRhs.m_loadFactor),
		m_size(0),
		m_entries(/* m_memoryManager */),
		m_buckets(size_type(m_loadFactor * theRhs.size())+ 1, m_entries.end(), m_memoryManager),
		m_freeList()
	{
		const_iterator entry = theRhs.begin();
		while(entry != theRhs.end())
		{
			insert(*entry);
			++entry;
		}

		assert(m_size == theRhs.m_size);
	}

	~XalanMap()
	{
	}

	XalanMap & operator=(const XalanMap& theRhs)
	{
		XalanMap theTemp(theRhs);
		swap(theTemp);
		return *this;
	}

	size_type size() const
	{
		return m_size;
	}

	bool empty() const {
		return m_size == 0;
	}

	iterator begin()
	{
		return iterator(*this, m_entries.begin());
	}

	const_iterator begin() const
	{
		return const_iterator(*this, m_entries.begin());
	}

	iterator end()
	{
		return iterator(*this, m_entries.end());
	}

	const_iterator end() const
	{
		return const_iterator(*this, m_entries.end());
	}

	iterator find(const key_type& key)
	{
		size_type index = doHash(key);

		EntryListIterator bucketPos = m_buckets[index];

		while (bucketPos != m_entries.end() &&
			   bucketPos->bucketIndex == index)
		{
			if (m_equals(key,bucketPos->first))
			{
				return iterator(*this,bucketPos);
			}
			++bucketPos;
		}

		return end();
	}

	const_iterator find(const key_type& key) const
	{
		size_type index = doHash(key);

		EntryListConstIterator bucketPos = m_buckets[index];

		while (bucketPos != m_entries.end() &&
			   bucketPos->bucketIndex == index)
		{
			if (m_equals(key,bucketPos->first))
			{
				return const_iterator(*this,bucketPos);
			}
			++bucketPos;
		}

		return end();
	}

	data_type & operator[](const key_type& key)
	{
		iterator pos = find(key);

		if (pos == end())
		{
			pos = doCreateEntry(key, data_type());
		}

		return (*pos).second;
	}

	void insert(const value_type& value)
	{
		const key_type& key = value.first;
		const data_type& data = value.second;

		iterator pos = find(key);

		if (pos == end())
		{
			doCreateEntry(key, data);
		}

	}

	void erase(iterator pos)
	{
		if (pos != end())
		{
			doRemoveEntry(pos.m_bucketPos);
		}
	}

	void erase(const key_type& key)
	{
		iterator pos = find(key);

		erase(pos);
	}

	void clear()
	{
		m_size = 0;

		XALAN_STD_QUALIFIER fill(
            m_buckets.begin(),
            m_buckets.end(),
            m_entries.end());

		m_freeList.splice(
            m_freeList.begin(),
            m_entries,
            m_entries.begin(),
            m_entries.end());
	}

	void swap(ThisType& theRhs)
	{
		size_type tempSize = m_size;
		m_size = theRhs.m_size;
		theRhs.m_size = tempSize;

		MemoryManagerType* tempMemoryManager = m_memoryManager;
		m_memoryManager = theRhs.m_memoryManager;
		theRhs.m_memoryManager = tempMemoryManager;

		m_entries.swap(theRhs.m_entries);
		m_buckets.swap(theRhs.m_buckets);
		m_freeList.swap(theRhs.m_freeList);

	}

	protected:

	iterator doCreateEntry(const key_type & key, const data_type&  data)
	{
		if (size_type(m_loadFactor * size()) > m_buckets.size())
		{
			rehash();
		}

		size_type index = doHash(key);

		EntryListIterator & bucketStartPos = m_buckets[index];

		if (m_freeList.empty() == true)
		{
			Entry newEntry = Entry(key, data, index);

			if (bucketStartPos == m_entries.end())
			{
				bucketStartPos = m_entries.insert(m_entries.end(), newEntry);
			}
			else
			{
				bucketStartPos = m_entries.insert(bucketStartPos, newEntry);
			}
		}
		else
		{
			(*m_freeList.begin()).~Entry();
			new (&*m_freeList.begin()) Entry(key, data, index);

			m_entries.splice(bucketStartPos, m_freeList, m_freeList.begin());
			--bucketStartPos;
		}

		++m_size;
		return iterator(*this, bucketStartPos);
	}

	void doRemoveEntry(const EntryListIterator & toRemoveIter)
	{
		size_type index = toRemoveIter->bucketIndex;
		EntryListIterator nextPosition = ++(EntryListIterator(toRemoveIter));

		if (m_buckets[index] == toRemoveIter)
		{
			if (nextPosition->bucketIndex == index)
			{
				m_buckets[index] = nextPosition;
			}
			else
			{
				m_buckets[index] = m_entries.end();
			}
		}

		m_freeList.splice(m_freeList.begin(), m_entries, toRemoveIter, nextPosition);
		--m_size;
	}

	size_type doHash(const Key & key) const
	{
		return m_hash(key) % m_buckets.size();
	}

	void rehash()
	{
		EntryPosVectorType temp(size_type(1.6 * size()), m_entries.end(), m_memoryManager);
		m_buckets.swap(temp);
		doRehashEntries();
	}

	void doRehashEntries()
	{
		EntryListType tempEntryList;
		tempEntryList.splice(tempEntryList.begin(),m_entries, m_entries.begin(), m_entries.end());

		while (tempEntryList.begin() != tempEntryList.end())
		{
			EntryListIterator entry = tempEntryList.begin();

			entry->bucketIndex = doHash(entry->first);
			EntryListIterator & bucketStartPos = m_buckets[entry->bucketIndex];

			if (bucketStartPos == m_entries.end())
			{
				bucketStartPos = entry;
				m_entries.splice(m_entries.begin(), tempEntryList, entry);
			}
			else
			{
				m_entries.splice(bucketStartPos, tempEntryList, entry);
				--bucketStartPos;
			}
		}
	}

	// Data members...
	Hash				m_hash;

	Comparator			m_equals;

    MemoryManagerType*  m_memoryManager;

	float				m_loadFactor;

	size_type			m_size;

	EntryListType		m_entries;

    EntryPosVectorType	m_buckets;

	EntryListType		m_freeList;

};

XALAN_CPP_NAMESPACE_END

#endif  // XALANMAP_HEADER_GUARD_1357924680

<|endoftext|>


<commit_before><commit_msg>Extra line.<commit_after><|endoftext|>