<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: LayerDialogContent.cxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include <com/sun/star/frame/XFrame.hpp>
#include <com/sun/star/text/WritingMode.hpp>

#include <vcl/image.hxx>

#include <sfx2/dockwin.hxx>
#include <sfx2/app.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/imagemgr.hxx>
#include <sfx2/tbxctrl.hxx>

#include <svl/languageoptions.hxx>

#include <svtools/valueset.hxx>

#include <svx/toolbarmenu.hxx>

#include "app.hrc"
#include "layoutdialog.hxx"
#include "glob.hrc"
#include "strings.hrc"
#include "res_bmp.hrc"
#include "sdresid.hxx"
#include "View.hxx"
#include "drawdoc.hxx"
#include "ViewShellBase.hxx"
#include "DrawViewShell.hxx"
#include "layoutdialog.hrc"

using ::rtl::OUString;
using namespace ::com::sun::star;
using namespace ::com::sun::star::text;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::frame;

namespace sd {

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

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

struct snewfoil_value_info
{
    USHORT mnBmpResId;
    USHORT mnHCBmpResId;
    USHORT mnStrResId;
    WritingMode meWritingMode;
    AutoLayout maAutoLayout;
};
static snewfoil_value_info standard[] =
{
    {BMP_LAYOUT_EMPTY, BMP_LAYOUT_EMPTY_H, STR_AUTOLAYOUT_NONE, WritingMode_LR_TB,        AUTOLAYOUT_NONE},
    {BMP_LAYOUT_HEAD03, BMP_LAYOUT_HEAD03_H, STR_AUTOLAYOUT_TITLE, WritingMode_LR_TB,       AUTOLAYOUT_TITLE},
    {BMP_LAYOUT_HEAD02, BMP_LAYOUT_HEAD02_H, STR_AUTOLAYOUT_CONTENT, WritingMode_LR_TB,        AUTOLAYOUT_ENUM},
    {BMP_LAYOUT_HEAD02A, BMP_LAYOUT_HEAD02A_H, STR_AUTOLAYOUT_2CONTENT, WritingMode_LR_TB,       AUTOLAYOUT_2TEXT},
    {BMP_LAYOUT_HEAD01, BMP_LAYOUT_HEAD01_H, STR_AUTOLAYOUT_ONLY_TITLE, WritingMode_LR_TB,  AUTOLAYOUT_ONLY_TITLE},
    {BMP_LAYOUT_TEXTONLY, BMP_LAYOUT_TEXTONLY_H, STR_AUTOLAYOUT_ONLY_TEXT, WritingMode_LR_TB,   AUTOLAYOUT_ONLY_TEXT},
    {BMP_LAYOUT_HEAD03B, BMP_LAYOUT_HEAD03B_H, STR_AUTOLAYOUT_2CONTENT_CONTENT, WritingMode_LR_TB,    AUTOLAYOUT_2OBJTEXT},
    {BMP_LAYOUT_HEAD03C, BMP_LAYOUT_HEAD03C_H, STR_AUTOLAYOUT_CONTENT_2CONTENT, WritingMode_LR_TB,    AUTOLAYOUT_TEXT2OBJ},
    {BMP_LAYOUT_HEAD03A, BMP_LAYOUT_HEAD03A_H, STR_AUTOLAYOUT_2CONTENT_OVER_CONTENT,WritingMode_LR_TB, AUTOLAYOUT_2OBJOVERTEXT},
    {BMP_LAYOUT_HEAD02B, BMP_LAYOUT_HEAD02B_H, STR_AUTOLAYOUT_CONTENT_OVER_CONTENT, WritingMode_LR_TB, AUTOLAYOUT_OBJOVERTEXT},
    {BMP_LAYOUT_HEAD04, BMP_LAYOUT_HEAD04_H, STR_AUTOLAYOUT_4CONTENT, WritingMode_LR_TB,        AUTOLAYOUT_4OBJ},
    {BMP_LAYOUT_HEAD06, BMP_LAYOUT_HEAD06_H, STR_AUTOLAYOUT_6CONTENT, WritingMode_LR_TB,    AUTOLAYOUT_6CLIPART},
    {0, 0, 0, WritingMode_LR_TB, AUTOLAYOUT_NONE}
};

static snewfoil_value_info v_standard[] =
{
    // vertical
    {BMP_LAYOUT_VERTICAL02, BMP_LAYOUT_VERTICAL02_H, STR_AL_VERT_TITLE_TEXT_CHART, WritingMode_TB_RL,AUTOLAYOUT_VERTICAL_TITLE_TEXT_CHART},
    {BMP_LAYOUT_VERTICAL01, BMP_LAYOUT_VERTICAL01_H, STR_AL_VERT_TITLE_VERT_OUTLINE, WritingMode_TB_RL, AUTOLAYOUT_VERTICAL_TITLE_VERTICAL_OUTLINE},
    {BMP_LAYOUT_HEAD02, BMP_LAYOUT_HEAD02_H, STR_AL_TITLE_VERT_OUTLINE, WritingMode_TB_RL, AUTOLAYOUT_TITLE_VERTICAL_OUTLINE},
    {BMP_LAYOUT_HEAD02A, BMP_LAYOUT_HEAD02A_H, STR_AL_TITLE_VERT_OUTLINE_CLIPART,   WritingMode_TB_RL, AUTOLAYOUT_TITLE_VERTICAL_OUTLINE_CLIPART},
    {0, 0, 0, WritingMode_LR_TB, AUTOLAYOUT_NONE}
};

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

static void fillLayoutValueSet( ValueSet* pValue, snewfoil_value_info* pInfo, const bool bHighContrast )
{
    Size aLayoutItemSize;
    for( ; pInfo->mnBmpResId; pInfo++ )
    {
        String aText( SdResId( pInfo->mnStrResId ) );
        BitmapEx aBmp( SdResId( (bHighContrast ? pInfo->mnHCBmpResId : pInfo->mnBmpResId) ) );

        pValue->InsertItem( static_cast<USHORT>(pInfo->maAutoLayout)+1, aBmp, aText );

        aLayoutItemSize.Width() = std::max( aLayoutItemSize.Width(), aBmp.GetSizePixel().Width() );
        aLayoutItemSize.Height() = std::max( aLayoutItemSize.Height(), aBmp.GetSizePixel().Height() );
    }

    aLayoutItemSize = pValue->CalcItemSizePixel( aLayoutItemSize );
    pValue->SetSizePixel( pValue->CalcWindowSizePixel( aLayoutItemSize ) );
}

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

SdLayoutDialogContent::SdLayoutDialogContent( ViewShellBase& rBase, ::Window* pParent, const bool bInsertPage )
: ToolbarMenu(rBase.GetFrame()->GetTopFrame()->GetFrameInterface(), pParent, SdResId( DLG_LAYOUTDIALOG ) /*WB_CLIPCHILDREN|WB_DIALOGCONTROL|WB_SYSTEMWINDOW|WB_MOVEABLE|WB_SIZEABLE|WB_CLOSEABLE*/)
, mrBase(rBase)
, mbInsertPage( bInsertPage )
, mpLayoutSet1( 0 )
, mpLayoutSet2( 0 )
, msAssignLayout( RTL_CONSTASCII_USTRINGPARAM( ".uno:AssignLayout" ) )
{
    String aTitle1( SdResId( STR_HORIZONTAL_LAYOUTS ) );
    String aTitle2( SdResId( STR_VERTICAL_LAYOUTS ) );

    FreeResource();

    const Color aMenuColor( GetSettings().GetStyleSettings().GetMenuColor() );
    const Color aMenuBarColor( GetSettings().GetStyleSettings().GetMenuBarColor() );
    const Color aMenuTextColor( GetSettings().GetStyleSettings().GetMenuBarColor() );
    const Color aMenuBarTextColor( GetSettings().GetStyleSettings().GetMenuBarTextColor() );

    const bool bHighContrast = GetSettings().GetStyleSettings().GetHighContrastMode();
    SvtLanguageOptions aLanguageOptions;
    const bool bVerticalEnabled = aLanguageOptions.IsVerticalTextEnabled();

    SetSelectHdl( LINK( this, SdLayoutDialogContent, SelectHdl ) );

    mpLayoutSet1 = new ValueSet( this, WB_TABSTOP | WB_MENUSTYLEVALUESET | WB_FLATVALUESET | WB_NOBORDER | WB_NO_DIRECTSELECT );
//  mpLayoutSet1->SetHelpId( HID_VALUESET_EXTRUSION_LIGHTING );

    mpLayoutSet1->SetSelectHdl( LINK( this, SdLayoutDialogContent, SelectHdl ) );
    mpLayoutSet1->SetColCount( 4 );
    mpLayoutSet1->EnableFullItemMode( FALSE );
    mpLayoutSet1->SetColor( GetControlBackground() );

    fillLayoutValueSet( mpLayoutSet1, &standard[0], bHighContrast );

    if( bVerticalEnabled )
        appendEntry( -1, aTitle1 );
    appendEntry( 0, mpLayoutSet1 );

    if( bVerticalEnabled )
    {
        mpLayoutSet2 = new ValueSet( this, WB_TABSTOP | WB_MENUSTYLEVALUESET | WB_FLATVALUESET | WB_NOBORDER | WB_NO_DIRECTSELECT );
    //  mpLayoutSet2->SetHelpId( HID_VALUESET_EXTRUSION_LIGHTING );

        mpLayoutSet2->SetSelectHdl( LINK( this, SdLayoutDialogContent, SelectHdl ) );
        mpLayoutSet2->SetColCount( 4 );
        mpLayoutSet2->EnableFullItemMode( FALSE );
        mpLayoutSet2->SetColor( GetControlBackground() );

        fillLayoutValueSet( mpLayoutSet2, &v_standard[0], bHighContrast );

        appendEntry( -1, aTitle2 );
        appendEntry( 1, mpLayoutSet2 );
    }

    //appendSeparator();

    OUString sSlotStr;
    Image aSlotImage;
    Reference< XFrame > xFrame( GetFrame(), UNO_QUERY );
    if( xFrame.is() )
    {
        if( bInsertPage )
            sSlotStr = OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:DuplicatePage" ) );
        else
            sSlotStr = OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:Undo" ) );
        aSlotImage = ::GetImage( xFrame, sSlotStr, FALSE, FALSE );
    }

    String sSlotTitle;
    if( bInsertPage )
        sSlotTitle = mrBase.RetrieveLabelFromCommand( sSlotStr );
    else
        sSlotTitle = String( SdResId( STR_RESET_LAYOUT ) );
    appendEntry( 2, sSlotTitle, aSlotImage);

    SetOutputSizePixel( getMenuSize() );

    AddStatusListener( msAssignLayout );
}

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

SdLayoutDialogContent::~SdLayoutDialogContent()
{
}

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

/*
void SdLayoutDialogContent::DataChanged( const DataChangedEvent& rDCEvt )
{
    SfxDockingWindow::DataChanged( rDCEvt );

    if( ( rDCEvt.GetType() == DATACHANGED_SETTINGS ) && ( rDCEvt.GetFlags() & SETTINGS_STYLE ) )
    {
        // const bool bHighContrast = GetSettings().GetStyleSettings().GetHighContrastMode();

        // todo switch images
    }
}
*/

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

/*
void SdLayoutDialogContent::StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState )
{
    if( (nSID == SID_ASSIGN_LAYOUT) && (eState != SFX_ITEM_DISABLED) )
    {
        const SfxUInt32Item* pStateItem = dynamic_cast< const SfxUInt32Item* >(pState);
        if( pStateItem )
        {
            meCurrentLayout = static_cast< AutoLayout >( pStateItem->GetValue() );
            mpLayoutSet1->SelectItem( static_cast<USHORT>(meCurrentLayout)+1 );
        }
    }
}
*/

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

IMPL_LINK( SdLayoutDialogContent, SelectHdl, void *, pControl )
{
    if ( IsInPopupMode() )
        EndPopupMode();

    if( mrBase.GetMainViewShell().get() && mrBase.GetMainViewShell()->GetViewFrame() )
    {
        if( pControl == mpLayoutSet1 )
        {
            AutoLayout eLayout = static_cast< AutoLayout >(mpLayoutSet1->GetSelectItemId()-1);

            const SfxUInt32Item aItem(ID_VAL_WHATLAYOUT, eLayout);
            mrBase.GetMainViewShell()->GetViewFrame()->GetBindings().GetDispatcher()->Execute(mbInsertPage ? SID_INSERTPAGE : SID_ASSIGN_LAYOUT,SFX_CALLMODE_ASYNCHRON,&aItem,0);
        }
        else if( pControl == mpLayoutSet2 )
        {
            AutoLayout eLayout = static_cast< AutoLayout >(mpLayoutSet2->GetSelectItemId()-1);

            const SfxUInt32Item aItem(ID_VAL_WHATLAYOUT, eLayout);
            mrBase.GetMainViewShell()->GetViewFrame()->GetBindings().GetDispatcher()->Execute(mbInsertPage ? SID_INSERTPAGE : SID_ASSIGN_LAYOUT,SFX_CALLMODE_ASYNCHRON,&aItem,0);
        }
        else
        {
            // reset autolayout
            mrBase.GetMainViewShell()->GetViewFrame()->GetBindings().GetDispatcher()->Execute( mbInsertPage ? SID_DUPLICATE_PAGE : SID_ASSIGN_LAYOUT,SFX_CALLMODE_ASYNCHRON);
        }
    }

    return 0;
}

void SAL_CALL SdLayoutDialogContent::statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event ) throw ( ::com::sun::star::uno::RuntimeException )
{
    if( Event.FeatureURL.Main.equals( msAssignLayout ) )
    {
        sal_Int32 nLayout = 0;
        Event.State >>= nLayout;
        OSL_TRACE("SdLayoutDialogContent::statusChanged(%ld)", nLayout );
    }
}

} // end of namespace sd
<commit_msg>enable toolbar menu cursor traveling without focus<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: LayerDialogContent.cxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include <com/sun/star/frame/XFrame.hpp>
#include <com/sun/star/text/WritingMode.hpp>

#include <vcl/image.hxx>

