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

#include "webkit/glue/plugins/plugin_list.h"

#include "base/file_util.h"
#include "base/path_service.h"

namespace NPAPI {

void PluginList::PlatformInit() {
}

void PluginList::GetPluginDirectories(std::vector<FilePath>* plugin_dirs) {
  // Mozilla code to reference:
  // http://mxr.mozilla.org/firefox/ident?i=NS_APP_PLUGINS_DIR_LIST
  // and tens of accompanying files (mxr is very helpful).
  // This code carefully matches their behavior for compat reasons.

  // 1) MOZ_PLUGIN_PATH env variable.
  const char* moz_plugin_path = getenv("MOZ_PLUGIN_PATH");
  if (moz_plugin_path)
    plugin_dirs->push_back(FilePath(moz_plugin_path));

  // 2) NS_USER_PLUGINS_DIR: ~/.mozilla/plugins.
  // TODO(evanm): should we do anything here?

  // 3) NS_APP_PLUGINS_DIR: the binary dir + "plugins/".
  FilePath dir;
  PathService::Get(base::DIR_EXE, &dir);
  plugin_dirs->push_back(dir.Append("plugins"));

  // 4) NS_SYSTEM_PLUGINS_DIR:
  // TODO(evanm): when we support 64-bit platforms, we'll need to fix this
  // to be conditional.
  COMPILE_ASSERT(sizeof(int)==4, fix_system_lib_path);
  plugin_dirs->push_back(FilePath("/usr/lib/mozilla/plugins"));
}

void PluginList::LoadPluginsFromDir(const FilePath& path) {
  file_util::FileEnumerator enumerator(path,
                                       false, // not recursive
                                       file_util::FileEnumerator::FILES);
  for (FilePath path = enumerator.Next(); !path.value().empty();
       path = enumerator.Next()) {
    // Skip over Mozilla .xpt files.
    if (!path.MatchesExtension(FILE_PATH_LITERAL(".xpt")))
      LoadPlugin(path);
  }
}

bool PluginList::ShouldLoadPlugin(const WebPluginInfo& info) {
  // The equivalent Windows code verifies we haven't loaded a newer version
  // of the same plugin, and then blacklists some known bad plugins.
  // The equivalent Mac code verifies that plugins encountered first in the
  // plugin list clobber later entries.
  // TODO(evanm): figure out which behavior is appropriate for Linux.
  // We don't need either yet as I'm just testing with Flash for now.
  return true;
}

void PluginList::LoadInternalPlugins() {
  // none for now
}

} // namespace NPAPI
<commit_msg>linux: also look in ~/.mozilla/plugins for plugins<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "webkit/glue/plugins/plugin_list.h"

#include "base/file_util.h"
#include "base/path_service.h"

namespace NPAPI {

void PluginList::PlatformInit() {
}

void PluginList::GetPluginDirectories(std::vector<FilePath>* plugin_dirs) {
  // Mozilla code to reference:
  // http://mxr.mozilla.org/firefox/ident?i=NS_APP_PLUGINS_DIR_LIST
  // and tens of accompanying files (mxr is very helpful).
  // This code carefully matches their behavior for compat reasons.

  // 1) MOZ_PLUGIN_PATH env variable.
  const char* moz_plugin_path = getenv("MOZ_PLUGIN_PATH");
  if (moz_plugin_path)
    plugin_dirs->push_back(FilePath(moz_plugin_path));

  // 2) NS_USER_PLUGINS_DIR: ~/.mozilla/plugins.
  // This is a de-facto standard, so even though we're not Mozilla, let's
  // look in there too.
  const char* home = getenv("HOME");
  if (home)
    plugin_dirs->push_back(FilePath(home).Append(".mozilla/plugins"));
  // TODO(evanm): maybe consult our own plugins dir, like
  // ~/.config/chromium/Plugins?

  // 3) NS_APP_PLUGINS_DIR: the binary dir + "plugins/".
  FilePath dir;
  PathService::Get(base::DIR_EXE, &dir);
  plugin_dirs->push_back(dir.Append("plugins"));

  // 4) NS_SYSTEM_PLUGINS_DIR:
  // TODO(evanm): when we support 64-bit platforms, we'll need to fix this
  // to be conditional.
  COMPILE_ASSERT(sizeof(int)==4, fix_system_lib_path);
  plugin_dirs->push_back(FilePath("/usr/lib/mozilla/plugins"));
}

void PluginList::LoadPluginsFromDir(const FilePath& path) {
  file_util::FileEnumerator enumerator(path,
                                       false, // not recursive
                                       file_util::FileEnumerator::FILES);
  for (FilePath path = enumerator.Next(); !path.value().empty();
       path = enumerator.Next()) {
    // Skip over Mozilla .xpt files.
    if (!path.MatchesExtension(FILE_PATH_LITERAL(".xpt")))
      LoadPlugin(path);
  }
}

bool PluginList::ShouldLoadPlugin(const WebPluginInfo& info) {
  // The equivalent Windows code verifies we haven't loaded a newer version
  // of the same plugin, and then blacklists some known bad plugins.
  // The equivalent Mac code verifies that plugins encountered first in the
  // plugin list clobber later entries.
  // TODO(evanm): figure out which behavior is appropriate for Linux.
  // We don't need either yet as I'm just testing with Flash for now.
  return true;
}

void PluginList::LoadInternalPlugins() {
  // none for now
}

} // namespace NPAPI
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: pathexpression.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: obo $ $Date: 2004-11-16 10:55:22 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _PATHEXPRESSION_HXX
#define _PATHEXPRESSION_HXX

// include for parent class
#include "computedexpression.hxx"

// includes for member variables
#include <vector>

// forward declaractions
namespace com { namespace sun { namespace star
{
    namespace xml { namespace dom
    {
        class XNodeList;
        namespace events { class XEventListener; }
    } }
} } }

namespace xforms
{

/** PathExpression represents an XPath Expression and caches results */
class PathExpression : public ComputedExpression
{
public:
    typedef std::vector<com::sun::star::uno::Reference<com::sun::star::xml::dom::XNode> > NodeVector_t;

private:
    /// the node-list result from the last bind (cached from mxResult)
    NodeVector_t maNodes;

protected:
    /// get expression for evaluation
    const rtl::OUString _getExpressionForEvaluation() const;

public:
    PathExpression();
    ~PathExpression();

    /// set the expression string
    /// (overridden to do remove old listeners)
    /// (also defines simple expressions)
    void setExpression( const rtl::OUString& rExpression );

    /// evaluate the expression relative to the content node.
    bool evaluate( const xforms::EvaluationContext& rContext );

    /// determine whether the expression can be considered as just an
    /// element name
    bool isElementName() const;

    // get the result of this expression as node/node list/...
    com::sun::star::uno::Reference<com::sun::star::xml::dom::XNode> getNode() const;
    const NodeVector_t getNodeList() const;
    com::sun::star::uno::Reference<com::sun::star::xml::dom::XNodeList> getXNodeList() const;

};

} // namespace xforms

#endif
<commit_msg>INTEGRATION: CWS eforms4 (1.2.6); FILE MERGED 2004/12/15 11:03:19 dvo 1.2.6.1: #i35397# use model namespaces (when possible) Issue number: Submitted by: Reviewed by:<commit_after>/*************************************************************************
 *
 *  $RCSfile: pathexpression.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: vg $ $Date: 2005-03-23 11:37:55 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _PATHEXPRESSION_HXX
#define _PATHEXPRESSION_HXX

// include for parent class
#include "computedexpression.hxx"

// includes for member variables
#include <vector>

// forward declaractions
namespace com { namespace sun { namespace star
{
    namespace xml { namespace dom
    {
        class XNodeList;
        namespace events { class XEventListener; }
    } }
} } }

namespace xforms
{

/** PathExpression represents an XPath Expression and caches results */
class PathExpression : public ComputedExpression
{
public:
    typedef std::vector<com::sun::star::uno::Reference<com::sun::star::xml::dom::XNode> > NodeVector_t;

private:
    /// the node-list result from the last bind (cached from mxResult)
    NodeVector_t maNodes;

protected:
    /// get expression for evaluation
    const rtl::OUString _getExpressionForEvaluation() const;

public:
    PathExpression();
    ~PathExpression();

    /// set the expression string
    /// (overridden to do remove old listeners)
    /// (also defines simple expressions)
    void setExpression( const rtl::OUString& rExpression );

    /// evaluate the expression relative to the content node.
    bool evaluate( const xforms::EvaluationContext& rContext );

    // get the result of this expression as node/node list/...
    com::sun::star::uno::Reference<com::sun::star::xml::dom::XNode> getNode() const;
    const NodeVector_t getNodeList() const;
    com::sun::star::uno::Reference<com::sun::star::xml::dom::XNodeList> getXNodeList() const;

};

} // namespace xforms

#endif
<|endoftext|>


<commit_before>/*  This file is part of the KDE project
    Copyright (C) 2007 Matthias Kretz <kretz@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License version 2 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.

*/

#include "path.h"
#include "path_p.h"

#include "backendinterface.h"
#include "factory.h"
#include "medianode.h"
#include "medianode_p.h"

