<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: CanvasUpdateRequester.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: kz $ $Date: 2008-04-03 14:06:05 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SD_PRESENTER_CANVAS_UPDATE_REQUESTER_HEADER
#define SD_PRESENTER_CANVAS_UPDATE_REQUESTER_HEADER

#include "precompiled_sd.hxx"

#include <com/sun/star/rendering/XSpriteCanvas.hpp>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include <sal/types.h>
#include <tools/solar.h>
#include <tools/link.hxx>
#include <vector>

namespace css = ::com::sun::star;

namespace sd { namespace presenter {

/** Each UpdateRequester handles update requests (calls to
    XCanvas::updateScreen()) for one shared canvas (a canvas that has one or
    more PresenterCanvas wrappers).  Multiple calls are collected and lead
    to a single call to updateScreen.
*/
class CanvasUpdateRequester : private ::boost::noncopyable
{
public:
    /** Return the Canvas UpdateRequester object for the given shared
        canvas.  A new object is created when it does not already exist.
    */
    static ::boost::shared_ptr<CanvasUpdateRequester> Instance (
        const css::uno::Reference<css::rendering::XSpriteCanvas>& rxCanvas);

    void RequestUpdate (const sal_Bool bUpdateAll);

private:
    CanvasUpdateRequester (const css::uno::Reference<css::rendering::XSpriteCanvas>& rxCanvas);
    ~CanvasUpdateRequester (void);
    class Deleter; friend class Deleter;

    typedef ::std::vector<
        ::std::pair<
            css::uno::Reference<css::rendering::XSpriteCanvas>,
           ::boost::shared_ptr<CanvasUpdateRequester> > > RequesterMap;
    static RequesterMap maRequesterMap;

    css::uno::Reference<css::rendering::XSpriteCanvas> mxCanvas;
    ULONG mnUserEventId;
    sal_Bool mbUpdateFlag;
    DECL_LINK(Callback, void*);
};

} } // end of namespace ::sd::presenter

#endif
<commit_msg>INTEGRATION: CWS changefileheaderm6 (1.2.4); FILE MERGED 2008/04/10 09:56:17 rt 1.2.4.1: #i87884# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: CanvasUpdateRequester.hxx,v $
 *
 * $Revision: 1.3 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef SD_PRESENTER_CANVAS_UPDATE_REQUESTER_HEADER
#define SD_PRESENTER_CANVAS_UPDATE_REQUESTER_HEADER

#include "precompiled_sd.hxx"

#include <com/sun/star/rendering/XSpriteCanvas.hpp>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include <sal/types.h>
#include <tools/solar.h>
#include <tools/link.hxx>
#include <vector>

namespace css = ::com::sun::star;

namespace sd { namespace presenter {

/** Each UpdateRequester handles update requests (calls to
    XCanvas::updateScreen()) for one shared canvas (a canvas that has one or
    more PresenterCanvas wrappers).  Multiple calls are collected and lead
    to a single call to updateScreen.
*/
class CanvasUpdateRequester : private ::boost::noncopyable
{
public:
    /** Return the Canvas UpdateRequester object for the given shared
        canvas.  A new object is created when it does not already exist.
    */
    static ::boost::shared_ptr<CanvasUpdateRequester> Instance (
        const css::uno::Reference<css::rendering::XSpriteCanvas>& rxCanvas);

    void RequestUpdate (const sal_Bool bUpdateAll);

private:
    CanvasUpdateRequester (const css::uno::Reference<css::rendering::XSpriteCanvas>& rxCanvas);
    ~CanvasUpdateRequester (void);
    class Deleter; friend class Deleter;

    typedef ::std::vector<
        ::std::pair<
            css::uno::Reference<css::rendering::XSpriteCanvas>,
           ::boost::shared_ptr<CanvasUpdateRequester> > > RequesterMap;
    static RequesterMap maRequesterMap;

    css::uno::Reference<css::rendering::XSpriteCanvas> mxCanvas;
    ULONG mnUserEventId;
    sal_Bool mbUpdateFlag;
    DECL_LINK(Callback, void*);
};

} } // end of namespace ::sd::presenter

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SlsViewOverlay.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: ihi $ $Date: 2006-11-14 14:37:02 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#include "view/SlsViewOverlay.hxx"

#include "controller/SlideSorterController.hxx"
#include "model/SlideSorterModel.hxx"
#include "model/SlsPageDescriptor.hxx"
#include "model/SlsPageEnumeration.hxx"
#include "view/SlideSorterView.hxx"
#include "SlideSorterViewShell.hxx"
#include "view/SlsLayouter.hxx"
#include "view/SlsPageObject.hxx"
#include "view/SlsPageObjectViewObjectContact.hxx"
#include "ViewShellBase.hxx"
#include "UpdateLockManager.hxx"

#include "Window.hxx"
#include "sdpage.hxx"

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

namespace {
class ShowingModeGuard
{
public:
    explicit ShowingModeGuard (::sd::slidesorter::view::OverlayBase& rOverlay,
        bool bHideAndSave = false)
        : mrOverlay (rOverlay),
          mbIsShowing (mrOverlay.IsShowing()),
          mbRestorePending(false)
    {
        if (mbIsShowing)
            if (bHideAndSave)
            {
                mrOverlay.GetViewOverlay().HideAndSave (
                    ::sd::slidesorter::view::ViewOverlay::OPT_XOR);
                mbRestorePending = true;
            }
            mrOverlay.Hide();
    }

    ~ShowingModeGuard (void)
    {
        if (mbIsShowing)
        {
            mrOverlay.Show();
            if (mbRestorePending)
                mrOverlay.GetViewOverlay().Restore ();
        }
    }

private:
    ::sd::slidesorter::view::OverlayBase& mrOverlay;
    bool mbIsShowing;
    bool mbRestorePending;
};
}