#include <sfx2/dockwin.hxx>
#include <sfx2/app.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/imagemgr.hxx>
#include <sfx2/tbxctrl.hxx>

#include <svl/languageoptions.hxx>

#include <svtools/valueset.hxx>

#include <svx/toolbarmenu.hxx>

#include "app.hrc"
#include "layoutdialog.hxx"
#include "glob.hrc"
#include "strings.hrc"
#include "res_bmp.hrc"
#include "sdresid.hxx"
#include "View.hxx"
#include "drawdoc.hxx"
#include "ViewShellBase.hxx"
#include "DrawViewShell.hxx"
#include "layoutdialog.hrc"

using ::rtl::OUString;
using namespace ::com::sun::star;
using namespace ::com::sun::star::text;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::frame;

namespace sd {

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

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

struct snewfoil_value_info
{
    USHORT mnBmpResId;
    USHORT mnHCBmpResId;
    USHORT mnStrResId;
    WritingMode meWritingMode;
    AutoLayout maAutoLayout;
};
static snewfoil_value_info standard[] =
{
    {BMP_LAYOUT_EMPTY, BMP_LAYOUT_EMPTY_H, STR_AUTOLAYOUT_NONE, WritingMode_LR_TB,        AUTOLAYOUT_NONE},
    {BMP_LAYOUT_HEAD03, BMP_LAYOUT_HEAD03_H, STR_AUTOLAYOUT_TITLE, WritingMode_LR_TB,       AUTOLAYOUT_TITLE},
    {BMP_LAYOUT_HEAD02, BMP_LAYOUT_HEAD02_H, STR_AUTOLAYOUT_CONTENT, WritingMode_LR_TB,        AUTOLAYOUT_ENUM},
    {BMP_LAYOUT_HEAD02A, BMP_LAYOUT_HEAD02A_H, STR_AUTOLAYOUT_2CONTENT, WritingMode_LR_TB,       AUTOLAYOUT_2TEXT},
    {BMP_LAYOUT_HEAD01, BMP_LAYOUT_HEAD01_H, STR_AUTOLAYOUT_ONLY_TITLE, WritingMode_LR_TB,  AUTOLAYOUT_ONLY_TITLE},
    {BMP_LAYOUT_TEXTONLY, BMP_LAYOUT_TEXTONLY_H, STR_AUTOLAYOUT_ONLY_TEXT, WritingMode_LR_TB,   AUTOLAYOUT_ONLY_TEXT},
    {BMP_LAYOUT_HEAD03B, BMP_LAYOUT_HEAD03B_H, STR_AUTOLAYOUT_2CONTENT_CONTENT, WritingMode_LR_TB,    AUTOLAYOUT_2OBJTEXT},
    {BMP_LAYOUT_HEAD03C, BMP_LAYOUT_HEAD03C_H, STR_AUTOLAYOUT_CONTENT_2CONTENT, WritingMode_LR_TB,    AUTOLAYOUT_TEXT2OBJ},
    {BMP_LAYOUT_HEAD03A, BMP_LAYOUT_HEAD03A_H, STR_AUTOLAYOUT_2CONTENT_OVER_CONTENT,WritingMode_LR_TB, AUTOLAYOUT_2OBJOVERTEXT},
    {BMP_LAYOUT_HEAD02B, BMP_LAYOUT_HEAD02B_H, STR_AUTOLAYOUT_CONTENT_OVER_CONTENT, WritingMode_LR_TB, AUTOLAYOUT_OBJOVERTEXT},
    {BMP_LAYOUT_HEAD04, BMP_LAYOUT_HEAD04_H, STR_AUTOLAYOUT_4CONTENT, WritingMode_LR_TB,        AUTOLAYOUT_4OBJ},
    {BMP_LAYOUT_HEAD06, BMP_LAYOUT_HEAD06_H, STR_AUTOLAYOUT_6CONTENT, WritingMode_LR_TB,    AUTOLAYOUT_6CLIPART},
    {0, 0, 0, WritingMode_LR_TB, AUTOLAYOUT_NONE}
};

static snewfoil_value_info v_standard[] =
{
    // vertical
    {BMP_LAYOUT_VERTICAL02, BMP_LAYOUT_VERTICAL02_H, STR_AL_VERT_TITLE_TEXT_CHART, WritingMode_TB_RL,AUTOLAYOUT_VERTICAL_TITLE_TEXT_CHART},
    {BMP_LAYOUT_VERTICAL01, BMP_LAYOUT_VERTICAL01_H, STR_AL_VERT_TITLE_VERT_OUTLINE, WritingMode_TB_RL, AUTOLAYOUT_VERTICAL_TITLE_VERTICAL_OUTLINE},
    {BMP_LAYOUT_HEAD02, BMP_LAYOUT_HEAD02_H, STR_AL_TITLE_VERT_OUTLINE, WritingMode_TB_RL, AUTOLAYOUT_TITLE_VERTICAL_OUTLINE},
    {BMP_LAYOUT_HEAD02A, BMP_LAYOUT_HEAD02A_H, STR_AL_TITLE_VERT_OUTLINE_CLIPART,   WritingMode_TB_RL, AUTOLAYOUT_TITLE_VERTICAL_OUTLINE_CLIPART},
    {0, 0, 0, WritingMode_LR_TB, AUTOLAYOUT_NONE}
};

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

static void fillLayoutValueSet( ValueSet* pValue, snewfoil_value_info* pInfo, const bool bHighContrast )
{
    Size aLayoutItemSize;
    for( ; pInfo->mnBmpResId; pInfo++ )
    {
        String aText( SdResId( pInfo->mnStrResId ) );
        BitmapEx aBmp( SdResId( (bHighContrast ? pInfo->mnHCBmpResId : pInfo->mnBmpResId) ) );

        pValue->InsertItem( static_cast<USHORT>(pInfo->maAutoLayout)+1, aBmp, aText );

        aLayoutItemSize.Width() = std::max( aLayoutItemSize.Width(), aBmp.GetSizePixel().Width() );
        aLayoutItemSize.Height() = std::max( aLayoutItemSize.Height(), aBmp.GetSizePixel().Height() );
    }

    aLayoutItemSize = pValue->CalcItemSizePixel( aLayoutItemSize );
    pValue->SetSizePixel( pValue->CalcWindowSizePixel( aLayoutItemSize ) );
}

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

SdLayoutDialogContent::SdLayoutDialogContent( ViewShellBase& rBase, ::Window* pParent, const bool bInsertPage )
: ToolbarMenu(rBase.GetFrame()->GetTopFrame()->GetFrameInterface(), pParent, SdResId( DLG_LAYOUTDIALOG ) /*WB_CLIPCHILDREN|WB_DIALOGCONTROL|WB_SYSTEMWINDOW|WB_MOVEABLE|WB_SIZEABLE|WB_CLOSEABLE*/)
, mrBase(rBase)
, mbInsertPage( bInsertPage )
, mpLayoutSet1( 0 )
, mpLayoutSet2( 0 )
, msAssignLayout( RTL_CONSTASCII_USTRINGPARAM( ".uno:AssignLayout" ) )
{
    String aTitle1( SdResId( STR_HORIZONTAL_LAYOUTS ) );
    String aTitle2( SdResId( STR_VERTICAL_LAYOUTS ) );

    FreeResource();

    const Color aMenuColor( GetSettings().GetStyleSettings().GetMenuColor() );
    const Color aMenuBarColor( GetSettings().GetStyleSettings().GetMenuBarColor() );
    const Color aMenuTextColor( GetSettings().GetStyleSettings().GetMenuBarColor() );
    const Color aMenuBarTextColor( GetSettings().GetStyleSettings().GetMenuBarTextColor() );

    const bool bHighContrast = GetSettings().GetStyleSettings().GetHighContrastMode();
    SvtLanguageOptions aLanguageOptions;
    const bool bVerticalEnabled = aLanguageOptions.IsVerticalTextEnabled();

    SetSelectHdl( LINK( this, SdLayoutDialogContent, SelectHdl ) );

    mpLayoutSet1 = new ValueSet( this, WB_TABSTOP | /* WB_MENUSTYLEVALUESET | */ WB_FLATVALUESET | WB_NOBORDER | WB_NO_DIRECTSELECT );
//  mpLayoutSet1->SetHelpId( HID_VALUESET_EXTRUSION_LIGHTING );

    mpLayoutSet1->SetSelectHdl( LINK( this, SdLayoutDialogContent, SelectHdl ) );
    mpLayoutSet1->SetColCount( 4 );
    mpLayoutSet1->EnableFullItemMode( FALSE );
    mpLayoutSet1->SetColor( GetControlBackground() );

    fillLayoutValueSet( mpLayoutSet1, &standard[0], bHighContrast );

    if( bVerticalEnabled )
        appendEntry( -1, aTitle1 );
    appendEntry( 0, mpLayoutSet1 );

    if( bVerticalEnabled )
    {
        mpLayoutSet2 = new ValueSet( this, WB_TABSTOP | /* WB_MENUSTYLEVALUESET | */ WB_FLATVALUESET | WB_NOBORDER | WB_NO_DIRECTSELECT );
    //  mpLayoutSet2->SetHelpId( HID_VALUESET_EXTRUSION_LIGHTING );

        mpLayoutSet2->SetSelectHdl( LINK( this, SdLayoutDialogContent, SelectHdl ) );
        mpLayoutSet2->SetColCount( 4 );
        mpLayoutSet2->EnableFullItemMode( FALSE );
        mpLayoutSet2->SetColor( GetControlBackground() );

        fillLayoutValueSet( mpLayoutSet2, &v_standard[0], bHighContrast );

        appendEntry( -1, aTitle2 );
        appendEntry( 1, mpLayoutSet2 );
    }

    //appendSeparator();

    OUString sSlotStr;
    Image aSlotImage;
    Reference< XFrame > xFrame( GetFrame(), UNO_QUERY );
    if( xFrame.is() )
    {
        if( bInsertPage )
            sSlotStr = OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:DuplicatePage" ) );
        else
            sSlotStr = OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:Undo" ) );
        aSlotImage = ::GetImage( xFrame, sSlotStr, FALSE, FALSE );
    }

    String sSlotTitle;
    if( bInsertPage )
        sSlotTitle = mrBase.RetrieveLabelFromCommand( sSlotStr );
    else
        sSlotTitle = String( SdResId( STR_RESET_LAYOUT ) );
    appendEntry( 2, sSlotTitle, aSlotImage);

    SetOutputSizePixel( getMenuSize() );

    AddStatusListener( msAssignLayout );
}

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

SdLayoutDialogContent::~SdLayoutDialogContent()
{
}

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

/*
void SdLayoutDialogContent::DataChanged( const DataChangedEvent& rDCEvt )
{
    SfxDockingWindow::DataChanged( rDCEvt );

    if( ( rDCEvt.GetType() == DATACHANGED_SETTINGS ) && ( rDCEvt.GetFlags() & SETTINGS_STYLE ) )
    {
        // const bool bHighContrast = GetSettings().GetStyleSettings().GetHighContrastMode();

        // todo switch images
    }
}
*/

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

/*
void SdLayoutDialogContent::StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState )
{
    if( (nSID == SID_ASSIGN_LAYOUT) && (eState != SFX_ITEM_DISABLED) )
    {
        const SfxUInt32Item* pStateItem = dynamic_cast< const SfxUInt32Item* >(pState);
        if( pStateItem )
        {
            meCurrentLayout = static_cast< AutoLayout >( pStateItem->GetValue() );
            mpLayoutSet1->SelectItem( static_cast<USHORT>(meCurrentLayout)+1 );
        }
    }
}
*/

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

IMPL_LINK( SdLayoutDialogContent, SelectHdl, void *, pControl )
{
    if ( IsInPopupMode() )
        EndPopupMode();

    if( mrBase.GetMainViewShell().get() && mrBase.GetMainViewShell()->GetViewFrame() )
    {
        if( pControl == mpLayoutSet1 )
        {
            AutoLayout eLayout = static_cast< AutoLayout >(mpLayoutSet1->GetSelectItemId()-1);

            const SfxUInt32Item aItem(ID_VAL_WHATLAYOUT, eLayout);
            mrBase.GetMainViewShell()->GetViewFrame()->GetBindings().GetDispatcher()->Execute(mbInsertPage ? SID_INSERTPAGE : SID_ASSIGN_LAYOUT,SFX_CALLMODE_ASYNCHRON,&aItem,0);
        }
        else if( pControl == mpLayoutSet2 )
        {
            AutoLayout eLayout = static_cast< AutoLayout >(mpLayoutSet2->GetSelectItemId()-1);

            const SfxUInt32Item aItem(ID_VAL_WHATLAYOUT, eLayout);
            mrBase.GetMainViewShell()->GetViewFrame()->GetBindings().GetDispatcher()->Execute(mbInsertPage ? SID_INSERTPAGE : SID_ASSIGN_LAYOUT,SFX_CALLMODE_ASYNCHRON,&aItem,0);
        }
        else
        {
            // reset autolayout
            mrBase.GetMainViewShell()->GetViewFrame()->GetBindings().GetDispatcher()->Execute( mbInsertPage ? SID_DUPLICATE_PAGE : SID_ASSIGN_LAYOUT,SFX_CALLMODE_ASYNCHRON);
        }
    }

    return 0;
}

void SAL_CALL SdLayoutDialogContent::statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event ) throw ( ::com::sun::star::uno::RuntimeException )
{
    if( Event.FeatureURL.Main.equals( msAssignLayout ) )
    {
        sal_Int32 nLayout = 0;
        Event.State >>= nLayout;
        OSL_TRACE("SdLayoutDialogContent::statusChanged(%ld)", nLayout );
    }
}

} // end of namespace sd
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2007, 2008, 2009, 2010, 2011, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

/// \file urbi/uvalue.hh
#ifndef URBI_UVALUE_HH
# define URBI_UVALUE_HH

# include <libport/warning-push.hh>

# include <vector>

# include <libport/hash.hh>
# include <libport/preproc.hh>
# include <libport/traits.hh>
# include <libport/ufloat.h>

# include <urbi/fwd.hh>
# include <urbi/export.hh>
# include <urbi/ubinary.hh>

namespace urbi
{