namespace Phonon
{

class ConnectionTransaction
{
    public:
        ConnectionTransaction(BackendInterface *b, const QSet<QObject*> &x) : backend(b), list(x)
        {
            success = backend->startConnectionChange(list);
        }
        ~ConnectionTransaction()
        {
            backend->endConnectionChange(list);
        }
        operator bool()
        {
            return success;
        }
    private:
        bool success;
        BackendInterface *const backend;
        const QSet<QObject*> list;
};

PathPrivate::~PathPrivate()
{
    foreach (Effect *e, effects) {
        e->k_ptr->removeDestructionHandler(this);
    }
    delete effectsParent;
}

Path::~Path()
{
}

Path::Path()
    : d(new PathPrivate)
{
}

Path::Path(const Path &rhs)
    : d(rhs.d)
{
}

bool Path::isValid() const
{
    return d->sourceNode != 0 && d->sinkNode != 0;
}

Effect *Path::insertEffect(const EffectDescription &desc, Effect *insertBefore)
{
    if (!d->effectsParent) {
        d->effectsParent = new QObject;
    }
    Effect *e = new Effect(desc, d->effectsParent);
    if (!e->isValid()) {
        delete e;
        return 0;
    }
    bool success = insertEffect(e, insertBefore);
    if (!success) {
        delete e;
        return 0;
    }
    return e;
}

bool Path::insertEffect(Effect *newEffect, Effect *insertBefore)
{
    QObject *newEffectBackend = newEffect ? newEffect->k_ptr->backendObject() : 0;
    if (!isValid() || !newEffectBackend || d->effects.contains(newEffect) ||
            (insertBefore && (!d->effects.contains(insertBefore) || !insertBefore->k_ptr->backendObject()))) {
        return false;
    }
    QObject *leftNode = 0;
    QObject *rightNode = 0;
    const int insertIndex = insertBefore ? d->effects.indexOf(insertBefore) : d->effects.size();
    if (insertIndex == 0) {
        //prepend
        leftNode = d->sourceNode->k_ptr->backendObject();
    } else {
        leftNode = d->effects[insertIndex - 1]->k_ptr->backendObject();
    }

    if (insertIndex == d->effects.size()) {
        //append
        rightNode = d->sinkNode->k_ptr->backendObject();
    } else {
        rightNode = insertBefore->k_ptr->backendObject();
    }

    QList<QObjectPair> disconnections, connections;
    disconnections << QObjectPair(leftNode, rightNode);
    connections << QObjectPair(leftNode, newEffectBackend)
        << QObjectPair(newEffectBackend, rightNode);

    if (d->executeTransaction(disconnections, connections)) {
        newEffect->k_ptr->addDestructionHandler(d);
        d->effects.insert(insertIndex, newEffect);
        return true;
    } else {
        return false;
    }
}

bool Path::removeEffect(Effect *effect)
{
    return d->removeEffect(effect);
}

QList<Effect *> Path::effects() const
{
    return d->effects;
}

bool Path::reconnect(MediaNode *source, MediaNode *sink)
{
    if (!source || !sink || !source->k_ptr->backendObject() || !source->k_ptr->backendObject()) {
        return false;
    }

    QList<QObjectPair> disconnections, connections;

    //backend objects
    QObject *bnewSource = source->k_ptr->backendObject();
    QObject *bnewSink = sink->k_ptr->backendObject();
    QObject *bcurrentSource = d->sourceNode ? d->sourceNode->k_ptr->backendObject() : 0;
    QObject *bcurrentSink = d->sinkNode ? d->sinkNode->k_ptr->backendObject() : 0;

    if (bnewSource != bcurrentSource) {
        //we need to change the source
        MediaNode *next = d->effects.isEmpty() ? sink : d->effects.first();
        QObject *bnext = next->k_ptr->backendObject();
        if (bcurrentSource)
            disconnections << QObjectPair(bcurrentSource, bnext);
        connections << QObjectPair(bnewSource, bnext);
    }

    if (bnewSink != bcurrentSink) {
        MediaNode *previous = d->effects.isEmpty() ? source : d->effects.last();
        QObject *bprevious = previous->k_ptr->backendObject();
        if (bcurrentSink)
            disconnections << QObjectPair(bprevious, bcurrentSink);
        QObjectPair pair(bprevious, bnewSink);
        if (!connections.contains(pair)) //avoid connecting twice
            connections << pair;
    }

    if (d->executeTransaction(disconnections, connections)) {
        //everything went well: let's update the path and the source node
        sink->k_ptr->addInputPath(*this);
        if (d->sinkNode) {
            d->sinkNode->k_ptr->removeInputPath(*this);
            d->sinkNode->k_ptr->removeDestructionHandler(d);
        }
        d->sinkNode = sink;
        d->sinkNode->k_ptr->addDestructionHandler(d);

        //everything went well: let's update the path and the sink node
        source->k_ptr->addOutputPath(*this);
        if (d->sourceNode) {
            d->sourceNode->k_ptr->removeOutputPath(*this);
            d->sourceNode->k_ptr->removeDestructionHandler(d);
        }
        d->sourceNode = source;
        d->sourceNode->k_ptr->addDestructionHandler(d);
        return true;
    } else {
        return false;
    }
}

bool Path::disconnect()
{
    if (!isValid()) {
        return false;
    }

    QObjectList list;
    if (d->sourceNode)
        list << d->sourceNode->k_ptr->backendObject();
    foreach(Effect *e, d->effects) {
        list << e->k_ptr->backendObject();
    }
    if (d->sinkNode)
        list << d->sinkNode->k_ptr->backendObject();

    //lets build the disconnection list
    QList<QObjectPair> disco;
    if (list.count() >=2 ) {
        QObjectList::const_iterator it = list.begin();
        for(;it+1 != list.end();++it) {
            disco << QObjectPair(*it, *(it+1));
        }
    }

    if (d->executeTransaction(disco, QList<QObjectPair>())) {
        //everything went well, let's remove the reference
        //to the paths from the source and sink
        if (d->sourceNode) {
            d->sourceNode->k_ptr->removeOutputPath(*this);
            d->sourceNode->k_ptr->removeDestructionHandler(d);
        }
        d->sourceNode = 0;

        foreach(Effect *e, d->effects) {
            e->k_ptr->removeDestructionHandler(d);
        }
        d->effects.clear();

        if (d->sinkNode) {
            d->sinkNode->k_ptr->removeInputPath(*this);
            d->sinkNode->k_ptr->removeDestructionHandler(d);
        }
        d->sinkNode = 0;
        return true;
    } else {
        return false;
    }
}

bool PathPrivate::executeTransaction( const QList<QObjectPair> &disconnections, const QList<QObjectPair> &connections)
{
    QSet<QObject*> nodesForTransaction;
    foreach(const QObjectPair &pair, disconnections) {
        nodesForTransaction << pair.first;
        nodesForTransaction << pair.second;
    }
    foreach(const QObjectPair &pair, connections) {
        nodesForTransaction << pair.first;
        nodesForTransaction << pair.second;
    }
    BackendInterface *backend = qobject_cast<BackendInterface *>(Factory::backend());
    if (!backend)
        return false;

    ConnectionTransaction transaction(backend, nodesForTransaction);
    if (!transaction)
        return false;

    QList<QObjectPair>::const_iterator it = disconnections.begin();
    for(;it != disconnections.end();++it) {
        const QObjectPair &pair = *it;
        if (!backend->disconnectNodes(pair.first, pair.second)) {

            //Error: a disconnection failed
            QList<QObjectPair>::const_iterator it2 = disconnections.begin();
            for(; it2 != it; ++it2) {
                const QObjectPair &pair = *it2;
                bool success = backend->connectNodes(pair.first, pair.second);
                Q_ASSERT(success); //a failure here means it is impossible to reestablish the connection
                Q_UNUSED(success);
            }
            return false;
        }
    }

    for(it = connections.begin(); it != connections.end();++it) {
        const QObjectPair &pair = *it;
        if (!backend->connectNodes(pair.first, pair.second)) {
            //Error: a connection failed
            QList<QObjectPair>::const_iterator it2 = connections.begin();
            for(; it2 != it; ++it2) {
                const QObjectPair &pair = *it2;
                bool success = backend->disconnectNodes(pair.first, pair.second);
                Q_ASSERT(success); //a failure here means it is impossible to reestablish the connection
                Q_UNUSED(success);
            }

            //and now let's reconnect the nodes that were disconnected: rollback
            foreach(const QObjectPair &pair, disconnections) {
                bool success = backend->connectNodes(pair.first, pair.second);
                Q_ASSERT(success); //a failure here means it is impossible to reestablish the connection
                Q_UNUSED(success);
            }

            return false;

        }
    }
    return true;
}

bool PathPrivate::removeEffect(Effect *effect)
{
    if (!effects.contains(effect))
        return false;

    QObject *leftNode = 0;
    QObject *rightNode = 0;
    const int index = effects.indexOf(effect);
    if (index == 0) {
        leftNode = sourceNode->k_ptr->backendObject(); //append
    } else {
        leftNode = effects[index - 1]->k_ptr->backendObject();
    }
    if (index == effects.size()-1) {
        rightNode = sinkNode->k_ptr->backendObject(); //prepend
    } else {
        rightNode = effects[index + 1]->k_ptr->backendObject();
    }

    QList<QObjectPair> disconnections, connections;
    QObject *beffect = effect->k_ptr->backendObject();
    disconnections << QObjectPair(leftNode, beffect) << QObjectPair(beffect, rightNode);
    connections << QObjectPair(leftNode, rightNode);

    if (executeTransaction(disconnections, connections)) {
        effect->k_ptr->removeDestructionHandler(this);
        effects.removeAt(index);
        return true;
    }
    return false;
}

void PathPrivate::phononObjectDestroyed(MediaNodePrivate *mediaNodePrivate)
{
    Q_ASSERT(mediaNodePrivate);
    if (mediaNodePrivate == sinkNode->k_ptr || mediaNodePrivate == sourceNode->k_ptr) {
        //let's first disconnectq the path from its source and sink
        QObject *bsink = sinkNode->k_ptr->backendObject();
        QObject *bsource = sourceNode->k_ptr->backendObject();
        QList<QObjectPair> disconnections;
        disconnections << QObjectPair(bsource, effects.isEmpty() ? bsink : effects.first()->k_ptr->backendObject());
        if (!effects.isEmpty())
            disconnections << QObjectPair(effects.last()->k_ptr->backendObject(), bsink);
        executeTransaction(disconnections, QList<QObjectPair>());

        Path p; //temporary path
        p.d = this;
        if (mediaNodePrivate == sinkNode->k_ptr) {
            sourceNode->k_ptr->removeOutputPath(p);
            sourceNode->k_ptr->removeDestructionHandler(this);
        } else {
            sinkNode->k_ptr->removeInputPath(p);
            sinkNode->k_ptr->removeDestructionHandler(this);
        }
        sourceNode = 0;
        sinkNode = 0;
    } else {
        foreach (Effect *e, effects) {
            if (e->k_ptr == mediaNodePrivate) {
                removeEffect(e);
            }
        }
    }
}

Path createPath(MediaNode *source, MediaNode *sink)
{
    Path p;
    if (!p.reconnect(source, sink)) {
        const QObject *const src = source ? source->k_ptr->qObject() : 0;
        const QObject *const snk = sink ? sink->k_ptr->qObject() : 0;
        qWarning("Phonon::createPath: Cannot connect %s(%s) to %s(%s).",
                src ? src->metaObject()->className() : "",
                src ? (src->objectName().isEmpty() ? "no objectName" : qPrintable(src->objectName())) : "null",
                snk ? snk->metaObject()->className() : "",
                snk ? (snk->objectName().isEmpty() ? "no objectName" : qPrintable(snk->objectName())) : "null");
    }
    return p;
}

Path & Path::operator=(const Path &other)
{
    d = other.d;
    return *this;
}

bool Path::operator==(const Path &other) const
{
    return d == other.d;
}

bool Path::operator!=(const Path &other) const
{
    return !operator==(other);
}

} // namespace Phonon
<commit_msg>Check both the source and sink backend objects (not the source twice).<commit_after>/*  This file is part of the KDE project
    Copyright (C) 2007 Matthias Kretz <kretz@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License version 2 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.

*/

#include "path.h"
#include "path_p.h"

#include "backendinterface.h"
#include "factory.h"
#include "medianode.h"
#include "medianode_p.h"