namespace sd { namespace slidesorter { namespace view {

//=====  ViewOverlay  =========================================================

ViewOverlay::ViewOverlay (SlideSorterViewShell& rViewShell)
    : mrViewShell (rViewShell),
      maSelectionRectangleOverlay(*this),
      maMouseOverIndicatorOverlay(*this),
      maInsertionIndicatorOverlay(*this),
      maSubstitutionOverlay(*this),
      mbSelectionRectangleWasVisible(false),
      mbMouseOverIndicatorWasVisible(false),
      mbInsertionIndicatorWasVisible(false),
      mbSubstitutionDisplayWasVisible(false),
      mnHideAndSaveLevel(0)
{
}

ViewOverlay::~ViewOverlay (void)
{
}

SelectionRectangleOverlay& ViewOverlay::GetSelectionRectangleOverlay (void)
{
    return maSelectionRectangleOverlay;
}

MouseOverIndicatorOverlay& ViewOverlay::GetMouseOverIndicatorOverlay (void)
{
    return maMouseOverIndicatorOverlay;
}

InsertionIndicatorOverlay& ViewOverlay::GetInsertionIndicatorOverlay (void)
{
    return maInsertionIndicatorOverlay;
}

SubstitutionOverlay& ViewOverlay::GetSubstitutionOverlay (void)
{
    return maSubstitutionOverlay;
}

void ViewOverlay::Paint (void)
{
    maSelectionRectangleOverlay.Paint();
    maMouseOverIndicatorOverlay.Paint();
    maInsertionIndicatorOverlay.Paint();
    maSubstitutionOverlay.Paint();
}

controller::SlideSorterController& ViewOverlay::GetController (void)
{
    return mrViewShell.GetSlideSorterController();
}

SlideSorterViewShell& ViewOverlay::GetViewShell (void)
{
    return mrViewShell;
}

void ViewOverlay::HideAndSave (OverlayPaintType eType)
{
    if (mnHideAndSaveLevel++ == 0)
    {
        // Remember the current state of the visiblities of the overlays.
        mbSelectionRectangleWasVisible = maSelectionRectangleOverlay.IsShowing();
        mbMouseOverIndicatorWasVisible = maMouseOverIndicatorOverlay.IsShowing();
        mbInsertionIndicatorWasVisible = maInsertionIndicatorOverlay.IsShowing();
        mbSubstitutionDisplayWasVisible = maSubstitutionOverlay.IsShowing();

        // Remember that we have saved the current state.
        meSavedStateType = eType;

        // Hide the overlays.
        if (eType==OPT_ALL || eType==OPT_XOR)
        {
            if (mbSelectionRectangleWasVisible)
                maSelectionRectangleOverlay.Hide();
        }
        if (mbSubstitutionDisplayWasVisible)
            maSubstitutionOverlay.Hide();

        if (eType==OPT_ALL || eType==OPT_PAINT)
        {
            if (mbMouseOverIndicatorWasVisible)
                maMouseOverIndicatorOverlay.Hide();
            if (mbInsertionIndicatorWasVisible)
                maInsertionIndicatorOverlay.Hide();
        }
    }
}

void ViewOverlay::Restore (void)
{
    if (--mnHideAndSaveLevel == 0)
    {
        if (meSavedStateType==OPT_ALL || meSavedStateType==OPT_PAINT)
        {
            if (mbInsertionIndicatorWasVisible)
                maInsertionIndicatorOverlay.Show();
            if (mbMouseOverIndicatorWasVisible)
                maMouseOverIndicatorOverlay.Show();
        }
        if (mbSubstitutionDisplayWasVisible)
            maSubstitutionOverlay.Show();
        if (meSavedStateType==OPT_ALL || meSavedStateType==OPT_XOR)
        {
            if (mbSelectionRectangleWasVisible)
                maSelectionRectangleOverlay.Show();
        }
    }
}

//=====  OverlayBase  =========================================================

OverlayBase::OverlayBase (ViewOverlay& rViewOverlay)
    : mrViewOverlay(rViewOverlay),
      mbIsShowing (false)
{
}

OverlayBase::~OverlayBase (void)
{
}

void OverlayBase::Paint (void)
{
}

bool OverlayBase::IsShowing (void)
{
    return mbIsShowing;
}

void OverlayBase::Toggle (void)
{
    if (IsShowing())
        Hide();
    else
        Show();
}

void OverlayBase::Show (void)
{
    if ( ! IsShowing())
    {
        mbIsShowing = true;
        Paint ();
    }
}

void OverlayBase::Hide (void)
{
    if (IsShowing())
    {
        mbIsShowing = false;
        Paint ();
    }
}

ViewOverlay& OverlayBase::GetViewOverlay (void)
{
    return mrViewOverlay;
}

//=====  SubstitutionOverlay  =================================================

SubstitutionOverlay::SubstitutionOverlay (ViewOverlay& rViewOverlay)
    : OverlayBase(rViewOverlay)
{
}

SubstitutionOverlay::~SubstitutionOverlay (void)
{
}

void SubstitutionOverlay::Paint (void)

{
    ::osl::MutexGuard aGuard (maMutex);

    SubstitutionShapeList::const_iterator aShape (maShapes.begin());
    SubstitutionShapeList::const_iterator aShapeEnd (maShapes.end());
    while (aShape!=aShapeEnd)
    {
        mrViewOverlay.GetViewShell().DrawMarkRect (*aShape);
        aShape++;
    }

    OverlayBase::Paint();
}

void SubstitutionOverlay::Create (
    model::PageEnumeration& rSelection,
    const Point& rPosition)
{
    ShowingModeGuard aGuard (*this);
    maPosition = rPosition;

    maShapes.clear();
    while (rSelection.HasMoreElements())
    {
        maShapes.push_back(
            rSelection.GetNextElement()->GetPageObject()->GetCurrentBoundRect());
    }
}

void SubstitutionOverlay::Clear (void)
{
    ShowingModeGuard aGuard (*this);

    maShapes.clear();
}

void SubstitutionOverlay::Move (const Point& rOffset)
{
    SetPosition (maPosition + rOffset);
}

void SubstitutionOverlay::SetPosition (const Point& rPosition)
{
    ShowingModeGuard aGuard (*this);
    Point rOffset = rPosition - maPosition;

    SubstitutionShapeList::iterator aShape (maShapes.begin());
    SubstitutionShapeList::const_iterator aShapeEnd (maShapes.end());
    for (;aShape!=aShapeEnd; aShape++)
        aShape->SetPos (aShape->TopLeft() + rOffset);

    maPosition = rPosition;
}

const Point& SubstitutionOverlay::GetPosition (void) const
{
    return maPosition;
}

//=====  SelectionRectangleOverlay  ===========================================

SelectionRectangleOverlay::SelectionRectangleOverlay (
    ViewOverlay& rViewOverlay)
    : OverlayBase (rViewOverlay),
      maAnchor(0,0),
      maSecondCorner(0,0)
{
}

void SelectionRectangleOverlay::Paint (void)
{
    //  mrViewOverlay.GetViewShell().DrawMarkRect (maSelectionRectangle);
}

void SelectionRectangleOverlay::Show (void)
{
    if ( ! mbIsShowing)
    {
        SlideSorterView& rView (mrViewOverlay.GetViewShell().GetSlideSorterController().GetView());
        rView.BegEncirclement(maAnchor);
        rView.MovEncirclement(maSecondCorner);
        OverlayBase::Show();
    }
}

void SelectionRectangleOverlay::Hide (void)
{
    if (mbIsShowing)
    {
        mrViewOverlay.GetViewShell().GetSlideSorterController().GetView().EndEncirclement();
        OverlayBase::Hide();
    }
}

Rectangle SelectionRectangleOverlay::GetSelectionRectangle (void)
{
    return Rectangle(maAnchor, maSecondCorner);
}

void SelectionRectangleOverlay::Start (const Point& rAnchor)
{
    maAnchor = rAnchor;
    maSecondCorner = rAnchor;
    mrViewOverlay.GetViewShell().GetSlideSorterController().GetView().BegEncirclement(maAnchor);
    OverlayBase::Show();
}

void SelectionRectangleOverlay::Update (const Point& rSecondCorner)
{
    maSecondCorner = rSecondCorner;
    mrViewOverlay.GetViewShell().GetSlideSorterController().GetView().MovEncirclement(maSecondCorner);
}

//=====  InsertionIndicatorOverlay  ===========================================

InsertionIndicatorOverlay::InsertionIndicatorOverlay (
    ViewOverlay& rViewOverlay)
    : OverlayBase (rViewOverlay)
{
}

void InsertionIndicatorOverlay::SetPositionAndSize (
    const Rectangle& aNewBoundingBox)
{
    if (maBoundingBox != aNewBoundingBox)
    {
        ShowingModeGuard aGuard (*this, true);

        maBoundingBox = aNewBoundingBox;
    }
}

void InsertionIndicatorOverlay::Paint (void)
{
    Color aColor;
    if (mbIsShowing)
        aColor = Application::GetSettings().GetStyleSettings().GetFontColor();
    else
        aColor = Application::GetSettings().GetStyleSettings().GetWindowColor();
    mrViewOverlay.GetViewShell().DrawFilledRect (
        maBoundingBox,
        aColor,
        aColor);
}

void InsertionIndicatorOverlay::SetPosition (const Point& rPoint)
{
    static const bool bAllowHorizontalInsertMarker = true;
    Layouter& rLayouter (
        mrViewOverlay.GetController().GetView().GetLayouter());
    USHORT nPageCount
        = mrViewOverlay.GetController().GetModel().GetPageCount();

    sal_Int32 nInsertionIndex = rLayouter.GetInsertionIndex (rPoint,
        bAllowHorizontalInsertMarker);
    if (nInsertionIndex >= nPageCount)
        nInsertionIndex = nPageCount-1;
    sal_Int32 nDrawIndex = nInsertionIndex;

    bool bVertical = false;
    bool bLeftOrTop = false;
    if (nInsertionIndex >= 0)
    {
        // Now that we know where to insert, we still have to determine
        // where to draw the marker.  There are two decisions to make:
        // 1. Draw a vertical or a horizontal insert marker.
        //    The horizontal one may only be chosen when there is only one
        //    column.
        // 2. The vertical (standard) insert marker may be painted left to
        //    the insert page or right of the previous one.  When both pages
        //    are in the same row this makes no difference.  Otherwise the
        //    posiotions are at the left and right ends of two rows.

        Point aPageCenter (rLayouter.GetPageObjectBox (
            nInsertionIndex).Center());

        if (bAllowHorizontalInsertMarker
            && rLayouter.GetColumnCount() == 1)
        {
            bVertical = false;
            bLeftOrTop = (rPoint.Y() <= aPageCenter.Y());
        }
        else
        {
            bVertical = true;
            bLeftOrTop = (rPoint.X() <= aPageCenter.X());
        }

        // Add one when the mark was painted below or to the right of the
        // page object.
        if ( ! bLeftOrTop)
            nInsertionIndex += 1;
    }

    mnInsertionIndex = nInsertionIndex;

    Rectangle aBox;
    if (mnInsertionIndex >= 0)
        aBox = rLayouter.GetInsertionMarkerBox (
            nDrawIndex,
            bVertical,
            bLeftOrTop);
    SetPositionAndSize (aBox);
}

sal_Int32 InsertionIndicatorOverlay::GetInsertionPageIndex (void) const
{
    return mnInsertionIndex;
}

//=====  MouseOverIndicatorOverlay  ===========================================

MouseOverIndicatorOverlay::MouseOverIndicatorOverlay (
    ViewOverlay& rViewOverlay)
    : OverlayBase (rViewOverlay),
      mpPageUnderMouse()
{
}

void MouseOverIndicatorOverlay::SetSlideUnderMouse (
    const model::SharedPageDescriptor& rpDescriptor)
{
    SlideSorterViewShell& rViewShell (mrViewOverlay.GetViewShell());
    if ( ! rViewShell.GetViewShellBase().GetUpdateLockManager().IsLocked())
    {
        model::SharedPageDescriptor pDescriptor;
        if ( ! mpPageUnderMouse.expired())
        {
            try
            {
                pDescriptor = model::SharedPageDescriptor(mpPageUnderMouse);
            }
            catch (::boost::bad_weak_ptr)
            {
            }
        }

         if (pDescriptor != rpDescriptor)
        {
            ShowingModeGuard aGuard (*this, true);

            mpPageUnderMouse = rpDescriptor;
        }
    }
}

void MouseOverIndicatorOverlay::Paint (void)
{
    if ( ! mpPageUnderMouse.expired())
    {
        model::SharedPageDescriptor pDescriptor;
        try
        {
            pDescriptor = model::SharedPageDescriptor(mpPageUnderMouse);
        }
        catch (::boost::bad_weak_ptr)
        {
        }

        if (pDescriptor.get() != NULL)
        {
            SlideSorterViewShell& rViewShell (mrViewOverlay.GetViewShell());
            if ( ! rViewShell.GetViewShellBase().GetUpdateLockManager().IsLocked())
            {
                SlideSorterView& rView (rViewShell.GetSlideSorterController().GetView());
                OutputDevice* pDevice = rView.GetWindow();
                PageObjectViewObjectContact* pContact = pDescriptor->GetViewObjectContact();
                if (pDevice != NULL
                    && pContact != NULL)
                {
                    pContact->PaintFrame(*pDevice, mbIsShowing);
                }
            }
        }
    }
}

} } } // end of namespace ::sd::slidesorter::view
<commit_msg>INTEGRATION: CWS sdwarningsbegone (1.11.4); FILE MERGED 2006/11/27 15:15:04 cl 1.11.4.1: #i69285# warning free code changes for sd project<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SlsViewOverlay.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: kz $ $Date: 2006-12-12 18:39:08 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#include "view/SlsViewOverlay.hxx"

