<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: PageMasterPropHdl.cxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 15:27:24 $
 *
 *  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_xmloff.hxx"

#ifndef _XMLOFF_PAGEMASTERPROPHDL_HXX_
#include "PageMasterPropHdl.hxx"
#endif

#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include <xmloff/xmluconv.hxx>
#endif
#ifndef _XMLOFF_XMLNUMI_HXX
#include <xmloff/xmlnumi.hxx>
#endif
#ifndef _XMLOFF_XMLNUME_HXX
#include <xmloff/xmlnume.hxx>
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_STYLE_PAGESTYLELAYOUT_HPP_
#include <com/sun/star/style/PageStyleLayout.hpp>
#endif

#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::style;
using namespace ::comphelper;
using namespace ::xmloff::token;

//______________________________________________________________________________

#define DEFAULT_PAPERTRAY   (sal_Int32(-1))

//______________________________________________________________________________
// property handler for style:page-usage (style::PageStyleLayout)

XMLPMPropHdl_PageStyleLayout::~XMLPMPropHdl_PageStyleLayout()
{
}

bool XMLPMPropHdl_PageStyleLayout::equals( const Any& rAny1, const Any& rAny2 ) const
{
    style::PageStyleLayout eLayout1, eLayout2;
    return ((rAny1 >>= eLayout1) && (rAny2 >>= eLayout2)) ? (eLayout1 == eLayout2) : sal_False;
}

sal_Bool XMLPMPropHdl_PageStyleLayout::importXML(
        const OUString& rStrImpValue,
        Any& rValue,
        const SvXMLUnitConverter& ) const
{
    sal_Bool bRet = sal_True;

    if( IsXMLToken( rStrImpValue, XML_ALL ) )
        rValue <<= PageStyleLayout_ALL;
    else if( IsXMLToken( rStrImpValue, XML_LEFT ) )
        rValue <<= PageStyleLayout_LEFT;
    else if( IsXMLToken( rStrImpValue, XML_RIGHT ) )
        rValue <<= PageStyleLayout_RIGHT;
    else if( IsXMLToken( rStrImpValue, XML_MIRRORED ) )
        rValue <<= PageStyleLayout_MIRRORED;
    else
        bRet = sal_False;

    return bRet;
}

sal_Bool XMLPMPropHdl_PageStyleLayout::exportXML(
        OUString& rStrExpValue,
        const Any& rValue,
        const SvXMLUnitConverter& ) const
{
    sal_Bool        bRet = sal_False;
    PageStyleLayout eLayout;

    if( rValue >>= eLayout )
    {
        bRet = sal_True;
        switch( eLayout )
        {
            case PageStyleLayout_ALL:
                rStrExpValue = GetXMLToken( XML_ALL );
            break;
            case PageStyleLayout_LEFT:
                rStrExpValue = GetXMLToken( XML_LEFT );
            break;
            case PageStyleLayout_RIGHT:
                rStrExpValue = GetXMLToken( XML_RIGHT );
            break;
            case PageStyleLayout_MIRRORED:
                rStrExpValue = GetXMLToken( XML_MIRRORED );
            break;
            default:
                bRet = sal_False;
        }
    }

    return bRet;
}

//______________________________________________________________________________
// property handler for style:num-format (style::NumberingType)

XMLPMPropHdl_NumFormat::~XMLPMPropHdl_NumFormat()
{
}

sal_Bool XMLPMPropHdl_NumFormat::importXML(
        const OUString& rStrImpValue,
        Any& rValue,
        const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Int16 nSync = sal_Int16();
    sal_Int16 nNumType = NumberingType::NUMBER_NONE;
    rUnitConverter.convertNumFormat( nNumType, rStrImpValue, OUString(),
                                     sal_True );

    if( !(rValue >>= nSync) )
        nSync = NumberingType::NUMBER_NONE;

    // if num-letter-sync appears before num-format, the function
    // XMLPMPropHdl_NumLetterSync::importXML() sets the value
    // NumberingType::CHARS_LOWER_LETTER_N
    if( nSync == NumberingType::CHARS_LOWER_LETTER_N )
    {
        switch( nNumType )
        {
            case NumberingType::CHARS_LOWER_LETTER:
                nNumType = NumberingType::CHARS_LOWER_LETTER_N;
            break;
            case NumberingType::CHARS_UPPER_LETTER:
                nNumType = NumberingType::CHARS_UPPER_LETTER_N;
            break;
        }
    }
    rValue <<= nNumType;

    return sal_True;
}

sal_Bool XMLPMPropHdl_NumFormat::exportXML(
        OUString& rStrExpValue,
        const Any& rValue,
        const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool    bRet = sal_False;
    sal_Int16   nNumType = sal_Int16();

    if( rValue >>= nNumType )
    {
        OUStringBuffer aBuffer( 10 );
        rUnitConverter.convertNumFormat( aBuffer, nNumType );
        rStrExpValue = aBuffer.makeStringAndClear();
        bRet = sal_True;
    }
    return bRet;
}

//______________________________________________________________________________
// property handler for style:num-letter-sync (style::NumberingType)

XMLPMPropHdl_NumLetterSync::~XMLPMPropHdl_NumLetterSync()
{
}

sal_Bool XMLPMPropHdl_NumLetterSync::importXML(
        const OUString& rStrImpValue,
        Any& rValue,
        const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Int16 nNumType;
    sal_Int16 nSync = NumberingType::NUMBER_NONE;
    rUnitConverter.convertNumFormat( nSync, rStrImpValue,
                                     GetXMLToken( XML_A ), sal_True );

    if( !(rValue >>= nNumType) )
        nNumType = NumberingType::NUMBER_NONE;

    if( nSync == NumberingType::CHARS_LOWER_LETTER_N )
    {
        switch( nNumType )
        {
            case NumberingType::CHARS_LOWER_LETTER:
                nNumType = NumberingType::CHARS_LOWER_LETTER_N;
            break;
            case NumberingType::CHARS_UPPER_LETTER:
                nNumType = NumberingType::CHARS_UPPER_LETTER_N;
            break;
        }
    }
    rValue <<= nNumType;

    return sal_True;
}

sal_Bool XMLPMPropHdl_NumLetterSync::exportXML(
        OUString& rStrExpValue,
        const Any& rValue,
        const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool    bRet = sal_False;
    sal_Int16   nNumType = sal_Int16();

    if( rValue >>= nNumType )
    {
        OUStringBuffer aBuffer( 5 );
        rUnitConverter.convertNumLetterSync( aBuffer, nNumType );
        rStrExpValue = aBuffer.makeStringAndClear();
        bRet = rStrExpValue.getLength() > 0;
    }
    return bRet;
}

//______________________________________________________________________________
// property handler for style:paper-tray-number

XMLPMPropHdl_PaperTrayNumber::~XMLPMPropHdl_PaperTrayNumber()
{
}

sal_Bool XMLPMPropHdl_PaperTrayNumber::importXML(
        const OUString& rStrImpValue,
        Any& rValue,
        const SvXMLUnitConverter& ) const
{
    sal_Bool bRet = sal_False;

    if( IsXMLToken( rStrImpValue, XML_DEFAULT ) )
    {
        rValue <<= DEFAULT_PAPERTRAY;
        bRet = sal_True;
    }
    else
    {
        sal_Int32 nPaperTray;
        if( SvXMLUnitConverter::convertNumber( nPaperTray, rStrImpValue, 0 ) )
        {
            rValue <<= nPaperTray;
            bRet = sal_True;
        }
    }

    return bRet;
}

sal_Bool XMLPMPropHdl_PaperTrayNumber::exportXML(
        OUString& rStrExpValue,
        const Any& rValue,
        const SvXMLUnitConverter& ) const
{
    sal_Bool    bRet = sal_False;
    sal_Int32   nPaperTray = 0;

    if( rValue >>= nPaperTray )
    {
        if( nPaperTray == DEFAULT_PAPERTRAY )
            rStrExpValue = GetXMLToken( XML_DEFAULT );
        else
        {
            OUStringBuffer aBuffer;
            SvXMLUnitConverter::convertNumber( aBuffer, nPaperTray );
            rStrExpValue = aBuffer.makeStringAndClear();
        }
        bRet = sal_True;
    }
    return bRet;
}

//______________________________________________________________________________
// property handler for style:print

XMLPMPropHdl_Print::XMLPMPropHdl_Print( enum XMLTokenEnum eValue ) :
    sAttrValue( GetXMLToken( eValue ) )
{
}

XMLPMPropHdl_Print::~XMLPMPropHdl_Print()
{
}

sal_Bool XMLPMPropHdl_Print::importXML(
        const OUString& rStrImpValue,
        Any& rValue,
        const SvXMLUnitConverter& ) const
{
    sal_Unicode cToken  = ' ';
    sal_Int32   nTokenIndex = 0;
    sal_Bool    bFound  = sal_False;

    do
    {
        bFound = (sAttrValue == rStrImpValue.getToken( 0, cToken, nTokenIndex ));
    }
    while ( (nTokenIndex >= 0) && !bFound );

    setBOOL( rValue, bFound );
    return sal_True;
}

sal_Bool XMLPMPropHdl_Print::exportXML(
        OUString& rStrExpValue,
        const Any& rValue,
        const SvXMLUnitConverter& ) const
{
    if( getBOOL( rValue ) )
    {
        if( rStrExpValue.getLength() )
            rStrExpValue += OUString( RTL_CONSTASCII_USTRINGPARAM( " " ) );
        rStrExpValue += sAttrValue;
    }

    return sal_True;
}

//______________________________________________________________________________
// property handler for style:table-centering

XMLPMPropHdl_CenterHorizontal::~XMLPMPropHdl_CenterHorizontal()
{
}

sal_Bool XMLPMPropHdl_CenterHorizontal::importXML(
        const OUString& rStrImpValue,
        Any& rValue,
        const SvXMLUnitConverter& ) const
{
    sal_Bool bRet = sal_False;

    if (rStrImpValue.getLength())
        if (IsXMLToken( rStrImpValue, XML_BOTH) ||
            IsXMLToken( rStrImpValue, XML_HORIZONTAL))
        {
            rValue = ::cppu::bool2any(sal_True);
            bRet = sal_True;
        }

    return bRet;
}

