<commit_before>/*************************************************************************
 *
 *  $RCSfile: XMLTextMasterPageContext.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2004-07-13 08:38:09 $
 *
 *  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 _COM_SUN_STAR_STYLE_XSTYLE_HPP_
#include <com/sun/star/style/XStyle.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_STYLE_PAGESTYLELAYOUT_HPP_
#include <com/sun/star/style/PageStyleLayout.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XMULTIPROPERTYSTATES_HPP_
#include <com/sun/star/beans/XMultiPropertyStates.hpp>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include "nmspmap.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XMLOFF_TEXTMASTERPAGECONTEXT_HXX_
#include "XMLTextMasterPageContext.hxx"
#endif
#ifndef _XMLOFF_TEXTHEADERFOOTERCONTEXT_HXX_
#include "XMLTextHeaderFooterContext.hxx"
#endif
#ifndef _XMLOFF_XMLIMP_HXX
#include "xmlimp.hxx"
#endif
#ifndef _XMLOFF_PAGEMASTERIMPORTCONTEXT_HXX
#include "PageMasterImportContext.hxx"
#endif

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;
using namespace ::com::sun::star::style;
using namespace ::com::sun::star::text;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
//using namespace ::com::sun::star::text;
using namespace ::xmloff::token;

Reference < XStyle > XMLTextMasterPageContext::Create()
{
    Reference < XStyle > xNewStyle;

    Reference< XMultiServiceFactory > xFactory( GetImport().GetModel(),
                                                    UNO_QUERY );
    if( xFactory.is() )
    {
        Reference < XInterface > xIfc =
            xFactory->createInstance(OUString(RTL_CONSTASCII_USTRINGPARAM(
                                    "com.sun.star.style.PageStyle")) );
        if( xIfc.is() )
            xNewStyle = Reference < XStyle >( xIfc, UNO_QUERY );
    }

    return xNewStyle;
}
TYPEINIT1( XMLTextMasterPageContext, SvXMLStyleContext );

XMLTextMasterPageContext::XMLTextMasterPageContext( SvXMLImport& rImport,
        sal_uInt16 nPrfx, const OUString& rLName,
        const Reference< XAttributeList > & xAttrList,
        sal_Bool bOverwrite ) :
    SvXMLStyleContext( rImport, nPrfx, rLName, xAttrList, XML_STYLE_FAMILY_MASTER_PAGE ),
    sIsPhysical( RTL_CONSTASCII_USTRINGPARAM( "IsPhysical" ) ),
    sFollowStyle( RTL_CONSTASCII_USTRINGPARAM( "FollowStyle" ) ),
    sPageStyleLayout( RTL_CONSTASCII_USTRINGPARAM( "PageStyleLayout" ) ),
    sPageMasterName(),
    bInsertHeader( sal_False ),
    bInsertFooter( sal_False ),
    bInsertHeaderLeft( sal_False ),
    bInsertFooterLeft( sal_False ),
    bHeaderInserted( sal_False ),
    bFooterInserted( sal_False ),
    bHeaderLeftInserted( sal_False ),
    bFooterLeftInserted( sal_False )
{
    OUString sName, sDisplayName;
    sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
    for( sal_Int16 i=0; i < nAttrCount; i++ )
    {
        const OUString& rAttrName = xAttrList->getNameByIndex( i );
        OUString aLocalName;
        sal_uInt16 nPrefix = GetImport().GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName );
        if( XML_NAMESPACE_STYLE == nPrefix )
        {
            if( IsXMLToken( aLocalName, XML_NAME ) )
            {
                sName = xAttrList->getValueByIndex( i );
            }
            else if( IsXMLToken( aLocalName, XML_DISPLAY_NAME ) )
            {
                sDisplayName = xAttrList->getValueByIndex( i );
            }
            else if( IsXMLToken( aLocalName, XML_NEXT_STYLE_NAME ) )
            {
                sFollow = xAttrList->getValueByIndex( i );
            }
            else if( IsXMLToken( aLocalName, XML_PAGE_LAYOUT_NAME ) )
            {
                sPageMasterName = xAttrList->getValueByIndex( i );
            }
        }
    }

    if( sDisplayName.getLength() )
    {
        rImport.AddStyleDisplayName( XML_STYLE_FAMILY_MASTER_PAGE, sName,
                                     sDisplayName );
    }
    else
    {
        sDisplayName = sName;
    }

    if( 0 == sDisplayName.getLength() )
        return;

    Reference < XNameContainer > xPageStyles =
            GetImport().GetTextImport()->GetPageStyles();
    if( !xPageStyles.is() )
        return;

    Any aAny;
    sal_Bool bNew = sal_False;
    if( xPageStyles->hasByName( sDisplayName ) )
    {
        aAny = xPageStyles->getByName( sDisplayName );
        aAny >>= xStyle;
    }
    else
    {
        xStyle = Create();
        if( !xStyle.is() )
            return;

        aAny <<= xStyle;
        xPageStyles->insertByName( sDisplayName, aAny );
        bNew = sal_True;
    }

    Reference < XPropertySet > xPropSet( xStyle, UNO_QUERY );
    Reference< XPropertySetInfo > xPropSetInfo =
                xPropSet->getPropertySetInfo();
    if( !bNew && xPropSetInfo->hasPropertyByName( sIsPhysical ) )
    {
        aAny = xPropSet->getPropertyValue( sIsPhysical );
        bNew = !*(sal_Bool *)aAny.getValue();
    }
    SetNew( bNew );

    if( bOverwrite || bNew )
    {
        Reference < XMultiPropertyStates > xMultiStates( xPropSet,
                                                         UNO_QUERY );
        OSL_ENSURE( xMultiStates.is(),
                    "text page style does not support multi property set" );
        if( xMultiStates.is() )
            xMultiStates->setAllPropertiesToDefault();

        bInsertHeader = bInsertFooter = sal_True;
        bInsertHeaderLeft = bInsertFooterLeft = sal_True;
    }
}

XMLTextMasterPageContext::~XMLTextMasterPageContext()
{
}

SvXMLImportContext *XMLTextMasterPageContext::CreateChildContext(
        sal_uInt16 nPrefix,
        const OUString& rLocalName,
        const Reference< XAttributeList > & xAttrList )
{
    SvXMLImportContext *pContext = 0;

    const SvXMLTokenMap& rTokenMap =
        GetImport().GetTextImport()->GetTextMasterPageElemTokenMap();

    sal_Bool bInsert = sal_False, bFooter = sal_False, bLeft = sal_False;
    switch( rTokenMap.Get( nPrefix, rLocalName ) )
    {
    case XML_TOK_TEXT_MP_HEADER:
        if( bInsertHeader && !bHeaderInserted )
        {
            bInsert = sal_True;
            bHeaderInserted = sal_True;
        }
        break;
    case XML_TOK_TEXT_MP_FOOTER:
        if( bInsertFooter && !bFooterInserted )
        {
            bInsert = bFooter = sal_True;
            bFooterInserted = sal_True;
        }
        break;
    case XML_TOK_TEXT_MP_HEADER_LEFT:
        if( bInsertHeaderLeft && bHeaderInserted && !bHeaderLeftInserted )
            bInsert = bLeft = sal_True;
        break;
    case XML_TOK_TEXT_MP_FOOTER_LEFT:
        if( bInsertFooterLeft && bFooterInserted && !bFooterLeftInserted )
            bInsert = bFooter = bLeft = sal_True;
        break;
    }

    if( bInsert && xStyle.is() )
    {
        pContext = CreateHeaderFooterContext( nPrefix, rLocalName,
                                                    xAttrList,
                                                    bFooter, bLeft );
    }
    else
    {
        pContext = SvXMLStyleContext::CreateChildContext( nPrefix, rLocalName,
                                                          xAttrList );
    }

    return pContext;
}

SvXMLImportContext *XMLTextMasterPageContext::CreateHeaderFooterContext(
            sal_uInt16 nPrefix,
            const ::rtl::OUString& rLocalName,
            const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList,
            const sal_Bool bFooter,
            const sal_Bool bLeft )
{
    Reference < XPropertySet > xPropSet( xStyle, UNO_QUERY );
    return new XMLTextHeaderFooterContext( GetImport(),
                                                nPrefix, rLocalName,
                                                xAttrList,
                                                xPropSet,
                                                bFooter, bLeft );
}

void XMLTextMasterPageContext::Finish( sal_Bool bOverwrite )
{
    if( xStyle.is() && (IsNew() || bOverwrite) )
    {
        Reference < XPropertySet > xPropSet( xStyle, UNO_QUERY );
        if ( sPageMasterName.getLength() )
        {
            XMLPropStyleContext* pStyle =
                GetImport().GetTextImport()->FindPageMaster( sPageMasterName );
            if (pStyle)
            {
                pStyle->FillPropertySet(xPropSet);
            }
        }

        Reference < XNameContainer > xPageStyles =
            GetImport().GetTextImport()->GetPageStyles();
        if( !xPageStyles.is() )
            return;

        if( !sFollow.getLength() || !xPageStyles->hasByName( sFollow ) )
            sFollow = xStyle->getName();

        Reference< XPropertySetInfo > xPropSetInfo =
            xPropSet->getPropertySetInfo();
        if( xPropSetInfo->hasPropertyByName( sFollowStyle ) )
        {
            OUString sDisplayFollow(
                GetImport().GetStyleDisplayName(
                        XML_STYLE_FAMILY_MASTER_PAGE, sFollow ) );
            Any aAny = xPropSet->getPropertyValue( sFollowStyle );
            OUString sCurrFollow;
            aAny >>= sCurrFollow;
            if( sCurrFollow != sDisplayFollow )
            {
                aAny <<= sDisplayFollow;
                xPropSet->setPropertyValue( sFollowStyle, aAny );
            }
        }
    }
}
<commit_msg>INTEGRATION: CWS oasis2 (1.8.4); FILE MERGED 2004/07/26 09:01:35 mib 1.8.4.1: i31300: next page was not set correctly<commit_after>/*************************************************************************
 *
 *  $RCSfile: XMLTextMasterPageContext.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: rt $ $Date: 2004-08-20 08:15:03 $
 *
 *  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 _COM_SUN_STAR_STYLE_XSTYLE_HPP_
#include <com/sun/star/style/XStyle.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_STYLE_PAGESTYLELAYOUT_HPP_
#include <com/sun/star/style/PageStyleLayout.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XMULTIPROPERTYSTATES_HPP_
#include <com/sun/star/beans/XMultiPropertyStates.hpp>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include "nmspmap.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XMLOFF_TEXTMASTERPAGECONTEXT_HXX_
#include "XMLTextMasterPageContext.hxx"
#endif
#ifndef _XMLOFF_TEXTHEADERFOOTERCONTEXT_HXX_
#include "XMLTextHeaderFooterContext.hxx"
#endif
#ifndef _XMLOFF_XMLIMP_HXX
#include "xmlimp.hxx"
#endif
#ifndef _XMLOFF_PAGEMASTERIMPORTCONTEXT_HXX
#include "PageMasterImportContext.hxx"
#endif

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::xml::sax;
using namespace ::com::sun::star::style;
using namespace ::com::sun::star::text;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
//using namespace ::com::sun::star::text;
using namespace ::xmloff::token;

Reference < XStyle > XMLTextMasterPageContext::Create()
{
    Reference < XStyle > xNewStyle;

    Reference< XMultiServiceFactory > xFactory( GetImport().GetModel(),
                                                    UNO_QUERY );
    if( xFactory.is() )
    {
        Reference < XInterface > xIfc =
            xFactory->createInstance(OUString(RTL_CONSTASCII_USTRINGPARAM(
                                    "com.sun.star.style.PageStyle")) );
        if( xIfc.is() )
            xNewStyle = Reference < XStyle >( xIfc, UNO_QUERY );
    }

    return xNewStyle;
}
TYPEINIT1( XMLTextMasterPageContext, SvXMLStyleContext );

XMLTextMasterPageContext::XMLTextMasterPageContext( SvXMLImport& rImport,
        sal_uInt16 nPrfx, const OUString& rLName,
        const Reference< XAttributeList > & xAttrList,
        sal_Bool bOverwrite ) :
    SvXMLStyleContext( rImport, nPrfx, rLName, xAttrList, XML_STYLE_FAMILY_MASTER_PAGE ),
    sIsPhysical( RTL_CONSTASCII_USTRINGPARAM( "IsPhysical" ) ),
    sFollowStyle( RTL_CONSTASCII_USTRINGPARAM( "FollowStyle" ) ),
    sPageStyleLayout( RTL_CONSTASCII_USTRINGPARAM( "PageStyleLayout" ) ),
    sPageMasterName(),
    bInsertHeader( sal_False ),
    bInsertFooter( sal_False ),
    bInsertHeaderLeft( sal_False ),
    bInsertFooterLeft( sal_False ),
    bHeaderInserted( sal_False ),
    bFooterInserted( sal_False ),
    bHeaderLeftInserted( sal_False ),
    bFooterLeftInserted( sal_False )
{
    OUString sName, sDisplayName;
    sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
    for( sal_Int16 i=0; i < nAttrCount; i++ )
    {
        const OUString& rAttrName = xAttrList->getNameByIndex( i );
        OUString aLocalName;
        sal_uInt16 nPrefix = GetImport().GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName );
        if( XML_NAMESPACE_STYLE == nPrefix )
        {
            if( IsXMLToken( aLocalName, XML_NAME ) )
            {
                sName = xAttrList->getValueByIndex( i );
            }
            else if( IsXMLToken( aLocalName, XML_DISPLAY_NAME ) )
            {
                sDisplayName = xAttrList->getValueByIndex( i );
            }
            else if( IsXMLToken( aLocalName, XML_NEXT_STYLE_NAME ) )
            {
                sFollow = xAttrList->getValueByIndex( i );
            }
            else if( IsXMLToken( aLocalName, XML_PAGE_LAYOUT_NAME ) )
            {
                sPageMasterName = xAttrList->getValueByIndex( i );
            }
        }
    }

    if( sDisplayName.getLength() )
    {
        rImport.AddStyleDisplayName( XML_STYLE_FAMILY_MASTER_PAGE, sName,
                                     sDisplayName );
    }
    else
    {
        sDisplayName = sName;
    }

    if( 0 == sDisplayName.getLength() )
        return;

    Reference < XNameContainer > xPageStyles =
            GetImport().GetTextImport()->GetPageStyles();
    if( !xPageStyles.is() )
        return;

    Any aAny;
    sal_Bool bNew = sal_False;
    if( xPageStyles->hasByName( sDisplayName ) )
    {
        aAny = xPageStyles->getByName( sDisplayName );
        aAny >>= xStyle;
    }
    else
    {
        xStyle = Create();
        if( !xStyle.is() )
            return;

        aAny <<= xStyle;
        xPageStyles->insertByName( sDisplayName, aAny );
        bNew = sal_True;
    }

    Reference < XPropertySet > xPropSet( xStyle, UNO_QUERY );
    Reference< XPropertySetInfo > xPropSetInfo =
                xPropSet->getPropertySetInfo();
    if( !bNew && xPropSetInfo->hasPropertyByName( sIsPhysical ) )
    {
        aAny = xPropSet->getPropertyValue( sIsPhysical );
        bNew = !*(sal_Bool *)aAny.getValue();
    }
    SetNew( bNew );

    if( bOverwrite || bNew )
    {
        Reference < XMultiPropertyStates > xMultiStates( xPropSet,
                                                         UNO_QUERY );
        OSL_ENSURE( xMultiStates.is(),
                    "text page style does not support multi property set" );
        if( xMultiStates.is() )
            xMultiStates->setAllPropertiesToDefault();

        bInsertHeader = bInsertFooter = sal_True;
        bInsertHeaderLeft = bInsertFooterLeft = sal_True;
    }
}

XMLTextMasterPageContext::~XMLTextMasterPageContext()
{
}

SvXMLImportContext *XMLTextMasterPageContext::CreateChildContext(
        sal_uInt16 nPrefix,
        const OUString& rLocalName,
        const Reference< XAttributeList > & xAttrList )
{
    SvXMLImportContext *pContext = 0;

    const SvXMLTokenMap& rTokenMap =
        GetImport().GetTextImport()->GetTextMasterPageElemTokenMap();

    sal_Bool bInsert = sal_False, bFooter = sal_False, bLeft = sal_False;
    switch( rTokenMap.Get( nPrefix, rLocalName ) )
    {
    case XML_TOK_TEXT_MP_HEADER:
        if( bInsertHeader && !bHeaderInserted )
        {
            bInsert = sal_True;
            bHeaderInserted = sal_True;
        }
        break;
    case XML_TOK_TEXT_MP_FOOTER:
        if( bInsertFooter && !bFooterInserted )
        {
            bInsert = bFooter = sal_True;
            bFooterInserted = sal_True;
        }
        break;
    case XML_TOK_TEXT_MP_HEADER_LEFT:
        if( bInsertHeaderLeft && bHeaderInserted && !bHeaderLeftInserted )
            bInsert = bLeft = sal_True;
        break;
    case XML_TOK_TEXT_MP_FOOTER_LEFT:
        if( bInsertFooterLeft && bFooterInserted && !bFooterLeftInserted )
            bInsert = bFooter = bLeft = sal_True;
        break;
    }

    if( bInsert && xStyle.is() )
    {
        pContext = CreateHeaderFooterContext( nPrefix, rLocalName,
                                                    xAttrList,
                                                    bFooter, bLeft );
    }
    else
    {
        pContext = SvXMLStyleContext::CreateChildContext( nPrefix, rLocalName,
                                                          xAttrList );
    }

    return pContext;
}

SvXMLImportContext *XMLTextMasterPageContext::CreateHeaderFooterContext(
            sal_uInt16 nPrefix,
            const ::rtl::OUString& rLocalName,
            const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList,
            const sal_Bool bFooter,
            const sal_Bool bLeft )
{
    Reference < XPropertySet > xPropSet( xStyle, UNO_QUERY );
    return new XMLTextHeaderFooterContext( GetImport(),
                                                nPrefix, rLocalName,
                                                xAttrList,
                                                xPropSet,
                                                bFooter, bLeft );
}

void XMLTextMasterPageContext::Finish( sal_Bool bOverwrite )
{
    if( xStyle.is() && (IsNew() || bOverwrite) )
    {
        Reference < XPropertySet > xPropSet( xStyle, UNO_QUERY );
        if( sPageMasterName.getLength() )
        {
            XMLPropStyleContext* pStyle =
                GetImport().GetTextImport()->FindPageMaster( sPageMasterName );
            if (pStyle)
            {
                pStyle->FillPropertySet(xPropSet);
            }
        }

        Reference < XNameContainer > xPageStyles =
            GetImport().GetTextImport()->GetPageStyles();
        if( !xPageStyles.is() )
            return;

        Reference< XPropertySetInfo > xPropSetInfo =
            xPropSet->getPropertySetInfo();
        if( xPropSetInfo->hasPropertyByName( sFollowStyle ) )
        {
            OUString sDisplayFollow(
                GetImport().GetStyleDisplayName(
                        XML_STYLE_FAMILY_MASTER_PAGE, sFollow ) );
            if( !sDisplayFollow.getLength() ||
                !xPageStyles->hasByName( sDisplayFollow ) )
                sDisplayFollow = xStyle->getName();

            Any aAny = xPropSet->getPropertyValue( sFollowStyle );
            OUString sCurrFollow;
            aAny >>= sCurrFollow;
            if( sCurrFollow != sDisplayFollow )
            {
                aAny <<= sDisplayFollow;
                xPropSet->setPropertyValue( sFollowStyle, aAny );
            }
        }
    }
}
<|endoftext|>


<commit_before>/*!
\file
	\brief
		Om hpp file.
	\version
		0.1
	\date
		2012
	\copyright
		Copyright (c) Jason Erb.
		All rights reserved.  This program and the accompanying materials are
		made available under the terms of the
		Eclipse
		Public License, Version 1.0, which accompanies this distribution.
	\authors
		Jason Erb - Initial API, implementation, and documentation.
*/
#if !defined( Om_Sources_CodePointStringFrontSource_ )
	#define Om_Sources_CodePointStringFrontSource_ \
	Om::Sources::CodePointStringFrontSource

	#include "om/sources/default_source.hpp"

