<commit_before>/*
    This file is part of cpp-ethereum.

    cpp-ethereum is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    cpp-ethereum is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @author Christian <c@ethdev.com>
 * @date 2014
 * Solidity data types
 */

#include <libdevcore/CommonIO.h>
#include <libdevcore/CommonData.h>
#include <libsolidity/Types.h>
#include <libsolidity/AST.h>

using namespace std;

namespace dev
{
namespace solidity
{

shared_ptr<Type> Type::fromElementaryTypeName(Token::Value _typeToken)
{
	if (asserts(Token::isElementaryTypeName(_typeToken)))
		BOOST_THROW_EXCEPTION(InternalCompilerError());

	if (Token::INT <= _typeToken && _typeToken <= Token::HASH256)
	{
		int offset = _typeToken - Token::INT;
		int bytes = offset % 33;
		if (bytes == 0)
			bytes = 32;
		int modifier = offset / 33;
		return make_shared<IntegerType>(bytes * 8,
										modifier == 0 ? IntegerType::Modifier::SIGNED :
										modifier == 1 ? IntegerType::Modifier::UNSIGNED :
										IntegerType::Modifier::HASH);
	}
	else if (_typeToken == Token::ADDRESS)
		return make_shared<IntegerType>(0, IntegerType::Modifier::ADDRESS);
	else if (_typeToken == Token::BOOL)
		return make_shared<BoolType>();
	else
		BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unable to convert elementary typename " +
																		 std::string(Token::toString(_typeToken)) + " to type."));
	return shared_ptr<Type>();
}

shared_ptr<Type> Type::fromUserDefinedTypeName(UserDefinedTypeName const& _typeName)
{
	return make_shared<StructType>(*_typeName.getReferencedStruct());
}

shared_ptr<Type> Type::fromMapping(Mapping const&)
{
	BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Mapping types not yet implemented."));
	return shared_ptr<Type>();
}

shared_ptr<Type> Type::forLiteral(Literal const& _literal)
{
	switch (_literal.getToken())
	{
	case Token::TRUE_LITERAL:
	case Token::FALSE_LITERAL:
		return make_shared<BoolType>();
	case Token::NUMBER:
		return IntegerType::smallestTypeForLiteral(_literal.getValue());
	case Token::STRING_LITERAL:
		return shared_ptr<Type>(); // @todo
	default:
		return shared_ptr<Type>();
	}
}

shared_ptr<IntegerType> IntegerType::smallestTypeForLiteral(string const& _literal)
{
	bigint value(_literal);
	bool isSigned = value < 0 || (!_literal.empty() && _literal.front() == '-');
	if (isSigned)
		// convert to positive number of same bit requirements
		value = ((-value) - 1) << 1;
	unsigned bytes = max(bytesRequired(value), 1u);
	if (bytes > 32)
		return shared_ptr<IntegerType>();
	return make_shared<IntegerType>(bytes * 8, isSigned ? Modifier::SIGNED : Modifier::UNSIGNED);
}

IntegerType::IntegerType(int _bits, IntegerType::Modifier _modifier):
	m_bits(_bits), m_modifier(_modifier)
{
	if (isAddress())
		_bits = 160;
	if (asserts(_bits > 0 && _bits <= 256 && _bits % 8 == 0))
		BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Invalid bit number for integer type: " + dev::toString(_bits)));
}

bool IntegerType::isImplicitlyConvertibleTo(Type const& _convertTo) const
{
	if (_convertTo.getCategory() != getCategory())
		return false;
	IntegerType const& convertTo = dynamic_cast<IntegerType const&>(_convertTo);
	if (convertTo.m_bits < m_bits)
		return false;
	if (isAddress())
		return convertTo.isAddress();
	else if (isHash())
		return convertTo.isHash();
	else if (isSigned())
		return convertTo.isSigned();
	else
		return !convertTo.isSigned() || convertTo.m_bits > m_bits;
}

bool IntegerType::isExplicitlyConvertibleTo(Type const& _convertTo) const
{
	return _convertTo.getCategory() == getCategory();
}

bool IntegerType::acceptsBinaryOperator(Token::Value _operator) const
{
	if (isAddress())
		return Token::isCompareOp(_operator);
	else if (isHash())
		return Token::isCompareOp(_operator) || Token::isBitOp(_operator);
	else
		return true;
}

bool IntegerType::acceptsUnaryOperator(Token::Value _operator) const
{
	if (_operator == Token::DELETE)
		return true;
	if (isAddress())
		return false;
	if (_operator == Token::BIT_NOT)
		return true;
	if (isHash())
		return false;
	return _operator == Token::ADD || _operator == Token::SUB ||
		   _operator == Token::INC || _operator == Token::DEC;
}

bool IntegerType::operator==(Type const& _other) const
{
	if (_other.getCategory() != getCategory())
		return false;
	IntegerType const& other = dynamic_cast<IntegerType const&>(_other);
	return other.m_bits == m_bits && other.m_modifier == m_modifier;
}

string IntegerType::toString() const
{
	if (isAddress())
		return "address";
	string prefix = isHash() ? "hash" : (isSigned() ? "int" : "uint");
	return prefix + dev::toString(m_bits);
}

u256 IntegerType::literalValue(Literal const& _literal) const
{
	bigint value(_literal.getValue());
	return u256(value);
}

bool BoolType::isExplicitlyConvertibleTo(Type const& _convertTo) const
{
	// conversion to integer is fine, but not to address
	// this is an example of explicit conversions being not transitive (though implicit should be)
	if (_convertTo.getCategory() == getCategory())
	{
		IntegerType const& convertTo = dynamic_cast<IntegerType const&>(_convertTo);
		if (!convertTo.isAddress())
			return true;
	}
	return isImplicitlyConvertibleTo(_convertTo);
}

u256 BoolType::literalValue(Literal const& _literal) const
{
	if (_literal.getToken() == Token::TRUE_LITERAL)
		return u256(1);
	else if (_literal.getToken() == Token::FALSE_LITERAL)
		return u256(0);
	else
		BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Bool type constructed from non-boolean literal."));
}

bool ContractType::operator==(Type const& _other) const
{
	if (_other.getCategory() != getCategory())
		return false;
	ContractType const& other = dynamic_cast<ContractType const&>(_other);
	return other.m_contract == m_contract;
}

bool StructType::operator==(Type const& _other) const
{
	if (_other.getCategory() != getCategory())
		return false;
	StructType const& other = dynamic_cast<StructType const&>(_other);
	return other.m_struct == m_struct;
}

bool FunctionType::operator==(Type const& _other) const
{
	if (_other.getCategory() != getCategory())
		return false;
	FunctionType const& other = dynamic_cast<FunctionType const&>(_other);
	return other.m_function == m_function;
}

bool MappingType::operator==(Type const& _other) const
{
	if (_other.getCategory() != getCategory())
		return false;
	MappingType const& other = dynamic_cast<MappingType const&>(_other);
	return *other.m_keyType == *m_keyType && *other.m_valueType == *m_valueType;
}

bool TypeType::operator==(Type const& _other) const
{
	if (_other.getCategory() != getCategory())
		return false;
	TypeType const& other = dynamic_cast<TypeType const&>(_other);
	return *getActualType() == *other.getActualType();
}

}
}
<commit_msg>Bugfix: Bit width of address types.<commit_after>/*
    This file is part of cpp-ethereum.

    cpp-ethereum is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    cpp-ethereum is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @author Christian <c@ethdev.com>
 * @date 2014
 * Solidity data types
 */

#include <libdevcore/CommonIO.h>
#include <libdevcore/CommonData.h>
#include <libsolidity/Types.h>
#include <libsolidity/AST.h>

using namespace std;

namespace dev
{
namespace solidity
{

shared_ptr<Type> Type::fromElementaryTypeName(Token::Value _typeToken)
{
	if (asserts(Token::isElementaryTypeName(_typeToken)))
		BOOST_THROW_EXCEPTION(InternalCompilerError());

	if (Token::INT <= _typeToken && _typeToken <= Token::HASH256)
	{
		int offset = _typeToken - Token::INT;
		int bytes = offset % 33;
		if (bytes == 0)
			bytes = 32;
		int modifier = offset / 33;
		return make_shared<IntegerType>(bytes * 8,
										modifier == 0 ? IntegerType::Modifier::SIGNED :
										modifier == 1 ? IntegerType::Modifier::UNSIGNED :
										IntegerType::Modifier::HASH);
	}
	else if (_typeToken == Token::ADDRESS)
		return make_shared<IntegerType>(0, IntegerType::Modifier::ADDRESS);
	else if (_typeToken == Token::BOOL)
		return make_shared<BoolType>();
	else
		BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unable to convert elementary typename " +
																		 std::string(Token::toString(_typeToken)) + " to type."));
	return shared_ptr<Type>();
}

shared_ptr<Type> Type::fromUserDefinedTypeName(UserDefinedTypeName const& _typeName)
{
	return make_shared<StructType>(*_typeName.getReferencedStruct());
}

shared_ptr<Type> Type::fromMapping(Mapping const&)
{
	BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Mapping types not yet implemented."));
	return shared_ptr<Type>();
}

shared_ptr<Type> Type::forLiteral(Literal const& _literal)
{
	switch (_literal.getToken())
	{
	case Token::TRUE_LITERAL:
	case Token::FALSE_LITERAL:
		return make_shared<BoolType>();
	case Token::NUMBER:
		return IntegerType::smallestTypeForLiteral(_literal.getValue());
	case Token::STRING_LITERAL:
		return shared_ptr<Type>(); // @todo
	default:
		return shared_ptr<Type>();
	}
}

shared_ptr<IntegerType> IntegerType::smallestTypeForLiteral(string const& _literal)
{
	bigint value(_literal);
	bool isSigned = value < 0 || (!_literal.empty() && _literal.front() == '-');
	if (isSigned)
		// convert to positive number of same bit requirements
		value = ((-value) - 1) << 1;
	unsigned bytes = max(bytesRequired(value), 1u);
	if (bytes > 32)
		return shared_ptr<IntegerType>();
	return make_shared<IntegerType>(bytes * 8, isSigned ? Modifier::SIGNED : Modifier::UNSIGNED);
}

IntegerType::IntegerType(int _bits, IntegerType::Modifier _modifier):
	m_bits(_bits), m_modifier(_modifier)
{
	if (isAddress())
		m_bits = 160;
	if (asserts(m_bits > 0 && m_bits <= 256 && m_bits % 8 == 0))
		BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Invalid bit number for integer type: " + dev::toString(_bits)));
}

bool IntegerType::isImplicitlyConvertibleTo(Type const& _convertTo) const
{
	if (_convertTo.getCategory() != getCategory())
		return false;
	IntegerType const& convertTo = dynamic_cast<IntegerType const&>(_convertTo);
	if (convertTo.m_bits < m_bits)
		return false;
	if (isAddress())
		return convertTo.isAddress();
	else if (isHash())
		return convertTo.isHash();
	else if (isSigned())
		return convertTo.isSigned();
	else
		return !convertTo.isSigned() || convertTo.m_bits > m_bits;
}

bool IntegerType::isExplicitlyConvertibleTo(Type const& _convertTo) const
{
	return _convertTo.getCategory() == getCategory();
}

