<commit_before>/*************************************************************************
 *
 *  $RCSfile: fmvwimp.hxx,v $
 *
 *  $Revision: 1.24 $
 *
 *  last change: $Author: obo $ $Date: 2005-06-14 16:34:00 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _SVX_FMVWIMP_HXX
#define _SVX_FMVWIMP_HXX

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

#ifndef _COM_SUN_STAR_FORM_XFORM_HPP_
#include <com/sun/star/form/XForm.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_
#include <com/sun/star/container/XIndexAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XENUMERATION_HPP_
#include <com/sun/star/container/XEnumeration.hpp>
#endif
#ifndef _COM_SUN_STAR_FORM_XFORMCONTROLLER_HPP_
#include <com/sun/star/form/XFormController.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINERLISTENER_HPP_
#include <com/sun/star/container/XContainerListener.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_CONTAINEREVENT_HPP_
#include <com/sun/star/container/ContainerEvent.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XFOCUSLISTENER_HPP_
#include <com/sun/star/awt/XFocusListener.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_SQLERROREVENT_HPP_
#include <com/sun/star/sdb/SQLErrorEvent.hpp>
#endif
#ifndef _LINK_HXX //autogen
#include <tools/link.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif

#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif

#ifndef _SVDMARK_HXX
#include "svdmark.hxx"
#endif

//class SdrPageViewWinRec;
class SdrPageViewWindow;

class SdrPageView;
class SdrObject;
class FmFormObj;
class FmFormModel;
class FmFormView;
class FmFormShell;
class Window;
class OutputDevice;

FORWARD_DECLARE_INTERFACE(awt,XControl)
FORWARD_DECLARE_INTERFACE(awt,XWindow)
FORWARD_DECLARE_INTERFACE(beans,XPropertySet)
FORWARD_DECLARE_INTERFACE(util,XNumberFormats)

class FmXFormController;
class FmXFormView;

namespace svx {
    class ODataAccessDescriptor;
    struct OXFormsDescriptor;
}

//==================================================================
// FmXPageViewWinRec
//==================================================================
class FmXPageViewWinRec : public ::cppu::WeakImplHelper1< ::com::sun::star::container::XIndexAccess>
{
    friend class FmXFormView;

    ::std::vector< ::com::sun::star::uno::Reference< ::com::sun::star::form::XFormController > >    m_aControllerList;
    ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >                m_xORB;
    FmXFormView*                m_pViewImpl;
    Window*                     m_pWindow;

public:
    FmXPageViewWinRec(  const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _xORB,
        const SdrPageViewWindow&, FmXFormView* pView);
        //const SdrPageViewWinRec*, FmXFormView* pView);
    ~FmXPageViewWinRec();

// UNO Anbindung

// ::com::sun::star::container::XElementAccess
    virtual ::com::sun::star::uno::Type SAL_CALL getElementType() throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL hasElements() throw(::com::sun::star::uno::RuntimeException);

// ::com::sun::star::container::XEnumerationAccess
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XEnumeration >  SAL_CALL createEnumeration() throw(::com::sun::star::uno::RuntimeException);

// ::com::sun::star::container::XIndexAccess
    virtual sal_Int32 SAL_CALL getCount() throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL getByIndex(sal_Int32 _Index) throw(::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    const vector< ::com::sun::star::uno::Reference< ::com::sun::star::form::XFormController > >& GetList() {return m_aControllerList;}

protected:
    ::com::sun::star::uno::Reference< ::com::sun::star::form::XFormController >  getController( const ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm >& xForm );
    void setController( const ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm >& xForm,
                        const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer >& xCC,
                        FmXFormController* pParent = NULL);
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer >  getControlContainer() const;
    void updateTabOrder( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >& xControl,
                         const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer >& xCC );
    void dispose();
    Window* getWindow() const {return m_pWindow;}
};

typedef vector<FmXPageViewWinRec*> FmWinRecList;
//==================================================================
// FmXFormView
//==================================================================
class FmXFormView : public ::cppu::WeakImplHelper3<
                            ::com::sun::star::form::XFormControllerListener,
                            ::com::sun::star::awt::XFocusListener,
                            ::com::sun::star::container::XContainerListener>
{
    friend class FmFormView;
    friend class FmFormShell;
    friend class FmXFormShell;
    friend class FmXPageViewWinRec;
    class ObjectRemoveListener;
    friend class ObjectRemoveListener;

    ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >    m_xORB;
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow>                   m_xWindow;

    FmFormObj*      m_pMarkedGrid;
    FmFormView*     m_pView;
    sal_uInt32      m_nActivationEvent;
    sal_uInt32      m_nErrorMessageEvent;   // event for an asynchronous error message. See also m_aAsyncError
    sal_uInt32      m_nAutoFocusEvent;      // event for asynchronously setting the focus to a control

    ::com::sun::star::sdb::SQLErrorEvent
                    m_aAsyncError;          // error event which is to be displayed asyn. See m_nErrorMessageEvent.

    FmWinRecList    m_aWinList;             // to be filled in alive mode only

    // Liste der markierten Object, dient zur Restauration beim Umschalten von Alive in DesignMode
    SdrMarkList             m_aMark;
    ObjectRemoveListener*   m_pWatchStoredList;

    sal_Bool        m_bFirstActivation  : 1;

    void AttachControl( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >& rControl, sal_Bool bDetach );
    void AttachControls( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer >&, sal_Bool bDetach );

    FmFormShell* GetFormShell() const;

    void removeGridWindowListening();

protected:
    FmXFormView(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _xORB,
                FmFormView* _pView);
    ~FmXFormView();

    void    saveMarkList( sal_Bool _bSmartUnmark = sal_True );
    void    restoreMarkList( SdrMarkList& _rRestoredMarkList );
    void    stopMarkListWatching();
    void    startMarkListWatching();

    void    notifyViewDying( );
        // notifies this impl class that the anti-impl instance (m_pView) is going to die

public:
    // UNO Anbindung

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

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

// ::com::sun::star::form::XFormControllerListener
    virtual void SAL_CALL formActivated(const ::com::sun::star::lang::EventObject& rEvent) throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL formDeactivated(const ::com::sun::star::lang::EventObject& rEvent) throw(::com::sun::star::uno::RuntimeException);

    // XFocusListener
    virtual void SAL_CALL focusGained( const ::com::sun::star::awt::FocusEvent& e ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL focusLost( const ::com::sun::star::awt::FocusEvent& e ) throw (::com::sun::star::uno::RuntimeException);

    FmFormView* getView() const {return m_pView;}
    FmWinRecList::const_iterator findWindow( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer >& rCC ) const;
    const FmWinRecList& getWindowList() const {return m_aWinList;}

    ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getORB() { return m_xORB; }

    // activation handling
    inline  sal_Bool    hasEverBeenActivated( ) const { return !m_bFirstActivation; }
    inline  void        setHasBeenActivated( ) { m_bFirstActivation = sal_False; }

            void        onFirstViewActivation( const FmFormModel* _pDocModel );

private:
    FmWinRecList::iterator findWindow( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer >& rCC );
    //void addWindow(const SdrPageViewWinRec*);
    void addWindow(const SdrPageViewWindow&);
    void removeWindow( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer >& rCC );
    void Activate(sal_Bool bSync = sal_False);
    void Deactivate(BOOL bDeactivateController = TRUE);

    SdrObject*  implCreateFieldControl( const ::svx::ODataAccessDescriptor& _rColumnDescriptor );
    SdrObject*  implCreateXFormsControl( const ::svx::OXFormsDescriptor &_rDesc );

    /// does some initializations to the newly created control model, returns the ClassId
    sal_Int16   implInitializeNewControlModel( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxModel, const SdrObject* _pObject ) const;

    void createControlLabelPair(
        OutputDevice* _pOutDev,
        sal_Int32 _nYOffsetMM,
        const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxField,
        const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormats >& _rxNumberFormats,
        sal_uInt16 _nObjID,
        const ::rtl::OUString& _rFieldPostfix,
        FmFormObj*& _rpLabel,
        FmFormObj*& _rpControl
    ) const;

    void ObjectRemovedInAliveMode(const SdrObject* pObject);

    // asynchronously displays an error message. See also OnDelayedErrorMessage.
    void    displayAsyncErrorMessage( const ::com::sun::star::sdb::SQLErrorEvent& _rEvent );

    // cancels all pending async events
    void cancelEvents();

    /// the the auto focus to the first (in terms of the tab order) control
    void AutoFocus( sal_Bool _bSync = sal_False );
    DECL_LINK( OnActivate, void* );
    DECL_LINK( OnAutoFocus, void* );
    DECL_LINK( OnDelayedErrorMessage, void* );
};

#endif // _SVX_FMVWIMP_HXX

<commit_msg>INTEGRATION: CWS ooo19126 (1.24.152); FILE MERGED 2005/09/05 14:25:13 rt 1.24.152.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fmvwimp.hxx,v $
 *
 *  $Revision: 1.25 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 23:21:49 $
 *
 *  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 _SVX_FMVWIMP_HXX
#define _SVX_FMVWIMP_HXX

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

#ifndef _COM_SUN_STAR_FORM_XFORM_HPP_
#include <com/sun/star/form/XForm.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_
#include <com/sun/star/container/XIndexAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XENUMERATION_HPP_
#include <com/sun/star/container/XEnumeration.hpp>
#endif
#ifndef _COM_SUN_STAR_FORM_XFORMCONTROLLER_HPP_
#include <com/sun/star/form/XFormController.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINERLISTENER_HPP_
#include <com/sun/star/container/XContainerListener.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_CONTAINEREVENT_HPP_
#include <com/sun/star/container/ContainerEvent.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XFOCUSLISTENER_HPP_
#include <com/sun/star/awt/XFocusListener.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_SQLERROREVENT_HPP_
#include <com/sun/star/sdb/SQLErrorEvent.hpp>
#endif
#ifndef _LINK_HXX //autogen
#include <tools/link.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif

#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif

#ifndef _SVDMARK_HXX
#include "svdmark.hxx"
#endif

//class SdrPageViewWinRec;
class SdrPageViewWindow;

class SdrPageView;
class SdrObject;
class FmFormObj;
class FmFormModel;
class FmFormView;
class FmFormShell;
class Window;
class OutputDevice;

FORWARD_DECLARE_INTERFACE(awt,XControl)
FORWARD_DECLARE_INTERFACE(awt,XWindow)
FORWARD_DECLARE_INTERFACE(beans,XPropertySet)
FORWARD_DECLARE_INTERFACE(util,XNumberFormats)

class FmXFormController;
class FmXFormView;

namespace svx {
    class ODataAccessDescriptor;
    struct OXFormsDescriptor;
}

//==================================================================
// FmXPageViewWinRec
//==================================================================
class FmXPageViewWinRec : public ::cppu::WeakImplHelper1< ::com::sun::star::container::XIndexAccess>
{
    friend class FmXFormView;

    ::std::vector< ::com::sun::star::uno::Reference< ::com::sun::star::form::XFormController > >    m_aControllerList;
    ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >                m_xORB;
    FmXFormView*                m_pViewImpl;
    Window*                     m_pWindow;

public:
    FmXPageViewWinRec(  const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _xORB,
        const SdrPageViewWindow&, FmXFormView* pView);
        //const SdrPageViewWinRec*, FmXFormView* pView);
    ~FmXPageViewWinRec();

// UNO Anbindung

// ::com::sun::star::container::XElementAccess
    virtual ::com::sun::star::uno::Type SAL_CALL getElementType() throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL hasElements() throw(::com::sun::star::uno::RuntimeException);

// ::com::sun::star::container::XEnumerationAccess
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XEnumeration >  SAL_CALL createEnumeration() throw(::com::sun::star::uno::RuntimeException);

// ::com::sun::star::container::XIndexAccess
    virtual sal_Int32 SAL_CALL getCount() throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL getByIndex(sal_Int32 _Index) throw(::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    const vector< ::com::sun::star::uno::Reference< ::com::sun::star::form::XFormController > >& GetList() {return m_aControllerList;}

protected:
    ::com::sun::star::uno::Reference< ::com::sun::star::form::XFormController >  getController( const ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm >& xForm );
    void setController( const ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm >& xForm,
                        const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer >& xCC,
                        FmXFormController* pParent = NULL);
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer >  getControlContainer() const;
    void updateTabOrder( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >& xControl,
                         const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer >& xCC );
    void dispose();
    Window* getWindow() const {return m_pWindow;}
};

typedef vector<FmXPageViewWinRec*> FmWinRecList;
//==================================================================
// FmXFormView
//==================================================================
class FmXFormView : public ::cppu::WeakImplHelper3<
                            ::com::sun::star::form::XFormControllerListener,
                            ::com::sun::star::awt::XFocusListener,
                            ::com::sun::star::container::XContainerListener>
{
    friend class FmFormView;
    friend class FmFormShell;
    friend class FmXFormShell;
    friend class FmXPageViewWinRec;
    class ObjectRemoveListener;
    friend class ObjectRemoveListener;

    ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >    m_xORB;
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow>                   m_xWindow;

    FmFormObj*      m_pMarkedGrid;
    FmFormView*     m_pView;
    sal_uInt32      m_nActivationEvent;
    sal_uInt32      m_nErrorMessageEvent;   // event for an asynchronous error message. See also m_aAsyncError
    sal_uInt32      m_nAutoFocusEvent;      // event for asynchronously setting the focus to a control

    ::com::sun::star::sdb::SQLErrorEvent
                    m_aAsyncError;          // error event which is to be displayed asyn. See m_nErrorMessageEvent.

    FmWinRecList    m_aWinList;             // to be filled in alive mode only

    // Liste der markierten Object, dient zur Restauration beim Umschalten von Alive in DesignMode
    SdrMarkList             m_aMark;
    ObjectRemoveListener*   m_pWatchStoredList;

    sal_Bool        m_bFirstActivation  : 1;

    void AttachControl( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >& rControl, sal_Bool bDetach );
    void AttachControls( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer >&, sal_Bool bDetach );

    FmFormShell* GetFormShell() const;

    void removeGridWindowListening();

protected:
    FmXFormView(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _xORB,
                FmFormView* _pView);
    ~FmXFormView();

    void    saveMarkList( sal_Bool _bSmartUnmark = sal_True );
    void    restoreMarkList( SdrMarkList& _rRestoredMarkList );
    void    stopMarkListWatching();
    void    startMarkListWatching();

    void    notifyViewDying( );
        // notifies this impl class that the anti-impl instance (m_pView) is going to die

public:
    // UNO Anbindung

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

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

// ::com::sun::star::form::XFormControllerListener
    virtual void SAL_CALL formActivated(const ::com::sun::star::lang::EventObject& rEvent) throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL formDeactivated(const ::com::sun::star::lang::EventObject& rEvent) throw(::com::sun::star::uno::RuntimeException);

    // XFocusListener
    virtual void SAL_CALL focusGained( const ::com::sun::star::awt::FocusEvent& e ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL focusLost( const ::com::sun::star::awt::FocusEvent& e ) throw (::com::sun::star::uno::RuntimeException);

    FmFormView* getView() const {return m_pView;}
    FmWinRecList::const_iterator findWindow( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer >& rCC ) const;
    const FmWinRecList& getWindowList() const {return m_aWinList;}

    ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getORB() { return m_xORB; }

    // activation handling
    inline  sal_Bool    hasEverBeenActivated( ) const { return !m_bFirstActivation; }
    inline  void        setHasBeenActivated( ) { m_bFirstActivation = sal_False; }

            void        onFirstViewActivation( const FmFormModel* _pDocModel );

private:
    FmWinRecList::iterator findWindow( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer >& rCC );
    //void addWindow(const SdrPageViewWinRec*);
    void addWindow(const SdrPageViewWindow&);
    void removeWindow( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer >& rCC );
    void Activate(sal_Bool bSync = sal_False);
    void Deactivate(BOOL bDeactivateController = TRUE);

    SdrObject*  implCreateFieldControl( const ::svx::ODataAccessDescriptor& _rColumnDescriptor );
    SdrObject*  implCreateXFormsControl( const ::svx::OXFormsDescriptor &_rDesc );

    /// does some initializations to the newly created control model, returns the ClassId
    sal_Int16   implInitializeNewControlModel( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxModel, const SdrObject* _pObject ) const;

    void createControlLabelPair(
        OutputDevice* _pOutDev,
        sal_Int32 _nYOffsetMM,
        const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxField,
        const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormats >& _rxNumberFormats,
        sal_uInt16 _nObjID,
        const ::rtl::OUString& _rFieldPostfix,
        FmFormObj*& _rpLabel,
        FmFormObj*& _rpControl
    ) const;

    void ObjectRemovedInAliveMode(const SdrObject* pObject);

    // asynchronously displays an error message. See also OnDelayedErrorMessage.
    void    displayAsyncErrorMessage( const ::com::sun::star::sdb::SQLErrorEvent& _rEvent );

    // cancels all pending async events
    void cancelEvents();

    /// the the auto focus to the first (in terms of the tab order) control
    void AutoFocus( sal_Bool _bSync = sal_False );
    DECL_LINK( OnActivate, void* );
    DECL_LINK( OnAutoFocus, void* );
    DECL_LINK( OnDelayedErrorMessage, void* );
};

#endif // _SVX_FMVWIMP_HXX

<|endoftext|>


<commit_before>
/*
 * Copyright 2013 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "Benchmark.h"
#include "SkDeferredCanvas.h"
#include "SkDevice.h"
#include "SkImage.h"
#include "SkSurface.h"
#if SK_SUPPORT_GPU
#include "GrRenderTarget.h"
#endif

class DeferredSurfaceCopyBench : public Benchmark {
    enum {
        kSurfaceWidth = 1000,
        kSurfaceHeight = 1000,
    };
public:
    DeferredSurfaceCopyBench(bool discardableContents) {
        fDiscardableContents = discardableContents;
    }

protected:
    virtual const char* onGetName() SK_OVERRIDE {
        return fDiscardableContents ? "DeferredSurfaceCopy_discardable" :
            "DeferredSurfaceCopy_nonDiscardable";
    }

    virtual void onDraw(const int loops, SkCanvas* canvas) SK_OVERRIDE {
        // The canvas is not actually used for this test except to provide
        // configuration information: gpu, multisampling, size, etc?
        SkImageInfo info = SkImageInfo::MakeN32Premul(kSurfaceWidth, kSurfaceHeight);
        const SkRect fullCanvasRect = SkRect::MakeWH(
            SkIntToScalar(kSurfaceWidth), SkIntToScalar(kSurfaceHeight));
        SkAutoTUnref<SkSurface> surface(canvas->newSurface(info));
        SkAutoTUnref<SkDeferredCanvas> drawingCanvas(SkDeferredCanvas::Create(surface));

        for (int iteration = 0; iteration < loops; iteration++) {
            drawingCanvas->clear(0);
            SkAutoTUnref<SkImage> image(drawingCanvas->newImageSnapshot());
            SkPaint paint;
            if (!fDiscardableContents) {
                // If paint is not opaque, prior canvas contents are
                // not discardable because they are needed for compositing.
                paint.setAlpha(127);
            }
            drawingCanvas->drawRect(fullCanvasRect, paint);
            // Trigger copy on write, which should be faster in the discardable case.
            drawingCanvas->flush();
        }
    }

private:
    bool fDiscardableContents;

    typedef Benchmark INHERITED;
};

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

DEF_BENCH( return new DeferredSurfaceCopyBench(false); )
DEF_BENCH( return new DeferredSurfaceCopyBench(true); )
<commit_msg>check for newSurface failure<commit_after>
/*
 * Copyright 2013 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "Benchmark.h"
#include "SkDeferredCanvas.h"
#include "SkDevice.h"
#include "SkImage.h"
#include "SkSurface.h"
#if SK_SUPPORT_GPU
#include "GrRenderTarget.h"
#endif

class DeferredSurfaceCopyBench : public Benchmark {
    enum {
        kSurfaceWidth = 1000,
        kSurfaceHeight = 1000,
    };
public:
    DeferredSurfaceCopyBench(bool discardableContents) {
        fDiscardableContents = discardableContents;
    }

protected:
    virtual const char* onGetName() SK_OVERRIDE {
        return fDiscardableContents ? "DeferredSurfaceCopy_discardable" :
            "DeferredSurfaceCopy_nonDiscardable";
    }

    virtual void onDraw(const int loops, SkCanvas* canvas) SK_OVERRIDE {
        // The canvas is not actually used for this test except to provide
        // configuration information: gpu, multisampling, size, etc?
        SkImageInfo info = SkImageInfo::MakeN32Premul(kSurfaceWidth, kSurfaceHeight);
        const SkRect fullCanvasRect = SkRect::MakeWH(
            SkIntToScalar(kSurfaceWidth), SkIntToScalar(kSurfaceHeight));
        SkAutoTUnref<SkSurface> surface(canvas->newSurface(info));

        // newSurface() can return NULL for several reasons, so we need to check
        if (NULL == surface.get()) {
            SkDebugf("DeferredSurfaceCopyBench newSurface failed, bench results are meaningless\n");
            return; // should we signal the caller that we hit an error?
        }

        SkAutoTUnref<SkDeferredCanvas> drawingCanvas(SkDeferredCanvas::Create(surface));

        for (int iteration = 0; iteration < loops; iteration++) {
            drawingCanvas->clear(0);
            SkAutoTUnref<SkImage> image(drawingCanvas->newImageSnapshot());
            SkPaint paint;
            if (!fDiscardableContents) {
                // If paint is not opaque, prior canvas contents are
                // not discardable because they are needed for compositing.
                paint.setAlpha(127);
            }
            drawingCanvas->drawRect(fullCanvasRect, paint);
            // Trigger copy on write, which should be faster in the discardable case.
            drawingCanvas->flush();
        }
    }

private:
    bool fDiscardableContents;

    typedef Benchmark INHERITED;
};

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

DEF_BENCH( return new DeferredSurfaceCopyBench(false); )
DEF_BENCH( return new DeferredSurfaceCopyBench(true); )
<|endoftext|>


<commit_before>/*
 * Copyright 2014-2015 CyberVision, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <memory>
#include <thread>
#include <kaa/Kaa.hpp>
#include <kaa/IKaaClient.hpp>

#include <kaa/profile/DefaultProfileContainer.hpp>

#include <kaa/configuration/storage/IConfigurationPersistenceManager.hpp>
#include <kaa/configuration/manager/IConfigurationReceiver.hpp>
#include <kaa/configuration/storage/FileConfigurationStorage.hpp>

#include <kaa/logging/Log.hpp>

#include <stdio.h>

using namespace kaa;

using std::cout;
using std::endl;

const char savedConfig[] = "saved_config.cfg";

class UserConfigurationReceiver : public IConfigurationReceiver {
public:
    void displayConfiguration(const KaaRootConfiguration &configuration)
    {
        if (!configuration.AddressList.is_null()) {
            cout << "Configuration body:" << endl;
            auto links = configuration.AddressList.get_array();
            for(auto& e : links) {
                cout << e.label << " - " << e.url << endl;
            }
        }
    }
    virtual void onConfigurationUpdated(const KaaRootConfiguration &configuration)
    {
        displayConfiguration(configuration);
    }
};

int main()
{
    Kaa::init();
    cout << "Configuration demo started" << endl;
    cout << "--= Press Enter to exit =--" << endl;
    IKaaClient& kaaClient = Kaa::getKaaClient();
    // Set up default profile container
    kaaClient.setProfileContainer(std::make_shared<DefaultProfileContainer>());
    kaaClient.updateProfile();
    // Set up a configuration subunit
    IConfigurationStoragePtr storage(std::make_shared<FileConfigurationStorage>(savedConfig));
    kaaClient.setConfigurationStorage(storage);
    UserConfigurationReceiver receiver;
    kaaClient.addConfigurationListener(receiver);
    Kaa::start();
    std::cin.get();
    // Waiting for Enter key pressed before exiting.
    Kaa::stop();
    cout << "Configuration demo stopped" << endl;
    return 0;
}
<commit_msg>KAA-449: Code style fix.<commit_after>/*
 * Copyright 2014-2015 CyberVision, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <memory>
#include <thread>
#include <kaa/Kaa.hpp>
#include <kaa/IKaaClient.hpp>

#include <kaa/profile/DefaultProfileContainer.hpp>

#include <kaa/configuration/storage/IConfigurationPersistenceManager.hpp>
#include <kaa/configuration/manager/IConfigurationReceiver.hpp>
#include <kaa/configuration/storage/FileConfigurationStorage.hpp>

#include <kaa/logging/Log.hpp>

#include <stdio.h>

using namespace kaa;

using std::cout;
using std::endl;

const char savedConfig[] = "saved_config.cfg";

class UserConfigurationReceiver : public IConfigurationReceiver {
public:
    void displayConfiguration(const KaaRootConfiguration &configuration)
    {
        if (!configuration.AddressList.is_null()) {
            cout << "Configuration body:" << endl;
            auto links = configuration.AddressList.get_array();
            for (auto& e : links) {
                 cout << e.label << " - " << e.url << endl;
            }
        }
    }
    virtual void onConfigurationUpdated(const KaaRootConfiguration &configuration)
    {
        displayConfiguration(configuration);
    }
};

int main()
{
    Kaa::init();
    cout << "Configuration demo started" << endl;
    cout << "--= Press Enter to exit =--" << endl;
    IKaaClient& kaaClient = Kaa::getKaaClient();
    // Set up default profile container
    kaaClient.setProfileContainer(std::make_shared<DefaultProfileContainer>());
    kaaClient.updateProfile();
    // Set up a configuration subunit
    IConfigurationStoragePtr storage(std::make_shared<FileConfigurationStorage>(savedConfig));
    kaaClient.setConfigurationStorage(storage);
    UserConfigurationReceiver receiver;
    kaaClient.addConfigurationListener(receiver);
    Kaa::start();
    // Waiting for Enter key pressed before exiting.
    std::cin.get();
    Kaa::stop();
    cout << "Configuration demo stopped" << endl;
    return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/base/x509_util.h"
#include "net/base/x509_util_nss.h"

#include <cert.h>
#include <secoid.h>

#include "base/memory/scoped_ptr.h"
#include "base/memory/ref_counted.h"
#include "crypto/ec_private_key.h"
#include "crypto/rsa_private_key.h"
#include "crypto/scoped_nss_types.h"
#include "crypto/signature_verifier.h"
#include "net/base/x509_certificate.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace net {

namespace {

CERTCertificate* CreateNSSCertHandleFromBytes(const char* data, size_t length) {
  SECItem der_cert;
  der_cert.data = reinterpret_cast<unsigned char*>(const_cast<char*>(data));
  der_cert.len  = length;
  der_cert.type = siDERCertBuffer;

  // Parse into a certificate structure.
  return CERT_NewTempCertificate(CERT_GetDefaultCertDB(), &der_cert, NULL,
                                 PR_FALSE, PR_TRUE);
}

void VerifyCertificateSignature(const std::string& der_cert,
                                const std::vector<uint8>& der_spki) {
  crypto::ScopedPLArenaPool arena;

  CERTSignedData sd;
  memset(&sd, 0, sizeof(sd));

  SECItem der_cert_item = {
    siDERCertBuffer,
    reinterpret_cast<unsigned char*>(const_cast<char*>(der_cert.data())),
    der_cert.size()
  };
  SECStatus rv = SEC_ASN1DecodeItem(arena.get(), &sd,
                                    SEC_ASN1_GET(CERT_SignedDataTemplate),
                                    &der_cert_item);
  ASSERT_EQ(SECSuccess, rv);

  // The CERTSignedData.signatureAlgorithm is decoded, but SignatureVerifier
  // wants the DER encoded form, so re-encode it again.
  SECItem* signature_algorithm = SEC_ASN1EncodeItem(
      arena.get(),
      NULL,
      &sd.signatureAlgorithm,
      SEC_ASN1_GET(SECOID_AlgorithmIDTemplate));
  ASSERT_TRUE(signature_algorithm);

  crypto::SignatureVerifier verifier;
  bool ok = verifier.VerifyInit(
      signature_algorithm->data,
      signature_algorithm->len,
      sd.signature.data,
      sd.signature.len / 8,  // Signature is a BIT STRING, convert to bytes.
      &der_spki[0],
      der_spki.size());

  ASSERT_TRUE(ok);
  verifier.VerifyUpdate(sd.data.data,
                        sd.data.len);

  ok = verifier.VerifyFinal();
  EXPECT_TRUE(ok);
}

void VerifyOriginBoundCert(const std::string& origin,
                           const std::string& der_cert) {
  // Origin Bound Cert OID.
  static const char oid_string[] = "1.3.6.1.4.1.11129.2.1.6";

  // Create object neccessary for extension lookup call.
  SECItem extension_object = {
    siAsciiString,
    (unsigned char*)origin.data(),
    origin.size()
  };

  scoped_refptr<X509Certificate> cert = X509Certificate::CreateFromBytes(
      der_cert.data(), der_cert.size());

  ASSERT_TRUE(cert);

  EXPECT_EQ("anonymous.invalid", cert->subject().GetDisplayName());
  EXPECT_FALSE(cert->HasExpired());

  // IA5Encode and arena allocate SECItem.
  PLArenaPool* arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
  SECItem* expected = SEC_ASN1EncodeItem(arena,
                                         NULL,
                                         &extension_object,
                                         SEC_ASN1_GET(SEC_IA5StringTemplate));

  ASSERT_NE(static_cast<SECItem*>(NULL), expected);

  // Create OID SECItem.
  SECItem ob_cert_oid = { siDEROID, NULL, 0 };
  SECStatus ok = SEC_StringToOID(arena, &ob_cert_oid,
                                 oid_string, 0);

  ASSERT_EQ(SECSuccess, ok);

  SECOidTag ob_cert_oid_tag = SECOID_FindOIDTag(&ob_cert_oid);

  ASSERT_NE(SEC_OID_UNKNOWN, ob_cert_oid_tag);

  // This test is run on Mac and Win where X509Certificate::os_cert_handle isn't
  // an NSS type, so we have to manually create a NSS certificate object so we
  // can use CERT_FindCertExtension.
  CERTCertificate* nss_cert = CreateNSSCertHandleFromBytes(
      der_cert.data(), der_cert.size());
  // Lookup Origin Bound Cert extension in generated cert.
  SECItem actual = { siBuffer, NULL, 0 };
  ok = CERT_FindCertExtension(nss_cert,
                              ob_cert_oid_tag,
                              &actual);
  CERT_DestroyCertificate(nss_cert);
  ASSERT_EQ(SECSuccess, ok);

  // Compare expected and actual extension values.
  PRBool result = SECITEM_ItemsAreEqual(expected, &actual);
  ASSERT_TRUE(result);

  // Do Cleanup.
  SECITEM_FreeItem(&actual, PR_FALSE);
  PORT_FreeArena(arena, PR_FALSE);
}

}  // namespace

// This test creates an origin-bound cert from a RSA private key and
// then verifies the content of the certificate.
TEST(X509UtilNSSTest, CreateOriginBoundCertRSA) {
  // Create a sample ASCII weborigin.
  std::string origin = "http://weborigin.com:443";

  scoped_ptr<crypto::RSAPrivateKey> private_key(
      crypto::RSAPrivateKey::Create(1024));
  std::string der_cert;
  ASSERT_TRUE(x509_util::CreateOriginBoundCertRSA(private_key.get(),
                                                  origin, 1,
                                                  base::TimeDelta::FromDays(1),
                                                  &der_cert));

  VerifyOriginBoundCert(origin, der_cert);

  std::vector<uint8> spki;
  ASSERT_TRUE(private_key->ExportPublicKey(&spki));
  VerifyCertificateSignature(der_cert, spki);
}

// This test creates an origin-bound cert from an EC private key and
// then verifies the content of the certificate.
TEST(X509UtilNSSTest, CreateOriginBoundCertEC) {
  // Create a sample ASCII weborigin.
  std::string origin = "http://weborigin.com:443";

  scoped_ptr<crypto::ECPrivateKey> private_key(
      crypto::ECPrivateKey::Create());
  std::string der_cert;
  ASSERT_TRUE(x509_util::CreateOriginBoundCertEC(private_key.get(),
                                                 origin, 1,
                                                 base::TimeDelta::FromDays(1),
                                                 &der_cert));

  VerifyOriginBoundCert(origin, der_cert);

#if !defined(OS_WIN) && !defined(OS_MACOSX)
  // signature_verifier_win and signature_verifier_mac can't handle EC certs.
  std::vector<uint8> spki;
  ASSERT_TRUE(private_key->ExportPublicKey(&spki));
  VerifyCertificateSignature(der_cert, spki);
#endif
}

}  // namespace net
<commit_msg>Fix leak in X509UtilNSSTest VerifyCertificateSignature.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/base/x509_util.h"
#include "net/base/x509_util_nss.h"

#include <cert.h>
#include <secoid.h>

#include "base/memory/scoped_ptr.h"
#include "base/memory/ref_counted.h"
#include "crypto/ec_private_key.h"
#include "crypto/rsa_private_key.h"
#include "crypto/scoped_nss_types.h"
#include "crypto/signature_verifier.h"
#include "net/base/x509_certificate.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace net {

namespace {

CERTCertificate* CreateNSSCertHandleFromBytes(const char* data, size_t length) {
  SECItem der_cert;
  der_cert.data = reinterpret_cast<unsigned char*>(const_cast<char*>(data));
  der_cert.len  = length;
  der_cert.type = siDERCertBuffer;

  // Parse into a certificate structure.
  return CERT_NewTempCertificate(CERT_GetDefaultCertDB(), &der_cert, NULL,
                                 PR_FALSE, PR_TRUE);
}

void VerifyCertificateSignature(const std::string& der_cert,
                                const std::vector<uint8>& der_spki) {
  crypto::ScopedPLArenaPool arena(PORT_NewArena(DER_DEFAULT_CHUNKSIZE));

  CERTSignedData sd;
  memset(&sd, 0, sizeof(sd));

  SECItem der_cert_item = {
    siDERCertBuffer,
    reinterpret_cast<unsigned char*>(const_cast<char*>(der_cert.data())),
    der_cert.size()
  };
  SECStatus rv = SEC_ASN1DecodeItem(arena.get(), &sd,
                                    SEC_ASN1_GET(CERT_SignedDataTemplate),
                                    &der_cert_item);
  ASSERT_EQ(SECSuccess, rv);

  // The CERTSignedData.signatureAlgorithm is decoded, but SignatureVerifier
  // wants the DER encoded form, so re-encode it again.
  SECItem* signature_algorithm = SEC_ASN1EncodeItem(
      arena.get(),
      NULL,
      &sd.signatureAlgorithm,
      SEC_ASN1_GET(SECOID_AlgorithmIDTemplate));
  ASSERT_TRUE(signature_algorithm);

  crypto::SignatureVerifier verifier;
  bool ok = verifier.VerifyInit(
      signature_algorithm->data,
      signature_algorithm->len,
      sd.signature.data,
      sd.signature.len / 8,  // Signature is a BIT STRING, convert to bytes.
      &der_spki[0],
      der_spki.size());

  ASSERT_TRUE(ok);
  verifier.VerifyUpdate(sd.data.data,
                        sd.data.len);

  ok = verifier.VerifyFinal();
  EXPECT_TRUE(ok);
}

void VerifyOriginBoundCert(const std::string& origin,
                           const std::string& der_cert) {
  // Origin Bound Cert OID.
  static const char oid_string[] = "1.3.6.1.4.1.11129.2.1.6";

  // Create object neccessary for extension lookup call.
  SECItem extension_object = {
    siAsciiString,
    (unsigned char*)origin.data(),
    origin.size()
  };

  scoped_refptr<X509Certificate> cert = X509Certificate::CreateFromBytes(
      der_cert.data(), der_cert.size());

  ASSERT_TRUE(cert);

  EXPECT_EQ("anonymous.invalid", cert->subject().GetDisplayName());
  EXPECT_FALSE(cert->HasExpired());

  // IA5Encode and arena allocate SECItem.
  PLArenaPool* arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
  SECItem* expected = SEC_ASN1EncodeItem(arena,
                                         NULL,
                                         &extension_object,
                                         SEC_ASN1_GET(SEC_IA5StringTemplate));

  ASSERT_NE(static_cast<SECItem*>(NULL), expected);

  // Create OID SECItem.
  SECItem ob_cert_oid = { siDEROID, NULL, 0 };
  SECStatus ok = SEC_StringToOID(arena, &ob_cert_oid,
                                 oid_string, 0);

  ASSERT_EQ(SECSuccess, ok);

  SECOidTag ob_cert_oid_tag = SECOID_FindOIDTag(&ob_cert_oid);

  ASSERT_NE(SEC_OID_UNKNOWN, ob_cert_oid_tag);

  // This test is run on Mac and Win where X509Certificate::os_cert_handle isn't
  // an NSS type, so we have to manually create a NSS certificate object so we
  // can use CERT_FindCertExtension.
  CERTCertificate* nss_cert = CreateNSSCertHandleFromBytes(
      der_cert.data(), der_cert.size());
  // Lookup Origin Bound Cert extension in generated cert.
  SECItem actual = { siBuffer, NULL, 0 };
  ok = CERT_FindCertExtension(nss_cert,
                              ob_cert_oid_tag,
                              &actual);
  CERT_DestroyCertificate(nss_cert);
  ASSERT_EQ(SECSuccess, ok);

  // Compare expected and actual extension values.
  PRBool result = SECITEM_ItemsAreEqual(expected, &actual);
  ASSERT_TRUE(result);

  // Do Cleanup.
  SECITEM_FreeItem(&actual, PR_FALSE);
  PORT_FreeArena(arena, PR_FALSE);
}

}  // namespace

// This test creates an origin-bound cert from a RSA private key and
// then verifies the content of the certificate.
TEST(X509UtilNSSTest, CreateOriginBoundCertRSA) {
  // Create a sample ASCII weborigin.
  std::string origin = "http://weborigin.com:443";

  scoped_ptr<crypto::RSAPrivateKey> private_key(
      crypto::RSAPrivateKey::Create(1024));
  std::string der_cert;
  ASSERT_TRUE(x509_util::CreateOriginBoundCertRSA(private_key.get(),
                                                  origin, 1,
                                                  base::TimeDelta::FromDays(1),
                                                  &der_cert));

  VerifyOriginBoundCert(origin, der_cert);

  std::vector<uint8> spki;
  ASSERT_TRUE(private_key->ExportPublicKey(&spki));
  VerifyCertificateSignature(der_cert, spki);
}

// This test creates an origin-bound cert from an EC private key and
// then verifies the content of the certificate.
TEST(X509UtilNSSTest, CreateOriginBoundCertEC) {
  // Create a sample ASCII weborigin.
  std::string origin = "http://weborigin.com:443";

  scoped_ptr<crypto::ECPrivateKey> private_key(
      crypto::ECPrivateKey::Create());
  std::string der_cert;
  ASSERT_TRUE(x509_util::CreateOriginBoundCertEC(private_key.get(),
                                                 origin, 1,
                                                 base::TimeDelta::FromDays(1),
                                                 &der_cert));

  VerifyOriginBoundCert(origin, der_cert);

#if !defined(OS_WIN) && !defined(OS_MACOSX)
  // signature_verifier_win and signature_verifier_mac can't handle EC certs.
  std::vector<uint8> spki;
  ASSERT_TRUE(private_key->ExportPublicKey(&spki));
  VerifyCertificateSignature(der_cert, spki);
#endif
}

}  // namespace net
<|endoftext|>


<commit_before>/*
 * Copyright 2009-2019 The VOTCA Development Team (http://www.votca.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <numeric>
#include <string>
#include <votca/csg/bead.h>
#include <votca/csg/map.h>
#include <votca/csg/topology.h>
#include <votca/tools/eigen.h>
#include <votca/tools/tokenizer.h>

namespace votca {
namespace csg {
class Molecule;
}  // namespace csg
namespace tools {
class Property;
}  // namespace tools
}  // namespace votca

namespace votca {
namespace csg {
using namespace tools;
using namespace std;

Map::~Map() {

  for (auto &_map : _maps) {
    delete _map;
  }
  _maps.clear();
}

void Map::Apply(const BoundaryCondition & bc) {
  for (auto &_map : _maps) {
    _map->Apply(bc);
  }
}

void Map_Sphere::Initialize(Molecule *in, Bead *out, Property *opts_bead,
                            Property *opts_map) {
  BeadMap::Initialize(in, out, opts_bead, opts_map);

  vector<string> beads;
  vector<double> weights;
  vector<double> fweights;

  // get the beads
  string s(_opts_bead->get("beads").value());
  Tokenizer tok_beads(s, " \n\t");
  tok_beads.ToVector(beads);

  // get vector of weights
  Tokenizer tok_weights(_opts_map->get("weights").value(), " \n\t");
  tok_weights.ConvertToVector<double>(weights);

  // check weather weights and # beads matches
  if (beads.size() != weights.size()) {
    throw runtime_error(
        string("number of subbeads in " + opts_bead->get("name").as<string>() +
               " and number of weights in map " +
               opts_map->get("name").as<string>() + " do not match"));
  }

  // normalize the weights
  double norm = 1. / std::accumulate(weights.begin(), weights.end(), 0.);

  transform(weights.begin(), weights.end(), weights.begin(),
            bind2nd(multiplies<double>(), norm));
  // get the d vector if exists or initialize same as weights
  vector<double> d;
  if (_opts_map->exists("d")) {
    Tokenizer tok_weights2(_opts_map->get("d").value(), " \n\t");
    tok_weights2.ConvertToVector(d);
    // normalize d coefficients
    norm = 1. / std::accumulate(d.begin(), d.end(), 0.);
    transform(d.begin(), d.end(), d.begin(),
              bind2nd(multiplies<double>(), norm));
  } else {
    // initialize force-weights with weights
    d.resize(weights.size());
    copy(weights.begin(), weights.end(), d.begin());
  }

  // check weather number of d coeffs is correct
  if (beads.size() != d.size()) {
    throw runtime_error(
        string("number of subbeads in " + opts_bead->get("name").as<string>() +
               " and number of d-coefficients in map " +
               opts_map->get("name").as<string>() + " do not match"));
  }

  fweights.resize(weights.size());
  // calculate force weights by d_i/w_i
  for (size_t i = 0; i < weights.size(); ++i) {
    if (weights[i] == 0 && d[i] != 0) {
      throw runtime_error(
          "A d coefficient is nonzero while weights is zero in mapping " +
          opts_map->get("name").as<string>());
    }
    if (weights[i] != 0) {
      fweights[i] = d[i] / weights[i];
    } else {
      fweights[i] = 0;
    }
  }

  for (size_t i = 0; i < beads.size(); ++i) {
    Index iin = in->getBeadByName(beads[i]);
    if (iin < 0) {
      throw std::runtime_error(
          string("mapping error: molecule " + beads[i] + " does not exist"));
    }
    AddElem(in->getBead(iin), weights[i], fweights[i]);
  }
}

void Map_Sphere::Apply(const BoundaryCondition & bc) {

  bool bPos, bVel, bF;
  bPos = bVel = bF = false;
  _out->ClearParentBeads();

  // the following is needed for pbc treatment
  double max_dist = 0.5 * bc.getShortestBoxDimension();
  Eigen::Vector3d r0 = Eigen::Vector3d::Zero();
  string name0;
  Index id0 = 0;
  if (_matrix.size() > 0) {
    if (_matrix.front()._in->HasPos()) {
      r0 = _matrix.front()._in->getPos();
      name0 = _matrix.front()._in->getName();
      id0 = _matrix.front()._in->getId();
    }
  }

  double M = 0;
  Eigen::Vector3d cg = Eigen::Vector3d::Zero();
  Eigen::Vector3d f = Eigen::Vector3d::Zero();
  Eigen::Vector3d vel = Eigen::Vector3d::Zero();

  for (auto &iter : _matrix) {
    Bead *bead = iter._in;
    _out->AddParentBead(bead->getId());
    M += bead->getMass();
    if (bead->HasPos()) {
      Eigen::Vector3d r = bc.BCShortestConnection(r0, bead->getPos());
      if (r.norm() > max_dist) {
        cout << r0 << " " << bead->getPos() << endl;
        throw std::runtime_error(
            "coarse-grained bead is bigger than half the box \n (atoms " +
            name0 + " (id " + boost::lexical_cast<string>(id0 + 1) + ")" +
            ", " + bead->getName() + " (id " +
            boost::lexical_cast<string>(bead->getId() + 1) + ")" +
            +" , molecule " +
            boost::lexical_cast<string>(bead->getMoleculeId() + 1) + ")");
      }
      cg += iter._weight * (r + r0);
      bPos = true;
    }
    if (bead->HasVel()) {
      vel += iter._weight * bead->getVel();
      bVel = true;
    }
    if (bead->HasF()) {
      f += iter._force_weight * bead->getF();
      bF = true;
    }
  }
  _out->setMass(M);
  if (bPos) {
    _out->setPos(cg);
  }
  if (bVel) {
    _out->setVel(vel);
  }
  if (bF) {
    _out->setF(f);
  }
}

/// \todo implement this function
void Map_Ellipsoid::Apply(const BoundaryCondition & bc) {

  bool bPos, bVel, bF;
  bPos = bVel = bF = false;

  // the following is needed for pbc treatment
  double max_dist = 0.5 * bc.getShortestBoxDimension();
  Eigen::Vector3d r0 = Eigen::Vector3d::Zero();
  if (_matrix.size() > 0) {
    if (_matrix.front()._in->HasPos()) {
      r0 = _matrix.front()._in->getPos();
    }
  }
  Eigen::Vector3d cg = Eigen::Vector3d::Zero();
  Eigen::Vector3d c = Eigen::Vector3d::Zero();
  Eigen::Vector3d f = Eigen::Vector3d::Zero();
  Eigen::Vector3d vel = Eigen::Vector3d::Zero();

  Index n;
  n = 0;
  _out->ClearParentBeads();
  for (auto &iter : _matrix) {
    Bead *bead = iter._in;
    _out->AddParentBead(bead->getId());
    if (bead->HasPos()) {
      Eigen::Vector3d r = bc.BCShortestConnection(r0, bead->getPos());
      if (r.norm() > max_dist) {
        throw std::runtime_error(
            "coarse-grained bead is bigger than half the box");
      }
      cg += iter._weight * (r + r0);
      bPos = true;
    }
    if (bead->HasVel() == true) {
      vel += iter._weight * bead->getVel();
      bVel = true;
    }
    if (bead->HasF()) {
      /// \todo fix me, right calculation should be F_i = m_cg / sum(w_i) *
      /// sum(w_i/m_i*F_i)
      // f += (*iter)._weight * _in->getBeadF((*iter)._in);
      f += iter._force_weight * bead->getF();
      bF = true;
    }

    if (iter._weight > 0 && bead->HasPos()) {
      c += bead->getPos();
      n++;
    }
  }

  if (bPos) {
    _out->setPos(cg);
  }
  if (bVel) {
    _out->setVel(vel);
  }
  if (bF) {
    _out->setF(f);
  }

  if (!_matrix[0]._in->HasPos()) {
    _out->setU(Eigen::Vector3d::UnitX());
    _out->setV(Eigen::Vector3d::UnitY());
    _out->setW(Eigen::Vector3d::UnitZ());
    return;
  }

  Eigen::Matrix3d m = Eigen::Matrix3d::Zero();
  // calculate the tensor of gyration
  c = c / (double)n;
  for (auto &iter : _matrix) {
    if (iter._weight == 0) {
      continue;
    }
    Bead *bead = iter._in;
    Eigen::Vector3d v = bead->getPos() - c;
    // v = vec(1, 0.5, 0) * 0.*(drand48()-0.5)
    //    + vec(0.5, -1, 0) * (drand48()-0.5)
    //    + vec(0, 0, 1) * (drand48()-0.5);

    // Normalize the tensor with 1/number_of_atoms_per_bead
    m += v * v.transpose() / (double)_matrix.size();
  }

  Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eig;
  eig.computeDirect(m);

  Eigen::Vector3d u = eig.eigenvectors().col(0);
  Eigen::Vector3d v = _matrix[1]._in->getPos() - _matrix[0]._in->getPos();
  v.normalize();

  _out->setV(v);

  Eigen::Vector3d w = _matrix[2]._in->getPos() - _matrix[0]._in->getPos();
  w.normalize();

  if (v.cross(w).dot(u) < 0) {
    u = -u;
  }
  _out->setU(u);

  // write out w
  w = u.cross(v);
  w.normalize();
  _out->setW(w);
}

}  // namespace csg
}  // namespace votca
<commit_msg>Made beadmap apply method safer for MapSphere<commit_after>/*
 * Copyright 2009-2019 The VOTCA Development Team (http://www.votca.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <numeric>
#include <string>
#include <votca/csg/bead.h>
#include <votca/csg/map.h>
#include <votca/csg/topology.h>
#include <votca/tools/eigen.h>
#include <votca/tools/tokenizer.h>

namespace votca {
namespace csg {
class Molecule;
}  // namespace csg
namespace tools {
class Property;
}  // namespace tools
}  // namespace votca

namespace votca {
namespace csg {
using namespace tools;
using namespace std;

Map::~Map() {

  for (auto &_map : _maps) {
    delete _map;
  }
  _maps.clear();
}

void Map::Apply(const BoundaryCondition &bc) {
  for (auto &_map : _maps) {
    _map->Apply(bc);
  }
}

void Map_Sphere::Initialize(Molecule *in, Bead *out, Property *opts_bead,
                            Property *opts_map) {
  BeadMap::Initialize(in, out, opts_bead, opts_map);

  vector<string> beads;
  vector<double> weights;
  vector<double> fweights;

  // get the beads
  string s(_opts_bead->get("beads").value());
  Tokenizer tok_beads(s, " \n\t");
  tok_beads.ToVector(beads);

  // get vector of weights
  Tokenizer tok_weights(_opts_map->get("weights").value(), " \n\t");
  tok_weights.ConvertToVector<double>(weights);

  // check weather weights and # beads matches
  if (beads.size() != weights.size()) {
    throw runtime_error(
        string("number of subbeads in " + opts_bead->get("name").as<string>() +
               " and number of weights in map " +
               opts_map->get("name").as<string>() + " do not match"));
  }

  // normalize the weights
  double norm = 1. / std::accumulate(weights.begin(), weights.end(), 0.);

  transform(weights.begin(), weights.end(), weights.begin(),
            bind2nd(multiplies<double>(), norm));
  // get the d vector if exists or initialize same as weights
  vector<double> d;
  if (_opts_map->exists("d")) {
    Tokenizer tok_weights2(_opts_map->get("d").value(), " \n\t");
    tok_weights2.ConvertToVector(d);
    // normalize d coefficients
    norm = 1. / std::accumulate(d.begin(), d.end(), 0.);
    transform(d.begin(), d.end(), d.begin(),
              bind2nd(multiplies<double>(), norm));
  } else {
    // initialize force-weights with weights
    d.resize(weights.size());
    copy(weights.begin(), weights.end(), d.begin());
  }

  // check weather number of d coeffs is correct
  if (beads.size() != d.size()) {
    throw runtime_error(
        string("number of subbeads in " + opts_bead->get("name").as<string>() +
               " and number of d-coefficients in map " +
               opts_map->get("name").as<string>() + " do not match"));
  }

  fweights.resize(weights.size());
  // calculate force weights by d_i/w_i
  for (size_t i = 0; i < weights.size(); ++i) {
    if (weights[i] == 0 && d[i] != 0) {
      throw runtime_error(
          "A d coefficient is nonzero while weights is zero in mapping " +
          opts_map->get("name").as<string>());
    }
    if (weights[i] != 0) {
      fweights[i] = d[i] / weights[i];
    } else {
      fweights[i] = 0;
    }
  }

  for (size_t i = 0; i < beads.size(); ++i) {
    Index iin = in->getBeadByName(beads[i]);
    if (iin < 0) {
      throw std::runtime_error(
          string("mapping error: molecule " + beads[i] + " does not exist"));
    }
    AddElem(in->getBead(iin), weights[i], fweights[i]);
  }
}

void Map_Sphere::Apply(const BoundaryCondition &bc) {

  assert(_matrix.size() > 0 && "Cannot map to sphere there are no beads");

  bool bPos, bVel, bF;
  bPos = bVel = bF = false;
  _out->ClearParentBeads();

  // the following is needed for pbc treatment
  Eigen::Vector3d r0 = Eigen::Vector3d::Zero();
  string name0;
  Index id0 = 0;
  if (_matrix.size() > 0) {
    if (_matrix.front()._in->HasPos()) {
      r0 = _matrix.front()._in->getPos();
      name0 = _matrix.front()._in->getName();
      id0 = _matrix.front()._in->getId();
    }
  }

  double M = 0;
  Eigen::Vector3d cg = Eigen::Vector3d::Zero();
  Eigen::Vector3d f = Eigen::Vector3d::Zero();
  Eigen::Vector3d vel = Eigen::Vector3d::Zero();

  Bead *bead_max_dist = _matrix.at(0)._in;
  double max_bead_dist =
      bc.BCShortestConnection(r0, bead_max_dist->getPos()).norm();

  for (auto &iter : _matrix) {
    Bead *bead = iter._in;
    _out->AddParentBead(bead->getId());
    M += bead->getMass();
    if (bead->HasPos()) {
      Eigen::Vector3d r = bc.BCShortestConnection(r0, bead->getPos());
      if (r.norm() > max_bead_dist || max_bead_dist < 0.0) {
        max_bead_dist = r.norm();
        bead_max_dist = bead;
      }
      cg += iter._weight * (r + r0);
      bPos = true;
    }
  }

  /// Safety check, if box is not open check if the bead is larger than the
  /// boundaries
  if (bc.getBoxType() != BoundaryCondition::eBoxtype::typeOpen) {
    double max_dist = 0.5 * bc.getShortestBoxDimension();
    if (max_bead_dist > max_dist) {
      cout << r0 << " " << bead_max_dist->getPos() << endl;
      throw std::runtime_error(
          "coarse-grained bead_max_dist is bigger than half the box \n "
          "(atoms " +
          name0 + " (id " + boost::lexical_cast<string>(id0 + 1) + ")" + ", " +
          bead_max_dist->getName() + " (id " +
          boost::lexical_cast<string>(bead_max_dist->getId() + 1) + ")" +
          +" , molecule " +
          boost::lexical_cast<string>(bead_max_dist->getMoleculeId() + 1) +
          ")");
    }
  }

  for (auto &iter : _matrix) {
    Bead *bead = iter._in;
    if (bead->HasVel()) {
      vel += iter._weight * bead->getVel();
      bVel = true;
    }
    if (bead->HasF()) {
      f += iter._force_weight * bead->getF();
      bF = true;
    }
  }
  _out->setMass(M);
  if (bPos) {
    _out->setPos(cg);
  }
  if (bVel) {
    _out->setVel(vel);
  }
  if (bF) {
    _out->setF(f);
  }
}

/// \todo implement this function
void Map_Ellipsoid::Apply(const BoundaryCondition &bc) {

  bool bPos, bVel, bF;
  bPos = bVel = bF = false;

  // the following is needed for pbc treatment
  double max_dist = 0.5 * bc.getShortestBoxDimension();
  Eigen::Vector3d r0 = Eigen::Vector3d::Zero();
  if (_matrix.size() > 0) {
    if (_matrix.front()._in->HasPos()) {
      r0 = _matrix.front()._in->getPos();
    }
  }
  Eigen::Vector3d cg = Eigen::Vector3d::Zero();
  Eigen::Vector3d c = Eigen::Vector3d::Zero();
  Eigen::Vector3d f = Eigen::Vector3d::Zero();
  Eigen::Vector3d vel = Eigen::Vector3d::Zero();

  Index n;
  n = 0;
  _out->ClearParentBeads();
  for (auto &iter : _matrix) {
    Bead *bead = iter._in;
    _out->AddParentBead(bead->getId());
    if (bead->HasPos()) {
      Eigen::Vector3d r = bc.BCShortestConnection(r0, bead->getPos());
      if (r.norm() > max_dist) {
        throw std::runtime_error(
            "coarse-grained bead is bigger than half the box");
      }
      cg += iter._weight * (r + r0);
      bPos = true;
    }
    if (bead->HasVel() == true) {
      vel += iter._weight * bead->getVel();
      bVel = true;
    }
    if (bead->HasF()) {
      /// \todo fix me, right calculation should be F_i = m_cg / sum(w_i) *
      /// sum(w_i/m_i*F_i)
      // f += (*iter)._weight * _in->getBeadF((*iter)._in);
      f += iter._force_weight * bead->getF();
      bF = true;
    }

    if (iter._weight > 0 && bead->HasPos()) {
      c += bead->getPos();
      n++;
    }
  }

  if (bPos) {
    _out->setPos(cg);
  }
  if (bVel) {
    _out->setVel(vel);
  }
  if (bF) {
    _out->setF(f);
  }

  if (!_matrix[0]._in->HasPos()) {
    _out->setU(Eigen::Vector3d::UnitX());
    _out->setV(Eigen::Vector3d::UnitY());
    _out->setW(Eigen::Vector3d::UnitZ());
    return;
  }

  Eigen::Matrix3d m = Eigen::Matrix3d::Zero();
  // calculate the tensor of gyration
  c = c / (double)n;
  for (auto &iter : _matrix) {
    if (iter._weight == 0) {
      continue;
    }
    Bead *bead = iter._in;
    Eigen::Vector3d v = bead->getPos() - c;
    // v = vec(1, 0.5, 0) * 0.*(drand48()-0.5)
    //    + vec(0.5, -1, 0) * (drand48()-0.5)
    //    + vec(0, 0, 1) * (drand48()-0.5);

    // Normalize the tensor with 1/number_of_atoms_per_bead
    m += v * v.transpose() / (double)_matrix.size();
  }

  Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eig;
  eig.computeDirect(m);

  Eigen::Vector3d u = eig.eigenvectors().col(0);
  Eigen::Vector3d v = _matrix[1]._in->getPos() - _matrix[0]._in->getPos();
  v.normalize();

  _out->setV(v);

  Eigen::Vector3d w = _matrix[2]._in->getPos() - _matrix[0]._in->getPos();
  w.normalize();

  if (v.cross(w).dot(u) < 0) {
    u = -u;
  }
  _out->setU(u);

  // write out w
  w = u.cross(v);
  w.normalize();
  _out->setW(w);
}

}  // namespace csg
}  // namespace votca
<|endoftext|>


<commit_before>#include <string>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iterator>
#include <tuple>
#include <regex>
#include <array>
#include <valarray>
#define all(v)begin(v),end(v)
#define dump(v)copy(all(v),ostream_iterator<decltype(*v.begin())>(cout,"\n"))
#define rg(i,a,b)for(int i=a,i##e=b;i<i##e;++i)
#define fr(i,n)for(int i=0,i##e=n;i<i##e;++i)
#define rf(i,n)for(int i=n-1;i>=0;--i)
#define ei(a,m)for(auto&a:m)if(int a##i=&a-&*begin(m)+1)if(--a##i,1)
#define sz(v)int(v.size())
#define sr(v)sort(all(v))
#define rs(v)sort(all(v),greater<int>())
#define rev(v)reverse(all(v))
#define eb emplace_back
#define stst stringstream
#define big numeric_limits<int>::max()
#define g(t,i)get<i>(t)
#define cb(v,w)copy(all(v),back_inserter(w))
#define uni(v)sort(all(v));v.erase(unique(all(v)),end(v))
#define vt(...)vector<tuple<__VA_ARGS__>>
#define smx(a,b)a=max(a,b)
#define smn(a,b)a=min(a,b)
#define words(w,q)vector<string>w;[&w](string&&s){stringstream u(s);string r;while(u>>r)w.eb(r);}(q);
#define digits(d,n,s)vector<int>d;[&d](int m){while(m)d.eb(m%s),m/=s;}(n);
typedef long long ll;
using namespace std;

struct BreakingTheCode {
	string decodingEncoding(string code, string m) {
		string r;
		if (isdigit(m[0])) {
			ei(a, m) if (ai % 2) {
				int p = a[ai - 1];
				r += code[(p - '0') * 10 + a - '0'];
			}
		} else {
			stst ss;
			ei(a, m) {
				int x = code.find(a);
				ss << x / 10 + '0' << x % 10 + '0';
			}
			getline(ss, r);
		}
		return r;
	}
};

// BEGIN KAWIGIEDIT TESTING
// Generated by KawigiEdit-pf 2.3.0
#include <iostream>
#include <string>
#include <vector>
#include <ctime>
#include <cmath>
using namespace std;
bool KawigiEdit_RunTest(int testNum, string p0, string p1, bool hasAnswer, string p2) {
	cout << "Test " << testNum << ": [" << "\"" << p0 << "\"" << "," << "\"" << p1 << "\"";
	cout << "]" << endl;
	BreakingTheCode *obj;
	string answer;
	obj = new BreakingTheCode();
	clock_t startTime = clock();
	answer = obj->decodingEncoding(p0, p1);
	clock_t endTime = clock();
	delete obj;
	bool res;
	res = true;
	cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
	if (hasAnswer) {
		cout << "Desired answer:" << endl;
		cout << "\t" << "\"" << p2 << "\"" << endl;
	}
	cout << "Your answer:" << endl;
	cout << "\t" << "\"" << answer << "\"" << endl;
	if (hasAnswer) {
		res = answer == p2;
	}
	if (!res) {
		cout << "DOESN'T MATCH!!!!" << endl;
	} else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) {
		cout << "FAIL the timeout" << endl;
		res = false;
	} else if (hasAnswer) {
		cout << "Match :-)" << endl;
	} else {
		cout << "OK, but is it right?" << endl;
	}
	cout << "" << endl;
	return res;
}
int main() {
	bool all_right;
	bool disabled;
	bool tests_disabled;
	all_right = true;
	tests_disabled = false;

	string p0;
	string p1;
	string p2;

	// ----- test 0 -----
	disabled = false;
	p0 = "abcdefghijklmnopqrstuvwxyz";
	p1 = "test";
	p2 = "20051920";
	all_right = (disabled || KawigiEdit_RunTest(0, p0, p1, true, p2) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	// ----- test 1 -----
	disabled = false;
	p0 = "abcdefghijklmnopqrstuvwxyz";
	p1 = "20051920";
	p2 = "test";
	all_right = (disabled || KawigiEdit_RunTest(1, p0, p1, true, p2) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	// ----- test 2 -----
	disabled = false;
	p0 = "qesdfvujrockgpthzymbnxawli";
	p1 = "mwiizkelza";
	p2 = "19242626171202251723";
	all_right = (disabled || KawigiEdit_RunTest(2, p0, p1, true, p2) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	// ----- test 3 -----
	disabled = false;
	p0 = "faxmswrpnqdbygcthuvkojizle";
	p1 = "02170308060416192402";
	p2 = "ahxpwmtvza";
	all_right = (disabled || KawigiEdit_RunTest(3, p0, p1, true, p2) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	if (all_right) {
		if (tests_disabled) {
			cout << "You're a stud (but some test cases were disabled)!" << endl;
		} else {
			cout << "You're a stud (at least on given cases)!" << endl;
		}
	} else {
		cout << "Some of the test cases had errors." << endl;
	}
	return 0;
}
// END KAWIGIEDIT TESTING
<commit_msg>BreakingTheCode<commit_after>#include <string>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iterator>
#include <tuple>
#include <regex>
#include <array>
#include <valarray>
#define all(v)begin(v),end(v)
#define dump(v)copy(all(v),ostream_iterator<decltype(*v.begin())>(cout,"\n"))
#define rg(i,a,b)for(int i=a,i##e=b;i<i##e;++i)
#define fr(i,n)for(int i=0,i##e=n;i<i##e;++i)
#define rf(i,n)for(int i=n-1;i>=0;--i)
#define ei(a,m)for(auto&a:m)if(int a##i=&a-&*begin(m)+1)if(--a##i,1)
#define sz(v)int(v.size())
#define sr(v)sort(all(v))
#define rs(v)sort(all(v),greater<int>())
#define rev(v)reverse(all(v))
#define eb emplace_back
#define stst stringstream
#define big numeric_limits<int>::max()
#define g(t,i)get<i>(t)
#define cb(v,w)copy(all(v),back_inserter(w))
#define uni(v)sort(all(v));v.erase(unique(all(v)),end(v))
#define vt(...)vector<tuple<__VA_ARGS__>>
#define smx(a,b)a=max(a,b)
#define smn(a,b)a=min(a,b)
#define words(w,q)vector<string>w;[&w](string&&s){stringstream u(s);string r;while(u>>r)w.eb(r);}(q);
#define digits(d,n,s)vector<int>d;[&d](int m){while(m)d.eb(m%s),m/=s;}(n);
typedef long long ll;
using namespace std;

struct BreakingTheCode {
	string decodingEncoding(string code, string m) {
		string r;
		if (isdigit(m[0])) {
			ei(a, m) if (ai % 2) {
				int p = m[ai - 1];
				r += code[(p - '0') * 10 + a - '0'];
			}
		} else {
			stst ss;
			ei(a, m) {
				int x = code.find(a);
				ss << x / 10 + '0' << x % 10 + '0';
			}
			getline(ss, r);
		}
		return r;
	}
};

// BEGIN KAWIGIEDIT TESTING
// Generated by KawigiEdit-pf 2.3.0
#include <iostream>
#include <string>
#include <vector>
#include <ctime>
#include <cmath>
using namespace std;
bool KawigiEdit_RunTest(int testNum, string p0, string p1, bool hasAnswer, string p2) {
	cout << "Test " << testNum << ": [" << "\"" << p0 << "\"" << "," << "\"" << p1 << "\"";
	cout << "]" << endl;
	BreakingTheCode *obj;
	string answer;
	obj = new BreakingTheCode();
	clock_t startTime = clock();
	answer = obj->decodingEncoding(p0, p1);
	clock_t endTime = clock();
	delete obj;
	bool res;
	res = true;
	cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
	if (hasAnswer) {
		cout << "Desired answer:" << endl;
		cout << "\t" << "\"" << p2 << "\"" << endl;
	}
	cout << "Your answer:" << endl;
	cout << "\t" << "\"" << answer << "\"" << endl;
	if (hasAnswer) {
		res = answer == p2;
	}
	if (!res) {
		cout << "DOESN'T MATCH!!!!" << endl;
	} else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) {
		cout << "FAIL the timeout" << endl;
		res = false;
	} else if (hasAnswer) {
		cout << "Match :-)" << endl;
	} else {
		cout << "OK, but is it right?" << endl;
	}
	cout << "" << endl;
	return res;
}
int main() {
	bool all_right;
	bool disabled;
	bool tests_disabled;
	all_right = true;
	tests_disabled = false;

	string p0;
	string p1;
	string p2;

	// ----- test 0 -----
	disabled = false;
	p0 = "abcdefghijklmnopqrstuvwxyz";
	p1 = "test";
	p2 = "20051920";
	all_right = (disabled || KawigiEdit_RunTest(0, p0, p1, true, p2) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	// ----- test 1 -----
	disabled = false;
	p0 = "abcdefghijklmnopqrstuvwxyz";
	p1 = "20051920";
	p2 = "test";
	all_right = (disabled || KawigiEdit_RunTest(1, p0, p1, true, p2) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	// ----- test 2 -----
	disabled = false;
	p0 = "qesdfvujrockgpthzymbnxawli";
	p1 = "mwiizkelza";
	p2 = "19242626171202251723";
	all_right = (disabled || KawigiEdit_RunTest(2, p0, p1, true, p2) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	// ----- test 3 -----
	disabled = false;
	p0 = "faxmswrpnqdbygcthuvkojizle";
	p1 = "02170308060416192402";
	p2 = "ahxpwmtvza";
	all_right = (disabled || KawigiEdit_RunTest(3, p0, p1, true, p2) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	if (all_right) {
		if (tests_disabled) {
			cout << "You're a stud (but some test cases were disabled)!" << endl;
		} else {
			cout << "You're a stud (at least on given cases)!" << endl;
		}
	} else {
		cout << "Some of the test cases had errors." << endl;
	}
	return 0;
}
// END KAWIGIEDIT TESTING
<|endoftext|>


<commit_before>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2013 Heiko Strathmann
 */

