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

#ifndef SVX_DBAOBJECTEX_HXX
#include "dbaobjectex.hxx"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XTablesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XSQLQUERYCOMPOSERFACTORY_HPP_
#include <com/sun/star/sdb/XSQLQueryComposerFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XSQLQUERYCOMPOSERFACTORY_HPP_
#include <com/sun/star/sdb/XSQLQueryComposerFactory.hpp>
#endif
#ifndef _SVX_FMPROP_HRC
#include "fmprop.hrc"
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _SOT_FORMATS_HXX
#include <sot/formats.hxx>
#endif
#ifndef _SOT_EXCHANGE_HXX
#include <sot/exchange.hxx>
#endif
#ifndef _COMPHELPER_PROPERTSETINFO_HXX_
#include <comphelper/propertysetinfo.hxx>
#endif
#ifndef _SVX_FMPROP_HRC
#include "fmprop.hrc"
#endif

//........................................................................
namespace svx
{
//........................................................................

    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::sdb;
    using namespace ::com::sun::star::sdbc;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::ucb;
    using namespace ::com::sun::star::sdbcx;
    using namespace ::com::sun::star::container;
    using namespace ::com::sun::star::datatransfer;
    using namespace ::svxform;
    using namespace ::comphelper;

    //====================================================================
    //= OComponentTransferable
    //====================================================================
    //--------------------------------------------------------------------
    OComponentTransferable::OComponentTransferable(const ::rtl::OUString& _rDatasourceOrLocation
            ,const Reference< XContent>& _xContent)
    {
        m_aDescriptor.setDataSource(_rDatasourceOrLocation);
        m_aDescriptor[daComponent] <<= _xContent;
    }

    //--------------------------------------------------------------------
    sal_uInt32 OComponentTransferable::getDescriptorFormatId(sal_Bool _bExtractForm)
    {
        static sal_uInt32 s_nReportFormat = (sal_uInt32)-1;
        static sal_uInt32 s_nFormFormat = (sal_uInt32)-1;
        if ( _bExtractForm && (sal_uInt32)-1 == s_nFormFormat )
        {
            s_nFormFormat = SotExchange::RegisterFormatName(String::CreateFromAscii("application/x-openoffice;windows_formatname=\"dbaccess.FormComponentDescriptorTransfer\"" ));
            OSL_ENSURE((sal_uInt32)-1 != s_nFormFormat, "OComponentTransferable::getDescriptorFormatId: bad exchange id!");
        }
        else if ( !_bExtractForm && (sal_uInt32)-1 == s_nReportFormat)
        {
            s_nReportFormat = SotExchange::RegisterFormatName(String::CreateFromAscii("application/x-openoffice;windows_formatname=\"dbaccess.ReportComponentDescriptorTransfer\""));
            OSL_ENSURE((sal_uInt32)-1 != s_nReportFormat, "OComponentTransferable::getDescriptorFormatId: bad exchange id!");
        }
        return _bExtractForm ? s_nFormFormat : s_nReportFormat;
    }

    //--------------------------------------------------------------------
    void OComponentTransferable::AddSupportedFormats()
    {
        sal_Bool bForm = sal_True;
        try
        {
            Reference<XPropertySet> xProp;
            m_aDescriptor[daComponent] >>= xProp;
            if ( xProp.is() )
                xProp->getPropertyValue(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("IsForm"))) >>= bForm;
        }
        catch(Exception)
        {}
        AddFormat(getDescriptorFormatId(bForm));
    }

    //--------------------------------------------------------------------
    sal_Bool OComponentTransferable::GetData( const DataFlavor& _rFlavor )
    {
        const sal_uInt32 nFormatId = SotExchange::GetFormat(_rFlavor);
        if ( nFormatId == getDescriptorFormatId(sal_True) || nFormatId == getDescriptorFormatId(sal_False) )
            return SetAny( makeAny( m_aDescriptor.createPropertyValueSequence() ), _rFlavor );

        return sal_False;
    }

    //--------------------------------------------------------------------
    sal_Bool OComponentTransferable::canExtractComponentDescriptor(const DataFlavorExVector& _rFlavors,sal_Bool _bForm )
    {
        DataFlavorExVector::const_iterator aEnd = _rFlavors.end();
        for (   DataFlavorExVector::const_iterator aCheck = _rFlavors.begin();
                aCheck != aEnd;
                ++aCheck
            )
        {
            if ( getDescriptorFormatId(_bForm) == aCheck->mnSotId )
                return sal_True;
        }

        return sal_False;
    }

    //--------------------------------------------------------------------
    ODataAccessDescriptor OComponentTransferable::extractComponentDescriptor(const TransferableDataHelper& _rData)
    {
        sal_Bool bForm;
        if ( (bForm = _rData.HasFormat(getDescriptorFormatId(sal_True))) || _rData.HasFormat(getDescriptorFormatId(sal_False)) )
        {
            // the object has a real descriptor object (not just the old compatible format)

            // extract the any from the transferable
            DataFlavor aFlavor;
#if OSL_DEBUG_LEVEL > 0
            sal_Bool bSuccess =
#endif
            SotExchange::GetFormatDataFlavor(getDescriptorFormatId(bForm), aFlavor);
            OSL_ENSURE(bSuccess, "OComponentTransferable::extractColumnDescriptor: invalid data format (no flavor)!");

            Any aDescriptor = _rData.GetAny(aFlavor);

            // extract the property value sequence
            Sequence< PropertyValue > aDescriptorProps;
#if OSL_DEBUG_LEVEL > 0
            bSuccess =
#endif
            aDescriptor >>= aDescriptorProps;
            OSL_ENSURE(bSuccess, "OComponentTransferable::extractColumnDescriptor: invalid clipboard format!");

            // build the real descriptor
            return ODataAccessDescriptor(aDescriptorProps);
        }

        return ODataAccessDescriptor();
    }

    //--------------------------------------------------------------------
    sal_Bool OComponentTransferable::extractComponentDescriptor(const TransferableDataHelper& _rData
        ,sal_Bool _bExtractForm
        , ::rtl::OUString&  _rDatasourceOrLocation
        , ::com::sun::star::uno::Reference< XContent>& _xContent)
    {
        if ( _rData.HasFormat( getDescriptorFormatId(_bExtractForm)) )
        {
            ODataAccessDescriptor aDescriptor = extractComponentDescriptor(_rData);
            _rDatasourceOrLocation = aDescriptor.getDataSource();
            aDescriptor[daComponent]            >>= _xContent;
            return sal_True;
        }

        return sal_False;
    }
//........................................................................
}   // namespace svx
//........................................................................

<commit_msg>INTEGRATION: CWS pchfix02 (1.4.516); FILE MERGED 2006/09/01 17:46:45 kaib 1.4.516.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dbaobjectex.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 05:00:46 $
 *
 *  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_svx.hxx"

#ifndef SVX_DBAOBJECTEX_HXX
#include "dbaobjectex.hxx"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XTablesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XSQLQUERYCOMPOSERFACTORY_HPP_
#include <com/sun/star/sdb/XSQLQueryComposerFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XSQLQUERYCOMPOSERFACTORY_HPP_
#include <com/sun/star/sdb/XSQLQueryComposerFactory.hpp>
#endif
#ifndef _SVX_FMPROP_HRC
#include "fmprop.hrc"
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _SOT_FORMATS_HXX
#include <sot/formats.hxx>
#endif
#ifndef _SOT_EXCHANGE_HXX
#include <sot/exchange.hxx>
#endif
#ifndef _COMPHELPER_PROPERTSETINFO_HXX_
#include <comphelper/propertysetinfo.hxx>
#endif
#ifndef _SVX_FMPROP_HRC
#include "fmprop.hrc"
#endif

//........................................................................
namespace svx
{
//........................................................................

    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::sdb;
    using namespace ::com::sun::star::sdbc;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::ucb;
    using namespace ::com::sun::star::sdbcx;
    using namespace ::com::sun::star::container;
    using namespace ::com::sun::star::datatransfer;
    using namespace ::svxform;
    using namespace ::comphelper;

    //====================================================================
    //= OComponentTransferable
    //====================================================================
    //--------------------------------------------------------------------
    OComponentTransferable::OComponentTransferable(const ::rtl::OUString& _rDatasourceOrLocation
            ,const Reference< XContent>& _xContent)
    {
        m_aDescriptor.setDataSource(_rDatasourceOrLocation);
        m_aDescriptor[daComponent] <<= _xContent;
    }

    //--------------------------------------------------------------------
    sal_uInt32 OComponentTransferable::getDescriptorFormatId(sal_Bool _bExtractForm)
    {
        static sal_uInt32 s_nReportFormat = (sal_uInt32)-1;
        static sal_uInt32 s_nFormFormat = (sal_uInt32)-1;
        if ( _bExtractForm && (sal_uInt32)-1 == s_nFormFormat )
        {
            s_nFormFormat = SotExchange::RegisterFormatName(String::CreateFromAscii("application/x-openoffice;windows_formatname=\"dbaccess.FormComponentDescriptorTransfer\"" ));
            OSL_ENSURE((sal_uInt32)-1 != s_nFormFormat, "OComponentTransferable::getDescriptorFormatId: bad exchange id!");
        }
        else if ( !_bExtractForm && (sal_uInt32)-1 == s_nReportFormat)
        {
            s_nReportFormat = SotExchange::RegisterFormatName(String::CreateFromAscii("application/x-openoffice;windows_formatname=\"dbaccess.ReportComponentDescriptorTransfer\""));
            OSL_ENSURE((sal_uInt32)-1 != s_nReportFormat, "OComponentTransferable::getDescriptorFormatId: bad exchange id!");
        }
        return _bExtractForm ? s_nFormFormat : s_nReportFormat;
    }