namespace Phonon
{

class ConnectionTransaction
{
    public:
        ConnectionTransaction(BackendInterface *b, const QSet<QObject*> &x) : backend(b), list(x)
        {
            success = backend->startConnectionChange(list);
        }
        ~ConnectionTransaction()
        {
            backend->endConnectionChange(list);
        }
        operator bool()
        {
            return success;
        }
    private:
        bool success;
        BackendInterface *const backend;
        const QSet<QObject*> list;
};

PathPrivate::~PathPrivate()
{
    foreach (Effect *e, effects) {
        e->k_ptr->removeDestructionHandler(this);
    }
    delete effectsParent;
}

Path::~Path()
{
}

Path::Path()
    : d(new PathPrivate)
{
}

Path::Path(const Path &rhs)
    : d(rhs.d)
{
}

bool Path::isValid() const
{
    return d->sourceNode != 0 && d->sinkNode != 0;
}

Effect *Path::insertEffect(const EffectDescription &desc, Effect *insertBefore)
{
    if (!d->effectsParent) {
        d->effectsParent = new QObject;
    }
    Effect *e = new Effect(desc, d->effectsParent);
    if (!e->isValid()) {
        delete e;
        return 0;
    }
    bool success = insertEffect(e, insertBefore);
    if (!success) {
        delete e;
        return 0;
    }
    return e;
}

bool Path::insertEffect(Effect *newEffect, Effect *insertBefore)
{
    QObject *newEffectBackend = newEffect ? newEffect->k_ptr->backendObject() : 0;
    if (!isValid() || !newEffectBackend || d->effects.contains(newEffect) ||
            (insertBefore && (!d->effects.contains(insertBefore) || !insertBefore->k_ptr->backendObject()))) {
        return false;
    }
    QObject *leftNode = 0;
    QObject *rightNode = 0;
    const int insertIndex = insertBefore ? d->effects.indexOf(insertBefore) : d->effects.size();
    if (insertIndex == 0) {
        //prepend
        leftNode = d->sourceNode->k_ptr->backendObject();
    } else {
        leftNode = d->effects[insertIndex - 1]->k_ptr->backendObject();
    }

    if (insertIndex == d->effects.size()) {
        //append
        rightNode = d->sinkNode->k_ptr->backendObject();
    } else {
        rightNode = insertBefore->k_ptr->backendObject();
    }

    QList<QObjectPair> disconnections, connections;
    disconnections << QObjectPair(leftNode, rightNode);
    connections << QObjectPair(leftNode, newEffectBackend)
        << QObjectPair(newEffectBackend, rightNode);

    if (d->executeTransaction(disconnections, connections)) {
        newEffect->k_ptr->addDestructionHandler(d);
        d->effects.insert(insertIndex, newEffect);
        return true;
    } else {
        return false;
    }
}

bool Path::removeEffect(Effect *effect)
{
    return d->removeEffect(effect);
}

QList<Effect *> Path::effects() const
{
    return d->effects;
}

bool Path::reconnect(MediaNode *source, MediaNode *sink)
{
    if (!source || !sink || !source->k_ptr->backendObject() || !sink->k_ptr->backendObject()) {
        return false;
    }

    QList<QObjectPair> disconnections, connections;

    //backend objects
    QObject *bnewSource = source->k_ptr->backendObject();
    QObject *bnewSink = sink->k_ptr->backendObject();
    QObject *bcurrentSource = d->sourceNode ? d->sourceNode->k_ptr->backendObject() : 0;
    QObject *bcurrentSink = d->sinkNode ? d->sinkNode->k_ptr->backendObject() : 0;

    if (bnewSource != bcurrentSource) {
        //we need to change the source
        MediaNode *next = d->effects.isEmpty() ? sink : d->effects.first();
        QObject *bnext = next->k_ptr->backendObject();
        if (bcurrentSource)
            disconnections << QObjectPair(bcurrentSource, bnext);
        connections << QObjectPair(bnewSource, bnext);
    }

    if (bnewSink != bcurrentSink) {
        MediaNode *previous = d->effects.isEmpty() ? source : d->effects.last();
        QObject *bprevious = previous->k_ptr->backendObject();
        if (bcurrentSink)
            disconnections << QObjectPair(bprevious, bcurrentSink);
        QObjectPair pair(bprevious, bnewSink);
        if (!connections.contains(pair)) //avoid connecting twice
            connections << pair;
    }

    if (d->executeTransaction(disconnections, connections)) {
        //everything went well: let's update the path and the source node
        sink->k_ptr->addInputPath(*this);
        if (d->sinkNode) {
            d->sinkNode->k_ptr->removeInputPath(*this);
            d->sinkNode->k_ptr->removeDestructionHandler(d);
        }
        d->sinkNode = sink;
        d->sinkNode->k_ptr->addDestructionHandler(d);

        //everything went well: let's update the path and the sink node
        source->k_ptr->addOutputPath(*this);
        if (d->sourceNode) {
            d->sourceNode->k_ptr->removeOutputPath(*this);
            d->sourceNode->k_ptr->removeDestructionHandler(d);
        }
        d->sourceNode = source;
        d->sourceNode->k_ptr->addDestructionHandler(d);
        return true;
    } else {
        return false;
    }
}

bool Path::disconnect()
{
    if (!isValid()) {
        return false;
    }

    QObjectList list;
    if (d->sourceNode)
        list << d->sourceNode->k_ptr->backendObject();
    foreach(Effect *e, d->effects) {
        list << e->k_ptr->backendObject();
    }
    if (d->sinkNode)
        list << d->sinkNode->k_ptr->backendObject();

    //lets build the disconnection list
    QList<QObjectPair> disco;
    if (list.count() >=2 ) {
        QObjectList::const_iterator it = list.begin();
        for(;it+1 != list.end();++it) {
            disco << QObjectPair(*it, *(it+1));
        }
    }

    if (d->executeTransaction(disco, QList<QObjectPair>())) {
        //everything went well, let's remove the reference
        //to the paths from the source and sink
        if (d->sourceNode) {
            d->sourceNode->k_ptr->removeOutputPath(*this);
            d->sourceNode->k_ptr->removeDestructionHandler(d);
        }
        d->sourceNode = 0;

        foreach(Effect *e, d->effects) {
            e->k_ptr->removeDestructionHandler(d);
        }
        d->effects.clear();

        if (d->sinkNode) {
            d->sinkNode->k_ptr->removeInputPath(*this);
            d->sinkNode->k_ptr->removeDestructionHandler(d);
        }
        d->sinkNode = 0;
        return true;
    } else {
        return false;
    }
}

bool PathPrivate::executeTransaction( const QList<QObjectPair> &disconnections, const QList<QObjectPair> &connections)
{
    QSet<QObject*> nodesForTransaction;
    foreach(const QObjectPair &pair, disconnections) {
        nodesForTransaction << pair.first;
        nodesForTransaction << pair.second;
    }
    foreach(const QObjectPair &pair, connections) {
        nodesForTransaction << pair.first;
        nodesForTransaction << pair.second;
    }
    BackendInterface *backend = qobject_cast<BackendInterface *>(Factory::backend());
    if (!backend)
        return false;

    ConnectionTransaction transaction(backend, nodesForTransaction);
    if (!transaction)
        return false;

    QList<QObjectPair>::const_iterator it = disconnections.begin();
    for(;it != disconnections.end();++it) {
        const QObjectPair &pair = *it;
        if (!backend->disconnectNodes(pair.first, pair.second)) {

            //Error: a disconnection failed
            QList<QObjectPair>::const_iterator it2 = disconnections.begin();
            for(; it2 != it; ++it2) {
                const QObjectPair &pair = *it2;
                bool success = backend->connectNodes(pair.first, pair.second);
                Q_ASSERT(success); //a failure here means it is impossible to reestablish the connection
                Q_UNUSED(success);
            }
            return false;
        }
    }

    for(it = connections.begin(); it != connections.end();++it) {
        const QObjectPair &pair = *it;
        if (!backend->connectNodes(pair.first, pair.second)) {
            //Error: a connection failed
            QList<QObjectPair>::const_iterator it2 = connections.begin();
            for(; it2 != it; ++it2) {
                const QObjectPair &pair = *it2;
                bool success = backend->disconnectNodes(pair.first, pair.second);
                Q_ASSERT(success); //a failure here means it is impossible to reestablish the connection
                Q_UNUSED(success);
            }

            //and now let's reconnect the nodes that were disconnected: rollback
            foreach(const QObjectPair &pair, disconnections) {
                bool success = backend->connectNodes(pair.first, pair.second);
                Q_ASSERT(success); //a failure here means it is impossible to reestablish the connection
                Q_UNUSED(success);
            }

            return false;

        }
    }
    return true;
}

bool PathPrivate::removeEffect(Effect *effect)
{
    if (!effects.contains(effect))
        return false;

    QObject *leftNode = 0;
    QObject *rightNode = 0;
    const int index = effects.indexOf(effect);
    if (index == 0) {
        leftNode = sourceNode->k_ptr->backendObject(); //append
    } else {
        leftNode = effects[index - 1]->k_ptr->backendObject();
    }
    if (index == effects.size()-1) {
        rightNode = sinkNode->k_ptr->backendObject(); //prepend
    } else {
        rightNode = effects[index + 1]->k_ptr->backendObject();
    }

    QList<QObjectPair> disconnections, connections;
    QObject *beffect = effect->k_ptr->backendObject();
    disconnections << QObjectPair(leftNode, beffect) << QObjectPair(beffect, rightNode);
    connections << QObjectPair(leftNode, rightNode);

    if (executeTransaction(disconnections, connections)) {
        effect->k_ptr->removeDestructionHandler(this);
        effects.removeAt(index);
        return true;
    }
    return false;
}

void PathPrivate::phononObjectDestroyed(MediaNodePrivate *mediaNodePrivate)
{
    Q_ASSERT(mediaNodePrivate);
    if (mediaNodePrivate == sinkNode->k_ptr || mediaNodePrivate == sourceNode->k_ptr) {
        //let's first disconnectq the path from its source and sink
        QObject *bsink = sinkNode->k_ptr->backendObject();
        QObject *bsource = sourceNode->k_ptr->backendObject();
        QList<QObjectPair> disconnections;
        disconnections << QObjectPair(bsource, effects.isEmpty() ? bsink : effects.first()->k_ptr->backendObject());
        if (!effects.isEmpty())
            disconnections << QObjectPair(effects.last()->k_ptr->backendObject(), bsink);
        executeTransaction(disconnections, QList<QObjectPair>());

        Path p; //temporary path
        p.d = this;
        if (mediaNodePrivate == sinkNode->k_ptr) {
            sourceNode->k_ptr->removeOutputPath(p);
            sourceNode->k_ptr->removeDestructionHandler(this);
        } else {
            sinkNode->k_ptr->removeInputPath(p);
            sinkNode->k_ptr->removeDestructionHandler(this);
        }
        sourceNode = 0;
        sinkNode = 0;
    } else {
        foreach (Effect *e, effects) {
            if (e->k_ptr == mediaNodePrivate) {
                removeEffect(e);
            }
        }
    }
}

Path createPath(MediaNode *source, MediaNode *sink)
{
    Path p;
    if (!p.reconnect(source, sink)) {
        const QObject *const src = source ? source->k_ptr->qObject() : 0;
        const QObject *const snk = sink ? sink->k_ptr->qObject() : 0;
        qWarning("Phonon::createPath: Cannot connect %s(%s) to %s(%s).",
                src ? src->metaObject()->className() : "",
                src ? (src->objectName().isEmpty() ? "no objectName" : qPrintable(src->objectName())) : "null",
                snk ? snk->metaObject()->className() : "",
                snk ? (snk->objectName().isEmpty() ? "no objectName" : qPrintable(snk->objectName())) : "null");
    }
    return p;
}

Path & Path::operator=(const Path &other)
{
    d = other.d;
    return *this;
}

bool Path::operator==(const Path &other) const
{
    return d == other.d;
}

bool Path::operator!=(const Path &other) const
{
    return !operator==(other);
}

} // namespace Phonon
<|endoftext|>