#include <shogun/base/init.h>
#include <shogun/kernel/GaussianKernel.h>
#include <shogun/labels/RegressionLabels.h>
#include <shogun/features/DenseFeatures.h>
#include <shogun/regression/svr/LibSVR.h>
#include <shogun/evaluation/MeanSquaredError.h>

using namespace shogun;

void test_libsvr()
{
	const int32_t kernel_cache=0;
	const float64_t rbf_width=10;
	const float64_t svm_C=10;
	const float64_t svm_nu=0.01;

	/* create some easy regression data: 1d noisy sine wave */
	index_t n=100;
	float64_t x_range=6;

	SGMatrix<float64_t> feat_train(1, n);
	SGMatrix<float64_t> feat_test(1, n);
	SGVector<float64_t> lab_train(n);
	SGVector<float64_t> lab_test(n);

	for (index_t i=0; i<n; ++i)
	{
		feat_train[i]=CMath::random(0.0, x_range);
		feat_test[i]=(float64_t)i/n*x_range;
		lab_train[i]=CMath::sin(feat_train[i]);
		lab_test[i]=CMath::sin(feat_test[i]);
	}

	/* shogun representation */
	CLabels* labels_train=new CRegressionLabels(lab_train);
	CLabels* labels_test=new CRegressionLabels(lab_test);
	CDenseFeatures<float64_t>* features_train=new CDenseFeatures<float64_t>(
			feat_train);
	CDenseFeatures<float64_t>* features_test=new CDenseFeatures<float64_t>(
			feat_test);

	CGaussianKernel* kernel=new CGaussianKernel(kernel_cache, rbf_width);
	kernel->init(features_train, features_train);

	// also epsilon svr possible here
	LIBSVR_SOLVER_TYPE st=LIBSVR_NU_SVR;
	CLibSVR* svm=new CLibSVR(svm_C, svm_nu, kernel, labels_train, st);
	svm->train();

	/* predict */
	CRegressionLabels* predicted_labels=CLabelsFactory::to_regression(
			svm->apply(features_test));

	/* evaluate */
	CEvaluation* eval=new CMeanSquaredError();
	SG_SPRINT("mean squared error: %f\n",
			eval->evaluate(predicted_labels, labels_test));

	 /* clean up */
	SG_UNREF(eval);
	SG_UNREF(labels_test)
	SG_UNREF(predicted_labels);
	SG_UNREF(svm);
}