namespace Om
{
	namespace Sources
	{
		// MARK: - Om::Sources::CodePointStringFrontSource
		/*!
		\brief
			A Source of #CodePoint strings from the front of a string.
		\note
			Const methods are not thread-safe due to a non-mutexed mutable
			member.
		\note
			Dereferencing exposes a reference to the member string cache of the
			current segment.  Modifying the string will not modify the source
			data.
		*/
		template< typename ThisStringIterator >
		struct CodePointStringFrontSource
		:
		DefaultSource<
			std::string,
			CodePointStringFrontSource< ThisStringIterator >
		>
		{
		public: // MARK: public (non-static)

			/*!
			\param theStringStart
				The string start.
			\param theStringEnd
				The string end.
			*/
			CodePointStringFrontSource(
				ThisStringIterator theStringStart,
				ThisStringIterator const theStringEnd
			);

			CodePointStringFrontSource & operator =( CodePointStringFrontSource );

			bool operator ==( CodePointStringFrontSource const & ) const;

			virtual bool operator !() const;

			virtual std::string & operator *() const;

			virtual void Pop();

			void Swap( CodePointStringFrontSource & );

		private: // MARK: private (non-static)

			/*!
			\brief
				Populates the #CodePoint string with each code unit of the next
				#CodePoint.
			*/
			void Update();

			ThisStringIterator thisStringIterator;

			ThisStringIterator thisStringEnd;

			//! The current #CodePoint string; empty if invalid.
			mutable std::string thisCodePoint;
		};
	}
}