<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2014 Torus Knot Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"

#include "OgreDynLib.h"

#include "OgreException.h"
#include "OgreLogManager.h"
#include "OgreStringConverter.h"

#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT
#  define WIN32_LEAN_AND_MEAN
#  if !defined(NOMINMAX) && defined(_MSC_VER)
#	define NOMINMAX // required to stop windows.h messing up std::min
#  endif
#  include <windows.h>
#endif

#if OGRE_PLATFORM == OGRE_PLATFORM_WINRT
#include "OgreUTFString.h"
#endif

#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE || OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS
#   include "macUtils.h"
#endif
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE || OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS || OGRE_PLATFORM == OGRE_PLATFORM_NACL || OGRE_PLATFORM == OGRE_PLATFORM_FLASHCC
#   include <dlfcn.h>
#endif

namespace Ogre {

    //-----------------------------------------------------------------------
    DynLib::DynLib( const String& name )
    {
        mName = name;
        mInst = NULL;
    }

    //-----------------------------------------------------------------------
    DynLib::~DynLib()
    {
    }

    //-----------------------------------------------------------------------
    void DynLib::load()
    {
        // Log library load
        LogManager::getSingleton().logMessage("Loading library " + mName);

		String name = mName;
#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX || OGRE_PLATFORM == OGRE_PLATFORM_NACL
        // dlopen() does not add .so to the filename, like windows does for .dll
        if (name.find(".so") == String::npos)
        {
            name += ".so.";
            name += StringConverter::toString(OGRE_VERSION_MAJOR) + ".";
            name += StringConverter::toString(OGRE_VERSION_MINOR) + ".";
            name += StringConverter::toString(OGRE_VERSION_PATCH);
        }
#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE
        // dlopen() does not add .dylib to the filename, like windows does for .dll
        if (name.substr(name.length() - 6, 6) != ".dylib")
			name += ".dylib";
#elif OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT
		// Although LoadLibraryEx will add .dll itself when you only specify the library name,
		// if you include a relative path then it does not. So, add it to be sure.
		if (name.substr(name.length() - 4, 4) != ".dll")
			name += ".dll";
#endif
        mInst = (DYNLIB_HANDLE)DYNLIB_LOAD( name.c_str() );
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
        if(!mInst)
        {
            // Try again as a framework
            mInst = (DYNLIB_HANDLE)FRAMEWORK_LOAD( mName );
        }
#endif
        if( !mInst )
            OGRE_EXCEPT(
                Exception::ERR_INTERNAL_ERROR,
                "Could not load dynamic library " + mName +
                ".  System Error: " + dynlibError(),
                "DynLib::load" );
    }

    //-----------------------------------------------------------------------
    void DynLib::unload()
    {
        // Log library unload
        LogManager::getSingleton().logMessage("Unloading library " + mName);

        if( DYNLIB_UNLOAD( mInst ) )
		{
            OGRE_EXCEPT(
                Exception::ERR_INTERNAL_ERROR,
                "Could not unload dynamic library " + mName +
                ".  System Error: " + dynlibError(),
                "DynLib::unload");
		}

    }

    //-----------------------------------------------------------------------
    void* DynLib::getSymbol( const String& strName ) const throw()
    {
        return (void*)DYNLIB_GETSYM( mInst, strName.c_str() );
    }
    //-----------------------------------------------------------------------
    String DynLib::dynlibError( void )
    {
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
        LPTSTR lpMsgBuf;
        FormatMessage(
            FORMAT_MESSAGE_ALLOCATE_BUFFER |
            FORMAT_MESSAGE_FROM_SYSTEM |
            FORMAT_MESSAGE_IGNORE_INSERTS,
            NULL,
            GetLastError(),
            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
            (LPTSTR)&lpMsgBuf,
            0,
            NULL
            );
        String ret = lpMsgBuf;
        // Free the buffer.
        LocalFree( lpMsgBuf );
        return ret;
#elif OGRE_PLATFORM == OGRE_PLATFORM_WINRT
        WCHAR wideMsgBuf[1024];
        if(0 == FormatMessageW(
            FORMAT_MESSAGE_FROM_SYSTEM |
            FORMAT_MESSAGE_IGNORE_INSERTS,
            NULL,
            GetLastError(),
            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
            wideMsgBuf,
            sizeof(wideMsgBuf) / sizeof(wideMsgBuf[0]),
            NULL
            ))
		{
			wideMsgBuf[0] = 0;
		}
		char narrowMsgBuf[2048] = "";
		if(0 == WideCharToMultiByte(
			CP_ACP, 0,
			wideMsgBuf, -1,
			narrowMsgBuf, sizeof(narrowMsgBuf) / sizeof(narrowMsgBuf[0]),
			NULL, NULL))
		{
			narrowMsgBuf[0] = 0;
		}
        String ret = narrowMsgBuf;

        return ret;
#elif OGRE_PLATFORM == OGRE_PLATFORM_LINUX || OGRE_PLATFORM == OGRE_PLATFORM_APPLE
        return String(dlerror());
#else
        return String("");
#endif
    }

}
<commit_msg>[OGRE-388] Fix issue loading shared libraries with names shorter than 3 chars.<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2014 Torus Knot Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"

#include "OgreDynLib.h"

#include "OgreException.h"
#include "OgreLogManager.h"
#include "OgreStringConverter.h"

#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT
#  define WIN32_LEAN_AND_MEAN
#  if !defined(NOMINMAX) && defined(_MSC_VER)
#	define NOMINMAX // required to stop windows.h messing up std::min
#  endif
#  include <windows.h>
#endif

#if OGRE_PLATFORM == OGRE_PLATFORM_WINRT
#include "OgreUTFString.h"
#endif

#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE || OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS
#   include "macUtils.h"
#endif
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE || OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS || OGRE_PLATFORM == OGRE_PLATFORM_NACL || OGRE_PLATFORM == OGRE_PLATFORM_FLASHCC
#   include <dlfcn.h>
#endif

namespace Ogre {

    //-----------------------------------------------------------------------
    DynLib::DynLib( const String& name )
    {
        mName = name;
        mInst = NULL;
    }

    //-----------------------------------------------------------------------
    DynLib::~DynLib()
    {
    }

    //-----------------------------------------------------------------------
    void DynLib::load()
    {
        // Log library load
        LogManager::getSingleton().logMessage("Loading library " + mName);

		String name = mName;
#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX || OGRE_PLATFORM == OGRE_PLATFORM_NACL
        // dlopen() does not add .so to the filename, like windows does for .dll
        if (name.find(".so") == String::npos)
        {
            name += ".so.";
            name += StringConverter::toString(OGRE_VERSION_MAJOR) + ".";
            name += StringConverter::toString(OGRE_VERSION_MINOR) + ".";
            name += StringConverter::toString(OGRE_VERSION_PATCH);
        }
#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE
        // dlopen() does not add .dylib to the filename, like windows does for .dll
        if(name.substr(name.find_last_not_of(".") + 1) != "dylib")
			name += ".dylib";
#elif OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT
		// Although LoadLibraryEx will add .dll itself when you only specify the library name,
		// if you include a relative path then it does not. So, add it to be sure.
        if(name.substr(name.find_last_not_of(".") + 1) != "dll")
			name += ".dll";
#endif
        mInst = (DYNLIB_HANDLE)DYNLIB_LOAD( name.c_str() );
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
        if(!mInst)
        {
            // Try again as a framework
            mInst = (DYNLIB_HANDLE)FRAMEWORK_LOAD( mName );
        }
#endif
        if( !mInst )
            OGRE_EXCEPT(
                Exception::ERR_INTERNAL_ERROR,
                "Could not load dynamic library " + mName +
                ".  System Error: " + dynlibError(),
                "DynLib::load" );
    }

    //-----------------------------------------------------------------------
    void DynLib::unload()
    {
        // Log library unload
        LogManager::getSingleton().logMessage("Unloading library " + mName);

        if( DYNLIB_UNLOAD( mInst ) )
		{
            OGRE_EXCEPT(
                Exception::ERR_INTERNAL_ERROR,
                "Could not unload dynamic library " + mName +
                ".  System Error: " + dynlibError(),
                "DynLib::unload");
		}

    }

    //-----------------------------------------------------------------------
    void* DynLib::getSymbol( const String& strName ) const throw()
    {
        return (void*)DYNLIB_GETSYM( mInst, strName.c_str() );
    }
    //-----------------------------------------------------------------------
    String DynLib::dynlibError( void )
    {
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
        LPTSTR lpMsgBuf;
        FormatMessage(
            FORMAT_MESSAGE_ALLOCATE_BUFFER |
            FORMAT_MESSAGE_FROM_SYSTEM |
            FORMAT_MESSAGE_IGNORE_INSERTS,
            NULL,
            GetLastError(),
            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
            (LPTSTR)&lpMsgBuf,
            0,
            NULL
            );
        String ret = lpMsgBuf;
        // Free the buffer.
        LocalFree( lpMsgBuf );
        return ret;
#elif OGRE_PLATFORM == OGRE_PLATFORM_WINRT
        WCHAR wideMsgBuf[1024];
        if(0 == FormatMessageW(
            FORMAT_MESSAGE_FROM_SYSTEM |
            FORMAT_MESSAGE_IGNORE_INSERTS,
            NULL,
            GetLastError(),
            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
            wideMsgBuf,
            sizeof(wideMsgBuf) / sizeof(wideMsgBuf[0]),
            NULL
            ))
		{
			wideMsgBuf[0] = 0;
		}
		char narrowMsgBuf[2048] = "";
		if(0 == WideCharToMultiByte(
			CP_ACP, 0,
			wideMsgBuf, -1,
			narrowMsgBuf, sizeof(narrowMsgBuf) / sizeof(narrowMsgBuf[0]),
			NULL, NULL))
		{
			narrowMsgBuf[0] = 0;
		}
        String ret = narrowMsgBuf;

        return ret;
#elif OGRE_PLATFORM == OGRE_PLATFORM_LINUX || OGRE_PLATFORM == OGRE_PLATFORM_APPLE
        return String(dlerror());
#else
        return String("");
#endif
    }

}
<|endoftext|>


<commit_before>#include <iostream>

#include "node_xenstat.h"
#include "domain.h"
#include "node.h"
#include "network.h"
#include "vbd.h"

namespace Xenstat {

static xenstat_handle *xhandle = xenstat_init();

class CollectWorker : public NanAsyncWorker {
  public:
    CollectWorker(NanCallback *callback, uint32_t flags)
      : NanAsyncWorker(callback), flags_(flags) {}
    ~CollectWorker() {}

    void Execute() {
      // Asynchronously call xenstat
      xnode_ = xenstat_get_node(xhandle, XENSTAT_ALL);
      if (xnode_ == NULL)
        SetErrorMessage("Failed to retrieve statistics from libxenstat");
    }

