<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: apitreeaccess.hxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 03:09:23 $
 *
 *  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 CONFIGMGR_API_TREEACCESS_HXX_
#define CONFIGMGR_API_TREEACCESS_HXX_

#ifndef CONFIGMGR_ACCESSOR_HXX
#include "accessor.hxx"
#endif
#ifndef CONFIGMGR_MISC_OPTIONS_HXX_
#include "options.hxx"
#endif
#ifndef CONFIGMGR_UTILITY_HXX_
#include "utility.hxx"
#endif

namespace osl { class Mutex; }

namespace configmgr
{
//-----------------------------------------------------------------------------
    struct ServiceImplementationInfo;
//-----------------------------------------------------------------------------
    namespace memory
    {
        class Accessor;
        class Segment;
    }
//-----------------------------------------------------------------------------
    namespace configuration
    {
        class Name;
        class Tree;
        class TreeRef;
        class ElementRef;
//      class RootTree;

        class TemplateInfo;
    }
//-----------------------------------------------------------------------------
    namespace configapi
    {
//-----------------------------------------------------------------------------
        namespace uno = com::sun::star::uno;
        typedef uno::XInterface UnoInterface;
        typedef uno::Any UnoAny;
//-----------------------------------------------------------------------------
        class Factory;
        class Notifier;
        class Committer;
        class NodeSetInfoAccess;
//-----------------------------------------------------------------------------
    // API object implementation wrappers
    //-------------------------------------------------------------------------
        class ApiTreeImpl;
        class ApiRootTreeImpl;

        // these objects just provide the pieces needed to navigate and manipulate trees and nodes

        // A common base class for 'element' classes
        class NodeElement : Noncopyable
        {
        public:
            typedef ServiceImplementationInfo ServiceInfo;
        public:
            virtual ~NodeElement() {}

        // self-locked methods for dispose handling
            void checkAlive() const;

        // api object handling
            UnoInterface* getUnoInstance() const
            { return doGetUnoInstance(); }

            ServiceInfo const * getServiceInfo() const
            { return doGetServiceInfo(); }
        private:
            virtual UnoInterface* doGetUnoInstance() const = 0;
            virtual ServiceInfo const* doGetServiceInfo() const = 0;
            virtual ApiTreeImpl& getApiTree() const = 0;

            friend class Factory;
        };
//-----------------------------------------------------------------------------

        // A class for tagging inner nodes
        class InnerElement : public NodeElement
        {
        public:
            // Only used as a tag
        };
//-----------------------------------------------------------------------------

        // A common base class for tree-owning elemnt classes
        class TreeElement : public NodeElement
        {
        public:
        // model access
            configuration::TreeRef      getTreeRef() const;
            configuration::Tree         getTree(memory::Accessor const& _aAccessor) const;

        // api object handling
            Factory&                    getFactory();
            Notifier                    getNotifier();

        // locking support
            osl::Mutex&                 getDataLock() const;
            osl::Mutex&                 getApiLock();
        protected:
            virtual ApiTreeImpl& getApiTree() const = 0;
        };
//-----------------------------------------------------------------------------

        // Info interfaces for Set Elements
        class SetElement : public TreeElement
        {
        public:
        // self-locked methods for dispose handling
            bool disposeTree(bool bForceDispose);

            void haveNewParent(NodeSetInfoAccess* pNewParent);

            configuration::ElementRef       getElementRef() const;
            configuration::TemplateInfo     getTemplateInfo() const;
        };
//-----------------------------------------------------------------------------

        // Info interfaces for Set Elements
        class RootElement : public TreeElement
        {
        public:
            bool disposeTree();

            memory::Segment const* getSourceData();
        protected:
            virtual ApiRootTreeImpl& getRootTree() = 0;
        };
//-----------------------------------------------------------------------------

        // Info interfaces for Set Elements
        class UpdateRootElement : public RootElement
        {
        public:
            Committer getCommitter();
        };
//-----------------------------------------------------------------------------
        /// guards a TreeElement; provides an object (read) lock, ensures object was not disposed
        class TreeReadGuardImpl : Noncopyable
        {
            osl::MutexGuard     m_aViewLock;
            TreeElement&        m_rTree;
        public:
            TreeReadGuardImpl(TreeElement& rTree);
            ~TreeReadGuardImpl() throw ();
        public:
            TreeElement&    get() const { return m_rTree; }
        };

    // Thin Wrappers around TreeElements: Provide guarding and convenient access
        /// wraps a TreeElement; provides an object (read) lock, ensures object was not disposed
        class GuardedTreeElement
        {
            TreeReadGuardImpl   m_aImpl;
        public:
            GuardedTreeElement(TreeElement& rTree) : m_aImpl(rTree) {}
        public:
            TreeElement&    get() const { return m_aImpl.get(); }
        };

        class GuardedRootElement
        {
            memory::Accessor      m_aDataAccess;
            TreeReadGuardImpl   m_aImpl;
        public:
            GuardedRootElement(RootElement& rTree);
        public:
            RootElement& get() const { return static_cast<RootElement&>(m_aImpl.get()); }

            configuration::Tree getTree() const;

            memory::Accessor const & getDataAccessor() const { return m_aDataAccess; };
        };
//-----------------------------------------------------------------------------
    }
}

#endif // CONFIGMGR_API_TREEACCESS_HXX_
<commit_msg>INTEGRATION: CWS configrefactor01 (1.10.84); FILE MERGED 2007/02/07 12:14:54 mmeeks 1.10.84.5: remove obsolete memory::Segment forward decls. 2007/01/16 12:18:18 mmeeks 1.10.84.4: Submitted by: mmeeks Kill 'memory::Segment' - no longer needed. Bin some other (empty / redundant) headers. 2007/01/12 17:51:17 mmeeks 1.10.84.3: RIP 'memory::Accessor' 2007/01/11 20:15:57 mmeeks 1.10.84.2: Submitted by: mmeeks More re-factoring, lots of locking rationalized, drastically reduced the mutex count, also removed ~300k interlocked increments with a non-interlocking SimpleReferencedObject base 2007/01/11 10:35:24 mmeeks 1.10.84.1: Submitted by: mmeeks<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: apitreeaccess.hxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: ihi $ $Date: 2007-11-23 14:04:08 $
 *
 *  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 CONFIGMGR_API_TREEACCESS_HXX_
#define CONFIGMGR_API_TREEACCESS_HXX_

#ifndef CONFIGMGR_MISC_OPTIONS_HXX_
#include "options.hxx"
#endif
#ifndef CONFIGMGR_UTILITY_HXX_
#include "utility.hxx"
#endif

namespace osl { class Mutex; }

namespace configmgr
{
//-----------------------------------------------------------------------------
    struct ServiceImplementationInfo;
//-----------------------------------------------------------------------------
    namespace configuration
    {
        class Name;
        class Tree;
        class TreeRef;
        class ElementRef;

        class TemplateInfo;
    }
//-----------------------------------------------------------------------------
    namespace configapi
    {
//-----------------------------------------------------------------------------
        namespace uno = com::sun::star::uno;
        typedef uno::XInterface UnoInterface;
        typedef uno::Any UnoAny;
//-----------------------------------------------------------------------------
        class Factory;
        class Notifier;
        class Committer;
        class NodeSetInfoAccess;
//-----------------------------------------------------------------------------
    // API object implementation wrappers
    //-------------------------------------------------------------------------
        class ApiTreeImpl;
        class ApiRootTreeImpl;

        // these objects just provide the pieces needed to navigate and manipulate trees and nodes

        // A common base class for 'element' classes
        class NodeElement : Noncopyable
        {
        public:
            typedef ServiceImplementationInfo ServiceInfo;
        public:
            virtual ~NodeElement() {}

        // self-locked methods for dispose handling
            void checkAlive() const;

        // api object handling
            UnoInterface* getUnoInstance() const
            { return doGetUnoInstance(); }

            ServiceInfo const * getServiceInfo() const
            { return doGetServiceInfo(); }
        private:
            virtual UnoInterface* doGetUnoInstance() const = 0;
            virtual ServiceInfo const* doGetServiceInfo() const = 0;
            virtual ApiTreeImpl& getApiTree() const = 0;

            friend class Factory;
        };
//-----------------------------------------------------------------------------

        // A class for tagging inner nodes
        class InnerElement : public NodeElement
        {
        public:
            // Only used as a tag
        };
//-----------------------------------------------------------------------------

        // A common base class for tree-owning elemnt classes
        class TreeElement : public NodeElement
        {
        public:
        // model access
            configuration::TreeRef      getTreeRef() const;
            configuration::Tree         getTree() const;

        // api object handling
            Factory&                    getFactory();
            Notifier                    getNotifier();

        protected:
            virtual ApiTreeImpl& getApiTree() const = 0;
        };
//-----------------------------------------------------------------------------

        // Info interfaces for Set Elements
        class SetElement : public TreeElement
        {
        public:
        // self-locked methods for dispose handling
            bool disposeTree(bool bForceDispose);

            void haveNewParent(NodeSetInfoAccess* pNewParent);

            configuration::ElementRef       getElementRef() const;
            configuration::TemplateInfo     getTemplateInfo() const;
        };
//-----------------------------------------------------------------------------

        // Info interfaces for Set Elements
        class RootElement : public TreeElement
        {
        public:
            bool disposeTree();
        protected:
            virtual ApiRootTreeImpl& getRootTree() = 0;
        };
//-----------------------------------------------------------------------------

        // Info interfaces for Set Elements
        class UpdateRootElement : public RootElement
        {
        public:
            Committer getCommitter();
        };
//-----------------------------------------------------------------------------
        /// guards a TreeElement; provides an object (read) lock, ensures object was not disposed
        // FIXME: bin this ...
        class TreeReadGuardImpl : Noncopyable
        {
            TreeElement&        m_rTree;
        public:
            TreeReadGuardImpl(TreeElement& rTree);
            ~TreeReadGuardImpl() throw ();
        public:
            TreeElement&    get() const { return m_rTree; }
        };

    // Thin Wrappers around TreeElements: Provide guarding and convenient access
        /// wraps a TreeElement; provides an object (read) lock, ensures object was not disposed
        class GuardedTreeElement
        {
            UnoApiLock          m_aLock;
            TreeReadGuardImpl   m_aImpl;
        public:
            GuardedTreeElement(TreeElement& rTree) : m_aImpl(rTree) {}
        public:
            TreeElement&    get() const { return m_aImpl.get(); }
        };