// MARK: - boost
namespace boost
{
	template< typename ThisStringIterator >
	void swap(
		Om::Sources::CodePointStringFrontSource< ThisStringIterator > &,
		Om::Sources::CodePointStringFrontSource< ThisStringIterator > &
	);
}

	#include "om/sources/code_point_string_front_source.cpp"
#endif
<commit_msg>Elaborated a comment.<commit_after>/*!
\file
	\brief
		Om hpp file.
	\version
		0.1
	\date
		2012
	\copyright
		Copyright (c) Jason Erb.
		All rights reserved.  This program and the accompanying materials are
		made available under the terms of the
		Eclipse
		Public License, Version 1.0, which accompanies this distribution.
	\authors
		Jason Erb - Initial API, implementation, and documentation.
*/
#if !defined( Om_Sources_CodePointStringFrontSource_ )
	#define Om_Sources_CodePointStringFrontSource_ \
	Om::Sources::CodePointStringFrontSource

	#include "om/sources/default_source.hpp"

namespace Om
{
	namespace Sources
	{
		// MARK: - Om::Sources::CodePointStringFrontSource
		/*!
		\brief
			A Source of #CodePoint strings from the front of a string.
		\note
			Const methods are not thread-safe due to a non-mutexed mutable
			member.
		\note
			Dereferencing exposes a non-const reference to the member string
			cache of the current segment, allowing swap as an optimization.
			Modifying the string will not modify the source data.
		*/
		template< typename ThisStringIterator >
		struct CodePointStringFrontSource
		:
		DefaultSource<
			std::string,
			CodePointStringFrontSource< ThisStringIterator >
		>
		{
		public: // MARK: public (non-static)

			/*!
			\param theStringStart
				The string start.
			\param theStringEnd
				The string end.
			*/
			CodePointStringFrontSource(
				ThisStringIterator theStringStart,
				ThisStringIterator const theStringEnd
			);

			CodePointStringFrontSource & operator =( CodePointStringFrontSource );

			bool operator ==( CodePointStringFrontSource const & ) const;

			virtual bool operator !() const;

			virtual std::string & operator *() const;

			virtual void Pop();

			void Swap( CodePointStringFrontSource & );

		private: // MARK: private (non-static)

			/*!
			\brief
				Populates the #CodePoint string with each code unit of the next
				#CodePoint.
			*/
			void Update();

			ThisStringIterator thisStringIterator;

			ThisStringIterator thisStringEnd;

			//! The current #CodePoint string; empty if invalid.
			mutable std::string thisCodePoint;
		};
	}
}

// MARK: - boost
namespace boost
{
	template< typename ThisStringIterator >
	void swap(
		Om::Sources::CodePointStringFrontSource< ThisStringIterator > &,
		Om::Sources::CodePointStringFrontSource< ThisStringIterator > &
	);
}

	#include "om/sources/code_point_string_front_source.cpp"
#endif
<|endoftext|>


<commit_before>#ifndef __MATRIX_FUNCTIONS_HPP_INCLUDED
#define __MATRIX_FUNCTIONS_HPP_INCLUDED

#include "matrix.hpp"

// Include standard headers
#include <cmath>    // NAN, std::isnan, std::pow
#include <memory>   // std::make_shared, std::shared_ptr

namespace linear_algebra
{
    std::shared_ptr<linear_algebra::Matrix> cat(uint32_t dimension, linear_algebra::Matrix& old_matrix1, linear_algebra::Matrix& old_matrix2);
}

#endif
<commit_msg>Bugfix: added missing `#include` line.<commit_after>#ifndef __MATRIX_FUNCTIONS_HPP_INCLUDED
#define __MATRIX_FUNCTIONS_HPP_INCLUDED

#include "matrix.hpp"

// Include standard headers
#include <cmath>    // NAN, std::isnan, std::pow
#include <memory>   // std::make_shared, std::shared_ptr
#include <stdint.h> // uint32_t etc.

namespace linear_algebra
{
    std::shared_ptr<linear_algebra::Matrix> cat(uint32_t dimension, linear_algebra::Matrix& old_matrix1, linear_algebra::Matrix& old_matrix2);
}

#endif
<|endoftext|>


<commit_before>#include <stddef.h>
#include <kernel/ext2.h>
#include <kernel/ata.h>
#include <kernel/itoa.h>
#include <kernel/panic.h>

Ext2::Ext2(uint32_t lba) : lba(lba) {
	ata_pio_read(lba + 1024 / 512, 2, &this->superblock);
	if(this->superblock.base.signature != 0xef53) {
		kernel_panic("invalid ext2 superblock signature");
	}
}

uint32_t Ext2::GetBlockSize(void) {
	return 1024u << this->superblock.base.block_shift;
}

uint32_t Ext2::GetBlockAddr(uint32_t block_id) {
	return block_id * this->GetBlockSize();
}

uint32_t Ext2::GetInodeAddr(uint32_t inode_id) {
	uint32_t group_id = (inode_id - 1) / this->superblock.base.group_inode_count;
	GroupDesc gd = this->GetGroupDesc(group_id);

	uint32_t index = (inode_id - 1) % this->superblock.base.group_inode_count;
	return gd.inode_table_addr * this->GetBlockSize() + index * sizeof(Inode);
}

Ext2::GroupDesc Ext2::GetGroupDesc(uint32_t group_id) {
	uint32_t block_id = this->superblock.base.superblock_id + 1;
	uint32_t offset = this->GetBlockAddr(block_id) + group_id * sizeof(GroupDesc);

	char buffer[1024];
	ata_pio_read(this->lba + offset / 512, 2, &buffer);

	GroupDesc *gd = reinterpret_cast<GroupDesc *>(&buffer[offset % 512]);
	return *gd;
}

Maybe<Ext2::Inode> Ext2::GetInode(uint32_t inode_id) {
	uint32_t inode_addr = this->GetInodeAddr(inode_id);

	char buffer[1024];
	ata_pio_read(this->lba + inode_addr / 512, 2, &buffer);

	Inode *inode = reinterpret_cast<Inode *>(&buffer[inode_addr % 512]);
	return Maybe<Inode>(*inode);
}

Maybe<Ext2::Inode> Ext2::GetInode(Inode &pwd, const char *name) {
	auto mDirent = this->GetDirectoryEntry(pwd.block_ptr[0], name);
	if(mDirent.IsNothing()) {
		return Maybe<Inode>();
	} else {
		return this->GetInode(mDirent.FromJust().inode_id);
	}
}

Maybe<Ext2::DirectoryEntry> Ext2::GetDirectoryEntry(uint32_t block_id, const char *name) {
	uint32_t block_size = this->GetBlockSize();
	uint32_t block_addr = this->GetBlockAddr(block_id);

	char buffer[1024];
	ata_pio_read(this->lba + block_addr / 512, 2, &buffer);

	DirectoryEntry *dirent;
	for(size_t offset = 0; offset < block_size; offset += dirent->size) {
		dirent = reinterpret_cast<DirectoryEntry *>(&buffer[offset]);
		if(dirent->inode_id == 0) { break; }

		bool match = true;
		for(size_t n = 0; n < dirent->len; ++n) {
			if(buffer[offset + sizeof(DirectoryEntry) + n] != name[n]) {
				match = false;
				break;
			}
		}
		if(match) {
			return Maybe<DirectoryEntry>(*dirent);
		}
	}
	return Maybe<DirectoryEntry>();
}
<commit_msg>Add XXX comment<commit_after>#include <stddef.h>
#include <kernel/ext2.h>
#include <kernel/ata.h>
#include <kernel/itoa.h>
#include <kernel/panic.h>

Ext2::Ext2(uint32_t lba) : lba(lba) {
	ata_pio_read(lba + 1024 / 512, 2, &this->superblock);
	if(this->superblock.base.signature != 0xef53) {
		kernel_panic("invalid ext2 superblock signature");
	}
}

uint32_t Ext2::GetBlockSize(void) {
	return 1024u << this->superblock.base.block_shift;
}

uint32_t Ext2::GetBlockAddr(uint32_t block_id) {
	return block_id * this->GetBlockSize();
}

uint32_t Ext2::GetInodeAddr(uint32_t inode_id) {
	uint32_t group_id = (inode_id - 1) / this->superblock.base.group_inode_count;
	GroupDesc gd = this->GetGroupDesc(group_id);

	uint32_t index = (inode_id - 1) % this->superblock.base.group_inode_count;
	return gd.inode_table_addr * this->GetBlockSize() + index * sizeof(Inode);
}

Ext2::GroupDesc Ext2::GetGroupDesc(uint32_t group_id) {
	uint32_t block_id = this->superblock.base.superblock_id + 1;
	uint32_t offset = this->GetBlockAddr(block_id) + group_id * sizeof(GroupDesc);

	char buffer[1024];
	ata_pio_read(this->lba + offset / 512, 2, &buffer);

	GroupDesc *gd = reinterpret_cast<GroupDesc *>(&buffer[offset % 512]);
	return *gd;
}

Maybe<Ext2::Inode> Ext2::GetInode(uint32_t inode_id) {
	uint32_t inode_addr = this->GetInodeAddr(inode_id);

	char buffer[1024];
	ata_pio_read(this->lba + inode_addr / 512, 2, &buffer);

	Inode *inode = reinterpret_cast<Inode *>(&buffer[inode_addr % 512]);
	return Maybe<Inode>(*inode);
}

Maybe<Ext2::Inode> Ext2::GetInode(Inode &pwd, const char *name) {
	auto mDirent = this->GetDirectoryEntry(pwd.block_ptr[0], name);
	if(mDirent.IsNothing()) {
		return Maybe<Inode>();
	} else {
		return this->GetInode(mDirent.FromJust().inode_id);
	}
}