sal_Bool XMLPMPropHdl_CenterHorizontal::exportXML(
        OUString& rStrExpValue,
        const Any& rValue,
        const SvXMLUnitConverter& ) const
{
    sal_Bool    bRet = sal_False;

    if ( ::cppu::any2bool( rValue ) )
    {
        bRet = sal_True;
        if (rStrExpValue.getLength())
            rStrExpValue = GetXMLToken(XML_BOTH);
        else
            rStrExpValue = GetXMLToken(XML_HORIZONTAL);
    }

    return bRet;
}

XMLPMPropHdl_CenterVertical::~XMLPMPropHdl_CenterVertical()
{
}

sal_Bool XMLPMPropHdl_CenterVertical::importXML(
        const OUString& rStrImpValue,
        Any& rValue,
        const SvXMLUnitConverter& ) const
{
    sal_Bool bRet = sal_False;

    if (rStrImpValue.getLength())
        if (IsXMLToken(rStrImpValue, XML_BOTH) ||
            IsXMLToken(rStrImpValue, XML_VERTICAL) )
        {
            rValue = ::cppu::bool2any(sal_True);
            bRet = sal_True;
        }

    return bRet;
}

sal_Bool XMLPMPropHdl_CenterVertical::exportXML(
        OUString& rStrExpValue,
        const Any& rValue,
        const SvXMLUnitConverter& ) const
{
    sal_Bool    bRet = sal_False;

    if ( ::cppu::any2bool( rValue ) )
    {
        bRet = sal_True;
        if (rStrExpValue.getLength())
            rStrExpValue = GetXMLToken(XML_BOTH);
        else
            rStrExpValue = GetXMLToken(XML_VERTICAL);
    }

    return bRet;
}

<commit_msg>INTEGRATION: CWS impresstables2 (1.14.46); FILE MERGED 2007/08/01 14:25:12 cl 1.14.46.2: RESYNC: (1.14-1.15); FILE MERGED 2007/07/27 09:09:53 cl 1.14.46.1: fixed build issues due to pch and namespace ::rtl<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: PageMasterPropHdl.cxx,v $
 *
 *  $Revision: 1.16 $
 *
 *  last change: $Author: rt $ $Date: 2008-03-12 10:43:42 $
 *
 *  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_xmloff.hxx"

#ifndef _XMLOFF_PAGEMASTERPROPHDL_HXX_
#include "PageMasterPropHdl.hxx"
#endif

#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include <xmloff/xmluconv.hxx>
#endif
#ifndef _XMLOFF_XMLNUMI_HXX
#include <xmloff/xmlnumi.hxx>
#endif
#ifndef _XMLOFF_XMLNUME_HXX
#include <xmloff/xmlnume.hxx>
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_STYLE_PAGESTYLELAYOUT_HPP_
#include <com/sun/star/style/PageStyleLayout.hpp>
#endif

#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif

using ::rtl::OUString;
using ::rtl::OUStringBuffer;

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::style;
using namespace ::comphelper;
using namespace ::xmloff::token;

//______________________________________________________________________________

#define DEFAULT_PAPERTRAY   (sal_Int32(-1))

//______________________________________________________________________________
// property handler for style:page-usage (style::PageStyleLayout)

XMLPMPropHdl_PageStyleLayout::~XMLPMPropHdl_PageStyleLayout()
{
}

bool XMLPMPropHdl_PageStyleLayout::equals( const Any& rAny1, const Any& rAny2 ) const
{
    style::PageStyleLayout eLayout1, eLayout2;
    return ((rAny1 >>= eLayout1) && (rAny2 >>= eLayout2)) ? (eLayout1 == eLayout2) : sal_False;
}

sal_Bool XMLPMPropHdl_PageStyleLayout::importXML(
        const OUString& rStrImpValue,
        Any& rValue,
        const SvXMLUnitConverter& ) const
{
    sal_Bool bRet = sal_True;

    if( IsXMLToken( rStrImpValue, XML_ALL ) )
        rValue <<= PageStyleLayout_ALL;
    else if( IsXMLToken( rStrImpValue, XML_LEFT ) )
        rValue <<= PageStyleLayout_LEFT;
    else if( IsXMLToken( rStrImpValue, XML_RIGHT ) )
        rValue <<= PageStyleLayout_RIGHT;
    else if( IsXMLToken( rStrImpValue, XML_MIRRORED ) )
        rValue <<= PageStyleLayout_MIRRORED;
    else
        bRet = sal_False;

    return bRet;
}

sal_Bool XMLPMPropHdl_PageStyleLayout::exportXML(
        OUString& rStrExpValue,
        const Any& rValue,
        const SvXMLUnitConverter& ) const
{
    sal_Bool        bRet = sal_False;
    PageStyleLayout eLayout;

    if( rValue >>= eLayout )
    {
        bRet = sal_True;
        switch( eLayout )
        {
            case PageStyleLayout_ALL:
                rStrExpValue = GetXMLToken( XML_ALL );
            break;
            case PageStyleLayout_LEFT:
                rStrExpValue = GetXMLToken( XML_LEFT );
            break;
            case PageStyleLayout_RIGHT:
                rStrExpValue = GetXMLToken( XML_RIGHT );
            break;
            case PageStyleLayout_MIRRORED:
                rStrExpValue = GetXMLToken( XML_MIRRORED );
            break;
            default:
                bRet = sal_False;
        }
    }

    return bRet;
}

//______________________________________________________________________________
// property handler for style:num-format (style::NumberingType)

XMLPMPropHdl_NumFormat::~XMLPMPropHdl_NumFormat()
{
}

sal_Bool XMLPMPropHdl_NumFormat::importXML(
        const OUString& rStrImpValue,
        Any& rValue,
        const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Int16 nSync = sal_Int16();
    sal_Int16 nNumType = NumberingType::NUMBER_NONE;
    rUnitConverter.convertNumFormat( nNumType, rStrImpValue, OUString(),
                                     sal_True );

    if( !(rValue >>= nSync) )
        nSync = NumberingType::NUMBER_NONE;

    // if num-letter-sync appears before num-format, the function
    // XMLPMPropHdl_NumLetterSync::importXML() sets the value
    // NumberingType::CHARS_LOWER_LETTER_N
    if( nSync == NumberingType::CHARS_LOWER_LETTER_N )
    {
        switch( nNumType )
        {
            case NumberingType::CHARS_LOWER_LETTER:
                nNumType = NumberingType::CHARS_LOWER_LETTER_N;
            break;
            case NumberingType::CHARS_UPPER_LETTER:
                nNumType = NumberingType::CHARS_UPPER_LETTER_N;
            break;
        }
    }
    rValue <<= nNumType;

    return sal_True;
}

sal_Bool XMLPMPropHdl_NumFormat::exportXML(
        OUString& rStrExpValue,
        const Any& rValue,
        const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool    bRet = sal_False;
    sal_Int16   nNumType = sal_Int16();

    if( rValue >>= nNumType )
    {
        OUStringBuffer aBuffer( 10 );
        rUnitConverter.convertNumFormat( aBuffer, nNumType );
        rStrExpValue = aBuffer.makeStringAndClear();
        bRet = sal_True;
    }
    return bRet;
}

//______________________________________________________________________________
// property handler for style:num-letter-sync (style::NumberingType)

XMLPMPropHdl_NumLetterSync::~XMLPMPropHdl_NumLetterSync()
{
}

sal_Bool XMLPMPropHdl_NumLetterSync::importXML(
        const OUString& rStrImpValue,
        Any& rValue,
        const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Int16 nNumType;
    sal_Int16 nSync = NumberingType::NUMBER_NONE;
    rUnitConverter.convertNumFormat( nSync, rStrImpValue,
                                     GetXMLToken( XML_A ), sal_True );

    if( !(rValue >>= nNumType) )
        nNumType = NumberingType::NUMBER_NONE;

    if( nSync == NumberingType::CHARS_LOWER_LETTER_N )
    {
        switch( nNumType )
        {
            case NumberingType::CHARS_LOWER_LETTER:
                nNumType = NumberingType::CHARS_LOWER_LETTER_N;
            break;
            case NumberingType::CHARS_UPPER_LETTER:
                nNumType = NumberingType::CHARS_UPPER_LETTER_N;
            break;
        }
    }
    rValue <<= nNumType;

    return sal_True;
}

sal_Bool XMLPMPropHdl_NumLetterSync::exportXML(
        OUString& rStrExpValue,
        const Any& rValue,
        const SvXMLUnitConverter& rUnitConverter ) const
{
    sal_Bool    bRet = sal_False;
    sal_Int16   nNumType = sal_Int16();

    if( rValue >>= nNumType )
    {
        OUStringBuffer aBuffer( 5 );
        rUnitConverter.convertNumLetterSync( aBuffer, nNumType );
        rStrExpValue = aBuffer.makeStringAndClear();
        bRet = rStrExpValue.getLength() > 0;
    }
    return bRet;
}

//______________________________________________________________________________
// property handler for style:paper-tray-number

XMLPMPropHdl_PaperTrayNumber::~XMLPMPropHdl_PaperTrayNumber()
{
}

sal_Bool XMLPMPropHdl_PaperTrayNumber::importXML(
        const OUString& rStrImpValue,
        Any& rValue,
        const SvXMLUnitConverter& ) const
{
    sal_Bool bRet = sal_False;

    if( IsXMLToken( rStrImpValue, XML_DEFAULT ) )
    {
        rValue <<= DEFAULT_PAPERTRAY;
        bRet = sal_True;
    }
    else
    {
        sal_Int32 nPaperTray;
        if( SvXMLUnitConverter::convertNumber( nPaperTray, rStrImpValue, 0 ) )
        {
            rValue <<= nPaperTray;
            bRet = sal_True;
        }
    }

    return bRet;
}

sal_Bool XMLPMPropHdl_PaperTrayNumber::exportXML(
        OUString& rStrExpValue,
        const Any& rValue,
        const SvXMLUnitConverter& ) const
{
    sal_Bool    bRet = sal_False;
    sal_Int32   nPaperTray = 0;

    if( rValue >>= nPaperTray )
    {
        if( nPaperTray == DEFAULT_PAPERTRAY )
            rStrExpValue = GetXMLToken( XML_DEFAULT );
        else
        {
            OUStringBuffer aBuffer;
            SvXMLUnitConverter::convertNumber( aBuffer, nPaperTray );
            rStrExpValue = aBuffer.makeStringAndClear();
        }
        bRet = sal_True;
    }
    return bRet;
}

