<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   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 .
 */
#ifndef RPTUI_VIEWSWINDOW_HXX
#define RPTUI_VIEWSWINDOW_HXX

#include <com/sun/star/report/XSection.hpp>
#include <vcl/window.hxx>
#include <svtools/colorcfg.hxx>
#include "ReportDefines.hxx"
#include "ReportSection.hxx"
#include <comphelper/propmultiplex.hxx>
#include "cppuhelper/basemutex.hxx"
#include <com/sun/star/beans/NamedValue.hpp>
#include <svx/svdedtv.hxx>
#include <SectionView.hxx>
#include <unotools/options.hxx>
#include <list>
#include <vector>
#include <boost/shared_ptr.hpp>

#include <MarkedSection.hxx>
#include <SectionWindow.hxx>

class SdrHdl;
namespace rptui
{
    class OReportWindow;
    class OReportSection;
    class OSectionView;

    struct RectangleLess : public ::std::binary_function< Rectangle, Rectangle, bool>
    {
        enum CompareMode { POS_LEFT,POS_RIGHT,POS_UPPER,POS_DOWN,POS_CENTER_HORIZONTAL,POS_CENTER_VERTICAL };
        CompareMode m_eCompareMode;
        Point       m_aRefPoint;
        RectangleLess(CompareMode _eCompareMode,const Point& _rRefPoint ) : m_eCompareMode(_eCompareMode),m_aRefPoint(_rRefPoint){}
        bool operator() (const Rectangle& lhs, const Rectangle& rhs) const
        {
            switch(m_eCompareMode)
            {
            case POS_LEFT:
                return lhs.Left() < rhs.Left();
            case POS_RIGHT:
                return lhs.Right() >= rhs.Right();
            case POS_UPPER:
                return lhs.Top() < rhs.Top();
            case POS_DOWN:
                return lhs.Bottom() >= rhs.Bottom();
            case POS_CENTER_HORIZONTAL:
                return std::abs(m_aRefPoint.X() - lhs.Center().X()) < std::abs(m_aRefPoint.X() - rhs.Center().X());
            case POS_CENTER_VERTICAL:
                return std::abs(lhs.Center().Y() - m_aRefPoint.Y()) < std::abs(rhs.Center().Y() - m_aRefPoint.Y());
            }
            return false;
        }
    };

    class OWindowPositionCorrector
    {
        ::std::vector< ::std::pair<Window*,Point> > m_aChildren;
        long m_nDeltaX;
        long m_nDeltaY;
    public:
        OWindowPositionCorrector(Window* _pWindow,long _nDeltaX, long _nDeltaY) :m_nDeltaX(_nDeltaX), m_nDeltaY(_nDeltaY)
        {
            sal_uInt16 nCount = _pWindow->GetChildCount();
            m_aChildren.reserve(nCount);
            while( nCount )
            {
                Window* pChild = _pWindow->GetChild(--nCount);
                m_aChildren.push_back(::std::pair<Window*,Point>(pChild,pChild->GetPosPixel()));
            }
        }
        ~OWindowPositionCorrector()
        {
            ::std::vector< ::std::pair<Window*,Point> >::iterator aIter = m_aChildren.begin();
            ::std::vector< ::std::pair<Window*,Point> >::iterator aEnd = m_aChildren.end();
            for (; aIter != aEnd; ++aIter)
            {
                const Point aPos = aIter->first->GetPosPixel();
                if ( aPos == aIter->second )
                    aIter->first->SetPosPixel(Point(m_nDeltaX,m_nDeltaY) + aPos);
            }
        }
    };

    class OViewsWindow :    public Window
                        ,   public utl::ConfigurationListener
                        ,   public IMarkedSection
    {
        typedef ::std::multimap<Rectangle,::std::pair<SdrObject*,OSectionView*>,RectangleLess>      TRectangleMap;
    public:
        typedef ::std::vector< ::boost::shared_ptr<OSectionWindow> >                                TSectionsMap;

        struct TReportPairHelper : public ::std::unary_function< TSectionsMap::value_type, OReportSection >
        {
            OReportSection& operator() (const TSectionsMap::value_type& lhs) const
            {
                return lhs->getReportSection();
            }
        };
        struct TStartMarkerHelper : public ::std::unary_function< TSectionsMap::value_type, OStartMarker >
        {
            OStartMarker& operator() (const TSectionsMap::value_type& lhs) const
            {
                return lhs->getStartMarker();
            }
        };
    private:
        TSectionsMap                            m_aSections;
        svtools::ColorConfig                    m_aColorConfig;
        OReportWindow*                          m_pParent;
        OUString                         m_sShapeType;
        sal_Bool                                m_bInSplitHandler;
        sal_Bool                                m_bInUnmark;

        void ImplInitSettings();
        /** returns the iterator at pos _nPos or the end()
        */
        TSectionsMap::iterator getIteratorAtPos(sal_uInt16 _nPos);
        void collectRectangles(TRectangleMap& _rMap,bool _bBoundRects);
        void collectBoundResizeRect(const TRectangleMap& _rSortRectangles,sal_Int32 _nControlModification,bool _bAlignAtSection,bool _bBoundRects,Rectangle& _rBound,Rectangle& _rResize);
        void impl_resizeSectionWindow(OSectionWindow& _rSectionWindow,Point& _rStartPoint,bool _bSet);

        OViewsWindow(OViewsWindow&);
        void operator =(OViewsWindow&);
    protected:
        virtual void DataChanged( const DataChangedEvent& rDCEvt );
        // windows overload
        virtual void MouseButtonDown( const MouseEvent& rMEvt );
        virtual void MouseButtonUp( const MouseEvent& rMEvt );

        virtual void Paint( const Rectangle& rRect );
        virtual void ConfigurationChanged( utl::ConfigurationBroadcaster*, sal_uInt32 );
    public:
        OViewsWindow(
            OReportWindow* _pReportWindow);
        virtual ~OViewsWindow();

        // windows overload
        virtual void Resize();

        void resize(const OSectionWindow& _rSectionWindow);

        /** late ctor
        */
        void initialize();

        inline OReportWindow*       getView()           const { return m_pParent; }

        /** removes the section at the given position.
        *
        * \param _nPosition Zero based.
        */
        void            removeSection(sal_uInt16 _nPosition);

        /** adds a new section at position _nPosition.
            If the section is <NULL/> nothing happens.
            If the position is grater than the current elements, the section will be appended.
        */
        void            addSection(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection >& _xSection
                                    ,const OUString& _sColorEntry
                                    ,sal_uInt16 _nPosition = USHRT_MAX);

        sal_uInt16          getSectionCount() const;
        /** return the section at the given position
        *
        * \param _nPos
        * \return the section at this pos or an empty section
        */
        ::boost::shared_ptr<OSectionWindow> getSectionWindow(const sal_uInt16 _nPos) const;

        /** turns the grid on or off
        *
        * \param _bVisible
        */
        void            toggleGrid(sal_Bool _bVisible);
        void            setGridSnap(sal_Bool bOn);
        void            setDragStripes(sal_Bool bOn);

        /** returns the total accumulated height of all sections until _pSection is reached
        */
        sal_Int32       getTotalHeight() const;

        inline bool     empty() const { return m_aSections.empty(); }
        void            SetMode( DlgEdMode m_eMode );
        void            SetInsertObj( sal_uInt16 eObj,const OUString& _sShapeType = OUString());
        OUString   GetInsertObjString() const;
        /** copies the current selection in this section
        */
        void Copy();

        /** returns if paste is allowed
        *
        * \return <TRUE/> if paste is allowed
        */
        sal_Bool IsPasteAllowed() const;

        /** paste a new control in this section
        */
        void Paste();

        /** Deletes the current selection in this section
        *
        */
        void Delete();

        /** All objects will be marked.
        */
        void SelectAll(const sal_uInt16 _nObjectType);

        /** returns <TRUE/> when a object is marked
        */
        sal_Bool HasSelection() const;

        /** unmark all objects on the views without the given one.
        *
        * @param _pSectionView The view where the objects should not be unmarked.
        */
        void            unmarkAllObjects(OSectionView* _pSectionView);

        /** returns the report section window for the given xsection
            @param  _xSection   the section
        */
        ::boost::shared_ptr<OSectionWindow> getSectionWindow(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection>& _xSection) const;

        /** checks if the keycode is known by the child windows
            @param  _rCode  the keycode
            @return <TRUE/> if the keycode is handled otherwise <FALSE/>
        */
        sal_Bool        handleKeyEvent(const KeyEvent& _rEvent);

        /** the section as marked or not marked
            @param  _pSectionView   the section where to set the marked flag
            @param  _bMark  the marked flag
        */
        void            setMarked(OSectionView* _pSectionView,sal_Bool _bMark);
        void            setMarked(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection>& _xSection,sal_Bool _bMark);
        void            setMarked(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent> >& _xShape,sal_Bool _bMark);

        // IMarkedSection
        ::boost::shared_ptr<OSectionWindow> getMarkedSection(NearSectionAccess nsa = CURRENT) const;
        virtual void markSection(const sal_uInt16 _nPos);

        /** align all marked objects in all sections
        */
        void alignMarkedObjects(sal_Int32 _nControlModification,bool _bAlignAtSection, bool bBoundRects = false);

        /** creates a default object
        *
        */
        void createDefault();

        /** shows or hides the ruler.
        */
        void showRuler(sal_Bool _bShow);

        /** returns the currently set shape type.
        *
        * \return \member m_sShapeType
        */
        inline OUString getShapeType() const { return m_sShapeType; }

        /** returns the current position in the list
        */
        sal_uInt16 getPosition(const OSectionWindow* _pSectionWindow = NULL) const;

        /** calls on every section BrkAction
        *
        */
        void BrkAction();
        void BegMarkObj(const Point& _aPnt,const OSectionView* _pSection);

    private:
        void BegDragObj_createInvisibleObjectAtPosition(const Rectangle& _aRect, const OSectionView& _rSection);
        void EndDragObj_removeInvisibleObjects();
        Point m_aDragDelta;
        ::std::vector<SdrObject*> m_aBegDragTempList;
        bool isObjectInMyTempList(SdrObject *);
    public:
        void BegDragObj(const Point& _aPnt, SdrHdl* _pHdl,const OSectionView* _pSection);
        void EndDragObj(sal_Bool _bDragIntoNewSection,const OSectionView* _pSection,const Point& _aPnt);

        void EndAction();
        void ForceMarkedToAnotherPage();
        sal_Bool IsAction() const;
        sal_Bool IsDragObj() const;
        void handleKey(const KeyCode& _rCode);
        void stopScrollTimer();

        /** return the section at the given point which is relative to the given section
        *
        * \param _pSection the section which is used as reference point
        * \param _rPnt the point, it will be changed that it is inside the section which will be returned
        * \return the section
        */
        OSectionView* getSectionRelativeToPosition(const OSectionView* _pSection,Point& _rPnt);

        void MovAction(const Point& rPnt,const OSectionView* _pSection,bool _bMove /*= true */, bool _bControlKeySet);

        sal_uInt32 getMarkedObjectCount() const;

        /** fills the positions of all collapsed sections.
        *
        * \param _rCollapsedPositions Out parameter which holds afterwards all positions of the collapsed sections.
        */
        void fillCollapsedSections(::std::vector<sal_uInt16>& _rCollapsedPositions) const;

        /** collpase all sections given by their position
        *
        * \param _aCollpasedSections The position of the sections which should be collapsed.
        */
        void collapseSections(const com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue>& _aCollpasedSections);

        /** zoom the ruler and view windows
        */
        void zoom(const Fraction& _aZoom);

        void scrollChildren(const Point& _aThumbPos);

        /** fills the vector with all selected control models
            /param  _rSelection The vector will be filled and will not be cleared before.
        */
        void fillControlModelSelection(::std::vector< ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > >& _rSelection) const;
    };

} // rptui