  /*--------------------------.
  | Free standing functions.  |
  `--------------------------*/

  /// If a kernel version was associated to this stream, its value.
  URBI_SDK_API
  int& kernelMajor(std::ostream& o);

  /// Issue a syncline.
  /// \param srcdir   the path from here to the top-srcdir.
  ///                 Will be removed from file.
  /// \param file     __FILE__
  /// \param line     __LINE__
  URBI_SDK_API
  std::string
  syncline_push(const std::string& srcdir, std::string file, unsigned line);

#define SYNCLINE_PUSH()                                         \
  "//#push " BOOST_PP_STRINGIZE(__LINE__) " \"" __FILE__ "\"\n"

#define SYNCLINE_POP()                          \
  "//#pop\n"

#ifndef __SRCDIR__
# define __SRCDIR__ ""
#endif

#define SYNCLINE_WRAP(...)                                      \
  (::urbi::syncline_push(__SRCDIR__, __FILE__, __LINE__)        \
   + libport::format(__VA_ARGS__)                               \
   + "\n"                                                       \
   SYNCLINE_POP())

  // UValue and other related types

  /// Possible value types a UValue can contain.
  enum UDataType
  {
    DATA_BINARY = 0,
    DATA_DICTIONARY = 1,
    DATA_DOUBLE = 2,
    DATA_LIST = 3,
    // No longer supported. DATA_OBJECT = 4,
    DATA_STRING = 5,
    DATA_SLOTNAME = 6,
    DATA_VOID = 7,
  };

  /*--------.
  | UList.  |
  `--------*/

  /// Class storing URBI List type
  class URBI_SDK_API UList
  {
  public:
    UList();
    UList(const UList &b);
    ~UList();

    UList& operator=(const UList &b);

    // Assign a container to the UList
    template<typename T>
    UList& operator=(const T& container);

    UList& operator=(UVar& v);

    // Transform the UList to a container.
    template<typename T>
    T as();

    /// Iteration.
    typedef std::vector<UValue*> list_type;
    typedef list_type::iterator iterator;
    typedef list_type::const_iterator const_iterator;
    iterator begin();
    iterator end();
    const_iterator begin() const;
    const_iterator end() const;

    // Append an element to the end.
    template<typename T>
    UList&
    push_back(const T& v);

    void pop_back();

    UValue& front();

    UValue& operator[](size_t i);
    const UValue& operator[](size_t i) const;

    size_t size() const;
    void setOffset(size_t n);

    std::ostream& print(std::ostream& o) const;

    // The actual contents.
    list_type array;

  private:
    void clear();
    size_t offset;
    friend class UValue;
  };

  URBI_SDK_API
  std::ostream& operator<< (std::ostream& o, const UList& t);

  /*--------------.
  | UDictionary.  |
  `--------------*/

  typedef boost::unordered_map<std::string, UValue> UDictionary;

  std::ostream& operator<<(std::ostream& s, const UDictionary& d);

  /*--------------.
  | UNamedValue.  |
  `--------------*/

  class URBI_SDK_API UNamedValue
  {
  public:
    UNamedValue(const std::string& n = "", UValue* v = 0);
    // Used on errors.
    static UNamedValue& error();
    std::string name;
    UValue* val;
  };

  /*---------.
  | UValue.  |
  `---------*/

  /** Container for a value that handles all types known to URBI.
   */
  class URBI_SDK_API UValue
  {
  public:
    UDataType type;

    ufloat val;                 ///< value if of type DATA_DOUBLE
    union
    {
      std::string* stringValue; ///< value if of type DATA_STRING
      UBinary* binary;          ///< value if of type DATA_BINARY
      UList* list;              ///< value if of type DATA_LIST
      UDictionary* dictionary;  ///< value if of type DATA_DICTIONARY
      void* storage;            ///< internal
    };

    UValue();
    UValue(const UValue&);

    ~UValue();

    UValue& operator=(const UValue&);
    /// Setter. If copy is false, binary data if present is not copied.
    /// This is dangerous, as the user must ensure that the source UValue
    /// lives longer than this one.
    UValue& set(const UValue&, bool copy=true);
    /// Delete content and reset type to void.
    void clear();
    /// A specific UValue used when we want to return an error.
    /// For instance, out-of-bound access returns this object.
    static UValue& error();

    /// We use an operator , that behaves like an assignment.  The
    /// only difference is when the rhs is void, in which case it is
    /// the regular comma which is used.  This allows to write "uval,
    /// expr" to mean "compute expr and assign its result to uval,
    /// unless expr is void".
    UValue& operator, (const UValue &b);

    /// Return a legible definition of UDataType
    const char* format_string() const;

#define CTOR_AND_ASSIGN_AND_COMMA(Type)           \
    explicit UValue(Type, bool copy=true);	  \
    UValue& operator=(Type);			  \
    UValue& operator,(Type rhs);

// Types convertibles to DATA_DOUBLE
#define URBI_DERIVED_NUMERIC_TYPES                     \
  LIBPORT_LIST(int, long, unsigned int, unsigned long, \
               unsigned long long, long long,)

#define URBI_NUMERIC_TYPES                                     \
  LIBPORT_LIST(ufloat, int, long, unsigned int, unsigned long, \
               unsigned long long, long long,)

// Types convertibles to DATA_STRING
#define URBI_STRING_TYPES \
  LIBPORT_LIST(const char*, const void*, const std::string&,)

#define URBI_MISC_TYPES                                          \
  LIBPORT_LIST(const UBinary&, const UList&, const UDictionary&, \
               const USound&, const UImage&,)

# ifndef SWIG
    LIBPORT_LIST_APPLY(CTOR_AND_ASSIGN_AND_COMMA, URBI_NUMERIC_TYPES)
    LIBPORT_LIST_APPLY(CTOR_AND_ASSIGN_AND_COMMA, URBI_STRING_TYPES)
    LIBPORT_LIST_APPLY(CTOR_AND_ASSIGN_AND_COMMA, URBI_MISC_TYPES)
# else
    // UFloats.
    CTOR_AND_ASSIGN_AND_COMMA(ufloat);
    CTOR_AND_ASSIGN_AND_COMMA(int);
    CTOR_AND_ASSIGN_AND_COMMA(long);
    CTOR_AND_ASSIGN_AND_COMMA(unsigned int);
    CTOR_AND_ASSIGN_AND_COMMA(unsigned long);
    CTOR_AND_ASSIGN_AND_COMMA(unsigned long long);
    CTOR_AND_ASSIGN_AND_COMMA(long long);

    // Strings.
    CTOR_AND_ASSIGN_AND_COMMA(const char*);
    CTOR_AND_ASSIGN_AND_COMMA(const void*);
    CTOR_AND_ASSIGN_AND_COMMA(const std::string&);

    // Others.
    CTOR_AND_ASSIGN_AND_COMMA(const UBinary&);
    CTOR_AND_ASSIGN_AND_COMMA(const UList&);
    CTOR_AND_ASSIGN_AND_COMMA(const UDictionary&);
    CTOR_AND_ASSIGN_AND_COMMA(const USound&);
    CTOR_AND_ASSIGN_AND_COMMA(const UImage&);
# endif

#undef CTOR_AND_ASSIGN_AND_COMMA

#define CAST_OPERATOR(Type) \
    operator Type() const;

# ifndef SWIG
    LIBPORT_LIST_APPLY(CAST_OPERATOR, URBI_NUMERIC_TYPES)
# else
    operator ufloat() const;
    operator std::string() const;
    operator int() const;
    operator unsigned int() const;
    operator long() const;
    operator unsigned long() const;
    operator bool() const;
# endif
#undef CAST_OPERATOR

#ifdef DOXYGEN
    // Doxygens needs a prototype for ufloat.
    operator ufloat() const;
#endif

    operator std::string() const;
    operator bool() const;

    /// Accessor. Gives us an implicit operator UBinary() const
    operator const UBinary&() const;

    /// Deep copy.
    operator UList() const;

    /// Deep copy.
    operator UDictionary() const;

    /// Shallow copy.
    ATTRIBUTE_PURE
    operator UImage() const;

    /// Shallow copy.
    ATTRIBUTE_PURE
    operator USound() const;

    /// This operator does nothing, but helps with the previous operator,.
    /// Indeed, when writing "uval, void_expr", the compiler complains
    /// about uval being evaluated for nothing.  Let's have it believe
    /// we're doing something...
    UValue& operator()();

    /// Parse an uvalue in current message+pos, returns pos of end of
    /// match -pos of error if error.
    int parse(const char* message,
	      int pos,
	      const binaries_type& bins,
	      binaries_type::const_iterator& binpos);

    /// Print itself on \c s, and return it.
    std::ostream& print(std::ostream& s) const;

    // Huge hack.
    static const bool copy = true;
  };

  std::ostream&
  operator<<(std::ostream& s, const UValue& v);

  /*----------.
  | Casters.  |
  `----------*/

  // For each Type, define an operator() that casts its UValue&
  // argument into Type.  We need partial specialization.

  template <typename Type>
  struct uvalue_caster
  {
  };

  // T -> UVar&  if T = UVar
  // T -> T      otherwise.
  template <typename T>
  struct uvar_ref_traits
  {
    typedef T type;
  };

  template <>
  struct uvar_ref_traits<UVar>
  {
    typedef UVar& type;
  };

  // Run the uvalue_caster<Type> on v.

  /* NM: Why exactly are we moving the const away?
   * I'm dropping it for UValue as it makes unnecessary copy.
   */

   template<typename T> struct uvalue_cast_return_type
   {
     typedef typename libport::traits::remove_reference<T>::type type;
   };

   template<> struct uvalue_cast_return_type<const UValue&>
   {
     typedef const UValue& type;
   };

  template <typename Type>
  typename uvar_ref_traits<typename uvalue_cast_return_type<Type>::type>::type
  uvalue_cast (UValue& v);

} // namespace urbi

#define URBI_STRUCT_CAST_FIELD(_, Cname, Field)                         \
  if (libport::has(dict, BOOST_PP_STRINGIZE(Field)))                   \
    uvalue_cast_bounce(res.Field, dict[BOOST_PP_STRINGIZE(Field)]);     \
  else                                                                  \
    GD_WARN("Serialized data for " #Cname "is missing field"            \
            BOOST_PP_STRINGIZE(Field));                                 \

#define URBI_STRUCT_BCAST_FIELD(_, Cname, Field)        \
  dict[BOOST_PP_STRINGIZE(Field)], c.Field;

#define URBI_REGISTER_STRUCT(Cname, ...)                                \
  namespace urbi                                                        \
  {                                                                     \
    template<>                                                          \
      struct uvalue_caster<Cname>                                       \
    {                                                                   \
      Cname operator()(UValue& v)                                       \
      {                                                                 \
        if (v.type != DATA_DICTIONARY)                                  \
          throw std::runtime_error("invalid cast to " #Cname "from "    \
                                   + string_cast(v));                   \
        UDictionary& dict = *v.dictionary;                              \
        Cname res;                                                      \
        LIBPORT_VAARGS_APPLY(URBI_STRUCT_CAST_FIELD, Cname, __VA_ARGS__); \
        return res;                                                     \
      }                                                                 \
    };                                                                  \
                                                                        \
    static UValue& operator,(UValue& v, const Cname &c)                 \
    {                                                                   \
      v = UDictionary();                                                \
      UDictionary& dict = *v.dictionary;                                \
      dict["$sn"] = BOOST_PP_STRINGIZE(Cname);                          \
      LIBPORT_VAARGS_APPLY(URBI_STRUCT_BCAST_FIELD, Cname, __VA_ARGS__); \
      return v;                                                         \
    }                                                                   \
  }

/** Packed data structure.
 *  This template class behaves exactly as a std::vector, except it gets
 *  serialized efficiently in a Binary, whereas std::vector is converted in
 *  an urbiscript list.
 */
template<typename T> class UPackedData: public std::vector<T>
{
public:
  UPackedData() {};
  UPackedData(const std::vector<T>& src): std::vector<T>(src) {};
  template<typename I> UPackedData(I begin, I end):std::vector<T>(begin, end){};
};

# include <urbi/uvalue.hxx>

# include <libport/warning-pop.hh>

#endif // ! URBI_UVALUE_HH
<commit_msg>Swig: formatting changes.<commit_after>/*
 * Copyright (C) 2007, 2008, 2009, 2010, 2011, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

/// \file urbi/uvalue.hh
#ifndef URBI_UVALUE_HH
# define URBI_UVALUE_HH

# include <libport/warning-push.hh>

# include <vector>

# include <libport/hash.hh>
# include <libport/preproc.hh>
# include <libport/traits.hh>
# include <libport/ufloat.h>

# include <urbi/fwd.hh>
# include <urbi/export.hh>
# include <urbi/ubinary.hh>

namespace urbi
{

  /*--------------------------.
  | Free standing functions.  |
  `--------------------------*/

  /// If a kernel version was associated to this stream, its value.
  URBI_SDK_API
  int& kernelMajor(std::ostream& o);

  /// Issue a syncline.
  /// \param srcdir   the path from here to the top-srcdir.
  ///                 Will be removed from file.
  /// \param file     __FILE__
  /// \param line     __LINE__
  URBI_SDK_API
  std::string
  syncline_push(const std::string& srcdir, std::string file, unsigned line);

# define SYNCLINE_PUSH()                                        \
  "//#push " BOOST_PP_STRINGIZE(__LINE__) " \"" __FILE__ "\"\n"

# define SYNCLINE_POP()                         \
  "//#pop\n"

# ifndef __SRCDIR__
#  define __SRCDIR__ ""
# endif

