<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: testframecontrol.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: vg $ $Date: 2006-06-02 13:04:32 $
 *
 *  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
 *
 ************************************************************************/

#pragma hdrstop
//#include <vos/mutex.hxx>
#include <vos/dynload.hxx>

#include <vcl/wrkwin.hxx>
#include <vcl/svapp.hxx>

#include <stardiv/uno/repos/implementationregistration.hxx>
#include <stardiv/uno/repos/serinfo.hxx>
#include <stardiv/uno/awt/vcllstnr.hxx>
#include <stardiv/uno/awt/device.hxx>
#include <stardiv/uno/awt/graphics.hxx>
#include <stardiv/uno/awt/vclwin.hxx>

#include <usr/services.hxx>

#include <svtools/unoiface.hxx>

using namespace vos;
using namespace usr;

//==================================================================================================
class Listener_Impl
    : public UsrObject
    , public XMouseListener
    , public XMouseMotionListener
    , public XKeyListener
    , public XWindowListener
    , public XFocusListener
    , public XPaintListener
{
public:
    SMART_UNO_DECLARATION( Listener_Impl, UsrObject );

    virtual BOOL        queryInterface( Uik aUik, XInterfaceRef& rOut );

    // XMouseListener
    virtual void        mousePressed( const VclMouseEvent& evt );
    virtual void        mouseReleased( const VclMouseEvent& evt );
    virtual void        mouseEntered( const VclMouseEvent& evt );
    virtual void        mouseExited( const VclMouseEvent& evt );

    // XMouseMotionListener
    virtual void        mouseDragged( const VclMouseEvent& evt );
    virtual void        mouseMoved( const VclMouseEvent& evt );

    // XKeyListener
    virtual void        keyPressed( const VclKeyEvent& evt );
    virtual void        keyReleased( const VclKeyEvent& evt );

    // XFocusListener
    virtual void        focusGained( const FocusEvent& evt );
    virtual void        focusLost( const FocusEvent& evt );

    // XWindowListener
    virtual void        windowResized( const WindowEvent& evt );
    virtual void        windowMoved( const WindowEvent& evt );
    virtual void        windowShown( const EventObject& evt );
    virtual void        windowHidden( const EventObject& evt );

    // XPaintListener
    virtual void        windowPaint( const PaintEvent& evt );

    // XEventListener
    virtual void        disposing( const EventObject& evt );

public:
    void                addAllListeners( const XControlRef& xControl );
    void                removeAllListeners( const XControlRef& xControl );
};

//--------------------------------------------------------------------------------------------------
void Listener_Impl::addAllListeners( const XControlRef& xControl )
{
    XWindowRef xWindow( xControl, USR_QUERY );

    xWindow->addMouseListener( (XMouseListener*)this );
    xWindow->addMouseMotionListener( (XMouseMotionListener*)this );
    xWindow->addKeyListener( (XKeyListener*)this );
    xWindow->addFocusListener( (XFocusListener*)this );
    xWindow->addWindowListener( (XWindowListener*)this );
    xWindow->addPaintListener( (XPaintListener*)this );
    // cast due to ambiguities
    xControl->addEventListener( (XEventListener*)(XPaintListener*)this );
}

//--------------------------------------------------------------------------------------------------
void Listener_Impl::removeAllListeners( const XControlRef& xControl )
{
    XWindowRef xWindow( xControl, USR_QUERY );

    xWindow->removeMouseListener( (XMouseListener*)this );
    xWindow->removeMouseMotionListener( (XMouseMotionListener*)this );
    xWindow->removeKeyListener( (XKeyListener*)this );
    xWindow->removeFocusListener( (XFocusListener*)this );
    xWindow->removeWindowListener( (XWindowListener*)this );
    xWindow->removePaintListener( (XPaintListener*)this );
    // cast due to ambiguities
    xControl->removeEventListener( (XEventListener*)(XPaintListener*)this );
}

//--------------------------------------------------------------------------------------------------
SMART_UNO_IMPLEMENTATION( Listener_Impl, UsrObject );

//--------------------------------------------------------------------------------------------------
BOOL Listener_Impl::queryInterface( Uik aUik, XInterfaceRef& rOut )
{
    if (aUik == XMouseListener::getSmartUik())
        rOut = (XMouseListener*)this;
    else if (aUik == XMouseMotionListener::getSmartUik())
        rOut = (XMouseMotionListener*)this;
    else if (aUik == XWindowListener::getSmartUik())
        rOut = (XWindowListener*)this;
    else if (aUik == XFocusListener::getSmartUik())
        rOut = (XFocusListener*)this;
    else if (aUik == XKeyListener::getSmartUik())
        rOut = (XKeyListener*)this;
    else if (aUik == XPaintListener::getSmartUik())
        rOut = (XPaintListener*)this;
    else if (aUik == ((XEventListener*)NULL)->getSmartUik())
        rOut = (XEventListener*)(XMouseListener*)this;
    else
        return UsrObject::queryInterface( aUik, rOut );

    return TRUE;
}

//--------------------------------------------------------------------------------------------------
// XMouseListener
void Listener_Impl::mousePressed( const VclMouseEvent& evt )    {}
void Listener_Impl::mouseReleased( const VclMouseEvent& evt )   {}
void Listener_Impl::mouseEntered( const VclMouseEvent& evt )    {}
void Listener_Impl::mouseExited( const VclMouseEvent& evt )     {}

// XMouseMotionListener
void Listener_Impl::mouseDragged( const VclMouseEvent& evt )    {}
void Listener_Impl::mouseMoved( const VclMouseEvent& evt )      {}

// XKeyListener
void Listener_Impl::keyPressed( const VclKeyEvent& evt )        {}
void Listener_Impl::keyReleased( const VclKeyEvent& evt )       {}

// XFocusListener
void Listener_Impl::focusGained( const FocusEvent& evt )        {}
void Listener_Impl::focusLost( const FocusEvent& evt )          {}

// XWindowListener
void Listener_Impl::windowResized( const WindowEvent& evt )     {}
void Listener_Impl::windowMoved( const WindowEvent& evt )       {}
void Listener_Impl::windowShown( const EventObject& evt )       {}
void Listener_Impl::windowHidden( const EventObject& evt )      {}

// XPaintListener
void Listener_Impl::windowPaint( const PaintEvent& evt )
{
    if (evt.Source.is())
    {
        XControlRef xControl( evt.Source, USR_QUERY );
        if (xControl.is())
        {
            XDeviceRef xDev( xControl->getPeer(), USR_QUERY );
            XGraphicsRef xGraphics = xDev->createGraphics();
            xGraphics->drawLine( 0, 0, 200, 200 );
            xGraphics->drawLine( 200, 0, 0, 200 );
        }
    }
}

// XEventListener
void Listener_Impl::disposing( const EventObject& evt )     {}

//==================================================================================================
class FrameControlApplication
    : public Application
{
public:
    virtual void        Main();
    virtual void        ShowStatusText( const XubString& rText );

public:
                        FrameControlApplication()       {}

private:
    void                init();
    void                deinit();

private:
    Listener_Impl*      _pListener;
    XControlRef         _xControl;

    WorkWindow*         _pWorkWin;
};

FrameControlApplication g_App;

#ifdef __MWERKS__
Application* pApp = &g_App;
#endif

//--------------------------------------------------------------------------------------------------
void FrameControlApplication::init()
{
    XMultiServiceFactoryRef xMgr = createRegistryServiceManager( L"test.rdb" );
    registerUsrServices( xMgr );
    setProcessServiceManager( xMgr );
    InitExtVclToolkit();
    Application::RegisterUnoServices();

    XServiceRegistryRef xRegMgr(xMgr, USR_QUERY);

    XImplementationRegistrationRef xIR( xMgr->createInstance(L"stardiv.uno.repos.ImplementationRegistration"), USR_QUERY );
    try
    {
        char szDllName[_MAX_PATH]="";

        ORealDynamicLoader::computeModuleName("fc", szDllName, _MAX_PATH);
        UString aFCDllName = StringToOUString(szDllName, CHARSET_SYSTEM);
        xIR->registerImplementation(L"stardiv.loader.SharedLibrary", aFCDllName, XSimpleRegistryRef() );
    }
    catch( CannotRegisterImplementationException& e )
    {
    }

    // ...

    XInterfaceRef xInst = xMgr->createInstance( L"stardiv.one.frame.FrameControl" );
    if (xInst->queryInterface( XControl::getSmartUik(), _xControl ))
    {
        _pWorkWin = new WorkWindow( NULL, WB_APP | WB_STDWORK );
        _pWorkWin->Show();
        XWindowPeerRef xParent( _pWorkWin->GetComponentInterface() );

        XToolkitRef xToolkit( xMgr->createInstance( L"stardiv.vcl.VclToolkit" ), USR_QUERY );
        //xToolkit = XToolkitRef( xMgr->createInstance( L"stardiv.uno.awt.Toolkit" ), USR_QUERY );
        _xControl->createPeer( xToolkit, xParent );
        XWindowRef xWin( _xControl, USR_QUERY );
        xWin->setPosSize( 50, 50, 400, 400, PosSize_POSSIZE );
        xWin->setVisible( TRUE );

        _pListener = new Listener_Impl();
        _pListener->acquire();
        _pListener->addAllListeners( _xControl );
        // ... on paint a cross should be drawn
    }
}

//--------------------------------------------------------------------------------------------------
void FrameControlApplication::deinit()
{
    if (_pListener)
    {

        _pListener->removeAllListeners( _xControl );
        _xControl->dispose();   // disposing event should occur
        _pListener->release();
        _pListener = NULL;

        _xControl = XControlRef();
    }

    _pWorkWin->Hide();
    delete _pWorkWin;
}

//--------------------------------------------------------------------------------------------------
void FrameControlApplication::Main()
{
//      void TestErrcodes();
//      TestErrcodes();

    EnterMultiThread();
    SetAppName( "RadioActiveControl-Demo" );
    EnableSVLook();

    init();

    Execute();

    deinit();
}