        class GuardedRootElement
        {
            UnoApiLock          m_aLock;
            TreeReadGuardImpl   m_aImpl;
        public:
            GuardedRootElement(RootElement& rTree);
        public:
            RootElement& get() const { return static_cast<RootElement&>(m_aImpl.get()); }

            configuration::Tree getTree() const;
        };
//-----------------------------------------------------------------------------
    }
}

#endif // CONFIGMGR_API_TREEACCESS_HXX_
<|endoftext|>


<commit_before>/*************************************************************************
*
*  $RCSfile: emptylayer.cxx,v $
*
*  $Revision: 1.3 $
*
*  last change: $Author: cyrillem $ $Date: 2002-11-29 13:18:41 $
*
*  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: 2002 by Sun Microsystems, Inc.
*
*  All Rights Reserved.
*
*  Contributor(s): _______________________________________
*
*
************************************************************************/

#include "emptylayerimpl.hxx"

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

namespace configmgr
{
    // -----------------------------------------------------------------------------
    namespace backend
    {
        // -----------------------------------------------------------------------------
        namespace uno       = ::com::sun::star::uno;
        // -----------------------------------------------------------------------------
        // -----------------------------------------------------------------------------

        uno::Reference< backenduno::XLayer > createEmptyLayer()
        {
            return new EmptyLayer();
        }
        // -----------------------------------------------------------------------------

        bool checkEmptyLayer(uno::Reference< backenduno::XLayer > const & xLayer )
        {
            OSL_ENSURE(xLayer.is(),"Unexpected NULL Layer");
            if (!xLayer.is()) return false;

            RequireEmptyLayer * const pChecker = new RequireEmptyLayer;
            uno::Reference< backenduno::XLayerHandler > xChecker(pChecker);

            try
            {
                xLayer->readData(xChecker);
            }
            catch (uno::Exception &)
            {
                OSL_ENSURE(!pChecker->wasEmpty(), "Checking for empty layer: exception occurred after empty layer was ended");
            }

            return pChecker->wasEmpty();
        }

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

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

        void SAL_CALL
            EmptyLayer::readData( const uno::Reference< backenduno::XLayerHandler >& aHandler )
            throw (uno::RuntimeException)
        {
            if (aHandler.is())
            {
                aHandler->startLayer();
                aHandler->endLayer();
            }
            // else throw uno::RuntimeException("Null Handler",*this);
        }
        // -----------------------------------------------------------------------------
        // -----------------------------------------------------------------------------

        RequireEmptyLayer::RequireEmptyLayer()
        : m_bStarted(false)
        , m_bInvalid(false)
        , m_bEmpty(false)
        {
        }
        // -----------------------------------------------------------------------------

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

        void SAL_CALL RequireEmptyLayer::startLayer(  )
            throw (backenduno::MalformedDataException, uno::RuntimeException)
        {
            m_bInvalid  = false;
            m_bEmpty    = false;

            if (m_bStarted) fail("Layer started twice");
            m_bStarted  = true;
        }
        // -----------------------------------------------------------------------------

        void SAL_CALL RequireEmptyLayer::endLayer(  )
            throw (backenduno::MalformedDataException, uno::RuntimeException)
        {
            if (!m_bStarted) fail("Layer was not started");
            m_bEmpty    = !m_bInvalid;
            m_bStarted  = false;
        }
        // -----------------------------------------------------------------------------

        void SAL_CALL RequireEmptyLayer::overrideNode( const OUString& aName, sal_Int16 aAttributes )
            throw (backenduno::MalformedDataException, uno::RuntimeException)
        {
            failNotEmpty();
        }
        // -----------------------------------------------------------------------------

        void SAL_CALL RequireEmptyLayer::addOrReplaceNode( const OUString& aName, sal_Int16 aAttributes )
            throw (backenduno::MalformedDataException, uno::RuntimeException)
        {
            failNotEmpty();
        }
        // -----------------------------------------------------------------------------

        void SAL_CALL RequireEmptyLayer::addOrReplaceNodeFromTemplate( const OUString& aName, const backenduno::TemplateIdentifier& aTemplate, sal_Int16 aAttributes )
            throw (backenduno::MalformedDataException, uno::RuntimeException)
        {
            failNotEmpty();
        }
        // -----------------------------------------------------------------------------

        void SAL_CALL RequireEmptyLayer::endNode(  )
            throw (backenduno::MalformedDataException, uno::RuntimeException)
        {
            failNotEmpty();
        }
        // -----------------------------------------------------------------------------

        void SAL_CALL RequireEmptyLayer::dropNode( const OUString& aName )
            throw (backenduno::MalformedDataException, uno::RuntimeException)
        {
            failNotEmpty();
        }
        // -----------------------------------------------------------------------------

        void SAL_CALL RequireEmptyLayer::addProperty( const OUString& aName, sal_Int16 aAttributes, const uno::Type& aType )
            throw (backenduno::MalformedDataException, uno::RuntimeException)
        {
            failNotEmpty();
        }
        // -----------------------------------------------------------------------------

        void SAL_CALL RequireEmptyLayer::addPropertyWithValue( const OUString& aName, sal_Int16 aAttributes, const uno::Any& aValue )
            throw (backenduno::MalformedDataException, uno::RuntimeException)
        {
            failNotEmpty();
        }
        // -----------------------------------------------------------------------------

        void SAL_CALL RequireEmptyLayer::overrideProperty( const OUString& aName, sal_Int16 aAttributes, const uno::Type& aType )
            throw (backenduno::MalformedDataException, uno::RuntimeException)
        {
            failNotEmpty();
        }
        // -----------------------------------------------------------------------------

        void SAL_CALL RequireEmptyLayer::endProperty(  )
            throw (backenduno::MalformedDataException, uno::RuntimeException)
        {
            failNotEmpty();
        }
        // -----------------------------------------------------------------------------

        void SAL_CALL RequireEmptyLayer::setPropertyValue( const uno::Any& aValue )
            throw (backenduno::MalformedDataException, uno::RuntimeException)
        {
            failNotEmpty();
        }
        // -----------------------------------------------------------------------------

        void SAL_CALL RequireEmptyLayer::setPropertyValueForLocale( const uno::Any& aValue, const OUString& aLocale )
            throw (backenduno::MalformedDataException, uno::RuntimeException)
        {
            failNotEmpty();
        }
        // -----------------------------------------------------------------------------

        void RequireEmptyLayer::fail(sal_Char const * pMsg)
        {
            if (!m_bStarted & !m_bInvalid) pMsg = "Layer was not started";
            m_bInvalid = true;
            m_bStarted = false;

            OSL_ASSERT(pMsg);
            OUString sMsg = OUString::createFromAscii(pMsg);

            throw backenduno::MalformedDataException( sMsg, *this );
        }

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

        // -----------------------------------------------------------------------------
    } // namespace

    // -----------------------------------------------------------------------------
} // namespace

<commit_msg>#105114# Put back emptylayer.hxx<commit_after>/*************************************************************************
*
*  $RCSfile: emptylayer.cxx,v $
*
*  $Revision: 1.4 $
*
*  last change: $Author: cyrillem $ $Date: 2002-11-29 14:07:06 $
*
*  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: 2002 by Sun Microsystems, Inc.
*
*  All Rights Reserved.
*
*  Contributor(s): _______________________________________
*
*
************************************************************************/

#include "emptylayerimpl.hxx"
#include "emptylayer.hxx"

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

namespace configmgr
{
    // -----------------------------------------------------------------------------
    namespace backend
    {
        // -----------------------------------------------------------------------------
        namespace uno       = ::com::sun::star::uno;
        // -----------------------------------------------------------------------------
        // -----------------------------------------------------------------------------

        uno::Reference< backenduno::XLayer > createEmptyLayer()
        {
            return new EmptyLayer();
        }
        // -----------------------------------------------------------------------------

        bool checkEmptyLayer(uno::Reference< backenduno::XLayer > const & xLayer )
        {
            OSL_ENSURE(xLayer.is(),"Unexpected NULL Layer");
            if (!xLayer.is()) return false;

            RequireEmptyLayer * const pChecker = new RequireEmptyLayer;
            uno::Reference< backenduno::XLayerHandler > xChecker(pChecker);

            try
            {
                xLayer->readData(xChecker);
            }
            catch (uno::Exception &)
            {
                OSL_ENSURE(!pChecker->wasEmpty(), "Checking for empty layer: exception occurred after empty layer was ended");
            }

            return pChecker->wasEmpty();
        }

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

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

        void SAL_CALL
            EmptyLayer::readData( const uno::Reference< backenduno::XLayerHandler >& aHandler )
            throw (uno::RuntimeException)
        {
            if (aHandler.is())
            {
                aHandler->startLayer();
                aHandler->endLayer();
            }
            // else throw uno::RuntimeException("Null Handler",*this);
        }
        // -----------------------------------------------------------------------------
        // -----------------------------------------------------------------------------

        RequireEmptyLayer::RequireEmptyLayer()
        : m_bStarted(false)
        , m_bInvalid(false)
        , m_bEmpty(false)
        {
        }
        // -----------------------------------------------------------------------------

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

        void SAL_CALL RequireEmptyLayer::startLayer(  )
            throw (backenduno::MalformedDataException, uno::RuntimeException)
        {
            m_bInvalid  = false;
            m_bEmpty    = false;

            if (m_bStarted) fail("Layer started twice");
            m_bStarted  = true;
        }
        // -----------------------------------------------------------------------------

        void SAL_CALL RequireEmptyLayer::endLayer(  )
            throw (backenduno::MalformedDataException, uno::RuntimeException)
        {
            if (!m_bStarted) fail("Layer was not started");
            m_bEmpty    = !m_bInvalid;
            m_bStarted  = false;
        }
        // -----------------------------------------------------------------------------

        void SAL_CALL RequireEmptyLayer::overrideNode( const OUString& aName, sal_Int16 aAttributes )
            throw (backenduno::MalformedDataException, uno::RuntimeException)
        {
            failNotEmpty();
        }
        // -----------------------------------------------------------------------------