#include "controller/SlideSorterController.hxx"
#include "model/SlideSorterModel.hxx"
#include "model/SlsPageDescriptor.hxx"
#include "model/SlsPageEnumeration.hxx"
#include "view/SlideSorterView.hxx"
#include "SlideSorterViewShell.hxx"
#include "view/SlsLayouter.hxx"
#include "view/SlsPageObject.hxx"
#include "view/SlsPageObjectViewObjectContact.hxx"
#include "ViewShellBase.hxx"
#include "UpdateLockManager.hxx"

#include "Window.hxx"
#include "sdpage.hxx"

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

namespace {
class ShowingModeGuard
{
public:
    explicit ShowingModeGuard (::sd::slidesorter::view::OverlayBase& rOverlay,
        bool bHideAndSave = false)
        : mrOverlay (rOverlay),
          mbIsShowing (mrOverlay.IsShowing()),
          mbRestorePending(false)
    {
        if (mbIsShowing)
            if (bHideAndSave)
            {
                mrOverlay.GetViewOverlay().HideAndSave (
                    ::sd::slidesorter::view::ViewOverlay::OPT_XOR);
                mbRestorePending = true;
            }
            mrOverlay.Hide();
    }

    ~ShowingModeGuard (void)
    {
        if (mbIsShowing)
        {
            mrOverlay.Show();
            if (mbRestorePending)
                mrOverlay.GetViewOverlay().Restore ();
        }
    }

private:
    ::sd::slidesorter::view::OverlayBase& mrOverlay;
    bool mbIsShowing;
    bool mbRestorePending;
};
}

namespace sd { namespace slidesorter { namespace view {

//=====  ViewOverlay  =========================================================

ViewOverlay::ViewOverlay (SlideSorterViewShell& rViewShell)
    : mrViewShell (rViewShell),
      maSelectionRectangleOverlay(*this),
      maMouseOverIndicatorOverlay(*this),
      maInsertionIndicatorOverlay(*this),
      maSubstitutionOverlay(*this),
      mbSelectionRectangleWasVisible(false),
      mbMouseOverIndicatorWasVisible(false),
      mbInsertionIndicatorWasVisible(false),
      mbSubstitutionDisplayWasVisible(false),
      mnHideAndSaveLevel(0)
{
}

ViewOverlay::~ViewOverlay (void)
{
}

SelectionRectangleOverlay& ViewOverlay::GetSelectionRectangleOverlay (void)
{
    return maSelectionRectangleOverlay;
}

MouseOverIndicatorOverlay& ViewOverlay::GetMouseOverIndicatorOverlay (void)
{
    return maMouseOverIndicatorOverlay;
}

InsertionIndicatorOverlay& ViewOverlay::GetInsertionIndicatorOverlay (void)
{
    return maInsertionIndicatorOverlay;
}

SubstitutionOverlay& ViewOverlay::GetSubstitutionOverlay (void)
{
    return maSubstitutionOverlay;
}

void ViewOverlay::Paint (void)
{
    maSelectionRectangleOverlay.Paint();
    maMouseOverIndicatorOverlay.Paint();
    maInsertionIndicatorOverlay.Paint();
    maSubstitutionOverlay.Paint();
}

controller::SlideSorterController& ViewOverlay::GetController (void)
{
    return mrViewShell.GetSlideSorterController();
}

SlideSorterViewShell& ViewOverlay::GetViewShell (void)
{
    return mrViewShell;
}

void ViewOverlay::HideAndSave (OverlayPaintType eType)
{
    if (mnHideAndSaveLevel++ == 0)
    {
        // Remember the current state of the visiblities of the overlays.
        mbSelectionRectangleWasVisible = maSelectionRectangleOverlay.IsShowing();
        mbMouseOverIndicatorWasVisible = maMouseOverIndicatorOverlay.IsShowing();
        mbInsertionIndicatorWasVisible = maInsertionIndicatorOverlay.IsShowing();
        mbSubstitutionDisplayWasVisible = maSubstitutionOverlay.IsShowing();

        // Remember that we have saved the current state.
        meSavedStateType = eType;

        // Hide the overlays.
        if (eType==OPT_ALL || eType==OPT_XOR)
        {
            if (mbSelectionRectangleWasVisible)
                maSelectionRectangleOverlay.Hide();
        }
        if (mbSubstitutionDisplayWasVisible)
            maSubstitutionOverlay.Hide();

        if (eType==OPT_ALL || eType==OPT_PAINT)
        {
            if (mbMouseOverIndicatorWasVisible)
                maMouseOverIndicatorOverlay.Hide();
            if (mbInsertionIndicatorWasVisible)
                maInsertionIndicatorOverlay.Hide();
        }
    }
}

void ViewOverlay::Restore (void)
{
    if (--mnHideAndSaveLevel == 0)
    {
        if (meSavedStateType==OPT_ALL || meSavedStateType==OPT_PAINT)
        {
            if (mbInsertionIndicatorWasVisible)
                maInsertionIndicatorOverlay.Show();
            if (mbMouseOverIndicatorWasVisible)
                maMouseOverIndicatorOverlay.Show();
        }
        if (mbSubstitutionDisplayWasVisible)
            maSubstitutionOverlay.Show();
        if (meSavedStateType==OPT_ALL || meSavedStateType==OPT_XOR)
        {
            if (mbSelectionRectangleWasVisible)
                maSelectionRectangleOverlay.Show();
        }
    }
}

//=====  OverlayBase  =========================================================

OverlayBase::OverlayBase (ViewOverlay& rViewOverlay)
    : mrViewOverlay(rViewOverlay),
      mbIsShowing (false)
{
}

OverlayBase::~OverlayBase (void)
{
}

void OverlayBase::Paint (void)
{
}

bool OverlayBase::IsShowing (void)
{
    return mbIsShowing;
}

void OverlayBase::Toggle (void)
{
    if (IsShowing())
        Hide();
    else
        Show();
}

void OverlayBase::Show (void)
{
    if ( ! IsShowing())
    {
        mbIsShowing = true;
        Paint ();
    }
}

void OverlayBase::Hide (void)
{
    if (IsShowing())
    {
        mbIsShowing = false;
        Paint ();
    }
}

ViewOverlay& OverlayBase::GetViewOverlay (void)
{
    return mrViewOverlay;
}

//=====  SubstitutionOverlay  =================================================

SubstitutionOverlay::SubstitutionOverlay (ViewOverlay& rViewOverlay)
    : OverlayBase(rViewOverlay)
{
}

SubstitutionOverlay::~SubstitutionOverlay (void)
{
}

void SubstitutionOverlay::Paint (void)

{
    ::osl::MutexGuard aGuard (maMutex);

    SubstitutionShapeList::const_iterator aShape (maShapes.begin());
    SubstitutionShapeList::const_iterator aShapeEnd (maShapes.end());
    while (aShape!=aShapeEnd)
    {
        mrViewOverlay.GetViewShell().DrawMarkRect (*aShape);
        aShape++;
    }

    OverlayBase::Paint();
}

void SubstitutionOverlay::Create (
    model::PageEnumeration& rSelection,
    const Point& rPosition)
{
    ShowingModeGuard aGuard (*this);
    maPosition = rPosition;

    maShapes.clear();
    while (rSelection.HasMoreElements())
    {
        maShapes.push_back(
            rSelection.GetNextElement()->GetPageObject()->GetCurrentBoundRect());
    }
}

void SubstitutionOverlay::Clear (void)
{
    ShowingModeGuard aGuard (*this);

    maShapes.clear();
}

void SubstitutionOverlay::Move (const Point& rOffset)
{
    SetPosition (maPosition + rOffset);
}

void SubstitutionOverlay::SetPosition (const Point& rPosition)
{
    ShowingModeGuard aGuard (*this);
    Point rOffset = rPosition - maPosition;

    SubstitutionShapeList::iterator aShape (maShapes.begin());
    SubstitutionShapeList::const_iterator aShapeEnd (maShapes.end());
    for (;aShape!=aShapeEnd; aShape++)
        aShape->SetPos (aShape->TopLeft() + rOffset);

    maPosition = rPosition;
}

const Point& SubstitutionOverlay::GetPosition (void) const
{
    return maPosition;
}

//=====  SelectionRectangleOverlay  ===========================================

SelectionRectangleOverlay::SelectionRectangleOverlay (
    ViewOverlay& rViewOverlay)
    : OverlayBase (rViewOverlay),
      maAnchor(0,0),
      maSecondCorner(0,0)
{
}

void SelectionRectangleOverlay::Paint (void)
{
    //  mrViewOverlay.GetViewShell().DrawMarkRect (maSelectionRectangle);
}

void SelectionRectangleOverlay::Show (void)
{
    if ( ! mbIsShowing)
    {
        SlideSorterView& rView (mrViewOverlay.GetViewShell().GetSlideSorterController().GetView());
        rView.BegEncirclement(maAnchor);
        rView.MovEncirclement(maSecondCorner);
        OverlayBase::Show();
    }
}

void SelectionRectangleOverlay::Hide (void)
{
    if (mbIsShowing)
    {
        mrViewOverlay.GetViewShell().GetSlideSorterController().GetView().EndEncirclement();
        OverlayBase::Hide();
    }
}

Rectangle SelectionRectangleOverlay::GetSelectionRectangle (void)
{
    return Rectangle(maAnchor, maSecondCorner);
}

void SelectionRectangleOverlay::Start (const Point& rAnchor)
{
    maAnchor = rAnchor;
    maSecondCorner = rAnchor;
    mrViewOverlay.GetViewShell().GetSlideSorterController().GetView().BegEncirclement(maAnchor);
    OverlayBase::Show();
}

void SelectionRectangleOverlay::Update (const Point& rSecondCorner)
{
    maSecondCorner = rSecondCorner;
    mrViewOverlay.GetViewShell().GetSlideSorterController().GetView().MovEncirclement(maSecondCorner);
}

//=====  InsertionIndicatorOverlay  ===========================================

InsertionIndicatorOverlay::InsertionIndicatorOverlay (
    ViewOverlay& rViewOverlay)
    : OverlayBase (rViewOverlay)
{
}

void InsertionIndicatorOverlay::SetPositionAndSize (
    const Rectangle& aNewBoundingBox)
{
    if (maBoundingBox != aNewBoundingBox)
    {
        ShowingModeGuard aGuard (*this, true);

        maBoundingBox = aNewBoundingBox;
    }
}

void InsertionIndicatorOverlay::Paint (void)
{
    Color aColor;
    if (mbIsShowing)
        aColor = Application::GetSettings().GetStyleSettings().GetFontColor();
    else
        aColor = Application::GetSettings().GetStyleSettings().GetWindowColor();
    mrViewOverlay.GetViewShell().DrawFilledRect (
        maBoundingBox,
        aColor,
        aColor);
}

void InsertionIndicatorOverlay::SetPosition (const Point& rPoint)
{
    static const bool bAllowHorizontalInsertMarker = true;
    Layouter& rLayouter (
        mrViewOverlay.GetController().GetView().GetLayouter());
    USHORT nPageCount
        = (USHORT)mrViewOverlay.GetController().GetModel().GetPageCount();

    sal_Int32 nInsertionIndex = rLayouter.GetInsertionIndex (rPoint,
        bAllowHorizontalInsertMarker);
    if (nInsertionIndex >= nPageCount)
        nInsertionIndex = nPageCount-1;
    sal_Int32 nDrawIndex = nInsertionIndex;

    bool bVertical = false;
    bool bLeftOrTop = false;
    if (nInsertionIndex >= 0)
    {
        // Now that we know where to insert, we still have to determine
        // where to draw the marker.  There are two decisions to make:
        // 1. Draw a vertical or a horizontal insert marker.
        //    The horizontal one may only be chosen when there is only one
        //    column.
        // 2. The vertical (standard) insert marker may be painted left to
        //    the insert page or right of the previous one.  When both pages
        //    are in the same row this makes no difference.  Otherwise the
        //    posiotions are at the left and right ends of two rows.

        Point aPageCenter (rLayouter.GetPageObjectBox (
            nInsertionIndex).Center());

        if (bAllowHorizontalInsertMarker
            && rLayouter.GetColumnCount() == 1)
        {
            bVertical = false;
            bLeftOrTop = (rPoint.Y() <= aPageCenter.Y());
        }
        else
        {
            bVertical = true;
            bLeftOrTop = (rPoint.X() <= aPageCenter.X());
        }

        // Add one when the mark was painted below or to the right of the
        // page object.
        if ( ! bLeftOrTop)
            nInsertionIndex += 1;
    }

    mnInsertionIndex = nInsertionIndex;

    Rectangle aBox;
    if (mnInsertionIndex >= 0)
        aBox = rLayouter.GetInsertionMarkerBox (
            nDrawIndex,
            bVertical,
            bLeftOrTop);
    SetPositionAndSize (aBox);
}

sal_Int32 InsertionIndicatorOverlay::GetInsertionPageIndex (void) const
{
    return mnInsertionIndex;
}

//=====  MouseOverIndicatorOverlay  ===========================================

MouseOverIndicatorOverlay::MouseOverIndicatorOverlay (
    ViewOverlay& rViewOverlay)
    : OverlayBase (rViewOverlay),
      mpPageUnderMouse()
{
}

void MouseOverIndicatorOverlay::SetSlideUnderMouse (
    const model::SharedPageDescriptor& rpDescriptor)
{
    SlideSorterViewShell& rViewShell (mrViewOverlay.GetViewShell());
    if ( ! rViewShell.GetViewShellBase().GetUpdateLockManager().IsLocked())
    {
        model::SharedPageDescriptor pDescriptor;
        if ( ! mpPageUnderMouse.expired())
        {
            try
            {
                pDescriptor = model::SharedPageDescriptor(mpPageUnderMouse);
            }
            catch (::boost::bad_weak_ptr)
            {
            }
        }

         if (pDescriptor != rpDescriptor)
        {
            ShowingModeGuard aGuard (*this, true);

            mpPageUnderMouse = rpDescriptor;
        }
    }
}

void MouseOverIndicatorOverlay::Paint (void)
{
    if ( ! mpPageUnderMouse.expired())
    {
        model::SharedPageDescriptor pDescriptor;
        try
        {
            pDescriptor = model::SharedPageDescriptor(mpPageUnderMouse);
        }
        catch (::boost::bad_weak_ptr)
        {
        }

        if (pDescriptor.get() != NULL)
        {
            SlideSorterViewShell& rViewShell (mrViewOverlay.GetViewShell());
            if ( ! rViewShell.GetViewShellBase().GetUpdateLockManager().IsLocked())
            {
                SlideSorterView& rView (rViewShell.GetSlideSorterController().GetView());
                OutputDevice* pDevice = rView.GetWindow();
                PageObjectViewObjectContact* pContact = pDescriptor->GetViewObjectContact();
                if (pDevice != NULL
                    && pContact != NULL)
                {
                    pContact->PaintFrame(*pDevice, mbIsShowing);
                }
            }
        }
    }
}

} } } // end of namespace ::sd::slidesorter::view
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2008, AMT – The Association For Manufacturing Technology (“AMT”)
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the AMT nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * DISCLAIMER OF WARRANTY. ALL MTCONNECT MATERIALS AND SPECIFICATIONS PROVIDED
 * BY AMT, MTCONNECT OR ANY PARTICIPANT TO YOU OR ANY PARTY ARE PROVIDED "AS IS"
 * AND WITHOUT ANY WARRANTY OF ANY KIND. AMT, MTCONNECT, AND EACH OF THEIR
 * RESPECTIVE MEMBERS, OFFICERS, DIRECTORS, AFFILIATES, SPONSORS, AND AGENTS
 * (COLLECTIVELY, THE "AMT PARTIES") AND PARTICIPANTS MAKE NO REPRESENTATION OR
 * WARRANTY OF ANY KIND WHATSOEVER RELATING TO THESE MATERIALS, INCLUDING, WITHOUT
 * LIMITATION, ANY EXPRESS OR IMPLIED WARRANTY OF NONINFRINGEMENT,
 * MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.

 * LIMITATION OF LIABILITY. IN NO EVENT SHALL AMT, MTCONNECT, ANY OTHER AMT
 * PARTY, OR ANY PARTICIPANT BE LIABLE FOR THE COST OF PROCURING SUBSTITUTE GOODS
 * OR SERVICES, LOST PROFITS, LOSS OF USE, LOSS OF DATA OR ANY INCIDENTAL,
 * CONSEQUENTIAL, INDIRECT, SPECIAL OR PUNITIVE DAMAGES OR OTHER DIRECT DAMAGES,
 * WHETHER UNDER CONTRACT, TORT, WARRANTY OR OTHERWISE, ARISING IN ANY WAY OUT OF
 * THIS AGREEMENT, USE OR INABILITY TO USE MTCONNECT MATERIALS, WHETHER OR NOT
 * SUCH PARTY HAD ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES.
 */