//______________________________________________________________________________
// property handler for style:print

XMLPMPropHdl_Print::XMLPMPropHdl_Print( enum XMLTokenEnum eValue ) :
    sAttrValue( GetXMLToken( eValue ) )
{
}

XMLPMPropHdl_Print::~XMLPMPropHdl_Print()
{
}

sal_Bool XMLPMPropHdl_Print::importXML(
        const OUString& rStrImpValue,
        Any& rValue,
        const SvXMLUnitConverter& ) const
{
    sal_Unicode cToken  = ' ';
    sal_Int32   nTokenIndex = 0;
    sal_Bool    bFound  = sal_False;

    do
    {
        bFound = (sAttrValue == rStrImpValue.getToken( 0, cToken, nTokenIndex ));
    }
    while ( (nTokenIndex >= 0) && !bFound );

    setBOOL( rValue, bFound );
    return sal_True;
}

sal_Bool XMLPMPropHdl_Print::exportXML(
        OUString& rStrExpValue,
        const Any& rValue,
        const SvXMLUnitConverter& ) const
{
    if( getBOOL( rValue ) )
    {
        if( rStrExpValue.getLength() )
            rStrExpValue += OUString( RTL_CONSTASCII_USTRINGPARAM( " " ) );
        rStrExpValue += sAttrValue;
    }

    return sal_True;
}

//______________________________________________________________________________
// property handler for style:table-centering

XMLPMPropHdl_CenterHorizontal::~XMLPMPropHdl_CenterHorizontal()
{
}

sal_Bool XMLPMPropHdl_CenterHorizontal::importXML(
        const OUString& rStrImpValue,
        Any& rValue,
        const SvXMLUnitConverter& ) const
{
    sal_Bool bRet = sal_False;

    if (rStrImpValue.getLength())
        if (IsXMLToken( rStrImpValue, XML_BOTH) ||
            IsXMLToken( rStrImpValue, XML_HORIZONTAL))
        {
            rValue = ::cppu::bool2any(sal_True);
            bRet = sal_True;
        }

    return bRet;
}

sal_Bool XMLPMPropHdl_CenterHorizontal::exportXML(
        OUString& rStrExpValue,
        const Any& rValue,
        const SvXMLUnitConverter& ) const
{
    sal_Bool    bRet = sal_False;

    if ( ::cppu::any2bool( rValue ) )
    {
        bRet = sal_True;
        if (rStrExpValue.getLength())
            rStrExpValue = GetXMLToken(XML_BOTH);
        else
            rStrExpValue = GetXMLToken(XML_HORIZONTAL);
    }

    return bRet;
}

XMLPMPropHdl_CenterVertical::~XMLPMPropHdl_CenterVertical()
{
}

sal_Bool XMLPMPropHdl_CenterVertical::importXML(
        const OUString& rStrImpValue,
        Any& rValue,
        const SvXMLUnitConverter& ) const
{
    sal_Bool bRet = sal_False;

    if (rStrImpValue.getLength())
        if (IsXMLToken(rStrImpValue, XML_BOTH) ||
            IsXMLToken(rStrImpValue, XML_VERTICAL) )
        {
            rValue = ::cppu::bool2any(sal_True);
            bRet = sal_True;
        }

    return bRet;
}

sal_Bool XMLPMPropHdl_CenterVertical::exportXML(
        OUString& rStrExpValue,
        const Any& rValue,
        const SvXMLUnitConverter& ) const
{
    sal_Bool    bRet = sal_False;

    if ( ::cppu::any2bool( rValue ) )
    {
        bRet = sal_True;
        if (rStrExpValue.getLength())
            rStrExpValue = GetXMLToken(XML_BOTH);
        else
            rStrExpValue = GetXMLToken(XML_VERTICAL);
    }

    return bRet;
}

<|endoftext|>


<commit_before>
// Config file test for MUON spectormeter
// Remember to define the directory and option
// gAlice->SetConfigFunction("Config('$HOME','box');");

void Config(char directory[100]="", char option[6]="box")
{
  //
  // Config file for MUON test
  // Gines MARITNEZ, Subatech, mai 2003
  //

  //=====================================================================
  //  Libraries required by geant321
  gSystem->Load("libgeant321.so");

  new TGeant3("C++ Interface to Geant3");

  //=======================================================================
  //  Create the output file
  Text_t filename[100];
  sprintf(filename,"%sgalice.root",directory);
  cout << ">>> Output file is " << filename << endl;
  cout << ">>> Config_MUON_test.C: Creating Run Loader ..."<<endl;
  AliRunLoader* rl = AliRunLoader::Open(
	filename, AliConfig::fgkDefaultEventFolderName, "recreate");
  if (rl == 0x0) {
    gAlice->Fatal("Config_MUON_test.C","Can not instatiate the Run Loader");
    return;
  }
  rl->SetCompressionLevel(2);
  rl->SetNumberOfEventsPerFile(100);
  gAlice->SetRunLoader(rl);

  //=======================================================================
  // MonteCarlo
  TGeant3 *geant3 = (TGeant3*)gMC;

  //=======================================================================
  // Set External decayer
  AliDecayer* decayer = new AliDecayerPythia();
  decayer->SetForceDecay(kAll);
  decayer->Init();
  gMC->SetExternalDecayer(decayer);

  //
  //=======================================================================
  // ******* GEANT STEERING parameters FOR ALICE SIMULATION *******
  geant3->SetTRIG(1); //Number of events to be processed
  geant3->SetSWIT(4,10);
  geant3->SetDEBU(0,0,1);
  //geant3->SetSWIT(2,2);
  geant3->SetDCAY(1);
  geant3->SetPAIR(1);
  geant3->SetCOMP(1);
  geant3->SetPHOT(1);
  geant3->SetPFIS(0);
  geant3->SetDRAY(0);
  geant3->SetANNI(1);
  geant3->SetBREM(1);
  geant3->SetMUNU(1);
  geant3->SetCKOV(1);
  geant3->SetHADR(1); //Select pure GEANH (HADR 1) or GEANH/NUCRIN (HADR 3)
  geant3->SetLOSS(2);
  geant3->SetSTRA(0); // Simulation des collisions dans the thin layers
  geant3->SetMULS(1);
  geant3->SetRAYL(1);
  geant3->SetAUTO(1); //Select automatic STMIN etc... calc. (AUTO 1) or manual (AUTO 0)
  geant3->SetABAN(0); //Restore 3.16 behaviour for abandoned tracks
  geant3->SetOPTI(2); //Select optimisation level for GEANT geometry searches (0,1,2)
  geant3->SetERAN(5.e-7);
  Float_t cut    = 1.e-3; // 1MeV cut by default
  Float_t tofmax = 1.e10;
  //             GAM ELEC NHAD CHAD MUON EBREM MUHAB EDEL MUDEL MUPA TOFMAX
  geant3->SetCUTS(cut,cut, cut, cut, cut, cut,  cut,  cut, cut,  cut, tofmax);
  //
  //=======================================================================
  // ************* STEERING parameters FOR ALICE SIMULATION **************
  // Chamber positions
  // From AliMUONConstants class we get :
  //   Position Z (along beam) of the chambers (in cm)
  //        (from AliMUONConstants class):
  //    533.5,  546.5,  678.5, 693.5,  964.0, 986.0, 1251.5, 1278.5,
  //   1416.5, 1443.5,  1610, 1625.,  1710., 1725.
  //   Internal Radius (in cm)
  //     36.4,  46.2,  66.0,  80.,  80., 100., 100.
  //   External Radius (in cm)
  //    183.,  245.,  395.,  560., 563., 850., 900.
  //=======================================================================
  if (!strcmp(option,"box")) {
    AliGenBox * gener = new AliGenBox(1);
    gener->SetMomentumRange(7.,7.1);
    gener->SetPhiRange(-180., 180.);
    gener->SetThetaRange(2.000,9.000);
    gener->SetPart(13);           // Muons
    gener->SetOrigin(0.,0., 0.);  //vertex position
    gener->SetSigma(0.0, 0.0, 0.0);         //Sigma in (X,Y,Z) (cm) on IP position
  }
  if (!strcmp(option,"gun")) {
    //*********************************************
    // Example for Fixed Particle Gun             *
    //*********************************************
    AliGenFixed *gener = new AliGenFixed(ntracks);
    gener->SetMomentum(10);
    gener->SetPhiRange(0.);
    gener->SetThetaRange(0.);
    gener->SetOrigin(30,30,1200);//vertex position
    gener->SetPart(13);          //GEANT particle type  13 is muons
  }
  if (!strcmp(option,"param")) {
    //*******************************************************
    // Example for J/psi or Upsilon Production from  Parameterisation *
    //*******************************************************
    AliGenParam *gener = new AliGenParam(1, AliGenMUONlib::kUpsilon);
    gener->SetMomentumRange(0,999);
    gener->SetPtRange(0,100.);
    gener->SetPhiRange(-180, 180);
    gener->SetYRange(2.5,4);
    gener->SetCutOnChild(1);
    gener->SetChildThetaRange(2.0,9);
    gener->SetOrigin(0,0,0);          //vertex position    gener->SetSigma(0,0,0);           //Sigma in (X,Y,Z) (cm) on IP position
    gener->SetForceDecay(kDiMuon);
    gener->SetTrackingFlag(1);
  }

  //=============================================================
  //Specify maximum magnetic field in Tesla (neg. ==> default field)
  gAlice->SetField(2,1) ;  //(-999,2);

  //=================== Alice BODY parameters =============================
  AliBODY *BODY = new AliBODY("BODY","Alice envelop");

  //=================== MUON Subsystem ===========================
  AliMUONv1 *MUON  = new AliMUONv1("MUON","default");

}

