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

#ifndef _SVDXCGV_HXX
#define _SVDXCGV_HXX

#ifndef _SVDEDXV_HXX
#include <svx/svdedxv.hxx>
#endif

#ifndef _GDIMTF_HXX //autogen
#include <vcl/gdimtf.hxx>
#endif

#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif

////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
//
//  @@@@@ @@   @@  @@@@  @@  @@  @@@@  @@  @@  @@@@  @@@@@  @@ @@ @@ @@@@@ @@   @@
//  @@    @@@ @@@ @@  @@ @@  @@ @@  @@ @@@ @@ @@  @@ @@     @@ @@ @@ @@    @@   @@
//  @@     @@@@@  @@     @@  @@ @@  @@ @@@@@@ @@     @@     @@ @@ @@ @@    @@ @ @@
//  @@@@    @@@   @@     @@@@@@ @@@@@@ @@@@@@ @@ @@@ @@@@   @@@@@ @@ @@@@  @@@@@@@
//  @@     @@@@@  @@     @@  @@ @@  @@ @@ @@@ @@  @@ @@      @@@  @@ @@    @@@@@@@
//  @@    @@@ @@@ @@  @@ @@  @@ @@  @@ @@  @@ @@  @@ @@      @@@  @@ @@    @@@ @@@
//  @@@@@ @@   @@  @@@@  @@  @@ @@  @@ @@  @@  @@@@@ @@@@@    @   @@ @@@@@ @@   @@
//
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////

class SVX_DLLPUBLIC SdrExchangeView: public SdrObjEditView
{
    friend class SdrPageView;

protected:

    void                ImpGetPasteObjList(Point& rPos, SdrObjList*& rpLst);
    void                ImpPasteObject(SdrObject* pObj, SdrObjList& rLst, const Point& rCenter, const Size& rSiz, const MapMode& rMap, UINT32 nOptions);
    BOOL                ImpGetPasteLayer(const SdrObjList* pObjList, SdrLayerID& rLayer) const;
    Point               GetPastePos(SdrObjList* pLst, OutputDevice* pOut=NULL);

    // liefert True, wenn rPt geaendert wurde
    BOOL                ImpLimitToWorkArea(Point& rPt) const;

protected:
    // #i71538# make constructors of SdrView sub-components protected to avoid incomplete incarnations which may get casted to SdrView
    SdrExchangeView(SdrModel* pModel1, OutputDevice* pOut = 0L);

public:
    // Alle markierten Objekte auf dem angegebenen OutputDevice ausgeben.
    virtual void        DrawMarkedObj(OutputDevice& rOut, const Point& rOfs) const;

    // Z.B. fuer's Clipboard, Drag&Drop, ...
    // Alle markierten Objekte in ein Metafile stecken. Z.Zt. noch etwas
    // buggee (Offset..., Fremdgrafikobjekte (SdrGrafObj), Virtuelle
    // Objektkopien (SdrVirtObj) mit Ankerpos<>(0,0)).
    virtual GDIMetaFile GetMarkedObjMetaFile(BOOL bNoVDevIfOneMtfMarked=FALSE) const;

    // Alle markierten Objekte auf eine Bitmap malen. Diese hat die Farbtiefe
    // und Aufloesung des Bildschirms.
    virtual Bitmap      GetMarkedObjBitmap(BOOL bNoVDevIfOneBmpMarked=FALSE) const;

    // Alle markierten Objekte in ein neues Model kopieren. Dieses neue Model
    // hat dann genau eine Page. Das Flag PageNotValid an diesem Model ist
    // gesetzt. Daran ist zu erkennen, dass nur die Objekte der Page Gueltikeit
    // haben, die Page sebst jedoch nicht (Seitengroesse, Raender). Das neue
    // Model wird auf dem Heap erzeugt und wird an den Aufrufer dieser Methode
    // uebergeben. Dieser hat es dann spaeter zu entsorgen.
    // Beim einfuegen der markierten Objekte in die eine Page des neuen Model
    // findet ein Merging der seitenlokalen Layer statt. Sollte kein Platz mehr
    // fuer weitere seitenlokale Layer sein, wird den entsprechenden Objekten
    // der Default-Layer zugewiesen (Layer 0, (dokumentglobaler Standardlayer).
    virtual SdrModel*   GetMarkedObjModel() const;

    void            DrawAllMarked(OutputDevice& rOut, const Point& rOfs) const { DrawMarkedObj(rOut,rOfs); }
    GDIMetaFile     GetAllMarkedMetaFile(BOOL bNoVDevIfOneMtfMarked=FALSE) const { return GetMarkedObjMetaFile(bNoVDevIfOneMtfMarked); }
    Bitmap          GetAllMarkedBitmap(BOOL bNoVDevIfOneBmpMarked=FALSE) const { return GetMarkedObjBitmap(bNoVDevIfOneBmpMarked); }
    Graphic         GetAllMarkedGraphic() const;
    SdrModel*       GetAllMarkedModel() const { return GetMarkedObjModel(); }

    /** Generate a Graphic for the given draw object in the given model

        @param pModel
        Must not be NULL. Denotes the draw model the object is a part
        of.

        @param pObj
        The object (can also be a group object) to retrieve a Graphic
        for. Must not be NULL.

        @return a graphical representation of the given object, as it
        appears on screen (e.g. with rotation, if any, applied).
     */
    static Graphic  GetObjGraphic( SdrModel* pModel, SdrObject* pObj );

    // Bestimmung des View-Mittelpunktes, z.B. zum Pasten
    Point           GetViewCenter(const OutputDevice* pOut=NULL) const;

    // Bei allen Paste-Methoden werden die neuen Draw-Objekte markiert.
    // Wird der Parameter bAddMark auf TRUE gesetzt, so werden die neuen
    // DrawObjekte zu einer bereits bestehenden Selektion "hinzumarkiert".
    // Dieser Fall ist fuer Drag&Drop mit mehreren Items gedacht.
    // Die Methoden mit Point-Parameter fuegen neue Objekte zentriert an
    // dieser Position ein, die anderen zentriert am 1.OutputDevice der View.
    // Ist der Parameter pPg gesetzt, werden die Objekte and dieser Seite
    // eingefuegt. Die Positionierung (rPos bzw. Zentrierung) bezieht sich
    // dann nichtmehr auf die View sondern auf die Page.
    // Hinweis: SdrObjList ist Basisklasse von SdrPage.
    // Die Methoden liefern TRUE, wenn die Objekte erfolgreich erzeugt und
    // eingefuegt wurden. Bei pLst=FALSE und kein TextEdit aktiv kann man
    // sich dann auch darauf verlassen, dass diese an der View markiert sind.
    // Andernfalls erfolgt die Markierung nur, wenn pLst z.Zt. auch an der
    // View angezeigt wird.
    // Gueltige Werte fuer nOptions sind SDRINSERT_DONTMARK und
    // SDRINSERT_ADDMARK (siehe svdedtv.hxx).
    BOOL            Paste(const GDIMetaFile& rMtf, SdrObjList* pLst=NULL, OutputDevice* pOut=NULL, UINT32 nOptions=0) { return Paste(rMtf,GetPastePos(pLst,pOut),pLst,nOptions); }
    BOOL            Paste(const GDIMetaFile& rMtf, const Point& rPos, SdrObjList* pLst=NULL, UINT32 nOptions=0);
    BOOL            Paste(const Bitmap& rBmp, SdrObjList* pLst=NULL, OutputDevice* pOut=NULL, UINT32 nOptions=0) { return Paste(rBmp,GetPastePos(pLst,pOut),pLst,nOptions); }
    BOOL            Paste(const Bitmap& rBmp, const Point& rPos, SdrObjList* pLst=NULL, UINT32 nOptions=0);
    BOOL            Paste(const SdrModel& rMod, SdrObjList* pLst=NULL, OutputDevice* pOut=NULL, UINT32 nOptions=0) { return Paste(rMod,GetPastePos(pLst,pOut),pLst,nOptions); }
    virtual BOOL    Paste(const SdrModel& rMod, const Point& rPos, SdrObjList* pLst=NULL, UINT32 nOptions=0);
    BOOL            Paste(const String& rStr, SdrObjList* pLst=NULL, OutputDevice* pOut=NULL, UINT32 nOptions=0) { return Paste(rStr,GetPastePos(pLst,pOut),pLst,nOptions); }
    BOOL            Paste(const String& rStr, const Point& rPos, SdrObjList* pLst=NULL, UINT32 nOptions=0);
    // der USHORT eFormat nimmt Werte des enum EETextFormat entgegen
    BOOL            Paste(SvStream& rInput, const String& rBaseURL, USHORT eFormat, SdrObjList* pLst=NULL, OutputDevice* pOut=NULL, UINT32 nOptions=0) { return Paste(rInput,rBaseURL,eFormat,GetPastePos(pLst,pOut),pLst,nOptions); }
    BOOL            Paste(SvStream& rInput, const String& rBaseURL, USHORT eFormat, const Point& rPos, SdrObjList* pLst=NULL, UINT32 nOptions=0);

    // Feststellen, ob ein bestimmtes Format ueber Drag&Drop bzw. ueber's
    // Clipboard angenommen werden kann.
    BOOL            IsExchangeFormatSupported(ULONG nFormat) const;

    BOOL            Cut( ULONG nFormat = SDR_ANYFORMAT );
    void            CutMarked( ULONG nFormat=SDR_ANYFORMAT );

    BOOL            Yank( ULONG nFormat = SDR_ANYFORMAT );
    void            YankMarked( ULONG nFormat=SDR_ANYFORMAT );

    BOOL            Paste( Window* pWin = NULL, ULONG nFormat = SDR_ANYFORMAT );
    BOOL            PasteClipboard( OutputDevice* pOut = NULL, ULONG nFormat = SDR_ANYFORMAT, UINT32 nOptions = 0 );
};

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

#ifndef _SVDXCGV_HXX
#define _SVDXCGV_HXX

#include <svx/svdedxv.hxx>

#ifndef _GDIMTF_HXX //autogen
#include <vcl/gdimtf.hxx>
#endif
#include "svx/svxdllapi.h"