//--------------------------------------------------------------------------------------------------
void FrameControlApplication::ShowStatusText( const XubString& rStatus )
{
    Application::GetAppWindow()->SetText( rStatus );
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.4.46); FILE MERGED 2006/09/01 17:26:54 kaib 1.4.46.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: testframecontrol.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 13:35:40 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

//#include <vos/mutex.hxx>
#include <vos/dynload.hxx>

#include <vcl/wrkwin.hxx>
#include <vcl/svapp.hxx>

#include <stardiv/uno/repos/implementationregistration.hxx>
#include <stardiv/uno/repos/serinfo.hxx>
#include <stardiv/uno/awt/vcllstnr.hxx>
#include <stardiv/uno/awt/device.hxx>
#include <stardiv/uno/awt/graphics.hxx>
#include <stardiv/uno/awt/vclwin.hxx>

#include <usr/services.hxx>

#include <svtools/unoiface.hxx>

using namespace vos;
using namespace usr;

//==================================================================================================
class Listener_Impl
    : public UsrObject
    , public XMouseListener
    , public XMouseMotionListener
    , public XKeyListener
    , public XWindowListener
    , public XFocusListener
    , public XPaintListener
{
public:
    SMART_UNO_DECLARATION( Listener_Impl, UsrObject );

    virtual BOOL        queryInterface( Uik aUik, XInterfaceRef& rOut );

    // XMouseListener
    virtual void        mousePressed( const VclMouseEvent& evt );
    virtual void        mouseReleased( const VclMouseEvent& evt );
    virtual void        mouseEntered( const VclMouseEvent& evt );
    virtual void        mouseExited( const VclMouseEvent& evt );

    // XMouseMotionListener
    virtual void        mouseDragged( const VclMouseEvent& evt );
    virtual void        mouseMoved( const VclMouseEvent& evt );

    // XKeyListener
    virtual void        keyPressed( const VclKeyEvent& evt );
    virtual void        keyReleased( const VclKeyEvent& evt );

    // XFocusListener
    virtual void        focusGained( const FocusEvent& evt );
    virtual void        focusLost( const FocusEvent& evt );

    // XWindowListener
    virtual void        windowResized( const WindowEvent& evt );
    virtual void        windowMoved( const WindowEvent& evt );
    virtual void        windowShown( const EventObject& evt );
    virtual void        windowHidden( const EventObject& evt );

    // XPaintListener
    virtual void        windowPaint( const PaintEvent& evt );

    // XEventListener
    virtual void        disposing( const EventObject& evt );

public:
    void                addAllListeners( const XControlRef& xControl );
    void                removeAllListeners( const XControlRef& xControl );
};

//--------------------------------------------------------------------------------------------------
void Listener_Impl::addAllListeners( const XControlRef& xControl )
{
    XWindowRef xWindow( xControl, USR_QUERY );

    xWindow->addMouseListener( (XMouseListener*)this );
    xWindow->addMouseMotionListener( (XMouseMotionListener*)this );
    xWindow->addKeyListener( (XKeyListener*)this );
    xWindow->addFocusListener( (XFocusListener*)this );
    xWindow->addWindowListener( (XWindowListener*)this );
    xWindow->addPaintListener( (XPaintListener*)this );
    // cast due to ambiguities
    xControl->addEventListener( (XEventListener*)(XPaintListener*)this );
}

//--------------------------------------------------------------------------------------------------
void Listener_Impl::removeAllListeners( const XControlRef& xControl )
{
    XWindowRef xWindow( xControl, USR_QUERY );

    xWindow->removeMouseListener( (XMouseListener*)this );
    xWindow->removeMouseMotionListener( (XMouseMotionListener*)this );
    xWindow->removeKeyListener( (XKeyListener*)this );
    xWindow->removeFocusListener( (XFocusListener*)this );
    xWindow->removeWindowListener( (XWindowListener*)this );
    xWindow->removePaintListener( (XPaintListener*)this );
    // cast due to ambiguities
    xControl->removeEventListener( (XEventListener*)(XPaintListener*)this );
}

//--------------------------------------------------------------------------------------------------
SMART_UNO_IMPLEMENTATION( Listener_Impl, UsrObject );

//--------------------------------------------------------------------------------------------------
BOOL Listener_Impl::queryInterface( Uik aUik, XInterfaceRef& rOut )
{
    if (aUik == XMouseListener::getSmartUik())
        rOut = (XMouseListener*)this;
    else if (aUik == XMouseMotionListener::getSmartUik())
        rOut = (XMouseMotionListener*)this;
    else if (aUik == XWindowListener::getSmartUik())
        rOut = (XWindowListener*)this;
    else if (aUik == XFocusListener::getSmartUik())
        rOut = (XFocusListener*)this;
    else if (aUik == XKeyListener::getSmartUik())
        rOut = (XKeyListener*)this;
    else if (aUik == XPaintListener::getSmartUik())
        rOut = (XPaintListener*)this;
    else if (aUik == ((XEventListener*)NULL)->getSmartUik())
        rOut = (XEventListener*)(XMouseListener*)this;
    else
        return UsrObject::queryInterface( aUik, rOut );

    return TRUE;
}

//--------------------------------------------------------------------------------------------------
// XMouseListener
void Listener_Impl::mousePressed( const VclMouseEvent& evt )    {}
void Listener_Impl::mouseReleased( const VclMouseEvent& evt )   {}
void Listener_Impl::mouseEntered( const VclMouseEvent& evt )    {}
void Listener_Impl::mouseExited( const VclMouseEvent& evt )     {}

// XMouseMotionListener
void Listener_Impl::mouseDragged( const VclMouseEvent& evt )    {}
void Listener_Impl::mouseMoved( const VclMouseEvent& evt )      {}

// XKeyListener
void Listener_Impl::keyPressed( const VclKeyEvent& evt )        {}
void Listener_Impl::keyReleased( const VclKeyEvent& evt )       {}

// XFocusListener
void Listener_Impl::focusGained( const FocusEvent& evt )        {}
void Listener_Impl::focusLost( const FocusEvent& evt )          {}

// XWindowListener
void Listener_Impl::windowResized( const WindowEvent& evt )     {}
void Listener_Impl::windowMoved( const WindowEvent& evt )       {}
void Listener_Impl::windowShown( const EventObject& evt )       {}
void Listener_Impl::windowHidden( const EventObject& evt )      {}

// XPaintListener
void Listener_Impl::windowPaint( const PaintEvent& evt )
{
    if (evt.Source.is())
    {
        XControlRef xControl( evt.Source, USR_QUERY );
        if (xControl.is())
        {
            XDeviceRef xDev( xControl->getPeer(), USR_QUERY );
            XGraphicsRef xGraphics = xDev->createGraphics();
            xGraphics->drawLine( 0, 0, 200, 200 );
            xGraphics->drawLine( 200, 0, 0, 200 );
        }
    }
}

// XEventListener
void Listener_Impl::disposing( const EventObject& evt )     {}

//==================================================================================================
class FrameControlApplication
    : public Application
{
public:
    virtual void        Main();
    virtual void        ShowStatusText( const XubString& rText );

public:
                        FrameControlApplication()       {}

private:
    void                init();
    void                deinit();

private:
    Listener_Impl*      _pListener;
    XControlRef         _xControl;

    WorkWindow*         _pWorkWin;
};

FrameControlApplication g_App;

#ifdef __MWERKS__
Application* pApp = &g_App;
#endif

//--------------------------------------------------------------------------------------------------
void FrameControlApplication::init()
{
    XMultiServiceFactoryRef xMgr = createRegistryServiceManager( L"test.rdb" );
    registerUsrServices( xMgr );
    setProcessServiceManager( xMgr );
    InitExtVclToolkit();
    Application::RegisterUnoServices();

    XServiceRegistryRef xRegMgr(xMgr, USR_QUERY);

    XImplementationRegistrationRef xIR( xMgr->createInstance(L"stardiv.uno.repos.ImplementationRegistration"), USR_QUERY );
    try
    {
        char szDllName[_MAX_PATH]="";

        ORealDynamicLoader::computeModuleName("fc", szDllName, _MAX_PATH);
        UString aFCDllName = StringToOUString(szDllName, CHARSET_SYSTEM);
        xIR->registerImplementation(L"stardiv.loader.SharedLibrary", aFCDllName, XSimpleRegistryRef() );
    }
    catch( CannotRegisterImplementationException& e )
    {
    }

    // ...

    XInterfaceRef xInst = xMgr->createInstance( L"stardiv.one.frame.FrameControl" );
    if (xInst->queryInterface( XControl::getSmartUik(), _xControl ))
    {
        _pWorkWin = new WorkWindow( NULL, WB_APP | WB_STDWORK );
        _pWorkWin->Show();
        XWindowPeerRef xParent( _pWorkWin->GetComponentInterface() );

        XToolkitRef xToolkit( xMgr->createInstance( L"stardiv.vcl.VclToolkit" ), USR_QUERY );
        //xToolkit = XToolkitRef( xMgr->createInstance( L"stardiv.uno.awt.Toolkit" ), USR_QUERY );
        _xControl->createPeer( xToolkit, xParent );
        XWindowRef xWin( _xControl, USR_QUERY );
        xWin->setPosSize( 50, 50, 400, 400, PosSize_POSSIZE );
        xWin->setVisible( TRUE );

        _pListener = new Listener_Impl();
        _pListener->acquire();
        _pListener->addAllListeners( _xControl );
        // ... on paint a cross should be drawn
    }
}

//--------------------------------------------------------------------------------------------------
void FrameControlApplication::deinit()
{
    if (_pListener)
    {

        _pListener->removeAllListeners( _xControl );
        _xControl->dispose();   // disposing event should occur
        _pListener->release();
        _pListener = NULL;

        _xControl = XControlRef();
    }

    _pWorkWin->Hide();
    delete _pWorkWin;
}