Float_t EtaToTheta(Float_t arg){
  return (180./TMath::Pi())*2.*atan(exp(-arg));
}
<commit_msg>Updating Config_MUON_test.C from macros/Config.C<commit_after>// Config file test for MUON spectormeter
// Remember to define the directory and option
// gAlice->SetConfigFunction("Config('$HOME','box');");

void Config(char directory[100]="", char option[6]="box")
{
  //
  // Config file for MUON test
  // Gines MARITNEZ, Subatech, mai 2003, august 2003
  //

  //=====================================================================
  //  Libraries required by geant321
  gSystem->Load("libgeant321.so");
  new TGeant3("C++ Interface to Geant3");
  //=======================================================================
  //  Create the output file
  Text_t filename[100];
  sprintf(filename,"%sgalice.root",directory);
  cout << ">>> Output file is " << filename << endl;
  cout << ">>> Config_MUON_test.C: Creating Run Loader ..."<<endl;
  AliRunLoader* rl=0x0;
  rl = AliRunLoader::Open(
	filename, AliConfig::fgkDefaultEventFolderName, "recreate");
  if (rl == 0x0) {
    gAlice->Fatal("Config_MUON_test.C","Can not instatiate the Run Loader");
    return;
  }
  rl->SetCompressionLevel(2);
  rl->SetNumberOfEventsPerFile(100);
  gAlice->SetRunLoader(rl);

  //=======================================================================
  // Set External decayer
  TVirtualMCDecayer *decayer = new AliDecayerPythia();
  decayer->SetForceDecay(kAll);
  decayer->Init();
  gMC->SetExternalDecayer(decayer);

  //
  //=======================================================================
  // ******* GEANT STEERING parameters FOR ALICE SIMULATION *******
    gMC->SetProcess("DCAY",1);
    gMC->SetProcess("PAIR",1);
    gMC->SetProcess("COMP",1);
    gMC->SetProcess("PHOT",1);
    gMC->SetProcess("PFIS",0);
    gMC->SetProcess("DRAY",0);
    gMC->SetProcess("ANNI",1);
    gMC->SetProcess("BREM",1);
    gMC->SetProcess("MUNU",1);
    gMC->SetProcess("CKOV",1);
    gMC->SetProcess("HADR",1);
    gMC->SetProcess("LOSS",2);
    gMC->SetProcess("MULS",1);
    gMC->SetProcess("RAYL",1);

    Float_t cut = 1.e-3;        // 1MeV cut by default
    Float_t tofmax = 1.e10;

    gMC->SetCut("CUTGAM", cut);
    gMC->SetCut("CUTELE", cut);
    gMC->SetCut("CUTNEU", cut);
    gMC->SetCut("CUTHAD", cut);
    gMC->SetCut("CUTMUO", cut);
    gMC->SetCut("BCUTE",  cut);
    gMC->SetCut("BCUTM",  cut);
    gMC->SetCut("DCUTE",  cut);
    gMC->SetCut("DCUTM",  cut);
    gMC->SetCut("PPCUTM", cut);
    gMC->SetCut("TOFMAX", tofmax);
  //
  //=======================================================================
  // ************* STEERING parameters FOR ALICE SIMULATION **************
  // Chamber positions
  // From AliMUONConstants class we get :
  //   Position Z (along beam) of the chambers (in cm)
  //        (from AliMUONConstants class):
  //    533.5,  546.5,  678.5, 693.5,  964.0, 986.0, 1251.5, 1278.5,
  //   1416.5, 1443.5,  1610, 1625.,  1710., 1725.
  //   Internal Radius (in cm)
  //     36.4,  46.2,  66.0,  80.,  80., 100., 100.
  //   External Radius (in cm)
  //    183.,  245.,  395.,  560., 563., 850., 900.
  //=======================================================================
  if (!strcmp(option,"box")) {
    AliGenBox * gener = new AliGenBox(1);
    gener->SetMomentumRange(7.,7.1);
    gener->SetPhiRange(-180., 180.);
    gener->SetThetaRange(2.000,9.000);
    gener->SetPart(13);           // Muons
    gener->SetOrigin(0.,0., 0.);  //vertex position
    gener->SetSigma(0.0, 0.0, 0.0);         //Sigma in (X,Y,Z) (cm) on IP position
  }
  if (!strcmp(option,"gun")) {
    //*********************************************
    // Example for Fixed Particle Gun             *
    //*********************************************
    AliGenFixed *gener = new AliGenFixed(ntracks);
    gener->SetMomentum(10);
    gener->SetPhiRange(0.);
    gener->SetThetaRange(0.);
    gener->SetOrigin(30,30,1200);//vertex position
    gener->SetPart(13);          //GEANT particle type  13 is muons
  }
  if (!strcmp(option,"param")) {
    //*******************************************************
    // Example for J/psi or Upsilon Production from  Parameterisation *
    //*******************************************************
    AliGenParam *gener = new AliGenParam(1, AliGenMUONlib::kUpsilon);
    gener->SetMomentumRange(0,999);
    gener->SetPtRange(0,100.);
    gener->SetPhiRange(-180, 180);
    gener->SetYRange(2.5,4);
    gener->SetCutOnChild(1);
    gener->SetChildThetaRange(2.0,9);
    gener->SetOrigin(0,0,0);          //vertex position    gener->SetSigma(0,0,0);           //Sigma in (X,Y,Z) (cm) on IP position
    gener->SetForceDecay(kDiMuon);
    gener->SetTrackingFlag(1);
  }

  //=============================================================
  //Specify maximum magnetic field in Tesla (neg. ==> default field)
  AliMagFMaps* field = new AliMagFMaps("Maps","Maps", 2, 1., 10., 1);
  gAlice->SetField(field);

  //=================== Alice BODY parameters =============================
  AliBODY *BODY = new AliBODY("BODY","Alice envelop");

  //=================== MUON Subsystem ===========================
  AliMUONv1 *MUON  = new AliMUONv1("MUON","default");

}

Float_t EtaToTheta(Float_t arg){
  return (180./TMath::Pi())*2.*atan(exp(-arg));
}
<|endoftext|>


<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
*                                                                        *
* Author: The ALICE Off-line Project.                                    *
* Contributors are mentioned in the code where appropriate.              *
*                                                                        *
* Permission to use, copy, modify and distribute this software and its   *
* documentation strictly for non-commercial purposes is hereby granted   *
* without fee, provided that the above copyright notice appears in all   *
* copies and that both the copyright notice and this permission notice   *
* appear in the supporting documentation. The authors make no claims     *
* about the suitability of this software for any purpose. It is          *
* provided "as is" without express or implied warranty.                  *
**************************************************************************/

/* $Id$ */

/// \ingroup macros
/// \file MUONOfflineShift.C
/// \brief Macro to be used to check raw data during MUON offline shifts.
///
/// Basic usage is :
///
/// MUONOfflineShift("path_to_raw_file","basename of output file"); > log
///
/// (the redirection to an output log file is recommended as the output from
/// this macro might be quite long...)
///
/// This will read the raw data and process it several times, varying what's done :
/// only decoding, decoding + zero-suppression, etc... (TBE)
///
/// Two outputs files will be created :
///
/// - basename.root, containing AliMUONVTrackerData objects that can then
///   be displayed using the mchview program (using mchview --use basename.root)
///
/// - basename.log, containing (for the moment) the occupancy numbers of the various detection elements
///
/// \author Laurent Aphecetche

#if !defined(__CINT__) || defined(__MAKECINT__)

#include "AliCDBManager.h"
#include "AliCodeTimer.h"
#include "AliMUONPainterRegistry.h"
#include "AliMUONTrackerDataMaker.h"
#include "AliMUONTrackerRawDataMaker.h"
#include "AliMUONVTrackerData.h"
#include "AliMpCDB.h"
#include "AliMpConstants.h"
#include "AliMpDEIterator.h"
#include "AliRawReader.h"
#include <Riostream.h>
#include <TFile.h>
#include <TGrid.h>
#include <TStopwatch.h>
#include <TString.h>
#include <TSystem.h>

#endif

//______________________________________________________________________________
Int_t DataMakerReading(const char* input,
                       TStopwatch& timer,
                       const char* cdbPath="",
                       const char* calibMode="",
                       Bool_t histogram=kFALSE,
                       Double_t xmin = 0.0,
                       Double_t xmax = 4096.0,
                       Bool_t fastDecoder=kFALSE)
{
  /// Run over the data and calibrate it if so required (if cdbPath != "")
  /// calibMode can be :
  /// - NOGAIN           : only zero-suppression will be done
  /// - GAINCONSTANTCAPA : zero-suppression + gain, but with a single capa value for all channels
  /// - GAIN             : zero-suppression + gain w/ individual capacitance per channel.

  TString fileName(gSystem->ExpandPathName(input));

  AliRawReader* rawReader = AliRawReader::Create(fileName.Data());

  if (!rawReader) return 0;

  AliMUONVTrackerDataMaker* dm(0x0);

  if ( strlen(cdbPath) > 0 )
  {
    dm = new AliMUONTrackerDataMaker(rawReader,cdbPath,calibMode,histogram,xmin,xmax);
  }
  else
  {
    dm = new AliMUONTrackerDataMaker(rawReader,histogram,fastDecoder);
  }

  AliMUONPainterRegistry::Instance()->Register(dm);

  timer.Start(kTRUE);
  Int_t n(0);

  dm->SetRunning(kTRUE);

  while (dm->NextEvent())
  {
    ++n;
  }

  timer.Stop();

  return n;
}

//______________________________________________________________________________
void Print(const char* method, TStopwatch& timer, Int_t n)
{
  /// Get the timing for a given method

  cout << Form("%20s %10d events. Total CPU time %7.2f seconds.",
               method,n,timer.CpuTime());

  Double_t cpu = timer.CpuTime()/n;
  Double_t real = timer.RealTime()/n;

  cout << Form(" ms real/event = %7.2f ms CPU/event = %7.2f",real*1E3,cpu*1E3)
    << endl;
}