bool IntegerType::acceptsBinaryOperator(Token::Value _operator) const
{
	if (isAddress())
		return Token::isCompareOp(_operator);
	else if (isHash())
		return Token::isCompareOp(_operator) || Token::isBitOp(_operator);
	else
		return true;
}

bool IntegerType::acceptsUnaryOperator(Token::Value _operator) const
{
	if (_operator == Token::DELETE)
		return true;
	if (isAddress())
		return false;
	if (_operator == Token::BIT_NOT)
		return true;
	if (isHash())
		return false;
	return _operator == Token::ADD || _operator == Token::SUB ||
		   _operator == Token::INC || _operator == Token::DEC;
}

bool IntegerType::operator==(Type const& _other) const
{
	if (_other.getCategory() != getCategory())
		return false;
	IntegerType const& other = dynamic_cast<IntegerType const&>(_other);
	return other.m_bits == m_bits && other.m_modifier == m_modifier;
}

string IntegerType::toString() const
{
	if (isAddress())
		return "address";
	string prefix = isHash() ? "hash" : (isSigned() ? "int" : "uint");
	return prefix + dev::toString(m_bits);
}

u256 IntegerType::literalValue(Literal const& _literal) const
{
	bigint value(_literal.getValue());
	return u256(value);
}

bool BoolType::isExplicitlyConvertibleTo(Type const& _convertTo) const
{
	// conversion to integer is fine, but not to address
	// this is an example of explicit conversions being not transitive (though implicit should be)
	if (_convertTo.getCategory() == getCategory())
	{
		IntegerType const& convertTo = dynamic_cast<IntegerType const&>(_convertTo);
		if (!convertTo.isAddress())
			return true;
	}
	return isImplicitlyConvertibleTo(_convertTo);
}

u256 BoolType::literalValue(Literal const& _literal) const
{
	if (_literal.getToken() == Token::TRUE_LITERAL)
		return u256(1);
	else if (_literal.getToken() == Token::FALSE_LITERAL)
		return u256(0);
	else
		BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Bool type constructed from non-boolean literal."));
}

bool ContractType::operator==(Type const& _other) const
{
	if (_other.getCategory() != getCategory())
		return false;
	ContractType const& other = dynamic_cast<ContractType const&>(_other);
	return other.m_contract == m_contract;
}

bool StructType::operator==(Type const& _other) const
{
	if (_other.getCategory() != getCategory())
		return false;
	StructType const& other = dynamic_cast<StructType const&>(_other);
	return other.m_struct == m_struct;
}

bool FunctionType::operator==(Type const& _other) const
{
	if (_other.getCategory() != getCategory())
		return false;
	FunctionType const& other = dynamic_cast<FunctionType const&>(_other);
	return other.m_function == m_function;
}

bool MappingType::operator==(Type const& _other) const
{
	if (_other.getCategory() != getCategory())
		return false;
	MappingType const& other = dynamic_cast<MappingType const&>(_other);
	return *other.m_keyType == *m_keyType && *other.m_valueType == *m_valueType;
}

bool TypeType::operator==(Type const& _other) const
{
	if (_other.getCategory() != getCategory())
		return false;
	TypeType const& other = dynamic_cast<TypeType const&>(_other);
	return *getActualType() == *other.getActualType();
}

}
}
<|endoftext|>


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

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

#include <stdio.h>
#include <signal.h>

#include <sal/main.h>

#include <vcl/svapp.hxx>
#include <vcl/window.hxx>
#include <vcl/wrkwin.hxx>
#include <vcl/dialog.hxx>
#include <vcl/menu.hxx>
#include <vcl/lstbox.hxx>
#include <vcl/button.hxx>
#include <vcl/fixed.hxx>
#include <vcl/edit.hxx>
#include <vcl/group.hxx>
#include <vcl/msgbox.hxx>
#include <vcl/virdev.hxx>
#include <vcl/bmpacc.hxx>

#ifndef _CONFIG_HXX
#include <tools/config.hxx>
#endif

#include "svtools/solar.hrc"
#include "filedlg.hxx"
#include "bmpcore.hxx"
#include "bmp.hrc"

// -----------
// - statics -
// -----------

static LangInfo aLangEntries[] =
{
    { "deut", 49 },
    { "enus", 1 },
    { "fren", 33 },
    { "ital", 39 },
    { "dtch", 31 },
    { "span", 34 },
    { "hung", 36 },
    { "estonian", 77},
    { "dan", 45 },
    { "swed", 46 },
    { "port", 03 },
    { "japn", 81 },
    { "chinsim", 86  },
    { "chintrad", 88 },
    { "hebrew", 97 },
    { "russ", 07 },
    { "pol", 48 },
    { "arab",96 },
    { "greek", 30 },
    { "catalan", 37},
    { "korean", 82 },
    { "turk", 90 },
    { "slovenian", 50 }
};

// ----------
// - BmpApp -
// ----------

class BmpWin;

class BmpApp : public Application
{
private:

    BmpWin* pBmpWin;
    String  aOutputFileName;
    BYTE    cExitCode;

            DECL_LINK( Select, Menu* pMenu );

public:

    void    Main();
    void    SetExitCode( BYTE cExit )
            {
                if( ( EXIT_NOERROR == cExitCode ) || ( cExit != EXIT_NOERROR ) )
                    cExitCode = cExit;
            }
};

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

BmpApp aBmpApp;

// ----------
// - Pathes -
// ----------

class Pathes : public ModalDialog
{
    OKButton        aBtnOk;
    CancelButton    aBtnCancel;
    GroupBox        aGrpPath;
    FixedText       aFtSrs;
    FixedText       aFtRes;
    FixedText       aFtOut;
    Edit            aEdtSrs;
    PushButton      aBtnSrs;
    Edit            aEdtRes;
    PushButton      aBtnRes;
    Edit            aEdtOut;
    PushButton      aBtnOut;
    GroupBox        aGrpLang;
    ListBox         aLbLang;

    DECL_LINK( ClickSrsHdl, void* );
    DECL_LINK( ClickResHdl, void* );
    DECL_LINK( ClickOutHdl, void* );

public:

            Pathes( Window* pParent,
                    const String& rSrsPath,
                    const String& rResPath,
                    const String& rOutPath,
                    const USHORT nLang );

    String  GetSrsPath() const { return aEdtSrs.GetText(); }
    String  GetResPath() const { return aEdtRes.GetText(); }
    String  GetOutPath() const { return aEdtOut.GetText(); }

    USHORT  GetLangNum() const { return aLbLang.GetSelectEntryPos(); }
};

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

Pathes::Pathes( Window* pParent,
                const String& rSrsPath,
                const String& rResPath,
                const String& rOutPath,
                const USHORT nLang ) :
            ModalDialog ( pParent, ResId( DLG_PATH ) ),
            aBtnOk      ( this, ResId( BTN_OK ) ),
            aBtnCancel  ( this, ResId( BTN_CANCEL ) ),
            aGrpPath    ( this, ResId( GRP_PATH ) ),
            aFtSrs      ( this, ResId( FT_SRS ) ),
            aFtRes      ( this, ResId( FT_RES ) ),
            aFtOut      ( this, ResId( FT_OUT ) ),
            aEdtSrs     ( this, ResId( EDT_SRS ) ),
            aBtnSrs     ( this, ResId( BTN_SRS ) ),
            aEdtRes     ( this, ResId( EDT_RES ) ),
            aBtnRes     ( this, ResId( BTN_RES ) ),
            aEdtOut     ( this, ResId( EDT_OUT ) ),
            aBtnOut     ( this, ResId( BTN_OUT ) ),
            aGrpLang    ( this, ResId( GRP_LANG ) ),
            aLbLang     ( this, ResId( LB_LANG ) )
{
    FreeResource();

    aBtnSrs.SetClickHdl( LINK( this, Pathes, ClickSrsHdl ) );
    aBtnRes.SetClickHdl( LINK( this, Pathes, ClickResHdl ) );
    aBtnOut.SetClickHdl( LINK( this, Pathes, ClickOutHdl ) );

    aEdtSrs.SetText( rSrsPath );
    aEdtRes.SetText( rResPath );
    aEdtOut.SetText( rOutPath );
    aEdtSrs.GrabFocus();

    aLbLang.InsertEntry( String( RTL_CONSTASCII_USTRINGPARAM( "all" ) ), 0 );
    for( USHORT i = 1, nCount = ( sizeof( aLangEntries ) / sizeof( aLangEntries[ 0 ] ) ); i <= nCount; i++ )
        aLbLang.InsertEntry( String::CreateFromInt32( aLangEntries[ i - 1 ].mnLangNum ), i );

    aLbLang.SelectEntryPos( nLang );
}

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

IMPL_LINK( Pathes, ClickSrsHdl, void*, EMPTYARG )
{
    FileDialog  aFileDlg( this, WB_OPEN | WB_3DLOOK );
    DirEntry    aPath( aEdtSrs.GetText() );

    aFileDlg.SetText( String( RTL_CONSTASCII_USTRINGPARAM( "SRS-Datei mit Imagelisten laden" ) ) );
    aPath += DirEntry( String( RTL_CONSTASCII_USTRINGPARAM( "*.srs" ) ) );
    aFileDlg.SetPath( aPath.GetFull() );
    if ( aFileDlg.Execute() == RET_OK )
        aEdtSrs.SetText( aFileDlg.GetPath() );

    return 0L;
}

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

IMPL_LINK( Pathes, ClickResHdl, void*, EMPTYARG )
{
    PathDialog aPathDlg( this, WB_OPEN | WB_3DLOOK );

    aPathDlg.SetText( String( RTL_CONSTASCII_USTRINGPARAM( "Quellpfad BMP-Dateien" ) ) );
    if ( aPathDlg.Execute() == RET_OK )
        aEdtRes.SetText( aPathDlg.GetPath() );

    return 0L;
}

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

IMPL_LINK( Pathes, ClickOutHdl, void*, EMPTYARG )
{
    PathDialog aPathDlg( this, WB_OPEN | WB_3DLOOK );

    aPathDlg.SetText( String( RTL_CONSTASCII_USTRINGPARAM( "Zielpfad BMP-Dateien" ) ) );
    if ( aPathDlg.Execute() == RET_OK )
        aEdtOut.SetText( aPathDlg.GetPath() );

    return 0L;
}

// ----------
// - BmpWin -
// ----------

class BmpWin : public WorkWindow, public BmpCreator
{
private:

    ListBox         aLB;
    USHORT          nPos;

protected:

    virtual void    Message( const String& rText, BYTE cExitCode = EXIT_NOERROR );

public:

                    BmpWin();

    void            Resize();
    void            SetMode( BOOL bMode ) { aLB.SetUpdateMode( bMode ); }
    void            ClearInfo();
};

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

BmpWin::BmpWin() :
    WorkWindow( NULL, WB_APP | WB_STDWORK ),
    aLB( this, WB_HSCROLL | WB_VSCROLL ),
    nPos( 0 )
{
    SetText( String( RTL_CONSTASCII_USTRINGPARAM( "SVX - BmpMaker" ) ) );
    aLB.SetUpdateMode( TRUE );
    aLB.Show();
}

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

