<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_start_cbs.C $      */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2016                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
//------------------------------------------------------------------------------
/// @file  p9_start_cbs.C
///
/// @brief Start CBS : Trigger CBS
//------------------------------------------------------------------------------
// *HWP HW Owner        : Abhishek Agarwal <abagarw8@in.ibm.com>
// *HWP HW Backup Owner : Srinivas V Naga <srinivan@in.ibm.com>
// *HWP FW Owner        : sunil kumar <skumar8j@in.ibm.com>
// *HWP Team            : Perv
// *HWP Level           : 2
// *HWP Consumed by     : SE:HB
//------------------------------------------------------------------------------

//## auto_generated
#include "p9_start_cbs.H"
//## auto_generated
#include "p9_const_common.H"

#include <p9_perv_scom_addresses.H>
#include <p9_perv_scom_addresses_fld.H>
#include <p9_perv_scom_addresses_fixes.H>
#include <p9_perv_scom_addresses_fld_fixes.H>

enum P9_START_CBS_Private_Constants
{
    P9_CFAM_CBS_POLL_COUNT = 20, // Observed Number of times CBS read for CBS_INTERNAL_STATE_VECTOR
    CBS_IDLE_VALUE = 0x002, // Read the value of CBS_CS_INTERNAL_STATE_VECTOR
    P9_CBS_IDLE_HW_NS_DELAY = 640000, // unit is nano seconds [min : 64k x (1/100MHz) = 64k x 10(-8) = 640 us
    //                       max : 64k x (1/50MHz) = 128k x 10(-8) = 1280 us]
    P9_CBS_IDLE_SIM_CYCLE_DELAY = 7500000 // unit is sim cycles,to match the poll count change( 250000 * 30 )
};

fapi2::ReturnCode p9_start_cbs(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>
                               & i_target_chip,
                               const bool i_sbe_start)
{
    fapi2::buffer<uint32_t> l_read_reg ;
    bool l_read_vdn_pgood_status = false;
    bool l_sbe_start_value = false;
    bool l_fsi2pib_status = false;
    fapi2::buffer<uint32_t> l_data32;
    fapi2::buffer<uint32_t> l_data32_cbs_cs;
    int l_timeout = 0;
    FAPI_INF("p9_start_cbs: Entering ...");

    l_sbe_start_value = !i_sbe_start;

    FAPI_DBG("Configuring Prevent SBE start option");
    FAPI_IMP("SBE start value : %d", l_sbe_start_value);
    //Setting CBS_CS register value
    FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_CBS_CS_FSI,
                                    l_data32_cbs_cs));
    //CFAM.CBS_CS.CBS_CS_PREVENT_SBE_START = l_sbe_start_value
    l_data32_cbs_cs.writeBit<3>(l_sbe_start_value);
    FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_CBS_CS_FSI,
                                    l_data32_cbs_cs));

    FAPI_DBG("check for VDN_PGOOD");
    //Getting PERV_CBS_ENVSTAT register value
    FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_CBS_ENVSTAT_FSI,
                                    l_data32));
    l_read_vdn_pgood_status =
        l_data32.getBit<PERV_CBS_ENVSTAT_C4_VDN_GPOOD>();  //l_read_vdn_pgood_status = PERV_CBS_ENVSTAT.PERV_CBS_ENVSTAT_C4_VDN_GPOOD

    FAPI_ASSERT(l_read_vdn_pgood_status,
                fapi2::VDN_PGOOD_NOT_SET()
                .set_MASTER_CHIP(i_target_chip)
                .set_CBS_ENVSTAT_READ(l_data32),
                "ERROR:VDN_PGOOD OFF, CBS_ENVSTAT BIT 2 NOT SET");

    FAPI_DBG("Resetting CFAM Boot Sequencer (CBS) to flush value");
    //Setting CBS_CS register value
    FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_CBS_CS_FSI,
                                    l_data32_cbs_cs));
    l_data32_cbs_cs.clearBit<0>();  //CFAM.CBS_CS.CBS_CS_START_BOOT_SEQUENCER = 0
    FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_CBS_CS_FSI,
                                    l_data32_cbs_cs));

    FAPI_DBG("Triggering CFAM Boot Sequencer (CBS) to start");
    //Setting CBS_CS register value
    l_data32_cbs_cs.setBit<0>();  //CFAM.CBS_CS.CBS_CS_START_BOOT_SEQUENCER = 1
    FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_CBS_CS_FSI,
                                    l_data32_cbs_cs));

    FAPI_DBG("Check cbs_cs_internal_state_vector");
    l_timeout = P9_CFAM_CBS_POLL_COUNT;

    //UNTIL CBS_CS.CBS_CS_INTERNAL_STATE_VECTOR == CBS_IDLE_VALUE
    while (l_timeout != 0)
    {
        //Getting CBS_CS register value
        FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_CBS_CS_FSI,
                                        l_data32_cbs_cs));
        uint32_t l_poll_data = 0;    //uint32_t l_poll_data = CFAM.CBS_CS.CBS_CS_INTERNAL_STATE_VECTOR
        l_data32_cbs_cs.extractToRight<16, 16>(l_poll_data);

        if (l_poll_data == CBS_IDLE_VALUE)
        {
            break;
        }

        fapi2::delay(P9_CBS_IDLE_HW_NS_DELAY, P9_CBS_IDLE_SIM_CYCLE_DELAY);
        --l_timeout;
    }

    FAPI_DBG("Loop Count :%d", l_timeout);

    FAPI_ASSERT(l_timeout > 0,
                fapi2::CBS_NOT_IN_IDLE_STATE()
                .set_MASTER_CHIP_TARGET(i_target_chip)
                .set_MASTER_CHIP(i_target_chip)
                .set_CBS_CS_READ(l_data32_cbs_cs)
                .set_CBS_CS_IDLE_VALUE(CBS_IDLE_VALUE)
                .set_LOOP_COUNT(l_timeout)
                .set_HW_DELAY(P9_CBS_IDLE_HW_NS_DELAY),
                "ERROR: CBS HAS NOT REACHED IDLE STATE VALUE 0x002 ");

    FAPI_DBG("check for VDD status");
    //Getting FSI2PIB_STATUS register value
    FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_FSI2PIB_STATUS_FSI,
                                    l_data32));
    //l_fsi2pib_status = CFAM.FSI2PIB_STATUS.VDD_NEST_OBSERVE
    l_fsi2pib_status = l_data32.getBit<PERV_FSI2PIB_STATUS_VDD_NEST_OBSERVE>();

    FAPI_ASSERT(l_fsi2pib_status,
                fapi2::VDD_NEST_OBSERVE_NOT_SET()
                .set_MASTER_CHIP(i_target_chip)
                .set_FSI2PIB_STATUS_READ(l_data32),
                "ERROR:VDD OFF, FSI2PIB  BIT 16 NOT SET");

    FAPI_INF("p9_start_cbs: Exiting ...");

fapi_try_exit:
    return fapi2::current_err;

}
<commit_msg>Clearing SB MSG register before cbs start<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_start_cbs.C $      */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2016                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
//------------------------------------------------------------------------------
/// @file  p9_start_cbs.C
///
/// @brief Start CBS : Trigger CBS
//------------------------------------------------------------------------------
// *HWP HW Owner        : Abhishek Agarwal <abagarw8@in.ibm.com>
// *HWP HW Backup Owner : Srinivas V Naga <srinivan@in.ibm.com>
// *HWP FW Owner        : sunil kumar <skumar8j@in.ibm.com>
// *HWP Team            : Perv
// *HWP Level           : 2
// *HWP Consumed by     : SE:HB
//------------------------------------------------------------------------------

//## auto_generated
#include "p9_start_cbs.H"
//## auto_generated
#include "p9_const_common.H"

#include <p9_perv_scom_addresses.H>
#include <p9_perv_scom_addresses_fld.H>
#include <p9_perv_scom_addresses_fixes.H>
#include <p9_perv_scom_addresses_fld_fixes.H>

enum P9_START_CBS_Private_Constants
{
    P9_CFAM_CBS_POLL_COUNT = 20, // Observed Number of times CBS read for CBS_INTERNAL_STATE_VECTOR
    CBS_IDLE_VALUE = 0x002, // Read the value of CBS_CS_INTERNAL_STATE_VECTOR
    P9_CBS_IDLE_HW_NS_DELAY = 640000, // unit is nano seconds [min : 64k x (1/100MHz) = 64k x 10(-8) = 640 us
    //                       max : 64k x (1/50MHz) = 128k x 10(-8) = 1280 us]
    P9_CBS_IDLE_SIM_CYCLE_DELAY = 7500000 // unit is sim cycles,to match the poll count change( 250000 * 30 )
};