//______________________________________________________________________________
void Occupancy(ostream& outfile)
{
  /// Write occupancy numbers to output text file

  outfile << "-----------------------------------------------------" << endl;
  outfile << "Occupancy numbers" << endl;
  outfile << "-----------------------------------------------------" << endl;

  const Int_t occIndex = 2;

  AliMUONPainterRegistry* reg = AliMUONPainterRegistry::Instance();

  Int_t nofDataSources = reg->NumberOfDataSources();

  outfile << Form("%11s|"," ");

  for ( Int_t ids = 0; ids < nofDataSources; ++ ids )
  {
    AliMUONVTrackerData* data = reg->DataSource(ids);
    outfile << Form(" %13s |",data->GetName());
  }

  outfile << endl;

  for ( Int_t chamberId = 0; chamberId < AliMpConstants::NofTrackingChambers(); ++chamberId )
  {
    Bool_t nonZero(kFALSE);
    for ( Int_t ids = 0; ids < nofDataSources && nonZero == kFALSE; ++ ids )
    {
      if ( reg->DataSource(ids)->Chamber(chamberId,occIndex) ) nonZero = kTRUE;
    }

    if ( !nonZero ) continue;

    outfile << Form("Chamber %2d |",chamberId);
    for ( Int_t ids = 0; ids < nofDataSources; ++ ids )
    {
      AliMUONVTrackerData* data = reg->DataSource(ids);
      outfile << Form("   %7.2f %%   |",100.0*data->Chamber(chamberId,occIndex));
    }
    outfile << endl;

    AliMpDEIterator it;
    it.First(chamberId);
    while (!it.IsDone())
    {
      Int_t detElemId = it.CurrentDEId();
      Bool_t nonZero(kFALSE);
      for ( Int_t ids = 0; ids < nofDataSources && nonZero == kFALSE; ++ ids )
      {
        AliMUONVTrackerData* data = reg->DataSource(ids);
        if ( data->DetectionElement(detElemId,occIndex) > 0 )
        {
          nonZero = kTRUE;
        }
      }

      if ( nonZero )
      {
        outfile << Form("   DE %04d |",detElemId);
        for ( Int_t ids = 0; ids < nofDataSources; ++ ids )
        {
          AliMUONVTrackerData* data = reg->DataSource(ids);
          outfile << Form("   %7.2f %%   |",100.0*data->DetectionElement(detElemId,occIndex));
        }
        outfile << endl;
      }
      it.Next();
    }
  }
}

//______________________________________________________________________________
void MUONOfflineShift(const char* input="alien:///alice/data/2008/LHC08a/000021931/raw/08000021931001.50.root",
                      const char* outputBase="21931.001.50",
                      const char* ocdbPath="alien://folder=/alice/data/2008/LHC08a/OCDB")
{
  /// Entry point of the macro.
  /// Example of syntax for an input file (from alien)
  ///
  /// alien::///alice/data/2007/LHC07w/000014493/raw/07000014493001.10.root
  ///
  /// and for an OCDB path :
  ///
  /// alien://folder=/alice/data/2007/LHC07w/OCDB
  ///

  TGrid::Connect("alien://");

  AliCodeTimer::Instance()->Reset();

  AliCDBManager::Instance()->SetDefaultStorage("local://$ALICE_ROOT/OCDB");
  AliCDBManager::Instance()->SetRun(0);
  AliMpCDB::LoadDDLStore();

  TStopwatch timer0;
  TStopwatch timer1;
  TStopwatch timer2;
  TStopwatch timer3;
  TStopwatch timer4;

  Int_t n0 = DataMakerReading(input,timer0,"","",kTRUE,0,0,kFALSE); // using old decoder

  Int_t n1 = DataMakerReading(input,timer1,"","",kTRUE,0,0,kTRUE); // using new decoder

  Int_t n2 = DataMakerReading(input,timer2,ocdbPath,"NOGAIN",kTRUE);

  Int_t n3 = DataMakerReading(input,timer3,ocdbPath,"GAINCONSTANTCAPA",kTRUE);

  Int_t n4 = DataMakerReading(input,timer4,ocdbPath,"GAIN",kTRUE);

  Print("DataMakerReading(HRAW)",timer0,n0);
  Print("DataMakerReading(HRAW)",timer1,n1);
  Print("DataMakerReading(HCALZ)",timer2,n2);
  Print("DataMakerReading(HCALG)",timer3,n3);
  Print("DataMakerReading(HCALC)",timer4,n4);

  AliMUONPainterRegistry* reg = AliMUONPainterRegistry::Instance();

  TFile f(gSystem->ExpandPathName(Form("%s.root",outputBase)),"RECREATE");
  ofstream out(gSystem->ExpandPathName(Form("%s.log",outputBase)));

  Occupancy(out);

  for ( Int_t i = 0; i < reg->NumberOfDataSources(); ++i )
  {
    AliMUONVTrackerData* data = reg->DataSource(i);
    data->Write();
  }

  f.Close();

  AliCodeTimer::Instance()->Print();

}
<commit_msg>Update for latest changes in muon code<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
*                                                                        *
* Author: The ALICE Off-line Project.                                    *
* Contributors are mentioned in the code where appropriate.              *
*                                                                        *
* Permission to use, copy, modify and distribute this software and its   *
* documentation strictly for non-commercial purposes is hereby granted   *
* without fee, provided that the above copyright notice appears in all   *
* copies and that both the copyright notice and this permission notice   *
* appear in the supporting documentation. The authors make no claims     *
* about the suitability of this software for any purpose. It is          *
* provided "as is" without express or implied warranty.                  *
**************************************************************************/

/* $Id$ */

/// \ingroup macros
/// \file MUONOfflineShift.C
/// \brief Macro to be used to check raw data during MUON offline shifts.
///
/// You NEED an access to the Grid to run this macro.
///
/// Basic usage is :
///
/// MUONOfflineShift("path_to_raw_file","basename of output file"); > log
///
/// (the redirection to an output log file is recommended as the output from
/// this macro might be quite long...)
///
/// This will read the raw data and process it several times, varying what's done :
/// only decoding, decoding + zero-suppression, etc... (TBE)
///
/// Two outputs files will be created :
///
/// - basename.root, containing AliMUONVTrackerData objects that can then
///   be displayed using the mchview program (using mchview --use basename.root)
///
/// - basename.log, containing (for the moment) the occupancy numbers of the various detection elements
///
/// Unless you really know what you're doing, please use this macro together with
/// the grid OCDB (i.e. don't set it to a local OCDB). There are now a lot of things
/// that are grabbed from the OCDB that are run dependent...
///
/// \author Laurent Aphecetche

#if !defined(__CINT__) || defined(__MAKECINT__)

#include "AliCDBEntry.h"
#include "AliCDBManager.h"
#include "AliCodeTimer.h"
#include "AliMUONPainterRegistry.h"
#include "AliMUONRecoParam.h"
#include "AliMUONTrackerDataMaker.h"
#include "AliMUONVTrackerData.h"
#include "AliMpCDB.h"
#include "AliMpConstants.h"
#include "AliMpDEIterator.h"
#include "AliRawReader.h"
#include <Riostream.h>
#include <TFile.h>
#include <TGrid.h>
#include <TStopwatch.h>
#include <TString.h>
#include <TSystem.h>

#endif

//______________________________________________________________________________
Int_t DataMakerReading(const char* input,
                       TStopwatch& timer,
                       const char* cdbPath="",
                       const char* calibMode="",
                       Bool_t histogram=kFALSE,
                       Double_t xmin = 0.0,
                       Double_t xmax = 4096.0)
{
  /// Run over the data and calibrate it if so required (if cdbPath != "")
  /// calibMode can be :
  /// - NOGAIN           : only zero-suppression will be done
  /// - GAINCONSTANTCAPA : zero-suppression + gain, but with a single capa value for all channels
  /// - GAIN             : zero-suppression + gain w/ individual capacitance per channel.

  TString fileName(gSystem->ExpandPathName(input));

  AliRawReader* rawReader = AliRawReader::Create(fileName.Data());

  if (!rawReader) return 0;

  AliMUONVTrackerDataMaker* dm(0x0);

  AliCDBEntry* entry = AliCDBManager::Instance()->Get("MUON/Calib/RecoParam");
  AliMUONRecoParam* recoParam(0x0);

  if ( entry ) recoParam = static_cast<AliMUONRecoParam*>(entry->GetObject());

  if ( strlen(cdbPath) > 0 )
  {
    dm = new AliMUONTrackerDataMaker(recoParam,rawReader,cdbPath,calibMode,histogram,xmin,xmax);
  }
  else
  {
    dm = new AliMUONTrackerDataMaker(rawReader,histogram);
  }

  AliMUONPainterRegistry::Instance()->Register(dm);

  timer.Start(kTRUE);
  Int_t n(0);

  dm->SetRunning(kTRUE);

  while (dm->NextEvent())
  {
    ++n;
  }

  timer.Stop();

  return n;
}

//______________________________________________________________________________
void Print(const char* method, TStopwatch& timer, Int_t n)
{
  /// Get the timing for a given method

  cout << Form("%20s %10d events. Total CPU time %7.2f seconds.",
               method,n,timer.CpuTime());

  Double_t cpu = timer.CpuTime()/n;
  Double_t real = timer.RealTime()/n;

  cout << Form(" ms real/event = %7.2f ms CPU/event = %7.2f",real*1E3,cpu*1E3)
    << endl;
}