//--------------------------------------------------------------------------------------------------
void FrameControlApplication::Main()
{
//      void TestErrcodes();
//      TestErrcodes();

    EnterMultiThread();
    SetAppName( "RadioActiveControl-Demo" );
    EnableSVLook();

    init();

    Execute();

    deinit();
}

//--------------------------------------------------------------------------------------------------
void FrameControlApplication::ShowStatusText( const XubString& rStatus )
{
    Application::GetAppWindow()->SetText( rStatus );
}
<|endoftext|>


<commit_before>/****************************************************************************
 *   Copyright (c) 2017 Zheng, Lei (realthunder) <realthunder.dev@gmail.com>*
 *                                                                          *
 *   This file is part of the FreeCAD CAx development system.               *
 *                                                                          *
 *   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; see the file COPYING.LIB. If not,     *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,          *
 *   Suite 330, Boston, MA  02111-1307, USA                                 *
 *                                                                          *
 ****************************************************************************/

#include "PreCompiled.h"

#ifndef _PreComp_
#endif

#include <BRep_Builder.hxx>
#include <TopoDS_Compound.hxx>

#include "FeatureArea.h"
#include "FeatureAreaPy.h"
#include <App/DocumentObjectPy.h>
#include <Base/Placement.h>
#include <Mod/Part/App/PartFeature.h>

using namespace Path;

PROPERTY_SOURCE(Path::FeatureArea, Part::Feature)

PARAM_ENUM_STRING_DECLARE(static const char *Enums,AREA_PARAMS_ALL)

FeatureArea::FeatureArea()
    :myInited(false)
{
    ADD_PROPERTY(Sources,(0));
    ADD_PROPERTY(WorkPlane,(TopoDS_Shape()));

    PARAM_PROP_ADD("Area",AREA_PARAMS_OPCODE);
    PARAM_PROP_ADD("Area",AREA_PARAMS_BASE);
    PARAM_PROP_ADD("Offset",AREA_PARAMS_OFFSET);
    PARAM_PROP_ADD("Offset", AREA_PARAMS_OFFSET_CONF);
    PARAM_PROP_ADD("Pocket",AREA_PARAMS_POCKET);
    PARAM_PROP_ADD("Pocket",AREA_PARAMS_POCKET_CONF);
    PARAM_PROP_ADD("Section",AREA_PARAMS_SECTION);
    PARAM_PROP_ADD("libarea",AREA_PARAMS_CAREA);

    PARAM_PROP_SET_ENUM(Enums,AREA_PARAMS_ALL);
    PocketMode.setValue((long)0);
}

FeatureArea::~FeatureArea()
{
}

Area &FeatureArea::getArea() {
    if(!myInited) execute();
    return myArea;
}

App::DocumentObjectExecReturn *FeatureArea::execute(void)
{
    myInited = true;

    std::vector<App::DocumentObject*> links = Sources.getValues();
    if (links.empty())
        return new App::DocumentObjectExecReturn("No shapes linked");

    for (std::vector<App::DocumentObject*>::iterator it = links.begin(); it != links.end(); ++it) {
        if (!(*it && (*it)->isDerivedFrom(Part::Feature::getClassTypeId())))
            return new App::DocumentObjectExecReturn("Linked object is not a Part object (has no Shape).");
        TopoDS_Shape shape = static_cast<Part::Feature*>(*it)->Shape.getShape().getShape();
        if (shape.IsNull())
            return new App::DocumentObjectExecReturn("Linked shape object is empty");
    }

    TIME_INIT(t);

    AreaParams params;

#define AREA_PROP_GET(_param) \
    params.PARAM_FNAME(_param) = PARAM_FNAME(_param).getValue();
    PARAM_FOREACH(AREA_PROP_GET,AREA_PARAMS_CONF)

    myArea.clean(true);
    myArea.setParams(params);

    TopoDS_Shape workPlane = WorkPlane.getShape().getShape();
    myArea.setPlane(workPlane);

    for (std::vector<App::DocumentObject*>::iterator it = links.begin(); it != links.end(); ++it) {
        myArea.add(static_cast<Part::Feature*>(*it)->Shape.getShape().getShape(),
                PARAM_PROP_ARGS(AREA_PARAMS_OPCODE));
    }

    myShapes.clear();
    if(myArea.getSectionCount()==0)
        myShapes.push_back(myArea.getShape(-1));
    else {
        myShapes.reserve(myArea.getSectionCount());
        for(int i=0;i<(int)myArea.getSectionCount();++i)
            myShapes.push_back(myArea.getShape(i));
    }

    bool hasShape = false;
    if(myShapes.empty())
        Shape.setValue(TopoDS_Shape());
    else{
        // compound is built even if there is only one shape to save the
        // trouble of messing around with placement
        BRep_Builder builder;
        TopoDS_Compound compound;
        builder.MakeCompound(compound);
        for(auto &shape : myShapes) {
            if(shape.IsNull()) continue;
            hasShape = true;
            builder.Add(compound,shape);
        }
        Shape.setValue(compound);
    }

    TIME_PRINT(t,"feature execute");

    if(!hasShape)
        return new App::DocumentObjectExecReturn("no output shape");

    return DocumentObject::StdReturn;
}

const std::vector<TopoDS_Shape> &FeatureArea::getShapes() {
    getArea();
    return myShapes;
}

short FeatureArea::mustExecute(void) const
{
    if(!myArea.isBuilt())
        return 1;
    return Part::Feature::mustExecute();
}

PyObject *FeatureArea::getPyObject()
{
    if (PythonObject.is(Py::_None())){
        // ref counter is set to 1
        PythonObject = Py::Object(new FeatureAreaPy(this),true);
    }
    return Py::new_reference_to(PythonObject);
}

// FeatureAreaView -------------------------------------------------------------
//
PROPERTY_SOURCE(Path::FeatureAreaView, Part::Feature)

FeatureAreaView::FeatureAreaView()
{
    ADD_PROPERTY(Source,(0));
    ADD_PROPERTY_TYPE(SectionIndex,(0),"Section",App::Prop_None,"The start index of the section to show, negative value for reverse index from bottom");
    ADD_PROPERTY_TYPE(SectionCount,(1),"Section",App::Prop_None,"Number of sections to show, 0 to show all section starting from SectionIndex");
}

std::list<TopoDS_Shape> FeatureAreaView::getShapes() {
    std::list<TopoDS_Shape> shapes;
    App::DocumentObject* pObj = Source.getValue();
    if (!pObj) return shapes;
    if(!pObj->isDerivedFrom(FeatureArea::getClassTypeId()))
        return shapes;

    auto all_shapes = static_cast<FeatureArea*>(pObj)->getShapes();

    if(all_shapes.empty())
        return shapes;

    int index=SectionIndex.getValue(),count=SectionCount.getValue();
    if(index<0) {
        index += ((int)all_shapes.size());
        if(index<0) return shapes;
        if(count<=0 || index+1-count<0) {
            count = index+1;
            index = 0;
        }else
            index -= count-1;
    }else if(index >= (int)all_shapes.size())
        return shapes;

    if(count<=0) count = all_shapes.size();
    count += index;
    if(count>(int)all_shapes.size())
        count = all_shapes.size();
    for(int i=index;i<count;++i)
        shapes.push_back(all_shapes[i]);
    return std::move(shapes);
}

App::DocumentObjectExecReturn *FeatureAreaView::execute(void)
{
    App::DocumentObject* pObj = Source.getValue();
    if (!pObj)
        return new App::DocumentObjectExecReturn("No shape linked");

    if(!pObj->isDerivedFrom(FeatureArea::getClassTypeId()))
            return new App::DocumentObjectExecReturn("Linked object is not a FeatureArea");

    bool hasShape = false;
    std::list<TopoDS_Shape> shapes = getShapes();
    if(shapes.empty())
        Shape.setValue(TopoDS_Shape());
    else{
        BRep_Builder builder;
        TopoDS_Compound compound;
        builder.MakeCompound(compound);
        for(auto &shape : shapes) {
            if(shape.IsNull()) continue;
            hasShape = true;
            builder.Add(compound,shape);
        }
        Shape.setValue(compound);
    }

    if(!hasShape)
        return new App::DocumentObjectExecReturn("no output shape");

    return DocumentObject::StdReturn;
}

// Python feature ---------------------------------------------------------

namespace App {
/// @cond DOXERR
PROPERTY_SOURCE_TEMPLATE(Path::FeatureAreaPython, Path::FeatureArea)
PROPERTY_SOURCE_TEMPLATE(Path::FeatureAreaViewPython, Path::FeatureAreaView)

template<> const char* Path::FeatureAreaPython::getViewProviderName(void) const {
    return "PathGui::ViewProviderAreaPython";
}
template<> const char* Path::FeatureAreaViewPython::getViewProviderName(void) const {
    return "PathGui::ViewProviderAreaViewPython";
}
/// @endcond

// explicit template instantiation
template class PathExport FeaturePythonT<Path::FeatureArea>;
}

<commit_msg>Path.Area: avoid FeatureArea recompute on doc load<commit_after>/****************************************************************************
 *   Copyright (c) 2017 Zheng, Lei (realthunder) <realthunder.dev@gmail.com>*
 *                                                                          *
 *   This file is part of the FreeCAD CAx development system.               *
 *                                                                          *
 *   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; see the file COPYING.LIB. If not,     *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,          *
 *   Suite 330, Boston, MA  02111-1307, USA                                 *
 *                                                                          *
 ****************************************************************************/

#include "PreCompiled.h"

#ifndef _PreComp_
#endif

#include <BRep_Builder.hxx>
#include <TopoDS_Compound.hxx>

#include "FeatureArea.h"
#include "FeatureAreaPy.h"
#include <App/DocumentObjectPy.h>
#include <Base/Placement.h>
#include <Mod/Part/App/PartFeature.h>

using namespace Path;

PROPERTY_SOURCE(Path::FeatureArea, Part::Feature)

