<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt QML Debugger of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QSplitter>
#include <QTabWidget>
#include <QFile>

#include <private/qmlenginedebug_p.h>
#include <private/qmldebugclient_p.h>
#include <QtDeclarative/qmlcomponent.h>
#include <QtDeclarative/qmlgraphicsitem.h>
#include <private/qmldebugservice_p.h>

#include "engine.h"
#include "objectpropertiesview.h"
#include "expressionquerywidget.h"
#include "objecttree.h"
#include "watchtable.h"

QT_BEGIN_NAMESPACE

class DebuggerEngineItem : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QString name READ name CONSTANT);
    Q_PROPERTY(int engineId READ engineId CONSTANT);

public:
    DebuggerEngineItem(const QString &name, int id)
    : m_name(name), m_engineId(id) {}

    QString name() const { return m_name; }
    int engineId() const { return m_engineId; }

private:
    QString m_name;
    int m_engineId;
};

EnginePane::EnginePane(QmlDebugConnection *conn, QWidget *parent)
: QWidget(parent), m_client(new QmlEngineDebug(conn, this)), m_engines(0), m_context(0), m_watchTableModel(0), m_exprQueryWidget(0)
{
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->setContentsMargins(0, 0, 0, 0);

    QFile enginesFile(":/engines.qml");
    enginesFile.open(QFile::ReadOnly);
    Q_ASSERT(enginesFile.isOpen());

    m_engineView = new QmlView(this);
    m_engineView->rootContext()->setContextProperty("engines", qVariantFromValue(QmlListProperty<QObject>(this, m_engineItems)));
    m_engineView->setContentResizable(true);
    m_engineView->setQml(enginesFile.readAll());
    m_engineView->execute();
    m_engineView->setFixedHeight(100);
    QObject::connect(m_engineView->root(), SIGNAL(engineClicked(int)),
                     this, SLOT(engineSelected(int)));
    QObject::connect(m_engineView->root(), SIGNAL(refreshEngines()),
                     this, SLOT(refreshEngines()));

    m_engineView->setVisible(false);
    layout->addWidget(m_engineView);

    QSplitter *splitter = new QSplitter;

    m_objTree = new ObjectTree(m_client, this);
    m_propertiesView = new ObjectPropertiesView(m_client);
    m_watchTableModel = new WatchTableModel(m_client, this);

    m_watchTableView = new WatchTableView(m_watchTableModel);
    m_watchTableView->setModel(m_watchTableModel);
    WatchTableHeaderView *header = new WatchTableHeaderView(m_watchTableModel);
    m_watchTableView->setHorizontalHeader(header);

    connect(m_objTree, SIGNAL(currentObjectChanged(QmlDebugObjectReference)),
            m_propertiesView, SLOT(reload(QmlDebugObjectReference)));
    connect(m_objTree, SIGNAL(expressionWatchRequested(QmlDebugObjectReference,QString)),
            m_watchTableModel, SLOT(expressionWatchRequested(QmlDebugObjectReference,QString)));

    connect(m_propertiesView, SIGNAL(activated(QmlDebugObjectReference,QmlDebugPropertyReference)),
            m_watchTableModel, SLOT(togglePropertyWatch(QmlDebugObjectReference,QmlDebugPropertyReference)));

    connect(m_watchTableModel, SIGNAL(watchCreated(QmlDebugWatch*)),
            m_propertiesView, SLOT(watchCreated(QmlDebugWatch*)));

    connect(m_watchTableView, SIGNAL(objectActivated(int)),
            m_objTree, SLOT(setCurrentObject(int)));

    m_exprQueryWidget = new ExpressionQueryWidget(ExpressionQueryWidget::SeparateEntryMode, m_client);
    connect(m_objTree, SIGNAL(currentObjectChanged(QmlDebugObjectReference)),
            m_exprQueryWidget, SLOT(setCurrentObject(QmlDebugObjectReference)));

    QSplitter *propertiesTab = new QSplitter(Qt::Vertical);
    propertiesTab->addWidget(m_propertiesView);
    propertiesTab->addWidget(m_exprQueryWidget);
    propertiesTab->setStretchFactor(0, 2);
    propertiesTab->setStretchFactor(1, 1);

    m_tabs = new QTabWidget(this);
    m_tabs->addTab(propertiesTab, tr("Properties"));
    m_tabs->addTab(m_watchTableView, tr("Watched"));

    splitter->addWidget(m_objTree);
    splitter->addWidget(m_tabs);
    splitter->setStretchFactor(1, 2);
    layout->addWidget(splitter);
}

void EnginePane::engineSelected(int id)
{
    qWarning() << "Engine selected" << id;
    queryContext(id);
}

void EnginePane::queryContext(int id)
{
    if (m_context) {
        delete m_context;
        m_context = 0;
    }

    m_context = m_client->queryRootContexts(QmlDebugEngineReference(id), this);
    if (!m_context->isWaiting())
        contextChanged();
    else
        QObject::connect(m_context, SIGNAL(stateChanged(QmlDebugQuery::State)),
                         this, SLOT(contextChanged()));
}

void EnginePane::contextChanged()
{
    //dump(m_context->rootContext(), 0);

    foreach (const QmlDebugObjectReference &object, m_context->rootContext().objects())
        m_objTree->reload(object.debugId());

    delete m_context; m_context = 0;
}

void EnginePane::refreshEngines()
{
    if (m_engines)
        return;

    m_engines = m_client->queryAvailableEngines(this);
    if (!m_engines->isWaiting())
        enginesChanged();
    else
        QObject::connect(m_engines, SIGNAL(stateChanged(QmlDebugQuery::State)),
                         this, SLOT(enginesChanged()));
}

void EnginePane::enginesChanged()
{
    qDeleteAll(m_engineItems);
    m_engineItems.clear();

    QList<QmlDebugEngineReference> engines = m_engines->engines();
    delete m_engines; m_engines = 0;

    if (engines.isEmpty())
        qWarning("qmldebugger: no engines found!");

    for (int ii = 0; ii < engines.count(); ++ii)
        m_engineItems << new DebuggerEngineItem(engines.at(ii).name(),
                                                engines.at(ii).debugId());

    m_engineView->rootContext()->setContextProperty("engines", qVariantFromValue(QmlListProperty<QObject>(this, m_engineItems)));

    m_engineView->setVisible(m_engineItems.count() > 1);
    if (m_engineItems.count() == 1)
        engineSelected(qobject_cast<DebuggerEngineItem*>(m_engineItems.at(0))->engineId());
}

#include "engine.moc"

QT_END_NAMESPACE

<commit_msg>Revert "Compile"<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt QML Debugger of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QSplitter>
#include <QTabWidget>
#include <QFile>

#include <private/qmlenginedebug_p.h>
#include <private/qmldebugclient_p.h>
#include <QtDeclarative/qmlcomponent.h>
#include <QtDeclarative/qmlgraphicsitem.h>
#include <private/qmldebugservice_p.h>

#include "engine.h"
#include "objectpropertiesview.h"
#include "expressionquerywidget.h"
#include "objecttree.h"
#include "watchtable.h"

QT_BEGIN_NAMESPACE

class DebuggerEngineItem : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QString name READ name CONSTANT);
    Q_PROPERTY(int engineId READ engineId CONSTANT);

public:
    DebuggerEngineItem(const QString &name, int id)
    : m_name(name), m_engineId(id) {}

    QString name() const { return m_name; }
    int engineId() const { return m_engineId; }

private:
    QString m_name;
    int m_engineId;
};

EnginePane::EnginePane(QmlDebugConnection *conn, QWidget *parent)
: QWidget(parent), m_client(new QmlEngineDebug(conn, this)), m_engines(0), m_context(0), m_watchTableModel(0), m_exprQueryWidget(0)
{
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->setContentsMargins(0, 0, 0, 0);

    QFile enginesFile(":/engines.qml");
    enginesFile.open(QFile::ReadOnly);
    Q_ASSERT(enginesFile.isOpen());

    m_engineView = new QmlView(this);
    m_engineView->rootContext()->setContextProperty("engines", qVariantFromValue(&m_engineItems));
    m_engineView->setContentResizable(true);
    m_engineView->setQml(enginesFile.readAll());
    m_engineView->execute();
    m_engineView->setFixedHeight(100);
    QObject::connect(m_engineView->root(), SIGNAL(engineClicked(int)),
                     this, SLOT(engineSelected(int)));
    QObject::connect(m_engineView->root(), SIGNAL(refreshEngines()),
                     this, SLOT(refreshEngines()));

    m_engineView->setVisible(false);
    layout->addWidget(m_engineView);

    QSplitter *splitter = new QSplitter;

    m_objTree = new ObjectTree(m_client, this);
    m_propertiesView = new ObjectPropertiesView(m_client);
    m_watchTableModel = new WatchTableModel(m_client, this);

    m_watchTableView = new WatchTableView(m_watchTableModel);
    m_watchTableView->setModel(m_watchTableModel);
    WatchTableHeaderView *header = new WatchTableHeaderView(m_watchTableModel);
    m_watchTableView->setHorizontalHeader(header);

    connect(m_objTree, SIGNAL(currentObjectChanged(QmlDebugObjectReference)),
            m_propertiesView, SLOT(reload(QmlDebugObjectReference)));
    connect(m_objTree, SIGNAL(expressionWatchRequested(QmlDebugObjectReference,QString)),
            m_watchTableModel, SLOT(expressionWatchRequested(QmlDebugObjectReference,QString)));

    connect(m_propertiesView, SIGNAL(activated(QmlDebugObjectReference,QmlDebugPropertyReference)),
            m_watchTableModel, SLOT(togglePropertyWatch(QmlDebugObjectReference,QmlDebugPropertyReference)));

    connect(m_watchTableModel, SIGNAL(watchCreated(QmlDebugWatch*)),
            m_propertiesView, SLOT(watchCreated(QmlDebugWatch*)));

    connect(m_watchTableView, SIGNAL(objectActivated(int)),
            m_objTree, SLOT(setCurrentObject(int)));

    m_exprQueryWidget = new ExpressionQueryWidget(ExpressionQueryWidget::SeparateEntryMode, m_client);
    connect(m_objTree, SIGNAL(currentObjectChanged(QmlDebugObjectReference)),
            m_exprQueryWidget, SLOT(setCurrentObject(QmlDebugObjectReference)));

    QSplitter *propertiesTab = new QSplitter(Qt::Vertical);
    propertiesTab->addWidget(m_propertiesView);
    propertiesTab->addWidget(m_exprQueryWidget);
    propertiesTab->setStretchFactor(0, 2);
    propertiesTab->setStretchFactor(1, 1);

    m_tabs = new QTabWidget(this);
    m_tabs->addTab(propertiesTab, tr("Properties"));
    m_tabs->addTab(m_watchTableView, tr("Watched"));

    splitter->addWidget(m_objTree);
    splitter->addWidget(m_tabs);
    splitter->setStretchFactor(1, 2);
    layout->addWidget(splitter);
}