//______________________________________________________________________________
void Occupancy(ostream& outfile)
{
  /// Write occupancy numbers to output text file

  outfile << "-----------------------------------------------------" << endl;
  outfile << "Occupancy numbers" << endl;
  outfile << "-----------------------------------------------------" << endl;

  const Int_t occIndex = 2;

  AliMUONPainterRegistry* reg = AliMUONPainterRegistry::Instance();

  Int_t nofDataSources = reg->NumberOfDataSources();

  outfile << Form("%11s|"," ");

  for ( Int_t ids = 0; ids < nofDataSources; ++ ids )
  {
    AliMUONVTrackerData* data = reg->DataSource(ids);
    outfile << Form(" %13s |",data->GetName());
  }

  outfile << endl;

  for ( Int_t chamberId = 0; chamberId < AliMpConstants::NofTrackingChambers(); ++chamberId )
  {
    Bool_t nonZero(kFALSE);
    for ( Int_t ids = 0; ids < nofDataSources && nonZero == kFALSE; ++ ids )
    {
      if ( reg->DataSource(ids)->Chamber(chamberId,occIndex) ) nonZero = kTRUE;
    }

    if ( !nonZero ) continue;

    outfile << Form("Chamber %2d |",chamberId);
    for ( Int_t ids = 0; ids < nofDataSources; ++ ids )
    {
      AliMUONVTrackerData* data = reg->DataSource(ids);
      outfile << Form("   %7.2f %%   |",100.0*data->Chamber(chamberId,occIndex));
    }
    outfile << endl;

    AliMpDEIterator it;
    it.First(chamberId);
    while (!it.IsDone())
    {
      Int_t detElemId = it.CurrentDEId();
      Bool_t nonZero(kFALSE);
      for ( Int_t ids = 0; ids < nofDataSources && nonZero == kFALSE; ++ ids )
      {
        AliMUONVTrackerData* data = reg->DataSource(ids);
        if ( data->DetectionElement(detElemId,occIndex) > 0 )
        {
          nonZero = kTRUE;
        }
      }

      if ( nonZero )
      {
        outfile << Form("   DE %04d |",detElemId);
        for ( Int_t ids = 0; ids < nofDataSources; ++ ids )
        {
          AliMUONVTrackerData* data = reg->DataSource(ids);
          outfile << Form("   %7.2f %%   |",100.0*data->DetectionElement(detElemId,occIndex));
        }
        outfile << endl;
      }
      it.Next();
    }
  }
}

//______________________________________________________________________________
void MUONOfflineShift(const char* input="alien:///alice/data/2009/LHC09a/000067495/raw/09000067495031.10.root",
                      const char* outputBase="67495031.10",
                      const char* ocdbPath="alien://folder=/alice/data/2009/OCDB")
{
  /// Entry point of the macro.

  AliCodeTimer::Instance()->Reset();

  TGrid::Connect("alien://");

  AliRawReader* rawReader = AliRawReader::Create(input);

  rawReader->NextEvent();

  Int_t runNumber = rawReader->GetRunNumber();

  delete rawReader;

  AliCDBManager::Instance()->SetDefaultStorage(ocdbPath);
  AliCDBManager::Instance()->SetRun(runNumber);

  AliMpCDB::LoadDDLStore();
  AliMpCDB::LoadManuStore();

  TStopwatch timer1;
  TStopwatch timer2;
  TStopwatch timer3;
  TStopwatch timer4;

  Int_t n1 = DataMakerReading(input,timer1,"","",kTRUE,0,0);

  Int_t n2 = DataMakerReading(input,timer2,ocdbPath,"NOGAIN");

  Int_t n3 = DataMakerReading(input,timer3,ocdbPath,"GAINCONSTANTCAPA");

  Int_t n4 = DataMakerReading(input,timer4,ocdbPath,"GAIN");

  Print("DataMakerReading(HRAW)",timer1,n1);
  Print("DataMakerReading(HCALZ)",timer2,n2);
  Print("DataMakerReading(HCALG)",timer3,n3);
  Print("DataMakerReading(HCALC)",timer4,n4);

  AliMUONPainterRegistry* reg = AliMUONPainterRegistry::Instance();

  TFile f(gSystem->ExpandPathName(Form("%s.root",outputBase)),"RECREATE");
  ofstream out(gSystem->ExpandPathName(Form("%s.log",outputBase)));

  Occupancy(out);

  for ( Int_t i = 0; i < reg->NumberOfDataSources(); ++i )
  {
    AliMUONVTrackerData* data = reg->DataSource(i);
    data->Write();
  }

  f.Close();

  AliCodeTimer::Instance()->Print();

}
<|endoftext|>


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

#include "common/harness.h"

#include "storage/tuple.h"
#include "type/value.h"

namespace peloton {
namespace test {

//===--------------------------------------------------------------------===//
// Value Tests
//===--------------------------------------------------------------------===//

class ValueTests : public PelotonTest {};

TEST_F(ValueTests, VarcharCopyTest) {
  std::string str = "hello hello world";

  // Try it once with and without a pool
  for (int i = 0; i < 2; i++) {
    type::VarlenPool *pool = nullptr;
    if (i == 0) {
      pool = TestingHarness::GetInstance().GetTestingPool();
    }
    type::Value val1 = type::ValueFactory::GetVarcharValue(str, pool);
    type::Value val2 = val1.Copy();

    // The Value objects should not be the same
    EXPECT_NE(val1.GetData(), val2.GetData());

    // But their underlying data should be equal
    auto result = val1.CompareEquals(val2);
    EXPECT_EQ(type::CmpBool::CMP_TRUE, result);
  }  // FOR
}
}
}
<commit_msg>New test case for Value.Hash()<commit_after>
//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// value_test.cpp
//
// Identification: /peloton/test/type/value_test.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "common/harness.h"

#include "storage/tuple.h"
#include "type/value.h"

namespace peloton {
namespace test {

//===--------------------------------------------------------------------===//
// Value Tests
//===--------------------------------------------------------------------===//

class ValueTests : public PelotonTest {};

const std::vector<type::Type::TypeId> valueTestTypes = {
    type::Type::BOOLEAN,   type::Type::TINYINT, type::Type::SMALLINT,
    type::Type::INTEGER,   type::Type::BIGINT,  type::Type::DECIMAL,
    type::Type::TIMESTAMP, type::Type::VARCHAR};

TEST_F(ValueTests, HashTest) {
  for (auto col_type : valueTestTypes) {
    auto maxVal = type::Type::GetMaxValue(col_type);
    auto minVal = type::Type::GetMinValue(col_type);

    // Special case for VARCHAR
    if (col_type == type::Type::VARCHAR) {
      maxVal = type::ValueFactory::GetVarcharValue("XXX", nullptr);
      minVal = type::ValueFactory::GetVarcharValue("YYY", nullptr);
    }
    LOG_TRACE("%s => MAX:%s <-> MIN:%s", TypeIdToString(col_type).c_str(),
              maxVal.ToString().c_str(), minVal.ToString().c_str());

    // They should not be equal
    EXPECT_EQ(type::CmpBool::CMP_FALSE, maxVal.CompareEquals(minVal));

    // Nor should their hash values be equal
    auto maxHash = maxVal.Hash();
    auto minHash = minVal.Hash();
    EXPECT_NE(maxHash, minHash);

    // But if I copy the first value then the hashes should be the same
    auto copyVal = maxVal.Copy();
    auto copyHash = copyVal.Hash();
    EXPECT_EQ(type::CmpBool::CMP_TRUE, maxVal.CompareEquals(copyVal));
    EXPECT_EQ(maxHash, copyHash);
  }  // FOR
}

TEST_F(ValueTests, VarcharCopyTest) {
  std::string str = "hello hello world";

  // Try it once with and without a pool
  for (int i = 0; i < 2; i++) {
    type::VarlenPool *pool = nullptr;
    if (i == 0) {
      pool = TestingHarness::GetInstance().GetTestingPool();
    }
    type::Value val1 = type::ValueFactory::GetVarcharValue(str, pool);
    type::Value val2 = val1.Copy();

    // The Value objects should not be the same
    EXPECT_NE(val1.GetData(), val2.GetData());

    // But their underlying data should be equal
    auto result = val1.CompareEquals(val2);
    EXPECT_EQ(type::CmpBool::CMP_TRUE, result);
  }  // FOR
}
}
}
<|endoftext|>


<commit_before>//
//  Video.cpp
//  Clock Signal
//
//  Created by Thomas Harte on 12/10/2016.
//  Copyright © 2016 Thomas Harte. All rights reserved.
//

#include "Video.hpp"

using namespace Oric;

namespace {
	const unsigned int PAL50VSyncStartPosition = 256*64;
	const unsigned int PAL60VSyncStartPosition = 234*64;
	const unsigned int PAL50VSyncEndPosition = 259*64;
	const unsigned int PAL60VSyncEndPosition = 238*64;
	const unsigned int PAL50Period = 312*64;
	const unsigned int PAL60Period = 262*64;
}

VideoOutput::VideoOutput(uint8_t *memory) :
	_ram(memory),
	_frame_counter(0), _counter(0),
	_state(Sync), _cycles_in_state(0),
	_is_graphics_mode(false),
	_character_set_base_address(0xb400),
	_phase(0),
	_v_sync_start_position(PAL50VSyncStartPosition), _v_sync_end_position(PAL50VSyncEndPosition),
	_counter_period(PAL50Period), _next_frame_is_sixty_hertz(false)
{
	_crt.reset(new Outputs::CRT::CRT(64*6, 6, Outputs::CRT::DisplayType::PAL50, 1));

	// TODO: this is a copy and paste from the Electron; factor out.
	_crt->set_rgb_sampling_function(
		"vec3 rgb_sample(usampler2D sampler, vec2 coordinate, vec2 icoordinate)"
		"{"
			"uint texValue = texture(sampler, coordinate).r;"
			"texValue >>= 4 - (int(icoordinate.x * 8) & 4);"
			"return vec3( uvec3(texValue) & uvec3(4u, 2u, 1u));"
		"}");

	_crt->set_output_device(Outputs::CRT::Television);
	_crt->set_visible_area(_crt->get_rect_for_area(50, 224, 16 * 6, 40 * 6, 4.0f / 3.0f));
}

std::shared_ptr<Outputs::CRT::CRT> VideoOutput::get_crt()
{
	return _crt;
}