Maybe<Ext2::DirectoryEntry> Ext2::GetDirectoryEntry(uint32_t block_id, const char *name) {
	uint32_t block_size = this->GetBlockSize();
	uint32_t block_addr = this->GetBlockAddr(block_id);

	// XXX: this assumes a block is 1024 bytes, which is very bad if it's not
	char buffer[1024];
	ata_pio_read(this->lba + block_addr / 512, 2, &buffer);

	DirectoryEntry *dirent;
	for(size_t offset = 0; offset < block_size; offset += dirent->size) {
		dirent = reinterpret_cast<DirectoryEntry *>(&buffer[offset]);
		if(dirent->inode_id == 0) { break; }

		bool match = true;
		for(size_t n = 0; n < dirent->len; ++n) {
			if(buffer[offset + sizeof(DirectoryEntry) + n] != name[n]) {
				match = false;
				break;
			}
		}
		if(match) {
			return Maybe<DirectoryEntry>(*dirent);
		}
	}
	return Maybe<DirectoryEntry>();
}
<|endoftext|>


<commit_before>/* KPilot
**
** Copyright (C) 2004 by Adriaan de Groot, Joern Ahrens
**
** The code for NotepadActionThread::unpackNotePad was taken from
** Angus Ainslies read-notepad.c, which is part of pilot-link.
** NotepadActionThread::saveImage is also based on read-notepad.c.
**
** This file is part of the Notepad conduit, a conduit for KPilot that
** stores the notepad drawings to files.
*/

/*
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU Lesser General Public License as published by
** the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
*/

/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/

#include "options.h"
#include "pilotUser.h"
#include "pilotSerialDatabase.h"

#include "notepad-conduit.h"  // The Conduit action
#include "notepadconduit.h"   // The settings class

#include <pi-notepad.h>

#include <qthread.h>
#include <qapplication.h>
#include <qvaluelist.h>
#include <qimage.h>
#include <qdir.h>

extern "C"
{
long version_conduit_notepad = KPILOT_PLUGIN_API;
const char *id_conduit_notepad =
	"$Id$";
}

NotepadConduit::NotepadConduit(KPilotDeviceLink *d,	const char *n,
	const QStringList &args) :	ConduitAction(d, n, args)
{
	FUNCTIONSETUP;
#ifdef DEBUG
	DEBUGCONDUIT << id_conduit_notepad << endl;
#endif
	fConduitName=i18n("Notepad");
	thread = 0L;

	(void) id_conduit_notepad;
}

NotepadConduit::~NotepadConduit()
{
	FUNCTIONSETUP;
}

/* virtual */ bool NotepadConduit::exec()
{
	FUNCTIONSETUP;

#ifdef DEBUG
	DEBUGCONDUIT << fname << ": In exec() @" << (unsigned long) this << endl;
#endif

	QDir dir(NotepadConduitSettings::outputDirectory());
	if(!dir.exists() && !dir.mkdir(dir.path())) {
		emit logError(i18n("Unable to open %1").arg(dir.path()));
		delayDone();
		return false;
	}
	else {
		thread = new NotepadActionThread(this, pilotSocket());
		thread->start();
		// tickle is disabled due to crashs during sync
		// -> PADP TX "unexpected package"
//		startTickle();
	}

	return true;
}

bool NotepadConduit::event(QEvent *e)
{
	FUNCTIONSETUP;

	if(e->type() == QEvent::User) {
#ifdef DEBUG
		DEBUGCONDUIT << fname << ": Notepad thread done." << endl;
#endif
//		stopTickle();
		delayDone();
		if(thread->getFailed())
			logError(i18n("1 notepad could not be saved", "%n notepads could not be saved", thread->getFailed()));
		logMessage(i18n("1 notepad saved", "%n notepads saved", thread->getSaved()));
		delete thread;
		return true;
	}
	else
		return ConduitAction::event(e);
}

//-----------------------------------------------------------------------------
// NotepadActionThread
//-----------------------------------------------------------------------------

NotepadActionThread::NotepadActionThread(QObject *parent, int pilotSocket) :
	fParent(parent), fPilotSocket(pilotSocket), notSaved(0), saved(0)
{
	FUNCTIONSETUP;
}

/*virtual*/ void NotepadActionThread::run()
{
	FUNCTIONSETUP;

	PilotSerialDatabase *db = new PilotSerialDatabase(fPilotSocket, "npadDB");

	int n = db->recordCount();
	QValueList<recordid_t> vl = db->idList();
	QValueList<recordid_t>::iterator it;
	struct NotePad a;
	for ( it = vl.begin(); it != vl.end(); ++it ) {
		PilotRecord *pr = db->readRecordById(*it);
		if(pr) {
			unpack_NotePad(&a, (unsigned char*)pr->getData(), pr->getLen());
			saveImage(&a);
		}
	}
	QApplication::postEvent(fParent, new QEvent(QEvent::User));
}

int NotepadActionThread::unpackNotePad(struct NotePad *a, unsigned char *buffer, int len)
{
	FUNCTIONSETUP;

	unsigned char *start = buffer;

	a->createDate.sec = (unsigned short int) get_short(buffer);
	buffer += 2;
	a->createDate.min = (unsigned short int) get_short(buffer);
	buffer += 2;
	a->createDate.hour = (unsigned short int) get_short(buffer);
	buffer += 2;
	a->createDate.day = (unsigned short int) get_short(buffer);
	buffer += 2;
	a->createDate.month = (unsigned short int) get_short(buffer);
	buffer += 2;
	a->createDate.year = (unsigned short int) get_short(buffer);
	buffer += 2;

	a->createDate.s = (unsigned short int) get_short(buffer);
	buffer += 2;

	a->changeDate.sec = (unsigned short int) get_short(buffer);
	buffer += 2;
	a->changeDate.min = (unsigned short int) get_short(buffer);
	buffer += 2;
	a->changeDate.hour = (unsigned short int) get_short(buffer);
	buffer += 2;
	a->changeDate.day = (unsigned short int) get_short(buffer);
	buffer += 2;
	a->changeDate.month = (unsigned short int) get_short(buffer);
	buffer += 2;
	a->changeDate.year = (unsigned short int) get_short(buffer);
	buffer += 2;

	a->changeDate.s = (unsigned short int) get_short(buffer);
	buffer += 2;

	a->flags = (unsigned short int) get_short(buffer);
	buffer += 2;

	if( a->flags & NOTEPAD_FLAG_ALARM ) {
			a->alarmDate.sec = (unsigned short int) get_short(buffer);
			buffer += 2;
			a->alarmDate.min = (unsigned short int) get_short(buffer);
			buffer += 2;
			a->alarmDate.hour = (unsigned short int) get_short(buffer);
			buffer += 2;
			a->alarmDate.day = (unsigned short int) get_short(buffer);
			buffer += 2;
			a->alarmDate.month = (unsigned short int) get_short(buffer);
			buffer += 2;
			a->alarmDate.year = (unsigned short int) get_short(buffer);
			buffer += 2;

			a->alarmDate.s = (unsigned short int) get_short(buffer);
			buffer += 2;
		}

		if( a->flags & NOTEPAD_FLAG_NAME ) {
			a->name = strdup((char *) buffer);

			buffer += strlen( a->name ) + 1;

			if( (strlen( a->name ) + 1)%2 == 1)
				++buffer;

		}
		else {
			a->name = NULL;
		}

	if( a->flags & NOTEPAD_FLAG_BODY ) {
			a->body.bodyLen = get_long( buffer );
			buffer += 4;

			a->body.width = get_long( buffer );
			buffer += 4;

			a->body.height = get_long( buffer );
			buffer += 4;

			a->body.l1 = get_long( buffer );
			buffer += 4;

			a->body.dataType = get_long( buffer );
			buffer += 4;

			a->body.dataLen = get_long( buffer );
			buffer += 4;

			a->data = (dataRec_t*)malloc( a->body.dataLen );

			if( a->data == NULL )
				return( 0 );

			memcpy( a->data, buffer, a->body.dataLen );
		}

	return ( buffer - start );	/* FIXME: return real length */
}

void NotepadActionThread::saveImage(struct NotePad *n)
{
	FUNCTIONSETUP;

	int i,j,k,datapoints = 0;
	QImage image(n->body.width+8, n->body.height, 8, 2);

	image.setColor(0, qRgb(0xaa, 0xc1 ,0x91) );
	image.setColor(1, qRgb(0x30, 0x36, 0x29) );

	int x = 0;
	int y = 0;
	int pos = 0;
	for(i=0; i<n->body.dataLen/2; ++i)
	{
		datapoints += n->data[i].repeat;
		for(j=0; j<n->data[i].repeat; ++j)
		{
			for(k=0; k<8; ++k)
			{
				y = pos / 160;
				x = pos % 160;

				if(n->data[i].data & 1<<(7-k))
					image.setPixel(x,y,1);
				else
		    		image.setPixel(x,y,0);
				++pos;
			}
		}
	}
	QString imgname = QString("%1/%2.png").arg(NotepadConduitSettings::outputDirectory()).arg(n->name);
	DEBUGCONDUIT << fname << ": Notepad " << imgname << endl;
	if(!image.save(imgname, "PNG", -1))
		++notSaved;
	else
		++saved;
}

<commit_msg>Unbreak build some more<commit_after>/* KPilot
**
** Copyright (C) 2004 by Adriaan de Groot, Joern Ahrens
**
** The code for NotepadActionThread::unpackNotePad was taken from
** Angus Ainslies read-notepad.c, which is part of pilot-link.
** NotepadActionThread::saveImage is also based on read-notepad.c.
**
** This file is part of the Notepad conduit, a conduit for KPilot that
** stores the notepad drawings to files.
*/

/*
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU Lesser General Public License as published by
** the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
*/

/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/

#include "options.h"
#include "pilotUser.h"
#include "pilotSerialDatabase.h"

#include "notepad-conduit.h"  // The Conduit action
#include "notepadconduit.h"   // The settings class

#include <pi-notepad.h>

#include <qthread.h>
#include <qapplication.h>
#include <qvaluelist.h>
#include <qimage.h>
#include <qdir.h>

extern "C"
{
long version_conduit_notepad = KPILOT_PLUGIN_API;
const char *id_conduit_notepad =
	"$Id$";
}

NotepadConduit::NotepadConduit(KPilotDeviceLink *d,	const char *n,
	const QStringList &args) :	ConduitAction(d, n, args)
{
	FUNCTIONSETUP;
#ifdef DEBUG
	DEBUGCONDUIT << id_conduit_notepad << endl;
#endif
	fConduitName=i18n("Notepad");
	thread = 0L;

	(void) id_conduit_notepad;
}

