text:
/**************************************************************
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 *************************************************************/

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

#include "PresenterPaneAnimator.hxx"

#include "PresenterAnimation.hxx"
#include "PresenterAnimator.hxx"
#include "PresenterCanvasHelper.hxx"
#include "PresenterController.hxx"
#include "PresenterGeometryHelper.hxx"
#include "PresenterPaintManager.hxx"
#include "PresenterPaneContainer.hxx"
#include "PresenterPaneFactory.hxx"
#include "PresenterSprite.hxx"
#include "PresenterSpritePane.hxx"
#include "PresenterWindowManager.hxx"

#include <com/sun/star/awt/PosSize.hpp>
#include <com/sun/star/awt/XWindowPeer.hpp>
#include <com/sun/star/rendering/CompositeOperation.hpp>
#include <boost/bind.hpp>
#include <boost/bind/protect.hpp>
#include <boost/enable_shared_from_this.hpp>

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::drawing::framework;
using ::rtl::OUString;
using ::std::vector;

namespace sdext { namespace presenter {

namespace {

    class PaneGroup;

    class PresenterPaneAnimatorBase
        : public ::boost::enable_shared_from_this<PresenterPaneAnimatorBase>,
          public PresenterPaneAnimator
    {
    public:
        PresenterPaneAnimatorBase (
            const css::uno::Reference<css::drawing::framework::XResourceId>& rxPaneId,
            const ::rtl::Reference<PresenterController>& rpPresenterController,
            const bool bAnimate,
            const EndActions& rShowEndActions,
            const EndActions& rEndEndActions);
        virtual ~PresenterPaneAnimatorBase (void);

        typedef ::std::vector< ::boost::function<void()> > EndOperators;

        void ActivatePanes (void);
        void ActivatePane (
            const css::uno::Reference<css::drawing::framework::XResourceId>& rxPaneId);
        void RestoreFrozenWindows (void);
        void FreezePanes (const Reference<rendering::XSpriteCanvas>& rxCanvas);

    protected:
        ::rtl::Reference<PresenterController> mpPresenterController;
        ::rtl::Reference<PresenterPaneContainer> mpPaneContainer;
        ::rtl::Reference<PresenterWindowManager> mpWindowManager;
        ::std::vector< ::boost::shared_ptr<PaneGroup> > maPaneGroups;
        css::uno::Reference<css::drawing::framework::XResourceId> mxCenterPaneId;
        bool mbDoAnimation;
        EndActions maShowEndActions;
        EndActions maHideEndActions;

        void DeactivatePanes (void);
        void ResizePane (
            const css::uno::Reference<css::drawing::framework::XResourceId>& rxPaneId,
            const geometry::RealRectangle2D& rBox);
        void DeactivatePane (
            const css::uno::Reference<css::drawing::framework::XResourceId>& rxPaneId);
    };

    class UnfoldInCenterAnimator : public PresenterPaneAnimatorBase
    {
    public:
        UnfoldInCenterAnimator (
            const css::uno::Reference<css::drawing::framework::XResourceId>& rxPaneId,
            const ::rtl::Reference<PresenterController>& rpPresenterController,
            const bool bAnimate,
            const EndActions& rShowEndActions,
            const EndActions& rEndEndActions);

        virtual ~UnfoldInCenterAnimator (void);

        virtual void ShowPane (void);

        virtual void HidePane (void);

    private:
        geometry::RealRectangle2D maCenterPaneBox;

        void SetupPaneGroups (void);
        geometry::RealRectangle2D MovePanesAway (
            const css::geometry::RealRectangle2D& rFreeCenterArea);
    };

    class MoveInFromBottomAnimator : public PresenterPaneAnimatorBase
    {
    public:
        MoveInFromBottomAnimator(
            const css::uno::Reference<css::drawing::framework::XResourceId>& rxPaneId,
            const ::rtl::Reference<PresenterController>& rpPresenterController,
            const bool bAnimate,
            const EndActions& rShowEndActions,
            const EndActions& rEndEndActions);
        virtual ~MoveInFromBottomAnimator (void);

        virtual void ShowPane (void);
        virtual void HidePane (void);

    private:
        ::boost::shared_ptr<PresenterSprite> maNewPaneSprite;
        geometry::RealRectangle2D maCenterPaneBox;

        void CreateShowAnimation (
            const css::uno::Reference<css::drawing::framework::XResourceId>& rxPaneId,
            const EndOperators& rpEndOperators,
            const css::uno::Reference<css::rendering::XSpriteCanvas>& rxSpriteCanvas,
            const bool bAnimate,
            const css::geometry::RealPoint2D& rStartLocation,
            const css::geometry::RealPoint2D& rEndLocation);
    };

    class TransparentOverlayAnimator : public PresenterPaneAnimatorBase
    {
    public:
        TransparentOverlayAnimator(
            const css::uno::Reference<css::drawing::framework::XResourceId>& rxPaneId,
            const ::rtl::Reference<PresenterController>& rpPresenterController,
            const bool bAnimate,
            const EndActions& rShowEndActions,
            const EndActions& rEndEndActions);
        virtual ~TransparentOverlayAnimator (void);

        virtual void ShowPane (void);
        virtual void HidePane (void);

    private:
        PresenterSprite maBackgroundSprite;
        void CreateBackgroundSprite (void);
    };

    class PaneDescriptor
    {
    public:
        PresenterPaneContainer::SharedPaneDescriptor mpPaneDescriptor;

        PaneDescriptor (const PresenterPaneContainer::SharedPaneDescriptor& rpDescriptor);
        void Restore (void) const;
    private:
        double mnLeft;
        double mnTop;
        double mnRight;
        double mnBottom;
    };

    class MultiAnimation : public PresenterAnimation
    {
    public:
        typedef ::boost::function<void(double)> Animation;
        MultiAnimation (const sal_uInt32 nDuration);
        void AddAnimation (const Animation& rAnimation);
        virtual void Run (const double nProgress, const sal_uInt64 nCurrentTime);
    private:
        vector<Animation> maAnimations;
    };

    class PaneGroup
    {
    public:
        PaneGroup (void);
        ~PaneGroup (void);
        void AddPane (const PresenterPaneContainer::SharedPaneDescriptor& rpPane);
        void CreateSubstitution (const Reference<rendering::XSpriteCanvas>& rxCanvas);
        void ThawPanes (void);
        void Restore (void);
        ::boost::shared_ptr<PresenterSprite> GetSubstitution (void);
        css::geometry::RealRectangle2D GetOriginalBoundingBox (void) const;
        css::geometry::RealRectangle2D GetCurrentBoundingBox (void) const;
        void MovePanes (
            const double nXOffset,
            const double nYOffset,
            const ::rtl::Reference<PresenterWindowManager>& rpWindowManager);
        void ActivatePanes (void);
        void DeactivatePanes (void);
        void HidePanes (void);
        void ShowPanes (void);

    private:
        vector<PaneDescriptor> maPanes;
        awt::Rectangle maOriginalBoundingBox;
        css::geometry::RealRectangle2D maCurrentBoundingBox;
        ::boost::shared_ptr<PresenterSprite> mpSubstitution;

    };
    typedef ::boost::shared_ptr<PaneGroup> SharedPaneGroup;

    void InterpolatePosition (
        const ::boost::function<void(geometry::RealPoint2D)>& rSetter,
        double nP,
        const geometry::RealPoint2D rInitialBox,
        const geometry::RealPoint2D rFinalBox);

    template<typename T>
    void InterpolateValue (
        const ::boost::function<void(T)>& rSetter,
        double nP,
        const T aInitialValue,
        const T aFinalValue);

    void SpriteTransform(
        const rtl::Reference<PresenterPaneContainer>& rpPaneContainer,
        const Reference<XResourceId>& rxPaneId,
        const Reference<awt::XWindow>& rxSpriteOwnerWindow,
        const ::boost::shared_ptr<PresenterPaintManager>& rpPaintManager,
        const bool bAppear,
        const double nX,
        const double nInitialTop,
        const double nFinalTop,
        const double nP);

    void SpritePaneMove (
        const rtl::Reference<PresenterPaneContainer>& rpPaneContainer,
        const Reference<XResourceId>& rxPaneId,
        const geometry::RealPoint2D& rLocation);