int main()
{
	init_shogun_with_defaults();

//	sg_io->set_loglevel(MSG_DEBUG);

	test_libsvr();

	exit_shogun();
	return 0;
}

<commit_msg>Remove kernel cache size set to 0 in libshogun libsvr example.<commit_after>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2013 Heiko Strathmann
 */

#include <shogun/base/init.h>
#include <shogun/kernel/GaussianKernel.h>
#include <shogun/labels/RegressionLabels.h>
#include <shogun/features/DenseFeatures.h>
#include <shogun/regression/svr/LibSVR.h>
#include <shogun/evaluation/MeanSquaredError.h>

using namespace shogun;

void test_libsvr()
{
	const float64_t rbf_width=10;
	const float64_t svm_C=10;
	const float64_t svm_nu=0.01;

	/* create some easy regression data: 1d noisy sine wave */
	index_t n=100;
	float64_t x_range=6;

	SGMatrix<float64_t> feat_train(1, n);
	SGMatrix<float64_t> feat_test(1, n);
	SGVector<float64_t> lab_train(n);
	SGVector<float64_t> lab_test(n);

	for (index_t i=0; i<n; ++i)
	{
		feat_train[i]=CMath::random(0.0, x_range);
		feat_test[i]=(float64_t)i/n*x_range;
		lab_train[i]=CMath::sin(feat_train[i]);
		lab_test[i]=CMath::sin(feat_test[i]);
	}

	/* shogun representation */
	CLabels* labels_train=new CRegressionLabels(lab_train);
	CLabels* labels_test=new CRegressionLabels(lab_test);
	CDenseFeatures<float64_t>* features_train=new CDenseFeatures<float64_t>(
			feat_train);
	CDenseFeatures<float64_t>* features_test=new CDenseFeatures<float64_t>(
			feat_test);

	CGaussianKernel* kernel=new CGaussianKernel(rbf_width);
	kernel->init(features_train, features_train);

	// also epsilon svr possible here
	LIBSVR_SOLVER_TYPE st=LIBSVR_NU_SVR;
	CLibSVR* svm=new CLibSVR(svm_C, svm_nu, kernel, labels_train, st);
	svm->train();

	/* predict */
	CRegressionLabels* predicted_labels=CLabelsFactory::to_regression(
			svm->apply(features_test));

	/* evaluate */
	CEvaluation* eval=new CMeanSquaredError();
	SG_SPRINT("mean squared error: %f\n",
			eval->evaluate(predicted_labels, labels_test));

	 /* clean up */
	SG_UNREF(eval);
	SG_UNREF(labels_test)
	SG_UNREF(predicted_labels);
	SG_UNREF(svm);
}