fapi2::ReturnCode p9_start_cbs(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>
                               & i_target_chip,
                               const bool i_sbe_start)
{
    fapi2::buffer<uint32_t> l_read_reg ;
    bool l_read_vdn_pgood_status = false;
    bool l_sbe_start_value = false;
    bool l_fsi2pib_status = false;
    fapi2::buffer<uint32_t> l_data32;
    fapi2::buffer<uint32_t> l_data32_cbs_cs;
    int l_timeout = 0;
    FAPI_INF("p9_start_cbs: Entering ...");

    FAPI_DBG("Clearing  Selfboot message register before every boot ");
    // buffer is init value is 0
    FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_SB_MSG_FSI, l_data32));

    l_sbe_start_value = !i_sbe_start;

    FAPI_DBG("Configuring Prevent SBE start option");
    FAPI_IMP("SBE start value : %d", l_sbe_start_value);
    //Setting CBS_CS register value
    FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_CBS_CS_FSI,
                                    l_data32_cbs_cs));
    //CFAM.CBS_CS.CBS_CS_PREVENT_SBE_START = l_sbe_start_value
    l_data32_cbs_cs.writeBit<3>(l_sbe_start_value);
    FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_CBS_CS_FSI,
                                    l_data32_cbs_cs));

    FAPI_DBG("check for VDN_PGOOD");
    //Getting PERV_CBS_ENVSTAT register value
    FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_CBS_ENVSTAT_FSI,
                                    l_data32));
    l_read_vdn_pgood_status =
        l_data32.getBit<PERV_CBS_ENVSTAT_C4_VDN_GPOOD>();  //l_read_vdn_pgood_status = PERV_CBS_ENVSTAT.PERV_CBS_ENVSTAT_C4_VDN_GPOOD

    FAPI_ASSERT(l_read_vdn_pgood_status,
                fapi2::VDN_PGOOD_NOT_SET()
                .set_MASTER_CHIP(i_target_chip)
                .set_CBS_ENVSTAT_READ(l_data32),
                "ERROR:VDN_PGOOD OFF, CBS_ENVSTAT BIT 2 NOT SET");

    FAPI_DBG("Resetting CFAM Boot Sequencer (CBS) to flush value");
    //Setting CBS_CS register value
    FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_CBS_CS_FSI,
                                    l_data32_cbs_cs));
    l_data32_cbs_cs.clearBit<0>();  //CFAM.CBS_CS.CBS_CS_START_BOOT_SEQUENCER = 0
    FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_CBS_CS_FSI,
                                    l_data32_cbs_cs));

    FAPI_DBG("Triggering CFAM Boot Sequencer (CBS) to start");
    //Setting CBS_CS register value
    l_data32_cbs_cs.setBit<0>();  //CFAM.CBS_CS.CBS_CS_START_BOOT_SEQUENCER = 1
    FAPI_TRY(fapi2::putCfamRegister(i_target_chip, PERV_CBS_CS_FSI,
                                    l_data32_cbs_cs));

    FAPI_DBG("Check cbs_cs_internal_state_vector");
    l_timeout = P9_CFAM_CBS_POLL_COUNT;

    //UNTIL CBS_CS.CBS_CS_INTERNAL_STATE_VECTOR == CBS_IDLE_VALUE
    while (l_timeout != 0)
    {
        //Getting CBS_CS register value
        FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_CBS_CS_FSI,
                                        l_data32_cbs_cs));
        uint32_t l_poll_data = 0;    //uint32_t l_poll_data = CFAM.CBS_CS.CBS_CS_INTERNAL_STATE_VECTOR
        l_data32_cbs_cs.extractToRight<16, 16>(l_poll_data);

        if (l_poll_data == CBS_IDLE_VALUE)
        {
            break;
        }

        fapi2::delay(P9_CBS_IDLE_HW_NS_DELAY, P9_CBS_IDLE_SIM_CYCLE_DELAY);
        --l_timeout;
    }

    FAPI_DBG("Loop Count :%d", l_timeout);

    FAPI_ASSERT(l_timeout > 0,
                fapi2::CBS_NOT_IN_IDLE_STATE()
                .set_MASTER_CHIP_TARGET(i_target_chip)
                .set_MASTER_CHIP(i_target_chip)
                .set_CBS_CS_READ(l_data32_cbs_cs)
                .set_CBS_CS_IDLE_VALUE(CBS_IDLE_VALUE)
                .set_LOOP_COUNT(l_timeout)
                .set_HW_DELAY(P9_CBS_IDLE_HW_NS_DELAY),
                "ERROR: CBS HAS NOT REACHED IDLE STATE VALUE 0x002 ");

    FAPI_DBG("check for VDD status");
    //Getting FSI2PIB_STATUS register value
    FAPI_TRY(fapi2::getCfamRegister(i_target_chip, PERV_FSI2PIB_STATUS_FSI,
                                    l_data32));
    //l_fsi2pib_status = CFAM.FSI2PIB_STATUS.VDD_NEST_OBSERVE
    l_fsi2pib_status = l_data32.getBit<PERV_FSI2PIB_STATUS_VDD_NEST_OBSERVE>();

    FAPI_ASSERT(l_fsi2pib_status,
                fapi2::VDD_NEST_OBSERVE_NOT_SET()
                .set_MASTER_CHIP(i_target_chip)
                .set_FSI2PIB_STATUS_READ(l_data32),
                "ERROR:VDD OFF, FSI2PIB  BIT 16 NOT SET");

    FAPI_INF("p9_start_cbs: Exiting ...");

fapi_try_exit:
    return fapi2::current_err;

}
<|endoftext|>


<commit_before>#pragma once

#include <iostream>
#include <sstream>

#include <stdlib.h>

#include "BigInt.hpp"
#include "types.hpp"

namespace Ethereum{namespace Connector{

template<typename T>
std::string hex(const T &);

template<typename T>
T unhex(const char *);

template<>
uint32_t unhex<uint32_t>(const char *);

#if __HAS_INT64__
template<>
uint64_t unhex<uint64_t>(const char *);
#endif

template<>
BigInt unhex<BigInt>(const char *);

}}

#include "hex.ipp"
<commit_msg>relative includes<commit_after>#pragma once

#include <iostream>
#include <sstream>

#include <stdlib.h>

#include "../BigInt.hpp"
#include "types.hpp"

namespace Ethereum{namespace Connector{

template<typename T>
std::string hex(const T &);

template<typename T>
T unhex(const char *);

template<>
uint32_t unhex<uint32_t>(const char *);

#if __HAS_INT64__
template<>
uint64_t unhex<uint64_t>(const char *);
#endif

template<>
BigInt unhex<BigInt>(const char *);

}}

#include "hex.ipp"
<|endoftext|>


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

#include <stdio.h>
#include <signal.h>
#include <vector>
#include <set>
#include <map>

#include <rtl/crc.h>
#include <tools/stream.hxx>
#include <tools/fsys.hxx>
#include <vcl/svapp.hxx>
#include <vcl/bitmap.hxx>
#include <vcl/bmpacc.hxx>
#include <vcl/pngread.hxx>

#include "solar.hrc"
#include "filedlg.hxx"

#define EXIT_NOERROR        0x00000000
#define EXIT_INVALIDFILE    0x00000001
#define EXIT_COMMONERROR    0x80000000

// ----------
// - BmpSum -
// ----------

class BmpSum
{
private:

    sal_uInt32      cExitCode;

    BOOL            GetCommandOption( const ::std::vector< String >& rArgs, const String& rSwitch, String& rSwitchParam );
    BOOL            GetCommandOptions( const ::std::vector< String >& rArgs, const String& rSwitch, ::std::vector< String >& rSwitchParams );

    void            SetExitCode( BYTE cExit )
                    {
                        if( ( EXIT_NOERROR == cExitCode ) || ( cExit != EXIT_NOERROR ) )
                            cExitCode = cExit;
                    }
    void            ShowUsage();
    void            Message( const String& rText, BYTE cExitCode );

    sal_uInt64      GetCRC( Bitmap& rBmp );

    void            ProcessFile( const String& rBmpFileName );
    void            ProcessFileList( const String& rInFileList, const String& rOutFileList, const String& rOutPath );

public:

                    BmpSum();
                    ~BmpSum();

    int             Start( const ::std::vector< String >& rArgs );
};

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

BmpSum::BmpSum()
{
}

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

BmpSum::~BmpSum()
{
}

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

BOOL BmpSum::GetCommandOption( const ::std::vector< String >& rArgs, const String& rSwitch, String& rParam )
{
    BOOL bRet = FALSE;

    for( int i = 0, nCount = rArgs.size(); ( i < nCount ) && !bRet; i++ )
    {
        String  aTestStr( '-' );

        for( int n = 0; ( n < 2 ) && !bRet; n++ )
        {
            aTestStr += rSwitch;

            if( aTestStr.CompareIgnoreCaseToAscii( rArgs[ i ] ) == COMPARE_EQUAL )
            {
                bRet = TRUE;

                if( i < ( nCount - 1 ) )
                    rParam = rArgs[ i + 1 ];
                else
                    rParam = String();
            }

            if( 0 == n )
                aTestStr = '/';
        }
    }

    return bRet;
}

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

BOOL BmpSum::GetCommandOptions( const ::std::vector< String >& rArgs, const String& rSwitch, ::std::vector< String >& rParams )
{
    BOOL bRet = FALSE;

    for( int i = 0, nCount = rArgs.size(); ( i < nCount ); i++ )
    {
        String  aTestStr( '-' );

        for( int n = 0; ( n < 2 ) && !bRet; n++ )
        {
            aTestStr += rSwitch;

            if( aTestStr.CompareIgnoreCaseToAscii( rArgs[ i ] ) == COMPARE_EQUAL )
            {
                if( i < ( nCount - 1 ) )
                    rParams.push_back( rArgs[ i + 1 ] );
                else
                    rParams.push_back( String() );

                break;
            }

            if( 0 == n )
                aTestStr = '/';
        }
    }

    return( rParams.size() > 0 );
}

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

void BmpSum::Message( const String& rText, BYTE nExitCode )
{
    if( EXIT_NOERROR != nExitCode )
        SetExitCode( nExitCode );

    ByteString aText( rText, RTL_TEXTENCODING_UTF8 );
    aText.Append( "\r\n" );
    fprintf( stderr, aText.GetBuffer() );
}

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

void BmpSum::ShowUsage()
{
    Message( String( RTL_CONSTASCII_USTRINGPARAM( "Usage:" ) ), EXIT_NOERROR );
    Message( String( RTL_CONSTASCII_USTRINGPARAM( "    bmpsum bmp_inputfile" ) ), EXIT_NOERROR );
    Message( String( RTL_CONSTASCII_USTRINGPARAM( "    bmpsum -i input_filelist -o output_filelist [-p path_for_copied_bitmaps]" ) ), EXIT_NOERROR );
    Message( String( RTL_CONSTASCII_USTRINGPARAM( "Options:" ) ), EXIT_NOERROR );
    Message( String( RTL_CONSTASCII_USTRINGPARAM( "Examples:" ) ), EXIT_NOERROR );
    Message( String( RTL_CONSTASCII_USTRINGPARAM( "    bmpsum /home/test.bmp" ) ), EXIT_NOERROR );
    Message( String( RTL_CONSTASCII_USTRINGPARAM( "    bmpsum -i /home/inlist.txt -o /home/outlist.txt" ) ), EXIT_NOERROR );
    Message( String( RTL_CONSTASCII_USTRINGPARAM( "    bmpsum -i /home/inlist.txt -o /home/outlist.txt -p /home/outpath" ) ), EXIT_NOERROR );
}

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

int BmpSum::Start( const ::std::vector< String >& rArgs )
{
    cExitCode = EXIT_NOERROR;

    if( rArgs.size() >= 1 )
    {
        String  aInFileList, aOutFileList, aOutPath;

        if( GetCommandOption( rArgs, 'i', aInFileList ) &&
            GetCommandOption( rArgs, 'o', aOutFileList ) )
        {
            GetCommandOption( rArgs, 'p', aOutPath );
            ProcessFileList( aInFileList, aOutFileList, aOutPath );
        }
        else
        {
            ProcessFile( rArgs[ 0 ] );
        }
    }
    else
    {
        ShowUsage();
        cExitCode = EXIT_COMMONERROR;
    }

    return cExitCode;
}

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

sal_uInt64 BmpSum::GetCRC( Bitmap& rBmp )
{
    BitmapReadAccess* pRAcc = rBmp.AcquireReadAccess();
    sal_uInt64        nRet = 0;
    sal_uInt32        nCrc = 0;

    if( pRAcc && pRAcc->Width() && pRAcc->Height() )
    {
        SVBT32 aBT32;

        for( long nY = 0; nY < pRAcc->Height(); ++nY )
        {
            for( long nX = 0; nX < pRAcc->Width(); ++nX )
            {
                const BitmapColor aCol( pRAcc->GetColor( nY, nX ) );

                UInt32ToSVBT32( aCol.GetRed(), aBT32 );
                nCrc = rtl_crc32( nCrc, aBT32, 4 );

                UInt32ToSVBT32( aCol.GetGreen(), aBT32 );
                nCrc = rtl_crc32( nCrc, aBT32, 4 );

                UInt32ToSVBT32( aCol.GetBlue(), aBT32 );
                nCrc = rtl_crc32( nCrc, aBT32, 4 );
            }
        }

        nRet = ( ( (sal_uInt64) pRAcc->Width() ) << 48 ) |
               ( ( (sal_uInt64) pRAcc->Height() ) << 32 ) |
               ( (sal_uInt64) nCrc );
    }

    rBmp.ReleaseAccess( pRAcc );

    return nRet;
}

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