    geometry::RealPoint2D GetLocation (const geometry::RealRectangle2D& rBox);
    geometry::RealSize2D GetSize (const geometry::RealRectangle2D& rBox);

} // end of anonymous namespace

//=============================================================================

::boost::shared_ptr<PresenterPaneAnimator> CreateUnfoldInCenterAnimator (
    const css::uno::Reference<css::drawing::framework::XResourceId>& rxPaneId,
    const ::rtl::Reference<PresenterController>& rpPresenterController,
    const bool bAnimate,
    const EndActions& rShowEndActions,
    const EndActions& rEndEndActions)
{
    return ::boost::shared_ptr<PresenterPaneAnimator>(
        new UnfoldInCenterAnimator(rxPaneId, rpPresenterController, bAnimate,
            rShowEndActions, rEndEndActions));
}

::boost::shared_ptr<PresenterPaneAnimator> CreateMoveInFromBottomAnimator (
        const css::uno::Reference<css::drawing::framework::XResourceId>& rxPaneId,
        const ::rtl::Reference<PresenterController>& rpPresenterController,
        const bool bAnimate,
        const EndActions& rShowEndActions,
        const EndActions& rEndEndActions)
{
    return ::boost::shared_ptr<PresenterPaneAnimator>(
        new MoveInFromBottomAnimator(rxPaneId, rpPresenterController, bAnimate,
            rShowEndActions, rEndEndActions));
}

::boost::shared_ptr<PresenterPaneAnimator> CreateTransparentOverlay (
        const css::uno::Reference<css::drawing::framework::XResourceId>& rxPaneId,
        const ::rtl::Reference<PresenterController>& rpPresenterController,
        const bool bAnimate,
        const EndActions& rShowEndActions,
        const EndActions& rEndEndActions)
{
    return ::boost::shared_ptr<PresenterPaneAnimator>(
        new TransparentOverlayAnimator(rxPaneId, rpPresenterController, bAnimate,
            rShowEndActions, rEndEndActions));
}

//===== PresenterPaneAnimator =================================================

namespace {

PresenterPaneAnimatorBase::PresenterPaneAnimatorBase (
    const css::uno::Reference<css::drawing::framework::XResourceId>& rxPaneId,
    const ::rtl::Reference<PresenterController>& rpPresenterController,
    const bool bAnimate,
    const EndActions& rShowEndActions,
    const EndActions& rHideEndActions)
    : mpPresenterController(rpPresenterController),
      mpPaneContainer(rpPresenterController->GetPaneContainer()),
      mpWindowManager(rpPresenterController->GetWindowManager()),
      maPaneGroups(),
      mxCenterPaneId(rxPaneId),
      mbDoAnimation(bAnimate),
      maShowEndActions(rShowEndActions),
      maHideEndActions(rHideEndActions)
{
}

PresenterPaneAnimatorBase::~PresenterPaneAnimatorBase (void)
{
}

void PresenterPaneAnimatorBase::FreezePanes (const Reference<rendering::XSpriteCanvas>& rxCanvas)
{
    ::std::vector<SharedPaneGroup>::const_iterator iGroup;
    for (iGroup=maPaneGroups.begin(); iGroup!=maPaneGroups.end(); ++iGroup)
    {
        (*iGroup)->CreateSubstitution(rxCanvas);
        (*iGroup)->GetSubstitution()->MoveTo(GetLocation((*iGroup)->GetOriginalBoundingBox()));
    }
}

void PresenterPaneAnimatorBase::ActivatePanes (void)
{
    ActivatePane(mxCenterPaneId);

    ::std::vector<SharedPaneGroup>::const_iterator iGroup;
    for (iGroup=maPaneGroups.begin(); iGroup!=maPaneGroups.end(); ++iGroup)
    {
        (*iGroup)->ShowPanes();
        (*iGroup)->ActivatePanes();
        (*iGroup)->GetSubstitution()->Hide();
    }

    mpWindowManager->Update();
}

void PresenterPaneAnimatorBase::DeactivatePanes (void)
{
    ::std::vector<SharedPaneGroup>::const_iterator iGroup;
    for (iGroup=maPaneGroups.begin(); iGroup!=maPaneGroups.end(); ++iGroup)
    {
        (*iGroup)->GetSubstitution()->Show();
        (*iGroup)->DeactivatePanes();
        (*iGroup)->HidePanes();
    }

    mpWindowManager->Update();
}

void PresenterPaneAnimatorBase::ResizePane (
    const Reference<drawing::framework::XResourceId>& rxPaneId,
    const geometry::RealRectangle2D& rBox)
{
    PresenterPaneContainer::SharedPaneDescriptor pDescriptor (
        mpPaneContainer->FindPaneId(rxPaneId));
    if (pDescriptor.get() != NULL)
    {
        mpWindowManager->SetPanePosSizeAbsolute (
            rxPaneId->getResourceURL(),
            rBox.X1,
            rBox.Y1,
            rBox.X2-rBox.X1,
            rBox.Y2-rBox.Y1);
        mpWindowManager->Layout();
        if ( ! pDescriptor->maSpriteProvider.empty())
        {
            pDescriptor->maSpriteProvider()->Resize(GetSize(rBox));
        }
    }
}

void PresenterPaneAnimatorBase::RestoreFrozenWindows (void)
{
    ::std::vector<SharedPaneGroup>::const_iterator iGroup;
    for (iGroup=maPaneGroups.begin(); iGroup!=maPaneGroups.end(); ++iGroup)
    {
        (*iGroup)->Restore();
        (*iGroup)->ShowPanes();
        (*iGroup)->ActivatePanes();
        (*iGroup)->GetSubstitution()->Hide();
    }
    maPaneGroups.clear();

    ActivatePane(mxCenterPaneId);

    mpWindowManager->Update();
}

void PresenterPaneAnimatorBase::ActivatePane (
    const Reference<drawing::framework::XResourceId>& rxPaneId)
{
    PresenterPaneContainer::SharedPaneDescriptor pDescriptor (
        mpPaneContainer->FindPaneId(rxPaneId));
    if (pDescriptor.get() != NULL)
        pDescriptor->SetActivationState(true);
}

void PresenterPaneAnimatorBase::DeactivatePane (
    const Reference<drawing::framework::XResourceId>& rxPaneId)
{
    PresenterPaneContainer::SharedPaneDescriptor pDescriptor (
        mpPaneContainer->FindPaneId(rxPaneId));
    if (pDescriptor.get() != NULL)
        pDescriptor->SetActivationState(false);
}

//===== UnfoldInCenterAnimator ================================================

UnfoldInCenterAnimator::UnfoldInCenterAnimator (
    const css::uno::Reference<css::drawing::framework::XResourceId>& rxPaneId,
    const ::rtl::Reference<PresenterController>& rpPresenterController,
    const bool bAnimate,
    const EndActions& rShowEndActions,
    const EndActions& rEndEndActions)
    : PresenterPaneAnimatorBase(rxPaneId, rpPresenterController, bAnimate,
        rShowEndActions, rEndEndActions)
{
}

UnfoldInCenterAnimator::~UnfoldInCenterAnimator (void)
{
}

void UnfoldInCenterAnimator::ShowPane (void)
{
    OSL_ASSERT(mpWindowManager.get()!=NULL);

    Reference<awt::XWindow> xParentWindow (mpWindowManager->GetParentWindow(), UNO_QUERY);
    if ( ! xParentWindow.is())
        return;

    Reference<rendering::XSpriteCanvas> xCanvas (mpWindowManager->GetParentCanvas(), UNO_QUERY);
    if ( ! xCanvas.is())
        return;

    Reference<rendering::XBitmap> xParentBitmap (xCanvas, UNO_QUERY);
    if ( ! xParentBitmap.is())
        return;

    Reference<rendering::XGraphicDevice> xDevice(xCanvas->getDevice());
    if ( ! xDevice.is())
        return;

    awt::Rectangle aWindowBox (xParentWindow->getPosSize());

    // Create two pane groups that will be moved together.  One contains the
    // notes view, the other group contains all other panes.
    SetupPaneGroups();

    // Setup the places where the two pane groups are moved to.
    maCenterPaneBox
        = MovePanesAway(geometry::RealRectangle2D(0,200,aWindowBox.Width, aWindowBox.Height-200));

    // Setup the final size of the new pane so that it fits into the space
    // between the two pane groups.
    ResizePane(mxCenterPaneId, maCenterPaneBox);

    // Avoid that the center pane updates its previews while being animated.
    DeactivatePane(mxCenterPaneId);

    // Replace the pane groups with sprites that look like the panes but can
    // be moved around much faster.
    FreezePanes(xCanvas);

    // The vertical center of the new pane.
    const double nY0 ((maPaneGroups[0]->GetOriginalBoundingBox().Y2
            + maPaneGroups[1]->GetOriginalBoundingBox().Y1) / 2);

    // Make sure that the new pane is painted once before the animation starts.
    SpriteTransform(
        mpPaneContainer,
        mxCenterPaneId,
        xParentWindow,
        mpPresenterController->GetPaintManager(),
        true,
        maCenterPaneBox.X1,
        nY0,
        maCenterPaneBox.Y1,
        0);
    PresenterPaneContainer::SharedPaneDescriptor pDescriptor (
        mpPaneContainer->FindPaneId(mxCenterPaneId));
    if (pDescriptor.get() != NULL)
    {
        mpPresenterController->GetPaintManager()->Invalidate(
            pDescriptor->mxBorderWindow,
            true);
    }

    // Animate the upper and lower window bitmaps.
    ::boost::shared_ptr<MultiAnimation> pMultiAnimation (
        new MultiAnimation(mbDoAnimation ? 500 : 0));

    // Animate the pane group sprites to be moved up or down.
    vector<SharedPaneGroup>::const_iterator iGroup;
    for (iGroup=maPaneGroups.begin(); iGroup!=maPaneGroups.end(); ++iGroup)
    {
        pMultiAnimation->AddAnimation(
            ::boost::bind(
                InterpolatePosition,
                ::boost::protect(::boost::bind(
                    &PresenterSprite::MoveTo, (*iGroup)->GetSubstitution(), _1)),
                _1,
                GetLocation((*iGroup)->GetOriginalBoundingBox()),
                GetLocation((*iGroup)->GetCurrentBoundingBox())));
    }

    // Animate the new center pane to expand.
    pMultiAnimation->AddAnimation(
        ::boost::bind(
            SpriteTransform,
            mpPaneContainer,
            mxCenterPaneId,
            xParentWindow,
            mpPresenterController->GetPaintManager(),
            true,
            maCenterPaneBox.X1,
            nY0,
            maCenterPaneBox.Y1,
            _1));

    // Call updateScreen after each animation step.
    if (xCanvas.is())
        pMultiAnimation->AddAnimation(
            ::boost::bind(&rendering::XSpriteCanvas::updateScreen, xCanvas, sal_False));

    // Activate the panes when the animation is over.
    pMultiAnimation->AddEndCallback(
        ::boost::bind(&PresenterPaneAnimatorBase::ActivatePanes, shared_from_this()));
    EndActions::const_iterator iAction;
    for (iAction=maShowEndActions.begin(); iAction!=maShowEndActions.end(); ++iAction)
        pMultiAnimation->AddEndCallback(*iAction);

    // Start the animation.
    ::boost::shared_ptr<PresenterAnimator> pAnimator (mpPresenterController->GetAnimator());
    OSL_ASSERT(pAnimator.get()!=NULL);
    pAnimator->AddAnimation(SharedPresenterAnimation(pMultiAnimation));

    mpWindowManager->Update();
}

void UnfoldInCenterAnimator::HidePane (void)
{
    OSL_ASSERT(mpWindowManager.get()!=NULL);

    Reference<awt::XWindow> xParentWindow (mpWindowManager->GetParentWindow(), UNO_QUERY);
    if ( ! xParentWindow.is())
        return;

    DeactivatePanes();
    DeactivatePane(mxCenterPaneId);

    ::boost::shared_ptr<PresenterAnimator> pAnimator (mpPresenterController->GetAnimator());
    const awt::Rectangle aWindowBox (xParentWindow->getPosSize());
    const rendering::ViewState aViewState (
        geometry::AffineMatrix2D(1,0,0, 0,1,0),
        NULL);
    const rendering::RenderState aRenderState (
        geometry::AffineMatrix2D(1,0,0, 0,1,0),
        NULL,
        Sequence<double>(4),
        rendering::CompositeOperation::SOURCE);

    // Animate the uppder and lower window bitmaps.
    Reference<rendering::XSpriteCanvas> xSpriteCanvas (mpWindowManager->GetParentCanvas(), UNO_QUERY);
    ::boost::shared_ptr<MultiAnimation> pMultiAnimation (new MultiAnimation(mbDoAnimation ? 500 : 1));

    vector<SharedPaneGroup>::const_iterator iGroup;
    for (iGroup=maPaneGroups.begin(); iGroup!=maPaneGroups.end(); ++iGroup)
    {
        pMultiAnimation->AddAnimation(
            ::boost::bind(
                InterpolatePosition,
                ::boost::protect(::boost::bind(
                    &PresenterSprite::MoveTo, (*iGroup)->GetSubstitution(), _1)),
                _1,
                GetLocation((*iGroup)->GetCurrentBoundingBox()),
                GetLocation((*iGroup)->GetOriginalBoundingBox())));
    }

    // Animate the new center pane to collapse.
    const double nY0 ((maPaneGroups[0]->GetOriginalBoundingBox().Y2
            + maPaneGroups[1]->GetOriginalBoundingBox().Y1) / 2);
    pMultiAnimation->AddAnimation(
        ::boost::bind(
            SpriteTransform,
            mpPaneContainer,
            mxCenterPaneId,
            xParentWindow,
            mpPresenterController->GetPaintManager(),
            false,
            maCenterPaneBox.X1,
            nY0,
            maCenterPaneBox.Y1,
            _1));

    if (mbDoAnimation)
    {
        pMultiAnimation->AddAnimation(
            ::boost::bind(&rendering::XSpriteCanvas::updateScreen, xSpriteCanvas, sal_False));
    }
    pMultiAnimation->AddEndCallback(
        ::boost::bind(&PresenterPaneAnimatorBase::RestoreFrozenWindows, shared_from_this()));
    EndActions::const_iterator iAction;
    for (iAction=maHideEndActions.begin(); iAction!=maHideEndActions.end(); ++iAction)
        pMultiAnimation->AddEndCallback(*iAction);

    pAnimator->AddAnimation(SharedPresenterAnimation(pMultiAnimation));
}

void UnfoldInCenterAnimator::SetupPaneGroups (void)
{
    maPaneGroups.clear();

    // Setup the upper pane group.
    SharedPaneGroup pUpperPanes (new PaneGroup());
    pUpperPanes->AddPane(mpPaneContainer->FindPaneURL(
        PresenterPaneFactory::msCurrentSlidePreviewPaneURL));
    pUpperPanes->AddPane(mpPaneContainer->FindPaneURL(
        PresenterPaneFactory::msNextSlidePreviewPaneURL));
    pUpperPanes->AddPane(mpPaneContainer->FindPaneURL(
        PresenterPaneFactory::msToolBarPaneURL));
    pUpperPanes->AddPane(mpPaneContainer->FindPaneURL(
        PresenterPaneFactory::msHelpPaneURL));
    maPaneGroups.push_back(pUpperPanes);

    // Setup the lower pane group.
    SharedPaneGroup pLowerPanes (new PaneGroup());
    pLowerPanes->AddPane(mpPaneContainer->FindPaneURL(
        PresenterPaneFactory::msNotesPaneURL));
    maPaneGroups.push_back(pLowerPanes);
}

geometry::RealRectangle2D UnfoldInCenterAnimator::MovePanesAway (
    const geometry::RealRectangle2D& rFreeCenterArea)
{
    SharedPaneGroup aUpperPanes = maPaneGroups[0];
    SharedPaneGroup aLowerPanes = maPaneGroups[1];

    // Move upper pane group out of the way.
    const double nTop (rFreeCenterArea.Y1);
    const double nUpperVerticalOffset (nTop - aUpperPanes->GetOriginalBoundingBox().Y2);
    aUpperPanes->MovePanes(0, nUpperVerticalOffset, mpWindowManager);

    // Move lower pane group out of the way.
    const double nBottom (rFreeCenterArea.Y2);
    const double nLowerVerticalOffset (nBottom - aLowerPanes->GetOriginalBoundingBox().Y1);
    aLowerPanes->MovePanes(0, nLowerVerticalOffset, mpWindowManager);

    return geometry::RealRectangle2D(
        ::std::min(
            aUpperPanes->GetOriginalBoundingBox().X1,
            aLowerPanes->GetOriginalBoundingBox().X1),
        nTop+20,
        ::std::max(
            aUpperPanes->GetOriginalBoundingBox().X2,
            aLowerPanes->GetOriginalBoundingBox().X2),
        nBottom-20);
}

//===== MoveInFromBottomAnimator ==============================================

MoveInFromBottomAnimator::MoveInFromBottomAnimator (
    const css::uno::Reference<css::drawing::framework::XResourceId>& rxPaneId,
    const ::rtl::Reference<PresenterController>& rpPresenterController,
    const bool bAnimate,
    const EndActions& rShowEndActions,
    const EndActions& rEndEndActions)
    : PresenterPaneAnimatorBase(rxPaneId, rpPresenterController, bAnimate,
        rShowEndActions, rEndEndActions),
      maNewPaneSprite()
{
}

MoveInFromBottomAnimator::~MoveInFromBottomAnimator (void)
{
}

void MoveInFromBottomAnimator::ShowPane (void)
{
    OSL_ASSERT(mpWindowManager.get()!=NULL);

    Reference<awt::XWindow> xParentWindow (mpWindowManager->GetParentWindow(), UNO_QUERY);
    if ( ! xParentWindow.is())
        return;

    Reference<rendering::XSpriteCanvas> xCanvas (mpWindowManager->GetParentCanvas(), UNO_QUERY);
    if ( ! xCanvas.is())
        return;

    Reference<rendering::XBitmap> xParentBitmap (xCanvas, UNO_QUERY);
    if ( ! xParentBitmap.is())
        return;

    Reference<rendering::XGraphicDevice> xDevice(xCanvas->getDevice());
    if ( ! xDevice.is())
        return;

    awt::Rectangle aWindowBox (xParentWindow->getPosSize());

    // Create a pane group that just contains the notes view.
    SharedPaneGroup pLowerPanes (new PaneGroup());
    pLowerPanes->AddPane(mpPaneContainer->FindPaneURL(
        PresenterPaneFactory::msNotesPaneURL));
    maPaneGroups.push_back(pLowerPanes);

    // Deactivate the panes that will take place in the animation.
    pLowerPanes->DeactivatePanes();
    DeactivatePane(mxCenterPaneId);

    // Set the size of the new pane.
    maCenterPaneBox = pLowerPanes->GetOriginalBoundingBox();
    ResizePane(mxCenterPaneId, maCenterPaneBox);

    geometry::RealPoint2D aStartLocation (maCenterPaneBox.X1, aWindowBox.Height);
    geometry::RealPoint2D aEndLocation (maCenterPaneBox.X1, maCenterPaneBox.Y1);

    // Get the sprite of the new pane, make it visible and move it to the
    // start location.
    PresenterPaneContainer::SharedPaneDescriptor pDescriptor (
        mpPaneContainer->FindPaneId(mxCenterPaneId));
    if (pDescriptor.get() != NULL)
    {
        if (pDescriptor->mxBorderWindow.is())
            pDescriptor->mxBorderWindow->setVisible(sal_True);

        maNewPaneSprite = pDescriptor->maSpriteProvider();
        if (maNewPaneSprite.get() != NULL)
        {
            maNewPaneSprite->MoveTo(aStartLocation);
            maNewPaneSprite->Show();
        }
        xCanvas->updateScreen(sal_False);
    }

    CreateShowAnimation(
        mxCenterPaneId,
        maShowEndActions,
        xCanvas,
        mbDoAnimation,
        aStartLocation,
        aEndLocation);

    mpWindowManager->Update();
}

void MoveInFromBottomAnimator::HidePane (void)
{
    OSL_ASSERT(mpWindowManager.get()!=NULL);

    Reference<awt::XWindow> xParentWindow (mpWindowManager->GetParentWindow(), UNO_QUERY);
    if ( ! xParentWindow.is())
        return;

    Reference<rendering::XSpriteCanvas> xCanvas (mpWindowManager->GetParentCanvas(), UNO_QUERY);
    if ( ! xCanvas.is())
        return;

    DeactivatePanes();
    DeactivatePane(mxCenterPaneId);

    SharedPaneGroup aPanes (maPaneGroups[0]);

    aPanes->ShowPanes();

    ::boost::shared_ptr<MultiAnimation> pMultiAnimation (
        new MultiAnimation(mbDoAnimation ? 500 : 0));
    awt::Rectangle aWindowBox (xParentWindow->getPosSize());

    // Animate the new center pane to collapse.
    pMultiAnimation->AddAnimation(
        ::boost::bind(
            InterpolatePosition,
            ::boost::protect(::boost::bind(&SpritePaneMove, mpPaneContainer, mxCenterPaneId, _1)),
            _1,
            geometry::RealPoint2D(maCenterPaneBox.X1, maCenterPaneBox.Y1),
            geometry::RealPoint2D(maCenterPaneBox.X1, aWindowBox.Height)));

    if (mbDoAnimation)
    {
        pMultiAnimation->AddAnimation(
            ::boost::bind(&rendering::XSpriteCanvas::updateScreen, xCanvas, sal_False));
    }
    pMultiAnimation->AddEndCallback(
        ::boost::bind(&PresenterPaneAnimatorBase::RestoreFrozenWindows, shared_from_this()));
    EndActions::const_iterator iAction;
    for (iAction=maHideEndActions.begin(); iAction!=maHideEndActions.end(); ++iAction)
        pMultiAnimation->AddEndCallback(*iAction);

    ::boost::shared_ptr<PresenterAnimator> pAnimator (mpPresenterController->GetAnimator());
    pAnimator->AddAnimation(SharedPresenterAnimation(pMultiAnimation));
}

void MoveInFromBottomAnimator::CreateShowAnimation (
    const Reference<drawing::framework::XResourceId>& rxPaneId,
    const EndOperators& rEndOperators,
    const Reference<rendering::XSpriteCanvas>& rxSpriteCanvas,
    const bool bAnimate,
    const geometry::RealPoint2D& rStartLocation,
    const geometry::RealPoint2D& rEndLocation)
{
    // Animate the uppder and lower window bitmaps.
    ::boost::shared_ptr<MultiAnimation> pMultiAnimation (new MultiAnimation(bAnimate ? 500 : 0));

    // Animate new pane to move in from the buttom.
    pMultiAnimation->AddAnimation(
        ::boost::bind(
            InterpolatePosition,
            ::boost::protect(::boost::bind(&SpritePaneMove, mpPaneContainer, rxPaneId, _1)),
            _1,
            rStartLocation,
            rEndLocation));

    // Call updateScreen after each animation step.
    if (rxSpriteCanvas.is())
        pMultiAnimation->AddAnimation(
            ::boost::bind(&rendering::XSpriteCanvas::updateScreen, rxSpriteCanvas, sal_False));

    // Activate the panes when the animation is over.
    pMultiAnimation->AddEndCallback(
        ::boost::bind(&PaneGroup::HidePanes, maPaneGroups[0]));
    pMultiAnimation->AddEndCallback(
        ::boost::bind(&PresenterPaneAnimatorBase::ActivatePane, shared_from_this(), mxCenterPaneId));
    EndActions::const_iterator iAction;
    for (iAction=rEndOperators.begin(); iAction!=rEndOperators.end(); ++iAction)
        pMultiAnimation->AddEndCallback(*iAction);

    // Start the animation.
    ::boost::shared_ptr<PresenterAnimator> pAnimator (mpPresenterController->GetAnimator());
    OSL_ASSERT(pAnimator.get()!=NULL);
    pAnimator->AddAnimation(SharedPresenterAnimation(pMultiAnimation));
}

//===== TransparentOverlayAnimator ============================================

TransparentOverlayAnimator::TransparentOverlayAnimator (
    const css::uno::Reference<css::drawing::framework::XResourceId>& rxPaneId,
    const ::rtl::Reference<PresenterController>& rpPresenterController,
    const bool bAnimate,
    const EndActions& rShowEndActions,
    const EndActions& rEndEndActions)
    : PresenterPaneAnimatorBase(
        rxPaneId,
        rpPresenterController,
        bAnimate,
        rShowEndActions,
        rEndEndActions),
      maBackgroundSprite()
{
}

TransparentOverlayAnimator::~TransparentOverlayAnimator (void)
{
}

void TransparentOverlayAnimator::ShowPane (void)
{
    EndActions::const_iterator iAction;
    for (iAction=maShowEndActions.begin(); iAction!=maShowEndActions.end(); ++iAction)
        (*iAction)();

    CreateBackgroundSprite();

    Reference<awt::XWindow> xParentWindow (mpWindowManager->GetParentWindow(), UNO_QUERY);
    if (xParentWindow.is())
    {
        const awt::Rectangle aWindowBox (xParentWindow->getPosSize());
        SharedPaneGroup pAllPanes (new PaneGroup());
        pAllPanes->AddPane(mpPaneContainer->FindPaneURL(
            PresenterPaneFactory::msCurrentSlidePreviewPaneURL));
        pAllPanes->AddPane(mpPaneContainer->FindPaneURL(
            PresenterPaneFactory::msNextSlidePreviewPaneURL));
        pAllPanes->AddPane(mpPaneContainer->FindPaneURL(
            PresenterPaneFactory::msToolBarPaneURL));
        pAllPanes->AddPane(mpPaneContainer->FindPaneURL(
            PresenterPaneFactory::msHelpPaneURL));
        pAllPanes->AddPane(mpPaneContainer->FindPaneURL(
            PresenterPaneFactory::msNotesPaneURL));
        maPaneGroups.push_back(pAllPanes);
        pAllPanes->DeactivatePanes();
        mpWindowManager->Update();
    }

    PresenterPaneContainer::SharedPaneDescriptor pDescriptor (
        mpPaneContainer->FindPaneId(mxCenterPaneId));
    if (pDescriptor.get() != NULL)
    {
        PresenterSpritePane* pPane = dynamic_cast<PresenterSpritePane*>(
            pDescriptor->mxPane.get());
        if (pPane != NULL)
            pPane->ShowTransparentBorder();

        pDescriptor->SetActivationState(true);
        if (pDescriptor->mxBorderWindow.is())
            pDescriptor->mxBorderWindow->setVisible(sal_True);
    }
}

void TransparentOverlayAnimator::HidePane (void)
{
    maPaneGroups[0]->ActivatePanes();
    EndActions::const_iterator iAction;
    for (iAction=maHideEndActions.begin(); iAction!=maHideEndActions.end(); ++iAction)
        (*iAction)();
    mpWindowManager->Update();
}

void TransparentOverlayAnimator::CreateBackgroundSprite (void)
{
    Reference<awt::XWindow> xParentWindow (mpWindowManager->GetParentWindow(), UNO_QUERY);
    Reference<rendering::XSpriteCanvas> xParentCanvas (mpWindowManager->GetParentCanvas(), UNO_QUERY);
    if (xParentWindow.is() && xParentCanvas.is())
    {
        const awt::Rectangle aWindowBox (xParentWindow->getPosSize());
        maBackgroundSprite.SetFactory(xParentCanvas);
        maBackgroundSprite.Resize(
            geometry::RealSize2D(aWindowBox.Width, aWindowBox.Height));
        maBackgroundSprite.MoveTo(
            geometry::RealPoint2D(aWindowBox.X, aWindowBox.Y));
        maBackgroundSprite.SetAlpha(0.5);
        maBackgroundSprite.Show();

        Reference<rendering::XCanvas> xCanvas (maBackgroundSprite.GetCanvas());

        if (xCanvas.is())
        {
            rendering::ViewState aViewState(
                geometry::AffineMatrix2D(1,0,0, 0,1,0),
                NULL);

            rendering::RenderState aRenderState(
                geometry::AffineMatrix2D(1,0,0, 0,1,0),
                NULL,
                Sequence<double>(4),
                rendering::CompositeOperation::SOURCE);
            PresenterCanvasHelper::SetDeviceColor(aRenderState, util::Color(0x80808080));

            Reference<rendering::XPolyPolygon2D> xPolygon (
                PresenterGeometryHelper::CreatePolygon(aWindowBox, xCanvas->getDevice()));
            if (xPolygon.is())
                xCanvas->fillPolyPolygon(
                    xPolygon,
                    aViewState,
                    aRenderState);
        }
    }
}

//===== PaneGroup =============================================================

PaneGroup::PaneGroup (void)
    : maPanes(),
      maOriginalBoundingBox(),
      maCurrentBoundingBox(),
      mpSubstitution(new PresenterSprite())
{
}

PaneGroup::~PaneGroup (void)
{
    mpSubstitution.reset();
}

void PaneGroup::AddPane (const PresenterPaneContainer::SharedPaneDescriptor& rpPane)
{
    OSL_ASSERT(rpPane.get() != NULL);

    if (rpPane->mxBorderWindow.is())
    {
        PaneDescriptor aDescriptor (rpPane);
        maPanes.push_back(aDescriptor);
        maOriginalBoundingBox = PresenterGeometryHelper::Union(
            maOriginalBoundingBox,
            rpPane->mxBorderWindow->getPosSize());
    }
}

void PaneGroup::CreateSubstitution (const Reference<rendering::XSpriteCanvas>& rxCanvas)
{
    // Get the bitmap of the background.
    Reference<rendering::XBitmap> xBackgroundBitmap (rxCanvas, UNO_QUERY);
    if ( ! xBackgroundBitmap.is())
        return;

    // Create the sprite.
    mpSubstitution->SetFactory(rxCanvas);
    mpSubstitution->Resize(
        geometry::RealSize2D(maOriginalBoundingBox.Width, maOriginalBoundingBox.Height));

    // Fill it with the background inside the bounding box.
    const rendering::ViewState aViewState (
        geometry::AffineMatrix2D(1,0,0, 0,1,0),
        NULL);
    const rendering::RenderState aRenderState (
        geometry::AffineMatrix2D(1,0,-maOriginalBoundingBox.X, 0,1,-maOriginalBoundingBox.Y),
        NULL,
        Sequence<double>(4),
        rendering::CompositeOperation::SOURCE);

    Reference<rendering::XCanvas> xSpriteCanvas (mpSubstitution->GetCanvas());
    if (xSpriteCanvas.is())
        xSpriteCanvas->drawBitmap(xBackgroundBitmap, aViewState, aRenderState);
}

void PaneGroup::Restore (void)
{
    vector<PaneDescriptor>::iterator iPane;
    for (iPane=maPanes.begin(); iPane!=maPanes.end(); ++iPane)
    {
        iPane->Restore();
    }
}

::boost::shared_ptr<PresenterSprite> PaneGroup::GetSubstitution (void)
{
    return mpSubstitution;
}

geometry::RealRectangle2D PaneGroup::GetOriginalBoundingBox (void) const
{
    return geometry::RealRectangle2D(
        maOriginalBoundingBox.X,
        maOriginalBoundingBox.Y,
        maOriginalBoundingBox.X + maOriginalBoundingBox.Width,
        maOriginalBoundingBox.Y + maOriginalBoundingBox.Height);
}

geometry::RealRectangle2D PaneGroup::GetCurrentBoundingBox (void) const
{
    return maCurrentBoundingBox;
}

void PaneGroup::MovePanes (
    const double nXOffset,
    const double nYOffset,
    const ::rtl::Reference<PresenterWindowManager>& rpWindowManager
    )
{
    awt::Rectangle aBBox;
    vector<PaneDescriptor>::iterator iPane;
    for (iPane=maPanes.begin(); iPane!=maPanes.end(); ++iPane)
    {
        awt::Rectangle aBox (iPane->mpPaneDescriptor->mxBorderWindow->getPosSize());
        aBox.X += sal_Int32(nXOffset);
        aBox.Y += sal_Int32(nYOffset);
        rpWindowManager->SetPanePosSizeAbsolute(
            iPane->mpPaneDescriptor->mxPaneId->getResourceURL(),
            aBox.X,
            aBox.Y,
            aBox.Width,
            aBox.Height);
        aBBox = PresenterGeometryHelper::Union(aBBox, aBox);
    }
    maCurrentBoundingBox = geometry::RealRectangle2D(
        aBBox.X, aBBox.Y, aBBox.X+aBBox.Width, aBBox.Y+aBBox.Height);
}

void PaneGroup::ActivatePanes (void)
{
    vector<PaneDescriptor>::iterator iPane;
    for (iPane=maPanes.begin(); iPane!=maPanes.end(); ++iPane)
    {
        iPane->mpPaneDescriptor->SetActivationState(true);
    }
}

void PaneGroup::DeactivatePanes (void)
{
    vector<PaneDescriptor>::iterator iPane;
    for (iPane=maPanes.begin(); iPane!=maPanes.end(); ++iPane)
    {
        iPane->mpPaneDescriptor->SetActivationState(false);
    }
}

void PaneGroup::ShowPanes (void)
{
    vector<PaneDescriptor>::iterator iPane;
    for (iPane=maPanes.begin(); iPane!=maPanes.end(); ++iPane)
    {
        iPane->mpPaneDescriptor->mxBorderWindow->setVisible(sal_True);
        iPane->mpPaneDescriptor->mxContentWindow->setVisible(sal_True);
    }
}

void PaneGroup::HidePanes (void)
{
    vector<PaneDescriptor>::iterator iPane;
    for (iPane=maPanes.begin(); iPane!=maPanes.end(); ++iPane)
    {
        iPane->mpPaneDescriptor->mxBorderWindow->setVisible(sal_False);
        iPane->mpPaneDescriptor->mxContentWindow->setVisible(sal_False);
    }
}

//===== PaneDescriptor ========================================================

PaneDescriptor::PaneDescriptor (const PresenterPaneContainer::SharedPaneDescriptor& rpDescriptor)
    : mpPaneDescriptor(rpDescriptor),
      mnLeft(rpDescriptor->mnLeft),
      mnTop(rpDescriptor->mnTop),
      mnRight(rpDescriptor->mnRight),
      mnBottom(rpDescriptor->mnBottom)
{
}

void PaneDescriptor::Restore (void) const
{
    mpPaneDescriptor->mnLeft = mnLeft;
    mpPaneDescriptor->mnTop = mnTop;
    mpPaneDescriptor->mnRight = mnRight;
    mpPaneDescriptor->mnBottom = mnBottom;
}

//===== MultiAnimation ========================================================

MultiAnimation::MultiAnimation (const sal_uInt32 nDuration)
    : PresenterAnimation(0, nDuration, 1000/50),
      maAnimations()
{
}

void MultiAnimation::AddAnimation (const Animation& rAnimation)
{
    maAnimations.push_back(rAnimation);
}

void MultiAnimation::Run (const double nProgress, const sal_uInt64 nCurrentTime)
{
    (void)nCurrentTime;
    vector<Animation>::const_iterator iAnimation (maAnimations.begin());
    vector<Animation>::const_iterator iEnd (maAnimations.end());
    for ( ; iAnimation!=iEnd; ++iAnimation)
        (*iAnimation)(nProgress);
}

//===== functors ==============================================================

void InterpolatePosition (
    const ::boost::function<void(geometry::RealPoint2D)>& rSetter,
    double nP,
    const geometry::RealPoint2D rInitialBox,
    const geometry::RealPoint2D rFinalBox)
{
    const double nQ (1 - nP);

    OSL_TRACE("InterpolatePosition %f\n", nP);
    rSetter(
        geometry::RealPoint2D(
            nQ * rInitialBox.X + nP * rFinalBox.X,
            nQ * rInitialBox.Y + nP * rFinalBox.Y));
}

template<typename T>
    void InterpolateValue (
        const ::boost::function<void(T)>& rSetter,
        double nP,
        const T aInitialValue,
        const T aFinalValue)
{
    const double nQ (1 - nP);

    rSetter(T(nQ * aInitialValue + nP * aFinalValue));
}

void SpriteTransform(
    const rtl::Reference<PresenterPaneContainer>& rpPaneContainer,
    const Reference<XResourceId>& rxPaneId,
    const Reference<awt::XWindow>& rxSpriteOwnerWindow,
    const ::boost::shared_ptr<PresenterPaintManager>& rpPaintManager,
    const bool bAppear,
    const double nX,
    const double nInitialTop,
    const double nFinalTop,
    const double nP)
{
    OSL_ASSERT(rpPaintManager.get()!=NULL);

    PresenterPaneContainer::SharedPaneDescriptor pDescriptor (
        rpPaneContainer->FindPaneId(rxPaneId));
    if (pDescriptor.get() != NULL
        && ! pDescriptor->maSpriteProvider.empty()
        && pDescriptor->mxBorderWindow.is())
    {
        ::boost::shared_ptr<PresenterSprite> pSprite (pDescriptor->maSpriteProvider());
        if (pSprite.get())
        {
            // There seems to be a problem with sprites not correctly
            // invalidating the background when being transformed.  As a
            // workaround invalidate the background in the bounding box of
            // the sprite before the transformation.
            rpPaintManager->Invalidate(
                rxSpriteOwnerWindow,
                awt::Rectangle(
                    sal::static_int_cast<sal_Int32>(pSprite->GetLocation().X),
                    sal::static_int_cast<sal_Int32>(pSprite->GetLocation().Y),
                    sal::static_int_cast<sal_Int32>(pSprite->GetSize().Width),
                    sal::static_int_cast<sal_Int32>(pSprite->GetSize().Height)));

            const double nYScale (bAppear ? nP : 1-nP);
            pSprite->Transform(geometry::AffineMatrix2D(
                1, 0, 0,
                0, nYScale, 0));
            pSprite->MoveTo(
                geometry::RealPoint2D(nX, nYScale*nFinalTop + (1-nYScale)*nInitialTop));
            pSprite->Show();

            pDescriptor->mxBorderWindow->setVisible(sal_True);
        }
    }
}

void SpritePaneMove (
    const rtl::Reference<PresenterPaneContainer>& rpPaneContainer,
    const Reference<XResourceId>& rxPaneId,
    const geometry::RealPoint2D& rLocation)
{
    PresenterPaneContainer::SharedPaneDescriptor pDescriptor (
        rpPaneContainer->FindPaneId(rxPaneId));
    if (pDescriptor.get() != NULL
        && ! pDescriptor->maSpriteProvider.empty()
        && pDescriptor->mxBorderWindow.is())
    {
        ::boost::shared_ptr<PresenterSprite> pSprite (pDescriptor->maSpriteProvider());
        if (pSprite.get() != NULL)
        {
            pDescriptor->mxBorderWindow->setVisible(sal_True);
            pSprite->MoveTo(rLocation);
        }
    }
}

geometry::RealPoint2D GetLocation (const geometry::RealRectangle2D& rBox)
{
    return geometry::RealPoint2D(rBox.X1, rBox.Y1);
}

geometry::RealSize2D GetSize (const geometry::RealRectangle2D& rBox)
{
    return geometry::RealSize2D(rBox.X2-rBox.X1, rBox.Y2-rBox.Y1);
}

} // end of anonymous namespace

} } // end of namespace ::sdext::presenter

