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

Copyright (c) 2000-2013 Torus Knot Software Ltd
Also see acknowledgements in Readme.html

You may use this sample code for anything you like, it is not covered by the
same license as the rest of the engine.
-----------------------------------------------------------------------------
*/
#include "SdkSample.h"
#include "SamplePlugin.h"

using namespace Ogre;
using namespace OgreBites;

SamplePlugin* sp;
Sample* s;

class _OgreSampleClassExport Sample_Basic : public SdkSample
{
    Entity* mOgreEnt;

    TexturePtr mImage;
    HardwarePixelBufferSharedPtr mPixelBuffer;

    //HardwareCounterBufferSharedPtr mBuffer;

 public:

    Sample_Basic()
    {
        mInfo["Title"] = "Basic";
        mInfo["Description"] = "A basic example using every available shader type.";
        mInfo["Thumbnail"] = "thumb_basic.png";
        mInfo["Category"] = "Tests";
    }

    void testCapabilities(const RenderSystemCapabilities* caps)
    {
        if (!caps->hasCapability(RSC_GEOMETRY_PROGRAM))
        {
            OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Your render system / hardware does not support geometry programs, "
                        "so you cannot run this sample. Sorry!",
                        "Sample_Basic::testCapabilities");
        }
        //TODO check for tessellation shaders and compute shaders too
    }

    // Just override the mandatory create scene method
    void setupContent(void)
    {
        mCamera->setPosition(0, 0, -40);
        mCamera->lookAt(0,0,0);
        // mCamera->setNearClipDistance(0.1);
        // mCamera->setFarClipDistance(100);

        mOgreEnt = mSceneMgr->createEntity("PlainHead", "ogrehead.mesh");
        mOgreEnt->setMaterialName("JAJ/Basic");
        //mOgreEnt->setMaterialName("BaseWhiteNoLighting");
        SceneNode* ogre = mSceneMgr->getRootSceneNode()->createChildSceneNode();
        ogre->setPosition(50, -50, 140);
        ogre->setDirection(0,0,1);
        ogre->attachObject(mOgreEnt);

        ////////////////////////////////
        // Image Load/Store
        ////////////////////////////////

        mImage = TextureManager::getSingleton().createManual(
            "ImageData", // Name of texture
            "General",   // Name of resource group in which the texture should be created
            TEX_TYPE_2D, // Texture type
            256, 256, 1, // Width, Height, Depth
            0,           // Number of mipmaps
            PF_X8R8G8B8  // Pixel format  //TODO support formats from GL3+
            //TU_DYNAMIC   // usage
        );

        mImage->createShaderAccessPoint(0);

        mPixelBuffer = mImage->getBuffer(0,0);

        // Lock the buffer so we can write to it.
        mPixelBuffer->lock(HardwareBuffer::HBL_DISCARD);
        const PixelBox &pb = mPixelBuffer->getCurrentLock();

        // Update the contents of pb here
        // Image data starts at pb.data and has format pb.format
        // Here we assume data.format is PF_X8R8G8B8 so we can address pixels as uint32.
        uint *data = static_cast<uint*>(pb.data);
        size_t height = pb.getHeight();
        size_t width = pb.getWidth();
        size_t pitch = pb.rowPitch; // Skip between rows of image
        for (size_t y = 0; y < height; ++y)
        {
            for(size_t x = 0; x < width; ++x)
            {
                // 0xXXRRGGBB -> fill the buffer with yellow pixels
                // data[pitch * y + x] = 0x00FFFF00;
                data[pitch * y + x] = 0x0087CEEB;
            }
        }

        // Unlock the buffer again (frees it for use by the GPU)
        mPixelBuffer->unlock();
    }

    void cleanupContent()
    {
        // Read image load/store data.
        mPixelBuffer->lock(HardwareBuffer::HBL_READ_ONLY);
        const PixelBox &pb = mPixelBuffer->getCurrentLock();
        uint *data = static_cast<uint*>(pb.data);
        size_t height = pb.getHeight();
        size_t width = pb.getWidth();
        size_t pitch = pb.rowPitch; // Skip between rows of image
        printf("Buffer values.\n");
        // for (size_t y = 0; y < height; ++y)
        // {
        //     for(size_t x = 0; x < width; ++x)
        //     {
        //         std::cout << " " << std::hex << data[pitch * y + x];
        //     }
        //     std::cout << std::endl;
        // }
        std::cout << std::hex << data[0];
        std::cout << " " << data[1] << std::endl;
        mPixelBuffer->unlock();

        //MeshManager::getSingleton().remove(mTetrahedraMesh->getName());
    }

    bool frameRenderingQueued(const FrameEvent& evt)
    {
        Real seconds = (Real)(Root::getSingleton().getTimer()->getMilliseconds()) / 1000.0;
        Pass* renderPass = mOgreEnt->getSubEntity(0)->getMaterial()->getTechnique(0)->getPass(0);
        if (renderPass->hasFragmentProgram())
        {
            Ogre::GpuProgramParametersSharedPtr pParams = renderPass->getFragmentProgramParameters();
            if ( pParams.isNull() )
            {
                //printf("SAD PANDA!");
            }
            else
            {
                if ( pParams->_findNamedConstantDefinition( "ColourMe[0]" ) )
                {
                    Vector4 constParam = Ogre::Vector4(0.5, 0.1, 0.0, 1.0);
                    renderPass->getFragmentProgramParameters()->setNamedConstant("ColourMe[0]", constParam);

                    Vector4 timeParam = Ogre::Vector4(
                        Ogre::Math::Sin(seconds)*0.5, 0.0, Ogre::Math::Cos(seconds)*0.5, 0.0);
                    renderPass->getFragmentProgramParameters()->setNamedConstant("ColourMe[1]", timeParam);
                }
                const Ogre::GpuConstantDefinition* atom_counter_def;
                if ( (atom_counter_def = &pParams->getConstantDefinition("atom_counter")) )
                {
                    //TODO lock buffer, retrieve counter value similar to compute above
                    //const uint* counter = pParams->getUnsignedIntPointer(atom_counter_def->physicalIndex);
                    //const uint* counter2 = ;
                    //std::cout << "FOUND THE ATOMS: " << *counter << " " << std::endl; //<< *counter2 << std::endl;
                }
            }
        }

        // renderPass->getFragmentProgramParameters()->getConstantDefinition("atom_counter").getValue();
        return SdkSample::frameRenderingQueued(evt);
    }
};

#ifndef OGRE_STATIC_LIB

extern "C" _OgreSampleExport void dllStartPlugin()
{
    s = new Sample_Basic;
    sp = OGRE_NEW SamplePlugin(s->getInfo()["Title"] + " Sample");
    sp->addSample(s);
    Root::getSingleton().installPlugin(sp);
}

extern "C" _OgreSampleExport void dllStopPlugin()
{
    Root::getSingleton().uninstallPlugin(sp);
    OGRE_DELETE sp;
    delete s;
}

#endif
<commit_msg>Add capabilities check to basic sample<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2013 Torus Knot Software Ltd
Also see acknowledgements in Readme.html

You may use this sample code for anything you like, it is not covered by the
same license as the rest of the engine.
-----------------------------------------------------------------------------
*/
#include "SdkSample.h"
#include "SamplePlugin.h"

using namespace Ogre;
using namespace OgreBites;

SamplePlugin* sp;
Sample* s;

class _OgreSampleClassExport Sample_Basic : public SdkSample
{
    Entity* mOgreEnt;

    TexturePtr mImage;
    HardwarePixelBufferSharedPtr mPixelBuffer;

    //HardwareCounterBufferSharedPtr mBuffer;

 public:

    Sample_Basic()
    {
        mInfo["Title"] = "Basic";
        mInfo["Description"] = "A basic example using every available shader type.";
        mInfo["Thumbnail"] = "thumb_basic.png";
        mInfo["Category"] = "Tests";
    }

    void testCapabilities(const RenderSystemCapabilities* caps)
    {
        if (!caps->hasCapability(RSC_ATOMIC_COUNTERS))
        {
            OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Your render system / hardware does not support atomic counters, "
                        "so you cannot run this sample. Sorry!",
                        "Sample_Basic::testCapabilities");
        }