        void SAL_CALL RequireEmptyLayer::addOrReplaceNode( const OUString& aName, sal_Int16 aAttributes )
            throw (backenduno::MalformedDataException, uno::RuntimeException)
        {
            failNotEmpty();
        }
        // -----------------------------------------------------------------------------

        void SAL_CALL RequireEmptyLayer::addOrReplaceNodeFromTemplate( const OUString& aName, const backenduno::TemplateIdentifier& aTemplate, sal_Int16 aAttributes )
            throw (backenduno::MalformedDataException, uno::RuntimeException)
        {
            failNotEmpty();
        }
        // -----------------------------------------------------------------------------

        void SAL_CALL RequireEmptyLayer::endNode(  )
            throw (backenduno::MalformedDataException, uno::RuntimeException)
        {
            failNotEmpty();
        }
        // -----------------------------------------------------------------------------

        void SAL_CALL RequireEmptyLayer::dropNode( const OUString& aName )
            throw (backenduno::MalformedDataException, uno::RuntimeException)
        {
            failNotEmpty();
        }
        // -----------------------------------------------------------------------------

        void SAL_CALL RequireEmptyLayer::addProperty( const OUString& aName, sal_Int16 aAttributes, const uno::Type& aType )
            throw (backenduno::MalformedDataException, uno::RuntimeException)
        {
            failNotEmpty();
        }
        // -----------------------------------------------------------------------------

        void SAL_CALL RequireEmptyLayer::addPropertyWithValue( const OUString& aName, sal_Int16 aAttributes, const uno::Any& aValue )
            throw (backenduno::MalformedDataException, uno::RuntimeException)
        {
            failNotEmpty();
        }
        // -----------------------------------------------------------------------------

        void SAL_CALL RequireEmptyLayer::overrideProperty( const OUString& aName, sal_Int16 aAttributes, const uno::Type& aType )
            throw (backenduno::MalformedDataException, uno::RuntimeException)
        {
            failNotEmpty();
        }
        // -----------------------------------------------------------------------------

        void SAL_CALL RequireEmptyLayer::endProperty(  )
            throw (backenduno::MalformedDataException, uno::RuntimeException)
        {
            failNotEmpty();
        }
        // -----------------------------------------------------------------------------

        void SAL_CALL RequireEmptyLayer::setPropertyValue( const uno::Any& aValue )
            throw (backenduno::MalformedDataException, uno::RuntimeException)
        {
            failNotEmpty();
        }
        // -----------------------------------------------------------------------------

        void SAL_CALL RequireEmptyLayer::setPropertyValueForLocale( const uno::Any& aValue, const OUString& aLocale )
            throw (backenduno::MalformedDataException, uno::RuntimeException)
        {
            failNotEmpty();
        }
        // -----------------------------------------------------------------------------

        void RequireEmptyLayer::fail(sal_Char const * pMsg)
        {
            if (!m_bStarted & !m_bInvalid) pMsg = "Layer was not started";
            m_bInvalid = true;
            m_bStarted = false;

            OSL_ASSERT(pMsg);
            OUString sMsg = OUString::createFromAscii(pMsg);

            throw backenduno::MalformedDataException( sMsg, *this );
        }

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

        // -----------------------------------------------------------------------------
    } // namespace

    // -----------------------------------------------------------------------------
} // namespace

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: backendfactory.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2003-04-17 13:27:47 $
 *
 *  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 CONFIGMGR_BACKENDFACTORY_HXX_
#define CONFIGMGR_BACKENDFACTORY_HXX_

#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XBACKEND_HPP_
#include <com/sun/star/configuration/backend/XBackend.hpp>
#endif

namespace configmgr
{
//-----------------------------------------------------------------------------
    namespace backend
    {
//-----------------------------------------------------------------------------

        struct IMergedDataProvider;
//-----------------------------------------------------------------------------
        class BackendFactory
        {
        public:
            typedef com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext >
                CreationContext;

            typedef com::sun::star::uno::Reference< com::sun::star::configuration::backend::XBackend >
                UnoBackend;

            rtl::Reference<IMergedDataProvider> createBackend();

            UnoBackend getUnoBackend();

            static BackendFactory instance(CreationContext const & _xCtx);

        private:
            explicit
            BackendFactory(CreationContext const & _xCtx)
            : m_xCtx(_xCtx)
            {}

            CreationContext m_xCtx;
        };
//-----------------------------------------------------------------------------
    }
//-----------------------------------------------------------------------------
}

#endif

<commit_msg>INTEGRATION: CWS ooo19126 (1.5.180); FILE MERGED 2005/09/05 17:04:20 rt 1.5.180.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: backendfactory.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 03:42:49 $
 *
 *  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 CONFIGMGR_BACKENDFACTORY_HXX_
#define CONFIGMGR_BACKENDFACTORY_HXX_

#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XBACKEND_HPP_
#include <com/sun/star/configuration/backend/XBackend.hpp>
#endif

namespace configmgr
{
//-----------------------------------------------------------------------------
    namespace backend
    {
//-----------------------------------------------------------------------------

        struct IMergedDataProvider;
//-----------------------------------------------------------------------------
        class BackendFactory
        {
        public:
            typedef com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext >
                CreationContext;

            typedef com::sun::star::uno::Reference< com::sun::star::configuration::backend::XBackend >
                UnoBackend;

            rtl::Reference<IMergedDataProvider> createBackend();

            UnoBackend getUnoBackend();

            static BackendFactory instance(CreationContext const & _xCtx);

        private:
            explicit
            BackendFactory(CreationContext const & _xCtx)
            : m_xCtx(_xCtx)
            {}

            CreationContext m_xCtx;
        };
//-----------------------------------------------------------------------------
    }
//-----------------------------------------------------------------------------
}

#endif

<|endoftext|>


<commit_before>// Copyright (c) 2012 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 "ash/shell/content_client/shell_main_delegate.h"

#include "ash/shell/content_client/shell_content_browser_client.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/path_service.h"
#include "content/public/browser/browser_main_runner.h"
#include "content/public/common/content_switches.h"
#include "content/shell/shell_content_plugin_client.h"
#include "content/shell/shell_content_renderer_client.h"
#include "content/shell/shell_content_utility_client.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_paths.h"

namespace ash {
namespace shell {
namespace {

int ShellBrowserMain(
    const content::MainFunctionParams& main_function_params) {
  scoped_ptr<content::BrowserMainRunner> main_runner(
      content::BrowserMainRunner::Create());
  int exit_code = main_runner->Initialize(main_function_params);
  if (exit_code >= 0)
    return exit_code;
  exit_code = main_runner->Run();
  main_runner->Shutdown();
  return exit_code;
}

}

ShellMainDelegate::ShellMainDelegate() {
}

ShellMainDelegate::~ShellMainDelegate() {
}

bool ShellMainDelegate::BasicStartupComplete(int* exit_code) {
  return false;
}

void ShellMainDelegate::PreSandboxStartup() {
  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  std::string process_type =
      command_line.GetSwitchValueASCII(switches::kProcessType);

  content::SetContentClient(&content_client_);
  InitializeShellContentClient(process_type);

  InitializeResourceBundle();
}

void ShellMainDelegate::SandboxInitialized(const std::string& process_type) {
}

int ShellMainDelegate::RunProcess(
    const std::string& process_type,
    const content::MainFunctionParams& main_function_params) {
  if (process_type != "")
    return -1;

  return ShellBrowserMain(main_function_params);
}

void ShellMainDelegate::ProcessExiting(const std::string& process_type) {
}

#if defined(OS_POSIX)
content::ZygoteForkDelegate* ShellMainDelegate::ZygoteStarting() {
  return NULL;
}

void ShellMainDelegate::ZygoteForked() {
  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  std::string process_type =
      command_line.GetSwitchValueASCII(switches::kProcessType);
  InitializeShellContentClient(process_type);
}
#endif

void ShellMainDelegate::InitializeShellContentClient(
    const std::string& process_type) {
  if (process_type.empty()) {
    browser_client_.reset(new ShellContentBrowserClient);
    content::GetContentClient()->set_browser(browser_client_.get());
  } else if (process_type == switches::kRendererProcess) {
    renderer_client_.reset(new content::ShellContentRendererClient);
    content::GetContentClient()->set_renderer(renderer_client_.get());
  } else if (process_type == switches::kPluginProcess) {
    plugin_client_.reset(new content::ShellContentPluginClient);
    content::GetContentClient()->set_plugin(plugin_client_.get());
  } else if (process_type == switches::kUtilityProcess) {
    utility_client_.reset(new content::ShellContentUtilityClient);
    content::GetContentClient()->set_utility(utility_client_.get());
  }
}

void ShellMainDelegate::InitializeResourceBundle() {
  ui::ResourceBundle::InitSharedInstanceWithLocale("en-US");
}

}  // namespace shell
}  // namespace ash
<commit_msg>ash: Fix a crash on startup for ash-shell.<commit_after>// Copyright (c) 2012 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 "ash/shell/content_client/shell_main_delegate.h"

#include "ash/shell/content_client/shell_content_browser_client.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/path_service.h"
#include "content/public/browser/browser_main_runner.h"
#include "content/public/common/content_switches.h"
#include "content/shell/shell_content_plugin_client.h"
#include "content/shell/shell_content_renderer_client.h"
#include "content/shell/shell_content_utility_client.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_paths.h"