void BmpSum::ProcessFile( const String& rBmpFileName )
{
    SvFileStream aIStm( rBmpFileName, STREAM_READ );

    if( aIStm.IsOpen() )
    {
        Bitmap aBmp;

        aIStm >> aBmp;

        if( !aBmp.IsEmpty() )
        {
#ifdef WNT
            fprintf( stdout, "%I64u\r\n", GetCRC( aBmp ) );
#else
            fprintf( stdout, "%llu\r\n", GetCRC( aBmp ) );
#endif
        }
        else
        {
            aIStm.ResetError();
            aIStm.Seek( 0 );

               ::vcl::PNGReader aPngReader( aIStm );

            aBmp = aPngReader.Read().GetBitmap();

              if( !aBmp.IsEmpty() )
            {
#ifdef WNT
                fprintf( stdout, "%I64u\r\n", GetCRC( aBmp ) );
#else
                fprintf( stdout, "%llu\r\n", GetCRC( aBmp ) );
#endif
            }
            else
                Message( String( RTL_CONSTASCII_USTRINGPARAM( "file not valid" ) ), EXIT_INVALIDFILE );
        }
    }
}

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

void BmpSum::ProcessFileList( const String& rInFileList,
                              const String& rOutFileList,
                              const String& rOutPath )
{
    SvFileStream    aIStm( rInFileList, STREAM_READ );
    SvFileStream    aOStm( rOutFileList, STREAM_WRITE | STREAM_TRUNC );
    const DirEntry  aBaseDir( rOutPath );

    if( rOutPath.Len() )
        aBaseDir.MakeDir();

    if( aIStm.IsOpen() && aOStm.IsOpen() )
    {
        ByteString                  aReadLine;
        ::std::set< ByteString >    aFileNameSet;

        while( aIStm.ReadLine( aReadLine ) )
        {
            if( aReadLine.Len() )
                aFileNameSet.insert( aReadLine );

            if( aReadLine.Search( "enus" ) != STRING_NOTFOUND )
            {
                static const char* aLanguages[] =
                {
                    "chinsim",
                    "chintrad",
                    "dtch",
                    "enus",
                    "fren",
                    "hebrew"
                    "ital",
                    "japn",
                    "korean",
                    "pol",
                    "poln",
                    "port",
                    "russ",
                    "span",
                    "turk"
                };

                for( sal_uInt32 n = 0; n < 14; ++n )
                {
                    ByteString aLangPath( aReadLine );

                    aLangPath.SearchAndReplace( "enus", aLanguages[ n ] );

                    DirEntry aTestFile( aLangPath );

                    if( aTestFile.Exists() )
                        aFileNameSet.insert( aLangPath );
                }
            }

            aReadLine.Erase();
        }

        aIStm.Close();

        ::std::set< ByteString >::iterator aIter( aFileNameSet.begin() );
        ::std::map< sal_uInt64, ::std::vector< ByteString > > aFileNameMap;

        while( aIter != aFileNameSet.end() )
        {
            ByteString      aStr( *aIter++ );
            SvFileStream    aBmpStm( String( aStr.GetBuffer(), RTL_TEXTENCODING_ASCII_US ), STREAM_READ );
            sal_uInt64      nCRC = 0;

            if( aBmpStm.IsOpen() )
            {
                Bitmap aBmp;

                aBmpStm >> aBmp;

                if( !aBmp.IsEmpty() )
                    nCRC = GetCRC( aBmp );
                else
                {
                    aBmpStm.ResetError();
                    aBmpStm.Seek( 0 );

                       ::vcl::PNGReader aPngReader( aBmpStm );

                    aBmp = aPngReader.Read().GetBitmap();

                      if( !aBmp.IsEmpty() )
                           nCRC = GetCRC( aBmp );

                    else
                        fprintf( stderr, "%s could not be opened\n", aStr.GetBuffer() );
               }

                aBmpStm.Close();
            }

            if( nCRC )
            {
                ::std::map< sal_uInt64, ::std::vector< ByteString > >::iterator aFound( aFileNameMap.find( nCRC ) );

                if( aFound != aFileNameMap.end() )
                    (*aFound).second.push_back( aStr );
                else
                {
                    ::std::vector< ByteString > aVector( 1, aStr );
                    aFileNameMap[ nCRC ]  = aVector;
                }

            }
            else
            {
                ::std::vector< ByteString > aVector( 1, aStr );
                aFileNameMap[ nCRC ]  = aVector;
            }
        }

        ::std::map< sal_uInt64, ::std::vector< ByteString > >::iterator aMapIter( aFileNameMap.begin() );
        sal_uInt32 nFileCount = 0;

        while( aMapIter != aFileNameMap.end() )
        {
            ::std::pair< const sal_uInt64, ::std::vector< ByteString > > aPair( *aMapIter++ );
            ::std::vector< ByteString > aFileNameVector( aPair.second );

            // write new entries
            for( sal_uInt32 i = 0; i < aFileNameVector.size(); ++i )
            {
                ByteString  aStr( ByteString::CreateFromInt64( aPair.first ) );
                ByteString  aFileName( aFileNameVector[ i ] );
                DirEntry    aSrcFile( aFileName );

                aStr += '\t';
                aStr += aFileName;

                aOStm.WriteLine( aStr );

                // copy bitmap
                if( rOutPath.Len() )
                {
                    if( aFileName.Search( ":\\" ) != STRING_NOTFOUND )
                        aFileName.Erase( 0, aFileName.Search( ":\\" ) + 2 );

                    aFileName.SearchAndReplaceAll( '\\', '/' );

                    sal_uInt16  nTokenCount = aFileName.GetTokenCount( '/' );
                    DirEntry    aNewDir( aBaseDir );

                    for( sal_uInt16 n = 0; ( n < nTokenCount - 1 ); n++ )
                    {
                        aNewDir += DirEntry( aFileName.GetToken( n, '/' ) );
                        aNewDir.MakeDir();
                    }

                    aNewDir += DirEntry( aFileName.GetToken( nTokenCount - 1, '/' ) );
                    aSrcFile.CopyTo( aNewDir, FSYS_ACTION_COPYFILE );
                }
            }

            ++nFileCount;
        }

        fprintf( stdout, "unique file count: %u", nFileCount );
    }
}

// --------
// - Main -
// --------

int main( int nArgCount, char* ppArgs[] )
{
    ::std::vector< String > aArgs;
    BmpSum                  aBmpSum;

    InitVCL( com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >() );

    for( int i = 1; i < nArgCount; i++ )
        aArgs.push_back( String( ppArgs[ i ], RTL_TEXTENCODING_ASCII_US ) );

    return aBmpSum.Start( aArgs );
}
<commit_msg>INTEGRATION: CWS warningfixes02 (1.8.12); FILE MERGED 2006/06/30 12:20:40 sb 1.8.12.1: #i66577# Made the code compile (warning-free) on a unxlngi6.pro GCC 4.1.1 Linux box.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: bmpsum.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: kz $ $Date: 2006-07-19 17:03:49 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <stdio.h>
#include <signal.h>
#include <vector>
#include <set>
#include <map>

#include <rtl/crc.h>
#include <tools/stream.hxx>
#include <tools/fsys.hxx>
#include <vcl/svapp.hxx>
#include <vcl/bitmap.hxx>
#include <vcl/bmpacc.hxx>
#include <vcl/pngread.hxx>

#include "solar.hrc"
#include "filedlg.hxx"

#define EXIT_NOERROR        0x00000000
#define EXIT_INVALIDFILE    0x00000001
#define EXIT_COMMONERROR    0x80000000

// ----------
// - BmpSum -
// ----------

class BmpSum
{
private:

    sal_uInt32      cExitCode;

    BOOL            GetCommandOption( const ::std::vector< String >& rArgs, const String& rSwitch, String& rSwitchParam );
    BOOL            GetCommandOptions( const ::std::vector< String >& rArgs, const String& rSwitch, ::std::vector< String >& rSwitchParams );

    void            SetExitCode( BYTE cExit )
                    {
                        if( ( EXIT_NOERROR == cExitCode ) || ( cExit != EXIT_NOERROR ) )
                            cExitCode = cExit;
                    }
    void            ShowUsage();
    void            Message( const String& rText, BYTE cExitCode );

    sal_uInt64      GetCRC( Bitmap& rBmp );

    void            ProcessFile( const String& rBmpFileName );
    void            ProcessFileList( const String& rInFileList, const String& rOutFileList, const String& rOutPath );

public:

                    BmpSum();
                    ~BmpSum();

    int             Start( const ::std::vector< String >& rArgs );
};

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

BmpSum::BmpSum()
{
}

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

BmpSum::~BmpSum()
{
}

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

BOOL BmpSum::GetCommandOption( const ::std::vector< String >& rArgs, const String& rSwitch, String& rParam )
{
    BOOL bRet = FALSE;

    for( int i = 0, nCount = rArgs.size(); ( i < nCount ) && !bRet; i++ )
    {
        String  aTestStr( '-' );

        for( int n = 0; ( n < 2 ) && !bRet; n++ )
        {
            aTestStr += rSwitch;

            if( aTestStr.CompareIgnoreCaseToAscii( rArgs[ i ] ) == COMPARE_EQUAL )
            {
                bRet = TRUE;

                if( i < ( nCount - 1 ) )
                    rParam = rArgs[ i + 1 ];
                else
                    rParam = String();
            }

            if( 0 == n )
                aTestStr = '/';
        }
    }

    return bRet;
}

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

BOOL BmpSum::GetCommandOptions( const ::std::vector< String >& rArgs, const String& rSwitch, ::std::vector< String >& rParams )
{
    BOOL bRet = FALSE;

    for( int i = 0, nCount = rArgs.size(); ( i < nCount ); i++ )
    {
        String  aTestStr( '-' );

        for( int n = 0; ( n < 2 ) && !bRet; n++ )
        {
            aTestStr += rSwitch;

            if( aTestStr.CompareIgnoreCaseToAscii( rArgs[ i ] ) == COMPARE_EQUAL )
            {
                if( i < ( nCount - 1 ) )
                    rParams.push_back( rArgs[ i + 1 ] );
                else
                    rParams.push_back( String() );

                break;
            }

            if( 0 == n )
                aTestStr = '/';
        }
    }

    return( rParams.size() > 0 );
}

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

void BmpSum::Message( const String& rText, BYTE nExitCode )
{
    if( EXIT_NOERROR != nExitCode )
        SetExitCode( nExitCode );

    ByteString aText( rText, RTL_TEXTENCODING_UTF8 );
    aText.Append( "\r\n" );
    fprintf( stderr, aText.GetBuffer() );
}

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