void EnginePane::engineSelected(int id)
{
    qWarning() << "Engine selected" << id;
    queryContext(id);
}

void EnginePane::queryContext(int id)
{
    if (m_context) {
        delete m_context;
        m_context = 0;
    }

    m_context = m_client->queryRootContexts(QmlDebugEngineReference(id), this);
    if (!m_context->isWaiting())
        contextChanged();
    else
        QObject::connect(m_context, SIGNAL(stateChanged(QmlDebugQuery::State)),
                         this, SLOT(contextChanged()));
}

void EnginePane::contextChanged()
{
    //dump(m_context->rootContext(), 0);

    foreach (const QmlDebugObjectReference &object, m_context->rootContext().objects())
        m_objTree->reload(object.debugId());

    delete m_context; m_context = 0;
}

void EnginePane::refreshEngines()
{
    if (m_engines)
        return;

    m_engines = m_client->queryAvailableEngines(this);
    if (!m_engines->isWaiting())
        enginesChanged();
    else
        QObject::connect(m_engines, SIGNAL(stateChanged(QmlDebugQuery::State)),
                         this, SLOT(enginesChanged()));
}

void EnginePane::enginesChanged()
{
    qDeleteAll(m_engineItems);
    m_engineItems.clear();

    QList<QmlDebugEngineReference> engines = m_engines->engines();
    delete m_engines; m_engines = 0;

    if (engines.isEmpty())
        qWarning("qmldebugger: no engines found!");

    for (int ii = 0; ii < engines.count(); ++ii)
        m_engineItems << new DebuggerEngineItem(engines.at(ii).name(),
                                                engines.at(ii).debugId());

    m_engineView->rootContext()->setContextProperty("engines", qVariantFromValue(&m_engineItems));

    m_engineView->setVisible(m_engineItems.count() > 1);
    if (m_engineItems.count() == 1)
        engineSelected(qobject_cast<DebuggerEngineItem*>(m_engineItems.at(0))->engineId());
}

#include "engine.moc"

QT_END_NAMESPACE

<|endoftext|>


<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (testabilitydriver@nokia.com)
**
** This file is part of Testability Driver Qt Agent
**
** If you have questions regarding the use of this file, please contact
** Nokia at testabilitydriver@nokia.com .
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include <QObject>
#include <QDir>

#include <tascoreutils.h>
#include "taspropertylogger.h"

const char* const PROPERTY = "property";
const char* const APPEND = "append";
const char* const CLEARLOG = "clearLog";
const char* const FILEPATH = "filePath";
const char* const ATTR_DELIM = ";";
const char* const VALUE_DELIM = ":";
const char* const INTERVAL = "interval";

TasPropertyLogger::TasPropertyLogger()
{
    mInterval = 1000;
    connect(&mTimer, SIGNAL(timeout()), this, SLOT(timerEvent()));
}
TasPropertyLogger::~TasPropertyLogger()
{
    mTimer.stop();
    foreach( QObject* key, mTargets.keys()){
        qDeleteAll(mTargets.value(key));
    }
    mTargets.clear();

}

/*!
  Collect the property values
 */
void TasPropertyLogger::timerEvent()
{
    foreach( QObject* object, mTargets.keys()){
        QHash<QString,QFile*> fileMap = mTargets.value(object);
        foreach(QString property, fileMap.keys()){
            QString line = "timeStamp:";
            line.append(QDateTime::currentDateTime().toString(DATE_FORMAT));
            line.append(ATTR_DELIM);
            line.append(property);
            line.append(VALUE_DELIM);
            line.append(object->property(property.toAscii()).toString());
            mLoggerUtil.writeLine(line, fileMap.value(property));
        }
    }
}

/*!
  Starts logging property values if possible. Returns false if logging cannot be started.
  Check error message in such cases.
 */
bool TasPropertyLogger::startPropertyLog(QObject* object, QHash<QString, QString> params, QString &errorMsg)
{
    if(!validateParams(params, errorMsg)){
        return false;
    }

    QString property = params.value(PROPERTY);
    if(!object->property(property.toAscii()).isValid()){
        errorMsg = "Target object does not have a property "+property+".";
        return false;
    }
    if(!params.contains(FILEPATH)){
        errorMsg = "Root directory for the log data must be defined";
        return false;
    }

    QHash<QString,QFile*> fileMap;
    if(mTargets.contains(object)){
        fileMap = mTargets.value(object);
    }
    if(!fileMap.contains(property)){
        QString name = params.value(FILEPATH);
        if(!name.endsWith('/') && !name.endsWith('\\')){
            name.append(QDir::separator());
        }
        name.append(TasCoreUtils::getApplicationName());
        name.append("_");
        name.append(object->metaObject()->className());
        name.append("_");
        name.append(property);
        name.append(".log");
        bool append = (params.value(APPEND, "") == "true");
        QFile* file = mLoggerUtil.openFile(name, append);
        fileMap.insert(property, file);
    }
    mTargets.insert(object, fileMap);

    if(params.contains(INTERVAL)){
        int interval = params.value(INTERVAL).toInt();
        if(interval != mInterval){
            mInterval = interval;
            mTimer.stop();
        }
    }
    if(!mTimer.isActive()){
        mTimer.start(mInterval);
    }
    return true;
}

bool TasPropertyLogger::getLogData(QObject* object, QHash<QString, QString> params, QString& data)
{
    if(!mTargets.contains(object)){
        data = QString("No data collected for the object.").toUtf8();
        return false;
    }
    else{
        QString errorMsg;
        if(!validateParams(params, errorMsg)){
            data = errorMsg;
            return false;
        }
        QString property = params.value(PROPERTY);
        QHash<QString,QFile*> fileMap = mTargets.value(object);
        if(!fileMap.contains(property)){
            data = QString("No data collected for the property: " + property);
            return false;
        }
        else{
            QFile* file = fileMap.value(property);
            QHash<QString,QString> objectAttrs;
            objectAttrs.insert("objectType",object->metaObject()->className());
            objectAttrs.insert("objectName",object->objectName());
            data = QString::fromUtf8(mLoggerUtil.loadLoggedData(file, property, objectAttrs).data());
            if (params.value(CLEARLOG, "") != "false"){
                file->remove();
                file->open(QIODevice::ReadWrite | QIODevice::Text | QIODevice::Truncate);
            }
        }
    }
    return true;
}

void TasPropertyLogger::stopLogger(QObject* object, QHash<QString, QString> params)
{
    if(mTargets.contains(object)){
        QString errorMsg;
        if(validateParams(params, errorMsg)){
            QString property = params.value(PROPERTY);
            QHash<QString,QFile*> fileMap = mTargets.value(object);
            if(fileMap.contains(property)){
                QFile* file = fileMap.value(property);
                file->remove();
                delete file;
                fileMap.remove(property);
            }
            if(fileMap.isEmpty()){
                mTargets.remove(object);
            }
        }
    }
}

bool TasPropertyLogger::validateParams(QHash<QString, QString> params, QString& errorMsg)
{
    if(!params.contains(PROPERTY)){
        errorMsg = "A property name must be given!";
        return false;
    }
    return true;
}
<commit_msg>file open situtation error handling<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (testabilitydriver@nokia.com)
**
** This file is part of Testability Driver Qt Agent
**
** If you have questions regarding the use of this file, please contact
** Nokia at testabilitydriver@nokia.com .
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include <QObject>
#include <QDir>

#include <tascoreutils.h>
#include "taspropertylogger.h"

const char* const PROPERTY = "property";
const char* const APPEND = "append";
const char* const CLEARLOG = "clearLog";
const char* const FILEPATH = "filePath";
const char* const ATTR_DELIM = ";";
const char* const VALUE_DELIM = ":";
const char* const INTERVAL = "interval";

TasPropertyLogger::TasPropertyLogger()
{
    mInterval = 1000;
    connect(&mTimer, SIGNAL(timeout()), this, SLOT(timerEvent()));
}
TasPropertyLogger::~TasPropertyLogger()
{
    mTimer.stop();
    foreach( QObject* key, mTargets.keys()){
        qDeleteAll(mTargets.value(key));
    }
    mTargets.clear();

}

/*!
  Collect the property values
 */
void TasPropertyLogger::timerEvent()
{
    foreach( QObject* object, mTargets.keys()){
        QHash<QString,QFile*> fileMap = mTargets.value(object);
        foreach(QString property, fileMap.keys()){
            QString line = "timeStamp:";
            line.append(QDateTime::currentDateTime().toString(DATE_FORMAT));
            line.append(ATTR_DELIM);
            line.append(property);
            line.append(VALUE_DELIM);
            line.append(object->property(property.toAscii()).toString());
            mLoggerUtil.writeLine(line, fileMap.value(property));
        }
    }
}

/*!
  Starts logging property values if possible. Returns false if logging cannot be started.
  Check error message in such cases.
 */
bool TasPropertyLogger::startPropertyLog(QObject* object, QHash<QString, QString> params, QString &errorMsg)
{
    if(!validateParams(params, errorMsg)){
        return false;
    }

    QString property = params.value(PROPERTY);
    if(!object->property(property.toAscii()).isValid()){
        errorMsg = "Target object does not have a property "+property+".";
        return false;
    }
    if(!params.contains(FILEPATH)){
        errorMsg = "Root directory for the log data must be defined";
        return false;
    }

    QHash<QString,QFile*> fileMap;
    if(mTargets.contains(object)){
        fileMap = mTargets.value(object);
    }
    if(!fileMap.contains(property)){
        QString name = params.value(FILEPATH);
        if(!name.endsWith('/') && !name.endsWith('\\')){
            name.append(QDir::separator());
        }
        name.append(TasCoreUtils::getApplicationName());
        name.append("_");
        name.append(object->metaObject()->className());
        name.append("_");
        name.append(property);
        name.append(".log");
        bool append = (params.value(APPEND, "") == "true");
        QFile* file = mLoggerUtil.openFile(name, append);
        if(file->error()!= QFile::NoError){
            errorMsg = "Opening file failed, reason: " + QString::number(file->error());
            delete file;
            return false;
        }
        fileMap.insert(property, file);
    }
    mTargets.insert(object, fileMap);

    if(params.contains(INTERVAL)){
        int interval = params.value(INTERVAL).toInt();
        if(interval != mInterval){
            mInterval = interval;
            mTimer.stop();
        }
    }
    if(!mTimer.isActive()){
        mTimer.start(mInterval);
    }
    return true;
}

bool TasPropertyLogger::getLogData(QObject* object, QHash<QString, QString> params, QString& data)
{
    if(!mTargets.contains(object)){
        data = QString("No data collected for the object.").toUtf8();
        return false;
    }
    else{
        QString errorMsg;
        if(!validateParams(params, errorMsg)){
            data = errorMsg;
            return false;
        }
        QString property = params.value(PROPERTY);
        QHash<QString,QFile*> fileMap = mTargets.value(object);
        if(!fileMap.contains(property)){
            data = QString("No data collected for the property: " + property);
            return false;
        }
        else{
            QFile* file = fileMap.value(property);
            QHash<QString,QString> objectAttrs;
            objectAttrs.insert("objectType",object->metaObject()->className());
            objectAttrs.insert("objectName",object->objectName());
            data = QString::fromUtf8(mLoggerUtil.loadLoggedData(file, property, objectAttrs).data());
            if (params.value(CLEARLOG, "") != "false"){
                file->remove();
                file->open(QIODevice::ReadWrite | QIODevice::Text | QIODevice::Truncate);
            }
        }
    }
    return true;
}