    //--------------------------------------------------------------------
    void OComponentTransferable::AddSupportedFormats()
    {
        sal_Bool bForm = sal_True;
        try
        {
            Reference<XPropertySet> xProp;
            m_aDescriptor[daComponent] >>= xProp;
            if ( xProp.is() )
                xProp->getPropertyValue(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("IsForm"))) >>= bForm;
        }
        catch(Exception)
        {}
        AddFormat(getDescriptorFormatId(bForm));
    }

    //--------------------------------------------------------------------
    sal_Bool OComponentTransferable::GetData( const DataFlavor& _rFlavor )
    {
        const sal_uInt32 nFormatId = SotExchange::GetFormat(_rFlavor);
        if ( nFormatId == getDescriptorFormatId(sal_True) || nFormatId == getDescriptorFormatId(sal_False) )
            return SetAny( makeAny( m_aDescriptor.createPropertyValueSequence() ), _rFlavor );

        return sal_False;
    }

    //--------------------------------------------------------------------
    sal_Bool OComponentTransferable::canExtractComponentDescriptor(const DataFlavorExVector& _rFlavors,sal_Bool _bForm )
    {
        DataFlavorExVector::const_iterator aEnd = _rFlavors.end();
        for (   DataFlavorExVector::const_iterator aCheck = _rFlavors.begin();
                aCheck != aEnd;
                ++aCheck
            )
        {
            if ( getDescriptorFormatId(_bForm) == aCheck->mnSotId )
                return sal_True;
        }

        return sal_False;
    }

    //--------------------------------------------------------------------
    ODataAccessDescriptor OComponentTransferable::extractComponentDescriptor(const TransferableDataHelper& _rData)
    {
        sal_Bool bForm;
        if ( (bForm = _rData.HasFormat(getDescriptorFormatId(sal_True))) || _rData.HasFormat(getDescriptorFormatId(sal_False)) )
        {
            // the object has a real descriptor object (not just the old compatible format)

            // extract the any from the transferable
            DataFlavor aFlavor;
#if OSL_DEBUG_LEVEL > 0
            sal_Bool bSuccess =
#endif
            SotExchange::GetFormatDataFlavor(getDescriptorFormatId(bForm), aFlavor);
            OSL_ENSURE(bSuccess, "OComponentTransferable::extractColumnDescriptor: invalid data format (no flavor)!");

            Any aDescriptor = _rData.GetAny(aFlavor);

            // extract the property value sequence
            Sequence< PropertyValue > aDescriptorProps;
#if OSL_DEBUG_LEVEL > 0
            bSuccess =
#endif
            aDescriptor >>= aDescriptorProps;
            OSL_ENSURE(bSuccess, "OComponentTransferable::extractColumnDescriptor: invalid clipboard format!");

            // build the real descriptor
            return ODataAccessDescriptor(aDescriptorProps);
        }

        return ODataAccessDescriptor();
    }

    //--------------------------------------------------------------------
    sal_Bool OComponentTransferable::extractComponentDescriptor(const TransferableDataHelper& _rData
        ,sal_Bool _bExtractForm
        , ::rtl::OUString&  _rDatasourceOrLocation
        , ::com::sun::star::uno::Reference< XContent>& _xContent)
    {
        if ( _rData.HasFormat( getDescriptorFormatId(_bExtractForm)) )
        {
            ODataAccessDescriptor aDescriptor = extractComponentDescriptor(_rData);
            _rDatasourceOrLocation = aDescriptor.getDataSource();
            aDescriptor[daComponent]            >>= _xContent;
            return sal_True;
        }

        return sal_False;
    }
//........................................................................
}   // namespace svx
//........................................................................

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: atrfld.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2004-03-17 12:16:04 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#include "doc.hxx"          // Update fuer UserFields
#include "fldbas.hxx"          // fuer FieldType

#ifndef _FMTFLD_HXX //autogen
#include <fmtfld.hxx>
#endif
#ifndef _TXTFLD_HXX //autogen
#include <txtfld.hxx>
#endif
#include "reffld.hxx"
#include "ddefld.hxx"
#include "usrfld.hxx"
#include "expfld.hxx"
#include "swfont.hxx"       // fuer GetFldsColor
#include "ndtxt.hxx"        // SwTxtNode
#include "calc.hxx"         // Update fuer UserFields
#include "hints.hxx"

TYPEINIT2( SwFmtFld, SfxPoolItem, SwClient )

/****************************************************************************
 *
 *  class SwFmtFld
 *
 ****************************************************************************/

    // Konstruktor fuers Default vom Attribut-Pool
SwFmtFld::SwFmtFld()
    : SfxPoolItem( RES_TXTATR_FIELD ),
    SwClient( 0 ),
    pField( 0 ),
    pTxtAttr( 0 )
{
}

SwFmtFld::SwFmtFld( const SwField &rFld )
    : SfxPoolItem( RES_TXTATR_FIELD ),
    SwClient( rFld.GetTyp() ),
    pTxtAttr( 0 )
{
    pField = rFld.Copy();
}

// #i24434#
// Since Items are used in ItemPool and in default constructed ItemSets with
// full pool range, all items need to be clonable. Thus, this one needed to be
// corrected
SwFmtFld::SwFmtFld( const SwFmtFld& rAttr )
    : SfxPoolItem( RES_TXTATR_FIELD ),
    pTxtAttr( 0 ),
    pField( 0 )
{
    if(rAttr.GetFld())
    {
        rAttr.GetFld()->GetTyp()->Add(this);
        pField = rAttr.GetFld()->Copy();
    }
}

SwFmtFld::~SwFmtFld()
{
    SwFieldType* pType = pField ? pField->GetTyp() : 0;

    if (pType && pType->Which() == RES_DBFLD)
        pType = 0;  // DB-Feldtypen zerstoeren sich selbst

    delete pField;

    // bei einige FeldTypen muessen wir den FeldTypen noch loeschen
    if( pType && pType->IsLastDepend() )
    {
        BOOL bDel = FALSE;
        switch( pType->Which() )
        {
        case RES_USERFLD:
            bDel = ((SwUserFieldType*)pType)->IsDeleted();
            break;

        case RES_SETEXPFLD:
            bDel = ((SwSetExpFieldType*)pType)->IsDeleted();
            break;

        case RES_DDEFLD:
            bDel = ((SwDDEFieldType*)pType)->IsDeleted();
            break;
        }

        if( bDel )
        {
            // vorm loeschen erstmal austragen
            pType->Remove( this );
            delete pType;
        }
    }
}

int SwFmtFld::operator==( const SfxPoolItem& rAttr ) const
{
    ASSERT( SfxPoolItem::operator==( rAttr ), "keine gleichen Attribute" );
    return pField->GetTyp() == ((SwFmtFld&)rAttr).GetFld()->GetTyp() &&
           pField->GetFormat() == ((SwFmtFld&)rAttr).GetFld()->GetFormat();
}

SfxPoolItem* SwFmtFld::Clone( SfxItemPool* ) const
{
    return new SwFmtFld( *this );
}

void SwFmtFld::Modify( SfxPoolItem* pOld, SfxPoolItem* pNew )
{
    if( !pTxtAttr )
        return;

    SwTxtNode* pTxtNd = (SwTxtNode*)&pTxtAttr->GetTxtNode();
    ASSERT( pTxtNd, "wo ist denn mein Node?" );
    if( pNew )
    {
        switch( pNew->Which() )
        {
        case RES_TXTATR_FLDCHG:
                // "Farbe hat sich geaendert !"
                // this, this fuer "nur Painten"
                pTxtNd->Modify( this, this );
                return;
        case RES_REFMARKFLD_UPDATE:
                // GetReferenz-Felder aktualisieren
                if( RES_GETREFFLD == GetFld()->GetTyp()->Which() )
                    ((SwGetRefField*)GetFld())->UpdateField();
                break;
        case RES_DOCPOS_UPDATE:
                // Je nach DocPos aktualisieren (SwTxtFrm::Modify())
                pTxtNd->Modify( pNew, this );
                return;

        case RES_ATTRSET_CHG:
        case RES_FMT_CHG:
                pTxtNd->Modify( pOld, pNew );
                return;
        }
    }

    switch (GetFld()->GetTyp()->Which())
    {
        case RES_HIDDENPARAFLD:
            if( !pOld || RES_HIDDENPARA_PRINT != pOld->Which() )
                break;
        case RES_DBSETNUMBERFLD:
        case RES_DBNUMSETFLD:
        case RES_DBNEXTSETFLD:
        case RES_DBNAMEFLD:
            pTxtNd->Modify( 0, pNew);
            return;
    }

    if( RES_USERFLD == GetFld()->GetTyp()->Which() )
    {
        SwUserFieldType* pType = (SwUserFieldType*)GetFld()->GetTyp();
        if(!pType->IsValid())
        {
            SwCalc aCalc( *pTxtNd->GetDoc() );
            pType->GetValue( aCalc );
        }
    }
    pTxtAttr->Expand();
}

BOOL SwFmtFld::GetInfo( SfxPoolItem& rInfo ) const
{
    const SwTxtNode* pTxtNd;
    if( RES_AUTOFMT_DOCNODE != rInfo.Which() ||
        !pTxtAttr || 0 == ( pTxtNd = pTxtAttr->GetpTxtNode() ) ||
        &pTxtNd->GetNodes() != ((SwAutoFmtGetDocNode&)rInfo).pNodes )
        return TRUE;

    ((SwAutoFmtGetDocNode&)rInfo).pCntntNode = pTxtNd;
    return FALSE;
}

BOOL SwFmtFld::IsFldInDoc() const
{
    const SwTxtNode* pTxtNd;
    return pTxtAttr && 0 != ( pTxtNd = pTxtAttr->GetpTxtNode() ) &&
            pTxtNd->GetNodes().IsDocNodes();
}

BOOL SwFmtFld::IsProtect() const
{
    const SwTxtNode* pTxtNd;
    return pTxtAttr && 0 != ( pTxtNd = pTxtAttr->GetpTxtNode() ) &&
            pTxtNd->IsProtect();
}

/*************************************************************************
|*
|*                SwTxtFld::SwTxtFld()
|*
|*    Beschreibung      Attribut fuer automatischen Text, Ctor
|*    Ersterstellung    BP 30.04.92
|*    Letzte Aenderung  JP 15.08.94
|*
*************************************************************************/

SwTxtFld::SwTxtFld( const SwFmtFld& rAttr, xub_StrLen nStart )
    : SwTxtAttr( rAttr, nStart ),
    aExpand( rAttr.GetFld()->Expand() ),
    pMyTxtNd( 0 )
{
    ((SwFmtFld&)rAttr).pTxtAttr = this;
}

SwTxtFld::~SwTxtFld( )
{
}

/*************************************************************************
|*
|*                SwTxtFld::Expand()
|*
|*    Beschreibung      exandiert das Feld und tauscht den Text im Node
|*    Ersterstellung    BP 30.04.92
|*    Letzte Aenderung  JP 15.08.94
|*
*************************************************************************/

void SwTxtFld::Expand() const
{
    // Wenn das expandierte Feld sich nicht veraendert hat, wird returnt
    ASSERT( pMyTxtNd, "wo ist denn mein Node?" );

    const SwField* pFld = GetFld().GetFld();
    XubString aNewExpand( pFld->Expand() );

    if( aNewExpand == aExpand )
    {
        // Bei Seitennummernfeldern
        const USHORT nWhich = pFld->GetTyp()->Which();
        if( RES_CHAPTERFLD != nWhich && RES_PAGENUMBERFLD != nWhich &&
            RES_REFPAGEGETFLD != nWhich &&
            ( RES_GETEXPFLD != nWhich ||
                ((SwGetExpField*)pFld)->IsInBodyTxt() ) )
        {
            // BP: das muesste man noch optimieren!
            //JP 12.06.97: stimmt, man sollte auf jedenfall eine Status-
            //              aenderung an die Frames posten
            if( pMyTxtNd->CalcHiddenParaField() )
                pMyTxtNd->Modify( 0, 0 );
            return;
        }
    }

    aExpand = aNewExpand;

    // 0, this fuer Formatieren
    pMyTxtNd->Modify( 0, (SfxPoolItem*)&GetFld() );
}

/*************************************************************************
 *                      SwTxtFld::CopyFld()
 *************************************************************************/