#include "cutting_tool.hpp"
#include "xml_printer.hpp"

using namespace std;

CuttingTool::~CuttingTool()
{
}

void CuttingTool::addValue(const CuttingToolValuePtr aValue)
{
  // Check for keys...
  if (aValue->mKey == "Location") {
    mKeys[aValue->mKey] = aValue->mValue;
  }

  mValues[aValue->mKey] = aValue;
}

inline static bool splitKey(string &key, string &sel, string &val)
{
  size_t found = key.find_first_of('@');
  if (found != string::npos) {
    sel = key;
    sel.erase(found);
    key.erase(0, found + 1);
    size_t found = sel.find_first_of('=');
    if (found == string::npos) {
      val = sel;
      val.erase(found);
      sel.erase(0, found + 1);
      return true;
    }
  }
  return false;
}

void CuttingTool::updateValue(const std::string &aKey, const std::string &aValue)
{
  if (aKey == "Location") {
    mKeys[aKey] = aValue;
  }

  // Split into path and parts and update the asset bits.
  string key = aKey, sel, val;
  if (splitKey(key, sel, val)) {
    for (size_t i = 0; i < mItems.size(); i++)
    {
      CuttingItemPtr item = mItems[i];
      if (item->mIdentity.count(sel) > 0 && val == item->mIdentity[sel])
      {
        if (item->mValues.count(key) > 0)
          item->mValues[key]->mValue = aValue;
        else if (item->mMeasurements.count(key) > 0)
          item->mMeasurements[key]->mValue = aValue;
        break;
      }
    }
  } else {
    if (mValues.count(aKey) > 0)
      mValues[aKey]->mValue = aValue;
    else if (mMeasurements.count(aKey) > 0)
      mMeasurements[aKey]->mValue = aValue;
  }
}

void CuttingTool::addIdentity(const std::string &aKey, const std::string &aValue)
{
  if (aKey == "toolId") {
    mKeys[aKey] = aValue;
    mIdentity[aKey] = aValue;
  } else if (aKey == "deviceUuid") {
    mDeviceUuid = aValue;
  } else if (aKey == "timestamp") {
    mTimestamp = aValue;
  } else {
    mIdentity[aKey] = aValue;
  }
}

std::string &CuttingTool::getContent()
{
  if (mContent.empty())
    mContent = XmlPrinter::printCuttingTool(this);

  return mContent;
}

CuttingToolValue::~CuttingToolValue()
{
}