void BmpWin::Resize()
{
    aLB.SetPosSizePixel( Point(), GetOutputSizePixel() );
}

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

void BmpWin::Message( const String& rText, BYTE cExitCode )
{
    aLB.InsertEntry( rText, nPos );
    aLB.SelectEntryPos( nPos++ );

    if( EXIT_NOERROR != cExitCode )
        aBmpApp.SetExitCode( cExitCode );

    ByteString aText( rText, RTL_TEXTENCODING_UTF8 );
#ifdef UNX
    aText.Append( "\r\n" );
#else
    aText.Append( "\n" );
#endif
    fprintf( stderr, aText.GetBuffer() );
}

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

void BmpWin::ClearInfo()
{
    aLB.Clear();
    Invalidate();
    nPos = 0;
}

// ----------
// - BmpApp -
// ----------

void BmpApp::Main( )
{
    // Param1: filename of *.srs input file with image lists
    // Param2: path to local bitmaps
    // Param3: output directory
    // Param4: Langugage dependent directory

    ResMgr*     pAppResMgr = ResMgr::CreateResMgr( "bmp" );
    MenuBar*    pMB = new MenuBar();
    PopupMenu*  pPB = new PopupMenu();
    String      aLangDir;
    String      aOutName;

    Resource::SetResManager( pAppResMgr );

    cExitCode = EXIT_NOERROR;

    pMB->InsertItem( 1, String( RTL_CONSTASCII_USTRINGPARAM( "~ImageList" ) ) );
        pPB->InsertItem( 1, String( RTL_CONSTASCII_USTRINGPARAM( "~Erstellen..." ) ) );
        pPB->InsertSeparator();
        pPB->InsertItem( 2, String( RTL_CONSTASCII_USTRINGPARAM( "~Beenden" ) ) );

    pMB->SetPopupMenu( 1, pPB );
    pMB->SetSelectHdl( LINK( this, BmpApp, Select ) );

    pBmpWin = new BmpWin;
    pBmpWin->SetMenuBar( pMB );
    pBmpWin->Show();

    Execute();

    delete pPB;
    delete pMB;
    delete pBmpWin;

    Resource::SetResManager( NULL );
    delete pAppResMgr;

    if( ( EXIT_NOERROR == cExitCode ) && aOutputFileName.Len() && aOutName.Len() )
    {
        SvFileStream    aOStm( aOutputFileName, STREAM_WRITE | STREAM_TRUNC );
        ByteString      aStr( "Successfully generated ImageList(s) in: " );

        aOStm.WriteLine( aStr.Append( ByteString( aOutName, RTL_TEXTENCODING_UTF8 ) ) );
        aOStm.Close();
    }

    if( EXIT_NOERROR != cExitCode )
        raise( SIGABRT );

    return;
}

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

IMPL_LINK( BmpApp, Select, Menu*, pMenu )
{
    if ( pMenu->GetCurItemId() == 1 )
    {
        Config  aCfg;
        aCfg.SetGroup( "Path-Entries" );

        String  aSrsPath( String::CreateFromAscii( aCfg.ReadKey( "SRS", ByteString() ).GetBuffer() ) );
        String  aResPath( String::CreateFromAscii( aCfg.ReadKey( "RES", ByteString() ).GetBuffer() ) );
        String  aOutPath( String::CreateFromAscii( aCfg.ReadKey( "OUT", ByteString() ).GetBuffer() ) );
        USHORT  nLanguage = (USHORT) aCfg.ReadKey( "LNG", '1' ).ToInt32();
        Pathes  aPathDlg( pBmpWin, aSrsPath, aResPath, aOutPath, nLanguage );

        if ( aPathDlg.Execute() == RET_OK )
        {
            ::std::vector< String > aInDirs;

            aCfg.WriteKey( "SRS", ByteString( aSrsPath = String( aPathDlg.GetSrsPath() ), RTL_TEXTENCODING_UTF8 ) );
            aCfg.WriteKey( "RES", ByteString( aResPath = String( aPathDlg.GetResPath() ), RTL_TEXTENCODING_UTF8 ) );
            aCfg.WriteKey( "OUT", ByteString( aOutPath = String( aPathDlg.GetOutPath() ), RTL_TEXTENCODING_UTF8 ) );
            aCfg.WriteKey( "LNG", ByteString::CreateFromInt32( nLanguage = aPathDlg.GetLangNum() ) );

            pBmpWin->ClearInfo();

            aInDirs.push_back( aResPath );

            if( getenv( "SOLARSRC" ) )
                aInDirs.push_back( ::rtl::OUString::createFromAscii( getenv( "SOLARSRC" ) ) );

            if( !nLanguage )
            {
                for ( USHORT i = 0, nCount = ( sizeof( aLangEntries ) / sizeof( aLangEntries[ 0 ] ) ); i < nCount; i++ )
                    pBmpWin->Create( aSrsPath, aInDirs, aOutPath, aLangEntries[ i ] );
            }
            else
                pBmpWin->Create( aSrsPath, aInDirs, aOutPath, aLangEntries[ nLanguage - 1 ] );
        }
    }
    else if( pMenu->GetCurItemId() == 2 )
        Quit();

    return 0;
}

BOOL SVMain();

SAL_IMPLEMENT_MAIN()
{
    SVMain();
    return 0;
}
<commit_msg>INTEGRATION: CWS residcleanup (1.14.80); FILE MERGED 2007/04/20 16:07:01 pl 1.14.80.2: RESYNC: (1.14-1.15); FILE MERGED 2007/02/18 19:21:40 pl 1.14.80.1: #i74635# get rid of implicit global ResMgr<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: bmpgui.cxx,v $
 *
 *  $Revision: 1.16 $
 *
 *  last change: $Author: rt $ $Date: 2007-04-26 09:41:10 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#include <stdio.h>
#include <signal.h>

#include <sal/main.h>

#include <vcl/svapp.hxx>
#include <vcl/window.hxx>
#include <vcl/wrkwin.hxx>
#include <vcl/dialog.hxx>
#include <vcl/menu.hxx>
#include <vcl/lstbox.hxx>
#include <vcl/button.hxx>
#include <vcl/fixed.hxx>
#include <vcl/edit.hxx>
#include <vcl/group.hxx>
#include <vcl/msgbox.hxx>
#include <vcl/virdev.hxx>
#include <vcl/bmpacc.hxx>

#ifndef _CONFIG_HXX
#include <tools/config.hxx>
#endif

#include "svtools/solar.hrc"
#include "filedlg.hxx"
#include "bmpcore.hxx"
#include "bmp.hrc"

// -----------
// - statics -
// -----------

static LangInfo aLangEntries[] =
{
    { "deut", 49 },
    { "enus", 1 },
    { "fren", 33 },
    { "ital", 39 },
    { "dtch", 31 },
    { "span", 34 },
    { "hung", 36 },
    { "estonian", 77},
    { "dan", 45 },
    { "swed", 46 },
    { "port", 03 },
    { "japn", 81 },
    { "chinsim", 86  },
    { "chintrad", 88 },
    { "hebrew", 97 },
    { "russ", 07 },
    { "pol", 48 },
    { "arab",96 },
    { "greek", 30 },
    { "catalan", 37},
    { "korean", 82 },
    { "turk", 90 },
    { "slovenian", 50 }
};

// ----------
// - BmpApp -
// ----------

class BmpWin;

static ResMgr* pAppResMgr = NULL;

class BmpApp : public Application
{
private:

    BmpWin* pBmpWin;
    String  aOutputFileName;
    BYTE    cExitCode;

            DECL_LINK( Select, Menu* pMenu );

public:

    void    Main();
    void    SetExitCode( BYTE cExit )
            {
                if( ( EXIT_NOERROR == cExitCode ) || ( cExit != EXIT_NOERROR ) )
                    cExitCode = cExit;
            }
};

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

BmpApp aBmpApp;

// ----------
// - Pathes -
// ----------

class Pathes : public ModalDialog
{
    OKButton        aBtnOk;
    CancelButton    aBtnCancel;
    GroupBox        aGrpPath;
    FixedText       aFtSrs;
    FixedText       aFtRes;
    FixedText       aFtOut;
    Edit            aEdtSrs;
    PushButton      aBtnSrs;
    Edit            aEdtRes;
    PushButton      aBtnRes;
    Edit            aEdtOut;
    PushButton      aBtnOut;
    GroupBox        aGrpLang;
    ListBox         aLbLang;

    DECL_LINK( ClickSrsHdl, void* );
    DECL_LINK( ClickResHdl, void* );
    DECL_LINK( ClickOutHdl, void* );

public:

            Pathes( Window* pParent,
                    const String& rSrsPath,
                    const String& rResPath,
                    const String& rOutPath,
                    const USHORT nLang );

    String  GetSrsPath() const { return aEdtSrs.GetText(); }
    String  GetResPath() const { return aEdtRes.GetText(); }
    String  GetOutPath() const { return aEdtOut.GetText(); }

    USHORT  GetLangNum() const { return aLbLang.GetSelectEntryPos(); }
};

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

Pathes::Pathes( Window* pParent,
                const String& rSrsPath,
                const String& rResPath,
                const String& rOutPath,
                const USHORT nLang ) :
            ModalDialog ( pParent, ResId( DLG_PATH, *pAppResMgr ) ),
            aBtnOk      ( this, ResId( BTN_OK, *pAppResMgr ) ),
            aBtnCancel  ( this, ResId( BTN_CANCEL, *pAppResMgr ) ),
            aGrpPath    ( this, ResId( GRP_PATH, *pAppResMgr ) ),
            aFtSrs      ( this, ResId( FT_SRS, *pAppResMgr ) ),
            aFtRes      ( this, ResId( FT_RES, *pAppResMgr ) ),
            aFtOut      ( this, ResId( FT_OUT, *pAppResMgr ) ),
            aEdtSrs     ( this, ResId( EDT_SRS, *pAppResMgr ) ),
            aBtnSrs     ( this, ResId( BTN_SRS, *pAppResMgr ) ),
            aEdtRes     ( this, ResId( EDT_RES, *pAppResMgr ) ),
            aBtnRes     ( this, ResId( BTN_RES, *pAppResMgr ) ),
            aEdtOut     ( this, ResId( EDT_OUT, *pAppResMgr ) ),
            aBtnOut     ( this, ResId( BTN_OUT, *pAppResMgr ) ),
            aGrpLang    ( this, ResId( GRP_LANG, *pAppResMgr ) ),
            aLbLang     ( this, ResId( LB_LANG, *pAppResMgr ) )
{
    FreeResource();

    aBtnSrs.SetClickHdl( LINK( this, Pathes, ClickSrsHdl ) );
    aBtnRes.SetClickHdl( LINK( this, Pathes, ClickResHdl ) );
    aBtnOut.SetClickHdl( LINK( this, Pathes, ClickOutHdl ) );

    aEdtSrs.SetText( rSrsPath );
    aEdtRes.SetText( rResPath );
    aEdtOut.SetText( rOutPath );
    aEdtSrs.GrabFocus();

    aLbLang.InsertEntry( String( RTL_CONSTASCII_USTRINGPARAM( "all" ) ), 0 );
    for( USHORT i = 1, nCount = ( sizeof( aLangEntries ) / sizeof( aLangEntries[ 0 ] ) ); i <= nCount; i++ )
        aLbLang.InsertEntry( String::CreateFromInt32( aLangEntries[ i - 1 ].mnLangNum ), i );

    aLbLang.SelectEntryPos( nLang );
}

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