NotepadConduit::~NotepadConduit()
{
	FUNCTIONSETUP;
}

/* virtual */ bool NotepadConduit::exec()
{
	FUNCTIONSETUP;

#ifdef DEBUG
	DEBUGCONDUIT << fname << ": In exec() @" << (unsigned long) this << endl;
#endif

	QDir dir(NotepadConduitSettings::outputDirectory());
	if(!dir.exists() && !dir.mkdir(dir.path())) {
		emit logError(i18n("Unable to open %1").arg(dir.path()));
		delayDone();
		return false;
	}
	else {
		thread = new NotepadActionThread(this, pilotSocket());
		thread->start();
		// tickle is disabled due to crashs during sync
		// -> PADP TX "unexpected package"
//		startTickle();
	}

	return true;
}

bool NotepadConduit::event(QEvent *e)
{
	FUNCTIONSETUP;

	if(e->type() == QEvent::User) {
#ifdef DEBUG
		DEBUGCONDUIT << fname << ": Notepad thread done." << endl;
#endif
//		stopTickle();
		delayDone();
		if(thread->getFailed())
			logError(i18n("1 notepad could not be saved", "%n notepads could not be saved", thread->getFailed()));
		logMessage(i18n("1 notepad saved", "%n notepads saved", thread->getSaved()));
		delete thread;
		return true;
	}
	else
		return ConduitAction::event(e);
}

//-----------------------------------------------------------------------------
// NotepadActionThread
//-----------------------------------------------------------------------------

NotepadActionThread::NotepadActionThread(QObject *parent, int pilotSocket) :
	fParent(parent), fPilotSocket(pilotSocket), notSaved(0), saved(0)
{
	FUNCTIONSETUP;
}

/*virtual*/ void NotepadActionThread::run()
{
	FUNCTIONSETUP;

	PilotSerialDatabase *db = new PilotSerialDatabase(fPilotSocket, "npadDB");

	int n = db->recordCount();
	QValueList<recordid_t> vl = db->idList();
	QValueList<recordid_t>::iterator it;
	struct NotePad a;
	for ( it = vl.begin(); it != vl.end(); ++it ) {
		PilotRecord *pr = db->readRecordById(*it);
		if(pr) {
			unpack_NotePad(&a, (unsigned char*)pr->getData(), pr->getLen());
			saveImage(&a);
		}
	}
	QApplication::postEvent(fParent, new QEvent(QEvent::User));
}

int NotepadActionThread::unpackNotePad(struct NotePad *a, unsigned char *buffer, int len)
{
	FUNCTIONSETUP;

	unsigned char *start = buffer;

	a->createDate.sec = (unsigned short int) get_short(buffer);
	buffer += 2;
	a->createDate.min = (unsigned short int) get_short(buffer);
	buffer += 2;
	a->createDate.hour = (unsigned short int) get_short(buffer);
	buffer += 2;
	a->createDate.day = (unsigned short int) get_short(buffer);
	buffer += 2;
	a->createDate.month = (unsigned short int) get_short(buffer);
	buffer += 2;
	a->createDate.year = (unsigned short int) get_short(buffer);
	buffer += 2;

	a->createDate.s = (unsigned short int) get_short(buffer);
	buffer += 2;

	a->changeDate.sec = (unsigned short int) get_short(buffer);
	buffer += 2;
	a->changeDate.min = (unsigned short int) get_short(buffer);
	buffer += 2;
	a->changeDate.hour = (unsigned short int) get_short(buffer);
	buffer += 2;
	a->changeDate.day = (unsigned short int) get_short(buffer);
	buffer += 2;
	a->changeDate.month = (unsigned short int) get_short(buffer);
	buffer += 2;
	a->changeDate.year = (unsigned short int) get_short(buffer);
	buffer += 2;

	a->changeDate.s = (unsigned short int) get_short(buffer);
	buffer += 2;

	a->flags = (unsigned short int) get_short(buffer);
	buffer += 2;

	if( a->flags & NOTEPAD_FLAG_ALARM ) {
			a->alarmDate.sec = (unsigned short int) get_short(buffer);
			buffer += 2;
			a->alarmDate.min = (unsigned short int) get_short(buffer);
			buffer += 2;
			a->alarmDate.hour = (unsigned short int) get_short(buffer);
			buffer += 2;
			a->alarmDate.day = (unsigned short int) get_short(buffer);
			buffer += 2;
			a->alarmDate.month = (unsigned short int) get_short(buffer);
			buffer += 2;
			a->alarmDate.year = (unsigned short int) get_short(buffer);
			buffer += 2;

			a->alarmDate.s = (unsigned short int) get_short(buffer);
			buffer += 2;
		}

		if( a->flags & NOTEPAD_FLAG_NAME ) {
			a->name = strdup((char *) buffer);

			buffer += strlen( a->name ) + 1;

			if( (strlen( a->name ) + 1)%2 == 1)
				++buffer;

		}
		else {
			a->name = NULL;
		}

	if( a->flags & NOTEPAD_FLAG_BODY ) {
			a->body.bodyLen = get_long( buffer );
			buffer += 4;

			a->body.width = get_long( buffer );
			buffer += 4;

			a->body.height = get_long( buffer );
			buffer += 4;

			a->body.l1 = get_long( buffer );
			buffer += 4;

			a->body.dataType = get_long( buffer );
			buffer += 4;

			a->body.dataLen = get_long( buffer );
			buffer += 4;

			a->data = (dataRec_t*)malloc( a->body.dataLen );

			if( a->data == NULL )
				return( 0 );

			memcpy( a->data, buffer, a->body.dataLen );
		}

	return ( buffer - start );	/* FIXME: return real length */
}

void NotepadActionThread::saveImage(struct NotePad *n)
{
	FUNCTIONSETUP;

	int i,j,k,datapoints = 0;
	QImage image(n->body.width+8, n->body.height, 8, 2);

	image.setColor(0, qRgb(0xaa, 0xc1 ,0x91) );
	image.setColor(1, qRgb(0x30, 0x36, 0x29) );

	int x = 0;
	int y = 0;
	int pos = 0;
	for(i=0; i<n->body.dataLen/2; ++i)
	{
		datapoints += n->data[i].repeat;
		for(j=0; j<n->data[i].repeat; ++j)
		{
			for(k=0; k<8; ++k)
			{
				y = pos / 160;
				x = pos % 160;

				if(n->data[i].data & 1<<(7-k))
					image.setPixel(x,y,1);
				else
		    		image.setPixel(x,y,0);
				++pos;
			}
		}
	}
	QString imgname = QString("%1/%2.png").arg(NotepadConduitSettings::outputDirectory()).arg(n->name);
#ifdef DEBUG
	DEBUGCONDUIT << fname << ": Notepad " << imgname << endl;
#endif
	if(!image.save(imgname, "PNG", -1))
		++notSaved;
	else
		++saved;
}

<|endoftext|>


<commit_before>#include "Sprite.h"
#include <string>
#include <iostream>

void Sprite::init(float x, float y, float width, float height)
{
    // TODO: check boundaries, check validity of params
    _x = x;
    _y = y;
    _width = width;
    _height = height;

    // a VBO has not been generated yet for this sprite
    if(_vboID == 0 ) {
        // allocate a VBO memory and assign it to the ID
        glGenBuffers(1, &_vboID);
    }

    // a square consists of 2 triangles
    //    float vertexData[6 * 2];

    //    //First Triangle
    //    vertexData[0] = x + width;
    //    vertexData[1] = y + height;

    //    vertexData[2] = x;
    //    vertexData[3] = y + height;

    //    vertexData[4] = x;
    //    vertexData[5] = y;

    //    //Second Triangle
    //    vertexData[6] = x;
    //    vertexData[7] = y;

    //    vertexData[8] = x + width;
    //    vertexData[9] = y;

    //    vertexData[10] = x + width;
    //    vertexData[11] = y + height;

    float vertices[3 * 2] = {
        0.0f,  0.5f, // Vertex 1 (X, Y)
        0.5f, -0.5f, // Vertex 2 (X, Y)
        -0.5f, -0.5f  // Vertex 3 (X, Y)
    };

    // Makes our VBO the active GL_ARRAY_BUFFER
    glBindBuffer(GL_ARRAY_BUFFER, _vboID);

    // Uploads the bound GL_ARRAY_BUFFER to the graphics card
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices,
                 GL_STATIC_DRAW /*
             * GL_STATIC_DRAW - the data will most likely not change at all or very rarely
             * GL_DYNAMIC_DRAW -the data is likely to change a lot
             * GL_STREAM_DRAW - the data will change every time it is drawn */);

    std::string vertexShaderSource = R"(#version 130
            in vec2 position;

            void main()
            {
                gl_Position = vec4(position, 0.0, 1.0);
            })";
    const char* vSSC = vertexShaderSource.c_str();

    std::string fragmentShaderSource = R"(#version 130

                                 out vec4 outColor;

                                 void main()
                                 {
                                     outColor = vec4(1.0, 1.0, 1.0, 1.0);
                                 })";

    const char* fSSC = fragmentShaderSource.c_str();

    GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertexShader, 1, &vSSC, NULL);

    GLint status;
    glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &status);

    if(status == GL_TRUE) {
        std::cout << "VERTEX SHADER COMPILED SUCCESSFULLY!" << std::endl;
    } else {
        std::cout << "VERTEX SHADER DIDNT COMPILE!" << std::endl;
        char buffer[512];
        glGetShaderInfoLog(vertexShader, 512, NULL, buffer);

        glDeleteShader(vertexShader); // Don't leak the shader

        std::cout << "Vertex shader compilation log: " << buffer << std::endl;
    }

    GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragmentShader, 1, &fSSC, NULL);
    glCompileShader(fragmentShader);

    glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &status);

    if(status == GL_TRUE) {
        std::cout << "FRAGMENT SHADER COMPILED SUCCESSFULLY!" << std::endl;
    } else {
        std::cout << "FRAGMENT SHADER DIDNT COMPILE!" << std::endl;
        char buffer[512];
        glGetShaderInfoLog(fragmentShader, 512, NULL, buffer);

        glDeleteShader(fragmentShader);

        std::cout << "Fragment shader compilation log: " << buffer << std::endl;
    }
}

Sprite::Sprite()
{
    _vboID = 0;
}

Sprite::~Sprite()
{
    if(_vboID != 0) {
        glDeleteBuffers(1, &_vboID);
    }
}