CuttingItem::~CuttingItem()
{
}
<commit_msg>Fixed key selectors for tools and cutting items<commit_after>/*
 * Copyright (c) 2008, AMT – The Association For Manufacturing Technology (“AMT”)
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the AMT nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * DISCLAIMER OF WARRANTY. ALL MTCONNECT MATERIALS AND SPECIFICATIONS PROVIDED
 * BY AMT, MTCONNECT OR ANY PARTICIPANT TO YOU OR ANY PARTY ARE PROVIDED "AS IS"
 * AND WITHOUT ANY WARRANTY OF ANY KIND. AMT, MTCONNECT, AND EACH OF THEIR
 * RESPECTIVE MEMBERS, OFFICERS, DIRECTORS, AFFILIATES, SPONSORS, AND AGENTS
 * (COLLECTIVELY, THE "AMT PARTIES") AND PARTICIPANTS MAKE NO REPRESENTATION OR
 * WARRANTY OF ANY KIND WHATSOEVER RELATING TO THESE MATERIALS, INCLUDING, WITHOUT
 * LIMITATION, ANY EXPRESS OR IMPLIED WARRANTY OF NONINFRINGEMENT,
 * MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.

 * LIMITATION OF LIABILITY. IN NO EVENT SHALL AMT, MTCONNECT, ANY OTHER AMT
 * PARTY, OR ANY PARTICIPANT BE LIABLE FOR THE COST OF PROCURING SUBSTITUTE GOODS
 * OR SERVICES, LOST PROFITS, LOSS OF USE, LOSS OF DATA OR ANY INCIDENTAL,
 * CONSEQUENTIAL, INDIRECT, SPECIAL OR PUNITIVE DAMAGES OR OTHER DIRECT DAMAGES,
 * WHETHER UNDER CONTRACT, TORT, WARRANTY OR OTHERWISE, ARISING IN ANY WAY OUT OF
 * THIS AGREEMENT, USE OR INABILITY TO USE MTCONNECT MATERIALS, WHETHER OR NOT
 * SUCH PARTY HAD ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES.
 */

#include "cutting_tool.hpp"
#include "xml_printer.hpp"

using namespace std;

CuttingTool::~CuttingTool()
{
}

void CuttingTool::addValue(const CuttingToolValuePtr aValue)
{
  // Check for keys...
  if (aValue->mKey == "Location") {
    mKeys[aValue->mKey] = aValue->mValue;
  }

  mValues[aValue->mKey] = aValue;
}

inline static bool splitKey(string &key, string &sel, string &val)
{
  size_t found = key.find_first_of('@');
  if (found != string::npos) {
    sel = key;
    key.erase(found);
    sel.erase(0, found + 1);
    size_t found = sel.find_first_of('=');
    if (found != string::npos) {
      val = sel;
      sel.erase(found);
      val.erase(0, found + 1);
      return true;
    }
  }
  return false;
}

void CuttingTool::updateValue(const std::string &aKey, const std::string &aValue)
{
  if (aKey == "Location") {
    mKeys[aKey] = aValue;
  }

  // Split into path and parts and update the asset bits.
  string key = aKey, sel, val;
  if (splitKey(key, sel, val)) {
    if (key == "ToolLife") {
      for (size_t i = 0; i < mLives.size(); i++)
      {
        CuttingToolValuePtr life = mLives[i];
        if (life->mProperties.count(sel) > 0 && life->mProperties[sel] == val)
        {
          life->mValue = aValue;
          break;
        }
      }
    } else {
      for (size_t i = 0; i < mItems.size(); i++)
      {
        CuttingItemPtr item = mItems[i];
        if (item->mIdentity.count(sel) > 0 && val == item->mIdentity[sel])
        {
          if (item->mValues.count(key) > 0)
            item->mValues[key]->mValue = aValue;
          else if (item->mMeasurements.count(key) > 0)
            item->mMeasurements[key]->mValue = aValue;
          break;
        }
      }
    }
  } else {
    if (mValues.count(aKey) > 0)
      mValues[aKey]->mValue = aValue;
    else if (mMeasurements.count(aKey) > 0)
      mMeasurements[aKey]->mValue = aValue;
  }
}

void CuttingTool::addIdentity(const std::string &aKey, const std::string &aValue)
{
  if (aKey == "toolId") {
    mKeys[aKey] = aValue;
    mIdentity[aKey] = aValue;
  } else if (aKey == "deviceUuid") {
    mDeviceUuid = aValue;
  } else if (aKey == "timestamp") {
    mTimestamp = aValue;
  } else {
    mIdentity[aKey] = aValue;
  }
}

std::string &CuttingTool::getContent()
{
  if (mContent.empty())
    mContent = XmlPrinter::printCuttingTool(this);

  return mContent;
}

CuttingToolValue::~CuttingToolValue()
{
}

CuttingItem::~CuttingItem()
{
}
<|endoftext|>


<commit_before>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc. 51 Franklin Street, Fifth Floor,
// Boston, MA  02110-1301  USA
//
//-----------------------------------------------------------------------el-

// C++
#include <iostream>

// GRINS
#include "grins/simulation.h"
#include "grins/simulation_builder.h"

// Function for getting initial temperature field
Real initial_values( const Point& p, const Parameters &params,
		     const std::string& system_name, const std::string& unknown_name );

int main(int argc, char* argv[])
{
  // Check command line count.
  if( argc < 2 )
    {
      // TODO: Need more consistent error handling.
      std::cerr << "Error: Must specify libMesh input file." << std::endl;
      exit(1); // TODO: something more sophisticated for parallel runs?
    }

  // libMesh input file should be first argument
  std::string libMesh_input_filename = argv[1];

  // Create our GetPot object.
  GetPot libMesh_inputfile( libMesh_input_filename );

  // Initialize libMesh library.
  LibMeshInit libmesh_init(argc, argv);

  GRINS::SimulationBuilder sim_builder;

  GRINS::Simulation grins( libMesh_inputfile,
			   sim_builder );

  //FIXME: We need to move this to within the Simulation object somehow...
  std::string restart_file = libMesh_inputfile( "restart-options/restart_file", "none" );

  if( restart_file == "none" )
    {
      // Asssign initial temperature value
      std::string system_name = libMesh_inputfile( "screen-options/system_name", "GRINS" );
      std::tr1::shared_ptr<libMesh::EquationSystems> es = grins.get_equation_system();
      const libMesh::System& system = es->get_system(system_name);

      Parameters &params = es->parameters;
      Real T_init = libMesh_inputfile("Physics/LowMachNavierStokes/T0", 0.0);
      Real p0_init = libMesh_inputfile("Physics/LowMachNavierStokes/p0", 0.0);

      Real& dummy_T  = params.set<Real>("T_init");
      dummy_T = T_init;

      Real& dummy_p0 = params.set<Real>("p0_init");
      dummy_p0 = p0_init;

      system.project_solution( initial_values, NULL, params );
    }

  grins.run();

  Real qoi = grins.get_qoi(0);

  // Note that this is a *really* coarse mesh. This is just for testing
  // and not even close to the real QoI for this problem.
  const Real exact_qoi = 4.8158910675853654e+00;

  const Real tol = 5.0e-12;

  int return_flag = 0;

  Real rel_error = std::fabs( (qoi-exact_qoi)/exact_qoi );

  if( rel_error > tol )
    {
      return_flag = 1;
      std::cerr << std::setprecision(16)
		<< std::scientific
		<< "Error: QoI value mismatch." << std::endl
		<< "Computed qoi   = " << qoi << std::endl
		<< "Exact qoi      = " << exact_qoi << std::endl
		<< "Relative error = " << rel_error << std::endl;
    }

  return return_flag;
}

Real initial_values( const Point&, const Parameters &params,
		     const std::string& , const std::string& unknown_name )
{
  Real value = 0.0;

  if( unknown_name == "T" )
    value = params.get<Real>("T_init");

  else if( unknown_name == "p0" )
    value = params.get<Real>("p0_init");

  else
    value = 0.0;

  return value;
}
<commit_msg>Bump up tolerance 60%<commit_after>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc. 51 Franklin Street, Fifth Floor,
// Boston, MA  02110-1301  USA
//
//-----------------------------------------------------------------------el-

// C++
#include <iostream>

// GRINS
#include "grins/simulation.h"
#include "grins/simulation_builder.h"

// Function for getting initial temperature field
Real initial_values( const Point& p, const Parameters &params,
		     const std::string& system_name, const std::string& unknown_name );

int main(int argc, char* argv[])
{
  // Check command line count.
  if( argc < 2 )
    {
      // TODO: Need more consistent error handling.
      std::cerr << "Error: Must specify libMesh input file." << std::endl;
      exit(1); // TODO: something more sophisticated for parallel runs?
    }

  // libMesh input file should be first argument
  std::string libMesh_input_filename = argv[1];

  // Create our GetPot object.
  GetPot libMesh_inputfile( libMesh_input_filename );

  // Initialize libMesh library.
  LibMeshInit libmesh_init(argc, argv);

  GRINS::SimulationBuilder sim_builder;

  GRINS::Simulation grins( libMesh_inputfile,
			   sim_builder );

  //FIXME: We need to move this to within the Simulation object somehow...
  std::string restart_file = libMesh_inputfile( "restart-options/restart_file", "none" );

  if( restart_file == "none" )
    {
      // Asssign initial temperature value
      std::string system_name = libMesh_inputfile( "screen-options/system_name", "GRINS" );
      std::tr1::shared_ptr<libMesh::EquationSystems> es = grins.get_equation_system();
      const libMesh::System& system = es->get_system(system_name);

      Parameters &params = es->parameters;
      Real T_init = libMesh_inputfile("Physics/LowMachNavierStokes/T0", 0.0);
      Real p0_init = libMesh_inputfile("Physics/LowMachNavierStokes/p0", 0.0);

      Real& dummy_T  = params.set<Real>("T_init");
      dummy_T = T_init;

      Real& dummy_p0 = params.set<Real>("p0_init");
      dummy_p0 = p0_init;

      system.project_solution( initial_values, NULL, params );
    }

  grins.run();

  Real qoi = grins.get_qoi(0);

  // Note that this is a *really* coarse mesh. This is just for testing
  // and not even close to the real QoI for this problem.
  const Real exact_qoi = 4.8158910675853654e+00;

  const Real tol = 8.0e-12;

  int return_flag = 0;

  Real rel_error = std::fabs( (qoi-exact_qoi)/exact_qoi );

  if( rel_error > tol )
    {
      return_flag = 1;
      std::cerr << std::setprecision(16)
		<< std::scientific
		<< "Error: QoI value mismatch." << std::endl
		<< "Computed qoi   = " << qoi << std::endl
		<< "Exact qoi      = " << exact_qoi << std::endl
		<< "Relative error = " << rel_error << std::endl;
    }

  return return_flag;
}

