<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: wizardmachine.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: vg $ $Date: 2007-04-11 19:43:21 $
 *
 *  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 _SVTOOLS_WIZARDMACHINE_HXX_
#define _SVTOOLS_WIZARDMACHINE_HXX_

#ifndef INCLUDED_SVTDLLAPI_H
#include "svtools/svtdllapi.h"
#endif

#ifndef _SVT_WIZDLG_HXX
#include <svtools/wizdlg.hxx>
#endif
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#ifndef _SV_TABPAGE_HXX
#include <vcl/tabpage.hxx>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif

class Bitmap;
//.........................................................................
namespace svt
{
//.........................................................................

// wizard buttons
#define WZB_NEXT                0x0001
#define WZB_PREVIOUS            0x0002
#define WZB_FINISH              0x0004
#define WZB_CANCEL              0x0008
#define WZB_HELP                0x0010

// wizard states
#define WZS_INVALID_STATE       ((WizardState)-1)

    //=====================================================================
    //= WizardTypes
    //=====================================================================
    struct WizardTypes
    {
        typedef sal_Int16  WizardState;
        enum CommitPageReason
        {
            eTravelForward,         // traveling forward (maybe with skipping pages)
            eTravelBackward,        // traveling backward (maybe with skipping pages)
            eFinish,                // the wizard is about to be finished
            eValidate,              // the data should be validated only, no traveling wll happen
            eValidateNoUI           // the data should be validated only, without displaying error messages and other UI
        };
    };

    class SAL_NO_VTABLE IWizardPage : public WizardTypes
    {
    public:
        // access control
        struct GrantAccess
        {
            friend class OWizardMachine;
        protected:
            GrantAccess() { }
        };

        enum COMMIT_REASON
        {
            CR_TRAVEL_NEXT = eTravelForward,
            CR_TRAVEL_PREVIOUS = eTravelBackward,
            CR_FINISH = eFinish,
            CR_VALIDATE = eValidate,
            CR_VALIDATE_NOUI = eValidateNoUI
        };
    public:
        //-----------------------------------------------------------------
        // methods which, though public, are acessible for the OWizardMachine only
        virtual void enableHeader( const Bitmap& _rBitmap, sal_Int32 _nPixelHeight, GrantAccess ) = 0;
        // This methods  behave somewhat different than ActivatePage/DeactivatePage
        // The latter are handled by the base class itself whenever changing the pages is in the offing,
        // i.e., when it's already decided which page is the next.
        // We may have situations where the next page depends on the state of the current, which needs
        // to be committed for this.
        // So initializePage and commitPage are designated to initialitzing/committing data on the page.
        virtual void        initializePage() = 0;
        virtual sal_Bool    commitPage(COMMIT_REASON _eReason) = 0;
    };
    //=====================================================================
    //= OWizardPage
    //=====================================================================
    class OWizardMachine;
    struct WizardPageImplData;

    class SVT_DLLPUBLIC OWizardPage : public TabPage, public IWizardPage
    {
    private:
        WizardPageImplData*     m_pImpl;

    public:
        OWizardPage( OWizardMachine* _pParent, WinBits _nStyle = 0 );
        OWizardPage( OWizardMachine* _pParent, const ResId& _rResId );
        ~OWizardPage();

        // This methods  behave somewhat different than ActivatePage/DeactivatePage
        // The latter are handled by the base class itself whenever changing the pages is in the offing,
        // i.e., when it's already decided which page is the next.
        // We may have situations where the next page depends on the state of the current, which needs
        // to be committed for this.
        // So initializePage and commitPage are designated to initialitzing/committing data on the page.
        virtual void        initializePage();
        virtual sal_Bool    commitPage(IWizardPage::COMMIT_REASON _eReason);

        //-----------------------------------------------------------------
        // methods which, though public, are acessible for the OWizardMachine only
        virtual void        enableHeader( const Bitmap& _rBitmap, sal_Int32 _nPixelHeight, IWizardPage::GrantAccess );

    protected:
        // TabPage overridables
        virtual void    ActivatePage();

        /** checks whether or not the header is enabled

            The header can only be enabled by the OWizardMachine the page belongs to. This way, it is ensured
            that all or none of the pages have a header.
        */
        sal_Bool        isHeaderEnabled( ) const;

        /** sets the text of the header.

            To be called if the header is enabled only.

            @see isHeaderEnabled
        */
        void            setHeaderText( const String& _rHeaderText );

    protected:
        /** called from within ActivatePage, enables the wizards "Next" button depending on the return value of
            <member>determineNextButtonState</member>
        */
        void implCheckNextButton();

        /** determines whether or not the Next button should be enabled in the current situation.

            The default implementation always returns <TRUE/>.
        */
        virtual sal_Bool determineNextButtonState();
    };

    //=====================================================================
    //= OWizardMachine
    //=====================================================================
    struct WizardMachineImplData;
    /** implements some kind of finite automata, where the states of the automata exactly correlate
        with tab pages.

        That is, the machine can have up to n states, where at each point in time exactly one state is
        the current one. A state being current is represented as one of n tab pages being displayed
        currently.

        The class handles the UI for traveling between the states (e.g. it administrates the Next and
        Previous buttons which you usually find in a wizard.

        Derived classes have to implement the travel logic by overriding <member>determineNextState</member>,
        which has to determine the state which follows the current state. Since this may depend
        on the actual data presented in the wizard (e.g. checkboxes checked, or something like this),
        they can implement non-linear traveling this way.
    */

    class SVT_DLLPUBLIC OWizardMachine : public WizardDialog, public WizardTypes
    {
    private:
        // restrict access to some aspects of our base class
        SVT_DLLPRIVATE void             AddPage( TabPage* pPage ) { WizardDialog::AddPage(pPage); }
        SVT_DLLPRIVATE void             RemovePage( TabPage* pPage ) { WizardDialog::RemovePage(pPage); }
        SVT_DLLPRIVATE void             SetPage( USHORT nLevel, TabPage* pPage ) { WizardDialog::SetPage(nLevel, pPage); }
        //  TabPage*            GetPage( USHORT nLevel ) const { return WizardDialog::GetPage(nLevel); }
        // TODO: probably the complete page handling (next, previous etc.) should be prohibited ...

        // IMPORTANT:
        // traveling pages should not be done by calling these base class member, some mechanisms of this class
        // here (e.g. committing page data) depend on having full control over page traveling.
        // So use the travelXXX methods if you need to travel

    protected:
        OKButton*       m_pFinish;
        CancelButton*   m_pCancel;
        PushButton*     m_pNextPage;
        PushButton*     m_pPrevPage;
        HelpButton*     m_pHelp;

    private:
        WizardMachineImplData*
                        m_pImpl;
            // hold members in this structure to allow keeping compatible when members are added

        SVT_DLLPRIVATE void addButtons(Window* _pParent, sal_uInt32 _nButtonFlags);
        SVT_DLLPRIVATE long calcRightHelpOffset(sal_uInt32 _nButtonFlags);

    public:
        /** ctor

            The ctor does not call FreeResource, this is the resposibility of the derived class.

            For the button flags, use any combination of the WZB_* flags.
        */
        OWizardMachine(Window* _pParent, const ResId& _rRes, sal_uInt32 _nButtonFlags, sal_Bool _bCheckButtonStates = sal_False, sal_Bool _bRoadmapMode = sal_False, sal_Int16 _nLeftAlignCount = 0  );
        ~OWizardMachine();

        /// enable (or disable) buttons
        void    enableButtons(sal_uInt32 _nWizardButtonFlags, sal_Bool _bEnable);
        /// set the default style for a button
        void    defaultButton(sal_uInt32 _nWizardButtonFlags);
        /// set the default style for a button
        void    defaultButton(PushButton* _pNewDefButton);

        /// set the base of the title to use - the title of the current page is appended
        void            setTitleBase(const String& _rTitleBase);
        const String&   getTitleBase() const;

    protected:
        // WizardDialog overridables
        virtual void        ActivatePage();
        virtual long        DeactivatePage();

        // our own overridables

        /// to override to create new pages
        virtual TabPage*    createPage(WizardState _nState) = 0;

        /// will be called when a new page is about to be displayed
        virtual void            enterState(WizardState _nState);

        /** will be called when the current state is about to be left for the given reason

            The base implementation in this class will simply call <member>OWizardPage::commitPage</member>
            for the current page, and return whatever this call returns.

            @param _eReason
                The reason why the state is to be left.
            @return
                <TRUE/> if and only if the page is allowed to be left
        */
        virtual sal_Bool        prepareLeaveCurrentState( CommitPageReason _eReason );

        /** will be called when the given state is left

            This is the very last possibility for derived classes to veto the deactivation
            of a page.

            @todo Normally, we would not need the return value here - derived classes now have
            the possibility to veto page deactivations in <member>prepareLeaveCurrentState</member>. However,
            changing this return type is too incompatible at the moment ...

            @return
                <TRUE/> if and only if the page is allowed to be left
        */
        virtual sal_Bool        leaveState( WizardState _nState );

        /** determine the next state to travel from the given one

            The default behaviour is linear traveling, overwrite this to change it

            Return WZS_INVALID_STATE to prevent traveling.
        */
        virtual WizardState     determineNextState(WizardState _nCurrentState);

        /** called when the finish button is pressed

By default, only the base class' Finnish method (which is not virtual) is called

        */
        virtual sal_Bool onFinish(sal_Int32 _nResult);

        /** enables a header bitmap

            Usually, wizards contain a header. This header is as wide as the dialog and positioned at the very top.
            In addition, it contains a (rather small) bitmap on the left side, and right next to this bitmap, a short
            text describing the current page.

            If you call this method, this header is automatically created on every page. In addition, all
            other controls on the pages are moved below the header. The title of every page is used as text
            for the header.

            This method must not be called if there are already pages created.

            @param _rBitmap
                the bitmap to use for the header
            @param _nPixelHeight
                the height of the header in pixels.

                If -1 is passed, the default of 30 APPFONT units will be used.
        */
        void            enableHeader( const Bitmap& _rBitmap, sal_Int32 _nPixelHeight = -1 );