namespace ash {
namespace shell {
namespace {

int ShellBrowserMain(
    const content::MainFunctionParams& main_function_params) {
  scoped_ptr<content::BrowserMainRunner> main_runner(
      content::BrowserMainRunner::Create());
  int exit_code = main_runner->Initialize(main_function_params);
  if (exit_code >= 0)
    return exit_code;
  exit_code = main_runner->Run();
  main_runner->Shutdown();
  return exit_code;
}

}

ShellMainDelegate::ShellMainDelegate() {
}

ShellMainDelegate::~ShellMainDelegate() {
}

bool ShellMainDelegate::BasicStartupComplete(int* exit_code) {
  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  std::string process_type =
      command_line.GetSwitchValueASCII(switches::kProcessType);

  content::SetContentClient(&content_client_);
  InitializeShellContentClient(process_type);

  return false;
}

void ShellMainDelegate::PreSandboxStartup() {
  InitializeResourceBundle();
}

void ShellMainDelegate::SandboxInitialized(const std::string& process_type) {
}

int ShellMainDelegate::RunProcess(
    const std::string& process_type,
    const content::MainFunctionParams& main_function_params) {
  if (process_type != "")
    return -1;

  return ShellBrowserMain(main_function_params);
}

void ShellMainDelegate::ProcessExiting(const std::string& process_type) {
}

#if defined(OS_POSIX)
content::ZygoteForkDelegate* ShellMainDelegate::ZygoteStarting() {
  return NULL;
}

void ShellMainDelegate::ZygoteForked() {
  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  std::string process_type =
      command_line.GetSwitchValueASCII(switches::kProcessType);
  InitializeShellContentClient(process_type);
}
#endif

void ShellMainDelegate::InitializeShellContentClient(
    const std::string& process_type) {
  if (process_type.empty()) {
    browser_client_.reset(new ShellContentBrowserClient);
    content::GetContentClient()->set_browser(browser_client_.get());
  } else if (process_type == switches::kRendererProcess) {
    renderer_client_.reset(new content::ShellContentRendererClient);
    content::GetContentClient()->set_renderer(renderer_client_.get());
  } else if (process_type == switches::kPluginProcess) {
    plugin_client_.reset(new content::ShellContentPluginClient);
    content::GetContentClient()->set_plugin(plugin_client_.get());
  } else if (process_type == switches::kUtilityProcess) {
    utility_client_.reset(new content::ShellContentUtilityClient);
    content::GetContentClient()->set_utility(utility_client_.get());
  }
}

void ShellMainDelegate::InitializeResourceBundle() {
  ui::ResourceBundle::InitSharedInstanceWithLocale("en-US");
}

}  // namespace shell
}  // namespace ash
<|endoftext|>


<commit_before>// Scintilla source code edit control
/** @file LexPOV.cxx
 ** Lexer for POV-Ray, based on lexer for C++.
 **/
// Copyright 2003 by Steven te Brinke <steven.t.b@zonnet.nl>
// The License.txt file describes the conditions under which this software may be distributed.

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>

#include "Platform.h"

#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"

#define KEYWORD_BOXHEADER 1
#define KEYWORD_FOLDCONTRACTED 2

static inline bool IsAWordChar(const int ch) {
	return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_');
}

static inline bool IsAWordStart(const int ch) {
	return (ch < 0x80) && (isalnum(ch) || ch == '_');
}

static inline bool IsStateComment(const int state) {
	return ((state == SCE_POV_COMMENT) ||
	        (state == SCE_POV_COMMENTLINE) ||
	        (state == SCE_POV_COMMENTDOC));
}

static inline bool IsStateString(const int state) {
	return ((state == SCE_POV_STRING));
}

static void ColourisePOVDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
                            Accessor &styler) {

	WordList &keywords = *keywordlists[0];
	WordList &keywords2 = *keywordlists[1];

	// Do not leak onto next line
	/*if (initStyle == SCE_POV_STRINGEOL)
		initStyle = SCE_POV_DEFAULT;*/

	StyleContext sc(startPos, length, initStyle, styler);

	bool caseSensitive = styler.GetPropertyInt("case.sensitive", 1) != 0;

	for (; sc.More(); sc.Forward()) {

		/*if (sc.atLineStart && (sc.state == SCE_POV_STRING)) {
			// Prevent SCE_POV_STRINGEOL from leaking back to previous line
			sc.SetState(SCE_POV_STRING);
		}*/

		// Handle line continuation generically.
		if (sc.ch == '\\') {
			if (sc.chNext == '\n' || sc.chNext == '\r') {
				sc.Forward();
				if (sc.ch == '\r' && sc.chNext == '\n') {
					sc.Forward();
				}
				continue;
			}
		}

		// Determine if the current state should terminate.
		if (sc.state == SCE_POV_OPERATOR || sc.state == SCE_POV_BRACE) {
			sc.SetState(SCE_POV_DEFAULT);
		} else if (sc.state == SCE_POV_NUMBER) {
			if (!IsADigit(sc.ch) || sc.ch != '.') {
				sc.SetState(SCE_POV_DEFAULT);
			}
		} else if (sc.state == SCE_POV_IDENTIFIER) {
			if (!IsAWordChar(sc.ch) || (sc.ch == '.')) {
				char s[100];
				if (caseSensitive) {
					sc.GetCurrent(s, sizeof(s));
				} else {
					sc.GetCurrentLowered(s, sizeof(s));
				}
				if (keywords.InList(s)) {
					sc.ChangeState(SCE_POV_WORD);
				} else if (keywords2.InList(s)) {
					sc.ChangeState(SCE_POV_WORD2);
				}
				sc.SetState(SCE_POV_DEFAULT);
			}
		} else if (sc.state == SCE_POV_COMMENT) {
			if (sc.Match('*', '/')) {
				sc.Forward();
				sc.ForwardSetState(SCE_POV_DEFAULT);
			}
		} else if (sc.state == SCE_POV_COMMENTDOC) {
			if (sc.Match('*', '/')) {
				sc.Forward();
				sc.ForwardSetState(SCE_POV_DEFAULT);
			}
		} else if (sc.state == SCE_POV_COMMENTLINE) {
			if (sc.atLineEnd) {
				sc.SetState(SCE_POV_DEFAULT);
			}
		} else if (sc.state == SCE_POV_STRING) {
			if (sc.ch == '\\') {
				if (sc.chNext == '\"' || sc.chNext == '\\') {
					sc.Forward();
				}
			} else if (sc.ch == '\"') {
				sc.ForwardSetState(SCE_POV_DEFAULT);
			}
		}

		// Determine if a new state should be entered.
		if (sc.state == SCE_POV_DEFAULT) {
			if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
				sc.SetState(SCE_POV_NUMBER);
			} else if (IsAWordStart(sc.ch) || (sc.ch == '#')) {
				sc.SetState(SCE_POV_IDENTIFIER);
			} else if (sc.Match('/', '*')) {
				sc.SetState(SCE_POV_COMMENT);
				sc.Forward();	// Eat the * so it isn't used for the end of the comment
			} else if (sc.Match('/', '/')) {
				sc.SetState(SCE_POV_COMMENTLINE);
			} else if (sc.ch == '\"') {
				sc.SetState(SCE_POV_STRING);
				//} else if (isoperator(static_cast<char>(sc.ch))) {
			} else if (sc.ch == '+' || sc.ch == '-' || sc.ch == '*' || sc.ch == '/' || sc.ch == '=' || sc.ch == '<' || sc.ch == '>' || sc.ch == '&' || sc.ch == '|' || sc.ch == '!' || sc.ch == '?' || sc.ch == ':') {
				sc.SetState(SCE_POV_OPERATOR);
			} else if (sc.ch == '{' || sc.ch == '}') {
				sc.SetState(SCE_POV_BRACE);
			}
		}

	}
	sc.Complete();
}

static bool IsStreamCommentStyle(int style) {
	return style == SCE_POV_COMMENT ||
	       style == SCE_POV_COMMENTDOC;
}

static void FoldNoBoxPOVDoc(unsigned int startPos, int length, int initStyle,
                            Accessor &styler) {
	bool foldComment = styler.GetPropertyInt("fold.comment", 1) != 0;
	bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
	unsigned int endPos = startPos + length;
	int visibleChars = 0;
	int lineCurrent = styler.GetLine(startPos);
	int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
	int levelCurrent = levelPrev;
	char chNext = styler[startPos];
	int styleNext = styler.StyleAt(startPos);
	int style = initStyle;
	for (unsigned int i = startPos; i < endPos; i++) {
		char ch = chNext;
		chNext = styler.SafeGetCharAt(i + 1);
		int stylePrev = style;
		style = styleNext;
		styleNext = styler.StyleAt(i + 1);
		bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
		if (foldComment && IsStreamCommentStyle(style)) {
			if (!IsStreamCommentStyle(stylePrev)) {
				levelCurrent++;
			} else if (!IsStreamCommentStyle(styleNext) && !atEOL) {
				// Comments don't end at end of line and the next character may be unstyled.
				levelCurrent--;
			}
		}
		if (style == SCE_POV_BRACE) {
			if (ch == '{') {
				levelCurrent++;
			} else if (ch == '}') {
				levelCurrent--;
			}
		}
		if (atEOL) {
			int lev = levelPrev;
			if (visibleChars == 0 && foldCompact)
				lev |= SC_FOLDLEVELWHITEFLAG;
			if ((levelCurrent > levelPrev) && (visibleChars > 0))
				lev |= SC_FOLDLEVELHEADERFLAG;
			if (lev != styler.LevelAt(lineCurrent)) {
				styler.SetLevel(lineCurrent, lev);
			}
			lineCurrent++;
			levelPrev = levelCurrent;
			visibleChars = 0;
		}
		if (!isspacechar(ch))
			visibleChars++;
	}
	// Fill in the real level of the next line, keeping the current flags as they will be filled in later
	int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
	styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}

static void FoldPOVDoc(unsigned int startPos, int length, int initStyle, WordList *[], Accessor &styler) {
	FoldNoBoxPOVDoc(startPos, length, initStyle, styler);
}

static const char * const POVWordLists[] = {
            "Primary keywords and identifiers",
            "Secondary keywords and identifiers",
            0,
        };

static void ColourisePOVDocSensitive(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
                                     Accessor &styler) {
	ColourisePOVDoc(startPos, length, initStyle, keywordlists, styler);
}

LexerModule lmPOV(SCLEX_POV, ColourisePOVDocSensitive, "pov", FoldPOVDoc, POVWordLists);
<commit_msg>POV-Ray support.<commit_after>// Scintilla source code edit control
/** @file LexPOV.cxx
 ** Lexer for POV-Ray, based on lexer for C++.
 **/
// Copyright 2003 by Steven te Brinke <steven.t.b@zonnet.nl>
// The License.txt file describes the conditions under which this software may be distributed.

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>

#include "Platform.h"

#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"

#define KEYWORD_BOXHEADER 1
#define KEYWORD_FOLDCONTRACTED 2

static inline bool IsAWordChar(const int ch) {
	return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_');
}

static inline bool IsAWordStart(const int ch) {
	return (ch < 0x80) && (isalnum(ch) || ch == '_');
}

static inline bool IsStateComment(const int state) {
	return ((state == SCE_POV_COMMENT) ||
	        (state == SCE_POV_COMMENTLINE) ||
	        (state == SCE_POV_COMMENTDOC));
}