        if (!caps->hasCapability(RSC_COMPUTE_PROGRAM))
        {
            OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Your render system / hardware does not support compute programs, "
                        "so you cannot run this sample. Sorry!",
                        "Sample_Basic::testCapabilities");
        }

        if (!caps->hasCapability(RSC_TESSELATION_HULL_PROGRAM) || !caps->hasCapability(RSC_TESSELATION_DOMAIN_PROGRAM))
        {
            OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Your render system / hardware does not support tesselation programs, "
                        "so you cannot run this sample. Sorry!",
                        "Sample_Basic::testCapabilities");
        }

        if (!caps->hasCapability(RSC_GEOMETRY_PROGRAM))
        {
            OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Your render system / hardware does not support geometry programs, "
                        "so you cannot run this sample. Sorry!",
                        "Sample_Basic::testCapabilities");
        }
    }

    // Just override the mandatory create scene method
    void setupContent(void)
    {
        mCamera->setPosition(0, 0, -40);
        mCamera->lookAt(0,0,0);
        // mCamera->setNearClipDistance(0.1);
        // mCamera->setFarClipDistance(100);

        mOgreEnt = mSceneMgr->createEntity("PlainHead", "ogrehead.mesh");
        mOgreEnt->setMaterialName("JAJ/Basic");
        //mOgreEnt->setMaterialName("BaseWhiteNoLighting");
        SceneNode* ogre = mSceneMgr->getRootSceneNode()->createChildSceneNode();
        ogre->setPosition(50, -50, 140);
        ogre->setDirection(0,0,1);
        ogre->attachObject(mOgreEnt);

        ////////////////////////////////
        // Image Load/Store
        ////////////////////////////////

        mImage = TextureManager::getSingleton().createManual(
            "ImageData", // Name of texture
            "General",   // Name of resource group in which the texture should be created
            TEX_TYPE_2D, // Texture type
            256, 256, 1, // Width, Height, Depth
            0,           // Number of mipmaps
            PF_X8R8G8B8  // Pixel format  //TODO support formats from GL3+
            //TU_DYNAMIC   // usage
        );

        mImage->createShaderAccessPoint(0);

        mPixelBuffer = mImage->getBuffer(0,0);

        // Lock the buffer so we can write to it.
        mPixelBuffer->lock(HardwareBuffer::HBL_DISCARD);
        const PixelBox &pb = mPixelBuffer->getCurrentLock();

        // Update the contents of pb here
        // Image data starts at pb.data and has format pb.format
        // Here we assume data.format is PF_X8R8G8B8 so we can address pixels as uint32.
        uint *data = static_cast<uint*>(pb.data);
        size_t height = pb.getHeight();
        size_t width = pb.getWidth();
        size_t pitch = pb.rowPitch; // Skip between rows of image
        for (size_t y = 0; y < height; ++y)
        {
            for(size_t x = 0; x < width; ++x)
            {
                // 0xXXRRGGBB -> fill the buffer with yellow pixels
                // data[pitch * y + x] = 0x00FFFF00;
                data[pitch * y + x] = 0x0087CEEB;
            }
        }

        // Unlock the buffer again (frees it for use by the GPU)
        mPixelBuffer->unlock();
    }

    void cleanupContent()
    {
        // Read image load/store data.
        mPixelBuffer->lock(HardwareBuffer::HBL_READ_ONLY);
        const PixelBox &pb = mPixelBuffer->getCurrentLock();
        uint *data = static_cast<uint*>(pb.data);
        size_t height = pb.getHeight();
        size_t width = pb.getWidth();
        size_t pitch = pb.rowPitch; // Skip between rows of image
        printf("Buffer values.\n");
        // for (size_t y = 0; y < height; ++y)
        // {
        //     for(size_t x = 0; x < width; ++x)
        //     {
        //         std::cout << " " << std::hex << data[pitch * y + x];
        //     }
        //     std::cout << std::endl;
        // }
        std::cout << std::hex << data[0];
        std::cout << " " << data[1] << std::endl;
        mPixelBuffer->unlock();

        //MeshManager::getSingleton().remove(mTetrahedraMesh->getName());
    }

    bool frameRenderingQueued(const FrameEvent& evt)
    {
        Real seconds = (Real)(Root::getSingleton().getTimer()->getMilliseconds()) / 1000.0;
        Pass* renderPass = mOgreEnt->getSubEntity(0)->getMaterial()->getTechnique(0)->getPass(0);
        if (renderPass->hasFragmentProgram())
        {
            Ogre::GpuProgramParametersSharedPtr pParams = renderPass->getFragmentProgramParameters();
            if ( pParams.isNull() )
            {
                //printf("SAD PANDA!");
            }
            else
            {
                if ( pParams->_findNamedConstantDefinition( "ColourMe[0]" ) )
                {
                    Vector4 constParam = Ogre::Vector4(0.5, 0.1, 0.0, 1.0);
                    renderPass->getFragmentProgramParameters()->setNamedConstant("ColourMe[0]", constParam);

                    Vector4 timeParam = Ogre::Vector4(
                        Ogre::Math::Sin(seconds)*0.5, 0.0, Ogre::Math::Cos(seconds)*0.5, 0.0);
                    renderPass->getFragmentProgramParameters()->setNamedConstant("ColourMe[1]", timeParam);
                }
                const Ogre::GpuConstantDefinition* atom_counter_def;
                if ( (atom_counter_def = &pParams->getConstantDefinition("atom_counter")) )
                {
                    //TODO lock buffer, retrieve counter value similar to compute above
                    //const uint* counter = pParams->getUnsignedIntPointer(atom_counter_def->physicalIndex);
                    //const uint* counter2 = ;
                    //std::cout << "FOUND THE ATOMS: " << *counter << " " << std::endl; //<< *counter2 << std::endl;
                }
            }
        }

        // renderPass->getFragmentProgramParameters()->getConstantDefinition("atom_counter").getValue();
        return SdkSample::frameRenderingQueued(evt);
    }
};

#ifndef OGRE_STATIC_LIB

extern "C" _OgreSampleExport void dllStartPlugin()
{
    s = new Sample_Basic;
    sp = OGRE_NEW SamplePlugin(s->getInfo()["Title"] + " Sample");
    sp->addSample(s);
    Root::getSingleton().installPlugin(sp);
}

extern "C" _OgreSampleExport void dllStopPlugin()
{
    Root::getSingleton().uninstallPlugin(sp);
    OGRE_DELETE sp;
    delete s;
}

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: OutlineViewShell.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-01-11 12:12:37 $
 *
 *  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 SD_OUTLINE_VIEW_SHELL_HXX
#define SD_OUTLINE_VIEW_SHELL_HXX

#ifndef SD_DRAW_DOC_SHELL_HXX
#include "DrawDocShell.hxx"
#endif
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#ifndef SD_OUTLINE_VIEW_HXX
#include "OutlineView.hxx"
#endif

class SdPage;
class TransferableDataHelper;
class TransferableClipboardListener;

namespace sd {

class SdUnoOutlineView;

/** Show a textual overview of the text contents of all slides.
*/
class OutlineViewShell
    : public ViewShell
{
public:
    TYPEINFO();

    SFX_DECL_VIEWFACTORY(OutlineViewShell);
    SFX_DECL_INTERFACE(SD_IF_SDOUTLINEVIEWSHELL);

    // The previous macros change access mode.  To be sure switch back
    // to public access.
public:
    /** Create a new view shell for the outline mode.
        @param rViewShellBase
            The new object will be stacked on this view shell base.
        @param pFrameView
            The frame view that makes it possible to pass information from
            one view shell to the next.
    */
    OutlineViewShell (
        SfxViewFrame* pFrame,
        ViewShellBase& rViewShellBase,
        ::Window* pParentWindow,
        FrameView* pFrameView = NULL);

    OutlineViewShell (
        SfxViewFrame* pFrame,
        ::Window* pParentWindow,
        const OutlineViewShell& rShell);

    virtual ~OutlineViewShell (void);

    virtual void Paint(const Rectangle& rRect, ::sd::Window* pWin);

    /** Arrange and resize the GUI elements like rulers, sliders, and
        buttons as well as the actual document view according to the size of
        the enclosing window and current sizes of buttons, rulers, and
        sliders.
    */
    virtual void ArrangeGUIElements (void);

    virtual USHORT PrepareClose( BOOL bUI = TRUE, BOOL bForBrowsing = FALSE );

    virtual long VirtHScrollHdl(ScrollBar* pHScroll);
    virtual long VirtVScrollHdl(ScrollBar* pVHScroll);

    virtual void AddWindow(::sd::Window* pWin);
    virtual void RemoveWindow(::sd::Window* pWin);

    virtual void Activate( BOOL IsMDIActivate );
    virtual void Deactivate( BOOL IsMDIActivate );

    virtual SdPage* GetActualPage();
    /** Return a string that describes the currently selected pages.
    */
    String GetPageRangeString (void);

    void ExecCtrl(SfxRequest &rReq);
    void GetCtrlState(SfxItemSet &rSet);
    void GetMenuState(SfxItemSet &rSet);
    void GetAttrState(SfxItemSet &rSet);
    void GetState (SfxItemSet& rSet);

    void ExecStatusBar(SfxRequest& rReq);
    void GetStatusBarState(SfxItemSet& rSet);

    void FuTemporary(SfxRequest &rReq);
    void FuPermanent(SfxRequest &rReq);
    void FuSupport(SfxRequest &rReq);

    virtual void SetZoom(long nZoom);
    virtual void SetZoomRect(const Rectangle& rZoomRect);
    virtual String  GetSelectionText( BOOL bCompleteWords = FALSE );
    virtual BOOL    HasSelection( BOOL bText = TRUE ) const;

    void Execute(SfxRequest& rReq);

    virtual void ReadFrameViewData(FrameView* pView);
    virtual void WriteFrameViewData();

    virtual void Command( const CommandEvent& rCEvt, ::sd::Window* pWin );
    virtual BOOL KeyInput(const KeyEvent& rKEvt, ::sd::Window* pWin);
    virtual void MouseButtonUp(const MouseEvent& rMEvt, ::sd::Window* pWin);

    ULONG   Read(SvStream& rInput, const String& rBaseURL, USHORT eFormat);

    virtual void WriteUserDataSequence ( ::com::sun::star::uno::Sequence < ::com::sun::star::beans::PropertyValue >&, sal_Bool bBrowse = sal_False );
    virtual void ReadUserDataSequence ( const ::com::sun::star::uno::Sequence < ::com::sun::star::beans::PropertyValue >&, sal_Bool bBrowse = sal_False );

    /** this method is called when the visible area of the view from this viewshell is changed */
    virtual void VisAreaChanged(const Rectangle& rRect);

    /** Create an accessible object representing the specified window.
        @param pWindow
            The returned object makes the document displayed in this window
            accessible.
        @return
            Returns an <type>AccessibleDrawDocumentView</type> object.
   */
    virtual ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible>
        CreateAccessibleDocumentView (::sd::Window* pWindow);

    /** Update the preview to show the specified page.
    */
    virtual void UpdatePreview (SdPage* pPage, BOOL bInit = FALSE);

    virtual DrawController* GetController (void);

protected:
    virtual Size GetOptimalSizePixel() const;

    // Methoden, die fuer die Preview gebraucht werden
    BOOL          UpdateTitleObject( SdPage* pPage, Paragraph* pPara );
    BOOL          UpdateLayoutObject( SdPage* pPage, Paragraph* pPara );

    /** Make the given page the new current page.  This method
        notifies the controller and adapts the selection of the
        model.
        @param pPage
            The new current page.  Pass NULL when there is no current page.
    */
    void SetCurrentPage (SdPage* pPage);

private:
    OutlineView* pOlView;
    SdPage*         pLastPage; // Zur performanten Aufbereitung der Preview
    TransferableClipboardListener* pClipEvtLstnr;
    BOOL            bPastePossible;

    void Construct (DrawDocShell* pDocSh);
    DECL_LINK( ClipboardChanged, TransferableDataHelper* );
};

} // end of namespace sd