////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
//
//  @@@@@ @@   @@  @@@@  @@  @@  @@@@  @@  @@  @@@@  @@@@@  @@ @@ @@ @@@@@ @@   @@
//  @@    @@@ @@@ @@  @@ @@  @@ @@  @@ @@@ @@ @@  @@ @@     @@ @@ @@ @@    @@   @@
//  @@     @@@@@  @@     @@  @@ @@  @@ @@@@@@ @@     @@     @@ @@ @@ @@    @@ @ @@
//  @@@@    @@@   @@     @@@@@@ @@@@@@ @@@@@@ @@ @@@ @@@@   @@@@@ @@ @@@@  @@@@@@@
//  @@     @@@@@  @@     @@  @@ @@  @@ @@ @@@ @@  @@ @@      @@@  @@ @@    @@@@@@@
//  @@    @@@ @@@ @@  @@ @@  @@ @@  @@ @@  @@ @@  @@ @@      @@@  @@ @@    @@@ @@@
//  @@@@@ @@   @@  @@@@  @@  @@ @@  @@ @@  @@  @@@@@ @@@@@    @   @@ @@@@@ @@   @@
//
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////

class SVX_DLLPUBLIC SdrExchangeView: public SdrObjEditView
{
    friend class SdrPageView;

protected:

    void                ImpGetPasteObjList(Point& rPos, SdrObjList*& rpLst);
    void                ImpPasteObject(SdrObject* pObj, SdrObjList& rLst, const Point& rCenter, const Size& rSiz, const MapMode& rMap, UINT32 nOptions);
    BOOL                ImpGetPasteLayer(const SdrObjList* pObjList, SdrLayerID& rLayer) const;
    Point               GetPastePos(SdrObjList* pLst, OutputDevice* pOut=NULL);

    // liefert True, wenn rPt geaendert wurde
    BOOL                ImpLimitToWorkArea(Point& rPt) const;

protected:
    // #i71538# make constructors of SdrView sub-components protected to avoid incomplete incarnations which may get casted to SdrView
    SdrExchangeView(SdrModel* pModel1, OutputDevice* pOut = 0L);

public:
    // Alle markierten Objekte auf dem angegebenen OutputDevice ausgeben.
    virtual void        DrawMarkedObj(OutputDevice& rOut, const Point& rOfs) const;

    // Z.B. fuer's Clipboard, Drag&Drop, ...
    // Alle markierten Objekte in ein Metafile stecken. Z.Zt. noch etwas
    // buggee (Offset..., Fremdgrafikobjekte (SdrGrafObj), Virtuelle
    // Objektkopien (SdrVirtObj) mit Ankerpos<>(0,0)).
    virtual GDIMetaFile GetMarkedObjMetaFile(BOOL bNoVDevIfOneMtfMarked=FALSE) const;

    // Alle markierten Objekte auf eine Bitmap malen. Diese hat die Farbtiefe
    // und Aufloesung des Bildschirms.
    virtual Bitmap      GetMarkedObjBitmap(BOOL bNoVDevIfOneBmpMarked=FALSE) const;

    // Alle markierten Objekte in ein neues Model kopieren. Dieses neue Model
    // hat dann genau eine Page. Das Flag PageNotValid an diesem Model ist
    // gesetzt. Daran ist zu erkennen, dass nur die Objekte der Page Gueltikeit
    // haben, die Page sebst jedoch nicht (Seitengroesse, Raender). Das neue
    // Model wird auf dem Heap erzeugt und wird an den Aufrufer dieser Methode
    // uebergeben. Dieser hat es dann spaeter zu entsorgen.
    // Beim einfuegen der markierten Objekte in die eine Page des neuen Model
    // findet ein Merging der seitenlokalen Layer statt. Sollte kein Platz mehr
    // fuer weitere seitenlokale Layer sein, wird den entsprechenden Objekten
    // der Default-Layer zugewiesen (Layer 0, (dokumentglobaler Standardlayer).
    virtual SdrModel*   GetMarkedObjModel() const;

    void            DrawAllMarked(OutputDevice& rOut, const Point& rOfs) const { DrawMarkedObj(rOut,rOfs); }
    GDIMetaFile     GetAllMarkedMetaFile(BOOL bNoVDevIfOneMtfMarked=FALSE) const { return GetMarkedObjMetaFile(bNoVDevIfOneMtfMarked); }
    Bitmap          GetAllMarkedBitmap(BOOL bNoVDevIfOneBmpMarked=FALSE) const { return GetMarkedObjBitmap(bNoVDevIfOneBmpMarked); }
    Graphic         GetAllMarkedGraphic() const;
    SdrModel*       GetAllMarkedModel() const { return GetMarkedObjModel(); }

    /** Generate a Graphic for the given draw object in the given model

        @param pModel
        Must not be NULL. Denotes the draw model the object is a part
        of.

        @param pObj
        The object (can also be a group object) to retrieve a Graphic
        for. Must not be NULL.

        @return a graphical representation of the given object, as it
        appears on screen (e.g. with rotation, if any, applied).
     */
    static Graphic  GetObjGraphic( SdrModel* pModel, SdrObject* pObj );

    // Bestimmung des View-Mittelpunktes, z.B. zum Pasten
    Point           GetViewCenter(const OutputDevice* pOut=NULL) const;

    // Bei allen Paste-Methoden werden die neuen Draw-Objekte markiert.
    // Wird der Parameter bAddMark auf TRUE gesetzt, so werden die neuen
    // DrawObjekte zu einer bereits bestehenden Selektion "hinzumarkiert".
    // Dieser Fall ist fuer Drag&Drop mit mehreren Items gedacht.
    // Die Methoden mit Point-Parameter fuegen neue Objekte zentriert an
    // dieser Position ein, die anderen zentriert am 1.OutputDevice der View.
    // Ist der Parameter pPg gesetzt, werden die Objekte and dieser Seite
    // eingefuegt. Die Positionierung (rPos bzw. Zentrierung) bezieht sich
    // dann nichtmehr auf die View sondern auf die Page.
    // Hinweis: SdrObjList ist Basisklasse von SdrPage.
    // Die Methoden liefern TRUE, wenn die Objekte erfolgreich erzeugt und
    // eingefuegt wurden. Bei pLst=FALSE und kein TextEdit aktiv kann man
    // sich dann auch darauf verlassen, dass diese an der View markiert sind.
    // Andernfalls erfolgt die Markierung nur, wenn pLst z.Zt. auch an der
    // View angezeigt wird.
    // Gueltige Werte fuer nOptions sind SDRINSERT_DONTMARK und
    // SDRINSERT_ADDMARK (siehe svdedtv.hxx).
    BOOL            Paste(const GDIMetaFile& rMtf, SdrObjList* pLst=NULL, OutputDevice* pOut=NULL, UINT32 nOptions=0) { return Paste(rMtf,GetPastePos(pLst,pOut),pLst,nOptions); }
    BOOL            Paste(const GDIMetaFile& rMtf, const Point& rPos, SdrObjList* pLst=NULL, UINT32 nOptions=0);
    BOOL            Paste(const Bitmap& rBmp, SdrObjList* pLst=NULL, OutputDevice* pOut=NULL, UINT32 nOptions=0) { return Paste(rBmp,GetPastePos(pLst,pOut),pLst,nOptions); }
    BOOL            Paste(const Bitmap& rBmp, const Point& rPos, SdrObjList* pLst=NULL, UINT32 nOptions=0);
    BOOL            Paste(const SdrModel& rMod, SdrObjList* pLst=NULL, OutputDevice* pOut=NULL, UINT32 nOptions=0) { return Paste(rMod,GetPastePos(pLst,pOut),pLst,nOptions); }
    virtual BOOL    Paste(const SdrModel& rMod, const Point& rPos, SdrObjList* pLst=NULL, UINT32 nOptions=0);
    BOOL            Paste(const String& rStr, SdrObjList* pLst=NULL, OutputDevice* pOut=NULL, UINT32 nOptions=0) { return Paste(rStr,GetPastePos(pLst,pOut),pLst,nOptions); }
    BOOL            Paste(const String& rStr, const Point& rPos, SdrObjList* pLst=NULL, UINT32 nOptions=0);
    // der USHORT eFormat nimmt Werte des enum EETextFormat entgegen
    BOOL            Paste(SvStream& rInput, const String& rBaseURL, USHORT eFormat, SdrObjList* pLst=NULL, OutputDevice* pOut=NULL, UINT32 nOptions=0) { return Paste(rInput,rBaseURL,eFormat,GetPastePos(pLst,pOut),pLst,nOptions); }
    BOOL            Paste(SvStream& rInput, const String& rBaseURL, USHORT eFormat, const Point& rPos, SdrObjList* pLst=NULL, UINT32 nOptions=0);

    // Feststellen, ob ein bestimmtes Format ueber Drag&Drop bzw. ueber's
    // Clipboard angenommen werden kann.
    BOOL            IsExchangeFormatSupported(ULONG nFormat) const;

    BOOL            Cut( ULONG nFormat = SDR_ANYFORMAT );
    void            CutMarked( ULONG nFormat=SDR_ANYFORMAT );

    BOOL            Yank( ULONG nFormat = SDR_ANYFORMAT );
    void            YankMarked( ULONG nFormat=SDR_ANYFORMAT );

    BOOL            Paste( Window* pWin = NULL, ULONG nFormat = SDR_ANYFORMAT );
    BOOL            PasteClipboard( OutputDevice* pOut = NULL, ULONG nFormat = SDR_ANYFORMAT, UINT32 nOptions = 0 );
};

#endif //_SVDXCGV_HXX
<|endoftext|>


<commit_before>#include <boost/python.hpp>

#include <Magick++/Montage.h>

using namespace boost::python;

