<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dinfdlg.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2007-07-17 13:37:03 $
 *
 *  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 _SFX_DINFDLG_HXX
#define _SFX_DINFDLG_HXX

#ifndef _SAL_CONFIG_H_
#include "sal/config.h"
#endif

#ifndef INCLUDED_SFX2_DLLAPI_H
#include "sfx2/dllapi.h"
#endif

#ifndef _SV_EDIT_HXX //autogen wg. Edit
#include <vcl/edit.hxx>
#endif
#ifndef _SV_FIELD_HXX //autogen wg. NumericField
#include <vcl/field.hxx>
#endif
#ifndef _STDCTRL_HXX //autogen wg. FixedText, FixedInfo
#include <svtools/stdctrl.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen wg. SfxStringItem
#include <svtools/stritem.hxx>
#endif
#ifndef _SVEDIT_HXX //autogen wg. MultiLineEdit
#include <svtools/svmedit.hxx>
#endif

#include "tabdlg.hxx"
#include "docinf.hxx"

// class SfxDocumentInfoItem ---------------------------------------------

class SFX2_DLLPUBLIC SfxDocumentInfoItem : public SfxStringItem
{
private:
    SfxDocumentInfo         aDocInfo;
    sal_Bool                bHasTemplate;
    sal_Bool                bDeleteUserData;
    sal_Bool                bIsUseUserData;

public:
    TYPEINFO();
    SfxDocumentInfoItem();
    SfxDocumentInfoItem( const String &rFileName, const SfxDocumentInfo&, sal_Bool bUseUserData );
    SfxDocumentInfoItem( const SfxDocumentInfoItem& );
    virtual ~SfxDocumentInfoItem();

    void                    SetTemplate( BOOL b ) { bHasTemplate = b; }
    FASTBOOL                HasTemplate() const { return bHasTemplate; }
    void                    SetDeleteUserData( BOOL bSet );
    void                    SetUseUserData( BOOL bSet );
    BOOL                    IsDeleteUserData() const;
    BOOL                    IsUseUserData() const;

    SfxDocumentInfo&        operator()() { return aDocInfo; }
    const SfxDocumentInfo&  operator()() const { return aDocInfo; }
    SfxDocumentInfo&        GetDocInfo() { return aDocInfo; }
    const SfxDocumentInfo&  GetDocInfo() const { return aDocInfo; }

    virtual SfxPoolItem*    Clone( SfxItemPool* pPool = NULL ) const;
    virtual int             operator==( const SfxPoolItem& ) const;
    virtual sal_Bool        QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;
    virtual sal_Bool        PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );
};

// class SfxDocumentPage -------------------------------------------------

class SfxDocumentPage : public SfxTabPage
{
private:
    FixedImage                  aBmp1;
    Edit                        aNameED;

    FixedLine                   aLine1FL;
    FixedText                   aTypeFT;
    svt::SelectableFixedText    aShowTypeFT;
    CheckBox                    aReadOnlyCB;
    FixedText                   aFileFt;
    svt::SelectableFixedText    aFileValFt;
    FixedText                   aSizeFT;
    svt::SelectableFixedText    aShowSizeFT;

    FixedLine                   aLine2FL;
    FixedText                   aCreateFt;
    svt::SelectableFixedText    aCreateValFt;
    FixedText                   aChangeFt;
    svt::SelectableFixedText    aChangeValFt;
    FixedText                   aSignedFt;
    svt::SelectableFixedText    aSignedValFt;
    PushButton                  aSignatureBtn;
    FixedText                   aPrintFt;
    svt::SelectableFixedText    aPrintValFt;
    FixedText                   aTimeLogFt;
    svt::SelectableFixedText    aTimeLogValFt;
    FixedText                   aDocNoFt;
    svt::SelectableFixedText    aDocNoValFt;
    CheckBox                    aUseUserDataCB;
    PushButton                  aDeleteBtn;

    FixedLine                   aLine3FL;
    FixedText                   aTemplFt;
    svt::SelectableFixedText    aTemplValFt;

    String                      aUnknownSize;
    String                      aMultiSignedStr;

    BOOL                        bEnableUseUserData  : 1,
                                bHandleDelete       : 1;

    DECL_LINK(          DeleteHdl, PushButton * );
    DECL_LINK(          SignatureHdl, PushButton * );
    void                ImplUpdateSignatures();

protected:
    SfxDocumentPage( Window* pParent, const SfxItemSet& );

    virtual BOOL        FillItemSet( SfxItemSet& );
    virtual void        Reset( const SfxItemSet& );

public:
    static SfxTabPage*  Create( Window* pParent, const SfxItemSet& );

    void                EnableUseUserData();
};

// class SfxDocumentDescPage ---------------------------------------------

class SfxDocumentDescPage : public SfxTabPage
{
private:
    FixedText               aTitleFt;
    Edit                    aTitleEd;
    FixedText               aThemaFt;
    Edit                    aThemaEd;
    FixedText               aKeywordsFt;
    Edit                    aKeywordsEd;
    FixedText               aCommentFt;
    MultiLineEdit           aCommentEd;
    SfxDocumentInfoItem*    pInfoItem;

protected:
    SfxDocumentDescPage( Window* pParent, const SfxItemSet& );

    virtual BOOL            FillItemSet( SfxItemSet& );
    virtual void            Reset( const SfxItemSet& );

public:
    static SfxTabPage*      Create( Window* pParent, const SfxItemSet& );
};

// class SfxDocumentUserPage ---------------------------------------------

class SfxDocumentUserPage : public SfxTabPage
{
private:
    BOOL                    bLabelModified;

    FixedText               aInfo1Ft;
    Edit                    aInfo1Ed;
    FixedText               aInfo2Ft;
    Edit                    aInfo2Ed;
    FixedText               aInfo3Ft;
    Edit                    aInfo3Ed;
    FixedText               aInfo4Ft;
    Edit                    aInfo4Ed;
    PushButton              aEditLabelBtn;
    SfxDocumentInfoItem*    pInfoItem;

#if _SOLAR__PRIVATE
    DECL_LINK( EditLabelHdl, PushButton * );

    String              GetLabelText_Impl( FixedText* pLabel );
    void                SetLabelText_Impl( FixedText* pLabel, const String& rNewLabel );
#endif

protected:
    SfxDocumentUserPage( Window* pParent, const SfxItemSet& );

    virtual BOOL        FillItemSet( SfxItemSet& );
    virtual void        Reset( const SfxItemSet& );

public:
    static SfxTabPage*  Create( Window* pParent, const SfxItemSet& );
};

// class SfxInternetPage -------------------------------------------------

class TargetList;
namespace sfx2
{
    class FileDialogHelper;
}

class SfxInternetPage : public SfxTabPage
{
private:
    RadioButton             aRBNoAutoUpdate;
    RadioButton             aRBReloadUpdate;
    RadioButton             aRBForwardUpdate;

    FixedText               aFTEvery;
    NumericField            aNFReload;
    FixedText               aFTReloadSeconds;

    FixedText               aFTAfter;
    NumericField            aNFAfter;
    FixedText               aFTAfterSeconds;
    FixedText               aFTURL;
    Edit                    aEDForwardURL;
    PushButton              aPBBrowseURL;
    FixedText               aFTFrame;
    ComboBox                aCBFrame;

    String                  aForwardErrorMessg;
    String                  aBaseURL;
    SfxDocumentInfoItem*    pInfoItem;
    sfx2::FileDialogHelper* pFileDlg;

    enum STATE              { S_Init, S_NoUpdate, S_Reload, S_Forward };
                            // S_Init is only valid as initial value
    STATE                   eState;

    void                    ChangeState( STATE eNewState );     // S_Init is not a valid value here
                                                                // also checks corresponding radiobutton
    void                    EnableNoUpdate( BOOL bEnable );
    void                    EnableReload( BOOL bEnable );
    void                    EnableForward( BOOL bEnable );

    DECL_LINK( ClickHdlNoUpdate, Control* );
    DECL_LINK( ClickHdlReload, Control* );
    DECL_LINK( ClickHdlForward, Control* );
    DECL_LINK( ClickHdlBrowseURL, PushButton* );
    DECL_LINK( DialogClosedHdl, sfx2::FileDialogHelper* );

        using TabPage::DeactivatePage;

protected:
    SfxInternetPage( Window* pParent, const SfxItemSet& );
    ~SfxInternetPage();

    virtual BOOL            FillItemSet( SfxItemSet& );
    virtual void            Reset( const SfxItemSet& );
    virtual int                     DeactivatePage( SfxItemSet* pSet = 0 );

public:
    static SfxTabPage*  Create( Window* pParent, const SfxItemSet& );
};

// class SfxDocumentInfoDialog -------------------------------------------

class SFX2_DLLPUBLIC SfxDocumentInfoDialog : public SfxTabDialog
{
protected:
    virtual void    PageCreated( USHORT nId, SfxTabPage& rPage );

public:
    SfxDocumentInfoDialog(  Window* pParent, const SfxItemSet& );
};

#endif

<commit_msg>INTEGRATION: CWS custommeta (1.4.66); FILE MERGED 2008/01/28 10:15:28 mst 1.4.66.3: - sfx2/inc/sfx2/dinfdlg.hxx:   + add missing include 2008/01/25 16:12:10 mst 1.4.66.2: interface change: SfxDocumentInfoItem - sfx2/inc/sfx2/dinfdlg.hxx, sfx2/source/dialog/dinfdlg.cxx:   + use XDocumentProperties instead of SfxDocumentInfo   + also use XDocumentInfo for additional weirdness   + use UNO types in SfxDocumentInfoItem 2007/12/18 17:43:39 mst 1.4.66.1: - sfx2/inc/sfx2/dinfdlg.hxx, sfx2/source/dialog/dinfdlg.cxx:   + SfxDocumentInfoItem no longer keeps a DocumentInfo reference;     instead, it has all the individual properties as members   + new method updateDocumentInfo   + new method resetUserData   + fixed bug: editing duration not properly displayed<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dinfdlg.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2008-02-26 14:57:08 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _SFX_DINFDLG_HXX
#define _SFX_DINFDLG_HXX

#ifndef _SAL_CONFIG_H_
#include "sal/config.h"
#endif

#ifndef INCLUDED_SFX2_DLLAPI_H
#include "sfx2/dllapi.h"
#endif

#include <com/sun/star/util/DateTime.hpp>