void Sprite::draw()
{
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    // draw only the first and only array in the buffer
    // without data about light and other
    glEnableVertexAttribArray(0);

    // TODO: RESEARCH: What does this do?!
    glVertexAttribPointer(0, 2 /* 2 coordinates - x and y*/, GL_FLOAT, GL_FALSE, 0, 0);

    glDrawArrays(GL_TRIANGLES, 0, 3);//6 /* 6 for 6 vertices in a square */);

    glDisableVertexAttribArray(0);

    glBindBuffer(GL_ARRAY_BUFFER, 0);
}
<commit_msg>fix vertex shader compilation<commit_after>#include "Sprite.h"
#include <string>
#include <iostream>

void Sprite::init(float x, float y, float width, float height)
{
    // TODO: check boundaries, check validity of params
    _x = x;
    _y = y;
    _width = width;
    _height = height;

    // a VBO has not been generated yet for this sprite
    if(_vboID == 0 ) {
        // allocate a VBO memory and assign it to the ID
        glGenBuffers(1, &_vboID);
    }

    // a square consists of 2 triangles
    //    float vertexData[6 * 2];

    //    //First Triangle
    //    vertexData[0] = x + width;
    //    vertexData[1] = y + height;

    //    vertexData[2] = x;
    //    vertexData[3] = y + height;

    //    vertexData[4] = x;
    //    vertexData[5] = y;

    //    //Second Triangle
    //    vertexData[6] = x;
    //    vertexData[7] = y;

    //    vertexData[8] = x + width;
    //    vertexData[9] = y;

    //    vertexData[10] = x + width;
    //    vertexData[11] = y + height;

    float vertices[3 * 2] = {
        0.0f,  0.5f, // Vertex 1 (X, Y)
        0.5f, -0.5f, // Vertex 2 (X, Y)
        -0.5f, -0.5f  // Vertex 3 (X, Y)
    };

    // Makes our VBO the active GL_ARRAY_BUFFER
    glBindBuffer(GL_ARRAY_BUFFER, _vboID);

    // Uploads the bound GL_ARRAY_BUFFER to the graphics card
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices,
                 GL_STATIC_DRAW /*
             * GL_STATIC_DRAW - the data will most likely not change at all or very rarely
             * GL_DYNAMIC_DRAW -the data is likely to change a lot
             * GL_STREAM_DRAW - the data will change every time it is drawn */);

    std::string vertexShaderSource = R"(#version 130
            in vec2 position;

            void main()
            {
                gl_Position = vec4(position, 0.0, 1.0);
            })";
    const char* vSSC = vertexShaderSource.c_str();

    std::string fragmentShaderSource = R"(#version 130

                                 out vec4 outColor;

                                 void main()
                                 {
                                     outColor = vec4(1.0, 1.0, 1.0, 1.0);
                                 })";

    const char* fSSC = fragmentShaderSource.c_str();

    GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertexShader, 1, &vSSC, NULL);
    glCompileShader(vertexShader);

    GLint status;
    glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &status);

    if(status == GL_TRUE) {
        std::cout << "VERTEX SHADER COMPILED SUCCESSFULLY!" << std::endl;
    } else {
        std::cout << "VERTEX SHADER DIDNT COMPILE!" << std::endl;
        char buffer[512];
        glGetShaderInfoLog(vertexShader, 512, NULL, buffer);

        glDeleteShader(vertexShader); // Don't leak the shader

        std::cout << "Vertex shader compilation log: " << buffer << std::endl;
    }

    GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragmentShader, 1, &fSSC, NULL);
    glCompileShader(fragmentShader);

    glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &status);

    if(status == GL_TRUE) {
        std::cout << "FRAGMENT SHADER COMPILED SUCCESSFULLY!" << std::endl;
    } else {
        std::cout << "FRAGMENT SHADER DIDNT COMPILE!" << std::endl;
        char buffer[512];
        glGetShaderInfoLog(fragmentShader, 512, NULL, buffer);

        glDeleteShader(fragmentShader);

        std::cout << "Fragment shader compilation log: " << buffer << std::endl;
    }
}

Sprite::Sprite()
{
    _vboID = 0;
}

Sprite::~Sprite()
{
    if(_vboID != 0) {
        glDeleteBuffers(1, &_vboID);
    }
}

void Sprite::draw()
{
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    // draw only the first and only array in the buffer
    // without data about light and other
    glEnableVertexAttribArray(0);

    // TODO: RESEARCH: What does this do?!
    glVertexAttribPointer(0, 2 /* 2 coordinates - x and y*/, GL_FLOAT, GL_FALSE, 0, 0);

    glDrawArrays(GL_TRIANGLES, 0, 3);//6 /* 6 for 6 vertices in a square */);

    glDisableVertexAttribArray(0);

    glBindBuffer(GL_ARRAY_BUFFER, 0);
}
<|endoftext|>


<commit_before>#include <cstddef>
#include <cstddef>
#include <fstream>
#include <iomanip>

#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <ShlObj.h>

#define WIDEIFYIMP(x) L##x
#define WIDEIFY(x) WIDEIFYIMP(x)

#include <queue>

#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;

#include <UWP/UWP.hpp>

#include <UWP/DumperIPC.hpp>

std::uint32_t __stdcall DumperThread(void* DLLHandle)
{
	std::wstring DumpPath = fs::path(UWP::Current::Storage::GetTemporaryPath()) / L"DUMP";

	IPC::SetTargetThread(GetCurrentThreadId());

	IPC::PushMessage(L"UWPDumper Build date(%ls : %ls)\n", WIDEIFY(__DATE__), WIDEIFY(__TIME__));
	IPC::PushMessage(L"\t-https://github.com/Wunkolo/UWPDumper\n");
	IPC::PushMessage(L"Publisher:\n\t%s\n", UWP::Current::GetPublisher().c_str());
	IPC::PushMessage(L"Publisher ID:\n\t%s\n", UWP::Current::GetPublisherID().c_str());
	IPC::PushMessage(L"Publisher Path:\n\t%s\n", UWP::Current::Storage::GetPublisherPath().c_str());
	IPC::PushMessage(L"Package Path:\n\t%s\n", UWP::Current::GetPackagePath().c_str());
	IPC::PushMessage(L"Package Name:\n\t%s\n", UWP::Current::GetFullName().c_str());
	IPC::PushMessage(L"Family Name:\n\t%s\n", UWP::Current::GetFamilyName().c_str());

	IPC::PushMessage(L"Dump Path:\n\t%s\n", DumpPath.c_str());

	std::vector<fs::directory_entry> FileList;

	for( auto& Entry : fs::recursive_directory_iterator(".") )
	{
		if( fs::is_regular_file(Entry.path()) )
		{
			FileList.push_back(Entry);
		}
	}

	IPC::PushMessage(L"\tDumping %zu files\n", FileList.size());

	std::size_t i = 0;
	for( const auto& File : FileList )
	{
		const fs::path WritePath = DumpPath + File.path().wstring().substr(1);
		const std::wstring ReadPath = File.path().wstring().substr(1);
		IPC::PushMessage(
			L"%*.*s %*.u bytes %*zu/%zu\n",
			60, 60,
			ReadPath.c_str() + (ReadPath.length() > 60 ? (ReadPath.length() - (60)) : 0),
			15,
			fs::file_size(File),
			20,
			++i,
			FileList.size()
		);

		std::error_code ErrorCode;
		if( fs::create_directories(WritePath.parent_path(), ErrorCode) )
		{
			IPC::PushMessage(
				L"Error creating subfolder: %s (%s)\n",
				WritePath.parent_path().c_str(),
				ErrorCode.message().c_str()
			);
			continue;
		}

		std::ifstream SourceFile(ReadPath, std::ios::binary);
		std::ofstream DestFile(WritePath, std::ios::binary);

		if( SourceFile && DestFile )
		{
			DestFile << SourceFile.rdbuf();
		}
		else
		{
			IPC::PushMessage(
				L"Error copying:\n"
				"\t%s\n"
				"\tto\n"
				"\t%s\n",
				File.path().c_str(),
				WritePath.c_str()
			);
		}
	}

	IPC::PushMessage(L"Dump complete!\n\tPath:\n\t%s\n", DumpPath.c_str());
	IPC::ClearTargetThread();

	FreeLibraryAndExitThread(reinterpret_cast<HMODULE>(DLLHandle), 0);

	return EXIT_SUCCESS;
}

std::int32_t __stdcall DllMain(HINSTANCE hDLL, std::uint32_t Reason, void* Reserved)
{
	switch( Reason )
	{
	case DLL_PROCESS_ATTACH:
	{
		if( IPC::GetTargetProcess() == GetCurrentProcessId() )
		{
			// We are the target process to be dumped
			CreateThread(
				nullptr,
				0,
				reinterpret_cast<unsigned long(__stdcall*)(void*)>(&DumperThread),
				hDLL,
				0,
				nullptr
			);
		}
	}
	case DLL_PROCESS_DETACH:
	case DLL_THREAD_ATTACH:
	case DLL_THREAD_DETACH:
	default:
	{
		return true;
	}
	}

	return false;
}
<commit_msg>Fix local dump path resolution<commit_after>#include <cstddef>
#include <cstddef>
#include <fstream>
#include <iomanip>

#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <ShlObj.h>

#define WIDEIFYIMP(x) L##x
#define WIDEIFY(x) WIDEIFYIMP(x)

#include <queue>

#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;

#include <UWP/UWP.hpp>

#include <UWP/DumperIPC.hpp>