# define SYNCLINE_WRAP(...)                                     \
  (::urbi::syncline_push(__SRCDIR__, __FILE__, __LINE__)        \
   + libport::format(__VA_ARGS__)                               \
   + "\n"                                                       \
   SYNCLINE_POP())

  // UValue and other related types

  /// Possible value types a UValue can contain.
  enum UDataType
  {
    DATA_BINARY = 0,
    DATA_DICTIONARY = 1,
    DATA_DOUBLE = 2,
    DATA_LIST = 3,
    // No longer supported. DATA_OBJECT = 4,
    DATA_STRING = 5,
    DATA_SLOTNAME = 6,
    DATA_VOID = 7,
  };

  /*--------.
  | UList.  |
  `--------*/

  /// Class storing URBI List type
  class URBI_SDK_API UList
  {
  public:
    UList();
    UList(const UList &b);
    ~UList();

    UList& operator=(const UList &b);

    // Assign a container to the UList
    template<typename T>
    UList& operator=(const T& container);

    UList& operator=(UVar& v);

    // Transform the UList to a container.
    template<typename T>
    T as();

    /// Iteration.
    typedef std::vector<UValue*> list_type;
    typedef list_type::iterator iterator;
    typedef list_type::const_iterator const_iterator;
    iterator begin();
    iterator end();
    const_iterator begin() const;
    const_iterator end() const;

    // Append an element to the end.
    template<typename T>
    UList&
    push_back(const T& v);

    void pop_back();

    UValue& front();

    UValue& operator[](size_t i);
    const UValue& operator[](size_t i) const;

    size_t size() const;
    void setOffset(size_t n);

    std::ostream& print(std::ostream& o) const;

    // The actual contents.
    list_type array;

  private:
    void clear();
    size_t offset;
    friend class UValue;
  };

  URBI_SDK_API
  std::ostream& operator<< (std::ostream& o, const UList& t);

  /*--------------.
  | UDictionary.  |
  `--------------*/

  typedef boost::unordered_map<std::string, UValue> UDictionary;

  std::ostream& operator<<(std::ostream& s, const UDictionary& d);

  /*--------------.
  | UNamedValue.  |
  `--------------*/

  class URBI_SDK_API UNamedValue
  {
  public:
    UNamedValue(const std::string& n = "", UValue* v = 0);
    // Used on errors.
    static UNamedValue& error();
    std::string name;
    UValue* val;
  };

  /*---------.
  | UValue.  |
  `---------*/

  /** Container for a value that handles all types known to URBI.
   */
  class URBI_SDK_API UValue
  {
  public:
    UDataType type;

    ufloat val;                 ///< value if of type DATA_DOUBLE
    union
    {
      std::string* stringValue; ///< value if of type DATA_STRING
      UBinary* binary;          ///< value if of type DATA_BINARY
      UList* list;              ///< value if of type DATA_LIST
      UDictionary* dictionary;  ///< value if of type DATA_DICTIONARY
      void* storage;            ///< internal
    };

    UValue();
    UValue(const UValue&);

    ~UValue();

    UValue& operator=(const UValue&);
    /// Setter. If copy is false, binary data if present is not copied.
    /// This is dangerous, as the user must ensure that the source UValue
    /// lives longer than this one.
    UValue& set(const UValue&, bool copy=true);
    /// Delete content and reset type to void.
    void clear();
    /// A specific UValue used when we want to return an error.
    /// For instance, out-of-bound access returns this object.
    static UValue& error();

    /// We use an operator , that behaves like an assignment.  The
    /// only difference is when the rhs is void, in which case it is
    /// the regular comma which is used.  This allows to write "uval,
    /// expr" to mean "compute expr and assign its result to uval,
    /// unless expr is void".
    UValue& operator, (const UValue &b);

    /// Return a legible definition of UDataType
    const char* format_string() const;

#define CTOR_AND_ASSIGN_AND_COMMA(Type)           \
    explicit UValue(Type, bool copy=true);	  \
    UValue& operator=(Type);			  \
    UValue& operator,(Type rhs);

// Types convertibles to DATA_DOUBLE
#define URBI_DERIVED_NUMERIC_TYPES                     \
  LIBPORT_LIST(int, long, unsigned int, unsigned long, \
               unsigned long long, long long,)

#define URBI_NUMERIC_TYPES                                     \
  LIBPORT_LIST(ufloat, int, long, unsigned int, unsigned long, \
               unsigned long long, long long,)

// Types convertibles to DATA_STRING
#define URBI_STRING_TYPES \
  LIBPORT_LIST(const char*, const void*, const std::string&,)

#define URBI_MISC_TYPES                                          \
  LIBPORT_LIST(const UBinary&, const UList&, const UDictionary&, \
               const USound&, const UImage&,)

# ifndef SWIG
    LIBPORT_LIST_APPLY(CTOR_AND_ASSIGN_AND_COMMA, URBI_NUMERIC_TYPES)
    LIBPORT_LIST_APPLY(CTOR_AND_ASSIGN_AND_COMMA, URBI_STRING_TYPES)
    LIBPORT_LIST_APPLY(CTOR_AND_ASSIGN_AND_COMMA, URBI_MISC_TYPES)
# else
    // UFloats.
    CTOR_AND_ASSIGN_AND_COMMA(ufloat);
    CTOR_AND_ASSIGN_AND_COMMA(int);
    CTOR_AND_ASSIGN_AND_COMMA(long);
    CTOR_AND_ASSIGN_AND_COMMA(unsigned int);
    CTOR_AND_ASSIGN_AND_COMMA(unsigned long);
    CTOR_AND_ASSIGN_AND_COMMA(unsigned long long);
    CTOR_AND_ASSIGN_AND_COMMA(long long);

    // Strings.
    CTOR_AND_ASSIGN_AND_COMMA(const char*);
    CTOR_AND_ASSIGN_AND_COMMA(const void*);
    CTOR_AND_ASSIGN_AND_COMMA(const std::string&);

    // Others.
    CTOR_AND_ASSIGN_AND_COMMA(const UBinary&);
    CTOR_AND_ASSIGN_AND_COMMA(const UList&);
    CTOR_AND_ASSIGN_AND_COMMA(const UDictionary&);
    CTOR_AND_ASSIGN_AND_COMMA(const USound&);
    CTOR_AND_ASSIGN_AND_COMMA(const UImage&);
# endif

#undef CTOR_AND_ASSIGN_AND_COMMA

#define CAST_OPERATOR(Type) \
    operator Type() const;

# ifndef SWIG
    LIBPORT_LIST_APPLY(CAST_OPERATOR, URBI_NUMERIC_TYPES)
# else
    operator ufloat() const;
    operator std::string() const;
    operator int() const;
    operator unsigned int() const;
    operator long() const;
    operator unsigned long() const;
    operator bool() const;
# endif
#undef CAST_OPERATOR

#ifdef DOXYGEN
    // Doxygens needs a prototype for ufloat.
    operator ufloat() const;
#endif

    operator std::string() const;
    operator bool() const;

    /// Accessor. Gives us an implicit operator UBinary() const
    operator const UBinary&() const;

    /// Deep copy.
    operator UList() const;

    /// Deep copy.
    operator UDictionary() const;

    /// Shallow copy.
    ATTRIBUTE_PURE
    operator UImage() const;

    /// Shallow copy.
    ATTRIBUTE_PURE
    operator USound() const;

    /// This operator does nothing, but helps with the previous operator,.
    /// Indeed, when writing "uval, void_expr", the compiler complains
    /// about uval being evaluated for nothing.  Let's have it believe
    /// we're doing something...
    UValue& operator()();

    /// Parse an uvalue in current message+pos, returns pos of end of
    /// match -pos of error if error.
    int parse(const char* message,
	      int pos,
	      const binaries_type& bins,
	      binaries_type::const_iterator& binpos);

    /// Print itself on \c s, and return it.
    std::ostream& print(std::ostream& s) const;

    // Huge hack.
    static const bool copy = true;
  };

  std::ostream&
  operator<<(std::ostream& s, const UValue& v);

  /*----------.
  | Casters.  |
  `----------*/

  // For each Type, define an operator() that casts its UValue&
  // argument into Type.  We need partial specialization.

  template <typename Type>
  struct uvalue_caster
  {
  };

  // T -> UVar&  if T = UVar
  // T -> T      otherwise.
  template <typename T>
  struct uvar_ref_traits
  {
    typedef T type;
  };

  template <>
  struct uvar_ref_traits<UVar>
  {
    typedef UVar& type;
  };

  // Run the uvalue_caster<Type> on v.

  /* NM: Why exactly are we moving the const away?
   * I'm dropping it for UValue as it makes unnecessary copy.
   */

   template<typename T> struct uvalue_cast_return_type
   {
     typedef typename libport::traits::remove_reference<T>::type type;
   };

   template<> struct uvalue_cast_return_type<const UValue&>
   {
     typedef const UValue& type;
   };

  template <typename Type>
  typename uvar_ref_traits<typename uvalue_cast_return_type<Type>::type>::type
  uvalue_cast (UValue& v);

} // namespace urbi

# define URBI_STRUCT_CAST_FIELD(_, Cname, Field)                       \
  if (libport::has(dict, BOOST_PP_STRINGIZE(Field)))                   \
    uvalue_cast_bounce(res.Field, dict[BOOST_PP_STRINGIZE(Field)]);     \
  else                                                                  \
    GD_WARN("Serialized data for " #Cname "is missing field"            \
            BOOST_PP_STRINGIZE(Field));                                 \

# define URBI_STRUCT_BCAST_FIELD(_, Cname, Field)       \
  dict[BOOST_PP_STRINGIZE(Field)], c.Field;

# define URBI_REGISTER_STRUCT(Cname, ...)                               \
  namespace urbi                                                        \
  {                                                                     \
    template<>                                                          \
      struct uvalue_caster<Cname>                                       \
    {                                                                   \
      Cname operator()(UValue& v)                                       \
      {                                                                 \
        if (v.type != DATA_DICTIONARY)                                  \
          throw std::runtime_error("invalid cast to " #Cname "from "    \
                                   + string_cast(v));                   \
        UDictionary& dict = *v.dictionary;                              \
        Cname res;                                                      \
        LIBPORT_VAARGS_APPLY(URBI_STRUCT_CAST_FIELD, Cname, __VA_ARGS__); \
        return res;                                                     \
      }                                                                 \
    };                                                                  \
                                                                        \
    static UValue& operator,(UValue& v, const Cname &c)                 \
    {                                                                   \
      v = UDictionary();                                                \
      UDictionary& dict = *v.dictionary;                                \
      dict["$sn"] = BOOST_PP_STRINGIZE(Cname);                          \
      LIBPORT_VAARGS_APPLY(URBI_STRUCT_BCAST_FIELD, Cname, __VA_ARGS__); \
      return v;                                                         \
    }                                                                   \
  }

/** Packed data structure.
 *  This template class behaves exactly as a std::vector, except it gets
 *  serialized efficiently in a Binary, whereas std::vector is converted in
 *  an urbiscript list.
 */
template<typename T> class UPackedData: public std::vector<T>
{
public:
  UPackedData()
  {}

  UPackedData(const std::vector<T>& src)
    : std::vector<T>(src)
  {}

  template<typename I>
  UPackedData(I begin, I end)
    :std::vector<T>(begin, end)
  {}
};

# include <urbi/uvalue.hxx>

# include <libport/warning-pop.hh>

#endif // ! URBI_UVALUE_HH
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "Problem2.h"

/*
https://projecteuler.net/problem=2
Even Fibonacci numbers
Problem 2
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
*/

int Problem2::FibonacciSumEven(int range)
{
    auto sum = 0;

    if (range >= 2)
    {
        sum += 2;
    }

    if (range == 8)
    {
        sum += 8;
    }

    return sum;
}

int Problem2::Fibonacci(int range)
{
    return -1;
}<commit_msg>green-commit - Fibonacci_Input1_Returns1<commit_after>#include "stdafx.h"
#include "Problem2.h"

/*
https://projecteuler.net/problem=2
Even Fibonacci numbers
Problem 2
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
*/

int Problem2::FibonacciSumEven(int range)
{
    auto sum = 0;

    if (range >= 2)
    {
        sum += 2;
    }

    if (range == 8)
    {
        sum += 8;
    }

    return sum;
}

int Problem2::Fibonacci(int range)
{
    return 1;
}<|endoftext|>


<commit_before>#ifndef BBPROJECTMANAGERCONSTANTS_HPP_INCLUDED
#define BBPROJECTMANAGERCONSTANTS_HPP_INCLUDED

#include <qglobal.h>

namespace BoostBuildProjectManager {
namespace Constants {

char const BOOSTBUILD[] = "Boost.Build";

char const PROJECT_CONTEXT[] = "BoostBuildProjectManager.ProjectContext";
char const PROJECT_ID[]      = "BoostBuildProjectManager.Project";

char const BUILDCONFIGURATION_ID[] = "BoostBuildProjectManager.BuildConfiguration";
char const BUILDSTEP_ID[] = "BoostBuildProjectManager.BuildStep";

char const TASK_PROJECT_READING[] = "BoostBuildProjectManager.Task.ProjectReading";

char const MIMETYPE_PROJECT[] = "text/x-boostbuild-project";
char const MIMETYPE_JAMFILE[] = "application/vnd.boostbuild.v2";
char const MIMETYPE_JAMFILE_FILES[]   = "application/vnd.qtcreator.boostbuild.files";
char const JAMFILE_FILES_EXT[] = ".qtcreator.files";
char const JAMFILE_INCLUDES_EXT[] = ".qtcreator.includes";

char const OUTPUT_PARSER[] = "Boost.Build Parser";

char const COMMAND_BB2[] = "b2";
char const COMMAND_BJAM[] = "bjam";

char const VARIANT_DEBUG[] = QT_TR_NOOP("Debug");
char const VARIANT_RELEASE[] = QT_TR_NOOP("Release");

bool const FileNotGenerated = false; // meaningful name for common boolean value

} // namespace Constants
} // namespace BoostBuildProjectManager

#endif // BBPROJECTMANAGERCONSTANTS_HPP_INCLUDED
<commit_msg>Add FileNotGenerated constant for boolean value<commit_after>#ifndef BBPROJECTMANAGERCONSTANTS_HPP_INCLUDED
#define BBPROJECTMANAGERCONSTANTS_HPP_INCLUDED

#include <qglobal.h>