#ifndef _SV_EDIT_HXX //autogen wg. Edit
#include <vcl/edit.hxx>
#endif
#ifndef _SV_FIELD_HXX //autogen wg. NumericField
#include <vcl/field.hxx>
#endif
#ifndef _STDCTRL_HXX //autogen wg. FixedText, FixedInfo
#include <svtools/stdctrl.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen wg. SfxStringItem
#include <svtools/stritem.hxx>
#endif
#ifndef _SVEDIT_HXX //autogen wg. MultiLineEdit
#include <svtools/svmedit.hxx>
#endif

#include "tabdlg.hxx"

namespace com { namespace sun { namespace star {
    namespace document {
        class XDocumentInfo;
        class XDocumentProperties;
    }
} } }

// class SfxDocumentInfoItem ---------------------------------------------

class SFX2_DLLPUBLIC SfxDocumentInfoItem : public SfxStringItem
{
private:
    sal_Int32                           m_AutoloadDelay;
    ::rtl::OUString                     m_AutoloadURL;
    sal_Bool                            m_isAutoloadEnabled;
    ::rtl::OUString                     m_DefaultTarget;
    ::rtl::OUString                     m_TemplateName;
    ::rtl::OUString                     m_Author;
    ::com::sun::star::util::DateTime    m_CreationDate;
    ::rtl::OUString                     m_ModifiedBy;
    ::com::sun::star::util::DateTime    m_ModificationDate;
    String                              m_PrintedBy;
    ::com::sun::star::util::DateTime    m_PrintDate;
    sal_Int16                           m_EditingCycles;
    sal_Int32                           m_EditingDuration;
    ::rtl::OUString                     m_Description;
    ::rtl::OUString                     m_Keywords;
    ::rtl::OUString                     m_Subject;
    ::rtl::OUString                     m_Title;
    ::rtl::OUString                     m_UserDefinedFieldTitles[4];
    ::rtl::OUString                     m_UserDefinedFieldValues[4];
    sal_Bool                            bHasTemplate;
    sal_Bool                            bDeleteUserData;
    sal_Bool                            bIsUseUserData;

public:
    TYPEINFO();
    SfxDocumentInfoItem();
//FIXME: remove XDocumentInfo when implementing "Custom" tab
    SfxDocumentInfoItem( const String &rFileName,
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::document::XDocumentProperties> & i_xDocProps,
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::document::XDocumentInfo> & i_xDocInfo,
        sal_Bool bUseUserData );
    SfxDocumentInfoItem( const SfxDocumentInfoItem& );
    virtual ~SfxDocumentInfoItem();

//FIXME: remove XDocumentInfo when implementing "Custom" tab
    /// update i_xDocProps with the data in this object
    void updateDocumentInfo(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::document::XDocumentProperties> & i_xDocProps,
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::document::XDocumentInfo> & i_xDocInfo) const;

    sal_Bool    isAutoloadEnabled() const { return m_isAutoloadEnabled; }
    void        setAutoloadEnabled(sal_Bool i_val) { m_isAutoloadEnabled = i_val; }
    sal_Int32   getAutoloadDelay() const { return m_AutoloadDelay; }
    void        setAutoloadDelay(sal_Int32 i_val) { m_AutoloadDelay = i_val; }
    ::rtl::OUString getAutoloadURL() const { return m_AutoloadURL; }
    void        setAutoloadURL(::rtl::OUString i_val) { m_AutoloadURL = i_val; }
    ::rtl::OUString getDefaultTarget() const { return m_DefaultTarget; }
    void        setDefaultTarget(::rtl::OUString i_val) { m_DefaultTarget = i_val; }
    ::rtl::OUString getTemplateName() const { return m_TemplateName; }
    void        setTemplateName(::rtl::OUString i_val) { m_TemplateName = i_val; }
    ::rtl::OUString getAuthor() const { return m_Author; }
    void        setAuthor(::rtl::OUString i_val) { m_Author = i_val; }

    ::com::sun::star::util::DateTime
                getCreationDate() const { return m_CreationDate; }
    void        setCreationDate(::com::sun::star::util::DateTime i_val) {
                    m_CreationDate = i_val;
                }
    ::rtl::OUString getModifiedBy() const { return m_ModifiedBy; }
    void        setModifiedBy(::rtl::OUString i_val) { m_ModifiedBy = i_val; }

    ::com::sun::star::util::DateTime
                getModificationDate() const { return m_ModificationDate; }
    void        setModificationDate(::com::sun::star::util::DateTime i_val) {
                    m_ModificationDate = i_val;
                }
    ::rtl::OUString getPrintedBy() const { return m_PrintedBy; }
    void        setPrintedBy(::rtl::OUString i_val) { m_PrintedBy = i_val; }
    ::com::sun::star::util::DateTime
                getPrintDate() const { return m_PrintDate; }
    void        setPrintDate(::com::sun::star::util::DateTime i_val) {
                    m_PrintDate = i_val;
                }
    sal_Int16   getEditingCycles() const { return m_EditingCycles; }
    void        setEditingCycles(sal_Int16 i_val) { m_EditingCycles = i_val; }
    sal_Int32   getEditingDuration() const { return m_EditingDuration; }
    void        setEditingDuration(sal_Int32 i_val) { m_EditingDuration = i_val; }
    ::rtl::OUString getDescription() const { return m_Description; }
    void        setDescription(::rtl::OUString i_val) { m_Description = i_val; }
    ::rtl::OUString getKeywords() const { return m_Keywords; }
    void        setKeywords(::rtl::OUString i_val) { m_Keywords = i_val; }
    ::rtl::OUString getSubject() const { return m_Subject; }
    void        setSubject(::rtl::OUString i_val) { m_Subject = i_val; }
    ::rtl::OUString getTitle() const { return m_Title; }
    void        setTitle(::rtl::OUString i_val) { m_Title = i_val; }
    ::rtl::OUString getUserDefinedFieldTitle(size_t i_ix) const;
    void        setUserDefinedFieldTitle(size_t i_ix, ::rtl::OUString i_val);
    ::rtl::OUString getUserDefinedFieldValue(size_t i_ix) const;
    void        setUserDefinedFieldValue(size_t i_ix, ::rtl::OUString i_val);

    /// reset user-specific data (author, modified-by, ...)
    void        resetUserData(const ::rtl::OUString & i_rAuthor);

    void                    SetTemplate( BOOL b ) { bHasTemplate = b; }
    FASTBOOL                HasTemplate() const { return bHasTemplate; }
    void                    SetDeleteUserData( BOOL bSet );
    void                    SetUseUserData( BOOL bSet );
    BOOL                    IsDeleteUserData() const;
    BOOL                    IsUseUserData() const;

    virtual SfxPoolItem*    Clone( SfxItemPool* pPool = NULL ) const;
    virtual int             operator==( const SfxPoolItem& ) const;
    virtual sal_Bool        QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;
    virtual sal_Bool        PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );
};

// class SfxDocumentPage -------------------------------------------------

class SfxDocumentPage : public SfxTabPage
{
private:
    FixedImage                  aBmp1;
    Edit                        aNameED;

    FixedLine                   aLine1FL;
    FixedText                   aTypeFT;
    svt::SelectableFixedText    aShowTypeFT;
    CheckBox                    aReadOnlyCB;
    FixedText                   aFileFt;
    svt::SelectableFixedText    aFileValFt;
    FixedText                   aSizeFT;
    svt::SelectableFixedText    aShowSizeFT;

    FixedLine                   aLine2FL;
    FixedText                   aCreateFt;
    svt::SelectableFixedText    aCreateValFt;
    FixedText                   aChangeFt;
    svt::SelectableFixedText    aChangeValFt;
    FixedText                   aSignedFt;
    svt::SelectableFixedText    aSignedValFt;
    PushButton                  aSignatureBtn;
    FixedText                   aPrintFt;
    svt::SelectableFixedText    aPrintValFt;
    FixedText                   aTimeLogFt;
    svt::SelectableFixedText    aTimeLogValFt;
    FixedText                   aDocNoFt;
    svt::SelectableFixedText    aDocNoValFt;
    CheckBox                    aUseUserDataCB;
    PushButton                  aDeleteBtn;

    FixedLine                   aLine3FL;
    FixedText                   aTemplFt;
    svt::SelectableFixedText    aTemplValFt;

    String                      aUnknownSize;
    String                      aMultiSignedStr;

    BOOL                        bEnableUseUserData  : 1,
                                bHandleDelete       : 1;

    DECL_LINK(          DeleteHdl, PushButton * );
    DECL_LINK(          SignatureHdl, PushButton * );
    void                ImplUpdateSignatures();

protected:
    SfxDocumentPage( Window* pParent, const SfxItemSet& );

    virtual BOOL        FillItemSet( SfxItemSet& );
    virtual void        Reset( const SfxItemSet& );

public:
    static SfxTabPage*  Create( Window* pParent, const SfxItemSet& );

    void                EnableUseUserData();
};

// class SfxDocumentDescPage ---------------------------------------------

class SfxDocumentDescPage : public SfxTabPage
{
private:
    FixedText               aTitleFt;
    Edit                    aTitleEd;
    FixedText               aThemaFt;
    Edit                    aThemaEd;
    FixedText               aKeywordsFt;
    Edit                    aKeywordsEd;
    FixedText               aCommentFt;
    MultiLineEdit           aCommentEd;
    SfxDocumentInfoItem*    pInfoItem;

protected:
    SfxDocumentDescPage( Window* pParent, const SfxItemSet& );

    virtual BOOL            FillItemSet( SfxItemSet& );
    virtual void            Reset( const SfxItemSet& );

public:
    static SfxTabPage*      Create( Window* pParent, const SfxItemSet& );
};

// class SfxDocumentUserPage ---------------------------------------------

class SfxDocumentUserPage : public SfxTabPage
{
private:
    BOOL                    bLabelModified;

    FixedText               aInfo1Ft;
    Edit                    aInfo1Ed;
    FixedText               aInfo2Ft;
    Edit                    aInfo2Ed;
    FixedText               aInfo3Ft;
    Edit                    aInfo3Ed;
    FixedText               aInfo4Ft;
    Edit                    aInfo4Ed;
    PushButton              aEditLabelBtn;
    SfxDocumentInfoItem*    pInfoItem;

#if _SOLAR__PRIVATE
    DECL_LINK( EditLabelHdl, PushButton * );

    String              GetLabelText_Impl( FixedText* pLabel );
    void                SetLabelText_Impl( FixedText* pLabel, const String& rNewLabel );
#endif

protected:
    SfxDocumentUserPage( Window* pParent, const SfxItemSet& );

    virtual BOOL        FillItemSet( SfxItemSet& );
    virtual void        Reset( const SfxItemSet& );

public:
    static SfxTabPage*  Create( Window* pParent, const SfxItemSet& );
};

// class SfxInternetPage -------------------------------------------------