void TasPropertyLogger::stopLogger(QObject* object, QHash<QString, QString> params)
{
    if(mTargets.contains(object)){
        QString errorMsg;
        if(validateParams(params, errorMsg)){
            QString property = params.value(PROPERTY);
            QHash<QString,QFile*> fileMap = mTargets.value(object);
            if(fileMap.contains(property)){
                QFile* file = fileMap.value(property);
                file->remove();
                delete file;
                fileMap.remove(property);
            }
            if(fileMap.isEmpty()){
                mTargets.remove(object);
            }
        }
    }
}

bool TasPropertyLogger::validateParams(QHash<QString, QString> params, QString& errorMsg)
{
    if(!params.contains(PROPERTY)){
        errorMsg = "A property name must be given!";
        return false;
    }
    return true;
}
<|endoftext|>


<commit_before>#ifndef SILICIUM_ASIO_POSTING_OBSERVABLE_HPP
#define SILICIUM_ASIO_POSTING_OBSERVABLE_HPP

#include <silicium/exchange.hpp>
#include <silicium/observable/function_observer.hpp>
#include <boost/asio/io_service.hpp>

namespace Si
{
	namespace asio
	{
		template <class Next>
		struct posting_observable
		{
			typedef typename Next::element_type element_type;

			posting_observable()
			    : m_io(nullptr)
			{
			}

			explicit posting_observable(boost::asio::io_service &io, Next next)
				: m_io(&io)
				, m_next(std::move(next))
			{
			}

			template <class Observer>
			void async_get_one(Observer &&observer_)
			{
				auto keep_io_running =
#if SILICIUM_COMPILER_HAS_EXTENDED_CAPTURE
					Si::make_unique
#else
					std::make_shared
#endif
					<boost::asio::io_service::work>(*m_io);
				m_next.async_get_one(
					make_function_observer([this, keep_io_running
#if SILICIUM_COMPILER_HAS_EXTENDED_CAPTURE
					= std::move(keep_io_running)
#endif
					, observer_
#if SILICIUM_COMPILER_HAS_EXTENDED_CAPTURE
					= std::forward<Observer>(observer_)
#endif
					](Si::optional<element_type> element) mutable
				{
					if (element)
					{
#if SILICIUM_COMPILER_HAS_EXTENDED_CAPTURE
						m_io->post([
							element = std::move(element),
							observer_ = std::forward<Observer>(observer_)
						]() mutable
						{
							std::forward<Observer>(observer_).got_element(std::move(*element));
						});
#else
						auto copyable_element = to_shared(std::move(*element));
						m_io->post([
							copyable_element,
							observer_
						]() mutable
						{
							std::forward<Observer>(observer_).got_element(std::move(*copyable_element));
						});
#endif
					}
					else
					{
						m_io->post([observer_
#if SILICIUM_COMPILER_HAS_EXTENDED_CAPTURE
							= std::forward<Observer>(observer_)
#endif
						]() mutable
						{
							std::forward<Observer>(observer_).ended();
						});
					}
				}));
			}

#if SILICIUM_COMPILER_GENERATES_MOVES
			posting_observable(posting_observable &&) = default;
			posting_observable &operator = (posting_observable &&) = default;
#else
			posting_observable(posting_observable &&other)
				: m_io(std::move(other.m_io))
				, m_next(std::move(other.m_next))
			{
			}

			posting_observable &operator = (posting_observable &&other)
			{
				m_io = std::move(other.m_io);
				m_next = std::move(other.m_next);
				return *this;
			}
#endif

		private:

			boost::asio::io_service *m_io;
			Next m_next;

			SILICIUM_DELETED_FUNCTION(posting_observable(posting_observable const &))
			SILICIUM_DELETED_FUNCTION(posting_observable &operator = (posting_observable const &))
		};

		template <class Next>
		auto make_posting_observable(boost::asio::io_service &io, Next &&next)
#if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE
			-> posting_observable<typename std::decay<Next>::type>
#endif
		{
			return posting_observable<typename std::decay<Next>::type>(io, std::forward<Next>(next));
		}
	}
}

#endif
<commit_msg>generalize posting_observable for strand<commit_after>#ifndef SILICIUM_ASIO_POSTING_OBSERVABLE_HPP
#define SILICIUM_ASIO_POSTING_OBSERVABLE_HPP

#include <silicium/exchange.hpp>
#include <silicium/observable/function_observer.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/asio/strand.hpp>

namespace Si
{
	namespace asio
	{
		inline boost::asio::io_service &get_io_service(boost::asio::io_service &io)
		{
			return io;
		}

		inline boost::asio::io_service &get_io_service(boost::asio::io_service::strand &strand)
		{
			return strand.get_io_service();
		}

		template <class Next, class Dispatcher = boost::asio::io_service>
		struct posting_observable
		{
			typedef typename Next::element_type element_type;

			posting_observable()
			    : m_io(nullptr)
			{
			}

			explicit posting_observable(Dispatcher &io, Next next)
				: m_io(&io)
				, m_next(std::move(next))
			{
			}

			template <class Observer>
			void async_get_one(Observer &&observer_)
			{
				auto keep_io_running =
#if SILICIUM_COMPILER_HAS_EXTENDED_CAPTURE
					Si::make_unique
#else
					std::make_shared
#endif
					<boost::asio::io_service::work>(get_io_service(*m_io));
				m_next.async_get_one(
					make_function_observer([this, keep_io_running
#if SILICIUM_COMPILER_HAS_EXTENDED_CAPTURE
					= std::move(keep_io_running)
#endif
					, observer_
#if SILICIUM_COMPILER_HAS_EXTENDED_CAPTURE
					= std::forward<Observer>(observer_)
#endif
					](Si::optional<element_type> element) mutable
				{
					if (element)
					{
#if SILICIUM_COMPILER_HAS_EXTENDED_CAPTURE
						m_io->post([
							element = std::move(element),
							observer_ = std::forward<Observer>(observer_)
						]() mutable
						{
							std::forward<Observer>(observer_).got_element(std::move(*element));
						});
#else
						auto copyable_element = to_shared(std::move(*element));
						m_io->post([
							copyable_element,
							observer_
						]() mutable
						{
							std::forward<Observer>(observer_).got_element(std::move(*copyable_element));
						});
#endif
					}
					else
					{
						m_io->post([observer_
#if SILICIUM_COMPILER_HAS_EXTENDED_CAPTURE
							= std::forward<Observer>(observer_)
#endif
						]() mutable
						{
							std::forward<Observer>(observer_).ended();
						});
					}
				}));
			}

#if SILICIUM_COMPILER_GENERATES_MOVES
			posting_observable(posting_observable &&) = default;
			posting_observable &operator = (posting_observable &&) = default;
#else
			posting_observable(posting_observable &&other)
				: m_io(std::move(other.m_io))
				, m_next(std::move(other.m_next))
			{
			}

			posting_observable &operator = (posting_observable &&other)
			{
				m_io = std::move(other.m_io);
				m_next = std::move(other.m_next);
				return *this;
			}
#endif

		private:

			Dispatcher *m_io;
			Next m_next;

			SILICIUM_DELETED_FUNCTION(posting_observable(posting_observable const &))
			SILICIUM_DELETED_FUNCTION(posting_observable &operator = (posting_observable const &))
		};

		template <class Next>
		auto make_posting_observable(boost::asio::io_service &io, Next &&next)
#if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE
			-> posting_observable<typename std::decay<Next>::type>
#endif
		{
			return posting_observable<typename std::decay<Next>::type>(io, std::forward<Next>(next));
		}
	}
}

#endif
<|endoftext|>


<commit_before>//
// Copyright (C) 2006-2007 SIPez LLC.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// Copyright (C) 2006-2007 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// Copyright (C) 2006 Hector Izquierdo Seliva.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// $$
//////////////////////////////////////////////////////////////////////////////

#ifdef HAVE_SPEEX /* [ */

// APPLICATION INCLUDES
#include "mp/MpdSipxSpeex.h"
#include "mp/MprDejitter.h"
#include "os/OsSysLog.h"
#include "os/OsSysLogFacilities.h"

const MpCodecInfo MpdSipxSpeex::smCodecInfo(
         SdpCodec::SDP_CODEC_SPEEX,    // codecType
         "Speex codec",                // codecVersion
         false,                        // usesNetEq
         8000,                         // samplingRate
         8,                            // numBitsPerSample (not used)
         1,                            // numChannels
         38,                           // interleaveBlockSize
         15000,                        // bitRate
         1*8,                          // minPacketBits
         38*8,                         // avgPacketBits
         63*8,                         // maxPacketBits
         160,                          // numSamplesPerFrame
         5);                           // preCodecJitterBufferSize (should be adjusted)

MpdSipxSpeex::MpdSipxSpeex(int payloadType)
: MpDecoderBase(payloadType, &smCodecInfo)
, mpDecoderState(NULL)
, mDecbits()
, mNumSamplesPerFrame(0)
{
}

MpdSipxSpeex::~MpdSipxSpeex()
{
}

OsStatus MpdSipxSpeex::initDecode()
{
   if (mpDecoderState == NULL) {
      int tmp;

      // Init decoder
      mpDecoderState = speex_decoder_init(speex_lib_get_mode(SPEEX_MODEID_NB));

      // It makes the decoded speech deviate further from the original,
      // but it sounds subjectively better.
      tmp = 1;
      speex_decoder_ctl(mpDecoderState,SPEEX_SET_ENH,&tmp);

      // Get number of samples in one frame
      speex_decoder_ctl(mpDecoderState,SPEEX_GET_FRAME_SIZE,&mNumSamplesPerFrame);

      speex_bits_init(&mDecbits);
   }

   return OS_SUCCESS;
}

OsStatus MpdSipxSpeex::freeDecode(void)
{
   if (mpDecoderState != NULL) {
      speex_decoder_destroy(mpDecoderState);
      mpDecoderState = NULL;

      speex_bits_destroy(&mDecbits);
   }

   return OS_SUCCESS;
}

int MpdSipxSpeex::decode(const MpRtpBufPtr &pPacket, unsigned decodedBufferLength, MpAudioSample *samplesBuffer)
{
   // Assert that available buffer size is enough for the packet.
   if (mNumSamplesPerFrame > decodedBufferLength)
   {
      osPrintf("MpdSipxSpeex::decode: Jitter buffer overloaded. Glitch!\n");
      return 0;
   }

   // Prepare data for Speex decoder
   speex_bits_read_from(&mDecbits,(char*)pPacket->getDataPtr(),pPacket->getPayloadSize());

   // Decode frame
   speex_decode_int(mpDecoderState,&mDecbits,(spx_int16_t*)samplesBuffer);

   return mNumSamplesPerFrame;
}