        /// travel to the next state
        sal_Bool        travelNext();

        /// travel to the previous state
        sal_Bool        travelPrevious();

        /**
            removes a page from the history. Should be called when the page is being disabled
        */
        void  removePageFromHistory( WizardState nToRemove );

        /** skip a state

            The method behaves as if from the current state, <arg>_nSteps</arg> <method>travelNext</method>s were
            called, but without actually creating or displaying the ntermediate pages. Only the
            (<arg>_nSteps</arg> + 1)th page is created.

            The skipped states appear in the state history, so <method>travelPrevious</method> will make use of them.

            A very essential precondition for using this method is that your <method>determineNextState</method>
            method is able to determine the next state without actually having the page of the current state.

            @return
                <TRUE/> if and only if traveling was successfull

            @see skipUntil
            @see skipBackwardUntil
        */
        sal_Bool        skip( sal_Int32 _nSteps = 1 );

        /** skips one or more states, until a given state is reached

            The method behaves as if from the current state, <method>travelNext</method>s were called
            successively, until <arg>_nTargetState</arg> is reached, but without actually creating or
            displaying the ntermediate pages.

            The skipped states appear in the state history, so <method>travelPrevious</method> will make use of them.

            @return
                <TRUE/> if and only if traveling was successfull

            @see skip
            @see skipBackwardUntil
        */
        sal_Bool        skipUntil( WizardState _nTargetState );

        /** moves back one or more states, until a given state is reached

            This method allows traveling backwards more than one state without actually showing the intermediate
            states.

            For instance, if you want to travel two steps backward at a time, you could used
            two travelPrevious calls, but this would show both pages, which is not necessary,
            since you're interested in the target page only. Using <member>skipBackwardUntil</member> reliefs
            you from this.

            @return
                <TRUE/> if and only if traveling was successfull

            @see skipUntil
            @see skip
        */
        sal_Bool        skipBackwardUntil( WizardState _nTargetState );

        /** returns the current state of the machine

            Vulgo, this is the identifier of the current tab page :)
        */
        WizardState     getCurrentState() const { return WizardDialog::GetCurLevel(); }

        virtual IWizardPage*    getWizardPage(TabPage* _pCurrentPage) const;

        /** prevent nested calls of links next/previous or page change with the roadmap control

         */
        bool IsInCallOfLink() const;

        void SetInCallOfLink( bool bSet );

    private:
       // long OnNextPage( PushButton* );
        DECL_DLLPRIVATE_LINK(OnNextPage, PushButton*);
        DECL_DLLPRIVATE_LINK(OnPrevPage, PushButton*);
        DECL_DLLPRIVATE_LINK(OnFinish, PushButton*);

        SVT_DLLPRIVATE void     implResetDefault(Window* _pWindow);
        SVT_DLLPRIVATE void     implUpdateTitle();
    };

//.........................................................................
}   // namespace svt
//.........................................................................

#endif // _SVTOOLS_WIZARDMACHINE_HXX_

<commit_msg>INTEGRATION: CWS chart2mst3 (1.2.30); FILE MERGED 2007/04/25 07:55:08 bm 1.2.30.1: saved changes done in file on branch before move here from ..<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: wizardmachine.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: vg $ $Date: 2007-05-22 19:32:34 $
 *
 *  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 _SVTOOLS_WIZARDMACHINE_HXX_
#define _SVTOOLS_WIZARDMACHINE_HXX_

#ifndef INCLUDED_SVTDLLAPI_H
#include "svtools/svtdllapi.h"
#endif

#ifndef _SVT_WIZDLG_HXX
#include <svtools/wizdlg.hxx>
#endif
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#ifndef _SV_TABPAGE_HXX
#include <vcl/tabpage.hxx>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif

class Bitmap;
//.........................................................................
namespace svt
{
//.........................................................................

// wizard buttons
#define WZB_NEXT                0x0001
#define WZB_PREVIOUS            0x0002
#define WZB_FINISH              0x0004
#define WZB_CANCEL              0x0008
#define WZB_HELP                0x0010

// wizard states
#define WZS_INVALID_STATE       ((WizardState)-1)

    //=====================================================================
    //= WizardTypes
    //=====================================================================
    struct WizardTypes
    {
        typedef sal_Int16  WizardState;
        enum CommitPageReason
        {
            eTravelForward,         // traveling forward (maybe with skipping pages)
            eTravelBackward,        // traveling backward (maybe with skipping pages)
            eFinish,                // the wizard is about to be finished
            eValidate,              // the data should be validated only, no traveling wll happen
            eValidateNoUI           // the data should be validated only, without displaying error messages and other UI
        };
    };

    class SAL_NO_VTABLE IWizardPage : public WizardTypes
    {
    public:
        // access control
        struct GrantAccess
        {
            friend class OWizardMachine;
        protected:
            GrantAccess() { }
        };

        /// compatibility only. Superseded by CommitPageReason
        enum COMMIT_REASON
        {
            CR_TRAVEL_NEXT = eTravelForward,
            CR_TRAVEL_PREVIOUS = eTravelBackward,
            CR_FINISH = eFinish,
            CR_VALIDATE = eValidate,
            CR_VALIDATE_NOUI = eValidateNoUI
        };
    public:
        //-----------------------------------------------------------------
        // methods which, though public, are acessible for the OWizardMachine only
        virtual void enableHeader( const Bitmap& _rBitmap, sal_Int32 _nPixelHeight, GrantAccess ) = 0;
        // This methods  behave somewhat different than ActivatePage/DeactivatePage
        // The latter are handled by the base class itself whenever changing the pages is in the offing,
        // i.e., when it's already decided which page is the next.
        // We may have situations where the next page depends on the state of the current, which needs
        // to be committed for this.
        // So initializePage and commitPage are designated to initialitzing/committing data on the page.
        virtual void        initializePage() = 0;
        virtual sal_Bool    commitPage(COMMIT_REASON _eReason) = 0;
    };
    //=====================================================================
    //= OWizardPage
    //=====================================================================
    class OWizardMachine;
    struct WizardPageImplData;

    class SVT_DLLPUBLIC OWizardPage : public TabPage, public IWizardPage
    {
    private:
        WizardPageImplData*     m_pImpl;

    public:
        /** @param _pParent
                if the OWizardPage is used in an OWizardMachine, this parameter
                must be the OWizardMachine (which is derived from Window)
         */
        OWizardPage( Window* _pParent, WinBits _nStyle = 0 );
        OWizardPage( Window* _pParent, const ResId& _rResId );
        ~OWizardPage();

        // This methods  behave somewhat different than ActivatePage/DeactivatePage
        // The latter are handled by the base class itself whenever changing the pages is in the offing,
        // i.e., when it's already decided which page is the next.
        // We may have situations where the next page depends on the state of the current, which needs
        // to be committed for this.
        // So initializePage and commitPage are designated to initialitzing/committing data on the page.
        virtual void        initializePage();
        virtual sal_Bool    commitPage(IWizardPage::COMMIT_REASON _eReason);

        //-----------------------------------------------------------------
        // methods which, though public, are acessible for the OWizardMachine only
        virtual void        enableHeader( const Bitmap& _rBitmap, sal_Int32 _nPixelHeight, IWizardPage::GrantAccess );

    protected:
        // TabPage overridables
        virtual void    ActivatePage();

        /** checks whether or not the header is enabled

            The header can only be enabled by the OWizardMachine the page belongs to. This way, it is ensured
            that all or none of the pages have a header.
        */
        sal_Bool        isHeaderEnabled( ) const;

        /** sets the text of the header.

            To be called if the header is enabled only.

            @see isHeaderEnabled
        */
        void            setHeaderText( const String& _rHeaderText );

    protected:
        /** called from within ActivatePage, enables the wizards "Next" button depending on the return value of
            <member>determineNextButtonState</member>
        */
        void implCheckNextButton();

        /** determines whether or not the Next button should be enabled in the current situation.

            The default implementation always returns <TRUE/>.
        */
        virtual sal_Bool determineNextButtonState();
    };

    //=====================================================================
    //= OWizardMachine
    //=====================================================================
    struct WizardMachineImplData;
    /** implements some kind of finite automata, where the states of the automata exactly correlate
        with tab pages.

        That is, the machine can have up to n states, where at each point in time exactly one state is
        the current one. A state being current is represented as one of n tab pages being displayed
        currently.

        The class handles the UI for traveling between the states (e.g. it administrates the Next and
        Previous buttons which you usually find in a wizard.

        Derived classes have to implement the travel logic by overriding <member>determineNextState</member>,
        which has to determine the state which follows the current state. Since this may depend
        on the actual data presented in the wizard (e.g. checkboxes checked, or something like this),
        they can implement non-linear traveling this way.
    */

    class SVT_DLLPUBLIC OWizardMachine : public WizardDialog, public WizardTypes
    {
    private:
        // restrict access to some aspects of our base class
        SVT_DLLPRIVATE void             AddPage( TabPage* pPage ) { WizardDialog::AddPage(pPage); }
        SVT_DLLPRIVATE void             RemovePage( TabPage* pPage ) { WizardDialog::RemovePage(pPage); }
        SVT_DLLPRIVATE void             SetPage( USHORT nLevel, TabPage* pPage ) { WizardDialog::SetPage(nLevel, pPage); }
        //  TabPage*            GetPage( USHORT nLevel ) const { return WizardDialog::GetPage(nLevel); }
        // TODO: probably the complete page handling (next, previous etc.) should be prohibited ...

        // IMPORTANT:
        // traveling pages should not be done by calling these base class member, some mechanisms of this class
        // here (e.g. committing page data) depend on having full control over page traveling.
        // So use the travelXXX methods if you need to travel