namespace BoostBuildProjectManager {
namespace Constants {

char const BOOSTBUILD[] = "Boost.Build";

char const PROJECT_CONTEXT[] = "BoostBuildProjectManager.ProjectContext";
char const PROJECT_ID[]      = "BoostBuildProjectManager.Project";

char const BUILDCONFIGURATION_ID[] = "BoostBuildProjectManager.BuildConfiguration";
char const BUILDSTEP_ID[] = "BoostBuildProjectManager.BuildStep";

char const TASK_PROJECT_READING[] = "BoostBuildProjectManager.Task.ProjectReading";

char const MIMETYPE_PROJECT[] = "text/x-boostbuild-project";
char const MIMETYPE_JAMFILE[] = "application/vnd.boostbuild.v2";
char const MIMETYPE_JAMFILE_FILES[]   = "application/vnd.qtcreator.boostbuild.files";
char const JAMFILE_FILES_EXT[] = ".qtcreator.files";
char const JAMFILE_INCLUDES_EXT[] = ".qtcreator.includes";

char const OUTPUT_PARSER[] = "Boost.Build Parser";

char const COMMAND_BB2[] = "b2";
char const COMMAND_BJAM[] = "bjam";

char const VARIANT_DEBUG[] = QT_TR_NOOP("Debug");
char const VARIANT_RELEASE[] = QT_TR_NOOP("Release");

// Set meaningful names for common boolean values
bool const FileNotGenerated = false; // used with GeneratedFile
bool const ReturnValueNotIgnored = false; // used with BuildStep

} // namespace Constants
} // namespace BoostBuildProjectManager

#endif // BBPROJECTMANAGERCONSTANTS_HPP_INCLUDED
<|endoftext|>


<commit_before>#include "StdAfx.h"
#include "NakedDecoder.h"
/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2009-2014 Klaus Post
    Copyright (C) 2014 Pedro Côrte-Real

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

    http://www.klauspost.com
*/

namespace RawSpeed {

NakedDecoder::NakedDecoder(FileMap* file, Camera* c) :
    RawDecoder(file) {
  cam = c;
}

NakedDecoder::~NakedDecoder(void) {
}

RawImage NakedDecoder::decodeRawInternal() {
  uint32 width=0, height=0, filesize=0, bits=0, offset=0;
  if(cam->hints.find("full_width") != cam->hints.end()) {
    string tmp = cam->hints.find(string("full_width"))->second;
    width = (uint32) atoi(tmp.c_str());
  } else
    ThrowRDE("Naked: couldn't find width");

  if(cam->hints.find("full_height") != cam->hints.end()) {
    string tmp = cam->hints.find(string("full_height"))->second;
    height = (uint32) atoi(tmp.c_str());
  } else
    ThrowRDE("Naked: couldn't find height");

  if(cam->hints.find("filesize") != cam->hints.end()) {
    string tmp = cam->hints.find(string("filesize"))->second;
    filesize = (uint32) atoi(tmp.c_str());
  } else
    ThrowRDE("Naked: couldn't find filesize");

  if(cam->hints.find("offset") != cam->hints.end()) {
    string tmp = cam->hints.find(string("offset"))->second;
    height = (uint32) atoi(tmp.c_str());
  }

  if(cam->hints.find("bits") != cam->hints.end()) {
    string tmp = cam->hints.find(string("bits"))->second;
    bits = (uint32) atoi(tmp.c_str());
  } else
    bits = (filesize-offset)*8/width/height;

  mRaw->dim = iPoint2D(width, height);
  mRaw->createData();

  ByteStream input(mFile->getData(offset), mFile->getSize()-offset);
  iPoint2D pos(0, 0);
  readUncompressedRaw(input, mRaw->dim, pos, width*bits/8, bits, BitOrder_Jpeg16);

  return mRaw;
}

void NakedDecoder::checkSupportInternal(CameraMetaData *meta) {
  this->checkCameraSupported(meta, cam->make, cam->model, cam->mode);
}

void NakedDecoder::decodeMetaDataInternal(CameraMetaData *meta) {
  setMetaData(meta, cam->make, cam->model, cam->mode, 0);
}

} // namespace RawSpeed
<commit_msg>CHDK:  - Fix height being overwritten with offset and offset not being read.  - Add configurable byteorder.<commit_after>#include "StdAfx.h"
#include "NakedDecoder.h"
/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2009-2014 Klaus Post
    Copyright (C) 2014 Pedro Côrte-Real

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

    http://www.klauspost.com
*/

namespace RawSpeed {

NakedDecoder::NakedDecoder(FileMap* file, Camera* c) :
    RawDecoder(file) {
  cam = c;
}

NakedDecoder::~NakedDecoder(void) {
}

RawImage NakedDecoder::decodeRawInternal() {
  uint32 width=0, height=0, filesize=0, bits=0, offset=0;
  if(cam->hints.find("full_width") != cam->hints.end()) {
    string tmp = cam->hints.find(string("full_width"))->second;
    width = (uint32) atoi(tmp.c_str());
  } else
    ThrowRDE("Naked: couldn't find width");

  if(cam->hints.find("full_height") != cam->hints.end()) {
    string tmp = cam->hints.find(string("full_height"))->second;
    height = (uint32) atoi(tmp.c_str());
  } else
    ThrowRDE("Naked: couldn't find height");

  if(cam->hints.find("filesize") != cam->hints.end()) {
    string tmp = cam->hints.find(string("filesize"))->second;
    filesize = (uint32) atoi(tmp.c_str());
  } else
    ThrowRDE("Naked: couldn't find filesize");

  if(cam->hints.find("offset") != cam->hints.end()) {
    string tmp = cam->hints.find(string("offset"))->second;
    offset = (uint32) atoi(tmp.c_str());
  }

  if(cam->hints.find("bits") != cam->hints.end()) {
    string tmp = cam->hints.find(string("bits"))->second;
    bits = (uint32) atoi(tmp.c_str());
  } else
    bits = (filesize-offset)*8/width/height;

  BitOrder bo = BitOrder_Jpeg16;  // Default
  if(cam->hints.find("order") != cam->hints.end()) {
    string tmp = cam->hints.find(string("order"))->second;
    if (tmp.compare("plain") == 0) {
      bo = BitOrder_Plain;
    } else if (tmp.compare("jpeg") == 0) {
      bo = BitOrder_Jpeg;
    } else if (tmp.compare("jpeg16") == 0) {
      bo = BitOrder_Jpeg16;
    } else if (tmp.compare("jpeg32") == 0) {
      bo = BitOrder_Jpeg32;
    }
  }

  mRaw->dim = iPoint2D(width, height);
  mRaw->createData();

  ByteStream input(mFile->getData(offset), mFile->getSize()-offset);
  iPoint2D pos(0, 0);
  readUncompressedRaw(input, mRaw->dim, pos, width*bits/8, bits, bo);

  return mRaw;
}

void NakedDecoder::checkSupportInternal(CameraMetaData *meta) {
  this->checkCameraSupported(meta, cam->make, cam->model, cam->mode);
}

void NakedDecoder::decodeMetaDataInternal(CameraMetaData *meta) {
  setMetaData(meta, cam->make, cam->model, cam->mode, 0);
}

} // namespace RawSpeed
<|endoftext|>


<commit_before>#include "offeracceptdialogbtc.h"
#include "ui_offeracceptdialogbtc.h"
#include "init.h"
#include "util.h"
#include "offerpaydialog.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "platformstyle.h"
#include "syscoingui.h"
#include <QMessageBox>
#include "rpcserver.h"
#include "pubkey.h"
#include "wallet/wallet.h"
#include "main.h"
#include <QDesktopServices>
#if QT_VERSION < 0x050000
#include <QUrl>
#else
#include <QUrlQuery>
#endif
#include <QPixmap>
#if defined(HAVE_CONFIG_H)
#include "config/syscoin-config.h" /* for USE_QRCODE */
#endif

#ifdef USE_QRCODE
#include <qrencode.h>
#endif
using namespace std;
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>

extern const CRPCTable tableRPC;
OfferAcceptDialogBTC::OfferAcceptDialogBTC(const PlatformStyle *platformStyle, QString alias, QString offer, QString quantity, QString notes, QString title, QString currencyCode, QString qstrPrice, QString sellerAlias, QString address, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::OfferAcceptDialogBTC), platformStyle(platformStyle), alias(alias), offer(offer), notes(notes), quantity(quantity), title(title), sellerAlias(sellerAlias), address(address)
{
    ui->setupUi(this);
	QString theme = GUIUtil::getThemeName();
	ui->aboutShadeBTC->setPixmap(QPixmap(":/images/" + theme + "/about_btc"));
	double dblPrice = qstrPrice.toDouble()*quantity.toUInt();
	string strfPrice = strprintf("%f", dblPrice);
	QString fprice = QString::fromStdString(strfPrice);
	string strCurrencyCode = currencyCode.toStdString();
	ui->escrowDisclaimer->setText(tr("Please note escrow is not available since you are paying in BTC, only SYS payments can be escrowed. "));
	ui->bitcoinInstructionLabel->setText(tr("After paying for this item, please enter the Bitcoin Transaction ID and click on the confirm button below. You may use the QR Code to the left to scan the payment request into your wallet or click on the Open BTC Wallet if you are on the desktop and have Bitcoin Core installed."));
	ui->acceptMessage->setText(tr("Are you sure you want to purchase %1 of '%2' from merchant: '%3'? To complete your purchase please pay %4 BTC using your Bitcoin wallet.").arg(quantity).arg(title).arg(sellerAlias).arg(fprice));
	string strPrice = strprintf("%f", dblPrice);
	price = QString::fromStdString(strPrice);

	if (!platformStyle->getImagesOnButtons())
	{
		ui->confirmButton->setIcon(QIcon());
		ui->openBtcWalletButton->setIcon(QIcon());
		ui->cancelButton->setIcon(QIcon());

	}
	else
	{
		ui->confirmButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/transaction_confirmed"));
		ui->openBtcWalletButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/send"));
		ui->cancelButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/quit"));
	}
	this->offerPaid = false;
	connect(ui->confirmButton, SIGNAL(clicked()), this, SLOT(acceptPayment()));
	connect(ui->openBtcWalletButton, SIGNAL(clicked()), this, SLOT(openBTCWallet()));

#ifdef USE_QRCODE
	QString message = "Payment for offer ID " + this->offer + " on Syscoin Decentralized Marketplace";
	QString uri = "bitcoin:" + this->address + "?amount=" + price + "&label=" + this->sellerAlias + "&message=" + GUIUtil::HtmlEscape(message);

	ui->lblQRCode->setText("");
    if(!uri.isEmpty())
    {
        // limit URI length
        if (uri.length() > MAX_URI_LENGTH)
        {
            ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message."));
        } else {
            QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1);
            if (!code)
            {
                ui->lblQRCode->setText(tr("Error encoding URI into QR Code."));
                return;
            }
            QImage myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32);
            myImage.fill(0xffffff);
            unsigned char *p = code->data;
            for (int y = 0; y width; y++)
            {
                for (int x = 0; x width; x++)
                {
                    myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff));
                    p++;
                }
            }
            QRcode_free(code);
            ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(128, 128));
        }
    }
#endif
}
void OfferAcceptDialogBTC::on_cancelButton_clicked()
{
    reject();
}
OfferAcceptDialogBTC::~OfferAcceptDialogBTC()
{
    delete ui;
}

void OfferAcceptDialogBTC::acceptPayment()
{
	acceptOffer();
}
bool OfferAcceptDialogBTC::CheckPaymentInBTC(const QString &strBTCTxId, const QString& address, const QString& price)
{
	QNetworkAccessManager *nam = new QNetworkAccessManager(this);
	QUrl url("https://blockchain.info/tx/" + strBTCTxId + "?format=json");
	QNetworkRequest request(url);
	request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
	QNetworkReply* reply = nam->get(request);
	reply->ignoreSslErrors();
	int totalTime = 0;
	while(!reply->isFinished())
	{
		qApp->processEvents();
		totalTime += 100;
		MilliSleep(100);
		if(totalTime > 30000)
			throw runtime_error("Timeout connecting to blockchain.info!");
	}
	if(reply->error() == QNetworkReply::NoError) {

		UniValue outerValue;
		bool read = outerValue.read(reply->readAll().toStdString());
		if (read)
		{
			LogPrintf("gotjson!\n");
			UniValue outerObj = outerValue.get_obj();
			UniValue ratesValue = find_value(outerObj, "rates");
			if (ratesValue.isArray())
			{
			}
		}
	}
	reply->deleteLater();
	return false;

}