#endif /* HAVE_SPEEX ] */
<commit_msg>Remove "MprDejitter.h" include from one more decoder.<commit_after>//
// Copyright (C) 2006-2007 SIPez LLC.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// Copyright (C) 2006-2007 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// Copyright (C) 2006 Hector Izquierdo Seliva.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// $$
//////////////////////////////////////////////////////////////////////////////

#ifdef HAVE_SPEEX /* [ */

// APPLICATION INCLUDES
#include "mp/MpdSipxSpeex.h"
#include "os/OsSysLog.h"
#include "os/OsSysLogFacilities.h"

const MpCodecInfo MpdSipxSpeex::smCodecInfo(
         SdpCodec::SDP_CODEC_SPEEX,    // codecType
         "Speex codec",                // codecVersion
         false,                        // usesNetEq
         8000,                         // samplingRate
         8,                            // numBitsPerSample (not used)
         1,                            // numChannels
         38,                           // interleaveBlockSize
         15000,                        // bitRate
         1*8,                          // minPacketBits
         38*8,                         // avgPacketBits
         63*8,                         // maxPacketBits
         160,                          // numSamplesPerFrame
         5);                           // preCodecJitterBufferSize (should be adjusted)

MpdSipxSpeex::MpdSipxSpeex(int payloadType)
: MpDecoderBase(payloadType, &smCodecInfo)
, mpDecoderState(NULL)
, mDecbits()
, mNumSamplesPerFrame(0)
{
}

MpdSipxSpeex::~MpdSipxSpeex()
{
}

OsStatus MpdSipxSpeex::initDecode()
{
   if (mpDecoderState == NULL) {
      int tmp;

      // Init decoder
      mpDecoderState = speex_decoder_init(speex_lib_get_mode(SPEEX_MODEID_NB));

      // It makes the decoded speech deviate further from the original,
      // but it sounds subjectively better.
      tmp = 1;
      speex_decoder_ctl(mpDecoderState,SPEEX_SET_ENH,&tmp);

      // Get number of samples in one frame
      speex_decoder_ctl(mpDecoderState,SPEEX_GET_FRAME_SIZE,&mNumSamplesPerFrame);

      speex_bits_init(&mDecbits);
   }

   return OS_SUCCESS;
}

OsStatus MpdSipxSpeex::freeDecode(void)
{
   if (mpDecoderState != NULL) {
      speex_decoder_destroy(mpDecoderState);
      mpDecoderState = NULL;

      speex_bits_destroy(&mDecbits);
   }

   return OS_SUCCESS;
}

int MpdSipxSpeex::decode(const MpRtpBufPtr &pPacket, unsigned decodedBufferLength, MpAudioSample *samplesBuffer)
{
   // Assert that available buffer size is enough for the packet.
   if (mNumSamplesPerFrame > decodedBufferLength)
   {
      osPrintf("MpdSipxSpeex::decode: Jitter buffer overloaded. Glitch!\n");
      return 0;
   }

   // Prepare data for Speex decoder
   speex_bits_read_from(&mDecbits,(char*)pPacket->getDataPtr(),pPacket->getPayloadSize());

   // Decode frame
   speex_decode_int(mpDecoderState,&mDecbits,(spx_int16_t*)samplesBuffer);

   return mNumSamplesPerFrame;
}

#endif /* HAVE_SPEEX ] */
<|endoftext|>


<commit_before>#include "src/graphics.h"
#include "src/utils.h"
#include <stdarg.h>
#include <string.h>

// maximum lenght of a string processed by utl_printf()
#define PRINTF_LEN 128

// internal: render a single character
static void drawChar(const int x, const int y, unsigned char c, const unsigned char fgCol, const unsigned char bgCol, gfx_drawBuffer *buffer);

/* ***** */
void utl_printf(gfx_drawBuffer *buffer, const int x, const int y, const unsigned char fgCol, const unsigned char bgCol, const char *format, ...)
{
    int i=-1;
    char strBuffer[PRINTF_LEN];
    va_list args;
    va_start(args, format);
    vsnprintf(strBuffer, PRINTF_LEN, format, args);
    va_end(args);

    while(strBuffer[++i])
        drawChar(x + (i << 3), y, strBuffer[i], fgCol, bgCol, buffer);
}

/* ***** */
void utl_drawPalette(gfx_drawBuffer *buffer)
{
    const int tileW = 20;
    const int tileH = 12;
    int x, y, xOffset, yOffset, c = 0;
    int bufferWidth  = buffer ? buffer->width : SCREEN_WIDTH;
    int bufferHeight = buffer ? buffer->height : SCREEN_HEIGHT;
    gfx_clrBufferColor(buffer, c);

    for(c = 0; c < 256; ++c)
    {
        xOffset = c % 16;
        yOffset = c / 16;

        for(y = yOffset * tileH + 4; y < (yOffset + 1) * tileH + 4 && y < bufferHeight; ++y)
        {
            for(x = xOffset * tileW; x < (xOffset + 1) * tileW && x < bufferWidth; ++x)
                gfx_drawPixel(x, y, c, buffer);
        }

        utl_printf(buffer, xOffset * tileW, yOffset * tileH + 4, 15, c, "%x", c);
    }
}

/* ***** */
static void drawChar(const int x, const int y, unsigned char c, const unsigned char fgCol, const unsigned char bgCol, gfx_drawBuffer *buffer)
{
    // start address of ROM character set storage
    static unsigned char *romCharSet = (unsigned char *)0xFFA6E;
    unsigned char bitMask;
    int xOffset, yOffset;
    int buffWidth  = buffer ? buffer->width : SCREEN_WIDTH;
    int buffHeight = buffer ? buffer->height : SCREEN_HEIGHT;

    // stored characters are 8x8 bitmaps
    unsigned char *currChar = &romCharSet[c * 8];

    for(yOffset = 0; yOffset < 8; ++yOffset) {
        if(y + yOffset < buffHeight)
        {
            bitMask = 0x80;

            for(xOffset = 0; xOffset < 8; ++xOffset)
            {
                if(x + xOffset < buffWidth)
                {
                   if (*currChar & bitMask)
                        gfx_drawPixel(x + xOffset, y + yOffset, fgCol, buffer);
                    else
                        gfx_drawPixel(x + xOffset, y + yOffset, bgCol, buffer);
                }
                bitMask >>= 1;
            }
        }

        ++currChar;
    }
}

<commit_msg>use color 0 to draw palette index<commit_after>#include "src/graphics.h"
#include "src/utils.h"
#include <stdarg.h>
#include <string.h>

// maximum lenght of a string processed by utl_printf()
#define PRINTF_LEN 128

// internal: render a single character
static void drawChar(const int x, const int y, unsigned char c, const unsigned char fgCol, const unsigned char bgCol, gfx_drawBuffer *buffer);

/* ***** */
void utl_printf(gfx_drawBuffer *buffer, const int x, const int y, const unsigned char fgCol, const unsigned char bgCol, const char *format, ...)
{
    int i=-1;
    char strBuffer[PRINTF_LEN];
    va_list args;
    va_start(args, format);
    vsnprintf(strBuffer, PRINTF_LEN, format, args);
    va_end(args);

    while(strBuffer[++i])
        drawChar(x + (i << 3), y, strBuffer[i], fgCol, bgCol, buffer);
}

/* ***** */
void utl_drawPalette(gfx_drawBuffer *buffer)
{
    const int tileW = 20;
    const int tileH = 12;
    int x, y, xOffset, yOffset, c = 0;
    int bufferWidth  = buffer ? buffer->width : SCREEN_WIDTH;
    int bufferHeight = buffer ? buffer->height : SCREEN_HEIGHT;
    gfx_clrBufferColor(buffer, c);

    for(c = 0; c < 256; ++c)
    {
        xOffset = c % 16;
        yOffset = c / 16;

        for(y = yOffset * tileH + 4; y < (yOffset + 1) * tileH + 4 && y < bufferHeight; ++y)
        {
            for(x = xOffset * tileW; x < (xOffset + 1) * tileW && x < bufferWidth; ++x)
                gfx_drawPixel(x, y, c, buffer);
        }

        utl_printf(buffer, xOffset * tileW, yOffset * tileH + 4, 0, c, "%x", c);
    }
}

/* ***** */
static void drawChar(const int x, const int y, unsigned char c, const unsigned char fgCol, const unsigned char bgCol, gfx_drawBuffer *buffer)
{
    // start address of ROM character set storage
    static unsigned char *romCharSet = (unsigned char *)0xFFA6E;
    unsigned char bitMask;
    int xOffset, yOffset;
    int buffWidth  = buffer ? buffer->width : SCREEN_WIDTH;
    int buffHeight = buffer ? buffer->height : SCREEN_HEIGHT;

    // stored characters are 8x8 bitmaps
    unsigned char *currChar = &romCharSet[c * 8];

    for(yOffset = 0; yOffset < 8; ++yOffset) {
        if(y + yOffset < buffHeight)
        {
            bitMask = 0x80;

            for(xOffset = 0; xOffset < 8; ++xOffset)
            {
                if(x + xOffset < buffWidth)
                {
                   if (*currChar & bitMask)
                        gfx_drawPixel(x + xOffset, y + yOffset, fgCol, buffer);
                    else
                        gfx_drawPixel(x + xOffset, y + yOffset, bgCol, buffer);
                }
                bitMask >>= 1;
            }
        }

        ++currChar;
    }
}

<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * 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 _CFSTRINGUTILITIES_HXX_
#define _CFSTRINGUTILITIES_HXX_

#include <premac.h>
#include <Carbon/Carbon.h>
#include <Cocoa/Cocoa.h>
#include <postmac.h>
#include <rtl/ustring.hxx>
#include <sal/types.h>
#include <osl/diagnose.h>

enum InfoType {
    FULLPATH,
    FILENAME,
    PATHWITHOUTLASTCOMPONENT
};

rtl::OUString CFStringToOUString(const CFStringRef sOrig);
rtl::OUString FSRefToOUString(FSRef fsRef, InfoType info = FULLPATH);
rtl::OUString CFURLRefToOUString(CFURLRef aUrlRef, InfoType info);
CFStringRef CFStringCreateWithOUString(const rtl::OUString& aString);

//debug utils
#define PARAMFILLER "\n                    "

inline void DBG_PRINT_ENTRY() {
    OSL_TRACE(">>> %s", __func__);
}

inline void DBG_PRINT_ENTRY(const char * classname, const char * methodname) {
    OSL_TRACE(">>> %s::%s", classname, methodname);
}

inline void DBG_PRINT_ENTRY(const char * classname, const char * methodname, const char* param1, const char* value1) {
    OSL_TRACE(">>> %s::%s%s%s = %s", classname, methodname, PARAMFILLER, param1, value1);
}