IMPL_LINK( Pathes, ClickSrsHdl, void*, EMPTYARG )
{
    FileDialog  aFileDlg( this, WB_OPEN | WB_3DLOOK );
    DirEntry    aPath( aEdtSrs.GetText() );

    aFileDlg.SetText( String( RTL_CONSTASCII_USTRINGPARAM( "SRS-Datei mit Imagelisten laden" ) ) );
    aPath += DirEntry( String( RTL_CONSTASCII_USTRINGPARAM( "*.srs" ) ) );
    aFileDlg.SetPath( aPath.GetFull() );
    if ( aFileDlg.Execute() == RET_OK )
        aEdtSrs.SetText( aFileDlg.GetPath() );

    return 0L;
}

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

IMPL_LINK( Pathes, ClickResHdl, void*, EMPTYARG )
{
    PathDialog aPathDlg( this, WB_OPEN | WB_3DLOOK );

    aPathDlg.SetText( String( RTL_CONSTASCII_USTRINGPARAM( "Quellpfad BMP-Dateien" ) ) );
    if ( aPathDlg.Execute() == RET_OK )
        aEdtRes.SetText( aPathDlg.GetPath() );

    return 0L;
}

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

IMPL_LINK( Pathes, ClickOutHdl, void*, EMPTYARG )
{
    PathDialog aPathDlg( this, WB_OPEN | WB_3DLOOK );

    aPathDlg.SetText( String( RTL_CONSTASCII_USTRINGPARAM( "Zielpfad BMP-Dateien" ) ) );
    if ( aPathDlg.Execute() == RET_OK )
        aEdtOut.SetText( aPathDlg.GetPath() );

    return 0L;
}

// ----------
// - BmpWin -
// ----------

class BmpWin : public WorkWindow, public BmpCreator
{
private:

    ListBox         aLB;
    USHORT          nPos;

protected:

    virtual void    Message( const String& rText, BYTE cExitCode = EXIT_NOERROR );

public:

                    BmpWin();

    void            Resize();
    void            SetMode( BOOL bMode ) { aLB.SetUpdateMode( bMode ); }
    void            ClearInfo();
};

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

BmpWin::BmpWin() :
    WorkWindow( NULL, WB_APP | WB_STDWORK ),
    aLB( this, WB_HSCROLL | WB_VSCROLL ),
    nPos( 0 )
{
    SetText( String( RTL_CONSTASCII_USTRINGPARAM( "SVX - BmpMaker" ) ) );
    aLB.SetUpdateMode( TRUE );
    aLB.Show();
}

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

void BmpWin::Resize()
{
    aLB.SetPosSizePixel( Point(), GetOutputSizePixel() );
}

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

void BmpWin::Message( const String& rText, BYTE cExitCode )
{
    aLB.InsertEntry( rText, nPos );
    aLB.SelectEntryPos( nPos++ );

    if( EXIT_NOERROR != cExitCode )
        aBmpApp.SetExitCode( cExitCode );

    ByteString aText( rText, RTL_TEXTENCODING_UTF8 );
#ifdef UNX
    aText.Append( "\r\n" );
#else
    aText.Append( "\n" );
#endif
    fprintf( stderr, aText.GetBuffer() );
}

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

void BmpWin::ClearInfo()
{
    aLB.Clear();
    Invalidate();
    nPos = 0;
}

// ----------
// - BmpApp -
// ----------

void BmpApp::Main( )
{
    // Param1: filename of *.srs input file with image lists
    // Param2: path to local bitmaps
    // Param3: output directory
    // Param4: Langugage dependent directory

    pAppResMgr = ResMgr::CreateResMgr( "bmp" );
    MenuBar*    pMB = new MenuBar();
    PopupMenu*  pPB = new PopupMenu();
    String      aLangDir;
    String      aOutName;

    cExitCode = EXIT_NOERROR;

    pMB->InsertItem( 1, String( RTL_CONSTASCII_USTRINGPARAM( "~ImageList" ) ) );
        pPB->InsertItem( 1, String( RTL_CONSTASCII_USTRINGPARAM( "~Erstellen..." ) ) );
        pPB->InsertSeparator();
        pPB->InsertItem( 2, String( RTL_CONSTASCII_USTRINGPARAM( "~Beenden" ) ) );

    pMB->SetPopupMenu( 1, pPB );
    pMB->SetSelectHdl( LINK( this, BmpApp, Select ) );

    pBmpWin = new BmpWin;
    pBmpWin->SetMenuBar( pMB );
    pBmpWin->Show();

    Execute();

    delete pPB;
    delete pMB;
    delete pBmpWin;

    delete pAppResMgr;
    pAppResMgr = NULL;

    if( ( EXIT_NOERROR == cExitCode ) && aOutputFileName.Len() && aOutName.Len() )
    {
        SvFileStream    aOStm( aOutputFileName, STREAM_WRITE | STREAM_TRUNC );
        ByteString      aStr( "Successfully generated ImageList(s) in: " );

        aOStm.WriteLine( aStr.Append( ByteString( aOutName, RTL_TEXTENCODING_UTF8 ) ) );
        aOStm.Close();
    }

    if( EXIT_NOERROR != cExitCode )
        raise( SIGABRT );

    return;
}

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

IMPL_LINK( BmpApp, Select, Menu*, pMenu )
{
    if ( pMenu->GetCurItemId() == 1 )
    {
        Config  aCfg;
        aCfg.SetGroup( "Path-Entries" );

        String  aSrsPath( String::CreateFromAscii( aCfg.ReadKey( "SRS", ByteString() ).GetBuffer() ) );
        String  aResPath( String::CreateFromAscii( aCfg.ReadKey( "RES", ByteString() ).GetBuffer() ) );
        String  aOutPath( String::CreateFromAscii( aCfg.ReadKey( "OUT", ByteString() ).GetBuffer() ) );
        USHORT  nLanguage = (USHORT) aCfg.ReadKey( "LNG", '1' ).ToInt32();
        Pathes  aPathDlg( pBmpWin, aSrsPath, aResPath, aOutPath, nLanguage );

        if ( aPathDlg.Execute() == RET_OK )
        {
            ::std::vector< String > aInDirs;

            aCfg.WriteKey( "SRS", ByteString( aSrsPath = String( aPathDlg.GetSrsPath() ), RTL_TEXTENCODING_UTF8 ) );
            aCfg.WriteKey( "RES", ByteString( aResPath = String( aPathDlg.GetResPath() ), RTL_TEXTENCODING_UTF8 ) );
            aCfg.WriteKey( "OUT", ByteString( aOutPath = String( aPathDlg.GetOutPath() ), RTL_TEXTENCODING_UTF8 ) );
            aCfg.WriteKey( "LNG", ByteString::CreateFromInt32( nLanguage = aPathDlg.GetLangNum() ) );

            pBmpWin->ClearInfo();

            aInDirs.push_back( aResPath );

            if( getenv( "SOLARSRC" ) )
                aInDirs.push_back( ::rtl::OUString::createFromAscii( getenv( "SOLARSRC" ) ) );

            if( !nLanguage )
            {
                for ( USHORT i = 0, nCount = ( sizeof( aLangEntries ) / sizeof( aLangEntries[ 0 ] ) ); i < nCount; i++ )
                    pBmpWin->Create( aSrsPath, aInDirs, aOutPath, aLangEntries[ i ] );
            }
            else
                pBmpWin->Create( aSrsPath, aInDirs, aOutPath, aLangEntries[ nLanguage - 1 ] );
        }
    }
    else if( pMenu->GetCurItemId() == 2 )
        Quit();

    return 0;
}

BOOL SVMain();

SAL_IMPLEMENT_MAIN()
{
    SVMain();
    return 0;
}
<|endoftext|>