#endif
<commit_msg>INTEGRATION: CWS impress31 (1.6.24); FILE MERGED 2005/01/28 09:13:04 cl 1.6.24.1: #i32920# reworked FuPage to work with master pages without a slide<commit_after>/*************************************************************************
 *
 *  $RCSfile: OutlineViewShell.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: vg $ $Date: 2005-02-17 09:42:18 $
 *
 *  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 SD_OUTLINE_VIEW_SHELL_HXX
#define SD_OUTLINE_VIEW_SHELL_HXX

#ifndef SD_DRAW_DOC_SHELL_HXX
#include "DrawDocShell.hxx"
#endif
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#ifndef SD_OUTLINE_VIEW_HXX
#include "OutlineView.hxx"
#endif

class SdPage;
class TransferableDataHelper;
class TransferableClipboardListener;

namespace sd {

class SdUnoOutlineView;

/** Show a textual overview of the text contents of all slides.
*/
class OutlineViewShell
    : public ViewShell
{
public:
    TYPEINFO();

    SFX_DECL_VIEWFACTORY(OutlineViewShell);
    SFX_DECL_INTERFACE(SD_IF_SDOUTLINEVIEWSHELL);

    // The previous macros change access mode.  To be sure switch back
    // to public access.
public:
    /** Create a new view shell for the outline mode.
        @param rViewShellBase
            The new object will be stacked on this view shell base.
        @param pFrameView
            The frame view that makes it possible to pass information from
            one view shell to the next.
    */
    OutlineViewShell (
        SfxViewFrame* pFrame,
        ViewShellBase& rViewShellBase,
        ::Window* pParentWindow,
        FrameView* pFrameView = NULL);

    OutlineViewShell (
        SfxViewFrame* pFrame,
        ::Window* pParentWindow,
        const OutlineViewShell& rShell);

    virtual ~OutlineViewShell (void);

    virtual void Paint(const Rectangle& rRect, ::sd::Window* pWin);

    /** Arrange and resize the GUI elements like rulers, sliders, and
        buttons as well as the actual document view according to the size of
        the enclosing window and current sizes of buttons, rulers, and
        sliders.
    */
    virtual void ArrangeGUIElements (void);

    virtual USHORT PrepareClose( BOOL bUI = TRUE, BOOL bForBrowsing = FALSE );

    virtual long VirtHScrollHdl(ScrollBar* pHScroll);
    virtual long VirtVScrollHdl(ScrollBar* pVHScroll);

    virtual void AddWindow(::sd::Window* pWin);
    virtual void RemoveWindow(::sd::Window* pWin);

    virtual void Activate( BOOL IsMDIActivate );
    virtual void Deactivate( BOOL IsMDIActivate );

    virtual SdPage* GetActualPage();

    /// inherited from sd::ViewShell
    virtual SdPage* getCurrentPage() const;

    /** Return a string that describes the currently selected pages.
    */
    String GetPageRangeString (void);

    void ExecCtrl(SfxRequest &rReq);
    void GetCtrlState(SfxItemSet &rSet);
    void GetMenuState(SfxItemSet &rSet);
    void GetAttrState(SfxItemSet &rSet);
    void GetState (SfxItemSet& rSet);

    void ExecStatusBar(SfxRequest& rReq);
    void GetStatusBarState(SfxItemSet& rSet);

    void FuTemporary(SfxRequest &rReq);
    void FuPermanent(SfxRequest &rReq);
    void FuSupport(SfxRequest &rReq);

    virtual void SetZoom(long nZoom);
    virtual void SetZoomRect(const Rectangle& rZoomRect);
    virtual String  GetSelectionText( BOOL bCompleteWords = FALSE );
    virtual BOOL    HasSelection( BOOL bText = TRUE ) const;

    void Execute(SfxRequest& rReq);

    virtual void ReadFrameViewData(FrameView* pView);
    virtual void WriteFrameViewData();

    virtual void Command( const CommandEvent& rCEvt, ::sd::Window* pWin );
    virtual BOOL KeyInput(const KeyEvent& rKEvt, ::sd::Window* pWin);
    virtual void MouseButtonUp(const MouseEvent& rMEvt, ::sd::Window* pWin);

    ULONG   Read(SvStream& rInput, const String& rBaseURL, USHORT eFormat);

    virtual void WriteUserDataSequence ( ::com::sun::star::uno::Sequence < ::com::sun::star::beans::PropertyValue >&, sal_Bool bBrowse = sal_False );
    virtual void ReadUserDataSequence ( const ::com::sun::star::uno::Sequence < ::com::sun::star::beans::PropertyValue >&, sal_Bool bBrowse = sal_False );

    /** this method is called when the visible area of the view from this viewshell is changed */
    virtual void VisAreaChanged(const Rectangle& rRect);

    /** Create an accessible object representing the specified window.
        @param pWindow
            The returned object makes the document displayed in this window
            accessible.
        @return
            Returns an <type>AccessibleDrawDocumentView</type> object.
   */
    virtual ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible>
        CreateAccessibleDocumentView (::sd::Window* pWindow);

    /** Update the preview to show the specified page.
    */
    virtual void UpdatePreview (SdPage* pPage, BOOL bInit = FALSE);

    virtual DrawController* GetController (void);

protected:
    virtual Size GetOptimalSizePixel() const;

    // Methoden, die fuer die Preview gebraucht werden
    BOOL          UpdateTitleObject( SdPage* pPage, Paragraph* pPara );
    BOOL          UpdateLayoutObject( SdPage* pPage, Paragraph* pPara );

    /** Make the given page the new current page.  This method
        notifies the controller and adapts the selection of the
        model.
        @param pPage
            The new current page.  Pass NULL when there is no current page.
    */
    void SetCurrentPage (SdPage* pPage);

private:
    OutlineView* pOlView;
    SdPage*         pLastPage; // Zur performanten Aufbereitung der Preview
    TransferableClipboardListener* pClipEvtLstnr;
    BOOL            bPastePossible;

    void Construct (DrawDocShell* pDocSh);
    DECL_LINK( ClipboardChanged, TransferableDataHelper* );
};

} // end of namespace sd

#endif
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: http://www.qt-project.org/
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**************************************************************************/

#include "startremotedialog.h"

#include <coreplugin/icore.h>
#include <coreplugin/id.h>
#include <projectexplorer/kitchooser.h>
#include <projectexplorer/kitinformation.h>
#include <ssh/sshconnection.h>
#include <utils/pathchooser.h>

#include <QDialogButtonBox>
#include <QFormLayout>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QSpinBox>

using namespace ProjectExplorer;
using namespace Utils;

namespace Analyzer {
namespace Internal {

class StartRemoteDialogPrivate
{
public:
    KitChooser *kitChooser;
    QLineEdit *executable;
    QLineEdit *arguments;
    QLineEdit *workingDirectory;
    QDialogButtonBox *buttonBox;
};

} // namespace Internal

StartRemoteDialog::StartRemoteDialog(QWidget *parent)
    : QDialog(parent)
    , d(new Internal::StartRemoteDialogPrivate)
{
    setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
    setWindowTitle(tr("Start Remote Analysis"));

    d->kitChooser = new KitChooser(this);
    d->executable = new QLineEdit(this);
    d->arguments = new QLineEdit(this);
    d->workingDirectory = new QLineEdit(this);

    d->buttonBox = new QDialogButtonBox(this);
    d->buttonBox->setOrientation(Qt::Horizontal);
    d->buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok);

    QFormLayout *formLayout = new QFormLayout;
    formLayout->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);
    formLayout->addRow(tr("Kit:"), d->kitChooser);
    formLayout->addRow(tr("Executable:"), d->executable);
    formLayout->addRow(tr("Arguments:"), d->arguments);
    formLayout->addRow(tr("Working directory:"), d->workingDirectory);

    QVBoxLayout *verticalLayout = new QVBoxLayout(this);
    verticalLayout->addLayout(formLayout);
    verticalLayout->addWidget(d->buttonBox);

    QSettings *settings = Core::ICore::settings();
    settings->beginGroup(QLatin1String("AnalyzerStartRemoteDialog"));
    QString kit = settings->value(QLatin1String("profile")).toString();
    d->kitChooser->setCurrentKitId(Core::Id(kit));
    d->executable->setText(settings->value(QLatin1String("executable")).toString());
    d->workingDirectory->setText(settings->value(QLatin1String("workingDirectory")).toString());
    d->arguments->setText(settings->value(QLatin1String("arguments")).toString());
    settings->endGroup();

    connect(d->kitChooser, SIGNAL(activated(int)), SLOT(validate()));
    connect(d->executable, SIGNAL(textChanged(QString)), SLOT(validate()));
    connect(d->workingDirectory, SIGNAL(textChanged(QString)), SLOT(validate()));
    connect(d->arguments, SIGNAL(textChanged(QString)), SLOT(validate()));
    connect(d->buttonBox, SIGNAL(accepted()), SLOT(accept()));
    connect(d->buttonBox, SIGNAL(rejected()), SLOT(reject()));

    validate();
}

StartRemoteDialog::~StartRemoteDialog()
{
    delete d;
}

void StartRemoteDialog::accept()
{
    QSettings *settings = Core::ICore::settings();
    settings->beginGroup(QLatin1String("AnalyzerStartRemoteDialog"));
    settings->setValue(QLatin1String("profile"), d->kitChooser->currentKitId().toString());
    settings->setValue(QLatin1String("executable"), d->executable->text());
    settings->setValue(QLatin1String("workingDirectory"), d->workingDirectory->text());
    settings->setValue(QLatin1String("arguments"), d->arguments->text());
    settings->endGroup();

    QDialog::accept();
}

void StartRemoteDialog::validate()
{
    bool valid = !d->executable->text().isEmpty();
    d->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(valid);
}

QSsh::SshConnectionParameters StartRemoteDialog::sshParams() const
{
    Kit *kit = d->kitChooser->currentKit();
    IDevice::ConstPtr device = DeviceKitInformation::device(kit);
    return device->sshParameters();
}

QString StartRemoteDialog::executable() const
{
    return d->executable->text();
}

QString StartRemoteDialog::arguments() const
{
    return d->arguments->text();
}