void BmpSum::ShowUsage()
{
    Message( String( RTL_CONSTASCII_USTRINGPARAM( "Usage:" ) ), EXIT_NOERROR );
    Message( String( RTL_CONSTASCII_USTRINGPARAM( "    bmpsum bmp_inputfile" ) ), EXIT_NOERROR );
    Message( String( RTL_CONSTASCII_USTRINGPARAM( "    bmpsum -i input_filelist -o output_filelist [-p path_for_copied_bitmaps]" ) ), EXIT_NOERROR );
    Message( String( RTL_CONSTASCII_USTRINGPARAM( "Options:" ) ), EXIT_NOERROR );
    Message( String( RTL_CONSTASCII_USTRINGPARAM( "Examples:" ) ), EXIT_NOERROR );
    Message( String( RTL_CONSTASCII_USTRINGPARAM( "    bmpsum /home/test.bmp" ) ), EXIT_NOERROR );
    Message( String( RTL_CONSTASCII_USTRINGPARAM( "    bmpsum -i /home/inlist.txt -o /home/outlist.txt" ) ), EXIT_NOERROR );
    Message( String( RTL_CONSTASCII_USTRINGPARAM( "    bmpsum -i /home/inlist.txt -o /home/outlist.txt -p /home/outpath" ) ), EXIT_NOERROR );
}

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

int BmpSum::Start( const ::std::vector< String >& rArgs )
{
    cExitCode = EXIT_NOERROR;

    if( rArgs.size() >= 1 )
    {
        String  aInFileList, aOutFileList, aOutPath;

        if( GetCommandOption( rArgs, 'i', aInFileList ) &&
            GetCommandOption( rArgs, 'o', aOutFileList ) )
        {
            GetCommandOption( rArgs, 'p', aOutPath );
            ProcessFileList( aInFileList, aOutFileList, aOutPath );
        }
        else
        {
            ProcessFile( rArgs[ 0 ] );
        }
    }
    else
    {
        ShowUsage();
        cExitCode = EXIT_COMMONERROR;
    }

    return cExitCode;
}

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

sal_uInt64 BmpSum::GetCRC( Bitmap& rBmp )
{
    BitmapReadAccess* pRAcc = rBmp.AcquireReadAccess();
    sal_uInt64        nRet = 0;
    sal_uInt32        nCrc = 0;

    if( pRAcc && pRAcc->Width() && pRAcc->Height() )
    {
        SVBT32 aBT32;

        for( long nY = 0; nY < pRAcc->Height(); ++nY )
        {
            for( long nX = 0; nX < pRAcc->Width(); ++nX )
            {
                const BitmapColor aCol( pRAcc->GetColor( nY, nX ) );

                UInt32ToSVBT32( aCol.GetRed(), aBT32 );
                nCrc = rtl_crc32( nCrc, aBT32, 4 );

                UInt32ToSVBT32( aCol.GetGreen(), aBT32 );
                nCrc = rtl_crc32( nCrc, aBT32, 4 );

                UInt32ToSVBT32( aCol.GetBlue(), aBT32 );
                nCrc = rtl_crc32( nCrc, aBT32, 4 );
            }
        }

        nRet = ( ( (sal_uInt64) pRAcc->Width() ) << 48 ) |
               ( ( (sal_uInt64) pRAcc->Height() ) << 32 ) |
               ( (sal_uInt64) nCrc );
    }

    rBmp.ReleaseAccess( pRAcc );

    return nRet;
}

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

void BmpSum::ProcessFile( const String& rBmpFileName )
{
    SvFileStream aIStm( rBmpFileName, STREAM_READ );

    if( aIStm.IsOpen() )
    {
        Bitmap aBmp;

        aIStm >> aBmp;

        if( !aBmp.IsEmpty() )
        {
#ifdef WNT
            fprintf( stdout, "%I64u\r\n", GetCRC( aBmp ) );
#else
            fprintf( stdout, "%llu\r\n", GetCRC( aBmp ) );
#endif
        }
        else
        {
            aIStm.ResetError();
            aIStm.Seek( 0 );

               ::vcl::PNGReader aPngReader( aIStm );

            aBmp = aPngReader.Read().GetBitmap();

              if( !aBmp.IsEmpty() )
            {
#ifdef WNT
                fprintf( stdout, "%I64u\r\n", GetCRC( aBmp ) );
#else
                fprintf( stdout, "%llu\r\n", GetCRC( aBmp ) );
#endif
            }
            else
                Message( String( RTL_CONSTASCII_USTRINGPARAM( "file not valid" ) ), EXIT_INVALIDFILE );
        }
    }
}

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

void BmpSum::ProcessFileList( const String& rInFileList,
                              const String& rOutFileList,
                              const String& rOutPath )
{
    SvFileStream    aIStm( rInFileList, STREAM_READ );
    SvFileStream    aOStm( rOutFileList, STREAM_WRITE | STREAM_TRUNC );
    const DirEntry  aBaseDir( rOutPath );

    if( rOutPath.Len() )
        aBaseDir.MakeDir();

    if( aIStm.IsOpen() && aOStm.IsOpen() )
    {
        ByteString                  aReadLine;
        ::std::set< ByteString >    aFileNameSet;

        while( aIStm.ReadLine( aReadLine ) )
        {
            if( aReadLine.Len() )
                aFileNameSet.insert( aReadLine );

            if( aReadLine.Search( "enus" ) != STRING_NOTFOUND )
            {
                static const char* aLanguages[] =
                {
                    "chinsim",
                    "chintrad",
                    "dtch",
                    "enus",
                    "fren",
                    "hebrew"
                    "ital",
                    "japn",
                    "korean",
                    "pol",
                    "poln",
                    "port",
                    "russ",
                    "span",
                    "turk"
                };

                for( sal_uInt32 n = 0; n < 14; ++n )
                {
                    ByteString aLangPath( aReadLine );

                    aLangPath.SearchAndReplace( "enus", aLanguages[ n ] );

                    DirEntry aTestFile( aLangPath );

                    if( aTestFile.Exists() )
                        aFileNameSet.insert( aLangPath );
                }
            }

            aReadLine.Erase();
        }

        aIStm.Close();

        ::std::set< ByteString >::iterator aIter( aFileNameSet.begin() );
        ::std::map< sal_uInt64, ::std::vector< ByteString > > aFileNameMap;

        while( aIter != aFileNameSet.end() )
        {
            ByteString      aStr( *aIter++ );
            SvFileStream    aBmpStm( String( aStr.GetBuffer(), RTL_TEXTENCODING_ASCII_US ), STREAM_READ );
            sal_uInt64      nCRC = 0;

            if( aBmpStm.IsOpen() )
            {
                Bitmap aBmp;

                aBmpStm >> aBmp;

                if( !aBmp.IsEmpty() )
                    nCRC = GetCRC( aBmp );
                else
                {
                    aBmpStm.ResetError();
                    aBmpStm.Seek( 0 );

                       ::vcl::PNGReader aPngReader( aBmpStm );

                    aBmp = aPngReader.Read().GetBitmap();

                      if( !aBmp.IsEmpty() )
                           nCRC = GetCRC( aBmp );

                    else
                        fprintf( stderr, "%s could not be opened\n", aStr.GetBuffer() );
               }

                aBmpStm.Close();
            }

            if( nCRC )
            {
                ::std::map< sal_uInt64, ::std::vector< ByteString > >::iterator aFound( aFileNameMap.find( nCRC ) );

                if( aFound != aFileNameMap.end() )
                    (*aFound).second.push_back( aStr );
                else
                {
                    ::std::vector< ByteString > aVector( 1, aStr );
                    aFileNameMap[ nCRC ]  = aVector;
                }

            }
            else
            {
                ::std::vector< ByteString > aVector( 1, aStr );
                aFileNameMap[ nCRC ]  = aVector;
            }
        }

        ::std::map< sal_uInt64, ::std::vector< ByteString > >::iterator aMapIter( aFileNameMap.begin() );
        sal_uInt32 nFileCount = 0;

        while( aMapIter != aFileNameMap.end() )
        {
            ::std::pair< const sal_uInt64, ::std::vector< ByteString > > aPair( *aMapIter++ );
            ::std::vector< ByteString > aFileNameVector( aPair.second );

            // write new entries
            for( sal_uInt32 i = 0; i < aFileNameVector.size(); ++i )
            {
                ByteString  aStr( ByteString::CreateFromInt64( aPair.first ) );
                ByteString  aFileName( aFileNameVector[ i ] );
                DirEntry    aSrcFile( aFileName );

                aStr += '\t';
                aStr += aFileName;

                aOStm.WriteLine( aStr );

                // copy bitmap
                if( rOutPath.Len() )
                {
                    if( aFileName.Search( ":\\" ) != STRING_NOTFOUND )
                        aFileName.Erase( 0, aFileName.Search( ":\\" ) + 2 );

                    aFileName.SearchAndReplaceAll( '\\', '/' );

                    sal_uInt16  nTokenCount = aFileName.GetTokenCount( '/' );
                    DirEntry    aNewDir( aBaseDir );

                    for( sal_uInt16 n = 0; ( n < nTokenCount - 1 ); n++ )
                    {
                        aNewDir += DirEntry( aFileName.GetToken( n, '/' ) );
                        aNewDir.MakeDir();
                    }

                    aNewDir += DirEntry( aFileName.GetToken( nTokenCount - 1, '/' ) );
                    aSrcFile.CopyTo( aNewDir, FSYS_ACTION_COPYFILE );
                }
            }

            ++nFileCount;
        }

        fprintf(
            stdout, "unique file count: %lu",
            sal::static_int_cast< unsigned long >(nFileCount) );
    }
}

// --------
// - Main -
// --------