ext: cxx

max_stars_repo_name: Grosskopf/openoffice

max_issues_repo_name: Grosskopf/openoffice

max_forks_repo_name: Grosskopf/openoffice


text:
#pragma once

#include <nano/lib/numbers.hpp>

#include <boost/optional/optional.hpp>

#include <atomic>
#include <functional>
#include <mutex>
#include <unordered_map>
#include <vector>

namespace nano
{
class node;
class distributed_work;
class root;

class distributed_work_factory final
{
public:
	distributed_work_factory (nano::node &);
	~distributed_work_factory ();
	bool make (nano::root const &, std::vector<std::pair<std::string, uint16_t>> const &, std::function<void(boost::optional<uint64_t>)> const &, uint64_t, boost::optional<nano::account> const & = boost::none);
	bool make (unsigned int, nano::root const &, std::vector<std::pair<std::string, uint16_t>> const &, std::function<void(boost::optional<uint64_t>)> const &, uint64_t, boost::optional<nano::account> const & = boost::none);
	void cancel (nano::root const &, bool const local_stop = false);
	void cleanup_finished ();
	void stop ();

	nano::node & node;
	std::unordered_map<nano::root, std::vector<std::weak_ptr<nano::distributed_work>>> items;
	std::mutex mutex;
	std::atomic<bool> stopped{ false };
};

class seq_con_info_component;
std::unique_ptr<seq_con_info_component> collect_seq_con_info (distributed_work_factory & distributed_work, const std::string & name);
}