QString StartRemoteDialog::workingDirectory() const
{
    return d->workingDirectory->text();
}

} // namespace Analyzer
<commit_msg>Populate Kit Chooser in Analyzer dialog.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: http://www.qt-project.org/
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**************************************************************************/

#include "startremotedialog.h"

#include <coreplugin/icore.h>
#include <coreplugin/id.h>
#include <projectexplorer/kitchooser.h>
#include <projectexplorer/kitinformation.h>
#include <ssh/sshconnection.h>
#include <utils/pathchooser.h>

#include <QDialogButtonBox>
#include <QFormLayout>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QSpinBox>

using namespace ProjectExplorer;
using namespace Utils;

namespace Analyzer {
namespace Internal {

class StartRemoteDialogPrivate
{
public:
    KitChooser *kitChooser;
    QLineEdit *executable;
    QLineEdit *arguments;
    QLineEdit *workingDirectory;
    QDialogButtonBox *buttonBox;
};

} // namespace Internal

StartRemoteDialog::StartRemoteDialog(QWidget *parent)
    : QDialog(parent)
    , d(new Internal::StartRemoteDialogPrivate)
{
    setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
    setWindowTitle(tr("Start Remote Analysis"));

    d->kitChooser = new KitChooser(this);
    d->executable = new QLineEdit(this);
    d->arguments = new QLineEdit(this);
    d->workingDirectory = new QLineEdit(this);

    d->buttonBox = new QDialogButtonBox(this);
    d->buttonBox->setOrientation(Qt::Horizontal);
    d->buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok);

    QFormLayout *formLayout = new QFormLayout;
    formLayout->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);
    formLayout->addRow(tr("Kit:"), d->kitChooser);
    formLayout->addRow(tr("Executable:"), d->executable);
    formLayout->addRow(tr("Arguments:"), d->arguments);
    formLayout->addRow(tr("Working directory:"), d->workingDirectory);

    QVBoxLayout *verticalLayout = new QVBoxLayout(this);
    verticalLayout->addLayout(formLayout);
    verticalLayout->addWidget(d->buttonBox);

    QSettings *settings = Core::ICore::settings();
    settings->beginGroup(QLatin1String("AnalyzerStartRemoteDialog"));
    QString kit = settings->value(QLatin1String("profile")).toString();
    d->kitChooser->populate();
    d->kitChooser->setCurrentKitId(Core::Id(kit));
    d->executable->setText(settings->value(QLatin1String("executable")).toString());
    d->workingDirectory->setText(settings->value(QLatin1String("workingDirectory")).toString());
    d->arguments->setText(settings->value(QLatin1String("arguments")).toString());
    settings->endGroup();

    connect(d->kitChooser, SIGNAL(activated(int)), SLOT(validate()));
    connect(d->executable, SIGNAL(textChanged(QString)), SLOT(validate()));
    connect(d->workingDirectory, SIGNAL(textChanged(QString)), SLOT(validate()));
    connect(d->arguments, SIGNAL(textChanged(QString)), SLOT(validate()));
    connect(d->buttonBox, SIGNAL(accepted()), SLOT(accept()));
    connect(d->buttonBox, SIGNAL(rejected()), SLOT(reject()));

    validate();
}

StartRemoteDialog::~StartRemoteDialog()
{
    delete d;
}

void StartRemoteDialog::accept()
{
    QSettings *settings = Core::ICore::settings();
    settings->beginGroup(QLatin1String("AnalyzerStartRemoteDialog"));
    settings->setValue(QLatin1String("profile"), d->kitChooser->currentKitId().toString());
    settings->setValue(QLatin1String("executable"), d->executable->text());
    settings->setValue(QLatin1String("workingDirectory"), d->workingDirectory->text());
    settings->setValue(QLatin1String("arguments"), d->arguments->text());
    settings->endGroup();

    QDialog::accept();
}

void StartRemoteDialog::validate()
{
    bool valid = !d->executable->text().isEmpty();
    d->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(valid);
}

QSsh::SshConnectionParameters StartRemoteDialog::sshParams() const
{
    Kit *kit = d->kitChooser->currentKit();
    IDevice::ConstPtr device = DeviceKitInformation::device(kit);
    return device->sshParameters();
}

QString StartRemoteDialog::executable() const
{
    return d->executable->text();
}

QString StartRemoteDialog::arguments() const
{
    return d->arguments->text();
}

QString StartRemoteDialog::workingDirectory() const
{
    return d->workingDirectory->text();
}

} // namespace Analyzer
<|endoftext|>


<commit_before>#include "generator/regions/regions_builder.hpp"

#include "generator/regions/admin_suburbs_marker.hpp"
#include "generator/regions/country_specifier_builder.hpp"
#include "generator/regions/place_points_integrator.hpp"
#include "generator/regions/specs/rus.hpp"

#include "base/assert.hpp"
#include "base/thread_pool_computational.hpp"
#include "base/stl_helpers.hpp"
#include "base/thread_pool_computational.hpp"

#include <algorithm>
#include <chrono>
#include <fstream>
#include <functional>
#include <numeric>
#include <queue>
#include <thread>
#include <unordered_set>