<commit_before>// @(#)root/roostats:$Id$
// Authors: Giovanni Petrucciani 4/21/2011
/*************************************************************************
 * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "RooStats/SequentialProposal.h"
#include <RooArgSet.h>
#include <iostream>
#include <memory>
#include <TIterator.h>
#include <RooRandom.h>
#include <RooStats/RooStatsUtils.h>

ClassImp(RooStats::SequentialProposal)

namespace RooStats {

SequentialProposal::SequentialProposal(double divisor) :
    ProposalFunction(),
    fDivisor(1./divisor)
{
}

// Populate xPrime with a new proposed point
void SequentialProposal::Propose(RooArgSet& xPrime, RooArgSet& x )
{
   RooStats::SetParameters(&x, &xPrime);
   std::auto_ptr<TIterator> it(xPrime.createIterator());
   RooRealVar* var;
   int n = xPrime.getSize(), j = floor(RooRandom::uniform()*n);
   for (int i = 0; (var = (RooRealVar*)it->Next()) != NULL; ++i) {
      if (i == j) {
        double val = var->getVal(), max = var->getMax(), min = var->getMin(), len = max - min;
        val += RooRandom::gaussian() * len * fDivisor;
        while (val > max) val -= len;
        while (val < min) val += len;
        var->setVal(val);
        //std::cout << "Proposing a step along " << var->GetName() << std::endl;
      }
   }
}

Bool_t SequentialProposal::IsSymmetric(RooArgSet& , RooArgSet& ) {
   return true;
}

// Return the probability of proposing the point x1 given the starting
// point x2
Double_t SequentialProposal::GetProposalDensity(RooArgSet& ,
                                                RooArgSet& )
{
   return 1.0; // should not be needed
}

}

<commit_msg>fix a compilation warning<commit_after>// @(#)root/roostats:$Id$
// Authors: Giovanni Petrucciani 4/21/2011
/*************************************************************************
 * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "RooStats/SequentialProposal.h"
#include <RooArgSet.h>
#include <iostream>
#include <memory>
#include <TIterator.h>
#include <RooRandom.h>
#include <RooStats/RooStatsUtils.h>

ClassImp(RooStats::SequentialProposal)

namespace RooStats {

SequentialProposal::SequentialProposal(double divisor) :
    ProposalFunction(),
    fDivisor(1./divisor)
{
}

// Populate xPrime with a new proposed point
void SequentialProposal::Propose(RooArgSet& xPrime, RooArgSet& x )
{
   RooStats::SetParameters(&x, &xPrime);
   std::auto_ptr<TIterator> it(xPrime.createIterator());
   RooRealVar* var;
   int n = xPrime.getSize();
   int j = int( floor(RooRandom::uniform()*n) );
   for (int i = 0; (var = (RooRealVar*)it->Next()) != NULL; ++i) {
      if (i == j) {
        double val = var->getVal(), max = var->getMax(), min = var->getMin(), len = max - min;
        val += RooRandom::gaussian() * len * fDivisor;
        while (val > max) val -= len;
        while (val < min) val += len;
        var->setVal(val);
        //std::cout << "Proposing a step along " << var->GetName() << std::endl;
      }
   }
}

Bool_t SequentialProposal::IsSymmetric(RooArgSet& , RooArgSet& ) {
   return true;
}

// Return the probability of proposing the point x1 given the starting
// point x2
Double_t SequentialProposal::GetProposalDensity(RooArgSet& ,
                                                RooArgSet& )
{
   return 1.0; // should not be needed
}

}

<|endoftext|>


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

#ifndef _SWTYPES_HXX
#include "swtypes.hxx"
#endif
#ifndef _FRMATR_HXX
#include "frmatr.hxx"
#endif

#ifndef _SVX_SVXENUM_HXX //autogen
#include <svx/svxenum.hxx>
#endif
#ifndef _GEN_HXX //autogen
#include <tools/gen.hxx>
#endif
#ifndef _FMTFSIZE_HXX //autogen
#include <fmtfsize.hxx>
#endif
#ifndef _FMTSRND_HXX //autogen
#include <fmtsrnd.hxx>
#endif
#ifndef _FMTORNT_HXX //autogen
#include <fmtornt.hxx>
#endif
#ifndef _FMTANCHR_HXX //autogen
#include <fmtanchr.hxx>
#endif

#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif

class   SwWrtShell;
struct  SvxSwFrameValidation;
struct  SwPosition;

class   SwFmt;
class   SwFmtCol;

const SwTwips   DFLT_WIDTH      = MM50 * 4;
const SwTwips   DFLT_HEIGHT     = MM50;

#define FULL_ATTRSET    0xffff

#define FRMMGR_TYPE_NONE    0x00
#define FRMMGR_TYPE_TEXT    0x01
#define FRMMGR_TYPE_GRF     0x02
#define FRMMGR_TYPE_OLE     0x04
#define FRMMGR_TYPE_LABEL   0x08
#define FRMMGR_TYPE_ENVELP  0x10

class SW_DLLPUBLIC SwFlyFrmAttrMgr
{
    SfxItemSet  aSet;
    Point       aAbsPos;
    SwWrtShell  *pOwnSh;

    BOOL        bAbsPos,
                bNewFrm;
    BOOL        bIsInVertical;

    // interne Verrechnung fuer Umrandung
    SW_DLLPRIVATE SwTwips           CalcTopSpace();
    SW_DLLPRIVATE SwTwips           CalcBottomSpace();
    SW_DLLPRIVATE SwTwips           CalcLeftSpace();
    SW_DLLPRIVATE SwTwips           CalcRightSpace();

    SW_DLLPRIVATE void _UpdateFlyFrm(); //Nacharbeit nach Einfuegen oder Update

public:
    SwFlyFrmAttrMgr( BOOL bNew, SwWrtShell* pSh, BYTE nType );

    //CopyCtor fuer die Dialoge, zum Pruefen der Metrics
    SwFlyFrmAttrMgr( BOOL bNew, SwWrtShell *pSh, const SfxItemSet &rSet );

    inline SwWrtShell*  GetShell() { return pOwnSh; }

    void                SetAnchor(RndStdIds eId);
    inline RndStdIds    GetAnchor()  const;

    void                SetHorzOrientation(sal_Int16 eOrient);
    void                SetVertOrientation(sal_Int16 eOrient);

    // Absolute Position
    void                SetAbsPos(const Point& rLPoint);

    // Relative Position vom Anker
    void                SetPos(const Point& rLPoint);
    inline Point        GetPos() const;

    // Groesse
    void                SetSize(const Size& rLSize);
    inline const Size&  GetSize() const;

    inline USHORT       GetHeightPercent() const;

    void                SetHeightSizeType(SwFrmSize eType);

    // Abstand zum Inhalt
    void                SetLRSpace( long nLeft  = LONG_MAX,
                                    long nRight = LONG_MAX );
    void                SetULSpace( long nTop   = LONG_MAX,
                                    long nBottom= LONG_MAX );

    void                SetCol( const SwFmtCol &rCol);

    // Attribute aendern und erfragen
    void                UpdateAttrMgr();
    void                UpdateFlyFrm();

    // neuen Rahmen erzeugen
    BOOL                InsertFlyFrm();
    void                InsertFlyFrm(RndStdIds      eAnchorType,
                                   const Point    &rPos,
                                   const Size     &rSize,
                                   BOOL           bAbsPos = FALSE);

    // Metriken pruefen und  aendern
    void                ValidateMetrics(SvxSwFrameValidation& rVal,
                            const SwPosition* pToCharCntntPos,
                            BOOL bOnlyPercentRefValue = FALSE);

    void                DelAttr(USHORT nId);

    // Set rausreichen
    inline const SfxItemSet &GetAttrSet() const { return aSet; }
    inline       SfxItemSet &GetAttrSet()       { return aSet; }
    void                     SetAttrSet(const SfxItemSet& rSet);

    inline const SwFmtVertOrient &GetVertOrient() const;
    inline const SwFmtHoriOrient &GetHoriOrient() const;
    inline const SvxShadowItem   &GetShadow() const;
    inline const SvxBoxItem      &GetBox() const;
    inline const SwFmtSurround   &GetSurround() const;
    inline const SwFmtFrmSize    &GetFrmSize() const;

    long CalcWidthBorder()  { return CalcLeftSpace()+CalcRightSpace(); }
    long CalcHeightBorder() { return CalcTopSpace()+CalcBottomSpace(); }
};

inline const Size& SwFlyFrmAttrMgr::GetSize() const
{
    return ((SwFmtFrmSize&)aSet.Get(RES_FRM_SIZE)).GetSize();
}

inline const SwFmtVertOrient &SwFlyFrmAttrMgr::GetVertOrient() const
{
    return ((SwFmtVertOrient&)aSet.Get(RES_VERT_ORIENT));
}
inline const SwFmtHoriOrient &SwFlyFrmAttrMgr::GetHoriOrient() const
{
    return ((SwFmtHoriOrient &)aSet.Get(RES_HORI_ORIENT));
}
inline const SwFmtFrmSize& SwFlyFrmAttrMgr::GetFrmSize() const
{
    return ((SwFmtFrmSize&)aSet.Get(RES_FRM_SIZE));
}
inline const SvxShadowItem &SwFlyFrmAttrMgr::GetShadow() const
{
    return ((SvxShadowItem&)aSet.Get(RES_SHADOW));
}
inline const SvxBoxItem &SwFlyFrmAttrMgr::GetBox() const
{
    return ((SvxBoxItem&)aSet.Get(RES_BOX));
}
inline const SwFmtSurround &SwFlyFrmAttrMgr::GetSurround() const
{
    return ((SwFmtSurround&)aSet.Get(RES_SURROUND));
}

inline Point SwFlyFrmAttrMgr::GetPos() const
{
    return Point( GetHoriOrient().GetPos(), GetVertOrient().GetPos() );
}

inline RndStdIds SwFlyFrmAttrMgr::GetAnchor()  const
{
    return ((SwFmtAnchor&)aSet.Get(RES_ANCHOR)).GetAnchorId();
}

inline USHORT SwFlyFrmAttrMgr::GetHeightPercent() const
{
    return GetFrmSize().GetHeightPercent();
}

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.11.242); FILE MERGED 2008/04/01 15:59:12 thb 1.11.242.3: #i85898# Stripping all external header guards 2008/04/01 12:55:27 thb 1.11.242.2: #i85898# Stripping all external header guards 2008/03/31 16:58:31 rt 1.11.242.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: frmmgr.hxx,v $
 * $Revision: 1.12 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _FRMMGR_HXX
#define _FRMMGR_HXX

#include "swtypes.hxx"
#include "frmatr.hxx"
#include <svx/svxenum.hxx>
#include <tools/gen.hxx>
#include <fmtfsize.hxx>
#include <fmtsrnd.hxx>
#include <fmtornt.hxx>
#include <fmtanchr.hxx>
#include "swdllapi.h"

class   SwWrtShell;
struct  SvxSwFrameValidation;
struct  SwPosition;

class   SwFmt;
class   SwFmtCol;

const SwTwips   DFLT_WIDTH      = MM50 * 4;
const SwTwips   DFLT_HEIGHT     = MM50;

#define FULL_ATTRSET    0xffff

#define FRMMGR_TYPE_NONE    0x00
#define FRMMGR_TYPE_TEXT    0x01
#define FRMMGR_TYPE_GRF     0x02
#define FRMMGR_TYPE_OLE     0x04
#define FRMMGR_TYPE_LABEL   0x08
#define FRMMGR_TYPE_ENVELP  0x10

class SW_DLLPUBLIC SwFlyFrmAttrMgr
{
    SfxItemSet  aSet;
    Point       aAbsPos;
    SwWrtShell  *pOwnSh;

    BOOL        bAbsPos,
                bNewFrm;
    BOOL        bIsInVertical;

    // interne Verrechnung fuer Umrandung
    SW_DLLPRIVATE SwTwips           CalcTopSpace();
    SW_DLLPRIVATE SwTwips           CalcBottomSpace();
    SW_DLLPRIVATE SwTwips           CalcLeftSpace();
    SW_DLLPRIVATE SwTwips           CalcRightSpace();

    SW_DLLPRIVATE void _UpdateFlyFrm(); //Nacharbeit nach Einfuegen oder Update

public:
    SwFlyFrmAttrMgr( BOOL bNew, SwWrtShell* pSh, BYTE nType );

    //CopyCtor fuer die Dialoge, zum Pruefen der Metrics
    SwFlyFrmAttrMgr( BOOL bNew, SwWrtShell *pSh, const SfxItemSet &rSet );

    inline SwWrtShell*  GetShell() { return pOwnSh; }

    void                SetAnchor(RndStdIds eId);
    inline RndStdIds    GetAnchor()  const;

    void                SetHorzOrientation(sal_Int16 eOrient);
    void                SetVertOrientation(sal_Int16 eOrient);

    // Absolute Position
    void                SetAbsPos(const Point& rLPoint);

    // Relative Position vom Anker
    void                SetPos(const Point& rLPoint);
    inline Point        GetPos() const;

    // Groesse
    void                SetSize(const Size& rLSize);
    inline const Size&  GetSize() const;

    inline USHORT       GetHeightPercent() const;

    void                SetHeightSizeType(SwFrmSize eType);

    // Abstand zum Inhalt
    void                SetLRSpace( long nLeft  = LONG_MAX,
                                    long nRight = LONG_MAX );
    void                SetULSpace( long nTop   = LONG_MAX,
                                    long nBottom= LONG_MAX );

    void                SetCol( const SwFmtCol &rCol);

    // Attribute aendern und erfragen
    void                UpdateAttrMgr();
    void                UpdateFlyFrm();

    // neuen Rahmen erzeugen
    BOOL                InsertFlyFrm();
    void                InsertFlyFrm(RndStdIds      eAnchorType,
                                   const Point    &rPos,
                                   const Size     &rSize,
                                   BOOL           bAbsPos = FALSE);

    // Metriken pruefen und  aendern
    void                ValidateMetrics(SvxSwFrameValidation& rVal,
                            const SwPosition* pToCharCntntPos,
                            BOOL bOnlyPercentRefValue = FALSE);

    void                DelAttr(USHORT nId);

    // Set rausreichen
    inline const SfxItemSet &GetAttrSet() const { return aSet; }
    inline       SfxItemSet &GetAttrSet()       { return aSet; }
    void                     SetAttrSet(const SfxItemSet& rSet);

    inline const SwFmtVertOrient &GetVertOrient() const;
    inline const SwFmtHoriOrient &GetHoriOrient() const;
    inline const SvxShadowItem   &GetShadow() const;
    inline const SvxBoxItem      &GetBox() const;
    inline const SwFmtSurround   &GetSurround() const;
    inline const SwFmtFrmSize    &GetFrmSize() const;

    long CalcWidthBorder()  { return CalcLeftSpace()+CalcRightSpace(); }
    long CalcHeightBorder() { return CalcTopSpace()+CalcBottomSpace(); }
};

inline const Size& SwFlyFrmAttrMgr::GetSize() const
{
    return ((SwFmtFrmSize&)aSet.Get(RES_FRM_SIZE)).GetSize();
}

inline const SwFmtVertOrient &SwFlyFrmAttrMgr::GetVertOrient() const
{
    return ((SwFmtVertOrient&)aSet.Get(RES_VERT_ORIENT));
}
inline const SwFmtHoriOrient &SwFlyFrmAttrMgr::GetHoriOrient() const
{
    return ((SwFmtHoriOrient &)aSet.Get(RES_HORI_ORIENT));
}
inline const SwFmtFrmSize& SwFlyFrmAttrMgr::GetFrmSize() const
{
    return ((SwFmtFrmSize&)aSet.Get(RES_FRM_SIZE));
}
inline const SvxShadowItem &SwFlyFrmAttrMgr::GetShadow() const
{
    return ((SvxShadowItem&)aSet.Get(RES_SHADOW));
}
inline const SvxBoxItem &SwFlyFrmAttrMgr::GetBox() const
{
    return ((SvxBoxItem&)aSet.Get(RES_BOX));
}
inline const SwFmtSurround &SwFlyFrmAttrMgr::GetSurround() const
{
    return ((SwFmtSurround&)aSet.Get(RES_SURROUND));
}

inline Point SwFlyFrmAttrMgr::GetPos() const
{
    return Point( GetHoriOrient().GetPos(), GetVertOrient().GetPos() );
}

inline RndStdIds SwFlyFrmAttrMgr::GetAnchor()  const
{
    return ((SwFmtAnchor&)aSet.Get(RES_ANCHOR)).GetAnchorId();
}

inline USHORT SwFlyFrmAttrMgr::GetHeightPercent() const
{
    return GetFrmSize().GetHeightPercent();
}

#endif
<|endoftext|>


<commit_before>/*
 Flexisip, a flexible SIP proxy server with media capabilities.
 Copyright (C) 2010  Belledonne Communications SARL.

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

 This program 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 Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "agent.hh"
#include "mediarelay.hh"

#include <poll.h>

#include <algorithm>
#include <list>

using namespace ::std;

MediaSource::MediaSource(const string &ip, int port) :
		mIp(ip), mPort(port) {
	struct addrinfo *res = NULL;
	struct addrinfo hints = { 0 };
	char portstr[20];
	snprintf(portstr, sizeof(portstr), "%i", port);
	hints.ai_flags = AI_NUMERICHOST | AI_NUMERICSERV;
	int err = getaddrinfo(ip.c_str(), portstr, &hints, &res);
	if (err != 0) {
		LOGE("MediaSource::MediaSource() failed for %s:%i : %s", ip.c_str(), port, gai_strerror(err));
	} else {
		memcpy(&mSockAddr, res->ai_addr, res->ai_addrlen);
		mSockAddrSize = res->ai_addrlen;
		freeaddrinfo(res);
	}
}

MediaSource::MediaSource(const struct sockaddr_storage &sockaddr, socklen_t sockaddr_size) :
		mSockAddrSize(sockaddr_size) {
	memcpy(&mSockAddr, &sockaddr, sockaddr_size);
	char buff[256];
	const char *ret = inet_ntop(AF_INET, &((struct sockaddr_in *) &sockaddr)->sin_addr, buff, sizeof(buff));
	if (ret == NULL) {
		LOGE("MediaSource::MediaSource() failed for %p:", &sockaddr);
	} else {
		mIp = string(ret);
		mPort = ntohs(((struct sockaddr_in *)&sockaddr)->sin_port);
	}
}

RelaySession::RelaySession(const string &bind_ip, const string & public_ip) :
		mBindIp(bind_ip), mPublicIp(public_ip) {
	mLastActivityTime = time(NULL);
	mSession[0] = rtp_session_new(RTP_SESSION_SENDRECV);
	mSession[1] = rtp_session_new(RTP_SESSION_SENDRECV);
	rtp_session_set_local_addr(mSession[0], mBindIp.c_str(), -1);
	rtp_session_set_local_addr(mSession[1], mBindIp.c_str(), -1);
	mSources[0] = rtp_session_get_rtp_socket(mSession[0]);
	mSources[1] = rtp_session_get_rtp_socket(mSession[1]);
	mSources[2] = rtp_session_get_rtcp_socket(mSession[0]);
	mSources[3] = rtp_session_get_rtcp_socket(mSession[1]);
	mUsed = true;
}

int RelaySession::getFrontPort() const {
	return rtp_session_get_local_port(mSession[0]);
}

int RelaySession::getBackPort() const {
	return rtp_session_get_local_port(mSession[1]);
}

void RelaySession::addFront(const string &ip, int port) {
	MediaSource src(ip, port);
	LOGD("Add Front %s:%i", ip.c_str(), port);
	mMutex.lock();
	addFront(src);
	mMutex.unlock();
}

void RelaySession::addBack(const string &ip, int port) {
	MediaSource src(ip, port);
	LOGD("Add Back %s:%i", ip.c_str(), port);
	mMutex.lock();
	addBack(src);
	mMutex.unlock();
}

void RelaySession::addFront(const MediaSource&src) {
	auto it = find(mFront.begin(), mFront.end(), src);
	if (it == mFront.end()) {
		mFront.push_back(src);
	}
}

void RelaySession::removeFront(const string &ip, int port) {
	MediaSource src(ip, port);
	LOGD("Remove Front %s:%i", ip.c_str(), port);
	auto it = find(mFront.begin(), mFront.end(), src);
	if (it != mFront.end()) {
		mFront.erase(it);
	}
}

void RelaySession::addBack(const MediaSource&src) {
	auto it = find(mBack.begin(), mBack.end(), src);
	if (it == mBack.end()) {
		mBack.push_back(src);
	}
}

void RelaySession::removeBack(const string &ip, int port) {
	MediaSource src(ip, port);
	LOGD("Remove Back %s:%i", ip.c_str(), port);
	auto it = find(mBack.begin(), mBack.end(), src);
	if (it != mBack.end()) {
		mBack.erase(it);
	}
}

RelaySession::~RelaySession() {
	rtp_session_destroy(mSession[0]);
	rtp_session_destroy(mSession[1]);
}

void RelaySession::unuse() {
	mUsed = false;
}

void RelaySession::fillPollFd(struct pollfd *tab) {
	int i;
	for (i = 0; i < 4; ++i) {
		tab[i].fd = mSources[i];
		tab[i].events = POLLIN;
		tab[i].revents = 0;
	}
}

void RelaySession::transfer(time_t curtime, struct pollfd *tab) {
	uint8_t buf[1500];
	const int maxsize = sizeof(buf);
	struct sockaddr_storage ss;
	socklen_t slen;
	int recv_len;
	int send_len;
	int i;

	mMutex.lock();
	for (i = 0; i < 4; i += 2) {
		if (tab[i].revents & POLLIN) {
			mLastActivityTime = curtime;
			recv_len = recvfrom(mSources[i], buf, maxsize, 0, (struct sockaddr*) &ss, &slen);
			if (recv_len > 0) {
				MediaSource src(ss, slen);
				addFront(src);
				list<MediaSource>::iterator it = mBack.begin();
				if (it != mBack.end()) {
					while (it != mBack.end()) {
						const MediaSource &dest = *it;
						//LOGD("(%i)%s:%i -> (%i)%s:%i", getFrontPort(), src.getIp().c_str(), src.getPort(), getBackPort(), dest.getIp().c_str(), dest.getPort());
						send_len = sendto(mSources[i + 1], buf, recv_len, 0, (const struct sockaddr*) &dest.getSockAddr(), dest.getSockAddrSize());
						if (send_len != recv_len) {
							//LOGW("Only %i bytes sent on %i bytes: %s", send_len, recv_len, strerror(errno));
							it = mBack.erase(it);
						} else {
							++it;
						}
					}
				} else {
					//LOGD("%s:%i -> GARBAGE", src.getIp().c_str(), src.getPort());
				}
			}
		}
		if (tab[i + 1].revents & POLLIN) {
			mLastActivityTime = curtime;
			recv_len = recvfrom(mSources[i + 1], buf, maxsize, 0, (struct sockaddr*) &ss, &slen);
			if (recv_len > 0) {
				MediaSource src(ss, slen);
				addBack(src);
				list<MediaSource>::iterator it = mFront.begin();
				if (it != mFront.end()) {
					while (it != mFront.end()) {
						const MediaSource &dest = *it;
						//LOGD("(%i)%s:%i -> (%i)%s:%i", getBackPort(), src.getIp().c_str(), src.getPort(), getFrontPort(), dest.getIp().c_str(), dest.getPort());
						send_len = sendto(mSources[i], buf, recv_len, 0, (const struct sockaddr*) &dest.getSockAddr(), dest.getSockAddrSize());
						if (send_len != recv_len) {
							//LOGW("Only %i bytes sent on %i bytes: %s", send_len, recv_len, strerror(errno));
							it = mFront.erase(it);
						} else {
							++it;
						}
					}
				} else {
					//LOGD("%s:%i -> GARBAGE", src.getIp().c_str(), src.getPort());
				}
			}
		}
	}
	mMutex.unlock();
}

MediaRelayServer::MediaRelayServer(const string &bind_ip, const string &public_ip) :
		mBindIp(bind_ip), mPublicIp(public_ip) {
	mRunning = false;
	if (pipe(mCtlPipe) == -1) {
		LOGF("Could not create MediaRelayServer control pipe.");
	}
}

void MediaRelayServer::start() {
	mRunning = true;
	pthread_create(&mThread, NULL, &MediaRelayServer::threadFunc, this);
}

MediaRelayServer::~MediaRelayServer() {
	if (mRunning) {
		mRunning = false;
		if (write(mCtlPipe[1], "e", 1) == -1)
			LOGE("MediaRelayServer: Fail to write to control pipe.");
		pthread_join(mThread, NULL);
	}
	for_each(mSessions.begin(), mSessions.end(), delete_functor<RelaySession>());
	close(mCtlPipe[0]);
	close(mCtlPipe[1]);
}

RelaySession *MediaRelayServer::createSession() {
	RelaySession *s = new RelaySession(mBindIp, mPublicIp);
	int count;
	mMutex.lock();
	mSessions.push_back(s);
	count = mSessions.size();
	mMutex.unlock();
	if (!mRunning)
		start();

	LOGD("There are now %i relay sessions running.", count);
	/*write to the control pipe to wakeup the server thread */
	if (write(mCtlPipe[1], "e", 1) == -1)
		LOGE("MediaRelayServer: fail to write to control pipe.");
	return s;
}