ext: hpp

max_stars_repo_name: ArdeshirV/nano-node

max_issues_repo_name: ArdeshirV/nano-node

max_forks_repo_name: ArdeshirV/nano-node


text:
#include <cradle/io/standard_image_io.hpp>
#include <cradle/imaging/contiguous.hpp>
#include <boost/noncopyable.hpp>
#include <boost/format.hpp>
#include <cradle/io/file.hpp>
#include <cradle/external/devil.hpp>
#include <alia/color.hpp>

namespace cradle {

// Check for pending DevIL errors.
// If one is found, a corresponding exception is thrown.
// All errors are cleared out after a call to this function.
static void check_devil_errors(file_path const& file)
{
    ILenum error = ilGetError();
    while (ilGetError() != IL_NO_ERROR)
        ;
    if (error != IL_NO_ERROR)
    {
        throw image_io_error(
            file,
            str(boost::format("DevIL error: %s (0x%x)")
                % string(iluErrorString(error))
                % static_cast<unsigned>(error)));
    }
}

static void initialize_devil(file_path const& file)
{
    static bool initialized = false;
    if (initialized)
        return;
    initialized = true;
    if (ilGetInteger(IL_VERSION_NUM) < IL_VERSION)
    {
        throw image_io_error(
            file, "DevIL DLL version is older than compiled version.");
    }
    ilInit();
    ilEnable(IL_FILE_OVERWRITE);
    iluInit();
    check_devil_errors(file);
}

ILenum get_devil_file_format(image_file_format format)
{
    switch (format)
    {
        case image_file_format::AUTO:
            return IL_TYPE_UNKNOWN;
        case image_file_format::PNG:
            return IL_PNG;
        case image_file_format::TIFF:
            return IL_TIF;
        case image_file_format::BMP:
            return IL_BMP;
        case image_file_format::JPEG:
            return IL_JPG;
        case image_file_format::TGA:
            return IL_TGA;
        case image_file_format::RAW:
            return IL_RAW;
        case image_file_format::PCX:
            return IL_PCX;
        case image_file_format::PNM:
            return IL_PNM;
        default:
            return IL_TYPE_UNKNOWN;
    }
}

struct create_variant_image_fn
{
    image<2,variant,shared> result;
    vector2u size;
    variant_type_info type_info;
    void const* pixels;
    template<class Pixel>
    void operator()(Pixel)
    {
        image<2,Pixel,unique> tmp;
        create_image(tmp, size);
        size_t image_size = product(size) * sizeof(Pixel);
        memcpy(tmp.pixels.ptr, pixels, image_size);
        image<2,Pixel,shared> img;
        img = share(tmp);
        result = as_variant(img);
    }
};

void interpret_devil_type_info(
    variant_type_info& type_info,
    ILenum image_format, ILenum image_type,
    file_path const& file)
{
    switch (image_format)
    {
      case IL_RGB:
        type_info.format = pixel_format::RGB;
        break;
      case IL_RGBA:
        type_info.format = pixel_format::RGBA;
        break;
      case IL_LUMINANCE:
        type_info.format = pixel_format::GRAY;
        break;
      default:
        throw image_io_error(file, "unsupported pixel format");
    }

    switch (image_type)
    {
      case IL_BYTE:
        type_info.type = channel_type::INT8;
        break;
      case IL_UNSIGNED_BYTE:
        type_info.type = channel_type::UINT8;
        break;
      case IL_SHORT:
        type_info.type = channel_type::INT16;
        break;
      case IL_UNSIGNED_SHORT:
        type_info.type = channel_type::UINT16;
        break;
      case IL_INT:
        type_info.type = channel_type::INT32;
        break;
      case IL_UNSIGNED_INT:
        type_info.type = channel_type::UINT32;
        break;
      case IL_FLOAT:
        type_info.type = channel_type::FLOAT;
        break;
      case IL_DOUBLE:
        type_info.type = channel_type::DOUBLE;
        break;
      default:
        throw image_io_error(file, "unsupported channel type");
    }
}

void read_image_file(
    image<2,variant,shared>& img,
    file_path const& file,
    image_file_format format)
{
    initialize_devil(file);

    ILenum devil_file_format = get_devil_file_format(format);

    auto file_as_string = file.string<string>();
    ilLoad(devil_file_format,
        const_cast<ILstring>(file_as_string.c_str()));
    check_devil_errors(file);

    vector2u size;
    size[0] = ilGetInteger(IL_IMAGE_WIDTH);
    size[1] = ilGetInteger(IL_IMAGE_HEIGHT);
    if (ilGetInteger(IL_IMAGE_DEPTH) > 1)
        throw image_io_error(file, "wrong dimensionality");

    variant_type_info type_info;
    interpret_devil_type_info(type_info, ilGetInteger(IL_IMAGE_FORMAT),
        ilGetInteger(IL_IMAGE_TYPE), file);

    create_variant_image_fn fn;
    fn.type_info = type_info;
    fn.size = size;
    fn.pixels = ilGetData();
    dispatch_variant(type_info, fn);

    swap(fn.result, img);
}

class devil_image : boost::noncopyable
{
 public:
    devil_image() { ilGenImages(1, &name_); }
    ~devil_image() { ilDeleteImages(1, &name_); }
    void bind() const { ilBindImage(name_); }
 private:
    ILuint name_;
};

void write_image_file(
    file_path const& file,
    image<2,variant,const_view> const& img,
    image_file_format format)
{
    assert(is_contiguous(img));

    initialize_devil(file);

    ILenum devil_file_format = get_devil_file_format(format);

    ILenum devil_format;
    switch (img.pixels.type_info.format)
    {
     case pixel_format::RGB:
        devil_format = IL_RGB;
        break;
     case pixel_format::RGBA:
        devil_format = IL_RGBA;
        break;
     case pixel_format::GRAY:
        devil_format = IL_LUMINANCE;
        break;
     default:
        throw image_io_error(file, "unsupported pixel format");
    }

    ILenum devil_type;
    switch (img.pixels.type_info.type)
    {
     case channel_type::INT8:
        devil_type = IL_BYTE;
        break;
     case channel_type::UINT8:
        devil_type = IL_UNSIGNED_BYTE;
        break;
     case channel_type::INT16:
        devil_type = IL_SHORT;
        break;
     case channel_type::UINT16:
        devil_type = IL_UNSIGNED_SHORT;
        break;
     case channel_type::INT32:
        devil_type = IL_INT;
        break;
     case channel_type::UINT32:
        devil_type = IL_UNSIGNED_INT;
        break;
     case channel_type::FLOAT:
        devil_type = IL_FLOAT;
        break;
     case channel_type::DOUBLE:
        devil_type = IL_DOUBLE;
        break;
     default:
        throw image_io_error(file, "unsupported channel type");
    }

    contiguous_view<2,variant> cv(img);

    devil_image di;
    di.bind();
    ilTexImage(img.size[0], img.size[1], 1,
        get_channel_count(img.pixels.type_info.format),
        devil_format, devil_type, const_cast<void*>(cv.get().pixels.view));
    check_devil_errors(file);

    // DevIL's convention for row ordering seems to be upside-down with
    // respect to ours, so we need to flip the image to correct it.
    iluFlipImage();
    check_devil_errors(file);

    auto file_as_string = file.string<string>();
    //ilSave(devil_file_format,
    auto devil_file = const_cast<ILstring>(file_as_string.c_str());
    ilSaveImage(devil_file);
    check_devil_errors(file);
}

void read_image_file(
    image<2,int16_t,shared>& img,
    file_path const& file,
    image_file_format format)
{
    initialize_devil(file);

    ILenum devil_file_format = get_devil_file_format(format);

    auto file_as_string = file.string<string>();
    ilLoad(devil_file_format,
        const_cast<ILstring>(file_as_string.c_str()));
    check_devil_errors(file);

    vector2u size;
    size[0] = ilGetInteger(IL_IMAGE_WIDTH);
    size[1] = ilGetInteger(IL_IMAGE_HEIGHT);
    if (ilGetInteger(IL_IMAGE_DEPTH) > 1)
        throw image_io_error(file, "wrong dimensionality");

    variant_type_info type_info;
    interpret_devil_type_info(type_info, ilGetInteger(IL_IMAGE_FORMAT),
        ilGetInteger(IL_IMAGE_TYPE), file);

    image<2,int16_t,unique> tmp;
    create_image(tmp, size);
    size_t image_size = product(size) * sizeof(int16_t);
    memcpy(tmp.pixels.ptr, ilGetData(), image_size);
    img = share(tmp);
}

image2 read_standard_image_file(file_path const& file)
{
    image2 img;
    read_image_file(img, file);
    return img;
}

void write_standard_image_file(file_path const& file, image2 const& img)
{
    write_image_file(file, img);
}

}