namespace generator
{
namespace regions
{
RegionsBuilder::RegionsBuilder(Regions && regions, PlacePointsMap && placePointsMap,
                               size_t threadsCount)
  : m_threadsCount(threadsCount)
{
  ASSERT(m_threadsCount != 0, ());

  MoveLabelPlacePoints(placePointsMap, regions);

  m_regionsInAreaOrder = FormRegionsInAreaOrder(std::move(regions));
  m_countriesOuters = ExtractCountriesOuters(m_regionsInAreaOrder);
  m_placePointsMap = std::move(placePointsMap);
}

void RegionsBuilder::MoveLabelPlacePoints(PlacePointsMap & placePointsMap, Regions & regions)
{
  for (auto & region : regions)
  {
    if (auto labelOsmId = region.GetLabelOsmId())
    {
      auto label = placePointsMap.find(*labelOsmId);
      if (label != placePointsMap.end())
      {
        region.SetLabel(label->second);
        placePointsMap.erase(label);
      }
    }
  }
}

RegionsBuilder::Regions RegionsBuilder::FormRegionsInAreaOrder(Regions && regions)
{
  auto const cmp = [](Region const & l, Region const & r) { return l.GetArea() > r.GetArea(); };
  std::sort(std::begin(regions), std::end(regions), cmp);
  return std::move(regions);
}

RegionsBuilder::Regions RegionsBuilder::ExtractCountriesOuters(Regions & regions)
{
  Regions countriesOuters;

  auto const isCountry = [](Region const & region) {
    auto const placeType = region.GetPlaceType();
    if (placeType == PlaceType::Country)
      return true;

    auto const adminLevel = region.GetAdminLevel();
    return adminLevel == AdminLevel::Two && placeType == PlaceType::Unknown;
  };
  std::copy_if(std::begin(regions), std::end(regions), std::back_inserter(countriesOuters),
      isCountry);

  base::EraseIf(regions, isCountry);

  return countriesOuters;
}

RegionsBuilder::Regions const & RegionsBuilder::GetCountriesOuters() const
{
  return m_countriesOuters;
}

RegionsBuilder::StringsList RegionsBuilder::GetCountryNames() const
{
  StringsList result;
  std::unordered_set<std::string> set;
  for (auto const & c : GetCountriesOuters())
  {
    auto const & name = c.GetName();
    if (set.insert(name).second)
      result.emplace_back(std::move(name));
  }

  return result;
}

Node::Ptr RegionsBuilder::BuildCountryRegionTree(
    Region const & outer, CountrySpecifier const & countrySpecifier) const
{
  auto nodes = MakeCountryNodesInAreaOrder(outer, m_regionsInAreaOrder, countrySpecifier);

  for (auto i = std::crbegin(nodes), end = std::crend(nodes); i != end; ++i)
  {
    if (auto parent = ChooseParent(nodes, i, countrySpecifier))
    {
      (*i)->SetParent(parent);
      parent->AddChild(*i);
    }
  }

  return nodes.front();
}

std::vector<Node::Ptr> RegionsBuilder::MakeCountryNodesInAreaOrder(
    Region const & countryOuter, Regions const & regionsInAreaOrder,
    CountrySpecifier const & countrySpecifier) const
{
  std::vector<Node::Ptr> nodes{std::make_shared<Node>(LevelRegion{PlaceLevel::Country,
                                                                  countryOuter})};
  for (auto const & region : regionsInAreaOrder)
  {
    if (countryOuter.ContainsRect(region))
    {
      auto level = countrySpecifier.GetLevel(region);
      auto node = std::make_shared<Node>(LevelRegion{level, region});
      nodes.emplace_back(std::move(node));
    }
  }

  return nodes;
}

Node::Ptr RegionsBuilder::ChooseParent(
    std::vector<Node::Ptr> const & nodesInAreaOrder,
    std::vector<Node::Ptr>::const_reverse_iterator forItem,
    CountrySpecifier const & countrySpecifier) const
{
  auto const & node = *forItem;
  auto const & region = node->GetData();

  auto const from = FindAreaLowerBoundRely(nodesInAreaOrder, forItem);
  CHECK(from <= forItem, ());

  Node::Ptr parent;
  for (auto i = from, end = std::crend(nodesInAreaOrder); i != end; ++i)
  {
    auto const & candidate = *i;
    auto const & candidateRegion = candidate->GetData();

    if (parent)
    {
      auto const & parentRegion = parent->GetData();
      if (IsAreaLessRely(parentRegion, candidateRegion))
        break;
    }

    if (!candidateRegion.ContainsRect(region) && !candidateRegion.Contains(region.GetCenter()))
      continue;

    if (i == forItem)
      continue;

    auto const c = CompareAffiliation(candidateRegion, region, countrySpecifier);
    if (c == 1)
    {
      if (parent && 0 <= CompareAffiliation(candidateRegion, parent->GetData(), countrySpecifier))
        continue;

      parent = candidate;
    }
  }

  return parent;
}

std::vector<Node::Ptr>::const_reverse_iterator RegionsBuilder::FindAreaLowerBoundRely(
    std::vector<Node::Ptr> const & nodesInAreaOrder,
    std::vector<Node::Ptr>::const_reverse_iterator forItem) const
{
  auto const & region = (*forItem)->GetData();

  auto areaLessRely = [](Node::Ptr const & element, Region const & region) {
    auto const & elementRegion = element->GetData();
    return IsAreaLessRely(elementRegion, region);
  };

  return std::lower_bound(std::crbegin(nodesInAreaOrder), forItem, region, areaLessRely);
}

// static
void RegionsBuilder::InsertIntoSubtree(Node::Ptr & subtree, LevelRegion && region,
    CountrySpecifier const & countrySpecifier)
{
  auto newNode = std::make_shared<Node>(std::move(region));
  InsertIntoSubtree(subtree, std::move(newNode), countrySpecifier);
}

// static
void RegionsBuilder::InsertIntoSubtree(Node::Ptr & subtree, Node::Ptr && newNode,
    CountrySpecifier const & countrySpecifier)
{
  CHECK(0 < CompareAffiliation(subtree->GetData(), newNode->GetData(), countrySpecifier), ());

  auto & children = subtree->GetChildren();
  auto childIt = children.begin();
  while (childIt != children.end())
  {
    auto & child = *childIt;
    auto const c = CompareAffiliation(child->GetData(), newNode->GetData(), countrySpecifier);
    if (c > 0)
      return InsertIntoSubtree(child, std::move(newNode), countrySpecifier);

    if (c < 0)
    {
      child->SetParent(newNode);
      newNode->AddChild(child);
      childIt = children.erase(childIt);
      continue;
    }

    ASSERT(c == 0, ());
    ++childIt;
  }

  newNode->SetParent(subtree);
  subtree->AddChild(newNode);
}

// static
int RegionsBuilder::CompareAffiliation(LevelRegion const & l, LevelRegion const & r,
    CountrySpecifier const & countrySpecifier)
{
  if (IsAreaLessRely(r, l) && l.Contains(r))
    return 1;
  if (IsAreaLessRely(l, r) && r.Contains(l))
    return -1;

  if (l.CalculateOverlapPercentage(r) < 50.0)
    return 0;

  auto const lArea = l.GetArea();
  auto const rArea = r.GetArea();
  if (0.5 * lArea >= rArea)
  {
    LOG(LDEBUG, ("Region", l.GetId(), GetRegionNotation(l), "contains partly",
                 r.GetId(), GetRegionNotation(r)));
    return 1;
  }
  if (0.5 * rArea >= lArea)
  {
    LOG(LDEBUG, ("Region", r.GetId(), GetRegionNotation(r), "contains partly",
                 l.GetId(), GetRegionNotation(l)));
    return -1;
  }

  return countrySpecifier.RelateByWeight(l, r);
}

// static
bool RegionsBuilder::IsAreaLessRely(Region const & l, Region const & r)
{
  constexpr auto lAreaRation = 1. + kAreaRelativeErrorPercent / 100.;
  return lAreaRation * l.GetArea() < r.GetArea();
}

void RegionsBuilder::ForEachCountry(CountryFn fn)
{
  std::vector<std::future<Node::PtrList>> buildingTasks;

  {
    base::thread_pool::computational::ThreadPool threadPool(m_threadsCount);

    for (auto const & countryName : GetCountryNames())
    {
      auto result = threadPool.Submit([this, countryName]() { return BuildCountry(countryName); });
      buildingTasks.emplace_back(std::move(result));
    }
  }

  for (auto && task : buildingTasks)
  {
    auto countryTrees = task.get();
    CHECK(!countryTrees.empty(), ());
    auto && countryName = countryTrees.front()->GetData().GetName();
    fn(countryName, countryTrees);
  }
}

Node::PtrList RegionsBuilder::BuildCountry(std::string const & countryName) const
{
  Regions outers;
  auto const & countries = GetCountriesOuters();
  auto const pred = [&](Region const & country) { return countryName == country.GetName(); };
  std::copy_if(std::begin(countries), std::end(countries), std::back_inserter(outers), pred);

  auto countrySpecifier = GetCountrySpecifier(countryName);
  auto countryTrees = BuildCountryRegionTrees(outers, *countrySpecifier);

  PlacePointsIntegrator pointsIntegrator{m_placePointsMap, *countrySpecifier};
  LOG(LINFO, ("Start integrate place points for", countryName));
  pointsIntegrator.ApplyTo(countryTrees);
  LOG(LINFO, ("Finish integrate place points for", countryName));

  AdminSuburbsMarker suburbsMarker;
  LOG(LINFO, ("Start mark admin suburbs for", countryName));
  for (auto & tree : countryTrees)
    suburbsMarker.MarkSuburbs(tree);
  LOG(LINFO, ("Finish mark admin suburbs for", countryName));

  countrySpecifier->AdjustRegionsLevel(countryTrees);

  return countryTrees;
}

Node::PtrList RegionsBuilder::BuildCountryRegionTrees(
    Regions const & outers, CountrySpecifier const & countrySpecifier) const
{
  Node::PtrList trees;
  for (auto const & outer : outers)
  {
    auto tree = BuildCountryRegionTree(outer, countrySpecifier);
    trees.push_back(std::move(tree));
  }

  return trees;
}
}  // namespace regions
}  // namespace generator
<commit_msg>[generator] style<commit_after>#include "generator/regions/regions_builder.hpp"

#include "generator/regions/admin_suburbs_marker.hpp"
#include "generator/regions/country_specifier_builder.hpp"
#include "generator/regions/place_points_integrator.hpp"
#include "generator/regions/specs/rus.hpp"

#include "base/assert.hpp"
#include "base/stl_helpers.hpp"
#include "base/thread_pool_computational.hpp"

#include <algorithm>
#include <chrono>
#include <fstream>
#include <functional>
#include <numeric>
#include <queue>
#include <thread>
#include <unordered_set>