Real initial_values( const Point&, const Parameters &params,
		     const std::string& , const std::string& unknown_name )
{
  Real value = 0.0;

  if( unknown_name == "T" )
    value = params.get<Real>("T_init");

  else if( unknown_name == "p0" )
    value = params.get<Real>("p0_init");

  else
    value = 0.0;

  return value;
}
<|endoftext|>


<commit_before>/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2017 Roman Lebedev

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/

#include "fuzz/Common.h"
#include "common/Point.h"              // for iPoint2D
#include "common/RawImage.h"           // for RawImage, RawImageData, RawIm...
#include "common/RawspeedException.h"  // for ThrowRSE
#include "io/ByteStream.h"             // for ByteStream
#include "io/IOException.h"            // for ThrowIOE
#include "metadata/ColorFilterArray.h" // for ColorFilterArray, CFAColor
#include <cassert>                     // for assert
#include <cstdint>                     // for uint32_t
#include <limits>                      // for numeric_limits

rawspeed::RawImage CreateRawImage(rawspeed::ByteStream* bs) {
  assert(bs);

  const uint32_t width = bs->getU32();
  const uint32_t height = bs->getU32();
  const uint32_t type = bs->getU32();
  const uint32_t cpp = bs->getU32();
  const uint32_t isCFA = bs->getU32();

  if (type != rawspeed::TYPE_USHORT16 && type != rawspeed::TYPE_FLOAT32)
    ThrowRSE("Unknown image type: %u", type);

  rawspeed::RawImage mRaw(
      rawspeed::RawImage::create(rawspeed::RawImageType(type)));

  mRaw->dim = rawspeed::iPoint2D(width, height);
  mRaw->setCpp(cpp);
  mRaw->isCFA = isCFA;

  return mRaw;
}

rawspeed::ColorFilterArray CreateCFA(rawspeed::ByteStream* bs) {
  assert(bs);

  const uint32_t cfaWidth = bs->getU32();
  const uint32_t cfaHeight = bs->getU32();

  rawspeed::ColorFilterArray cfa;

  if (cfaHeight &&
      cfaWidth > std::numeric_limits<decltype(cfaWidth)>::max() / cfaHeight)
    ThrowIOE("Integer overflow when calculating CFA area");
  bs->check(cfaWidth * cfaHeight, 4);

  cfa.setSize(rawspeed::iPoint2D(cfaWidth, cfaHeight));

  for (auto x = 0U; x < cfaWidth; x++) {
    for (auto y = 0U; y < cfaHeight; y++) {
      const uint32_t color = bs->getU32();
      if (color >= static_cast<uint32_t>(rawspeed::CFA_END))
        ThrowRSE("Unknown color: %u", color);

      cfa.setColorAt(rawspeed::iPoint2D(x, y), rawspeed::CFAColor(color));
    }
  }

  return cfa;
}
<commit_msg>Fuzz: CreateRawImage(): silence implicit-sign-change sanitizer diag<commit_after>/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2017 Roman Lebedev

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/

#include "fuzz/Common.h"
#include "common/Point.h"              // for iPoint2D
#include "common/RawImage.h"           // for RawImage, RawImageData, RawIm...
#include "common/RawspeedException.h"  // for ThrowRSE
#include "io/ByteStream.h"             // for ByteStream
#include "io/IOException.h"            // for ThrowIOE
#include "metadata/ColorFilterArray.h" // for ColorFilterArray, CFAColor
#include <cassert>                     // for assert
#include <cstdint>                     // for uint32_t
#include <limits>                      // for numeric_limits

rawspeed::RawImage CreateRawImage(rawspeed::ByteStream* bs) {
  assert(bs);

  const uint32_t width = bs->getU32();
  const uint32_t height = bs->getU32();
  const uint32_t type = bs->getU32();
  const uint32_t cpp = bs->getU32();
  const uint32_t isCFA = bs->getU32();

  if (type != rawspeed::TYPE_USHORT16 && type != rawspeed::TYPE_FLOAT32)
    ThrowRSE("Unknown image type: %u", type);

  rawspeed::RawImage mRaw(
      rawspeed::RawImage::create(rawspeed::RawImageType(type)));

  mRaw->dim =
      rawspeed::iPoint2D(static_cast<rawspeed::iPoint2D::value_type>(width),
                         static_cast<rawspeed::iPoint2D::value_type>(height));
  mRaw->setCpp(cpp);
  mRaw->isCFA = isCFA;

  return mRaw;
}

rawspeed::ColorFilterArray CreateCFA(rawspeed::ByteStream* bs) {
  assert(bs);

  const uint32_t cfaWidth = bs->getU32();
  const uint32_t cfaHeight = bs->getU32();

  rawspeed::ColorFilterArray cfa;

  if (cfaHeight &&
      cfaWidth > std::numeric_limits<decltype(cfaWidth)>::max() / cfaHeight)
    ThrowIOE("Integer overflow when calculating CFA area");
  bs->check(cfaWidth * cfaHeight, 4);

  cfa.setSize(rawspeed::iPoint2D(cfaWidth, cfaHeight));

  for (auto x = 0U; x < cfaWidth; x++) {
    for (auto y = 0U; y < cfaHeight; y++) {
      const uint32_t color = bs->getU32();
      if (color >= static_cast<uint32_t>(rawspeed::CFA_END))
        ThrowRSE("Unknown color: %u", color);

      cfa.setColorAt(rawspeed::iPoint2D(x, y), rawspeed::CFAColor(color));
    }
  }

  return cfa;
}
<|endoftext|>


<commit_before>/*
 *  libTML:  A BEEP based Messaging Suite
 *  Copyright (C) 2016 wobe-systems GmbH
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public License
 *  as published by the Free Software Foundation; either version 2.1
 *  of the License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this program; if not, write to the Free
 *  Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
 *  02111-1307 USA
 *
 *  You may find a copy of the license under this software is released
 *  at COPYING file. This is LGPL software: you are welcome to develop
 *  proprietary applications using this library without any royalty or
 *  fee but returning back any change, improvement or addition in the
 *  form of source code, project image, documentation patches, etc.
 *
 *  Homepage:
 *    http://www.libtml.org
 *
 *  For professional support contact us:
 *
 *    wobe-systems GmbH
 *    support@libtml.org
 *
 * Contributors:
 *    wobe-systems GmbH
 */

#include "TestParams.h"

CTestParams* TestParams = NULL;

SIDEX_TCHAR* S_TP_TESTPARAMS      = tmlrtT("TestParams");
SIDEX_TCHAR* S_TP_NETWORK         = tmlrtT("Network");
SIDEX_TCHAR* S_TP_CARDS           = tmlrtT("Cards");
SIDEX_TCHAR* S_TP_127_0_0_1       = tmlrtT("127.0.0.1");
SIDEX_TCHAR* S_TP_FIRSTPORTNUMBER = tmlrtT("FirstPortNumber");
SIDEX_TCHAR* S_TP_TEST            = tmlrtT("Test");
SIDEX_TCHAR* S_TP_LOOPCOUNT       = tmlrtT("LoopCount");

CTestParams::CTestParams(SIDEX_TCHAR* testParamsFileName)
{
  m_ParamsFileName = NULL;
  m_sdxParams      = SIDEX_HANDLE_TYPE_NULL;
  SIDEX_INT32 iErr = sidex_Create(S_TP_TESTPARAMS, &m_sdxParams);
  if(iErr == SIDEX_SUCCESS)
  {
    if(testParamsFileName)
    {
      iErr = sidex_Load_Content(m_sdxParams, testParamsFileName);
      if(iErr == SIDEX_SUCCESS) m_ParamsFileName = tmlrt_cpy(testParamsFileName);
    }
    if(!ensureDefaultParams())
    {
      sidex_Save_Content(m_sdxParams, tmlrtT("C:\\filledTestParams.sdx"));
    }
  }
}

CTestParams::~CTestParams()
{
  if(m_sdxParams != SIDEX_HANDLE_TYPE_NULL)
  {
    sidex_Free(&m_sdxParams);
    m_sdxParams = SIDEX_HANDLE_TYPE_NULL;
  }
  DELETE_STR(m_ParamsFileName);
}

bool CTestParams::hasParams()
{
  return(m_sdxParams != SIDEX_HANDLE_TYPE_NULL);
}

SIDEX_TCHAR* CTestParams::getParamsFileName()
{
  return(m_ParamsFileName);
}

bool CTestParams::ensureDefaultParams()
{
  bool result = true;
  if(hasParams())
  {
    SIDEX_INT32 nCards = getNetworkCardCount();
    if(nCards == 0)
    {
      result = false;
      SIDEX_VARIANT card = SIDEX_HANDLE_TYPE_NULL;
      SIDEX_INT32   iErr = sidex_Variant_New_String(S_TP_127_0_0_1, &card);
      if(iErr == SIDEX_SUCCESS)
      {
        SIDEX_VARIANT cards = sidex_Variant_New_List();
        if(cards != SIDEX_HANDLE_TYPE_NULL)
        {
          SIDEX_INT32 pos = 0;
          iErr = sidex_Variant_List_Append(cards, card, &pos);
          if(iErr == SIDEX_SUCCESS)
          {
            sidex_List_Write(m_sdxParams, S_TP_NETWORK, S_TP_CARDS, cards);
          }
          sidex_Variant_DecRef(cards);
          cards = SIDEX_HANDLE_TYPE_NULL;
        }
        sidex_Variant_DecRef(card);
        card = SIDEX_HANDLE_TYPE_NULL;
      }
    }

    if(getFirstPortNumber() <= 0)
    {
      result = false;
      sidex_Integer_Write(m_sdxParams, S_TP_NETWORK, S_TP_FIRSTPORTNUMBER, DEFAULT_PORTNUMBER);
    }

    if(getTestLoopCount() <= 0)
    {
      result = false;
      sidex_Integer_Write(m_sdxParams, S_TP_TEST, S_TP_LOOPCOUNT, 1);
    }
  }
  return(result);
}