#endif // RPTUI_VIEWSWINDOW_HXX

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#738782 Uninitialized scalar field<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   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 .
 */
#ifndef RPTUI_VIEWSWINDOW_HXX
#define RPTUI_VIEWSWINDOW_HXX

#include <com/sun/star/report/XSection.hpp>
#include <vcl/window.hxx>
#include <svtools/colorcfg.hxx>
#include "ReportDefines.hxx"
#include "ReportSection.hxx"
#include <comphelper/propmultiplex.hxx>
#include "cppuhelper/basemutex.hxx"
#include <com/sun/star/beans/NamedValue.hpp>
#include <svx/svdedtv.hxx>
#include <SectionView.hxx>
#include <unotools/options.hxx>
#include <list>
#include <vector>
#include <boost/shared_ptr.hpp>

#include <MarkedSection.hxx>
#include <SectionWindow.hxx>

class SdrHdl;
namespace rptui
{
    class OReportWindow;
    class OReportSection;
    class OSectionView;

    struct RectangleLess : public ::std::binary_function< Rectangle, Rectangle, bool>
    {
        enum CompareMode { POS_LEFT,POS_RIGHT,POS_UPPER,POS_DOWN,POS_CENTER_HORIZONTAL,POS_CENTER_VERTICAL };
        CompareMode m_eCompareMode;
        Point       m_aRefPoint;
        RectangleLess(CompareMode _eCompareMode,const Point& _rRefPoint ) : m_eCompareMode(_eCompareMode),m_aRefPoint(_rRefPoint){}
        bool operator() (const Rectangle& lhs, const Rectangle& rhs) const
        {
            switch(m_eCompareMode)
            {
            case POS_LEFT:
                return lhs.Left() < rhs.Left();
            case POS_RIGHT:
                return lhs.Right() >= rhs.Right();
            case POS_UPPER:
                return lhs.Top() < rhs.Top();
            case POS_DOWN:
                return lhs.Bottom() >= rhs.Bottom();
            case POS_CENTER_HORIZONTAL:
                return std::abs(m_aRefPoint.X() - lhs.Center().X()) < std::abs(m_aRefPoint.X() - rhs.Center().X());
            case POS_CENTER_VERTICAL:
                return std::abs(lhs.Center().Y() - m_aRefPoint.Y()) < std::abs(rhs.Center().Y() - m_aRefPoint.Y());
            }
            return false;
        }
    };

    class OWindowPositionCorrector
    {
        ::std::vector< ::std::pair<Window*,Point> > m_aChildren;
        long m_nDeltaX;
        long m_nDeltaY;
    public:
        OWindowPositionCorrector(Window* _pWindow,long _nDeltaX, long _nDeltaY) :m_nDeltaX(_nDeltaX), m_nDeltaY(_nDeltaY)
        {
            sal_uInt16 nCount = _pWindow->GetChildCount();
            m_aChildren.reserve(nCount);
            while( nCount )
            {
                Window* pChild = _pWindow->GetChild(--nCount);
                m_aChildren.push_back(::std::pair<Window*,Point>(pChild,pChild->GetPosPixel()));
            }
        }
        ~OWindowPositionCorrector()
        {
            ::std::vector< ::std::pair<Window*,Point> >::iterator aIter = m_aChildren.begin();
            ::std::vector< ::std::pair<Window*,Point> >::iterator aEnd = m_aChildren.end();
            for (; aIter != aEnd; ++aIter)
            {
                const Point aPos = aIter->first->GetPosPixel();
                if ( aPos == aIter->second )
                    aIter->first->SetPosPixel(Point(m_nDeltaX,m_nDeltaY) + aPos);
            }
        }
    };

    class OViewsWindow :    public Window
                        ,   public utl::ConfigurationListener
                        ,   public IMarkedSection
    {
        typedef ::std::multimap<Rectangle,::std::pair<SdrObject*,OSectionView*>,RectangleLess>      TRectangleMap;
    public:
        typedef ::std::vector< ::boost::shared_ptr<OSectionWindow> >                                TSectionsMap;

        struct TReportPairHelper : public ::std::unary_function< TSectionsMap::value_type, OReportSection >
        {
            OReportSection& operator() (const TSectionsMap::value_type& lhs) const
            {
                return lhs->getReportSection();
            }
        };
        struct TStartMarkerHelper : public ::std::unary_function< TSectionsMap::value_type, OStartMarker >
        {
            OStartMarker& operator() (const TSectionsMap::value_type& lhs) const
            {
                return lhs->getStartMarker();
            }
        };
    private:
        TSectionsMap                            m_aSections;
        svtools::ColorConfig                    m_aColorConfig;
        OReportWindow*                          m_pParent;
        OUString                         m_sShapeType;
        sal_Bool                                m_bInUnmark;

        void ImplInitSettings();
        /** returns the iterator at pos _nPos or the end()
        */
        TSectionsMap::iterator getIteratorAtPos(sal_uInt16 _nPos);
        void collectRectangles(TRectangleMap& _rMap,bool _bBoundRects);
        void collectBoundResizeRect(const TRectangleMap& _rSortRectangles,sal_Int32 _nControlModification,bool _bAlignAtSection,bool _bBoundRects,Rectangle& _rBound,Rectangle& _rResize);
        void impl_resizeSectionWindow(OSectionWindow& _rSectionWindow,Point& _rStartPoint,bool _bSet);

        OViewsWindow(OViewsWindow&);
        void operator =(OViewsWindow&);
    protected:
        virtual void DataChanged( const DataChangedEvent& rDCEvt );
        // windows overload
        virtual void MouseButtonDown( const MouseEvent& rMEvt );
        virtual void MouseButtonUp( const MouseEvent& rMEvt );

        virtual void Paint( const Rectangle& rRect );
        virtual void ConfigurationChanged( utl::ConfigurationBroadcaster*, sal_uInt32 );
    public:
        OViewsWindow(
            OReportWindow* _pReportWindow);
        virtual ~OViewsWindow();

        // windows overload
        virtual void Resize();

        void resize(const OSectionWindow& _rSectionWindow);

        /** late ctor
        */
        void initialize();

        inline OReportWindow*       getView()           const { return m_pParent; }

        /** removes the section at the given position.
        *
        * \param _nPosition Zero based.
        */
        void            removeSection(sal_uInt16 _nPosition);

        /** adds a new section at position _nPosition.
            If the section is <NULL/> nothing happens.
            If the position is grater than the current elements, the section will be appended.
        */
        void            addSection(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection >& _xSection
                                    ,const OUString& _sColorEntry
                                    ,sal_uInt16 _nPosition = USHRT_MAX);

        sal_uInt16          getSectionCount() const;
        /** return the section at the given position
        *
        * \param _nPos
        * \return the section at this pos or an empty section
        */
        ::boost::shared_ptr<OSectionWindow> getSectionWindow(const sal_uInt16 _nPos) const;

        /** turns the grid on or off
        *
        * \param _bVisible
        */
        void            toggleGrid(sal_Bool _bVisible);
        void            setGridSnap(sal_Bool bOn);
        void            setDragStripes(sal_Bool bOn);

        /** returns the total accumulated height of all sections until _pSection is reached
        */
        sal_Int32       getTotalHeight() const;

        inline bool     empty() const { return m_aSections.empty(); }
        void            SetMode( DlgEdMode m_eMode );
        void            SetInsertObj( sal_uInt16 eObj,const OUString& _sShapeType = OUString());
        OUString   GetInsertObjString() const;
        /** copies the current selection in this section
        */
        void Copy();

        /** returns if paste is allowed
        *
        * \return <TRUE/> if paste is allowed
        */
        sal_Bool IsPasteAllowed() const;

        /** paste a new control in this section
        */
        void Paste();

        /** Deletes the current selection in this section
        *
        */
        void Delete();

        /** All objects will be marked.
        */
        void SelectAll(const sal_uInt16 _nObjectType);

        /** returns <TRUE/> when a object is marked
        */
        sal_Bool HasSelection() const;

        /** unmark all objects on the views without the given one.
        *
        * @param _pSectionView The view where the objects should not be unmarked.
        */
        void            unmarkAllObjects(OSectionView* _pSectionView);

        /** returns the report section window for the given xsection
            @param  _xSection   the section
        */
        ::boost::shared_ptr<OSectionWindow> getSectionWindow(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection>& _xSection) const;

        /** checks if the keycode is known by the child windows
            @param  _rCode  the keycode
            @return <TRUE/> if the keycode is handled otherwise <FALSE/>
        */
        sal_Bool        handleKeyEvent(const KeyEvent& _rEvent);

        /** the section as marked or not marked
            @param  _pSectionView   the section where to set the marked flag
            @param  _bMark  the marked flag
        */
        void            setMarked(OSectionView* _pSectionView,sal_Bool _bMark);
        void            setMarked(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection>& _xSection,sal_Bool _bMark);
        void            setMarked(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent> >& _xShape,sal_Bool _bMark);

        // IMarkedSection
        ::boost::shared_ptr<OSectionWindow> getMarkedSection(NearSectionAccess nsa = CURRENT) const;
        virtual void markSection(const sal_uInt16 _nPos);

        /** align all marked objects in all sections
        */
        void alignMarkedObjects(sal_Int32 _nControlModification,bool _bAlignAtSection, bool bBoundRects = false);

        /** creates a default object
        *
        */
        void createDefault();

        /** shows or hides the ruler.
        */
        void showRuler(sal_Bool _bShow);

        /** returns the currently set shape type.
        *
        * \return \member m_sShapeType
        */
        inline OUString getShapeType() const { return m_sShapeType; }

        /** returns the current position in the list
        */
        sal_uInt16 getPosition(const OSectionWindow* _pSectionWindow = NULL) const;

        /** calls on every section BrkAction
        *
        */
        void BrkAction();
        void BegMarkObj(const Point& _aPnt,const OSectionView* _pSection);

    private:
        void BegDragObj_createInvisibleObjectAtPosition(const Rectangle& _aRect, const OSectionView& _rSection);
        void EndDragObj_removeInvisibleObjects();
        Point m_aDragDelta;
        ::std::vector<SdrObject*> m_aBegDragTempList;
        bool isObjectInMyTempList(SdrObject *);
    public:
        void BegDragObj(const Point& _aPnt, SdrHdl* _pHdl,const OSectionView* _pSection);
        void EndDragObj(sal_Bool _bDragIntoNewSection,const OSectionView* _pSection,const Point& _aPnt);

        void EndAction();
        void ForceMarkedToAnotherPage();
        sal_Bool IsAction() const;
        sal_Bool IsDragObj() const;
        void handleKey(const KeyCode& _rCode);
        void stopScrollTimer();

        /** return the section at the given point which is relative to the given section
        *
        * \param _pSection the section which is used as reference point
        * \param _rPnt the point, it will be changed that it is inside the section which will be returned
        * \return the section
        */
        OSectionView* getSectionRelativeToPosition(const OSectionView* _pSection,Point& _rPnt);

        void MovAction(const Point& rPnt,const OSectionView* _pSection,bool _bMove /*= true */, bool _bControlKeySet);

        sal_uInt32 getMarkedObjectCount() const;

        /** fills the positions of all collapsed sections.
        *
        * \param _rCollapsedPositions Out parameter which holds afterwards all positions of the collapsed sections.
        */
        void fillCollapsedSections(::std::vector<sal_uInt16>& _rCollapsedPositions) const;

        /** collpase all sections given by their position
        *
        * \param _aCollpasedSections The position of the sections which should be collapsed.
        */
        void collapseSections(const com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue>& _aCollpasedSections);

        /** zoom the ruler and view windows
        */
        void zoom(const Fraction& _aZoom);

        void scrollChildren(const Point& _aThumbPos);

        /** fills the vector with all selected control models
            /param  _rSelection The vector will be filled and will not be cleared before.
        */
        void fillControlModelSelection(::std::vector< ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > >& _rSelection) const;
    };

} // rptui