PARAM_ENUM_STRING_DECLARE(static const char *Enums,AREA_PARAMS_ALL)

FeatureArea::FeatureArea()
    :myInited(false)
{
    ADD_PROPERTY(Sources,(0));
    ADD_PROPERTY(WorkPlane,(TopoDS_Shape()));

    PARAM_PROP_ADD("Area",AREA_PARAMS_OPCODE);
    PARAM_PROP_ADD("Area",AREA_PARAMS_BASE);
    PARAM_PROP_ADD("Offset",AREA_PARAMS_OFFSET);
    PARAM_PROP_ADD("Offset", AREA_PARAMS_OFFSET_CONF);
    PARAM_PROP_ADD("Pocket",AREA_PARAMS_POCKET);
    PARAM_PROP_ADD("Pocket",AREA_PARAMS_POCKET_CONF);
    PARAM_PROP_ADD("Section",AREA_PARAMS_SECTION);
    PARAM_PROP_ADD("libarea",AREA_PARAMS_CAREA);

    PARAM_PROP_SET_ENUM(Enums,AREA_PARAMS_ALL);
    PocketMode.setValue((long)0);
}

FeatureArea::~FeatureArea()
{
}

Area &FeatureArea::getArea() {
    if(!myInited) execute();
    return myArea;
}

App::DocumentObjectExecReturn *FeatureArea::execute(void)
{
    myInited = true;

    std::vector<App::DocumentObject*> links = Sources.getValues();
    if (links.empty())
        return new App::DocumentObjectExecReturn("No shapes linked");

    for (std::vector<App::DocumentObject*>::iterator it = links.begin(); it != links.end(); ++it) {
        if (!(*it && (*it)->isDerivedFrom(Part::Feature::getClassTypeId())))
            return new App::DocumentObjectExecReturn("Linked object is not a Part object (has no Shape).");
        TopoDS_Shape shape = static_cast<Part::Feature*>(*it)->Shape.getShape().getShape();
        if (shape.IsNull())
            return new App::DocumentObjectExecReturn("Linked shape object is empty");
    }

    TIME_INIT(t);

    AreaParams params;

#define AREA_PROP_GET(_param) \
    params.PARAM_FNAME(_param) = PARAM_FNAME(_param).getValue();
    PARAM_FOREACH(AREA_PROP_GET,AREA_PARAMS_CONF)

    myArea.clean(true);
    myArea.setParams(params);

    TopoDS_Shape workPlane = WorkPlane.getShape().getShape();
    myArea.setPlane(workPlane);

    for (std::vector<App::DocumentObject*>::iterator it = links.begin(); it != links.end(); ++it) {
        myArea.add(static_cast<Part::Feature*>(*it)->Shape.getShape().getShape(),
                PARAM_PROP_ARGS(AREA_PARAMS_OPCODE));
    }

    myShapes.clear();
    if(myArea.getSectionCount()==0)
        myShapes.push_back(myArea.getShape(-1));
    else {
        myShapes.reserve(myArea.getSectionCount());
        for(int i=0;i<(int)myArea.getSectionCount();++i)
            myShapes.push_back(myArea.getShape(i));
    }

    bool hasShape = false;
    if(myShapes.empty())
        Shape.setValue(TopoDS_Shape());
    else{
        // compound is built even if there is only one shape to save the
        // trouble of messing around with placement
        BRep_Builder builder;
        TopoDS_Compound compound;
        builder.MakeCompound(compound);
        for(auto &shape : myShapes) {
            if(shape.IsNull()) continue;
            hasShape = true;
            builder.Add(compound,shape);
        }
        Shape.setValue(compound);
    }

    TIME_PRINT(t,"feature execute");

    if(!hasShape)
        return new App::DocumentObjectExecReturn("no output shape");

    return DocumentObject::StdReturn;
}

const std::vector<TopoDS_Shape> &FeatureArea::getShapes() {
    getArea();
    return myShapes;
}

short FeatureArea::mustExecute(void) const
{
    if(myInited && !myArea.isBuilt())
        return 1;
    return Part::Feature::mustExecute();
}

PyObject *FeatureArea::getPyObject()
{
    if (PythonObject.is(Py::_None())){
        // ref counter is set to 1
        PythonObject = Py::Object(new FeatureAreaPy(this),true);
    }
    return Py::new_reference_to(PythonObject);
}

// FeatureAreaView -------------------------------------------------------------
//
PROPERTY_SOURCE(Path::FeatureAreaView, Part::Feature)

FeatureAreaView::FeatureAreaView()
{
    ADD_PROPERTY(Source,(0));
    ADD_PROPERTY_TYPE(SectionIndex,(0),"Section",App::Prop_None,"The start index of the section to show, negative value for reverse index from bottom");
    ADD_PROPERTY_TYPE(SectionCount,(1),"Section",App::Prop_None,"Number of sections to show, 0 to show all section starting from SectionIndex");
}

std::list<TopoDS_Shape> FeatureAreaView::getShapes() {
    std::list<TopoDS_Shape> shapes;
    App::DocumentObject* pObj = Source.getValue();
    if (!pObj) return shapes;
    if(!pObj->isDerivedFrom(FeatureArea::getClassTypeId()))
        return shapes;

    auto all_shapes = static_cast<FeatureArea*>(pObj)->getShapes();

    if(all_shapes.empty())
        return shapes;

    int index=SectionIndex.getValue(),count=SectionCount.getValue();
    if(index<0) {
        index += ((int)all_shapes.size());
        if(index<0) return shapes;
        if(count<=0 || index+1-count<0) {
            count = index+1;
            index = 0;
        }else
            index -= count-1;
    }else if(index >= (int)all_shapes.size())
        return shapes;

    if(count<=0) count = all_shapes.size();
    count += index;
    if(count>(int)all_shapes.size())
        count = all_shapes.size();
    for(int i=index;i<count;++i)
        shapes.push_back(all_shapes[i]);
    return std::move(shapes);
}

App::DocumentObjectExecReturn *FeatureAreaView::execute(void)
{
    App::DocumentObject* pObj = Source.getValue();
    if (!pObj)
        return new App::DocumentObjectExecReturn("No shape linked");

    if(!pObj->isDerivedFrom(FeatureArea::getClassTypeId()))
            return new App::DocumentObjectExecReturn("Linked object is not a FeatureArea");

    bool hasShape = false;
    std::list<TopoDS_Shape> shapes = getShapes();
    if(shapes.empty())
        Shape.setValue(TopoDS_Shape());
    else{
        BRep_Builder builder;
        TopoDS_Compound compound;
        builder.MakeCompound(compound);
        for(auto &shape : shapes) {
            if(shape.IsNull()) continue;
            hasShape = true;
            builder.Add(compound,shape);
        }
        Shape.setValue(compound);
    }

    if(!hasShape)
        return new App::DocumentObjectExecReturn("no output shape");

    return DocumentObject::StdReturn;
}

// Python feature ---------------------------------------------------------

namespace App {
/// @cond DOXERR
PROPERTY_SOURCE_TEMPLATE(Path::FeatureAreaPython, Path::FeatureArea)
PROPERTY_SOURCE_TEMPLATE(Path::FeatureAreaViewPython, Path::FeatureAreaView)

template<> const char* Path::FeatureAreaPython::getViewProviderName(void) const {
    return "PathGui::ViewProviderAreaPython";
}
template<> const char* Path::FeatureAreaViewPython::getViewProviderName(void) const {
    return "PathGui::ViewProviderAreaViewPython";
}
/// @endcond

// explicit template instantiation
template class PathExport FeaturePythonT<Path::FeatureArea>;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: GroupManager.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: hr $ $Date: 2004-02-04 12:34:57 $
 *
 *  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 _FRM_GROUPMANAGER_HXX_
#define _FRM_GROUPMANAGER_HXX_

#ifndef _COM_SUN_STAR_SDBC_XROWSET_HPP_
#include <com/sun/star/sdbc/XRowSet.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XCONTROLMODEL_HPP_
#include <com/sun/star/awt/XControlModel.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYCHANGELISTENER_HPP_
#include <com/sun/star/beans/XPropertyChangeListener.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINERLISTENER_HPP_
#include <com/sun/star/container/XContainerListener.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINER_HPP_
#include <com/sun/star/container/XContainer.hpp>
#endif

#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif

#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif

#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
using namespace comphelper;

/*========================================================================
Funktionsweise GroupManager:

Der GroupManager horcht an der starform, ob FormComponents eingefuegt oder entfernt
werden. Zusaetzlich horcht er bei den FormComponents an den Properties
"Name" und "TabIndex". Mit diesen Infos aktualisiert er seine Gruppen.

Der GroupManager verwaltet eine Gruppe, in der alle Controls nach TabIndex
geordnet sind, und ein Array von Gruppen, in dem jede FormComponent noch
einmal einer Gruppe dem Namen nach zugeordnet wird.
Die einzelnen Gruppen werden ueber eine Map aktiviert, wenn sie mehr als
ein Element besitzen.

Die Gruppen verwalten intern die FormComponents in zwei Arrays. In dem
GroupCompArray werden die Components nach TabIndex und Einfuegepostion
sortiert. Da auf dieses Array ueber die FormComponent zugegriffen
wird, gibt es noch das GroupCompAccessArray, in dem die FormComponents
nach ihrer Speicheradresse sortiert sind. Jedes Element des
GroupCompAccessArrays ist mit einem Element des GroupCompArrays verpointert.

========================================================================*/

//.........................................................................
namespace frm
{
//.........................................................................

//========================================================================
    template <class ELEMENT, class LESS_COMPARE>
    sal_Int32 insert_sorted(::std::vector<ELEMENT>& _rArray, const ELEMENT& _rNewElement, const LESS_COMPARE& _rCompareOp)
    {
        typename ::std::vector<ELEMENT>::iterator aInsertPos = lower_bound(
            _rArray.begin(),
            _rArray.end(),
            _rNewElement,
            _rCompareOp
        );
        aInsertPos = _rArray.insert(aInsertPos, _rNewElement);
        return aInsertPos - _rArray.begin();
    }