namespace generator
{
namespace regions
{
RegionsBuilder::RegionsBuilder(Regions && regions, PlacePointsMap && placePointsMap,
                               size_t threadsCount)
  : m_threadsCount(threadsCount)
{
  ASSERT(m_threadsCount != 0, ());

  MoveLabelPlacePoints(placePointsMap, regions);

  m_regionsInAreaOrder = FormRegionsInAreaOrder(std::move(regions));
  m_countriesOuters = ExtractCountriesOuters(m_regionsInAreaOrder);
  m_placePointsMap = std::move(placePointsMap);
}

void RegionsBuilder::MoveLabelPlacePoints(PlacePointsMap & placePointsMap, Regions & regions)
{
  for (auto & region : regions)
  {
    if (auto labelOsmId = region.GetLabelOsmId())
    {
      auto label = placePointsMap.find(*labelOsmId);
      if (label != placePointsMap.end())
      {
        region.SetLabel(label->second);
        placePointsMap.erase(label);
      }
    }
  }
}

RegionsBuilder::Regions RegionsBuilder::FormRegionsInAreaOrder(Regions && regions)
{
  auto const cmp = [](Region const & l, Region const & r) { return l.GetArea() > r.GetArea(); };
  std::sort(std::begin(regions), std::end(regions), cmp);
  return std::move(regions);
}

RegionsBuilder::Regions RegionsBuilder::ExtractCountriesOuters(Regions & regions)
{
  Regions countriesOuters;

  auto const isCountry = [](Region const & region) {
    auto const placeType = region.GetPlaceType();
    if (placeType == PlaceType::Country)
      return true;

    auto const adminLevel = region.GetAdminLevel();
    return adminLevel == AdminLevel::Two && placeType == PlaceType::Unknown;
  };
  std::copy_if(std::begin(regions), std::end(regions), std::back_inserter(countriesOuters),
               isCountry);

  base::EraseIf(regions, isCountry);

  return countriesOuters;
}

RegionsBuilder::Regions const & RegionsBuilder::GetCountriesOuters() const
{
  return m_countriesOuters;
}

RegionsBuilder::StringsList RegionsBuilder::GetCountryNames() const
{
  StringsList result;
  std::unordered_set<std::string> set;
  for (auto const & c : GetCountriesOuters())
  {
    auto const & name = c.GetName();
    if (set.insert(name).second)
      result.emplace_back(std::move(name));
  }

  return result;
}

Node::Ptr RegionsBuilder::BuildCountryRegionTree(Region const & outer,
                                                 CountrySpecifier const & countrySpecifier) const
{
  auto nodes = MakeCountryNodesInAreaOrder(outer, m_regionsInAreaOrder, countrySpecifier);

  for (auto i = std::crbegin(nodes), end = std::crend(nodes); i != end; ++i)
  {
    if (auto parent = ChooseParent(nodes, i, countrySpecifier))
    {
      (*i)->SetParent(parent);
      parent->AddChild(*i);
    }
  }

  return nodes.front();
}

std::vector<Node::Ptr> RegionsBuilder::MakeCountryNodesInAreaOrder(
    Region const & countryOuter, Regions const & regionsInAreaOrder,
    CountrySpecifier const & countrySpecifier) const
{
  std::vector<Node::Ptr> nodes{
      std::make_shared<Node>(LevelRegion{PlaceLevel::Country, countryOuter})};
  for (auto const & region : regionsInAreaOrder)
  {
    if (countryOuter.ContainsRect(region))
    {
      auto level = countrySpecifier.GetLevel(region);
      auto node = std::make_shared<Node>(LevelRegion{level, region});
      nodes.emplace_back(std::move(node));
    }
  }

  return nodes;
}

Node::Ptr RegionsBuilder::ChooseParent(std::vector<Node::Ptr> const & nodesInAreaOrder,
                                       std::vector<Node::Ptr>::const_reverse_iterator forItem,
                                       CountrySpecifier const & countrySpecifier) const
{
  auto const & node = *forItem;
  auto const & region = node->GetData();

  auto const from = FindAreaLowerBoundRely(nodesInAreaOrder, forItem);
  CHECK(from <= forItem, ());

  Node::Ptr parent;
  for (auto i = from, end = std::crend(nodesInAreaOrder); i != end; ++i)
  {
    auto const & candidate = *i;
    auto const & candidateRegion = candidate->GetData();

    if (parent)
    {
      auto const & parentRegion = parent->GetData();
      if (IsAreaLessRely(parentRegion, candidateRegion))
        break;
    }

    if (!candidateRegion.ContainsRect(region) && !candidateRegion.Contains(region.GetCenter()))
      continue;

    if (i == forItem)
      continue;

    auto const c = CompareAffiliation(candidateRegion, region, countrySpecifier);
    if (c == 1)
    {
      if (parent && 0 <= CompareAffiliation(candidateRegion, parent->GetData(), countrySpecifier))
        continue;

      parent = candidate;
    }
  }

  return parent;
}

std::vector<Node::Ptr>::const_reverse_iterator RegionsBuilder::FindAreaLowerBoundRely(
    std::vector<Node::Ptr> const & nodesInAreaOrder,
    std::vector<Node::Ptr>::const_reverse_iterator forItem) const
{
  auto const & region = (*forItem)->GetData();

  auto areaLessRely = [](Node::Ptr const & element, Region const & region) {
    auto const & elementRegion = element->GetData();
    return IsAreaLessRely(elementRegion, region);
  };

  return std::lower_bound(std::crbegin(nodesInAreaOrder), forItem, region, areaLessRely);
}

// static
void RegionsBuilder::InsertIntoSubtree(Node::Ptr & subtree, LevelRegion && region,
                                       CountrySpecifier const & countrySpecifier)
{
  auto newNode = std::make_shared<Node>(std::move(region));
  InsertIntoSubtree(subtree, std::move(newNode), countrySpecifier);
}

// static
void RegionsBuilder::InsertIntoSubtree(Node::Ptr & subtree, Node::Ptr && newNode,
                                       CountrySpecifier const & countrySpecifier)
{
  CHECK(0 < CompareAffiliation(subtree->GetData(), newNode->GetData(), countrySpecifier), ());

  auto & children = subtree->GetChildren();
  auto childIt = children.begin();
  while (childIt != children.end())
  {
    auto & child = *childIt;
    auto const c = CompareAffiliation(child->GetData(), newNode->GetData(), countrySpecifier);
    if (c > 0)
      return InsertIntoSubtree(child, std::move(newNode), countrySpecifier);

    if (c < 0)
    {
      child->SetParent(newNode);
      newNode->AddChild(child);
      childIt = children.erase(childIt);
      continue;
    }

    ASSERT(c == 0, ());
    ++childIt;
  }

  newNode->SetParent(subtree);
  subtree->AddChild(newNode);
}

// static
int RegionsBuilder::CompareAffiliation(LevelRegion const & l, LevelRegion const & r,
                                       CountrySpecifier const & countrySpecifier)
{
  if (IsAreaLessRely(r, l) && l.Contains(r))
    return 1;
  if (IsAreaLessRely(l, r) && r.Contains(l))
    return -1;

  if (l.CalculateOverlapPercentage(r) < 50.0)
    return 0;

  auto const lArea = l.GetArea();
  auto const rArea = r.GetArea();
  if (0.5 * lArea >= rArea)
  {
    LOG(LDEBUG, ("Region", l.GetId(), GetRegionNotation(l), "contains partly", r.GetId(),
                 GetRegionNotation(r)));
    return 1;
  }
  if (0.5 * rArea >= lArea)
  {
    LOG(LDEBUG, ("Region", r.GetId(), GetRegionNotation(r), "contains partly", l.GetId(),
                 GetRegionNotation(l)));
    return -1;
  }

  return countrySpecifier.RelateByWeight(l, r);
}

// static
bool RegionsBuilder::IsAreaLessRely(Region const & l, Region const & r)
{
  constexpr auto lAreaRation = 1. + kAreaRelativeErrorPercent / 100.;
  return lAreaRation * l.GetArea() < r.GetArea();
}

void RegionsBuilder::ForEachCountry(CountryFn fn)
{
  std::vector<std::future<Node::PtrList>> buildingTasks;

  {
    base::thread_pool::computational::ThreadPool threadPool(m_threadsCount);

    for (auto const & countryName : GetCountryNames())
    {
      auto result = threadPool.Submit([this, countryName]() { return BuildCountry(countryName); });
      buildingTasks.emplace_back(std::move(result));
    }
  }

  for (auto && task : buildingTasks)
  {
    auto countryTrees = task.get();
    CHECK(!countryTrees.empty(), ());
    auto && countryName = countryTrees.front()->GetData().GetName();
    fn(countryName, countryTrees);
  }
}

Node::PtrList RegionsBuilder::BuildCountry(std::string const & countryName) const
{
  Regions outers;
  auto const & countries = GetCountriesOuters();
  auto const pred = [&](Region const & country) { return countryName == country.GetName(); };
  std::copy_if(std::begin(countries), std::end(countries), std::back_inserter(outers), pred);

  auto countrySpecifier = GetCountrySpecifier(countryName);
  auto countryTrees = BuildCountryRegionTrees(outers, *countrySpecifier);

  PlacePointsIntegrator pointsIntegrator{m_placePointsMap, *countrySpecifier};
  LOG(LINFO, ("Start integrate place points for", countryName));
  pointsIntegrator.ApplyTo(countryTrees);
  LOG(LINFO, ("Finish integrate place points for", countryName));

  AdminSuburbsMarker suburbsMarker;
  LOG(LINFO, ("Start mark admin suburbs for", countryName));
  for (auto & tree : countryTrees)
    suburbsMarker.MarkSuburbs(tree);
  LOG(LINFO, ("Finish mark admin suburbs for", countryName));

  countrySpecifier->AdjustRegionsLevel(countryTrees);

  return countryTrees;
}

Node::PtrList RegionsBuilder::BuildCountryRegionTrees(
    Regions const & outers, CountrySpecifier const & countrySpecifier) const
{
  Node::PtrList trees;
  for (auto const & outer : outers)
  {
    auto tree = BuildCountryRegionTree(outer, countrySpecifier);
    trees.push_back(std::move(tree));
  }

  return trees;
}
}  // namespace regions
}  // namespace generator
<|endoftext|>


<commit_before>/**
 *    PermutationWT.cpp
 *    Copyright (C) 2011  Francisco Claude F.
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    This program 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 General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include<PermutationWT.h>

namespace cds_static {

PermutationWT::PermutationWT(uint *perm, size_t len) {
  uint b = bits(len-1);
  uint * seq = new uint[len];
  uint * marker = new uint[uint_len(len,1)];
  for(size_t i=0;i<uint_len(len,1);i++)
    marker[i] = 0;

  runs = 0;
  uint last = get_field(perm,b,0);
  seq[get_field(perm,b,0)] = 0;
  bitset(marker,0);

  for(size_t i=1;i<len;i++) {
    if(last > get_field(perm,b,i)) {
      runs++;
      bitset(marker,i);
    }
    seq[get_field(perm,b,i)] = runs;
    last = get_field(perm,b,i);
  }

  wt = new WaveletTree(seq, len, new wt_coder_huff(seq, len, new MapperNone()), new BitSequenceBuilderRG(20), new MapperNone());
  marks = new BitSequenceRG(marker, len, 20);
  delete [] seq;
}

PermutationWT::~PermutationWT(){
  delete wt;
}

uint PermutationWT::pi(uint k) const {
  uint v = (uint)marks->rank1(k);
  return (uint)wt->select(v-1, k - marks->select1(v) + 1);
}

uint PermutationWT::revpi(uint k) const {
  size_t val = 0;
  uint s = wt->access(k, val);
  return marks->select1(s+1) + val - 1;
}

size_t PermutationWT::getSize() const {
  return marks->getSize()+wt->getSize()+sizeof(PermutationWT);
}

  void PermutationWT::save(ofstream & out) const {
    saveValue(out,WTPERM);
    saveValue(out, length);
    wt->save(out);
    marks->save(out);
  }

  PermutationWT * PermutationWT::load(ifstream &in) {
    uint rd = loadValue<uint>(in);
    if(rd!=WTPERM) return NULL;
    PermutationWT * ret = new PermutationWT();
    ret->length = loadValue<size_t>(in);
    ret->wt = Sequence::load(in);
    ret->marks = BitSequence::load(in);
    return ret;
  }
};
<commit_msg>pointers break everything<commit_after>/**
 *    PermutationWT.cpp
 *    Copyright (C) 2011  Francisco Claude F.
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    This program 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 General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include<PermutationWT.h>

namespace cds_static {

PermutationWT::PermutationWT(uint *perm, size_t len) {
  uint b = bits(len-1);
  uint * seq = new uint[len];
  uint * marker = new uint[uint_len(len,1)];
  for(size_t i=0;i<uint_len(len,1);i++)
    marker[i] = 0;

  runs = 0;
  uint last = get_field(perm,b,0);
  seq[get_field(perm,b,0)] = 0;
  bitset(marker,0);

  for(size_t i=1;i<len;i++) {
    if(last > get_field(perm,b,i)) {
      runs++;
      bitset(marker,i);
    }
    seq[get_field(perm,b,i)] = runs;
    last = get_field(perm,b,i);
  }

  wt = new WaveletTreeNoptrs(seq, len, new BitSequenceBuilderRRR(40), new MapperNone());
  marks = new BitSequenceRG(marker, len, 20);
  delete [] seq;
}

PermutationWT::~PermutationWT(){
  delete wt;
}

uint PermutationWT::pi(uint k) const {
  uint v = (uint)marks->rank1(k);
  return (uint)wt->select(v-1, k - marks->select1(v) + 1);
}

uint PermutationWT::revpi(uint k) const {
  size_t val = 0;
  uint s = wt->access(k, val);
  return marks->select1(s+1) + val - 1;
}

size_t PermutationWT::getSize() const {
  return marks->getSize()+wt->getSize()+sizeof(PermutationWT);
}

  void PermutationWT::save(ofstream & out) const {
    saveValue(out,WTPERM);
    saveValue(out, length);
    wt->save(out);
    marks->save(out);
  }

  PermutationWT * PermutationWT::load(ifstream &in) {
    uint rd = loadValue<uint>(in);
    if(rd!=WTPERM) return NULL;
    PermutationWT * ret = new PermutationWT();
    ret->length = loadValue<size_t>(in);
    ret->wt = Sequence::load(in);
    ret->marks = BitSequence::load(in);
    return ret;
  }
};
<|endoftext|>


<commit_before>template <int num_rotors>
void MultirotorVehicleSystem<num_rotors>::init() {
}

template <int num_rotors>
void MultirotorVehicleSystem<num_rotors>::update() {
  // Poll the accelerometer and gyroscope
  accelerometer_reading_t accel_reading = getAccelerometer()->read();
  gyroscope_reading_t gyro_reading = getGyroscope()->read();

  // Update the attitude estimate
  attitude_estimate_t estimate = getAttitudeEstimator()->update(accel_reading, gyro_reading);

  // Poll for controller input
  controller_input_t input = getInputSource()->read();

  // Run the controllers
  angular_position_setpoint_t angular_setpoint = {
    .pitch_pos_sp = input.pitch_sp,
    .roll_pos_sp = input.roll_sp,
    .yaw_pos_sp = input.yaw_sp,
    .throttle_sp = input.throttle_sp
  };

  actuator_setpoint_t actuator_setpoint = runController(estimate, angular_setpoint);

  // TODO: Update motor outputs
  getMotorMapper()->run(actuator_setpoint);
}
<commit_msg>Remove finished TODO.<commit_after>template <int num_rotors>
void MultirotorVehicleSystem<num_rotors>::init() {
}

template <int num_rotors>
void MultirotorVehicleSystem<num_rotors>::update() {
  // Poll the accelerometer and gyroscope
  accelerometer_reading_t accel_reading = getAccelerometer()->read();
  gyroscope_reading_t gyro_reading = getGyroscope()->read();

  // Update the attitude estimate
  attitude_estimate_t estimate = getAttitudeEstimator()->update(accel_reading, gyro_reading);

  // Poll for controller input
  controller_input_t input = getInputSource()->read();

  // Run the controllers
  angular_position_setpoint_t angular_setpoint = {
    .pitch_pos_sp = input.pitch_sp,
    .roll_pos_sp = input.roll_sp,
    .yaw_pos_sp = input.yaw_sp,
    .throttle_sp = input.throttle_sp
  };

  actuator_setpoint_t actuator_setpoint = runController(estimate, angular_setpoint);

  // Update motor outputs
  getMotorMapper()->run(actuator_setpoint);
}
<|endoftext|>


<commit_before>/*************** <auto-copyright.pl BEGIN do not edit this line> **************
 *
 * VR Juggler is (C) Copyright 1998-2003 by Iowa State University
 *
 * Original Authors:
 *   Allen Bierbaum, Christopher Just,
 *   Patrick Hartling, Kevin Meinert,
 *   Carolina Cruz-Neira, Albert Baker
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 * -----------------------------------------------------------------
 * File:          $RCSfile$
 * Date modified: $Date$
 * Version:       $Revision$
 * -----------------------------------------------------------------
 *
 *************** <auto-copyright.pl END do not edit this line> ***************/