    protected:
        OKButton*       m_pFinish;
        CancelButton*   m_pCancel;
        PushButton*     m_pNextPage;
        PushButton*     m_pPrevPage;
        HelpButton*     m_pHelp;

    private:
        WizardMachineImplData*
                        m_pImpl;
            // hold members in this structure to allow keeping compatible when members are added

        SVT_DLLPRIVATE void addButtons(Window* _pParent, sal_uInt32 _nButtonFlags);
        SVT_DLLPRIVATE long calcRightHelpOffset(sal_uInt32 _nButtonFlags);

    public:
        /** ctor

            The ctor does not call FreeResource, this is the resposibility of the derived class.

            For the button flags, use any combination of the WZB_* flags.
        */
        OWizardMachine(Window* _pParent, const ResId& _rRes, sal_uInt32 _nButtonFlags, sal_Bool _bCheckButtonStates = sal_False, sal_Bool _bRoadmapMode = sal_False, sal_Int16 _nLeftAlignCount = 0  );
        ~OWizardMachine();

        /// enable (or disable) buttons
        void    enableButtons(sal_uInt32 _nWizardButtonFlags, sal_Bool _bEnable);
        /// set the default style for a button
        void    defaultButton(sal_uInt32 _nWizardButtonFlags);
        /// set the default style for a button
        void    defaultButton(PushButton* _pNewDefButton);

        /// set the base of the title to use - the title of the current page is appended
        void            setTitleBase(const String& _rTitleBase);
        const String&   getTitleBase() const;

    protected:
        // WizardDialog overridables
        virtual void        ActivatePage();
        virtual long        DeactivatePage();

        // our own overridables

        /// to override to create new pages
        virtual TabPage*    createPage(WizardState _nState) = 0;

        /// will be called when a new page is about to be displayed
        virtual void            enterState(WizardState _nState);

        /** will be called when the current state is about to be left for the given reason

            The base implementation in this class will simply call <member>OWizardPage::commitPage</member>
            for the current page, and return whatever this call returns.

            @param _eReason
                The reason why the state is to be left.
            @return
                <TRUE/> if and only if the page is allowed to be left
        */
        virtual sal_Bool        prepareLeaveCurrentState( CommitPageReason _eReason );

        /** will be called when the given state is left

            This is the very last possibility for derived classes to veto the deactivation
            of a page.

            @todo Normally, we would not need the return value here - derived classes now have
            the possibility to veto page deactivations in <member>prepareLeaveCurrentState</member>. However,
            changing this return type is too incompatible at the moment ...

            @return
                <TRUE/> if and only if the page is allowed to be left
        */
        virtual sal_Bool        leaveState( WizardState _nState );

        /** determine the next state to travel from the given one

            The default behaviour is linear traveling, overwrite this to change it

            Return WZS_INVALID_STATE to prevent traveling.
        */
        virtual WizardState     determineNextState(WizardState _nCurrentState);

        /** called when the finish button is pressed

By default, only the base class' Finnish method (which is not virtual) is called

        */
        virtual sal_Bool onFinish(sal_Int32 _nResult);

        /** enables a header bitmap

            Usually, wizards contain a header. This header is as wide as the dialog and positioned at the very top.
            In addition, it contains a (rather small) bitmap on the left side, and right next to this bitmap, a short
            text describing the current page.

            If you call this method, this header is automatically created on every page. In addition, all
            other controls on the pages are moved below the header. The title of every page is used as text
            for the header.

            This method must not be called if there are already pages created.

            @param _rBitmap
                the bitmap to use for the header
            @param _nPixelHeight
                the height of the header in pixels.

                If -1 is passed, the default of 30 APPFONT units will be used.
        */
        void            enableHeader( const Bitmap& _rBitmap, sal_Int32 _nPixelHeight = -1 );

        /// travel to the next state
        sal_Bool        travelNext();

        /// travel to the previous state
        sal_Bool        travelPrevious();

        /**
            removes a page from the history. Should be called when the page is being disabled
        */
        void  removePageFromHistory( WizardState nToRemove );

        /** skip a state

            The method behaves as if from the current state, <arg>_nSteps</arg> <method>travelNext</method>s were
            called, but without actually creating or displaying the ntermediate pages. Only the
            (<arg>_nSteps</arg> + 1)th page is created.

            The skipped states appear in the state history, so <method>travelPrevious</method> will make use of them.

            A very essential precondition for using this method is that your <method>determineNextState</method>
            method is able to determine the next state without actually having the page of the current state.

            @return
                <TRUE/> if and only if traveling was successfull

            @see skipUntil
            @see skipBackwardUntil
        */
        sal_Bool        skip( sal_Int32 _nSteps = 1 );

        /** skips one or more states, until a given state is reached

            The method behaves as if from the current state, <method>travelNext</method>s were called
            successively, until <arg>_nTargetState</arg> is reached, but without actually creating or
            displaying the ntermediate pages.

            The skipped states appear in the state history, so <method>travelPrevious</method> will make use of them.

            @return
                <TRUE/> if and only if traveling was successfull

            @see skip
            @see skipBackwardUntil
        */
        sal_Bool        skipUntil( WizardState _nTargetState );

        /** moves back one or more states, until a given state is reached

            This method allows traveling backwards more than one state without actually showing the intermediate
            states.

            For instance, if you want to travel two steps backward at a time, you could used
            two travelPrevious calls, but this would show both pages, which is not necessary,
            since you're interested in the target page only. Using <member>skipBackwardUntil</member> reliefs
            you from this.

            @return
                <TRUE/> if and only if traveling was successfull

            @see skipUntil
            @see skip
        */
        sal_Bool        skipBackwardUntil( WizardState _nTargetState );

        /** returns the current state of the machine

            Vulgo, this is the identifier of the current tab page :)
        */
        WizardState     getCurrentState() const { return WizardDialog::GetCurLevel(); }

        virtual IWizardPage*    getWizardPage(TabPage* _pCurrentPage) const;

        /** prevent nested calls of links next/previous or page change with the roadmap control

         */
        bool IsInCallOfLink() const;

        void SetInCallOfLink( bool bSet );

    private:
       // long OnNextPage( PushButton* );
        DECL_DLLPRIVATE_LINK(OnNextPage, PushButton*);
        DECL_DLLPRIVATE_LINK(OnPrevPage, PushButton*);
        DECL_DLLPRIVATE_LINK(OnFinish, PushButton*);

        SVT_DLLPRIVATE void     implResetDefault(Window* _pWindow);
        SVT_DLLPRIVATE void     implUpdateTitle();
    };

//.........................................................................
}   // namespace svt
//.........................................................................

#endif // _SVTOOLS_WIZARDMACHINE_HXX_

<|endoftext|>


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

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

#ifndef _VOS_MUTEX_HXX_ //autogen
#include <vos/mutex.hxx>
#endif

#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_
#include <com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLESTATETYPE_HPP_
#include <com/sun/star/accessibility/AccessibleStateType.hpp>
#endif

#ifndef _UTL_ACCESSIBLESTATESETHELPER_HXX_
#include <unotools/accessiblestatesethelper.hxx>
#endif
#ifndef _RTL_UUID_H_
#include <rtl/uuid.h>
#endif
#ifndef _SV_SVAPP_HXX //autogen
#include <vcl/svapp.hxx>
#endif
#ifndef _FTNFRM_HXX
#include <ftnfrm.hxx>
#endif
#ifndef _FMTFTN_HXX //autogen
#include <fmtftn.hxx>
#endif
#ifndef _TXTFTN_HXX //autogen
#include <txtftn.hxx>
#endif
#ifndef _VIEWSH_HXX
#include <viewsh.hxx>
#endif
#ifndef _PAGEFRM_HXX
//#include <pagefrm.hxx>
#endif
#ifndef _PAGEDESC_HXX
//#include <pagedesc.hxx>
#endif

#ifndef _FLDBAS_HXX
//#include <fldbas.hxx>
#endif
#ifndef _ACCMAP_HXX
#include <accmap.hxx>
#endif
#ifndef _ACCFOOTNOTE_HXX
#include "accfootnote.hxx"
#endif
#ifndef _ACCESS_HRC
#include "access.hrc"
#endif

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::accessibility;
using namespace ::rtl;

const sal_Char sServiceNameFootnote[] = "com.sun.star.text.AccessibleFootnoteView";
const sal_Char sServiceNameEndnote[] = "com.sun.star.text.AccessibleEndnoteView";
const sal_Char sImplementationNameFootnote[] = "com.sun.star.comp.Writer.SwAccessibleFootnoteView";
const sal_Char sImplementationNameEndnote[] = "com.sun.star.comp.Writer.SwAccessibleEndnoteView";

SwAccessibleFootnote::SwAccessibleFootnote(
        SwAccessibleMap* pInitMap,
        sal_Bool bIsEndnote,
        sal_Int32 nFootEndNote,
        const SwFtnFrm *pFtnFrm ) :
    SwAccessibleContext( pInitMap,
        bIsEndnote ? AccessibleRole::END_NOTE : AccessibleRole::FOOTNOTE,
        pFtnFrm )
{
    vos::OGuard aGuard(Application::GetSolarMutex());

    sal_uInt16 nResId = bIsEndnote ? STR_ACCESS_ENDNOTE_NAME
                                   : STR_ACCESS_FOOTNOTE_NAME;
    OUString sArg( OUString::valueOf( nFootEndNote ) );
    SetName( GetResource( nResId, &sArg ) );
}

SwAccessibleFootnote::~SwAccessibleFootnote()
{
}