    void HandleOKCallback() {
      NanScope();

      Local<Value> argv[2];

      // Create a new Node V8 Object with the xnode from the asynchronous
      // call to xenstat.
      argv[0] = NanNew<External>(xnode_);
      Local<Value> node = NanNew<Value>(Node::NewInstance(1, argv));

      argv[0] = NanNull();
      argv[1] = node;

      callback->Call(2, argv);
    }

  private:
    uint32_t flags_;
    xenstat_node *xnode_;
};

NAN_METHOD(Collect) {
  NanScope();

  // Flags is optional and defaults to XENSTAT_ALL
  uint32_t flags = (args[0]->IsNumber()) ? args[0]->Uint32Value() : XENSTAT_ALL;

  // Check last argument is callback and is function
  if (args.Length() == 0 || !args[args.Length()-1]->IsFunction())
    NanReturnUndefined();
  NanCallback *callback = new NanCallback(args[args.Length()-1].As<Function>());

  NanAsyncQueueWorker(new CollectWorker(callback, flags));
  NanReturnUndefined();
}

NAN_METHOD(CollectSync) {
  NanScope();

  // Flags is optional and defaults to XENSTAT_ALL
  uint32_t flags = (args[0]->IsNumber()) ? args[0]->Uint32Value() : XENSTAT_ALL;

  Local<Value> argv[1];
  argv[0] = NanNew<External>(xenstat_get_node(xhandle, flags));

  NanReturnValue(Node::NewInstance(1, argv));
}

static void Init(Handle<Object> target) {
  NanScope();

  if (xhandle == NULL) {
    std::cerr << "Failed to initialize libxenstat. Is Xen running?" << std::endl << std::endl;
    return;
  }

  target->Set(NanNew<String>("collect"),
    NanNew<FunctionTemplate>(Collect)->GetFunction());
  target->Set(NanNew<String>("collectSync"),
    NanNew<FunctionTemplate>(CollectSync)->GetFunction());

  Domain::Init(target);
  Node::Init(target);
  Network::Init(target);
  Vbd::Init(target);
}

} // namespace

NODE_MODULE(xenstat, Xenstat::Init);
<commit_msg>Fix async worker not honoring flags<commit_after>#include <iostream>

#include "node_xenstat.h"
#include "domain.h"
#include "node.h"
#include "network.h"
#include "vbd.h"

namespace Xenstat {

static xenstat_handle *xhandle = xenstat_init();

class CollectWorker : public NanAsyncWorker {
  public:
    CollectWorker(NanCallback *callback, uint32_t flags)
      : NanAsyncWorker(callback), flags_(flags) {}
    ~CollectWorker() {}

    void Execute() {
      // Asynchronously call xenstat
      xnode_ = xenstat_get_node(xhandle, flags_);
      if (xnode_ == NULL)
        SetErrorMessage("Failed to retrieve statistics from libxenstat");
    }

    void HandleOKCallback() {
      NanScope();

      Local<Value> argv[2];

      // Create a new Node V8 Object with the xnode from the asynchronous
      // call to xenstat.
      argv[0] = NanNew<External>(xnode_);
      Local<Value> node = NanNew<Value>(Node::NewInstance(1, argv));

      argv[0] = NanNull();
      argv[1] = node;

      callback->Call(2, argv);
    }

  private:
    uint32_t flags_;
    xenstat_node *xnode_;
};

NAN_METHOD(Collect) {
  NanScope();

  // Flags is optional and defaults to XENSTAT_ALL
  uint32_t flags = (args[0]->IsNumber()) ? args[0]->Uint32Value() : XENSTAT_ALL;

  // Check last argument is callback and is function
  if (args.Length() == 0 || !args[args.Length()-1]->IsFunction())
    NanReturnUndefined();
  NanCallback *callback = new NanCallback(args[args.Length()-1].As<Function>());

  NanAsyncQueueWorker(new CollectWorker(callback, flags));
  NanReturnUndefined();
}

NAN_METHOD(CollectSync) {
  NanScope();

  // Flags is optional and defaults to XENSTAT_ALL
  uint32_t flags = (args[0]->IsNumber()) ? args[0]->Uint32Value() : XENSTAT_ALL;

  Local<Value> argv[1];
  argv[0] = NanNew<External>(xenstat_get_node(xhandle, flags));

  NanReturnValue(Node::NewInstance(1, argv));
}

static void Init(Handle<Object> target) {
  NanScope();

  if (xhandle == NULL) {
    std::cerr << "Failed to initialize libxenstat. Is Xen running?" << std::endl << std::endl;
    return;
  }

  target->Set(NanNew<String>("collect"),
    NanNew<FunctionTemplate>(Collect)->GetFunction());
  target->Set(NanNew<String>("collectSync"),
    NanNew<FunctionTemplate>(CollectSync)->GetFunction());

  Domain::Init(target);
  Node::Init(target);
  Network::Init(target);
  Vbd::Init(target);
}

} // namespace

NODE_MODULE(xenstat, Xenstat::Init);
<|endoftext|>


<commit_before>#include <ESP8266WiFi.h>
#include <Ticker.h>
#include "Sds011.h"
#include "Pcd8544.h"
#include "Expander.h"
#include "Dht.h"
#include "config.h"
#include "send.h"
#include "ui.h"

extern expander::Expander expand;
extern struct Configuration config;
extern sds011::Sds011 sensor;

dht::Dht dht22(14);
Ticker timer1;
Ticker timer2;

static const int SAMPLES=10;

static void turnOff(void)
{
    expand.digitalWrite(0, HIGH);
}

static void turnOn(void)
{
    uint8_t b = expand.readByte();

    if ((b & 0b10) != 0b10) {
        timer2.once_ms(5000, turnOff);
        expand.digitalWrite(0, LOW);
    }
}

static void iter()
{
    timer1.once_ms(30, turnOn);
}

void normal_setup(void)
{
    dht22.begin();
    expand.attachInterrupt(iter);

    WiFi.mode(WIFI_STA);

    sensor.set_sleep(false);
    sensor.set_mode(sds011::QUERY);
    sensor.set_sleep(true);
}

void normal_loop(void)
{
    int pm25, pm10;
    bool ok;
    int16_t t, h;
    dht::dht_status dhts;

    display_template();

    dhts = dht22.read(&t, &h);
    display_status_dht(dhts);
    if (dhts == dht::DHT_OK) {
        display_temp(t, h);
    }

    WiFi.begin(config.wifi_ssid, config.wifi_pass);
    display_status_wifi(WIFI_CONNECTING);

    sensor.set_sleep(false);
    display_status_sensor(SENSOR_START);
    delay(1000);
    ok = sensor.query_data_auto(&pm25, &pm10, SAMPLES);
    sensor.set_sleep(true);

    if (ok) {
        display_dust(pm25, pm10);
        display_status_sensor(SENSOR_OK);
    } else {
        display_status_sensor(SENSOR_ERROR);
        pm25 = pm10 = 0;
    }

    if (WiFi.waitForConnectResult() != WL_CONNECTED) {
        display_status_wifi(WIFI_ERROR);
    } else {
        display_status_wifi(WIFI_OK);
        display_status_send(SEND_START);
        int res = send_ts(pm25, pm10, t, h);
        if (res == 200) {
            display_status_send(SEND_OK);
        } else {
            display_status_send(SEND_ERROR);
        }
    }

    WiFi.disconnect();
    delay(100);
    WiFi.forceSleepBegin(); // Use WiFi.forceSleepWake() to enable wifi

    delay(3000);
    ESP.deepSleep(1000*1000*config.sleep_time, WAKE_RF_DEFAULT);
}
<commit_msg>normal_mode: don't wait for WIFI forever<commit_after>#include <ESP8266WiFi.h>
#include <Ticker.h>
#include "Sds011.h"
#include "Pcd8544.h"
#include "Expander.h"
#include "Dht.h"
#include "config.h"
#include "send.h"
#include "ui.h"

extern expander::Expander expand;
extern struct Configuration config;
extern sds011::Sds011 sensor;

dht::Dht dht22(14);
Ticker timer1;
Ticker timer2;

static const int SAMPLES=10;
static const int WIFI_TIMEOUT=30;

static void turnOff(void)
{
    expand.digitalWrite(0, HIGH);
}

static void turnOn(void)
{
    uint8_t b = expand.readByte();

    if ((b & 0b10) != 0b10) {
        timer2.once_ms(5000, turnOff);
        expand.digitalWrite(0, LOW);
    }
}

static void iter()
{
    timer1.once_ms(30, turnOn);
}

void normal_setup(void)
{
    dht22.begin();
    expand.attachInterrupt(iter);

    WiFi.mode(WIFI_STA);

    sensor.set_sleep(false);
    sensor.set_mode(sds011::QUERY);
    sensor.set_sleep(true);
}

void normal_loop(void)
{
    int pm25, pm10;
    bool ok;
    int16_t t, h;
    dht::dht_status dhts;

    display_template();

    dhts = dht22.read(&t, &h);
    display_status_dht(dhts);
    if (dhts == dht::DHT_OK) {
        display_temp(t, h);
    }

    WiFi.begin(config.wifi_ssid, config.wifi_pass);
    display_status_wifi(WIFI_CONNECTING);

    sensor.set_sleep(false);
    display_status_sensor(SENSOR_START);
    delay(1000);
    ok = sensor.query_data_auto(&pm25, &pm10, SAMPLES);
    sensor.set_sleep(true);

    if (ok) {
        display_dust(pm25, pm10);
        display_status_sensor(SENSOR_OK);
    } else {
        display_status_sensor(SENSOR_ERROR);
        pm25 = pm10 = 0;
    }

    for (int i = 0; i < WIFI_TIMEOUT; i++) {
        if (WiFi.isConnected()) {
            break;
        }
        delay(1000);
    }
    if (!WiFi.isConnected()) {
        display_status_wifi(WIFI_ERROR);
    } else {
        display_status_wifi(WIFI_OK);
        display_status_send(SEND_START);
        int res = send_ts(pm25, pm10, t, h);
        if (res == 200) {
            display_status_send(SEND_OK);
        } else {
            display_status_send(SEND_ERROR);
        }
    }

    WiFi.disconnect();
    delay(100);
    WiFi.forceSleepBegin(); // Use WiFi.forceSleepWake() to enable wifi

    delay(3000);
    ESP.deepSleep(1000*1000*config.sleep_time, WAKE_RF_DEFAULT);
}
<|endoftext|>


<commit_before>#pragma once

#include <iostream>
#include <iomanip>
#include <chrono>

#include "acmacs-base/to-string.hh"

// ----------------------------------------------------------------------

namespace acmacs
{
    using clock_t = std::chrono::high_resolution_clock;
    using timestamp_t = decltype(clock_t::now());
    using duration_t = std::chrono::nanoseconds;

    inline timestamp_t timestamp() { return clock_t::now(); }

    inline duration_t elapsed(timestamp_t start) { return std::chrono::duration_cast<duration_t>(timestamp() - start); }

    std::string format(duration_t duration);
    inline std::string to_string(duration_t duration) { return format(duration); }

    inline double elapsed_seconds(timestamp_t start) { return std::chrono::duration<double>{timestamp() - start}.count(); }

} // namespace acmacs

// ----------------------------------------------------------------------

enum class report_time { No, Yes };