ext: cpp

max_stars_repo_name: dotdecimal/open-cradle

max_issues_repo_name: dotdecimal/open-cradle

max_forks_repo_name: dotdecimal/open-cradle


text:
#include "image_processing.h"
#include <numeric>
#include <cfloat>
#include <Eigen/LU>
#include <QImage>

namespace ImageProcessing
{

template <typename Scalar>
Scalar crop(Scalar x, Scalar min_x, Scalar max_x)
{
    return std::max(std::min(x, max_x), min_x);
}

void Image::force_unity()
{
    const double sum = std::accumulate(pixels.begin(), pixels.end(), 0.0);
    assert(sum > 1e-16);
    for (int x = 0; x < width(); ++ x) for (int y = 0; y < height(); ++ y)
    {
        set_pixel(x, y, get_pixel(x, y) / sum);
    }
}

void Image::scale_to_unit()
{
    double max_value = - DBL_MAX;
    double min_value = + DBL_MAX;

    for (int x = 0; x < width(); ++ x) for (int y = 0; y < height(); ++ y)
    {
        const double value = get_pixel(x, y);
        max_value = std::max(max_value, value);
        min_value = std::min(min_value, value);
    }
    assert(max_value - min_value > 0.0);
    for (int x = 0; x < width(); ++ x) for (int y = 0; y < height(); ++ y)
    {
        set_pixel(x, y, (get_pixel(x, y) - min_value) / (max_value - min_value));
    }
}

void AbstractImage::save(const std::string &file_path) const
{
    QImage q_image(width(), height(), QImage::Format_ARGB32);
    for (int x = 0; x < width(); ++ x) for (int y = 0; y < height(); ++ y)
    {
        const IntColor color = get_color(x, y);
        q_image.setPixelColor(x, y, QColor(color(0), color(1), color(2), color(3)));
    }
    q_image.save(QString::fromStdString(file_path));
}

AbstractImage::IntColor Image::get_color(int x, int y) const
{
    const double value = crop(get_pixel(x, y), 0.0, 1.0);
    return IntColor(value * 255, value * 255, value * 255, 255);
}

AbstractImage::IntColor ColorImage::get_color(int x, int y) const
{
    Eigen::Vector4d color = get_rgba(x, y);
    for (int i : { 0, 1, 2, 3 }) color(i) = crop(color(i), 0.0, 1.0);
    return IntColor(color(0) * 255, color(1) * 255, color(2) * 255, color(3) * 255);
}

ColorImage::ColorImage(const std::string &file_path)
{
    QImage q_image(QString::fromStdString(file_path));
    width_  = q_image.width();
    height_ = q_image.height();

    assert(width() > 0 && height() > 0);

    rgba_ = std::vector<Image>(4, Image(width(), height()));
    for (int x = 0; x < width(); ++ x) for (int y = 0; y < height(); ++ y)
    {
        const QColor q_color = q_image.pixelColor(x, y);
        rgba_[0].set_pixel(x, y, q_color.redF());
        rgba_[1].set_pixel(x, y, q_color.greenF());
        rgba_[2].set_pixel(x, y, q_color.blueF());
        rgba_[3].set_pixel(x, y, q_color.alphaF());
    }
}

Image ColorImage::get_luminance() const
{
    Image new_image(width(), height());
    for (int x = 0; x < width(); ++ x) for (int y = 0; y < height(); ++ y)
    {
        const double r = rgba_[0].get_pixel(x, y);
        const double g = rgba_[1].get_pixel(x, y);
        const double b = rgba_[2].get_pixel(x, y);

        // https://en.wikipedia.org/wiki/Relative_luminance
        const double luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;

        new_image.set_pixel(x, y, luminance);
    }
    return new_image;
}

///////////////////////////////////////////////////////////////////////////////////////

Image apply_convolution(const Image& image, const Eigen::MatrixXd &kernel)
{
    const int w = image.width();
    const int h = image.height();

    const int kernel_size = kernel.rows();

    assert(kernel_size % 2 == 1);
    assert(kernel_size == kernel.cols());

    Image new_image(w, h);

    for (int x = 0; x < w; ++ x) for (int y = 0; y < h; ++ y)
    {
        double value = 0.0;
        for (int kernel_x = 0; kernel_x < kernel_size; ++ kernel_x)
        {
            for (int kernel_y = 0; kernel_y < kernel_size; ++ kernel_y)
            {
                const int original_image_x = crop(x + kernel_x - ((kernel_size - 1) / 2), 0, w - 1);
                const int original_image_y = crop(y + kernel_y - ((kernel_size - 1) / 2), 0, h - 1);

                value += kernel(kernel_x, kernel_y) * image.get_pixel(original_image_x, original_image_y);
            }
        }
        new_image.set_pixel(x, y, value);
    }
    return new_image;
}

Image calculate_guided_filter_kernel(const Image& image, int center_x, int center_y, int radius, double epsilon, bool force_positive)
{
    const int width  = image.width();
    const int height = image.height();

    const Image mean_I = ImageProcessing::apply_box_filter(image, radius);
    const Image corr_I = ImageProcessing::apply_box_filter(ImageProcessing::square(image), radius);
    const Image var_I  = ImageProcessing::subtract(corr_I, ImageProcessing::square(mean_I));
    const double I_seed = image.get_pixel(center_x, center_y);

    Image weight_map(width, height, 0.0);
    for (int x = center_x - radius; x <= center_x + radius; ++ x)
    {
        for (int y = center_y - radius; y <= center_y + radius; ++ y)
        {
            if (x < 0 || x >= width || y < 0 || y >= height) continue;

            const double I_j = image.get_pixel(x, y);
            double weight = 0.0;
            for (int k_x = 0; k_x < width; ++ k_x)
            {
                for (int k_y = 0; k_y < height; ++ k_y)
                {
                    bool range_j    = (k_x >= x - radius && k_x <= x + radius) && (k_y >= y - radius && k_y <= y + radius);
                    bool range_seed = (k_x >= center_x - radius && k_x <= center_x + radius) && (k_y >= center_y - radius && k_y <= center_y + radius);
                    if (!range_j || !range_seed) continue;

                    const double mu_k  = mean_I.get_pixel(k_x, k_y);
                    const double var_k = var_I.get_pixel(k_x, k_y);
                    weight += 1.0 + ((I_seed - mu_k) * (I_j - mu_k)) / (epsilon + var_k);
                }
            }
            if (force_positive) weight = std::max(0.0, weight);
            weight_map.set_pixel(x, y, weight);
        }
    }
    weight_map.force_unity();
    return weight_map;
}

Image calculate_gradient_magnitude(const Image& image)
{
    const int width  = image.width();
    const int height = image.height();
    const Image sobel_x = ImageProcessing::apply_sobel_filter_x(image);
    const Image sobel_y = ImageProcessing::apply_sobel_filter_y(image);

    Image gradient_magnitude = Image(width, height);
    for (int x = 0; x < width; ++ x)
    {
        for (int y = 0; y < height; ++ y)
        {
            const double g_x = sobel_x.get_pixel(x, y);
            const double g_y = sobel_y.get_pixel(x, y);
            const double value = std::sqrt(g_x * g_x + g_y * g_y);
            gradient_magnitude.set_pixel(x, y, value);
        }
    }
    return gradient_magnitude;
}

Image apply_guided_filter(const Image& input_image, const ColorImage& guidance_image, int radius, double epsilon)
{
    const int width  = input_image.width();
    const int height = input_image.height();

    assert(width == guidance_image.width());
    assert(height == guidance_image.height());

    const Image I_r = guidance_image.get_r();
    const Image I_g = guidance_image.get_g();
    const Image I_b = guidance_image.get_b();

    const Image mean_I_r = apply_box_filter(I_r, radius);
    const Image mean_I_g = apply_box_filter(I_g, radius);
    const Image mean_I_b = apply_box_filter(I_b, radius);

    const Image mean_p = apply_box_filter(input_image, radius);

    const Image mean_Ip_r = apply_box_filter(multiply(I_r, input_image), radius);
    const Image mean_Ip_g = apply_box_filter(multiply(I_g, input_image), radius);
    const Image mean_Ip_b = apply_box_filter(multiply(I_b, input_image), radius);

    const Image cov_Ip_r = subtract(mean_Ip_r, multiply(mean_I_r, mean_p));
    const Image cov_Ip_g = subtract(mean_Ip_g, multiply(mean_I_g, mean_p));
    const Image cov_Ip_b = subtract(mean_Ip_b, multiply(mean_I_b, mean_p));

    const Image var_I_rr = subtract(apply_box_filter(multiply(I_r, I_r), radius), multiply(mean_I_r, mean_I_r));
    const Image var_I_rg = subtract(apply_box_filter(multiply(I_r, I_g), radius), multiply(mean_I_r, mean_I_g));
    const Image var_I_rb = subtract(apply_box_filter(multiply(I_r, I_b), radius), multiply(mean_I_r, mean_I_b));
    const Image var_I_gg = subtract(apply_box_filter(multiply(I_g, I_g), radius), multiply(mean_I_g, mean_I_g));
    const Image var_I_gb = subtract(apply_box_filter(multiply(I_g, I_b), radius), multiply(mean_I_g, mean_I_b));
    const Image var_I_bb = subtract(apply_box_filter(multiply(I_b, I_b), radius), multiply(mean_I_b, mean_I_b));

    Image a_r(width, height);
    Image a_g(width, height);
    Image a_b(width, height);
    for (int x = 0; x < width; ++ x) for (int y = 0; y < height; ++ y)
    {
        Eigen::Matrix3d sigma;
        sigma << var_I_rr.get_pixel(x, y), var_I_rg.get_pixel(x, y), var_I_rb.get_pixel(x, y),
                 var_I_rg.get_pixel(x, y), var_I_gg.get_pixel(x, y), var_I_gb.get_pixel(x, y),
                 var_I_rb.get_pixel(x, y), var_I_gb.get_pixel(x, y), var_I_bb.get_pixel(x, y);

        const Eigen::Vector3d cov_Ip = { cov_Ip_r.get_pixel(x, y), cov_Ip_g.get_pixel(x, y), cov_Ip_b.get_pixel(x, y) };
        const Eigen::Vector3d a_xy = (sigma + epsilon * Eigen::Matrix3d::Identity()).inverse() * cov_Ip;

        a_r.set_pixel(x, y, a_xy(0));
        a_g.set_pixel(x, y, a_xy(1));
        a_b.set_pixel(x, y, a_xy(2));
    }

    const Image b = subtract(subtract(subtract(mean_p, multiply(a_r, mean_I_r)), multiply(a_g, mean_I_g)), multiply(a_b, mean_I_b));

    Image q = apply_box_filter(b, radius);
    q = add(q, multiply(apply_box_filter(a_r, radius), I_r));
    q = add(q, multiply(apply_box_filter(a_g, radius), I_g));
    q = add(q, multiply(apply_box_filter(a_b, radius), I_b));

    return q;
}

}