static inline bool IsStateString(const int state) {
	return ((state == SCE_POV_STRING));
}

static void ColourisePOVDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
                            Accessor &styler) {

	WordList &keywords = *keywordlists[0];
	WordList &keywords2 = *keywordlists[1];

	// Do not leak onto next line
	/*if (initStyle == SCE_POV_STRINGEOL)
		initStyle = SCE_POV_DEFAULT;*/

	StyleContext sc(startPos, length, initStyle, styler);

	bool caseSensitive = styler.GetPropertyInt("pov.case.sensitive", 1) != 0;

	for (; sc.More(); sc.Forward()) {

		/*if (sc.atLineStart && (sc.state == SCE_POV_STRING)) {
			// Prevent SCE_POV_STRINGEOL from leaking back to previous line
			sc.SetState(SCE_POV_STRING);
		}*/

		// Handle line continuation generically.
		if (sc.ch == '\\') {
			if (sc.chNext == '\n' || sc.chNext == '\r') {
				sc.Forward();
				if (sc.ch == '\r' && sc.chNext == '\n') {
					sc.Forward();
				}
				continue;
			}
		}

		// Determine if the current state should terminate.
		if (sc.state == SCE_POV_OPERATOR || sc.state == SCE_POV_BRACE) {
			sc.SetState(SCE_POV_DEFAULT);
		} else if (sc.state == SCE_POV_NUMBER) {
			if (!IsADigit(sc.ch) || sc.ch != '.') {
				sc.SetState(SCE_POV_DEFAULT);
			}
		} else if (sc.state == SCE_POV_IDENTIFIER) {
			if (!IsAWordChar(sc.ch) || (sc.ch == '.')) {
				char s[100];
				if (caseSensitive) {
					sc.GetCurrent(s, sizeof(s));
				} else {
					sc.GetCurrentLowered(s, sizeof(s));
				}
				if (keywords.InList(s)) {
					sc.ChangeState(SCE_POV_WORD);
				} else if (keywords2.InList(s)) {
					sc.ChangeState(SCE_POV_WORD2);
				}
				sc.SetState(SCE_POV_DEFAULT);
			}
		} else if (sc.state == SCE_POV_COMMENT) {
			if (sc.Match('*', '/')) {
				sc.Forward();
				sc.ForwardSetState(SCE_POV_DEFAULT);
			}
		} else if (sc.state == SCE_POV_COMMENTDOC) {
			if (sc.Match('*', '/')) {
				sc.Forward();
				sc.ForwardSetState(SCE_POV_DEFAULT);
			}
		} else if (sc.state == SCE_POV_COMMENTLINE) {
			if (sc.atLineEnd) {
				sc.SetState(SCE_POV_DEFAULT);
			}
		} else if (sc.state == SCE_POV_STRING) {
			if (sc.ch == '\\') {
				if (sc.chNext == '\"' || sc.chNext == '\\') {
					sc.Forward();
				}
			} else if (sc.ch == '\"') {
				sc.ForwardSetState(SCE_POV_DEFAULT);
			}
		}

		// Determine if a new state should be entered.
		if (sc.state == SCE_POV_DEFAULT) {
			if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
				sc.SetState(SCE_POV_NUMBER);
			} else if (IsAWordStart(sc.ch) || (sc.ch == '#')) {
				sc.SetState(SCE_POV_IDENTIFIER);
			} else if (sc.Match('/', '*')) {
				sc.SetState(SCE_POV_COMMENT);
				sc.Forward();	// Eat the * so it isn't used for the end of the comment
			} else if (sc.Match('/', '/')) {
				sc.SetState(SCE_POV_COMMENTLINE);
			} else if (sc.ch == '\"') {
				sc.SetState(SCE_POV_STRING);
				//} else if (isoperator(static_cast<char>(sc.ch))) {
			} else if (sc.ch == '+' || sc.ch == '-' || sc.ch == '*' || sc.ch == '/' || sc.ch == '=' || sc.ch == '<' || sc.ch == '>' || sc.ch == '&' || sc.ch == '|' || sc.ch == '!' || sc.ch == '?' || sc.ch == ':') {
				sc.SetState(SCE_POV_OPERATOR);
			} else if (sc.ch == '{' || sc.ch == '}') {
				sc.SetState(SCE_POV_BRACE);
			}
		}

	}
	sc.Complete();
}

static bool IsStreamCommentStyle(int style) {
	return style == SCE_POV_COMMENT ||
	       style == SCE_POV_COMMENTDOC;
}

static void FoldNoBoxPOVDoc(unsigned int startPos, int length, int initStyle,
                            Accessor &styler) {
	bool foldComment = styler.GetPropertyInt("fold.comment", 1) != 0;
	bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
	unsigned int endPos = startPos + length;
	int visibleChars = 0;
	int lineCurrent = styler.GetLine(startPos);
	int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
	int levelCurrent = levelPrev;
	char chNext = styler[startPos];
	int styleNext = styler.StyleAt(startPos);
	int style = initStyle;
	for (unsigned int i = startPos; i < endPos; i++) {
		char ch = chNext;
		chNext = styler.SafeGetCharAt(i + 1);
		int stylePrev = style;
		style = styleNext;
		styleNext = styler.StyleAt(i + 1);
		bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
		if (foldComment && IsStreamCommentStyle(style)) {
			if (!IsStreamCommentStyle(stylePrev)) {
				levelCurrent++;
			} else if (!IsStreamCommentStyle(styleNext) && !atEOL) {
				// Comments don't end at end of line and the next character may be unstyled.
				levelCurrent--;
			}
		}
		if (style == SCE_POV_BRACE) {
			if (ch == '{') {
				levelCurrent++;
			} else if (ch == '}') {
				levelCurrent--;
			}
		}
		if (atEOL) {
			int lev = levelPrev;
			if (visibleChars == 0 && foldCompact)
				lev |= SC_FOLDLEVELWHITEFLAG;
			if ((levelCurrent > levelPrev) && (visibleChars > 0))
				lev |= SC_FOLDLEVELHEADERFLAG;
			if (lev != styler.LevelAt(lineCurrent)) {
				styler.SetLevel(lineCurrent, lev);
			}
			lineCurrent++;
			levelPrev = levelCurrent;
			visibleChars = 0;
		}
		if (!isspacechar(ch))
			visibleChars++;
	}
	// Fill in the real level of the next line, keeping the current flags as they will be filled in later
	int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
	styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}

static void FoldPOVDoc(unsigned int startPos, int length, int initStyle, WordList *[], Accessor &styler) {
	FoldNoBoxPOVDoc(startPos, length, initStyle, styler);
}

static const char * const POVWordLists[] = {
            "Primary keywords and identifiers",
            "Secondary keywords and identifiers",
            0,
        };

static void ColourisePOVDocSensitive(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
                                     Accessor &styler) {
	ColourisePOVDoc(startPos, length, initStyle, keywordlists, styler);
}

LexerModule lmPOV(SCLEX_POV, ColourisePOVDocSensitive, "pov", FoldPOVDoc, POVWordLists);
<|endoftext|>


<commit_before>// ///////////////////////////////////////////////////////////////////////////
// tenh/interop/eigen.hpp by Victor Dods, created 2013/03/31
// Copyright Leap Motion Inc.
// ///////////////////////////////////////////////////////////////////////////

#ifndef TENH_INTEROP_EIGEN_HPP_
#define TENH_INTEROP_EIGEN_HPP_

#include "tenh/core.hpp"
#include "tenh/implementation/euclideanembedding.hpp"
#include "tenh/implementation/implementationof.hpp"
#include "tenh/implementation/tensor.hpp"

#include "Eigen/Core"
#include "Eigen/LU"