void SwTxtFld::CopyFld( SwTxtFld *pDest ) const
{
    ASSERT( pMyTxtNd, "wo ist denn mein Node?" );
    ASSERT( pDest->pMyTxtNd, "wo ist denn mein Node?" );

    SwDoc *pDoc = pMyTxtNd->GetDoc();
    SwDoc *pDestDoc = pDest->pMyTxtNd->GetDoc();

    SwFmtFld& rFmtFld = (SwFmtFld&)pDest->GetFld();
    const USHORT nFldWhich = rFmtFld.GetFld()->GetTyp()->Which();

    if( pDoc != pDestDoc )
    {
        // Die Hints stehen in unterschiedlichen Dokumenten,
        // der Feldtyp muss im neuen Dokument angemeldet werden.
        // Z.B: Kopieren ins ClipBoard.
        SwFieldType* pFldType;
        if( nFldWhich != RES_DBFLD && nFldWhich != RES_USERFLD &&
            nFldWhich != RES_SETEXPFLD && nFldWhich != RES_DDEFLD &&
            RES_AUTHORITY != nFldWhich )
            pFldType = pDestDoc->GetSysFldType( (const RES_FIELDS)nFldWhich );
        else
            pFldType = pDestDoc->InsertFldType( *rFmtFld.GetFld()->GetTyp() );

        // Sonderbehandlung fuer DDE-Felder
        if( RES_DDEFLD == nFldWhich )
        {
            if( rFmtFld.GetTxtFld() )
                ((SwDDEFieldType*)rFmtFld.GetFld()->GetTyp())->DecRefCnt();
            ((SwDDEFieldType*)pFldType)->IncRefCnt();
        }

        ASSERT( pFldType, "unbekannter FieldType" );
        pFldType->Add( &rFmtFld );          // ummelden
        rFmtFld.GetFld()->ChgTyp( pFldType );
    }

    // Expressionfelder Updaten
    if( nFldWhich == RES_SETEXPFLD || nFldWhich == RES_GETEXPFLD ||
        nFldWhich == RES_HIDDENTXTFLD )
    {
        SwTxtFld* pFld = (SwTxtFld*)this;
        pDestDoc->UpdateExpFlds( pFld );
    }
    // Tabellenfelder auf externe Darstellung
    else if( RES_TABLEFLD == nFldWhich &&
        ((SwTblField*)rFmtFld.GetFld())->IsIntrnlName() )
    {
        // erzeuge aus der internen (fuer CORE) die externe (fuer UI) Formel
        const SwTableNode* pTblNd = pMyTxtNd->FindTableNode();
        if( pTblNd )        // steht in einer Tabelle
            ((SwTblField*)rFmtFld.GetFld())->PtrToBoxNm( &pTblNd->GetTable() );
    }
}

<commit_msg>INTEGRATION: CWS swundo01 (1.2.126); FILE MERGED 2004/04/19 10:24:01 hbrinkm 1.2.126.2: RESYNC: (1.2-1.5); FILE MERGED 2004/01/06 15:37:11 hbrinkm 1.2.126.1: #111840#<commit_after>/*************************************************************************
 *
 *  $RCSfile: atrfld.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: kz $ $Date: 2004-05-18 14:04:55 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#include "doc.hxx"          // Update fuer UserFields
#include "fldbas.hxx"          // fuer FieldType

#ifndef _FMTFLD_HXX //autogen
#include <fmtfld.hxx>
#endif
#ifndef _TXTFLD_HXX //autogen
#include <txtfld.hxx>
#endif
#include "reffld.hxx"
#include "ddefld.hxx"
#include "usrfld.hxx"
#include "expfld.hxx"
#include "swfont.hxx"       // fuer GetFldsColor
#include "ndtxt.hxx"        // SwTxtNode
#include "calc.hxx"         // Update fuer UserFields
#include "hints.hxx"

TYPEINIT2( SwFmtFld, SfxPoolItem, SwClient )

/****************************************************************************
 *
 *  class SwFmtFld
 *
 ****************************************************************************/

    // Konstruktor fuers Default vom Attribut-Pool
SwFmtFld::SwFmtFld()
    : SfxPoolItem( RES_TXTATR_FIELD ),
    SwClient( 0 ),
    pField( 0 ),
    pTxtAttr( 0 )
{
}

SwFmtFld::SwFmtFld( const SwField &rFld )
    : SfxPoolItem( RES_TXTATR_FIELD ),
    SwClient( rFld.GetTyp() ),
    pTxtAttr( 0 )
{
    pField = rFld.Copy();
}

// #i24434#
// Since Items are used in ItemPool and in default constructed ItemSets with
// full pool range, all items need to be clonable. Thus, this one needed to be
// corrected
SwFmtFld::SwFmtFld( const SwFmtFld& rAttr )
    : SfxPoolItem( RES_TXTATR_FIELD ),
    pTxtAttr( 0 ),
    pField( 0 )
{
    if(rAttr.GetFld())
    {
        rAttr.GetFld()->GetTyp()->Add(this);
        pField = rAttr.GetFld()->Copy();
    }
}

SwFmtFld::~SwFmtFld()
{
    SwFieldType* pType = pField ? pField->GetTyp() : 0;

    if (pType && pType->Which() == RES_DBFLD)
        pType = 0;  // DB-Feldtypen zerstoeren sich selbst

    delete pField;

    // bei einige FeldTypen muessen wir den FeldTypen noch loeschen
    if( pType && pType->IsLastDepend() )
    {
        BOOL bDel = FALSE;
        switch( pType->Which() )
        {
        case RES_USERFLD:
            bDel = ((SwUserFieldType*)pType)->IsDeleted();
            break;

        case RES_SETEXPFLD:
            bDel = ((SwSetExpFieldType*)pType)->IsDeleted();
            break;

        case RES_DDEFLD:
            bDel = ((SwDDEFieldType*)pType)->IsDeleted();
            break;
        }

        if( bDel )
        {
            // vorm loeschen erstmal austragen
            pType->Remove( this );
            delete pType;
        }
    }
}

// #111840#
void SwFmtFld::SetFld(SwField * _pField)
{
    if (NULL != pField)
        delete pField;

    pField = _pField;
}

int SwFmtFld::operator==( const SfxPoolItem& rAttr ) const
{
    ASSERT( SfxPoolItem::operator==( rAttr ), "keine gleichen Attribute" );
    return pField->GetTyp() == ((SwFmtFld&)rAttr).GetFld()->GetTyp() &&
           pField->GetFormat() == ((SwFmtFld&)rAttr).GetFld()->GetFormat();
}

SfxPoolItem* SwFmtFld::Clone( SfxItemPool* ) const
{
    return new SwFmtFld( *this );
}

void SwFmtFld::Modify( SfxPoolItem* pOld, SfxPoolItem* pNew )
{
    if( !pTxtAttr )
        return;

    SwTxtNode* pTxtNd = (SwTxtNode*)&pTxtAttr->GetTxtNode();
    ASSERT( pTxtNd, "wo ist denn mein Node?" );
    if( pNew )
    {
        switch( pNew->Which() )
        {
        case RES_TXTATR_FLDCHG:
                // "Farbe hat sich geaendert !"
                // this, this fuer "nur Painten"
                pTxtNd->Modify( this, this );
                return;
        case RES_REFMARKFLD_UPDATE:
                // GetReferenz-Felder aktualisieren
                if( RES_GETREFFLD == GetFld()->GetTyp()->Which() )
                    ((SwGetRefField*)GetFld())->UpdateField();
                break;
        case RES_DOCPOS_UPDATE:
                // Je nach DocPos aktualisieren (SwTxtFrm::Modify())
                pTxtNd->Modify( pNew, this );
                return;

        case RES_ATTRSET_CHG:
        case RES_FMT_CHG:
                pTxtNd->Modify( pOld, pNew );
                return;
        }
    }

    switch (GetFld()->GetTyp()->Which())
    {
        case RES_HIDDENPARAFLD:
            if( !pOld || RES_HIDDENPARA_PRINT != pOld->Which() )
                break;
        case RES_DBSETNUMBERFLD:
        case RES_DBNUMSETFLD:
        case RES_DBNEXTSETFLD:
        case RES_DBNAMEFLD:
            pTxtNd->Modify( 0, pNew);
            return;
    }

    if( RES_USERFLD == GetFld()->GetTyp()->Which() )
    {
        SwUserFieldType* pType = (SwUserFieldType*)GetFld()->GetTyp();
        if(!pType->IsValid())
        {
            SwCalc aCalc( *pTxtNd->GetDoc() );
            pType->GetValue( aCalc );
        }
    }
    pTxtAttr->Expand();
}

BOOL SwFmtFld::GetInfo( SfxPoolItem& rInfo ) const
{
    const SwTxtNode* pTxtNd;
    if( RES_AUTOFMT_DOCNODE != rInfo.Which() ||
        !pTxtAttr || 0 == ( pTxtNd = pTxtAttr->GetpTxtNode() ) ||
        &pTxtNd->GetNodes() != ((SwAutoFmtGetDocNode&)rInfo).pNodes )
        return TRUE;

    ((SwAutoFmtGetDocNode&)rInfo).pCntntNode = pTxtNd;
    return FALSE;
}

BOOL SwFmtFld::IsFldInDoc() const
{
    const SwTxtNode* pTxtNd;
    return pTxtAttr && 0 != ( pTxtNd = pTxtAttr->GetpTxtNode() ) &&
            pTxtNd->GetNodes().IsDocNodes();
}

BOOL SwFmtFld::IsProtect() const
{
    const SwTxtNode* pTxtNd;
    return pTxtAttr && 0 != ( pTxtNd = pTxtAttr->GetpTxtNode() ) &&
            pTxtNd->IsProtect();
}

/*************************************************************************
|*
|*                SwTxtFld::SwTxtFld()
|*
|*    Beschreibung      Attribut fuer automatischen Text, Ctor
|*    Ersterstellung    BP 30.04.92
|*    Letzte Aenderung  JP 15.08.94
|*
*************************************************************************/

SwTxtFld::SwTxtFld( const SwFmtFld& rAttr, xub_StrLen nStart )
    : SwTxtAttr( rAttr, nStart ),
    aExpand( rAttr.GetFld()->Expand() ),
    pMyTxtNd( 0 )
{
    ((SwFmtFld&)rAttr).pTxtAttr = this;
}

SwTxtFld::~SwTxtFld( )
{
}

/*************************************************************************
|*
|*                SwTxtFld::Expand()
|*
|*    Beschreibung      exandiert das Feld und tauscht den Text im Node
|*    Ersterstellung    BP 30.04.92
|*    Letzte Aenderung  JP 15.08.94
|*
*************************************************************************/

void SwTxtFld::Expand() const
{
    // Wenn das expandierte Feld sich nicht veraendert hat, wird returnt
    ASSERT( pMyTxtNd, "wo ist denn mein Node?" );

    const SwField* pFld = GetFld().GetFld();
    XubString aNewExpand( pFld->Expand() );

    if( aNewExpand == aExpand )
    {
        // Bei Seitennummernfeldern
        const USHORT nWhich = pFld->GetTyp()->Which();
        if( RES_CHAPTERFLD != nWhich && RES_PAGENUMBERFLD != nWhich &&
            RES_REFPAGEGETFLD != nWhich &&
            ( RES_GETEXPFLD != nWhich ||
                ((SwGetExpField*)pFld)->IsInBodyTxt() ) )
        {
            // BP: das muesste man noch optimieren!
            //JP 12.06.97: stimmt, man sollte auf jedenfall eine Status-
            //              aenderung an die Frames posten
            if( pMyTxtNd->CalcHiddenParaField() )
                pMyTxtNd->Modify( 0, 0 );
            return;
        }
    }

    aExpand = aNewExpand;

    // 0, this fuer Formatieren
    pMyTxtNd->Modify( 0, (SfxPoolItem*)&GetFld() );
}

/*************************************************************************
 *                      SwTxtFld::CopyFld()
 *************************************************************************/