void VideoOutput::run_for_cycles(int number_of_cycles)
{
	// Vertical: 0–39: pixels; otherwise blank; 48–53 sync
	// Horizontal: 0–223: pixels; otherwise blank; 256–259 sync

	while(number_of_cycles--)
	{
		_counter = (_counter + 1)%_counter_period;
		int h_counter =_counter & 63;

		if(!h_counter)
		{
			_ink = 0xff;
			_paper = 0x00;
			_use_alternative_character_set = _use_double_height_characters = _blink_text = false;
			set_character_set_base_address();
			_phase += 64;

			if(!_counter)
			{
				_phase += 128;
				_frame_counter++;

				_v_sync_start_position = _next_frame_is_sixty_hertz ? PAL60VSyncStartPosition : PAL50VSyncStartPosition;
				_v_sync_end_position = _next_frame_is_sixty_hertz ? PAL60VSyncEndPosition : PAL50VSyncEndPosition;
				_counter_period = _next_frame_is_sixty_hertz ? PAL60Period : PAL50Period;
			}
		}

		State new_state = Blank;
		if(
			(h_counter >= 48 && h_counter <= 53) ||
			(_counter >= _v_sync_start_position && _counter <= _v_sync_end_position)) new_state = Sync;
		else if(h_counter >= 54 && h_counter <= 56) new_state = ColourBurst;
		else if(_counter < 224*64 && h_counter < 40) new_state = Pixels;

		if(_state != new_state)
		{
			switch(_state)
			{
				case ColourBurst:	_crt->output_colour_burst(_cycles_in_state * 6, _phase, 128);	break;
				case Sync:			_crt->output_sync(_cycles_in_state * 6);						break;
				case Blank:			_crt->output_blank(_cycles_in_state * 6);						break;
				case Pixels:		_crt->output_data(_cycles_in_state * 6, 2);						break;
			}
			_state = new_state;
			_cycles_in_state = 0;
			if(_state == Pixels) _pixel_target = _crt->allocate_write_area(120);
		}
		_cycles_in_state++;

		if(new_state == Pixels) {
			uint8_t pixels, control_byte;

			if(_is_graphics_mode && _counter < 200*64)
			{
				control_byte = pixels = _ram[0xa000 + (_counter >> 6) * 40 + h_counter];
			}
			else
			{
				int address = 0xbb80 + (_counter >> 9) * 40 + h_counter;
				control_byte = _ram[address];
				int line = _use_double_height_characters ? ((_counter >> 7) & 7) : ((_counter >> 6) & 7);
				pixels = _ram[_character_set_base_address + (control_byte&127) * 8 + line];
			}

			uint8_t inverse_mask = (control_byte & 0x80) ? 0x77 : 0x00;
			if(_blink_text) inverse_mask ^= (_frame_counter&32) ? 0x77 : 0x00;

			if((control_byte & 0x7f) >= 32)
			{
				if(_pixel_target)
				{
					uint8_t colours[2] = {
						(uint8_t)(_paper ^ inverse_mask),
						(uint8_t)(_ink ^ inverse_mask),
					};

					_pixel_target[0] = (colours[(pixels >> 4)&1] & 0x0f) | (colours[(pixels >> 5)&1] & 0xf0);
					_pixel_target[1] = (colours[(pixels >> 2)&1] & 0x0f) | (colours[(pixels >> 3)&1] & 0xf0);
					_pixel_target[2] = (colours[(pixels >> 0)&1] & 0x0f) | (colours[(pixels >> 1)&1] & 0xf0);
				}
			}
			else
			{
				switch(control_byte & 0x7f)
				{
					case 0x00:		_ink = 0x00;	break;
					case 0x01:		_ink = 0x44;	break;
					case 0x02:		_ink = 0x22;	break;
					case 0x03:		_ink = 0x66;	break;
					case 0x04:		_ink = 0x11;	break;
					case 0x05:		_ink = 0x55;	break;
					case 0x06:		_ink = 0x33;	break;
					case 0x07:		_ink = 0x77;	break;

					case 0x08:	case 0x09:	case 0x0a: case 0x0b:
					case 0x0c:	case 0x0d:	case 0x0e: case 0x0f:
						_use_alternative_character_set = (control_byte&1);
						_use_double_height_characters = (control_byte&2);
						_blink_text = (control_byte&4);
						set_character_set_base_address();
					break;

					case 0x10:		_paper = 0x00;	break;
					case 0x11:		_paper = 0x44;	break;
					case 0x12:		_paper = 0x22;	break;
					case 0x13:		_paper = 0x66;	break;
					case 0x14:		_paper = 0x11;	break;
					case 0x15:		_paper = 0x55;	break;
					case 0x16:		_paper = 0x33;	break;
					case 0x17:		_paper = 0x77;	break;

					case 0x18: case 0x19: case 0x1a: case 0x1b:
					case 0x1c: case 0x1d: case 0x1e: case 0x1f:
						_is_graphics_mode = (control_byte & 4);
						_next_frame_is_sixty_hertz = !(control_byte & 2);
					break;

					default: break;
				}
				if(_pixel_target) _pixel_target[0] = _pixel_target[1] = _pixel_target[2] = (uint8_t)(_paper ^ inverse_mask);
			}
			if(_pixel_target) _pixel_target += 3;
		}
	}
}
<commit_msg>Made it slightly more clear that the correct test is conformed to.<commit_after>//
//  Video.cpp
//  Clock Signal
//
//  Created by Thomas Harte on 12/10/2016.
//  Copyright © 2016 Thomas Harte. All rights reserved.
//

#include "Video.hpp"

using namespace Oric;

namespace {
	const unsigned int PAL50VSyncStartPosition = 256*64;
	const unsigned int PAL60VSyncStartPosition = 234*64;
	const unsigned int PAL50VSyncEndPosition = 259*64;
	const unsigned int PAL60VSyncEndPosition = 238*64;
	const unsigned int PAL50Period = 312*64;
	const unsigned int PAL60Period = 262*64;
}

VideoOutput::VideoOutput(uint8_t *memory) :
	_ram(memory),
	_frame_counter(0), _counter(0),
	_state(Sync), _cycles_in_state(0),
	_is_graphics_mode(false),
	_character_set_base_address(0xb400),
	_phase(0),
	_v_sync_start_position(PAL50VSyncStartPosition), _v_sync_end_position(PAL50VSyncEndPosition),
	_counter_period(PAL50Period), _next_frame_is_sixty_hertz(false)
{
	_crt.reset(new Outputs::CRT::CRT(64*6, 6, Outputs::CRT::DisplayType::PAL50, 1));

	// TODO: this is a copy and paste from the Electron; factor out.
	_crt->set_rgb_sampling_function(
		"vec3 rgb_sample(usampler2D sampler, vec2 coordinate, vec2 icoordinate)"
		"{"
			"uint texValue = texture(sampler, coordinate).r;"
			"texValue >>= 4 - (int(icoordinate.x * 8) & 4);"
			"return vec3( uvec3(texValue) & uvec3(4u, 2u, 1u));"
		"}");

	_crt->set_output_device(Outputs::CRT::Television);
	_crt->set_visible_area(_crt->get_rect_for_area(50, 224, 16 * 6, 40 * 6, 4.0f / 3.0f));
}

std::shared_ptr<Outputs::CRT::CRT> VideoOutput::get_crt()
{
	return _crt;
}

void VideoOutput::run_for_cycles(int number_of_cycles)
{
	// Vertical: 0–39: pixels; otherwise blank; 48–53 sync
	// Horizontal: 0–223: pixels; otherwise blank; 256–259 sync

	while(number_of_cycles--)
	{
		_counter = (_counter + 1)%_counter_period;
		int h_counter =_counter & 63;

		if(!h_counter)
		{
			printf("\n");
			_ink = 0xff;
			_paper = 0x00;
			_use_alternative_character_set = _use_double_height_characters = _blink_text = false;
			set_character_set_base_address();
			_phase += 64;

			if(!_counter)
			{
				_phase += 128;
				_frame_counter++;

				_v_sync_start_position = _next_frame_is_sixty_hertz ? PAL60VSyncStartPosition : PAL50VSyncStartPosition;
				_v_sync_end_position = _next_frame_is_sixty_hertz ? PAL60VSyncEndPosition : PAL50VSyncEndPosition;
				_counter_period = _next_frame_is_sixty_hertz ? PAL60Period : PAL50Period;
			}
		}

		State new_state = Blank;
		if(
			(h_counter >= 48 && h_counter <= 53) ||
			(_counter >= _v_sync_start_position && _counter <= _v_sync_end_position)) new_state = Sync;
		else if(h_counter >= 54 && h_counter <= 56) new_state = ColourBurst;
		else if(_counter < 224*64 && h_counter < 40) new_state = Pixels;

		if(_state != new_state)
		{
			switch(_state)
			{
				case ColourBurst:	_crt->output_colour_burst(_cycles_in_state * 6, _phase, 128);	break;
				case Sync:			_crt->output_sync(_cycles_in_state * 6);						break;
				case Blank:			_crt->output_blank(_cycles_in_state * 6);						break;
				case Pixels:		_crt->output_data(_cycles_in_state * 6, 2);						break;
			}
			_state = new_state;
			_cycles_in_state = 0;
			if(_state == Pixels) _pixel_target = _crt->allocate_write_area(120);
		}
		_cycles_in_state++;

		if(new_state == Pixels) {
			uint8_t pixels, control_byte;

			if(_is_graphics_mode && _counter < 200*64)
			{
				control_byte = pixels = _ram[0xa000 + (_counter >> 6) * 40 + h_counter];
			}
			else
			{
				int address = 0xbb80 + (_counter >> 9) * 40 + h_counter;
				control_byte = _ram[address];
				int line = _use_double_height_characters ? ((_counter >> 7) & 7) : ((_counter >> 6) & 7);
				pixels = _ram[_character_set_base_address + (control_byte&127) * 8 + line];
			}

			uint8_t inverse_mask = (control_byte & 0x80) ? 0x77 : 0x00;
			if(_blink_text) inverse_mask ^= (_frame_counter&32) ? 0x77 : 0x00;

			if(control_byte & 0x60)
			{
				if(_pixel_target)
				{
					uint8_t colours[2] = {
						(uint8_t)(_paper ^ inverse_mask),
						(uint8_t)(_ink ^ inverse_mask),
					};

					_pixel_target[0] = (colours[(pixels >> 4)&1] & 0x0f) | (colours[(pixels >> 5)&1] & 0xf0);
					_pixel_target[1] = (colours[(pixels >> 2)&1] & 0x0f) | (colours[(pixels >> 3)&1] & 0xf0);
					_pixel_target[2] = (colours[(pixels >> 0)&1] & 0x0f) | (colours[(pixels >> 1)&1] & 0xf0);
				}
			}
			else
			{
				switch(control_byte & 0x1f)
				{
					case 0x00:		_ink = 0x00;	break;
					case 0x01:		_ink = 0x44;	break;
					case 0x02:		_ink = 0x22;	break;
					case 0x03:		_ink = 0x66;	break;
					case 0x04:		_ink = 0x11;	break;
					case 0x05:		_ink = 0x55;	break;
					case 0x06:		_ink = 0x33;	break;
					case 0x07:		_ink = 0x77;	break;

					case 0x08:	case 0x09:	case 0x0a: case 0x0b:
					case 0x0c:	case 0x0d:	case 0x0e: case 0x0f:
						_use_alternative_character_set = (control_byte&1);
						_use_double_height_characters = (control_byte&2);
						_blink_text = (control_byte&4);
						set_character_set_base_address();
					break;

					case 0x10:		_paper = 0x00;	break;
					case 0x11:		_paper = 0x44;	break;
					case 0x12:		_paper = 0x22;	break;
					case 0x13:		_paper = 0x66;	break;
					case 0x14:		_paper = 0x11;	break;
					case 0x15:		_paper = 0x55;	break;
					case 0x16:		_paper = 0x33;	break;
					case 0x17:		_paper = 0x77;	break;

					case 0x18: case 0x19: case 0x1a: case 0x1b:
					case 0x1c: case 0x1d: case 0x1e: case 0x1f:
						_is_graphics_mode = (control_byte & 4);
						_next_frame_is_sixty_hertz = !(control_byte & 2);
					break;

					default: break;
				}
				if(_pixel_target) _pixel_target[0] = _pixel_target[1] = _pixel_target[2] = (uint8_t)(_paper ^ inverse_mask);
			}
			if(_pixel_target) _pixel_target += 3;
		}
	}
}
<|endoftext|>