class Timeit
{
 public:
    inline Timeit(std::string msg, report_time aReport = report_time::Yes, std::ostream& out = std::cerr)
        : message_(msg), out_stream_(out), report_(aReport), start_{acmacs::timestamp()} {}

    inline ~Timeit() { report(); }

    inline void report()
        {
            if (report_ == report_time::Yes) {
                report_ = report_time::No;
                out_stream_ << message_ << acmacs::to_string(acmacs::elapsed(start_)) << '\n';
            }
        }

    inline void message_append(std::string to_append) { message_ += to_append; }

 private:
    std::string message_;
    std::ostream& out_stream_;
    report_time report_;
    acmacs::timestamp_t start_;
};

constexpr report_time do_report_time(bool do_report) { return do_report ? report_time::Yes : report_time::No; }

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>enum report_time updated<commit_after>#pragma once

#include <iostream>
#include <iomanip>
#include <chrono>

#include "acmacs-base/to-string.hh"

// ----------------------------------------------------------------------

namespace acmacs
{
    using clock_t = std::chrono::high_resolution_clock;
    using timestamp_t = decltype(clock_t::now());
    using duration_t = std::chrono::nanoseconds;

    inline timestamp_t timestamp() { return clock_t::now(); }

    inline duration_t elapsed(timestamp_t start) { return std::chrono::duration_cast<duration_t>(timestamp() - start); }

    std::string format(duration_t duration);
    inline std::string to_string(duration_t duration) { return format(duration); }

    inline double elapsed_seconds(timestamp_t start) { return std::chrono::duration<double>{timestamp() - start}.count(); }

} // namespace acmacs

// ----------------------------------------------------------------------

enum class report_time { no, yes };

constexpr report_time do_report_time(bool do_report) { return do_report ? report_time::yes : report_time::no; }

// class report_time_t
// {
//  public:
//     report_time_t() = default;
//     report_time_t(bool do_report) : report_time_{do_report ? report_time::yes : report_time::no} {}
//     constexpr operator report_time() const noexcept { return report_time_; }

//  private:
//     report_time report_time_{report_time::yes};
// };

// ----------------------------------------------------------------------

class Timeit
{
 public:
    inline Timeit(std::string msg, report_time aReport = report_time::yes, std::ostream& out = std::cerr)
        : message_(msg), out_stream_(out), report_(aReport), start_{acmacs::timestamp()} {}

    inline ~Timeit() { report(); }

    inline void report()
        {
            if (report_ == report_time::yes) {
                report_ = report_time::no;
                out_stream_ << message_ << acmacs::to_string(acmacs::elapsed(start_)) << '\n';
            }
        }

    inline void message_append(std::string to_append) { message_ += to_append; }

 private:
    std::string message_;
    std::ostream& out_stream_;
    report_time report_;
    acmacs::timestamp_t start_;
};

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|>


<commit_before>#include "orderinginfo.h"
#include "defs.h"
#include "eval.h"
#include <cstring>

OrderingInfo::OrderingInfo(const TranspTable* tt) {
  _tt = tt;
  _ply = 0;
  std::memset(_history, 0, sizeof(_history));
}

void OrderingInfo::incrementHistory(Color color, int from, int to, int depth) {
  _history[color][from][to] += depth^2;
}

int OrderingInfo::getHistory(Color color, int from, int to) const {
  return _history[color][from][to];
}

void OrderingInfo::incrementPly() {
  _ply++;
}

void OrderingInfo::deincrementPly() {
  _ply--;
}

int OrderingInfo::getPly() const {
  return _ply;
}

const TranspTable* OrderingInfo::getTt() const {
  return _tt;
}

void OrderingInfo::updateKillers(int ply, Move move) {
  _killer2[ply] = _killer1[ply];
  _killer1[ply] = move;
}

Move OrderingInfo::getKiller1(int ply) const {
  return _killer1[ply];
}

Move OrderingInfo::getKiller2(int ply) const {
  return _killer2[ply];
}<commit_msg>Fix incorrect operator in OrderingInfo<commit_after>#include "orderinginfo.h"
#include "defs.h"
#include "eval.h"
#include <cstring>

OrderingInfo::OrderingInfo(const TranspTable* tt) {
  _tt = tt;
  _ply = 0;
  std::memset(_history, 0, sizeof(_history));
}

void OrderingInfo::incrementHistory(Color color, int from, int to, int depth) {
  _history[color][from][to] += depth*depth;
}

int OrderingInfo::getHistory(Color color, int from, int to) const {
  return _history[color][from][to];
}

void OrderingInfo::incrementPly() {
  _ply++;
}

void OrderingInfo::deincrementPly() {
  _ply--;
}

int OrderingInfo::getPly() const {
  return _ply;
}

const TranspTable* OrderingInfo::getTt() const {
  return _tt;
}

void OrderingInfo::updateKillers(int ply, Move move) {
  _killer2[ply] = _killer1[ply];
  _killer1[ply] = move;
}

Move OrderingInfo::getKiller1(int ply) const {
  return _killer1[ply];
}

Move OrderingInfo::getKiller2(int ply) const {
  return _killer2[ply];
}<|endoftext|>


<commit_before>#ifndef _CONTRAST_SUBMODULAR_FEATURE_HPP_
#define _CONTRAST_SUBMODULAR_FEATURE_HPP_

#include "interactive_seg_app.hpp"
#include "feature.hpp"
#include <opencv2/core/core.hpp>
#include <boost/serialization/access.hpp>
#include <boost/serialization/base_object.hpp>
#include <boost/serialization/export.hpp>

class ContrastSubmodularFeature : public InteractiveSegApp::FG {
    public:
    typedef InteractiveSegApp::FG::Constr Constr;
    typedef std::function<void(const std::vector<unsigned char>&)> PatchFn;
    typedef uint32_t Assgn;

    static constexpr Assgn clique_size = 4;
    static constexpr size_t per_cluster = (1 << clique_size) - 2;
    static constexpr size_t num_clusters = 50;
    double m_scale;

    ContrastSubmodularFeature() : m_scale(1.0) { }
    explicit ContrastSubmodularFeature(double scale) : m_scale(scale) { }