OUString SAL_CALL SwAccessibleFootnote::getAccessibleDescription (void)
        throw (uno::RuntimeException)
{
    vos::OGuard aGuard(Application::GetSolarMutex());

    CHECK_FOR_DEFUNC( XAccessibleContext )

    sal_uInt16 nResId = AccessibleRole::END_NOTE == GetRole()
        ? STR_ACCESS_ENDNOTE_DESC
        : STR_ACCESS_FOOTNOTE_DESC ;

    OUString sArg;
    const SwTxtFtn *pTxtFtn =
        static_cast< const SwFtnFrm *>( GetFrm() )->GetAttr();
    if( pTxtFtn )
    {
        const SwDoc *pDoc = GetMap()->GetShell()->GetDoc();
        sArg = pTxtFtn->GetFtn().GetViewNumStr( *pDoc );
    }

    return GetResource( nResId, &sArg );
}

OUString SAL_CALL SwAccessibleFootnote::getImplementationName()
        throw( RuntimeException )
{
    if( AccessibleRole::END_NOTE == GetRole() )
        return OUString(RTL_CONSTASCII_USTRINGPARAM(sImplementationNameEndnote));
    else
        return OUString(RTL_CONSTASCII_USTRINGPARAM(sImplementationNameFootnote));
}

sal_Bool SAL_CALL SwAccessibleFootnote::supportsService(
        const ::rtl::OUString& sTestServiceName)
    throw (uno::RuntimeException)
{
    if( sTestServiceName.equalsAsciiL( sAccessibleServiceName,
                                       sizeof(sAccessibleServiceName)-1 ) )
        return sal_True;
    else if( AccessibleRole::END_NOTE == GetRole() )
        return sTestServiceName.equalsAsciiL( sServiceNameEndnote, sizeof(sServiceNameEndnote)-1 );
    else
        return sTestServiceName.equalsAsciiL( sServiceNameFootnote, sizeof(sServiceNameFootnote)-1 );

}

Sequence< OUString > SAL_CALL SwAccessibleFootnote::getSupportedServiceNames()
        throw( uno::RuntimeException )
{
    Sequence< OUString > aRet(2);
    OUString* pArray = aRet.getArray();
    if( AccessibleRole::END_NOTE == GetRole() )
        pArray[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(sServiceNameEndnote) );
    else
        pArray[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(sServiceNameFootnote) );
    pArray[1] = OUString( RTL_CONSTASCII_USTRINGPARAM(sAccessibleServiceName) );
    return aRet;
}

Sequence< sal_Int8 > SAL_CALL SwAccessibleFootnote::getImplementationId()
        throw(RuntimeException)
{
    vos::OGuard aGuard(Application::GetSolarMutex());
    static Sequence< sal_Int8 > aId( 16 );
    static sal_Bool bInit = sal_False;
    if(!bInit)
    {
        rtl_createUuid( (sal_uInt8 *)(aId.getArray() ), 0, sal_True );
        bInit = sal_True;
    }
    return aId;
}

sal_Bool SwAccessibleFootnote::IsEndnote( const SwFtnFrm *pFtnFrm )
{
    const SwTxtFtn *pTxtFtn = pFtnFrm ->GetAttr();
    return pTxtFtn && pTxtFtn->GetFtn().IsEndNote() ;
}
<commit_msg>INTEGRATION: CWS swnewlistlevelattrs_DEV300 (1.13.140); FILE MERGED 2008/01/31 12:39:46 od 1.13.140.1: #i85348# refactoring: adjust includes<commit_after> /*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: accfootnote.cxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: kz $ $Date: 2008-03-05 16:51:46 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#ifndef _VOS_MUTEX_HXX_ //autogen
#include <vos/mutex.hxx>
#endif

#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_
#include <com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLESTATETYPE_HPP_
#include <com/sun/star/accessibility/AccessibleStateType.hpp>
#endif

#ifndef _UTL_ACCESSIBLESTATESETHELPER_HXX_
#include <unotools/accessiblestatesethelper.hxx>
#endif
#ifndef _RTL_UUID_H_
#include <rtl/uuid.h>
#endif
#ifndef _SV_SVAPP_HXX //autogen
#include <vcl/svapp.hxx>
#endif
#ifndef _FTNFRM_HXX
#include <ftnfrm.hxx>
#endif
#ifndef _FMTFTN_HXX //autogen
#include <fmtftn.hxx>
#endif
#ifndef _TXTFTN_HXX //autogen
#include <txtftn.hxx>
#endif
#ifndef _VIEWSH_HXX
#include <viewsh.hxx>
#endif

#ifndef _ACCMAP_HXX
#include <accmap.hxx>
#endif
#ifndef _ACCFOOTNOTE_HXX
#include "accfootnote.hxx"
#endif
#ifndef _ACCESS_HRC
#include "access.hrc"
#endif

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::accessibility;
using namespace ::rtl;

const sal_Char sServiceNameFootnote[] = "com.sun.star.text.AccessibleFootnoteView";
const sal_Char sServiceNameEndnote[] = "com.sun.star.text.AccessibleEndnoteView";
const sal_Char sImplementationNameFootnote[] = "com.sun.star.comp.Writer.SwAccessibleFootnoteView";
const sal_Char sImplementationNameEndnote[] = "com.sun.star.comp.Writer.SwAccessibleEndnoteView";

SwAccessibleFootnote::SwAccessibleFootnote(
        SwAccessibleMap* pInitMap,
        sal_Bool bIsEndnote,
        sal_Int32 nFootEndNote,
        const SwFtnFrm *pFtnFrm ) :
    SwAccessibleContext( pInitMap,
        bIsEndnote ? AccessibleRole::END_NOTE : AccessibleRole::FOOTNOTE,
        pFtnFrm )
{
    vos::OGuard aGuard(Application::GetSolarMutex());

    sal_uInt16 nResId = bIsEndnote ? STR_ACCESS_ENDNOTE_NAME
                                   : STR_ACCESS_FOOTNOTE_NAME;
    OUString sArg( OUString::valueOf( nFootEndNote ) );
    SetName( GetResource( nResId, &sArg ) );
}

SwAccessibleFootnote::~SwAccessibleFootnote()
{
}

OUString SAL_CALL SwAccessibleFootnote::getAccessibleDescription (void)
        throw (uno::RuntimeException)
{
    vos::OGuard aGuard(Application::GetSolarMutex());

    CHECK_FOR_DEFUNC( XAccessibleContext )

    sal_uInt16 nResId = AccessibleRole::END_NOTE == GetRole()
        ? STR_ACCESS_ENDNOTE_DESC
        : STR_ACCESS_FOOTNOTE_DESC ;

    OUString sArg;
    const SwTxtFtn *pTxtFtn =
        static_cast< const SwFtnFrm *>( GetFrm() )->GetAttr();
    if( pTxtFtn )
    {
        const SwDoc *pDoc = GetMap()->GetShell()->GetDoc();
        sArg = pTxtFtn->GetFtn().GetViewNumStr( *pDoc );
    }

    return GetResource( nResId, &sArg );
}

OUString SAL_CALL SwAccessibleFootnote::getImplementationName()
        throw( RuntimeException )
{
    if( AccessibleRole::END_NOTE == GetRole() )
        return OUString(RTL_CONSTASCII_USTRINGPARAM(sImplementationNameEndnote));
    else
        return OUString(RTL_CONSTASCII_USTRINGPARAM(sImplementationNameFootnote));
}

sal_Bool SAL_CALL SwAccessibleFootnote::supportsService(
        const ::rtl::OUString& sTestServiceName)
    throw (uno::RuntimeException)
{
    if( sTestServiceName.equalsAsciiL( sAccessibleServiceName,
                                       sizeof(sAccessibleServiceName)-1 ) )
        return sal_True;
    else if( AccessibleRole::END_NOTE == GetRole() )
        return sTestServiceName.equalsAsciiL( sServiceNameEndnote, sizeof(sServiceNameEndnote)-1 );
    else
        return sTestServiceName.equalsAsciiL( sServiceNameFootnote, sizeof(sServiceNameFootnote)-1 );

}

Sequence< OUString > SAL_CALL SwAccessibleFootnote::getSupportedServiceNames()
        throw( uno::RuntimeException )
{
    Sequence< OUString > aRet(2);
    OUString* pArray = aRet.getArray();
    if( AccessibleRole::END_NOTE == GetRole() )
        pArray[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(sServiceNameEndnote) );
    else
        pArray[0] = OUString( RTL_CONSTASCII_USTRINGPARAM(sServiceNameFootnote) );
    pArray[1] = OUString( RTL_CONSTASCII_USTRINGPARAM(sAccessibleServiceName) );
    return aRet;
}

Sequence< sal_Int8 > SAL_CALL SwAccessibleFootnote::getImplementationId()
        throw(RuntimeException)
{
    vos::OGuard aGuard(Application::GetSolarMutex());
    static Sequence< sal_Int8 > aId( 16 );
    static sal_Bool bInit = sal_False;
    if(!bInit)
    {
        rtl_createUuid( (sal_uInt8 *)(aId.getArray() ), 0, sal_True );
        bInit = sal_True;
    }
    return aId;
}

sal_Bool SwAccessibleFootnote::IsEndnote( const SwFtnFrm *pFtnFrm )
{
    const SwTxtFtn *pTxtFtn = pFtnFrm ->GetAttr();
    return pTxtFtn && pTxtFtn->GetFtn().IsEndNote() ;
}
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/system_wrappers/source/trace_posix.h"

#include <assert.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>

#ifdef WEBRTC_ANDROID
#include <pthread.h>
#else
#include <iostream>
#endif

#if defined(_DEBUG)
#define BUILDMODE "d"
#elif defined(DEBUG)
#define BUILDMODE "d"
#elif defined(NDEBUG)
#define BUILDMODE "r"
#else
#define BUILDMODE "?"
#endif
#define BUILDTIME __TIME__
#define BUILDDATE __DATE__
// example: "Oct 10 2002 12:05:30 r"
#define BUILDINFO BUILDDATE " " BUILDTIME " " BUILDMODE