max_stars_repo_name: yaochaorui/color-unmixing

max_issues_repo_name: yaochaorui/color-unmixing

max_forks_repo_name: yaochaorui/color-unmixing


text:
/*
 Copyright (C) 2016 Quaternion Risk Management Ltd
 All rights reserved.

 This file is part of ORE, a free-software/open-source library
 for transparent pricing and risk analysis - http://opensourcerisk.org

 ORE is free software: you can redistribute it and/or modify it
 under the terms of the Modified BSD License.  You should have received a
 copy of the license along with this program.
 The license is also available online at <http://opensourcerisk.org>

 This program is distributed on the basis that it will form a useful
 contribution to risk analytics and model standardisation, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/

#include <iomanip>
#include <iostream>
using namespace std;

// Boost
#include <boost/timer/timer.hpp>
using namespace boost;
using boost::timer::cpu_timer;

// Boost.Test
#define BOOST_TEST_MODULE OREAnalyticsTestSuite
#include <boost/test/parameterized_test.hpp>
#include <boost/test/test_tools.hpp>
#include <boost/test/unit_test.hpp>
using boost::unit_test::test_suite;
using boost::unit_test::framework::master_test_suite;

#include <oret/oret.hpp>
using ore::test::setupTestLogging;

#ifdef BOOST_MSVC
#include <orea/auto_link.hpp>
#include <ored/auto_link.hpp>
#include <ql/auto_link.hpp>
#include <qle/auto_link.hpp>
#define BOOST_LIB_NAME boost_serialization
#include <boost/config/auto_link.hpp>
#define BOOST_LIB_NAME boost_regex
#include <boost/config/auto_link.hpp>
#endif

class OreaGlobalFixture {
public:
    OreaGlobalFixture() {
        int argc = master_test_suite().argc;
        char** argv = master_test_suite().argv;

        // Set up test logging
        setupTestLogging(argc, argv);
    }

    ~OreaGlobalFixture() { stopTimer(); }

    // Method called in destructor to log time taken
    void stopTimer() {
        t.stop();
        double seconds = t.elapsed().wall * 1e-9;
        int hours = int(seconds / 3600);
        seconds -= hours * 3600;
        int minutes = int(seconds / 60);
        seconds -= minutes * 60;
        cout << endl << "OREAnalytics tests completed in ";
        if (hours > 0)
            cout << hours << " h ";
        if (hours > 0 || minutes > 0)
            cout << minutes << " m ";
        cout << fixed << setprecision(0) << seconds << " s" << endl;
    }

private:
    // Timing the test run
    cpu_timer t;
};

// Breaking change in 1.65.0
// https://www.boost.org/doc/libs/1_65_0/libs/test/doc/html/boost_test/change_log.html
// Deprecating BOOST_GLOBAL_FIXTURE in favor of BOOST_TEST_GLOBAL_FIXTURE
#if BOOST_VERSION < 106500
BOOST_GLOBAL_FIXTURE(OreaGlobalFixture);
#else
BOOST_TEST_GLOBAL_FIXTURE(OreaGlobalFixture);
#endif

max_stars_repo_name: nvolfango/Engine

max_issues_repo_name: zhangjiayin/Engine

max_forks_repo_name: zhangjiayin/Engine


text:
/*=============================================================================
    Copyright (c) 2001-2011 Joel de Guzman

    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#if !defined(FUSION_FRONT_10022005_1618)
#define FUSION_FRONT_10022005_1618

#include <boost/fusion/iterator/value_of.hpp>
#include <boost/fusion/sequence/intrinsic/begin.hpp>
#include <boost/fusion/support/config.hpp>
#include <boost/mpl/front.hpp>

namespace boost {
namespace mpl {
template <typename Tag> struct front_impl;

template <> struct front_impl<fusion::fusion_sequence_tag> {
  template <typename Sequence>
  struct apply : fusion::result_of::value_of<
                     typename fusion::result_of::begin<Sequence>::type> {};
};
} // namespace mpl
} // namespace boost

#endif

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


text:
#ifndef NDNPH_PORT_QUEUE_BOOSTLF_HPP
#define NDNPH_PORT_QUEUE_BOOSTLF_HPP

#include "../../core/common.hpp"

#include <boost/lockfree/spsc_queue.hpp>

namespace ndnph {
namespace port_queue_boostlf {

/** @brief Generic thread-safe queue, implemented with Boost Lockfree library. */
template<typename T, size_t capacity>
class SafeQueue
{
public:
  using Item = T;