namespace Tenh {

template <typename Factor1_, typename Factor2_, typename Scalar_>
struct EigenMapOf2Tensor_const_f
{
    typedef Eigen::Map<Eigen::Matrix<Scalar_,
                                     DimensionOf_f<Factor1_>::V,
                                     DimensionOf_f<Factor2_>::V,
                                     Eigen::RowMajor> const> T;
};

template <typename Factor1_, typename Factor2_, typename Scalar_>
struct EigenMapOf2Tensor_nonconst_f
{
    typedef Eigen::Map<Eigen::Matrix<Scalar_,
                                     DimensionOf_f<Factor1_>::V,
                                     DimensionOf_f<Factor2_>::V,
                                     Eigen::RowMajor> > T;
};

// const version
template <typename Factor1_, typename Factor2_, typename Scalar_, typename UseArrayType_>
typename EigenMapOf2Tensor_const_f<Factor1_,Factor2_,Scalar_>::T
    EigenMap_of_2tensor (ImplementationOf_t<TensorProductOfBasedVectorSpaces_c<TypeList_t<Factor1_,
                                                                               TypeList_t<Factor2_> > >,
                                            Scalar_,
                                            UseArrayType_> const &t)
{
    STATIC_ASSERT(!IsUseImmutableArray_f<UseArrayType_>::V, CANT_MAKE_EIGEN_MAP_OF_IMMUTABLE_ARRAY);
    return typename EigenMapOf2Tensor_const_f<Factor1_,Factor2_,Scalar_>::T(t.pointer_to_allocation());
}

// non-const version
template <typename Factor1_, typename Factor2_, typename Scalar_, typename UseArrayType_>
typename EigenMapOf2Tensor_nonconst_f<Factor1_,Factor2_,Scalar_>::T
    EigenMap_of_2tensor (ImplementationOf_t<TensorProductOfBasedVectorSpaces_c<TypeList_t<Factor1_,
                                                                               TypeList_t<Factor2_> > >,
                                            Scalar_,
                                            UseArrayType_> &t)
{
    STATIC_ASSERT(!IsUseImmutableArray_f<UseArrayType_>::V, CANT_MAKE_EIGEN_MAP_OF_IMMUTABLE_ARRAY);
    return typename EigenMapOf2Tensor_nonconst_f<Factor1_,Factor2_,Scalar_>::T(t.pointer_to_allocation());
}

template <typename Type_, typename Scalar_>
struct EigenMapOfVector_const_f
{
    typedef Eigen::Map<Eigen::Matrix<Scalar_,
                                     DimensionOf_f<Type_>::V,
                                     1,
                                     Eigen::RowMajor> const> T;
};

template <typename Type_, typename Scalar_>
struct EigenMapOfVector_nonconst_f
{
    typedef Eigen::Map<Eigen::Matrix<Scalar_,
                                     DimensionOf_f<Type_>::V,
                                     1,
                                     Eigen::RowMajor> > T;
};

// const version
template <typename Type_, typename Scalar_, typename UseArrayType_>
typename EigenMapOfVector_const_f<Type_,Scalar_>::T
    EigenMap_of_vector (ImplementationOf_t<Type_,
                                           Scalar_,
                                           UseArrayType_> const &t)
{
    STATIC_ASSERT(!IsUseImmutableArray_f<UseArrayType_>::V, CANT_MAKE_EIGEN_MAP_OF_IMMUTABLE_ARRAY);
    return typename EigenMapOfVector_const_f<Type_,Scalar_>::T(t.pointer_to_allocation());
}

// non-const version
template <typename Type_, typename Scalar_, typename UseArrayType_>
typename EigenMapOfVector_nonconst_f<Type_,Scalar_>::T
    EigenMap_of_vector (ImplementationOf_t<Type_,
                                           Scalar_,
                                           UseArrayType_> &t)
{
    STATIC_ASSERT(!IsUseImmutableArray_f<UseArrayType_>::V, CANT_MAKE_EIGEN_MAP_OF_IMMUTABLE_ARRAY);
    return typename EigenMapOfVector_nonconst_f<Type_,Scalar_>::T(t.pointer_to_allocation());
}

// returns true iff the tensor was actually considered to be invertible (by Eigen::MatrixBase::computeInverseWithCheck)
template <typename Factor1_, typename Factor2_, typename Scalar_, typename UseArrayType_, typename InverseUseArrayType_>
bool invert_2tensor (ImplementationOf_t<TensorProductOfBasedVectorSpaces_c<TypeList_t<Factor1_,
                                                                           TypeList_t<Factor2_> > >,
                                        Scalar_,
                                        UseArrayType_> const &t,
                     ImplementationOf_t<TensorProductOfBasedVectorSpaces_c<TypeList_t<typename DualOf_f<Factor2_>::T,
                                                                           TypeList_t<typename DualOf_f<Factor1_>::T> > >,
                                        Scalar_,
                                        InverseUseArrayType_> &t_inverse)
{
    STATIC_ASSERT(DimensionOf_f<Factor1_>::V == DimensionOf_f<Factor2_>::V, FACTOR_DIMENSIONS_MUST_BE_EQUAL);
    STATIC_ASSERT(!IsUseImmutableArray_f<UseArrayType_>::V, CANT_MAKE_EIGEN_MAP_OF_IMMUTABLE_ARRAY); // TODO: provide invert for UseImmutableArray
    // create Eigen Maps for each of the parameters -- this way no copying is necessary;
    // the t tensor's components are read directly by Eigen, and t_inverse's components
    // are directly written to by Eigen.
    typedef Eigen::Matrix<Scalar_, DimensionOf_f<Factor1_>::V, DimensionOf_f<Factor2_>::V, Eigen::RowMajor> EigenMatrixType;
    typename EigenMapOf2Tensor_const_f<Factor1_,Factor2_,Scalar_>::T eigen_map_of_t(EigenMap_of_2tensor(t));
    typename EigenMapOf2Tensor_nonconst_f<typename DualOf_f<Factor2_>::T,typename DualOf_f<Factor1_>::T,Scalar_>::T eigen_map_of_t_inverse(EigenMap_of_2tensor(t_inverse));
    Eigen::FullPivLU<EigenMatrixType> lu(eigen_map_of_t);

    if (lu.isInvertible())
    {
       eigen_map_of_t_inverse = lu.inverse();
       return true;
    }
    else
    {
      return false;
    }
}

// returns true iff the tensor was actually considered to be invertible (by Eigen::MatrixBase::computeInverseWithCheck)
template <typename Factor1_, typename Factor2_, typename Scalar_, typename UseArrayType_>
Scalar_ determinant_of_2tensor (ImplementationOf_t<TensorProductOfBasedVectorSpaces_c<TypeList_t<Factor1_,
                                                                           TypeList_t<Factor2_> > >,
                                                  Scalar_,
                                                  UseArrayType_> const &t)
{
    STATIC_ASSERT(DimensionOf_f<Factor1_>::V == DimensionOf_f<Factor2_>::V, FACTOR_DIMENSIONS_MUST_BE_EQUAL);
    STATIC_ASSERT(!IsUseImmutableArray_f<UseArrayType_>::V, CANT_MAKE_EIGEN_MAP_OF_IMMUTABLE_ARRAY); // TODO: provide determinant for UseImmutableArray
    // create Eigen Maps for the parameter -- this way no copying is necessary;
    // the t tensor's components are read directly by Eigen.
    typedef Eigen::Matrix<Scalar_, DimensionOf_f<Factor1_>::V, DimensionOf_f<Factor2_>::V, Eigen::RowMajor> EigenMatrixType;
    typename EigenMapOf2Tensor_const_f<Factor1_,Factor2_,Scalar_>::T eigen_map_of_t(EigenMap_of_2tensor(t));

    if (DimensionOf_f<Factor1_>::V > 4)
    {
      Eigen::FullPivLU<EigenMatrixType> lu(eigen_map_of_t);
      return lu.determinant();
    }
    else
    {
      return eigen_map_of_t.determinant();
    }
}

// TODO: specialization for diagonal 2-tensors

} // end of namespace Tenh

#endif // TENH_INTEROP_EIGEN_HPP_
<commit_msg>Add invert for SymmetricPowers, right now there’s a template problem of some sort.<commit_after>// ///////////////////////////////////////////////////////////////////////////
// tenh/interop/eigen.hpp by Victor Dods, created 2013/03/31
// Copyright Leap Motion Inc.
// ///////////////////////////////////////////////////////////////////////////

#ifndef TENH_INTEROP_EIGEN_HPP_
#define TENH_INTEROP_EIGEN_HPP_

#include "tenh/core.hpp"
#include "tenh/implementation/euclideanembedding.hpp"
#include "tenh/implementation/implementationof.hpp"
#include "tenh/implementation/tensor.hpp"

#include "Eigen/Core"
#include "Eigen/LU"