std::uint32_t __stdcall DumperThread(void* DLLHandle)
{
	std::wstring DumpPath = fs::path(UWP::Current::Storage::GetTemporaryPath()) / L"DUMP";

	IPC::SetTargetThread(GetCurrentThreadId());

	IPC::PushMessage(L"UWPDumper Build date(%ls : %ls)\n", WIDEIFY(__DATE__), WIDEIFY(__TIME__));
	IPC::PushMessage(L"\t-https://github.com/Wunkolo/UWPDumper\n");
	IPC::PushMessage(L"Publisher:\n\t%s\n", UWP::Current::GetPublisher().c_str());
	IPC::PushMessage(L"Publisher ID:\n\t%s\n", UWP::Current::GetPublisherID().c_str());
	IPC::PushMessage(L"Publisher Path:\n\t%s\n", UWP::Current::Storage::GetPublisherPath().c_str());
	IPC::PushMessage(L"Package Path:\n\t%s\n", UWP::Current::GetPackagePath().c_str());
	IPC::PushMessage(L"Package Name:\n\t%s\n", UWP::Current::GetFullName().c_str());
	IPC::PushMessage(L"Family Name:\n\t%s\n", UWP::Current::GetFamilyName().c_str());

	IPC::PushMessage(L"Dump Path:\n\t%s\n", DumpPath.c_str());

	std::vector<fs::directory_entry> FileList;

	for( auto& Entry : fs::recursive_directory_iterator(".") )
	{
		if( fs::is_regular_file(Entry.path()) )
		{
			FileList.push_back(Entry);
		}
	}

	IPC::PushMessage(L"\tDumping %zu files\n", FileList.size());

	std::size_t i = 0;
	for( const auto& File : FileList )
	{
		const fs::path WritePath = DumpPath + File.path().wstring().substr(1);
		const std::wstring ReadPath = File.path().wstring();
		IPC::PushMessage(
			L"%*.*s %*.u bytes %*zu/%zu\n",
			60, 60,
			ReadPath.c_str() + (ReadPath.length() > 60 ? (ReadPath.length() - (60)) : 0),
			15,
			fs::file_size(File),
			20,
			++i,
			FileList.size()
		);

		std::error_code ErrorCode;
		if( fs::create_directories(WritePath.parent_path(), ErrorCode) )
		{
			IPC::PushMessage(
				L"Error creating subfolder: %s (%s)\n",
				WritePath.parent_path().c_str(),
				ErrorCode.message().c_str()
			);
			continue;
		}

		std::ifstream SourceFile(ReadPath, std::ios::binary);
		if( !SourceFile.is_open() )
		{
			IPC::PushMessage(
				L"Error opening %s for reading\n",
				ReadPath.c_str()
			);
			continue;
		}

		std::ofstream DestFile(WritePath, std::ios::binary);
		if( !DestFile.is_open() )
		{
			IPC::PushMessage(
				L"Error opening %s for writing\n",
				WritePath.c_str()
			);
			continue;
		}

		if( SourceFile && DestFile )
		{
			DestFile << SourceFile.rdbuf();
		}
		else
		{
			IPC::PushMessage(
				L"Error copying:\n"
				"\t%s\n"
				"\tto\n"
				"\t%s\n",
				File.path().c_str(),
				WritePath.c_str()
			);
		}
	}

	IPC::PushMessage(L"Dump complete!\n\tPath:\n\t%s\n", DumpPath.c_str());
	IPC::ClearTargetThread();

	FreeLibraryAndExitThread(reinterpret_cast<HMODULE>(DLLHandle), 0);

	return EXIT_SUCCESS;
}

std::int32_t __stdcall DllMain(HINSTANCE hDLL, std::uint32_t Reason, void* Reserved)
{
	switch( Reason )
	{
	case DLL_PROCESS_ATTACH:
	{
		if( IPC::GetTargetProcess() == GetCurrentProcessId() )
		{
			// We are the target process to be dumped
			CreateThread(
				nullptr,
				0,
				reinterpret_cast<unsigned long(__stdcall*)(void*)>(&DumperThread),
				hDLL,
				0,
				nullptr
			);
		}
	}
	case DLL_PROCESS_DETACH:
	case DLL_THREAD_ATTACH:
	case DLL_THREAD_DETACH:
	default:
	{
		return true;
	}
	}

	return false;
}
<|endoftext|>


<commit_before>#include "rhoruntime.h"
#include "common/RhoStd.h"
#include "common/StringConverter.h"
#include "common/RhodesApp.h"
#include "ruby/ext/rho/rhoruby.h"
#include "common/RhoConvertWP8.h"

using namespace rhoruntime;
using namespace Platform;

extern "C" void rho_webview_navigate_back()
{
	CRhoRuntime::getInstance()->getMainPage()->GoBack();
}

extern "C" int rho_webview_active_tab()
{
	return CRhoRuntime::getInstance()->getMainPage()->tabbarGetCurrent();
}

extern "C" void rho_webview_navigate_forward()
{
    CRhoRuntime::getInstance()->getMainPage()->GoForward();
}

extern "C" const char* rho_webview_execute_js(const char* js, int index)
{
	rho::String urlA = rho::common::convertStringAFromWP8(CRhoRuntime::getInstance()->getMainPage()->executeScript(rho::common::convertStringCToWP8(js), index));
    return strdup(urlA.c_str());
}

extern "C" const char* rho_webview_execute_js_sync(const char* js, int index)
{
    // TODO: implement sync js callback
    rho_webview_execute_js(js, index);
    return "";
}

extern "C" const char* rho_webview_current_location(int index)
{
	rho::String urlA = rho::common::convertStringAFromWP8(CRhoRuntime::getInstance()->getMainPage()->getCurrentURL(index));
	return strdup(urlA.c_str());
}

extern "C" unsigned long rho_webview_get_current_url(int index)
{
	return rho_ruby_create_string(rho_webview_current_location(index));
}

extern "C" void rho_webview_full_screen_mode(int enable)
{
	CRhoRuntime::getInstance()->getMainPage()->fullscreenCommand(enable);
}

extern "C" void rho_webview_set_cookie(const char *url, const char *cookie)
{
	rho::String fullUrl = RHODESAPPBASE().canonicalizeRhoUrl(url);
	CRhoRuntime::getInstance()->getMainPage()->setCookie(rho::common::convertStringToWP8(fullUrl), rho::common::convertStringToWP8(cookie));
}

extern "C" void waitForBrowserInitialized()
{
	while(true)
	{

		if(CRhoRuntime::getInstance()->getMainPage()->isBrowserInitialized())
			return;
		else
			Sleep(100);
	}
}

extern "C" void rho_webview_navigate(const char* url, int index)
{
	waitForBrowserInitialized();
	rho::String fullUrl = RHODESAPPBASE().canonicalizeRhoUrl(url);
	LOG(INFO) + fullUrl.c_str();
	CRhoRuntime::getInstance()->getMainPage()->navigate(rho::common::convertStringToWP8(fullUrl), index);
}

extern "C" void rho_webview_refresh(int index)
{
	CRhoRuntime::getInstance()->getMainPage()->Refresh(index);
}

extern "C" HINSTANCE rho_wmimpl_get_appinstance()
{
    return 0;//_AtlModule.GetModuleInstance();
}

extern "C" void rho_webview_set_menu_items(VALUE valMenu)
{
    rho_rhodesapp_setViewMenu(valMenu);
	CRhoRuntime^ runtime = CRhoRuntime::getInstance();
	if (runtime != nullptr)
		runtime->createCustomMenu();
}

extern "C" void rho_webview_save(const char* format, const char* path, int tab_index)
{
}
<commit_msg>wp8: build fixed (depricated function removed)<commit_after>#include "rhoruntime.h"
#include "common/RhoStd.h"
#include "common/StringConverter.h"
#include "common/RhodesApp.h"
#include "ruby/ext/rho/rhoruby.h"
#include "common/RhoConvertWP8.h"

using namespace rhoruntime;
using namespace Platform;

extern "C" void rho_webview_navigate_back()
{
	CRhoRuntime::getInstance()->getMainPage()->GoBack();
}

extern "C" int rho_webview_active_tab()
{
	return CRhoRuntime::getInstance()->getMainPage()->tabbarGetCurrent();
}

extern "C" void rho_webview_navigate_forward()
{
    CRhoRuntime::getInstance()->getMainPage()->GoForward();
}

extern "C" const char* rho_webview_execute_js(const char* js, int index)
{
	rho::String urlA = rho::common::convertStringAFromWP8(CRhoRuntime::getInstance()->getMainPage()->executeScript(rho::common::convertStringCToWP8(js), index));
    return strdup(urlA.c_str());
}

extern "C" const char* rho_webview_execute_js_sync(const char* js, int index)
{
    // TODO: implement sync js callback
    rho_webview_execute_js(js, index);
    return "";
}

extern "C" const char* rho_webview_current_location(int index)
{
	rho::String urlA = rho::common::convertStringAFromWP8(CRhoRuntime::getInstance()->getMainPage()->getCurrentURL(index));
	return strdup(urlA.c_str());
}

extern "C" unsigned long rho_webview_get_current_url(int index)
{
	return rho_ruby_create_string(rho_webview_current_location(index));
}

extern "C" void rho_webview_full_screen_mode(int enable)
{
	CRhoRuntime::getInstance()->getMainPage()->fullscreenCommand(enable);
}

extern "C" void rho_webview_set_cookie(const char *url, const char *cookie)
{
	rho::String fullUrl = RHODESAPPBASE().canonicalizeRhoUrl(url);
	CRhoRuntime::getInstance()->getMainPage()->setCookie(rho::common::convertStringToWP8(fullUrl), rho::common::convertStringToWP8(cookie));
}

extern "C" void waitForBrowserInitialized()
{
	while(true)
	{

		if(CRhoRuntime::getInstance()->getMainPage()->isBrowserInitialized())
			return;
		else
			Sleep(100);
	}
}

extern "C" void rho_webview_navigate(const char* url, int index)
{
	waitForBrowserInitialized();
	rho::String fullUrl = RHODESAPPBASE().canonicalizeRhoUrl(url);
	LOG(INFO) + fullUrl.c_str();
	CRhoRuntime::getInstance()->getMainPage()->navigate(rho::common::convertStringToWP8(fullUrl), index);
}

extern "C" void rho_webview_refresh(int index)
{
	CRhoRuntime::getInstance()->getMainPage()->Refresh(index);
}

extern "C" HINSTANCE rho_wmimpl_get_appinstance()
{
    return 0;//_AtlModule.GetModuleInstance();
}

extern "C" void rho_webview_save(const char* format, const char* path, int tab_index)
{
}
<|endoftext|>


<commit_before>#include <iostream>
#include <math.h>

using namespace std;

const int N_data = 64;
const int N_obj = 100;
const float A = 1.34;
const float B = 0.87;
const int MAX = 10000;

#define UNIFORM (rand() + 0.5)/(RAND_MAX + 1.0)
#define PLUS(x,y) (x>y ? x+log(1+exp(y-x)) : y+log(1+exp(x-y)))

class my_data{
public:
  double x[N_data], value[N_data], error[N_data];
  my_data();
};

class my_obj{
public:
  double u, v;
  double a, b;
  double lnL, lnWt;
  void setPrior();
  void getlnLhood(double, double, my_data);
  my_obj Explore(double, my_data);
};

void Results(my_obj*, int, double);