void MediaRelayServer::run() {
	int sessionCount;
	int i;
	struct pollfd *pfds = NULL;
	list<RelaySession*>::iterator it;
	int err;
	int pfds_size = 0, cur_pfds_size = 0;

	while (mRunning) {
		mMutex.lock();
		sessionCount = mSessions.size();
		mMutex.unlock();
		pfds_size = (sessionCount * 4) + 1;
		if (pfds_size > cur_pfds_size) {
			pfds = (struct pollfd*) realloc(pfds, pfds_size * sizeof(struct pollfd));
			cur_pfds_size = pfds_size;
		}
		for (i = 0, it = mSessions.begin(); i < sessionCount; ++i, ++it) {
			(*it)->fillPollFd(&pfds[i * 4]);
		}

		pfds[sessionCount * 4].fd = mCtlPipe[0];
		pfds[sessionCount * 4].events = POLLIN;
		pfds[sessionCount * 4].revents = 0;

		err = poll(pfds, (sessionCount * 4) + 1, -1);
		if (err > 0) {
			if (pfds[sessionCount * 4].revents) {
				char tmp;
				if (read(mCtlPipe[0], &tmp, 1) == -1) {
					LOGE("Fail to read from control pipe.");
				}
			}
			time_t curtime = time(NULL);
			for (i = 0, it = mSessions.begin(); i < sessionCount; ++i, ++it) {
				RelaySession *s = (*it);
				if (s->isUsed()) {
					s->transfer(curtime, &pfds[i * 4]);
				}
			}
		}
		/*cleanup loop*/
		mMutex.lock();
		for (it = mSessions.begin(); it != mSessions.end();) {
			if (!(*it)->isUsed()) {
				delete *it;
				it = mSessions.erase(it);
			} else {
				++it;
			}
		}
		mMutex.unlock();
	}
	if (pfds)
		free(pfds);
}