#endif // RPTUI_VIEWSWINDOW_HXX

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>
/// \author James Hughes
/// \date   November 2013

#ifndef IAUNS_GL_BATCH_CONTEXT_BATCH_HPP
#define IAUNS_GL_BATCH_CONTEXT_BATCH_HPP

#include <stdint.h>

namespace CPM_GL_BATCH_CONTEXT_NS {

/// Base context class.
class Context
{
public:
  Context();
  virtual ~Context();

  virtual bool isValid() const=0;

  /// Creates a batch context not associated with any windows.
  static Context* createBatchContext(
      uint32_t width, uint32_t height, uint8_t color_bits, uint8_t depth_bits,
      uint8_t stencil_bits, bool double_buffer, bool visible);

  //============================================================================
  // Mandatory OpenGL-context related functions
  //============================================================================

  /// Make the context current on the active thread.
  virtual void makeCurrent()    = 0;

  /// Swap the front and back buffers.
  virtual void swapBuffers()    = 0;
};

} // namespace CPM_GL_BATCH_CONTEXT_NS

#endif
<commit_msg>Add NoAvailableContext exception class.<commit_after>
/// \author James Hughes
/// \date   November 2013

#ifndef IAUNS_GL_BATCH_CONTEXT_BATCH_HPP
#define IAUNS_GL_BATCH_CONTEXT_BATCH_HPP

#include <stdint.h>

namespace CPM_GL_BATCH_CONTEXT_NS {

/// Base context class.
class Context
{
public:
  Context();
  virtual ~Context();

  virtual bool isValid() const=0;

  /// Creates a batch context not associated with any windows.
  static Context* createBatchContext(
      uint32_t width, uint32_t height, uint8_t color_bits, uint8_t depth_bits,
      uint8_t stencil_bits, bool double_buffer, bool visible);

  //============================================================================
  // Mandatory OpenGL-context related functions
  //============================================================================

  /// Make the context current on the active thread.
  virtual void makeCurrent()    = 0;

  /// Swap the front and back buffers.
  virtual void swapBuffers()    = 0;
};

class NoAvailableContext : public std::exception
{
  public:
    virtual ~NoAvailableContext() throw() {}
    virtual const char* what() const throw()
    {
      return "No context was available to utilize.";
    }
};

} // namespace CPM_GL_BATCH_CONTEXT_NS

#endif
<|endoftext|>


<commit_before>#include "common.h"
#include "psettings.h"
#include "pcloudapp.h"
#include <QDir>

#ifdef Q_OS_LINUX
#include <sys/sysinfo.h>
#endif

#ifdef Q_OS_WIN
char getFirstFreeDevice()
{
    DWORD devices = GetLogicalDrives();
    for (int i = 3; i < 32; ++i)
        if ((devices & (1<<i))==0)
            return i + 'A';
    return 0;
}

bool isConnected(char drive)
{
    DWORD devices = GetLogicalDrives();
    return devices & (1<<drive);
}

#endif

PSettings::PSettings(PCloudApp *a){
    app=a;
    settings=new QSettings("PCloud", "pCloud");
    if (!settings->contains("path")){
#ifdef Q_OS_WIN
        QString path("a:");
        path[0] = getFirstFreeDevice();
#else
        QString path(QDir::homePath()+"/" DEFAULT_PCLOUD_DIR);
        QDir dir(path);
        if (!dir.exists())
            dir.mkpath(path);
#endif
        settings->setValue("path", path);
    }
    if (!settings->contains("usessl"))
        settings->setValue("usessl", DEFAULT_USE_SSL);
    if (!settings->contains("cachesize"))
    {
        qint32 cacheSize = getCacheSize();
        settings->setValue("cachesize", cacheSize);
    }

}

PSettings::~PSettings(){
    delete settings;
}

bool PSettings::isSet(const QString &key){
    return settings->contains(key);
}

QString PSettings::get(const QString &key){
    return settings->value(key).toString();
}

void PSettings::set(const QString &key, const QString &val){
    settings->setValue(key, val);
}

void PSettings::unset(const QString &key){
    settings->remove(key);
}

int PSettings::geti(const QString &key){
    return settings->value(key).toInt();
}

void PSettings::seti(const QString &key, int val){
    settings->setValue(key, val);
}

quint64 PSettings::getu64(const QString &key){
    return settings->value(key).toULongLong();
}

void PSettings::setu64(const QString &key, quint64 val){
    settings->setValue(key, val);
}

qint32 PSettings::getCacheSize(){

#ifdef Q_OS_WIN
    MEMORYSTATUSEX status;
    status.dwLength = sizeof(status);
    GlobalMemoryStatusEx(&status);
    qint32 totalPhysRAM = (qint32)status.ullTotalPhys/1024/1024/10;
    qint32 totalAvailRAM = (qint32)status.ullAvailPhys/1024/1024;
#else
    struct sysinfo sys_info;
    sysinfo(&sys_info);
    qint32  totalPhysRAM=(qint32)(sys_info.totalram/1024/1024/10);
    qint32  totalAvailRAM=(qint32)(sys_info.freeram/1024/1024);
#endif

    qint32 totalRAM = (totalPhysRAM < totalAvailRAM)? totalPhysRAM:totalAvailRAM ;
    return totalRAM;
}
<commit_msg>ram update<commit_after>#include "common.h"
#include "psettings.h"
#include "pcloudapp.h"
#include <QDir>

#ifdef Q_OS_LINUX
#include <sys/sysinfo.h>
#endif

#ifdef Q_OS_WIN
char getFirstFreeDevice()
{
    DWORD devices = GetLogicalDrives();
    for (int i = 3; i < 32; ++i)
        if ((devices & (1<<i))==0)
            return i + 'A';
    return 0;
}

bool isConnected(char drive)
{
    DWORD devices = GetLogicalDrives();
    return devices & (1<<drive);
}

#endif

PSettings::PSettings(PCloudApp *a){
    app=a;
    settings=new QSettings("PCloud", "pCloud");
    if (!settings->contains("path")){
#ifdef Q_OS_WIN
        QString path("a:");
        path[0] = getFirstFreeDevice();
#else
        QString path(QDir::homePath()+"/" DEFAULT_PCLOUD_DIR);
        QDir dir(path);
        if (!dir.exists())
            dir.mkpath(path);
#endif
        settings->setValue("path", path);
    }
    if (!settings->contains("usessl"))
        settings->setValue("usessl", DEFAULT_USE_SSL);
    if (!settings->contains("cachesize"))
    {
        qint32 cacheSize = getCacheSize();
        settings->setValue("cachesize", cacheSize);
    }

}

PSettings::~PSettings(){
    delete settings;
}

bool PSettings::isSet(const QString &key){
    return settings->contains(key);
}

QString PSettings::get(const QString &key){
    return settings->value(key).toString();
}

void PSettings::set(const QString &key, const QString &val){
    settings->setValue(key, val);
}

void PSettings::unset(const QString &key){
    settings->remove(key);
}

int PSettings::geti(const QString &key){
    return settings->value(key).toInt();
}

void PSettings::seti(const QString &key, int val){
    settings->setValue(key, val);
}

quint64 PSettings::getu64(const QString &key){
    return settings->value(key).toULongLong();
}

void PSettings::setu64(const QString &key, quint64 val){
    settings->setValue(key, val);
}

qint32 PSettings::getCacheSize(){

#ifdef Q_OS_WIN
    MEMORYSTATUSEX status;
    status.dwLength = sizeof(status);
    GlobalMemoryStatusEx(&status);
    quint64 totalPhysRAM = (quint64)status.ullTotalPhys/1024/1024/10;
    quint64 totalAvailRAM = (quint64)status.ullAvailPhys/1024/1024;
#else
    struct sysinfo sys_info;
    sysinfo(&sys_info);
    quint64  totalPhysRAM=(quint64)(sys_info.totalram/1024/1024/10);
    quint64  totalAvailRAM=(quint64)(sys_info.freeram/1024/1024);
#endif

    quint64 totalRAM = (totalPhysRAM < totalAvailRAM)? totalPhysRAM:totalAvailRAM ;
    return totalRAM;
}
<|endoftext|>