namespace Tenh {

template <typename Factor1_, typename Factor2_, typename Scalar_>
struct EigenMapOf2Tensor_const_f
{
    typedef Eigen::Map<Eigen::Matrix<Scalar_,
                                     DimensionOf_f<Factor1_>::V,
                                     DimensionOf_f<Factor2_>::V,
                                     Eigen::RowMajor> const> T;
};

template <typename Factor1_, typename Factor2_, typename Scalar_>
struct EigenMapOf2Tensor_nonconst_f
{
    typedef Eigen::Map<Eigen::Matrix<Scalar_,
                                     DimensionOf_f<Factor1_>::V,
                                     DimensionOf_f<Factor2_>::V,
                                     Eigen::RowMajor> > T;
};

// const version
template <typename Factor1_, typename Factor2_, typename Scalar_, typename UseArrayType_>
typename EigenMapOf2Tensor_const_f<Factor1_,Factor2_,Scalar_>::T
    EigenMap_of_2tensor (ImplementationOf_t<TensorProductOfBasedVectorSpaces_c<TypeList_t<Factor1_,
                                                                               TypeList_t<Factor2_> > >,
                                            Scalar_,
                                            UseArrayType_> const &t)
{
    STATIC_ASSERT(!IsUseImmutableArray_f<UseArrayType_>::V, CANT_MAKE_EIGEN_MAP_OF_IMMUTABLE_ARRAY);
    return typename EigenMapOf2Tensor_const_f<Factor1_,Factor2_,Scalar_>::T(t.pointer_to_allocation());
}

// non-const version
template <typename Factor1_, typename Factor2_, typename Scalar_, typename UseArrayType_>
typename EigenMapOf2Tensor_nonconst_f<Factor1_,Factor2_,Scalar_>::T
    EigenMap_of_2tensor (ImplementationOf_t<TensorProductOfBasedVectorSpaces_c<TypeList_t<Factor1_,
                                                                               TypeList_t<Factor2_> > >,
                                            Scalar_,
                                            UseArrayType_> &t)
{
    STATIC_ASSERT(!IsUseImmutableArray_f<UseArrayType_>::V, CANT_MAKE_EIGEN_MAP_OF_IMMUTABLE_ARRAY);
    return typename EigenMapOf2Tensor_nonconst_f<Factor1_,Factor2_,Scalar_>::T(t.pointer_to_allocation());
}

template <typename Type_, typename Scalar_>
struct EigenMapOfVector_const_f
{
    typedef Eigen::Map<Eigen::Matrix<Scalar_,
                                     DimensionOf_f<Type_>::V,
                                     1,
                                     Eigen::RowMajor> const> T;
};

template <typename Type_, typename Scalar_>
struct EigenMapOfVector_nonconst_f
{
    typedef Eigen::Map<Eigen::Matrix<Scalar_,
                                     DimensionOf_f<Type_>::V,
                                     1,
                                     Eigen::RowMajor> > T;
};

// const version
template <typename Type_, typename Scalar_, typename UseArrayType_>
typename EigenMapOfVector_const_f<Type_,Scalar_>::T
    EigenMap_of_vector (ImplementationOf_t<Type_,
                                           Scalar_,
                                           UseArrayType_> const &t)
{
    STATIC_ASSERT(!IsUseImmutableArray_f<UseArrayType_>::V, CANT_MAKE_EIGEN_MAP_OF_IMMUTABLE_ARRAY);
    return typename EigenMapOfVector_const_f<Type_,Scalar_>::T(t.pointer_to_allocation());
}

// non-const version
template <typename Type_, typename Scalar_, typename UseArrayType_>
typename EigenMapOfVector_nonconst_f<Type_,Scalar_>::T
    EigenMap_of_vector (ImplementationOf_t<Type_,
                                           Scalar_,
                                           UseArrayType_> &t)
{
    STATIC_ASSERT(!IsUseImmutableArray_f<UseArrayType_>::V, CANT_MAKE_EIGEN_MAP_OF_IMMUTABLE_ARRAY);
    return typename EigenMapOfVector_nonconst_f<Type_,Scalar_>::T(t.pointer_to_allocation());
}

// returns true iff the tensor was actually considered to be invertible (by Eigen::MatrixBase::computeInverseWithCheck)
template <typename Factor1_, typename Factor2_, typename Scalar_, typename UseArrayType_, typename InverseUseArrayType_>
bool invert_2tensor (ImplementationOf_t<TensorProductOfBasedVectorSpaces_c<TypeList_t<Factor1_,
                                                                           TypeList_t<Factor2_> > >,
                                        Scalar_,
                                        UseArrayType_> const &t,
                     ImplementationOf_t<TensorProductOfBasedVectorSpaces_c<TypeList_t<typename DualOf_f<Factor2_>::T,
                                                                           TypeList_t<typename DualOf_f<Factor1_>::T> > >,
                                        Scalar_,
                                        InverseUseArrayType_> &t_inverse)
{
    STATIC_ASSERT(DimensionOf_f<Factor1_>::V == DimensionOf_f<Factor2_>::V, FACTOR_DIMENSIONS_MUST_BE_EQUAL);
    STATIC_ASSERT(!IsUseImmutableArray_f<UseArrayType_>::V, CANT_MAKE_EIGEN_MAP_OF_IMMUTABLE_ARRAY); // TODO: provide invert for UseImmutableArray
    // create Eigen Maps for each of the parameters -- this way no copying is necessary;
    // the t tensor's components are read directly by Eigen, and t_inverse's components
    // are directly written to by Eigen.
    typedef Eigen::Matrix<Scalar_, DimensionOf_f<Factor1_>::V, DimensionOf_f<Factor2_>::V, Eigen::RowMajor> EigenMatrixType;
    typename EigenMapOf2Tensor_const_f<Factor1_,Factor2_,Scalar_>::T eigen_map_of_t(EigenMap_of_2tensor(t));
    typename EigenMapOf2Tensor_nonconst_f<typename DualOf_f<Factor2_>::T,typename DualOf_f<Factor1_>::T,Scalar_>::T eigen_map_of_t_inverse(EigenMap_of_2tensor(t_inverse));
    Eigen::FullPivLU<EigenMatrixType> lu(eigen_map_of_t);

    if (lu.isInvertible())
    {
       eigen_map_of_t_inverse = lu.inverse();
       return true;
    }
    else
    {
      return false;
    }
}

// returns true iff the tensor was actually considered to be invertible (by Eigen::MatrixBase::computeInverseWithCheck)
template <typename Factor_, typename Scalar_, typename UseArrayType_, typename InverseUseArrayType_>
bool invert_2tensor (ImplementationOf_t<SymmetricPowerOfBasedVectorSpace_c<2, Factor_>,
                                        Scalar_,
                                        UseArrayType_> const &s,
                     ImplementationOf_t<SymmetricPowerOfBasedVectorSpace_c<2, typename DualOf_f<Factor_>::T >,
                                        Scalar_,
                                        InverseUseArrayType_> &s_inverse)
{
    STATIC_ASSERT(!IsUseImmutableArray_f<UseArrayType_>::V, CANT_MAKE_EIGEN_MAP_OF_IMMUTABLE_ARRAY); // TODO: provide invert for UseImmutableArray
    // create Eigen Maps for each of the parameters -- this way no copying is necessary;
    // the t tensor's components are read directly by Eigen, and t_inverse's components
    // are directly written to by Eigen.
    typedef ImplementationOf_t<TensorProductOfBasedVectorSpaces_c<TypeList_t<Factor_, TypeList_t<Factor_> > >, Scalar_> TwoTensorType;
    typedef ImplementationOf_t<TensorProductOfBasedVectorSpaces_c<TypeList_t<typename DualOf_f<Factor_>::T, TypeList_t<typename DualOf_f<Factor_>::T> > >, Scalar_> TwoTensorDualType;
    typedef SymmetricPowerOfBasedVectorSpace_c<2, typename DualOf_f<Factor_>::T > SymDualType;
    typedef Eigen::Matrix<Scalar_, DimensionOf_f<Factor_>::V, DimensionOf_f<Factor_>::V, Eigen::RowMajor> EigenMatrixType;

    AbstractIndex_c<'a'> a;
    AbstractIndex_c<'i'> i;
    AbstractIndex_c<'j'> j;

    TwoTensorType t(Static<WithoutInitialization>::SINGLETON);
    TwoTensorDualType t_inverse(Static<WithoutInitialization>::SINGLETON);
    t(i|j) = s(a).split(a,i|j);
    typename EigenMapOf2Tensor_const_f<Factor_,Factor_,Scalar_>::T eigen_map_of_t(EigenMap_of_2tensor(t));
    typename EigenMapOf2Tensor_nonconst_f<typename DualOf_f<Factor_>::T,typename DualOf_f<Factor_>::T,Scalar_>::T eigen_map_of_t_inverse(EigenMap_of_2tensor(t_inverse));
    Eigen::FullPivLU<EigenMatrixType> lu(eigen_map_of_t);

    if (lu.isInvertible())
    {
       eigen_map_of_t_inverse = lu.inverse();
       s_inverse(a) = t_inverse(i|j).bundle(i|j, SymDualType(), a);
       return true;
    }
    else
    {
      return false;
    }
}

// returns true iff the tensor was actually considered to be invertible (by Eigen::MatrixBase::computeInverseWithCheck)
template <typename Factor1_, typename Factor2_, typename Scalar_, typename UseArrayType_>
Scalar_ determinant_of_2tensor (ImplementationOf_t<TensorProductOfBasedVectorSpaces_c<TypeList_t<Factor1_,
                                                                           TypeList_t<Factor2_> > >,
                                                  Scalar_,
                                                  UseArrayType_> const &t)
{
    STATIC_ASSERT(DimensionOf_f<Factor1_>::V == DimensionOf_f<Factor2_>::V, FACTOR_DIMENSIONS_MUST_BE_EQUAL);
    STATIC_ASSERT(!IsUseImmutableArray_f<UseArrayType_>::V, CANT_MAKE_EIGEN_MAP_OF_IMMUTABLE_ARRAY); // TODO: provide determinant for UseImmutableArray
    // create Eigen Maps for the parameter -- this way no copying is necessary;
    // the t tensor's components are read directly by Eigen.
    typedef Eigen::Matrix<Scalar_, DimensionOf_f<Factor1_>::V, DimensionOf_f<Factor2_>::V, Eigen::RowMajor> EigenMatrixType;
    typename EigenMapOf2Tensor_const_f<Factor1_,Factor2_,Scalar_>::T eigen_map_of_t(EigenMap_of_2tensor(t));

    if (DimensionOf_f<Factor1_>::V > 4)
    {
      Eigen::FullPivLU<EigenMatrixType> lu(eigen_map_of_t);
      return lu.determinant();
    }
    else
    {
      return eigen_map_of_t.determinant();
    }
}

// TODO: specialization for diagonal 2-tensors

} // end of namespace Tenh

#endif // TENH_INTEROP_EIGEN_HPP_
<|endoftext|>


<commit_before><commit_msg>take a const reference rather than a copy<commit_after><|endoftext|>


<commit_before><commit_msg>5.27 引数の重複確認<commit_after><|endoftext|>


<commit_before><commit_msg>Add --accuracy option to udpipe.<commit_after><|endoftext|>


<commit_before><commit_msg>Fix count of all spent compromised ATXOs in CountAnonOutputs() <commit_after><|endoftext|>


<commit_before>#include <cstdio>
#include <cmath>
#include <vector>
#include <algorithm>

using namespace std;

// Some performance optimizations are commented out as an alternative implementation.
// See the comments by Vinicius Miranda for more information:
// http://blog.famzah.net/2010/07/01/cpp-vs-python-vs-perl-vs-php-performance-benchmark/#comment-5347

void get_primes7(int n, vector<int> &res) {
	if (n < 2) return;
	if (n == 2) {
		res.push_back(2);
		return;
	}
	vector<int> s;
	// 1 //s.reserve(n/2); // hint the compiler that we will use "n/2" elements in "s"
	// 2 //s.resize( static_cast<int>(n/2) ); // pre-allocate memory
	// 2 //int j = 0;
	for (int i = 3; i < n + 1; i += 2) {
		s.push_back(i);
		// 2 //s[j] = i;
		// 2 //++j;
	}
	// 2 //s.resize(j);
	int mroot = sqrt(n);
	int half = static_cast<int>(s.size());
	int i = 0;
	int m = 3;
	while (m <= mroot) {
		if (s[i]) {
			int j = static_cast<int>((m*m - 3)*0.5);
			s[j] = 0;
			while (j < half) {
				s[j] = 0;
				j += m;
			}
		}
		i = i + 1;
		m = 2*i + 3;
	}
	// 1 //res.reserve(n/log(n)); // "Prime number theorem" says that we expect this amount of primes
	res.push_back(2);

	/*
	// loop manually
	for (vector<int>::iterator it = s.begin() ; it < s.end(); ++it) {
		if (*it) {
			res.push_back(*it);
		}
	}
	*/

	// use standard methods instead of a loop
	std::vector<int>::iterator pend = std::remove(s.begin(), s.end(), 0);
	res.insert(res.begin() + 1, s.begin(), pend);
}

int main() {
	while (1) {
		vector<int> res;
		get_primes7(10000000, res);
		printf("Found %d prime numbers.\n", (int)res.size());
	}

	return 0;
}
<commit_msg>Limit running time by an ENV variable<commit_after>#include <cstdio>
#include <cmath>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <ctime>

using namespace std;

// Some performance optimizations are commented out as an alternative implementation.
// See the comments by Vinicius Miranda for more information:
// http://blog.famzah.net/2010/07/01/cpp-vs-python-vs-perl-vs-php-performance-benchmark/#comment-5347