void *MediaRelayServer::threadFunc(void *arg) {
	MediaRelayServer *zis = (MediaRelayServer*) arg;
	zis->run();
	return NULL;
}
<commit_msg>Fix unset variable<commit_after>/*
 Flexisip, a flexible SIP proxy server with media capabilities.
 Copyright (C) 2010  Belledonne Communications SARL.

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

 This program 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 Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "agent.hh"
#include "mediarelay.hh"

#include <poll.h>

#include <algorithm>
#include <list>

using namespace ::std;

MediaSource::MediaSource(const string &ip, int port) :
		mIp(ip), mPort(port) {
	struct addrinfo *res = NULL;
	struct addrinfo hints = { 0 };
	char portstr[20];
	snprintf(portstr, sizeof(portstr), "%i", port);
	hints.ai_flags = AI_NUMERICHOST | AI_NUMERICSERV;
	int err = getaddrinfo(ip.c_str(), portstr, &hints, &res);
	if (err != 0) {
		LOGE("MediaSource::MediaSource() failed for %s:%i : %s", ip.c_str(), port, gai_strerror(err));
	} else {
		memcpy(&mSockAddr, res->ai_addr, res->ai_addrlen);
		mSockAddrSize = res->ai_addrlen;
		freeaddrinfo(res);
	}
}

MediaSource::MediaSource(const struct sockaddr_storage &sockaddr, socklen_t sockaddr_size) :
		mSockAddrSize(sockaddr_size) {
	memcpy(&mSockAddr, &sockaddr, sockaddr_size);
	char buff[256];
	const char *ret = inet_ntop(AF_INET, &((struct sockaddr_in *) &sockaddr)->sin_addr, buff, sizeof(buff));
	if (ret == NULL) {
		LOGE("MediaSource::MediaSource() failed for %p:", &sockaddr);
	} else {
		mIp = string(ret);
		mPort = ntohs(((struct sockaddr_in *)&sockaddr)->sin_port);
	}
}

RelaySession::RelaySession(const string &bind_ip, const string & public_ip) :
		mBindIp(bind_ip), mPublicIp(public_ip) {
	mLastActivityTime = time(NULL);
	mSession[0] = rtp_session_new(RTP_SESSION_SENDRECV);
	mSession[1] = rtp_session_new(RTP_SESSION_SENDRECV);
	rtp_session_set_local_addr(mSession[0], mBindIp.c_str(), -1);
	rtp_session_set_local_addr(mSession[1], mBindIp.c_str(), -1);
	mSources[0] = rtp_session_get_rtp_socket(mSession[0]);
	mSources[1] = rtp_session_get_rtp_socket(mSession[1]);
	mSources[2] = rtp_session_get_rtcp_socket(mSession[0]);
	mSources[3] = rtp_session_get_rtcp_socket(mSession[1]);
	mUsed = true;
}

int RelaySession::getFrontPort() const {
	return rtp_session_get_local_port(mSession[0]);
}

int RelaySession::getBackPort() const {
	return rtp_session_get_local_port(mSession[1]);
}

void RelaySession::addFront(const string &ip, int port) {
	MediaSource src(ip, port);
	LOGD("Add Front %s:%i", ip.c_str(), port);
	mMutex.lock();
	addFront(src);
	mMutex.unlock();
}

void RelaySession::addBack(const string &ip, int port) {
	MediaSource src(ip, port);
	LOGD("Add Back %s:%i", ip.c_str(), port);
	mMutex.lock();
	addBack(src);
	mMutex.unlock();
}

void RelaySession::addFront(const MediaSource&src) {
	auto it = find(mFront.begin(), mFront.end(), src);
	if (it == mFront.end()) {
		mFront.push_back(src);
	}
}

void RelaySession::removeFront(const string &ip, int port) {
	MediaSource src(ip, port);
	LOGD("Remove Front %s:%i", ip.c_str(), port);
	auto it = find(mFront.begin(), mFront.end(), src);
	if (it != mFront.end()) {
		mFront.erase(it);
	}
}

void RelaySession::addBack(const MediaSource&src) {
	auto it = find(mBack.begin(), mBack.end(), src);
	if (it == mBack.end()) {
		mBack.push_back(src);
	}
}

void RelaySession::removeBack(const string &ip, int port) {
	MediaSource src(ip, port);
	LOGD("Remove Back %s:%i", ip.c_str(), port);
	auto it = find(mBack.begin(), mBack.end(), src);
	if (it != mBack.end()) {
		mBack.erase(it);
	}
}

RelaySession::~RelaySession() {
	rtp_session_destroy(mSession[0]);
	rtp_session_destroy(mSession[1]);
}

void RelaySession::unuse() {
	mUsed = false;
}

void RelaySession::fillPollFd(struct pollfd *tab) {
	int i;
	for (i = 0; i < 4; ++i) {
		tab[i].fd = mSources[i];
		tab[i].events = POLLIN;
		tab[i].revents = 0;
	}
}

void RelaySession::transfer(time_t curtime, struct pollfd *tab) {
	uint8_t buf[1500];
	const int maxsize = sizeof(buf);
	struct sockaddr_storage ss;
	socklen_t slen = sizeof(struct sockaddr);
	int recv_len;
	int send_len;
	int i;

	mMutex.lock();
	for (i = 0; i < 4; i += 2) {
		if (tab[i].revents & POLLIN) {
			mLastActivityTime = curtime;
			recv_len = recvfrom(mSources[i], buf, maxsize, 0, (struct sockaddr*) &ss, &slen);
			if (recv_len > 0) {
				MediaSource src(ss, slen);
				addFront(src);
				list<MediaSource>::iterator it = mBack.begin();
				if (it != mBack.end()) {
					while (it != mBack.end()) {
						const MediaSource &dest = *it;
						//LOGD("(%i)%s:%i -> (%i)%s:%i", getFrontPort(), src.getIp().c_str(), src.getPort(), getBackPort(), dest.getIp().c_str(), dest.getPort());
						send_len = sendto(mSources[i + 1], buf, recv_len, 0, (const struct sockaddr*) &dest.getSockAddr(), dest.getSockAddrSize());
						if (send_len != recv_len) {
							//LOGW("Only %i bytes sent on %i bytes: %s", send_len, recv_len, strerror(errno));
							it = mBack.erase(it);
						} else {
							++it;
						}
					}
				} else {
					//LOGD("%s:%i -> GARBAGE", src.getIp().c_str(), src.getPort());
				}
			}
		}
		if (tab[i + 1].revents & POLLIN) {
			mLastActivityTime = curtime;
			recv_len = recvfrom(mSources[i + 1], buf, maxsize, 0, (struct sockaddr*) &ss, &slen);
			if (recv_len > 0) {
				MediaSource src(ss, slen);
				addBack(src);
				list<MediaSource>::iterator it = mFront.begin();
				if (it != mFront.end()) {
					while (it != mFront.end()) {
						const MediaSource &dest = *it;
						//LOGD("(%i)%s:%i -> (%i)%s:%i", getBackPort(), src.getIp().c_str(), src.getPort(), getFrontPort(), dest.getIp().c_str(), dest.getPort());
						send_len = sendto(mSources[i], buf, recv_len, 0, (const struct sockaddr*) &dest.getSockAddr(), dest.getSockAddrSize());
						if (send_len != recv_len) {
							//LOGW("Only %i bytes sent on %i bytes: %s", send_len, recv_len, strerror(errno));
							it = mFront.erase(it);
						} else {
							++it;
						}
					}
				} else {
					//LOGD("%s:%i -> GARBAGE", src.getIp().c_str(), src.getPort());
				}
			}
		}
	}
	mMutex.unlock();
}

MediaRelayServer::MediaRelayServer(const string &bind_ip, const string &public_ip) :
		mBindIp(bind_ip), mPublicIp(public_ip) {
	mRunning = false;
	if (pipe(mCtlPipe) == -1) {
		LOGF("Could not create MediaRelayServer control pipe.");
	}
}

void MediaRelayServer::start() {
	mRunning = true;
	pthread_create(&mThread, NULL, &MediaRelayServer::threadFunc, this);
}

MediaRelayServer::~MediaRelayServer() {
	if (mRunning) {
		mRunning = false;
		if (write(mCtlPipe[1], "e", 1) == -1)
			LOGE("MediaRelayServer: Fail to write to control pipe.");
		pthread_join(mThread, NULL);
	}
	for_each(mSessions.begin(), mSessions.end(), delete_functor<RelaySession>());
	close(mCtlPipe[0]);
	close(mCtlPipe[1]);
}

RelaySession *MediaRelayServer::createSession() {
	RelaySession *s = new RelaySession(mBindIp, mPublicIp);
	int count;
	mMutex.lock();
	mSessions.push_back(s);
	count = mSessions.size();
	mMutex.unlock();
	if (!mRunning)
		start();

	LOGD("There are now %i relay sessions running.", count);
	/*write to the control pipe to wakeup the server thread */
	if (write(mCtlPipe[1], "e", 1) == -1)
		LOGE("MediaRelayServer: fail to write to control pipe.");
	return s;
}