namespace webrtc {

TracePosix::TracePosix()
    : crit_sect_(*CriticalSectionWrapper::CreateCriticalSection()) {
  struct timeval system_time_high_res;
  gettimeofday(&system_time_high_res, 0);
  prev_api_tick_count_ = prev_tick_count_ = system_time_high_res.tv_sec;
}

TracePosix::~TracePosix() {
  delete &crit_sect_;
  StopThread();
}

int32_t TracePosix::AddTime(char* trace_message, const TraceLevel level) const {
  struct timeval system_time_high_res;
  if (gettimeofday(&system_time_high_res, 0) == -1) {
    return -1;
  }
  struct tm buffer;
  const struct tm* system_time =
    localtime_r(&system_time_high_res.tv_sec, &buffer);

  const uint32_t ms_time = system_time_high_res.tv_usec / 1000;
  uint32_t prev_tickCount = 0;
  {
    CriticalSectionScoped lock(&crit_sect_);
    if (level == kTraceApiCall) {
      prev_tickCount = prev_tick_count_;
      prev_tick_count_ = ms_time;
    } else {
      prev_tickCount = prev_api_tick_count_;
      prev_api_tick_count_ = ms_time;
    }
  }

  uint32_t dw_delta_time = ms_time - prev_tickCount;
  if (prev_tickCount == 0) {
    dw_delta_time = 0;
  }
  if (dw_delta_time > 0x0fffffff) {
    // Either wraparound or data race.
    dw_delta_time = 0;
  }
  if (dw_delta_time > 99999) {
    dw_delta_time = 99999;
  }

  sprintf(trace_message, "(%2u:%2u:%2u:%3u |%5lu) ", system_time->tm_hour,
          system_time->tm_min, system_time->tm_sec, ms_time,
          static_cast<unsigned long>(dw_delta_time));
  // Messages are 22 characters.
  return 22;
}

int32_t TracePosix::AddBuildInfo(char* trace_message) const {
  sprintf(trace_message, "Build info: %s", BUILDINFO);
  // Include NULL termination (hence + 1).
  return strlen(trace_message) + 1;
}

int32_t TracePosix::AddDateTimeInfo(char* trace_message) const {
  time_t t;
  time(&t);
  char buffer[26];  // man ctime says buffer should have room for >=26 bytes.
  sprintf(trace_message, "Local Date: %s", ctime_r(&t, buffer));
  int32_t len = static_cast<int32_t>(strlen(trace_message));

  if ('\n' == trace_message[len - 1]) {
    trace_message[len - 1] = '\0';
    --len;
  }

  // Messages is 12 characters.
  return len + 1;
}

}  // namespace webrtc
<commit_msg>Remove unneeded includes from trace_posix.cc.<commit_after>/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/system_wrappers/source/trace_posix.h"

#include <assert.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>

#if defined(_DEBUG)
#define BUILDMODE "d"
#elif defined(DEBUG)
#define BUILDMODE "d"
#elif defined(NDEBUG)
#define BUILDMODE "r"
#else
#define BUILDMODE "?"
#endif
#define BUILDTIME __TIME__
#define BUILDDATE __DATE__
// example: "Oct 10 2002 12:05:30 r"
#define BUILDINFO BUILDDATE " " BUILDTIME " " BUILDMODE

namespace webrtc {

TracePosix::TracePosix()
    : crit_sect_(*CriticalSectionWrapper::CreateCriticalSection()) {
  struct timeval system_time_high_res;
  gettimeofday(&system_time_high_res, 0);
  prev_api_tick_count_ = prev_tick_count_ = system_time_high_res.tv_sec;
}

TracePosix::~TracePosix() {
  delete &crit_sect_;
  StopThread();
}

int32_t TracePosix::AddTime(char* trace_message, const TraceLevel level) const {
  struct timeval system_time_high_res;
  if (gettimeofday(&system_time_high_res, 0) == -1) {
    return -1;
  }
  struct tm buffer;
  const struct tm* system_time =
    localtime_r(&system_time_high_res.tv_sec, &buffer);

  const uint32_t ms_time = system_time_high_res.tv_usec / 1000;
  uint32_t prev_tickCount = 0;
  {
    CriticalSectionScoped lock(&crit_sect_);
    if (level == kTraceApiCall) {
      prev_tickCount = prev_tick_count_;
      prev_tick_count_ = ms_time;
    } else {
      prev_tickCount = prev_api_tick_count_;
      prev_api_tick_count_ = ms_time;
    }
  }

  uint32_t dw_delta_time = ms_time - prev_tickCount;
  if (prev_tickCount == 0) {
    dw_delta_time = 0;
  }
  if (dw_delta_time > 0x0fffffff) {
    // Either wraparound or data race.
    dw_delta_time = 0;
  }
  if (dw_delta_time > 99999) {
    dw_delta_time = 99999;
  }

  sprintf(trace_message, "(%2u:%2u:%2u:%3u |%5lu) ", system_time->tm_hour,
          system_time->tm_min, system_time->tm_sec, ms_time,
          static_cast<unsigned long>(dw_delta_time));
  // Messages are 22 characters.
  return 22;
}

int32_t TracePosix::AddBuildInfo(char* trace_message) const {
  sprintf(trace_message, "Build info: %s", BUILDINFO);
  // Include NULL termination (hence + 1).
  return strlen(trace_message) + 1;
}

int32_t TracePosix::AddDateTimeInfo(char* trace_message) const {
  time_t t;
  time(&t);
  char buffer[26];  // man ctime says buffer should have room for >=26 bytes.
  sprintf(trace_message, "Local Date: %s", ctime_r(&t, buffer));
  int32_t len = static_cast<int32_t>(strlen(trace_message));

  if ('\n' == trace_message[len - 1]) {
    trace_message[len - 1] = '\0';
    --len;
  }

  // Messages is 12 characters.
  return len + 1;
}

}  // namespace webrtc
<|endoftext|>


<commit_before><commit_msg>Printing solver.function as energy<commit_after><|endoftext|>


<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is [Open Source Virtual Machine.].
 *
 * The Initial Developer of the Original Code is
 * Adobe System Incorporated.
 * Portions created by the Initial Developer are Copyright (C) 2004-2006
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Adobe AS3 Team
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

#include "avmthane.h"

namespace thane
{
	BEGIN_NATIVE_MAP(DomainClass)
		NATIVE_METHOD(avmplus_Domain_Domain, DomainObject::constructFromDomain)
		NATIVE_METHOD(avmplus_Domain_loadBytes, DomainObject::loadBytes)
		NATIVE_METHOD(avmplus_Domain_currentDomain_get, DomainClass::get_currentDomain)
		NATIVE_METHOD(avmplus_Domain_getClass, DomainObject::getClass)
		NATIVE_METHOD(avmplus_Domain_getClassName, DomainObject::getClassName)
		NATIVE_METHOD(avmplus_Domain_isAssignableAs, DomainObject::isAssignableAs)
	END_NATIVE_MAP()

	DomainObject::DomainObject(VTable *vtable, ScriptObject *delegate)
		: ScriptObject(vtable, delegate)
	{
	}

	DomainObject::~DomainObject()
	{
	}

	void DomainObject::constructFromDomain(DomainObject *parentDomain)
	{
		Shell *core = (Shell*) this->core();

		Domain* baseDomain;
		if (parentDomain) {
			baseDomain = parentDomain->domainEnv->getDomain();
		} else {
			baseDomain = core->builtinDomain;
		}

		Domain* domain = new (core->GetGC()) Domain(core, baseDomain);

		if (parentDomain) {
			domainToplevel = parentDomain->domainToplevel;
		} else {
			domainToplevel = core->initShellBuiltins();
		}

		domainEnv = new (core->GetGC()) DomainEnv(core, domain, parentDomain->domainEnv);
	}

	Atom DomainObject::loadBytes(ByteArrayObject *b)
	{
		AvmCore* core = this->core();
		if (!b)
			toplevel()->throwTypeError(kNullArgumentError, core->toErrorString("bytes"));

		ShellCodeContext* codeContext = new (core->GetGC()) ShellCodeContext();
		codeContext->m_domainEnv = domainEnv;

		// parse new bytecode
		size_t len = b->get_length();
		ScriptBuffer code = core->newScriptBuffer(len);
		memcpy(code.getBuffer(), &b->GetByteArray()[0], len);
		Toplevel *toplevel = domainToplevel;
		return core->handleActionBlock(code, 0,
								  domainEnv,
								  toplevel,
								  NULL, NULL, NULL, codeContext);
	}

	ScriptObject* DomainObject::finddef(Multiname* multiname,
										DomainEnv* domainEnv)
	{
		Toplevel* toplevel = this->toplevel();

		ScriptEnv* script = (ScriptEnv*) domainEnv->getScriptInit(multiname);
		if (script == (ScriptEnv*)BIND_AMBIGUOUS)
            toplevel->throwReferenceError(kAmbiguousBindingError, multiname);

		if (script == (ScriptEnv*)BIND_NONE)
            toplevel->throwReferenceError(kUndefinedVarError, multiname);

		if (script->global == NULL)
		{
			script->initGlobal();
			Atom argv[1] = { script->global->atom() };
			script->coerceEnter(0, argv);
		}

		return script->global;
	}