int CTestParams::getNetworkCardCount()
{
  SIDEX_INT32 nCards = 0;
  if(hasParams())
  {
    SIDEX_VARIANT cards = SIDEX_HANDLE_TYPE_NULL;
    SIDEX_INT32 iErr = sidex_List_Read(m_sdxParams, S_TP_NETWORK, S_TP_CARDS, &cards);
    if(iErr == SIDEX_SUCCESS)
    {
      iErr = sidex_Variant_List_Size(cards, &nCards);
      if(iErr != SIDEX_SUCCESS) nCards = 0;
      sidex_Variant_DecRef(cards);
    }
  }
  return(nCards);
}

SIDEX_TCHAR* CTestParams::getNetworkCard(SIDEX_INT32 index)
{
  SIDEX_TCHAR* result = NULL;
  if(hasParams())
  {
    SIDEX_INT32 nCards = getNetworkCardCount();
    if((index >= 0) && (index < nCards))
    {
      SIDEX_VARIANT cards = SIDEX_HANDLE_TYPE_NULL;
      SIDEX_INT32 iErr = sidex_List_Read(m_sdxParams, S_TP_NETWORK, S_TP_CARDS, &cards);
      if(iErr == SIDEX_SUCCESS)
      {
        SIDEX_VARIANT card = SIDEX_HANDLE_TYPE_NULL;
        iErr = sidex_Variant_List_Get(cards, index, &card);
        if(iErr == SIDEX_SUCCESS)
        {
          SIDEX_TCHAR* pCard = NULL;
          SIDEX_INT32  len   = 0;
          iErr = sidex_Variant_As_String(card, &pCard, &len);
          if(iErr == SIDEX_SUCCESS)
          {
            result = tmlrt_cpy(pCard);
            // pCard = borrowed reference -> do not delete!
            pCard = NULL;
          }
          // card = borrowed reference -> do not DecRef!
          card = SIDEX_HANDLE_TYPE_NULL;
        }
        sidex_Variant_DecRef(cards);
        cards = SIDEX_HANDLE_TYPE_NULL;
      }
    }
  }
  return(result);
}

int CTestParams::getFirstPortNumber()
{
  int firstPortNumber = 0;
  if(hasParams())
  {
    SIDEX_INT64 value = 0;
    SIDEX_INT32 iErr = sidex_Integer_Read(m_sdxParams, S_TP_NETWORK, S_TP_FIRSTPORTNUMBER, &value);
    if(iErr == SIDEX_SUCCESS) firstPortNumber = (int)value;
  }
  return(firstPortNumber);
}

int CTestParams::getTestLoopCount()
{
  int nLoops = 0;
  if(hasParams())
  {
    SIDEX_INT64 value = 0;
    SIDEX_INT32 iErr = sidex_Integer_Read(m_sdxParams, S_TP_TEST, S_TP_LOOPCOUNT, &value);
    if(iErr == SIDEX_SUCCESS) nLoops = (int)value;
  }
  return(nLoops);
}
<commit_msg>Fix segmentation fault on Linux at connection close after async calls<commit_after>/*
 *  libTML:  A BEEP based Messaging Suite
 *  Copyright (C) 2016 wobe-systems GmbH
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public License
 *  as published by the Free Software Foundation; either version 2.1
 *  of the License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this program; if not, write to the Free
 *  Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
 *  02111-1307 USA
 *
 *  You may find a copy of the license under this software is released
 *  at COPYING file. This is LGPL software: you are welcome to develop
 *  proprietary applications using this library without any royalty or
 *  fee but returning back any change, improvement or addition in the
 *  form of source code, project image, documentation patches, etc.
 *
 *  Homepage:
 *    http://www.libtml.org
 *
 *  For professional support contact us:
 *
 *    wobe-systems GmbH
 *    support@libtml.org
 *
 * Contributors:
 *    wobe-systems GmbH
 */

#include "TestParams.h"

CTestParams* TestParams = NULL;

SIDEX_TCHAR* S_TP_TESTPARAMS      = tmlrtT("TestParams");
SIDEX_TCHAR* S_TP_NETWORK         = tmlrtT("Network");
SIDEX_TCHAR* S_TP_CARDS           = tmlrtT("Cards");
SIDEX_TCHAR* S_TP_127_0_0_1       = tmlrtT("127.0.0.1");
SIDEX_TCHAR* S_TP_FIRSTPORTNUMBER = tmlrtT("FirstPortNumber");
SIDEX_TCHAR* S_TP_TEST            = tmlrtT("Test");
SIDEX_TCHAR* S_TP_LOOPCOUNT       = tmlrtT("LoopCount");

CTestParams::CTestParams(SIDEX_TCHAR* testParamsFileName)
{
  m_ParamsFileName = NULL;
  m_sdxParams      = SIDEX_HANDLE_TYPE_NULL;
  SIDEX_INT32 iErr = sidex_Create(S_TP_TESTPARAMS, &m_sdxParams);
  if(iErr == SIDEX_SUCCESS)
  {
    if(testParamsFileName)
    {
      iErr = sidex_Load_Content(m_sdxParams, testParamsFileName);
      if(iErr == SIDEX_SUCCESS) m_ParamsFileName = tmlrt_cpy(testParamsFileName);
    }
    if(!ensureDefaultParams())
    {
      #ifndef LINUX
        sidex_Save_Content(m_sdxParams, tmlrtT("C:\\filledTestParams.sdx"));
      #endif
    }
  }
}

CTestParams::~CTestParams()
{
  if(m_sdxParams != SIDEX_HANDLE_TYPE_NULL)
  {
    sidex_Free(&m_sdxParams);
    m_sdxParams = SIDEX_HANDLE_TYPE_NULL;
  }
  DELETE_STR(m_ParamsFileName);
}

bool CTestParams::hasParams()
{
  return(m_sdxParams != SIDEX_HANDLE_TYPE_NULL);
}

SIDEX_TCHAR* CTestParams::getParamsFileName()
{
  return(m_ParamsFileName);
}

bool CTestParams::ensureDefaultParams()
{
  bool result = true;
  if(hasParams())
  {
    SIDEX_INT32 nCards = getNetworkCardCount();
    if(nCards == 0)
    {
      result = false;
      SIDEX_VARIANT card = SIDEX_HANDLE_TYPE_NULL;
      SIDEX_INT32   iErr = sidex_Variant_New_String(S_TP_127_0_0_1, &card);
      if(iErr == SIDEX_SUCCESS)
      {
        SIDEX_VARIANT cards = sidex_Variant_New_List();
        if(cards != SIDEX_HANDLE_TYPE_NULL)
        {
          SIDEX_INT32 pos = 0;
          iErr = sidex_Variant_List_Append(cards, card, &pos);
          if(iErr == SIDEX_SUCCESS)
          {
            sidex_List_Write(m_sdxParams, S_TP_NETWORK, S_TP_CARDS, cards);
          }
          sidex_Variant_DecRef(cards);
          cards = SIDEX_HANDLE_TYPE_NULL;
        }
        sidex_Variant_DecRef(card);
        card = SIDEX_HANDLE_TYPE_NULL;
      }
    }

    if(getFirstPortNumber() <= 0)
    {
      result = false;
      sidex_Integer_Write(m_sdxParams, S_TP_NETWORK, S_TP_FIRSTPORTNUMBER, DEFAULT_PORTNUMBER);
    }

    if(getTestLoopCount() <= 0)
    {
      result = false;
      sidex_Integer_Write(m_sdxParams, S_TP_TEST, S_TP_LOOPCOUNT, 1);
    }
  }
  return(result);
}

int CTestParams::getNetworkCardCount()
{
  SIDEX_INT32 nCards = 0;
  if(hasParams())
  {
    SIDEX_VARIANT cards = SIDEX_HANDLE_TYPE_NULL;
    SIDEX_INT32 iErr = sidex_List_Read(m_sdxParams, S_TP_NETWORK, S_TP_CARDS, &cards);
    if(iErr == SIDEX_SUCCESS)
    {
      iErr = sidex_Variant_List_Size(cards, &nCards);
      if(iErr != SIDEX_SUCCESS) nCards = 0;
      sidex_Variant_DecRef(cards);
    }
  }
  return(nCards);
}

SIDEX_TCHAR* CTestParams::getNetworkCard(SIDEX_INT32 index)
{
  SIDEX_TCHAR* result = NULL;
  if(hasParams())
  {
    SIDEX_INT32 nCards = getNetworkCardCount();
    if((index >= 0) && (index < nCards))
    {
      SIDEX_VARIANT cards = SIDEX_HANDLE_TYPE_NULL;
      SIDEX_INT32 iErr = sidex_List_Read(m_sdxParams, S_TP_NETWORK, S_TP_CARDS, &cards);
      if(iErr == SIDEX_SUCCESS)
      {
        SIDEX_VARIANT card = SIDEX_HANDLE_TYPE_NULL;
        iErr = sidex_Variant_List_Get(cards, index, &card);
        if(iErr == SIDEX_SUCCESS)
        {
          SIDEX_TCHAR* pCard = NULL;
          SIDEX_INT32  len   = 0;
          iErr = sidex_Variant_As_String(card, &pCard, &len);
          if(iErr == SIDEX_SUCCESS)
          {
            result = tmlrt_cpy(pCard);
            // pCard = borrowed reference -> do not delete!
            pCard = NULL;
          }
          // card = borrowed reference -> do not DecRef!
          card = SIDEX_HANDLE_TYPE_NULL;
        }
        sidex_Variant_DecRef(cards);
        cards = SIDEX_HANDLE_TYPE_NULL;
      }
    }
  }
  return(result);
}