int main()
{
	init_shogun_with_defaults();

//	sg_io->set_loglevel(MSG_DEBUG);

	test_libsvr();

	exit_shogun();
	return 0;
}

<|endoftext|>


<commit_before>#ifndef H_EXTENSIONS_CUTEHMI_2_INCLUDE_CUTEHMI_NOTIFICATION_HPP
#define H_EXTENSIONS_CUTEHMI_2_INCLUDE_CUTEHMI_NOTIFICATION_HPP

#include "internal/platform.hpp"
#include "ErrorInfo.hpp"
#include "MPtr.hpp"

#include <QObject>
#include <QDateTime>

namespace cutehmi {

/**
 * %Notification.
 *
 * Notifications are a mean to store information about events that occur to the system. Compared to logs they shall be more concise,
 * accessible and friendly in general. They belong to user space or power-user space rather than developer/expert space. Contrary to
 * log messages, notification messages shall be translatable. Compared to @ref Messages "messages" they are less intrusive and do
 * not require user action.
 *
 * %Notification objects are designed to work with Notifier and NotificationListModel classes.
 */
class CUTEHMI_API Notification:
	public QObject
{
		Q_OBJECT

	public:
		/**
		  Notification type.
		  */
		Q_PROPERTY(Type type READ type WRITE setType NOTIFY typeChanged)

		/**
		  Notification text.
		  */
		Q_PROPERTY(QString text READ text WRITE setText NOTIFY textChanged)

		enum Type {
			INFO = 1,		///< Informative level notification type.
			WARNING = 2,	///< Warning level notification type.
			CRITICAL = 3	///< Critical level notification type.
		};
		Q_ENUM(Type)

		/**
		 * Default constructor.
		 * @param text notification text.
		 * @param type notification type.
		 * @param parent parent object.
		 */
		explicit Notification(const QString & text = QString(), Type type = INFO, QObject * parnt = nullptr);

		/**
		 * Constructor.
		 * @param type notification type.
		 * @param text notification text.
		 * @param parent parent object.
		 *
		 * @deprecated Notification(const QString &, Type, QObject *) constructor should be used instead.
		 */
		explicit Notification(Type type, const QString & text = QString(), QObject * parent = nullptr);

		/**
		 * Add informative notification. Convenient function that creates informative notification and adds it to the
		 * Notifier.
		 * @param text notification text.
		 */
		static void Info(const QString & text);

		/**
		 * Add warning notification. Convenient function that creates warning notification and adds it to the Notifier.
		 * @param text notification text.
		 */
		static void Warning(const QString & text);

		/**
		 * Add critical notification. Convenient function that creates critical notification and adds it to the Notifier.
		 * @param text notification text.
		 */
		static void Critical(const QString & text);

		/**
		 * Add critical notification. Convenient function that creates critical notification from ErrorInfo object and adds
		 * it to the Notifier.
		 * @param errorInfo ErrorInfo object.
		 */
		static void Critical(const ErrorInfo & errorInfo);

		/**
		 * Get type.
		 * @return notification type.
		 */
		Type type() const;

		/**
		 * Set type.
		 * @param type notification type.
		 */
		void setType(Type type);

		/**
		 * Get text.
		 * @return notification text.
		 */
		QString text() const;

		/**
		 * Set text.
		 * @param text notification text.
		 */
		void setText(const QString & text);

		/**
		 * Get date. Date is set automatically upon notification creation.
		 * @return date of notification.
		 */
		const QDateTime & dateTime() const;

		/**
		 * Cone notification.
		 * @return notification clone.
		 */
		std::unique_ptr<Notification> clone() const;

	signals:
		/**
		 * Type changed signal.
		 */
		void typeChanged();

		/**
		 * Text changed signal.
		 */
		void textChanged();

	private:
		struct Members
		{
			Type type;
			QString text;
			QDateTime dateTime;
		};

		MPtr<Members> m;
};

}