class TargetList;
namespace sfx2
{
    class FileDialogHelper;
}

class SfxInternetPage : public SfxTabPage
{
private:
    RadioButton             aRBNoAutoUpdate;
    RadioButton             aRBReloadUpdate;
    RadioButton             aRBForwardUpdate;

    FixedText               aFTEvery;
    NumericField            aNFReload;
    FixedText               aFTReloadSeconds;

    FixedText               aFTAfter;
    NumericField            aNFAfter;
    FixedText               aFTAfterSeconds;
    FixedText               aFTURL;
    Edit                    aEDForwardURL;
    PushButton              aPBBrowseURL;
    FixedText               aFTFrame;
    ComboBox                aCBFrame;

    String                  aForwardErrorMessg;
    String                  aBaseURL;
    SfxDocumentInfoItem*    pInfoItem;
    sfx2::FileDialogHelper* pFileDlg;

    enum STATE              { S_Init, S_NoUpdate, S_Reload, S_Forward };
                            // S_Init is only valid as initial value
    STATE                   eState;

    void                    ChangeState( STATE eNewState );     // S_Init is not a valid value here
                                                                // also checks corresponding radiobutton
    void                    EnableNoUpdate( BOOL bEnable );
    void                    EnableReload( BOOL bEnable );
    void                    EnableForward( BOOL bEnable );

    DECL_LINK( ClickHdlNoUpdate, Control* );
    DECL_LINK( ClickHdlReload, Control* );
    DECL_LINK( ClickHdlForward, Control* );
    DECL_LINK( ClickHdlBrowseURL, PushButton* );
    DECL_LINK( DialogClosedHdl, sfx2::FileDialogHelper* );

        using TabPage::DeactivatePage;

protected:
    SfxInternetPage( Window* pParent, const SfxItemSet& );
    ~SfxInternetPage();

    virtual BOOL            FillItemSet( SfxItemSet& );
    virtual void            Reset( const SfxItemSet& );
    virtual int                     DeactivatePage( SfxItemSet* pSet = 0 );

public:
    static SfxTabPage*  Create( Window* pParent, const SfxItemSet& );
};

// class SfxDocumentInfoDialog -------------------------------------------

class SFX2_DLLPUBLIC SfxDocumentInfoDialog : public SfxTabDialog
{
protected:
    virtual void    PageCreated( USHORT nId, SfxTabPage& rPage );

public:
    SfxDocumentInfoDialog(  Window* pParent, const SfxItemSet& );
};

#endif

<|endoftext|>


<commit_before>/**
Copyright 2014-2015 Jason R. Wendlandt

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 "Graphics/RenderData.h"
#include "Math/Vector3.h"

namespace alpha
{
    RenderData::RenderData(std::string psEntryPoint /*= "PS"*/)
        : m_psEntryPoint(psEntryPoint)
    {

    }

    RenderData::~RenderData()
    {

    }

    void SetPosition(const Vector3 & /*pos*/)
    {

    }

    void SetScale(const Vector3 & /*scale*/)
    {

    }
}
<commit_msg>Fixed last undefined reference in linux build.<commit_after>/**
Copyright 2014-2015 Jason R. Wendlandt

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 "Graphics/RenderData.h"
#include "Math/Vector3.h"

namespace alpha
{
    RenderData::RenderData(std::string psEntryPoint /*= "PS"*/)
        : m_psEntryPoint(psEntryPoint)
    {

    }

    RenderData::~RenderData()
    {

    }

    void RenderData::SetPosition(const Vector3 & /*pos*/)
    {

    }

    void RenderData::SetScale(const Vector3 & /*scale*/)
    {

    }
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2017 ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <boost/test/unit_test.hpp>
#include <seastar/core/thread.hh>
#include <seastar/core/semaphore.hh>
#include "utils/serialized_action.hh"
#include <seastar/testing/test_case.hh>
#include "utils/phased_barrier.hh"