<commit_before>#include "../ui.h"
#include "ui-node.h"
#include "nbind/api.h"

class UiButton : public UiControl {
	DEFINE_EVENT(onClicked)

  public:
	UiButton(const char *text);
	UiButton();
	DEFINE_CONTROL_METHODS()
	void setText(const char *text);
	const char *getText();
};

UiButton::UiButton(const char *text)
	: UiControl((uiControl *)uiNewButton(text)) {}
UiButton::UiButton() : UiControl((uiControl *)uiNewButton("")) {}

INHERITS_CONTROL_METHODS(UiButton)

void UiButton::setText(const char *text) {
	uiButtonSetText((uiButton *)getHandle(), text);
}

const char *UiButton::getText() {
	return uiButtonText((uiButton *)getHandle());
}

IMPLEMENT_EVENT(UiButton, uiButton, onClicked, uiButtonOnClicked)

NBIND_CLASS(UiButton) {
	construct<const char *>();
	construct<>();
	DECLARE_CHILD_CONTROL_METHODS()
	getset(getText, setText);
	method(getText);
	method(setText);
	method(onClicked);
}
<commit_msg>std::string --> UiButton<commit_after>#include <string>
#include "../ui.h"
#include "ui-node.h"
#include "nbind/api.h"

class UiButton : public UiControl {
	DEFINE_EVENT(onClicked)

  public:
	UiButton(std::string text);
	UiButton();
	DEFINE_CONTROL_METHODS()
	void setText(std::string text);
	std::string getText();
};

UiButton::UiButton(std::string text)
	: UiControl(uiControl(uiNewButton(text.c_str()))) {}
UiButton::UiButton() : UiControl(uiControl(uiNewButton(""))) {}

INHERITS_CONTROL_METHODS(UiButton)

void UiButton::setText(std::string text) {
	uiButtonSetText(uiButton(getHandle()), text.c_str());
}

std::string UiButton::getText() {
	char *char_ptr = uiButtonText(uiButton(getHandle()));
	std::string s(char_ptr);
	uiFreeText(char_ptr);
	return s;
}

IMPLEMENT_EVENT(UiButton, uiButton, onClicked, uiButtonOnClicked)

NBIND_CLASS(UiButton) {
	construct<std::string>();
	construct<>();
	DECLARE_CHILD_CONTROL_METHODS()
	getset(getText, setText);
	method(getText);
	method(setText);
	method(onClicked);
}
<|endoftext|>


<commit_before>/*
 * This file is part of libcontextprovider.
 *
 * Copyright (C) 2009 Nokia Corporation.
 *
 * Contact: Jean-Luc Lamadon <jean-luc.lamadon@nokia.com>
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

#include "servicetest.h"
#include "sconnect.h"

#include "service.h"
#include "property.h"

#include <QtTest/QtTest>
#include <QProcess>
#include <QStringList>

#define SERVICE_NAME "org.maemo.contextkit.testProvider"

namespace ContextProvider {

void ServiceTests::initTestCase()
{
}

void ServiceTests::cleanupTestCase()
{
}

// Before each test
void ServiceTests::init()
{
    // Initialize test program state
    isReadyToRead = false;

    // Start the client
    client = new QProcess();
    sconnect(client, SIGNAL(readyReadStandardOutput()), this, SLOT(readStandardOutput()));
    client->start("client");
    // Record whether the client was successfully started
    clientStarted = client->waitForStarted();

    // Associate shorter names for the test services when communicating with the client
    if (clientStarted) {
        qDebug() << "Writing";
        writeToClient("assign session " SERVICE_NAME " service\n");
    }
}

// After each test
void ServiceTests::cleanup()
{
    // Stop the client
    if (clientStarted) {
        client->kill();
        client->waitForFinished();
    }
    delete client; client = NULL;
}

void ServiceTests::startStopStart()
{
    // Check that the initialization went well.
    // Doing this only in init() is not enough; doesn't stop the test case.
    QVERIFY(clientStarted);

    // Test: create a Service and an associated Property
    Service* service = new Service(QDBusConnection::SessionBus, SERVICE_NAME);
    Property* property = new Property(*service, "Test.Property");

    // Test: command client to subscribe
    QString actual = writeToClient("subscribe service Test.Property\n");

    // Expected result: service is started automatically and Subscribe works
    QString expected = "Subscribe returned: Unknown";
    QCOMPARE(actual.simplified(), expected.simplified());

    // Test: stop the service and try to subscribe again
    service->stop();
    actual = writeToClient("subscribe service Test.Property\n");

    // Expected result: the client can no more subscribe
    expected = "Subscribe error: org.freedesktop.DBus.Error.ServiceUnknown";
    QCOMPARE(actual.simplified(), expected.simplified());

    // Test: start the service and try to subscribe again
    service->start();
    actual = writeToClient("subscribe service Test.Property\n");

    // Expected result: service is started and Subscribe works
    expected = "Subscribe returned: Unknown";
    QCOMPARE(actual.simplified(), expected.simplified());

}

void ServiceTests::readStandardOutput()
{
    isReadyToRead = true;
}

// Note: input must end with \n
QString ServiceTests::writeToClient(const char* input)
{
    isReadyToRead = false;
    client->write(input);
    client->waitForBytesWritten();

    // Blocking for reading operation is bad idea since the client
    // expects provider to reply to dbus calls

    while (!isReadyToRead) {
        QCoreApplication::processEvents(QEventLoop::AllEvents);
    }

    // Return the output from the client
    return client->readAll();
}

} // end namespace

QTEST_MAIN(ContextProvider::ServiceTests);
<commit_msg>libcontextprovider, protocol change: Updating customer tests cont.<commit_after>/*
 * This file is part of libcontextprovider.
 *
 * Copyright (C) 2009 Nokia Corporation.
 *
 * Contact: Jean-Luc Lamadon <jean-luc.lamadon@nokia.com>
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

#include "servicetest.h"
#include "sconnect.h"

#include "service.h"
#include "property.h"

#include <QtTest/QtTest>
#include <QProcess>
#include <QStringList>

#define SERVICE_NAME "org.maemo.contextkit.testProvider"

namespace ContextProvider {

void ServiceTests::initTestCase()
{
}

void ServiceTests::cleanupTestCase()
{
}

// Before each test
void ServiceTests::init()
{
    // Initialize test program state
    isReadyToRead = false;

    // Start the client
    client = new QProcess();
    sconnect(client, SIGNAL(readyReadStandardOutput()), this, SLOT(readStandardOutput()));
    client->start("client");
    // Record whether the client was successfully started
    clientStarted = client->waitForStarted();

    // Associate shorter names for the test services when communicating with the client
    if (clientStarted) {
        writeToClient("assign session " SERVICE_NAME " service\n");
    }
}

// After each test
void ServiceTests::cleanup()
{
    // Stop the client
    if (clientStarted) {
        client->kill();
        client->waitForFinished();
    }
    delete client; client = NULL;
}

void ServiceTests::startStopStart()
{
    // Check that the initialization went well.
    // Doing this only in init() is not enough; doesn't stop the test case.
    QVERIFY(clientStarted);

    // Test: create a Service and an associated Property
    Service* service = new Service(QDBusConnection::SessionBus, SERVICE_NAME);
    Property* property = new Property(*service, "Test.Property");

    // Test: command client to subscribe
    QString actual = writeToClient("subscribe service Test.Property\n");

    // Expected result: service is started automatically and Subscribe works
    QString expected = "Subscribe returned: Unknown";
    QCOMPARE(actual.simplified(), expected.simplified());

    // Test: stop the service and try to subscribe again
    service->stop();
    actual = writeToClient("subscribe service Test.Property\n");

    // Expected result: the client can no more subscribe
    expected = "Subscribe error: org.freedesktop.DBus.Error.ServiceUnknown";
    QCOMPARE(actual.simplified(), expected.simplified());

    // Test: start the service and try to subscribe again
    service->start();
    actual = writeToClient("subscribe service Test.Property\n");

    // Expected result: service is started and Subscribe works
    expected = "Subscribe returned: Unknown";
    QCOMPARE(actual.simplified(), expected.simplified());

}

void ServiceTests::readStandardOutput()
{
    isReadyToRead = true;
}

// Note: input must end with \n
QString ServiceTests::writeToClient(const char* input)
{
    isReadyToRead = false;
    client->write(input);
    client->waitForBytesWritten();

    // Blocking for reading operation is bad idea since the client
    // expects provider to reply to dbus calls

    while (!isReadyToRead) {
        QCoreApplication::processEvents(QEventLoop::AllEvents);
    }

    // Return the output from the client
    return client->readAll();
}

} // end namespace

QTEST_MAIN(ContextProvider::ServiceTests);
<|endoftext|>