int main( int nArgCount, char* ppArgs[] )
{
    ::std::vector< String > aArgs;
    BmpSum                  aBmpSum;

    InitVCL( com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >() );

    for( int i = 1; i < nArgCount; i++ )
        aArgs.push_back( String( ppArgs[ i ], RTL_TEXTENCODING_ASCII_US ) );

    return aBmpSum.Start( aArgs );
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <udis86.h>

#include <disassembly.hh>

static int next_byte(ud_t *ud);

class Disassembly : public IDisassembly
{
public:
	friend int next_byte(ud_t *);

	Disassembly()
	{
		ud_init(&m_ud);

		ud_set_user_opaque_data(&m_ud, (void *)this);
		ud_set_input_hook(&m_ud, next_byte);

		ud_set_mode(&m_ud, 32);

		m_data = NULL;
		m_dataSize = 0;
		m_count = 0;
	}

	bool execute(IDisassembly::IInstructionListener *listener,
			uint8_t *data, size_t size)
	{
		if (!listener)
			return false;

		if (!data || size == 0)
			return false;

		m_data = data;
		m_dataSize = size;
		m_count = 0;

		while (ud_disassemble(&m_ud)) {
			bool mem = (m_ud.operand[0].type == UD_OP_MEM ||
					m_ud.operand[1].type == UD_OP_MEM ||
					m_ud.operand[2].type == UD_OP_MEM);

			bool call = m_ud.mnemonic == UD_Icall;

			bool branch = m_ud.mnemonic == UD_Ijo ||
					m_ud.mnemonic == UD_Ijno ||
					m_ud.mnemonic == UD_Ijb ||
					m_ud.mnemonic == UD_Ijae ||
					m_ud.mnemonic == UD_Ijz ||
					m_ud.mnemonic == UD_Ijnz ||
					m_ud.mnemonic == UD_Ijbe ||
					m_ud.mnemonic == UD_Ija ||
					m_ud.mnemonic == UD_Ijs ||
					m_ud.mnemonic == UD_Ijns ||
					m_ud.mnemonic == UD_Ijp ||
					m_ud.mnemonic == UD_Ijnp ||
					m_ud.mnemonic == UD_Ijl ||
					m_ud.mnemonic == UD_Ijge ||
					m_ud.mnemonic == UD_Ijle ||
					m_ud.mnemonic == UD_Ijg ||
					m_ud.mnemonic == UD_Ijcxz ||
					m_ud.mnemonic == UD_Ijecxz ||
					m_ud.mnemonic == UD_Ijrcxz ||
					m_ud.mnemonic == UD_Ijmp;

			if (mem)
				listener->onMemoryReference(ud_insn_off(&m_ud), false);

			if (call)
				listener->onCall(ud_insn_off(&m_ud));

			if (branch)
				listener->onBranch(ud_insn_off(&m_ud));
		}

		return true;
	}

private:
	int nextUdByte()
	{
		if (m_count == m_dataSize)
			return UD_EOI;

		return m_data[m_count++];
	}

	ud_t m_ud;
	uint8_t *m_data;
	size_t m_dataSize;
	size_t m_count;
};

static int next_byte(ud_t *ud)
{
	Disassembly *p = (Disassembly *)ud_get_user_opaque_data(ud);

	return p->nextUdByte();
}

IDisassembly &IDisassembly::getInstance()
{
	static Disassembly *instance;

	if (!instance)
		instance = new Disassembly();

	return *instance;
}
<commit_msg>disassembly: Set the input hook for each run<commit_after>#include <stdio.h>
#include <udis86.h>

#include <disassembly.hh>

static int next_byte(ud_t *ud);

class Disassembly : public IDisassembly
{
public:
	friend int next_byte(ud_t *);

	Disassembly()
	{
		ud_init(&m_ud);

		ud_set_user_opaque_data(&m_ud, (void *)this);
		ud_set_mode(&m_ud, 32);

		m_data = NULL;
		m_dataSize = 0;
		m_count = 0;
	}

	bool execute(IDisassembly::IInstructionListener *listener,
			uint8_t *data, size_t size)
	{
		if (!listener)
			return false;

		if (!data || size == 0)
			return false;

		m_data = data;
		m_dataSize = size;
		m_count = 0;

		ud_set_input_hook(&m_ud, next_byte);

		while (ud_disassemble(&m_ud)) {
			bool mem = (m_ud.operand[0].type == UD_OP_MEM ||
					m_ud.operand[1].type == UD_OP_MEM ||
					m_ud.operand[2].type == UD_OP_MEM);

			bool call = m_ud.mnemonic == UD_Icall;

			bool branch = m_ud.mnemonic == UD_Ijo ||
					m_ud.mnemonic == UD_Ijno ||
					m_ud.mnemonic == UD_Ijb ||
					m_ud.mnemonic == UD_Ijae ||
					m_ud.mnemonic == UD_Ijz ||
					m_ud.mnemonic == UD_Ijnz ||
					m_ud.mnemonic == UD_Ijbe ||
					m_ud.mnemonic == UD_Ija ||
					m_ud.mnemonic == UD_Ijs ||
					m_ud.mnemonic == UD_Ijns ||
					m_ud.mnemonic == UD_Ijp ||
					m_ud.mnemonic == UD_Ijnp ||
					m_ud.mnemonic == UD_Ijl ||
					m_ud.mnemonic == UD_Ijge ||
					m_ud.mnemonic == UD_Ijle ||
					m_ud.mnemonic == UD_Ijg ||
					m_ud.mnemonic == UD_Ijcxz ||
					m_ud.mnemonic == UD_Ijecxz ||
					m_ud.mnemonic == UD_Ijrcxz ||
					m_ud.mnemonic == UD_Ijmp;

			if (mem)
				listener->onMemoryReference(ud_insn_off(&m_ud), false);

			if (call)
				listener->onCall(ud_insn_off(&m_ud));

			if (branch)
				listener->onBranch(ud_insn_off(&m_ud));
		}

		return true;
	}

private:
	int nextUdByte()
	{
		if (m_count == m_dataSize)
			return UD_EOI;

		return m_data[m_count++];
	}

	ud_t m_ud;
	uint8_t *m_data;
	size_t m_dataSize;
	size_t m_count;
};

static int next_byte(ud_t *ud)
{
	Disassembly *p = (Disassembly *)ud_get_user_opaque_data(ud);

	return p->nextUdByte();
}

IDisassembly &IDisassembly::getInstance()
{
	static Disassembly *instance;

	if (!instance)
		instance = new Disassembly();

	return *instance;
}
<|endoftext|>


<commit_before>
#ifndef SVTOOLS_COLLATORRESSOURCE_HXX
#define SVTOOLS_COLLATORRESSOURCE_HXX

#ifndef INCLUDED_SVTDLLAPI_H
#include "svtools/svtdllapi.h"
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif

class CollatorRessourceData;

class SVT_DLLPUBLIC CollatorRessource
{
    private:

        CollatorRessourceData  *mp_Data;

    public:
                                CollatorRessource ();
                                ~CollatorRessource ();
        const String&           GetTranslation (const String& r_Algorithm);
};

#endif /* SVTOOLS_COLLATORRESSOURCE_HXX */

<commit_msg>INTEGRATION: CWS changefileheader (1.3.546); FILE MERGED 2008/04/01 15:44:18 thb 1.3.546.2: #i85898# Stripping all external header guards 2008/04/01 12:43:05 thb 1.3.546.1: #i85898# Stripping all external header guards<commit_after>
#ifndef SVTOOLS_COLLATORRESSOURCE_HXX
#define SVTOOLS_COLLATORRESSOURCE_HXX

#include "svtools/svtdllapi.h"
#include <tools/string.hxx>

class CollatorRessourceData;

class SVT_DLLPUBLIC CollatorRessource
{
    private:

        CollatorRessourceData  *mp_Data;

    public:
                                CollatorRessource ();
                                ~CollatorRessource ();
        const String&           GetTranslation (const String& r_Algorithm);
};

#endif /* SVTOOLS_COLLATORRESSOURCE_HXX */

<|endoftext|>


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

// SMARTTAGS

#ifndef _STMENU_HXX
#define _STMENU_HXX

#ifndef _MENU_HXX //autogen
#include <vcl/menu.hxx>
#endif

#include <vector>

#ifndef _COM_SUN_STAR_SMARTTAGS_XSMARTTAGACTION_HPP_
#include <com/sun/star/smarttags/XSmartTagAction.hpp>
#endif

#ifndef _COM_SUN_STAR_SMARTTAGS_XSTRINGKEYMAP_HPP_
#include <com/sun/star/container/XStringKeyMap.hpp>
#endif

#ifndef _COM_SUN_STAR_TEXT_XTEXTRANGE_HPP_
#include <com/sun/star/text/XTextRange.hpp>
#endif

class SwView;

/** Class: SwSmartTagPopup

   This class contains the implementation of the smarttag popup
   menu that is opened if a user clicks on an underlined word.

   The menu is built in the constructor and the actions for each
   menu entry are invoked in the excute-method.
*/

class SwSmartTagPopup : public PopupMenu
{
    SwView*  mpSwView;
    com::sun::star::uno::Reference< com::sun::star::text::XTextRange > mxTextRange;

    struct InvokeAction
    {
        com::sun::star::uno::Reference< com::sun::star::smarttags::XSmartTagAction > mxAction;
        com::sun::star::uno::Reference< com::sun::star::container::XStringKeyMap > mxSmartTagProperties;
        sal_uInt32 mnActionID;
        InvokeAction( com::sun::star::uno::Reference< com::sun::star::smarttags::XSmartTagAction > xAction,
                      com::sun::star::uno::Reference< com::sun::star::container::XStringKeyMap > xSmartTagProperties,
                      sal_uInt32 nActionID ) : mxAction( xAction ), mxSmartTagProperties( xSmartTagProperties ), mnActionID( nActionID ) {}
    };

    std::vector< InvokeAction > maInvokeActions;

public:
    SwSmartTagPopup( SwView* _pSwView,
                     ::com::sun::star::uno::Sequence< rtl::OUString >& rSmartTagTypes,
                     ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::container::XStringKeyMap > >& rStringKeyMaps,
                     ::com::sun::star::uno::Reference< com::sun::star::text::XTextRange > xTextRange );

    sal_uInt16  Execute( Window* pWin, const Rectangle& rPopupPos );
};

#endif

<commit_msg>INTEGRATION: CWS swwarnings (1.2.102); FILE MERGED 2007/08/24 10:55:15 tl 1.2.102.3: #i69287# warning-free code 2007/08/20 15:53:18 tl 1.2.102.2: RESYNC: (1.2-1.3); FILE MERGED 2007/03/05 12:45:49 tl 1.2.102.1: #i69287# warning-free code<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: stmenu.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2007-09-27 12:10:13 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    Initial Contributer was Fabalabs Software GmbH, Jakob Lechner
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// SMARTTAGS

#ifndef _STMENU_HXX
#define _STMENU_HXX

#ifndef _MENU_HXX //autogen
#include <vcl/menu.hxx>
#endif

#include <vector>

#ifndef _COM_SUN_STAR_SMARTTAGS_XSMARTTAGACTION_HPP_
#include <com/sun/star/smarttags/XSmartTagAction.hpp>
#endif

#ifndef _COM_SUN_STAR_SMARTTAGS_XSTRINGKEYMAP_HPP_
#include <com/sun/star/container/XStringKeyMap.hpp>
#endif

#ifndef _COM_SUN_STAR_TEXT_XTEXTRANGE_HPP_
#include <com/sun/star/text/XTextRange.hpp>
#endif

class SwView;

/** Class: SwSmartTagPopup

   This class contains the implementation of the smarttag popup
   menu that is opened if a user clicks on an underlined word.

   The menu is built in the constructor and the actions for each
   menu entry are invoked in the excute-method.
*/

class SwSmartTagPopup : public PopupMenu
{
    SwView*  mpSwView;
    com::sun::star::uno::Reference< com::sun::star::text::XTextRange > mxTextRange;

    struct InvokeAction
    {
        com::sun::star::uno::Reference< com::sun::star::smarttags::XSmartTagAction > mxAction;
        com::sun::star::uno::Reference< com::sun::star::container::XStringKeyMap > mxSmartTagProperties;
        sal_uInt32 mnActionID;
        InvokeAction( com::sun::star::uno::Reference< com::sun::star::smarttags::XSmartTagAction > xAction,
                      com::sun::star::uno::Reference< com::sun::star::container::XStringKeyMap > xSmartTagProperties,
                      sal_uInt32 nActionID ) : mxAction( xAction ), mxSmartTagProperties( xSmartTagProperties ), mnActionID( nActionID ) {}
    };

    std::vector< InvokeAction > maInvokeActions;

protected:
  using PopupMenu::Execute;

public:
    SwSmartTagPopup( SwView* _pSwView,
                     ::com::sun::star::uno::Sequence< rtl::OUString >& rSmartTagTypes,
                     ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::container::XStringKeyMap > >& rStringKeyMaps,
                     ::com::sun::star::uno::Reference< com::sun::star::text::XTextRange > xTextRange );

    sal_uInt16  Execute( const Rectangle& rPopupPos, Window* pWin );
};

#endif

<|endoftext|>


<commit_before>#include "../include/image.h"
#include "../include/glinclude.h"
#include "../include/math.h"
#include <math.h>
#include <stdlib.h>
#include "../include/renderer.h"

// TAREA: Declarar funciones de stb_image.c

extern "C" {
	unsigned char *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp);
	void stbi_image_free(void *retval_from_stbi_load);
}