	ClassClosure* DomainObject::getClass(Stringp name)
	{
		AvmCore *core = this->core();

		if (name == NULL) {
			toplevel()->throwArgumentError(kNullArgumentError, core->toErrorString("name"));
		}

		// Search for a dot from the end.
		int dot;
		for (dot=name->length()-1; dot >= 0; dot--)
			if ((*name)[dot] == (wchar)'.')
				break;

		// If there is a '.', this is a fully-qualified
		// class name in a package.  Must turn it into
		// a namespace-qualified multiname.
		Namespace* ns;
		Stringp className;
		if (dot != -1) {
			Stringp uri = core->internString(new (core->GetGC()) String(name, 0, dot));
			ns = core->internNamespace(core->newNamespace(uri));
			className = core->internString(new (core->GetGC()) String(name, dot+1, name->length()-(dot+1)));
		} else {
			ns = core->publicNamespace;
			className = core->internString(name);
		}

		Multiname multiname(ns, className);

		ShellCodeContext* codeContext = (ShellCodeContext*)core->codeContext();

		ScriptObject *container = finddef(&multiname, codeContext->domainEnv());
		if (!container) {
			toplevel()->throwTypeError(kClassNotFoundError, core->toErrorString(&multiname));
		}
		Atom atom = toplevel()->getproperty(container->atom(),
											&multiname,
											container->vtable);

		if (!core->istype(atom, core->traits.class_itraits)) {
			toplevel()->throwTypeError(kClassNotFoundError, core->toErrorString(&multiname));
		}
		return (ClassClosure*)AvmCore::atomToScriptObject(atom);
	}

    Stringp DomainObject::getClassName (Atom a)
    {
        return getTraits(a)->formatClassName();
    }

    Traits *DomainObject::getTraits (Atom a)
    {
        if (a < kSpecialType) {
            return core()->traits.null_itraits;
        }
        if (a == kSpecialType) {
            return core()->traits.void_itraits;
        }
        switch (a & 7) {
        case kObjectType:
            return AvmCore::atomToScriptObject(a)->traits();
        case kNamespaceType:
            return core()->traits.namespace_itraits;
        case kStringType:
            return core()->traits.string_itraits;
        case kBooleanType:
            return core()->traits.boolean_itraits;
        case kIntegerType:
            return core()->traits.int_itraits;
        case kDoubleType:
            return core()->traits.number_itraits;
        }
        toplevel()->throwArgumentError(kNotImplementedError, core()->toErrorString("value"));
        return core()->traits.void_itraits;
   }

    bool DomainObject::isAssignableAs (ClassClosure *asClass, ClassClosure *srcClass)
    {
        // Note: itraits guaranteed != NULL in ClassClosure
        return srcClass->traits()->itraits->containsInterface(asClass->traits()->itraits);
    }

	DomainClass::DomainClass(VTable *cvtable)
		: ClassClosure(cvtable)
	{
		createVanillaPrototype();
	}

	ScriptObject* DomainClass::createInstance(VTable *ivtable,
											  ScriptObject *prototype)
	{
		return new (core()->GetGC(), ivtable->getExtraSize()) DomainObject(ivtable, prototype);
	}

	DomainObject* DomainClass::get_currentDomain()
	{
		ShellCodeContext* codeContext = (ShellCodeContext*)core()->codeContext();

		DomainObject* domainObject = (DomainObject*) createInstance(ivtable(), prototype);
		domainObject->domainEnv = codeContext->domainEnv();
		domainObject->domainToplevel = toplevel();

		return domainObject;
	}
}
<commit_msg>Oh boy, that took a while to find.<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is [Open Source Virtual Machine.].
 *
 * The Initial Developer of the Original Code is
 * Adobe System Incorporated.
 * Portions created by the Initial Developer are Copyright (C) 2004-2006
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Adobe AS3 Team
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

#include "avmthane.h"

namespace thane
{
	BEGIN_NATIVE_MAP(DomainClass)
		NATIVE_METHOD(avmplus_Domain_Domain, DomainObject::constructFromDomain)
		NATIVE_METHOD(avmplus_Domain_loadBytes, DomainObject::loadBytes)
		NATIVE_METHOD(avmplus_Domain_currentDomain_get, DomainClass::get_currentDomain)
		NATIVE_METHOD(avmplus_Domain_getClass, DomainObject::getClass)
		NATIVE_METHOD(avmplus_Domain_getClassName, DomainObject::getClassName)
		NATIVE_METHOD(avmplus_Domain_isAssignableAs, DomainObject::isAssignableAs)
	END_NATIVE_MAP()

	DomainObject::DomainObject(VTable *vtable, ScriptObject *delegate)
		: ScriptObject(vtable, delegate)
	{
	}

	DomainObject::~DomainObject()
	{
	}

	void DomainObject::constructFromDomain(DomainObject *parentDomain)
	{
		Shell *core = (Shell*) this->core();

		Domain* baseDomain;
		if (parentDomain) {
			baseDomain = parentDomain->domainEnv->getDomain();
		} else {
			baseDomain = core->builtinDomain;
		}

		Domain* domain = new (core->GetGC()) Domain(core, baseDomain);

		if (parentDomain) {
			domainToplevel = parentDomain->domainToplevel;
		} else {
			domainToplevel = core->initShellBuiltins();
		}

		domainEnv = new (core->GetGC()) DomainEnv(core, domain, parentDomain->domainEnv);
	}

	Atom DomainObject::loadBytes(ByteArrayObject *b)
	{
		AvmCore* core = this->core();
		if (!b)
			toplevel()->throwTypeError(kNullArgumentError, core->toErrorString("bytes"));

		ShellCodeContext* codeContext = new (core->GetGC()) ShellCodeContext();
		codeContext->m_domainEnv = domainEnv;

		// parse new bytecode
		size_t len = b->get_length();
		ScriptBuffer code = core->newScriptBuffer(len);
		memcpy(code.getBuffer(), &b->GetByteArray()[0], len);
		Toplevel *toplevel = domainToplevel;
		return core->handleActionBlock(code, 0,
								  domainEnv,
								  toplevel,
								  NULL, NULL, NULL, codeContext);
	}

	ScriptObject* DomainObject::finddef(Multiname* multiname,
										DomainEnv* domainEnv)
	{
		Toplevel* toplevel = this->toplevel();

		ScriptEnv* script = (ScriptEnv*) domainEnv->getScriptInit(multiname);
		if (script == (ScriptEnv*)BIND_AMBIGUOUS)
            toplevel->throwReferenceError(kAmbiguousBindingError, multiname);

		if (script == (ScriptEnv*)BIND_NONE)
            toplevel->throwReferenceError(kUndefinedVarError, multiname);

		if (script->global == NULL)
		{
			script->initGlobal();
			Atom argv[1] = { script->global->atom() };
			script->coerceEnter(0, argv);
		}

		return script->global;
	}

	ClassClosure* DomainObject::getClass(Stringp name)
	{
		AvmCore *core = this->core();

		if (name == NULL) {
			toplevel()->throwArgumentError(kNullArgumentError, core->toErrorString("name"));
		}

		// Search for a dot from the end.
		int dot;
		for (dot=name->length()-1; dot >= 0; dot--)
			if ((*name)[dot] == (wchar)'.')
				break;

		// If there is a '.', this is a fully-qualified
		// class name in a package.  Must turn it into
		// a namespace-qualified multiname.
		Namespace* ns;
		Stringp className;
		if (dot != -1) {
			Stringp uri = core->internString(new (core->GetGC()) String(name, 0, dot));
			ns = core->internNamespace(core->newNamespace(uri));
			className = core->internString(new (core->GetGC()) String(name, dot+1, name->length()-(dot+1)));
		} else {
			ns = core->publicNamespace;
			className = core->internString(name);
		}

		Multiname multiname(ns, className);

		ShellCodeContext* codeContext = (ShellCodeContext*)core->codeContext();

		ScriptObject *container = finddef(&multiname, codeContext->domainEnv());
		if (!container) {
			toplevel()->throwTypeError(kClassNotFoundError, core->toErrorString(&multiname));
		}
		Atom atom = toplevel()->getproperty(container->atom(),
											&multiname,
											container->vtable);

		if (!core->istype(atom, core->traits.class_itraits)) {
			toplevel()->throwTypeError(kClassNotFoundError, core->toErrorString(&multiname));
		}
		return (ClassClosure*)AvmCore::atomToScriptObject(atom);
	}

    Stringp DomainObject::getClassName (Atom a)
    {
        return getTraits(a)->formatClassName();
    }

    Traits *DomainObject::getTraits (Atom a)
    {
        if (ISNULL(a)) {
            return core()->traits.null_itraits;
        }
        if (a == kSpecialType) {
            return core()->traits.void_itraits;
        }
        switch (a & 7) {
        case kObjectType:
            return AvmCore::atomToScriptObject(a)->traits();
        case kNamespaceType:
            return core()->traits.namespace_itraits;
        case kStringType:
            return core()->traits.string_itraits;
        case kBooleanType:
            return core()->traits.boolean_itraits;
        case kIntegerType:
            return core()->traits.int_itraits;
        case kDoubleType:
            return core()->traits.number_itraits;
        }
        toplevel()->throwArgumentError(kNotImplementedError, core()->toErrorString("value"));
        return core()->traits.void_itraits;
   }

    bool DomainObject::isAssignableAs (ClassClosure *asClass, ClassClosure *srcClass)
    {
        // Note: itraits guaranteed != NULL in ClassClosure
        return srcClass->traits()->itraits->containsInterface(asClass->traits()->itraits);
    }

	DomainClass::DomainClass(VTable *cvtable)
		: ClassClosure(cvtable)
	{
		createVanillaPrototype();
	}

	ScriptObject* DomainClass::createInstance(VTable *ivtable,
											  ScriptObject *prototype)
	{
		return new (core()->GetGC(), ivtable->getExtraSize()) DomainObject(ivtable, prototype);
	}

	DomainObject* DomainClass::get_currentDomain()
	{
		ShellCodeContext* codeContext = (ShellCodeContext*)core()->codeContext();

		DomainObject* domainObject = (DomainObject*) createInstance(ivtable(), prototype);
		domainObject->domainEnv = codeContext->domainEnv();
		domainObject->domainToplevel = toplevel();

		return domainObject;
	}
}
<|endoftext|>


<commit_before>#include <memory>
#include <string>
#include <utility>

#include "core/AllPix.hpp"
#include "core/config/ConfigManager.hpp"
#include "core/geometry/GeometryManager.hpp"
#include "core/module/StaticModuleManager.hpp"
#include "core/utils/exceptions.h"
#include "core/utils/log.h"