void __Montage()
{
    class_< Magick::Montage >("Montage", init<  >())
        .def("backgroundColor",
             (void (Magick::Montage::*)(const Magick::Color&))
             &Magick::Montage::backgroundColor)
        .def("backgroundColor", (Magick::Color (Magick::Montage::*)() const)
             &Magick::Montage::backgroundColor)
        .def("compose",
             (void (Magick::Montage::*)(const Magick::CompositeOperator))
             &Magick::Montage::compose)
        .def("compose",
             (Magick::CompositeOperator (Magick::Montage::*)() const)
             &Magick::Montage::compose)
        .def("fileName", (void (Magick::Montage::*)(const std::string&))
             &Magick::Montage::fileName)
        .def("fileName", (std::string (Magick::Montage::*)() const)
             &Magick::Montage::fileName)
        .def("fillColor", (void (Magick::Montage::*)(const Magick::Color&))
             &Magick::Montage::fillColor)
        .def("fillColor", (Magick::Color (Magick::Montage::*)() const)
             &Magick::Montage::fillColor)
        .def("geometry", (void (Magick::Montage::*)(const Magick::Geometry&))
             &Magick::Montage::geometry)
        .def("geometry", (Magick::Geometry (Magick::Montage::*)() const)
             &Magick::Montage::geometry)
        .def("gravity", (void (Magick::Montage::*)(const Magick::GravityType))
             &Magick::Montage::gravity)
        .def("gravity", (Magick::GravityType (Magick::Montage::*)() const)
             &Magick::Montage::gravity)
        .def("label", (void (Magick::Montage::*)(const std::string&))
             &Magick::Montage::label)
        .def("label", (std::string (Magick::Montage::*)() const)
             &Magick::Montage::label)
        .def("penColor", (void (Magick::Montage::*)(const Magick::Color&))
             &Magick::Montage::penColor)
        .def("penColor", (Magick::Color (Magick::Montage::*)() const)
             &Magick::Montage::penColor)
        .def("pointSize", (void (Magick::Montage::*)(unsigned int))
             &Magick::Montage::pointSize)
        .def("pointSize", (unsigned int (Magick::Montage::*)() const)
             &Magick::Montage::pointSize)
        .def("shadow", (void (Magick::Montage::*)(const bool))
             &Magick::Montage::shadow)
        .def("shadow", (bool (Magick::Montage::*)() const)
             &Magick::Montage::shadow)
        .def("strokeColor", (void (Magick::Montage::*)(const Magick::Color&))
             &Magick::Montage::strokeColor)
        .def("strokeColor", (Magick::Color (Magick::Montage::*)() const)
             &Magick::Montage::strokeColor)
        .def("texture", (void (Magick::Montage::*)(const std::string&))
             &Magick::Montage::texture)
        .def("texture", (std::string (Magick::Montage::*)() const)
             &Magick::Montage::texture)
        .def("title", (void (Magick::Montage::*)(const std::string&))
             &Magick::Montage::title)
        .def("title", (std::string (Magick::Montage::*)() const)
             &Magick::Montage::title)
        .def("transparentColor",
             (void (Magick::Montage::*)(const Magick::Color&))
             &Magick::Montage::transparentColor)
        .def("transparentColor", (Magick::Color (Magick::Montage::*)() const)
             &Magick::Montage::transparentColor)
    ;

    class_< Magick::MontageFramed >("MontageFramed", init<  >())
        .def("borderColor",
             (void (Magick::MontageFramed::*)(const Magick::Color&))
             &Magick::MontageFramed::borderColor)
        .def("borderColor", (Magick::Color (Magick::MontageFramed::*)() const)
             &Magick::MontageFramed::borderColor)
        .def("borderWidth", (void (Magick::MontageFramed::*)(unsigned int))
             &Magick::MontageFramed::borderWidth)
        .def("borderWidth", (unsigned int (Magick::MontageFramed::*)() const)
             &Magick::MontageFramed::borderWidth)
        .def("frameGeometry",
             (void (Magick::MontageFramed::*)(const Magick::Geometry&))
             &Magick::MontageFramed::geometry)
        .def("frameGeometry",
             (Magick::Geometry (Magick::MontageFramed::*)() const)
             &Magick::MontageFramed::geometry)
        .def("matteColor",
             (void (Magick::MontageFramed::*)(const Magick::Color&))
             &Magick::MontageFramed::matteColor)
        .def("matteColor", (Magick::Color (Magick::MontageFramed::*)() const)
             &Magick::MontageFramed::matteColor)
    ;
}
<commit_msg>fixed: Montage.pointSize's in/out parameter for ImageMagick<commit_after>#include <boost/python.hpp>

#include <Magick++/Montage.h>

using namespace boost::python;

void __Montage()
{
    class_< Magick::Montage >("Montage", init<  >())
        .def("backgroundColor",
             (void (Magick::Montage::*)(const Magick::Color&))
             &Magick::Montage::backgroundColor)
        .def("backgroundColor", (Magick::Color (Magick::Montage::*)() const)
             &Magick::Montage::backgroundColor)
        .def("compose",
             (void (Magick::Montage::*)(const Magick::CompositeOperator))
             &Magick::Montage::compose)
        .def("compose",
             (Magick::CompositeOperator (Magick::Montage::*)() const)
             &Magick::Montage::compose)
        .def("fileName", (void (Magick::Montage::*)(const std::string&))
             &Magick::Montage::fileName)
        .def("fileName", (std::string (Magick::Montage::*)() const)
             &Magick::Montage::fileName)
        .def("fillColor", (void (Magick::Montage::*)(const Magick::Color&))
             &Magick::Montage::fillColor)
        .def("fillColor", (Magick::Color (Magick::Montage::*)() const)
             &Magick::Montage::fillColor)
        .def("geometry", (void (Magick::Montage::*)(const Magick::Geometry&))
             &Magick::Montage::geometry)
        .def("geometry", (Magick::Geometry (Magick::Montage::*)() const)
             &Magick::Montage::geometry)
        .def("gravity", (void (Magick::Montage::*)(const Magick::GravityType))
             &Magick::Montage::gravity)
        .def("gravity", (Magick::GravityType (Magick::Montage::*)() const)
             &Magick::Montage::gravity)
        .def("label", (void (Magick::Montage::*)(const std::string&))
             &Magick::Montage::label)
        .def("label", (std::string (Magick::Montage::*)() const)
             &Magick::Montage::label)
        .def("penColor", (void (Magick::Montage::*)(const Magick::Color&))
             &Magick::Montage::penColor)
        .def("penColor", (Magick::Color (Magick::Montage::*)() const)
             &Magick::Montage::penColor)
#ifdef PGMAGICK_LIB_IMAGEMAGICK
        .def("pointSize", (void (Magick::Montage::*)(size_t))
             &Magick::Montage::pointSize)
        .def("pointSize", (size_t (Magick::Montage::*)() const)
             &Magick::Montage::pointSize)
#else
        .def("pointSize", (void (Magick::Montage::*)(unsigned int))
             &Magick::Montage::pointSize)
        .def("pointSize", (unsigned int (Magick::Montage::*)() const)
             &Magick::Montage::pointSize)
#endif
        .def("shadow", (void (Magick::Montage::*)(const bool))
             &Magick::Montage::shadow)
        .def("shadow", (bool (Magick::Montage::*)() const)
             &Magick::Montage::shadow)
        .def("strokeColor", (void (Magick::Montage::*)(const Magick::Color&))
             &Magick::Montage::strokeColor)
        .def("strokeColor", (Magick::Color (Magick::Montage::*)() const)
             &Magick::Montage::strokeColor)
        .def("texture", (void (Magick::Montage::*)(const std::string&))
             &Magick::Montage::texture)
        .def("texture", (std::string (Magick::Montage::*)() const)
             &Magick::Montage::texture)
        .def("title", (void (Magick::Montage::*)(const std::string&))
             &Magick::Montage::title)
        .def("title", (std::string (Magick::Montage::*)() const)
             &Magick::Montage::title)
        .def("transparentColor",
             (void (Magick::Montage::*)(const Magick::Color&))
             &Magick::Montage::transparentColor)
        .def("transparentColor", (Magick::Color (Magick::Montage::*)() const)
             &Magick::Montage::transparentColor)
    ;

    class_< Magick::MontageFramed >("MontageFramed", init<  >())
        .def("borderColor",
             (void (Magick::MontageFramed::*)(const Magick::Color&))
             &Magick::MontageFramed::borderColor)
        .def("borderColor", (Magick::Color (Magick::MontageFramed::*)() const)
             &Magick::MontageFramed::borderColor)
        .def("borderWidth", (void (Magick::MontageFramed::*)(unsigned int))
             &Magick::MontageFramed::borderWidth)
        .def("borderWidth", (unsigned int (Magick::MontageFramed::*)() const)
             &Magick::MontageFramed::borderWidth)
        .def("frameGeometry",
             (void (Magick::MontageFramed::*)(const Magick::Geometry&))
             &Magick::MontageFramed::geometry)
        .def("frameGeometry",
             (Magick::Geometry (Magick::MontageFramed::*)() const)
             &Magick::MontageFramed::geometry)
        .def("matteColor",
             (void (Magick::MontageFramed::*)(const Magick::Color&))
             &Magick::MontageFramed::matteColor)
        .def("matteColor", (Magick::Color (Magick::MontageFramed::*)() const)
             &Magick::MontageFramed::matteColor)
    ;
}
<|endoftext|>


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

#ifndef _SW_APPLET_IMPL_HXX
#define _SW_APPLET_IMPL_HXX

#define SWHTML_OPTTYPE_IGNORE 0
#define SWHTML_OPTTYPE_TAG 1
#define SWHTML_OPTTYPE_PARAM 2
#define SWHTML_OPTTYPE_SIZE 3

#ifndef _COM_SUN_STAR_EMBED_XEMBEDDEDOBJECT_HPP_
#include <com/sun/star/embed/XEmbeddedObject.hpp>
#endif

#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif

#ifndef _HTMLKYWD_HXX
#include <svtools/htmlkywd.hxx>
#endif
#ifndef _FRMHTML_HXX //autogen
#include <sfx2/frmhtml.hxx>
#endif
#ifndef _FRMHTMLW_HXX //autogen
#include <sfx2/frmhtmlw.hxx>
#endif
#ifndef _WRKWIN_HXX //autogen
#include <vcl/wrkwin.hxx>
#endif
#include <sot/storage.hxx>
#ifndef _SFXITEMSET_HXX
#include <svtools/itemset.hxx>
#endif

#include <svtools/ownlist.hxx>

class SfxItemSet;