    template <class ELEMENT, class LESS_COMPARE>
    sal_Bool seek_entry(const ::std::vector<ELEMENT>& _rArray, const ELEMENT& _rNewElement, sal_Int32& nPos, const LESS_COMPARE& _rCompareOp)
    {
        typename ::std::vector<ELEMENT>::const_iterator aExistentPos = ::std::lower_bound(
            _rArray.begin(),
            _rArray.end(),
            _rNewElement,
            _rCompareOp
        );
        if ((aExistentPos != _rArray.end()) && (*aExistentPos == _rNewElement))
        {   // we have a valid "lower or equal" element and it's really "equal"
            nPos = aExistentPos - _rArray.begin();
            return sal_True;
        }
        nPos = -1;
        return sal_False;
    }

//========================================================================
class OGroupComp
{
    ::rtl::OUString m_aName;
    ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>    m_xComponent;
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel>     m_xControlModel;
    sal_Int32   m_nPos;
    sal_Int16   m_nTabIndex;

    friend class OGroupCompLess;

public:
    OGroupComp(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& rxElement, sal_Int32 nInsertPos );
    OGroupComp(const OGroupComp& _rSource);
    OGroupComp();

    sal_Bool operator==( const OGroupComp& rComp ) const;

    inline const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& GetComponent() const { return m_xComponent; }
    inline const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel>&   GetControlModel() const { return m_xControlModel; }

    sal_Int32   GetPos() const { return m_nPos; }
    sal_Int16   GetTabIndex() const { return m_nTabIndex; }
    ::rtl::OUString GetName() const { return m_aName; }
};

DECLARE_STL_VECTOR(OGroupComp, OGroupCompArr);

//========================================================================
class OGroupComp;
class OGroupCompAcc
{
    ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>    m_xComponent;

    OGroupComp                                      m_aGroupComp;

    friend class OGroupCompAccLess;

public:
    OGroupCompAcc(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& rxElement, const OGroupComp& _rGroupComp );

    sal_Bool operator==( const OGroupCompAcc& rCompAcc ) const;

    inline const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>&  GetComponent() const { return m_xComponent; }
    const OGroupComp&   GetGroupComponent() const { return m_aGroupComp; }
};

DECLARE_STL_VECTOR(OGroupCompAcc, OGroupCompAccArr);

//========================================================================
class OGroup
{
    OGroupCompArr       m_aCompArray;
    OGroupCompAccArr    m_aCompAccArray;

    ::rtl::OUString m_aGroupName;
    sal_uInt16  m_nInsertPos;               // Die Einfugeposition der GroupComps wird von der Gruppe bestimmt.

    friend class OGroupLess;

public:
    OGroup( const ::rtl::OUString& rGroupName );
#ifdef DBG_UTIL
    OGroup( const OGroup& _rSource );   // just to ensure the DBG_CTOR call
#endif
    virtual ~OGroup();

    sal_Bool operator==( const OGroup& rGroup ) const;

    ::rtl::OUString GetGroupName() const { return m_aGroupName; }
    ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel>  > GetControlModels() const;

    void InsertComponent( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& rxElement );
    void RemoveComponent( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& rxElement );
    sal_uInt16 Count() const { return m_aCompArray.size(); }
    const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& GetObject( sal_uInt16 nP ) const
        { return m_aCompArray[nP].GetComponent(); }
};

DECLARE_STL_USTRINGACCESS_MAP(OGroup, OGroupArr);
DECLARE_STL_VECTOR(OGroupArr::iterator, OActiveGroups);

//========================================================================
class OGroupManager : public ::cppu::WeakImplHelper2< ::com::sun::star::beans::XPropertyChangeListener, ::com::sun::star::container::XContainerListener>
{
    OGroup*         m_pCompGroup;           // Alle Components nach TabIndizes sortiert
    OGroupArr       m_aGroupArr;            // Alle Components nach Gruppen sortiert
    OActiveGroups   m_aActiveGroupMap;      // In dieser Map werden die Indizes aller Gruppen gehalten,
                                        // die mehr als 1 Element haben

    ::com::sun::star::uno::Reference< ::com::sun::star::container::XContainer >
                    m_xContainer;

    // Helper functions
    void InsertElement( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& rxElement );
    void RemoveElement( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& rxElement );
    void removeFromGroupMap(const ::rtl::OUString& _sGroupName,const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xSet);

public:
    OGroupManager(const ::com::sun::star::uno::Reference< ::com::sun::star::container::XContainer >& _rxContainer);
    virtual ~OGroupManager();

// ::com::sun::star::lang::XEventListener
    virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& _rSource) throw(::com::sun::star::uno::RuntimeException);

// ::com::sun::star::beans::XPropertyChangeListener
    virtual void SAL_CALL propertyChange(const ::com::sun::star::beans::PropertyChangeEvent& evt) throw ( ::com::sun::star::uno::RuntimeException);

// ::com::sun::star::container::XContainerListener
    virtual void SAL_CALL elementInserted(const ::com::sun::star::container::ContainerEvent& _rEvent) throw ( ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL elementRemoved(const ::com::sun::star::container::ContainerEvent& _rEvent) throw ( ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL elementReplaced(const ::com::sun::star::container::ContainerEvent& _rEvent) throw ( ::com::sun::star::uno::RuntimeException);

// Other functions
    sal_Int32 getGroupCount();
    void getGroup(sal_Int32 nGroup, ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel> >& _rGroup, ::rtl::OUString& Name);
    void getGroupByName(const ::rtl::OUString& Name, ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel> >& _rGroup);
    ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel> > getControlModels();
};

//.........................................................................
}   // namespace frm
//.........................................................................

#endif // _FRM_GROUPMANAGER_HXX_

<commit_msg>INTEGRATION: CWS gcc340fixes01 (1.8.38); FILE MERGED 2004/07/16 12:37:49 cmc 1.8.38.1: #i31586# trivial namespace mod for gcc34<commit_after>/*************************************************************************
 *
 *  $RCSfile: GroupManager.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: kz $ $Date: 2004-07-30 15:05:02 $
 *
 *  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 _FRM_GROUPMANAGER_HXX_
#define _FRM_GROUPMANAGER_HXX_

#ifndef _COM_SUN_STAR_SDBC_XROWSET_HPP_
#include <com/sun/star/sdbc/XRowSet.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XCONTROLMODEL_HPP_
#include <com/sun/star/awt/XControlModel.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYCHANGELISTENER_HPP_
#include <com/sun/star/beans/XPropertyChangeListener.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINERLISTENER_HPP_
#include <com/sun/star/container/XContainerListener.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINER_HPP_
#include <com/sun/star/container/XContainer.hpp>
#endif

#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif

#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif

#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
using namespace comphelper;

/*========================================================================
Funktionsweise GroupManager:

Der GroupManager horcht an der starform, ob FormComponents eingefuegt oder entfernt
werden. Zusaetzlich horcht er bei den FormComponents an den Properties
"Name" und "TabIndex". Mit diesen Infos aktualisiert er seine Gruppen.

Der GroupManager verwaltet eine Gruppe, in der alle Controls nach TabIndex
geordnet sind, und ein Array von Gruppen, in dem jede FormComponent noch
einmal einer Gruppe dem Namen nach zugeordnet wird.
Die einzelnen Gruppen werden ueber eine Map aktiviert, wenn sie mehr als
ein Element besitzen.

Die Gruppen verwalten intern die FormComponents in zwei Arrays. In dem
GroupCompArray werden die Components nach TabIndex und Einfuegepostion
sortiert. Da auf dieses Array ueber die FormComponent zugegriffen
wird, gibt es noch das GroupCompAccessArray, in dem die FormComponents
nach ihrer Speicheradresse sortiert sind. Jedes Element des
GroupCompAccessArrays ist mit einem Element des GroupCompArrays verpointert.

========================================================================*/

//.........................................................................
namespace frm
{
//.........................................................................

//========================================================================
    template <class ELEMENT, class LESS_COMPARE>
    sal_Int32 insert_sorted(::std::vector<ELEMENT>& _rArray, const ELEMENT& _rNewElement, const LESS_COMPARE& _rCompareOp)
    {
        typename ::std::vector<ELEMENT>::iterator aInsertPos = lower_bound(
            _rArray.begin(),
            _rArray.end(),
            _rNewElement,
            _rCompareOp
        );
        aInsertPos = _rArray.insert(aInsertPos, _rNewElement);
        return aInsertPos - _rArray.begin();
    }

    template <class ELEMENT, class LESS_COMPARE>
    sal_Bool seek_entry(const ::std::vector<ELEMENT>& _rArray, const ELEMENT& _rNewElement, sal_Int32& nPos, const LESS_COMPARE& _rCompareOp)
    {
        typename ::std::vector<ELEMENT>::const_iterator aExistentPos = lower_bound(
            _rArray.begin(),
            _rArray.end(),
            _rNewElement,
            _rCompareOp
        );
        if ((aExistentPos != _rArray.end()) && (*aExistentPos == _rNewElement))
        {   // we have a valid "lower or equal" element and it's really "equal"
            nPos = aExistentPos - _rArray.begin();
            return sal_True;
        }
        nPos = -1;
        return sal_False;
    }

//========================================================================
class OGroupComp
{
    ::rtl::OUString m_aName;
    ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>    m_xComponent;
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel>     m_xControlModel;
    sal_Int32   m_nPos;
    sal_Int16   m_nTabIndex;

    friend class OGroupCompLess;

public:
    OGroupComp(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& rxElement, sal_Int32 nInsertPos );
    OGroupComp(const OGroupComp& _rSource);
    OGroupComp();

    sal_Bool operator==( const OGroupComp& rComp ) const;

    inline const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& GetComponent() const { return m_xComponent; }
    inline const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel>&   GetControlModel() const { return m_xControlModel; }