my_data::my_data(){
  int i;

  for(i = 0; i < N_data; i++){
    x[i] = UNIFORM;
    value[i] = (A * x[i] + B);
    value[i] += (UNIFORM - 0.5) * 0.1 * value[i];
    error[i] = 0.1 * value[i];
  }
}

void my_obj::getlnLhood(double a, double b, my_data D){
  int i;
  double value, residue, L;

  for(i = 0, L = 0.0; i < N_data; i++){
    value = a * D.x[i] + b;
    residue = (value - D.value[i]) / D.error[i];
    L += - 0.5 * residue * residue - log(D.error[i] * sqrt(2.0 * M_PI));
  }

  lnL = L;
}

void my_obj::setPrior(){
  u = UNIFORM;
  v = UNIFORM;
  a = u * (2.0 - 1.0) + 1.0;
  b = v;
}

my_obj my_obj::Explore(double lnLstar, my_data D){
  double  step = 0.1;
  int     m    = 20;
  int     accept = 0;
  int     reject = 0;
  my_obj  Try, Get;

  for( ; m > 0; m-- ){
	  // Trial object
	  Try.u = u + step * (2.*UNIFORM - 1.);  // |move| < step
	  Try.v = v + step * (2.*UNIFORM - 1.);  // |move| < step
	  Try.u -= floor(Try.u);      // wraparound to stay within (0,1)
      Try.v -= floor(Try.v);      // wraparound to stay within (0,1)
      Try.a = Try.u * (2.0 - 1.0) + 1.0;  // map to x
      Try.b = Try.v;        // map to y
      Try.getlnLhood(Try.a, Try.b, D);  // trial likelihood value
      // Accept if and only if within hard likelihood constraint
      if(Try.lnL > lnLstar){
    	  Get = Try;
    	  accept++;
      }
      else
	reject++;
      // Refine step-size to let acceptance ratio converge around 50%
      if(accept > reject)    step *= exp(1.0 / accept);
      if(accept < reject)    step /= exp(1.0 / reject);
    }

 return Get;
}

void Results(my_obj* sample, int nest, double lnZ){
  double a = 0.0, aa = 0.0;   // 1st and 2nd moments of x
  double b = 0.0, bb = 0.0;   // 1st and 2nd moments of y
  double w;                   // Proportional weight
  int    i;                   // Sample counter

  for(i = 0; i < nest; i++){
    w = exp(sample[i].lnWt - lnZ);
    a  += w * sample[i].a;
    aa += w * sample[i].a * sample[i].a;
    b  += w * sample[i].b;
    bb += w * sample[i].b * sample[i].b;
  }

  cout<<"real A = "<< A <<" mean(A) = "<< a <<" stddev(A) = "<< sqrt(aa - a*a) <<"\n";
  cout<<"real B = "<< B <<" mean(B) = "<< b <<" stddev(B) = "<< sqrt(bb - b*b) <<"\n";
}

int mcmc(){
  double lnwidth;      // ln(width in prior mass)
  double lnLstar;      // ln(Likelihood constraint)
  double H    = 0.0;    // Information, initially 0
  double lnZ = 0.0;// ln(Evidence Z, initially 0)
  double lnZnew;       // Updated logZ
  int    i;             // Object counter
  int    copy;          // Duplicated object
  int    worst;         // Worst object
  int    nest;          // Nested sampling iteration count
  my_obj Obj[N_obj];
  my_obj Sample[MAX];
  my_data D;

  for(i = 0; i < N_obj; i++){
    Obj[i].setPrior();
    Obj[i].getlnLhood(Obj[i].a,Obj[i].b,D);
   }

  lnwidth = log(1.0 - exp(-1.0 / N_obj));

  for(nest = 0; nest < MAX; nest++){

    for(i = 1, worst = 0; i < N_obj; i++)
      if(Obj[i].lnL < Obj[worst].lnL)
	worst = i;

    Obj[worst].lnWt = lnwidth + Obj[worst].lnL;

    lnZnew = PLUS(lnZ, Obj[worst].lnWt);

    H = exp(Obj[worst].lnWt - lnZnew) * Obj[worst].lnL
      + exp(lnZ - lnZnew) * (H + lnZ) - lnZnew;

    lnZ = lnZnew;

    Sample[nest] = Obj[worst];

    do{
      copy = (int)(N_obj * UNIFORM) % N_obj;
    }while(copy == worst && N_obj > 1);

    lnLstar = Obj[worst].lnL;
    Obj[worst] = Obj[copy];

    Obj[worst] = Obj[worst].Explore(lnLstar,D);

    lnwidth -= 1.0 / N_obj;
  }

  cout<<"# iterates = "<< nest <<"\n";
  cout<<"Evidence: ln(Z) = "<< lnZ <<" +- "<< sqrt(H/N_obj) <<"\n";
  cout<<"Information: H = "<< H <<" nats = "<< H/log(2.) <<" bits\n";
  Results(&Sample[0], nest, lnZ);

  return 0;
}

<commit_msg>added #include <cstdlib> in mcmc.cpp<commit_after>#include <iostream>
#include <math.h>
#include <cstdlib>
using namespace std;

const int N_data = 64;
const int N_obj = 100;
const float A = 1.34;
const float B = 0.87;
const int MAX = 10000;

#define UNIFORM (rand() + 0.5)/(RAND_MAX + 1.0)
#define PLUS(x,y) (x>y ? x+log(1+exp(y-x)) : y+log(1+exp(x-y)))

class my_data{
public:
  double x[N_data], value[N_data], error[N_data];
  my_data();
};

class my_obj{
public:
  double u, v;
  double a, b;
  double lnL, lnWt;
  void setPrior();
  void getlnLhood(double, double, my_data);
  my_obj Explore(double, my_data);
};

void Results(my_obj*, int, double);

my_data::my_data(){
  int i;

  for(i = 0; i < N_data; i++){
    x[i] = UNIFORM;
    value[i] = (A * x[i] + B);
    value[i] += (UNIFORM - 0.5) * 0.1 * value[i];
    error[i] = 0.1 * value[i];
  }
}

void my_obj::getlnLhood(double a, double b, my_data D){
  int i;
  double value, residue, L;

  for(i = 0, L = 0.0; i < N_data; i++){
    value = a * D.x[i] + b;
    residue = (value - D.value[i]) / D.error[i];
    L += - 0.5 * residue * residue - log(D.error[i] * sqrt(2.0 * M_PI));
  }

  lnL = L;
}

void my_obj::setPrior(){
  u = UNIFORM;
  v = UNIFORM;
  a = u * (2.0 - 1.0) + 1.0;
  b = v;
}

my_obj my_obj::Explore(double lnLstar, my_data D){
  double  step = 0.1;
  int     m    = 20;
  int     accept = 0;
  int     reject = 0;
  my_obj  Try, Get;

  for( ; m > 0; m-- ){
	  // Trial object
	  Try.u = u + step * (2.*UNIFORM - 1.);  // |move| < step
	  Try.v = v + step * (2.*UNIFORM - 1.);  // |move| < step
	  Try.u -= floor(Try.u);      // wraparound to stay within (0,1)
      Try.v -= floor(Try.v);      // wraparound to stay within (0,1)
      Try.a = Try.u * (2.0 - 1.0) + 1.0;  // map to x
      Try.b = Try.v;        // map to y
      Try.getlnLhood(Try.a, Try.b, D);  // trial likelihood value
      // Accept if and only if within hard likelihood constraint
      if(Try.lnL > lnLstar){
    	  Get = Try;
    	  accept++;
      }
      else
	reject++;
      // Refine step-size to let acceptance ratio converge around 50%
      if(accept > reject)    step *= exp(1.0 / accept);
      if(accept < reject)    step /= exp(1.0 / reject);
    }

 return Get;
}

void Results(my_obj* sample, int nest, double lnZ){
  double a = 0.0, aa = 0.0;   // 1st and 2nd moments of x
  double b = 0.0, bb = 0.0;   // 1st and 2nd moments of y
  double w;                   // Proportional weight
  int    i;                   // Sample counter

  for(i = 0; i < nest; i++){
    w = exp(sample[i].lnWt - lnZ);
    a  += w * sample[i].a;
    aa += w * sample[i].a * sample[i].a;
    b  += w * sample[i].b;
    bb += w * sample[i].b * sample[i].b;
  }

  cout<<"real A = "<< A <<" mean(A) = "<< a <<" stddev(A) = "<< sqrt(aa - a*a) <<"\n";
  cout<<"real B = "<< B <<" mean(B) = "<< b <<" stddev(B) = "<< sqrt(bb - b*b) <<"\n";
}

int mcmc(){
  double lnwidth;      // ln(width in prior mass)
  double lnLstar;      // ln(Likelihood constraint)
  double H    = 0.0;    // Information, initially 0
  double lnZ = 0.0;// ln(Evidence Z, initially 0)
  double lnZnew;       // Updated logZ
  int    i;             // Object counter
  int    copy;          // Duplicated object
  int    worst;         // Worst object
  int    nest;          // Nested sampling iteration count
  my_obj Obj[N_obj];
  my_obj Sample[MAX];
  my_data D;

  for(i = 0; i < N_obj; i++){
    Obj[i].setPrior();
    Obj[i].getlnLhood(Obj[i].a,Obj[i].b,D);
   }

  lnwidth = log(1.0 - exp(-1.0 / N_obj));

  for(nest = 0; nest < MAX; nest++){

    for(i = 1, worst = 0; i < N_obj; i++)
      if(Obj[i].lnL < Obj[worst].lnL)
	worst = i;

    Obj[worst].lnWt = lnwidth + Obj[worst].lnL;

    lnZnew = PLUS(lnZ, Obj[worst].lnWt);

    H = exp(Obj[worst].lnWt - lnZnew) * Obj[worst].lnL
      + exp(lnZ - lnZnew) * (H + lnZ) - lnZnew;

    lnZ = lnZnew;

    Sample[nest] = Obj[worst];

    do{
      copy = (int)(N_obj * UNIFORM) % N_obj;
    }while(copy == worst && N_obj > 1);

    lnLstar = Obj[worst].lnL;
    Obj[worst] = Obj[copy];

    Obj[worst] = Obj[worst].Explore(lnLstar,D);

    lnwidth -= 1.0 / N_obj;
  }

  cout<<"# iterates = "<< nest <<"\n";
  cout<<"Evidence: ln(Z) = "<< lnZ <<" +- "<< sqrt(H/N_obj) <<"\n";
  cout<<"Information: H = "<< H <<" nats = "<< H/log(2.) <<" bits\n";
  Results(&Sample[0], nest, lnZ);

  return 0;
}

<|endoftext|>