extern sal_Char const SVTOOLS_CONSTASCII_DECL( sHTML_O_hidden, "HIDDEN" );
extern sal_Char const SVTOOLS_CONSTASCII_DECL( sHTML_HIDDEN_false, "FALSE" );
extern sal_Char const SVTOOLS_CONSTASCII_DECL( sHTML_O_archive, "ARCHIVE" );
extern sal_Char const SVTOOLS_CONSTASCII_DECL( sHTML_O_archives, "ARCHIVES" );
extern sal_Char const SVTOOLS_CONSTASCII_DECL( sHTML_O_object, "OBJECT" );

class SwApplet_Impl
{
    com::sun::star::uno::Reference < com::sun::star::embed::XEmbeddedObject > xApplet;
    SvCommandList     aCommandList; // und die szugehorige Command-List
    SfxItemSet        aItemSet;
    String            sAlt;

public:
    static USHORT GetOptionType( const String& rName, BOOL bApplet );
    SwApplet_Impl( SfxItemPool& rPool, USHORT nWhich1, USHORT nWhich2 );
    SwApplet_Impl( SfxItemSet& rSet ): aItemSet ( rSet) {}
    ~SwApplet_Impl();
    void CreateApplet( const String& rCode, const String& rName,
                       BOOL bMayScript, const String& rCodeBase,
                       const String& rBaseURL );
#ifdef SOLAR_JAVA
    sal_Bool CreateApplet( const String& rBaseURL );
    void AppendParam( const String& rName, const String& rValue );
#endif
    void FinishApplet();
    com::sun::star::uno::Reference < com::sun::star::embed::XEmbeddedObject > GetApplet() { return xApplet; }
    SfxItemSet& GetItemSet() { return aItemSet; }
    const String& GetAltText() { return sAlt; }
    void          SetAltText( const String& rAlt ) {sAlt = rAlt;}
};
#endif
<commit_msg>INTEGRATION: CWS writercorehandoff (1.6.54); FILE MERGED 2005/09/13 11:09:31 tra 1.6.54.2: RESYNC: (1.6-1.7); FILE MERGED 2005/06/07 14:09:35 fme 1.6.54.1: #i50348# General cleanup - removed unused header files, functions, members, declarations etc.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SwAppletImpl.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: hr $ $Date: 2006-08-14 15:14:39 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SW_APPLET_IMPL_HXX
#define _SW_APPLET_IMPL_HXX

#define SWHTML_OPTTYPE_IGNORE 0
#define SWHTML_OPTTYPE_TAG 1
#define SWHTML_OPTTYPE_PARAM 2
#define SWHTML_OPTTYPE_SIZE 3

#ifndef _COM_SUN_STAR_EMBED_XEMBEDDEDOBJECT_HPP_
#include <com/sun/star/embed/XEmbeddedObject.hpp>
#endif

#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif

#ifndef _HTMLKYWD_HXX
#include <svtools/htmlkywd.hxx>
#endif
#ifndef _FRMHTML_HXX //autogen
#include <sfx2/frmhtml.hxx>
#endif
#ifndef _FRMHTMLW_HXX //autogen
#include <sfx2/frmhtmlw.hxx>
#endif
#ifndef _WRKWIN_HXX //autogen
#include <vcl/wrkwin.hxx>
#endif
#include <sot/storage.hxx>
#ifndef _SFXITEMSET_HXX
#include <svtools/itemset.hxx>
#endif

#include <svtools/ownlist.hxx>

class SfxItemSet;

extern sal_Char const SVTOOLS_CONSTASCII_DECL( sHTML_O_hidden, "HIDDEN" );
extern sal_Char const SVTOOLS_CONSTASCII_DECL( sHTML_HIDDEN_false, "FALSE" );
extern sal_Char const SVTOOLS_CONSTASCII_DECL( sHTML_O_archive, "ARCHIVE" );
extern sal_Char const SVTOOLS_CONSTASCII_DECL( sHTML_O_archives, "ARCHIVES" );
extern sal_Char const SVTOOLS_CONSTASCII_DECL( sHTML_O_object, "OBJECT" );

class SwApplet_Impl
{
    com::sun::star::uno::Reference < com::sun::star::embed::XEmbeddedObject > xApplet;
    SvCommandList     aCommandList; // und die szugehorige Command-List
    SfxItemSet        aItemSet;
    String            sAlt;

public:
    static USHORT GetOptionType( const String& rName, BOOL bApplet );
    SwApplet_Impl( SfxItemPool& rPool, USHORT nWhich1, USHORT nWhich2 );
    SwApplet_Impl( SfxItemSet& rSet ): aItemSet ( rSet) {}
    ~SwApplet_Impl();
    void CreateApplet( const String& rCode, const String& rName,
                       BOOL bMayScript, const String& rCodeBase,
                       const String& rBaseURL );
#ifdef SOLAR_JAVA
    sal_Bool CreateApplet( const String& rBaseURL );
    void AppendParam( const String& rName, const String& rValue );
#endif
    void FinishApplet();
    com::sun::star::uno::Reference < com::sun::star::embed::XEmbeddedObject > GetApplet() { return xApplet; }
    SfxItemSet& GetItemSet() { return aItemSet; }
    const String& GetAltText() { return sAlt; }
    void          SetAltText( const String& rAlt ) {sAlt = rAlt;}
};
#endif
<|endoftext|>


<commit_before>
#include <gtest/gtest.h>

#include <aerial_autonomy/common/conversions.h>
#include <aerial_autonomy/controller_connectors/mpc_controller_quad_connector.h>
#include <aerial_autonomy/controller_connectors/visual_servoing_reference_connector.h>
#include <aerial_autonomy/controllers/ddp_quad_mpc_controller.h>
#include <aerial_autonomy/controllers/quad_particle_reference_controller.h>
#include <aerial_autonomy/estimators/thrust_gain_estimator.h>
#include <aerial_autonomy/tests/test_utils.h>
#include <aerial_autonomy/trackers/simple_tracker.h>
#include <chrono>
#include <quad_simulator_parser/quad_simulator.h>
#include <thread>

/**
* @brief Namespace for UAV Simulator Hardware
*/
using namespace quad_simulator;

using namespace test_utils;

class VisualServoingReferenceConnectorTests : public ::testing::Test {
public:
  using VisualServoingReferenceConnectorT =
      VisualServoingReferenceConnector<Eigen::VectorXd, Eigen::VectorXd,
                                       MPCControllerQuadConnector>;

  VisualServoingReferenceConnectorTests()
      : tracking_offset_transform_(
            tf::createQuaternionFromRPY(0, M_PI / 3, M_PI / 2),
            tf::Vector3(0, 0, 0)),
        thrust_gain_estimator_(0.18), tol_(0.5) {
    // Drone settings
    drone_hardware_.usePerfectTime();
    drone_hardware_.set_delay_send_time(0.02);
    // Config
    mpc_config_ = createQuadMPCConfig();
    tf::Transform camera_transform = tf::Transform::getIdentity();
    simple_tracker_.reset(new SimpleTracker(drone_hardware_, camera_transform));
    auto duration = std::chrono::milliseconds(20);
    // Low-level:
    mpc_controller_.reset(new DDPQuadMPCController(mpc_config_, duration));
    quad_mpc_connector_.reset(new MPCControllerQuadConnector(
        drone_hardware_, *mpc_controller_, thrust_gain_estimator_));
    // High level
    reference_generator_.reset(
        new QuadParticleReferenceController(particle_reference_config_));
    visual_servoing_connector_.reset(new VisualServoingReferenceConnectorT(
        *simple_tracker_, drone_hardware_, *reference_generator_,
        *quad_mpc_connector_, camera_transform, tracking_offset_transform_));
  }

  static void SetUpTestCase() {
    // Configure logging
    LogConfig log_config;
    log_config.set_directory("/tmp/data");
    Log::instance().configure(log_config);
    DataStreamConfig data_config;
    data_config.set_stream_id("visual_servoing_reference_connector");
    Log::instance().addDataStream(data_config);
    data_config.set_stream_id("quad_mpc_state_estimator");
    Log::instance().addDataStream(data_config);
    data_config.set_stream_id("ddp_quad_mpc_controller");
    Log::instance().addDataStream(data_config);
    data_config.set_stream_id("thrust_gain_estimator");
    Log::instance().addDataStream(data_config);
    data_config.set_stream_id("tracking_vector_estimator");
    Log::instance().addDataStream(data_config);
  }

  void runUntilConvergence(const tf::Transform &tracked_pose,
                           const PositionYaw &goal_relative_pose) {
    simple_tracker_->setTargetPoseGlobalFrame(tracked_pose);
    simple_tracker_->setTrackingIsValid(true);
    tf::Transform gravity_aligned_tracked_pose =
        tracked_pose * tracking_offset_transform_;
    double roll, pitch, yaw;
    gravity_aligned_tracked_pose.getBasis().getRPY(roll, pitch, yaw);
    gravity_aligned_tracked_pose.getBasis().setRPY(0, 0, yaw);
    // Fly quadrotor which sets the altitude to 0.5
    drone_hardware_.setBatteryPercent(60);
    drone_hardware_.takeoff();
    // Set goal
    tf::Transform goal_relative_pose_tf;
    conversions::positionYawToTf(goal_relative_pose, goal_relative_pose_tf);
    visual_servoing_connector_->setGoal(goal_relative_pose);
    visual_servoing_connector_->initialize();
    quad_mpc_connector_->initialize();
    // Run controller until inactive
    auto runController = [&]() {
      visual_servoing_connector_->run();
      quad_mpc_connector_->run();
      return quad_mpc_connector_->getStatus() == ControllerStatus::Active;
    };
    ASSERT_FALSE(test_utils::waitUntilFalse()(runController,
                                              std::chrono::seconds(200),
                                              std::chrono::milliseconds(0)));
    // Check position is the goal position
    parsernode::common::quaddata sensor_data;
    drone_hardware_.getquaddata(sensor_data);
    tf::Transform quad_transform(
        tf::createQuaternionFromRPY(0, 0, sensor_data.rpydata.z),
        tf::Vector3(sensor_data.localpos.x, sensor_data.localpos.y,
                    sensor_data.localpos.z));
    ASSERT_TF_NEAR(quad_transform,
                   gravity_aligned_tracked_pose * goal_relative_pose_tf, tol_);
    ASSERT_EQ(quad_mpc_connector_->getStatus(), ControllerStatus::Completed);
    ASSERT_NEAR(thrust_gain_estimator_.getThrustGain(), 0.16, 2e-2);
  }