    sal_Int32   GetPos() const { return m_nPos; }
    sal_Int16   GetTabIndex() const { return m_nTabIndex; }
    ::rtl::OUString GetName() const { return m_aName; }
};

DECLARE_STL_VECTOR(OGroupComp, OGroupCompArr);

//========================================================================
class OGroupComp;
class OGroupCompAcc
{
    ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>    m_xComponent;

    OGroupComp                                      m_aGroupComp;

    friend class OGroupCompAccLess;

public:
    OGroupCompAcc(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& rxElement, const OGroupComp& _rGroupComp );

    sal_Bool operator==( const OGroupCompAcc& rCompAcc ) const;

    inline const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>&  GetComponent() const { return m_xComponent; }
    const OGroupComp&   GetGroupComponent() const { return m_aGroupComp; }
};

DECLARE_STL_VECTOR(OGroupCompAcc, OGroupCompAccArr);

//========================================================================
class OGroup
{
    OGroupCompArr       m_aCompArray;
    OGroupCompAccArr    m_aCompAccArray;

    ::rtl::OUString m_aGroupName;
    sal_uInt16  m_nInsertPos;               // Die Einfugeposition der GroupComps wird von der Gruppe bestimmt.

    friend class OGroupLess;

public:
    OGroup( const ::rtl::OUString& rGroupName );
#ifdef DBG_UTIL
    OGroup( const OGroup& _rSource );   // just to ensure the DBG_CTOR call
#endif
    virtual ~OGroup();

    sal_Bool operator==( const OGroup& rGroup ) const;

    ::rtl::OUString GetGroupName() const { return m_aGroupName; }
    ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel>  > GetControlModels() const;

    void InsertComponent( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& rxElement );
    void RemoveComponent( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& rxElement );
    sal_uInt16 Count() const { return m_aCompArray.size(); }
    const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& GetObject( sal_uInt16 nP ) const
        { return m_aCompArray[nP].GetComponent(); }
};

DECLARE_STL_USTRINGACCESS_MAP(OGroup, OGroupArr);
DECLARE_STL_VECTOR(OGroupArr::iterator, OActiveGroups);

//========================================================================
class OGroupManager : public ::cppu::WeakImplHelper2< ::com::sun::star::beans::XPropertyChangeListener, ::com::sun::star::container::XContainerListener>
{
    OGroup*         m_pCompGroup;           // Alle Components nach TabIndizes sortiert
    OGroupArr       m_aGroupArr;            // Alle Components nach Gruppen sortiert
    OActiveGroups   m_aActiveGroupMap;      // In dieser Map werden die Indizes aller Gruppen gehalten,
                                        // die mehr als 1 Element haben

    ::com::sun::star::uno::Reference< ::com::sun::star::container::XContainer >
                    m_xContainer;

    // Helper functions
    void InsertElement( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& rxElement );
    void RemoveElement( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& rxElement );
    void removeFromGroupMap(const ::rtl::OUString& _sGroupName,const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xSet);

public:
    OGroupManager(const ::com::sun::star::uno::Reference< ::com::sun::star::container::XContainer >& _rxContainer);
    virtual ~OGroupManager();

// ::com::sun::star::lang::XEventListener
    virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& _rSource) throw(::com::sun::star::uno::RuntimeException);

// ::com::sun::star::beans::XPropertyChangeListener
    virtual void SAL_CALL propertyChange(const ::com::sun::star::beans::PropertyChangeEvent& evt) throw ( ::com::sun::star::uno::RuntimeException);

// ::com::sun::star::container::XContainerListener
    virtual void SAL_CALL elementInserted(const ::com::sun::star::container::ContainerEvent& _rEvent) throw ( ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL elementRemoved(const ::com::sun::star::container::ContainerEvent& _rEvent) throw ( ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL elementReplaced(const ::com::sun::star::container::ContainerEvent& _rEvent) throw ( ::com::sun::star::uno::RuntimeException);

// Other functions
    sal_Int32 getGroupCount();
    void getGroup(sal_Int32 nGroup, ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel> >& _rGroup, ::rtl::OUString& Name);
    void getGroupByName(const ::rtl::OUString& Name, ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel> >& _rGroup);
    ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel> > getControlModels();
};

//.........................................................................
}   // namespace frm
//.........................................................................

#endif // _FRM_GROUPMANAGER_HXX_

<|endoftext|>


<commit_before>/*
    This file is part of Magnum.

    Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <mosra@centrum.cz>

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

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

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

#include "Sdl2Application.h"

#include "Context.h"
#include "ExtensionWrangler.h"

namespace Magnum { namespace Platform {

namespace {

/*
 * Fix up the modifiers -- we want >= operator to work properly on Shift,
 * Ctrl, Alt, but SDL generates different event for left / right keys, thus
 * (modifiers >= Shift) would pass only if both left and right were pressed,
 * which is usually not what the developers wants.
 */
Sdl2Application::InputEvent::Modifiers fixedModifiers(Uint16 mod) {
    Sdl2Application::InputEvent::Modifiers modifiers(static_cast<Sdl2Application::InputEvent::Modifier>(mod));
    if(modifiers & Sdl2Application::InputEvent::Modifier::Shift) modifiers |= Sdl2Application::InputEvent::Modifier::Shift;
    if(modifiers & Sdl2Application::InputEvent::Modifier::Ctrl) modifiers |= Sdl2Application::InputEvent::Modifier::Ctrl;
    if(modifiers & Sdl2Application::InputEvent::Modifier::Alt) modifiers |= Sdl2Application::InputEvent::Modifier::Alt;
    return modifiers;
}

}

Sdl2Application::Sdl2Application(const Arguments&): context(nullptr), flags(Flag::Redraw) {
    initialize();
    createContext(new Configuration);
}

Sdl2Application::Sdl2Application(const Arguments&, Configuration* configuration): context(nullptr), flags(Flag::Redraw) {
    initialize();
    if(configuration) createContext(configuration);
}

void Sdl2Application::initialize() {
    if(SDL_Init(SDL_INIT_VIDEO) < 0) {
        Error() << "Cannot initialize SDL.";
        std::exit(1);
    }
}

void Sdl2Application::createContext(Configuration* configuration) {
    if(!tryCreateContext(configuration)) {
        Error() << "Platform::Sdl2Application::createContext(): cannot create context:" << SDL_GetError();
        delete configuration;
        std::exit(1);

    } else delete configuration;
}

bool Sdl2Application::tryCreateContext(Configuration* configuration) {
    CORRADE_ASSERT(!context, "Platform::Sdl2Application::tryCreateContext(): context already created", false);

    /* Enable double buffering and 24bt depth buffer */
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);

    /* Multisampling */
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, configuration->sampleCount() > 1 ? 1 : 0);
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, configuration->sampleCount());

    /* Flags: if not hidden, set as shown */
    Uint32 flags(configuration->flags());
    if(!(configuration->flags() & Configuration::Flag::Hidden)) flags |= SDL_WINDOW_SHOWN;

    if(!(window = SDL_CreateWindow(configuration->title().c_str(),
            SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
            configuration->size().x(), configuration->size().y(),
            SDL_WINDOW_OPENGL|flags)))
        return false;

    if(!(context = SDL_GL_CreateContext(window))) {
        SDL_DestroyWindow(window);
        window = nullptr;
        return false;
    }

    /* This must be enabled, otherwise (on my NVidia) it crashes when creating
       VAO. WTF. */
    ExtensionWrangler::initialize(ExtensionWrangler::ExperimentalFeatures::Enable);

    /* Push resize event, so viewportEvent() is called at startup */
    SDL_Event* sizeEvent = new SDL_Event;
    sizeEvent->type = SDL_WINDOWEVENT;
    sizeEvent->window.event = SDL_WINDOWEVENT_RESIZED;
    sizeEvent->window.data1 = configuration->size().x();
    sizeEvent->window.data2 = configuration->size().y();
    SDL_PushEvent(sizeEvent);

    c = new Context;
    return true;
}

Sdl2Application::~Sdl2Application() {
    delete c;

    SDL_GL_DeleteContext(context);
    SDL_DestroyWindow(window);
    SDL_Quit();
}

int Sdl2Application::exec() {
    while(!(flags & Flag::Exit)) mainLoop();
    return 0;
}

void Sdl2Application::mainLoop() {
    SDL_Event event;

    while(SDL_PollEvent(&event)) {
        switch(event.type) {
            case SDL_WINDOWEVENT:
                switch(event.window.event) {
                    case SDL_WINDOWEVENT_RESIZED:
                        viewportEvent({event.window.data1, event.window.data2});
                        flags |= Flag::Redraw;
                        break;
                    case SDL_WINDOWEVENT_EXPOSED:
                        flags |= Flag::Redraw;
                        break;
                } break;

            case SDL_KEYDOWN:
            case SDL_KEYUP: {
                KeyEvent e(static_cast<KeyEvent::Key>(event.key.keysym.sym), fixedModifiers(event.key.keysym.mod));
                event.type == SDL_KEYDOWN ? keyPressEvent(e) : keyReleaseEvent(e);
            } break;

            case SDL_MOUSEBUTTONDOWN:
            case SDL_MOUSEBUTTONUP: {
                MouseEvent e(static_cast<MouseEvent::Button>(event.button.button), {event.button.x, event.button.y});
                event.type == SDL_MOUSEBUTTONDOWN ? mousePressEvent(e) : mouseReleaseEvent(e);
            } break;

            case SDL_MOUSEWHEEL:
                if(event.wheel.y != 0) {
                    MouseEvent e(event.wheel.y < 0 ? MouseEvent::Button::WheelUp : MouseEvent::Button::WheelDown, {event.wheel.x, event.wheel.y});
                    mousePressEvent(e);
                } break;

            case SDL_MOUSEMOTION: {
                MouseMoveEvent e({event.motion.x, event.motion.y}, {event.motion.xrel, event.motion.yrel});
                mouseMoveEvent(e);
                break;
            }

            case SDL_QUIT: return;
        }
    }

    if(flags & Flag::Redraw) {
        flags &= ~Flag::Redraw;
        drawEvent();
    } else SDL_WaitEvent(nullptr);
}