inline void DBG_PRINT_ENTRY(const char * classname, const char * methodname, const char* param1, const rtl::OUString& value1) {
    OSL_TRACE(">>> %s::%s%s%s = %s", classname, methodname, PARAMFILLER, param1, OUStringToOString(value1, RTL_TEXTENCODING_UTF8).getStr());
}

inline void DBG_PRINT_ENTRY(const char * classname, const char * methodname, const char* param1, const CFStringRef value1) {
    OSL_TRACE(">>> %s::%s%s%s =", classname, methodname, PARAMFILLER, param1);
#if OSL_DEBUG_LEVEL > 1
    CFShow(value1);
#endif
}

inline void DBG_PRINT_ENTRY(const char * classname, const char * methodname, const char* param1, const NSString* value1) {
    OSL_TRACE(">>> %s::%s%s%s =", classname, methodname, PARAMFILLER, param1);
#if OSL_DEBUG_LEVEL > 1
    NSLog(value1);
#endif
}

inline void DBG_PRINT_ENTRY(const char * classname, const char * methodname, const char* param1, const int value1) {
    OSL_TRACE(">>> %s::%s%s%s = %d", classname, methodname, PARAMFILLER, param1, value1);
}

inline void DBG_PRINT_ENTRY(const char * classname, const char * methodname, const char* param1, const char* value1, const char* param2, const int value2) {
    OSL_TRACE(">>> %s::%s%s%s = %s%s%s = %d", classname, methodname, PARAMFILLER, param1, value1, PARAMFILLER, param2, value2);
}

inline void DBG_PRINT_ENTRY(const char * classname, const char * methodname, const char* param1, const char* value1, const char* param2, const char* value2) {
    OSL_TRACE(">>> %s::%s%s%s = %s%s%s = %s", classname, methodname, PARAMFILLER, param1, value1, PARAMFILLER, param2, value2);
}

inline void DBG_PRINT_ENTRY(const char * classname, const char * methodname, const char* param1, const int value1, const char* param2, const int value2) {
    OSL_TRACE(">>> %s::%s%s%s = %d%s%s = %d", classname, methodname, PARAMFILLER, param1, value1, PARAMFILLER, param2, value2);
}

inline void DBG_PRINT_ENTRY(const char * classname, const char * methodname, const char* param1, const int value1, const char* param2, const char* value2) {
    OSL_TRACE(">>> %s::%s%s%s = %d%s%s = %s", classname, methodname, PARAMFILLER, param1, value1, PARAMFILLER, param2, value2);
}

inline void DBG_PRINT_ENTRY(const char * classname, const char * methodname, const char* param1, const int value1, const char* param2, const CFStringRef value2) {
    OSL_TRACE(">>> %s::%s%s%s = %d%s%s =", classname, methodname, PARAMFILLER, param1, value1, PARAMFILLER, param2, value2);
#if OSL_DEBUG_LEVEL > 1
    CFShow(value2);
#endif
}

inline void DBG_PRINT_ENTRY(const char * classname, const char * methodname, const char* param1, const int value1, const char* param2, const NSString* value2) {
    OSL_TRACE(">>> %s::%s%s%s = %d%s%s =", classname, methodname, PARAMFILLER, param1, value1, PARAMFILLER, param2, value2);
#if OSL_DEBUG_LEVEL > 1
    NSLog(value2);
#endif
}

inline void DBG_PRINT_ENTRY(const char * classname, const char * methodname, const char* param1, const rtl::OUString& value1, const char* param2, const rtl::OUString& value2) {
    OSL_TRACE(">>> %s::%s%s%s = %s%s%s = %s", classname, methodname, PARAMFILLER, param1, OUStringToOString(value1, RTL_TEXTENCODING_UTF8).getStr(), PARAMFILLER, param2, OUStringToOString(value2, RTL_TEXTENCODING_UTF8).getStr());
}

inline void DBG_PRINT_ENTRY(const char * classname, const char * methodname, const char* param1, const rtl::OUString& value1, const char* param2, const int value2) {
    OSL_TRACE(">>> %s::%s%s%s = %s%s%s = %d", classname, methodname, PARAMFILLER, param1, OUStringToOString(value1, RTL_TEXTENCODING_UTF8).getStr(), PARAMFILLER, param2, value2);
}

//exit method debugs

inline void DBG_PRINT_EXIT() {
    OSL_TRACE("<<< %s", __func__);
}

inline void DBG_PRINT_EXIT(const char * classname, const char * methodname) {
    OSL_TRACE("<<< %s::%s", classname, methodname);
}

inline void DBG_PRINT_EXIT(const char * classname, const char * methodname, const char* retVal) {
    OSL_TRACE("<<< %s::%s%sreturnValue = %s", classname, methodname, PARAMFILLER, retVal);
}

inline void DBG_PRINT_EXIT(const char * classname, const char * methodname, int retVal) {
    OSL_TRACE("<<< %s::%s%sreturnValue = %d", classname, methodname, PARAMFILLER, retVal);
}

inline void DBG_PRINT_EXIT(const char * classname, const char * methodname, const CFStringRef retVal) {
    OSL_TRACE("<<< %s::%s%sreturnValue = ", classname, methodname, PARAMFILLER);
#if OSL_DEBUG_LEVEL > 1
    CFShow(retVal);
#endif
}

inline void DBG_PRINT_EXIT(const char * classname, const char * methodname, const NSString* retVal) {
    OSL_TRACE("<<< %s::%s%sreturnValue = ", classname, methodname, PARAMFILLER);
#if OSL_DEBUG_LEVEL > 1
    NSLog(retVal);
#endif
}

inline void DBG_PRINT_EXIT(const char * classname, const char * methodname, const rtl::OUString& retVal) {
    OSL_TRACE("<<< %s::%s%sreturnValue = %s", classname, methodname, PARAMFILLER, OUStringToOString(retVal, RTL_TEXTENCODING_UTF8).getStr());
}

#endif //_CFSTRINGUTILITIES_HXX_

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>WaE: unused variables<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * 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 _CFSTRINGUTILITIES_HXX_
#define _CFSTRINGUTILITIES_HXX_

#include <premac.h>
#include <Carbon/Carbon.h>
#include <Cocoa/Cocoa.h>
#include <postmac.h>
#include <rtl/ustring.hxx>
#include <sal/types.h>
#include <osl/diagnose.h>

enum InfoType {
    FULLPATH,
    FILENAME,
    PATHWITHOUTLASTCOMPONENT
};

rtl::OUString CFStringToOUString(const CFStringRef sOrig);
rtl::OUString FSRefToOUString(FSRef fsRef, InfoType info = FULLPATH);
rtl::OUString CFURLRefToOUString(CFURLRef aUrlRef, InfoType info);
CFStringRef CFStringCreateWithOUString(const rtl::OUString& aString);

//debug utils
#define PARAMFILLER "\n                    "

inline void DBG_PRINT_ENTRY() {
    OSL_TRACE(">>> %s", __func__);
}

inline void DBG_PRINT_ENTRY(const char * classname, const char * methodname) {
    OSL_TRACE(">>> %s::%s", classname, methodname);
}

inline void DBG_PRINT_ENTRY(const char * classname, const char * methodname, const char* param1, const char* value1) {
    OSL_TRACE(">>> %s::%s%s%s = %s", classname, methodname, PARAMFILLER, param1, value1);
}

inline void DBG_PRINT_ENTRY(const char * classname, const char * methodname, const char* param1, const rtl::OUString& value1) {
    OSL_TRACE(">>> %s::%s%s%s = %s", classname, methodname, PARAMFILLER, param1, OUStringToOString(value1, RTL_TEXTENCODING_UTF8).getStr());
}

inline void DBG_PRINT_ENTRY(const char * classname, const char * methodname, const char* param1, const CFStringRef value1) {
    OSL_TRACE(">>> %s::%s%s%s =", classname, methodname, PARAMFILLER, param1);
#if OSL_DEBUG_LEVEL > 1
    CFShow(value1);
#else
    (void)value1;
#endif
}

inline void DBG_PRINT_ENTRY(const char * classname, const char * methodname, const char* param1, const NSString* value1) {
    OSL_TRACE(">>> %s::%s%s%s =", classname, methodname, PARAMFILLER, param1);
#if OSL_DEBUG_LEVEL > 1
    NSLog(value1);
#else
    (void)value1;
#endif
}

inline void DBG_PRINT_ENTRY(const char * classname, const char * methodname, const char* param1, const int value1) {
    OSL_TRACE(">>> %s::%s%s%s = %d", classname, methodname, PARAMFILLER, param1, value1);
}

inline void DBG_PRINT_ENTRY(const char * classname, const char * methodname, const char* param1, const char* value1, const char* param2, const int value2) {
    OSL_TRACE(">>> %s::%s%s%s = %s%s%s = %d", classname, methodname, PARAMFILLER, param1, value1, PARAMFILLER, param2, value2);
}

inline void DBG_PRINT_ENTRY(const char * classname, const char * methodname, const char* param1, const char* value1, const char* param2, const char* value2) {
    OSL_TRACE(">>> %s::%s%s%s = %s%s%s = %s", classname, methodname, PARAMFILLER, param1, value1, PARAMFILLER, param2, value2);
}

inline void DBG_PRINT_ENTRY(const char * classname, const char * methodname, const char* param1, const int value1, const char* param2, const int value2) {
    OSL_TRACE(">>> %s::%s%s%s = %d%s%s = %d", classname, methodname, PARAMFILLER, param1, value1, PARAMFILLER, param2, value2);
}

inline void DBG_PRINT_ENTRY(const char * classname, const char * methodname, const char* param1, const int value1, const char* param2, const char* value2) {
    OSL_TRACE(">>> %s::%s%s%s = %d%s%s = %s", classname, methodname, PARAMFILLER, param1, value1, PARAMFILLER, param2, value2);
}

inline void DBG_PRINT_ENTRY(const char * classname, const char * methodname, const char* param1, const int value1, const char* param2, const CFStringRef value2) {
    OSL_TRACE(">>> %s::%s%s%s = %d%s%s =", classname, methodname, PARAMFILLER, param1, value1, PARAMFILLER, param2, value2);
#if OSL_DEBUG_LEVEL > 1
    CFShow(value2);
#endif
}

inline void DBG_PRINT_ENTRY(const char * classname, const char * methodname, const char* param1, const int value1, const char* param2, const NSString* value2) {
    OSL_TRACE(">>> %s::%s%s%s = %d%s%s =", classname, methodname, PARAMFILLER, param1, value1, PARAMFILLER, param2, value2);
#if OSL_DEBUG_LEVEL > 1
    NSLog(value2);
#endif
}

inline void DBG_PRINT_ENTRY(const char * classname, const char * methodname, const char* param1, const rtl::OUString& value1, const char* param2, const rtl::OUString& value2) {
    OSL_TRACE(">>> %s::%s%s%s = %s%s%s = %s", classname, methodname, PARAMFILLER, param1, OUStringToOString(value1, RTL_TEXTENCODING_UTF8).getStr(), PARAMFILLER, param2, OUStringToOString(value2, RTL_TEXTENCODING_UTF8).getStr());
}