<commit_before>//=====================================================================//
/*! @file
	@brief  img メイン関係
	@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <iostream>
#include "img_main.hpp"
#include "core/glcore.hpp"
#include "widgets/widget_utils.hpp"

namespace app {

	//-----------------------------------------------------------------//
	/*!
		@brief  初期化
	*/
	//-----------------------------------------------------------------//
	void img_main::initialize()
	{
		gl::IGLcore* igl = gl::get_glcore();

		using namespace gui;
		widget_director& wd = director_.at().widget_director_;

		{ // 画像ファイル表示用フレーム
			widget::param wp(vtx::srect(30, 30, 256, 256));
			widget_frame::param wp_;
			wp_.plate_param_.set_caption(24);
			frame_ = wd.add_widget<widget_frame>(wp, wp_);
		}
		{ // 画像ファイル表示イメージ
			widget::param wp(vtx::srect(0, 0, 256, 256), frame_);
			widget_image::param wp_;
			image_ = wd.add_widget<widget_image>(wp, wp_);
			image_->set_state(widget::state::CLIP_PARENTS);
			image_->set_state(widget::state::RESIZE_ROOT);
			image_->set_state(widget::state::MOVE_ROOT, false);
		}

		{ // 機能ツールパレット
			widget::param wp(vtx::srect(10, 10, 150, 300));
			widget_frame::param wp_;
			tools_ = wd.add_widget<widget_frame>(wp, wp_);
		}
		{ // ファイラー起動ボタン
			widget::param wp(vtx::srect(10, 10, 100, 40), tools_);
			widget_button::param wp_("file");
			open_ = wd.add_widget<widget_button>(wp, wp_);
		}
		{ // スケールチェックボックス
			widget::param wp(vtx::srect(10, 60, 100, 40), tools_);
			widget_check::param wp_("fit");
			scale_ = wd.add_widget<widget_check>(wp, wp_);
		}

		{ // ファイラー本体
			widget::param wp(vtx::srect(10, 30, 300, 200));
			widget_filer::param wp_(igl->get_current_path());
			filer_ = wd.add_widget<widget_filer>(wp, wp_);
			filer_->enable(false);
		}
		{ // ダイアログ
			widget::param wp(vtx::srect(10, 30, 450, 200));
			widget_dialog::param wp_;
			dialog_ = wd.add_widget<widget_dialog>(wp, wp_);
			dialog_->enable(false);
		}

		mobj_.initialize();

		// プリファレンスの取得
		sys::preference& pre = director_.at().preference_;
		if(filer_) {
			filer_->load(pre);
			frame_->load(pre);
			tools_->load(pre);
			scale_->load(pre);
		}
	}

	//-----------------------------------------------------------------//
	/*!
		@brief  アップデート
	*/
	//-----------------------------------------------------------------//
	void img_main::update()
	{
		gl::IGLcore* igl = gl::get_glcore();
		const vtx::spos& size = igl->get_size();

		gui::widget_director& wd = director_.at().widget_director_;

		if(open_) {
			if(open_->get_selected()) {
				if(filer_) {
					bool f = filer_->get_state(gui::widget::state::ENABLE);
					filer_->enable(!f);
				}
			}
		}

		if(filer_) {
			wd.top_widget(filer_);

			if(filer_id_ != filer_->get_select_file_id()) {
				filer_id_ = filer_->get_select_file_id();

				img::img_files& imf = wd.at_img_files();
				if(!imf.load(filer_->get_file())) {
					dialog_->set_text("Can't decode image file:\n '"
						+ filer_->get_file() + "'");
					dialog_->enable();
				} else {
					image_offset_.set(0.0f);
					frame_->at_local_param().text_param_.text_ = filer_->get_file();
					mobj_.destroy();
					mobj_.initialize();
					img_handle_ = mobj_.install(imf.get_image_if());
					image_->at_local_param().mobj_ = mobj_;
					image_->at_local_param().mobj_handle_ = img_handle_;
// imf.set_image_if(imf.get_image_if());
// imf.save("test.jp2");
				}
			}
		}

		// frame 内 image のサイズを設定
		if(frame_ && image_) {
			vtx::spos ofs(frame_->get_local_param().plate_param_.frame_width_);
			image_->at_rect().org = ofs;
			image_->at_rect().org.y += frame_->get_local_param().plate_param_.caption_width_;
			image_->at_rect().size = frame_->get_rect().size - ofs * 2;
			image_->at_rect().size.y -= frame_->get_local_param().plate_param_.caption_width_;

			float s = 1.0f;
			if(scale_->get_check()) {
				vtx::fpos is = mobj_.get_size(img_handle_);
				vtx::fpos ss = image_->at_rect().size;
				vtx::fpos sc = ss / is;
				if(sc.x < sc.y) s = sc.x; else s = sc.y;
				image_->at_local_param().offset_ = 0.0f;
			} else {
				if(image_->get_select_in()) {
					image_offset_ = image_->get_local_param().offset_;
				}
				if(image_->get_select()) {
					vtx::spos d = image_->get_param().move_pos_ - image_->get_param().move_org_;
					image_->at_local_param().offset_ = image_offset_ + d;
				}
			}
			image_->at_local_param().scale_ = s;
		}

		wd.update();
	}

	//-----------------------------------------------------------------//
	/*!
		@brief  レンダリング
	*/
	//-----------------------------------------------------------------//
	void img_main::render()
	{
		director_.at().widget_director_.service();
		director_.at().widget_director_.render();
	}

	//-----------------------------------------------------------------//
	/*!
		@brief  廃棄
	*/
	//-----------------------------------------------------------------//
	void img_main::destroy()
	{
		sys::preference& pre = director_.at().preference_;
		if(filer_) {
			filer_->save(pre);
			frame_->save(pre);
			tools_->save(pre);
			scale_->save(pre);
		}
	}
}
<commit_msg>ツールパレットのサイズ固定<commit_after>//=====================================================================//
/*! @file
	@brief  img メイン関係
	@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <iostream>
#include "img_main.hpp"
#include "core/glcore.hpp"
#include "widgets/widget_utils.hpp"

namespace app {

	//-----------------------------------------------------------------//
	/*!
		@brief  初期化
	*/
	//-----------------------------------------------------------------//
	void img_main::initialize()
	{
		gl::IGLcore* igl = gl::get_glcore();

		using namespace gui;
		widget_director& wd = director_.at().widget_director_;

		{ // 画像ファイル表示用フレーム
			widget::param wp(vtx::srect(30, 30, 256, 256));
			widget_frame::param wp_;
			wp_.plate_param_.set_caption(24);
			frame_ = wd.add_widget<widget_frame>(wp, wp_);
		}
		{ // 画像ファイル表示イメージ
			widget::param wp(vtx::srect(0, 0, 256, 256), frame_);
			widget_image::param wp_;
			image_ = wd.add_widget<widget_image>(wp, wp_);
			image_->set_state(widget::state::CLIP_PARENTS);
			image_->set_state(widget::state::RESIZE_ROOT);
			image_->set_state(widget::state::MOVE_ROOT, false);
		}

		{ // 機能ツールパレット
			widget::param wp(vtx::srect(10, 10, 130, 300));
			widget_frame::param wp_;
			tools_ = wd.add_widget<widget_frame>(wp, wp_);
			tools_->set_state(widget::state::SIZE_LOCK);
		}
		{ // ファイラー起動ボタン
			widget::param wp(vtx::srect(10, 10, 100, 40), tools_);
			widget_button::param wp_("file");
			open_ = wd.add_widget<widget_button>(wp, wp_);
		}
		{ // スケールチェックボックス
			widget::param wp(vtx::srect(10, 60, 100, 40), tools_);
			widget_check::param wp_("fit");
			scale_ = wd.add_widget<widget_check>(wp, wp_);
		}

		{ // ファイラー本体
			widget::param wp(vtx::srect(10, 30, 300, 200));
			widget_filer::param wp_(igl->get_current_path());
			filer_ = wd.add_widget<widget_filer>(wp, wp_);
			filer_->enable(false);
		}
		{ // ダイアログ
			widget::param wp(vtx::srect(10, 30, 450, 200));
			widget_dialog::param wp_;
			dialog_ = wd.add_widget<widget_dialog>(wp, wp_);
			dialog_->enable(false);
		}

		mobj_.initialize();

		// プリファレンスの取得
		sys::preference& pre = director_.at().preference_;
		if(filer_) {
			filer_->load(pre);
			frame_->load(pre);
			tools_->load(pre);
			scale_->load(pre);
		}
	}

	//-----------------------------------------------------------------//
	/*!
		@brief  アップデート
	*/
	//-----------------------------------------------------------------//
	void img_main::update()
	{
		gl::IGLcore* igl = gl::get_glcore();
		const vtx::spos& size = igl->get_size();

		gui::widget_director& wd = director_.at().widget_director_;

		if(open_) {
			if(open_->get_selected()) {
				if(filer_) {
					bool f = filer_->get_state(gui::widget::state::ENABLE);
					filer_->enable(!f);
				}
			}
		}

		if(filer_) {
			wd.top_widget(filer_);

			if(filer_id_ != filer_->get_select_file_id()) {
				filer_id_ = filer_->get_select_file_id();

				img::img_files& imf = wd.at_img_files();
				if(!imf.load(filer_->get_file())) {
					dialog_->set_text("Can't decode image file:\n '"
						+ filer_->get_file() + "'");
					dialog_->enable();
				} else {
					image_offset_.set(0.0f);
					frame_->at_local_param().text_param_.text_ = filer_->get_file();
					mobj_.destroy();
					mobj_.initialize();
					img_handle_ = mobj_.install(imf.get_image_if());
					image_->at_local_param().mobj_ = mobj_;
					image_->at_local_param().mobj_handle_ = img_handle_;
// imf.set_image_if(imf.get_image_if());
// imf.save("test.jp2");
				}
			}
		}

		// frame 内 image のサイズを設定
		if(frame_ && image_) {
			vtx::spos ofs(frame_->get_local_param().plate_param_.frame_width_);
			image_->at_rect().org = ofs;
			image_->at_rect().org.y += frame_->get_local_param().plate_param_.caption_width_;
			image_->at_rect().size = frame_->get_rect().size - ofs * 2;
			image_->at_rect().size.y -= frame_->get_local_param().plate_param_.caption_width_;

			float s = 1.0f;
			if(scale_->get_check()) {
				vtx::fpos is = mobj_.get_size(img_handle_);
				vtx::fpos ss = image_->at_rect().size;
				vtx::fpos sc = ss / is;
				if(sc.x < sc.y) s = sc.x; else s = sc.y;
				image_->at_local_param().offset_ = 0.0f;
			} else {
				if(image_->get_select_in()) {
					image_offset_ = image_->get_local_param().offset_;
				}
				if(image_->get_select()) {
					vtx::spos d = image_->get_param().move_pos_ - image_->get_param().move_org_;
					image_->at_local_param().offset_ = image_offset_ + d;
				}
			}
			image_->at_local_param().scale_ = s;
		}

		wd.update();
	}

	//-----------------------------------------------------------------//
	/*!
		@brief  レンダリング
	*/
	//-----------------------------------------------------------------//
	void img_main::render()
	{
		director_.at().widget_director_.service();
		director_.at().widget_director_.render();
	}

	//-----------------------------------------------------------------//
	/*!
		@brief  廃棄
	*/
	//-----------------------------------------------------------------//
	void img_main::destroy()
	{
		sys::preference& pre = director_.at().preference_;
		if(filer_) {
			filer_->save(pre);
			frame_->save(pre);
			tools_->save(pre);
			scale_->save(pre);
		}
	}
}
<|endoftext|>


<commit_before>/*
 *  Phusion Passenger - https://www.phusionpassenger.com/
 *  Copyright (c) 2010-2014 Phusion
 *
 *  "Phusion Passenger" is a trademark of Hongli Lai & Ninh Bui.
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *  THE SOFTWARE.
 */
#include <iomanip>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <unistd.h>

#include <boost/atomic.hpp>
#include <Logging.h>
#include <Constants.h>
#include <StaticString.h>
#include <Utils/StrIntUtils.h>
#include <Utils/IOUtils.h>