void Sdl2Application::setMouseLocked(bool enabled) {
    SDL_SetWindowGrab(window, enabled ? SDL_TRUE : SDL_FALSE);
    SDL_SetRelativeMouseMode(enabled ? SDL_TRUE : SDL_FALSE);
}

Sdl2Application::Configuration::Configuration(): _title("Magnum SDL2 Application"), _size(800, 600), _flags(Flag::Resizable), _sampleCount(0) {}
Sdl2Application::Configuration::~Configuration() = default;

Sdl2Application::InputEvent::Modifiers Sdl2Application::MouseEvent::modifiers() {
    if(modifiersLoaded) return _modifiers;
    modifiersLoaded = true;
    return _modifiers = fixedModifiers(SDL_GetModState());
}

Sdl2Application::InputEvent::Modifiers Sdl2Application::MouseMoveEvent::modifiers() {
    if(modifiersLoaded) return _modifiers;
    modifiersLoaded = true;
    return _modifiers = fixedModifiers(SDL_GetModState());
}

}}
<commit_msg>Platform::Sdl2Application: properly handle SDL_QUIT.<commit_after>/*
    This file is part of Magnum.

    Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <mosra@centrum.cz>

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

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

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

#include "Sdl2Application.h"

#include "Context.h"
#include "ExtensionWrangler.h"

namespace Magnum { namespace Platform {

namespace {

/*
 * Fix up the modifiers -- we want >= operator to work properly on Shift,
 * Ctrl, Alt, but SDL generates different event for left / right keys, thus
 * (modifiers >= Shift) would pass only if both left and right were pressed,
 * which is usually not what the developers wants.
 */
Sdl2Application::InputEvent::Modifiers fixedModifiers(Uint16 mod) {
    Sdl2Application::InputEvent::Modifiers modifiers(static_cast<Sdl2Application::InputEvent::Modifier>(mod));
    if(modifiers & Sdl2Application::InputEvent::Modifier::Shift) modifiers |= Sdl2Application::InputEvent::Modifier::Shift;
    if(modifiers & Sdl2Application::InputEvent::Modifier::Ctrl) modifiers |= Sdl2Application::InputEvent::Modifier::Ctrl;
    if(modifiers & Sdl2Application::InputEvent::Modifier::Alt) modifiers |= Sdl2Application::InputEvent::Modifier::Alt;
    return modifiers;
}

}

Sdl2Application::Sdl2Application(const Arguments&): context(nullptr), flags(Flag::Redraw) {
    initialize();
    createContext(new Configuration);
}

Sdl2Application::Sdl2Application(const Arguments&, Configuration* configuration): context(nullptr), flags(Flag::Redraw) {
    initialize();
    if(configuration) createContext(configuration);
}

void Sdl2Application::initialize() {
    if(SDL_Init(SDL_INIT_VIDEO) < 0) {
        Error() << "Cannot initialize SDL.";
        std::exit(1);
    }
}

void Sdl2Application::createContext(Configuration* configuration) {
    if(!tryCreateContext(configuration)) {
        Error() << "Platform::Sdl2Application::createContext(): cannot create context:" << SDL_GetError();
        delete configuration;
        std::exit(1);

    } else delete configuration;
}

bool Sdl2Application::tryCreateContext(Configuration* configuration) {
    CORRADE_ASSERT(!context, "Platform::Sdl2Application::tryCreateContext(): context already created", false);

    /* Enable double buffering and 24bt depth buffer */
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);

    /* Multisampling */
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, configuration->sampleCount() > 1 ? 1 : 0);
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, configuration->sampleCount());

    /* Flags: if not hidden, set as shown */
    Uint32 flags(configuration->flags());
    if(!(configuration->flags() & Configuration::Flag::Hidden)) flags |= SDL_WINDOW_SHOWN;

    if(!(window = SDL_CreateWindow(configuration->title().c_str(),
            SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
            configuration->size().x(), configuration->size().y(),
            SDL_WINDOW_OPENGL|flags)))
        return false;

    if(!(context = SDL_GL_CreateContext(window))) {
        SDL_DestroyWindow(window);
        window = nullptr;
        return false;
    }

    /* This must be enabled, otherwise (on my NVidia) it crashes when creating
       VAO. WTF. */
    ExtensionWrangler::initialize(ExtensionWrangler::ExperimentalFeatures::Enable);

    /* Push resize event, so viewportEvent() is called at startup */
    SDL_Event* sizeEvent = new SDL_Event;
    sizeEvent->type = SDL_WINDOWEVENT;
    sizeEvent->window.event = SDL_WINDOWEVENT_RESIZED;
    sizeEvent->window.data1 = configuration->size().x();
    sizeEvent->window.data2 = configuration->size().y();
    SDL_PushEvent(sizeEvent);

    c = new Context;
    return true;
}

Sdl2Application::~Sdl2Application() {
    delete c;

    SDL_GL_DeleteContext(context);
    SDL_DestroyWindow(window);
    SDL_Quit();
}

int Sdl2Application::exec() {
    while(!(flags & Flag::Exit)) mainLoop();
    return 0;
}

void Sdl2Application::mainLoop() {
    SDL_Event event;

    while(SDL_PollEvent(&event)) {
        switch(event.type) {
            case SDL_WINDOWEVENT:
                switch(event.window.event) {
                    case SDL_WINDOWEVENT_RESIZED:
                        viewportEvent({event.window.data1, event.window.data2});
                        flags |= Flag::Redraw;
                        break;
                    case SDL_WINDOWEVENT_EXPOSED:
                        flags |= Flag::Redraw;
                        break;
                } break;

            case SDL_KEYDOWN:
            case SDL_KEYUP: {
                KeyEvent e(static_cast<KeyEvent::Key>(event.key.keysym.sym), fixedModifiers(event.key.keysym.mod));
                event.type == SDL_KEYDOWN ? keyPressEvent(e) : keyReleaseEvent(e);
            } break;

            case SDL_MOUSEBUTTONDOWN:
            case SDL_MOUSEBUTTONUP: {
                MouseEvent e(static_cast<MouseEvent::Button>(event.button.button), {event.button.x, event.button.y});
                event.type == SDL_MOUSEBUTTONDOWN ? mousePressEvent(e) : mouseReleaseEvent(e);
            } break;

            case SDL_MOUSEWHEEL:
                if(event.wheel.y != 0) {
                    MouseEvent e(event.wheel.y < 0 ? MouseEvent::Button::WheelUp : MouseEvent::Button::WheelDown, {event.wheel.x, event.wheel.y});
                    mousePressEvent(e);
                } break;

            case SDL_MOUSEMOTION: {
                MouseMoveEvent e({event.motion.x, event.motion.y}, {event.motion.xrel, event.motion.yrel});
                mouseMoveEvent(e);
                break;
            }

            case SDL_QUIT:
                flags |= Flag::Exit;
                return;
        }
    }

    if(flags & Flag::Redraw) {
        flags &= ~Flag::Redraw;
        drawEvent();
    } else SDL_WaitEvent(nullptr);
}

void Sdl2Application::setMouseLocked(bool enabled) {
    SDL_SetWindowGrab(window, enabled ? SDL_TRUE : SDL_FALSE);
    SDL_SetRelativeMouseMode(enabled ? SDL_TRUE : SDL_FALSE);
}

Sdl2Application::Configuration::Configuration(): _title("Magnum SDL2 Application"), _size(800, 600), _flags(Flag::Resizable), _sampleCount(0) {}
Sdl2Application::Configuration::~Configuration() = default;

Sdl2Application::InputEvent::Modifiers Sdl2Application::MouseEvent::modifiers() {
    if(modifiersLoaded) return _modifiers;
    modifiersLoaded = true;
    return _modifiers = fixedModifiers(SDL_GetModState());
}

Sdl2Application::InputEvent::Modifiers Sdl2Application::MouseMoveEvent::modifiers() {
    if(modifiersLoaded) return _modifiers;
    modifiersLoaded = true;
    return _modifiers = fixedModifiers(SDL_GetModState());
}

}}
<|endoftext|>


<commit_before>#include "FreeListAllocator.h"
#include "Utils.h"		/* CalculatePaddingWithHeader */
#include <stdlib.h>     /* malloc, free */
#include <cassert> 		/* assert		*/
#include <limits>		/* limits_max */

#ifdef _DEBUG
	#include <iostream>
#endif

FreeListAllocator::FreeListAllocator(const std::size_t totalSize, enum PlacementPolicy pPolicy, enum sPolicy);
	: Allocator(totalSize) {
	m_pPolicy = pPolicy;
	m_sPolicy = sPolicy;
}

void FreeListAllocator::Init() {
	if (m_freeList != nullptr){
		delete m_freeList;
	}
	if (m_start_ptr != nullptr){
		free(m_start_ptr);
		m_start_ptr = nullptr;
	}
	m_start_ptr = malloc(m_totalSize);

	this->Reset();
}

FreeListAllocator::~FreeListAllocator(){
	free(m_start_ptr);
	m_start_ptr = nullptr;
}

void* FreeListAllocator::Allocate(const std::size_t size, const std::size_t alignment){
	// Search through the free list for a free block that has enough space to allocate our data
	Node<BlockHeader> * affectedNode = this->Find(size);
	const int rest = affectedNode->size - size;
	if (rest > 0){
		// We have to split the block into the data block and a free block of size 'rest'
		Node<BlockHeader> * newFreeNode = (Node<BlockHeader> *)((std::size_t) affectedNode + size + 1);
		newFreeNode->data = BlockHeader { rest };
		m_freeList->insert(affectedNode, newFreeNode);
	}
	m_freeList->delete(affectedNode)

#ifdef _DEBUG
	std::cout << "A" << "\t@C " << (void*) affectedBlock << std::endl;
#endif

	return (void*) affectedBlock;
}