  QuadSimulator drone_hardware_;
  std::unique_ptr<SimpleTracker> simple_tracker_;
  std::unique_ptr<QuadParticleReferenceController> reference_generator_;
  std::unique_ptr<VisualServoingReferenceConnectorT> visual_servoing_connector_;
  std::unique_ptr<DDPQuadMPCController> mpc_controller_;
  std::unique_ptr<MPCControllerQuadConnector> quad_mpc_connector_;
  tf::Transform tracking_offset_transform_;
  ThrustGainEstimator thrust_gain_estimator_;
  QuadMPCControllerConfig mpc_config_;
  ParticleReferenceConfig particle_reference_config_;
  double tol_;
};

TEST_F(VisualServoingReferenceConnectorTests, Constructor) {}

TEST_F(VisualServoingReferenceConnectorTests, InitializationTest) {
  // ASSERT_EQ(quad_mpc_connector_->getGoal(), nullptr);
  tf::Transform tracker_pose;
  tracker_pose.setIdentity();
  tracker_pose.setOrigin(tf::Vector3(1, 1, 1));
  simple_tracker_->setTargetPoseGlobalFrame(tracker_pose);
  simple_tracker_->setTrackingIsValid(true);
  visual_servoing_connector_->setGoal(PositionYaw());
  visual_servoing_connector_->initialize();
  auto reference = quad_mpc_connector_->getGoal();
  auto state_control = reference->atTime(20);
  Eigen::VectorXd goal = state_control.first;
  ASSERT_VEC_NEAR(tracker_pose.getOrigin(),
                  tf::Vector3(goal[0], goal[1], goal[2]), 1e-3);
  ASSERT_NEAR(goal[3], 0, 1e-2);
  ASSERT_NEAR(goal[4], 0, 1e-2);
  ASSERT_NEAR(goal[5], M_PI / 2.0, 1e-2);
}

TEST_F(VisualServoingReferenceConnectorTests, CriticalRun) {
  visual_servoing_connector_->setGoal(PositionYaw());
  // make tracking invalid:
  simple_tracker_->setTrackingIsValid(false);
  // Run connector
  visual_servoing_connector_->run();
  ASSERT_EQ(visual_servoing_connector_->getStatus(),
            ControllerStatus::Critical);
}

TEST_F(VisualServoingReferenceConnectorTests, RunUntilConvergence) {
  // set tracking goal
  tf::Transform tracked_pose(tf::createQuaternionFromRPY(0, 0, -0.1),
                             tf::Vector3(2, -0.5, 0.5));
  PositionYaw goal_relative_pose(1, 0, 0, 0.5);
  runUntilConvergence(tracked_pose, goal_relative_pose);
}