SEASTAR_TEST_CASE(test_serialized_action_triggering) {
    return seastar::async([] {
        int current = 0;
        std::vector<int> history;
        promise<> p;
        seastar::semaphore sem{0};

        serialized_action act([&] {
            sem.signal(1);
            auto val = current;
            return p.get_future().then([&, val] {
                history.push_back(val);
            });
        });

        auto release = [&] {
            std::exchange(p, promise<>()).set_value();
        };

        auto t1 = act.trigger();
        sem.wait().get(); // wait for t1 action to block
        current = 1;
        auto t2 = act.trigger();
        auto t3 = act.trigger();

        current = 2;
        release();

        t1.get();
        BOOST_REQUIRE(history.size() == 1);
        BOOST_REQUIRE(history.back() == 0);
        BOOST_REQUIRE(!t2.available());
        BOOST_REQUIRE(!t3.available());

        sem.wait().get(); // wait for t2 action to block
        current = 3;
        auto t4 = act.trigger();
        release();

        t2.get();
        t3.get();
        BOOST_REQUIRE(history.size() == 2);
        BOOST_REQUIRE(history.back() == 2);
        BOOST_REQUIRE(!t4.available());

        sem.wait().get(); // wait for t4 action to block
        current = 4;
        release();

        t4.get();
        BOOST_REQUIRE(history.size() == 3);
        BOOST_REQUIRE(history.back() == 3);

        current = 5;
        auto t5 = act.trigger();
        sem.wait().get(); // wait for t5 action to block
        release();
        t5.get();

        BOOST_REQUIRE(history.size() == 4);
        BOOST_REQUIRE(history.back() == 5);
    });
}
<commit_msg>test: serialized_action_test: add test_serialized_action_exception<commit_after>/*
 * Copyright (C) 2017 ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <boost/test/unit_test.hpp>
#include <seastar/core/thread.hh>
#include <seastar/core/semaphore.hh>
#include "utils/serialized_action.hh"
#include <seastar/testing/test_case.hh>
#include <seastar/testing/thread_test_case.hh>
#include "utils/phased_barrier.hh"

SEASTAR_TEST_CASE(test_serialized_action_triggering) {
    return seastar::async([] {
        int current = 0;
        std::vector<int> history;
        promise<> p;
        seastar::semaphore sem{0};

        serialized_action act([&] {
            sem.signal(1);
            auto val = current;
            return p.get_future().then([&, val] {
                history.push_back(val);
            });
        });

        auto release = [&] {
            std::exchange(p, promise<>()).set_value();
        };

        auto t1 = act.trigger();
        sem.wait().get(); // wait for t1 action to block
        current = 1;
        auto t2 = act.trigger();
        auto t3 = act.trigger();

        current = 2;
        release();

        t1.get();
        BOOST_REQUIRE(history.size() == 1);
        BOOST_REQUIRE(history.back() == 0);
        BOOST_REQUIRE(!t2.available());
        BOOST_REQUIRE(!t3.available());

        sem.wait().get(); // wait for t2 action to block
        current = 3;
        auto t4 = act.trigger();
        release();

        t2.get();
        t3.get();
        BOOST_REQUIRE(history.size() == 2);
        BOOST_REQUIRE(history.back() == 2);
        BOOST_REQUIRE(!t4.available());

        sem.wait().get(); // wait for t4 action to block
        current = 4;
        release();

        t4.get();
        BOOST_REQUIRE(history.size() == 3);
        BOOST_REQUIRE(history.back() == 3);

        current = 5;
        auto t5 = act.trigger();
        sem.wait().get(); // wait for t5 action to block
        release();
        t5.get();

        BOOST_REQUIRE(history.size() == 4);
        BOOST_REQUIRE(history.back() == 5);
    });
}

SEASTAR_THREAD_TEST_CASE(test_serialized_action_exception) {
    class expected_exception : public std::exception {
    public:
        virtual const char* what() const noexcept override {
            return "expected_exception";
        }
    };

    serialized_action simple_action([&] {
        return make_exception_future<>(expected_exception());
    });

    // test that the exception returned by the serialized action
    // is propageted to the caller of trigger().
    BOOST_REQUIRE_THROW(simple_action.trigger(false).get(), expected_exception);
    BOOST_REQUIRE_THROW(simple_action.trigger(true).get(), expected_exception);

    int count = 0;
    promise<> p;
    seastar::semaphore sem{0};

    serialized_action triggered_action([&] {
        sem.signal(1);
        return p.get_future().then([&] {
            count++;
            return make_exception_future<>(expected_exception());
        });
    });

    auto release = [&] {
        std::exchange(p, promise<>()).set_value();
    };

    // test that the exception returned by the serialized action
    // is propageted to pending callers of trigger().
    auto t1 = triggered_action.trigger();   // launch the action in the background.
    sem.wait().get();                       // wait for t1 to block on `p`.
    auto t2 = triggered_action.trigger();   // trigger the action again.
    auto t3 = triggered_action.trigger();   // trigger the action again. t3 and t2 should share the same future.

    release();                              // signal t1 to proceed (and return the exception).
    BOOST_REQUIRE_THROW(t1.get(), expected_exception);
    BOOST_REQUIRE_EQUAL(count, 1);

    sem.wait().get();                       // wait for t2 to block on `p`.
    release();                              // signal t2 to proceed (and return the exception).
    BOOST_REQUIRE_THROW(t2.get(), expected_exception);
    BOOST_REQUIRE_THROW(t3.get(), expected_exception);
    BOOST_REQUIRE_EQUAL(count, 2);          // verify that `triggered_action` was called only once for t2 and t3.
}
<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// type_integrity_test.cpp
//
// Identification: ../peloton-1/test/codegen/type_integrity_test.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "codegen/testing_codegen_util.h"
#include "codegen/type/type.h"
#include "codegen/type/boolean_type.h"
#include "codegen/type/tinyint_type.h"
#include "codegen/type/smallint_type.h"
#include "codegen/type/integer_type.h"
#include "codegen/type/bigint_type.h"
#include "codegen/type/decimal_type.h"
#include "codegen/type/timestamp_type.h"
#include "codegen/type/date_type.h"

namespace peloton {
namespace test {

class TypeIntegrityTest : public PelotonCodeGenTest {};

TEST_F(TypeIntegrityTest, ImplicitCastTest) {
  // Tinyint's can be implicitly casted to any higher-bit integer type
  codegen::type::Type input_type = codegen::type::TinyInt::Instance();
  EXPECT_TRUE(codegen::type::TypeSystem::CanImplicitlyCastTo(
      input_type, codegen::type::TinyInt::Instance()));
  EXPECT_TRUE(codegen::type::TypeSystem::CanImplicitlyCastTo(
      input_type, codegen::type::SmallInt::Instance()));
  EXPECT_TRUE(codegen::type::TypeSystem::CanImplicitlyCastTo(
      input_type, codegen::type::Integer::Instance()));
  EXPECT_TRUE(codegen::type::TypeSystem::CanImplicitlyCastTo(
      input_type, codegen::type::BigInt::Instance()));
  EXPECT_TRUE(codegen::type::TypeSystem::CanImplicitlyCastTo(
      input_type, codegen::type::Decimal::Instance()));

  // Small's can be implicitly casted to any higher-bit integer type
  input_type = codegen::type::SmallInt::Instance();
  EXPECT_TRUE(codegen::type::TypeSystem::CanImplicitlyCastTo(
      input_type, codegen::type::SmallInt::Instance()));
  EXPECT_TRUE(codegen::type::TypeSystem::CanImplicitlyCastTo(
      input_type, codegen::type::Integer::Instance()));
  EXPECT_TRUE(codegen::type::TypeSystem::CanImplicitlyCastTo(
      input_type, codegen::type::BigInt::Instance()));
  EXPECT_TRUE(codegen::type::TypeSystem::CanImplicitlyCastTo(
      input_type, codegen::type::Decimal::Instance()));

  // Integer's can be implicitly casted to any higher-bit integer type
  input_type = codegen::type::Integer::Instance();
  EXPECT_TRUE(codegen::type::TypeSystem::CanImplicitlyCastTo(
      input_type, codegen::type::Integer::Instance()));
  EXPECT_TRUE(codegen::type::TypeSystem::CanImplicitlyCastTo(
      input_type, codegen::type::BigInt::Instance()));
  EXPECT_TRUE(codegen::type::TypeSystem::CanImplicitlyCastTo(
      input_type, codegen::type::Decimal::Instance()));

  // Integer's can be implicitly casted to any higher-bit integer type
  input_type = codegen::type::BigInt::Instance();
  EXPECT_TRUE(codegen::type::TypeSystem::CanImplicitlyCastTo(
      input_type, codegen::type::BigInt::Instance()));
  EXPECT_TRUE(codegen::type::TypeSystem::CanImplicitlyCastTo(
      input_type, codegen::type::Decimal::Instance()));

  // Decimal's can only be casted to itself
  input_type = codegen::type::Decimal::Instance();
  EXPECT_TRUE(codegen::type::TypeSystem::CanImplicitlyCastTo(
      input_type, codegen::type::Decimal::Instance()));
}

// This test performs checks that comparisons between every possible pair of
// (the most important) input types are possible through potentially implicitly
// casting the inputs.
TEST_F(TypeIntegrityTest, ComparisonWithImplicitCastTest) {
  const std::vector<codegen::type::Type> types_to_test = {
      codegen::type::Boolean::Instance(),
      codegen::type::TinyInt::Instance(),
      codegen::type::SmallInt::Instance(),
      codegen::type::Integer::Instance(),
      codegen::type::BigInt::Instance(),
      codegen::type::Decimal::Instance(),
      codegen::type::Date::Instance(),
      codegen::type::Timestamp::Instance()};

  for (const auto &left_type : types_to_test) {
    for (const auto &right_type : types_to_test) {
      const auto &type_system = left_type.GetTypeSystem();

      codegen::type::Type type_to_cast_left = left_type;
      codegen::type::Type type_to_cast_right = right_type;

      const codegen::type::TypeSystem::Comparison *result;
      if (codegen::type::TypeSystem::CanImplicitlyCastTo(left_type,
                                                         right_type) ||
          codegen::type::TypeSystem::CanImplicitlyCastTo(right_type,
                                                         left_type)) {
        // If the types are implicitly cast-able to one or the other, the
        // comparison shouldn't fail
        EXPECT_NO_THROW({
          result = type_system.GetComparison(left_type, type_to_cast_left,
                                             right_type, type_to_cast_right);
        });
        EXPECT_NE(nullptr, result);
      } else {
        // The types are **NOT** implicitly cast-able, this should fail
        EXPECT_THROW({
          result = type_system.GetComparison(left_type, type_to_cast_left,
                                             right_type, type_to_cast_right);
        }, Exception);
      }
    }
  }
}

// TODO: This test only does math ops. We need a generic way to test binary ops.
TEST_F(TypeIntegrityTest, MathOpWithImplicitCastTest) {
  const auto binary_ops = {OperatorId::Add, OperatorId::Sub, OperatorId::Mul,
                           OperatorId::Div, OperatorId::Mod};

  const std::vector<codegen::type::Type> types_to_test = {
      codegen::type::Boolean::Instance(),
      codegen::type::TinyInt::Instance(),
      codegen::type::SmallInt::Instance(),
      codegen::type::Integer::Instance(),
      codegen::type::BigInt::Instance(),
      codegen::type::Decimal::Instance(),
      codegen::type::Date::Instance(),
      codegen::type::Timestamp::Instance()};

  const auto IsNumber = [](const codegen::type::Type &type) {
    switch (type.type_id) {
      case peloton::type::TypeId::TINYINT:
      case peloton::type::TypeId::SMALLINT:
      case peloton::type::TypeId::INTEGER:
      case peloton::type::TypeId::BIGINT:
      case peloton::type::TypeId::DECIMAL:
        return true;
      default:
        return false;
    }
  };

  for (auto left_type : types_to_test) {
    for (auto right_type : types_to_test) {
      for (auto bin_op : binary_ops) {
        const auto &type_system = left_type.GetTypeSystem();

        codegen::type::Type type_to_cast_left = left_type;
        codegen::type::Type type_to_cast_right = right_type;
        const codegen::type::TypeSystem::BinaryOperator *result;
        if (IsNumber(left_type) && IsNumber(right_type)) {
          // If the types are implicitly cast-able to one or the other, the
          // comparison shouldn't fail
          EXPECT_NO_THROW({
            result = type_system.GetBinaryOperator(
                bin_op, left_type, type_to_cast_left, right_type,
                type_to_cast_right);
          });
          EXPECT_NE(nullptr, result);
        } else {
          // The types are **NOT** implicitly cast-able, this should fail
          EXPECT_THROW({
            result = type_system.GetBinaryOperator(
                bin_op, left_type, type_to_cast_left, right_type,
                type_to_cast_right);
          }, Exception);
        }
      }
    }
  }
}

}  // namespace test
}  // namespace peloton
<commit_msg>More type tests<commit_after>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// type_integrity_test.cpp
//
// Identification: ../peloton-1/test/codegen/type_integrity_test.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "codegen/testing_codegen_util.h"

#include <vector>

#include "codegen/type/array_type.h"
#include "codegen/type/type.h"
#include "codegen/type/bigint_type.h"
#include "codegen/type/boolean_type.h"
#include "codegen/type/date_type.h"
#include "codegen/type/decimal_type.h"
#include "codegen/type/integer_type.h"
#include "codegen/type/smallint_type.h"
#include "codegen/type/timestamp_type.h"
#include "codegen/type/tinyint_type.h"
#include "codegen/type/varbinary_type.h"
#include "codegen/type/varchar_type.h"

namespace peloton {
namespace test {

class TypeIntegrityTest : public PelotonCodeGenTest {};

TEST_F(TypeIntegrityTest, ImplicitCastTest) {
  struct ImplicitCastTestCase {
    codegen::type::Type source_type;
    std::vector<codegen::type::Type> target_types;

    ImplicitCastTestCase(const codegen::type::Type &_source_type,
                         const std::vector<codegen::type::Type> &_target_types)
        : source_type(_source_type), target_types(_target_types) {}

    bool CanCastTo(const codegen::type::Type &t) const {
      return std::find(target_types.begin(), target_types.end(), t) !=
             target_types.end();
    }
  };

  // This list contains a list of the the above structs that essentially tracks
  // which SQL types can be implicitly casted to which other SQL types
  std::vector<ImplicitCastTestCase> implicit_casting_table = {
      // Boolean can only be casted to itself
      {codegen::type::Boolean::Instance(),
       {codegen::type::Boolean::Instance()}},

      //////////////////////////////////////////////////////////////////////////
      // All other integral types can only be casted to WIDER integral types
      //////////////////////////////////////////////////////////////////////////

      {codegen::type::TinyInt::Instance(),
       {codegen::type::TinyInt::Instance(), codegen::type::SmallInt::Instance(),
        codegen::type::Integer::Instance(), codegen::type::BigInt::Instance(),
        codegen::type::Decimal::Instance()}},

      {codegen::type::SmallInt::Instance(),
       {codegen::type::SmallInt::Instance(), codegen::type::Integer::Instance(),
        codegen::type::BigInt::Instance(), codegen::type::Decimal::Instance()}},

      {codegen::type::Integer::Instance(),
       {codegen::type::Integer::Instance(), codegen::type::BigInt::Instance(),
        codegen::type::Decimal::Instance()}},

      {codegen::type::BigInt::Instance(),
       {codegen::type::BigInt::Instance(), codegen::type::Decimal::Instance()}},

      {codegen::type::Decimal::Instance(),
       {codegen::type::Decimal::Instance()}},
  };

  const std::vector<codegen::type::Type> types_to_test = {
      codegen::type::Boolean::Instance(),  codegen::type::TinyInt::Instance(),
      codegen::type::SmallInt::Instance(), codegen::type::Integer::Instance(),
      codegen::type::BigInt::Instance(),   codegen::type::Decimal::Instance(),
      codegen::type::Date::Instance(),     codegen::type::Timestamp::Instance(),
      codegen::type::Varchar::Instance(),  codegen::type::Varbinary::Instance(),
      codegen::type::Array::Instance()};

  // Check that all the proper types can be casted when allowed
  for (const auto &test_case : implicit_casting_table) {
    const auto &src_type = test_case.source_type;
    for (const auto &target_type : types_to_test) {
      if (test_case.CanCastTo(target_type)) {
        EXPECT_TRUE(codegen::type::TypeSystem::CanImplicitlyCastTo(
            src_type, target_type));
      } else {
        EXPECT_FALSE(codegen::type::TypeSystem::CanImplicitlyCastTo(
            src_type, target_type));
      }
    }
  }
}

// This test performs checks that comparisons between every possible pair of
// (the most important) input types are possible through potentially implicitly
// casting the inputs.
TEST_F(TypeIntegrityTest, ComparisonWithImplicitCastTest) {
  const std::vector<codegen::type::Type> types_to_test = {
      codegen::type::Boolean::Instance(),
      codegen::type::TinyInt::Instance(),
      codegen::type::SmallInt::Instance(),
      codegen::type::Integer::Instance(),
      codegen::type::BigInt::Instance(),
      codegen::type::Decimal::Instance(),
      codegen::type::Date::Instance(),
      codegen::type::Timestamp::Instance()};

  for (const auto &left_type : types_to_test) {
    for (const auto &right_type : types_to_test) {
      const auto &type_system = left_type.GetTypeSystem();

      codegen::type::Type type_to_cast_left = left_type;
      codegen::type::Type type_to_cast_right = right_type;

      const codegen::type::TypeSystem::Comparison *result;
      if (codegen::type::TypeSystem::CanImplicitlyCastTo(left_type,
                                                         right_type) ||
          codegen::type::TypeSystem::CanImplicitlyCastTo(right_type,
                                                         left_type)) {
        // If the types are implicitly cast-able to one or the other, the
        // comparison shouldn't fail
        EXPECT_NO_THROW({
          result = type_system.GetComparison(left_type, type_to_cast_left,
                                             right_type, type_to_cast_right);
        });
        EXPECT_NE(nullptr, result);
      } else {
        // The types are **NOT** implicitly cast-able, this should fail
        EXPECT_THROW({
          result = type_system.GetComparison(left_type, type_to_cast_left,
                                             right_type, type_to_cast_right);
        }, Exception);
      }
    }
  }
}

// TODO: This test only does math ops. We need a generic way to test binary ops.
TEST_F(TypeIntegrityTest, MathOpWithImplicitCastTest) {
  const auto binary_ops = {OperatorId::Add, OperatorId::Sub, OperatorId::Mul,
                           OperatorId::Div, OperatorId::Mod};

  const std::vector<codegen::type::Type> types_to_test = {
      codegen::type::Boolean::Instance(),
      codegen::type::TinyInt::Instance(),
      codegen::type::SmallInt::Instance(),
      codegen::type::Integer::Instance(),
      codegen::type::BigInt::Instance(),
      codegen::type::Decimal::Instance(),
      codegen::type::Date::Instance(),
      codegen::type::Timestamp::Instance()};

  const auto IsNumber = [](const codegen::type::Type &type) {
    switch (type.type_id) {
      case peloton::type::TypeId::TINYINT:
      case peloton::type::TypeId::SMALLINT:
      case peloton::type::TypeId::INTEGER:
      case peloton::type::TypeId::BIGINT:
      case peloton::type::TypeId::DECIMAL:
        return true;
      default:
        return false;
    }
  };

  for (auto left_type : types_to_test) {
    for (auto right_type : types_to_test) {
      for (auto bin_op : binary_ops) {
        const auto &type_system = left_type.GetTypeSystem();

        codegen::type::Type type_to_cast_left = left_type;
        codegen::type::Type type_to_cast_right = right_type;
        const codegen::type::TypeSystem::BinaryOperator *result;
        if (IsNumber(left_type) && IsNumber(right_type)) {
          // If the types are implicitly cast-able to one or the other, the
          // comparison shouldn't fail
          EXPECT_NO_THROW({
            result = type_system.GetBinaryOperator(
                bin_op, left_type, type_to_cast_left, right_type,
                type_to_cast_right);
          });
          EXPECT_NE(nullptr, result);
        } else {
          // The types are **NOT** implicitly cast-able, this should fail
          EXPECT_THROW({
            result = type_system.GetBinaryOperator(
                bin_op, left_type, type_to_cast_left, right_type,
                type_to_cast_right);
          }, Exception);
        }
      }
    }
  }
}

}  // namespace test
}  // namespace peloton
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2017-present ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include "schema_fwd.hh"
#include "query-request.hh"
#include "mutation_fragment.hh"
#include "partition_version.hh"
#include "tracing/tracing.hh"
#include "row_cache.hh"

namespace cache {

/*
* Represent a flat reader to the underlying source.
* This reader automatically makes sure that it's up to date with all cache updates
*/
class autoupdating_underlying_reader final {
    row_cache& _cache;
    read_context& _read_context;
    flat_mutation_reader_opt _reader;
    utils::phased_barrier::phase_type _reader_creation_phase = 0;
    dht::partition_range _range = { };
    std::optional<dht::decorated_key> _last_key;
    std::optional<dht::decorated_key> _new_last_key;