    virtual size_t NumFeatures() const override { return per_cluster*num_clusters; }
    virtual std::vector<FVAL> Psi(const IS_PatternData& p, const IS_LabelData& l) const override {
        cv::Mat patch_feature = m_patch_feature[p.Name()];
        const Assgn all_zeros = 0;
        const Assgn all_ones = (1 << clique_size) - 1;
        std::vector<FVAL> psi(NumFeatures(), 0);
        cv::Point base, pt;
        const cv::Point patch_size(1.0, 1.0);
        for (base.y = 0; base.y + patch_size.y < p.m_image.rows; ++base.y) {
            for (base.x = 0; base.x + patch_size.x < p.m_image.cols; ++base.x) {
                Assgn a = 0;
                int feature = patch_feature.at<int>(base);
                int i = 0;
                for (pt.y = base.y; pt.y <= base.y + patch_size.y; ++pt.y) {
                    for (pt.x = base.x; pt.x <= base.x + patch_size.x; ++pt.x) {
                        unsigned char label = l.m_gt.at<unsigned char>(pt);
                        if (label == cv::GC_FGD || label == cv::GC_PR_FGD)
                            a |= 1 << i;
                        i++;
                    }
                }
                if (a != all_zeros && a != all_ones)
                    psi[a-1 + feature*per_cluster] += m_scale;
            }
        }
        for (auto& v : psi)
            v = -v;
        return psi;
    }
    virtual void AddToCRF(CRF& crf, const IS_PatternData& p, double* w) const override {
        cv::Mat patch_feature = m_patch_feature[p.Name()];
        std::vector<std::vector<REAL>> costTables(num_clusters, std::vector<REAL>(per_cluster+2, 0));
        for (size_t i = 0; i < num_clusters; ++i) {
            for (size_t j = 0; j < per_cluster; ++j) {
                costTables[i][j+1] = doubleToREAL(m_scale*w[i*per_cluster+j]);
            }
        }
        cv::Point base, pt;
        const cv::Point patch_size(1.0, 1.0);
        for (base.y = 0; base.y + patch_size.y < p.m_image.rows; ++base.y) {
            for (base.x = 0; base.x + patch_size.x < p.m_image.cols; ++base.x) {
                std::vector<CRF::NodeId> vars;
                int feature = patch_feature.at<int>(base);
                for (pt.y = base.y; pt.y <= base.y + patch_size.y; ++pt.y) {
                    for (pt.x = base.x; pt.x <= base.x + patch_size.x; ++pt.x) {
                        vars.push_back(pt.y*p.m_image.cols + pt.x);
                    }
                }
                crf.AddClique(vars, costTables[feature]);
            }
        }
    }
    virtual Constr CollectConstrs(size_t feature_base, double constraint_scale) const override {
        typedef std::vector<std::pair<size_t, double>> LHS;
        typedef double RHS;
        Constr ret;
        Assgn all_zeros = 0;
        Assgn all_ones = (1 << clique_size) - 1;
        for (size_t cluster = 0; cluster < num_clusters; ++cluster) {
            size_t base = feature_base + cluster*per_cluster;
            for (Assgn s = 0; s < all_ones; ++s) {
                for (size_t i = 0; i < clique_size; ++i) {
                    Assgn si = s | (1 << i);
                    if (si != s) {
                        for (size_t j = i+1; j < clique_size; ++j) {
                            Assgn t = s | (1 << j);
                            if (t != s && j != i) {
                                Assgn ti = t | (1 << i);
                                // Decreasing marginal costs, so we require
                                // f(ti) - f(t) <= f(si) - f(s)
                                // i.e. f(si) - f(s) - f(ti) + f(t) >= 0
                                LHS lhs = {{base+si-1, constraint_scale}, {base+t-1, constraint_scale}};
                                if (s != all_zeros) lhs.push_back(std::make_pair(base+s-1, -constraint_scale));
                                if (ti != all_ones) lhs.push_back(std::make_pair(base+ti-1, -constraint_scale));
                                RHS rhs = 0;
                                ret.push_back(std::make_pair(lhs, rhs));
                            }
                        }
                    }
                }
            }
        }
        return ret;
    }
    virtual double Violation(size_t feature_base, double* w) const override {
        size_t num_constraints = 0;
        double total_violation = 0;
        Assgn all_zeros = 0;
        Assgn all_ones = (1 << clique_size) - 1;
        for (size_t cluster = 0; cluster < num_clusters; ++cluster) {
            size_t base = feature_base + cluster*per_cluster;
            for (Assgn s = 0; s < all_ones; ++s) {
                for (size_t i = 0; i < clique_size; ++i) {
                    Assgn si = s | (1 << i);
                    if (si != s) {
                        for (size_t j = i+1; j < clique_size; ++j) {
                            Assgn t = s | (1 << j);
                            if (t != s && j != i) {
                                Assgn ti = t | (1 << i);
                                num_constraints++;
                                // Decreasing marginal costs, so we require
                                // f(ti) - f(t) <= f(si) - f(s)
                                // i.e. f(si) - f(s) - f(ti) + f(t) >= 0
                                double violation = -w[base+si-1] - w[base+t-1];
                                if (s != all_zeros) violation += w[base+s-1];
                                if (ti != all_ones) violation += w[base+ti-1];
                                if (violation > 0) total_violation += violation;
                            }
                        }
                    }
                }
            }
        }
        //std::cout << "Num constraints: " << num_constraints <<"\n";
        //std::cout << "Min violation: " << min_violation << "\n";
        return total_violation;
    }
    virtual void Train(const std::vector<IS_PatternData*>& patterns, const std::vector<IS_LabelData*>& labels) {
        cv::Mat samples;
        std::cout << "Training submodular filters -- ";
        std::cout.flush();
        samples.create(0, num_filters, CV_32FC1);
        for (const IS_PatternData* xp : patterns) {
            cv::Mat im = xp->m_image;
            cv::Mat response;
            GetResponse(im, response);
            samples.push_back(response);
        }
        std::cout << samples.rows << " samples...";
        std::cout.flush();
        cv::Mat best_labels;
        cv::kmeans(samples, num_clusters, best_labels, cv::TermCriteria(CV_TERMCRIT_EPS, 10, 0.01), 3, cv::KMEANS_RANDOM_CENTERS, m_centers);
        std::cout << "Done!\n";
    }
    virtual void Evaluate(const std::vector<IS_PatternData*>& patterns) override {
        std::cout << "Evaluating Contrast Submodular Features...";
        std::cout.flush();
        for (const IS_PatternData* xp : patterns) {
            cv::Mat im = xp->m_image;
            cv::Mat response;
            cv::Mat& features = m_patch_feature[xp->Name()];
            GetResponse(im, response);
            features.create(im.rows, im.cols, CV_32SC1);
            Classify(response, features, m_centers);
        }
        std::cout << "Done!\n";
    }
    virtual void SaveEvaluation(const std::string& output_dir) const {
        std::string outfile = output_dir + "/contrast-submodular-feature.dat";
        std::ofstream os(outfile, std::ios_base::binary);
        boost::archive::binary_oarchive ar(os);
        ar & m_patch_feature;
    }
    virtual void LoadEvaluation(const std::string& output_dir) {
        std::string infile = output_dir + "/contrast-submodular-feature.dat";
        std::ifstream is(infile, std::ios_base::binary);
        boost::archive::binary_iarchive ar(is);
        ar & m_patch_feature;
    }
    private:
    static constexpr int num_filters = 12;
    void FilterResponse(cv::Mat im, cv::Mat& out) {
        ASSERT(im.channels() == 3);
        ASSERT(im.type() == CV_32FC3);
        const size_t samples = im.rows*im.cols;
        out.create(samples, num_filters, CV_32FC1);

        std::vector<cv::Mat> all_filtered;
        cv::Mat filtered;
        filtered.create(im.rows, im.cols, CV_32FC3);

        cv::Mat x_deriv = (cv::Mat_<float>(2,2) << 1.0, -1.0, 1.0, -1.0);
        cv::filter2D(im, filtered, CV_32F, x_deriv, cv::Point(0,0));
        all_filtered.push_back(filtered);

        cv::Mat y_deriv = (cv::Mat_<float>(2,2) << 1.0, 1.0, -1.0, -1.0);
        cv::filter2D(im, filtered, CV_32F, y_deriv, cv::Point(0,0));
        all_filtered.push_back(filtered);

        cv::Mat xy_deriv = (cv::Mat_<float>(2,2) << 1.0, 0.0, 0.0, -1.0);
        cv::filter2D(im, filtered, CV_32F, xy_deriv, cv::Point(0,0));
        all_filtered.push_back(filtered);

        cv::Mat yx_deriv = (cv::Mat_<float>(2,2) << 0.0, 1.0, -1.0, 0.0);
        cv::filter2D(im, filtered, CV_32F, yx_deriv, cv::Point(0,0));
        all_filtered.push_back(filtered);

        cv::Point pf, po;
        po.y = 0;
        for (pf.y = 0; pf.y < im.rows; ++pf.y) {
            for (pf.x = 0; pf.x < im.cols; ++pf.x) {
                po.x = 0;
                for (int i = 0; i < num_filters/3; ++i) {
                    cv::Vec3f v = all_filtered[i].at<cv::Vec3f>(pf);
                    for (int j = 0; j < 3; ++j, ++po.x) {
                        out.at<float>(po) = v[j];
                    }
                }
                ASSERT(po.x == num_filters);
                po.y++;
            }
        }
        ASSERT(po.y == out.rows);
    }
    void GetResponse(cv::Mat im, cv::Mat& response) {
            cv::Mat tmp;
            im.convertTo(tmp, CV_32F);
            FilterResponse(tmp, response);
            ASSERT(response.rows == im.cols*im.rows);
            ASSERT(response.cols == num_filters);
    }
    void Subsample(cv::Mat in, cv::Mat& out, size_t num_samples) {
        std::uniform_int_distribution<size_t> dist(0, in.rows-1);
        out.create(num_samples, in.cols, in.type());
        for (size_t i = 0; i < num_samples; ++i) {
            size_t r = dist(gen);
            in.row(r).copyTo(out.row(i));
        }
    }
    void Classify(cv::Mat response, cv::Mat& out, cv::Mat centers) {
        ASSERT(response.cols == num_filters);
        ASSERT(centers.cols == num_filters);
        ASSERT((size_t)centers.rows == num_clusters);
        std::vector<size_t> counts(num_clusters, 0);
        size_t i = 0;
        cv::Point p;
        for (p.y = 0; p.y < out.rows; ++p.y) {
            for (p.x = 0; p.x < out.cols; ++p.x) {
                ASSERT(i < (size_t)response.rows);
                cv::Mat row = response.row(i);
                double min_dist = std::numeric_limits<double>::max();
                int min_center = 0;
                for (int j = 0; j < centers.rows; ++j) {
                    cv::Mat center = centers.row(j);
                    double dist = cv::norm(row, center);
                    if (dist < min_dist) {
                        min_dist = dist;
                        min_center = j;
                    }
                }
                counts[min_center]++;
                ASSERT(min_dist < std::numeric_limits<double>::max());
                out.at<int>(p) = min_center;
                i++;
            }
        }
        std::cout << "Cluster counts: ";
        for (auto c : counts)
            std::cout << c << " ";
        std::cout << "\n";
    }
    friend class boost::serialization::access;
    template <class Archive>
    void serialize(Archive& ar, const unsigned int version) {
        //std::cout << "Serializing ContrastSubmodularFeature\n";
        ar & boost::serialization::base_object<FeatureGroup>(*this);
        ar & m_scale;
    }
    mutable std::map<std::string, cv::Mat> m_patch_feature;
    std::mt19937 gen;
    cv::Mat m_centers;
};

BOOST_CLASS_EXPORT_GUID(ContrastSubmodularFeature, "ContrastSubmodularFeature")

#endif
<commit_msg>Removing fixing f(0) = f(S) = 0 for contrast-submodular<commit_after>#ifndef _CONTRAST_SUBMODULAR_FEATURE_HPP_
#define _CONTRAST_SUBMODULAR_FEATURE_HPP_

#include "interactive_seg_app.hpp"
#include "feature.hpp"
#include <opencv2/core/core.hpp>
#include <boost/serialization/access.hpp>
#include <boost/serialization/base_object.hpp>
#include <boost/serialization/export.hpp>

class ContrastSubmodularFeature : public InteractiveSegApp::FG {
    public:
    typedef InteractiveSegApp::FG::Constr Constr;
    typedef std::function<void(const std::vector<unsigned char>&)> PatchFn;
    typedef uint32_t Assgn;

    static constexpr Assgn clique_size = 4;
    static constexpr size_t per_cluster = (1 << clique_size);
    static constexpr size_t num_clusters = 50;
    double m_scale;

    ContrastSubmodularFeature() : m_scale(1.0) { }
    explicit ContrastSubmodularFeature(double scale) : m_scale(scale) { }