bool OfferAcceptDialogBTC::lookup(const QString &lookupid, QString& address, QString& price)
{
	string strError;
	string strMethod = string("offerinfo");
	UniValue params(UniValue::VARR);
	UniValue result;
	params.push_back(lookupid.toStdString());

    try {
        result = tableRPC.execute(strMethod, params);

		if (result.type() == UniValue::VOBJ)
		{
			const UniValue &offerObj = result.get_obj();

			const string &strAddress = find_value(offerObj, "address").get_str();
			const string &strPrice = find_value(offerObj, "price").get_str();
			address = QString::fromStdString(strAddress);
			price = QString::fromStdString(strPrice);
			return true;
		}
	}
	catch (UniValue& objError)
	{
		QMessageBox::critical(this, windowTitle(),
			tr("Could not find this offer, please check the offer ID and that it has been confirmed by the blockchain: ") + lookupid,
				QMessageBox::Ok, QMessageBox::Ok);
		return true;

	}
	catch(std::exception& e)
	{
		QMessageBox::critical(this, windowTitle(),
			tr("There was an exception trying to locate this offer, please check the offer ID and that it has been confirmed by the blockchain: ") + QString::fromStdString(e.what()),
				QMessageBox::Ok, QMessageBox::Ok);
		return true;
	}
	return false;

}
// send offeraccept with offer guid/qty as params and then send offerpay with wtxid (first param of response) as param, using RPC commands.
void OfferAcceptDialogBTC::acceptOffer()
{
		QString address, price;
		if (ui->btctxidEdit->text().trimmed().isEmpty()) {
            ui->btctxidEdit->setText("");
            QMessageBox::information(this, windowTitle(),
            tr("Please enter a valid Bitcoin Transaction ID into the input box and try again"),
                QMessageBox::Ok, QMessageBox::Ok);
            return;
        }
		if(!lookup(this->offer, address, price))
		{
            QMessageBox::information(this, windowTitle(),
            tr("Could not find this offer, please check the offer ID and that it has been confirmed by the blockchain: ") + this->offer,
                QMessageBox::Ok, QMessageBox::Ok);
            return;
		}
		if(!CheckPaymentInBTC(ui->btctxidEdit->text().trimmed(), address, price))
		{
            QMessageBox::information(this, windowTitle(),
            tr("Could not find this payment, please check the Transaction ID and that it has been confirmed by the Bitcoin blockchain: ") + ui->btctxidEdit->text().trimmed(),
                QMessageBox::Ok, QMessageBox::Ok);
            return;
		}

		UniValue params(UniValue::VARR);
		UniValue valError;
		UniValue valResult;
		UniValue valId;
		UniValue result ;
		string strReply;
		string strError;

		string strMethod = string("offeraccept");
		if(this->quantity.toLong() <= 0)
		{
			QMessageBox::critical(this, windowTitle(),
				tr("Invalid quantity when trying to accept offer!"),
				QMessageBox::Ok, QMessageBox::Ok);
			return;
		}
		this->offerPaid = false;
		params.push_back(this->alias.toStdString());
		params.push_back(this->offer.toStdString());
		params.push_back(this->quantity.toStdString());
		params.push_back(this->notes.toStdString());
		params.push_back(ui->btctxidEdit->text().toStdString());

	    try {
            result = tableRPC.execute(strMethod, params);
			if (result.type() != UniValue::VNULL)
			{
				const UniValue &arr = result.get_array();
				string strResult = arr[0].get_str();
				QString offerAcceptTXID = QString::fromStdString(strResult);
				if(offerAcceptTXID != QString(""))
				{
					OfferPayDialog dlg(platformStyle, this->title, this->quantity, this->price, "BTC", this);
					dlg.exec();
					this->offerPaid = true;
					OfferAcceptDialogBTC::accept();
					return;

				}
			}
		}
		catch (UniValue& objError)
		{
			strError = find_value(objError, "message").get_str();
			QMessageBox::critical(this, windowTitle(),
			tr("Error accepting offer: \"%1\"").arg(QString::fromStdString(strError)),
				QMessageBox::Ok, QMessageBox::Ok);
			return;
		}
		catch(std::exception& e)
		{
			QMessageBox::critical(this, windowTitle(),
				tr("General exception when accepting offer"),
				QMessageBox::Ok, QMessageBox::Ok);
			return;
		}

}
void OfferAcceptDialogBTC::openBTCWallet()
{
	QString message = "Payment for offer ID " + this->offer + " on Syscoin Decentralized Marketplace";
	QString uri = "bitcoin:" + this->address + "?amount=" + price + "&label=" + this->sellerAlias + "&message=" + GUIUtil::HtmlEscape(message);
	QDesktopServices::openUrl(QUrl(uri, QUrl::TolerantMode));
}
bool OfferAcceptDialogBTC::getPaymentStatus()
{
	return this->offerPaid;
}
<commit_msg>work on CheckPaymentInBTC<commit_after>#include "offeracceptdialogbtc.h"
#include "ui_offeracceptdialogbtc.h"
#include "init.h"
#include "util.h"
#include "offerpaydialog.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "platformstyle.h"
#include "syscoingui.h"
#include <QMessageBox>
#include "rpcserver.h"
#include "pubkey.h"
#include "wallet/wallet.h"
#include "main.h"
#include <QDesktopServices>
#if QT_VERSION < 0x050000
#include <QUrl>
#else
#include <QUrlQuery>
#endif
#include <QPixmap>
#if defined(HAVE_CONFIG_H)
#include "config/syscoin-config.h" /* for USE_QRCODE */
#endif

#ifdef USE_QRCODE
#include <qrencode.h>
#endif
using namespace std;
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>

extern const CRPCTable tableRPC;
OfferAcceptDialogBTC::OfferAcceptDialogBTC(const PlatformStyle *platformStyle, QString alias, QString offer, QString quantity, QString notes, QString title, QString currencyCode, QString qstrPrice, QString sellerAlias, QString address, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::OfferAcceptDialogBTC), platformStyle(platformStyle), alias(alias), offer(offer), notes(notes), quantity(quantity), title(title), sellerAlias(sellerAlias), address(address)
{
    ui->setupUi(this);
	QString theme = GUIUtil::getThemeName();
	ui->aboutShadeBTC->setPixmap(QPixmap(":/images/" + theme + "/about_btc"));
	double dblPrice = qstrPrice.toDouble()*quantity.toUInt();
	string strfPrice = strprintf("%f", dblPrice);
	QString fprice = QString::fromStdString(strfPrice);
	string strCurrencyCode = currencyCode.toStdString();
	ui->escrowDisclaimer->setText(tr("Please note escrow is not available since you are paying in BTC, only SYS payments can be escrowed. "));
	ui->bitcoinInstructionLabel->setText(tr("After paying for this item, please enter the Bitcoin Transaction ID and click on the confirm button below. You may use the QR Code to the left to scan the payment request into your wallet or click on the Open BTC Wallet if you are on the desktop and have Bitcoin Core installed."));
	ui->acceptMessage->setText(tr("Are you sure you want to purchase %1 of '%2' from merchant: '%3'? To complete your purchase please pay %4 BTC using your Bitcoin wallet.").arg(quantity).arg(title).arg(sellerAlias).arg(fprice));
	string strPrice = strprintf("%f", dblPrice);
	price = QString::fromStdString(strPrice);

	if (!platformStyle->getImagesOnButtons())
	{
		ui->confirmButton->setIcon(QIcon());
		ui->openBtcWalletButton->setIcon(QIcon());
		ui->cancelButton->setIcon(QIcon());

	}
	else
	{
		ui->confirmButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/transaction_confirmed"));
		ui->openBtcWalletButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/send"));
		ui->cancelButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/quit"));
	}
	this->offerPaid = false;
	connect(ui->confirmButton, SIGNAL(clicked()), this, SLOT(acceptPayment()));
	connect(ui->openBtcWalletButton, SIGNAL(clicked()), this, SLOT(openBTCWallet()));

#ifdef USE_QRCODE
	QString message = "Payment for offer ID " + this->offer + " on Syscoin Decentralized Marketplace";
	QString uri = "bitcoin:" + this->address + "?amount=" + price + "&label=" + this->sellerAlias + "&message=" + GUIUtil::HtmlEscape(message);

	ui->lblQRCode->setText("");
    if(!uri.isEmpty())
    {
        // limit URI length
        if (uri.length() > MAX_URI_LENGTH)
        {
            ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message."));
        } else {
            QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1);
            if (!code)
            {
                ui->lblQRCode->setText(tr("Error encoding URI into QR Code."));
                return;
            }
            QImage myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32);
            myImage.fill(0xffffff);
            unsigned char *p = code->data;
            for (int y = 0; y width; y++)
            {
                for (int x = 0; x width; x++)
                {
                    myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff));
                    p++;
                }
            }
            QRcode_free(code);
            ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(128, 128));
        }
    }
#endif
}
void OfferAcceptDialogBTC::on_cancelButton_clicked()
{
    reject();
}
OfferAcceptDialogBTC::~OfferAcceptDialogBTC()
{
    delete ui;
}

void OfferAcceptDialogBTC::acceptPayment()
{
	acceptOffer();
}
bool OfferAcceptDialogBTC::CheckPaymentInBTC(const QString &strBTCTxId, const QString& address, const QString& price)
{
	QNetworkAccessManager *nam = new QNetworkAccessManager(this);
	QUrl url("https://blockchain.info/tx/" + strBTCTxId + "?format=json");
	QNetworkRequest request(url);
	request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
	QNetworkReply* reply = nam->get(request);
	reply->ignoreSslErrors();
	CAmount value;
	CAmount price;
	if(!ParseMoney(price.toStdString(), price))
		return false;
	LogPrintf("price: %lld\n", price);
	int totalTime = 0;
	while(!reply->isFinished())
	{
		qApp->processEvents();
		totalTime += 100;
		MilliSleep(100);
		if(totalTime > 30000)
			throw runtime_error("Timeout connecting to blockchain.info!");
	}
	bool doubleSpend = false;
	if(reply->error() == QNetworkReply::NoError) {

		UniValue outerValue;
		bool read = outerValue.read(reply->readAll().toStdString());
		if (read)
		{
			LogPrintf("gotjson!\n");
			UniValue outerObj = outerValue.get_obj();
			UniValue doubleSpendValue = find_value(outerObj, "double_spend");
			if (doubleSpendValue.isBool())
			{
				doubleSpend = doubleSpendValue.get_bool();
				if(!doubleSpend)
					return false;
			}
			UniValue outputsValue = find_value(outerObj, "out");
			if (outputsValue.isArray())
			{
				UniValue outputs = outputsValue.get_array();
				for (unsigned int idx = 0; idx < outputs.size(); idx++) {
					const UniValue& output = outputs[idx];
					UniValue addressValue = find_value(output, "addr");
					if(addressValue.isStr())
					{
						LogPrintf("address: %s\n", address.toStdString().c_str());
						if(addressValue.get_str() == address.toStdString())
						{
							UniValue paymentValue = find_value(output, "value");
							LogPrintf("value: %lld\n", paymentValue.get_int64());
							if(paymentValue.isNum())
							{
								value += paymentValue.get_int64();
								if(value >= price)
									return true;
							}
						}

					}

				}
			}
		}
	}
	reply->deleteLater();
	return false;

}

bool OfferAcceptDialogBTC::lookup(const QString &lookupid, QString& address, QString& price)
{
	string strError;
	string strMethod = string("offerinfo");
	UniValue params(UniValue::VARR);
	UniValue result;
	params.push_back(lookupid.toStdString());

    try {
        result = tableRPC.execute(strMethod, params);

		if (result.type() == UniValue::VOBJ)
		{
			const UniValue &offerObj = result.get_obj();

			const string &strAddress = find_value(offerObj, "address").get_str();
			const string &strPrice = find_value(offerObj, "price").get_str();
			address = QString::fromStdString(strAddress);
			price = QString::fromStdString(strPrice);
			return true;
		}
	}
	catch (UniValue& objError)
	{
		QMessageBox::critical(this, windowTitle(),
			tr("Could not find this offer, please check the offer ID and that it has been confirmed by the blockchain: ") + lookupid,
				QMessageBox::Ok, QMessageBox::Ok);
		return true;

	}
	catch(std::exception& e)
	{
		QMessageBox::critical(this, windowTitle(),
			tr("There was an exception trying to locate this offer, please check the offer ID and that it has been confirmed by the blockchain: ") + QString::fromStdString(e.what()),
				QMessageBox::Ok, QMessageBox::Ok);
		return true;
	}
	return false;

}
// send offeraccept with offer guid/qty as params and then send offerpay with wtxid (first param of response) as param, using RPC commands.
void OfferAcceptDialogBTC::acceptOffer()
{
		QString address, price;
		if (ui->btctxidEdit->text().trimmed().isEmpty()) {
            ui->btctxidEdit->setText("");
            QMessageBox::information(this, windowTitle(),
            tr("Please enter a valid Bitcoin Transaction ID into the input box and try again"),
                QMessageBox::Ok, QMessageBox::Ok);
            return;
        }
		if(!lookup(this->offer, address, price))
		{
            QMessageBox::information(this, windowTitle(),
            tr("Could not find this offer, please check the offer ID and that it has been confirmed by the blockchain: ") + this->offer,
                QMessageBox::Ok, QMessageBox::Ok);
            return;
		}
		if(!CheckPaymentInBTC(ui->btctxidEdit->text().trimmed(), address, price))
		{
            QMessageBox::information(this, windowTitle(),
            tr("Could not find this payment, please check the Transaction ID and that it has been confirmed by the Bitcoin blockchain: ") + ui->btctxidEdit->text().trimmed(),
                QMessageBox::Ok, QMessageBox::Ok);
            return;
		}

		UniValue params(UniValue::VARR);
		UniValue valError;
		UniValue valResult;
		UniValue valId;
		UniValue result ;
		string strReply;
		string strError;

		string strMethod = string("offeraccept");
		if(this->quantity.toLong() <= 0)
		{
			QMessageBox::critical(this, windowTitle(),
				tr("Invalid quantity when trying to accept offer!"),
				QMessageBox::Ok, QMessageBox::Ok);
			return;
		}
		this->offerPaid = false;
		params.push_back(this->alias.toStdString());
		params.push_back(this->offer.toStdString());
		params.push_back(this->quantity.toStdString());
		params.push_back(this->notes.toStdString());
		params.push_back(ui->btctxidEdit->text().toStdString());

	    try {
            result = tableRPC.execute(strMethod, params);
			if (result.type() != UniValue::VNULL)
			{
				const UniValue &arr = result.get_array();
				string strResult = arr[0].get_str();
				QString offerAcceptTXID = QString::fromStdString(strResult);
				if(offerAcceptTXID != QString(""))
				{
					OfferPayDialog dlg(platformStyle, this->title, this->quantity, this->price, "BTC", this);
					dlg.exec();
					this->offerPaid = true;
					OfferAcceptDialogBTC::accept();
					return;

				}
			}
		}
		catch (UniValue& objError)
		{
			strError = find_value(objError, "message").get_str();
			QMessageBox::critical(this, windowTitle(),
			tr("Error accepting offer: \"%1\"").arg(QString::fromStdString(strError)),
				QMessageBox::Ok, QMessageBox::Ok);
			return;
		}
		catch(std::exception& e)
		{
			QMessageBox::critical(this, windowTitle(),
				tr("General exception when accepting offer"),
				QMessageBox::Ok, QMessageBox::Ok);
			return;
		}

}
void OfferAcceptDialogBTC::openBTCWallet()
{
	QString message = "Payment for offer ID " + this->offer + " on Syscoin Decentralized Marketplace";
	QString uri = "bitcoin:" + this->address + "?amount=" + price + "&label=" + this->sellerAlias + "&message=" + GUIUtil::HtmlEscape(message);
	QDesktopServices::openUrl(QUrl(uri, QUrl::TolerantMode));
}
bool OfferAcceptDialogBTC::getPaymentStatus()
{
	return this->offerPaid;
}
<|endoftext|>