    future<> close_reader() noexcept {
        return _reader ? _reader->close() : make_ready_future<>();
    }
public:
    autoupdating_underlying_reader(row_cache& cache, read_context& context)
        : _cache(cache)
        , _read_context(context)
    { }
    future<mutation_fragment_opt> move_to_next_partition(db::timeout_clock::time_point timeout) {
        _last_key = std::move(_new_last_key);
        auto start = population_range_start();
        auto phase = _cache.phase_of(start);
        auto refresh_reader = make_ready_future<>();
        if (!_reader || _reader_creation_phase != phase) {
            if (_last_key) {
                auto cmp = dht::ring_position_comparator(*_cache._schema);
                auto&& new_range = _range.split_after(*_last_key, cmp);
                if (!new_range) {
                  return close_reader().then([] {
                    return make_ready_future<mutation_fragment_opt>();
                  });
                }
                _range = std::move(*new_range);
                _last_key = {};
            }
            if (_reader) {
                ++_cache._tracker._stats.underlying_recreations;
            }
            auto old_reader = std::move(*_reader);
          refresh_reader = futurize_invoke([this, phase] () {
            _reader = _cache.create_underlying_reader(_read_context, _cache.snapshot_for_phase(phase), _range);
            _reader_creation_phase = phase;
          }).finally([rd = std::move(old_reader)] () mutable {
            return rd.close();
          });
        }
     return refresh_reader.then([this, timeout] {
      return _reader->next_partition().then([this, timeout] {
        if (_reader->is_end_of_stream() && _reader->is_buffer_empty()) {
            return make_ready_future<mutation_fragment_opt>();
        }
        return (*_reader)(timeout).then([this] (auto&& mfopt) {
            if (mfopt) {
                assert(mfopt->is_partition_start());
                _new_last_key = mfopt->as_partition_start().key();
            }
            return std::move(mfopt);
        });
      });
     });
    }
    future<> fast_forward_to(dht::partition_range&& range, db::timeout_clock::time_point timeout) {
        auto snapshot_and_phase = _cache.snapshot_of(dht::ring_position_view::for_range_start(_range));
        return fast_forward_to(std::move(range), snapshot_and_phase.snapshot, snapshot_and_phase.phase, timeout);
    }
    future<> fast_forward_to(dht::partition_range&& range, mutation_source& snapshot, row_cache::phase_type phase, db::timeout_clock::time_point timeout) {
        _range = std::move(range);
        _last_key = { };
        _new_last_key = { };
        if (_reader) {
            if (_reader_creation_phase == phase) {
                ++_cache._tracker._stats.underlying_partition_skips;
                return _reader->fast_forward_to(_range, timeout);
            } else {
                ++_cache._tracker._stats.underlying_recreations;
            }
        }
        return close_reader().then([this, snapshot, phase] () mutable {
        // FIXME: indentation
        _reader = _cache.create_underlying_reader(_read_context, snapshot, _range);
        _reader_creation_phase = phase;
        });
    }
    future<> close() noexcept {
        return close_reader();
    }
    utils::phased_barrier::phase_type creation_phase() const {
        return _reader_creation_phase;
    }
    const dht::partition_range& range() const {
        return _range;
    }
    flat_mutation_reader& underlying() { return *_reader; }
    dht::ring_position_view population_range_start() const {
        return _last_key ? dht::ring_position_view::for_after_key(*_last_key)
                         : dht::ring_position_view::for_range_start(_range);
    }
};

class read_context final : public enable_lw_shared_from_this<read_context> {
    row_cache& _cache;
    schema_ptr _schema;
    reader_permit _permit;
    const dht::partition_range& _range;
    const query::partition_slice& _slice;
    const io_priority_class& _pc;
    tracing::trace_state_ptr _trace_state;
    mutation_reader::forwarding _fwd_mr;
    bool _range_query;
    // When reader enters a partition, it must be set up for reading that
    // partition from the underlying mutation source (_underlying) in one of two ways:
    //
    //  1) either _underlying is already in that partition
    //
    //  2) _underlying is before the partition, then _underlying_snapshot and _key
    //     are set so that _underlying_flat can be fast forwarded to the right partition.
    //
    autoupdating_underlying_reader _underlying;
    uint64_t _underlying_created = 0;

    mutation_source_opt _underlying_snapshot;
    dht::partition_range _sm_range;
    std::optional<dht::decorated_key> _key;
    bool _partition_exists;
    row_cache::phase_type _phase;
public:
    read_context(row_cache& cache,
            schema_ptr schema,
            reader_permit permit,
            const dht::partition_range& range,
            const query::partition_slice& slice,
            const io_priority_class& pc,
            tracing::trace_state_ptr trace_state,
            mutation_reader::forwarding fwd_mr)
        : _cache(cache)
        , _schema(std::move(schema))
        , _permit(std::move(permit))
        , _range(range)
        , _slice(slice)
        , _pc(pc)
        , _trace_state(std::move(trace_state))
        , _fwd_mr(fwd_mr)
        , _range_query(!query::is_single_partition(range))
        , _underlying(_cache, *this)
    {
        ++_cache._tracker._stats.reads;
        if (!_range_query) {
            _key = range.start()->value().as_decorated_key();
        }
    }
    ~read_context() {
        ++_cache._tracker._stats.reads_done;
        if (_underlying_created) {
            _cache._stats.reads_with_misses.mark();
            ++_cache._tracker._stats.reads_with_misses;
        } else {
            _cache._stats.reads_with_no_misses.mark();
        }
    }
    read_context(const read_context&) = delete;
    row_cache& cache() { return _cache; }
    const schema_ptr& schema() const { return _schema; }
    reader_permit permit() const { return _permit; }
    const dht::partition_range& range() const { return _range; }
    const query::partition_slice& slice() const { return _slice; }
    const io_priority_class& pc() const { return _pc; }
    tracing::trace_state_ptr trace_state() const { return _trace_state; }
    mutation_reader::forwarding fwd_mr() const { return _fwd_mr; }
    bool is_range_query() const { return _range_query; }
    autoupdating_underlying_reader& underlying() { return _underlying; }
    row_cache::phase_type phase() const { return _phase; }
    const dht::decorated_key& key() const { return *_key; }
    bool partition_exists() const { return _partition_exists; }
    void on_underlying_created() { ++_underlying_created; }
    bool digest_requested() const { return _slice.options.contains<query::partition_slice::option::with_digest>(); }
public:
    future<> ensure_underlying(db::timeout_clock::time_point timeout) {
        if (_underlying_snapshot) {
            return create_underlying(timeout).then([this, timeout] {
                return _underlying.underlying()(timeout).then([this] (mutation_fragment_opt&& mfopt) {
                    _partition_exists = bool(mfopt);
                });
            });
        }
        // We know that partition exists because all the callers of
        // enter_partition(const dht::decorated_key&, row_cache::phase_type)
        // check that and there's no other way of setting _underlying_snapshot
        // to empty. Except for calling create_underlying.
        _partition_exists = true;
        return make_ready_future<>();
    }
public:
    future<> create_underlying(db::timeout_clock::time_point timeout);
    void enter_partition(const dht::decorated_key& dk, mutation_source& snapshot, row_cache::phase_type phase) {
        _phase = phase;
        _underlying_snapshot = snapshot;
        _key = dk;
    }
    // Precondition: each caller needs to make sure that partition with |dk| key
    //               exists in underlying before calling this function.
    void enter_partition(const dht::decorated_key& dk, row_cache::phase_type phase) {
        _phase = phase;
        _underlying_snapshot = {};
        _key = dk;
    }
    future<> close() noexcept {
        return _underlying.close();
    }
};

}
<commit_msg>row_cache: autoupdating_underlying_reader: fast_forward_to: fixup indentation<commit_after>/*
 * Copyright (C) 2017-present ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include "schema_fwd.hh"
#include "query-request.hh"
#include "mutation_fragment.hh"
#include "partition_version.hh"
#include "tracing/tracing.hh"
#include "row_cache.hh"

namespace cache {

/*
* Represent a flat reader to the underlying source.
* This reader automatically makes sure that it's up to date with all cache updates
*/
class autoupdating_underlying_reader final {
    row_cache& _cache;
    read_context& _read_context;
    flat_mutation_reader_opt _reader;
    utils::phased_barrier::phase_type _reader_creation_phase = 0;
    dht::partition_range _range = { };
    std::optional<dht::decorated_key> _last_key;
    std::optional<dht::decorated_key> _new_last_key;