inline void DBG_PRINT_ENTRY(const char * classname, const char * methodname, const char* param1, const rtl::OUString& value1, const char* param2, const int value2) {
    OSL_TRACE(">>> %s::%s%s%s = %s%s%s = %d", classname, methodname, PARAMFILLER, param1, OUStringToOString(value1, RTL_TEXTENCODING_UTF8).getStr(), PARAMFILLER, param2, value2);
}

//exit method debugs

inline void DBG_PRINT_EXIT() {
    OSL_TRACE("<<< %s", __func__);
}

inline void DBG_PRINT_EXIT(const char * classname, const char * methodname) {
    OSL_TRACE("<<< %s::%s", classname, methodname);
}

inline void DBG_PRINT_EXIT(const char * classname, const char * methodname, const char* retVal) {
    OSL_TRACE("<<< %s::%s%sreturnValue = %s", classname, methodname, PARAMFILLER, retVal);
}

inline void DBG_PRINT_EXIT(const char * classname, const char * methodname, int retVal) {
    OSL_TRACE("<<< %s::%s%sreturnValue = %d", classname, methodname, PARAMFILLER, retVal);
}

inline void DBG_PRINT_EXIT(const char * classname, const char * methodname, const CFStringRef retVal) {
    OSL_TRACE("<<< %s::%s%sreturnValue = ", classname, methodname, PARAMFILLER);
#if OSL_DEBUG_LEVEL > 1
    CFShow(retVal);
#else
    (void)retVal;
#endif
}

inline void DBG_PRINT_EXIT(const char * classname, const char * methodname, const NSString* retVal) {
    OSL_TRACE("<<< %s::%s%sreturnValue = ", classname, methodname, PARAMFILLER);
#if OSL_DEBUG_LEVEL > 1
    NSLog(retVal);
#else
    (void)retVal;
#endif
}

inline void DBG_PRINT_EXIT(const char * classname, const char * methodname, const rtl::OUString& retVal) {
    OSL_TRACE("<<< %s::%s%sreturnValue = %s", classname, methodname, PARAMFILLER, OUStringToOString(retVal, RTL_TEXTENCODING_UTF8).getStr());
}

#endif //_CFSTRINGUTILITIES_HXX_

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<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: SalGtkPicker.cxx,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.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_fpicker.hxx"

//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------
#include <com/sun/star/lang/DisposedException.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/uri/XExternalUriReferenceTranslator.hpp>
#include <comphelper/processfactory.hxx>
#include <cppuhelper/interfacecontainer.h>
#include <osl/diagnose.h>
#include <com/sun/star/uno/Any.hxx>
#include <FPServiceInfo.hxx>
#include <vos/mutex.hxx>
#include <vcl/svapp.hxx>
#ifndef _SALGTKPICKER_HXX_
#include "SalGtkPicker.hxx"
#endif
#include <tools/urlobj.hxx>
#include <stdio.h>

//------------------------------------------------------------------------
// namespace directives
//------------------------------------------------------------------------

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::uno;