<commit_before>

#ifndef _CONF_H_
#define _CONF_H_

#include "utility.hpp"

#define VE_VERSION "r1.1.0-20150201"
#define VE_INFO "OpenCVR r1.1.0 2015"

#ifdef WIN32
#define VE_NVR_CLIENT
#else
#define VE_NVR
#endif

/* NVR Client feature */
#ifdef VE_NVR_CLIENT
#define VE_RECORDER_MGR_CLIENT_SUPPORT
#endif

/* NVR feature */
#ifdef VE_NVR
#define VE_RECORDER_MGR_SERVER_SUPPORT
#endif

#define CONF_NAME_MAX 128
/* support Camera num */
#define CONF_MAP_MAX 4096
#define CONF_USER_PASSWORD_MAX 1024
#define CONF_PATH_MAX 1024
/* 0xFF FFFF to 0xFFFF FFFF is for status for the map */
#define CONF_MAP_INVALID_MIN 0xFFFFFF
#define CONF_KEY_STR_MAX 16

/* Support VMS(site, recorder) num */
#define CONF_VMS_NUM_MAX 128
#define CONF_VIEW_NUM_MAX 128
/* IP camera Group max num */
#define CONF_VGROUP_NUM_MAX 128

#define VSC_CONF_KEY "ConfVSCSystem"
#define VSC_CONF_LIC_KEY "ConfVSCLicense"
#define VSC_CONF_CHANNEL_KEY "ConfVSCDevice"
#define VSC_CONF_VIPC_KEY "ConfVSCVIPC"
#define VSC_CONF_VMS_KEY "ConfVSCVms"
#define VSC_CONF_VIEW_KEY "ConfVSCView"
#define VSC_CONF_VGROUP_KEY "ConfVSCVGroup"
#define VSC_CONF_HDFS_RECORD_KEY "ConfVSCHdfsRec"
#define VSC_CONF_EMAP_FILE_KEY "ConfVSCEmapFile"
#define VSC_CONF_EMAP_CONF_KEY "ConfVSCEmapConf"
#define VSC_CONF_PARAM_MAX 1024
#define VSC_CONF_PARAM_S_MAX 128
/* Max camera in one view */
#define VSC_CONF_VIEW_CH_MAX 256
/* Max camera in one Group */
#define VSC_CONF_VGROUP_CH_MAX 256

typedef enum
{
    VSC_DEVICE_CAM = 1,
    VSC_DEVICE_RECORDER,

    VSC_DEVICE_LAST
} VSCDeviceType;

/* Device Type */
typedef enum
{
    VSC_SUB_DEVICE_USB_CAM = 1,
    VSC_SUB_DEVICE_FILE,
    VSC_SUB_DEVICE_RTSP,
    VSC_SUB_DEVICE_ONVIF,
    VSC_SUB_DEVICE_ONVIF_RECODER,
    VSC_SUB_DEVICE_GB28181,

    VSC_SUB_DEVICE_LAST
} VSCDeviceSubType;

typedef enum
{
    VSC_VMS_RECORDER = 1,
    VSC_VMS_SITE,
    VSC_VMS_VIRTUL_IPC,

    VSC_VMS_LAST
} VSCVmsType;

typedef enum
{
    VSC_SUB_VMS_PG = 1,
    VSC_SUB_VMS_ZB,
    VSC_SUB_VIPC_FILE,
    VSC_SUB_VIPC_LIVE,

    VSC_SUB_VMS_LAST
} VSCVmsSubType;

/* Control command */
typedef enum
{
    LAYOUT_MODE_1 = 1,
    LAYOUT_MODE_2X2,
    LAYOUT_MODE_3X3,
    LAYOUT_MODE_4X4,
    LAYOUT_MODE_6,
    LAYOUT_MODE_8,
    LAYOUT_MODE_12p1,
    LAYOUT_MODE_5x5,
    LAYOUT_MODE_6x6,
    LAYOUT_MODE_8x8,
    LAYOUT_MODE_ONE,
    LAYOUT_MODE_LAST
} VideoWallLayoutMode;

#pragma pack(push,  1 )
typedef struct __VSCConfSystemKey {
    s8 Key[CONF_KEY_STR_MAX];
    __VSCConfSystemKey()
    {
        memset(Key, 0, CONF_KEY_STR_MAX);
        strcpy(Key, VSC_CONF_KEY);
    }
}VSCConfSystemKey;

typedef struct __VSCConfLicenseKey {
    s8 Key[CONF_KEY_STR_MAX];
    __VSCConfLicenseKey()
    {
        memset(Key, 0, CONF_KEY_STR_MAX);
        strcpy(Key, VSC_CONF_LIC_KEY);
    }
}VSCConfLicenseKey;

typedef struct __VSCConfDeviceKey {
    u32 nId;
    s8 Key[CONF_KEY_STR_MAX];
    __VSCConfDeviceKey(u32 id)
    {
        memset(Key, 0, CONF_KEY_STR_MAX);
        strcpy(Key, VSC_CONF_CHANNEL_KEY);
        nId = id;
    }
}VSCConfDeviceKey;

typedef struct __VSCConfVIPCKey {
    u32 nId;
    s8 Key[CONF_KEY_STR_MAX];
    __VSCConfVIPCKey(u32 id)
    {
        memset(Key, 0, CONF_KEY_STR_MAX);
        strcpy(Key, VSC_CONF_VIPC_KEY);
        nId = id;
    }
}VSCConfVIPCKey;

typedef struct __VSCConfVmsKey {
    s8 Key[CONF_KEY_STR_MAX];
    __VSCConfVmsKey()
    {
        memset(Key, 0, CONF_KEY_STR_MAX);
        strcpy(Key, VSC_CONF_VMS_KEY);
    }
}VSCConfVmsKey;

typedef struct __VSCConfViewKey {
    s8 Key[CONF_KEY_STR_MAX];
    __VSCConfViewKey()
    {
        memset(Key, 0, CONF_KEY_STR_MAX);
        strcpy(Key, VSC_CONF_VIEW_KEY);
    }
}VSCConfViewKey;

/* Camera Group key */
typedef struct __VSCConfGroupKey {
    s8 Key[CONF_KEY_STR_MAX];
    __VSCConfGroupKey()
    {
        memset(Key, 0, CONF_KEY_STR_MAX);
        strcpy(Key, VSC_CONF_VGROUP_KEY);
    }
}VSCConfVGroupKey;

/* HDFS Reocrd key */
typedef struct __VSCConfHdfsRecordKey {
    s8 Key[CONF_KEY_STR_MAX];
    __VSCConfHdfsRecordKey()
    {
        memset(Key, 0, CONF_KEY_STR_MAX);
        strcpy(Key, VSC_CONF_HDFS_RECORD_KEY);
    }
}VSCConfHdfsRecordKey;

typedef struct __VSCConfData__ {
    u32 DeviceMap[CONF_MAP_MAX];
    u32 Language;
    u32 DeviceNum;
    u32 VIPCMap[CONF_MAP_MAX];
    u32 VIPCNum;
    u32 ConfVer;/* Current version is 0 */
}VSCConfData__;

typedef struct __VSCConfData {
    union {
        VSCConfData__ conf;
        u8 whole[1024 * 128];
    } data;
}VSCConfData;

typedef struct __VSCDeviceData__ {
	u32 nId;
	VSCDeviceType nType;
	VSCDeviceSubType nSubType;

	s8 Name[CONF_NAME_MAX];
	s8 Param[VSC_CONF_PARAM_MAX];

	s8 IP[VSC_CONF_PARAM_MAX];
	s8 Port[VSC_CONF_PARAM_MAX];
	s8 User[VSC_CONF_PARAM_MAX];
	s8 Password[VSC_CONF_PARAM_MAX];

	/* Camera Param */
	s8 RtspLocation[VSC_CONF_PARAM_MAX];
	s8 FileLocation[VSC_CONF_PARAM_MAX];
	s8 OnvifAddress[VSC_CONF_PARAM_MAX];
	s8 CameraIndex[VSC_CONF_PARAM_MAX];/* This is For USB Camera */

	u32 UseProfileToken;/* 1 stand for use, 0 stand for do not use */
	s8 OnvifProfileToken[VSC_CONF_PARAM_MAX];

	/* Recording */
	u32 Recording;/* 1 stand for recording, 0 stand for do record */
	u32 GroupId;
	u32 HdfsRecording;/* 1 stand for recording, 0 stand for do record */
	/* Second stream, only for VA */
	s8 OnvifProfileToken2[VSC_CONF_PARAM_MAX];
	u32 ConnectType;/* 0 UDP, 1 TCP, 2 Multicast, 3 HTTP */
	u32 Mining;/* 1 stand for mining, 0 stand for no mining */

}VSCDeviceData__;

typedef struct __VSCConfHdfsRecordData__ {
	s8 NameNode[VSC_CONF_PARAM_MAX];
	s8 Port[VSC_CONF_PARAM_MAX];
	s8 User[VSC_CONF_PARAM_MAX];
	s8 Password[VSC_CONF_PARAM_MAX];
	int FileInterval;/* In Seconds */
}VSCConfHdfsRecordData__;

typedef struct __VSCVmsDataItem__ {
	u32 nId;
	VSCVmsType nType;
	VSCVmsSubType nSubType;

	s8 Name[CONF_NAME_MAX];
	s8 Param[VSC_CONF_PARAM_MAX];

	s8 IP[VSC_CONF_PARAM_MAX];
	s8 Port[VSC_CONF_PARAM_MAX];
	s8 User[VSC_CONF_PARAM_MAX];
	s8 Password[VSC_CONF_PARAM_MAX];

	s8 OnvifAddress[VSC_CONF_PARAM_MAX];
	u32 GroupId;
	u32 Used;/* 1 stand for used, 0 stand for not used */
}VSCVmsDataItem;

typedef struct __VSCViewDataItem__ {
	u32 nId;
	s8 Name[CONF_NAME_MAX];
	/* Map for this view */
	u32 Map[VSC_CONF_VIEW_CH_MAX];
	VideoWallLayoutMode Mode;
	u32 Used;/* 1 stand for used, 0 stand for not used */
}VSCViewDataItem;

/* IP Camera Group */
typedef struct __VSCVGroupDataItem__ {
	u32 nId;
	s8 Name[CONF_NAME_MAX];
	/* Map for this group */
	u32 Map[VSC_CONF_VGROUP_CH_MAX];
	u32 Used;/* 1 stand for used, 0 stand for not used */
}VSCVGroupDataItem;

typedef struct __VSCVIPCDataItem__ {
	u32 nId;
	VSCVmsType nType;
	VSCVmsSubType nSubType;

	s8 Name[CONF_NAME_MAX];
	s8 Param[VSC_CONF_PARAM_S_MAX];
	s32 nStreamId;

	s8 IP[VSC_CONF_PARAM_S_MAX];
	s8 Port[VSC_CONF_PARAM_S_MAX];
	s8 User[VSC_CONF_PARAM_S_MAX];
	s8 Password[VSC_CONF_PARAM_S_MAX];

	s8 OnvifAddress[VSC_CONF_PARAM_S_MAX];
}VSCVIPCDataItem__;

typedef struct __VSCVmsData__ {
	VSCVmsDataItem vms[CONF_VMS_NUM_MAX];
}VSCVmsData__;

typedef struct __VSCViewData__ {
	VSCViewDataItem view[CONF_VIEW_NUM_MAX];
}VSCViewData__;

typedef struct __VSCVGroupData__ {
	VSCVGroupDataItem group[CONF_VGROUP_NUM_MAX];
}VSCVGroupData__;

typedef struct __VSCDeviceData {
    union {
        VSCDeviceData__ conf;
        u8 whole[1024 * 128];
    } data;
}VSCDeviceData;

typedef struct __VSCVmsData {
    union {
        VSCVmsData__ conf;
        u8 whole[1024 * 128];
    } data;
}VSCVmsData;

typedef struct __VSCViewData {
    union {
        VSCViewData__ conf;
        u8 whole[1024 * 128];
    } data;
}VSCViewData;

typedef struct __VSCVGroupData {
    union {
        VSCVGroupData__ conf;
        u8 whole[1024 * 128];
    } data;
}VSCVGroupData;

typedef struct __VSCVIPCData {
    union {
        VSCVIPCDataItem__ conf;
        u8 whole[1024 * 128];
    } data;
}VSCVIPCData;

typedef struct __VSCHdfsRecordData {
    union {
        VSCConfHdfsRecordData__ conf;
        u8 whole[1024 * 128];
    } data;
}VSCHdfsRecordData;

inline void VSCVmsDataItemDefault(VSCVmsDataItem &item)
{
    sprintf(item.Name, "Recorder");

    strcpy(item.IP, "192.168.0.1");
    strcpy(item.Port, "80");
    strcpy(item.User, "admin");
    strcpy(item.Password, "admin");
    strcpy(item.Param, "none");
    item.Used = 0;
    item.nId = 0;
    item.GroupId = 0;
}

inline void VSCViewDataItemDefault(VSCViewDataItem &item)
{
    memset(&item, 0, sizeof(VSCViewDataItem));
    sprintf(item.Name, "View");
    item.Mode = LAYOUT_MODE_3X3;
}

inline void VSCVGroupDataItemDefault(VSCVGroupDataItem &item)
{
    memset(&item, 0, sizeof(VSCVGroupDataItem));
    sprintf(item.Name, "Group");
}

inline void VSCVIPCDataItemDefault(VSCVIPCDataItem__ &item)
{
    sprintf(item.Name, "Virutal IPC");

    strcpy(item.IP, "192.168.0.1");
    strcpy(item.Port, "8000");
    strcpy(item.User, "admin");
    strcpy(item.Password, "admin");
    item.nStreamId = 1;
}

inline void VSCHdfsRecordDataItemDefault(VSCConfHdfsRecordData__ &item)
{
    strcpy(item.NameNode, "localhost");//default for hdd
    strcpy(item.Port, "8020");//0 for hdd
    strcpy(item.User, "admin");
    strcpy(item.Password, "admin");
    item.FileInterval = 30;/* 30s */
}

#pragma pack(pop)

#endif /* _CONF_H_ */
<commit_msg>change version<commit_after>