#include <gadget/gadgetConfig.h>
#include <typeinfo>
#include <vpr/vpr.h>
#include <jccl/Config/ConfigElement.h>
#include <gadget/Type/DeviceFactory.h>
#include <gadget/Type/DeviceConstructor.h>

// Sims
#include <gadget/Devices/Sim/SimAnalog.h>
#include <gadget/Devices/Sim/SimDigital.h>
#include <gadget/Devices/Sim/SimPosition.h>
#include <gadget/Devices/Sim/SimGloveGesture.h>
//#include <gadget/Devices/Sim/SimKeyboardDigital.h>
#include <gadget/Devices/Sim/SimRelativePosition.h>
#include <gadget/Devices/Sim/SimSetablePosition.h>
#include <gadget/Devices/Sim/SimDigitalGlove.h>

#if defined(VPR_OS_Win32)
#  include <gadget/Devices/EventWindow/EventWindowWin32.h>
#elif defined(VPR_OS_Darwin) && ! defined(GADGET_USE_X11)
#  include <gadget/Devices/EventWindow/EventWindowOSX.h>
#else
#  include <gadget/Devices/EventWindow/EventWindowXWin.h>
#  include <gadget/Devices/EventWindow/EventWindowDepCheckerXWin.h>
#endif

/* Physical devices */
#ifdef STATIC_DRIVERS

/* PThread Dependant Driver */
#ifdef GADGET_HAVE_DTK
#   include <gadget/Devices/Open/DTK/DTK.h>
#endif

#endif /* STATIC_DRIVERS */

#include <gadget/Util/Debug.h>

namespace gadget
{

// Initialize the singleton ptr
//vjDeviceFactory* DeviceFactory::mInstance = NULL;
//vjSingletonImp( DeviceFactory ); //kevin
vprSingletonImpWithInitFunc(DeviceFactory, loadKnownDevices);

/**
 * Registers all the devices that I know about.
 */
void DeviceFactory::loadKnownDevices()
{
   gadget::InputManager* input_mgr = gadget::InputManager::instance();

#ifdef STATIC_DRIVERS

#ifdef GADGET_HAVE_DTK
   DeviceConstructor<DTK>* dtk_wrapper = new DeviceConstructor<DTK>;
   if( (NULL == dtk_wrapper))
   {
      vprDEBUG(vprDBG_ALL,vprDBG_CRITICAL_LVL) << clrOutBOLD(clrRED,"ERROR:") << "Failed to load a known device\n" << vprDEBUG_FLUSH;
   }
#endif

#endif /* STATIC_DRIVERS */

   DeviceConstructor<SimAnalog>* sim_analog = new DeviceConstructor<SimAnalog>(input_mgr);
   DeviceConstructor<SimDigital>* sim_digital = new DeviceConstructor<SimDigital>(input_mgr);
   DeviceConstructor<SimPosition>* sim_position = new DeviceConstructor<SimPosition>(input_mgr);
   //DeviceConstructor<SimKeyboardDigital>* sim_keyboard_digital = new DeviceConstructor<SimKeyboardDigital>(input_mgr);
   DeviceConstructor<SimSetablePosition>* sim_setable = new DeviceConstructor<SimSetablePosition>(input_mgr);
   DeviceConstructor<SimRelativePosition>* sim_relative = new DeviceConstructor<SimRelativePosition>(input_mgr);

   DeviceConstructor<SimGloveGesture>* sim_glove = new DeviceConstructor<SimGloveGesture>(input_mgr);
   DeviceConstructor<SimDigitalGlove>* simpinch_glove = new DeviceConstructor<SimDigitalGlove>(input_mgr);

   if( (NULL == sim_analog)   ||
       (NULL == sim_digital)  ||
       (NULL == sim_position) ||
       (NULL == sim_glove)    ||
       (NULL == simpinch_glove) ||
       (NULL == sim_setable) ||
       (NULL == sim_relative) )
   {
      vprDEBUG(vprDBG_ALL,vprDBG_CRITICAL_LVL) << clrOutBOLD(clrRED,"ERROR:") << "Failed to load a known device\n" << vprDEBUG_FLUSH;
   }

#if defined(VPR_OS_Win32)
   DeviceConstructor<EventWindowWin32>* key_win32 =
      new DeviceConstructor<EventWindowWin32>(input_mgr);
   if( (NULL == key_win32))
   {
      vprDEBUG(vprDBG_ALL,vprDBG_CRITICAL_LVL)
         << clrOutBOLD(clrRED,"ERROR:") << "Failed to load a known device\n"
         << vprDEBUG_FLUSH;
   }
#elif defined(VPR_OS_Darwin) && ! defined(GADGET_USE_X11)
   DeviceConstructor<EventWindowOSX>* osx_keyboard =
      new DeviceConstructor<EventWindowOSX>(input_mgr);
   if( (NULL == osx_keyboard) )
   {
      vprDEBUG(vprDBG_ALL,vprDBG_CRITICAL_LVL)
         << clrOutBOLD(clrRED,"ERROR:") << "Failed to load a known device\n"
         << vprDEBUG_FLUSH;
   }
#else
   DeviceConstructor<EventWindowXWin>* xwin_key =
      new DeviceConstructor<EventWindowXWin>(input_mgr);
   jccl::DependencyManager::instance()->registerChecker(new EventWindowDepCheckerXWin());
   if( (NULL == xwin_key) )
   {
      vprDEBUG(vprDBG_ALL,vprDBG_CRITICAL_LVL)
         << clrOutBOLD(clrRED,"ERROR:") << "Failed to load a known device\n"
         << vprDEBUG_FLUSH;
   }
#endif

}

void DeviceFactory::registerDevice(DeviceConstructorBase* constructor)
{
   vprASSERT(constructor != NULL);
   mConstructors.push_back(constructor);     // Add the constructor to the list
   vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_STATE_LVL)
      << "gadget::DeviceFactory: Registered: "
      << std::setiosflags(std::ios::right) << std::setw(25)
      << std::setfill(' ') << constructor->getElementType()
      << std::setiosflags(std::ios::right)
      //<< "   :" << (void*)constructor
      << "  type: " << typeid(*constructor).name() << std::endl
      << vprDEBUG_FLUSH;
}

// Simply query all device constructors registered looking
// for one that knows how to load the device
bool DeviceFactory::recognizeDevice(jccl::ConfigElementPtr element)
{
   return ! (findConstructor(element) == -1);
}

/**
 * Loads the specified device.
 */
Input* DeviceFactory::loadDevice(jccl::ConfigElementPtr element)
{
   vprASSERT(recognizeDevice(element));

   int index(findConstructor(element));

   Input* new_dev;
   DeviceConstructorBase* constructor = mConstructors[index];

   vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_STATE_LVL)
      << "gadget::DeviceFactory::loadDevice: Loading device: "
      << element->getID() << "  with: " << typeid(*constructor).name()
      << std::endl << vprDEBUG_FLUSH;

   new_dev = constructor->createDevice(element);
   return new_dev;
}

int DeviceFactory::findConstructor(jccl::ConfigElementPtr element)
{
   const std::string element_type(element->getID());

   for ( unsigned int i = 0; i < mConstructors.size(); ++i )
   {
      // Get next constructor
      DeviceConstructorBase* construct = mConstructors[i];
      vprASSERT(construct != NULL);

      if(construct->getElementType() == element_type)
      {
         return i;
      }
   }

   return -1;
}