    virtual size_t NumFeatures() const override { return per_cluster*num_clusters; }
    virtual std::vector<FVAL> Psi(const IS_PatternData& p, const IS_LabelData& l) const override {
        cv::Mat patch_feature = m_patch_feature[p.Name()];
        std::vector<FVAL> psi(NumFeatures(), 0);
        cv::Point base, pt;
        const cv::Point patch_size(1.0, 1.0);
        for (base.y = 0; base.y + patch_size.y < p.m_image.rows; ++base.y) {
            for (base.x = 0; base.x + patch_size.x < p.m_image.cols; ++base.x) {
                Assgn a = 0;
                int feature = patch_feature.at<int>(base);
                int i = 0;
                for (pt.y = base.y; pt.y <= base.y + patch_size.y; ++pt.y) {
                    for (pt.x = base.x; pt.x <= base.x + patch_size.x; ++pt.x) {
                        unsigned char label = l.m_gt.at<unsigned char>(pt);
                        if (label == cv::GC_FGD || label == cv::GC_PR_FGD)
                            a |= 1 << i;
                        i++;
                    }
                }
                psi[a + feature*per_cluster] += m_scale;
            }
        }
        for (auto& v : psi)
            v = -v;
        return psi;
    }
    virtual void AddToCRF(CRF& crf, const IS_PatternData& p, double* w) const override {
        cv::Mat patch_feature = m_patch_feature[p.Name()];
        std::vector<std::vector<REAL>> costTables(num_clusters, std::vector<REAL>(per_cluster+2, 0));
        for (size_t i = 0; i < num_clusters; ++i) {
            for (size_t j = 0; j < per_cluster; ++j) {
                costTables[i][j] = doubleToREAL(m_scale*w[i*per_cluster+j]);
            }
        }
        cv::Point base, pt;
        const cv::Point patch_size(1.0, 1.0);
        for (base.y = 0; base.y + patch_size.y < p.m_image.rows; ++base.y) {
            for (base.x = 0; base.x + patch_size.x < p.m_image.cols; ++base.x) {
                std::vector<CRF::NodeId> vars;
                int feature = patch_feature.at<int>(base);
                for (pt.y = base.y; pt.y <= base.y + patch_size.y; ++pt.y) {
                    for (pt.x = base.x; pt.x <= base.x + patch_size.x; ++pt.x) {
                        vars.push_back(pt.y*p.m_image.cols + pt.x);
                    }
                }
                crf.AddClique(vars, costTables[feature]);
            }
        }
    }
    virtual Constr CollectConstrs(size_t feature_base, double constraint_scale) const override {
        typedef std::vector<std::pair<size_t, double>> LHS;
        typedef double RHS;
        Constr ret;
        Assgn all_ones = (1 << clique_size) - 1;
        for (size_t cluster = 0; cluster < num_clusters; ++cluster) {
            size_t base = feature_base + cluster*per_cluster;
            for (Assgn s = 0; s < all_ones; ++s) {
                for (size_t i = 0; i < clique_size; ++i) {
                    Assgn si = s | (1 << i);
                    if (si != s) {
                        for (size_t j = i+1; j < clique_size; ++j) {
                            Assgn t = s | (1 << j);
                            if (t != s && j != i) {
                                Assgn ti = t | (1 << i);
                                // Decreasing marginal costs, so we require
                                // f(ti) - f(t) <= f(si) - f(s)
                                // i.e. f(si) - f(s) - f(ti) + f(t) >= 0
                                LHS lhs = {{base+si, constraint_scale}, {base+t, constraint_scale}};
                                lhs.push_back(std::make_pair(base+s, -constraint_scale));
                                lhs.push_back(std::make_pair(base+ti, -constraint_scale));
                                RHS rhs = 0;
                                ret.push_back(std::make_pair(lhs, rhs));
                            }
                        }
                    }
                }
            }
        }
        return ret;
    }
    virtual double Violation(size_t feature_base, double* w) const override {
        size_t num_constraints = 0;
        double total_violation = 0;
        Assgn all_ones = (1 << clique_size) - 1;
        for (size_t cluster = 0; cluster < num_clusters; ++cluster) {
            size_t base = feature_base + cluster*per_cluster;
            for (Assgn s = 0; s < all_ones; ++s) {
                for (size_t i = 0; i < clique_size; ++i) {
                    Assgn si = s | (1 << i);
                    if (si != s) {
                        for (size_t j = i+1; j < clique_size; ++j) {
                            Assgn t = s | (1 << j);
                            if (t != s && j != i) {
                                Assgn ti = t | (1 << i);
                                num_constraints++;
                                // Decreasing marginal costs, so we require
                                // f(ti) - f(t) <= f(si) - f(s)
                                // i.e. f(si) - f(s) - f(ti) + f(t) >= 0
                                double violation = -w[base+si] - w[base+t];
                                violation += w[base+s];
                                violation += w[base+ti];
                                if (violation > 0) total_violation += violation;
                            }
                        }
                    }
                }
            }
        }
        //std::cout << "Num constraints: " << num_constraints <<"\n";
        //std::cout << "Min violation: " << min_violation << "\n";
        return total_violation;
    }
    virtual void Train(const std::vector<IS_PatternData*>& patterns, const std::vector<IS_LabelData*>& labels) {
        cv::Mat samples;
        std::cout << "Training submodular filters -- ";
        std::cout.flush();
        samples.create(0, num_filters, CV_32FC1);
        for (const IS_PatternData* xp : patterns) {
            cv::Mat im = xp->m_image;
            cv::Mat response;
            GetResponse(im, response);
            samples.push_back(response);
        }
        std::cout << samples.rows << " samples...";
        std::cout.flush();
        cv::Mat best_labels;
        cv::kmeans(samples, num_clusters, best_labels, cv::TermCriteria(CV_TERMCRIT_EPS, 10, 0.01), 3, cv::KMEANS_RANDOM_CENTERS, m_centers);
        std::cout << "Done!\n";
    }
    virtual void Evaluate(const std::vector<IS_PatternData*>& patterns) override {
        std::cout << "Evaluating Contrast Submodular Features...";
        std::cout.flush();
        for (const IS_PatternData* xp : patterns) {
            cv::Mat im = xp->m_image;
            cv::Mat response;
            cv::Mat& features = m_patch_feature[xp->Name()];
            GetResponse(im, response);
            features.create(im.rows, im.cols, CV_32SC1);
            Classify(response, features, m_centers);
        }
        std::cout << "Done!\n";
    }
    virtual void SaveEvaluation(const std::string& output_dir) const {
        std::string outfile = output_dir + "/contrast-submodular-feature.dat";
        std::ofstream os(outfile, std::ios_base::binary);
        boost::archive::binary_oarchive ar(os);
        ar & m_patch_feature;
    }
    virtual void LoadEvaluation(const std::string& output_dir) {
        std::string infile = output_dir + "/contrast-submodular-feature.dat";
        std::ifstream is(infile, std::ios_base::binary);
        boost::archive::binary_iarchive ar(is);
        ar & m_patch_feature;
    }
    private:
    static constexpr int num_filters = 12;
    void FilterResponse(cv::Mat im, cv::Mat& out) {
        ASSERT(im.channels() == 3);
        ASSERT(im.type() == CV_32FC3);
        const size_t samples = im.rows*im.cols;
        out.create(samples, num_filters, CV_32FC1);

        std::vector<cv::Mat> all_filtered;
        cv::Mat filtered;
        filtered.create(im.rows, im.cols, CV_32FC3);

        cv::Mat x_deriv = (cv::Mat_<float>(2,2) << 1.0, -1.0, 1.0, -1.0);
        cv::filter2D(im, filtered, CV_32F, x_deriv, cv::Point(0,0));
        all_filtered.push_back(filtered);

        cv::Mat y_deriv = (cv::Mat_<float>(2,2) << 1.0, 1.0, -1.0, -1.0);
        cv::filter2D(im, filtered, CV_32F, y_deriv, cv::Point(0,0));
        all_filtered.push_back(filtered);

        cv::Mat xy_deriv = (cv::Mat_<float>(2,2) << 1.0, 0.0, 0.0, -1.0);
        cv::filter2D(im, filtered, CV_32F, xy_deriv, cv::Point(0,0));
        all_filtered.push_back(filtered);

        cv::Mat yx_deriv = (cv::Mat_<float>(2,2) << 0.0, 1.0, -1.0, 0.0);
        cv::filter2D(im, filtered, CV_32F, yx_deriv, cv::Point(0,0));
        all_filtered.push_back(filtered);

        cv::Point pf, po;
        po.y = 0;
        for (pf.y = 0; pf.y < im.rows; ++pf.y) {
            for (pf.x = 0; pf.x < im.cols; ++pf.x) {
                po.x = 0;
                for (int i = 0; i < num_filters/3; ++i) {
                    cv::Vec3f v = all_filtered[i].at<cv::Vec3f>(pf);
                    for (int j = 0; j < 3; ++j, ++po.x) {
                        out.at<float>(po) = v[j];
                    }
                }
                ASSERT(po.x == num_filters);
                po.y++;
            }
        }
        ASSERT(po.y == out.rows);
    }
    void GetResponse(cv::Mat im, cv::Mat& response) {
            cv::Mat tmp;
            im.convertTo(tmp, CV_32F);
            FilterResponse(tmp, response);
            ASSERT(response.rows == im.cols*im.rows);
            ASSERT(response.cols == num_filters);
    }
    void Subsample(cv::Mat in, cv::Mat& out, size_t num_samples) {
        std::uniform_int_distribution<size_t> dist(0, in.rows-1);
        out.create(num_samples, in.cols, in.type());
        for (size_t i = 0; i < num_samples; ++i) {
            size_t r = dist(gen);
            in.row(r).copyTo(out.row(i));
        }
    }
    void Classify(cv::Mat response, cv::Mat& out, cv::Mat centers) {
        ASSERT(response.cols == num_filters);
        ASSERT(centers.cols == num_filters);
        ASSERT((size_t)centers.rows == num_clusters);
        std::vector<size_t> counts(num_clusters, 0);
        size_t i = 0;
        cv::Point p;
        for (p.y = 0; p.y < out.rows; ++p.y) {
            for (p.x = 0; p.x < out.cols; ++p.x) {
                ASSERT(i < (size_t)response.rows);
                cv::Mat row = response.row(i);
                double min_dist = std::numeric_limits<double>::max();
                int min_center = 0;
                for (int j = 0; j < centers.rows; ++j) {
                    cv::Mat center = centers.row(j);
                    double dist = cv::norm(row, center);
                    if (dist < min_dist) {
                        min_dist = dist;
                        min_center = j;
                    }
                }
                counts[min_center]++;
                ASSERT(min_dist < std::numeric_limits<double>::max());
                out.at<int>(p) = min_center;
                i++;
            }
        }
        std::cout << "Cluster counts: ";
        for (auto c : counts)
            std::cout << c << " ";
        std::cout << "\n";
    }
    friend class boost::serialization::access;
    template <class Archive>
    void serialize(Archive& ar, const unsigned int version) {
        //std::cout << "Serializing ContrastSubmodularFeature\n";
        ar & boost::serialization::base_object<FeatureGroup>(*this);
        ar & m_scale;
    }
    mutable std::map<std::string, cv::Mat> m_patch_feature;
    std::mt19937 gen;
    cv::Mat m_centers;
};

BOOST_CLASS_EXPORT_GUID(ContrastSubmodularFeature, "ContrastSubmodularFeature")

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: macropg_impl.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2006-07-14 07:18:30 $
 *
 *  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
 *
 ************************************************************************/

#ifndef _MACROPG_IMPL_HXX
#define _MACROPG_IMPL_HXX

class _SvxMacroTabPage_Impl
{
public:
                                    _SvxMacroTabPage_Impl( const SfxItemSet& rAttrSet );
                                    ~_SvxMacroTabPage_Impl();

    FixedText*                      pAssignFT;
    PushButton*                     pAssignPB;
    PushButton*                     pAssignComponentPB;
    PushButton*                     pDeletePB;
    Image*                          pMacroImg;
    Image*                          pComponentImg;
    Image*                          pMacroImg_h;
    Image*                          pComponentImg_h;
    String*                         pStrEvent;
    String*                         pAssignedMacro;
    _HeaderTabListBox*              pEventLB;
    BOOL                            bReadOnly;
    BOOL                            bIDEDialogMode;
};

class AssignComponentDialog : public ModalDialog
{
private:
    FixedText       maMethodLabel;
    Edit            maMethodEdit;
    OKButton        maOKButton;
    CancelButton    maCancelButton;
    HelpButton      maHelpButton;

    ::rtl::OUString maURL;

    DECL_LINK(ButtonHandler, Button *);

public:
    AssignComponentDialog( Window * pParent, const ::rtl::OUString& rURL );
    ~AssignComponentDialog();

    ::rtl::OUString getURL( void ) const
        { return maURL; }
};

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.4.820); FILE MERGED 2008/03/31 14:22:21 rt 1.4.820.1: #i87441# Change license header to LPGL v3.<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: macropg_impl.hxx,v $
 * $Revision: 1.5 $
 *
 * 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 _MACROPG_IMPL_HXX
#define _MACROPG_IMPL_HXX

class _SvxMacroTabPage_Impl
{
public:
                                    _SvxMacroTabPage_Impl( const SfxItemSet& rAttrSet );
                                    ~_SvxMacroTabPage_Impl();

    FixedText*                      pAssignFT;
    PushButton*                     pAssignPB;
    PushButton*                     pAssignComponentPB;
    PushButton*                     pDeletePB;
    Image*                          pMacroImg;
    Image*                          pComponentImg;
    Image*                          pMacroImg_h;
    Image*                          pComponentImg_h;
    String*                         pStrEvent;
    String*                         pAssignedMacro;
    _HeaderTabListBox*              pEventLB;
    BOOL                            bReadOnly;
    BOOL                            bIDEDialogMode;
};

class AssignComponentDialog : public ModalDialog
{
private:
    FixedText       maMethodLabel;
    Edit            maMethodEdit;
    OKButton        maOKButton;
    CancelButton    maCancelButton;
    HelpButton      maHelpButton;

    ::rtl::OUString maURL;

    DECL_LINK(ButtonHandler, Button *);

public:
    AssignComponentDialog( Window * pParent, const ::rtl::OUString& rURL );
    ~AssignComponentDialog();

    ::rtl::OUString getURL( void ) const
        { return maURL; }
};

#endif
<|endoftext|>