int CTestParams::getFirstPortNumber()
{
  int firstPortNumber = 0;
  if(hasParams())
  {
    SIDEX_INT64 value = 0;
    SIDEX_INT32 iErr = sidex_Integer_Read(m_sdxParams, S_TP_NETWORK, S_TP_FIRSTPORTNUMBER, &value);
    if(iErr == SIDEX_SUCCESS) firstPortNumber = (int)value;
  }
  return(firstPortNumber);
}

int CTestParams::getTestLoopCount()
{
  int nLoops = 0;
  if(hasParams())
  {
    SIDEX_INT64 value = 0;
    SIDEX_INT32 iErr = sidex_Integer_Read(m_sdxParams, S_TP_TEST, S_TP_LOOPCOUNT, &value);
    if(iErr == SIDEX_SUCCESS) nLoops = (int)value;
  }
  return(nLoops);
}
<|endoftext|>


<commit_before>/******************************************************************************
**
** Copyright (C) 2009-2012 Kyle Lutz <kyle.r.lutz@gmail.com>
** All rights reserved.
**
** This file is a part of the chemkit project. For more information
** see <http://www.chemkit.org>.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in the
**     documentation and/or other materials provided with the distribution.
**   * Neither the name of the chemkit project nor the names of its
**     contributors may be used to endorse or promote products derived
**     from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
******************************************************************************/

#include "fingerprint.h"

#include "pluginmanager.h"

namespace chemkit {

// === Fingerprint ========================================================= //
/// \class Fingerprint fingerprint.h chemkit/fingerprint.h
/// \ingroup chemkit
/// \brief The Fingerprint class represents a molecular fingerprint.

// --- Construction and Destruction ---------------------------------------- //
/// Creates a new fingerprint with \p name.
Fingerprint::Fingerprint(const std::string &name)
    : m_name(name)
{
}

/// Destroys the fingerprint object.
Fingerprint::~Fingerprint()
{
}

// --- Properties ---------------------------------------------------------- //
/// Returns the name for the fingerprint.
std::string Fingerprint::name() const
{
    return m_name;
}

// --- Fingerprint --------------------------------------------------------- //
/// Returns the fingerprint value as a bitset.
Bitset Fingerprint::value(const Molecule *molecule) const
{
    CHEMKIT_UNUSED(molecule);

    return Bitset();
}

// --- Similarity ---------------------------------------------------------- //
/// Returns the tanimoto coefficent between \p a and \p b.
Real Fingerprint::tanimotoCoefficient(const Bitset &a, const Bitset &b)
{
    size_t intersection = (a & b).count();

    return Real(intersection) / Real(a.count() + b.count() - intersection);
}

// --- Static Methods ------------------------------------------------------ //
/// Creates a new fingerprint object for \p name. Returns \c 0 if
/// \p name is not supported.
Fingerprint* Fingerprint::create(const std::string &name)
{
    return PluginManager::instance()->createPluginClass<Fingerprint>(name);
}

/// Returns a list containing the names of all supported
/// fingerprints.
std::vector<std::string> Fingerprint::fingerprints()
{
    return PluginManager::instance()->pluginClassNames<Fingerprint>();
}

} // end chemkit namespace
<commit_msg>Add documentation for the Fingerprint class<commit_after>/******************************************************************************
**
** Copyright (C) 2009-2012 Kyle Lutz <kyle.r.lutz@gmail.com>
** All rights reserved.
**
** This file is a part of the chemkit project. For more information
** see <http://www.chemkit.org>.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in the
**     documentation and/or other materials provided with the distribution.
**   * Neither the name of the chemkit project nor the names of its
**     contributors may be used to endorse or promote products derived
**     from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
******************************************************************************/

#include "fingerprint.h"

#include "pluginmanager.h"

namespace chemkit {

// === Fingerprint ========================================================= //
/// \class Fingerprint fingerprint.h chemkit/fingerprint.h
/// \ingroup chemkit
/// \brief The Fingerprint class represents a molecular fingerprint.
///
/// A list of supported fingerprints is available at:
/// http://wiki.chemkit.org/Features#Fingerprints
///
/// The following example shows how to calculate the FP2 fingerprint
/// for a uracil molecule:
/// \code
/// // create molecule from its SMILES
/// Molecule uracil("O=C1NC=CC(=O)N1", "smiles");
///
/// // create FP2 fingerprint
/// Fingerprint *fp2 = Fingerprint::create("fp2");
///
/// // calculate fingerprint for the molecule
/// Bitset fingerprint = fp2->value(&uracil);
///
/// // cleanup memory
/// delete fp2;
/// \endcode
///
/// The above fingerprint can also be calculated using the
/// Molecule::fingerprint() conveinence method:
/// \code
/// // create molecule from its SMILES
/// Molecule uracil("O=C1NC=CC(=O)N1", "smiles");
///
/// // calculate fingerprint for the molecule
/// Bitset fingerprint = uracil.fingerprint("fp2");
/// \endcode
///
/// \see Bitset, Molecule::fingerprint()

// --- Construction and Destruction ---------------------------------------- //
/// Creates a new fingerprint with \p name.
Fingerprint::Fingerprint(const std::string &name)
    : m_name(name)
{
}

/// Destroys the fingerprint object.
Fingerprint::~Fingerprint()
{
}

// --- Properties ---------------------------------------------------------- //
/// Returns the name for the fingerprint.
std::string Fingerprint::name() const
{
    return m_name;
}

// --- Fingerprint --------------------------------------------------------- //
/// Returns the fingerprint value as a bitset.
Bitset Fingerprint::value(const Molecule *molecule) const
{
    CHEMKIT_UNUSED(molecule);

    return Bitset();
}

// --- Similarity ---------------------------------------------------------- //
/// Returns the tanimoto coefficent between \p a and \p b.
Real Fingerprint::tanimotoCoefficient(const Bitset &a, const Bitset &b)
{
    size_t intersection = (a & b).count();

    return Real(intersection) / Real(a.count() + b.count() - intersection);
}

// --- Static Methods ------------------------------------------------------ //
/// Creates a new fingerprint object for \p name. Returns \c 0 if
/// \p name is not supported.
Fingerprint* Fingerprint::create(const std::string &name)
{
    return PluginManager::instance()->createPluginClass<Fingerprint>(name);
}

/// Returns a list containing the names of all supported
/// fingerprints.
std::vector<std::string> Fingerprint::fingerprints()
{
    return PluginManager::instance()->pluginClassNames<Fingerprint>();
}

} // end chemkit namespace
<|endoftext|>


<commit_before>
#ifndef __GPG_KEYINFO_LIST__
#define __GPG_KEYINFO_LIST__

#include <map>
#include <vector>
#include <string>

#include <cstdlib>

#include <boost/algorithm/string.hpp>
#include <boost/regex.hpp>
#include <boost/optional.hpp>

#include <easylogging++.h>

class GpgKeyInfo {
public:
  std::string group;
  std::string trust;
  std::string cardid;
  std::string keyId;

  static boost::optional<GpgKeyInfo> fill(std::vector<std::string> match) {
    if (!(match.size() >= 6 && match[0] == "S" && match[1] == "KEYINFO")) {
      LOG(ERROR) << "no keyinfo line";
      return boost::none;
    }
    GpgKeyInfo ret;
    ret.group = match[2];
    ret.trust = match[3];
    ret.cardid = match[4];
    ret.keyId = match[5];
    return ret;
  }

  static std::vector<GpgKeyInfo> read(std::istream &istream) {
    std::vector<GpgKeyInfo> ret;
    std::string line;
    while (std::getline(istream, line)) {
      std::vector<std::string> strs;
      boost::split(strs, line, boost::is_any_of(" "));
      if (strs[0] == "OK") {
        break;
      }
      auto ki = GpgKeyInfo::fill(strs);
      if (ki == boost::none) {
          continue;
      }
      ret.push_back(*ki);
    }
    return ret;
  }
};

#endif
<commit_msg>* bother by gcc 4.8<commit_after>
#ifndef __GPG_KEYINFO_LIST__
#define __GPG_KEYINFO_LIST__

#include <map>
#include <vector>
#include <string>

#include <cstdlib>

#include <boost/algorithm/string.hpp>
#include <boost/regex.hpp>
#include <boost/optional.hpp>

#include <easylogging++.h>

class GpgKeyInfo {
public:
  std::string group;
  std::string trust;
  std::string cardid;
  std::string keyId;
  bool operator==(const GpgKeyInfo& obj) const {
	return this->group == obj.group &&
	 this->trust == obj.trust &&
	 this->cardid == obj.cardid &&
	 this->keyId == obj.keyId;
  }

  static boost::optional<GpgKeyInfo> fill(std::vector<std::string> match) {
    if (!(match.size() >= 6 && match[0] == "S" && match[1] == "KEYINFO")) {
      LOG(ERROR) << "no keyinfo line";
      return boost::none;
    }
    GpgKeyInfo ret;
    ret.group = match[2];
    ret.trust = match[3];
    ret.cardid = match[4];
    ret.keyId = match[5];
    return ret;
  }

  static std::vector<GpgKeyInfo> read(std::istream &istream) {
    std::vector<GpgKeyInfo> ret;
    std::string line;
    while (std::getline(istream, line)) {
      std::vector<std::string> strs;
      boost::split(strs, line, boost::is_any_of(" "));
      if (strs[0] == "OK") {
        break;
      }
      auto ki = GpgKeyInfo::fill(strs);
      if (ki == boost::none) {
          continue;
      }
      ret.push_back(*ki);
    }
    return ret;
  }
};

#endif
<|endoftext|>