void get_primes7(int n, vector<int> &res) {
	if (n < 2) return;
	if (n == 2) {
		res.push_back(2);
		return;
	}
	vector<int> s;
	// 1 //s.reserve(n/2); // hint the compiler that we will use "n/2" elements in "s"
	// 2 //s.resize( static_cast<int>(n/2) ); // pre-allocate memory
	// 2 //int j = 0;
	for (int i = 3; i < n + 1; i += 2) {
		s.push_back(i);
		// 2 //s[j] = i;
		// 2 //++j;
	}
	// 2 //s.resize(j);
	int mroot = sqrt(n);
	int half = static_cast<int>(s.size());
	int i = 0;
	int m = 3;
	while (m <= mroot) {
		if (s[i]) {
			int j = static_cast<int>((m*m - 3)*0.5);
			s[j] = 0;
			while (j < half) {
				s[j] = 0;
				j += m;
			}
		}
		i = i + 1;
		m = 2*i + 3;
	}
	// 1 //res.reserve(n/log(n)); // "Prime number theorem" says that we expect this amount of primes
	res.push_back(2);

	/*
	// loop manually
	for (vector<int>::iterator it = s.begin() ; it < s.end(); ++it) {
		if (*it) {
			res.push_back(*it);
		}
	}
	*/

	// use standard methods instead of a loop
	std::vector<int>::iterator pend = std::remove(s.begin(), s.end(), 0);
	res.insert(res.begin() + 1, s.begin(), pend);
}

int main() {
	std::time_t startTime = std::time(NULL);
	std::time_t periodTime = (std::time_t) atoi(std::getenv("RUN_TIME"));

	while ((std::time(NULL) - startTime) < periodTime) {
		vector<int> res;
		get_primes7(10000000, res);
		printf("Found %d prime numbers.\n", (int)res.size());
	}

	return 0;
}
<|endoftext|>


<commit_before>#include "problem.h"

#include <complex>
#include <vector>
#include <fstream>

#include "base/base.h"
#include "boost/multiprecision/cpp_int.hpp"
#include "boost/rational.hpp"
#include "polygon.h"

DEFINE_bool(expand_viewbox, true,
            "Expand viewbox to covert the entire silhouette.");
DEFINE_bool(shrink_viewbox, true,
            "Shrink viewbox to fit silhouette and hide the original rect.");
DEFINE_string(input, "/dev/stdin", "input problem file");
DEFINE_bool(filtered, false, "set if input is filtered by prefilter");

using boost::rational;
using boost::rational_cast;
using namespace std;

int main(int argc, char** argv) {
  ParseCommandLineFlags(&argc, &argv);

  std::ifstream ifs(FLAGS_input);
  Problem problem;
  FilteredProblem filtered_problem;
  if (FLAGS_filtered) {
    ReadFilteredProblem(ifs, &filtered_problem);
    problem.polygons.resize(filtered_problem.polygons.size());
    for (int i = 0; i < filtered_problem.polygons.size(); ++i) {
      ResolveIndexReference(filtered_problem.polygons[i],
                            filtered_problem.vertices, &problem.polygons[i]);
    }
  } else {
    ReadProblem(ifs, &problem);
  }

  // viewbox size
  Q min_x = 0, min_y = 0, max_x = 1, max_y = 1;
  if (FLAGS_shrink_viewbox) {
    min_x = max_x = problem.polygons[0][0].x;
    min_y = max_y = problem.polygons[0][0].y;
  }
  if (FLAGS_expand_viewbox) {
    for (int i = 0; i < problem.polygons.size(); ++i) {
      for (const auto& v : problem.polygons[i]) {
        if (v.x < min_x) min_x = v.x;
        if (max_x < v.x) max_x = v.x;
        if (v.y < min_y) min_y = v.y;
        if (max_y < v.y) max_y = v.y;
      }
    }
  }
  if (FLAGS_shrink_viewbox) {
    // Translate to reasonable coordinates
    for (auto& p : problem.polygons) {
      for (auto& v : p) {
        v.x -= min_x;
        v.y -= min_y;
      }
    }
    for (auto& e : problem.skelton) {
      e.first.x -= min_x;
      e.first.y -= min_y;
      e.second.x -= min_x;
      e.second.y -= min_y;
    }
    LOG(INFO) << "Translate " << min_x << "," << min_y;
    max_x -= min_x;
    max_y -= min_y;
    min_x = min_y = 0;
  }
  printf(
      R"q(<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="400px" height="400px" viewBox="%.3f %.3f %.3f %.3f" stroke-linejoin="round" stroke-linecap="round"><g transform="scale(1,-1)">)q",
      min_x.convert_to<double>() - 0.005, -max_y.convert_to<double>() - 0.005,
      (max_x - min_x).convert_to<double>() + 0.01,
      (max_y - min_y).convert_to<double>() + 0.01);
  if (!FLAGS_shrink_viewbox) {
    printf(
        R"(<rect x="0" y="0" width="1" height="1" fill="none" stroke="blue" stroke-width="0.005"/>)");
  }
  printf(
      R"(<path fill="silver" stroke="gray" stroke-width="0.005" fill-rule="nonzero" d=")");
  for (int i = 0; i < problem.polygons.size(); ++i) {
    for (int j = 0; j < problem.polygons[i].size(); ++j) {
      printf("%c%.3f %.3f", j == 0 ? 'M' : 'L',
             problem.polygons[i][j].x.convert_to<double>(),
             problem.polygons[i][j].y.convert_to<double>());
    }
    printf("Z");
  }
  printf(
      R"("/><g fill="none" stroke="purple" stroke-width="0.003">)");
  for (const auto& e : problem.skelton) {
    printf(
        R"(<path d="M%.3f %.3fL%.3f %.3f"/>)", e.first.x.convert_to<double>(),
        e.first.y.convert_to<double>(), e.second.x.convert_to<double>(),
        e.second.y.convert_to<double>());
  }
  printf("</g>");
  for (int i = 0; i < filtered_problem.vertices.size(); ++i) {
    printf(
        R"(<circle id="v%d" fill="black" cx="%.3f" cy="%.3f" r="0.008"/>)", i,
        filtered_problem.vertices[i].x.convert_to<double>(),
        filtered_problem.vertices[i].y.convert_to<double>());
  }
  printf("</g></svg>");

  return 0;
}
<commit_msg>Fix problem.<commit_after>#include "problem.h"

#include <complex>
#include <vector>
#include <fstream>

#include "base/base.h"
#include "boost/multiprecision/cpp_int.hpp"
#include "boost/rational.hpp"
#include "polygon.h"

DEFINE_bool(expand_viewbox, true,
            "Expand viewbox to covert the entire silhouette.");
DEFINE_bool(shrink_viewbox, true,
            "Shrink viewbox to fit silhouette and hide the original rect.");
DEFINE_string(input, "/dev/stdin", "input problem file");
DEFINE_bool(filtered, false, "set if input is filtered by prefilter");

using boost::rational;
using boost::rational_cast;
using namespace std;

int main(int argc, char** argv) {
  ParseCommandLineFlags(&argc, &argv);

  std::ifstream ifs(FLAGS_input);
  Problem problem;
  FilteredProblem filtered_problem;
  if (FLAGS_filtered) {
    ReadFilteredProblem(ifs, &filtered_problem);
    problem.polygons.resize(filtered_problem.polygons.size());
    for (int i = 0; i < filtered_problem.polygons.size(); ++i) {
      ResolveIndexReference(filtered_problem.polygons[i],
                            filtered_problem.vertices, &problem.polygons[i]);
    }
  } else {
    ReadProblem(ifs, &problem);
  }

  // viewbox size
  Q min_x = 0, min_y = 0, max_x = 1, max_y = 1;
  if (FLAGS_shrink_viewbox) {
    min_x = max_x = problem.polygons[0][0].x;
    min_y = max_y = problem.polygons[0][0].y;
  }
  if (FLAGS_expand_viewbox) {
    for (int i = 0; i < problem.polygons.size(); ++i) {
      for (const auto& v : problem.polygons[i]) {
        if (v.x < min_x) min_x = v.x;
        if (max_x < v.x) max_x = v.x;
        if (v.y < min_y) min_y = v.y;
        if (max_y < v.y) max_y = v.y;
      }
    }
  }
  if (FLAGS_shrink_viewbox) {
    // Translate to reasonable coordinates
    for (auto& p : problem.polygons) {
      for (auto& v : p) {
        v.x -= min_x;
        v.y -= min_y;
      }
    }
    for (auto& e : problem.skelton) {
      e.first.x -= min_x;
      e.first.y -= min_y;
      e.second.x -= min_x;
      e.second.y -= min_y;
    }
    for (auto& v : filtered_problem.vertices) {
      v.x -= min_x;
      v.y -= min_y;
    }
    LOG(INFO) << "Translate " << min_x << "," << min_y;
    max_x -= min_x;
    max_y -= min_y;
    min_x = min_y = 0;
  }
  printf(
      R"q(<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="400px" height="400px" viewBox="%.3f %.3f %.3f %.3f" stroke-linejoin="round" stroke-linecap="round"><g transform="scale(1,-1)">)q",
      min_x.convert_to<double>() - 0.005, -max_y.convert_to<double>() - 0.005,
      (max_x - min_x).convert_to<double>() + 0.01,
      (max_y - min_y).convert_to<double>() + 0.01);
  if (!FLAGS_shrink_viewbox) {
    printf(
        R"(<rect x="0" y="0" width="1" height="1" fill="none" stroke="blue" stroke-width="0.005"/>)");
  }
  printf(
      R"(<path fill="silver" stroke="gray" stroke-width="0.005" fill-rule="nonzero" d=")");
  for (int i = 0; i < problem.polygons.size(); ++i) {
    for (int j = 0; j < problem.polygons[i].size(); ++j) {
      printf("%c%.3f %.3f", j == 0 ? 'M' : 'L',
             problem.polygons[i][j].x.convert_to<double>(),
             problem.polygons[i][j].y.convert_to<double>());
    }
    printf("Z");
  }
  printf(
      R"("/><g fill="none" stroke="purple" stroke-width="0.003">)");
  for (const auto& e : problem.skelton) {
    printf(
        R"(<path d="M%.3f %.3fL%.3f %.3f"/>)", e.first.x.convert_to<double>(),
        e.first.y.convert_to<double>(), e.second.x.convert_to<double>(),
        e.second.y.convert_to<double>());
  }
  printf("</g>");
  for (int i = 0; i < filtered_problem.vertices.size(); ++i) {
    printf(
        R"(<circle id="v%d" fill="black" cx="%.3f" cy="%.3f" r="0.008"/>)", i,
        filtered_problem.vertices[i].x.convert_to<double>(),
        filtered_problem.vertices[i].y.convert_to<double>());
  }
  printf("</g></svg>");

  return 0;
}
<|endoftext|>


<commit_before><commit_msg>Test updates<commit_after><|endoftext|>