namespace Passenger {

volatile sig_atomic_t _logLevel = DEFAULT_LOG_LEVEL;
AssertionFailureInfo lastAssertionFailure;
static bool printAppOutputAsDebuggingMessages = false;
static char *logFile = NULL;

void
setLogLevel(int value) {
	_logLevel = value;
	boost::atomic_signal_fence(boost::memory_order_seq_cst);
}

bool
setLogFile(const char *path) {
	int fd = open(path, O_WRONLY | O_CREAT | O_APPEND, 0644);
	if (fd != -1) {
		char *newLogFile = strdup(path);
		if (newLogFile == NULL) {
			P_CRITICAL("Cannot allocate memory");
			abort();
		}

		dup2(fd, STDOUT_FILENO);
		dup2(fd, STDERR_FILENO);
		close(fd);

		if (logFile != NULL) {
			free(logFile);
		}
		logFile = newLogFile;
		return true;
	} else {
		return false;
	}
}

string getLogFile() {
	if (logFile == NULL) {
		return string();
	} else {
		return string(logFile);
	}
}

void
_prepareLogEntry(std::stringstream &sstream, const char *file, unsigned int line) {
	time_t the_time;
	struct tm the_tm;
	char datetime_buf[60];
	struct timeval tv;

	if (startsWith(file, "ext/")) {
		file += sizeof("ext/") - 1;
		if (startsWith(file, "common/")) {
			file += sizeof("common/") - 1;
			if (startsWith(file, "ApplicationPool2/")) {
				file += sizeof("Application") - 1;
			}
		}
	}

	the_time = time(NULL);
	localtime_r(&the_time, &the_tm);
	strftime(datetime_buf, sizeof(datetime_buf) - 1, "%F %H:%M:%S", &the_tm);
	gettimeofday(&tv, NULL);
	sstream <<
		"[ " << datetime_buf << "." << std::setfill('0') << std::setw(4) <<
			(unsigned long) (tv.tv_usec / 100) <<
		" " << std::dec << getpid() << "/" <<
			std::hex << pthread_self() << std::dec <<
		" " << file << ":" << line <<
		" ]: ";
}

static void
_writeLogEntry(const StaticString &str) {
	try {
		writeExact(STDERR_FILENO, str.data(), str.size());
	} catch (const SystemException &) {
		/* The most likely reason why this fails is when the user has setup
		 * Apache to log to a pipe (e.g. to a log rotation script). Upon
		 * restarting the web server, the process that reads from the pipe
		 * shuts down, so we can't write to it anymore. That's why we
		 * just ignore write errors. It doesn't make sense to abort for
		 * something like this.
		 */
	}
}

void
_writeLogEntry(const std::string &str) {
	_writeLogEntry(StaticString(str));
}

void
_writeLogEntry(const char *str, unsigned int size) {
	_writeLogEntry(StaticString(str, size));
}

const char *
_strdupStringStream(const std::stringstream &stream) {
	string str = stream.str();
	char *buf = (char *) malloc(str.size() + 1);
	memcpy(buf, str.data(), str.size());
	buf[str.size()] = '\0';
	return buf;
}

static void
realPrintAppOutput(char *buf, unsigned int bufSize,
	const char *pidStr, unsigned int pidStrLen,
	const char *channelName, unsigned int channelNameLen,
	const char *message, unsigned int messageLen)
{
	char *pos = buf;
	char *end = buf + bufSize;

	pos = appendData(pos, end, "App ");
	pos = appendData(pos, end, pidStr, pidStrLen);
	pos = appendData(pos, end, " ");
	pos = appendData(pos, end, channelName, channelNameLen);
	pos = appendData(pos, end, ": ");
	pos = appendData(pos, end, message, messageLen);
	pos = appendData(pos, end, "\n");
	_writeLogEntry(StaticString(buf, pos - buf));
}

void
printAppOutput(pid_t pid, const char *channelName, const char *message, unsigned int size) {
	if (printAppOutputAsDebuggingMessages) {
		P_DEBUG("App " << pid << " " << channelName << ": " << StaticString(message, size));
	} else {
		char pidStr[sizeof("4294967295")];
		unsigned int pidStrLen, channelNameLen, totalLen;

		try {
			pidStrLen = integerToOtherBase<pid_t, 10>(pid, pidStr, sizeof(pidStr));
		} catch (const std::length_error &) {
			pidStr[0] = '?';
			pidStr[1] = '\0';
			pidStrLen = 1;
		}

		channelNameLen = strlen(channelName);
		totalLen = (sizeof("App X Y: \n") - 2) + pidStrLen + channelNameLen + size;
		if (totalLen < 1024) {
			char buf[1024];
			realPrintAppOutput(buf, sizeof(buf),
				pidStr, pidStrLen,
				channelName, channelNameLen,
				message, size);
		} else {
			DynamicBuffer buf(totalLen);
			realPrintAppOutput(buf.data, totalLen,
				pidStr, pidStrLen,
				channelName, channelNameLen,
				message, size);
		}
	}
}

void
setPrintAppOutputAsDebuggingMessages(bool enabled) {
	printAppOutputAsDebuggingMessages = enabled;
}

} // namespace Passenger

<commit_msg>Truncate paths in logging strings (to 3 chars) to reduce redundant info. Closes GH #1383<commit_after>/*
 *  Phusion Passenger - https://www.phusionpassenger.com/
 *  Copyright (c) 2010-2015 Phusion
 *
 *  "Phusion Passenger" is a trademark of Hongli Lai & Ninh Bui.
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *  THE SOFTWARE.
 */
#include <iomanip>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <unistd.h>

#include <boost/atomic.hpp>
#include <Logging.h>
#include <Constants.h>
#include <StaticString.h>
#include <Utils/StrIntUtils.h>
#include <Utils/IOUtils.h>

namespace Passenger {

volatile sig_atomic_t _logLevel = DEFAULT_LOG_LEVEL;
AssertionFailureInfo lastAssertionFailure;
static bool printAppOutputAsDebuggingMessages = false;
static char *logFile = NULL;

#define TRUNCATE_LOGPATHS_TO_MAXCHARS 3 // set to 0 to disable truncation

void
setLogLevel(int value) {
	_logLevel = value;
	boost::atomic_signal_fence(boost::memory_order_seq_cst);
}

bool
setLogFile(const char *path) {
	int fd = open(path, O_WRONLY | O_CREAT | O_APPEND, 0644);
	if (fd != -1) {
		char *newLogFile = strdup(path);
		if (newLogFile == NULL) {
			P_CRITICAL("Cannot allocate memory");
			abort();
		}

		dup2(fd, STDOUT_FILENO);
		dup2(fd, STDERR_FILENO);
		close(fd);

		if (logFile != NULL) {
			free(logFile);
		}
		logFile = newLogFile;
		return true;
	} else {
		return false;
	}
}

string getLogFile() {
	if (logFile == NULL) {
		return string();
	} else {
		return string(logFile);
	}
}

void
_prepareLogEntry(std::stringstream &sstream, const char *file, unsigned int line) {
	time_t the_time;
	struct tm the_tm;
	char datetime_buf[60];
	struct timeval tv;

	the_time = time(NULL);
	localtime_r(&the_time, &the_tm);
	strftime(datetime_buf, sizeof(datetime_buf) - 1, "%F %H:%M:%S", &the_tm);
	gettimeofday(&tv, NULL);
	sstream <<
		"[ " << datetime_buf << "." << std::setfill('0') << std::setw(4) <<
			(unsigned long) (tv.tv_usec / 100) <<
		" " << std::dec << getpid() << "/" <<
			std::hex << pthread_self() << std::dec <<
		" ";

	if (startsWith(file, "ext/")) { // special reduncancy filter because most code resides in these paths
		file += sizeof("ext/") - 1;
		if (startsWith(file, "common/")) {
			file += sizeof("common/") - 1;
		}
	}

	if (TRUNCATE_LOGPATHS_TO_MAXCHARS > 0) {
		truncateBeforeTokens(file, "/\\", TRUNCATE_LOGPATHS_TO_MAXCHARS, sstream);
	} else {
		sstream << file;
	}

	sstream << ":" << line <<
		" ]: ";
}

static void
_writeLogEntry(const StaticString &str) {
	try {
		writeExact(STDERR_FILENO, str.data(), str.size());
	} catch (const SystemException &) {
		/* The most likely reason why this fails is when the user has setup
		 * Apache to log to a pipe (e.g. to a log rotation script). Upon
		 * restarting the web server, the process that reads from the pipe
		 * shuts down, so we can't write to it anymore. That's why we
		 * just ignore write errors. It doesn't make sense to abort for
		 * something like this.
		 */
	}
}

void
_writeLogEntry(const std::string &str) {
	_writeLogEntry(StaticString(str));
}

void
_writeLogEntry(const char *str, unsigned int size) {
	_writeLogEntry(StaticString(str, size));
}

const char *
_strdupStringStream(const std::stringstream &stream) {
	string str = stream.str();
	char *buf = (char *) malloc(str.size() + 1);
	memcpy(buf, str.data(), str.size());
	buf[str.size()] = '\0';
	return buf;
}

static void
realPrintAppOutput(char *buf, unsigned int bufSize,
	const char *pidStr, unsigned int pidStrLen,
	const char *channelName, unsigned int channelNameLen,
	const char *message, unsigned int messageLen)
{
	char *pos = buf;
	char *end = buf + bufSize;

	pos = appendData(pos, end, "App ");
	pos = appendData(pos, end, pidStr, pidStrLen);
	pos = appendData(pos, end, " ");
	pos = appendData(pos, end, channelName, channelNameLen);
	pos = appendData(pos, end, ": ");
	pos = appendData(pos, end, message, messageLen);
	pos = appendData(pos, end, "\n");
	_writeLogEntry(StaticString(buf, pos - buf));
}

void
printAppOutput(pid_t pid, const char *channelName, const char *message, unsigned int size) {
	if (printAppOutputAsDebuggingMessages) {
		P_DEBUG("App " << pid << " " << channelName << ": " << StaticString(message, size));
	} else {
		char pidStr[sizeof("4294967295")];
		unsigned int pidStrLen, channelNameLen, totalLen;

		try {
			pidStrLen = integerToOtherBase<pid_t, 10>(pid, pidStr, sizeof(pidStr));
		} catch (const std::length_error &) {
			pidStr[0] = '?';
			pidStr[1] = '\0';
			pidStrLen = 1;
		}

		channelNameLen = strlen(channelName);
		totalLen = (sizeof("App X Y: \n") - 2) + pidStrLen + channelNameLen + size;
		if (totalLen < 1024) {
			char buf[1024];
			realPrintAppOutput(buf, sizeof(buf),
				pidStr, pidStrLen,
				channelName, channelNameLen,
				message, size);
		} else {
			DynamicBuffer buf(totalLen);
			realPrintAppOutput(buf.data, totalLen,
				pidStr, pidStrLen,
				channelName, channelNameLen,
				message, size);
		}
	}
}

void
setPrintAppOutputAsDebuggingMessages(bool enabled) {
	printAppOutputAsDebuggingMessages = enabled;
}

} // namespace Passenger

<|endoftext|>


<commit_before>#include <chrono>
#include <iostream>

#include <hckt/tree.hpp>
#include <hckt/lmemvector.hpp>
#include "inc_populate_2d_a.cpp"

int main()
{
    for(size_t i=0; i<7; ++i) {
        std::cout << "DEPTH " << i << std::endl;
        auto pstart = std::chrono::steady_clock::now();
        hckt::tree<uint32_t> m;
        populate(m, i);
        auto pend = std::chrono::steady_clock::now();
        auto pdiff = pend-pstart;
        auto mstart = std::chrono::steady_clock::now();
        m.mem_usage_info();
        auto mend = std::chrono::steady_clock::now();
        auto mdiff = mend - mstart;
        std::cout << std::endl;
        std::cout << "poptime: " << std::chrono::duration<double, std::milli>(pdiff).count() << " ms" << std::endl;
        std::cout << "memtime: " << std::chrono::duration<double, std::milli>(mdiff).count() << " ms" << std::endl;
        std::cout << std::endl;
        std::cout << std::endl;
    }

    return 0;
}

<commit_msg>use 2 byte + increase depth... 1.5b per 8gb<commit_after>#include <chrono>
#include <iostream>

#include <hckt/tree.hpp>
#include <hckt/lmemvector.hpp>
#include "inc_populate_2d_a.cpp"

int main()
{
    for(size_t i=0; i<8; ++i) {
        std::cout << "DEPTH " << i << std::endl;
        auto pstart = std::chrono::steady_clock::now();
        hckt::tree<short> m;
        populate(m, i);
        auto pend = std::chrono::steady_clock::now();
        auto pdiff = pend-pstart;
        auto mstart = std::chrono::steady_clock::now();
        m.mem_usage_info();
        auto mend = std::chrono::steady_clock::now();
        auto mdiff = mend - mstart;
        std::cout << std::endl;
        std::cout << "poptime: " << std::chrono::duration<double, std::milli>(pdiff).count() << " ms" << std::endl;
        std::cout << "memtime: " << std::chrono::duration<double, std::milli>(mdiff).count() << " ms" << std::endl;
        std::cout << std::endl;
        std::cout << std::endl;
    }

    return 0;
}

<|endoftext|>