  bool push(Item item)
  {
    return m_queue.push(item);
  }

  std::tuple<Item, bool> pop()
  {
    Item item;
    bool ok = m_queue.pop(item);
    return std::make_tuple(std::move(item), ok);
  }

private:
  using Q = typename boost::lockfree::spsc_queue<T, boost::lockfree::capacity<capacity>>;
  Q m_queue;
};

} // namespace port_queue_boostlf

#ifdef NDNPH_PORT_QUEUE_BOOSTLF
namespace port {
template<typename T, size_t capacity>
using SafeQueue = port_queue_boostlf::SafeQueue<T, capacity>;
} // namespace port
#endif

} // namespace ndnph

#endif // NDNPH_PORT_QUEUE_BOOSTLF_HPP

max_stars_repo_name: Pesa/NDNph

max_issues_repo_name: Pesa/NDNph

max_forks_repo_name: Pesa/NDNph


text:
#include <map>
#include <vector>
#include <iostream>
#include <sstream>
#include <boost/algorithm/string/replace.hpp>

using namespace std;

static std::string dress(string s)
{
    boost::replace_all(s , string("'"), string("''"));
}

int main(int argc,char *argv[])
{

    string sample = "sample's";
    cout << "sample  " << sample << endl;
    boost::replace_all(sample , string("'"), string("''"));
    cout << "becomes " << sample << endl;
    cout << "sample  " << sample << endl;
    boost::replace_all(sample , string("''"), string("'"));
    cout << "becomes " << sample << endl;

}

max_issues_repo_name: vassalos/deep-learning-lang-detection

max_forks_repo_name: vassalos/deep-learning-lang-detection


text:
/*
 * Copyright 2020 © Centre Interdisciplinaire de développement en Cartographie des Océans (CIDCO), Tous droits réservés
 */

/*
 * File:   MonitorTest.hpp
 * Author: Jordan McManus
 */

#ifndef MONITORTEST_HPP
#define MONITORTEST_HPP

#include "catch.hpp"
#include <Eigen/Dense>
#include "../src/OpenSidescan/sidescan/sidescanfile.h"
#include "../src/OpenSidescan/sidescan/sidescanimager.h"
#include "../src/OpenSidescan/detector/roidetector.h"
#include "../src/thirdParty/MBES-lib/src/datagrams/DatagramParserFactory.hpp"
#include "../src/thirdParty/MBES-lib/src/datagrams/DatagramParser.hpp"
#include <string>
#include <map>
#include <vector>
#include <experimental/filesystem>
#include <atomic>
#include "../src/OpenSidescan/utilities/FileLockUtils.h"
#include "../src/OpenSidescan/utilities/SideScanFileProcessor.hpp"
#include "../src/OpenSidescan/utilities/DirectoryMonitor.hpp"
#include <string>
#include <iostream>
#include <cstring>

class SideScanFileProcessorForTest : public SideScanFileProcessor {
    //Sub class this to connect with OpenSideScan
public:

    void processFile(SidescanFile * f) {
        std::string filenameTest = "test/data/lockTest/s4.xtf";
        REQUIRE(filenameTest.compare(f->getFilename()) == 0);
        REQUIRE(f->getImages().size() == 2);
        REQUIRE(f->getImages()[1]->getObjects().size() == 1);

    }

    void reportProgress(std::string progress) {
    }

};

TEST_CASE("Test monitor") {

    std::string path = "test/data/lockTest/";

    Eigen::Vector3d leverArm;
    leverArm << 0.0, 0.0, 0.0;

    // setup region of interest detector
    int fastThreshold = 300;
    cv::FastFeatureDetector::DetectorType fastType = cv::FastFeatureDetector::TYPE_9_16;
    bool fastNonMaxSuppression = false;
    double dbscanEpsilon = 50;
    int dbscanMinimumPoints = 20;
    int mserDelta = 6;
    int mserMinimumArea = 320;
    int mserMaximumArea = 15000;
    bool mergeOverlappingObjects = true;

    RoiDetector * roiDetector = new RoiDetector(
            fastThreshold,
            fastType,
            fastNonMaxSuppression,
            dbscanEpsilon,
            dbscanMinimumPoints,
            mserDelta,
            mserMinimumArea,
            mserMaximumArea,
            mergeOverlappingObjects);

    SideScanFileProcessorForTest * processor = new SideScanFileProcessorForTest();
    DirectoryMonitor *monitor = new DirectoryMonitor(roiDetector, processor, leverArm);

    monitor->monitor(path);

    delete processor;
    delete monitor;
}

#endif /* MONITORTEST_HPP */

max_stars_repo_name: patcmorneau/OpenSidescan

max_issues_repo_name: patcmorneau/OpenSidescan

max_forks_repo_name: patcmorneau/OpenSidescan


text:
/** Copyright : Arthur Bit-Monnot (2013)  arthur.bit-monnot@laas.fr

This software is a computer program whose purpose is to [describe
functionalities and technical features of your software].

This software is governed by the CeCILL-B license under French law and
abiding by the rules of distribution of free software.  You can  use,
modify and/ or redistribute the software under the terms of the CeCILL-B
license as circulated by CEA, CNRS and INRIA at the following URL
"http://www.cecill.info".

As a counterpart to the access to the source code and  rights to copy,
modify and redistribute granted by the license, users are provided only
with a limited warranty  and the software's author,  the holder of the
economic rights,  and the successive licensors  have only  limited
liability.

In this respect, the user's attention is drawn to the risks associated
with loading,  using,  modifying and/or developing or reproducing the
software by the user in light of its specific status of free software,
that may mean  that it is complicated to manipulate,  and  that  also
therefore means  that it is reserved for developers  and  experienced
professionals having in-depth computer knowledge. Users are therefore
encouraged to load and test the software's suitability as regards their
requirements in conditions enabling the security of their systems and/or
data to be ensured and,  more generally, to use and operate it in the
same conditions as regards security.

The fact that you are presently reading this means that you have had
knowledge of the CeCILL-B license and that you accept its terms.
*/

#include <boost/foreach.hpp>

#include "reglc_graph.h"

using namespace std;
using namespace boost;

namespace RLC {

/*************************** DFA ************************/

  DFA::DFA(void) :
    start_state(0)
  {
    accepting_states.insert(0);
  }

DFA::DFA(int start, std::set<int> accepting, DfaEdgeList edges) :
start_state(start), accepting_states(accepting)
{
    DfaEdgeList::iterator it;
    for(it = edges.begin() ; it != edges.end() ; ++it) {
        ::Edge e;
        e.type = (EdgeMode) it->second;
        boost::add_edge(it->first.first, it->first.second, e, graph);
    }
}

DFA foot_subway_dfa()
{
    DfaEdgeList edges;
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(0, 0), FootEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(0, 0), TransferEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(0, 1), SubwayEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(1, 1), FootEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(1, 1), SubwayEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(1, 1), TransferEdge));
    set<int> accepting;
    accepting.insert(1);

    return DFA(0, accepting, edges);
}

DFA foot_dfa()
{
    DfaEdgeList edges;
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(0, 0), FootEdge));
    set<int> accepting;
    accepting.insert(0);

    return DFA(0, accepting, edges);
}

DFA bike_dfa()
{
    DfaEdgeList edges;
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(0, 0), BikeEdge));
    set<int> accepting;
    accepting.insert(0);

    return DFA(0, accepting, edges);
}

DFA car_dfa()
{
    DfaEdgeList edges;
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(0, 0), CarEdge));
    set<int> accepting;
    accepting.insert(0);

    return DFA(0, accepting, edges);
}

DFA pt_foot_dfa()
{
    DfaEdgeList edges;
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(0, 0), FootEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(0, 0), TransferEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(0, 0), SubwayEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(0, 0), BusEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(0, 0), TramEdge));
    set<int> accepting;
    accepting.insert(0);

    return DFA(0, accepting, edges);
}

DFA pt_car_dfa()
{
    DfaEdgeList edges;
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(0, 1), FootEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(0, 1), TransferEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(0, 1), SubwayEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(0, 1), BusEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(1, 1), FootEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(1, 1), SubwayEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(1, 1), TransferEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(1, 1), BusEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(0, 2), CarEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(2, 2), CarEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(2, 3), FootEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(1, 3), FootEdge));
    set<int> accepting;
    accepting.insert(3);

    return DFA(0, accepting, edges);
}

DFA bike_pt_dfa()
{
    DfaEdgeList edges;
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(0, 1), FootEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(0, 1), TransferEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(0, 1), SubwayEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(0, 1), BusEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(1, 1), FootEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(1, 1), SubwayEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(1, 1), TransferEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(1, 1), BusEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(0, 2), BikeEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(2, 2), BikeEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(2, 3), FootEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(1, 3), FootEdge));
    set<int> accepting;
    accepting.insert(3);

    return DFA(0, accepting, edges);
}

DFA pt_dfa()
{
    DfaEdgeList edges;
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(0, 0), FootEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(0, 0), TransferEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(0, 0), SubwayEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(0, 0), BusEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(0, 1), TransferEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(1, 2), SubwayEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(1, 2), BusEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(2, 2), FootEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(2, 2), TransferEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(2, 2), SubwayEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(2, 2), BusEdge));
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(2, 2), TransferEdge));

    set<int> accepting;
    accepting.insert(2);

    return DFA(0, accepting, edges);
}

DFA all_dfa()
{
    DfaEdgeList edges;
    edges.push_back(pair<pair<int,int>,EdgeMode>(pair<int,int>(0, 0), WhateverEdge));
    set<int> accepting;
    accepting.insert(0);

    return DFA(0, accepting, edges);
}

  std::map<std::string, DFA> get_dfas(void)
  {
    std::map<std::string, DFA> dfas = std::map<std::string, DFA>();

    dfas.insert(std::make_pair("foot-subway", foot_subway_dfa()));
    dfas.insert(std::make_pair("bike", bike_dfa()));
    dfas.insert(std::make_pair("foot", foot_dfa()));
    dfas.insert(std::make_pair("car", car_dfa()));
    dfas.insert(std::make_pair("pt-foot", pt_foot_dfa()));
    dfas.insert(std::make_pair("pt-car", pt_car_dfa()));
    dfas.insert(std::make_pair("bike-pt", bike_pt_dfa()));
    dfas.insert(std::make_pair("pt", pt_dfa()));
    dfas.insert(std::make_pair("all", all_dfa()));

    return dfas;
  }

  std::pair<bool, DFA> get_dfa(const std::string & name)
  {
    std::map<std::string, DFA> dfas = get_dfas();
    std::map<std::string, DFA>::iterator dfa = dfas.find(name);

      if(dfa == dfas.end())
	{
	  return std::make_pair(false, DFA());
	}
      else
	{
	  return std::make_pair(true, dfa->second);
	}
  }

  std::pair<bool, DFA> get_dfa(std::ostream & os, const std::string & name)
  {
    std::map<std::string, DFA> dfas = get_dfas();
    std::map<std::string, DFA>::iterator dfa = dfas.find(name);

    if(dfa == dfas.end())
      {
	std::pair<bool, DFA> dfa = get_dfa(name);

	os << "Unrecognized dfa '" << name << "'" << std::endl;

	os << "Available dfas are: " << std::endl;
	for(std::map<std::string, RLC::DFA>::const_iterator it = dfas.begin(); it != dfas.end(); ++it)
	  {
	    if(it != dfas.begin()) std::cerr << ", ";
	    os << "'" << it->first << "'";
	  }
	os << std::endl;

	return std::make_pair(false, DFA());
      }
    else
      {
	return std::make_pair(true, dfa->second);
      }
  }

/**************************** Graph ***********************************/

Graph::Graph(const Transport::Graph* transport, DFA dfa) :
AbstractGraph(true, transport),
transport(transport),
dfa(dfa)
{
}

RLC::Vertice Graph::source( const RLC::Edge & edge) const
{
    return RLC::Vertice(transport->source( edge.first ), boost::source(edge.second, dfa.graph));
}

RLC::Vertice Graph::target( const RLC::Edge & edge) const
{
    return RLC::Vertice(transport->target( edge.first ), boost::target(edge.second, dfa.graph));
}