Image::Image(const String &filename, uint16 hframes, uint16 vframes) {
	this->filename = filename;
	this->hframes = hframes;
	this->vframes = vframes;
	width = 0;
	height = 0;
	handlex = 0;
	handley = 0;
	gltex = 0;
	lastU = 1.0;
	lastV = 1.0;

	int width32 = 0;
	int height32 = 0;
	int *ptrComp = NULL;

	uint8 *buffer = stbi_load(filename.ToCString(), &width32, &height32, ptrComp, 4);

	width = static_cast<uint16>(width32);
	height = static_cast<uint16>(height32);

	//PO2 -> Power of 2
	double widthPO2 = pow(2, ceil(Log2(width)));
	double heightPO2 = pow(2, ceil(Log2(height)));

	if (widthPO2 != width || heightPO2 != height) {
		lastU = static_cast<double>(width / widthPO2);
		lastV = static_cast<double>(height / heightPO2);

		widthPO2 = static_cast<uint16>(widthPO2);
		heightPO2 = static_cast<uint16>(heightPO2);

		//allocating memory for new buffer
		uint8 *bufferPO2 = (uint8 *)malloc(widthPO2 * heightPO2 * 4);		// * 4 because each pixel needs 32 bits

		uint8 * const origBufferPO2pos = bufferPO2;		//ptr to keep reference to the bufferPO2

		//setting pixels to white -> as texture has transparent pixels, check everything is working properly
		memset(bufferPO2, 255, widthPO2 * heightPO2 * 4);

		for (unsigned int h = 0; h < height; h++) {
			memcpy(bufferPO2, buffer, width * 4);
			bufferPO2 += static_cast<int>(widthPO2) * 4;
			buffer += (width * 4);
		}

		bufferPO2 = origBufferPO2pos;
		//bufferPO2 -= static_cast<int>(widthPO2) * height * 4;

		//call to genImage, creating texture in VRAM
		this->gltex = Renderer::Instance().GenImage(bufferPO2, widthPO2, heightPO2);

		//now, the texture is in VRAM so we no longer need it in RAM
		stbi_image_free(bufferPO2);
	}
	else {
		// Generamos la textura
		if ( buffer ) {
			this->gltex = Renderer::Instance().GenImage(buffer, width, height);
			stbi_image_free(buffer);
		}
	}
}

Image::~Image() {
	if (gltex != 0) Renderer::Instance().DeleteImage(this->gltex);
}

void Image::Bind() const {
	Renderer::Instance().BindImage(this->gltex);
}
<commit_msg>Refactor<commit_after>#include "../include/image.h"
#include "../include/glinclude.h"
#include "../include/math.h"
#include <math.h>
#include <stdlib.h>
#include "../include/renderer.h"

// TAREA: Declarar funciones de stb_image.c

extern "C" {
	unsigned char *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp);
	void stbi_image_free(void *retval_from_stbi_load);
}

Image::Image(const String &filename, uint16 hframes, uint16 vframes) {
	this->filename = filename;
	this->hframes = hframes;
	this->vframes = vframes;
	width = 0;
	height = 0;
	handlex = 0;
	handley = 0;
	gltex = 0;
	lastU = 1.0;
	lastV = 1.0;

	int width32 = 0;
	int height32 = 0;
	int *ptrComp = NULL;

	uint8 *buffer = stbi_load(filename.ToCString(), &width32, &height32, ptrComp, 4);

	width = static_cast<uint16>(width32);
	height = static_cast<uint16>(height32);

	//PO2 -> Power of 2
	double widthPO2 = pow(2, ceil(Log2(width)));
	double heightPO2 = pow(2, ceil(Log2(height)));

	if (widthPO2 != width || heightPO2 != height) {
		lastU = static_cast<double>(width / widthPO2);
		lastV = static_cast<double>(height / heightPO2);

		widthPO2 = static_cast<uint16>(widthPO2);
		heightPO2 = static_cast<uint16>(heightPO2);

		//allocating memory for new buffer
		uint8 *bufferPO2 = (uint8 *)malloc(widthPO2 * heightPO2 * 4);		// * 4 because each pixel needs 32 bits

		uint8 * const origBufferPO2pos = bufferPO2;		//ptr to keep reference to the bufferPO2

		//setting pixels to white -> as texture has transparent pixels, check everything is working properly
		memset(bufferPO2, 255, widthPO2 * heightPO2 * 4);

		for (unsigned int h = 0; h < height; h++) {
			memcpy(bufferPO2, buffer, width * 4);
			bufferPO2 += static_cast<int>(widthPO2) * 4;
			buffer += (width * 4);
		}

		bufferPO2 = origBufferPO2pos;
		//bufferPO2 -= static_cast<int>(widthPO2) * height * 4;

		//call to genImage, creating texture in VRAM
		this->gltex = Renderer::Instance().GenImage(bufferPO2, widthPO2, heightPO2);

		//now, the texture is in VRAM so we no longer need it in RAM
		stbi_image_free(bufferPO2);
	} else {
		// Generamos la textura
		if ( buffer ) {
			this->gltex = Renderer::Instance().GenImage(buffer, width, height);
			stbi_image_free(buffer);
		}
	}
}

Image::~Image() {
	if (gltex != 0) Renderer::Instance().DeleteImage(this->gltex);
}