void SwTxtFld::CopyFld( SwTxtFld *pDest ) const
{
    ASSERT( pMyTxtNd, "wo ist denn mein Node?" );
    ASSERT( pDest->pMyTxtNd, "wo ist denn mein Node?" );

    SwDoc *pDoc = pMyTxtNd->GetDoc();
    SwDoc *pDestDoc = pDest->pMyTxtNd->GetDoc();

    SwFmtFld& rFmtFld = (SwFmtFld&)pDest->GetFld();
    const USHORT nFldWhich = rFmtFld.GetFld()->GetTyp()->Which();

    if( pDoc != pDestDoc )
    {
        // Die Hints stehen in unterschiedlichen Dokumenten,
        // der Feldtyp muss im neuen Dokument angemeldet werden.
        // Z.B: Kopieren ins ClipBoard.
        SwFieldType* pFldType;
        if( nFldWhich != RES_DBFLD && nFldWhich != RES_USERFLD &&
            nFldWhich != RES_SETEXPFLD && nFldWhich != RES_DDEFLD &&
            RES_AUTHORITY != nFldWhich )
            pFldType = pDestDoc->GetSysFldType( (const RES_FIELDS)nFldWhich );
        else
            pFldType = pDestDoc->InsertFldType( *rFmtFld.GetFld()->GetTyp() );

        // Sonderbehandlung fuer DDE-Felder
        if( RES_DDEFLD == nFldWhich )
        {
            if( rFmtFld.GetTxtFld() )
                ((SwDDEFieldType*)rFmtFld.GetFld()->GetTyp())->DecRefCnt();
            ((SwDDEFieldType*)pFldType)->IncRefCnt();
        }

        ASSERT( pFldType, "unbekannter FieldType" );
        pFldType->Add( &rFmtFld );          // ummelden
        rFmtFld.GetFld()->ChgTyp( pFldType );
    }

    // Expressionfelder Updaten
    if( nFldWhich == RES_SETEXPFLD || nFldWhich == RES_GETEXPFLD ||
        nFldWhich == RES_HIDDENTXTFLD )
    {
        SwTxtFld* pFld = (SwTxtFld*)this;
        pDestDoc->UpdateExpFlds( pFld );
    }
    // Tabellenfelder auf externe Darstellung
    else if( RES_TABLEFLD == nFldWhich &&
        ((SwTblField*)rFmtFld.GetFld())->IsIntrnlName() )
    {
        // erzeuge aus der internen (fuer CORE) die externe (fuer UI) Formel
        const SwTableNode* pTblNd = pMyTxtNd->FindTableNode();
        if( pTblNd )        // steht in einer Tabelle
            ((SwTblField*)rFmtFld.GetFld())->PtrToBoxNm( &pTblNd->GetTable() );
    }
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: ascatr.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: vg $ $Date: 2003-04-17 14:48:33 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif

#ifndef _STREAM_HXX //autogen
#include <tools/stream.hxx>
#endif
#ifndef _SVSTDARR_HXX
#define _SVSTDARR_USHORTS
#include <svtools/svstdarr.hxx>
#endif
#ifndef _SVX_FONTITEM_HXX
#include <svx/fontitem.hxx>
#endif

#ifndef _PAM_HXX
#include <pam.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _NDTXT_HXX
#include <ndtxt.hxx>
#endif
#ifndef _WRTASC_HXX
#include <wrtasc.hxx>
#endif
#ifndef _TXATBASE_HXX
#include <txatbase.hxx>
#endif
#ifndef _FCHRFMT_HXX
#include <fchrfmt.hxx>
#endif
#ifndef _TXTFLD_HXX
#include <txtfld.hxx>
#endif
#ifndef _TXTATR_HXX
#include <txtatr.hxx>
#endif
#ifndef _FMTFTN_HXX
#include <fmtftn.hxx>
#endif
#ifndef _CHARFMT_HXX
#include <charfmt.hxx>
#endif
#ifndef _FMTFLD_HXX
#include <fmtfld.hxx>
#endif
#ifndef _FLDBAS_HXX
#include <fldbas.hxx>
#endif
#ifndef _FTNINFO_HXX //autogen
#include <ftninfo.hxx>
#endif

/*
 * Dieses File enthaelt alle Ausgabe-Funktionen des ASCII-Writers;
 * fuer alle Nodes, Attribute, Formate und Chars.
 */

class SwASC_AttrIter
{
    SwASCWriter& rWrt;
    const SwTxtNode& rNd;
    xub_StrLen nAktSwPos;

    xub_StrLen SearchNext( xub_StrLen nStartPos );

public:
    SwASC_AttrIter( SwASCWriter& rWrt, const SwTxtNode& rNd, xub_StrLen nStt );

    void NextPos()      { nAktSwPos = SearchNext( nAktSwPos + 1 ); }

    xub_StrLen WhereNext() const        { return nAktSwPos; }
    BOOL OutAttr( xub_StrLen nSwPos );
};

SwASC_AttrIter::SwASC_AttrIter( SwASCWriter& rWr, const SwTxtNode& rTxtNd,
                                xub_StrLen nStt )
    : rWrt( rWr ), rNd( rTxtNd ), nAktSwPos( 0 )
{
    nAktSwPos = SearchNext( nStt + 1 );
}

xub_StrLen SwASC_AttrIter::SearchNext( xub_StrLen nStartPos )
{
    register xub_StrLen nMinPos = STRING_MAXLEN;
    const SwpHints* pTxtAttrs = rNd.GetpSwpHints();
    if( pTxtAttrs )
    {
        register USHORT i;
        register xub_StrLen nPos;
        const xub_StrLen * pPos;

// kann noch optimiert werden, wenn ausgenutzt wird, dass die TxtAttrs
// nach der Anfangsposition geordnet sind. Dann muessten
// allerdings noch 2 Indices gemerkt werden
        for( i = 0; i < pTxtAttrs->Count(); i++ )
        {
            const SwTxtAttr* pHt = (*pTxtAttrs)[i];
            nPos = *pHt->GetStart();    // gibt erstes Attr-Zeichen
            pPos = pHt->GetEnd();
            if( !pPos )
            {
                if( nPos >= nStartPos && nPos <= nMinPos )
                    nMinPos = nPos;

                if( ( ++nPos ) >= nStartPos && nPos < nMinPos )
                    nMinPos = nPos;
            }
        }
    }
    return nMinPos;
}

BOOL SwASC_AttrIter::OutAttr( xub_StrLen nSwPos )
{
    BOOL bRet = FALSE;
    const SwpHints* pTxtAttrs = rNd.GetpSwpHints();
    if( pTxtAttrs )
    {
        register USHORT i;
        for( i = 0; i < pTxtAttrs->Count(); i++ )
        {
            const SwTxtAttr* pHt = (*pTxtAttrs)[i];
            const xub_StrLen * pEnd = pHt->GetEnd();
            if( !pEnd && nSwPos == *pHt->GetStart() )
            {
                bRet = TRUE;
                String sOut;
                switch( pHt->Which() )
                {
                case RES_TXTATR_FIELD:
                    sOut = ((SwTxtFld*)pHt)->GetFld().GetFld()->Expand();
                    break;

                case RES_TXTATR_HARDBLANK:
                    sOut = ((SwTxtHardBlank*)pHt)->GetChar();
                    break;

                case RES_TXTATR_FTN:
                    {
                        const SwFmtFtn& rFtn = pHt->GetFtn();
                        if( rFtn.GetNumStr().Len() )
                            sOut = rFtn.GetNumStr();
                        else if( rFtn.IsEndNote() )
                            sOut = rWrt.pDoc->GetEndNoteInfo().aFmt.
                                            GetNumStr( rFtn.GetNumber() );
                        else
                            sOut = rWrt.pDoc->GetFtnInfo().aFmt.
                                            GetNumStr( rFtn.GetNumber() );
                    }
                    break;
                }
                if( sOut.Len() )
                    rWrt.Strm().WriteUnicodeOrByteText( sOut );
            }
            else if( nSwPos < *pHt->GetStart() )
                break;
        }
    }
    return bRet;
}

//------------------------
/* Ausgabe der Nodes */
//------------------------

static Writer& OutASC_SwTxtNode( Writer& rWrt, SwCntntNode& rNode )
{
    const SwTxtNode& rNd = (SwTxtNode&)rNode;

    xub_StrLen nStrPos = rWrt.pCurPam->GetPoint()->nContent.GetIndex();
    xub_StrLen nNodeEnde = rNd.Len(), nEnde = nNodeEnde;
    BOOL bLastNd =  rWrt.pCurPam->GetPoint()->nNode == rWrt.pCurPam->GetMark()->nNode;
    if( bLastNd )
        nEnde = rWrt.pCurPam->GetMark()->nContent.GetIndex();

    SwASC_AttrIter aAttrIter( (SwASCWriter&)rWrt, rNd, nStrPos );

    if( !nStrPos )
        rWrt.Strm().WriteUnicodeOrByteText( rNd.GetNumString() );

    String aStr( rNd.GetTxt() );
    if( rWrt.bASCII_ParaAsBlanc )
        aStr.SearchAndReplaceAll( 0x0A, ' ' );

    do {
        xub_StrLen nNextAttr = aAttrIter.WhereNext();

        if( nNextAttr > nEnde )
            nNextAttr = nEnde;

        if( !aAttrIter.OutAttr( nStrPos ))
            rWrt.Strm().WriteUnicodeOrByteText(
                                aStr.Copy( nStrPos, nNextAttr - nStrPos ));
        nStrPos = nNextAttr;
        aAttrIter.NextPos();
    } while( nStrPos < nEnde );

    if( !bLastNd ||
        ( !rWrt.bWriteClipboardDoc && !rWrt.bASCII_NoLastLineEnd )
            && !nStrPos && nEnde == nNodeEnde )
        rWrt.Strm().WriteUnicodeOrByteText( ((SwASCWriter&)rWrt).GetLineEnd());

    return rWrt;
}

/*
 * lege hier jetzt die Tabellen fuer die ASCII-Funktions-Pointer auf
 * die Ausgabe-Funktionen an.
 * Es sind lokale Strukturen, die nur innerhalb der ASCII-DLL
 * bekannt sein muessen.
 */

SwNodeFnTab aASCNodeFnTab = {
/* RES_TXTNODE  */                   OutASC_SwTxtNode,
/* RES_GRFNODE  */                   0,
/* RES_OLENODE  */                   0
};

<commit_msg>INTEGRATION: CWS mullingarfilterteam18 (1.4.278); FILE MERGED 2003/11/19 09:14:55 cmc 1.4.278.1: #i9055# clean warnings from ascii dir<commit_after>/*************************************************************************
 *
 *  $RCSfile: ascatr.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2004-01-13 16:36:19 $
 *
 *  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 _HINTIDS_HXX
#include <hintids.hxx>
#endif

#ifndef _STREAM_HXX //autogen
#include <tools/stream.hxx>
#endif
#ifndef _SVSTDARR_HXX
#define _SVSTDARR_USHORTS
#include <svtools/svstdarr.hxx>
#endif
#ifndef _SVX_FONTITEM_HXX
#include <svx/fontitem.hxx>
#endif

#ifndef _PAM_HXX
#include <pam.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _NDTXT_HXX
#include <ndtxt.hxx>
#endif
#ifndef _WRTASC_HXX
#include <wrtasc.hxx>
#endif
#ifndef _TXATBASE_HXX
#include <txatbase.hxx>
#endif
#ifndef _FCHRFMT_HXX
#include <fchrfmt.hxx>
#endif
#ifndef _TXTFLD_HXX
#include <txtfld.hxx>
#endif
#ifndef _TXTATR_HXX
#include <txtatr.hxx>
#endif
#ifndef _FMTFTN_HXX
#include <fmtftn.hxx>
#endif
#ifndef _CHARFMT_HXX
#include <charfmt.hxx>
#endif
#ifndef _FMTFLD_HXX
#include <fmtfld.hxx>
#endif
#ifndef _FLDBAS_HXX
#include <fldbas.hxx>
#endif
#ifndef _FTNINFO_HXX //autogen
#include <ftninfo.hxx>
#endif

/*
 * Dieses File enthaelt alle Ausgabe-Funktionen des ASCII-Writers;
 * fuer alle Nodes, Attribute, Formate und Chars.
 */

class SwASC_AttrIter
{
    SwASCWriter& rWrt;
    const SwTxtNode& rNd;
    xub_StrLen nAktSwPos;

    xub_StrLen SearchNext( xub_StrLen nStartPos );

public:
    SwASC_AttrIter( SwASCWriter& rWrt, const SwTxtNode& rNd, xub_StrLen nStt );

    void NextPos()      { nAktSwPos = SearchNext( nAktSwPos + 1 ); }

    xub_StrLen WhereNext() const        { return nAktSwPos; }
    BOOL OutAttr( xub_StrLen nSwPos );
};

SwASC_AttrIter::SwASC_AttrIter( SwASCWriter& rWr, const SwTxtNode& rTxtNd,
                                xub_StrLen nStt )
    : rWrt( rWr ), rNd( rTxtNd ), nAktSwPos( 0 )
{
    nAktSwPos = SearchNext( nStt + 1 );
}

xub_StrLen SwASC_AttrIter::SearchNext( xub_StrLen nStartPos )
{
    register xub_StrLen nMinPos = STRING_MAXLEN;
    const SwpHints* pTxtAttrs = rNd.GetpSwpHints();
    if( pTxtAttrs )
    {
        register USHORT i;
        register xub_StrLen nPos;
        const xub_StrLen * pPos;

// kann noch optimiert werden, wenn ausgenutzt wird, dass die TxtAttrs
// nach der Anfangsposition geordnet sind. Dann muessten
// allerdings noch 2 Indices gemerkt werden
        for( i = 0; i < pTxtAttrs->Count(); i++ )
        {
            const SwTxtAttr* pHt = (*pTxtAttrs)[i];
            nPos = *pHt->GetStart();    // gibt erstes Attr-Zeichen
            pPos = pHt->GetEnd();
            if( !pPos )
            {
                if( nPos >= nStartPos && nPos <= nMinPos )
                    nMinPos = nPos;

                if( ( ++nPos ) >= nStartPos && nPos < nMinPos )
                    nMinPos = nPos;
            }
        }
    }
    return nMinPos;
}

BOOL SwASC_AttrIter::OutAttr( xub_StrLen nSwPos )
{
    BOOL bRet = FALSE;
    const SwpHints* pTxtAttrs = rNd.GetpSwpHints();
    if( pTxtAttrs )
    {
        register USHORT i;
        for( i = 0; i < pTxtAttrs->Count(); i++ )
        {
            const SwTxtAttr* pHt = (*pTxtAttrs)[i];
            const xub_StrLen * pEnd = pHt->GetEnd();
            if( !pEnd && nSwPos == *pHt->GetStart() )
            {
                bRet = TRUE;
                String sOut;
                switch( pHt->Which() )
                {
                case RES_TXTATR_FIELD:
                    sOut = ((SwTxtFld*)pHt)->GetFld().GetFld()->Expand();
                    break;

                case RES_TXTATR_HARDBLANK:
                    sOut = ((SwTxtHardBlank*)pHt)->GetChar();
                    break;

                case RES_TXTATR_FTN:
                    {
                        const SwFmtFtn& rFtn = pHt->GetFtn();
                        if( rFtn.GetNumStr().Len() )
                            sOut = rFtn.GetNumStr();
                        else if( rFtn.IsEndNote() )
                            sOut = rWrt.pDoc->GetEndNoteInfo().aFmt.
                                            GetNumStr( rFtn.GetNumber() );
                        else
                            sOut = rWrt.pDoc->GetFtnInfo().aFmt.
                                            GetNumStr( rFtn.GetNumber() );
                    }
                    break;
                }
                if( sOut.Len() )
                    rWrt.Strm().WriteUnicodeOrByteText( sOut );
            }
            else if( nSwPos < *pHt->GetStart() )
                break;
        }
    }
    return bRet;
}

//------------------------
/* Ausgabe der Nodes */
//------------------------

static Writer& OutASC_SwTxtNode( Writer& rWrt, SwCntntNode& rNode )
{
    const SwTxtNode& rNd = (SwTxtNode&)rNode;

    xub_StrLen nStrPos = rWrt.pCurPam->GetPoint()->nContent.GetIndex();
    xub_StrLen nNodeEnde = rNd.Len(), nEnde = nNodeEnde;
    BOOL bLastNd =  rWrt.pCurPam->GetPoint()->nNode == rWrt.pCurPam->GetMark()->nNode;
    if( bLastNd )
        nEnde = rWrt.pCurPam->GetMark()->nContent.GetIndex();

    SwASC_AttrIter aAttrIter( (SwASCWriter&)rWrt, rNd, nStrPos );

    if( !nStrPos )
        rWrt.Strm().WriteUnicodeOrByteText( rNd.GetNumString() );

    String aStr( rNd.GetTxt() );
    if( rWrt.bASCII_ParaAsBlanc )
        aStr.SearchAndReplaceAll( 0x0A, ' ' );

    do {
        xub_StrLen nNextAttr = aAttrIter.WhereNext();

        if( nNextAttr > nEnde )
            nNextAttr = nEnde;

        if( !aAttrIter.OutAttr( nStrPos ))
            rWrt.Strm().WriteUnicodeOrByteText(
                                aStr.Copy( nStrPos, nNextAttr - nStrPos ));
        nStrPos = nNextAttr;
        aAttrIter.NextPos();
    } while( nStrPos < nEnde );

    if( !bLastNd ||
        ( !rWrt.bWriteClipboardDoc && !rWrt.bASCII_NoLastLineEnd )
            && !nStrPos && nEnde == nNodeEnde )
        rWrt.Strm().WriteUnicodeOrByteText( ((SwASCWriter&)rWrt).GetLineEnd());

    return rWrt;
}

/*
 * lege hier jetzt die Tabellen fuer die ASCII-Funktions-Pointer auf
 * die Ausgabe-Funktionen an.
 * Es sind lokale Strukturen, die nur innerhalb der ASCII-DLL
 * bekannt sein muessen.
 */

SwNodeFnTab aASCNodeFnTab = {
/* RES_TXTNODE  */                   OutASC_SwTxtNode,
/* RES_GRFNODE  */                   0,
/* RES_OLENODE  */                   0
};

<|endoftext|>


<commit_before>// RUN: %clangxx_asan -O0 %s -o %t && not %run %t 2>&1 | FileCheck %s --check-prefix=CHECK-%os --check-prefix=CHECK
// RUN: %clangxx_asan -O1 %s -o %t && not %run %t 2>&1 | FileCheck %s --check-prefix=CHECK-%os --check-prefix=CHECK
// RUN: %clangxx_asan -O2 %s -o %t && not %run %t 2>&1 | FileCheck %s --check-prefix=CHECK-%os --check-prefix=CHECK
// RUN: %clangxx_asan -O3 %s -o %t && not %run %t 2>&1 | FileCheck %s --check-prefix=CHECK-%os --check-prefix=CHECK

__attribute__((noinline))
static void NullDeref(int *ptr) {
  // CHECK: ERROR: AddressSanitizer: SEGV on unknown address
  // CHECK:   {{0x0*000.. .*pc 0x.*}}
  ptr[10]++;  // BOOM
  // atos on Mac cannot extract the symbol name correctly.
  // CHECK-Linux: {{    #0 0x.* in NullDeref.*null_deref.cc:}}[[@LINE-2]]
  // CHECK-Darwin: {{    #0 0x.* in .*NullDeref.*null_deref.cc:}}[[@LINE-3]]
}
int main() {
  NullDeref((int*)0);
  // CHECK: {{    #1 0x.* in main.*null_deref.cc:}}[[@LINE-1]]
  // CHECK: AddressSanitizer can not provide additional info.
}
<commit_msg>Add FreeBSD support to the address sanitizer's null_deref.cc test case Differential Revision: http://reviews.llvm.org/D4421<commit_after>// RUN: %clangxx_asan -O0 %s -o %t && not %run %t 2>&1 | FileCheck %s
// RUN: %clangxx_asan -O1 %s -o %t && not %run %t 2>&1 | FileCheck %s
// RUN: %clangxx_asan -O2 %s -o %t && not %run %t 2>&1 | FileCheck %s
// RUN: %clangxx_asan -O3 %s -o %t && not %run %t 2>&1 | FileCheck %s

__attribute__((noinline))
static void NullDeref(int *ptr) {
  // CHECK: ERROR: AddressSanitizer: SEGV on unknown address
  // CHECK:   {{0x0*000.. .*pc 0x.*}}
  ptr[10]++;  // BOOM
  // atos on Mac cannot extract the symbol name correctly. Also, on FreeBSD 9.2
  // the demangling function rejects local names with 'L' in front of them.
  // CHECK: {{    #0 0x.* in .*NullDeref.*null_deref.cc:}}[[@LINE-3]]
}
int main() {
  NullDeref((int*)0);
  // CHECK: {{    #1 0x.* in main.*null_deref.cc:}}[[@LINE-1]]
  // CHECK: AddressSanitizer can not provide additional info.
}
<|endoftext|>


<commit_before>/*
 *
 * Copyright 2019 gRPC authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include "src/core/lib/iomgr/executor/mpmcqueue.h"

#include <grpc/grpc.h>

#include "src/core/lib/gprpp/thd.h"
#include "test/core/util/test_config.h"

#define THREAD_LARGE_ITERATION 10000

// Testing items for queue
struct WorkItem {
  int index;
  bool done;

  WorkItem(int i) : index(i) { done = false; }
};

// Thread for put items into queue
class ProducerThread {
 public:
  ProducerThread(grpc_core::InfLenFIFOQueue* queue, int start_index,
                 int num_items)
      : start_index_(start_index), num_items_(num_items), queue_(queue) {
    items_ = nullptr;
    thd_ = grpc_core::Thread(
        "mpmcq_test_mt_put_thd",
        [](void* th) { static_cast<ProducerThread*>(th)->Run(); }, this);
  }
  ~ProducerThread() {
    for (int i = 0; i < num_items_; ++i) {
      GPR_ASSERT(items_[i]->done);
      grpc_core::Delete(items_[i]);
    }
    gpr_free(items_);
  }

  void Start() { thd_.Start(); }
  void Join() { thd_.Join(); }

 private:
  void Run() {
    items_ = static_cast<WorkItem**>(gpr_zalloc(num_items_));
    for (int i = 0; i < num_items_; ++i) {
      items_[i] = grpc_core::New<WorkItem>(start_index_ + i);
      queue_->Put(items_[i]);
    }
  }

  int start_index_;
  int num_items_;
  grpc_core::InfLenFIFOQueue* queue_;
  grpc_core::Thread thd_;
  WorkItem** items_;
};

static void ConsumerThread(void* args) {
  grpc_core::InfLenFIFOQueue* queue =
      static_cast<grpc_core::InfLenFIFOQueue*>(args);

  // count number of Get() called in this thread
  int count = 0;

  WorkItem* item;
  while ((item = static_cast<WorkItem*>(queue->Get())) != nullptr) {
    count++;
    GPR_ASSERT(!item->done);
    item->done = true;
  }

  gpr_log(GPR_DEBUG, "ConsumerThread: %d times of Get() called.", count);
}

static void test_get_empty(void) {
  gpr_log(GPR_INFO, "test_get_empty");
  grpc_core::InfLenFIFOQueue queue;
  GPR_ASSERT(queue.count() == 0);
  const int num_threads = 10;
  grpc_core::Thread thds[num_threads];

  // Fork threads. Threads should block at the beginning since queue is empty.
  for (int i = 0; i < num_threads; ++i) {
    thds[i] = grpc_core::Thread("mpmcq_test_ge_thd", ConsumerThread, &queue);
    thds[i].Start();
  }

  WorkItem** items =
      static_cast<WorkItem**>(gpr_zalloc(THREAD_LARGE_ITERATION));
  for (int i = 0; i < THREAD_LARGE_ITERATION; ++i) {
    items[i] = grpc_core::New<WorkItem>(i);
    queue.Put(static_cast<void*>(items[i]));
  }

  gpr_log(GPR_DEBUG, "Terminating threads...");
  for (int i = 0; i < num_threads; ++i) {
    queue.Put(nullptr);
  }
  for (int i = 0; i < num_threads; ++i) {
    thds[i].Join();
  }
  gpr_log(GPR_DEBUG, "Checking and Cleaning Up...");
  for (int i = 0; i < THREAD_LARGE_ITERATION; ++i) {
    GPR_ASSERT(items[i]->done);
    grpc_core::Delete(items[i]);
  }
  gpr_free(items);
  gpr_log(GPR_DEBUG, "Done.");
}

static void test_FIFO(void) {
  gpr_log(GPR_INFO, "test_FIFO");
  grpc_core::InfLenFIFOQueue large_queue;
  for (int i = 0; i < THREAD_LARGE_ITERATION; ++i) {
    large_queue.Put(static_cast<void*>(grpc_core::New<WorkItem>(i)));
  }
  GPR_ASSERT(large_queue.count() == THREAD_LARGE_ITERATION);
  for (int i = 0; i < THREAD_LARGE_ITERATION; ++i) {
    WorkItem* item = static_cast<WorkItem*>(large_queue.Get());
    GPR_ASSERT(i == item->index);
    grpc_core::Delete(item);
  }
}

static void test_many_thread(void) {
  gpr_log(GPR_INFO, "test_many_thread");
  const int num_work_thd = 10;
  const int num_get_thd = 20;
  grpc_core::InfLenFIFOQueue queue;
  ProducerThread** work_thds =
      static_cast<ProducerThread**>(gpr_zalloc(num_work_thd));
  grpc_core::Thread get_thds[num_get_thd];

  gpr_log(GPR_DEBUG, "Fork ProducerThread...");
  for (int i = 0; i < num_work_thd; ++i) {
    work_thds[i] = grpc_core::New<ProducerThread>(
        &queue, i * THREAD_LARGE_ITERATION, THREAD_LARGE_ITERATION);
    work_thds[i]->Start();
  }
  gpr_log(GPR_DEBUG, "ProducerThread Started.");
  gpr_log(GPR_DEBUG, "Fork Getter Thread...");
  for (int i = 0; i < num_get_thd; ++i) {
    get_thds[i] =
        grpc_core::Thread("mpmcq_test_mt_get_thd", ConsumerThread, &queue);
    get_thds[i].Start();
  }
  gpr_log(GPR_DEBUG, "Getter Thread Started.");
  gpr_log(GPR_DEBUG, "Waiting ProducerThread to finish...");
  for (int i = 0; i < num_work_thd; ++i) {
    work_thds[i]->Join();
  }
  gpr_log(GPR_DEBUG, "All ProducerThread Terminated.");
  gpr_log(GPR_DEBUG, "Terminating Getter Thread...");
  for (int i = 0; i < num_get_thd; ++i) {
    queue.Put(nullptr);
  }
  for (int i = 0; i < num_get_thd; ++i) {
    get_thds[i].Join();
  }
  gpr_log(GPR_DEBUG, "All Getter Thread Terminated.");
  gpr_log(GPR_DEBUG, "Checking WorkItems and Cleaning Up...");
  for (int i = 0; i < num_work_thd; ++i) {
    grpc_core::Delete(work_thds[i]);
  }
  gpr_free(work_thds);
  gpr_log(GPR_DEBUG, "Done.");
}

int main(int argc, char** argv) {
  grpc::testing::TestEnvironment env(argc, argv);
  grpc_init();
  gpr_set_log_verbosity(GPR_LOG_SEVERITY_DEBUG);
  test_get_empty();
  test_FIFO();
  test_many_thread();
  grpc_shutdown();
  return 0;
}
<commit_msg>Change to malloc<commit_after>/*
 *
 * Copyright 2019 gRPC authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include "src/core/lib/iomgr/executor/mpmcqueue.h"

#include <grpc/grpc.h>

#include "src/core/lib/gprpp/thd.h"
#include "test/core/util/test_config.h"

#define THREAD_LARGE_ITERATION 10000

// Testing items for queue
struct WorkItem {
  int index;
  bool done;

  WorkItem(int i) : index(i) { done = false; }
};

// Thread for put items into queue
class ProducerThread {
 public:
  ProducerThread(grpc_core::InfLenFIFOQueue* queue, int start_index,
                 int num_items)
      : start_index_(start_index), num_items_(num_items), queue_(queue) {
    items_ = nullptr;
    thd_ = grpc_core::Thread(
        "mpmcq_test_put_thd",
        [](void* th) { static_cast<ProducerThread*>(th)->Run(); }, this);
  }
  ~ProducerThread() {
    for (int i = 0; i < num_items_; ++i) {
      GPR_ASSERT(items_[i]->done);
      grpc_core::Delete(items_[i]);
    }
    gpr_free(items_);
  }

  void Start() { thd_.Start(); }
  void Join() { thd_.Join(); }

 private:
  void Run() {
    items_ =
        static_cast<WorkItem**>(gpr_malloc(num_items_ * sizeof(WorkItem*)));
    for (int i = 0; i < num_items_; ++i) {
      items_[i] = grpc_core::New<WorkItem>(start_index_ + i);
      queue_->Put(items_[i]);
    }
  }

  int start_index_;
  int num_items_;
  grpc_core::InfLenFIFOQueue* queue_;
  grpc_core::Thread thd_;
  WorkItem** items_;
};

static void ConsumerThread(void* args) {
  grpc_core::InfLenFIFOQueue* queue =
      static_cast<grpc_core::InfLenFIFOQueue*>(args);

  // count number of Get() called in this thread
  int count = 0;

  WorkItem* item;
  while ((item = static_cast<WorkItem*>(queue->Get())) != nullptr) {
    count++;
    GPR_ASSERT(!item->done);
    item->done = true;
  }

  gpr_log(GPR_DEBUG, "ConsumerThread: %d times of Get() called.", count);
}

static void test_get_empty(void) {
  gpr_log(GPR_INFO, "test_get_empty");
  grpc_core::InfLenFIFOQueue queue;
  GPR_ASSERT(queue.count() == 0);
  const int num_threads = 10;
  grpc_core::Thread thds[num_threads];

  // Fork threads. Threads should block at the beginning since queue is empty.
  for (int i = 0; i < num_threads; ++i) {
    thds[i] = grpc_core::Thread("mpmcq_test_ge_thd", ConsumerThread, &queue);
    thds[i].Start();
  }

  WorkItem** items = static_cast<WorkItem**>(
      gpr_malloc(THREAD_LARGE_ITERATION * sizeof(WorkItem*)));
  for (int i = 0; i < THREAD_LARGE_ITERATION; ++i) {
    items[i] = grpc_core::New<WorkItem>(i);
    queue.Put(static_cast<void*>(items[i]));
  }

  gpr_log(GPR_DEBUG, "Terminating threads...");
  for (int i = 0; i < num_threads; ++i) {
    queue.Put(nullptr);
  }
  for (int i = 0; i < num_threads; ++i) {
    thds[i].Join();
  }
  gpr_log(GPR_DEBUG, "Checking and Cleaning Up...");
  for (int i = 0; i < THREAD_LARGE_ITERATION; ++i) {
    GPR_ASSERT(items[i]->done);
    grpc_core::Delete(items[i]);
  }
  gpr_free(items);
  gpr_log(GPR_DEBUG, "Done.");
}

static void test_FIFO(void) {
  gpr_log(GPR_INFO, "test_FIFO");
  grpc_core::InfLenFIFOQueue large_queue;
  for (int i = 0; i < THREAD_LARGE_ITERATION; ++i) {
    large_queue.Put(static_cast<void*>(grpc_core::New<WorkItem>(i)));
  }
  GPR_ASSERT(large_queue.count() == THREAD_LARGE_ITERATION);
  for (int i = 0; i < THREAD_LARGE_ITERATION; ++i) {
    WorkItem* item = static_cast<WorkItem*>(large_queue.Get());
    GPR_ASSERT(i == item->index);
    grpc_core::Delete(item);
  }
}

static void test_many_thread(void) {
  gpr_log(GPR_INFO, "test_many_thread");
  const int num_work_thd = 10;
  const int num_get_thd = 20;
  grpc_core::InfLenFIFOQueue queue;
  ProducerThread** work_thds = static_cast<ProducerThread**>(
      gpr_malloc(num_work_thd * sizeof(ProducerThread*)));
  grpc_core::Thread get_thds[num_get_thd];

  gpr_log(GPR_DEBUG, "Fork ProducerThread...");
  for (int i = 0; i < num_work_thd; ++i) {
    work_thds[i] = grpc_core::New<ProducerThread>(
        &queue, i * THREAD_LARGE_ITERATION, THREAD_LARGE_ITERATION);
    work_thds[i]->Start();
  }
  gpr_log(GPR_DEBUG, "ProducerThread Started.");
  gpr_log(GPR_DEBUG, "Fork Getter Thread...");
  for (int i = 0; i < num_get_thd; ++i) {
    get_thds[i] =
        grpc_core::Thread("mpmcq_test_mt_get_thd", ConsumerThread, &queue);
    get_thds[i].Start();
  }
  gpr_log(GPR_DEBUG, "Getter Thread Started.");
  gpr_log(GPR_DEBUG, "Waiting ProducerThread to finish...");
  for (int i = 0; i < num_work_thd; ++i) {
    work_thds[i]->Join();
  }
  gpr_log(GPR_DEBUG, "All ProducerThread Terminated.");
  gpr_log(GPR_DEBUG, "Terminating Getter Thread...");
  for (int i = 0; i < num_get_thd; ++i) {
    queue.Put(nullptr);
  }
  for (int i = 0; i < num_get_thd; ++i) {
    get_thds[i].Join();
  }
  gpr_log(GPR_DEBUG, "All Getter Thread Terminated.");
  gpr_log(GPR_DEBUG, "Checking WorkItems and Cleaning Up...");
  for (int i = 0; i < num_work_thd; ++i) {
    grpc_core::Delete(work_thds[i]);
  }
  gpr_free(work_thds);
  gpr_log(GPR_DEBUG, "Done.");
}

int main(int argc, char** argv) {
  grpc::testing::TestEnvironment env(argc, argv);
  grpc_init();
  gpr_set_log_verbosity(GPR_LOG_SEVERITY_DEBUG);
  test_get_empty();
  test_FIFO();
  test_many_thread();
  grpc_shutdown();
  return 0;
}
<|endoftext|>


<commit_before>#include "ai.h"
#include <iostream>
#include <stdlib.h>
#include <time.h>

using namespace BWAPI;
using namespace Filter;

// Global variables.
bool supplyNeeded;
int infantryBuildingCheckTimer;
int infantryBuildingCost;
int infantryBuildingLimit;
int infantryCost;
int resourceDepotBuildingCheckTimer;
int resourceDepotBuildingCost;
int resourceDepotBuildingLimit;
int savingMinerals;
int supplyCheckTimer;
int workerLimit;
Race playerRace;
static int infantryBuildingChecked;
static int resourceDepotBuildingChecked;
static int supplyChecked;
UnitType infantryBuilding;
UnitType infantryType;
UnitType resourceDepotBuilding;
UnitType supplyProviderType;
UnitType workerType;

void ai::onEnd(bool isWinner){
}

void ai::onFrame(){
    int frameCount = Broodwar->getFrameCount();

    if(!Broodwar->self()
      || frameCount % Broodwar->getLatencyFrames() != 0
      || Broodwar->isPaused()
      || Broodwar->isReplay()){
        return;
    }

    int infantryBuildingCount = Broodwar->self()->allUnitCount(infantryBuilding);
    int minerals = Broodwar->self()->minerals();
    int resourceDepotBuildingCount = Broodwar->self()->allUnitCount(resourceDepotBuilding);
    int supplyTotal = Broodwar->self()->supplyTotal();
    int supplyUsed = Broodwar->self()->supplyUsed();
    int workerCount = Broodwar->self()->allUnitCount(workerType);

    int supplyCutoff = (int)(supplyUsed / 10);
    if(supplyCutoff < 4){
        supplyCutoff = 4;
    }

    if(supplyTotal < 400
      && supplyTotal - supplyUsed <= supplyCutoff
      && Broodwar->self()->incompleteUnitCount(supplyProviderType) == 0){
        savingMinerals = 100;
        supplyNeeded = true;

    }else{
        savingMinerals = 0;
        supplyNeeded = false;
    }

    if(minerals >= infantryBuildingCost
      && infantryBuildingCount < infantryBuildingLimit){
        savingMinerals += infantryBuildingCost;
    }
    if(minerals >= resourceDepotBuildingCost
      && resourceDepotBuildingCount < resourceDepotBuildingLimit){
        savingMinerals += resourceDepotBuildingCost;
    }

    for(auto &unit : Broodwar->self()->getUnits()){
        if(!unit->exists()
          || !unit->isCompleted()
          || unit->isConstructing()
          || unit->isLoaded()
          || unit->isLockedDown()
          || unit->isMaelstrommed()
          || !unit->isPowered()
          || unit->isStasised()
          || unit->isStuck()){
            continue;
        }

        // Setup unit information variables.
        bool unitIsIdle = unit->isIdle();
        UnitType unitType = unit->getType();

        // Handle workers.
        if(unitType.isWorker()){
            // Handle insufficient supply by building Pylon or building Supply Depot.
            if(playerRace != Races::Zerg
              && supplyNeeded
              && minerals >= 100
              && supplyChecked + supplyCheckTimer < frameCount){
                supplyChecked = frameCount;

                Unit supplyBuilder = unit->getClosestUnit(GetType == supplyProviderType.whatBuilds().first
                  && (IsIdle || IsGatheringMinerals)
                  && IsOwned);

                buildBuilding(
                  supplyBuilder,
                  supplyProviderType
                );

            // Build Command Centers, Hatcheries, and Nexuses.
            }else if(resourceDepotBuildingCount < resourceDepotBuildingLimit
              && minerals >= resourceDepotBuildingCost
              && resourceDepotBuildingChecked + resourceDepotBuildingCheckTimer < frameCount){
                resourceDepotBuildingChecked = frameCount;

                buildBuilding(
                  unit,
                  resourceDepotBuilding
                );

            // Build Barracks/Gateway/Spawning Pool.
            }else if(infantryBuildingCount < infantryBuildingLimit
              && minerals >= infantryBuildingCost
              && infantryBuildingChecked + infantryBuildingCheckTimer < frameCount){
                infantryBuildingChecked = frameCount;

                buildBuilding(
                  unit,
                  infantryBuilding
                );

            }else if(unitIsIdle){
                // Return resources.
                if(unit->isCarryingMinerals()
                  || unit->isCarryingGas()){
                    unit->returnCargo();

                // Gather resources.
                }else{
                    unit->gather(unit->getClosestUnit(IsMineralField || IsRefinery));
                }
            }

        }else if(unitIsIdle){
            // Handle Command Centers, Hatcheries, and Nexuses.
            if(unitType.isResourceDepot()){
                if(playerRace == Races::Zerg
                  && supplyNeeded
                  && playerRace == Races::Zerg
                  && minerals >= 100
                  && supplyChecked + supplyCheckTimer < frameCount){
                    supplyChecked = frameCount;

                    // Train Overlords.
                    unit->train(supplyProviderType);

                }else if(workerCount < workerLimit
                  && minerals >= savingMinerals + 50){
                    // Train workers.
                    unit->train(workerType);

                }else if(playerRace == Races::Zerg
                  && minerals >= savingMinerals + infantryCost){
                    // Train Zerglings.
                    unit->train(infantryType);
                }

            // Handle Barracks and Gateways.
            }else if(playerRace != Races::Zerg
              && unit->canTrain(infantryType)){
                if(minerals >= savingMinerals + infantryCost){
                    // Train Marines and Zealots.
                    unit->train(infantryType);
                }

            // Everything else should attack-move scout.
            }else{
                Position position = unit->getPosition();
                position.x += rand() % 501 - 250;
                position.y += rand() % 501 - 250;
                if(!unit->attack(position)){
                    unit->move(position);
                }
            }
        }
    }
}

void ai::onNukeDetect(BWAPI::Position target){
}

void ai::onPlayerLeft(BWAPI::Player player){
}

void ai::onReceiveText(BWAPI::Player player, std::string text){
}

void ai::onSaveGame(std::string gameName){
}

void ai::onSendText(std::string text){
    Broodwar->sendText("%s", text.c_str());
}

void ai::onStart(){
    Broodwar->setCommandOptimizationLevel(1);
    srand(time(NULL));

    // Setup global variables.
    infantryBuildingChecked = 0;
    infantryBuildingCheckTimer = 1900;
    playerRace = Broodwar->self()->getRace();
    resourceDepotBuildingChecked = 0;
    resourceDepotBuildingCheckTimer = 1900;
    savingMinerals = 0;
    supplyChecked = 0;
    supplyCheckTimer = 500;
    supplyNeeded = false;
    supplyProviderType = playerRace.getSupplyProvider();
    workerLimit = 25;

    workerType = playerRace.getWorker();

    // Handle race-specific stuff.
    if(playerRace == Races::Zerg){
        infantryBuilding = UnitTypes::Zerg_Spawning_Pool;
        infantryBuildingCost = 200;
        infantryBuildingLimit = 1;
        infantryCost = 50;
        infantryType = UnitTypes::Zerg_Zergling;
        resourceDepotBuilding = UnitTypes::Zerg_Hatchery;
        resourceDepotBuildingCost = 300;
        resourceDepotBuildingLimit = 5;

    }else if(playerRace == Races::Terran){
        infantryBuilding = UnitTypes::Terran_Barracks;
        infantryBuildingCost = 150;
        infantryBuildingLimit = 5;
        infantryCost = 50;
        infantryType = UnitTypes::Terran_Marine;
        resourceDepotBuilding = UnitTypes::Terran_Command_Center;
        resourceDepotBuildingCost = 400;
        resourceDepotBuildingLimit = 1;

    }else{
        infantryBuilding = UnitTypes::Protoss_Gateway;
        infantryBuildingCost = 200;
        infantryBuildingLimit = 5;
        infantryCost = 100;
        infantryType = UnitTypes::Protoss_Zealot;
        resourceDepotBuilding = UnitTypes::Protoss_Nexus;
        resourceDepotBuildingCost = 400;
        resourceDepotBuildingLimit = 1;
    }

    Broodwar->sendText("glhf");
}

void ai::onUnitComplete(BWAPI::Unit unit){
}

void ai::onUnitCreate(BWAPI::Unit unit){
}

void ai::onUnitDestroy(BWAPI::Unit unit){
}

void ai::onUnitDiscover(BWAPI::Unit unit){
}

void ai::onUnitEvade(BWAPI::Unit unit){
}

void ai::onUnitHide(BWAPI::Unit unit){
}

void ai::onUnitMorph(BWAPI::Unit unit){
}

void ai::onUnitRenegade(BWAPI::Unit unit){
}

void ai::onUnitShow(BWAPI::Unit unit){
}

bool buildBuilding(Unit builder, UnitType building){
    TilePosition targetBuildLocation = Broodwar->getBuildLocation(
      builing,
      builder->getTilePosition()
    );

    if(targetBuildLocation){
        return builder->build(
          building,
          targetBuildLocation
        );
    }

    return false;
}
<commit_msg>replaced hardcoded supply cost with savingMinerals check<commit_after>#include "ai.h"
#include <iostream>
#include <stdlib.h>
#include <time.h>

using namespace BWAPI;
using namespace Filter;

// Global variables.
bool supplyNeeded;
int infantryBuildingCheckTimer;
int infantryBuildingCost;
int infantryBuildingLimit;
int infantryCost;
int resourceDepotBuildingCheckTimer;
int resourceDepotBuildingCost;
int resourceDepotBuildingLimit;
int savingMinerals;
int supplyCheckTimer;
int workerLimit;
Race playerRace;
static int infantryBuildingChecked;
static int resourceDepotBuildingChecked;
static int supplyChecked;
UnitType infantryBuilding;
UnitType infantryType;
UnitType resourceDepotBuilding;
UnitType supplyProviderType;
UnitType workerType;

void ai::onEnd(bool isWinner){
}

void ai::onFrame(){
    int frameCount = Broodwar->getFrameCount();

    if(!Broodwar->self()
      || frameCount % Broodwar->getLatencyFrames() != 0
      || Broodwar->isPaused()
      || Broodwar->isReplay()){
        return;
    }

    int infantryBuildingCount = Broodwar->self()->allUnitCount(infantryBuilding);
    int minerals = Broodwar->self()->minerals();
    int resourceDepotBuildingCount = Broodwar->self()->allUnitCount(resourceDepotBuilding);
    int supplyTotal = Broodwar->self()->supplyTotal();
    int supplyUsed = Broodwar->self()->supplyUsed();
    int workerCount = Broodwar->self()->allUnitCount(workerType);

    int supplyCutoff = (int)(supplyUsed / 10);
    if(supplyCutoff < 4){
        supplyCutoff = 4;
    }

    if(supplyTotal < 400
      && supplyTotal - supplyUsed <= supplyCutoff
      && Broodwar->self()->incompleteUnitCount(supplyProviderType) == 0){
        savingMinerals = 100;
        supplyNeeded = true;

    }else{
        savingMinerals = 0;
        supplyNeeded = false;
    }

    if(minerals >= infantryBuildingCost
      && infantryBuildingCount < infantryBuildingLimit){
        savingMinerals += infantryBuildingCost;
    }
    if(minerals >= resourceDepotBuildingCost
      && resourceDepotBuildingCount < resourceDepotBuildingLimit){
        savingMinerals += resourceDepotBuildingCost;
    }

    for(auto &unit : Broodwar->self()->getUnits()){
        if(!unit->exists()
          || !unit->isCompleted()
          || unit->isConstructing()
          || unit->isLoaded()
          || unit->isLockedDown()
          || unit->isMaelstrommed()
          || !unit->isPowered()
          || unit->isStasised()
          || unit->isStuck()){
            continue;
        }

        // Setup unit information variables.
        bool unitIsIdle = unit->isIdle();
        UnitType unitType = unit->getType();

        // Handle workers.
        if(unitType.isWorker()){
            // Handle insufficient supply by building Pylon or building Supply Depot.
            if(playerRace != Races::Zerg
              && supplyNeeded
              && minerals >= savingMinerals
              && supplyChecked + supplyCheckTimer < frameCount){
                supplyChecked = frameCount;

                Unit supplyBuilder = unit->getClosestUnit(GetType == supplyProviderType.whatBuilds().first
                  && (IsIdle || IsGatheringMinerals)
                  && IsOwned);

                buildBuilding(
                  supplyBuilder,
                  supplyProviderType
                );

            // Build Command Centers, Hatcheries, and Nexuses.
            }else if(resourceDepotBuildingCount < resourceDepotBuildingLimit
              && minerals >= resourceDepotBuildingCost
              && resourceDepotBuildingChecked + resourceDepotBuildingCheckTimer < frameCount){
                resourceDepotBuildingChecked = frameCount;

                buildBuilding(
                  unit,
                  resourceDepotBuilding
                );

            // Build Barracks/Gateway/Spawning Pool.
            }else if(infantryBuildingCount < infantryBuildingLimit
              && minerals >= infantryBuildingCost
              && infantryBuildingChecked + infantryBuildingCheckTimer < frameCount){
                infantryBuildingChecked = frameCount;

                buildBuilding(
                  unit,
                  infantryBuilding
                );

            }else if(unitIsIdle){
                // Return resources.
                if(unit->isCarryingMinerals()
                  || unit->isCarryingGas()){
                    unit->returnCargo();

                // Gather resources.
                }else{
                    unit->gather(unit->getClosestUnit(IsMineralField || IsRefinery));
                }
            }

        }else if(unitIsIdle){
            // Handle Command Centers, Hatcheries, and Nexuses.
            if(unitType.isResourceDepot()){
                if(playerRace == Races::Zerg
                  && supplyNeeded
                  && playerRace == Races::Zerg
                  && minerals >= savingMinerals
                  && supplyChecked + supplyCheckTimer < frameCount){
                    supplyChecked = frameCount;

                    // Train Overlords.
                    unit->train(supplyProviderType);

                }else if(workerCount < workerLimit
                  && minerals >= savingMinerals + 50){
                    // Train workers.
                    unit->train(workerType);

                }else if(playerRace == Races::Zerg
                  && minerals >= savingMinerals + infantryCost){
                    // Train Zerglings.
                    unit->train(infantryType);
                }

            // Handle Barracks and Gateways.
            }else if(playerRace != Races::Zerg
              && unit->canTrain(infantryType)){
                if(minerals >= savingMinerals + infantryCost){
                    // Train Marines and Zealots.
                    unit->train(infantryType);
                }

            // Everything else should attack-move scout.
            }else{
                Position position = unit->getPosition();
                position.x += rand() % 501 - 250;
                position.y += rand() % 501 - 250;
                if(!unit->attack(position)){
                    unit->move(position);
                }
            }
        }
    }
}

void ai::onNukeDetect(BWAPI::Position target){
}

void ai::onPlayerLeft(BWAPI::Player player){
}

void ai::onReceiveText(BWAPI::Player player, std::string text){
}

void ai::onSaveGame(std::string gameName){
}

void ai::onSendText(std::string text){
    Broodwar->sendText("%s", text.c_str());
}

void ai::onStart(){
    Broodwar->setCommandOptimizationLevel(1);
    srand(time(NULL));

    // Setup global variables.
    infantryBuildingChecked = 0;
    infantryBuildingCheckTimer = 1900;
    playerRace = Broodwar->self()->getRace();
    resourceDepotBuildingChecked = 0;
    resourceDepotBuildingCheckTimer = 1900;
    savingMinerals = 0;
    supplyChecked = 0;
    supplyCheckTimer = 500;
    supplyNeeded = false;
    supplyProviderType = playerRace.getSupplyProvider();
    workerLimit = 25;

    workerType = playerRace.getWorker();

    // Handle race-specific stuff.
    if(playerRace == Races::Zerg){
        infantryBuilding = UnitTypes::Zerg_Spawning_Pool;
        infantryBuildingCost = 200;
        infantryBuildingLimit = 1;
        infantryCost = 50;
        infantryType = UnitTypes::Zerg_Zergling;
        resourceDepotBuilding = UnitTypes::Zerg_Hatchery;
        resourceDepotBuildingCost = 300;
        resourceDepotBuildingLimit = 5;

    }else if(playerRace == Races::Terran){
        infantryBuilding = UnitTypes::Terran_Barracks;
        infantryBuildingCost = 150;
        infantryBuildingLimit = 5;
        infantryCost = 50;
        infantryType = UnitTypes::Terran_Marine;
        resourceDepotBuilding = UnitTypes::Terran_Command_Center;
        resourceDepotBuildingCost = 400;
        resourceDepotBuildingLimit = 1;

    }else{
        infantryBuilding = UnitTypes::Protoss_Gateway;
        infantryBuildingCost = 200;
        infantryBuildingLimit = 5;
        infantryCost = 100;
        infantryType = UnitTypes::Protoss_Zealot;
        resourceDepotBuilding = UnitTypes::Protoss_Nexus;
        resourceDepotBuildingCost = 400;
        resourceDepotBuildingLimit = 1;
    }

    Broodwar->sendText("glhf");
}

void ai::onUnitComplete(BWAPI::Unit unit){
}

void ai::onUnitCreate(BWAPI::Unit unit){
}

void ai::onUnitDestroy(BWAPI::Unit unit){
}

void ai::onUnitDiscover(BWAPI::Unit unit){
}

void ai::onUnitEvade(BWAPI::Unit unit){
}

void ai::onUnitHide(BWAPI::Unit unit){
}

void ai::onUnitMorph(BWAPI::Unit unit){
}

void ai::onUnitRenegade(BWAPI::Unit unit){
}

void ai::onUnitShow(BWAPI::Unit unit){
}

bool buildBuilding(Unit builder, UnitType building){
    TilePosition targetBuildLocation = Broodwar->getBuildLocation(
      builing,
      builder->getTilePosition()
    );

    if(targetBuildLocation){
        return builder->build(
          building,
          targetBuildLocation
        );
    }

    return false;
}
<|endoftext|>


<commit_before>#include "ai.h"
#include <iostream>

using namespace BWAPI;
using namespace Filter;

void ai::onEnd(bool isWinner){
}

void ai::onFrame(){
    if(!Broodwar->self()
      || Broodwar->getFrameCount() % Broodwar->getLatencyFrames() != 0
      || Broodwar->isPaused()
      || Broodwar->isReplay()){
        return;
    }

    for(auto &u : Broodwar->self()->getUnits()){
        if(!u->exists()
          || !u->isCompleted()
          || u->isConstructing()
          || u->isLoaded()
          || u->isLockedDown()
          || u->isMaelstrommed()
          || !u->isPowered()
          || u->isStasised()
          || u->isStuck()){
            continue;
        }

        // Handle workers.
        if(u->getType().isWorker()){
            if(u->isIdle()){
                if(u->isCarryingMinerals()
                  || u->isCarryingGas()){
                    u->returnCargo();

                }else{
                    u->gather(u->getClosestUnit(IsMineralField || IsRefinery));
                }
            }

        // Handle Command Centers, Hatcheries, and Nexuses.
        }else if(u->getType().isResourceDepot()){
            // Build workers.
            if(u->isIdle()){
                u->train(u->getType().getRace().getWorker());
            }
        }
    }
}

void ai::onNukeDetect(BWAPI::Position target){
}

void ai::onPlayerLeft(BWAPI::Player player){
}

void ai::onReceiveText(BWAPI::Player player, std::string text){
}

void ai::onSaveGame(std::string gameName){
}

void ai::onSendText(std::string text){
    Broodwar->sendText("%s", text.c_str());
}

void ai::onStart(){
    Broodwar->setCommandOptimizationLevel(2);

    Broodwar->sendText("iterami/SC-AI.cpp vs");
}

void ai::onUnitComplete(BWAPI::Unit unit){
}

void ai::onUnitCreate(BWAPI::Unit unit){
}

void ai::onUnitDestroy(BWAPI::Unit unit){
}

void ai::onUnitDiscover(BWAPI::Unit unit){
}

void ai::onUnitEvade(BWAPI::Unit unit){
}

void ai::onUnitHide(BWAPI::Unit unit){
}

void ai::onUnitMorph(BWAPI::Unit unit){
}

void ai::onUnitRenegade(BWAPI::Unit unit){
}

void ai::onUnitShow(BWAPI::Unit unit){
}

<commit_msg>improved formatting<commit_after>#include "ai.h"
#include <iostream>

using namespace BWAPI;
using namespace Filter;

void ai::onEnd(bool isWinner){
}

void ai::onFrame(){
    if(!Broodwar->self()
      || Broodwar->getFrameCount() % Broodwar->getLatencyFrames() != 0
      || Broodwar->isPaused()
      || Broodwar->isReplay()){
        return;
    }

    for(auto &u : Broodwar->self()->getUnits()){
        if(!u->exists()
          || !u->isCompleted()
          || u->isConstructing()
          || u->isLoaded()
          || u->isLockedDown()
          || u->isMaelstrommed()
          || !u->isPowered()
          || u->isStasised()
          || u->isStuck()){
            continue;
        }

        // Handle workers.
        if(u->getType().isWorker()){
            if(!u->isIdle()){
                continue;
            }

            if(u->isCarryingMinerals()
              || u->isCarryingGas()){
                u->returnCargo();

            }else{
                u->gather(u->getClosestUnit(IsMineralField || IsRefinery));
            }

        // Handle Command Centers, Hatcheries, and Nexuses.
        }else if(u->getType().isResourceDepot()){
            if(!u->isIdle()){
                continue
            }

            // Build workers.
            u->train(u->getType().getRace().getWorker());
        }
    }
}

void ai::onNukeDetect(BWAPI::Position target){
}

void ai::onPlayerLeft(BWAPI::Player player){
}

void ai::onReceiveText(BWAPI::Player player, std::string text){
}

void ai::onSaveGame(std::string gameName){
}

void ai::onSendText(std::string text){
    Broodwar->sendText("%s", text.c_str());
}

void ai::onStart(){
    Broodwar->setCommandOptimizationLevel(2);

    Broodwar->sendText("iterami/SC-AI.cpp vs");
}

void ai::onUnitComplete(BWAPI::Unit unit){
}

void ai::onUnitCreate(BWAPI::Unit unit){
}

void ai::onUnitDestroy(BWAPI::Unit unit){
}

void ai::onUnitDiscover(BWAPI::Unit unit){
}

void ai::onUnitEvade(BWAPI::Unit unit){
}

void ai::onUnitHide(BWAPI::Unit unit){
}

void ai::onUnitMorph(BWAPI::Unit unit){
}

void ai::onUnitRenegade(BWAPI::Unit unit){
}

void ai::onUnitShow(BWAPI::Unit unit){
}

<|endoftext|>