void MediaRelayServer::run() {
	int sessionCount;
	int i;
	struct pollfd *pfds = NULL;
	list<RelaySession*>::iterator it;
	int err;
	int pfds_size = 0, cur_pfds_size = 0;

	while (mRunning) {
		mMutex.lock();
		sessionCount = mSessions.size();
		mMutex.unlock();
		pfds_size = (sessionCount * 4) + 1;
		if (pfds_size > cur_pfds_size) {
			pfds = (struct pollfd*) realloc(pfds, pfds_size * sizeof(struct pollfd));
			cur_pfds_size = pfds_size;
		}
		for (i = 0, it = mSessions.begin(); i < sessionCount; ++i, ++it) {
			(*it)->fillPollFd(&pfds[i * 4]);
		}

		pfds[sessionCount * 4].fd = mCtlPipe[0];
		pfds[sessionCount * 4].events = POLLIN;
		pfds[sessionCount * 4].revents = 0;

		err = poll(pfds, (sessionCount * 4) + 1, -1);
		if (err > 0) {
			if (pfds[sessionCount * 4].revents) {
				char tmp;
				if (read(mCtlPipe[0], &tmp, 1) == -1) {
					LOGE("Fail to read from control pipe.");
				}
			}
			time_t curtime = time(NULL);
			for (i = 0, it = mSessions.begin(); i < sessionCount; ++i, ++it) {
				RelaySession *s = (*it);
				if (s->isUsed()) {
					s->transfer(curtime, &pfds[i * 4]);
				}
			}
		}
		/*cleanup loop*/
		mMutex.lock();
		for (it = mSessions.begin(); it != mSessions.end();) {
			if (!(*it)->isUsed()) {
				delete *it;
				it = mSessions.erase(it);
			} else {
				++it;
			}
		}
		mMutex.unlock();
	}
	if (pfds)
		free(pfds);
}

void *MediaRelayServer::threadFunc(void *arg) {
	MediaRelayServer *zis = (MediaRelayServer*) arg;
	zis->run();
	return NULL;
}
<|endoftext|>


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

#ifndef DBAUI_JOINCONTROLLER_HXX
#include "JoinController.hxx"
#endif
#ifndef DBAUI_RELATIONDESIGNVIEW_HXX
#include "RelationDesignView.hxx"
#endif

class VCLXWindow;
namespace dbaui
{
    class OTableConnectionData;
    class OTableWindowData;
    class OAddTableDlg;
    class OTableFieldDesc;
    class OTableWindow;
    class ORelationController : public OJoinController
    {
        ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >    m_xTables;
    protected:
        // all the features which should be handled by this class
        virtual void            AddSupportedFeatures();
        // execute a feature
        virtual void            Execute(sal_uInt16 nId);
        virtual ToolBox* CreateToolBox(Window* pParent);

        ORelationDesignView*    getRelationView() { return static_cast<ORelationDesignView*>(m_pView); }
        void loadData();
        sal_Bool existsTable(const ::rtl::OUString& _rComposedTableName) const;
    public:
        ORelationController(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM);

        ~ORelationController();
        // temp
        void SaveTabWinsPosSize( OJoinTableView::OTableWindowMap* pTabWinList, long nOffsetX, long nOffsetY );

        virtual sal_Bool Construct(Window* pParent);

        // ::com::sun::star::beans::XPropertyChangeListener
        virtual void SAL_CALL propertyChange(const ::com::sun::star::beans::PropertyChangeEvent& evt);
        // ::com::sun::star::container::XContainerListener
        virtual void SAL_CALL elementInserted(const ::com::sun::star::container::ContainerEvent& Event) throw( ::com::sun::star::uno::RuntimeException );
        virtual void SAL_CALL elementRemoved(const ::com::sun::star::container::ContainerEvent& Event) throw( ::com::sun::star::uno::RuntimeException );
        virtual void SAL_CALL elementReplaced(const ::com::sun::star::container::ContainerEvent& Event) throw( ::com::sun::star::uno::RuntimeException );

        // ::com::sun::star::frame::XController
        virtual sal_Bool SAL_CALL suspend(sal_Bool bSuspend) throw( ::com::sun::star::uno::RuntimeException );

        // XServiceInfo
        virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);
        // need by registration
        static ::rtl::OUString getImplementationName_Static() throw( ::com::sun::star::uno::RuntimeException );
        static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(void) throw( ::com::sun::star::uno::RuntimeException );
        static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
                SAL_CALL Create(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&);
        // lang::XInitialization
        virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw(::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);

    protected:
        virtual OTableWindowData* createTableWindowData();
    };
}
#endif // DBAUI_RELATIONCONTROLLER_HXX

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

#ifndef DBAUI_JOINCONTROLLER_HXX
#include "JoinController.hxx"
#endif
#ifndef DBAUI_RELATIONDESIGNVIEW_HXX
#include "RelationDesignView.hxx"
#endif

class VCLXWindow;
namespace dbaui
{
    class OTableConnectionData;
    class OTableWindowData;
    class OAddTableDlg;
    class OTableFieldDesc;
    class OTableWindow;
    class ORelationController : public OJoinController
    {
        ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >    m_xTables;
    protected:
        // all the features which should be handled by this class
        virtual void            AddSupportedFeatures();
        // state of a feature. 'feature' may be the handle of a ::com::sun::star::util::URL somebody requested a dispatch interface for OR a toolbar slot.
        virtual FeatureState    GetState(sal_uInt16 nId);
        // execute a feature
        virtual void            Execute(sal_uInt16 nId);
        virtual ToolBox* CreateToolBox(Window* pParent);

        ORelationDesignView*    getRelationView() { return static_cast<ORelationDesignView*>(m_pView); }
        void loadData();
        sal_Bool existsTable(const ::rtl::OUString& _rComposedTableName) const;
    public:
        ORelationController(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM);

        ~ORelationController();
        // temp
        void SaveTabWinsPosSize( OJoinTableView::OTableWindowMap* pTabWinList, long nOffsetX, long nOffsetY );

        virtual sal_Bool Construct(Window* pParent);

        // ::com::sun::star::beans::XPropertyChangeListener
        virtual void SAL_CALL propertyChange(const ::com::sun::star::beans::PropertyChangeEvent& evt);
        // ::com::sun::star::container::XContainerListener
        virtual void SAL_CALL elementInserted(const ::com::sun::star::container::ContainerEvent& Event) throw( ::com::sun::star::uno::RuntimeException );
        virtual void SAL_CALL elementRemoved(const ::com::sun::star::container::ContainerEvent& Event) throw( ::com::sun::star::uno::RuntimeException );
        virtual void SAL_CALL elementReplaced(const ::com::sun::star::container::ContainerEvent& Event) throw( ::com::sun::star::uno::RuntimeException );

        // ::com::sun::star::frame::XController
        virtual sal_Bool SAL_CALL suspend(sal_Bool bSuspend) throw( ::com::sun::star::uno::RuntimeException );

        // XServiceInfo
        virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);
        // need by registration
        static ::rtl::OUString getImplementationName_Static() throw( ::com::sun::star::uno::RuntimeException );
        static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(void) throw( ::com::sun::star::uno::RuntimeException );
        static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
                SAL_CALL Create(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&);
        // lang::XInitialization
        virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw(::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);

    protected:
        virtual OTableWindowData* createTableWindowData();
    };
}
#endif // DBAUI_RELATIONCONTROLLER_HXX

<|endoftext|>


<commit_before>//
// Created by zeph on 11/18/16.
//

#include <iostream>
#include <cassert>
#include <vector>
#include "../helpers/Printer.cpp"

/***
From: https://leetcode.com/problems/two-sum/

 Given an array of integers, return **indices** of the
 two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution.

Example:
```
        Given nums = [2, 7, 11, 15], target = 9,

        Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
```
****/

/**
 * Input:
 *   nums - T array of summable
 *   target - sum to search for
 *
 * Output:
 *   Indices of first two DISTINCT elements of nums which add up to target
 *     IF THIS EXISTS
 *   pair(0,0) - if these don't exist
 */

using namespace std;
typedef pair<unsigned int, unsigned int> indexPair;

template<typename T>
indexPair TwoSum(vector<T> nums, T target) {
    size_t L = nums.size();
    for(unsigned i=0; i<L-1; i++){
        T currTarget = target - nums[i];
        for(unsigned j=i+1; j<L; j++){
            if(nums[j] == currTarget)
                return indexPair(i, j);
        }
    }
    return indexPair(0,0);
}

template <typename T>
indexPair runExample(const vector<T> &nums, T target) {
    cout << "Given: nums = ";
    Printer<T>::prettyPrint(nums);
    cout << "\t\t target = " << target << endl;

    auto solution = TwoSum(nums, target);
    cout << "Solution = ";
    Printer<T>::prettyPrint(solution);
    cout << endl;
    return solution;
}

int main()
{
    vector<int> nums = {2, 7, 11, 15};
    int target = 9;

    indexPair solution = runExample(nums, target);
    assert(solution.first == 0);
    assert(solution.second == 1);

    nums = {1,2,3,4,5,6,7,8,9,10};
    target = 11;
    solution = runExample(nums, target);
    assert(solution.first == 0);
    assert(solution.second == 9);

    target = 14;
    solution = runExample(nums, target);
    assert(solution.first == 3);
    assert(solution.second == 9);

    target = -5;
    solution = runExample(nums, target);
    assert(solution.first == 0);
    assert(solution.second == 0);

    return 0;
}<commit_msg>pass by const reference mangit add ../leetcode/TwoSum.cpp git add ../leetcode/TwoSum.cpp<commit_after>//
// Created by zeph on 11/18/16.
//

#include <iostream>
#include <cassert>
#include <vector>
#include "../helpers/Printer.cpp"

/***
From: https://leetcode.com/problems/two-sum/

 Given an array of integers, return **indices** of the
 two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution.

Example:
```
        Given nums = [2, 7, 11, 15], target = 9,

        Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
```
****/

/**
 * Input:
 *   nums - T array of summable
 *   target - sum to search for
 *
 * Output:
 *   Indices of first two DISTINCT elements of nums which add up to target
 *     IF THIS EXISTS
 *   pair(0,0) - if these don't exist
 */

using namespace std;
typedef pair<unsigned int, unsigned int> indexPair;

template<typename T>
indexPair TwoSum(const vector<T>& nums, const T& target) {
    size_t L = nums.size();
    for(unsigned i=0; i<L-1; i++){
        T currTarget = target - nums[i];
        for(unsigned j=i+1; j<L; j++){
            if(nums[j] == currTarget)
                return indexPair(i, j);
        }
    }
    return indexPair(0,0);
}

template <typename T>
indexPair runExample(const vector<T> &nums, T target) {
    cout << "Given: nums = ";
    Printer<T>::prettyPrint(nums);
    cout << "\t\t target = " << target << endl;

    auto solution = TwoSum(nums, target);
    cout << "Solution = ";
    Printer<T>::prettyPrint(solution);
    cout << endl;
    return solution;
}

int main()
{
    vector<int> nums = {2, 7, 11, 15};
    int target = 9;

    indexPair solution = runExample(nums, target);
    assert(solution.first == 0);
    assert(solution.second == 1);

    nums = {1,2,3,4,5,6,7,8,9,10};
    target = 11;
    solution = runExample(nums, target);
    assert(solution.first == 0);
    assert(solution.second == 9);

    target = 14;
    solution = runExample(nums, target);
    assert(solution.first == 3);
    assert(solution.second == 9);

    target = -5;
    solution = runExample(nums, target);
    assert(solution.first == 0);
    assert(solution.second == 0);

    return 0;
}
<|endoftext|>