#include "core/module/DetectorModuleFactory.hpp"
#include "core/module/UniqueModuleFactory.hpp"

// FIXME: should not be here
#include "modules/GeometryBuilderTGeo/TGeoBuilderModule.hpp"
#include "modules/deposit_reader_test/TestDepositReaderModule.hpp"
#include "modules/detector_histogrammer_test/DetectorHistogrammerTestModule.hpp"

#include "modules/DepositionGeant4/DepositionGeant4Module.hpp"
#include "modules/Example/ExampleModule.hpp"
#include "modules/GeometryBuilderGeant4/GeometryBuilderGeant4Module.hpp"
#include "modules/VisualizationGeant4/VisualizationGeant4Module.hpp"

using namespace allpix;

// FIXME: temporary generator function for as long we do not have dynamic loading
std::unique_ptr<ModuleFactory> generator(const std::string& str);
std::unique_ptr<ModuleFactory> generator(const std::string& str) {
    if(str == GeometryBuilderGeant4Module::name) {
        return std::make_unique<UniqueModuleFactory<GeometryBuilderGeant4Module>>();
    }
    if(str == DepositionGeant4Module::name) {
        return std::make_unique<UniqueModuleFactory<DepositionGeant4Module>>();
    }
    if(str == VisualizationGeant4Module::name) {
        return std::make_unique<UniqueModuleFactory<VisualizationGeant4Module>>();
    }
    if(str == ExampleModule::name) {
        return std::make_unique<UniqueModuleFactory<ExampleModule>>();
    }

    if(str == DetectorHistogrammerModule::name) {
        return std::make_unique<DetectorModuleFactory<DetectorHistogrammerModule>>();
    }
    if(str == TGeoBuilderModule::name) {
        return std::make_unique<UniqueModuleFactory<TGeoBuilderModule>>();
    }
    if(str == TestDepositReaderModule::name) {
        return std::make_unique<UniqueModuleFactory<TestDepositReaderModule>>();
    }

    return nullptr;
}

int main(int argc, const char* argv[]) {
    // FIXME: have standard config and pass replacement as single argument until we have proper argument handling
    std::string config_file_name = "etc/example_config.ini";
    if(argc == 2) {
        config_file_name = argv[1];
    }

    try {
        // Set global log level:
        LogLevel log_level = Log::getLevelFromString("DEBUG");
        Log::setReportingLevel(log_level);
        LOG(INFO) << "Set log level: " << Log::getStringFromLevel(log_level);

        // Construct managers
        // FIXME: move module manager initialization to AllPix as soon we have dynamic loading
        std::unique_ptr<StaticModuleManager> mod = std::make_unique<StaticModuleManager>(&generator);

        // Construct main AllPix object
        std::unique_ptr<AllPix> apx = std::make_unique<AllPix>(config_file_name, std::move(mod));

        LOG(INFO) << "Initializing AllPix";
        apx->init();

        LOG(INFO) << "Running AllPix";
        apx->run();

        LOG(INFO) << "Finishing AllPix";
        apx->finalize();
    } catch(ConfigurationError& e) {
        LOG(CRITICAL) << "Error in the configuration file:" << std::endl
                      << "   " << e.what() << std::endl
                      << "The configuration file needs to be updated! Cannot continue...";
        return 1;
    } catch(RuntimeError& e) {
        LOG(CRITICAL) << "Error during execution of run:" << std::endl
                      << "   " << e.what() << std::endl
                      << "Please check your configuration and modules! Cannot continue...";
        return 1;
    } catch(LogicError& e) {
        LOG(CRITICAL) << "Error in the logic of module:" << std::endl
                      << "   " << e.what() << std::endl
                      << "Module has to be properly defined! Cannot continue...";
        return 1;
    } catch(std::exception& e) {
        LOG(CRITICAL) << "Fatal internal error" << std::endl << "   " << e.what() << std::endl << "Cannot continue...";
        return 127;
    }

    return 0;
}
<commit_msg>removed direct factory include<commit_after>#include <memory>
#include <string>
#include <utility>

#include "core/AllPix.hpp"
#include "core/config/ConfigManager.hpp"
#include "core/geometry/GeometryManager.hpp"
#include "core/module/StaticModuleManager.hpp"
#include "core/utils/exceptions.h"
#include "core/utils/log.h"

#include "core/module/ModuleFactory.hpp"

// FIXME: should not be here
#include "modules/GeometryBuilderTGeo/TGeoBuilderModule.hpp"
#include "modules/deposit_reader_test/TestDepositReaderModule.hpp"
#include "modules/detector_histogrammer_test/DetectorHistogrammerTestModule.hpp"

#include "modules/DepositionGeant4/DepositionGeant4Module.hpp"
#include "modules/Example/ExampleModule.hpp"
#include "modules/GeometryBuilderGeant4/GeometryBuilderGeant4Module.hpp"
#include "modules/VisualizationGeant4/VisualizationGeant4Module.hpp"

using namespace allpix;

// FIXME: temporary generator function for as long we do not have dynamic loading
std::unique_ptr<ModuleFactory> generator(const std::string& str);
std::unique_ptr<ModuleFactory> generator(const std::string& str) {
    if(str == GeometryBuilderGeant4Module::name) {
        return std::make_unique<UniqueModuleFactory<GeometryBuilderGeant4Module>>();
    }
    if(str == DepositionGeant4Module::name) {
        return std::make_unique<UniqueModuleFactory<DepositionGeant4Module>>();
    }
    if(str == VisualizationGeant4Module::name) {
        return std::make_unique<UniqueModuleFactory<VisualizationGeant4Module>>();
    }
    if(str == ExampleModule::name) {
        return std::make_unique<UniqueModuleFactory<ExampleModule>>();
    }

    if(str == DetectorHistogrammerModule::name) {
        return std::make_unique<DetectorModuleFactory<DetectorHistogrammerModule>>();
    }
    if(str == TGeoBuilderModule::name) {
        return std::make_unique<UniqueModuleFactory<TGeoBuilderModule>>();
    }
    if(str == TestDepositReaderModule::name) {
        return std::make_unique<UniqueModuleFactory<TestDepositReaderModule>>();
    }

    return nullptr;
}

int main(int argc, const char* argv[]) {
    // FIXME: have standard config and pass replacement as single argument until we have proper argument handling
    std::string config_file_name = "etc/example_config.ini";
    if(argc == 2) {
        config_file_name = argv[1];
    }

    try {
        // Set global log level:
        LogLevel log_level = Log::getLevelFromString("DEBUG");
        Log::setReportingLevel(log_level);
        LOG(INFO) << "Set log level: " << Log::getStringFromLevel(log_level);

        // Construct managers
        // FIXME: move module manager initialization to AllPix as soon we have dynamic loading
        std::unique_ptr<StaticModuleManager> mod = std::make_unique<StaticModuleManager>(&generator);

        // Construct main AllPix object
        std::unique_ptr<AllPix> apx = std::make_unique<AllPix>(config_file_name, std::move(mod));

        LOG(INFO) << "Initializing AllPix";
        apx->init();

        LOG(INFO) << "Running AllPix";
        apx->run();

        LOG(INFO) << "Finishing AllPix";
        apx->finalize();
    } catch(ConfigurationError& e) {
        LOG(CRITICAL) << "Error in the configuration file:" << std::endl
                      << "   " << e.what() << std::endl
                      << "The configuration file needs to be updated! Cannot continue...";
        return 1;
    } catch(RuntimeError& e) {
        LOG(CRITICAL) << "Error during execution of run:" << std::endl
                      << "   " << e.what() << std::endl
                      << "Please check your configuration and modules! Cannot continue...";
        return 1;
    } catch(LogicError& e) {
        LOG(CRITICAL) << "Error in the logic of module:" << std::endl
                      << "   " << e.what() << std::endl
                      << "Module has to be properly defined! Cannot continue...";
        return 1;
    } catch(std::exception& e) {
        LOG(CRITICAL) << "Fatal internal error" << std::endl << "   " << e.what() << std::endl << "Cannot continue...";
        return 127;
    }

    return 0;
}
<|endoftext|>


<commit_before>//
// Description: Widget that local variables of the gdb inferior
//
// Copyright (c) 2010 Kåre Särs <kare.sars@iki.fi>
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Library General Public
//  License version 2 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
//  Library General Public License for more details.
//
//  You should have received a copy of the GNU Library General Public License
//  along with this library; see the file COPYING.LIB.  If not, write to
//  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
//  Boston, MA 02110-1301, USA.

#include "localsview.h"
#include <klocale.h>
#include <kdebug.h>

LocalsView::LocalsView(QWidget *parent)
:   QTreeWidget(parent), m_allAdded(true)
{
    QStringList headers;
    headers << i18n("Symbol");
    headers << i18n("Value");
    setHeaderLabels(headers);
    setAutoScroll(false);
}

LocalsView::~LocalsView()
{
}

void LocalsView::addLocal(const QString &vString)
{
    static QRegExp isValue("(\\S*)\\s=\\s(.*)");
    static QRegExp isStruct("\\{\\S*\\s=\\s.*");
    static QRegExp isStartPartial("\\S*\\s=\\s\\{");

    if (m_allAdded) {
        clear();
        m_allAdded = false;
    }

    if (vString.isEmpty()) {
        m_allAdded = true;
        resizeColumnToContents(1);
        return;
    }

    if (isStartPartial.exactMatch(vString)) {
        m_local = vString;
        return;
    }

    if (!isValue.exactMatch(vString)) {
        if (!m_local.isEmpty()) {
            m_local += vString;
        }
        if (vString != "}") {
            return;
        }
    }

    QStringList symbolVal;
    symbolVal << isValue.cap(1);
    QString val = isValue.cap(2);
    QTreeWidgetItem *item;
    if (val[0] == '{') {
        if (val[1] == '{') {
            item = new QTreeWidgetItem(this, symbolVal);
            addArray(item, val.mid(1, val.size()-2));
        }
        else {
            if (isStruct.exactMatch(val)) {
                item = new QTreeWidgetItem(this, symbolVal);
                addStruct(item, val.mid(1, val.size()-2));
            }
            else {
                symbolVal << val;
                new QTreeWidgetItem(this, symbolVal);
            }
        }
    }
    else {
        symbolVal << val;
        new QTreeWidgetItem(this, symbolVal);
    }

    m_local.clear();
}