Node<BlockHeader> * FreeListAllocator::Find(const std::size_t size){
	switch(m_pPolicy){
		case FIND_FIRST:
			return FindFirst(size);
		case FIND_BEST:
			return FindBest(size);
		default:
			return nullptr;
	}
}

Node<BlockHeader> * FreeListAllocator::FindFirst(const std::size_t size){
	//Iterate list and return the first free block with a size >= than given size
	Node<BlockHeader> * it = m_freeList->head;
	while(it != nullptr){
		if (it->size >= size){
			return it;
		}
		it = it->next;
	}
	return nullptr;
}

Node<BlockHeader> * FreeListAllocator::FindBest(const std::size_t size){
	// Iterate WHOLE list keeping a pointer to the best fit
	std::size_t smallestDiff = 	std::numeric_limits<std::size_t>::max();
	Node<BlockHeader> * bestBlock = nullptr;
	Node<BlockHeader> * it = m_freeList->head;
	while(it != nullptr){
		if (it->size >= size && (it->size - size < smallestDiff)){
			bestBlock = it;
		}
		it = it->next;
	}
	return bestBlock;
}

void FreeListAllocator::Free(void* ptr){
	Node<BlockHeader> * freeNode = InsertFree(ptr);
	Coalescence(freeNode);
}

Node<BlockHeader> * FreeListAllocator::InsertFree(void * ptr){
	switch(m_sPolicy){
		case LIFO:
			return InsertFreeLIFO(ptr);
		case SORTED:
			return InsertFreeSorted(ptr);
	}
}

Node<BlockHeader> * FreeListAllocator::InsertFreeLIFO(void * ptr){
	// Insert it in a LIFO (or stack) fashion (at the beginning)
	Node<BlockHeader> * freeNode = (Node<BlockHeader> *) ptr;
	freeNode->data = BlockHeader { 3 }; //TODO SIZE???
	m_freeList.insert(nullptr, freeNode);

	return freeNode;
}

Node<BlockHeader> * FreeListAllocator::InsertFreeSorted(void * ptr){
	// Insert it in a sorted position by the address number
	Node<BlockHeader> * freeNode = (Node<BlockHeader> *) ptr;
	Node<BlockHeader> * it = m_freeList.head;
	while(it != nullptr){
		if ((std::size_t) ptr < (std::size_t) it->data.size){
			m_freeList->insert(it->previous, freeNode);
			break;
		}
		it = it->next;
	}
	return freeNode;

}

void FreeListAllocator::Coalescence(Node<BlockHeader> * freeNode){
	if ((std::size_t) freeNode->previous +
		(std::size_t) freeNode->previous->size + 1 == (std::size_t) freeNode){
		freeNode->data.size = BlockHeader { freeNode->previous->data.size + freeNode->data.size };
		m_freeList->delete(freeNode->previous);
	}

	if ((std::size_t) freeNode +
		(std::size_t) freeNode->size + 1 == (std::size_t) freeNode->next){
		freeNode->data.size = BlockHeader { freeNode->next->data.size + freeNode->data.size };
		m_freeList->delete(freeNode->next);
	}
}

void FreeListAllocator::Reset() {
	Node<BlockHeader> * firstNode = (Node<BlockHeader> *) m_start_ptr;
	firstNode->data = BlockHeader { m_totalSize };
	firstNode->previous = nullptr;
	firstNode->next = nullptr;

	// Init linkedlist with only one element
	m_freeList = DoublyLinkedList<BlockHeader>(m_start_ptr);
	m_freeList->insert(nullptr, firstNode);
}

// TODO HEADERS!!!!! and ALIGNMENT and SIZE when deallocate!<commit_msg>Added headers to allocated blocks in order to retrieve the size on free<commit_after>#include "FreeListAllocator.h"
#include "Utils.h"		/* CalculatePaddingWithHeader */
#include <stdlib.h>     /* malloc, free */
#include <cassert> 		/* assert		*/
#include <limits>		/* limits_max */

#ifdef _DEBUG
	#include <iostream>
#endif

FreeListAllocator::FreeListAllocator(const std::size_t totalSize, enum PlacementPolicy pPolicy, enum sPolicy);
	: Allocator(totalSize) {
	m_pPolicy = pPolicy;
	m_sPolicy = sPolicy;
}

void FreeListAllocator::Init() {
	if (m_freeList != nullptr){
		delete m_freeList;
	}
	if (m_start_ptr != nullptr){
		free(m_start_ptr);
		m_start_ptr = nullptr;
	}
	m_start_ptr = malloc(m_totalSize);

	this->Reset();
}

FreeListAllocator::~FreeListAllocator(){
	free(m_start_ptr);
	m_start_ptr = nullptr;
}

void* FreeListAllocator::Allocate(const std::size_t size, const std::size_t alignment){
	// Search through the free list for a free block that has enough space to allocate our data
	const std::size_t requiredSpace = size + sizeof(BlockHeader); //TODO ALIGNMENT!!!!
	Node<BlockHeader> * affectedNode = this->Find(requiredSpace);
	const int rest = affectedNode->size - requiredSpace;
	if (rest > 0){
		// We have to split the block into the data block and a free block of size 'rest'
		Node<BlockHeader> * newFreeNode = (Node<BlockHeader> *)((std::size_t) affectedNode + size + 1);
		newFreeNode->data = BlockHeader { rest };
		m_freeList->insert(affectedNode, newFreeNode);
	}
	m_freeList->delete(affectedNode)

	const std::size_t headerAddress = (std::size_t) affectedNode;
	const std::size_t dataAddress 	= headerAddress + (std::size_t) + sizeof(BlockHeader) + 1;
	(*(BlockHeader *) headerAddress).blockSize = BlockHeader { requiredSpace };	//TODO ALIGNMENT!!!!

#ifdef _DEBUG
	std::cout << "A" << "\t@C " << (void*) affectedBlock << std::endl;
#endif

	return (void*) dataAddress;
}

Node<BlockHeader> * FreeListAllocator::Find(const std::size_t size){
	switch(m_pPolicy){
		case FIND_FIRST:
			return FindFirst(size);
		case FIND_BEST:
			return FindBest(size);
		default:
			return nullptr;
	}
}

Node<BlockHeader> * FreeListAllocator::FindFirst(const std::size_t size){
	//Iterate list and return the first free block with a size >= than given size
	Node<BlockHeader> * it = m_freeList->head;
	while(it != nullptr){
		if (it->size >= size){
			return it;
		}
		it = it->next;
	}
	return nullptr;
}

Node<BlockHeader> * FreeListAllocator::FindBest(const std::size_t size){
	// Iterate WHOLE list keeping a pointer to the best fit
	std::size_t smallestDiff = 	std::numeric_limits<std::size_t>::max();
	Node<BlockHeader> * bestBlock = nullptr;
	Node<BlockHeader> * it = m_freeList->head;
	while(it != nullptr){
		if (it->size >= size && (it->size - size < smallestDiff)){
			bestBlock = it;
		}
		it = it->next;
	}
	return bestBlock;
}

void FreeListAllocator::Free(void* ptr){
	Node<BlockHeader> * freeNode = InsertFree(ptr);
	Coalescence(freeNode);
}

Node<BlockHeader> * FreeListAllocator::InsertFree(void * ptr){
	switch(m_sPolicy){
		case LIFO:
			return InsertFreeLIFO(ptr);
		case SORTED:
			return InsertFreeSorted(ptr);
	}
}

Node<BlockHeader> * FreeListAllocator::InsertFreeLIFO(void * ptr){
	// Insert it in a LIFO (or stack) fashion (at the beginning)
	const std::size_t currentAddress = (std::size_t) ptr;
	const std::size_t headerAddress = currentAddress - sizeof(BlockHeader);
	const BlockHeader * allocationHeader { (BlockHeader *) headerAddress};

	Node<BlockHeader> * freeNode = (Node<BlockHeader> *) ptr;
	freeNode->data = BlockHeader { allocationHeader->blockSize };
	m_freeList.insert(nullptr, freeNode);

	return freeNode;
}

Node<BlockHeader> * FreeListAllocator::InsertFreeSorted(void * ptr){
	// Insert it in a sorted position by the address number
	const std::size_t currentAddress = (std::size_t) ptr;
	const std::size_t headerAddress = currentAddress - sizeof(BlockHeader);
	const BlockHeader * allocationHeader { (BlockHeader *) headerAddress};

	Node<BlockHeader> * freeNode = (Node<BlockHeader> *) ptr;
	freeNode->data = BlockHeader { allocationHeader->blockSize };

	Node<BlockHeader> * it = m_freeList.head;
	while(it != nullptr){
		if ((std::size_t) ptr < (std::size_t) it->data.size){
			m_freeList->insert(it->previous, freeNode);
			break;
		}
		it = it->next;
	}
	return freeNode;

}

void FreeListAllocator::Coalescence(Node<BlockHeader> * freeNode){
	if ((std::size_t) freeNode->previous +
		(std::size_t) freeNode->previous->size + 1 == (std::size_t) freeNode){
		freeNode->data.size = BlockHeader { freeNode->previous->data.size + freeNode->data.size };
		m_freeList->delete(freeNode->previous);
	}

	if ((std::size_t) freeNode +
		(std::size_t) freeNode->size + 1 == (std::size_t) freeNode->next){
		freeNode->data.size = BlockHeader { freeNode->next->data.size + freeNode->data.size };
		m_freeList->delete(freeNode->next);
	}
}

void FreeListAllocator::Reset() {
	Node<BlockHeader> * firstNode = (Node<BlockHeader> *) m_start_ptr;
	firstNode->data = BlockHeader { m_totalSize };
	firstNode->previous = nullptr;
	firstNode->next = nullptr;

	// Init linkedlist with only one element
	m_freeList = DoublyLinkedList<BlockHeader>(m_start_ptr);
	m_freeList->insert(nullptr, firstNode);
}

// TODO and ALIGNMENT and <|endoftext|>