rtl::OUString SalGtkPicker::uritounicode(const gchar* pIn)
{
    rtl::OUString sURL( const_cast<const sal_Char *>(pIn), strlen(pIn),
        RTL_TEXTENCODING_UTF8 );

    INetURLObject aURL(sURL);
    if (INET_PROT_FILE == aURL.GetProtocol())
    {
        gchar *pEncodedFileName = g_filename_from_uri(pIn, NULL, NULL);
        if ( pEncodedFileName )
        {
            rtl::OUString sEncoded(pEncodedFileName, strlen(pEncodedFileName),
                osl_getThreadTextEncoding());
            INetURLObject aCurrentURL(sEncoded, INetURLObject::FSYS_UNX);
            aCurrentURL.SetHost(aURL.GetHost());
            sURL = aCurrentURL.getExternalURL();
        }
        else
        {
            OUString aNewURL = Reference<uri::XExternalUriReferenceTranslator>(Reference<XMultiServiceFactory>(comphelper::getProcessServiceFactory(), UNO_QUERY_THROW)->createInstance(OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.uri.ExternalUriReferenceTranslator"))), UNO_QUERY_THROW)->translateToInternal(sURL);
            if( aNewURL.getLength() )
                sURL = aNewURL;
        }
    }
    return sURL;
}

rtl::OString SalGtkPicker::unicodetouri(const rtl::OUString &rURL)
{
    OString sURL = OUStringToOString(rURL, RTL_TEXTENCODING_UTF8);
    INetURLObject aURL(rURL);
    if (INET_PROT_FILE == aURL.GetProtocol())
    {
        rtl::OUString sOUURL = aURL.getExternalURL(INetURLObject::DECODE_WITH_CHARSET, osl_getThreadTextEncoding());
        sURL = OUStringToOString( sOUURL, osl_getThreadTextEncoding());
    }
    return sURL;
}

gboolean rundialog(RunDialog *pDialog)
{
    pDialog->run();
    return false;
}

void RunDialog::run()
{
    mnStatus = gtk_dialog_run( GTK_DIALOG( m_pDialog ) );
    if (mnStatus != 1)  //PLAY
        gtk_widget_hide( m_pDialog );

    maLock.acquire();
    mbFinished = true;
    maLock.release();

    Application::EndYield();
}

gint RunDialog::runandwaitforresult()
{
    g_timeout_add_full(G_PRIORITY_HIGH_IDLE, 0, (GSourceFunc)rundialog, this, NULL);
    while (1)
    {
    maLock.acquire();
        if (mbFinished)
            break;
    maLock.release();
        Application::Yield();
    }
    return mnStatus;
}

SalGtkPicker::~SalGtkPicker()
{
    if (m_pDialog)
        gtk_widget_destroy(m_pDialog);
}

void SAL_CALL SalGtkPicker::implsetDisplayDirectory( const rtl::OUString& aDirectory )
    throw( lang::IllegalArgumentException, uno::RuntimeException )
{
    OSL_ASSERT( m_pDialog != NULL );
    ::vos::OGuard aGuard( Application::GetSolarMutex() );

    OString aTxt = unicodetouri(aDirectory);

    if( aTxt.lastIndexOf('/') == aTxt.getLength() - 1 )
        aTxt = aTxt.copy( 0, aTxt.getLength() - 1 );

    OSL_TRACE( "setting path to %s\n", aTxt.getStr() );

    gtk_file_chooser_set_current_folder_uri( GTK_FILE_CHOOSER( m_pDialog ),
                         aTxt.getStr() );
}

rtl::OUString SAL_CALL SalGtkPicker::implgetDisplayDirectory() throw( uno::RuntimeException )
{
    OSL_ASSERT( m_pDialog != NULL );
    ::vos::OGuard aGuard( Application::GetSolarMutex() );

    gchar* pCurrentFolder =
        gtk_file_chooser_get_current_folder_uri( GTK_FILE_CHOOSER( m_pDialog ) );
    ::rtl::OUString aCurrentFolderName = uritounicode(pCurrentFolder);
    g_free( pCurrentFolder );

    return aCurrentFolderName;
}

void SAL_CALL SalGtkPicker::implsetTitle( const rtl::OUString& aTitle ) throw( uno::RuntimeException )
{
    OSL_ASSERT( m_pDialog != NULL );
    ::vos::OGuard aGuard( Application::GetSolarMutex() );

    ::rtl::OString aWindowTitle = OUStringToOString( aTitle, RTL_TEXTENCODING_UTF8 );
    gtk_window_set_title( GTK_WINDOW( m_pDialog ), aWindowTitle.getStr() );
}
<commit_msg>INTEGRATION: CWS vcl88 (1.15.18); FILE MERGED 2008/04/17 05:49:53 pl 1.15.18.2: RESYNC: (1.15-1.16); FILE MERGED 2008/04/15 15:04:43 pl 1.15.18.1: #i87991# catch NULL ptr (thanks cmc)<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: SalGtkPicker.cxx,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.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_fpicker.hxx"

//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------
#include <com/sun/star/lang/DisposedException.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/uri/XExternalUriReferenceTranslator.hpp>
#include <comphelper/processfactory.hxx>
#include <cppuhelper/interfacecontainer.h>
#include <osl/diagnose.h>
#include <com/sun/star/uno/Any.hxx>
#include <FPServiceInfo.hxx>
#include <vos/mutex.hxx>
#include <vcl/svapp.hxx>
#ifndef _SALGTKPICKER_HXX_
#include "SalGtkPicker.hxx"
#endif
#include <tools/urlobj.hxx>
#include <stdio.h>

//------------------------------------------------------------------------
// namespace directives
//------------------------------------------------------------------------

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::uno;

rtl::OUString SalGtkPicker::uritounicode(const gchar* pIn)
{
    if (!pIn)
        return rtl::OUString();

    rtl::OUString sURL( const_cast<const sal_Char *>(pIn), strlen(pIn),
        RTL_TEXTENCODING_UTF8 );

    INetURLObject aURL(sURL);
    if (INET_PROT_FILE == aURL.GetProtocol())
    {
        gchar *pEncodedFileName = g_filename_from_uri(pIn, NULL, NULL);
        if ( pEncodedFileName )
        {
            rtl::OUString sEncoded(pEncodedFileName, strlen(pEncodedFileName),
                osl_getThreadTextEncoding());
            INetURLObject aCurrentURL(sEncoded, INetURLObject::FSYS_UNX);
            aCurrentURL.SetHost(aURL.GetHost());
            sURL = aCurrentURL.getExternalURL();
        }
        else
        {
            OUString aNewURL = Reference<uri::XExternalUriReferenceTranslator>(Reference<XMultiServiceFactory>(comphelper::getProcessServiceFactory(), UNO_QUERY_THROW)->createInstance(OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.uri.ExternalUriReferenceTranslator"))), UNO_QUERY_THROW)->translateToInternal(sURL);
            if( aNewURL.getLength() )
                sURL = aNewURL;
        }
    }
    return sURL;
}

rtl::OString SalGtkPicker::unicodetouri(const rtl::OUString &rURL)
{
    OString sURL = OUStringToOString(rURL, RTL_TEXTENCODING_UTF8);
    INetURLObject aURL(rURL);
    if (INET_PROT_FILE == aURL.GetProtocol())
    {
        rtl::OUString sOUURL = aURL.getExternalURL(INetURLObject::DECODE_WITH_CHARSET, osl_getThreadTextEncoding());
        sURL = OUStringToOString( sOUURL, osl_getThreadTextEncoding());
    }
    return sURL;
}

gboolean rundialog(RunDialog *pDialog)
{
    pDialog->run();
    return false;
}

void RunDialog::run()
{
    mnStatus = gtk_dialog_run( GTK_DIALOG( m_pDialog ) );
    if (mnStatus != 1)  //PLAY
        gtk_widget_hide( m_pDialog );

    maLock.acquire();
    mbFinished = true;
    maLock.release();

    Application::EndYield();
}

gint RunDialog::runandwaitforresult()
{
    g_timeout_add_full(G_PRIORITY_HIGH_IDLE, 0, (GSourceFunc)rundialog, this, NULL);
    while (1)
    {
    maLock.acquire();
        if (mbFinished)
            break;
    maLock.release();
        Application::Yield();
    }
    return mnStatus;
}

SalGtkPicker::~SalGtkPicker()
{
    if (m_pDialog)
        gtk_widget_destroy(m_pDialog);
}

void SAL_CALL SalGtkPicker::implsetDisplayDirectory( const rtl::OUString& aDirectory )
    throw( lang::IllegalArgumentException, uno::RuntimeException )
{
    OSL_ASSERT( m_pDialog != NULL );
    ::vos::OGuard aGuard( Application::GetSolarMutex() );

    OString aTxt = unicodetouri(aDirectory);

    if( aTxt.lastIndexOf('/') == aTxt.getLength() - 1 )
        aTxt = aTxt.copy( 0, aTxt.getLength() - 1 );

    OSL_TRACE( "setting path to %s\n", aTxt.getStr() );

    gtk_file_chooser_set_current_folder_uri( GTK_FILE_CHOOSER( m_pDialog ),
                         aTxt.getStr() );
}

rtl::OUString SAL_CALL SalGtkPicker::implgetDisplayDirectory() throw( uno::RuntimeException )
{
    OSL_ASSERT( m_pDialog != NULL );
    ::vos::OGuard aGuard( Application::GetSolarMutex() );

    gchar* pCurrentFolder =
        gtk_file_chooser_get_current_folder_uri( GTK_FILE_CHOOSER( m_pDialog ) );
    ::rtl::OUString aCurrentFolderName = uritounicode(pCurrentFolder);
    g_free( pCurrentFolder );

    return aCurrentFolderName;
}

void SAL_CALL SalGtkPicker::implsetTitle( const rtl::OUString& aTitle ) throw( uno::RuntimeException )
{
    OSL_ASSERT( m_pDialog != NULL );
    ::vos::OGuard aGuard( Application::GetSolarMutex() );

    ::rtl::OString aWindowTitle = OUStringToOString( aTitle, RTL_TEXTENCODING_UTF8 );
    gtk_window_set_title( GTK_WINDOW( m_pDialog ), aWindowTitle.getStr() );
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: SalGtkPicker.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2005-05-03 13:48:40 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): Anil Bhatia
 *
 *
 ************************************************************************/

#ifndef _SALGTKFPICKER_HXX_
#define _SALGTKFPICKER_HXX_

//_____________________________________________________________________________
//  includes of other projects
//_____________________________________________________________________________

#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif

#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKER_HPP_
#include <com/sun/star/ui/dialogs/XFilePicker.hpp>
#endif

#ifndef _COM_SUN_STAR_UI_XFOLDERPICKER_HPP_
#include <com/sun/star/ui/dialogs/XFolderPicker.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif

#ifndef _COM_SUN_STAR_UTIL_XCANCELLABLE_HPP_
#include <com/sun/star/util/XCancellable.hpp>
#endif

#include <gtk/gtk.h>
#include <gdk/gdkkeysyms.h>

//----------------------------------------------------------
// class declaration
//----------------------------------------------------------

class SalGtkPicker
{
    public:
        SalGtkPicker() : m_pDialog(0) {}
        virtual ~SalGtkPicker();
    protected:
        osl::Mutex m_rbHelperMtx;
        GtkWidget  *m_pDialog;
    protected:
        virtual void SAL_CALL implsetTitle( const ::rtl::OUString& aTitle )
            throw( ::com::sun::star::uno::RuntimeException );

        virtual void SAL_CALL implsetDisplayDirectory( const rtl::OUString& rDirectory )
            throw( com::sun::star::lang::IllegalArgumentException, com::sun::star::uno::RuntimeException );

        virtual rtl::OUString SAL_CALL implgetDisplayDirectory(  )
            throw( com::sun::star::uno::RuntimeException );
        static rtl::OUString uritounicode(const gchar *pIn);
        static rtl::OString unicodetouri(const rtl::OUString &rURL);
};

class RunDialog
{
private:
    bool bFinished;
    gint mnStatus;
    GtkWidget *m_pDialog;
public:
    void run();
    RunDialog(GtkWidget *pDialog) : bFinished(false), m_pDialog(pDialog) { }
    gint runandwaitforresult();
};

#endif
<commit_msg>INTEGRATION: CWS fpicker4 (1.4.8); FILE MERGED 2005/06/01 11:05:22 cmc 1.4.8.1: #i44627# UnYield and lock variable<commit_after>/*************************************************************************
 *
 *  $RCSfile: SalGtkPicker.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: kz $ $Date: 2005-07-12 11:59:39 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): Anil Bhatia
 *
 *
 ************************************************************************/

#ifndef _SALGTKFPICKER_HXX_
#define _SALGTKFPICKER_HXX_

//_____________________________________________________________________________
//  includes of other projects
//_____________________________________________________________________________

#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif

#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKER_HPP_
#include <com/sun/star/ui/dialogs/XFilePicker.hpp>
#endif

#ifndef _COM_SUN_STAR_UI_XFOLDERPICKER_HPP_
#include <com/sun/star/ui/dialogs/XFolderPicker.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif

#ifndef _COM_SUN_STAR_UTIL_XCANCELLABLE_HPP_
#include <com/sun/star/util/XCancellable.hpp>
#endif

#include <gtk/gtk.h>
#include <gdk/gdkkeysyms.h>

//----------------------------------------------------------
// class declaration
//----------------------------------------------------------

class SalGtkPicker
{
    public:
        SalGtkPicker() : m_pDialog(0) {}
        virtual ~SalGtkPicker();
    protected:
        osl::Mutex m_rbHelperMtx;
        GtkWidget  *m_pDialog;
    protected:
        virtual void SAL_CALL implsetTitle( const ::rtl::OUString& aTitle )
            throw( ::com::sun::star::uno::RuntimeException );

        virtual void SAL_CALL implsetDisplayDirectory( const rtl::OUString& rDirectory )
            throw( com::sun::star::lang::IllegalArgumentException, com::sun::star::uno::RuntimeException );

        virtual rtl::OUString SAL_CALL implgetDisplayDirectory(  )
            throw( com::sun::star::uno::RuntimeException );
        static rtl::OUString uritounicode(const gchar *pIn);
        static rtl::OString unicodetouri(const rtl::OUString &rURL);
};

class RunDialog
{
private:
    bool mbFinished;
    osl::Mutex maLock;
    gint mnStatus;
    GtkWidget *m_pDialog;
public:
    void run();
    RunDialog(GtkWidget *pDialog) : mbFinished(false), m_pDialog(pDialog) { }
    gint runandwaitforresult();
};

#endif
<|endoftext|>


<commit_before>
#include <string>
#include <iostream>

#include <openvoronoi/medial_axis.hpp>
#include <openvoronoi/voronoidiagram.hpp>
#include <openvoronoi/polygon_interior.hpp>
#include <openvoronoi/utility/vd2svg.hpp>
#include <openvoronoi/version.hpp>

// very simple OpenVoronoi example program
int main() {
    ovd::VoronoiDiagram* vd = new ovd::VoronoiDiagram(1,100); // (r, bins)
    // double r: radius of circle within which all input geometry must fall. use 1 (unit-circle). Scale geometry if necessary.
    // int bins:  bins for face-grid search. roughly sqrt(n), where n is the number of sites is good according to Held.

    std::cout << ovd::version() << "\n"; // the git revision-string
    ovd::Point p0(-0.1,-0.2);
    ovd::Point p1(0.2,0.1);
    ovd::Point p2(0.4,0.2);
    ovd::Point p3(0.6,0.6);
    ovd::Point p4(-0.6,0.3);

    int id0 = vd->insert_point_site(p0);
    int id1 = vd->insert_point_site(p1);
    int id2 = vd->insert_point_site(p2);
    int id3 = vd->insert_point_site(p3);
    int id4 = vd->insert_point_site(p4);

    vd->insert_line_site(id0, id1);
    vd->insert_line_site(id1, id2);
    vd->insert_line_site(id2, id3);
    vd->insert_line_site(id3, id4);
    vd->insert_line_site(id4, id0);
    vd->check();

    ovd::HEGraph& g = vd->get_graph_reference();
    // try commenting-out the line below; massive exterior clearance discs will
    // be drawn!
    ovd::PolygonInterior pi(g, true);
    ovd::MedialAxis ma(g);

    // save drawing to svg file.
    svg::Dimensions dimensions(1024, 1024);
    svg::Document doc("basic_offset.svg", svg::Layout(dimensions, svg::Layout::BottomLeft));
    BOOST_FOREACH( ovd::HEEdge e, g.edges() ) {
        if( g[e].valid ) write_edge_to_svd(g,doc,e);
    }

    // walk the medial axis.
    ovd::MedialAxisWalk maw(g);
    ovd::MedialChainList chain_list = maw.walk();
    std::cout << "walking " << int(chain_list.size()) << " medial axis chains." << std::endl;
    BOOST_FOREACH( ovd::MedialChain chain, chain_list ) { // loop through each chain
        std::cout << "new chain length:" << int(chain.size()) << std::endl;
        BOOST_FOREACH( ovd::MedialPointList pt_list, chain ) { //loop through each medial-point list
            std::cout << "new point list length:" << int(pt_list.size()) << std::endl;
            BOOST_FOREACH( ovd::MedialPoint pt, pt_list ) { //loop through each medial-point
                std::cout << "pt:p:" << pt.p << ", clearance_radius:" << pt.clearance_radius << std::endl;
                if (pt.clearance_radius < 0.001) {
                    std::cout << "(the clearance radius is so small that the rendered circle will be too tiny to see.)" << std::endl;
                }
                ovd::Point ctr( scale( pt.p ) );
                double radius( scale( pt.clearance_radius ) );
                svg::Circle clearance_disc( svg::Point( ctr.x, ctr.y ), 2*radius, svg::Fill(), svg::Stroke( 1, svg::Color::Red ) );
                doc << clearance_disc;
            }
        }
    }

    doc.save();
    std::cout << vd->print();
    delete vd;

    return 0;
}
<commit_msg>add some comments. change filename of svg output.<commit_after>
#include <string>
#include <iostream>

#include <openvoronoi/medial_axis.hpp>
#include <openvoronoi/voronoidiagram.hpp>
#include <openvoronoi/polygon_interior.hpp>
#include <openvoronoi/utility/vd2svg.hpp>
#include <openvoronoi/version.hpp>

// OpenVoronoi example program. Uses MedialAxis filter to filter the complete Voronoi diagram
// down to the medial axis.
// then uses MedialAxisWalk to walk along the medial axis and draw clearance-disks
int main() {
    ovd::VoronoiDiagram* vd = new ovd::VoronoiDiagram(1,100); // (r, bins)
    // double r: radius of circle within which all input geometry must fall. use 1 (unit-circle). Scale geometry if necessary.
    // int bins:  bins for face-grid search. roughly sqrt(n), where n is the number of sites is good according to Held.

    std::cout << ovd::version() << "\n"; // the git revision-string
    ovd::Point p0(-0.1,-0.2);
    ovd::Point p1(0.2,0.1);
    ovd::Point p2(0.4,0.2);
    ovd::Point p3(0.6,0.6);
    ovd::Point p4(-0.6,0.3);

    int id0 = vd->insert_point_site(p0);
    int id1 = vd->insert_point_site(p1);
    int id2 = vd->insert_point_site(p2);
    int id3 = vd->insert_point_site(p3);
    int id4 = vd->insert_point_site(p4);

    vd->insert_line_site(id0, id1);
    vd->insert_line_site(id1, id2);
    vd->insert_line_site(id2, id3);
    vd->insert_line_site(id3, id4);
    vd->insert_line_site(id4, id0);
    vd->check();

    ovd::HEGraph& g = vd->get_graph_reference();
    // try commenting-out the line below; massive exterior clearance discs will
    // be drawn!
    ovd::PolygonInterior pi(g, true);
    ovd::MedialAxis ma(g);

    // save drawing to svg file.
    svg::Dimensions dimensions(1024, 1024);
    svg::Document doc("medial_axis.svg", svg::Layout(dimensions, svg::Layout::BottomLeft));
    BOOST_FOREACH( ovd::HEEdge e, g.edges() ) {
        if( g[e].valid ) write_edge_to_svd(g,doc,e);
    }

    // walk the medial axis.
    ovd::MedialAxisWalk maw(g);
    ovd::MedialChainList chain_list = maw.walk();
    std::cout << "walking " << int(chain_list.size()) << " medial axis chains." << std::endl;
    BOOST_FOREACH( ovd::MedialChain chain, chain_list ) { // loop through each chain
        std::cout << "new chain length:" << int(chain.size()) << std::endl;
        BOOST_FOREACH( ovd::MedialPointList pt_list, chain ) { //loop through each medial-point list
            std::cout << "new point list length:" << int(pt_list.size()) << std::endl;
            BOOST_FOREACH( ovd::MedialPoint pt, pt_list ) { //loop through each medial-point
                std::cout << "pt:p:" << pt.p << ", clearance_radius:" << pt.clearance_radius << std::endl;
                if (pt.clearance_radius < 0.001) {
                    std::cout << "(the clearance radius is so small that the rendered circle will be too tiny to see.)" << std::endl;
                }
                ovd::Point ctr( scale( pt.p ) );
                double radius( scale( pt.clearance_radius ) );
                // draw a circle, centered on the medial-axis, with radius = clearance-disc
                svg::Circle clearance_disc( svg::Point( ctr.x, ctr.y ), 2*radius, svg::Fill(), svg::Stroke( 1, svg::Color::Red ) );
                doc << clearance_disc;
            }
        }
    }

    doc.save();
    std::cout << vd->print();
    delete vd;

    return 0;
}
<|endoftext|>


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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_cppcanvas.hxx"

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _BGFX_MATRIX_B2DHOMMATRIX_HXX
#include <basegfx/matrix/b2dhommatrix.hxx>
#endif
#ifndef _BGFX_POLYGON_B2DPOLYPOLYGON_HXX
#include <basegfx/polygon/b2dpolypolygon.hxx>
#endif
#ifndef _BGFX_TOOLS_CANVASTOOLS_HXX
#include <basegfx/tools/canvastools.hxx>
#endif

#ifndef _COM_SUN_STAR_RENDERING_XCANVAS_HPP_
#include <com/sun/star/rendering/XCanvas.hpp>
#endif

#include <canvas/canvastools.hxx>

#include <cppcanvas/polypolygon.hxx>
#include <implfont.hxx>
#include <implcolor.hxx>

#include <implcanvas.hxx>

using namespace ::com::sun::star;

namespace cppcanvas
{
    namespace internal
    {

        ImplCanvas::ImplCanvas( const uno::Reference< rendering::XCanvas >& xCanvas ) :
            maViewState(),
            maClipPolyPolygon(),
            mxCanvas( xCanvas )
        {
            OSL_ENSURE( mxCanvas.is(), "Canvas::Canvas() invalid XCanvas" );

            ::canvas::tools::initViewState( maViewState );
        }

        ImplCanvas::~ImplCanvas()
        {
        }

        void ImplCanvas::setTransformation( const ::basegfx::B2DHomMatrix& rMatrix )
        {
            ::canvas::tools::setViewStateTransform( maViewState, rMatrix );
        }

        ::basegfx::B2DHomMatrix ImplCanvas::getTransformation() const
        {
            ::basegfx::B2DHomMatrix aMatrix;
            return ::canvas::tools::getViewStateTransform( aMatrix,
                                                           maViewState );
        }

        void ImplCanvas::setClip( const ::basegfx::B2DPolyPolygon& rClipPoly )
        {
            // TODO(T3): not thread-safe. B2DPolyPolygon employs copy-on-write
            maClipPolyPolygon = rClipPoly;
            maViewState.Clip.clear();
        }

        ::basegfx::B2DPolyPolygon ImplCanvas::getClip() const
        {
            return maClipPolyPolygon;
        }

        FontSharedPtr ImplCanvas::createFont( const ::rtl::OUString& rFontName, const double& rCellSize ) const
        {
            return FontSharedPtr( new ImplFont( getUNOCanvas(), rFontName, rCellSize ) );
        }

        ColorSharedPtr ImplCanvas::createColor() const
        {
            return ColorSharedPtr( new ImplColor( getUNOCanvas()->getDevice() ) );
        }

        CanvasSharedPtr ImplCanvas::clone() const
        {
            return CanvasSharedPtr( new ImplCanvas( *this ) );
        }

        uno::Reference< rendering::XCanvas > ImplCanvas::getUNOCanvas() const
        {
            OSL_ENSURE( mxCanvas.is(), "ImplCanvas::getUNOCanvas(): Invalid XCanvas" );

            return mxCanvas;
        }

        rendering::ViewState ImplCanvas::getViewState() const
        {
            if( maClipPolyPolygon.count() && !maViewState.Clip.is() )
            {
                if( !mxCanvas.is() )
                    return maViewState;

                maViewState.Clip = ::basegfx::unotools::xPolyPolygonFromB2DPolyPolygon(
                    mxCanvas->getDevice(),
                    maClipPolyPolygon );
            }

            return maViewState;
        }

    }
}
<commit_msg>INTEGRATION: CWS presfixes12 (1.8.22); FILE MERGED 2007/06/19 11:25:24 thb 1.8.22.4: #i10000# Reversed order, seems that gcc does not handle the safe bool idiom correctly here 2007/06/18 14:33:23 thb 1.8.22.3: #i10000# Avoid boost::optional::get(), which changed semantics after 1.31 (breaks the build for --with-system-boost) 2007/03/08 21:37:07 thb 1.8.22.2: #i37778# Added extra setClip() method to be able to set no clip - setting a clip with zero polygons by definition clips everything 2007/02/20 22:29:30 thb 1.8.22.1: #i37778# Added XCanvas::clear() to all relevant interfaces<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: implcanvas.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: obo $ $Date: 2007-07-17 15:26:44 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_cppcanvas.hxx"

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _BGFX_MATRIX_B2DHOMMATRIX_HXX
#include <basegfx/matrix/b2dhommatrix.hxx>
#endif
#ifndef _BGFX_POLYGON_B2DPOLYPOLYGON_HXX
#include <basegfx/polygon/b2dpolypolygon.hxx>
#endif
#ifndef _BGFX_TOOLS_CANVASTOOLS_HXX
#include <basegfx/tools/canvastools.hxx>
#endif

#ifndef _COM_SUN_STAR_RENDERING_XCANVAS_HPP_
#include <com/sun/star/rendering/XCanvas.hpp>
#endif

#include <canvas/canvastools.hxx>

#include <cppcanvas/polypolygon.hxx>
#include <implfont.hxx>
#include <implcolor.hxx>

#include <implcanvas.hxx>

using namespace ::com::sun::star;

namespace cppcanvas
{
    namespace internal
    {

        ImplCanvas::ImplCanvas( const uno::Reference< rendering::XCanvas >& xCanvas ) :
            maViewState(),
            maClipPolyPolygon(),
            mxCanvas( xCanvas )
        {
            OSL_ENSURE( mxCanvas.is(), "Canvas::Canvas() invalid XCanvas" );

            ::canvas::tools::initViewState( maViewState );
        }

        ImplCanvas::~ImplCanvas()
        {
        }

        void ImplCanvas::setTransformation( const ::basegfx::B2DHomMatrix& rMatrix )
        {
            ::canvas::tools::setViewStateTransform( maViewState, rMatrix );
        }

        ::basegfx::B2DHomMatrix ImplCanvas::getTransformation() const
        {
            ::basegfx::B2DHomMatrix aMatrix;
            return ::canvas::tools::getViewStateTransform( aMatrix,
                                                           maViewState );
        }

        void ImplCanvas::setClip( const ::basegfx::B2DPolyPolygon& rClipPoly )
        {
            // TODO(T3): not thread-safe. B2DPolyPolygon employs copy-on-write
            maClipPolyPolygon.reset( rClipPoly );
            maViewState.Clip.clear();
        }

        void ImplCanvas::setClip()
        {
            maClipPolyPolygon.reset();
            maViewState.Clip.clear();
        }

        ::basegfx::B2DPolyPolygon const* ImplCanvas::getClip() const
        {
            return !maClipPolyPolygon ? NULL : &(*maClipPolyPolygon);
        }

        FontSharedPtr ImplCanvas::createFont( const ::rtl::OUString& rFontName, const double& rCellSize ) const
        {
            return FontSharedPtr( new ImplFont( getUNOCanvas(), rFontName, rCellSize ) );
        }

        ColorSharedPtr ImplCanvas::createColor() const
        {
            return ColorSharedPtr( new ImplColor( getUNOCanvas()->getDevice() ) );
        }

        CanvasSharedPtr ImplCanvas::clone() const
        {
            return CanvasSharedPtr( new ImplCanvas( *this ) );
        }

        void ImplCanvas::clear() const
        {
            OSL_ENSURE( mxCanvas.is(), "ImplCanvas::clear(): Invalid XCanvas" );
            mxCanvas->clear();
        }

        uno::Reference< rendering::XCanvas > ImplCanvas::getUNOCanvas() const
        {
            OSL_ENSURE( mxCanvas.is(), "ImplCanvas::getUNOCanvas(): Invalid XCanvas" );

            return mxCanvas;
        }

        rendering::ViewState ImplCanvas::getViewState() const
        {
            if( maClipPolyPolygon && !maViewState.Clip.is() )
            {
                if( !mxCanvas.is() )
                    return maViewState;

                maViewState.Clip = ::basegfx::unotools::xPolyPolygonFromB2DPolyPolygon(
                    mxCanvas->getDevice(),
                    *maClipPolyPolygon );
            }

            return maViewState;
        }

    }
}
<|endoftext|>