int main(int argc, char **argv) {
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<commit_msg>Add fixed test<commit_after>
#include <gtest/gtest.h>

#include <aerial_autonomy/common/conversions.h>
#include <aerial_autonomy/controller_connectors/mpc_controller_quad_connector.h>
#include <aerial_autonomy/controller_connectors/visual_servoing_reference_connector.h>
#include <aerial_autonomy/controllers/ddp_quad_mpc_controller.h>
#include <aerial_autonomy/controllers/quad_particle_reference_controller.h>
#include <aerial_autonomy/estimators/thrust_gain_estimator.h>
#include <aerial_autonomy/tests/test_utils.h>
#include <aerial_autonomy/trackers/simple_tracker.h>
#include <chrono>
#include <quad_simulator_parser/quad_simulator.h>
#include <thread>

/**
* @brief Namespace for UAV Simulator Hardware
*/
using namespace quad_simulator;

using namespace test_utils;

class VisualServoingReferenceConnectorTests : public ::testing::Test {
public:
  using VisualServoingReferenceConnectorT =
      VisualServoingReferenceConnector<Eigen::VectorXd, Eigen::VectorXd,
                                       MPCControllerQuadConnector>;

  VisualServoingReferenceConnectorTests()
      : tracking_offset_transform_(
            tf::createQuaternionFromRPY(0, M_PI / 3, M_PI / 2),
            tf::Vector3(0, 0, 0)),
        thrust_gain_estimator_(0.18), tol_(0.5) {
    // Drone settings
    drone_hardware_.usePerfectTime();
    drone_hardware_.set_delay_send_time(0.02);
    // Config
    mpc_config_ = createQuadMPCConfig();
    tf::Transform camera_transform = tf::Transform::getIdentity();
    simple_tracker_.reset(new SimpleTracker(drone_hardware_, camera_transform));
    auto duration = std::chrono::milliseconds(20);
    // Low-level:
    mpc_controller_.reset(new DDPQuadMPCController(mpc_config_, duration));
    quad_mpc_connector_.reset(new MPCControllerQuadConnector(
        drone_hardware_, *mpc_controller_, thrust_gain_estimator_));
    // High level
    reference_generator_.reset(
        new QuadParticleReferenceController(particle_reference_config_));
    visual_servoing_connector_.reset(new VisualServoingReferenceConnectorT(
        *simple_tracker_, drone_hardware_, *reference_generator_,
        *quad_mpc_connector_, camera_transform, tracking_offset_transform_));
  }

  static void SetUpTestCase() {
    // Configure logging
    LogConfig log_config;
    log_config.set_directory("/tmp/data");
    Log::instance().configure(log_config);
    DataStreamConfig data_config;
    data_config.set_stream_id("visual_servoing_reference_connector");
    Log::instance().addDataStream(data_config);
    data_config.set_stream_id("quad_mpc_state_estimator");
    Log::instance().addDataStream(data_config);
    data_config.set_stream_id("ddp_quad_mpc_controller");
    Log::instance().addDataStream(data_config);
    data_config.set_stream_id("thrust_gain_estimator");
    Log::instance().addDataStream(data_config);
    data_config.set_stream_id("tracking_vector_estimator");
    Log::instance().addDataStream(data_config);
  }

  void runUntilConvergence(const tf::Transform &tracked_pose,
                           const PositionYaw &goal_relative_pose) {
    simple_tracker_->setTargetPoseGlobalFrame(tracked_pose);
    simple_tracker_->setTrackingIsValid(true);
    tf::Transform gravity_aligned_tracked_pose =
        tracked_pose * tracking_offset_transform_;
    double roll, pitch, yaw;
    gravity_aligned_tracked_pose.getBasis().getRPY(roll, pitch, yaw);
    gravity_aligned_tracked_pose.getBasis().setRPY(0, 0, yaw);
    // Fly quadrotor which sets the altitude to 0.5
    drone_hardware_.setBatteryPercent(60);
    drone_hardware_.takeoff();
    // Set goal
    tf::Transform goal_relative_pose_tf;
    conversions::positionYawToTf(goal_relative_pose, goal_relative_pose_tf);
    visual_servoing_connector_->setGoal(goal_relative_pose);
    visual_servoing_connector_->initialize();
    quad_mpc_connector_->initialize();
    // Run controller until inactive
    auto runController = [&]() {
      visual_servoing_connector_->run();
      quad_mpc_connector_->run();
      return quad_mpc_connector_->getStatus() == ControllerStatus::Active;
    };
    ASSERT_FALSE(test_utils::waitUntilFalse()(runController,
                                              std::chrono::seconds(200),
                                              std::chrono::milliseconds(0)));
    // Check position is the goal position
    parsernode::common::quaddata sensor_data;
    drone_hardware_.getquaddata(sensor_data);
    tf::Transform quad_transform(
        tf::createQuaternionFromRPY(0, 0, sensor_data.rpydata.z),
        tf::Vector3(sensor_data.localpos.x, sensor_data.localpos.y,
                    sensor_data.localpos.z));
    ASSERT_TF_NEAR(quad_transform,
                   gravity_aligned_tracked_pose * goal_relative_pose_tf, tol_);
    ASSERT_EQ(quad_mpc_connector_->getStatus(), ControllerStatus::Completed);
    ASSERT_NEAR(thrust_gain_estimator_.getThrustGain(), 0.16, 2e-2);
  }

  QuadSimulator drone_hardware_;
  std::unique_ptr<SimpleTracker> simple_tracker_;
  std::unique_ptr<QuadParticleReferenceController> reference_generator_;
  std::unique_ptr<VisualServoingReferenceConnectorT> visual_servoing_connector_;
  std::unique_ptr<DDPQuadMPCController> mpc_controller_;
  std::unique_ptr<MPCControllerQuadConnector> quad_mpc_connector_;
  tf::Transform tracking_offset_transform_;
  ThrustGainEstimator thrust_gain_estimator_;
  QuadMPCControllerConfig mpc_config_;
  ParticleReferenceConfig particle_reference_config_;
  double tol_;
};

TEST_F(VisualServoingReferenceConnectorTests, Constructor) {}

TEST_F(VisualServoingReferenceConnectorTests, InitializationTest) {
  // ASSERT_EQ(quad_mpc_connector_->getGoal(), nullptr);
  tf::Transform tracker_pose;
  tracker_pose.setIdentity();
  tracker_pose.setOrigin(tf::Vector3(1, 1, 1));
  simple_tracker_->setTargetPoseGlobalFrame(tracker_pose);
  simple_tracker_->setTrackingIsValid(true);
  visual_servoing_connector_->setGoal(PositionYaw());
  visual_servoing_connector_->initialize();
  auto reference = quad_mpc_connector_->getGoal();
  auto state_control = reference->atTime(20);
  Eigen::VectorXd goal = state_control.first;
  ASSERT_VEC_NEAR(tracker_pose.getOrigin(),
                  tf::Vector3(goal[0], goal[1], goal[2]), 1e-3);
  ASSERT_NEAR(goal[3], 0, 1e-2);
  ASSERT_NEAR(goal[4], 0, 1e-2);
  ASSERT_NEAR(goal[5], M_PI / 2.0, 1e-2);
}

TEST_F(VisualServoingReferenceConnectorTests, CriticalRun) {
  visual_servoing_connector_->setGoal(PositionYaw());
  // make tracking invalid:
  simple_tracker_->setTrackingIsValid(false);
  // Run connector
  visual_servoing_connector_->run();
  ASSERT_EQ(visual_servoing_connector_->getStatus(),
            ControllerStatus::Critical);
}

TEST_F(VisualServoingReferenceConnectorTests, RunUntilConvergence) {
  // set tracking goal
  tf::Transform tracked_pose(tf::createQuaternionFromRPY(0, 0, 0.5),
                             tf::Vector3(1, -0.1, 0.5));
  PositionYaw goal_relative_pose(1, 0, 0, 0.5);
  runUntilConvergence(tracked_pose, goal_relative_pose);
}

TEST_F(VisualServoingReferenceConnectorTests,
       RunUntilConvergenceNonZeroRollPitch) {
  // set tracking goal
  tf::Transform tracked_pose(tf::createQuaternionFromRPY(0.1, -0.1, 0.2),
                             tf::Vector3(1, -0.05, 0.5));
  PositionYaw goal_relative_pose(1, 0, 0, 0.5);
  runUntilConvergence(tracked_pose, goal_relative_pose);
}

int main(int argc, char **argv) {
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>#include "iApp.h"
#include "bbcConfig.h"

#include "Poco/DateTimeParser.h"

string iApp::app_name = "iApp";
string iApp::app_version = "1.0.0";

// Archive (compress) logs that are 1MB
#define IAPP_DEF_LOG_SIZE_ARCH_KB_MAX 1024

using namespace bbc::utils;

iApp::iApp(string _app_name, string _app_version, bool _log_to_file, bool _archive_logs) {

    if(!Config::instance()->load_success){
        ofLogError("Config XML failed to load") << Config::data_file_path;
    }else{
        ofLogNotice("Config XML loaded!") << Config::data_file_path;
    }

	auto_hide_cursor = true;
    cursor_visible = true;

    keep_cursor_hidden = false; // a lock

    header_logged = false;

	cursor_duration_ms = 3000;

    if(_app_name != "") app_name = _app_name;
    if(_app_version != "") app_version = _app_version;

    log_to_file = _log_to_file;
    archive_logs = _archive_logs;

    if(CONFIG_GET("log", "to_file", false)) {
        if(!log_to_file) { // not already setup
            log_to_file = true;
            logSetup(CONFIG_GET("log", "append", true));
            logHeader(); // relog header so it gets to file
        }
    }else{
        logSetup();
        logHeader();
    }

    ofSetLogLevel((ofLogLevel)CONFIG_GET("log", "level", (int)OF_LOG_NOTICE));

    if(Config::instance()->attributeExists("config:window", "fps")) {
		int fps = CONFIG_GET("window", "fps", 60);
        ofSetFrameRate(fps);
        ofLogNotice("iApp set") << "fps=" << fps;
    }

	bool vs = CONFIG_GET("window", "vertical_sync", true);

    ofSetVerticalSync(vs);
    ofLogNotice("iApp set") << "vertical_sync=" << vs;

    // NOTE: to get full fps, dont specify fps and set vertical_sync="0"

    if(CONFIG_GET("window", "fullscreen", true)){
		ofToggleFullscreen();
    }

    cursor_timer = ofGetElapsedTimeMillis() + cursor_duration_ms;

    if(CONFIG_GET("mouse", "hide", false)) { // override auto hide cursor
        auto_hide_cursor = false;
        hideCursor(true);
    }else{
      //  showCursor(); // work around 0.8.4 bug: https://github.com/openframeworks/openFrameworks/issues/3052#issuecomment-63941074
    }

    auto_shutdown = CONFIG_GET("shutdown", "enabled", false);

    if(auto_shutdown) { // override auto hide cursor

        string time_str = CONFIG_GET("shutdown", "time", "20:20");

        ofLogNotice("auto_shutdown setting up with time") << time_str;

        Poco::LocalDateTime now;

        int time_zone_dif = now.tzd();

        Poco::DateTime t = Poco::DateTimeParser::parse("%H:%M:%S", time_str, time_zone_dif);

        Poco::LocalDateTime next(now.year(), now.month(), now.day(), t.hour(), t.minute(), t.second());

        if(next < now) {
            ofLogNotice("Shutdown time already elapsed for today making it for tomorrow");

            // Add a day
            Poco::Timespan dif(0, 24, 0, 0, 0);
            shutdown_time = next + dif;

        }else{
            shutdown_time = next;
        }

    }

}

void iApp::setup() {
    ofBaseApp::setup();
    ofLogNotice("iApp:setup");
    // NOT SURE THIS WILL WORK?
}

void iApp::draw(ofEventArgs & args) {
    ofBaseApp::draw(args);

}

void iApp::update(ofEventArgs& args) {
    ofBaseApp::update(args);

    if(auto_hide_cursor) cursorCheck();

    if(keep_cursor_hidden) hideCursor();

    if(auto_shutdown) {
        Poco::LocalDateTime now;

        if( now > shutdown_time && canAutoShutdownNow() ) {
            ofLogWarning("iApp: AUTO SHUTDOWN was scheduled for now. Terminating app.");
            ofExit();
        }
    }

}

bool iApp::canAutoShutdownNow() {
    return true;
}

void iApp::cursorCheck() {

    // cout << "check cursor " << ofGetElapsedTimeMillis() << endl;

    if(cursor_visible) {
        if(ofGetElapsedTimeMillis() >= cursor_timer) { // its been still long enough to auto hide it
            hideCursor();
           // cout << " hideCursor " << ofGetElapsedTimeMillis() << endl;
            // cursor_visible = false;
        }
    }

}

void iApp::toggleCursor() {

    if(cursor_visible) {
        hideCursor();
    }else{
        showCursor();
    }
}

void iApp::hideCursor(bool permanent) {

    // ofLogNotice("iApp::hideCursor");

    // Cursor show and hide not working on mac in 0.8.0 : using workaroud from http://forum.openframeworks.cc/t/ofhidecursor-not-working-on-osx-10-8-v0-8-0/13379/3
    // Is working in 0.8.1 so do a OF compile check here
    //#ifdef __APPLE__
   //     CGDisplayHideCursor(NULL);
   // #else
        ofHideCursor();
   // #endif

    cursor_visible = false;

    if(permanent) keep_cursor_hidden = true;

}

void iApp::showCursor() {

    ofLogNotice("iApp::showCursor");

    //#ifdef __APPLE__
   //     CGDisplayShowCursor(NULL);
   // #else
        ofShowCursor();
    //#endif

    cursor_visible = true;

    if(keep_cursor_hidden) keep_cursor_hidden = false;

}

void iApp::cursorUpdate() {

    // reset the timer that was counting down to when it restarts

    //  cout << "cursorUpdate " << ofGetElapsedTimeMillis() << endl;

    if(!cursor_visible) { // >> why??
        // cursor_visible = true;
        showCursor();
    }

    cursor_timer = ofGetElapsedTimeMillis() + cursor_duration_ms; // reset timer hid it after 3 seconds of no movement
}

//------------------------------------------------------------------------------------------------------

void iApp::keyPressed(ofKeyEventArgs & key) {
    ofBaseApp::keyPressed(key);

}

void iApp::keyReleased(ofKeyEventArgs & key) {
    ofBaseApp::keyReleased(key);

}

//------------------------------------------------------------------------------------------------------

void iApp::mouseMoved( ofMouseEventArgs & mouse ) {
    ofBaseApp::mouseMoved(mouse);

    if(auto_hide_cursor) cursorUpdate();

}

void iApp::mouseDragged( ofMouseEventArgs & mouse ) {
    ofBaseApp::mouseDragged(mouse);

    if(auto_hide_cursor) cursorUpdate();

}

void iApp::mousePressed( ofMouseEventArgs & mouse ) {
    ofBaseApp::mousePressed(mouse);

    if(auto_hide_cursor) cursorUpdate();

}

void iApp::mouseReleased( ofMouseEventArgs & mouse ) {
    ofBaseApp::mouseReleased(mouse);
}

//------------------------------------------------------------------------------------------------------

void iApp::windowResized(ofResizeEventArgs & resize) {
    ofBaseApp::windowResized(resize);

}

void iApp::dragEvent(ofDragInfo dragInfo) {
    ofBaseApp::dragEvent(dragInfo);

}

void iApp::gotMessage(ofMessage msg){
    ofBaseApp::gotMessage(msg);

}

void iApp::exit(ofEventArgs & args) {
    ofBaseApp::exit(args);
    logFooter();
    ofLogToConsole(); // reset logging to file
}

//------------------------------------------------------------------------------------------------------

void iApp::drawCalibration(int alpha) {

    /*
     Draw a screen calibration graphic, useful for projection calibration,
     */

    ofPushStyle();

    float sw = 2.0f;
    ofSetLineWidth(sw);

    float w = ofGetWidth();
    float h = ofGetHeight();

    float cx = w / 2.0;
    float cy = h / 2.0;

    float hsw = sw / 2.0;

    ofSetCircleResolution(36);

    ofSetColor(255, alpha);
    ofNoFill();

    // border
    ofRectMode(OF_RECTMODE_CORNER);
    ofDrawRectangle(hsw, hsw, w-sw, h-sw);

    // diagonal lines
    ofDrawLine(hsw, hsw, w+hsw, h-hsw);
    ofDrawLine(-hsw, h-hsw, w-hsw, hsw);

    // centre lines
    ofDrawLine(cx, 0, cx, h);
    ofDrawLine(0, cy, w, cy);

    // horizontal 1/4 lines
    ofDrawLine(0, h/4, w, h/4);
    ofDrawLine(0, h-h/4, w, h-h/4);

    // Draw centre rect & circle
    ofRectMode(OF_RECTMODE_CENTER);

    float dim = min(w, h) * .66f;

    ofDrawEllipse(cx, cy, dim, dim);

    ofSetLineWidth(1.0f);

    // Draw circles at the sides
    int n = 8;
    float mini_rad = h / n;
    float y;

    for(int i = 0; i<n-1; i++) {
        y = (mini_rad)+(i*mini_rad);
        int c = i % 4;
        switch(c) {
            case 0: ofSetColor(255, alpha); break;
            case 1: ofSetColor(255,0,0, alpha); break;
            case 2: ofSetColor(0,255,0, alpha); break;
            case 3: ofSetColor(0,0,255, alpha); break;
        }

        ofDrawEllipse(0, y, mini_rad, mini_rad); // LHS
        ofDrawEllipse(w, y, mini_rad, mini_rad); // RHS
    }

    // Draw more comprehensive grid

    // do this at the ratio of the screen?
    // TODO: make the ratio dynamic too reading getWidth and getHeight
    float wc = 16.0f;
    float hc = 9.0f;

    float grid_x = w / wc;
    float grid_y = h / hc;

    ofSetColor(255, alpha);

    // vertical lines
    for(int col = 1; col < wc; col++) {
        int gx = round(col * grid_x);
        ofDrawLine(gx, 0, gx, h);
    }

    // horizontal lines
    for(int row = 1; row < hc; row++) {
        int gy = round(row * grid_y);
        ofDrawLine(0, gy, w, gy);
    }

    ofPopStyle();

}

//-----------------------------------------------------------------------------

void iApp::logSetup(bool appending) {

    if(log_to_file) {

        string log_name = app_name + ".log";

        if(archive_logs) {

            ofFile f("logs/" + log_name);

            if(f.exists()) {

                uint64_t sz_kb = f.getSize() / 1024;

                if(sz_kb >= IAPP_DEF_LOG_SIZE_ARCH_KB_MAX) {

                    ofFile parent_dir(f.getEnclosingDirectory());

                    #if defined(TARGET_OSX)
                        string zip_cmd = "gzip '" + f.getAbsolutePath() + "'";
                        ofLogNotice("ARCHIVING LOG with") << zip_cmd;
                        string zip_result = ofSystem(zip_cmd);
                        ofLogNotice("zip_result") << zip_result;

                        string rename_cmd =  "mv '" + f.getAbsolutePath() + ".gz' '" + parent_dir.getAbsolutePath() + "/" + ofGetTimestampString("%Y-%m-%d-%H-%M-%S") + "_" + app_name + ".log.gz'";
                        ofLogNotice("RENAMING LOG ARCHIVE with") << rename_cmd;
                        string rename_result = ofSystem(rename_cmd);
                        ofLogNotice("rename_result") << rename_result;
                    #endif

                    #if defined(TARGET_WIN32)
                        // TODO: Win could use: win7 cmd option: http://superuser.com/questions/110991/can-you-zip-a-file-from-the-command-prompt-using-only-windows-built-in-capabili
                    #endif

                }

            }

        }

        ofLogToFile("logs/" + log_name, appending);
    }

    int level = CONFIG_GET("log", "level", 1);
    // VERBOSE = 0  NOTICE = 1 WARNING = 2 ERROR = 3 FATAL_ERROR = 4 SILENT = 5

    if(level >= 0 && level <= (int)OF_LOG_SILENT) {
        ofSetLogLevel( (ofLogLevel)level );
    }

}

void iApp::logHeader() {
    ofLogNotice("");
    ofLogNotice("--------------------------------------");
    ofLogNotice("--- START ") << app_name << " app v" << app_version << " @ " << ofGetTimestampString("%H:%M:%S %d-%m-%Y");
    ofLogNotice("--- ") << "oF:" << OF_VERSION_MAJOR << "." << OF_VERSION_MINOR << "." << OF_VERSION_PATCH << ", platform:" << ofGetTargetPlatform();
    // TODO: log OS version and name + opengl properties, free gpu memory?
    ofLogNotice("--------------------------------------");

    header_logged = true;
}

void iApp::logFooter() {
    ofLogNotice("--------------------------------------");
    ofLogNotice("--- STOP ") << app_name << " app v" << app_version << " @ " << ofGetTimestampString("%H:%M:%S %d-%m-%Y");
    ofLogNotice("--------------------------------------");
}

//-----------------------------------------------------------------------------
<commit_msg>log to file refactor, adding win 10 file archiving<commit_after>#include "iApp.h"
#include "bbcConfig.h"

#include "Poco/DateTimeParser.h"

string iApp::app_name = "iApp";
string iApp::app_version = "1.0.0";

// Archive (compress) logs that are 1MB
#define IAPP_DEF_LOG_SIZE_ARCH_KB_MAX 1024

using namespace bbc::utils;

iApp::iApp(string _app_name, string _app_version, bool _log_to_file, bool _archive_logs) {

    if(!Config::instance()->load_success){
        ofLogError("Config XML failed to load") << Config::data_file_path;
    }else{
        ofLogNotice("Config XML loaded!") << Config::data_file_path;
    }

	auto_hide_cursor = true;
    cursor_visible = true;

    keep_cursor_hidden = false; // a lock

    header_logged = false;

	cursor_duration_ms = 3000;

    if(_app_name != "") app_name = _app_name;
    if(_app_version != "") app_version = _app_version;

    log_to_file = _log_to_file;
    archive_logs = _archive_logs;

    if(CONFIG_GET("log", "to_file", false)) {
        if(!log_to_file) { // not already setup
            log_to_file = true;
            logSetup(CONFIG_GET("log", "append", true));
            logHeader(); // relog header so it gets to file
        }
    }else{
        logSetup();
        logHeader();
    }

    ofSetLogLevel((ofLogLevel)CONFIG_GET("log", "level", (int)OF_LOG_NOTICE));

    if(Config::instance()->attributeExists("config:window", "fps")) {
		int fps = CONFIG_GET("window", "fps", 60);
        ofSetFrameRate(fps);
        ofLogNotice("iApp set") << "fps=" << fps;
    }

	bool vs = CONFIG_GET("window", "vertical_sync", true);

    ofSetVerticalSync(vs);
    ofLogNotice("iApp set") << "vertical_sync=" << vs;

    // NOTE: to get full fps, dont specify fps and set vertical_sync="0"

    if(CONFIG_GET("window", "fullscreen", true)){
		ofToggleFullscreen();
    }

    cursor_timer = ofGetElapsedTimeMillis() + cursor_duration_ms;

    if(CONFIG_GET("mouse", "hide", false)) { // override auto hide cursor
        auto_hide_cursor = false;
        hideCursor(true);
    }else{
      //  showCursor(); // work around 0.8.4 bug: https://github.com/openframeworks/openFrameworks/issues/3052#issuecomment-63941074
    }

    auto_shutdown = CONFIG_GET("shutdown", "enabled", false);

    if(auto_shutdown) { // override auto hide cursor

        string time_str = CONFIG_GET("shutdown", "time", "20:20");

        ofLogNotice("auto_shutdown setting up with time") << time_str;

        Poco::LocalDateTime now;

        int time_zone_dif = now.tzd();

        Poco::DateTime t = Poco::DateTimeParser::parse("%H:%M:%S", time_str, time_zone_dif);

        Poco::LocalDateTime next(now.year(), now.month(), now.day(), t.hour(), t.minute(), t.second());

        if(next < now) {
            ofLogNotice("Shutdown time already elapsed for today making it for tomorrow");

            // Add a day
            Poco::Timespan dif(0, 24, 0, 0, 0);
            shutdown_time = next + dif;

        }else{
            shutdown_time = next;
        }

    }

}

void iApp::setup() {
    ofBaseApp::setup();
    ofLogNotice("iApp:setup");
    // NOT SURE THIS WILL WORK?
}

void iApp::draw(ofEventArgs & args) {
    ofBaseApp::draw(args);

}

void iApp::update(ofEventArgs& args) {
    ofBaseApp::update(args);

    if(auto_hide_cursor) cursorCheck();

    if(keep_cursor_hidden) hideCursor();

    if(auto_shutdown) {
        Poco::LocalDateTime now;

        if( now > shutdown_time && canAutoShutdownNow() ) {
            ofLogWarning("iApp: AUTO SHUTDOWN was scheduled for now. Terminating app.");
            ofExit();
        }
    }

}

bool iApp::canAutoShutdownNow() {
    return true;
}

void iApp::cursorCheck() {

    // cout << "check cursor " << ofGetElapsedTimeMillis() << endl;

    if(cursor_visible) {
        if(ofGetElapsedTimeMillis() >= cursor_timer) { // its been still long enough to auto hide it
            hideCursor();
           // cout << " hideCursor " << ofGetElapsedTimeMillis() << endl;
            // cursor_visible = false;
        }
    }

}

void iApp::toggleCursor() {

    if(cursor_visible) {
        hideCursor();
    }else{
        showCursor();
    }
}

void iApp::hideCursor(bool permanent) {

    // ofLogNotice("iApp::hideCursor");

    // Cursor show and hide not working on mac in 0.8.0 : using workaroud from http://forum.openframeworks.cc/t/ofhidecursor-not-working-on-osx-10-8-v0-8-0/13379/3
    // Is working in 0.8.1 so do a OF compile check here
    //#ifdef __APPLE__
   //     CGDisplayHideCursor(NULL);
   // #else
        ofHideCursor();
   // #endif

    cursor_visible = false;

    if(permanent) keep_cursor_hidden = true;

}

void iApp::showCursor() {

    ofLogNotice("iApp::showCursor");

    //#ifdef __APPLE__
   //     CGDisplayShowCursor(NULL);
   // #else
        ofShowCursor();
    //#endif

    cursor_visible = true;

    if(keep_cursor_hidden) keep_cursor_hidden = false;

}

void iApp::cursorUpdate() {

    // reset the timer that was counting down to when it restarts

    //  cout << "cursorUpdate " << ofGetElapsedTimeMillis() << endl;

    if(!cursor_visible) { // >> why??
        // cursor_visible = true;
        showCursor();
    }

    cursor_timer = ofGetElapsedTimeMillis() + cursor_duration_ms; // reset timer hid it after 3 seconds of no movement
}

//------------------------------------------------------------------------------------------------------

void iApp::keyPressed(ofKeyEventArgs & key) {
    ofBaseApp::keyPressed(key);

}

void iApp::keyReleased(ofKeyEventArgs & key) {
    ofBaseApp::keyReleased(key);

}

//------------------------------------------------------------------------------------------------------

void iApp::mouseMoved( ofMouseEventArgs & mouse ) {
    ofBaseApp::mouseMoved(mouse);

    if(auto_hide_cursor) cursorUpdate();

}

void iApp::mouseDragged( ofMouseEventArgs & mouse ) {
    ofBaseApp::mouseDragged(mouse);

    if(auto_hide_cursor) cursorUpdate();

}

void iApp::mousePressed( ofMouseEventArgs & mouse ) {
    ofBaseApp::mousePressed(mouse);

    if(auto_hide_cursor) cursorUpdate();

}

void iApp::mouseReleased( ofMouseEventArgs & mouse ) {
    ofBaseApp::mouseReleased(mouse);
}

//------------------------------------------------------------------------------------------------------

void iApp::windowResized(ofResizeEventArgs & resize) {
    ofBaseApp::windowResized(resize);

}

void iApp::dragEvent(ofDragInfo dragInfo) {
    ofBaseApp::dragEvent(dragInfo);

}

void iApp::gotMessage(ofMessage msg){
    ofBaseApp::gotMessage(msg);

}

void iApp::exit(ofEventArgs & args) {
    ofBaseApp::exit(args);
    logFooter();
    ofLogToConsole(); // reset logging to file
}

//------------------------------------------------------------------------------------------------------

void iApp::drawCalibration(int alpha) {

    /*
     Draw a screen calibration graphic, useful for projection calibration,
     */

    ofPushStyle();

    float sw = 2.0f;
    ofSetLineWidth(sw);

    float w = ofGetWidth();
    float h = ofGetHeight();

    float cx = w / 2.0;
    float cy = h / 2.0;

    float hsw = sw / 2.0;

    ofSetCircleResolution(36);

    ofSetColor(255, alpha);
    ofNoFill();

    // border
    ofRectMode(OF_RECTMODE_CORNER);
    ofDrawRectangle(hsw, hsw, w-sw, h-sw);

    // diagonal lines
    ofDrawLine(hsw, hsw, w+hsw, h-hsw);
    ofDrawLine(-hsw, h-hsw, w-hsw, hsw);

    // centre lines
    ofDrawLine(cx, 0, cx, h);
    ofDrawLine(0, cy, w, cy);

    // horizontal 1/4 lines
    ofDrawLine(0, h/4, w, h/4);
    ofDrawLine(0, h-h/4, w, h-h/4);

    // Draw centre rect & circle
    ofRectMode(OF_RECTMODE_CENTER);

    float dim = min(w, h) * .66f;

    ofDrawEllipse(cx, cy, dim, dim);

    ofSetLineWidth(1.0f);

    // Draw circles at the sides
    int n = 8;
    float mini_rad = h / n;
    float y;

    for(int i = 0; i<n-1; i++) {
        y = (mini_rad)+(i*mini_rad);
        int c = i % 4;
        switch(c) {
            case 0: ofSetColor(255, alpha); break;
            case 1: ofSetColor(255,0,0, alpha); break;
            case 2: ofSetColor(0,255,0, alpha); break;
            case 3: ofSetColor(0,0,255, alpha); break;
        }

        ofDrawEllipse(0, y, mini_rad, mini_rad); // LHS
        ofDrawEllipse(w, y, mini_rad, mini_rad); // RHS
    }

    // Draw more comprehensive grid

    // do this at the ratio of the screen?
    // TODO: make the ratio dynamic too reading getWidth and getHeight
    float wc = 16.0f;
    float hc = 9.0f;

    float grid_x = w / wc;
    float grid_y = h / hc;

    ofSetColor(255, alpha);

    // vertical lines
    for(int col = 1; col < wc; col++) {
        int gx = round(col * grid_x);
        ofDrawLine(gx, 0, gx, h);
    }

    // horizontal lines
    for(int row = 1; row < hc; row++) {
        int gy = round(row * grid_y);
        ofDrawLine(0, gy, w, gy);
    }

    ofPopStyle();

}

//-----------------------------------------------------------------------------

void iApp::logSetup(bool appending) {

    if(log_to_file) {

        string log_name = app_name + ".log";

        if(archive_logs) {

            ofFile log_file("logs/" + log_name);

            if(log_file.exists()) {

                uint64_t sz_kb = log_file.getSize() / 1024;

                if(sz_kb >= IAPP_DEF_LOG_SIZE_ARCH_KB_MAX) {

                    ofFile parent_dir(log_file.getEnclosingDirectory());

                    #if defined(TARGET_OSX)
                        string zip_cmd = "gzip '" + log_file.getAbsolutePath() + "'";
                        ofLogNotice("ARCHIVING LOG with") << zip_cmd;
                        string zip_result = ofSystem(zip_cmd);
                        ofLogNotice("zip_result") << zip_result;

                        string rename_cmd =  "mv '" + log_file.getAbsolutePath() + ".gz' '" + parent_dir.getAbsolutePath() + "/" + ofGetTimestampString("%Y-%m-%d-%H-%M-%S") + "_" + app_name + ".log.gz'";
                        ofLogNotice("RENAMING LOG ARCHIVE with") << rename_cmd;
                        string rename_result = ofSystem(rename_cmd);
                        ofLogNotice("rename_result") << rename_result;
                    #endif

                    #if defined(TARGET_WIN32)

                        // TODO: Win7 could use: http://superuser.com/questions/110991/can-you-zip-a-file-from-the-command-prompt-using-only-windows-built-in-capabili

						// Assume windows 10, which comes with tar.exe
						// https://superuser.com/questions/201371/create-zip-folder-from-the-command-line-windows
						// tar.exe -a -c -f out.zip in.txt
						//

						string input_path = log_file.getAbsolutePath();

						stringstream output;
						output << parent_dir.getAbsolutePath() << "\\" << ofGetTimestampString("%Y-%m-%d-%H-%M-%S") << "_" << app_name << ".log.zip";
						string output_path = output.str();
						ofLogToConsole();

						string zip_cmd = "tar.exe -acf \"" + output_path + "\" \"" + input_path + "\"";

						// Note: This will currently have the fullpath to the log inside the zip
						// TODO: fix this above

						// e.g, tar.exe -cvzf "E:\userfiles\Documents\........\bin\data\logs\2020-06-27-10-32-28_APPNAME.log.zip" "E:\userfiles\Documents\........\bin\data\logs\APPNAME.log"

						ofLogNotice("ARCHIVING LOG with") << zip_cmd;

						string zip_result = ofSystem(zip_cmd);

						// ofLogNotice("zip_result") << zip_result;

						// remove the original log file (f
						bool success = log_file.remove();
						ofLogNotice("Existing log file removed") << success;

					#endif

                }

            }

        }

		string log_path = "logs/" + log_name;

		ofLogToConsole();
		ofLogNotice(app_name) << "Logging output to file:" << log_path;

        ofLogToFile(log_path, appending);
    }

    int level = CONFIG_GET("log", "level", 1);
    // VERBOSE = 0  NOTICE = 1 WARNING = 2 ERROR = 3 FATAL_ERROR = 4 SILENT = 5

    if(level >= 0 && level <= (int)OF_LOG_SILENT) {
        ofSetLogLevel( (ofLogLevel)level );
    }

}

void iApp::logHeader() {
    ofLogNotice("");
    ofLogNotice("--------------------------------------");
    ofLogNotice("--- START ") << app_name << " app v" << app_version << " @ " << ofGetTimestampString("%H:%M:%S %d-%m-%Y");
    ofLogNotice("--- ") << "oF:" << OF_VERSION_MAJOR << "." << OF_VERSION_MINOR << "." << OF_VERSION_PATCH << ", platform:" << ofGetTargetPlatform();
    // TODO: log OS version and name + opengl properties, free gpu memory?
    ofLogNotice("--------------------------------------");

    header_logged = true;
}

void iApp::logFooter() {
    ofLogNotice("--------------------------------------");
    ofLogNotice("--- STOP ") << app_name << " app v" << app_version << " @ " << ofGetTimestampString("%H:%M:%S %d-%m-%Y");
    ofLogNotice("--------------------------------------");
}

//-----------------------------------------------------------------------------
<|endoftext|>


<commit_before>/* ===========================================================================
 * The MIT License (MIT)
 *
 * Copyright (c) 2016 Jedidiah Buck McCready <jbuckmccready@gmail.com>
 *
 * 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 "Models/modelsrepo.h"
#include "QmlHelpers/systemintegrator.h"
#include <QApplication>
#include <QHash>
#include <QObject>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QtQml>

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

  using namespace staticpendulum;

  qmlRegisterType<SystemIntegrator>("QmlHelpers", 1, 0, "SystemIntegrator");

  qmlRegisterSingletonType<ModelsRepo>("ModelsRepo", 1, 0, "ModelsRepo",
                                       &ModelsRepo::qmlInstance);

  QQmlApplicationEngine engine;
  // Add import path to resolve Qml modules, note: using qrc path
  engine.addImportPath("qrc:/Qml/");
  engine.rootContext()->setContextProperty("applicationDirPath",
                                           qApp->applicationDirPath());

  engine.load(QUrl(QLatin1String("qrc:/Qml/Main/Main.qml")));

  return app.exec();
}
<commit_msg>force use of basic QSG render loop for smoother rendering when resizing the main window<commit_after>/* ===========================================================================
 * The MIT License (MIT)
 *
 * Copyright (c) 2016 Jedidiah Buck McCready <jbuckmccready@gmail.com>
 *
 * 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 "Models/modelsrepo.h"
#include "QmlHelpers/systemintegrator.h"
#include <QApplication>
#include <QHash>
#include <QObject>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QtQml>

int main(int argc, char *argv[]) {
  // Smoother rendering when resizing the window using the basic render loop
  // see: http://doc.qt.io/qt-5/qtquick-visualcanvas-scenegraph.html
  // for details of how it works
  qputenv("QSG_RENDER_LOOP", "basic");

  QApplication app(argc, argv);

  using namespace staticpendulum;

  qmlRegisterType<SystemIntegrator>("QmlHelpers", 1, 0, "SystemIntegrator");

  qmlRegisterSingletonType<ModelsRepo>("ModelsRepo", 1, 0, "ModelsRepo",
                                       &ModelsRepo::qmlInstance);

  QQmlApplicationEngine engine;
  // Add import path to resolve Qml modules, note: using qrc path
  engine.addImportPath("qrc:/Qml/");
  engine.rootContext()->setContextProperty("applicationDirPath",
                                           qApp->applicationDirPath());

  engine.load(QUrl(QLatin1String("qrc:/Qml/Main/Main.qml")));

  return app.exec();
}
<|endoftext|>