std::list<RLC::Edge> Graph::out_edges( const RLC::Vertice & vertice) const
{
    std::list<RLC::Edge> edges;

    Graph_t::out_edge_iterator g_ei, g_end, dfa_beg, dfa_end, dfa_it;
    tie(g_ei,g_end) = boost::out_edges(vertice.first, transport->g);
    tie(dfa_beg,dfa_end) = boost::out_edges(vertice.second, dfa.graph);
    dfa_it = dfa_beg;

    while(g_ei != g_end && dfa_it != dfa_end) {
        while(dfa_it != dfa_end) {
            if(transport->map(*g_ei).type == dfa.graph[*dfa_it].type)
                edges.push_back(RLC::Edge(*g_ei, *dfa_it));
            ++dfa_it;
        }
        ++g_ei;
        dfa_it = dfa_beg;
    }
    return edges;
}

std::pair<bool, int> Graph::duration( const RLC::Edge & edge, const float start_sec, const int day) const
{
    return transport->duration_forward(edge.first, start_sec, day);
}

std::pair<bool, int> Graph::min_duration (const Edge & edge ) const
{
    return transport->min_duration(edge.first);
}

std::set<int> Graph::dfa_start_states() const
{
    std::set<int> states;
    states.insert(dfa.start_state);
    return states;
}

std::set<int> Graph::dfa_accepting_states() const
{
    return dfa.accepting_states;
}

int Graph::num_transport_vertices() const
{
    return transport->num_vertices();
}

int Graph::num_dfa_vertices() const
{
    return num_vertices(dfa.graph);
}

/****************** Backward Graph ************************/

BackwardGraph::BackwardGraph ( Graph* forward_graph ) :
AbstractGraph(false, forward_graph->transport),
forward_graph(forward_graph)
{
}

Vertice BackwardGraph::source ( const Edge & edge ) const
{
    return forward_graph->target( edge );
}

Vertice BackwardGraph::target ( const Edge & edge ) const
{
    return forward_graph->source( edge );
}

list< Edge > BackwardGraph::out_edges ( const Vertice & vertice ) const
{
    std::list<RLC::Edge> edges;

    Graph_t::in_edge_iterator g_ei, g_end, dfa_beg, dfa_end, dfa_it;
    tie(g_ei,g_end) = boost::in_edges(vertice.first, forward_graph->transport->g);
    tie(dfa_beg,dfa_end) = boost::in_edges(vertice.second, forward_graph->dfa.graph);
    dfa_it = dfa_beg;

    while(g_ei != g_end && dfa_it != dfa_end) {
        while(dfa_it != dfa_end) {
            if(forward_graph->transport->map(*g_ei).type == forward_graph->dfa.graph[*dfa_it].type)
                edges.push_back(RLC::Edge(*g_ei, *dfa_it));
            ++dfa_it;
        }
        ++g_ei;
        dfa_it = dfa_beg;
    }
    return edges;
}

std::pair<bool, int> BackwardGraph::duration ( const Edge & edge, const float start_sec, const int day ) const
{
    return forward_graph->transport->duration_backward(edge.first, start_sec, day);
}

std::pair<bool, int> BackwardGraph::min_duration ( const Edge & edge ) const
{
    return forward_graph->transport->min_duration(edge.first);
}

std::set< int > BackwardGraph::dfa_start_states() const
{
    return forward_graph->dfa_accepting_states();
}

std::set< int > BackwardGraph::dfa_accepting_states() const
{
    return forward_graph->dfa_start_states();
}

int BackwardGraph::num_transport_vertices() const
{
    return forward_graph->num_transport_vertices();
}

int BackwardGraph::num_dfa_vertices() const
{
    return forward_graph->num_dfa_vertices();
}

} // end RLC namespace


text:
/*! \file
    \brief A UTF-16 encoding.

    Copyright (C) 2019-2022 kaoru  https://www.tetengo.org/
*/

#if !defined(TETENGO_TEXT_ENCODING_UTF16_HPP)
#define TETENGO_TEXT_ENCODING_UTF16_HPP

#include <memory>
#include <string>
#include <string_view>

#include <boost/core/noncopyable.hpp>

namespace tetengo::text::encoding
{
    /*!
        \brief A UTF-16 encoding.
    */
    class utf16 : private boost::noncopyable
    {
    public:
        // types

        //! The string type.
        using string_type = std::string;

        //! The string view type.
        using string_view_type = std::string_view;

        //! The encoded string type.
        using encoded_string_type = std::u16string;

        //! The encoded string view type.
        using encoded_string_view_type = std::u16string_view;

        // static functions

        /*!
            \brief Returns the instance.

            \return The instance.
        */
        [[nodiscard]] static const utf16& instance();

        // constructors and destructor

        /*!
            \brief Destroys the encoding.
        */
        ~utf16();

        // functions

        /*!
            \brief Encodes a UTF-8 string to this encoding.

            \param utf8 A UTF-8 string.

            \return An encoded string.
        */
        [[nodiscard]] encoded_string_type encode(const string_view_type& utf8) const;

        /*!
            \brief Decodes a string in this encoding to UTF-8.

            \param string_ A string in this encoding.

            \return A decoded string.
        */
        [[nodiscard]] string_type decode(const encoded_string_view_type& string_) const;

    private:
        // types

        class impl;

        // variables

        const std::unique_ptr<impl> m_p_impl;

        // constructors

        utf16();
    };

}

#endif

max_stars_repo_name: tetengo/tetengo

max_issues_repo_name: tetengo/tetengo

max_forks_repo_name: tetengo/tetengo


text: #include <boost/mpl/aux_/basic_bind.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// Copyright 2019 Lawrence Livermore National Security, LLC and other Metall Project Developers.
// See the top-level COPYRIGHT file for details.
//
// SPDX-License-Identifier: (Apache-2.0 OR MIT)

#include <iostream>
#include <random>
#include <boost/random/mersenne_twister.hpp>
#include <metall/utility/random.hpp>
#include <metall/detail/time.hpp>

template <typename rand_engine_type>
auto run_bench(const uint64_t num_generate) {
  rand_engine_type rand_engine(123);
  const auto s =  metall::mtlldetail::elapsed_time_sec();
  for (uint64_t i = 0; i < num_generate; ++i) {
    [[maybe_unused]] volatile const uint64_t x = rand_engine();
  }
  const auto t =  metall::mtlldetail::elapsed_time_sec(s);
  return t;
}

int main() {

  const uint64_t num_generate = (1ULL << 20ULL);
  std::cout << "Generate " << num_generate << " values" << std::endl;

  std::cout << "std::mt19937_64  \t" << run_bench<std::mt19937_64>(num_generate) << std::endl;
  std::cout << "boost::mt19937_64\t" << run_bench<boost::random::mt19937_64>(num_generate) << std::endl;
  std::cout << "xoshiro512++     \t" << run_bench<metall::utility::rand_512>(num_generate) << std::endl;
  std::cout << "xoshiro1024++    \t" << run_bench<metall::utility::rand_1024>(num_generate) << std::endl;

  return 0;
}

max_stars_repo_name: dice-group/metall

max_issues_repo_name: dice-group/metall

max_forks_repo_name: dice-group/metall


text:
// GMTL is (C) Copyright 2001-2010 by Allen Bierbaum
// Distributed under the GNU Lesser General Public License 2.1 with an
// addendum covering inlined code. (See accompanying files LICENSE and
// LICENSE.addendum or http://www.gnu.org/copyleft/lesser.txt)

// Includes ====================================================================
#include <boost/python.hpp>
#include <gmtl-PlaneOps.h>

// Using =======================================================================
using namespace boost::python;

// Module ======================================================================
void _Export_gmtl_PlaneOps_h()
{
    def("findNearestPt", (float (*)(const gmtl::Plane<float> &, const gmtl::Point<float,3> &, gmtl::Point<float,3> &))&gmtl::findNearestPt);
    def("findNearestPt", (double (*)(const gmtl::Plane<double> &, const gmtl::Point<double,3> &, gmtl::Point<double,3> &))&gmtl::findNearestPt);
    def("reflect", (void (*)(gmtl::Point<float,3> &, const gmtl::Plane<float> &, const gmtl::Point<float,3> &))&gmtl::reflect);
    def("reflect", (void (*)(gmtl::Point<double,3> &, const gmtl::Plane<double> &, const gmtl::Point<double,3> &))&gmtl::reflect);
    def("distance", (double (*)(const gmtl::Plane<double> &, const gmtl::Point<double,3> &))&gmtl::distance);
    def("distance", (float (*)(const gmtl::Plane<float> &, const gmtl::Point<float,3> &))&gmtl::distance);
    def("whichSide", (gmtl::PlaneSide (*)(const gmtl::Plane<double> &, const gmtl::Point<double,3> &))&gmtl::whichSide);
    def("whichSide", (gmtl::PlaneSide (*)(const gmtl::Plane<float> &, const gmtl::Point<float,3> &))&gmtl::whichSide);
    def("whichSide", (gmtl::PlaneSide (*)(const gmtl::Plane<double> &, const gmtl::Point<double,3> &, const double &))&gmtl::whichSide);
    def("whichSide", (gmtl::PlaneSide (*)(const gmtl::Plane<float> &, const gmtl::Point<float,3> &, const float &))&gmtl::whichSide);
    def("isEqual", (bool (*)(const gmtl::Plane<float> &, const gmtl::Plane<float> &, const float &))&gmtl::isEqual);
    def("isEqual", (bool (*)(const gmtl::Plane<double> &, const gmtl::Plane<double> &, const double &))&gmtl::isEqual);
}


text:
/**
 * @file weight_size_visitor.hpp
 * @author Marcus Edel
 *
 * This file provides an abstraction for the WeightSize() function for
 * different layers and automatically directs any parameter to the right layer
 * type.
 *
 * mlpack is free software; you may redistribute it and/or modify it under the
 * terms of the 3-clause BSD license.  You should have received a copy of the
 * 3-clause BSD license along with mlpack.  If not, see
 * http://www.opensource.org/licenses/BSD-3-Clause for more information.
 */
#ifndef MLPACK_METHODS_ANN_VISITOR_WEIGHT_SIZE_VISITOR_HPP
#define MLPACK_METHODS_ANN_VISITOR_WEIGHT_SIZE_VISITOR_HPP

#include <mlpack/methods/ann/layer/layer_traits.hpp>
#include <mlpack/methods/ann/layer/layer_types.hpp>

#include <boost/variant.hpp>

namespace mlpack {
namespace ann {

/**
 * WeightSizeVisitor returns the number of weights of the given module.
 */
class WeightSizeVisitor : public boost::static_visitor<size_t>
{
 public:
  //! Return the number of weights.
  template<typename LayerType>
  size_t operator()(LayerType* layer) const;

 private:
  //! If the module doesn't implement the Parameters() or Model() function
  //! return 0.
  template<typename T, typename P>
  typename std::enable_if<
      !HasParametersCheck<T, P&(T::*)()>::value &&
      !HasModelCheck<T, std::vector<LayerTypes>&(T::*)()>::value, size_t>::type
  LayerSize(T* layer, P& output) const;

  //! Return the number of parameters if the module implements the Model()
  //! function.
  template<typename T, typename P>
  typename std::enable_if<
      !HasParametersCheck<T, P&(T::*)()>::value &&
      HasModelCheck<T, std::vector<LayerTypes>&(T::*)()>::value, size_t>::type
  LayerSize(T* layer, P& output) const;

  //! Return the number of parameters if the module implements the Parameters()
  //! function.
  template<typename T, typename P>
  typename std::enable_if<
      HasParametersCheck<T, P&(T::*)()>::value &&
      !HasModelCheck<T, std::vector<LayerTypes>&(T::*)()>::value, size_t>::type
  LayerSize(T* layer, P& output) const;

  //! Return the accumulated number of parameters if the module implements the
  //! Parameters() and Model() function.
  template<typename T, typename P>
  typename std::enable_if<
      HasParametersCheck<T, P&(T::*)()>::value &&
      HasModelCheck<T, std::vector<LayerTypes>&(T::*)()>::value, size_t>::type
  LayerSize(T* layer, P& output) const;
};

} // namespace ann
} // namespace mlpack

// Include implementation.
#include "weight_size_visitor_impl.hpp"

#endif

max_issues_repo_name: kosmaz/Mlpack

max_forks_repo_name: kosmaz/Mlpack