<commit_before>// -*- Mode:C++; Coding:us-ascii-unix; fill-column:158 -*-
/***************************************************************************************************************************************************************
 @file      cplxColor.cpp
 @author    Mitch Richling <https://www.mitchr.me>
 @brief     draw complex function plots@EOL
 @keywords
 @std       C++11
 @copyright
  @parblock
  Copyright (c) 1988-2015, Mitchell Jay Richling <https://www.mitchr.me> All rights reserved.

  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions, and the following disclaimer.

  2. 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.

  3. Neither the name of the copyright holder 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 HOLDER 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.
  @endparblock
***************************************************************************************************************************************************************/

//--------------------------------------------------------------------------------------------------------------------------------------------------------------
#include "ramCanvas.hpp"

//--------------------------------------------------------------------------------------------------------------------------------------------------------------
#include <chrono>                                                        /* time                    C++11    */
#include <complex>                                                       /* Complex Numbers         C++11    */
#include <iostream>                                                      /* C++ iostream            C++11    */

//--------------------------------------------------------------------------------------------------------------------------------------------------------------
using cplx = std::complex<double>;

//--------------------------------------------------------------------------------------------------------------------------------------------------------------
cplx f(cplx z);

//--------------------------------------------------------------------------------------------------------------------------------------------------------------
int main(void) {
  std::chrono::time_point<std::chrono::system_clock> startTime = std::chrono::system_clock::now();
  const double ar       = 16/9.0; // Aspect ratio
  const int    hdLevel  = 4;      // 1=FHD/2 2=FHD, 4=4k, 8=8k
  mjr::ramCanvas3c8b theRamCanvas(960*hdLevel, 540*hdLevel, -2.2*ar, 2.2*ar, -2.2, 2.2);
  mjr::ramCanvas3c8b::colorType aColor;

  const double tau      = 6.28318530718; // 2*Pi
  const double cutDepth = 10.0;          // Range: $[1, ~30]$ Smaller means more contrast on cuts.
  const double argCuts  = 16.0;          // Number of grey cuts for arg
  const int    argWrap  = 3;             // Number of times to wrap around the color ramp for arg
  const double absCuts  = 2.0;           // Number of grey cuts for abs
  const int    numColor = 6*255;         // Number of colors in cmpClrCubeRainbow -1

  for(int y=0;y<theRamCanvas.get_numYpix();y++)  {
    //std::cout << "LINE: " << y << " of " << (1080*hdLevel) << std::endl;
    for(int x=0;x<theRamCanvas.get_numXpix();x++) {
      cplx z { theRamCanvas.int2realX(x), theRamCanvas.int2realY(y) };
      cplx fz      = f(z);

      double zArg  = std::arg(fz);                           // Arg
      double pzArg = (zArg < 0.0 ? tau + zArg : zArg) / tau; // Arg mapped to [0, 1]
      double zAbs  = std::abs(fz);                           // Abs
      double lzAbs = std::log(zAbs);                         // log(Abs
      // double x     = std::real(fz);                       // re
      // double y     = std::imag(fz);                       // img
      // double xAbs  = std::abs(x);                         // abs(re
      // double yAbs  = std::abs(y);                         // abs(img
      // double xPz   = 1.0/(xAbs + 1.0);                    // Map real z to [0,1]  0->1, \inf->0
      // double yPz   = 1.0/(yAbs + 1.0);                    // Map real z to [0,1]  0->1, \inf->0
      // double zPz   = 1.0/(zAbs + 1.0);                    // Map abs(z) to [0,1]  0->1, \inf->0

      // Primary color for fz
      aColor.cmpClrCubeRainbow(mjr::intWrap(mjr::unitTooIntLinMap(mjr::unitClamp(pzArg), numColor*argWrap), numColor)); // Make color

      // Modify the color with "cuts" along argument & magnitede scales.
      aColor.tfrmLinearGreyLevelScale(1.0 - std::fabs(int(pzArg*argCuts) - pzArg*argCuts)/cutDepth, 0);
      aColor.tfrmLinearGreyLevelScale(1.0 - std::fabs(int(lzAbs*absCuts) - lzAbs*absCuts)/cutDepth, 0);

      theRamCanvas.drawPoint(x, y, aColor);
    }
  }
  theRamCanvas.writeTIFFfile("cplxColor.tiff");
  std::chrono::duration<double> runTime = std::chrono::system_clock::now() - startTime;
  std::cout << "Total Runtime " << runTime.count() << " sec" << std::endl;
}

//--------------------------------------------------------------------------------------------------------------------------------------------------------------
cplx f(cplx z) {
  try {
    z=z*cplx(1.5);
    return ((z-2.0)*(z-2.0)*(z+cplx(1,-2))*(z+cplx(2,2))/(z*z*z));

    // z=z/cplx(5.5);
    // return (std::sin(cplx(1)/z));

    // z=z/cplx(2.3);
    // for(int i=0; i<20; i++)
    //   z = z*z-cplx(0.75, 0.2);
    // return z;

    // z=(z*cplx(0, 1)+cplx(1.8, 0))*cplx(0.6, 0);
    // for(int i=0; i<3; i++)
    //   z = (std::sin(std::exp(z)) - cplx(1))/(std::cos(z*z) - cplx(2.0)*z*z + z + cplx(1));
    // return z;

    //return (std::sin(z) - cplx(1))/(z*z*z - cplx(0.5)*z*z + z + cplx(1));

    //return (std::sin(std::exp(z)) - cplx(1))/(std::cos(z*z) - cplx(2.0)*z*z + z + cplx(1));

    //return (z - cplx(1))/(z*z*z - cplx(0.5)*z*z + z + cplx(1));

    // return z;

    //// Eisenstein series E4
    // cplx f = 0.0;
    // cplx zp = z;
    // for(int n=1; n<20; n++) {
    //   f += static_cast<double>(n*n*n)*zp/(1.0-zp);
    //   zp *= z;
    // }
    // f *= 240;
    // f += 1;
    // return f;

    //// Eisenstein series E6
    // cplx f = 0.0;
    // cplx zp = z;
    // for(int n=1; n<20; n++) {
    //   f += static_cast<double>(n*n*n*n*n)*zp/(1.0-zp);
    //   zp *= z;
    // }
    // f *= 504.0;
    // f = 1.0 - f;
    // return f;

    // //// Eisenstein series G6
    // cplx f = 0.0;
    // for(int n=1; n<10; n++)
    //   for(int m=1; m<10; m++) {
    //     cplx d = 1.0/std::pow(static_cast<double>(m) + static_cast<double>(n) * z, 6.0);
    //     f += d;
    //     if (std::abs(d) < 0.00001) break;
    //   }
    // return f;

  } catch(...) {
    std::cout << "Something went wrong!!" << std::endl;
    return 0;
  }
}

<commit_msg>Fleshed out cplxColor<commit_after>// -*- Mode:C++; Coding:us-ascii-unix; fill-column:158 -*-
/***************************************************************************************************************************************************************
 @file      cplxColor.cpp
 @author    Mitch Richling <https://www.mitchr.me>
 @brief     draw complex function plots@EOL
 @keywords
 @std       C++11
 @copyright
  @parblock
  Copyright (c) 1988-2015, Mitchell Jay Richling <https://www.mitchr.me> All rights reserved.

  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions, and the following disclaimer.

  2. 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.

  3. Neither the name of the copyright holder 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 HOLDER 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.
  @endparblock
***************************************************************************************************************************************************************/

//--------------------------------------------------------------------------------------------------------------------------------------------------------------
#include "ramCanvas.hpp"

//--------------------------------------------------------------------------------------------------------------------------------------------------------------
#include <chrono>                                                        /* time                    C++11    */
#include <complex>                                                       /* Complex Numbers         C++11    */
#include <iostream>                                                      /* C++ iostream            C++11    */

//--------------------------------------------------------------------------------------------------------------------------------------------------------------
using cplx = std::complex<double>;

//--------------------------------------------------------------------------------------------------------------------------------------------------------------
cplx f(cplx z);

//--------------------------------------------------------------------------------------------------------------------------------------------------------------
int main(void) {
  std::chrono::time_point<std::chrono::system_clock> startTime = std::chrono::system_clock::now();
  const double ar       = 16/9.0; // Aspect ratio
  const int    hdLevel  = 4;      // 1=FHD/2 2=FHD, 4=4k, 8=8k
  mjr::ramCanvas3c8b theRamCanvas(960*hdLevel, 540*hdLevel, -2.2*ar, 2.2*ar, -2.2, 2.2);
  mjr::ramCanvas3c8b::colorType aColor;

  const double tau      = 6.28318530718; // 2*Pi
  const double pi       = tau/2;         // Pi
  const double cutDepth = 10.0;          // Range: $[1, ~30]$ Smaller means more contrast on cuts.
  const double argCuts  = 16.0;          // Number of grey cuts for arg
  const int    argWrap  = 3;             // Number of times to wrap around the color ramp for arg
  const double absCuts  = 2.0;           // Number of grey cuts for abs
  const int    numColor = 6*255;         // Number of colors in cmpClrCubeRainbow -1

  for(int y=0;y<theRamCanvas.get_numYpix();y++)  {
    //std::cout << "LINE: " << y << " of " << (1080*hdLevel) << std::endl;
    for(int x=0;x<theRamCanvas.get_numXpix();x++) {
      cplx z { theRamCanvas.int2realX(x), theRamCanvas.int2realY(y) };
      cplx fz      = f(z);

      double zArg  = std::arg(fz);                           // Arg
      double pzArg = (zArg < 0.0 ? tau + zArg : zArg) / tau; // Arg mapped to [0, 1]
      double zAbs  = std::abs(fz);                           // Abs
      double lzAbs = std::log(zAbs);                         // log(Abs
      double xAbs  = std::abs(x);                            // abs(re
      double yAbs  = std::abs(y);                            // abs(img
      double xPz   = 1.0/(xAbs + 1.0);                       // Map real z to [0,1]  0->1, \inf->0
      double yPz   = 1.0/(yAbs + 1.0);                       // Map real z to [0,1]  0->1, \inf->0
      double zPz   = 1.0/(zAbs + 1.0);                       // Map abs(z) to [0,1]  0->1, \inf->0
      double atm   = 2*atan(zAbs)/pi;                        // Map Abs to [0,1]
      double a     = 2;                                      // param for sgpm
      double tmp   = std::pow(zAbs, a);                      // tmp for sgpm
      double sgpm  = tmp / (tmp + 1);                        // Map Abs to [0, 1] e stereographic projection onto the Riemann sphere.
      double patm  = 1 - std::pow(0.5, zAbs);                // Map Abs to [0,1] -- much like atm, but no trig

      // Primary color for fz
      aColor.cmpClrCubeRainbow(mjr::intWrap(mjr::unitTooIntLinMap(mjr::unitClamp(pzArg), numColor*argWrap), numColor)); // Make color

      // Modify the color with "cuts" along argument & magnitede scales.
      aColor.tfrmLinearGreyLevelScale(1.0 - std::fabs(int(pzArg*argCuts) - pzArg*argCuts)/cutDepth, 0);
      aColor.tfrmLinearGreyLevelScale(1.0 - std::fabs(int(lzAbs*absCuts) - lzAbs*absCuts)/cutDepth, 0);

      theRamCanvas.drawPoint(x, y, aColor);
    }
  }
  theRamCanvas.writeTIFFfile("cplxColor.tiff");
  std::chrono::duration<double> runTime = std::chrono::system_clock::now() - startTime;
  std::cout << "Total Runtime " << runTime.count() << " sec" << std::endl;
}