#endif

//(c)C: Copyright © 2018-2020, Michał Policht <michal@policht.pl>. All rights reserved.
//(c)C: SPDX-License-Identifier: LGPL-3.0-or-later OR MIT
//(c)C: This file is a part of CuteHMI.
//(c)C: CuteHMI is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
//(c)C: CuteHMI 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.
//(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI.  If not, see <https://www.gnu.org/licenses/>.
//(c)C: Additionally, this file is licensed under terms of MIT license as expressed below.
//(c)C: 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:
//(c)C: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//(c)C: 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.
<commit_msg>Remove redundant new line<commit_after>#ifndef H_EXTENSIONS_CUTEHMI_2_INCLUDE_CUTEHMI_NOTIFICATION_HPP
#define H_EXTENSIONS_CUTEHMI_2_INCLUDE_CUTEHMI_NOTIFICATION_HPP

#include "internal/platform.hpp"
#include "ErrorInfo.hpp"
#include "MPtr.hpp"

#include <QObject>
#include <QDateTime>

namespace cutehmi {

/**
 * %Notification.
 *
 * Notifications are a mean to store information about events that occur to the system. Compared to logs they shall be more concise,
 * accessible and friendly in general. They belong to user space or power-user space rather than developer/expert space. Contrary to
 * log messages, notification messages shall be translatable. Compared to @ref Messages "messages" they are less intrusive and do
 * not require user action.
 *
 * %Notification objects are designed to work with Notifier and NotificationListModel classes.
 */
class CUTEHMI_API Notification:
	public QObject
{
		Q_OBJECT

	public:
		/**
		  Notification type.
		  */
		Q_PROPERTY(Type type READ type WRITE setType NOTIFY typeChanged)

		/**
		  Notification text.
		  */
		Q_PROPERTY(QString text READ text WRITE setText NOTIFY textChanged)

		enum Type {
			INFO = 1,		///< Informative level notification type.
			WARNING = 2,	///< Warning level notification type.
			CRITICAL = 3	///< Critical level notification type.
		};
		Q_ENUM(Type)

		/**
		 * Default constructor.
		 * @param text notification text.
		 * @param type notification type.
		 * @param parent parent object.
		 */
		explicit Notification(const QString & text = QString(), Type type = INFO, QObject * parnt = nullptr);

		/**
		 * Constructor.
		 * @param type notification type.
		 * @param text notification text.
		 * @param parent parent object.
		 *
		 * @deprecated Notification(const QString &, Type, QObject *) constructor should be used instead.
		 */
		explicit Notification(Type type, const QString & text = QString(), QObject * parent = nullptr);

		/**
		 * Add informative notification. Convenient function that creates informative notification and adds it to the
		 * Notifier.
		 * @param text notification text.
		 */
		static void Info(const QString & text);

		/**
		 * Add warning notification. Convenient function that creates warning notification and adds it to the Notifier.
		 * @param text notification text.
		 */
		static void Warning(const QString & text);

		/**
		 * Add critical notification. Convenient function that creates critical notification and adds it to the Notifier.
		 * @param text notification text.
		 */
		static void Critical(const QString & text);

		/**
		 * Add critical notification. Convenient function that creates critical notification from ErrorInfo object and adds
		 * it to the Notifier.
		 * @param errorInfo ErrorInfo object.
		 */
		static void Critical(const ErrorInfo & errorInfo);

		/**
		 * Get type.
		 * @return notification type.
		 */
		Type type() const;

		/**
		 * Set type.
		 * @param type notification type.
		 */
		void setType(Type type);

		/**
		 * Get text.
		 * @return notification text.
		 */
		QString text() const;

		/**
		 * Set text.
		 * @param text notification text.
		 */
		void setText(const QString & text);

		/**
		 * Get date. Date is set automatically upon notification creation.
		 * @return date of notification.
		 */
		const QDateTime & dateTime() const;

		/**
		 * Cone notification.
		 * @return notification clone.
		 */
		std::unique_ptr<Notification> clone() const;

	signals:
		/**
		 * Type changed signal.
		 */
		void typeChanged();

		/**
		 * Text changed signal.
		 */
		void textChanged();

	private:
		struct Members
		{
			Type type;
			QString text;
			QDateTime dateTime;
		};

		MPtr<Members> m;
};

}

#endif

//(c)C: Copyright © 2018-2020, Michał Policht <michal@policht.pl>. All rights reserved.
//(c)C: SPDX-License-Identifier: LGPL-3.0-or-later OR MIT
//(c)C: This file is a part of CuteHMI.
//(c)C: CuteHMI is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
//(c)C: CuteHMI 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.
//(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI.  If not, see <https://www.gnu.org/licenses/>.
//(c)C: Additionally, this file is licensed under terms of MIT license as expressed below.
//(c)C: 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:
//(c)C: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//(c)C: 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.
<|endoftext|>