    future<> close_reader() noexcept {
        return _reader ? _reader->close() : make_ready_future<>();
    }
public:
    autoupdating_underlying_reader(row_cache& cache, read_context& context)
        : _cache(cache)
        , _read_context(context)
    { }
    future<mutation_fragment_opt> move_to_next_partition(db::timeout_clock::time_point timeout) {
        _last_key = std::move(_new_last_key);
        auto start = population_range_start();
        auto phase = _cache.phase_of(start);
        auto refresh_reader = make_ready_future<>();
        if (!_reader || _reader_creation_phase != phase) {
            if (_last_key) {
                auto cmp = dht::ring_position_comparator(*_cache._schema);
                auto&& new_range = _range.split_after(*_last_key, cmp);
                if (!new_range) {
                  return close_reader().then([] {
                    return make_ready_future<mutation_fragment_opt>();
                  });
                }
                _range = std::move(*new_range);
                _last_key = {};
            }
            if (_reader) {
                ++_cache._tracker._stats.underlying_recreations;
            }
            auto old_reader = std::move(*_reader);
          refresh_reader = futurize_invoke([this, phase] () {
            _reader = _cache.create_underlying_reader(_read_context, _cache.snapshot_for_phase(phase), _range);
            _reader_creation_phase = phase;
          }).finally([rd = std::move(old_reader)] () mutable {
            return rd.close();
          });
        }
     return refresh_reader.then([this, timeout] {
      return _reader->next_partition().then([this, timeout] {
        if (_reader->is_end_of_stream() && _reader->is_buffer_empty()) {
            return make_ready_future<mutation_fragment_opt>();
        }
        return (*_reader)(timeout).then([this] (auto&& mfopt) {
            if (mfopt) {
                assert(mfopt->is_partition_start());
                _new_last_key = mfopt->as_partition_start().key();
            }
            return std::move(mfopt);
        });
      });
     });
    }
    future<> fast_forward_to(dht::partition_range&& range, db::timeout_clock::time_point timeout) {
        auto snapshot_and_phase = _cache.snapshot_of(dht::ring_position_view::for_range_start(_range));
        return fast_forward_to(std::move(range), snapshot_and_phase.snapshot, snapshot_and_phase.phase, timeout);
    }
    future<> fast_forward_to(dht::partition_range&& range, mutation_source& snapshot, row_cache::phase_type phase, db::timeout_clock::time_point timeout) {
        _range = std::move(range);
        _last_key = { };
        _new_last_key = { };
        if (_reader) {
            if (_reader_creation_phase == phase) {
                ++_cache._tracker._stats.underlying_partition_skips;
                return _reader->fast_forward_to(_range, timeout);
            } else {
                ++_cache._tracker._stats.underlying_recreations;
            }
        }
        return close_reader().then([this, snapshot, phase] () mutable {
            _reader = _cache.create_underlying_reader(_read_context, snapshot, _range);
            _reader_creation_phase = phase;
        });
    }
    future<> close() noexcept {
        return close_reader();
    }
    utils::phased_barrier::phase_type creation_phase() const {
        return _reader_creation_phase;
    }
    const dht::partition_range& range() const {
        return _range;
    }
    flat_mutation_reader& underlying() { return *_reader; }
    dht::ring_position_view population_range_start() const {
        return _last_key ? dht::ring_position_view::for_after_key(*_last_key)
                         : dht::ring_position_view::for_range_start(_range);
    }
};

class read_context final : public enable_lw_shared_from_this<read_context> {
    row_cache& _cache;
    schema_ptr _schema;
    reader_permit _permit;
    const dht::partition_range& _range;
    const query::partition_slice& _slice;
    const io_priority_class& _pc;
    tracing::trace_state_ptr _trace_state;
    mutation_reader::forwarding _fwd_mr;
    bool _range_query;
    // When reader enters a partition, it must be set up for reading that
    // partition from the underlying mutation source (_underlying) in one of two ways:
    //
    //  1) either _underlying is already in that partition
    //
    //  2) _underlying is before the partition, then _underlying_snapshot and _key
    //     are set so that _underlying_flat can be fast forwarded to the right partition.
    //
    autoupdating_underlying_reader _underlying;
    uint64_t _underlying_created = 0;

    mutation_source_opt _underlying_snapshot;
    dht::partition_range _sm_range;
    std::optional<dht::decorated_key> _key;
    bool _partition_exists;
    row_cache::phase_type _phase;
public:
    read_context(row_cache& cache,
            schema_ptr schema,
            reader_permit permit,
            const dht::partition_range& range,
            const query::partition_slice& slice,
            const io_priority_class& pc,
            tracing::trace_state_ptr trace_state,
            mutation_reader::forwarding fwd_mr)
        : _cache(cache)
        , _schema(std::move(schema))
        , _permit(std::move(permit))
        , _range(range)
        , _slice(slice)
        , _pc(pc)
        , _trace_state(std::move(trace_state))
        , _fwd_mr(fwd_mr)
        , _range_query(!query::is_single_partition(range))
        , _underlying(_cache, *this)
    {
        ++_cache._tracker._stats.reads;
        if (!_range_query) {
            _key = range.start()->value().as_decorated_key();
        }
    }
    ~read_context() {
        ++_cache._tracker._stats.reads_done;
        if (_underlying_created) {
            _cache._stats.reads_with_misses.mark();
            ++_cache._tracker._stats.reads_with_misses;
        } else {
            _cache._stats.reads_with_no_misses.mark();
        }
    }
    read_context(const read_context&) = delete;
    row_cache& cache() { return _cache; }
    const schema_ptr& schema() const { return _schema; }
    reader_permit permit() const { return _permit; }
    const dht::partition_range& range() const { return _range; }
    const query::partition_slice& slice() const { return _slice; }
    const io_priority_class& pc() const { return _pc; }
    tracing::trace_state_ptr trace_state() const { return _trace_state; }
    mutation_reader::forwarding fwd_mr() const { return _fwd_mr; }
    bool is_range_query() const { return _range_query; }
    autoupdating_underlying_reader& underlying() { return _underlying; }
    row_cache::phase_type phase() const { return _phase; }
    const dht::decorated_key& key() const { return *_key; }
    bool partition_exists() const { return _partition_exists; }
    void on_underlying_created() { ++_underlying_created; }
    bool digest_requested() const { return _slice.options.contains<query::partition_slice::option::with_digest>(); }
public:
    future<> ensure_underlying(db::timeout_clock::time_point timeout) {
        if (_underlying_snapshot) {
            return create_underlying(timeout).then([this, timeout] {
                return _underlying.underlying()(timeout).then([this] (mutation_fragment_opt&& mfopt) {
                    _partition_exists = bool(mfopt);
                });
            });
        }
        // We know that partition exists because all the callers of
        // enter_partition(const dht::decorated_key&, row_cache::phase_type)
        // check that and there's no other way of setting _underlying_snapshot
        // to empty. Except for calling create_underlying.
        _partition_exists = true;
        return make_ready_future<>();
    }
public:
    future<> create_underlying(db::timeout_clock::time_point timeout);
    void enter_partition(const dht::decorated_key& dk, mutation_source& snapshot, row_cache::phase_type phase) {
        _phase = phase;
        _underlying_snapshot = snapshot;
        _key = dk;
    }
    // Precondition: each caller needs to make sure that partition with |dk| key
    //               exists in underlying before calling this function.
    void enter_partition(const dht::decorated_key& dk, row_cache::phase_type phase) {
        _phase = phase;
        _underlying_snapshot = {};
        _key = dk;
    }
    future<> close() noexcept {
        return _underlying.close();
    }
};

}
<|endoftext|>


<commit_before>// tUtil.cpp
//
// Utility functions. These include hardware querying utilities like supported instruction sets, number or cores,
// hardware timer functions, and computer name/ip accessors.
//
// Copyright (c) 2004-2006, 2017, 2019 Tristan Grimmer.
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby
// granted, provided that the above copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
// AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.

#ifdef PLATFORM_WIN
#include <Windows.h>
#include <intrin.h>
#endif
#include "Foundation/tStandard.h"
#include "System/tFile.h"
#include "System/tUtil.h"
#include "System/tPrint.h"

#ifdef PLATFORM_WIN
bool tSystem::tSupportsSSE()
{
	int cpuInfo[4];
	int infoType = 1;
	__cpuid(cpuInfo, infoType);

	int features = cpuInfo[3];

	// SSE feature bit is 25.
	if (features & (1 << 25))
		return true;
	else
		return false;
}

bool tSystem::tSupportsSSE2()
{
	int cpuInfo[4];
	int infoType = 1;
	__cpuid(cpuInfo, infoType);

	int features = cpuInfo[3];

	// SSE2 feature bit is 26.
	if (features & (1 << 26))
		return true;
	else
		return false;
}
#endif