//--------------------------------------------------------------------------------------------------------------------------------------------------------------
cplx f(cplx z) {
  try {
    z=z*cplx(1.5);
    return ((z-2.0)*(z-2.0)*(z+cplx(1,-2))*(z+cplx(2,2))/(z*z*z));

    // z=z/cplx(5.5);
    // return (std::sin(cplx(1)/z));

    // z=z/cplx(2.3);
    // for(int i=0; i<20; i++)
    //   z = z*z-cplx(0.75, 0.2);
    // return z;

    // z=(z*cplx(0, 1)+cplx(1.8, 0))*cplx(0.6, 0);
    // for(int i=0; i<3; i++)
    //   z = (std::sin(std::exp(z)) - cplx(1))/(std::cos(z*z) - cplx(2.0)*z*z + z + cplx(1));
    // return z;

    //return (std::sin(z) - cplx(1))/(z*z*z - cplx(0.5)*z*z + z + cplx(1));

    //return (std::sin(std::exp(z)) - cplx(1))/(std::cos(z*z) - cplx(2.0)*z*z + z + cplx(1));

    //return (z - cplx(1))/(z*z*z - cplx(0.5)*z*z + z + cplx(1));

    // return z;

    //// Eisenstein series E4
    // cplx f = 0.0;
    // cplx zp = z;
    // for(int n=1; n<20; n++) {
    //   f += static_cast<double>(n*n*n)*zp/(1.0-zp);
    //   zp *= z;
    // }
    // f *= 240;
    // f += 1;
    // return f;

    //// Eisenstein series E6
    // cplx f = 0.0;
    // cplx zp = z;
    // for(int n=1; n<20; n++) {
    //   f += static_cast<double>(n*n*n*n*n)*zp/(1.0-zp);
    //   zp *= z;
    // }
    // f *= 504.0;
    // f = 1.0 - f;
    // return f;

    // //// Eisenstein series G6
    // cplx f = 0.0;
    // for(int n=1; n<10; n++)
    //   for(int m=1; m<10; m++) {
    //     cplx d = 1.0/std::pow(static_cast<double>(m) + static_cast<double>(n) * z, 6.0);
    //     f += d;
    //     if (std::abs(d) < 0.00001) break;
    //   }
    // return f;

  } catch(...) {
    std::cout << "Something went wrong!!" << std::endl;
    return 0;
  }
}

<|endoftext|>


<commit_before>#include <iostream>
#include <string>
using namespace std;

int main() {
	string x, y, sum;

	cin >> x >> y;

	reverse(x.begin(), x.end());
	reverse(y.begin(), y.end());

	sum = to_string(stoi(x) + stoi(y));

	reverse(sum.begin(), sum.end());

	cout << sum << endl;
}<commit_msg>Prob 1357 c++11<commit_after>#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int main() {
	string x, y, sum;

	cin >> x >> y;

	reverse(x.begin(), x.end());
	reverse(y.begin(), y.end());

	sum = to_string(stoi(x) + stoi(y));

	reverse(sum.begin(), sum.end());

	cout << sum << endl;
}<|endoftext|>


<commit_before>// Copyright since 2016 : Evgenii Shatunov (github.com/FrankStain/jnipp-test)
// Apache 2.0 License
#include <main.h>
#include <gtest/gtest.h>

TEST( TestClassHandle, EmptyIsValid )
{
	jnipp::ClassHandle class_handle;

	EXPECT_FALSE( class_handle.IsValid() );
};

TEST( TestClassHandle, ConstructedIsValid )
{
	jnipp::ClassHandle class_handle{ "java/lang/String" };

	EXPECT_TRUE( class_handle.IsValid() );
};

TEST( TestClassHandle, Invalidate )
{
	jnipp::ClassHandle class_handle{ "java/lang/String" };

	EXPECT_TRUE( class_handle.IsValid() );

	class_handle.Invalidate();
	EXPECT_FALSE( class_handle.IsValid() );
};

TEST( TestClassHandle, AssignString )
{
	jnipp::ClassHandle class_handle;

	EXPECT_FALSE( class_handle.IsValid() );

	class_handle = "java/lang/String";
	EXPECT_TRUE( class_handle.IsValid() );
};

TEST( TestClassHandle, CopyValid )
{
	jnipp::ClassHandle class_handle1;
	const jnipp::ClassHandle class_handle2{ "java/lang/String" };

	EXPECT_FALSE( class_handle1.IsValid() );
	EXPECT_TRUE( class_handle2.IsValid() );

	class_handle1 = class_handle2;
	EXPECT_TRUE( class_handle1.IsValid() );
	EXPECT_TRUE( class_handle2.IsValid() );

	const jnipp::ClassHandle class_handle3{ class_handle2 };
	EXPECT_TRUE( class_handle3.IsValid() );
	EXPECT_TRUE( class_handle2.IsValid() );
};

TEST( TestClassHandle, MoveValid )
{
	jnipp::ClassHandle class_handle1;
	jnipp::ClassHandle class_handle2{ "java/lang/String" };

	EXPECT_FALSE( class_handle1.IsValid() );
	EXPECT_TRUE( class_handle2.IsValid() );

	class_handle1 = std::move( class_handle2 );
	EXPECT_TRUE( class_handle1.IsValid() );
	EXPECT_FALSE( class_handle2.IsValid() );

	jnipp::ClassHandle class_handle3{ std::move( class_handle1 ) };
	EXPECT_TRUE( class_handle3.IsValid() );
	EXPECT_FALSE( class_handle1.IsValid() );
};

TEST( TestClassHandle, GetReference )
{
	jnipp::ClassHandle class_handle{ "java/lang/String" };

	EXPECT_TRUE( class_handle.IsValid() );
	EXPECT_NE( nullptr, *class_handle );
};
<commit_msg>Tests for Java class name.<commit_after>// Copyright since 2016 : Evgenii Shatunov (github.com/FrankStain/jnipp-test)
// Apache 2.0 License
#include <main.h>
#include <gtest/gtest.h>

TEST( TestClassHandle, EmptyIsValid )
{
	jnipp::ClassHandle class_handle;

	EXPECT_FALSE( class_handle.IsValid() );
};

TEST( TestClassHandle, ConstructedIsValid )
{
	jnipp::ClassHandle class_handle{ "java/lang/String" };

	EXPECT_TRUE( class_handle.IsValid() );
};

TEST( TestClassHandle, Invalidate )
{
	jnipp::ClassHandle class_handle{ "java/lang/String" };

	EXPECT_TRUE( class_handle.IsValid() );

	class_handle.Invalidate();
	EXPECT_FALSE( class_handle.IsValid() );
};

TEST( TestClassHandle, AssignString )
{
	jnipp::ClassHandle class_handle;

	EXPECT_FALSE( class_handle.IsValid() );

	class_handle = "java/lang/String";
	EXPECT_TRUE( class_handle.IsValid() );
};

TEST( TestClassHandle, CopyValid )
{
	jnipp::ClassHandle class_handle1;
	const jnipp::ClassHandle class_handle2{ "java/lang/String" };

	EXPECT_FALSE( class_handle1.IsValid() );
	EXPECT_TRUE( class_handle2.IsValid() );

	class_handle1 = class_handle2;
	EXPECT_TRUE( class_handle1.IsValid() );
	EXPECT_TRUE( class_handle2.IsValid() );

	const jnipp::ClassHandle class_handle3{ class_handle2 };
	EXPECT_TRUE( class_handle3.IsValid() );
	EXPECT_TRUE( class_handle2.IsValid() );
};

TEST( TestClassHandle, MoveValid )
{
	jnipp::ClassHandle class_handle1;
	jnipp::ClassHandle class_handle2{ "java/lang/String" };

	EXPECT_FALSE( class_handle1.IsValid() );
	EXPECT_TRUE( class_handle2.IsValid() );

	class_handle1 = std::move( class_handle2 );
	EXPECT_TRUE( class_handle1.IsValid() );
	EXPECT_FALSE( class_handle2.IsValid() );

	jnipp::ClassHandle class_handle3{ std::move( class_handle1 ) };
	EXPECT_TRUE( class_handle3.IsValid() );
	EXPECT_FALSE( class_handle1.IsValid() );
};

TEST( TestClassHandle, GetReference )
{
	jnipp::ClassHandle class_handle{ "java/lang/String" };

	EXPECT_TRUE( class_handle.IsValid() );
	EXPECT_NE( nullptr, *class_handle );
};

TEST( TestClassHandle, ValidGetName )
{
	jnipp::ClassHandle class_handle{ "java/lang/String" };

	EXPECT_TRUE( class_handle.IsValid() );

	const std::string class_name{ class_handle.GetName() };
	EXPECT_STREQ( "java/lang/String", class_name.c_str() );
};

TEST( TestClassHandle, InvalidGetName )
{
	jnipp::ClassHandle class_handle;

	EXPECT_FALSE( class_handle.IsValid() );

	const std::string class_name{ class_handle.GetName() };
	EXPECT_STREQ( "", class_name.c_str() );
};
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: salvd.cxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: hr $ $Date: 2006-08-11 17:52:16 $
 *
 *  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
 *
 ************************************************************************/

#include <prex.h>
#include <X11/extensions/Xrender.h>
#include <postx.h>

#include <salunx.h>

#ifndef _SV_SALDATA_HXX
#include <saldata.hxx>
#endif
#ifndef _SV_SALDISP_HXX
#include <saldisp.hxx>
#endif
#ifndef _SV_SALINST_HXX
#include <salinst.hxx>
#endif
#ifndef _SV_SALGDI_H
#include <salgdi.h>
#endif
#ifndef _SV_SALVD_H
#include <salvd.h>
#endif
#ifndef _SV_SYSDATA_HXX
#include <sysdata.hxx>
#endif

// -=-= SalInstance =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
SalVirtualDevice* X11SalInstance::CreateVirtualDevice( SalGraphics* pGraphics,
                                                       long nDX, long nDY,
                                                       USHORT nBitCount, const SystemGraphicsData *pData )
{
    X11SalVirtualDevice *pVDev = new X11SalVirtualDevice();
    if( !nBitCount && pGraphics )
        nBitCount = pGraphics->GetBitCount();

    SalDisplay* pSalDisplay = GetX11SalData()->GetDisplay();
    if( pData && pData->hDrawable != None )
    {
        XLIB_Window aRoot;
        int x, y;
        unsigned int w = 0, h = 0, bw, d;
        XGetGeometry( pSalDisplay->GetDisplay(), pData->hDrawable,
                      &aRoot, &x, &y, &w, &h, &bw, &d );
        nDX = (long)w;
        nDY = (long)h;
        if( !pVDev->Init( pSalDisplay, nDX, nDY, nBitCount, pData->hDrawable, pData->pRenderFormat ) )
        {
            delete pVDev;
            return NULL;
        }
    }
    else if( !pVDev->Init( pSalDisplay, nDX, nDY, nBitCount ) )
    {
        delete pVDev;
        return NULL;
    }

    pVDev->InitGraphics( pVDev );
    return pVDev;
}

void X11SalInstance::DestroyVirtualDevice( SalVirtualDevice* pDevice )
{
    delete pDevice;
}