void Image::Bind() const {
	Renderer::Instance().BindImage(this->gltex);
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_l2_flush.H $       */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file p9_l2_flush.H
/// @brief Flush the P9 L2 cache (FAPI)
///
/// *HWP HWP Owner   : Benjamin Gass <bgass@us.ibm.com>
/// *HWP FW Owner    : Bilicon Patil <bilpatil@in.ibm.com>
/// *HWP Team        : Quad
/// *HWP Consumed by : FSP
/// *HWP Level       : 2
///
///  Procedure Additional Comments:
///
///  High-level procedure flow:
///    o Poll Purge Engine Command Register to confirm that purge engine
///      is idle before starting (fail if self-imposed timeout occurs)
///    o Write Purge Engine Command Register to kick off complete/requested
///      cache flush operation
///    o Poll Purge Engine Command Register to wait for completion of
///      flush (fail if self-imposed timeout occurs) & check for errors
///
///  Successful operations assumes that:
///    o System clocks are running
///    o While not strictly required, to guarantee a completely empty cache
///      at the end of the procedure execution, instructions should be
///      stopped on the core underneath the L2 being flushed before the flush
///      is executed
///

#ifndef _P9_L2_FLUSH_H_
#define _P9_L2_FLUSH_H_

//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------

#include <fapi2.H>

//------------------------------------------------------------------------------
// Constants
//------------------------------------------------------------------------------

namespace p9core
{

// This structure specifies the data needed in case when there
// is request for specific L2 purges
struct purgeData_t
{
    uint8_t iv_cmdType: 4;
    uint8_t iv_cmdMem: 3;
    uint8_t iv_cmdBank: 1;
    uint8_t iv_cmdCGC: 8;

    purgeData_t(): iv_cmdType(0),
        iv_cmdMem(0),
        iv_cmdBank(0),
        iv_cmdCGC(0) {}
};

} // end of p9core namespace

//------------------------------------------------------------------------------
// Structure definitions
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// Function prototypes
//------------------------------------------------------------------------------

typedef fapi2::ReturnCode (*p9_l2_flush_FP_t)
(const fapi2::Target < fapi2::TARGET_TYPE_EX >& i_target,
 const p9core::purgeData_t& i_purgeData);

extern "C"
{

///
/// @brief p9_l2_flush HWP to flush entire content of L2 cache via purge engine
/// @param[in] i_target Ex target
/// @param[in] i_purgeData Specifies a particular purge type
/// @return: FAPI2_RC_SUCCESS if purge operation completes successfully,
///          RC_P9_L2_FLUSH_UNKNOWN_PLATFORM
///              if executed on unsupported platform,
///          RC_P9_L2_FLUSH_PURGE_REQ_OUTSTANDING
///              if called when existing L2 purge is in progress,
///          RC_P9_L2_FLUSH_CMD_TIMEOUT
///              if purge operation does not complete in expected time,
///          RC_P9_L2_FLUSH_CMD_ERROR
///              if purge operation reports error,
///          else FAPI getscom/putscom return code for failing operation
///
    fapi2::ReturnCode p9_l2_flush(const fapi2::Target < fapi2::TARGET_TYPE_EX >
                                  & i_target,
                                  const p9core::purgeData_t& i_purgeData);

} // end of extern C

#endif // _P9_L2_FLUSH_H_
<commit_msg>L3 Update - p9_l2/l3_flush.C<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_l2_flush.H $       */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file p9_l2_flush.H
/// @brief Flush the P9 L2 cache (FAPI)
///
/// *HWP HWP Owner   : Benjamin Gass <bgass@us.ibm.com>
/// *HWP FW Owner    : Thi Tran <thi@us.ibm.com>
/// *HWP Team        : Quad
/// *HWP Consumed by : FSP and SBE
/// *HWP Level       : 3
///
///  Procedure Additional Comments:
///
///  High-level procedure flow:
///    o Poll Purge Engine Command Register to confirm that purge engine
///      is idle before starting (fail if self-imposed timeout occurs)
///    o Write Purge Engine Command Register to kick off complete/requested
///      cache flush operation
///    o Poll Purge Engine Command Register to wait for completion of
///      flush (fail if self-imposed timeout occurs) & check for errors
///
///  Successful operations assumes that:
///    o System clocks are running
///    o While not strictly required, to guarantee a completely empty cache
///      at the end of the procedure execution, instructions should be
///      stopped on the core underneath the L2 being flushed before the flush
///      is executed
///

#ifndef _P9_L2_FLUSH_H_
#define _P9_L2_FLUSH_H_

//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------

#include <fapi2.H>

//------------------------------------------------------------------------------
// Structure definitions
//------------------------------------------------------------------------------
namespace p9core
{

// This structure specifies the data needed in case when there
// is request for specific L2 purges
struct purgeData_t
{
    uint8_t iv_cmdType: 4;
    uint8_t iv_cmdMem: 3;
    uint8_t iv_cmdBank: 1;
    uint8_t iv_cmdCGC: 8;

    purgeData_t(): iv_cmdType(0),
        iv_cmdMem(0),
        iv_cmdBank(0),
        iv_cmdCGC(0) {}
};

} // end of p9core namespace

//------------------------------------------------------------------------------
// Function prototypes
//------------------------------------------------------------------------------
typedef fapi2::ReturnCode (*p9_l2_flush_FP_t)
(const fapi2::Target < fapi2::TARGET_TYPE_EX >& i_target,
 const p9core::purgeData_t& i_purgeData);

extern "C"
{

///
/// @brief Flush entire content of L2 cache via purge engine
/// @param[in] i_target EX target
/// @param[in] i_purgeData Specifies a particular purge type
/// @return: FAPI2_RC_SUCCESS if purge operation completes successfully,
///          RC_P9_L2_FLUSH_PURGE_REQ_OUTSTANDING
///              if called when existing L2 purge is in progress,
///          RC_P9_L2_FLUSH_CMD_TIMEOUT
///              if purge operation does not complete in expected time,
///          RC_P9_L2_FLUSH_CMD_ERROR
///              if purge operation reports error,
///          else FAPI getscom/putscom return code for failing operation
///
    fapi2::ReturnCode p9_l2_flush(const fapi2::Target < fapi2::TARGET_TYPE_EX >
                                  & i_target,
                                  const p9core::purgeData_t& i_purgeData);

} // end of extern C

#endif // _P9_L2_FLUSH_H_
<|endoftext|>


<commit_before>#include "combiner_gridcompare_hist.h"

/// SYSTEM
#include <pluginlib/class_list_macros.h>
#include <QComboBox>

PLUGINLIB_EXPORT_CLASS(csapex::GridCompareHist, csapex::BoxedObject)

using namespace csapex;
using namespace cv_grid;

GridCompareHist::GridCompareHist() :
    GridCompare(State::Ptr(new State)),
    container_hist_sliders_(NULL)
{
    private_state_gch_ = dynamic_cast<State*>(state_.get());
    assert(private_state_gch_);
}

GridCompareHist::GridCompareHist(GridCompare::State::Ptr state) :
    GridCompare(state),
    container_hist_sliders_(NULL)
{
    private_state_gch_ = dynamic_cast<State*>(state_.get());
    assert(private_state_gch_);
}

cv::Mat GridCompareHist::combine(const cv::Mat img1, const cv::Mat mask1, const cv::Mat img2, const cv::Mat mask2)
{
    if(!img1.empty() && !img2.empty()) {
        /// PREPARE
        if(img1.channels() != img2.channels())
            throw std::runtime_error("Channel count is not matching!");
        //        if(img1.rows != img2.rows || img1.cols != img2.cols)
        //            throw std::runtime_error("Dimension is not matching!");

        if(private_state_gch_->channel_count != img1.channels()) {
            private_state_gch_->channel_count = img1.channels();
            private_state_gch_->bins.clear();
            private_state_gch_->eps.clear();
            Q_EMIT modelChanged();
        }

        updateSliderMaxima(img1.cols, img1.rows);

        /// COMPUTE
        if(hist_sliders_.size() == private_state_gch_->channel_count) {
            state_buffer_gch_ = *private_state_gch_;
            GridHist g1, g2;
            prepareGrid(g1, img1, mask1, state_buffer_gch_.grid_width, state_buffer_gch_.grid_width);
            prepareGrid(g2, img2, mask2, state_buffer_gch_.grid_width, state_buffer_gch_.grid_width);

            cv::Mat out;
            render_grid(g1, g2, cv::Size(10,10), out);
            return out;
        }
    }
    return cv::Mat();
}

void GridCompareHist::updateDynamicGui(QBoxLayout *layout)
{
    QVBoxLayout *internal_layout;
    if(container_hist_sliders_ != NULL) {
        container_hist_sliders_->deleteLater();
    }
    internal_layout = new QVBoxLayout;

    for(int i = 0 ; i < private_state_gch_->channel_count ; i++) {
        std::stringstream ch;
        ch << i + 1;

        int    default_bin = 32;
        double default_eps = 0.0;

        if(private_state_gch_->bins.size() < private_state_gch_->channel_count ) {
            private_state_gch_->bins.push_back(default_bin);
            private_state_gch_->eps.push_back(default_eps);
        } else {
            default_bin = private_state_gch_->bins[i];
            default_eps = private_state_gch_->eps[i];
        }

        QSlider *bins = QtHelper::makeSlider(internal_layout, "Ch." + ch.str() + " bins", default_bin, 1, 1000);
        QDoubleSlider *eps = QtHelper::makeDoubleSlider(internal_layout, "Ch." + ch.str() + " eps", default_eps, 0.0, 255.0, 0.01);
        addHistSliders(bins, eps);
    }

    container_hist_sliders_ = QtHelper::wrapLayout(internal_layout);
    layout->addWidget(container_hist_sliders_);

}

void GridCompareHist::updateState(int value)
{
    if(state_mutex_.tryLock()) {
        private_state_gch_->combo_index = combo_compare_->currentIndex();
        private_state_gch_->grid_width  = slide_width_->value();
        private_state_gch_->grid_height = slide_height_->value();
        state_mutex_.unlock();
    }
}

void GridCompareHist::fill(QBoxLayout *layout)
{
    GridCompare::fill(layout);

    combo_compare_ = new QComboBox();
    combo_compare_->addItem("Correlation");
    combo_compare_->addItem("Chi-Square");
    combo_compare_->addItem("Intersection");
    combo_compare_->addItem("Hellinger");
    combo_compare_->addItem("Squared Distances");

    int index = combo_compare_->findText("Correlation");
    index_to_compare_.insert(intPair(index, CV_COMP_CORREL));
    index = combo_compare_->findText("Chi-Square");
    index_to_compare_.insert(intPair(index, CV_COMP_CHISQR));
    index = combo_compare_->findText("Intersection");
    index_to_compare_.insert(intPair(index, CV_COMP_INTERSECT));
    index = combo_compare_->findText("Hellinger");
    index_to_compare_.insert(intPair(index, CV_COMP_BHATTACHARYYA));
    index = combo_compare_->findText("Squared Distances");
    index_to_compare_.insert(intPair(index, AttrHistogram::CV_COMP_SQRD));

    layout->addWidget(combo_compare_);
    private_state_gch_->combo_index = combo_compare_->currentIndex();

    connect(combo_compare_, SIGNAL(currentIndexChanged(int)), this, SLOT(updateState(int)));
    connect(slide_height_, SIGNAL(valueChanged(int)), this, SLOT(updateState(int)));
    connect(slide_width_, SIGNAL(valueChanged(int)), this, SLOT(updateState(int)));

}

void GridCompareHist::prepareGrid(GridHist &g, const cv::Mat &img, const cv::Mat &mask, const int width, const int height)
{
    AttrHistogram::Params p;
    prepareHistParams(p.bins, p.ranges, p.eps);
    p.method = index_to_compare_[private_state_gch_->combo_index];
    p.image  = img;
    cv_grid::prepare_grid<AttrHistogram>(g, height, width, p, mask, 1.0);
}

void GridCompareHist::addHistSliders(QSlider *bins, QDoubleSlider *eps)
{
    HistSliderPair p;
    p.first = bins;
    p.second = eps;
    hist_sliders_.push_back(p);
}

void GridCompareHist::prepareHistParams(cv::Mat &bins, cv::Mat &ranges, cv::Scalar &eps)
{
    bins = cv::Mat_<int>(private_state_gch_->channel_count, 1);
    ranges = cv::Mat_<float>(private_state_gch_->channel_count * 2 ,1);
    for(int i = 0 ; i < private_state_gch_->channel_count ; i++) {
        HistSliderPair p = hist_sliders_[i];
        bins.at<int>(i)     = p.first->value();
        ranges.at<float>(2 * i)     = 0.f;
        ranges.at<float>(2 * i + 1) = 256.f;
        eps[i]          = p.second->doubleValue();

        /// MEMENTO
        private_state_gch_->bins[i] = p.first->value();
        private_state_gch_->eps[i] = p.second->doubleValue();
    }
}

/// MEMENTO ------------------------------------------------------------------------------------
void GridCompareHist::setState(Memento::Ptr memento)
{
    state_.reset(new State);
    State::Ptr s = boost::dynamic_pointer_cast<State>(memento);
    assert(s.get());
    *boost::dynamic_pointer_cast<State>(state_) = *s;
    assert(state_.get());
    private_state_gch_ = boost::dynamic_pointer_cast<State>(state_).get();
    assert(private_state_gch_);

    state_mutex_.lock();
    slide_height_->setValue(private_state_gch_->grid_height);
    slide_width_->setValue(private_state_gch_->grid_width);
    combo_compare_->setCurrentIndex(private_state_gch_->combo_index);
    state_mutex_.unlock();

    Q_EMIT modelChanged();
}

void GridCompareHist::State::readYaml(const YAML::Node &node)
{
    GridCompare::State::readYaml(node);
    node["compare"] >> combo_index;

    const YAML::Node &_bins = node["bins"];
    for(YAML::Iterator it = _bins.begin() ; it != _bins.end() ; it++) {
        int bin_val;
        *it >> bin_val;
        bins.push_back(bin_val);
    }

    const YAML::Node &_eps = node["eps"];
    for(YAML::Iterator it = _eps.begin() ; it != _eps.end() ; it++) {
        double eps_val;
        *it >> eps_val;
        eps.push_back(eps_val);
    }
}

GridCompareHist::State::State() :
    GridCompare::State(),
    combo_index(0)
{
}

Memento::Ptr GridCompareHist::getState() const
{
    State::Ptr memento(new State);
    *memento = *boost::dynamic_pointer_cast<State>(state_);
    return memento;
}

void GridCompareHist::State::writeYaml(YAML::Emitter &out) const
{
    GridCompare::State::writeYaml(out);

    out << YAML::Key << "compare" << YAML::Value << combo_index;
    out << YAML::Key << "bins" << YAML::Value << YAML::BeginSeq;
    for(std::vector<int>::const_iterator it = bins.begin() ; it != bins.end() ; it++) {
        out << *it;
    }
    out << YAML::EndSeq;

    out << YAML::Key << "eps" << YAML::Value << YAML::BeginSeq;
    for(std::vector<double>::const_iterator it = eps.begin() ; it != eps.end() ; it++) {
        out << *it;
    }
    out << YAML::EndSeq;

}
<commit_msg>fixes and rotated template header<commit_after>#include "combiner_gridcompare_hist.h"

/// SYSTEM
#include <pluginlib/class_list_macros.h>
#include <QComboBox>

PLUGINLIB_EXPORT_CLASS(csapex::GridCompareHist, csapex::BoxedObject)

using namespace csapex;
using namespace cv_grid;

GridCompareHist::GridCompareHist() :
    GridCompare(State::Ptr(new State)),
    container_hist_sliders_(NULL)
{
    private_state_gch_ = dynamic_cast<State*>(state_.get());
    assert(private_state_gch_);
}

GridCompareHist::GridCompareHist(GridCompare::State::Ptr state) :
    GridCompare(state),
    container_hist_sliders_(NULL)
{
    private_state_gch_ = dynamic_cast<State*>(state_.get());
    assert(private_state_gch_);
}

cv::Mat GridCompareHist::combine(const cv::Mat img1, const cv::Mat mask1, const cv::Mat img2, const cv::Mat mask2)
{
    if(!img1.empty() && !img2.empty()) {
        /// PREPARE
        if(img1.channels() != img2.channels())
            throw std::runtime_error("Channel count is not matching!");
        //        if(img1.rows != img2.rows || img1.cols != img2.cols)
        //            throw std::runtime_error("Dimension is not matching!");

        if(private_state_gch_->channel_count != img1.channels()) {
            private_state_gch_->channel_count = img1.channels();
            private_state_gch_->bins.clear();
            private_state_gch_->eps.clear();
            Q_EMIT modelChanged();
        }

        updateSliderMaxima(img1.cols, img1.rows);

        /// COMPUTE
        if(hist_sliders_.size() == private_state_gch_->channel_count) {
            state_buffer_gch_ = *private_state_gch_;
            GridHist g1, g2;
            prepareGrid(g1, img1, mask1, state_buffer_gch_.grid_width, state_buffer_gch_.grid_height);
            prepareGrid(g2, img2, mask2, state_buffer_gch_.grid_width, state_buffer_gch_.grid_height);

            cv::Mat out;
            render_grid(g1, g2, cv::Size(10,10), out);
            return out;
        }
    }
    return cv::Mat();
}

void GridCompareHist::updateDynamicGui(QBoxLayout *layout)
{
    QVBoxLayout *internal_layout;
    if(container_hist_sliders_ != NULL) {
        container_hist_sliders_->deleteLater();
    }
    internal_layout = new QVBoxLayout;

    for(int i = 0 ; i < private_state_gch_->channel_count ; i++) {
        std::stringstream ch;
        ch << i + 1;

        int    default_bin = 32;
        double default_eps = 0.0;

        if(private_state_gch_->bins.size() < private_state_gch_->channel_count ) {
            private_state_gch_->bins.push_back(default_bin);
            private_state_gch_->eps.push_back(default_eps);
        } else {
            default_bin = private_state_gch_->bins[i];
            default_eps = private_state_gch_->eps[i];
        }

        QSlider *bins = QtHelper::makeSlider(internal_layout, "Ch." + ch.str() + " bins", default_bin, 1, 1000);
        QDoubleSlider *eps = QtHelper::makeDoubleSlider(internal_layout, "Ch." + ch.str() + " eps", default_eps, 0.0, 255.0, 0.01);
        addHistSliders(bins, eps);
    }

    container_hist_sliders_ = QtHelper::wrapLayout(internal_layout);
    layout->addWidget(container_hist_sliders_);

}

void GridCompareHist::updateState(int value)
{
    if(state_mutex_.tryLock()) {
        private_state_gch_->combo_index = combo_compare_->currentIndex();
        private_state_gch_->grid_width  = slide_width_->value();
        private_state_gch_->grid_height = slide_height_->value();
        state_mutex_.unlock();
    }
}

void GridCompareHist::fill(QBoxLayout *layout)
{
    GridCompare::fill(layout);

    combo_compare_ = new QComboBox();
    combo_compare_->addItem("Correlation");
    combo_compare_->addItem("Chi-Square");
    combo_compare_->addItem("Intersection");
    combo_compare_->addItem("Hellinger");
    combo_compare_->addItem("Squared Distances");

    int index = combo_compare_->findText("Correlation");
    index_to_compare_.insert(intPair(index, CV_COMP_CORREL));
    index = combo_compare_->findText("Chi-Square");
    index_to_compare_.insert(intPair(index, CV_COMP_CHISQR));
    index = combo_compare_->findText("Intersection");
    index_to_compare_.insert(intPair(index, CV_COMP_INTERSECT));
    index = combo_compare_->findText("Hellinger");
    index_to_compare_.insert(intPair(index, CV_COMP_BHATTACHARYYA));
    index = combo_compare_->findText("Squared Distances");
    index_to_compare_.insert(intPair(index, AttrHistogram::CV_COMP_SQRD));

    layout->addWidget(combo_compare_);
    private_state_gch_->combo_index = combo_compare_->currentIndex();

    connect(combo_compare_, SIGNAL(currentIndexChanged(int)), this, SLOT(updateState(int)));
    connect(slide_height_, SIGNAL(valueChanged(int)), this, SLOT(updateState(int)));
    connect(slide_width_, SIGNAL(valueChanged(int)), this, SLOT(updateState(int)));

}

void GridCompareHist::prepareGrid(GridHist &g, const cv::Mat &img, const cv::Mat &mask, const int width, const int height)
{
    AttrHistogram::Params p;
    prepareHistParams(p.bins, p.ranges, p.eps);
    p.method = index_to_compare_[private_state_gch_->combo_index];
    p.image  = img;
    cv_grid::prepare_grid<AttrHistogram>(g, height, width, p, mask, 1.0);
}

void GridCompareHist::addHistSliders(QSlider *bins, QDoubleSlider *eps)
{
    HistSliderPair p;
    p.first = bins;
    p.second = eps;
    hist_sliders_.push_back(p);
}

void GridCompareHist::prepareHistParams(cv::Mat &bins, cv::Mat &ranges, cv::Scalar &eps)
{
    bins = cv::Mat_<int>(private_state_gch_->channel_count, 1);
    ranges = cv::Mat_<float>(private_state_gch_->channel_count * 2 ,1);
    for(int i = 0 ; i < private_state_gch_->channel_count ; i++) {
        HistSliderPair p = hist_sliders_[i];
        bins.at<int>(i)     = p.first->value();
        ranges.at<float>(2 * i)     = 0.f;
        ranges.at<float>(2 * i + 1) = 256.f;
        eps[i]          = p.second->doubleValue();

        /// MEMENTO
        private_state_gch_->bins[i] = p.first->value();
        private_state_gch_->eps[i] = p.second->doubleValue();
    }
}

/// MEMENTO ------------------------------------------------------------------------------------
void GridCompareHist::setState(Memento::Ptr memento)
{
    state_.reset(new State);
    State::Ptr s = boost::dynamic_pointer_cast<State>(memento);
    assert(s.get());
    *boost::dynamic_pointer_cast<State>(state_) = *s;
    assert(state_.get());
    private_state_gch_ = boost::dynamic_pointer_cast<State>(state_).get();
    assert(private_state_gch_);

    state_mutex_.lock();
    slide_height_->setValue(private_state_gch_->grid_height);
    slide_width_->setValue(private_state_gch_->grid_width);
    combo_compare_->setCurrentIndex(private_state_gch_->combo_index);
    state_mutex_.unlock();

    Q_EMIT modelChanged();
}

void GridCompareHist::State::readYaml(const YAML::Node &node)
{
    GridCompare::State::readYaml(node);
    node["compare"] >> combo_index;

    const YAML::Node &_bins = node["bins"];
    for(YAML::Iterator it = _bins.begin() ; it != _bins.end() ; it++) {
        int bin_val;
        *it >> bin_val;
        bins.push_back(bin_val);
    }

    const YAML::Node &_eps = node["eps"];
    for(YAML::Iterator it = _eps.begin() ; it != _eps.end() ; it++) {
        double eps_val;
        *it >> eps_val;
        eps.push_back(eps_val);
    }
}

GridCompareHist::State::State() :
    GridCompare::State(),
    combo_index(0)
{
}

Memento::Ptr GridCompareHist::getState() const
{
    State::Ptr memento(new State);
    *memento = *boost::dynamic_pointer_cast<State>(state_);
    return memento;
}

void GridCompareHist::State::writeYaml(YAML::Emitter &out) const
{
    GridCompare::State::writeYaml(out);

    out << YAML::Key << "compare" << YAML::Value << combo_index;
    out << YAML::Key << "bins" << YAML::Value << YAML::BeginSeq;
    for(std::vector<int>::const_iterator it = bins.begin() ; it != bins.end() ; it++) {
        out << *it;
    }
    out << YAML::EndSeq;

    out << YAML::Key << "eps" << YAML::Value << YAML::BeginSeq;
    for(std::vector<double>::const_iterator it = eps.begin() ; it != eps.end() ; it++) {
        out << *it;
    }
    out << YAML::EndSeq;

}
<|endoftext|>


<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2012      Shou Ya <shouyatf@gmail.com>
// Copyright 2012      Dennis Nienhüser <earthwings@gentoo.org>
//

#include "KmlGroundOverlayWriter.h"

#include "GeoDataGroundOverlay.h"
#include "GeoDataTypes.h"
#include "GeoWriter.h"
#include "KmlElementDictionary.h"

namespace Marble
{

static GeoTagWriterRegistrar s_writerLookAt(
    GeoTagWriter::QualifiedName( GeoDataTypes::GeoDataGroundOverlayType,
				 kml::kmlTag_nameSpace22 ),
    new KmlGroundOverlayWriter );

KmlGroundOverlayWriter::KmlGroundOverlayWriter() : KmlOverlayTagWriter( kml::kmlTag_GroundOverlay )
{
    // nothing to do
}

bool KmlGroundOverlayWriter::writeMid(const GeoNode *node, GeoWriter &writer) const
{
    const GeoDataGroundOverlay *ground_overlay =
        static_cast<const GeoDataGroundOverlay*>( node );

    writer.writeTextElement( kml::kmlTag_altitude,
                             QString::number(ground_overlay->altitude()) );
    writer.writeTextElement( kml::kmlTag_altitudeMode,
                             altitudeModeToString(ground_overlay->altitudeMode()) );

    if ( !ground_overlay->latLonBox().isEmpty() ) {
        writeElement( &ground_overlay->latLonBox(), writer );
    }

    if ( ground_overlay->latLonQuad().isValid() ) {
        writeElement( &ground_overlay->latLonQuad(), writer );
    }

    return true;
}

QString KmlGroundOverlayWriter::altitudeModeToString(AltitudeMode mode)
{
    switch (mode) {
    case ClampToGround:
	return "ClampToGround";
    case RelativeToGround:
	return "RelativeToGround";
    case Absolute:
	return "Absolute";
    }
    return "";
}

}

<commit_msg>Fix capitalization according to kml spec.<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2012      Shou Ya <shouyatf@gmail.com>
// Copyright 2012      Dennis Nienhüser <earthwings@gentoo.org>
//

#include "KmlGroundOverlayWriter.h"

#include "GeoDataGroundOverlay.h"
#include "GeoDataTypes.h"
#include "GeoWriter.h"
#include "KmlElementDictionary.h"

namespace Marble
{

static GeoTagWriterRegistrar s_writerLookAt(
    GeoTagWriter::QualifiedName( GeoDataTypes::GeoDataGroundOverlayType,
				 kml::kmlTag_nameSpace22 ),
    new KmlGroundOverlayWriter );

KmlGroundOverlayWriter::KmlGroundOverlayWriter() : KmlOverlayTagWriter( kml::kmlTag_GroundOverlay )
{
    // nothing to do
}

bool KmlGroundOverlayWriter::writeMid(const GeoNode *node, GeoWriter &writer) const
{
    const GeoDataGroundOverlay *ground_overlay =
        static_cast<const GeoDataGroundOverlay*>( node );

    writer.writeTextElement( kml::kmlTag_altitude,
                             QString::number(ground_overlay->altitude()) );
    writer.writeTextElement( kml::kmlTag_altitudeMode,
                             altitudeModeToString(ground_overlay->altitudeMode()) );

    if ( !ground_overlay->latLonBox().isEmpty() ) {
        writeElement( &ground_overlay->latLonBox(), writer );
    }

    if ( ground_overlay->latLonQuad().isValid() ) {
        writeElement( &ground_overlay->latLonQuad(), writer );
    }

    return true;
}

QString KmlGroundOverlayWriter::altitudeModeToString(AltitudeMode mode)
{
    switch (mode) {
    case ClampToGround:
	return "clampToGround";
    case RelativeToGround:
	return "relativeToGround";
    case Absolute:
	return "absolute";
    }
    return "";
}

}

<|endoftext|>