tString tSystem::tGetCompName()
{
	#ifdef PLATFORM_WIN
	char name[128];
	ulong nameSize = 128;

	WinBool success = GetComputerName(name, &nameSize);
	if (success)
		return name;
	#endif

	return tString();
}

tString tSystem::tGetIPAddress()
{
	// @todo Implement. Maybe use gethostname.
	return tString();
}

#ifdef PLATFORM_WIN
int tSystem::tGetNumCores()
{
	SYSTEM_INFO sysinfo;
	tStd::tMemset(&sysinfo, 0, sizeof(sysinfo));
	GetSystemInfo(&sysinfo);
	if ((sysinfo.dwNumberOfProcessors == 0) || (sysinfo.dwNumberOfProcessors == -1))
		return 1;

	return sysinfo.dwNumberOfProcessors;
}
#endif
<commit_msg>GetNumCores caches result for fast execution after the first time.<commit_after>// tUtil.cpp
//
// Utility functions. These include hardware querying utilities like supported instruction sets, number or cores,
// hardware timer functions, and computer name/ip accessors.
//
// Copyright (c) 2004-2006, 2017, 2019 Tristan Grimmer.
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby
// granted, provided that the above copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
// AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.

#ifdef PLATFORM_WIN
#include <Windows.h>
#include <intrin.h>
#endif
#include "Foundation/tStandard.h"
#include "System/tFile.h"
#include "System/tUtil.h"
#include "System/tPrint.h"

#ifdef PLATFORM_WIN
bool tSystem::tSupportsSSE()
{
	int cpuInfo[4];
	int infoType = 1;
	__cpuid(cpuInfo, infoType);

	int features = cpuInfo[3];

	// SSE feature bit is 25.
	if (features & (1 << 25))
		return true;
	else
		return false;
}

bool tSystem::tSupportsSSE2()
{
	int cpuInfo[4];
	int infoType = 1;
	__cpuid(cpuInfo, infoType);

	int features = cpuInfo[3];

	// SSE2 feature bit is 26.
	if (features & (1 << 26))
		return true;
	else
		return false;
}
#endif

tString tSystem::tGetCompName()
{
	#ifdef PLATFORM_WIN
	char name[128];
	ulong nameSize = 128;

	WinBool success = GetComputerName(name, &nameSize);
	if (success)
		return name;
	#endif

	return tString();
}

tString tSystem::tGetIPAddress()
{
	// @todo Implement. Maybe use gethostname.
	return tString();
}

#ifdef PLATFORM_WIN
int tSystem::tGetNumCores()
{
	// Lets cache this value as it never changes.
	static int numCores = 0;
	if (numCores > 0)
		return numCores;

	SYSTEM_INFO sysinfo;
	tStd::tMemset(&sysinfo, 0, sizeof(sysinfo));
	GetSystemInfo(&sysinfo);

	// dwNumberOfProcessors is unsigned, so can't say just > 0.
	if ((sysinfo.dwNumberOfProcessors == 0) || (sysinfo.dwNumberOfProcessors == -1))
		numCores = 1;
	else
		numCores = sysinfo.dwNumberOfProcessors;

	return numCores;
}
#endif
<|endoftext|>


<commit_before>#ifndef WIN32

//===--- TerminalConfigUnix.cpp - termios storage -------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// TerminalReader and TerminalDisplay need to reset the terminal configuration
// upon destruction, to leave the terminal as before. To avoid a possible
// misunderstanding of what "before" means, centralize their storage of the
// previous termios and have them share it.
//
//  Axel Naumann <axel@cern.ch>, 2011-05-12
//===----------------------------------------------------------------------===//

#include "textinput/TerminalConfigUnix.h"

#include <termios.h>
#include <unistd.h>
#include <stdio.h>
#include <cstring>

using namespace textinput;
using std::memcpy;
using std::signal;
using std::raise;

namespace {
void
TerminalConfigUnix__handleSignal(int signum) {
  // Clean up before we are killed.
  TerminalConfigUnix::Get().HandleSignal(signum);
}
}

const int TerminalConfigUnix::fgSignals[kNumHandledSignals] = {
  // SIGKILL: can't handle by definition
  // Order: most to least common signal
  SIGTERM,
  SIGABRT,
  SIGSEGV,
  SIGILL,
  SIGBUS
};

TerminalConfigUnix&
TerminalConfigUnix::Get() {
  static TerminalConfigUnix s;
  return s;
}

TerminalConfigUnix::TerminalConfigUnix():
  fIsAttached(false), fFD(fileno(stdin)), fOldTIOS(), fConfTIOS() {
#ifdef TCSANOW
  fOldTIOS = new termios;
  fConfTIOS = new termios;
  tcgetattr(fFD, fOldTIOS);
  *fConfTIOS = *fOldTIOS;
#endif
  for (int i = 0; i < kNumHandledSignals; ++i) {
    fPrevHandler[i] = signal(fgSignals[i], TerminalConfigUnix__handleSignal);
  }
}

TerminalConfigUnix::~TerminalConfigUnix() {
  // Restore signals and detach.
  for (int i = 0; i < kNumHandledSignals; ++i) {
    if (fPrevHandler[i]) {
      signal(fgSignals[i], fPrevHandler[i]);
    } else {
      // default:
      signal(fgSignals[i], SIG_DFL);
    }
  }
  Detach();
  delete fOldTIOS;
  delete fConfTIOS;
}

void
TerminalConfigUnix::HandleSignal(int signum) {
  // Process has received a fatal signal, detach.
  bool sSignalHandlerActive = false;
  if (!sSignalHandlerActive) {
    sSignalHandlerActive = true;
    Detach();
    // find previous signal handler index:
    for (int i = 0; i < kNumHandledSignals; ++i) {
      if (fgSignals[i] == signum) {
        // Call previous signal handler if it exists.
        if (fPrevHandler[i]) {
          fPrevHandler[i](signum);
          // should not end up here...
          sSignalHandlerActive = false;
          return;
        } else break;
      }
    }
  }

  // No previous handler found, re-raise to get default handling:
  signal(signum, SIG_DFL); // unregister ourselves
  raise(signum); // terminate through default handler

  // should not end up here...
  signal(signum, TerminalConfigUnix__handleSignal);
  sSignalHandlerActive = false;
}

void
TerminalConfigUnix::Attach() {
  if (fIsAttached) return;
#ifdef TCSANOW
  if (IsInteractive()) {
    tcsetattr(fFD, TCSANOW, fConfTIOS);
  }
#endif
  fIsAttached = true;
}

void
TerminalConfigUnix::Detach() {
  // Reset the terminal configuration.
  if (!fIsAttached) return;
#ifdef TCSANOW
  if (IsInteractive()) {
    tcsetattr(fFD, TCSANOW, fOldTIOS);
  }
#endif
  fIsAttached = false;
}

bool TerminalConfigUnix::IsInteractive() const {
  // Whether both stdin and stdout are attached to a tty.
  return isatty(fileno(stdin)) && isatty(fileno(stdout))
    && (getpgrp() == tcgetpgrp(STDOUT_FILENO));
}

#endif // ndef WIN32
<commit_msg>Don't set the signal handler again; the program is supposed to call the default signal handler, and by setting ours again it doesn't. Fixes problem with ".qqqqqqqq".<commit_after>#ifndef WIN32

//===--- TerminalConfigUnix.cpp - termios storage -------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// TerminalReader and TerminalDisplay need to reset the terminal configuration
// upon destruction, to leave the terminal as before. To avoid a possible
// misunderstanding of what "before" means, centralize their storage of the
// previous termios and have them share it.
//
//  Axel Naumann <axel@cern.ch>, 2011-05-12
//===----------------------------------------------------------------------===//

#include "textinput/TerminalConfigUnix.h"

#include <termios.h>
#include <unistd.h>
#include <stdio.h>
#include <cstring>

using namespace textinput;
using std::memcpy;
using std::signal;
using std::raise;

namespace {
void
TerminalConfigUnix__handleSignal(int signum) {
  // Clean up before we are killed.
  TerminalConfigUnix::Get().HandleSignal(signum);
}
}

const int TerminalConfigUnix::fgSignals[kNumHandledSignals] = {
  // SIGKILL: can't handle by definition
  // Order: most to least common signal
  SIGTERM,
  SIGABRT,
  SIGSEGV,
  SIGILL,
  SIGBUS
};

TerminalConfigUnix&
TerminalConfigUnix::Get() {
  static TerminalConfigUnix s;
  return s;
}

TerminalConfigUnix::TerminalConfigUnix():
  fIsAttached(false), fFD(fileno(stdin)), fOldTIOS(), fConfTIOS() {
#ifdef TCSANOW
  fOldTIOS = new termios;
  fConfTIOS = new termios;
  tcgetattr(fFD, fOldTIOS);
  *fConfTIOS = *fOldTIOS;
#endif
  for (int i = 0; i < kNumHandledSignals; ++i) {
    fPrevHandler[i] = signal(fgSignals[i], TerminalConfigUnix__handleSignal);
  }
}

TerminalConfigUnix::~TerminalConfigUnix() {
  // Restore signals and detach.
  for (int i = 0; i < kNumHandledSignals; ++i) {
    if (fPrevHandler[i]) {
      signal(fgSignals[i], fPrevHandler[i]);
    } else {
      // default:
      signal(fgSignals[i], SIG_DFL);
    }
  }
  Detach();
  delete fOldTIOS;
  delete fConfTIOS;
}

void
TerminalConfigUnix::HandleSignal(int signum) {
  // Process has received a fatal signal, detach.
  bool sSignalHandlerActive = false;
  if (!sSignalHandlerActive) {
    sSignalHandlerActive = true;
    Detach();
    // find previous signal handler index:
    for (int i = 0; i < kNumHandledSignals; ++i) {
      if (fgSignals[i] == signum) {
        // Call previous signal handler if it exists.
        if (fPrevHandler[i]) {
          fPrevHandler[i](signum);
          // should not end up here...
          sSignalHandlerActive = false;
          return;
        } else break;
      }
    }
  }

  // No previous handler found, re-raise to get default handling:
  signal(signum, SIG_DFL); // unregister ourselves
  raise(signum); // terminate through default handler

  // No need to recover our state; there will be no "next time":
  // the signal raised above will cause the program to quit.
  //signal(signum, TerminalConfigUnix__handleSignal);
  //sSignalHandlerActive = false;
}

void
TerminalConfigUnix::Attach() {
  if (fIsAttached) return;
#ifdef TCSANOW
  if (IsInteractive()) {
    tcsetattr(fFD, TCSANOW, fConfTIOS);
  }
#endif
  fIsAttached = true;
}