void DeviceFactory::debugDump()
{
   vprDEBUG_OutputGuard(gadgetDBG_INPUT_MGR, vprDBG_VERB_LVL,
      std::string("gadget::DeviceFactory::debugDump\n"),
      std::string("------ END DUMP ------\n"));
   vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_VERB_LVL) << "num constructors:"
                                   << mConstructors.size() << "\n"
                                   << vprDEBUG_FLUSH;

   for(unsigned int cNum=0;cNum<mConstructors.size();cNum++)
   {
      DeviceConstructorBase* dev_constr = mConstructors[cNum];
      vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_VERB_LVL)
         << cNum << ": Constructor:" << (void*)dev_constr
         << "   type:" << typeid(*dev_constr).name() << "\n" << vprDEBUG_FLUSH;
      vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_VERB_LVL)
         << "   recog:" << dev_constr->getElementType() << "\n"
         << vprDEBUG_FLUSH;
   }
}

} // End of gadget namespace
<commit_msg>Added a missing #include.<commit_after>/*************** <auto-copyright.pl BEGIN do not edit this line> **************
 *
 * VR Juggler is (C) Copyright 1998-2003 by Iowa State University
 *
 * Original Authors:
 *   Allen Bierbaum, Christopher Just,
 *   Patrick Hartling, Kevin Meinert,
 *   Carolina Cruz-Neira, Albert Baker
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 * -----------------------------------------------------------------
 * File:          $RCSfile$
 * Date modified: $Date$
 * Version:       $Revision$
 * -----------------------------------------------------------------
 *
 *************** <auto-copyright.pl END do not edit this line> ***************/

#include <gadget/gadgetConfig.h>
#include <typeinfo>
#include <vpr/vpr.h>
#include <jccl/Config/ConfigElement.h>
#include <gadget/Type/DeviceFactory.h>
#include <gadget/Type/DeviceConstructor.h>

// Sims
#include <gadget/Devices/Sim/SimAnalog.h>
#include <gadget/Devices/Sim/SimDigital.h>
#include <gadget/Devices/Sim/SimPosition.h>
#include <gadget/Devices/Sim/SimGloveGesture.h>
//#include <gadget/Devices/Sim/SimKeyboardDigital.h>
#include <gadget/Devices/Sim/SimRelativePosition.h>
#include <gadget/Devices/Sim/SimSetablePosition.h>
#include <gadget/Devices/Sim/SimDigitalGlove.h>

#if defined(VPR_OS_Win32)
#  include <gadget/Devices/EventWindow/EventWindowWin32.h>
#elif defined(VPR_OS_Darwin) && ! defined(GADGET_USE_X11)
#  include <gadget/Devices/EventWindow/EventWindowOSX.h>
#else
#  include <jccl/RTRC/DependencyManager.h>
#  include <gadget/Devices/EventWindow/EventWindowXWin.h>
#  include <gadget/Devices/EventWindow/EventWindowDepCheckerXWin.h>
#endif

/* Physical devices */
#ifdef STATIC_DRIVERS

/* PThread Dependant Driver */
#ifdef GADGET_HAVE_DTK
#   include <gadget/Devices/Open/DTK/DTK.h>
#endif

#endif /* STATIC_DRIVERS */

#include <gadget/Util/Debug.h>

namespace gadget
{

// Initialize the singleton ptr
//vjDeviceFactory* DeviceFactory::mInstance = NULL;
//vjSingletonImp( DeviceFactory ); //kevin
vprSingletonImpWithInitFunc(DeviceFactory, loadKnownDevices);

/**
 * Registers all the devices that I know about.
 */
void DeviceFactory::loadKnownDevices()
{
   gadget::InputManager* input_mgr = gadget::InputManager::instance();

#ifdef STATIC_DRIVERS

#ifdef GADGET_HAVE_DTK
   DeviceConstructor<DTK>* dtk_wrapper = new DeviceConstructor<DTK>;
   if( (NULL == dtk_wrapper))
   {
      vprDEBUG(vprDBG_ALL,vprDBG_CRITICAL_LVL) << clrOutBOLD(clrRED,"ERROR:") << "Failed to load a known device\n" << vprDEBUG_FLUSH;
   }
#endif

#endif /* STATIC_DRIVERS */

   DeviceConstructor<SimAnalog>* sim_analog = new DeviceConstructor<SimAnalog>(input_mgr);
   DeviceConstructor<SimDigital>* sim_digital = new DeviceConstructor<SimDigital>(input_mgr);
   DeviceConstructor<SimPosition>* sim_position = new DeviceConstructor<SimPosition>(input_mgr);
   //DeviceConstructor<SimKeyboardDigital>* sim_keyboard_digital = new DeviceConstructor<SimKeyboardDigital>(input_mgr);
   DeviceConstructor<SimSetablePosition>* sim_setable = new DeviceConstructor<SimSetablePosition>(input_mgr);
   DeviceConstructor<SimRelativePosition>* sim_relative = new DeviceConstructor<SimRelativePosition>(input_mgr);

   DeviceConstructor<SimGloveGesture>* sim_glove = new DeviceConstructor<SimGloveGesture>(input_mgr);
   DeviceConstructor<SimDigitalGlove>* simpinch_glove = new DeviceConstructor<SimDigitalGlove>(input_mgr);

   if( (NULL == sim_analog)   ||
       (NULL == sim_digital)  ||
       (NULL == sim_position) ||
       (NULL == sim_glove)    ||
       (NULL == simpinch_glove) ||
       (NULL == sim_setable) ||
       (NULL == sim_relative) )
   {
      vprDEBUG(vprDBG_ALL,vprDBG_CRITICAL_LVL) << clrOutBOLD(clrRED,"ERROR:") << "Failed to load a known device\n" << vprDEBUG_FLUSH;
   }

#if defined(VPR_OS_Win32)
   DeviceConstructor<EventWindowWin32>* key_win32 =
      new DeviceConstructor<EventWindowWin32>(input_mgr);
   if( (NULL == key_win32))
   {
      vprDEBUG(vprDBG_ALL,vprDBG_CRITICAL_LVL)
         << clrOutBOLD(clrRED,"ERROR:") << "Failed to load a known device\n"
         << vprDEBUG_FLUSH;
   }
#elif defined(VPR_OS_Darwin) && ! defined(GADGET_USE_X11)
   DeviceConstructor<EventWindowOSX>* osx_keyboard =
      new DeviceConstructor<EventWindowOSX>(input_mgr);
   if( (NULL == osx_keyboard) )
   {
      vprDEBUG(vprDBG_ALL,vprDBG_CRITICAL_LVL)
         << clrOutBOLD(clrRED,"ERROR:") << "Failed to load a known device\n"
         << vprDEBUG_FLUSH;
   }
#else
   DeviceConstructor<EventWindowXWin>* xwin_key =
      new DeviceConstructor<EventWindowXWin>(input_mgr);
   jccl::DependencyManager::instance()->registerChecker(new EventWindowDepCheckerXWin());
   if( (NULL == xwin_key) )
   {
      vprDEBUG(vprDBG_ALL,vprDBG_CRITICAL_LVL)
         << clrOutBOLD(clrRED,"ERROR:") << "Failed to load a known device\n"
         << vprDEBUG_FLUSH;
   }
#endif

}

void DeviceFactory::registerDevice(DeviceConstructorBase* constructor)
{
   vprASSERT(constructor != NULL);
   mConstructors.push_back(constructor);     // Add the constructor to the list
   vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_STATE_LVL)
      << "gadget::DeviceFactory: Registered: "
      << std::setiosflags(std::ios::right) << std::setw(25)
      << std::setfill(' ') << constructor->getElementType()
      << std::setiosflags(std::ios::right)
      //<< "   :" << (void*)constructor
      << "  type: " << typeid(*constructor).name() << std::endl
      << vprDEBUG_FLUSH;
}

// Simply query all device constructors registered looking
// for one that knows how to load the device
bool DeviceFactory::recognizeDevice(jccl::ConfigElementPtr element)
{
   return ! (findConstructor(element) == -1);
}

/**
 * Loads the specified device.
 */
Input* DeviceFactory::loadDevice(jccl::ConfigElementPtr element)
{
   vprASSERT(recognizeDevice(element));

   int index(findConstructor(element));

   Input* new_dev;
   DeviceConstructorBase* constructor = mConstructors[index];

   vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_STATE_LVL)
      << "gadget::DeviceFactory::loadDevice: Loading device: "
      << element->getID() << "  with: " << typeid(*constructor).name()
      << std::endl << vprDEBUG_FLUSH;

   new_dev = constructor->createDevice(element);
   return new_dev;
}

int DeviceFactory::findConstructor(jccl::ConfigElementPtr element)
{
   const std::string element_type(element->getID());

   for ( unsigned int i = 0; i < mConstructors.size(); ++i )
   {
      // Get next constructor
      DeviceConstructorBase* construct = mConstructors[i];
      vprASSERT(construct != NULL);

      if(construct->getElementType() == element_type)
      {
         return i;
      }
   }

   return -1;
}

void DeviceFactory::debugDump()
{
   vprDEBUG_OutputGuard(gadgetDBG_INPUT_MGR, vprDBG_VERB_LVL,
      std::string("gadget::DeviceFactory::debugDump\n"),
      std::string("------ END DUMP ------\n"));
   vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_VERB_LVL) << "num constructors:"
                                   << mConstructors.size() << "\n"
                                   << vprDEBUG_FLUSH;

   for(unsigned int cNum=0;cNum<mConstructors.size();cNum++)
   {
      DeviceConstructorBase* dev_constr = mConstructors[cNum];
      vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_VERB_LVL)
         << cNum << ": Constructor:" << (void*)dev_constr
         << "   type:" << typeid(*dev_constr).name() << "\n" << vprDEBUG_FLUSH;
      vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_VERB_LVL)
         << "   recog:" << dev_constr->getElementType() << "\n"
         << vprDEBUG_FLUSH;
   }
}

} // End of gadget namespace
<|endoftext|>