// -=-= SalGraphicsData =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
void X11SalGraphics::Init( X11SalVirtualDevice *pDevice, SalColormap* pColormap, bool bDeleteColormap )
{
    SalDisplay *pDisplay  = pDevice->GetDisplay();

    int nVisualDepth = pDisplay->GetColormap().GetVisual()->GetDepth();
    int nDeviceDepth = pDevice->GetDepth();

    if( pColormap )
    {
        m_pColormap = pColormap;
        if( bDeleteColormap )
            m_pDeleteColormap = m_pColormap;
    }
    else
    if( nDeviceDepth == nVisualDepth )
        m_pColormap = &pDisplay->GetColormap();
    else
    if( nDeviceDepth == 1 )
        m_pDeleteColormap = m_pColormap = new SalColormap();

    hDrawable_   = pDevice->GetDrawable();
    m_pVDev      = pDevice;
    m_pFrame     = NULL;

    bWindow_     = pDisplay->IsDisplay();
    bVirDev_     = TRUE;

    nPenPixel_   = GetPixel( nPenColor_ );
    nTextPixel_  = GetPixel( nTextColor_ );
    nBrushPixel_ = GetPixel( nBrushColor_ );
}

// -=-= SalVirDevData / SalVirtualDevice -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
BOOL X11SalVirtualDevice::Init( SalDisplay *pDisplay,
                                long nDX, long nDY,
                                USHORT nBitCount,
                                Pixmap hDrawable,
                                void* pRenderFormatVoid )
{
    SalColormap* pColormap = NULL;
    bool bDeleteColormap = false;

    pDisplay_               = pDisplay;
    pGraphics_              = new X11SalGraphics();
    if( pRenderFormatVoid ) {
        XRenderPictFormat *pRenderFormat = ( XRenderPictFormat* )pRenderFormatVoid;
        pGraphics_->SetXRenderFormat( pRenderFormat );
        if( pRenderFormat->colormap )
            pColormap = new SalColormap( pDisplay, pRenderFormat->colormap );
        else
            pColormap = new SalColormap( nBitCount );
         bDeleteColormap = true;
    }
    pGraphics_->SetLayout( 0 ); // by default no! mirroring for VirtualDevices, can be enabled with EnableRTL()
    nDX_                    = nDX;
    nDY_                    = nDY;
    nDepth_                 = nBitCount;

    if( hDrawable == None )
        hDrawable_          = XCreatePixmap( GetXDisplay(),
                                             pDisplay_->GetDrawable(),
                                             nDX_, nDY_,
                                             GetDepth() );
    else
    {
        hDrawable_ = hDrawable;
        bExternPixmap_ = TRUE;
    }

    pGraphics_->Init( this, pColormap, bDeleteColormap );

    return hDrawable_ != None ? TRUE : FALSE;
}

// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
X11SalVirtualDevice::X11SalVirtualDevice()
{
    pDisplay_               = (SalDisplay*)ILLEGAL_POINTER;
    pGraphics_              = NULL;
    hDrawable_              = None;
    nDX_                    = 0;
    nDY_                    = 0;
    nDepth_                 = 0;
    bGraphics_              = FALSE;
    bExternPixmap_          = FALSE;
}

// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
X11SalVirtualDevice::~X11SalVirtualDevice()
{
    if( pGraphics_ )
        delete pGraphics_;
    pGraphics_ = NULL;

    if( GetDrawable() && !bExternPixmap_ )
        XFreePixmap( GetXDisplay(), GetDrawable() );
}

SalGraphics* X11SalVirtualDevice::GetGraphics()
{
    if( bGraphics_ )
        return NULL;

    if( pGraphics_ )
        bGraphics_ = TRUE;

    return pGraphics_;
}

void X11SalVirtualDevice::ReleaseGraphics( SalGraphics* )
{ bGraphics_ = FALSE; }

BOOL X11SalVirtualDevice::SetSize( long nDX, long nDY )
{
    if( bExternPixmap_ )
        return FALSE;

    if( !nDX ) nDX = 1;
    if( !nDY ) nDY = 1;

    Pixmap h = XCreatePixmap( GetXDisplay(),
                              pDisplay_->GetDrawable(),
                              nDX, nDY, nDepth_ );

    if( !h )
    {
        if( !GetDrawable() )
        {
            hDrawable_ = XCreatePixmap( GetXDisplay(),
                                        pDisplay_->GetDrawable(),
                                        1, 1, nDepth_ );
            nDX_ = 1;
            nDY_ = 1;
        }
        return FALSE;
    }

    if( GetDrawable() )
        XFreePixmap( GetXDisplay(), GetDrawable() );
    hDrawable_ = h;

    nDX_ = nDX;
    nDY_ = nDY;

    if( pGraphics_ )
        InitGraphics( this );

    return TRUE;
}

void X11SalVirtualDevice::GetSize( long& rWidth, long& rHeight )
{
    rWidth  = GetWidth();
    rHeight = GetHeight();
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.14.4); FILE MERGED 2006/09/01 17:58:09 kaib 1.14.4.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: salvd.cxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 12:39:55 $
 *
 *  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_vcl.hxx"

#include <prex.h>
#include <X11/extensions/Xrender.h>
#include <postx.h>

#include <salunx.h>

#ifndef _SV_SALDATA_HXX
#include <saldata.hxx>
#endif
#ifndef _SV_SALDISP_HXX
#include <saldisp.hxx>
#endif
#ifndef _SV_SALINST_HXX
#include <salinst.hxx>
#endif
#ifndef _SV_SALGDI_H
#include <salgdi.h>
#endif
#ifndef _SV_SALVD_H
#include <salvd.h>
#endif
#ifndef _SV_SYSDATA_HXX
#include <sysdata.hxx>
#endif

// -=-= SalInstance =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
SalVirtualDevice* X11SalInstance::CreateVirtualDevice( SalGraphics* pGraphics,
                                                       long nDX, long nDY,
                                                       USHORT nBitCount, const SystemGraphicsData *pData )
{
    X11SalVirtualDevice *pVDev = new X11SalVirtualDevice();
    if( !nBitCount && pGraphics )
        nBitCount = pGraphics->GetBitCount();

    SalDisplay* pSalDisplay = GetX11SalData()->GetDisplay();
    if( pData && pData->hDrawable != None )
    {
        XLIB_Window aRoot;
        int x, y;
        unsigned int w = 0, h = 0, bw, d;
        XGetGeometry( pSalDisplay->GetDisplay(), pData->hDrawable,
                      &aRoot, &x, &y, &w, &h, &bw, &d );
        nDX = (long)w;
        nDY = (long)h;
        if( !pVDev->Init( pSalDisplay, nDX, nDY, nBitCount, pData->hDrawable, pData->pRenderFormat ) )
        {
            delete pVDev;
            return NULL;
        }
    }
    else if( !pVDev->Init( pSalDisplay, nDX, nDY, nBitCount ) )
    {
        delete pVDev;
        return NULL;
    }

    pVDev->InitGraphics( pVDev );
    return pVDev;
}

void X11SalInstance::DestroyVirtualDevice( SalVirtualDevice* pDevice )
{
    delete pDevice;
}

// -=-= SalGraphicsData =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
void X11SalGraphics::Init( X11SalVirtualDevice *pDevice, SalColormap* pColormap, bool bDeleteColormap )
{
    SalDisplay *pDisplay  = pDevice->GetDisplay();

    int nVisualDepth = pDisplay->GetColormap().GetVisual()->GetDepth();
    int nDeviceDepth = pDevice->GetDepth();

    if( pColormap )
    {
        m_pColormap = pColormap;
        if( bDeleteColormap )
            m_pDeleteColormap = m_pColormap;
    }
    else
    if( nDeviceDepth == nVisualDepth )
        m_pColormap = &pDisplay->GetColormap();
    else
    if( nDeviceDepth == 1 )
        m_pDeleteColormap = m_pColormap = new SalColormap();

    hDrawable_   = pDevice->GetDrawable();
    m_pVDev      = pDevice;
    m_pFrame     = NULL;

    bWindow_     = pDisplay->IsDisplay();
    bVirDev_     = TRUE;

    nPenPixel_   = GetPixel( nPenColor_ );
    nTextPixel_  = GetPixel( nTextColor_ );
    nBrushPixel_ = GetPixel( nBrushColor_ );
}

// -=-= SalVirDevData / SalVirtualDevice -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
BOOL X11SalVirtualDevice::Init( SalDisplay *pDisplay,
                                long nDX, long nDY,
                                USHORT nBitCount,
                                Pixmap hDrawable,
                                void* pRenderFormatVoid )
{
    SalColormap* pColormap = NULL;
    bool bDeleteColormap = false;

    pDisplay_               = pDisplay;
    pGraphics_              = new X11SalGraphics();
    if( pRenderFormatVoid ) {
        XRenderPictFormat *pRenderFormat = ( XRenderPictFormat* )pRenderFormatVoid;
        pGraphics_->SetXRenderFormat( pRenderFormat );
        if( pRenderFormat->colormap )
            pColormap = new SalColormap( pDisplay, pRenderFormat->colormap );
        else
            pColormap = new SalColormap( nBitCount );
         bDeleteColormap = true;
    }
    pGraphics_->SetLayout( 0 ); // by default no! mirroring for VirtualDevices, can be enabled with EnableRTL()
    nDX_                    = nDX;
    nDY_                    = nDY;
    nDepth_                 = nBitCount;

    if( hDrawable == None )
        hDrawable_          = XCreatePixmap( GetXDisplay(),
                                             pDisplay_->GetDrawable(),
                                             nDX_, nDY_,
                                             GetDepth() );
    else
    {
        hDrawable_ = hDrawable;
        bExternPixmap_ = TRUE;
    }

    pGraphics_->Init( this, pColormap, bDeleteColormap );

    return hDrawable_ != None ? TRUE : FALSE;
}

// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
X11SalVirtualDevice::X11SalVirtualDevice()
{
    pDisplay_               = (SalDisplay*)ILLEGAL_POINTER;
    pGraphics_              = NULL;
    hDrawable_              = None;
    nDX_                    = 0;
    nDY_                    = 0;
    nDepth_                 = 0;
    bGraphics_              = FALSE;
    bExternPixmap_          = FALSE;
}

// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
X11SalVirtualDevice::~X11SalVirtualDevice()
{
    if( pGraphics_ )
        delete pGraphics_;
    pGraphics_ = NULL;

    if( GetDrawable() && !bExternPixmap_ )
        XFreePixmap( GetXDisplay(), GetDrawable() );
}

SalGraphics* X11SalVirtualDevice::GetGraphics()
{
    if( bGraphics_ )
        return NULL;

    if( pGraphics_ )
        bGraphics_ = TRUE;

    return pGraphics_;
}

void X11SalVirtualDevice::ReleaseGraphics( SalGraphics* )
{ bGraphics_ = FALSE; }

BOOL X11SalVirtualDevice::SetSize( long nDX, long nDY )
{
    if( bExternPixmap_ )
        return FALSE;

    if( !nDX ) nDX = 1;
    if( !nDY ) nDY = 1;

    Pixmap h = XCreatePixmap( GetXDisplay(),
                              pDisplay_->GetDrawable(),
                              nDX, nDY, nDepth_ );

    if( !h )
    {
        if( !GetDrawable() )
        {
            hDrawable_ = XCreatePixmap( GetXDisplay(),
                                        pDisplay_->GetDrawable(),
                                        1, 1, nDepth_ );
            nDX_ = 1;
            nDY_ = 1;
        }
        return FALSE;
    }

    if( GetDrawable() )
        XFreePixmap( GetXDisplay(), GetDrawable() );
    hDrawable_ = h;

    nDX_ = nDX;
    nDY_ = nDY;

    if( pGraphics_ )
        InitGraphics( this );

    return TRUE;
}

void X11SalVirtualDevice::GetSize( long& rWidth, long& rHeight )
{
    rWidth  = GetWidth();
    rHeight = GetHeight();
}
<|endoftext|>