void
TerminalConfigUnix::Detach() {
  // Reset the terminal configuration.
  if (!fIsAttached) return;
#ifdef TCSANOW
  if (IsInteractive()) {
    tcsetattr(fFD, TCSANOW, fOldTIOS);
  }
#endif
  fIsAttached = false;
}

bool TerminalConfigUnix::IsInteractive() const {
  // Whether both stdin and stdout are attached to a tty.
  return isatty(fileno(stdin)) && isatty(fileno(stdout))
    && (getpgrp() == tcgetpgrp(STDOUT_FILENO));
}

#endif // ndef WIN32
<|endoftext|>


<commit_before>/** \copyright
 * Copyright (c) 2015, Balazs Racz
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are  permitted provided that the following conditions are met:
 *
 *  - Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 *  - Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * \file CpuLoad.hxx
 * Class for maintining a CPU load indication.
 *
 * @author Balazs Racz
 * @date 30 August 2015
 */

#include "CpuLoad.hxx"

#include "os/os.h"
#include "freertos_includes.h"

extern "C" {

/// The bits to shift to get multiples of 1.0
static constexpr uint32_t SHIFT_ONE = 24;

/// The bits to shift after a rate inclusing
static constexpr uint32_t SHIFT_RATE = 8;
/// The multiplication for the rate
static constexpr uint8_t AVG_RATE = 0xff;
/// If the last measurement was busy, we add this much weight
static constexpr uint32_t ADD_RATE = 0x1 << 24;

void CpuLoad::record_value(bool busy, uintptr_t key)
{
    avg_ *= AVG_RATE;
    ++countSinceUpdate_;
    if (busy)
    {
        avg_ += ADD_RATE;
    }
    avg_ >>= SHIFT_RATE;
    // Check streak
    if (busy)
    {
        if (consecutive_ < 255)
        {
            ++consecutive_;
        }
        if (consecutive_ > maxConsecutive_)
        {
            maxConsecutive_ = consecutive_;
        }
    }
    else
    {
        consecutive_ = 0;
    }
    // Check window of 16.
    last16Bits_ <<= 1;
    last16Bits_ |= (busy ? 1 : 0);
    // sums up last 16 bits.
    unsigned v = last16Bits_;
    v = (v & 0x5555) + ((v & 0xaaaa) >> 1);
    v = (v & 0x3333) + ((v & 0xcccc) >> 2);
    v = (v & 0x0F0F) + ((v & 0xF0F0) >> 4);
    v = (v & 0x00FF) + ((v & 0xFF00) >> 8);
    if (v > peakOver16Counts_)
    {
        peakOver16Counts_ = v;
    }
    // Record per-key information
    if (key == 0)
        return;
    bool found = false;
    for (auto it = perKeyCost_.begin(); it != perKeyCost_.end(); ++it)
    {
        if (it->key == key)
        {
            found = true;
            ++it->rolling_count;
            break;
        }
    }
    if (!found && newKey_ == 0)
    {
        newKey_ = key;
    }
}

uint8_t CpuLoad::get_load() {
    return (avg_ * 100) >> SHIFT_ONE;
}

void cpuload_tick(unsigned irq)
{
    if (!Singleton<CpuLoad>::exists())
        return;
    if (irq != 0)
    {
        Singleton<CpuLoad>::instance()->record_value(true, (uintptr_t)irq);
        return;
    }
#ifdef ESP32
    auto hdl = xTaskGetCurrentTaskHandleForCPU(0);
    bool is_idle = xTaskGetIdleTaskHandleForCPU(0) == hdl;
    Singleton<CpuLoad>::instance()->record_value(!is_idle, (uintptr_t)hdl);
    hdl = xTaskGetCurrentTaskHandleForCPU(1);
    is_idle = xTaskGetIdleTaskHandleForCPU(1) == hdl;
    Singleton<CpuLoad>::instance()->record_value(!is_idle, (uintptr_t)hdl);
#else
    auto hdl = xTaskGetCurrentTaskHandle();
    bool is_idle = xTaskGetIdleTaskHandle() == hdl;
    Singleton<CpuLoad>::instance()->record_value(!is_idle, (uintptr_t)hdl);
#endif
}
}

DEFINE_SINGLETON_INSTANCE(CpuLoad);
<commit_msg>Fixes load accounting for esp32 (#280)<commit_after>/** \copyright
 * Copyright (c) 2015, Balazs Racz
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are  permitted provided that the following conditions are met:
 *
 *  - Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 *  - Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * \file CpuLoad.hxx
 * Class for maintining a CPU load indication.
 *
 * @author Balazs Racz
 * @date 30 August 2015
 */

#include "CpuLoad.hxx"

#include "os/os.h"
#include "freertos_includes.h"

extern "C" {

/// The bits to shift to get multiples of 1.0
static constexpr uint32_t SHIFT_ONE = 24;

/// The bits to shift after a rate inclusing
static constexpr uint32_t SHIFT_RATE = 8;
/// The multiplication for the rate
static constexpr uint8_t AVG_RATE = 0xff;
/// If the last measurement was busy, we add this much weight
static constexpr uint32_t ADD_RATE = 0x1 << 24;

void CpuLoad::record_value(bool busy, uintptr_t key)
{
    avg_ *= AVG_RATE;
    ++countSinceUpdate_;
    if (busy)
    {
        avg_ += ADD_RATE;
    }
    avg_ >>= SHIFT_RATE;
    // Check streak
    if (busy)
    {
        if (consecutive_ < 255)
        {
            ++consecutive_;
        }
        if (consecutive_ > maxConsecutive_)
        {
            maxConsecutive_ = consecutive_;
        }
    }
    else
    {
        consecutive_ = 0;
    }
    // Check window of 16.
    last16Bits_ <<= 1;
    last16Bits_ |= (busy ? 1 : 0);
    // sums up last 16 bits.
    unsigned v = last16Bits_;
    v = (v & 0x5555) + ((v & 0xaaaa) >> 1);
    v = (v & 0x3333) + ((v & 0xcccc) >> 2);
    v = (v & 0x0F0F) + ((v & 0xF0F0) >> 4);
    v = (v & 0x00FF) + ((v & 0xFF00) >> 8);
    if (v > peakOver16Counts_)
    {
        peakOver16Counts_ = v;
    }
    // Record per-key information
    if (key == 0)
        return;
    bool found = false;
    for (auto it = perKeyCost_.begin(); it != perKeyCost_.end(); ++it)
    {
        if (it->key == key)
        {
            found = true;
            ++it->rolling_count;
            break;
        }
    }
    if (!found && newKey_ == 0)
    {
        newKey_ = key;
    }
}

uint8_t CpuLoad::get_load() {
    return (avg_ * 100) >> SHIFT_ONE;
}

void cpuload_tick(unsigned irq)
{
    if (!Singleton<CpuLoad>::exists())
        return;
#ifdef ESP32
    if (irq != 0)
    {
        Singleton<CpuLoad>::instance()->record_value(true, (uintptr_t)irq);
    }
    else // assumes openmrn task is pinned to core 0
    {
        auto hdl = xTaskGetCurrentTaskHandleForCPU(0);
        bool is_idle = xTaskGetIdleTaskHandleForCPU(0) == hdl;
        Singleton<CpuLoad>::instance()->record_value(!is_idle, (uintptr_t)hdl);
    }
    // always records CPU 1 task.
    auto hdl = xTaskGetCurrentTaskHandleForCPU(1);
    bool is_idle = xTaskGetIdleTaskHandleForCPU(1) == hdl;
    Singleton<CpuLoad>::instance()->record_value(!is_idle, (uintptr_t)hdl);
#else
    if (irq != 0)
    {
        Singleton<CpuLoad>::instance()->record_value(true, (uintptr_t)irq);
        return;
    }
    auto hdl = xTaskGetCurrentTaskHandle();
    bool is_idle = xTaskGetIdleTaskHandle() == hdl;
    Singleton<CpuLoad>::instance()->record_value(!is_idle, (uintptr_t)hdl);
#endif
}
}

DEFINE_SINGLETON_INSTANCE(CpuLoad);
<|endoftext|>


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

#pragma once
#ifndef SIELOBROWSER_BOOKMARKSIMPORTER_HPP
#define SIELOBROWSER_BOOKMARKSIMPORTER_HPP

#include <QObject>

#include <QString>

namespace Sn
{
class BookmarkItem;

class BookmarksImporter: public QObject {
	BookmarksImporter(QObject* parent = nullptr);
	virtual ~BookmarksImporter();

	bool error() const;
	QString errorString() const;

	virtual QString description() const = 0;
	virtual QString standardPath() const = 0;

	virtual QString getPath(QWidget* parent) = 0;
	virtual bool prepareImport() = 0;
	virtual BookmarkItem *importBookmarks() = 0;

protected:
	// Empty error = no error
	void setError(const QString& error);

private:
	QString m_error{};
};
}

#endif //SIELOBROWSER_BOOKMARKSIMPORTER_HPP
<commit_msg>[Update] Bookmarks importer<commit_after>/***********************************************************************************
** MIT License                                                                    **
**                                                                                **
** Copyright (c) 2018 Victor DENIS (victordenis01@gmail.com)                      **
**                                                                                **
** Permission is hereby granted, free of charge, to any person obtaining a copy   **
** of this software and associated documentation files (the "Software"), to deal  **
** in the Software without restriction, including without limitation the rights   **
** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell      **
** copies of the Software, and to permit persons to whom the Software is          **
** furnished to do so, subject to the following conditions:                       **
**                                                                                **
** The above copyright notice and this permission notice shall be included in all **
** copies or substantial portions of the Software.                                **
**                                                                                **
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR     **
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,       **
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE    **
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER         **
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,  **
** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE  **
** SOFTWARE.                                                                      **
***********************************************************************************/

#pragma once
#ifndef SIELOBROWSER_BOOKMARKSIMPORTER_HPP
#define SIELOBROWSER_BOOKMARKSIMPORTER_HPP

#include <QObject>

#include <QString>

namespace Sn
{
class BookmarkItem;

class BookmarksImporter: public QObject {
	Q_OBJECT

public:
	BookmarksImporter(QObject* parent = nullptr);
	virtual ~BookmarksImporter();

	bool error() const;
	QString errorString() const;

	virtual QString description() const = 0;
	virtual QString standardPath() const = 0;

	virtual QString getPath(QWidget* parent) = 0;
	virtual bool prepareImport() = 0;
	virtual BookmarkItem *importBookmarks() = 0;

protected:
	// Empty error = no error
	void setError(const QString& error);

private:
	QString m_error{};
};
}

#endif //SIELOBROWSER_BOOKMARKSIMPORTER_HPP
<|endoftext|>