#ifndef _CONF_H_
#define _CONF_H_

#include "utility.hpp"

#define VE_VERSION "r1.1.2-20150201"
#define VE_INFO "OpenCVR r1.1.2 2015"

#ifdef WIN32
#define VE_NVR_CLIENT
#else
#define VE_NVR
#endif

/* NVR Client feature */
#ifdef VE_NVR_CLIENT
#define VE_RECORDER_MGR_CLIENT_SUPPORT
#endif

/* NVR feature */
#ifdef VE_NVR
#define VE_RECORDER_MGR_SERVER_SUPPORT
#endif

#define CONF_NAME_MAX 128
/* support Camera num */
#define CONF_MAP_MAX 4096
#define CONF_USER_PASSWORD_MAX 1024
#define CONF_PATH_MAX 1024
/* 0xFF FFFF to 0xFFFF FFFF is for status for the map */
#define CONF_MAP_INVALID_MIN 0xFFFFFF
#define CONF_KEY_STR_MAX 16

/* Support VMS(site, recorder) num */
#define CONF_VMS_NUM_MAX 128
#define CONF_VIEW_NUM_MAX 128
/* IP camera Group max num */
#define CONF_VGROUP_NUM_MAX 128

#define VSC_CONF_KEY "ConfVSCSystem"
#define VSC_CONF_LIC_KEY "ConfVSCLicense"
#define VSC_CONF_CHANNEL_KEY "ConfVSCDevice"
#define VSC_CONF_VIPC_KEY "ConfVSCVIPC"
#define VSC_CONF_VMS_KEY "ConfVSCVms"
#define VSC_CONF_VIEW_KEY "ConfVSCView"
#define VSC_CONF_VGROUP_KEY "ConfVSCVGroup"
#define VSC_CONF_HDFS_RECORD_KEY "ConfVSCHdfsRec"
#define VSC_CONF_EMAP_FILE_KEY "ConfVSCEmapFile"
#define VSC_CONF_EMAP_CONF_KEY "ConfVSCEmapConf"
#define VSC_CONF_PARAM_MAX 1024
#define VSC_CONF_PARAM_S_MAX 128
/* Max camera in one view */
#define VSC_CONF_VIEW_CH_MAX 256
/* Max camera in one Group */
#define VSC_CONF_VGROUP_CH_MAX 256

typedef enum
{
    VSC_DEVICE_CAM = 1,
    VSC_DEVICE_RECORDER,

    VSC_DEVICE_LAST
} VSCDeviceType;

/* Device Type */
typedef enum
{
    VSC_SUB_DEVICE_USB_CAM = 1,
    VSC_SUB_DEVICE_FILE,
    VSC_SUB_DEVICE_RTSP,
    VSC_SUB_DEVICE_ONVIF,
    VSC_SUB_DEVICE_ONVIF_RECODER,
    VSC_SUB_DEVICE_GB28181,

    VSC_SUB_DEVICE_LAST
} VSCDeviceSubType;

typedef enum
{
    VSC_VMS_RECORDER = 1,
    VSC_VMS_SITE,
    VSC_VMS_VIRTUL_IPC,

    VSC_VMS_LAST
} VSCVmsType;

typedef enum
{
    VSC_SUB_VMS_PG = 1,
    VSC_SUB_VMS_ZB,
    VSC_SUB_VIPC_FILE,
    VSC_SUB_VIPC_LIVE,

    VSC_SUB_VMS_LAST
} VSCVmsSubType;

/* Control command */
typedef enum
{
    LAYOUT_MODE_1 = 1,
    LAYOUT_MODE_2X2,
    LAYOUT_MODE_3X3,
    LAYOUT_MODE_4X4,
    LAYOUT_MODE_6,
    LAYOUT_MODE_8,
    LAYOUT_MODE_12p1,
    LAYOUT_MODE_5x5,
    LAYOUT_MODE_6x6,
    LAYOUT_MODE_8x8,
    LAYOUT_MODE_ONE,
    LAYOUT_MODE_LAST
} VideoWallLayoutMode;

#pragma pack(push,  1 )
typedef struct __VSCConfSystemKey {
    s8 Key[CONF_KEY_STR_MAX];
    __VSCConfSystemKey()
    {
        memset(Key, 0, CONF_KEY_STR_MAX);
        strcpy(Key, VSC_CONF_KEY);
    }
}VSCConfSystemKey;

typedef struct __VSCConfLicenseKey {
    s8 Key[CONF_KEY_STR_MAX];
    __VSCConfLicenseKey()
    {
        memset(Key, 0, CONF_KEY_STR_MAX);
        strcpy(Key, VSC_CONF_LIC_KEY);
    }
}VSCConfLicenseKey;

typedef struct __VSCConfDeviceKey {
    u32 nId;
    s8 Key[CONF_KEY_STR_MAX];
    __VSCConfDeviceKey(u32 id)
    {
        memset(Key, 0, CONF_KEY_STR_MAX);
        strcpy(Key, VSC_CONF_CHANNEL_KEY);
        nId = id;
    }
}VSCConfDeviceKey;

typedef struct __VSCConfVIPCKey {
    u32 nId;
    s8 Key[CONF_KEY_STR_MAX];
    __VSCConfVIPCKey(u32 id)
    {
        memset(Key, 0, CONF_KEY_STR_MAX);
        strcpy(Key, VSC_CONF_VIPC_KEY);
        nId = id;
    }
}VSCConfVIPCKey;

typedef struct __VSCConfVmsKey {
    s8 Key[CONF_KEY_STR_MAX];
    __VSCConfVmsKey()
    {
        memset(Key, 0, CONF_KEY_STR_MAX);
        strcpy(Key, VSC_CONF_VMS_KEY);
    }
}VSCConfVmsKey;

typedef struct __VSCConfViewKey {
    s8 Key[CONF_KEY_STR_MAX];
    __VSCConfViewKey()
    {
        memset(Key, 0, CONF_KEY_STR_MAX);
        strcpy(Key, VSC_CONF_VIEW_KEY);
    }
}VSCConfViewKey;

/* Camera Group key */
typedef struct __VSCConfGroupKey {
    s8 Key[CONF_KEY_STR_MAX];
    __VSCConfGroupKey()
    {
        memset(Key, 0, CONF_KEY_STR_MAX);
        strcpy(Key, VSC_CONF_VGROUP_KEY);
    }
}VSCConfVGroupKey;

/* HDFS Reocrd key */
typedef struct __VSCConfHdfsRecordKey {
    s8 Key[CONF_KEY_STR_MAX];
    __VSCConfHdfsRecordKey()
    {
        memset(Key, 0, CONF_KEY_STR_MAX);
        strcpy(Key, VSC_CONF_HDFS_RECORD_KEY);
    }
}VSCConfHdfsRecordKey;

typedef struct __VSCConfData__ {
    u32 DeviceMap[CONF_MAP_MAX];
    u32 Language;
    u32 DeviceNum;
    u32 VIPCMap[CONF_MAP_MAX];
    u32 VIPCNum;
    u32 ConfVer;/* Current version is 0 */
}VSCConfData__;

typedef struct __VSCConfData {
    union {
        VSCConfData__ conf;
        u8 whole[1024 * 128];
    } data;
}VSCConfData;

typedef struct __VSCDeviceData__ {
	u32 nId;
	VSCDeviceType nType;
	VSCDeviceSubType nSubType;

	s8 Name[CONF_NAME_MAX];
	s8 Param[VSC_CONF_PARAM_MAX];

	s8 IP[VSC_CONF_PARAM_MAX];
	s8 Port[VSC_CONF_PARAM_MAX];
	s8 User[VSC_CONF_PARAM_MAX];
	s8 Password[VSC_CONF_PARAM_MAX];

	/* Camera Param */
	s8 RtspLocation[VSC_CONF_PARAM_MAX];
	s8 FileLocation[VSC_CONF_PARAM_MAX];
	s8 OnvifAddress[VSC_CONF_PARAM_MAX];
	s8 CameraIndex[VSC_CONF_PARAM_MAX];/* This is For USB Camera */

	u32 UseProfileToken;/* 1 stand for use, 0 stand for do not use */
	s8 OnvifProfileToken[VSC_CONF_PARAM_MAX];

	/* Recording */
	u32 Recording;/* 1 stand for recording, 0 stand for do record */
	u32 GroupId;
	u32 HdfsRecording;/* 1 stand for recording, 0 stand for do record */
	/* Second stream, only for VA */
	s8 OnvifProfileToken2[VSC_CONF_PARAM_MAX];
	u32 ConnectType;/* 0 UDP, 1 TCP, 2 Multicast, 3 HTTP */
	u32 Mining;/* 1 stand for mining, 0 stand for no mining */

}VSCDeviceData__;

typedef struct __VSCConfHdfsRecordData__ {
	s8 NameNode[VSC_CONF_PARAM_MAX];
	s8 Port[VSC_CONF_PARAM_MAX];
	s8 User[VSC_CONF_PARAM_MAX];
	s8 Password[VSC_CONF_PARAM_MAX];
	int FileInterval;/* In Seconds */
}VSCConfHdfsRecordData__;

typedef struct __VSCVmsDataItem__ {
	u32 nId;
	VSCVmsType nType;
	VSCVmsSubType nSubType;

	s8 Name[CONF_NAME_MAX];
	s8 Param[VSC_CONF_PARAM_MAX];

	s8 IP[VSC_CONF_PARAM_MAX];
	s8 Port[VSC_CONF_PARAM_MAX];
	s8 User[VSC_CONF_PARAM_MAX];
	s8 Password[VSC_CONF_PARAM_MAX];

	s8 OnvifAddress[VSC_CONF_PARAM_MAX];
	u32 GroupId;
	u32 Used;/* 1 stand for used, 0 stand for not used */
}VSCVmsDataItem;

typedef struct __VSCViewDataItem__ {
	u32 nId;
	s8 Name[CONF_NAME_MAX];
	/* Map for this view */
	u32 Map[VSC_CONF_VIEW_CH_MAX];
	VideoWallLayoutMode Mode;
	u32 Used;/* 1 stand for used, 0 stand for not used */
}VSCViewDataItem;

/* IP Camera Group */
typedef struct __VSCVGroupDataItem__ {
	u32 nId;
	s8 Name[CONF_NAME_MAX];
	/* Map for this group */
	u32 Map[VSC_CONF_VGROUP_CH_MAX];
	u32 Used;/* 1 stand for used, 0 stand for not used */
}VSCVGroupDataItem;

typedef struct __VSCVIPCDataItem__ {
	u32 nId;
	VSCVmsType nType;
	VSCVmsSubType nSubType;

	s8 Name[CONF_NAME_MAX];
	s8 Param[VSC_CONF_PARAM_S_MAX];
	s32 nStreamId;

	s8 IP[VSC_CONF_PARAM_S_MAX];
	s8 Port[VSC_CONF_PARAM_S_MAX];
	s8 User[VSC_CONF_PARAM_S_MAX];
	s8 Password[VSC_CONF_PARAM_S_MAX];

	s8 OnvifAddress[VSC_CONF_PARAM_S_MAX];
}VSCVIPCDataItem__;

typedef struct __VSCVmsData__ {
	VSCVmsDataItem vms[CONF_VMS_NUM_MAX];
}VSCVmsData__;

typedef struct __VSCViewData__ {
	VSCViewDataItem view[CONF_VIEW_NUM_MAX];
}VSCViewData__;

typedef struct __VSCVGroupData__ {
	VSCVGroupDataItem group[CONF_VGROUP_NUM_MAX];
}VSCVGroupData__;

typedef struct __VSCDeviceData {
    union {
        VSCDeviceData__ conf;
        u8 whole[1024 * 128];
    } data;
}VSCDeviceData;

typedef struct __VSCVmsData {
    union {
        VSCVmsData__ conf;
        u8 whole[1024 * 128];
    } data;
}VSCVmsData;

typedef struct __VSCViewData {
    union {
        VSCViewData__ conf;
        u8 whole[1024 * 128];
    } data;
}VSCViewData;

typedef struct __VSCVGroupData {
    union {
        VSCVGroupData__ conf;
        u8 whole[1024 * 128];
    } data;
}VSCVGroupData;

typedef struct __VSCVIPCData {
    union {
        VSCVIPCDataItem__ conf;
        u8 whole[1024 * 128];
    } data;
}VSCVIPCData;

typedef struct __VSCHdfsRecordData {
    union {
        VSCConfHdfsRecordData__ conf;
        u8 whole[1024 * 128];
    } data;
}VSCHdfsRecordData;

inline void VSCVmsDataItemDefault(VSCVmsDataItem &item)
{
    sprintf(item.Name, "Recorder");

    strcpy(item.IP, "192.168.0.1");
    strcpy(item.Port, "80");
    strcpy(item.User, "admin");
    strcpy(item.Password, "admin");
    strcpy(item.Param, "none");
    item.Used = 0;
    item.nId = 0;
    item.GroupId = 0;
}

inline void VSCViewDataItemDefault(VSCViewDataItem &item)
{
    memset(&item, 0, sizeof(VSCViewDataItem));
    sprintf(item.Name, "View");
    item.Mode = LAYOUT_MODE_3X3;
}

inline void VSCVGroupDataItemDefault(VSCVGroupDataItem &item)
{
    memset(&item, 0, sizeof(VSCVGroupDataItem));
    sprintf(item.Name, "Group");
}

inline void VSCVIPCDataItemDefault(VSCVIPCDataItem__ &item)
{
    sprintf(item.Name, "Virutal IPC");

    strcpy(item.IP, "192.168.0.1");
    strcpy(item.Port, "8000");
    strcpy(item.User, "admin");
    strcpy(item.Password, "admin");
    item.nStreamId = 1;
}

inline void VSCHdfsRecordDataItemDefault(VSCConfHdfsRecordData__ &item)
{
    strcpy(item.NameNode, "localhost");//default for hdd
    strcpy(item.Port, "8020");//0 for hdd
    strcpy(item.User, "admin");
    strcpy(item.Password, "admin");
    item.FileInterval = 30;/* 30s */
}

#pragma pack(pop)

#endif /* _CONF_H_ */
<|endoftext|>