void LocalsView::addStruct(QTreeWidgetItem *parent, const QString &vString)
{
    static QRegExp isArray("\\{\\S*\\s=\\s.*");
    static QRegExp isStruct("\\S*\\s=\\s.*");
    QTreeWidgetItem *item;
    QStringList symbolVal;
    QString subValue;
    int start = 0;
    int end;
    while (start < vString.size()) {
        // Symbol
        symbolVal.clear();
        end = vString.indexOf(" = ", start);
        symbolVal << vString.mid(start, end-start);
        //kDebug() << symbolVal;

        // Value
        start = end + 3;
        end = start+1;
        if (vString[start] == '{') {
            start++;
            int count = 1;
            bool inComment = false;
            // search for the matching }
            while(end < vString.size()) {
                if (!inComment) {
                    if (vString[end] == '"') inComment = true;
                    else if (vString[end] == '}') count--;
                    else if (vString[end] == '{') count++;
                    if (count == 0) break;
                }
                else {
                    if ((vString[end] == '"') && (vString[end-1] != '\\')) {
                        inComment = false;
                    }
                }
                end++;
            }
            subValue = vString.mid(start, end-start);
            if (isArray.exactMatch(subValue)) {
                item = new QTreeWidgetItem(parent, symbolVal);
                addArray(item, subValue);
            }
            else if (isStruct.exactMatch(subValue)) {
                item = new QTreeWidgetItem(parent, symbolVal);
                addStruct(item, subValue);
            }
            else {
                symbolVal << vString.mid(start, end-start);
                new QTreeWidgetItem(parent, symbolVal);
            }
            start = end + 3; // },_
        }
        else {
            // look for the end of the vString
            bool inComment = false;
            while(end < vString.size()) {
                if (!inComment) {
                    if (vString[end] == '"') inComment = true;
                    else if (vString[end] == ',') break;
                }
                else {
                    if ((vString[end] == '"') && (vString[end-1] != '\\')) {
                        inComment = false;
                    }
                }
                end++;
            }
            symbolVal << vString.mid(start, end-start);
            new QTreeWidgetItem(parent, symbolVal);
            start = end + 2; // ,_
        }
    }
}

void LocalsView::addArray(QTreeWidgetItem *parent, const QString &vString)
{
    // getting here we have this kind of string:
    // "{...}" or "{...}, {...}" or ...
    QTreeWidgetItem *item;
    int count = 1;
    bool inComment = false;
    int index = 0;
    int start = 1;
    int end = 1;

    while (end < vString.size()) {
        if (!inComment) {
            if (vString[end] == '"') inComment = true;
            else if (vString[end] == '}') count--;
            else if (vString[end] == '{') count++;
            if (count == 0) {
                QStringList name;
                name << QString("[%1]").arg(index);
                index++;
                item = new QTreeWidgetItem(parent, name);
                addStruct(item, vString.mid(start, end-start));
                end += 4; // "}, {"
                start = end;
                count = 1;
            }
        }
        else {
            if ((vString[end] == '"') && (vString[end-1] != '\\')) {
                inComment = false;
            }
        }
        end++;
    }
}<commit_msg>gdb-plugin: Add support for pretty printed QList<...> in the locals<commit_after>//
// Description: Widget that local variables of the gdb inferior
//
// Copyright (c) 2010 Kåre Särs <kare.sars@iki.fi>
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Library General Public
//  License version 2 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
//  Library General Public License for more details.
//
//  You should have received a copy of the GNU Library General Public License
//  along with this library; see the file COPYING.LIB.  If not, write to
//  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
//  Boston, MA 02110-1301, USA.

#include "localsview.h"
#include <klocale.h>
#include <kdebug.h>

LocalsView::LocalsView(QWidget *parent)
:   QTreeWidget(parent), m_allAdded(true)
{
    QStringList headers;
    headers << i18n("Symbol");
    headers << i18n("Value");
    setHeaderLabels(headers);
    setAutoScroll(false);
}

LocalsView::~LocalsView()
{
}

void LocalsView::addLocal(const QString &vString)
{
    static QRegExp isValue("(\\S*)\\s=\\s(.*)");
    static QRegExp isStruct("\\{\\S*\\s=\\s.*");
    static QRegExp isStartPartial("\\S*\\s=\\s\\S*\\s=\\s\\{");
    static QRegExp isPrettyQList("\\s*\\[\\S*\\]\\s=\\s\\S*");
    static QRegExp isPrettyValue("(\\S*)\\s=\\s(\\S*)\\s=\\s(.*)");

    if (m_allAdded) {
        clear();
        m_allAdded = false;
    }

    if (vString.isEmpty()) {
        m_allAdded = true;
        resizeColumnToContents(1);
        return;
    }
    if (isStartPartial.exactMatch(vString)) {
        m_local = vString;
        return;
    }
    if (isPrettyQList.exactMatch(vString)) {
        m_local += vString.trimmed();
        if (m_local.endsWith(',')) m_local += ' ';
        return;
    }
    if (vString == "}") {
        m_local += vString;
    }

    QStringList symbolAndValue;
    QString value;

    if (m_local.isEmpty()) {
        if (!isValue.exactMatch(vString)) {
            qDebug() << "Could not parse:" << vString;
            return;
        }
        symbolAndValue << isValue.cap(1);
        value = isValue.cap(2);
    }
    else {
        if (!isPrettyValue.exactMatch(m_local)) {
            qDebug() << "Could not parse:" << m_local;
            m_local.clear();
            return;
        }
        symbolAndValue << isPrettyValue.cap(1) << isPrettyValue.cap(2);
        value = isPrettyValue.cap(3);
    }

    QTreeWidgetItem *item;
    if (value[0] == '{') {
        if (value[1] == '{') {
            item = new QTreeWidgetItem(this, symbolAndValue);
            addArray(item, value.mid(1, value.size()-2));
        }
        else {
            if (isStruct.exactMatch(value)) {
                item = new QTreeWidgetItem(this, symbolAndValue);
                addStruct(item, value.mid(1, value.size()-2));
            }
            else {
                symbolAndValue << value;
                new QTreeWidgetItem(this, symbolAndValue);
            }
        }
    }
    else {
        symbolAndValue << value;
        new QTreeWidgetItem(this, symbolAndValue);
    }

    m_local.clear();
}

void LocalsView::addStruct(QTreeWidgetItem *parent, const QString &vString)
{
    static QRegExp isArray("\\{\\S*\\s=\\s.*");
    static QRegExp isStruct("\\S*\\s=\\s.*");
    QTreeWidgetItem *item;
    QStringList symbolAndValue;
    QString subValue;
    int start = 0;
    int end;
    while (start < vString.size()) {
        // Symbol
        symbolAndValue.clear();
        end = vString.indexOf(" = ", start);
        symbolAndValue << vString.mid(start, end-start);
        //kDebug() << symbolAndValue;

        // Value
        start = end + 3;
        end = start;
        if (vString[start] == '{') {
            start++;
            end++;
            int count = 1;
            bool inComment = false;
            // search for the matching }
            while(end < vString.size()) {
                if (!inComment) {
                    if (vString[end] == '"') inComment = true;
                    else if (vString[end] == '}') count--;
                    else if (vString[end] == '{') count++;
                    if (count == 0) break;
                }
                else {
                    if ((vString[end] == '"') && (vString[end-1] != '\\')) {
                        inComment = false;
                    }
                }
                end++;
            }
            subValue = vString.mid(start, end-start);
            if (isArray.exactMatch(subValue)) {
                item = new QTreeWidgetItem(parent, symbolAndValue);
                addArray(item, subValue);
            }
            else if (isStruct.exactMatch(subValue)) {
                item = new QTreeWidgetItem(parent, symbolAndValue);
                addStruct(item, subValue);
            }
            else {
                symbolAndValue << vString.mid(start, end-start);
                new QTreeWidgetItem(parent, symbolAndValue);
            }
            start = end + 3; // },_
        }
        else {
            // look for the end of the value in the vString
            bool inComment = false;
            while(end < vString.size()) {
                if (!inComment) {
                    if (vString[end] == '"') inComment = true;
                    else if (vString[end] == ',') break;
                }
                else {
                    if ((vString[end] == '"') && (vString[end-1] != '\\')) {
                        inComment = false;
                    }
                }
                end++;
            }
            symbolAndValue << vString.mid(start, end-start);
            new QTreeWidgetItem(parent, symbolAndValue);
            start = end + 2; // ,_
        }
    }
}

void LocalsView::addArray(QTreeWidgetItem *parent, const QString &vString)
{
    // getting here we have this kind of string:
    // "{...}" or "{...}, {...}" or ...
    QTreeWidgetItem *item;
    int count = 1;
    bool inComment = false;
    int index = 0;
    int start = 1;
    int end = 1;

    while (end < vString.size()) {
        if (!inComment) {
            if (vString[end] == '"') inComment = true;
            else if (vString[end] == '}') count--;
            else if (vString[end] == '{') count++;
            if (count == 0) {
                QStringList name;
                name << QString("[%1]").arg(index);
                index++;
                item = new QTreeWidgetItem(parent, name);
                addStruct(item, vString.mid(start, end-start));
                end += 4; // "}, {"
                start = end;
                count = 1;
            }
        }
        else {
            if ((vString[end] == '"') && (vString[end-1] != '\\')) {
                inComment = false;
            }
        }
        end++;
    }
}<|endoftext|>